def test_create_truck_object_instance_multiple_times_with_valid_details( color, max_speed, acceleration, tyre_friction, max_cargo_weight): # Arrange truck1 = Truck(color=color, max_speed=max_speed, acceleration=acceleration, tyre_friction=tyre_friction, max_cargo_weight=max_cargo_weight) truck2 = Truck(color=color, max_speed=max_speed, acceleration=acceleration, tyre_friction=tyre_friction, max_cargo_weight=max_cargo_weight) # Act # Assert assert truck1.color == color assert truck1.max_speed == max_speed assert truck1.acceleration == acceleration assert truck1.tyre_friction == tyre_friction assert truck1.max_cargo_weight == max_cargo_weight assert truck2.color == color assert truck2.max_speed == max_speed assert truck2.acceleration == acceleration assert truck2.tyre_friction == tyre_friction assert truck2.max_cargo_weight == max_cargo_weight
def __init__(self, id_truck, id_driver, id_itinerary): Thread.__init__(self) self.id_truck = id_truck self.id_driver = id_driver new_driver = driver_to_db({'iddriver': id_driver}) self.id_itinerary = id_itinerary self.truck = Truck(self.id_truck) self.connection = None self.departure, self.arrival = self.truck.drive() self.departure = [self.departure['lng'], self.departure['lat']] self.arrival = [self.arrival['lng'], self.arrival['lat']] new_itinerary = itinerary_to_db({ 'iditinerary': id_itinerary, 'mission': 'Undefined', 'departure': self.departure, 'arrival': self.arrival }) if new_driver == 0: print('Driver id #%i created' % (self.id_driver)) elif new_driver == 1: print('Driver id #%i already in DB' % (self.id_driver)) if new_itinerary == 0: print('Itinerary id #%i created' % (self.id_itinerary)) elif new_itinerary == 1: print('Itinerary id #%i already in DB' % (self.id_itinerary))
def load_delayed_truck(self, truck: Truck, has_deadline=True): """ Loads a truck with delayed packages :param truck: :param has_deadline: :return: """ for pkg in self.database.table: if truck.not_full() is False: break if pkg.delivery_status != "At Hub": continue if has_deadline: if pkg.deadline == "EOD": continue if pkg.special_notes.__contains__("Delayed"): delay = pkg.special_notes[-8:] later_time = pkg.calculate_deadline(delay) depart_time = Package.calculate_deadline(truck.depart_at) if later_time > depart_time: truck.depart_at = delay if truck.load_package( pkg.pkg_id, self.destinations.get_location(pkg.address)): pkg.delivery_status = "In Route"
def find_a_way(self, truck: Truck): """ finds the shortest route along the stops from truck in O(N^2) time :param truck: truck with stops to make :return: the list of locations and the total distance traveled by the truck """ stops = list(truck.cargo.keys()) current = self.center # start at the Hub the_way = [current] distance = 0.0 while stops: result = self.nearest_neighbor(stops, current) distance += result[1] the_way.append(result[0]) current = stops.pop(0) packages = truck.unload_package(current) delivery_time = Package.get_delivery_time(distance, truck.speed, truck.depart_at) for pkg_id in packages: pkg = self.database.look_up(pkg_id) pkg.delivery_status = "Delivered" pkg.delivery_time = delivery_time distance += self.destinations.get_distance( the_way[-1], self.center) # return to the Hub truck.depart_at = Package.get_delivery_time(distance, truck.speed, truck.depart_at) return the_way, distance
def load_any_truck_(self, truck: Truck): """ Loads the next available package from hash table onto the truck. :param truck:Truck :return:None """ for pkg in self.database.table: if truck.not_full() is False: break if pkg.delivery_status != "At Hub": continue if truck.load_package(pkg.pkg_id, self.destinations.get_location(pkg.address)): pkg.delivery_status = "In Route"
def load_same_stop_truck(self, truck: Truck): """ Loads packages with delivery addresses that the truck is already going to. :param truck:Truck :return:None """ for pkg in self.database.table: if truck.not_full() is False: break if pkg.delivery_status != "At Hub": continue pkg_location = self.destinations.get_location(pkg.address) if pkg_location in truck.cargo.keys(): if truck.load_package(pkg.pkg_id, pkg_location): pkg.delivery_status = "In Route"
def test_apply_break_when_current_speed_with_different_acceleration_more_than_tyre_friction_returns_current_speed(): # Arrange truck = Truck(color="Red", max_speed=50, acceleration=10, tyre_friction=3, max_cargo_weight=100) current_speed = 27 truck.start_engine() truck.accelerate() truck.accelerate() truck.accelerate() # Act truck.apply_brakes() # Assert assert truck.current_speed == current_speed
def load_truck_2(self, truck: Truck): """ Loads all packages that must be on truck 2. :param truck:Truck :return:None """ for pkg in self.database.table: if truck.not_full() is False: break if pkg.delivery_status != "At Hub": continue if pkg.special_notes.endswith('truck 2'): if truck.load_package( pkg.pkg_id, self.destinations.get_location(pkg.address)): pkg.delivery_status = "In Route"
def test_accelerate_truck_when_engine_stoped_and_return_start_engine_to_accelerate( capfd): # Arrange truck = Truck(color='Blue', max_speed=1, acceleration=1, tyre_friction=1, max_cargo_weight=1) start_engine_to_accelerate = "Start the engine to accelerate\n" # Act truck.accelerate() output = capfd.readouterr() # Assert assert output.out == start_engine_to_accelerate
def test_sound_horn_when_truck_engine_stoped_and_return_start_engine_to_sound_horn( capfd): # Arrange truck = Truck(color='Blue', max_speed=5, acceleration=4, tyre_friction=3, max_cargo_weight=1) start_engine_to_sound = "Start the engine to sound_horn\n" # Act truck.sound_horn() output = capfd.readouterr() # Assert assert output.out == start_engine_to_sound
def truck(): truck_obj = Truck(color='Blue', max_speed=1, acceleration=1, tyre_friction=1, max_cargo_weight=1) return truck_obj
def truck2(): # Our Fixture function truck_obj = Truck(color="blue", max_speed=50, acceleration=20, tyre_friction=4, max_cargo_weight=40) return truck_obj
def get_hours_working(self): self.minutes_passed = self.miles_traveled / Truck(-1).speed_miles_min hours = int(self.minutes_passed / 60) minutes_left = self.minutes_passed % 60 new_hour = self.hour_of_start + timedelta(hours=hours, minutes=minutes_left) return new_hour
def generate_dataset( N=100, sigma=0.1, mu=0, balanced_sample=True, # equal number of each class p=[1. / 5] * 5, # for multinomial distribution of classes datapath="/home/joel/datasets/csi5138-img/dataset1" ): # do not add trailing / for i in range(N): if balanced_sample: c = i % 5 else: c = np.random.multinomial(1, p) # choose class from distribution p c = np.argmax(c) # construct vector of N(mu, sigma**2) var = sigma * np.random.randn(5) + mu # no switch statement in Python?#yes noswitch statement in python if c == 0: obj = Dog(*var) elif c == 1: obj = Truck(*var) elif c == 2: obj = Airplane(*var) elif c == 3: obj = Person(*var) else: obj = Frog(*var) obj.generate(datapath, i)
def truck3(): # Our Fixture function truck_obj = Truck(color="blue", max_speed=30, acceleration=3, tyre_friction=3, max_cargo_weight=20) return truck_obj
def truck(): # Our Fixture function truck_obj = Truck(color="Red", max_speed=30, acceleration=10, tyre_friction=3, max_cargo_weight=30) return truck_obj
def __init__(self, df: pd.DataFrame, T=math.inf, C=math.inf, strategy=0): # statistical information self.df = df self.id2station = dict() # id to station instance self.station_set = set() # set of id self.df_pop = None # type: pd.DataFrame # finish id2station and station_set for i in range(len(self.df)): s = self.df["start station id"][i] if s not in self.station_set: self.station_set.add(s) self.id2station[s] = cb_utils.Station( s, self.df["start station latitude"][i], self.df["start station longitude"][i]) s = self.df["end station id"][i] if s not in self.station_set: self.station_set.add(s) self.id2station[s] = cb_utils.Station( s, self.df["end station latitude"][i], self.df["end station longitude"][i]) # members for running the scheme self.t = None # type: datetime.datetime self.T, self.C, self.strategy = T, C, strategy self.truck = Truck(self.id2station[self.df["start station id"][0]], T=T, C=C) self.dist = dict() # s_id1, s_id2 distance for s1 in self.station_set: for s2 in self.station_set: self.dist[(s1, s2)] = \ cb_utils.dist_bet(self.id2station[s1], self.id2station[s2]) self.neg_re = 0 # negtive reward till t temp_df = df.sort_values(by='starttime')[[ 'stoptime', 'starttime', 'start station id', 'end station id' ]] # use these two sequences to detect events self.start_sequence = deque(tuple(x) for x in temp_df.values) # type: deque self.end_sequence = [] # members for observation self.loss_history = [] # (time, loss) self.station_popularity_history = [] self.observe_s = None
def load_zip_code_truck(self, truck: Truck): """ Loads packages with similar zip_codes onto the given truck. :param truck:Truck :return:None """ zip_code_locations = self.destinations.get_zip_code_matches( truck.cargo.keys()) for pkg in self.database.table: if truck.not_full() is False: break if pkg.delivery_status != "At Hub": continue pkg_location = self.destinations.get_location(pkg.address) if pkg_location in zip_code_locations: if truck.load_package(pkg.pkg_id, pkg_location): pkg.delivery_status = "In Route"
def test_unload_when_truck_in_motion_and_print_string(capfd): # Arrange truck = Truck(color='Blue', max_speed=5, acceleration=4, tyre_friction=3, max_cargo_weight=100) truck.start_engine() truck.load(1) truck.accelerate() cannot_unload = "Cannot unload cargo during motion\n" # Act truck.unload(1) output = capfd.readouterr() # Assert assert output.out == cannot_unload
def load_early_truck(self, truck: Truck): """ Load truck with packages that have deadlines before 10:30 AM. :param truck: :return: """ for pkg in self.database.table: if truck.not_full() is False: break if pkg.delivery_status != "At Hub": continue if len(pkg.special_notes) > 1: continue if pkg.calculate_deadline(pkg.deadline) <= 10.5: if truck.load_package( pkg.pkg_id, self.destinations.get_location(pkg.address)): pkg.delivery_status = "In Route"
def test_load_cargo_when_truck_is_stopped_and_current_speed_is_not_zero_returns_statement( capsys): # Arrange truck = Truck(color="Red", max_speed=50, acceleration=10, tyre_friction=30, max_cargo_weight=100) truck.start_engine() truck.accelerate() statement = "Cannot load cargo during motion\n" # Act truck.stop_engine() truck.load(50) captured = capsys.readouterr() # Assert assert captured.out == statement
def test_truck_instance_with_invalid_max_speed_attr_raises_error(): # Arrange error_message = 'Invalid value for max_speed' # Act with pytest.raises(ValueError) as raised_error: Truck(color="Red", max_speed=0, acceleration=10, tyre_friction=3, max_cargo_weight=100) assert str(raised_error.value) == error_message # Assert with pytest.raises(ValueError) as raised_error: Truck(color="Red", max_speed=-1, acceleration=10, tyre_friction=3, max_cargo_weight=100) assert str(raised_error.value) == error_message # Assert
def test_apply_break_when_current_speed_is_less_than_tyre_friction(): # Arrange truck = Truck(color="Red", max_speed=50, acceleration=10, tyre_friction=30, max_cargo_weight=100) current_speed = 0 truck.start_engine() truck.accelerate() # Act truck.apply_brakes() # Assert assert truck.current_speed == current_speed
def add_truck(self, count): """ Adds a number of new trucks to Hub according to the given count. :param count:int :return:None """ while count > 0: new_truck = Truck(count) self.trucks.append(new_truck) count -= 1 self.trucks.reverse()
def simple_sim(): routes = [ new_depot("Bluefield", [ Cargo('Utensils', "Washington"), Cargo('TVs', "Carrington") ]), new_depot("Jamestown", [ Cargo('Phones', "Dartfield"), Cargo('Computers', "Bloomington") ]), new_depot("Washington", []), new_depot("Carrington", [ Cargo('Toys', 'Bloomington') ]), new_depot("Bloomington", []), new_depot("Dartfield", []) ] t1 = Truck("Iron Giant", 4, [routes[0], routes[2], routes[4], routes[5]]) t2 = Truck("The Train", 2, [routes[0], routes[1], routes[3], routes[4], routes[5]]) trucks = [t1, t2] iteration = 1 all_trucks_stopped = False while not all_trucks_stopped: all_trucks_stopped = True # assume true output_all(routes, trucks, iteration) for t in trucks: if not t.has_stopped(): all_trucks_stopped = False # at least one truck is still moving d = t.current_depot() # get the current depot of the truck d.take_cargo(t) # the depot will take cargo to the truck d.give_cargo(t) # the depot will give cargo to the truck t.move() # the truck will move to the next depot # output_all(routes, trucks, iteration) iteration += 1
def test_load_when_truck_not_in_motion_with_valid_load_value_equals_to_zero_and_update_load_in_truck( ): # Arrange color = 'Blue' max_speed = 5 acceleration = 4 tyre_friction = 3 max_cargo_weight = 100 truck = Truck(color=color, max_speed=max_speed, acceleration=acceleration, tyre_friction=tyre_friction, max_cargo_weight=max_cargo_weight) load_value = 0 # Act truck.load(0) # Assert assert truck.load_value == load_value
def test_invalid_max_speed_attr_for_truck(color, max_speed, acceleration, tyre_friction, max_cargo_weight): #arrange #act with pytest.raises(Exception) as err: assert Truck(color=color, max_speed=max_speed, acceleration=acceleration, tyre_friction=tyre_friction, max_cargo_weight=max_cargo_weight) #assert assert str(err.value) == "Invalid value for max_speed"
def _get_trucks_from_file(inp_file): ''' Internal function to get trucks from a csv. Takes input file path, yields assembled Truck objects ''' with open(inp_file, 'r') as inp: first_line = True for line in inp: items = line.strip().split(",") if first_line: name_idx = items.index("Applicant") address_idx = items.index("Address") food_idx = items.index("FoodItems") status_idx = items.index("Status") lat_idx = items.index("Latitude") lon_idx = items.index("Longitude") first_line = False continue status = items[status_idx] if status != "APPROVED": #Don't want expried/requested trucks continue t = Truck() try: #Some trucks don't have latlong; could GeoCode from address, but that's another project t.lat = float(items[lat_idx]) t.lon = float(items[lon_idx]) except ValueError: continue t.name = items[name_idx] t.address = items[address_idx] t.food = [f.strip().upper() for f in items[food_idx].split(":")] yield t
def test_truck_instance_with_invalid_tyre_friction_attr_raises_error( tyre_friction): # Arrange error_message = 'Invalid value for tyre_friction' # Act with pytest.raises(ValueError) as raised_error: Truck(color="Blue", max_speed=10, acceleration=5, tyre_friction=tyre_friction, max_cargo_weight=100) assert str(raised_error.value) == error_message
def test_truck_object_instance_create_and_engine_status(): # Arrange truck = Truck(color='Blue', max_speed=5, acceleration=4, tyre_friction=3, max_cargo_weight=1) engine_started = False # Act # Assert assert truck.is_engine_started == engine_started
def test_create_truck_object_with_invalid_acceleration_value_raise_error( color, max_speed, acceleration, tyre_friction, max_cargo_weight): # Arrange # Act with pytest.raises(ValueError) as truck: assert Truck(color=color, max_speed=max_speed, acceleration=acceleration, tyre_friction=tyre_friction, max_cargo_weight=max_cargo_weight) # Assert assert str(truck.value) == 'Invalid value for acceleration'
def test_truck_changable_top_speed(self): truck = Truck() truck.top_speed = 100 self.assertEqual(truck.top_speed, 100)
def test(): car = Truck('GMC', configuration) car.display() print car.power
def test_truck_has_carriage_when_has_none(self): truck = Truck() self.assertEqual(truck.has_carriage(), False)
def test_truck_has_carry_limit(self): truck = Truck() truck.carry_limit = 1000 self.assertEqual(truck.carry_limit, 1000)
def test_truck_can_attach_limit_carriage(self): truck = Truck() truck.carry_limit = 1000 result = truck.attach_carriage(1000) self.assertEqual(result, True)
def test_truck_has_carriage_when_has(self): truck = Truck() truck.current_carriage_weight = 100 self.assertEqual(truck.has_carriage(), True)
def test_truck_can_attach_heavy_carriage(self): truck = Truck() truck.carry_limit = 1000 result = truck.attach_carriage(2000) self.assertEqual(result, False)
def test_truck_can_detach_cariage(self): truck = Truck() truck.current_carriage_weight = 100 truck.detach_carriage() self.assertEqual(truck.current_carriage_weight, None)
def test_truck_not_runns_to_error_when_try_to_detach_not_existing_cariage(self): truck = Truck() truck.detach_carriage() self.assertEqual(truck.current_carriage_weight, None)
#!/usr/bin/python3 """ Test file for Vehicles """ from car import Car from truck import Truck car = Car(4000, "Volvo", "X90", 2015) print(car.price()) truck = Truck(5000, "Scania", "XBC", 2014) print(truck.price())
def test_truck_changable_ccm(self): truck = Truck() truck.ccm = 100 self.assertEqual(truck.ccm, 100)