Advertisement
Puddingpikachu

Tester

Apr 26th, 2017
206
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 37.75 KB | None | 0 0
  1. # STUDENTS: TO USE:
  2. #
  3. # The following command will test all test cases on your file:
  4. #
  5. #   python3 <thisfile.py> <your_one_file.py>
  6. #
  7. #
  8. # You can also limit the tester to only the functions you want tested.
  9. # Just add as many functions as you want tested on to the command line at the end.
  10. # Example: to only run tests associated with func1, func2, and func3, run this command:
  11. #
  12. #   python3 <thisfile.py> <your_one_file.py> func1 func2 func3
  13. #
  14.  
  15.  
  16. # INSTRUCTOR: TO PREPARE:
  17. #  - add test cases to class AllTests. The test case functions' names must
  18. # be precise - to test a function named foobar, the test must be named "test_foobar_#"
  19. # where # may be any digits at the end, such as "test_foobar_13".
  20. # - any extra-credit tests must be named "test_extra_credit_foobar_#"
  21. #
  22. # - name all required definitions in REQUIRED_DEFNS. Do not include any unofficial
  23. #   helper functions. If you want to make helper definitions to use while testing,
  24. #   those can also be added there for clarity.
  25. #
  26. # to run on either a single file or all .py files in a folder (recursively):
  27. #   python3 <thisfile.py> <your_one_file.py>
  28. #   python3 <thisfile.py> <dir_of_files>
  29. #
  30. # A work in progress by Mark Snyder, Oct. 2015.
  31. #  Edited by Yutao Zhong, Spring 2016.
  32. #  Edited by Raven Russell, Spring 2017.
  33.  
  34.  
  35. import unittest
  36. import shutil
  37. import sys
  38. import os
  39. import time
  40.  
  41. import importlib
  42.  
  43. ############################################################################
  44. ############################################################################
  45. # BEGIN SPECIALIZATION SECTION (the only part you need to modify beyond
  46. # adding new test cases).
  47.  
  48. # name all expected definitions; if present, their definition (with correct
  49. # number of arguments) will be used; if not, a decoy complainer function
  50. # will be used, and all tests on that function should fail.
  51.    
  52. REQUIRED_DEFNS = [  "Train",
  53.                     "TrainCapacityException",
  54.                     "City",
  55.                     "Journey"
  56.                  ]
  57.  
  58. # for method names in classes that will be tested
  59. SUB_DEFNS = [   "time_to_travel", "load_passengers", "unload_passengers",
  60.                 "load_passengers_exception","unload_passengers_exception",
  61.                 "distance_to_city", "journey_type_error",
  62.                 "add_destination","city_in_journey","check_journey_includes",
  63.                 "total_journey_distance", "city_arrival_time","city_departure_time",
  64.                 "total_journey_time","all_passengers_accommodated"
  65.             ]
  66.  
  67.  
  68. extra_credit = []
  69.  
  70. weight_required = 1
  71. weight_extra_credit = 1
  72.                  
  73. RENAMED_FILE = "student"
  74.  
  75.  
  76.  
  77. # END SPECIALIZATION SECTION
  78. ############################################################################
  79. ############################################################################
  80.  
  81.  
  82.  
  83. # enter batch mode by giving a directory to work on.
  84. BATCH_MODE = (sys.argv[1] in ["."] or os.path.isdir(sys.argv[1]))
  85.  
  86. # This class contains multiple "unit tests" that each check
  87. # various inputs to specific functions, checking that we get
  88. # the correct behavior (output value) from completing the call.
  89. class AllTests (unittest.TestCase):
  90.        
  91.    
  92.     ############################################################################
  93.    
  94.     # Train class basics
  95.    
  96.     def test_Train_1(self): self.assertEqual(Train("train 1", 10, 22).name,"train 1")
  97.     def test_Train_2(self): self.assertEqual(Train("train 1", 10, 22).max_passengers,10)
  98.     def test_Train_3(self): self.assertEqual(Train("train 1", 10, 22).num_passengers,0)
  99.     def test_Train_4(self): self.assertEqual(Train("train 1", 10, 22).speed_fps,22)
  100.     def test_Train_5(self):
  101.         self.assertEqual(Train("train 1", 10, 22).__str__(),'Train named train 1 with 0 passengers will travel at 15.00mph')
  102.     def test_Train_6(self):
  103.         self.assertEqual(Train("Express One", 50, 100).__str__(),'Train named Express One with 0 passengers will travel at 68.18mph')
  104.     def test_Train_7(self):
  105.         train = Train("NYC Express", 20, 5280)
  106.         train.num_passengers += 10
  107.         self.assertEqual(str(train),'Train named NYC Express with 10 passengers will travel at 3600.00mph')
  108.    
  109.     ############################################################################   
  110.     # Train class time_to_travel() method
  111.  
  112.     def test_time_to_travel_1(self): self.assertEqual(Train("train 1", 10, 22).time_to_travel(2200),100)
  113.     def test_time_to_travel_2(self): self.assertEqual(Train("Express One", 50, 100).time_to_travel(36000),360)
  114.     def test_time_to_travel_3(self): self.assertEqual(Train("NYC Express", 20, 280).time_to_travel(1500),5)
  115.     def test_time_to_travel_4(self): self.assertEqual(Train("train 2", 100, 45).time_to_travel(2000),44)
  116.    
  117.     ############################################################################
  118.     # Train class load_passengers() method, no exception
  119.    
  120.     def test_load_passengers_1(self):
  121.         train = Train("train 1", 10, 22)
  122.         train.load_passengers(6)
  123.         self.assertEqual(train.num_passengers,6)
  124.  
  125.     def test_load_passengers_2(self):
  126.         train = Train("train 1", 50, 22)
  127.         train.load_passengers(20)
  128.         train.load_passengers(30)
  129.         self.assertEqual(train.num_passengers,50)
  130.  
  131.     def test_load_passengers_3(self):
  132.         train = Train("train 1", 50, 22)
  133.         train.load_passengers(20)
  134.         train.num_passengers -= 10
  135.         train.load_passengers(29)
  136.         self.assertEqual(train.num_passengers,39)
  137.        
  138.     ############################################################################
  139.     # Train class unload_passengers() method, no exception
  140.    
  141.     def test_unload_passengers_1(self):
  142.         train = Train("train 1", 10, 22)
  143.         train.num_passengers=10
  144.         train.unload_passengers(6)
  145.         self.assertEqual(train.num_passengers,4)
  146.  
  147.     def test_unload_passengers_2(self):     #testing both load and unload
  148.         train = Train("train 1", 50, 22)
  149.         train.num_passengers= 40
  150.         train.unload_passengers(25)
  151.         train.unload_passengers(5)
  152.         train.unload_passengers(10)
  153.         self.assertEqual(train.num_passengers,0)
  154.        
  155.     def test_unload_passengers_3(self):     #testing both load and unload
  156.         train = Train("train 1", 50, 22)
  157.         train.load_passengers(20)
  158.         train.unload_passengers(11)
  159.         train.load_passengers(18)
  160.         train.unload_passengers(5)
  161.         self.assertEqual(train.num_passengers,22)
  162.        
  163.  
  164.     ############################################################################
  165.     # TrainCapacityError class
  166.    
  167.     def test_TrainCapacityException_1(self):  #test basics
  168.         tc = TrainCapacityException(5,"full")
  169.         self.assertEqual(tc.number,5)
  170.         self.assertEqual(tc.issue,"full")
  171.         self.assertEqual(str(tc), "5 passengers cannot be loaded because the train is full!")
  172.  
  173.     def test_TrainCapacityException_2(self):  #test: can we raise it?
  174.         tc = TrainCapacityException(5,"full")
  175.         try:
  176.             raise tc
  177.         except TrainCapacityException:
  178.             pass
  179.         except:
  180.             self.fail("should have been able to raise a TrainCapacityException")
  181.            
  182.     def test_TrainCapacityException_3(self):  
  183.         tc = TrainCapacityException(20,"empty")
  184.         self.assertEqual(tc.number,20)
  185.         self.assertEqual(tc.issue,"empty")
  186.         self.assertEqual(str(tc), "20 passengers cannot be unloaded because the train is empty!")
  187.         try:
  188.             raise tc
  189.         except TrainCapacityException:
  190.             pass
  191.         except:
  192.             self.fail("should have been able to raise a TrainCapacityException")
  193.  
  194.     def test_TrainCapacityException_4(self):    # test: default value
  195.         tc = TrainCapacityException(18)
  196.         self.assertEqual(tc.number,18)
  197.         self.assertEqual(tc.issue,"full")
  198.         self.assertEqual(str(tc), "18 passengers cannot be loaded because the train is full!")
  199.         try:
  200.             raise tc
  201.         except TrainCapacityException:
  202.             pass
  203.         except:
  204.             self.fail("should have been able to raise a TrainCapacityException")
  205.  
  206.     ############################################################################
  207.     # Train class load_passengers() method exception behavior
  208.    
  209.     def test_load_passengers_exception_1(self):     # test: Train::load_passengers() triggers exception
  210.         train = Train("train 1", 10, 22)
  211.         try:
  212.             train.load_passengers(20)
  213.             self.fail("should have raised a TrainCapacityException")
  214.         except TrainCapacityException:
  215.             pass
  216.         except:
  217.             self.fail("should have raised a TrainCapacityException")
  218.        
  219.     def test_load_passengers_exception_2(self):     # test: exception details
  220.         train = Train("train 1", 10, 22)
  221.         try:
  222.             train.load_passengers(20)
  223.             self.fail("should have raised a TrainCapacityException")
  224.         except TrainCapacityException as e:
  225.             self.assertEqual(e.number, 10)
  226.             self.assertEqual(e.issue,"full")
  227.             self.assertEqual(train.num_passengers, 0)   #num_passengers not changed
  228.         except:
  229.             self.fail("should have raised a TrainCapacityException")
  230.  
  231.     ############################################################################
  232.     # Train class unload_passengers() method exception behavior
  233.  
  234.     def test_unload_passengers_exception_1(self):   # test: Train::unload_passengers() triggers exception
  235.         train = Train("train 1", 10, 22)
  236.         train.load_passengers(10)
  237.         try:
  238.             train.unload_passengers(16)
  239.             self.fail("should have raised a TrainCapacityException")
  240.         except TrainCapacityException:
  241.             pass
  242.         except:
  243.             self.fail("should have raised a TrainCapacityException")
  244.        
  245.     def test_unload_passengers_exception_2(self):   # test: exception details
  246.         train = Train("train 1", 10, 22)
  247.         train.load_passengers(10)
  248.         try:
  249.             train.unload_passengers(16)
  250.             self.fail("should have raised a TrainCapacityException")
  251.         except TrainCapacityException as e:
  252.             self.assertEqual(e.number, 6)
  253.             self.assertEqual(e.issue,"empty")
  254.             self.assertEqual(train.num_passengers, 10)  #num_passengers not changed
  255.         except:
  256.             self.fail("should have raised a TrainCapacityException")
  257.    
  258.     ############################################################################
  259.     # City class
  260.    
  261.     def test_City_1(self): self.assertEqual(City("New York", 0, 3, 300).name,"New York")
  262.     def test_City_2(self): self.assertEqual(City("New York", 0, 3, 300).loc_x,0)
  263.     def test_City_3(self): self.assertEqual(City("New York", 0, 3, 300).loc_y,3)
  264.     def test_City_4(self): self.assertEqual(City("New York", 0, 3, 300).stop_time,300)
  265.     def test_City_5(self): self.assertEqual(City("New York", 0, 3, 300).__str__(),"New York (0,3). Exchange time: 5.00 minutes")
  266.     def test_City_6(self):
  267.         city = City("New York", 0, 3, 1000)
  268.         self.assertEqual(str(city),"New York (0,3). Exchange time: 16.67 minutes")
  269.     def test_City_7(self):
  270.         c1 = City("New York", 0, 3, 1000)
  271.         c2 = City("The Big Apple",0,3,6000)
  272.         self.assertEqual(c1.__eq__(c2), True)
  273.     def test_City_8(self):
  274.         c1 = City("Rochester",4,8,300)
  275.         c2 = City("Rochester",1,10,300)
  276.         c3 = City("The Lilac City",4,8,600)
  277.         self.assertEqual(c1,c3)
  278.         self.assertEqual(c1==c2, False)
  279.        
  280.     ############################################################################
  281.  
  282.     # City class distance_to_city()
  283.     def test_distance_to_city_1(self):
  284.         c1 = City("City 1",0,3,300)
  285.         c2 = City("City 2",0,8,300)
  286.         self.assertEqual(c1.distance_to_city(c2),5)
  287.  
  288.     def test_distance_to_city_2(self):
  289.         c1 = City("City 1",14,3,300)
  290.         c2 = City("City 2",5,3,300)
  291.         self.assertEqual(c1.distance_to_city(c2),9)
  292.  
  293.     def test_distance_to_city_3(self):
  294.         c1 = City("City 1", 0,3,300)
  295.         c2 = City("City 2",4,8,300)
  296.         self.assertAlmostEqual(c1.distance_to_city(c2),6.403,places=3)
  297.  
  298.     def test_distance_to_city_4(self):
  299.         c1 = City("Emerald City", 100,300,4000)
  300.         c2 = City("Kansas City", 1, 1,500)
  301.         self.assertAlmostEqual(c1.distance_to_city(c2),314.963,places=3)
  302.    
  303.     ############################################################################
  304.     # Journey class basics
  305.    
  306.     def test_Journey_1(self):
  307.         t = Train("Express One", 50, 100)
  308.         cities = [City("City 1", 0,3,600)]
  309.         self.assertEqual(Journey(t,cities,10000).train,t)
  310.  
  311.     def test_Journey_2(self):
  312.         t = Train("Express One", 50, 100)
  313.         cities = [City("City 1", 0,3,600)]
  314.         self.assertEqual(Journey(t,cities,10000).destinations,cities)
  315.  
  316.     def test_Journey_3(self):
  317.         t = Train("Express One", 50, 100)
  318.         cities = [City("City 1", 0,3,600)]
  319.         self.assertEqual(Journey(t,cities,10000).start_time,10000)
  320.        
  321.     def test_Journey_4(self):               #default values
  322.         t = Train("Express One", 50, 100)
  323.         self.assertEqual(Journey(t).train,t)
  324.         self.assertEqual(Journey(t).destinations,[])
  325.         self.assertEqual(Journey(t).start_time,0)
  326.  
  327.     def test_Journey_5(self):               #default values
  328.         t = Train("Express One", 50, 100)
  329.         self.assertEqual(Journey(t,[]).train,t)
  330.         self.assertEqual(Journey(t,[]).destinations,[])
  331.         self.assertEqual(Journey(t,[]).start_time,0)
  332.  
  333.     def test_Journey_6(self):
  334.         t = Train("Express One", 50, 100)
  335.         cities = [City("City 1", 0,3,600), City("City 2",4,8,300)]
  336.         self.assertEqual(Journey(t,cities,10000).train,t)
  337.         self.assertEqual(Journey(t,cities,10000).destinations,cities)
  338.         self.assertEqual(Journey(t,cities,10000).start_time,10000)
  339.  
  340.     def test_Journey_7(self):
  341.         t = Train("Express One", 50, 22)
  342.         cities = [City("City 1", 0,3,600), City("City 2",4,8,300), City("City 3",400,8000,120)]
  343.         journey = Journey(t,cities,10000)
  344.         self.assertEqual(str(journey),
  345.             "Journey with 3 stops:\n\tCity 1 (0,3). Exchange time: 10.00 minutes\n\tCity 2 (4,8). Exchange time: 5.00 minutes\n\tCity 3 (400,8000). Exchange time: 2.00 minutes\nTrain Information: Train named Express One with 0 passengers will travel at 15.00mph\n")
  346.  
  347.     def test_Journey_8(self):
  348.         t = Train("Express One", 50, 200)
  349.         t.num_passengers += 30
  350.         cities = [City("Emerald City",1000,1000,320), City("Kansas",0,0,300)]
  351.         journey = Journey(t,cities,10000)
  352.         self.assertEqual(str(journey),
  353.             "Journey with 2 stops:\n\tEmerald City (1000,1000). Exchange time: 5.33 minutes\n\tKansas (0,0). Exchange time: 5.00 minutes\nTrain Information: Train named Express One with 30 passengers will travel at 136.36mph\n")
  354.  
  355.     def test_Journey_9(self):
  356.         t = Train("Express One", 50, 22)
  357.         j = Journey(t)
  358.         self.assertEqual(str(j),
  359.             "Journey with 0 stops:\nTrain Information: Train named Express One with 0 passengers will travel at 15.00mph\n")
  360.        
  361.  
  362.     ############################################################################
  363.  
  364.     # Journey class incorrect argument type to constructor
  365.     def test_journey_type_error_1(self):
  366.         try:
  367.             j = Journey("train",[])
  368.             self.fail("should have raised a TypeError")
  369.         except TypeError:
  370.             pass
  371.         except:
  372.             self.fail("should have raised a TypeError")
  373.  
  374.     def test_journey_type_error_2(self):
  375.         t = Train("Express One", 50, 22)
  376.         try:
  377.             j = Journey(t,"destination")
  378.             self.fail("should have raised a TypeError")
  379.         except TypeError:
  380.             pass
  381.         except:
  382.             self.fail("should have raised a TypeError")
  383.  
  384.     def test_journey_type_error_3(self):
  385.         t = Train("Express One", 50, 22)
  386.         c1 = City("New York", 0,3,600)
  387.         try:
  388.             j = Journey(t,[c1,"c2"])
  389.             self.fail("should have raised a TypeError")
  390.         except TypeError:
  391.             pass
  392.         except:
  393.             self.fail("should have raised a TypeError")
  394.  
  395.     ############################################################################
  396.  
  397.     # Journey class add_destination method
  398.    
  399.     def test_add_destination_1(self):       #test: add one destination
  400.         t = Train("Express One", 50, 100)
  401.         j = Journey(t,[],0)
  402.         c1 = City("New York", 0,3,600)
  403.         j.add_destination(c1)
  404.         self.assertEqual(j.destinations,[c1])
  405.  
  406.     def test_add_destination_2(self):       #test: returns None
  407.         t = Train("Express One", 50, 100)
  408.         j = Journey(t,[],0)
  409.         c1 = City("New York", 0,3,600)
  410.         self.assertEqual(j.add_destination(c1),None)
  411.  
  412.     def test_add_destination_3(self):       #test: add more than one destination
  413.         t = Train("Express One", 50, 100)
  414.         j = Journey(t,[],0)
  415.         c1 = City("City 1",2,3,900)
  416.         c2 = City("City 2",5,10,600)
  417.         c3 = City("City 3", 0,0,300)
  418.         j.add_destination(c1)
  419.         j.add_destination(c2)
  420.         j.add_destination(c3)
  421.         self.assertEqual(j.destinations[0],c1)
  422.         self.assertEqual(j.destinations[1],c2)
  423.         self.assertEqual(j.destinations[-1],c3)
  424.  
  425.     def test_add_destination_4(self):       #test: keeps appending, not changing the id
  426.         t = Train("Express One", 50, 100)
  427.         c = City("City 1",5,10,600)
  428.         j = Journey(t,[c],0)
  429.         c1 = City("City 2",2,3,900)
  430.         c2 = City("City 3", 0,0,300)
  431.         old_id = id(j.destinations)
  432.         j.add_destination(c1)
  433.         self.assertEqual(id(j.destinations), old_id)
  434.         j.add_destination(c2)
  435.         self.assertEqual(id(j.destinations), old_id)
  436.         self.assertEqual(j.destinations,[c, c1,c2])
  437.        
  438.     ############################################################################
  439.     # Journey class city_in_journey method
  440.  
  441.     def test_city_in_journey_1(self):      
  442.         t = Train("Express One", 50, 100)
  443.         c1 = City("City 1",5,10,600)
  444.         cities = [c1,City("City 2",2,3,900), City("City 3", 0,0,300)]
  445.         j = Journey(t,cities,200)
  446.         self.assertEqual(j.city_in_journey(c1),True)
  447.                
  448.     def test_city_in_journey_2(self):       # same features, different objects
  449.         t = Train("Express One", 50, 100)      
  450.         cities = [City("City 1",5,10,600),City("City 2",2,3,900), City("City 3", 0,0,300)]
  451.         j = Journey(t,cities,200)
  452.         c2 = City("City 2",2,3,900)
  453.         self.assertEqual(j.city_in_journey(c2),True)
  454.  
  455.     def test_city_in_journey_3(self):       # same location, different name
  456.         t = Train("Express One", 50, 100)      
  457.         cities = [City("City 1",5,10,600),City("City 2",2,3,900), City("City 3", 0,0,300)]
  458.         j = Journey(t,cities,200)
  459.         c3 = City("City 3_alias",5,10,100)
  460.         self.assertEqual(j.city_in_journey(c3),True)
  461.  
  462.     def test_city_in_journey_4(self):       # return False
  463.         t = Train("Express One", 50, 100)      
  464.         cities = [City("City 1",5,10,600),City("City 2",2,3,900), City("City 3", 0,0,300)]
  465.         j = Journey(t,cities,200)
  466.         c = City("City 4",0,110,200)
  467.         self.assertEqual(j.city_in_journey(c),False)
  468.  
  469.     def test_city_in_journey_5(self):       # same name, different location ==> not same city
  470.         t = Train("Express One", 50, 100)      
  471.         cities = [City("City 1",5,10,600),City("City 2",2,3,900), City("City 3", 0,0,300)]
  472.         j = Journey(t,cities,200)
  473.         c = City("City 1",0,110,200)
  474.         self.assertEqual(j.city_in_journey(c),False)
  475.  
  476.  
  477.     ############################################################################
  478.     # Journey class check_journey_includes method
  479.                
  480.     def test_check_journey_includes_1(self):       
  481.         t = Train("Express One", 50, 100)      
  482.         c1 = City("City 1",5,10,600)
  483.         c2 = City("City 2",2,3,900)
  484.         c3 = City("City 3", 0,0,300)
  485.         c4 = City("City 4", 12,4,1000)
  486.         j = Journey(t,[c1,c2,c3,c4],200)
  487.         self.assertEqual(j.check_journey_includes(c1,c2),True)
  488.  
  489.     def test_check_journey_includes_2(self):       
  490.         t = Train("Express One", 50, 100)      
  491.         c1 = City("City 1",5,10,600)
  492.         c2 = City("City 2",2,3,900)
  493.         c3 = City("City 3", 0,0,300)
  494.         c4 = City("City 4", 12,4,1000)
  495.         j = Journey(t,[c1,c2,c3,c4],200)
  496.         self.assertEqual(j.check_journey_includes(c3,c4),True)
  497.  
  498.     def test_check_journey_includes_3(self):       
  499.         t = Train("Express One", 50, 100)      
  500.         c1 = City("City 1",5,10,600)
  501.         c2 = City("City 2",2,3,900)
  502.         c3 = City("City 3", 0,0,300)
  503.         c4 = City("City 4", 12,4,1000)
  504.         j = Journey(t,[c1,c2,c3,c4],200)
  505.         self.assertEqual(j.check_journey_includes(c1,c4),True)
  506.  
  507.     def test_check_journey_includes_4(self):       
  508.         t = Train("Express One", 50, 100)      
  509.         c1 = City("City 1",5,10,600)
  510.         c2 = City("City 2",2,3,900)
  511.         c3 = City("City 3", 0,0,300)
  512.         c4 = City("City 4", 12,4,1000)
  513.         j = Journey(t,[c1,c2,c3,c4],200)
  514.         self.assertEqual(j.check_journey_includes(c3,c2),False) #order incorrect
  515.  
  516.     def test_check_journey_includes_5(self):       
  517.         t = Train("Express One", 50, 100)      
  518.         c1 = City("City 1",5,10,600)
  519.         c2 = City("City 2",2,3,900)
  520.         c3 = City("City 3", 0,0,300)
  521.         c4 = City("City 4", 12,4,1000)
  522.         j = Journey(t,[c2,c3,c4],200)
  523.         self.assertEqual(j.check_journey_includes(c1,c3),False)
  524.  
  525.     def test_check_journey_includes_6(self):       
  526.         t = Train("Express One", 50, 100)      
  527.         c1 = City("City 1",5,10,600)
  528.         c2 = City("City 2",2,3,900)
  529.         c3 = City("City 3", 0,0,300)
  530.         c4 = City("City 4", 12,4,1000)
  531.         j = Journey(t,[c1,c2,c3],200)
  532.         self.assertEqual(j.check_journey_includes(c3,c4),False)
  533.  
  534.     def test_check_journey_includes_7(self):       
  535.         t = Train("Express One", 50, 100)      
  536.         c1 = City("City 1",5,10,600)
  537.         c2 = City("City 2",2,3,900)
  538.         c3 = City("City 3", 0,0,300)
  539.         c4 = City("City 4", 12,4,1000)
  540.         j = Journey(t,[c1,c2,c3,c1],200)
  541.         self.assertEqual(j.check_journey_includes(c2,c1),True)
  542.  
  543.     ############################################################################
  544.     # Journey class total_journey_distance method
  545.  
  546.     def test_total_journey_distance_1(self):    #empty list of destinations
  547.         t = Train("Express One", 50, 100)      
  548.         j = Journey(t,[],200)
  549.         self.assertEqual(j.total_journey_distance(),0)
  550.  
  551.     def test_total_journey_distance_2(self):    #one destination
  552.         t = Train("Express One", 50, 100)      
  553.         c1 = City("City 1",0,3,300)
  554.         j = Journey(t,[c1],200)
  555.         self.assertEqual(j.total_journey_distance(),0)
  556.  
  557.     def test_total_journey_distance_3(self):    #two destinations
  558.         t = Train("Express One", 50, 100)      
  559.         c1 = City("City 1",0,3,300)
  560.         c2 = City("City 2",0,8,300)
  561.         j = Journey(t,[c1,c2],200)
  562.         self.assertEqual(j.total_journey_distance(),5)
  563.  
  564.     def test_total_journey_distance_4(self):    #two destinations
  565.         t = Train("Express One", 50, 100)      
  566.         c1 = City("City 1", 0,8,300)
  567.         c2 = City("City 2",4,3,300)
  568.         j = Journey(t,[c1,c2],200)
  569.         self.assertAlmostEqual(j.total_journey_distance(),6.403,places=3)
  570.  
  571.     def test_total_journey_distance_5(self):    #more destinations
  572.         t = Train("Express One", 50, 100)      
  573.         c1 = City("City 1",14,8,300)
  574.         c2 = City("City 2",4,8,300)
  575.         c3 = City("City 3",4,10,200)
  576.         j = Journey(t,[c1,c2,c3],200)
  577.         self.assertEqual(j.total_journey_distance(),12)
  578.  
  579.     def test_total_journey_distance_6(self):    #more destinations
  580.         t = Train("Express One", 50, 100)      
  581.         c1 = City("City 1",14,8,300)
  582.         c2 = City("City 2",4,8,300)
  583.         c3 = City("City 3",20,6,200)
  584.         c4 = City("City 4",1,10,180)
  585.         j = Journey(t,[c1,c2,c3,c4],0)
  586.         self.assertAlmostEqual(j.total_journey_distance(),45.54, places=2)
  587.  
  588.  
  589.     ############################################################################
  590.     # Journey class city_arrival_time method
  591.  
  592.     def test_city_arrival_time_1(self):     #first destination
  593.         t = Train("Express One", 50, 100)      
  594.         c1 = City("City 1",0,3,300)
  595.         j = Journey(t,[c1],200)
  596.         self.assertEqual(j.city_arrival_time(c1),200)
  597.  
  598.     def test_city_arrival_time_2(self):     #2nd destination
  599.         t = Train("Express One", 50, 10)       
  600.         c1 = City("City 1",0,3,300)
  601.         c2 = City("City 2",0,3003,300)
  602.         j = Journey(t,[c1,c2],200)
  603.         self.assertEqual(j.city_arrival_time(c2),800)
  604.  
  605.     def test_city_arrival_time_3(self):     #2nd destination
  606.         t = Train("Express One", 50, 10)       
  607.         c1 = City("City 1",100,3,120)
  608.         c2 = City("City 2",78,300,300)
  609.         j = Journey(t,[c1,c2],1000)
  610.         self.assertEqual(j.city_arrival_time(c1),1000)
  611.         self.assertEqual(j.city_arrival_time(c2),1149)
  612.  
  613.     def test_city_arrival_time_4(self):    
  614.         t = Train("Express One", 50, 10)       
  615.         c1 = City("City 1",100,3,120)
  616.         c2 = City("City 2",78,300,300)
  617.         c3 = City("City 3", 50, 100, 240)
  618.         j = Journey(t,[c1,c2,c3],1000)
  619.         self.assertEqual(j.city_arrival_time(c3),1469)
  620.  
  621.     def test_city_arrival_time_5(self):     #return the first arrival
  622.         t = Train("Express One", 50, 10)       
  623.         c1 = City("City 1",100,10,120)
  624.         c2 = City("City 2",78,300,300)
  625.         c3 = City("City 3", 50, 100, 240)
  626.         j = Journey(t,[c1,c2,c3,c2],1000)
  627.         self.assertEqual(j.city_arrival_time(c2),1149)
  628.  
  629.     def test_city_arrival_time_6(self):     # city not in journey, should return None
  630.         t = Train("Express One", 50, 10)       
  631.         c1 = City("City 1",100,3,120)
  632.         c2 = City("City 2",78,300,300)
  633.         c3 = City("City 3", 50, 100, 240)
  634.         j = Journey(t,[c1,c2],1000)
  635.         self.assertEqual(j.city_arrival_time(c3),None)
  636.  
  637.     ############################################################################
  638.     # Journey class city_arrival_time method
  639.  
  640.     def test_city_departure_time_1(self):   #first destination
  641.         t = Train("Express One", 50, 100)      
  642.         c1 = City("City 1",0,3,300)
  643.         j = Journey(t,[c1],200)
  644.         self.assertEqual(j.city_departure_time(c1),500)
  645.  
  646.     def test_city_departure_time_2(self):   #2nd destination
  647.         t = Train("Express One", 50, 10)       
  648.         c1 = City("City 1",0,3,300)
  649.         c2 = City("City 2",0,3003,300)
  650.         j = Journey(t,[c1,c2],200)
  651.         self.assertEqual(j.city_departure_time(c2),1100)
  652.  
  653.     def test_city_departure_time_3(self):   #2nd destination
  654.         t = Train("Express One", 50, 10)       
  655.         c1 = City("City 1",100,3,120)
  656.         c2 = City("City 2",78,300,300)
  657.         j = Journey(t,[c1,c2],1000)
  658.         self.assertEqual(j.city_departure_time(c1),1120)
  659.         self.assertEqual(j.city_departure_time(c2),1449)
  660.  
  661.     def test_city_departure_time_4(self):  
  662.         t = Train("Express One", 50, 10)       
  663.         c1 = City("City 1",100,3,120)
  664.         c2 = City("City 2",78,300,300)
  665.         c3 = City("City 3", 50, 100, 240)
  666.         j = Journey(t,[c1,c2,c3],1000)
  667.         self.assertEqual(j.city_departure_time(c3),1709)
  668.  
  669.     def test_city_departure_time_5(self):   #return the last departure
  670.         t = Train("Express One", 50, 10)       
  671.         c1 = City("City 1",100,10,120)
  672.         c2 = City("City 2",78,300,300)
  673.         c3 = City("City 3", 50, 100, 240)
  674.         j = Journey(t,[c1,c2,c3,c2],1000)
  675.         self.assertEqual(j.city_departure_time(c2),2029)
  676.  
  677.     def test_city_departure_time_6(self):   # city not in journey, should return None
  678.         t = Train("Express One", 50, 10)       
  679.         c1 = City("City 1",100,3,120)
  680.         c2 = City("City 2",78,300,300)
  681.         c3 = City("City 3", 50, 100, 240)
  682.         j = Journey(t,[c1,c2],1000)
  683.         self.assertEqual(j.city_departure_time(c3),None)
  684.  
  685.     ############################################################################
  686.     # Journey class total_journey_time method
  687.  
  688.     def test_total_journey_time_1(self):    #one destination
  689.         t = Train("Express One", 50, 100)      
  690.         c1 = City("City 1",0,3,300)
  691.         j = Journey(t,[c1],200)
  692.         self.assertEqual(j.total_journey_time(),300)
  693.  
  694.     def test_total_journey_time_2(self):    #two destinations
  695.         t = Train("Express One", 50, 10)       
  696.         c1 = City("City 1",0,3,300)
  697.         c2 = City("City 2",0,3003,300)
  698.         j = Journey(t,[c1,c2],200)
  699.         self.assertEqual(j.total_journey_time(),900)
  700.  
  701.     def test_total_journey_time_3(self):    #2nd destination
  702.         t = Train("Express One", 50, 10)       
  703.         c1 = City("City 1",100,3,120)
  704.         c2 = City("City 2",78,300,300)
  705.         j = Journey(t,[c1,c2],1000)
  706.         self.assertEqual(j.total_journey_time(),449)
  707.  
  708.     def test_total_journey_time_4(self):    
  709.         t = Train("Express One", 50, 10)       
  710.         c1 = City("City 1",100,3,120)
  711.         c2 = City("City 2",78,300,300)
  712.         c3 = City("City 3", 50, 100, 240)
  713.         j = Journey(t,[c1,c2,c3],1000)
  714.         self.assertEqual(j.total_journey_time(),709)
  715.  
  716.     def test_total_journey_time_5(self):    
  717.         t = Train("Express One", 50, 10)       
  718.         c1 = City("City 1",100,10,120)
  719.         c2 = City("City 2",78,300,300)
  720.         c3 = City("City 3", 50, 100, 240)
  721.         j = Journey(t,[c1,c2,c3,c2],1000)
  722.         self.assertEqual(j.total_journey_time(),1029)
  723.  
  724.     ############################################################################
  725.     # Journey class all_passengers_accommodated method
  726.  
  727.     def test_all_passengers_accommodated_1(self):   #one destination
  728.         t = Train("Express One", 50, 100)      
  729.         c1 = City("City 1",0,3,300)
  730.         j = Journey(t,[c1],200)
  731.         self.assertEqual(j.all_passengers_accommodated([5],[5]),False) #no passenger to be unloaded
  732.         #self.assertEqual(t.num_passengers, 0)
  733.  
  734.     def test_all_passengers_accommodated_2(self):   #one destination
  735.         t = Train("Express One", 50, 100)      
  736.         c1 = City("City 1",0,3,300)
  737.         j = Journey(t,[c1],200)
  738.         self.assertEqual(j.all_passengers_accommodated([0],[100]),False) #too many to load
  739.         #self.assertEqual(t.num_passengers, 0)
  740.        
  741.     def test_all_passengers_accommodated_3(self):   #one destination
  742.         t = Train("Express One", 50, 10)       
  743.         c1 = City("City 1",0,3,300)
  744.         j = Journey(t,[c1],200)
  745.         self.assertEqual(j.all_passengers_accommodated([0],[30]),True)
  746.         #self.assertEqual(t.num_passengers, 30)
  747.  
  748.     def test_all_passengers_accommodated_4(self):   #two destination
  749.         t = Train("Express One", 50, 10)       
  750.         c1 = City("City 1",0,3,300)
  751.         c2 = City("City 2",78,300,300)
  752.         j = Journey(t,[c1,c2],200)
  753.         self.assertEqual(j.all_passengers_accommodated([0,40],[30,10]),False)
  754.         #self.assertEqual(t.num_passengers, 30)
  755.        
  756.     def test_all_passengers_accommodated_5(self):   #two destination
  757.         t = Train("Express One", 50, 10)       
  758.         c1 = City("City 1",0,3,300)
  759.         c2 = City("City 2",78,300,300)
  760.         j = Journey(t,[c1,c2],200)
  761.         self.assertEqual(j.all_passengers_accommodated([0,5],[30,20]),True)
  762.         self.assertEqual(t.num_passengers, 45)
  763.  
  764.     def test_all_passengers_accommodated_6(self):  
  765.         t = Train("Express One", 50, 10)
  766.         t.load_passengers(15)
  767.         c1 = City("City 1",0,3,300)
  768.         c2 = City("City 2",78,300,300)
  769.         j = Journey(t,[c1,c2,c1,c2],200)
  770.         self.assertEqual(j.all_passengers_accommodated([5,15,5,45],[30,20,5,0]),True)
  771.         self.assertEqual(t.num_passengers, 0)
  772.  
  773.     def test_all_passengers_accommodated_7(self):  
  774.         t = Train("Express One", 50, 10)
  775.         t.load_passengers(15)
  776.         c1 = City("City 1",0,3,300)
  777.         c2 = City("City 2",78,300,300)
  778.         j = Journey(t,[c1,c2,c1,c2],200)
  779.         self.assertEqual(j.all_passengers_accommodated([5,15,5,45],[30,20,15,0]),False)
  780.         #self.assertEqual(t.num_passengers, 40)
  781.  
  782.        
  783.     ############################################################################
  784.    
  785. #   def test_extra_credit_NAME_1(self):
  786. #       self.assertEqual(1,1)
  787.    
  788.     ############################################################
  789.    
  790. # This class digs through AllTests, counts and builds all the tests,
  791. # so that we have an entire test suite that can be run as a group.
  792. class TheTestSuite (unittest.TestSuite):
  793.     # constructor.
  794.     def __init__(self,wants):
  795.         # find all methods that begin with "test".
  796.         fs = []
  797.         for w in wants:
  798.             for func in AllTests.__dict__:
  799.                 # append regular tests
  800.                 # drop any digits from the end of str(func).
  801.                 dropnum = str(func)
  802.                 while dropnum[-1] in "1234567890":
  803.                     dropnum = dropnum[:-1]
  804.                
  805.                 if dropnum==("test_"+w+"_") and (not (dropnum==("test_extra_credit_"+w+"_"))):
  806.                     fs.append(AllTests(str(func)))
  807.                 if dropnum==("test_extra_credit_"+w+"_") and not BATCH_MODE:
  808.                     fs.append(AllTests(str(func)))
  809.        
  810.         # call parent class's constructor.
  811.         unittest.TestSuite.__init__(self,fs)
  812.  
  813. class TheExtraCreditTestSuite (unittest.TestSuite):
  814.         # constructor.
  815.         def __init__(self,wants):
  816.             # find all methods that begin with "test_extra_credit_".
  817.             fs = []
  818.             for w in wants:
  819.                 for func in AllTests.__dict__:
  820.                     if str(func).startswith("test_extra_credit_"+w):
  821.                         fs.append(AllTests(str(func)))
  822.        
  823.             # call parent class's constructor.
  824.             unittest.TestSuite.__init__(self,fs)
  825.  
  826. # all (non-directory) file names, regardless of folder depth,
  827. # under the given directory 'dir'.
  828. def files_list(dir):
  829.     info = os.walk(dir)
  830.     filenames = []
  831.     for (dirpath,dirnames,filez) in info:
  832. #       print(dirpath,dirnames,filez)
  833.         if dirpath==".":
  834.             continue
  835.         for file in filez:
  836.             filenames.append(os.path.join(dirpath,file))
  837. #       print(dirpath,dirnames,filez,"\n")
  838. #       filenames.extend(os.path.join(dirpath, filez))
  839.     return filenames
  840.  
  841. def main():
  842.     if len(sys.argv)<2:
  843.         raise Exception("needed student's file name as command-line argument:"\
  844.             +"\n\t\"python3 tester4L.py gmason76_2xx_L4.py\"")
  845.     want_all = len(sys.argv) <=2
  846.     wants = []
  847.    
  848.     # remove batch_mode signifiers from want-candidates.
  849.     want_candidates = sys.argv[2:]
  850.     for i in range(len(want_candidates)-1,-1,-1):
  851.         if want_candidates[i] in ['.'] or os.path.isdir(want_candidates[i]):
  852.             del want_candidates[i]
  853.    
  854.     if not want_all:
  855.         #print("args: ",sys.argv)
  856.         for w in want_candidates:
  857.             if w in REQUIRED_DEFNS:
  858.                 wants.append(w)
  859.             elif w in SUB_DEFNS:
  860.                 wants.append(w)
  861.             else:
  862.                 raise Exception("asked to limit testing to unknown function '%s'."%w)
  863.     else:
  864.         wants = REQUIRED_DEFNS + SUB_DEFNS
  865.  
  866.    
  867.     if not BATCH_MODE:
  868.         if not want_all:
  869.             run_file(sys.argv[1],wants)
  870.         else:
  871.             if len(extra_credit) == 0:
  872.                 (tag, passed1,tried1,ec) = run_file(sys.argv[1],wants)
  873.  
  874.                 print("\nTest cases: %d/%d passed" % (passed1,tried1) )
  875.                 print("Score based on test cases: %.2f/100" % (passed1*weight_required))
  876.            
  877.             else:  
  878.                 (tag, passed1,tried1,ec) = run_file(sys.argv[1],wants[:-len(extra_credit)])
  879.                 if passed1 == None:
  880.                     return
  881.  
  882.            
  883.                 (tag, passed2,tried2,ec) = run_file(sys.argv[1],extra_credit)
  884.                 if passed2!= None:
  885.                     print("\nRequired test cases: %d/%d passed" % (passed1,tried1) )
  886.                     print("Extra credit test cases: %d/%d passed" % (passed2, tried2))
  887.                     print("Score based on test cases: %.2f (%.2f+%d) " % (passed1*weight_required+passed2*weight_extra_credit,
  888.                                                         passed1*weight_required, passed2*weight_extra_credit))
  889.  
  890.                 else:
  891.                     print("\nRequired test cases: %d/%d passed" % (passed1,tried1) )
  892.                     print("Extra credit test cases: 0 passed")
  893.                     print("Score based on test cases: %.2f (%.2f+0) " % (passed1*weight_required,
  894.                                                         passed1*weight_required))
  895.     else:
  896.         filenames = files_list(sys.argv[1])
  897.    
  898. #       print(filenames)
  899.    
  900.         results = []
  901.         for filename in filenames:
  902.             try:
  903.                 print("\n\n\nRUNNING: "+filename)
  904.                 (tag, passed,tried,ec) = run_file(filename,wants)
  905.                 results.append((tag,passed,tried,ec))
  906.             except SyntaxError as e:
  907.                 results.append((filename+"_SYNTAX_ERROR",0,1)) 
  908.             except NameError as e:
  909.                 results.append((filename+"_Name_ERROR",0,1))   
  910.             except ValueError as e:
  911.                 results.append(filename+"_VALUE_ERROR",0,1)
  912.             except TypeError as e:
  913.                 results.append(filename+"_TYPE_ERROR",0,1)
  914.             except ImportError as e:
  915.                 results.append((filename+"_IMPORT_ERROR_TRY_AGAIN   ",0,1))
  916.             except Exception as e:
  917.                 results.append(filename+str(e.__reduce__()[0]),0,1)
  918.            
  919.         print("\n\n\nGRAND RESULTS:\n")
  920.         for (tag, passed, tried, ec) in results:
  921.             print(("%.0f%%  (%d/%d, %dEC) - " % (passed/tried*100 + ec, passed, tried, ec))+tag)
  922.  
  923. def try_copy(filename1, filename2, numTries):
  924.     have_copy = False
  925.     i = 0
  926.     while (not have_copy) and (i < numTries):
  927.         try:
  928.             # move the student's code to a valid file.
  929.             shutil.copy(filename1,filename2)
  930.            
  931.             # wait for file I/O to catch up...
  932.             if(not wait_for_access(filename2, numTries)):
  933.                 return False
  934.                
  935.             have_copy = True
  936.         except PermissionError:
  937.             print("Trying to copy "+filename1+", may be locked...")
  938.             i += 1
  939.             time.sleep(1)
  940.    
  941.     if(i == numTries):
  942.         return False
  943.     return True
  944.  
  945. def try_remove(filename, numTries):
  946.     removed = False
  947.     i = 0
  948.     while os.path.exists(filename) and (not removed) and (i < numTries):
  949.         try:
  950.             os.remove(filename)
  951.             removed = True
  952.         except OSError:
  953.             print("Trying to remove "+filename+", may be locked...")
  954.             i += 1
  955.             time.sleep(1)
  956.     if(i == numTries):
  957.         return False
  958.     return True
  959.  
  960. def wait_for_access(filename, numTries):
  961.     i = 0
  962.     while (not os.path.exists(filename) or not os.access(filename, os.R_OK)) and i < numTries:
  963.         print("Waiting for access to "+filename+", may be locked...")
  964.         time.sleep(1)
  965.         i += 1
  966.     if(i == numTries):
  967.         return False
  968.     return True
  969.  
  970. # this will group all the tests together, prepare them as
  971. # a test suite, and run them.
  972. def run_file(filename,wants=[]):
  973.    
  974.     # move the student's code to a valid file.
  975.     if(not try_copy(filename,"student.py", 5)):
  976.         print("Failed to copy " + filename + " to student.py.")
  977.         quit()
  978.        
  979.     # import student's code, and *only* copy over the expected functions
  980.     # for later use.
  981.     import imp
  982.     count = 0
  983.     while True:
  984.         try:
  985.             import student
  986.             imp.reload(student)
  987.             break
  988.         except ImportError as e:
  989.             print("import error getting student.. trying again. "+os.getcwd(), os.path.exists("student.py"))
  990.             time.sleep(0.5)
  991.             count+=1
  992.             if count>3:
  993.                 raise ImportError("too many attempts at importing!")
  994.         except SyntaxError as e:
  995.             print("SyntaxError in "+filename+":\n"+str(e))
  996.             print("Run your file without the tester to see the details")
  997.             return(filename+"_SYNTAX_ERROR",None, None, None)
  998.         except NameError as e:
  999.             print("NameError in "+filename+":\n"+str(e))
  1000.             print("Run your file without the tester to see the details")
  1001.             return((filename+"_Name_ERROR",0,1))   
  1002.         except ValueError as e:
  1003.             print("ValueError in "+filename+":\n"+str(e))
  1004.             print("Run your file without the tester to see the details")
  1005.             return(filename+"_VALUE_ERROR",0,1)
  1006.         except TypeError as e:
  1007.             print("TypeError in "+filename+":\n"+str(e))
  1008.             print("Run your file without the tester to see the details")
  1009.             return(filename+"_TYPE_ERROR",0,1)
  1010.         except ImportError as e:           
  1011.             print("ImportError in "+filename+":\n"+str(e))
  1012.             print("Run your file without the tester to see the details or try again")
  1013.             return((filename+"_IMPORT_ERROR_TRY_AGAIN   ",0,1))
  1014.         except Exception as e:
  1015.             print("Exception in loading"+filename+":\n"+str(e))
  1016.             print("Run your file without the tester to see the details")
  1017.             return(filename+str(e.__reduce__()[0]),0,1)
  1018.         #except Exception as e:
  1019.         #   print("didn't get to import student yet... " + e)
  1020.     # but we want to re-load this between student runs...
  1021.     # the imp module helps us force this reload.s
  1022.    
  1023.     import student
  1024.     imp.reload(student)
  1025.    
  1026.     # make a global for each expected definition.
  1027.     def decoy(name):
  1028.         return (lambda x: "<no '%s' definition found>" % name)
  1029.        
  1030.     for fn in REQUIRED_DEFNS:
  1031.         globals()[fn] = decoy(fn)
  1032.         try:
  1033.             globals()[fn] = getattr(student,fn)
  1034.         except:
  1035.             print("\nNO DEFINITION FOR '%s'." % fn)
  1036.    
  1037.     # create an object that can run tests.
  1038.     runner1 = unittest.TextTestRunner()
  1039.    
  1040.     # define the suite of tests that should be run.
  1041.     suite1 = TheTestSuite(wants)
  1042.    
  1043.     # let the runner run the suite of tests.
  1044.     ans = runner1.run(suite1)
  1045.     num_errors   = len(ans.__dict__['errors'])
  1046.     num_failures = len(ans.__dict__['failures'])
  1047.     num_tests    = ans.__dict__['testsRun']
  1048.     num_passed   = num_tests - num_errors - num_failures
  1049.     # print(ans)
  1050.    
  1051.    
  1052.     if BATCH_MODE:
  1053.         # do the same for the extra credit.
  1054.         runnerEC = unittest.TextTestRunner()
  1055.         suiteEC = TheExtraCreditTestSuite(wants)
  1056.         ansEC = runnerEC.run(suiteEC)
  1057.         num_errorsEC   = len(ansEC.__dict__['errors'])
  1058.         num_failuresEC = len(ansEC.__dict__['failures'])
  1059.         num_testsEC    = ansEC.__dict__['testsRun']
  1060.         num_passedEC   = num_testsEC - num_errorsEC - num_failuresEC
  1061.         print(ansEC)
  1062.     else:
  1063.         num_passedEC = 0
  1064.    
  1065.     # remove our temporary file.
  1066.     os.remove("student.py")
  1067.     if os.path.exists("__pycache__"):
  1068.         shutil.rmtree("__pycache__")
  1069.     if(not try_remove("student.py", 5)):
  1070.         print("Failed to copy " + filename + " to student.py.")
  1071.    
  1072.     tag = ".".join(filename.split(".")[:-1])
  1073.     return (tag, num_passed, num_tests,num_passedEC)
  1074.  
  1075. # this determines if we were imported (not __main__) or not;
  1076. # when we are the one file being run, perform the tests! :)
  1077. if __name__ == "__main__":
  1078.     main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement