def test_elevator_can_open_doors_on_start(capsys): elevator = Elevator(name="Elevator 1") doors_opening_message = Elevator.MESSAGE_TEMPLATES["doors_opening"].format( elevator.name) elevator.open_doors() stdout = capsys.readouterr().out.split("\n") assert check_stdout([doors_opening_message], stdout)
def test_async(capsys): async def open_and_close_doors(ele): await ele.open_doors() await ele.close_doors() elevator_1 = Elevator(name="Elevator 1") elevator_2 = Elevator(name="Elevator 2") expected_messages_order = [ Elevator.MESSAGE_TEMPLATES["doors_opening"].format(elevator_1.name), Elevator.MESSAGE_TEMPLATES["doors_opening"].format(elevator_2.name), Elevator.MESSAGE_TEMPLATES["doors_closing"].format(elevator_1.name), Elevator.MESSAGE_TEMPLATES["doors_closing"].format(elevator_2.name) ] async def main(): await asyncio.gather(open_and_close_doors(elevator_1), open_and_close_doors(elevator_2)) time_1 = time.time() asyncio.run(main()) stdout = capsys.readouterr().out.split("\n") delta_time = time.time() - time_1 # assuming door_action duration is the same assert delta_time > elevator_1.door_action_duration * 2 and delta_time < elevator_2.door_action_duration * 4 check_stdout(expected_messages_order, stdout)
def test_closest_elevator_to_floor(self): elevators = [Elevator(current_floor=0), Elevator(current_floor=2), Elevator(current_floor=5)] behaviour = ClosestCallPrepend() result = behaviour.closest_elevator_to_floor(elevators, 3) self.assertEqual(result, 1)
def main(): parser = argparse.ArgumentParser() parser.add_argument( "-f", "--floors", help="number of floors in the building", type=int, choices=range(5, 21), default=12 ) parser.add_argument( "-H", "--height", help="height of the floor (meters)", type=float, default=2.65 ) parser.add_argument( "-v", "--velocity", help="velocity of the elevator cabin (meters per second)", type=float, default=3.0 ) parser.add_argument( "-d", "--doors_delay", help="time delay while cabin doors are open (seconds)", type=float, default=3.0 ) parser.add_argument( "-p", "--port", help="controller port", type=int, default=4455 ) args = parser.parse_args() print("Welcome to Elevator Simulator") print("Floors:\t\t{floors:>8}\nHeight:\t\t{height:>8}\nVelocity:\t{velocity:>8}\nDoors delay:{doors_delay:>8}" .format(**vars(args))) loop = asyncio.get_event_loop() controller = Controller('Elevator Controller', port=args.port, loop=loop) print("Elevator controller server is listening on port {}".format(args.port)) elevator = Elevator( floors=args.floors, height=args.height, velocity=args.velocity, doors_delay=args.doors_delay ) tasks = asyncio.gather( loop.create_task(elevator.handle_commands(controller.get_command_queue())), loop.create_task(elevator.run()) ) try: loop.run_until_complete(tasks) except KeyboardInterrupt: print("Shutdown requested") tasks.cancel() loop.run_forever() finally: loop.close() return 0
def test_init(self): conf = defaultdict(lambda: 0) initial_floor = random.randint(1, 100000) conf["INITIAL_FLOOR"] = initial_floor elevator = Elevator(conf) current_ts, current_location = elevator.get_status() self.assertEqual(current_ts, 0) self.assertEqual(current_location, initial_floor)
def test_changing_directions_no_furtherup(self): e = Elevator(ElevatorLogic()) e.call(2, DOWN) e.call(4, UP) e.run_until_stopped() self.assertEqual(e._logic_delegate.debug_path, [1, 2, 3, 4]) e.run_until_stopped() self.assertEqual(e._logic_delegate.debug_path, [1, 2, 3, 4, 3, 2])
def test_elevator_can_only_carry_passengers_when_door_is_open(): elevator = Elevator(name="Elevator 1") assert elevator.door_status == "closed" passenger_1 = Passenger(destination=2) try: elevator.load_passengers([passenger_1]) assert False, "No Exception was thrown" except Exception as ex: assert str(ex) == "You tried to load passengers into {} while it was in state {}!".format(elevator.name, elevator.state)
def test_elevator_will_not_alight_passengers_at_wrong_floor(): elevator = Elevator(name="Elevator 1") passenger_1 = Passenger(destination=2) passenger_2 = Passenger(destination=2) elevator.open_doors() elevator.load_passengers([passenger_1, passenger_2]) elevator.goto_floor(3) elevator.unload_passengers() assert len(elevator.passengers) == 2
def test_directionality(self): e = Elevator(ElevatorLogic()) e.call(2, DOWN) e.select_floor(5) e.run_until_stopped() self.assertEqual(e._logic_delegate.debug_path, [1, 2, 3, 4, 5]) e.run_until_stopped() self.assertEqual(e._logic_delegate.debug_path, [1, 2, 3, 4, 5, 4, 3, 2])
def test_unordered_select(self): info("Test: {0}".format("test_unordered_select")) elevator = Elevator(10, 4) elevator.select(5) elevator.select(2) elevator.select(0) elevator.select(8) elevator.select(7) elevator.act() self.assertEqual(elevator.current, 0)
def test_call_and_select(self): info("Test: {0}".format("test_call_and_select")) elevator = Elevator(10, 4) from_floor = 2 to_floor = 6 elevator.call(from_floor) elevator.act() elevator.select(to_floor) elevator.act() self.assertEqual(elevator.current, to_floor)
def test_iterate_up(self): e = Elevator(current_floor=0) e.destinations.append(2) e.door_state = DoorState.OPEN result = e.iterate() self.assertEqual(result, Action.MOVE_UP) self.assertEqual(e.door_state, DoorState.CLOSED) self.assertEqual(e.current_floor, 1)
def test_iterate_blocked(self): e = Elevator(current_floor=0) e.destinations.append(2) e.blocked_for = 5 result = e.iterate() self.assertEqual(result, Action.BLOCKED) self.assertEqual(e.current_floor, 0) self.assertEqual(e.blocked_for, 4)
def main(): num_passengers = int(input("How many passengers does the building have?")) num_floors = int(input("How many floors does the building have?")) strategy = int( input( "Which strategy do you want to use? (1 for FIFO, 2 for move-to-max-min)" )) building = Building(num_passengers, num_floors) elevator = Elevator(num_floors) passengers = [] for i in range(num_passengers): start_floor = random.choice(range(elevator.n_floors)) destination_floor = random.choice(range(elevator.n_floors)) while start_floor == destination_floor: destination_floor = random.choice(range(elevator.n_floors)) passenger = Passenger(start_floor, destination_floor) passengers.append(passenger) elevator.add_call(passenger.start_floor, passenger.destination, passenger) elevator.snapshot() if strategy == 1: for passenger in passengers: elevator.FIFO() else: elevator.max_floor_strategy() print "\n" costs = [] for passenger in passengers: costs.append(passenger.time_cost) print "Average cost: ", np.mean(costs), " floors" print "Average squared cost: ", np.mean([i**2 for i in costs]), " floors" print "Median cost: ", np.median(costs), " floors" print "Maximum cost: ", max(costs), " floors"
def test_elevator_can_carry_passengers_to_one_floor(capsys): elevator = Elevator(name="Elevator 1") passenger_1 = Passenger(destination=2) passenger_2 = Passenger(destination=2) elevator.open_doors() elevator.load_passengers([passenger_1, passenger_2]) assert passenger_1 in elevator.passengers assert passenger_2 in elevator.passengers elevator.goto_floor(2) elevator.unload_passengers() assert len(elevator.passengers) == 0
def main(): direcao = up_down() start_pos = pos_init() print('*'*55) posicoes = receive_inputs() if start_pos is not None: if len(posicoes) != 0: elevator = Elevator(posicoes=posicoes, direcao=direcao, start_pos=start_pos) elevator.run()
def test_iterate_open_doors_not_lobby(self): e = Elevator(current_floor=5) e.door_state = DoorState.CLOSED e.destinations.append(5) result = e.iterate() self.assertEqual(result, Action.OPEN_DOORS) self.assertEqual(e.door_state, DoorState.OPEN) self.assertEqual(len(e.destinations), 0) self.assertEqual(e.blocked_for, ActionTimings[Action.OPEN_DOORS] - 1)
def test_loading_to_idle(self): elevator = Elevator(lobby_load_delay=1, load_delay=1, verbosity="off") elevator.simulate_tick([Call(origin=1, destination=2, size=1, init_time=1)]) self.assertEqual(elevator.state, 'LOADING') elevator.simulate_tick([]) elevator.simulate_tick([]) self.assertEqual(elevator.state, 'MOVING') elevator.simulate_tick([]) self.assertEqual(elevator.state, 'LOADING') elevator.simulate_tick([]) elevator.simulate_tick([]) self.assertEqual(elevator.state, 'IDLE')
class TestElevator(TestCase): elevator = None def setUp(self): self.elevator = Elevator() def test_1(self): self.elevator.load = Elevator.MAX_LOAD + 1 self.assertTrue(self.elevator.is_overloaded()) self.elevator.load = Elevator.MAX_LOAD - 1 self.assertFalse(self.elevator.is_overloaded())
def robotInit(self): print('robotinit') self.slowMode = True self.drivetrain = Drivetrain() self.elevator = Elevator() self.driver = wpilib.XboxController(JOYSTICK_PORT) self.intake = Intake() self.limelight = CitrusLumen() self.autonTimer = wpilib.Timer() self.autonCase = None self.autonAbort = None self.debugging = False
def random_elevator(): e = Elevator( [ Platform(floor, [ Person(random.randrange(FLOORS)) for _ in range(PEOPLE_PER_FLOOR) ]) for floor in range(FLOORS) ], capacity=ELEVATOR_CAPACITY, ) while not e.full: e.add(Person(random.randrange(FLOORS))) return e
def main(): for i in range(0, FLOOR): # initial locks at every floor _lock = threading.Lock() _lock.acquire() floor_lock.append(_lock) global elevator elevator = Elevator() elevator.start() RandomAccessFloor(elevator).start() # start random access floors RandomCreatePeople(100).start() # start creating people
def add_person_to_lift(self, elevator: Elevator, person: Person) -> None: """ Moves a person into a lift. TODO: Provide better abstractions for adding and removing people. """ if not elevator.door.is_open: elevator.open_door() elevator.people.append(person) self.waiting_for_elevator.remove(person) print( f"{person.name} has entered the {elevator} at {elevator.floor} floor" )
def main(): """Точка входа в программу""" args = parse_args() elevator = Elevator(**args) events_to_output = ['passed_floor', 'opened_doors', 'closed_doors'] for event in events_to_output: elevator.subscribe(event, print_elevator_event) stop = Event() elevator.start(stop) for line in sys.stdin: try: name, floor = line.split(SEPARATOR, 2) if int(floor) not in range(1, int(args['n']) + 1): print(_('< ERROR: Wrong floors number: min=%d, max=%d' % (1, args['n']))) continue elevator.perform(name, int(floor)) except ValueError: print(_('< ERROR: Wrong input format. Expected: action_name floor_number')) except WrongActionError: print(_('< ERROR: Wrong action')) else: print(_('< OK')) stop.set()
def test_multiple_select_down(self): info("Test: {0}".format("test_multiple_select_down")) elevator = Elevator(10, 8) elevator.select(5) elevator.select(2) elevator.select(0) elevator.act() self.assertEqual(elevator.current, 0)
def score(self, total_elapsed): waits = [] for r in self._all_riders: waits.append( (total_elapsed if r.trip_start is None else r.trip_start) - r.started_waiting) trip_efficiencies = [] satisfied = [r for r in self._all_riders if r.trip_end is not None] trip_distances = [ abs(r.start_floor_num - r.destination_floor_num) for r in satisfied ] sum_of_distances = sum(trip_distances) for i, r in enumerate(satisfied): optimal = Elevator.calculate_optimal_trip(r.start_floor_num, r.destination_floor_num) base_efficiency = optimal / (r.trip_end - r.trip_start) trip_efficiencies.append(base_efficiency * trip_distances[i] / sum_of_distances) if len(trip_efficiencies) == 0: mean_trip_efficiency = 0 else: mean_trip_efficiency = statistics.mean(trip_efficiencies) return { 'finished_rides': len(satisfied), 'unfinished_rides': len([r for r in self._all_riders if r.trip_end is None]), 'average_wait': statistics.mean(waits), 'trip_efficiency': round(mean_trip_efficiency * 100), }
def __init__(self, env, floor_count, elevator_count): self.env = env self.floor_count = floor_count self.elevators = [ Elevator(self.env, i) for i in range(1, elevator_count + 1) ] self.sectors = self.make_sectors(floor_count)
def remove_person_to_lift(self, elevator: Elevator, person: Person) -> None: """ Removes people from a lift. TODO: Provide better abstractions removing people from a lift. """ if not elevator.door.is_open: elevator.open_door() elevator.people.remove(person) # If there are not people in the lift, it is not moving nowhere if not elevator.people: elevator.moving_to = None print( f"{person.name} has {elevator} the lift at {elevator.floor} floor")
def init_elevators(self, **kwargs): self.elevators = [] for idx in range(self.plan.n_els): self.elevators.append(Elevator(idx, self.plan.n_floors, **kwargs)) self.plan.strategy.init_elevators(self.elevators) if self.debug: self.print_elevators_info()
def __init__(self, parser, n_floors, n_elevators): self.parser = parser self.n_floors = n_floors self.elevators = [] for i in range(n_elevators): self.elevators.append(Elevator(i, self.n_floors // 2)) self.active_requests = []
def __init__(self, num_elevators, num_floors): # the elevator are numbered from 0 to num_elevators-1 self.num_elevators = num_elevators # the floors are numbered from 0 to num_floors-1 self.num_floors = num_floors # the elevator objects are saved in a dictionary keyed by their number self.elevators = dict() self.queue = Queue.Queue() for i in range(self.num_elevators): e = Elevator(self.num_floors) e.setName(i) # the elevators are threaded e.start() self.elevators[i] = e threading.Thread.__init__(self)
def __init__(self, nfloors, max_new_people): self.nfloors = nfloors self.expo_lambda = [1. / (f ** 2 + 1) for f in xrange(nfloors)] self.intervals = [int(random.expovariate(self.expo_lambda[f])) for f in xrange(self.nfloors)] self.waiting_people = [[] for _ in xrange(self.nfloors)] self.elevator_people = [[] for _ in xrange(self.nfloors)] self.max_new_people = max_new_people self.elevator = Elevator(self.nfloors) self.stats = Stats()
def __init__(self): print "booogh" self.floors = [] self.elevators = [] self.time = 0 for i in range (int(util.read_parameter("floors.number"))): self.floors.append(Floor(i)) util.log("Floor " + str(i) + "created") for i in range (int(util.read_parameter("elevators.number"))): capacities = (list(util.read_parameter("elevators.capacity"))) idle_floors = (list(util.read_parameter("elevators.idle_floor"))) speeds = (list(util.read_parameter("elevators.speed"))) elv = Elevator() elv.set_capacity(capacities[i]) elv.set_idle_floor(idle_floors[i]) elv.set_speed(speeds[i]) self.elevators.append(elv) util.log("Elevator " + str(i) + "created") self.eventList = EventList for floor in self.floors: for event in floor.generate_events(): self.eventList.addEvent(event)
def reset_elevator(self): self.el = Elevator(0, 10)
def setUp(self): self.e = Elevator(id=10)
class test_elevator(unittest.TestCase): def setUp(self): self.e = Elevator(id=10) def test_update(self): self.e.update(4, 9) self.assertEqual(self.e.floor, 4) self.assertEqual(self.e.goal, 9) self.assertEqual(self.e.direction, 1) self.e.update(10, 5) self.assertEqual(self.e.floor, 10) self.assertEqual(self.e.goal, 5) self.assertEqual(self.e.direction, -1) def test_add_request(self): self.e.update(5, 8) self.assertEqual(self.e.floor, 5) self.assertEqual(self.e.goal, 8) # add request in the direction of the elevator self.e.addRequest(7, 10) self.assertEqual(self.e.floor, 5) self.assertEqual(self.e.goal, 7) # test priority queue implement. closest floor gets updated # hence no FCFS self.e.addRequest(6, 10) self.assertEqual(self.e.floor, 5) self.assertEqual(self.e.goal, 6) def test_step(self): # setting a starting state self.e.update(3, 9) self.assertEqual(self.e.floor, 3) self.assertEqual(self.e.goal, 9) # moving quickly through time for i in range(3): self.e.step() self.assertEqual(self.e.floor, i+1+3) self.assertEqual(self.e.goal, 9) self.assertEqual(self.e.floor, 6) self.assertEqual(self.e.goal, 9) # add a new request and making sure # goals are updated correctly self.e.addRequest(7, 11) self.assertEqual(self.e.goal, 7) self.e.step() self.assertEqual(self.e.goal, 9) self.e.step() self.e.step() self.assertEqual(self.e.floor, 9) self.assertEqual(self.e.goal, 11) # calling step multiple times shouldn't change # state when the lift has stopped for i in range(10): self.e.step() self.assertEqual(self.e.floor, 11) self.assertEqual(self.e.goal, 11)
def ElevatorTests(): print "" print "-----Elevator Tests Starting------" elevator = Elevator() elevator.start() elevator.add_request(4) elevator.add_request(7) elevator.add_request(3) elevator.add_request(9) sleep(5) elevator.add_request(3) elevator.add_request(5) elevator.add_request(2) sleep(5) elevator.add_request(10) elevator.add_request(14) sleep(5) print "-----Elevator Tests Passed-------"
class Simulation: """ Runs the elevator simulation. """ def __init__(self, nfloors, max_new_people): self.nfloors = nfloors self.expo_lambda = [1. / (f ** 2 + 1) for f in xrange(nfloors)] self.intervals = [int(random.expovariate(self.expo_lambda[f])) for f in xrange(self.nfloors)] self.waiting_people = [[] for _ in xrange(self.nfloors)] self.elevator_people = [[] for _ in xrange(self.nfloors)] self.max_new_people = max_new_people self.elevator = Elevator(self.nfloors) self.stats = Stats() def run(self, time): """ Main loop of simulation. At each time step, new people request the elevator, the elevator makes an action, and statistics are aggregated about wait times and elevator position. """ for t in xrange(time): self.generate_new_requests() action = self.elevator.action() self.update(action) self.stats.display_stats() def generate_new_requests(self): """ Creates new people that request the elevator. Each floor has a separate countdown timer before new people are created at that floor. The intervals are determined by an exponential distribution, with varying parameters between floors. Once a timer hits 0, a random number of new people are created at the floor who request the elevator. """ requests = [] for floor in xrange(self.nfloors): if self.intervals[floor] == 0: # Create new people on this floor who request elevator. new_people = int(random.random() * self.max_new_people) + 1 for _ in xrange(new_people): self.waiting_people[floor].append(Person(self.nfloors, floor)) requests.append(floor) # New interval until floor spawns new people. self.intervals[floor] = int(random.expovariate(self.expo_lambda[floor])) + 1 else: # Decrement timer. self.intervals[floor] -= 1 self.elevator.new_requests(requests) def update(self, action): """ Updates the state of people on the floor the elevator has stopped at. Also updates statistics about wait times and elevator position. """ f = self.elevator.current_floor self.stats.update_floor(f) if action == Actions['open']: # People getting off on this floor. for p in self.elevator_people[f]: self.stats.update_wait(p) self.elevator_people[f] = [] # All waiting people get on the elevator and press their desired location. floor_requests = [] for p in self.waiting_people[f]: floor_requests.append(p.desired_floor) self.elevator_people[p.desired_floor].append(p) self.elevator.new_requests(floor_requests) self.waiting_people[f] = [] for f in xrange(self.nfloors): for p in self.elevator_people[f]: p.wait(True) for p in self.waiting_people[f]: p.wait(False)
from flask import Flask from flask import request from datetime import datetime from datetime import timedelta app = Flask(__name__) logging.basicConfig(level=logging.DEBUG) LOCK_FILENAME = "reserved_for.txt" LOCK_TIMER_SECONDS = 60 # Elevator thread logging.info('creating elevator thread') kill_event = threading.Event() queue = Queue() elevator = Elevator(kill_event) elevator.daemon = True elevator.start() # Watch dog thread def watch_dog(): while True: # Clean up if lock has expired. if os.path.isfile(LOCK_FILENAME): file_age_in_seconds = time.time() - os.path.getmtime(LOCK_FILENAME) if file_age_in_seconds > LOCK_TIMER_SECONDS: locked_ip = None with open(LOCK_FILENAME, 'r') as f: locked_ip = f.read() logging.info('releasing lock held by IP {}'.format(locked_ip)) os.remove(LOCK_FILENAME)
fang.shortDescription = "small knife with a faint glow" fang.keywords = ['knife', 'dagger'] fang.verb = english.Verb("stab") r_bedroom = mc.Room("Bedroom") r_bedroom.longDescription = "Your bedroom." r_apartment = mc.Room("An apartment") r_apartment.longDescription = "Your room, a desk sits in the corner." r_cy = mc.Room("Courtyard") r_cy.longDescription = "You are standing in front of a large concrete building.\ There is a small park with concrete benches and countles scooters parked on\ the side walk. The guard sits quietly in his little shelter near the steps." r_lobby = mc.Room("Lobby") r_lobby.longDescription = "A looby. It smells funny." elevator = Elevator() elevator.buildFloors({1: r_lobby, 10: r_apartment}) r_apartment.append(mc.Collection(100, "dollars")) r_apartment.append(cretin) r_lobby.addExit(r_cy, "south") r_apartment.append(desk) r_apartment.append(backpack) r_apartment.append(Hestia()) r_apartment.addExit(r_bedroom, "east") r_bedroom.append(Whiteboard()) player = tc.LocalPlayer(cretin)
class TestElevator: """Test the Elevator class and its internal methods""" def setup(self): state = { 'id': 0, 'floor': 0 } self.elevator = Elevator(state, 10) def test_go_to_up(self): """Elevator will go up""" will_do_it = self.elevator.go_to(2, 1) assert self.elevator.stops[-1] == 2 assert will_do_it is True def test_get_command(self): """Elevator will give the correct command object""" self.elevator.go_to(2, 1) comm = self.elevator.get_command() assert comm.direction == 1 assert comm.id == 0 assert comm.speed == 1 def test_process_buttons(self): """Will take buttons in and set up the next stops""" buttons = [2, 3] self.elevator.process_buttons(buttons) assert self.elevator.stops == buttons new_buttons = [3, 4] self.elevator.process_buttons(new_buttons) assert self.elevator.stops == [2, 3, 4] def test_update_state_no_buttons(self): """Takes in a state object with no buttons""" state = { 'id': 1, 'floor': 2 } self.elevator.update_state(state) assert self.elevator.location == state['floor'] def test_update_state_with_buttons(self): """Takes in a state object with buttons""" state = { 'id': 1, 'floor': 2, 'buttons_pressed': [1, 2] } self.elevator.update_state(state) assert self.elevator.location == state['floor'] assert self.elevator.stops == state['buttons_pressed'] def test_update_state_with_more_buttons(self): """Updates the elevator state by adding more buttons""" self.elevator.process_buttons([1, 2]) state = { 'id': 1, 'floor': 2, 'buttons_pressed': [2, 3] } self.elevator.update_state(state) assert self.elevator.stops == [1, 2, 3] def test_update_state_with_high_dest(self): """Updating state with a higher destination updates buttons""" self.elevator.go_to(5, 1) self.elevator.process_buttons([5, 6]) assert_equals(self.elevator.stops, [5, 6]) assert_equals(self.elevator.stops[-1], 6) def test_go_to_down(self): """Elevator will go to a lower floor""" self.elevator.location = 5 self.elevator.go_to(3, -1) comm = self.elevator.get_command() assert comm.id == 0 assert comm.direction == -1 assert comm.speed == 1 def test_will_not_go_to(self): """Should refuse to go to a floor beacuse it's out of the way""" self.elevator.location = 5 self.elevator.process_buttons([9]) self.elevator.get_command() assert self.elevator.go_to(4, 1) is False def test_process_request(self): """Handle a request object""" request = Request(floor=5, direction=1) will_do = self.elevator.process_request(request) assert will_do is True def test_elevator_request_up(self): """Works how I expect it to work""" cur_floor = 0 while self.elevator.location < 5: request = Request(direction=1, floor=5) res = self.elevator.process_request(request) assert res is True comm = self.elevator.get_command() assert comm.direction == 1 assert comm.speed == 1 assert self.elevator.next_direction == 1 cur_floor += 1 state = { "floor": cur_floor, "id": 0 } self.elevator.update_state(state) comm = self.elevator.get_command() assert comm.direction == 1 assert self.elevator.speed == 0 def test_elevator_buttons_pressed(self): """Goes to the floor requested by a passenger""" cur_floor = 3 while cur_floor > 1: state = { "buttons_pressed": [ 1 ], "floor": cur_floor, "id": 0 } cur_floor -= 1 self.elevator.update_state(state) comm = self.elevator.get_command() assert_equals(comm.direction, -1) assert_equals(comm.speed, 1) state['floor'] = cur_floor self.elevator.update_state(state) comm = self.elevator.get_command() assert_equals(comm.direction, 0) assert_equals(comm.speed, 0) def test_floor_on_the_way(self): """Test to see if we can pick up the new passenger""" state = { 'id': 0, 'floor': 3 } self.elevator.update_state(state) request = Request(direction=1, floor=5) res = self.elevator.process_request(request) assert_true(res) com = self.elevator.get_command() assert_equals(com.direction, 1) otw = self.elevator.is_on_the_way(5, 1) assert_true(otw) otw = self.elevator.is_on_the_way(2, 1) assert_false(otw) def test_floor_on_the_way_no_direction(self): """Test to see if we can pick up the new passenger when empty""" state = { 'id': 0, 'floor': 3 } self.elevator.update_state(state) otw = self.elevator.is_on_the_way(5, 1) assert_true(otw) otw = self.elevator.is_on_the_way(2, -1) assert_true(otw) def test_process_request_combine(self): """Test combining of trips to save time""" state = { 'id': 0, 'floor': 3 } self.elevator.update_state(state) request = Request(direction=1, floor=7) res = self.elevator.process_request(request) assert_true(res) com = self.elevator.get_command() assert_equals(com.direction, 1) state = { 'id': 0, 'floor': 4 } self.elevator.update_state(state) request = Request(direction=1, floor=8) res = self.elevator.process_request(request) assert_true(res) com = self.elevator.get_command() assert_equals(com.direction, 1) state = { 'id': 0, 'floor': 5 } self.elevator.update_state(state) request = Request(direction=1, floor=4) res = self.elevator.process_request(request) assert_false(res) request = Request(direction=-1, floor=6) res = self.elevator.process_request(request) assert_false(res) def test_calculate_distance_not_on_the_way(self): """Calculates the distance from the elevator to the destination When the stop is not on the way """ state = {'id': 0, 'floor': 3} self.elevator.update_state(state) down_req = Request(floor=1, direction=1) self.elevator.process_request(down_req) self.elevator.get_command() request = Request(floor=5, direction=1) distance = self.elevator.calculate_distance(request) assert_equals(distance, 12) def test_calculate_distance_on_the_way(self): """Calculates the distance from the elevator to the destination When the stop is on the way """ state = {'id': 0, 'floor': 3} self.elevator.update_state(state) down_req = Request(floor=1, direction=1) self.elevator.process_request(down_req) self.elevator.get_command() # We have to spend a turn stopping and opening request = Request(floor=2, direction=1) distance = self.elevator.calculate_distance(request) assert_equals(distance, 1) # It's where we're going anyways, it's free request = Request(floor=1, direction=1) distance = self.elevator.calculate_distance(request) assert_equals(distance, 0)
class ElevatorTest(unittest.TestCase): def setUp(self): self.reset_elevator() def reset_elevator(self): self.el = Elevator(0, 10) def test_request_crud(self): self.assertFalse(self.el.is_request_assigned(1, -1)) self.assertFalse(self.el.has_requests()) self.el.assign_request(1, -1) self.assertEqual(self.el.get_request_by_floor(1), (1, -1)) self.assertTrue(self.el.is_request_assigned(1, -1)) self.assertTrue(self.el.has_requests()) self.el.remove_request(1, -1) self.assertFalse(self.el.is_request_assigned(1, -1)) def test_button_pressed(self): self.assertFalse(self.el.is_button_pressed(2)) self.assertFalse(self.el.has_buttons()) self.el.button_pressed = [2, 5, 8] self.assertTrue(self.el.is_button_pressed(2)) self.assertFalse(self.el.is_button_pressed(3)) self.assertTrue(self.el.has_buttons()) def test_requests_along_direction(self): self.assertRaises(ValueError, self.el.requests_along_direction, -2) for floor, direction in [(3, -1), (1, 1), (7, 1), (8, -1), (1, -1)]: self.el.assign_request(floor, direction) floors = self.el.requests_along_direction(-1) self.assertEqual(floors, [8, 3, 1]) floors = self.el.requests_along_direction(1) self.assertEqual(floors, [1, 7]) def test_distance_direction_to(self): self.el.floor = 2 self.assertEqual(self.el.distance_to(3), 1) self.assertEqual(self.el.distance_to(0), -2) self.assertEqual(self.el.direction_to(5), 1) self.assertEqual(self.el.direction_to(0), -1) def test_closest_req(self): self.el.floor = 3 self.el.requests = [(0, 1), (2, -1), (6, -1)] self.assertEqual(self.el.closest_request(), -1) self.el.requests = [(5, -1), (0, 1), (9, -1)] self.assertEqual(self.el.closest_request(), 1) def test_update_state(self): bad_state = {'nid': 0} self.assertRaises(TypeError, self.el.update_state, bad_state) bad_state = {'id': 1} self.assertRaises(ValueError, self.el.update_state, bad_state) good_state = {'id': 0, 'floor': 1, 'buttons_pressed': [3, 5]} self.el.update_state(good_state) self.assertEqual(self.el.floor, 1) self.assertEqual(self.el.button_pressed, [3, 5]) def check_command(self, speed=None, direction=None): command = self.el.get_command() self.assertIsNotNone(command) if speed is not None: self.assertEqual(command.speed, speed) if direction is not None: self.assertEqual(command.direction, direction) def test_commands(self): # If no requests at home, do nothing self.assertIsNone(self.el.get_command()) # If no requests, and not at home, then send down self.el.floor = 3 # self.check_command(speed=1, direction=-1) self.el.direction = 1 self.el.speed = 1 self.el.button_pressed = [3, 4] self.check_command(speed=0) self.el.speed = 0 self.el.button_pressed = [4] self.check_command(speed=1, direction=1) self.el.button_pressed = [] self.el.requests = [(5, 1)] self.check_command(speed=1, direction=1) self.el.floor = 5 self.check_command(speed=0, direction=1)
def setup(self): state = { 'id': 0, 'floor': 0 } self.elevator = Elevator(state, 10)
def main(): elev = Elevator() elev.set_speed(300) while True: if elev.get_floor() == 0: elev.set_speed(300) elif elev.get_floor() == elev.NUM_FLOORS-1: elev.set_speed(-300) if elev.get_stop_signal(): elev.set_speed(0) break