Beispiel #1
0
class TestAirport(unittest.TestCase):
    def setUp(self):
        self.airport = Airport()
        self.flight = Flight()
        self.flight2 = Flight(start_time=Date(day=29,
                                              month=11,
                                              year=2016,
                                              hour='17:30'),
                              from_dest="Vancouver",
                              to_dest="New York")
        self.terminal = Terminal()
        self.airport.add_terminal(self.terminal)

    def test_init(self):  # passed
        self.assertEqual(self.airport.name, "Sofia")
        self.assertEqual(self.airport.terminals, [self.terminal])

    def test_add_terminal(self):
        self.assertEqual(self.airport.add_terminal(self.terminal),
                         [self.terminal, self.terminal])

    def test_passengers_from_terminal(self):
        passenger = Passenger(first_name="Georgi",
                              second_name="Atanasov",
                              age=20,
                              flight=self.flight)
        passenger2 = Passenger(flight=self.flight2)
        self.flight.add_passenger(passenger)
        self.flight2.add_passenger(passenger2)
        self.terminal.add_flight(self.flight)
        self.terminal.add_flight(self.flight2)
        self.assertEqual(self.airport.passengers_from_terminal(self.terminal),
                         [passenger, passenger2])
Beispiel #2
0
    def setUpClass(cls):
        print("setUpClass()")

        # Initialize airports
        cls.Logan = Airport()
        cls.JFK = Airport()
        cls.Logan.set_name("Logan")
        cls.JFK.set_name("JFK")

        # Initialize passengers
        cls.Ben = Passenger("Ben")
        cls.Julia = Passenger("Julia")
        cls.Jamie = Passenger("Jamie")

        # Initialize flights
        cls.flightLoganToJFK = Flight.airports_to_from(cls.Logan, cls.JFK)
        # Flight 1
        cls.flightLoganToJFK.set_flight_number("UA1161")
        cls.flightLoganToJFK.set_flight_date("04-27-2020")
        cls.flightLoganToJFK.set_flight_time("4:30pm")
        cls.flightLoganToJFK.set_airline("United Airlines")

        # Add flights to airport
        cls.Logan.add_flight(cls.flightLoganToJFK)
        cls.JFK.add_flight(cls.flightLoganToJFK)
Beispiel #3
0
 def test_stormy_weather(self):
     airport = Airport()
     plane = Mock()
     weather = Mock(stormy=True)
     airport.planes = [plane]
     self.assertEqual(airport.release_plane(plane, weather),
                      "Weather is Stormy")
Beispiel #4
0
    def test_flight_creation(self):
        # Create a new airport - LAX
        self.LAX = Airport()
        self.LAX.set_name("LAX")

        # Check that the LAX airport currently has no flights
        LAXflights = self.LAX.get_flights()
        self.assertEqual(len(LAXflights), 0)

        # Create a new flight from LAX to Logan
        self.flightLAXToLogan = Flight.airports_to_from(self.LAX, self.Logan)
        self.flightLAXToLogan.set_flight_number("UA2274")
        self.flightLAXToLogan.set_flight_date("04-26-2020")
        self.flightLAXToLogan.set_flight_time("9:30pm")
        self.flightLAXToLogan.set_airline("United Airlines")

        # Add the new flight to LAX and Logan's flights
        self.Logan.add_flight(self.flightLAXToLogan)
        self.LAX.add_flight(self.flightLAXToLogan)

        # Check that the LAX airport now has this flight outgoing
        LAXflights = self.LAX.get_outgoing_flights()
        self.assertEqual(len(LAXflights), 1)
        self.assertEqual(LAXflights, [self.flightLAXToLogan])

        # Check that Logan airport now has this flight incoming
        Loganflights = self.Logan.get_incoming_flights()
        self.assertEqual(Loganflights, [self.flightLAXToLogan])

        # Remove flight in order to clean up for next test case
        self.Logan.remove_flight(self.flightLAXToLogan)
        self.LAX.remove_flight(self.flightLAXToLogan)
	def __init__(self, src, dest, departure_time):
		self._owm = pyowm.OWM(API_KEY)
		self._src = Airport(src)
		self._dest = Airport(dest)
		self._dep_hour, self._dep_minute = departure_time.split(":")
		distance_btn_src_dst = vincenty(self._src.lat_lng(), self._dest.lat_lng()).miles
		self._approx_duration = distance_btn_src_dst/COMMERCIAL_AIRPLANE_SPEED + TIME_FOR_TAKING_OFF_AND_LANDING
 def test_airport_take_off_plane(self):
     airport = Airport()
     plane = Mock()
     weather = Mock()
     weather.stormy.return_value = False
     airport.planes = [plane]
     airport.release_plane(plane,weather)
     plane.take_off.assert_called_once_with()
Beispiel #7
0
 def test_airport_take_off_plane(self):
     airport = Airport()
     plane = Mock()
     weather = Mock()
     weather.stormy.return_value = False
     airport.planes = [plane]
     airport.release_plane(plane, weather)
     plane.take_off.assert_called_once_with()
 def test_airport_release_plane(self):
     airport = Airport()
     plane = Mock()
     weather = Mock()
     weather.stormy.return_value = False
     airport.land_plane(plane)
     airport.release_plane(plane,weather)
     self.assertEqual(airport.planes,[])
Beispiel #9
0
 def setUp(self):
     self.airport = Airport()
     self.flight = Flight()
     self.flight2 = Flight(start_time=Date(day=29,
                                           month=11,
                                           year=2016,
                                           hour='17:30'),
                           from_dest="Vancouver",
                           to_dest="New York")
     self.terminal = Terminal()
     self.airport.add_terminal(self.terminal)
Beispiel #10
0
    def __init__(self):
        self.flight_number = 'Flight_number'
        self.airline = "Airline"

        self.passengers = []
        self.max_capacity = 0

        self.current_airport = Airport()
        self.destination_airport = Airport()
        self.flight_date = "flight_date"
        self.flight_time = "flight_time"
Beispiel #11
0
def setup():
    global airportList
    airportList["Llyne"] = Airport("Llyne", 2)
    airportList["Tenby"] = Airport("Tenby", 2)
    airportList["Hythe"] = Airport("Hythe", 2)
    airportList["Pontheugh"] = Airport("Pontheugh", 6)
    airportList["Alderdyfi"] = Airport("Alderdyfi", 6)
    airportList["Stathmore"] = Airport("Stathmore", 6)
    airportList["Orilon"] = Airport("Orilon", 2)
    airportList["Hwen"] = Airport("Hwen", 2)
    airportList["Ecrin"] = Airport("Ecrin", 2)
    airportList["Erith"] = Airport("Erith", 2)
Beispiel #12
0
    def input(self, csv_path):
        """Takes csv input from command-line and checks for errors"""
        # test_routes_csv = csv.reader(io.open(
        #     csv_path.csv_file_path, "r", encoding=csv_path.encoding), delimiter=",", quotechar='"')

        inputFile = open(csv_path.csv_file_path, 'r', encoding='utf-8')
        fileReader = csv.reader(inputFile, delimiter=',')
        finalCsv = []
        aircrafts = []
        aircraftRange = []
        for row in fileReader:
            self.__csv_data = []
            # print("ROW:::", row)
            #finding duplicate values
            D = [k for k, v in Counter(row).items() if v > 1]
            if len(D) != 0:
                print("There are duplicate values")
                #dont append row to csv_data

            _airdict = Airport()
            parsedAirportDict = _airdict.parseAirport('airport.csv')
            parsedAircraft = _airdict.Aircraft('aircraft.csv')
            # print(parsedAircraft)
            #Checking for incorrect IATA codes
            dests = row[:-1]
            # print(dests)
            if len(dests) <= 1:
                print("Need to enter a minimum of 2 aircodes", '\n')
            else:
                for i in dests:
                    if i in list(parsedAirportDict.keys()):
                        self.__csv_data.append(i)
                    else:
                        print("Incorrect IATA entered", '\n')

            #Presuming Aircraft code will always be last item in csv file
            aircraft_code = row[-1]
            #print(aircraft_code)

            if aircraft_code in list(parsedAircraft.keys()):
                print("Aircraft range for", aircraft_code, "is:",
                      parsedAircraft.get(aircraft_code))
                #self.__csv_data.append(parsedAircraft.get(aircraft_code))
            else:
                print("Warning, please specify aircraft model")
            aircrafts.append(aircraft_code)
            aircraftRange.append(parsedAircraft.get(aircraft_code))
            finalCsv.append(self.__csv_data)
        return finalCsv, aircrafts, aircraftRange
Beispiel #13
0
def update_information():
    print('UPDATING METAR INFORMATION')

    airports.clear()

    # NOAA Weather Data URL
    url2 = 'https://www.aviationweather.gov/adds/dataserver_current/httpparam?dataSource=metars&requestType=retrieve&format=xml&hoursBeforeNow=2&mostRecentForEachStation=true&stationString=%s'

    identifiers = []
    for airport in settings.airports:
        ident = settings.airports[airport]

        identifiers.append(ident)
        airports.append(Airport(ident, airport))

    query_stirng = ','.join(identifiers)
    url2 = url2 % query_stirng

    dom = ET.fromstring(requests.get(url2).text)

    metars = dom.findall('./data/METAR')

    for m in metars:
        metar = m.find("raw_text").text
        station_id = m.find("station_id").text

        for airport in airports:
            if airport.get_station_info().icao == station_id:
                airport.set_metar(metar)
    def test_sfo_terminal_2_all(self):

        airport_code = "sfo-terminal-2"

        # Sets up the airport
        self.airport = Airport.create(airport_code)

        # Sets up the scenario
        self.scenario = Scenario.create(airport_code, self.airport.surface)

        links = self.airport.surface.links
        nodes = self.airport.surface.nodes

        routing_expert = RoutingExpert(links, nodes, True)
        runway_start = self.airport.surface.get_link("10R/28L").start

        # Checks the gate that is far from the runway (G53)
        gate_names = [
            "50", "55", "53", "52", "54A", "51A", "51B", "54B", "56B", "56A",
            "57", "59", "58B", "58A"
        ]
        for gate_name in gate_names:
            gate = self.airport.surface.get_node(gate_name)
            route = routing_expert.get_shortest_route(gate, runway_start)
            # Make sure they all have a route to go to the runway
            self.assertTrue(len(route.nodes) >= 2)
            self.assertTrue(len(route.links) >= 1)
            self.assertTrue(route.distance > 0.0)
    def test_conflicts(self):

        simulation = self.SimulationMock()
        airport = Airport.create("simple")

        a1 = Aircraft("A1", None, self.n1, State.stop)
        a2 = Aircraft("A2", None, self.n1, State.stop)
        a3 = Aircraft("A3", None, self.n2, State.stop)

        airport.aircrafts.append(a1)
        airport.aircrafts.append(a2)
        airport.aircrafts.append(a3)

        # Get only one conflict
        self.assertEqual(len(airport.conflicts), 1)

        # Test if the conflict looks like what we expected
        conflict = airport.conflicts[0]
        self.assertTrue(conflict.locations[0] == self.n1)
        self.assertEqual(len(conflict.aircrafts), 2)
        self.assertTrue(a1 in conflict.aircrafts)
        self.assertTrue(a2 in conflict.aircrafts)

        # Add one far aircraft to the same spot
        a4 = Aircraft("A4", None, self.n1, State.stop)
        airport.aircrafts.append(a4)

        # Test if the third aircraft shown in conflict correctly
        self.assertEqual(len(airport.conflicts), 3)
    def get_airports_within_radius(self, lat, lon, radius):
        # Note: implementing a half-solution for getting a bounding box:
        # treat world as if it was flat. Getting a bounding box for coordinates
        # around the poles seems really difficult.
        # We'll interpret radius as degrees.
        west = max(-180, lon - radius)
        east = min(180, lon + radius)
        south = max(-90, lat - radius)
        north = min(90, lat + radius)

        box_center = ((west + east) / 2, (south + north) / 2)

        # Note: no need to sanitize input, the query will only read the db
        query = 'lon:[{} TO {}] AND lat:[{} TO {}]'.format(
            west, east, south, north)

        # No docs for this either, found by looking at source, searching for "search"
        # TODO: find out how pagination works, currently `rows` contains max 25 elements
        airports_query_result = self.db.get_search_result("view1",
                                                          "geo",
                                                          q=query)
        rows = airports_query_result.get("rows", [])

        airports = list(map(lambda x: Airport(x, box_center), rows))
        airports.sort(key=lambda airport: airport.distance)

        return airports
class TestFlight(unittest.TestCase):
    def setUp(self):
        self.flight = None
        self.airport = Airport()

    def test_flight_constructor(self):
        self.flight = Flight(start_time=Date(29, 11, 2016, hour='12:20'),
                             end_time=Date(29, 11, 2016, hour='15:30'),
                             passengers=100,
                             max_passengers=120,
                             from_dest="Sofia",
                             to_dest="London",
                             terminal=Terminal(2, 30),
                             declined=False)

    def test_terminal_constructor(self):
        self.terminal = Terminal(number=1, max_flights=20)

    def test_passenger_constructor(self):
        self.passenger = Passenger(first_name="Rositsa",
                                   last_name="Zlateva",
                                   flight=Flight(),
                                   age=22)

    def test_reservation_constructor(self):
        self.reservation = Reservation(flight=Flight(),
                                       passenger=Passenger(),
                                       accepted=True)

    def test_get_flights_for(self):
        self.flight = constants.flights[2]
        self.assertEqual(
            self.airport.get_flights_for(Date(29, 11, 2016, hour='12:20'))[0],
            self.flight)

    def test_get_flight_before(self):
        self.assertEqual(
            self.airport.get_flights_before(Date(29, 11, 2016, hour='15:29')),
            [constants.flights[2]])

    def test_get_flight_from(self):
        self.assertEqual(constants.flights[0],
                         self.airport.get_flight_from('Sofia')[0])

    def test_get_flight_to(self):
        self.assertEqual(constants.flights[0],
                         self.airport.get_flight_to('Sofia')[0])
Beispiel #18
0
def test_airport_capacity():
    airport = Airport()
    weather = Weather()
    allow(weather).weather_check.and_return('sunny')
    airport.land("plane")
    airport.land("plane")
    airport.land("plane")
    assert airport.land("plane") == "Hangar Capacity Reached!"
Beispiel #19
0
class AirportTestCase(unittest.TestCase):

    def setUp(self):
        self.airport = Airport(20,[])
        self.plane = MagicMock()

    def test_planes_default_empty(self):
        self.assertEqual(self.airport.planes,[])

    def test_planes_can_be_overriden(self):
        self.airport = Airport(20, [self.plane])
        self.assertEqual(self.airport.planes,[self.plane])

    def test_capacity_default(self):
        self.assertEqual(self.airport.capacity, self.airport._DEFAULTCAPACITY)

    def test_capacity_can_be_overriden(self):
        self.random_capacity = 100
        self.airport = Airport(self.random_capacity)
        self.assertEqual(self.airport.capacity, self.random_capacity)

    def test_isFull_returns_true_when_airport_at_capacity(self):
        self.airport = Airport(1, [self.plane])
        self.assertTrue(self.airport.is_full())

    def test_isFull_returns_false_when_airport_not_full(self):
        self.assertFalse(self.airport.is_full())

    def test_land_plane_stores_plane_in_airport(self):
        self.airport.land_plane(self.plane)
        self.assertEqual(self.airport.planes, [self.plane])

    def test_land_plane_prevented_when_is_full_True(self):
        self.airport = Airport(1, [self.plane])
        with self.assertRaisesRegexp(Exception, 'Airport is Full'):
            self.airport.land_plane(self.plane)

    def test_take_off_plane_causes_plane_to_leave(self):
        self.airport.land_plane(self.plane)
        self.airport.take_off_plane(self.plane)
        self.assertEqual(self.airport.planes, [])
Beispiel #20
0
def test_airport_take_off():
    airport = Airport()
    weather = Weather()
    allow(weather).weather_check.and_return('sunny')
    airport.land("plane")
    airport.take_off("plane")
    assert airport.hangar == []
Beispiel #21
0
 def test_docking_same_plane_twice_not_allowed(self):
   jfk = Airport()
   boeing = Plane("Boeing")
   jfk.dock(boeing)
   self.assertEqual(len(jfk.docked), 1)
   with self.assertRaises(ValueError):
     jfk.dock(boeing)
Beispiel #22
0
def initialize_airports(airport_names):
    airports = []

    # create airport objects
    for i in range(len(airport_names)):
        airports.append(Airport())

    # add names to objects
    for airport in airports:
        airport.set_name(airport_names[0])
        airport_names.remove(airport_names[0])

    return airports
Beispiel #23
0
 def test_airport_release_plane(self):
     airport = Airport()
     plane = Mock()
     weather = Mock()
     weather.stormy.return_value = False
     airport.land_plane(plane)
     airport.release_plane(plane, weather)
     self.assertEqual(airport.planes, [])
Beispiel #24
0
    def load_data(filename):
        airports = {}
        with open(os.path.join("", "clean_files", filename),
                  "rt",
                  encoding="utf8") as f:

            reader = csv.reader(f)

            for row in reader:
                airport_code = row[4]
                # remove cr
                airports[airport_code] =\
                    Airport(row[4], row[5], row[6], row[7], row[3], row[1], row[2], row[9], row[8])
        return airports
Beispiel #25
0
    def get(self, departure=True):

        for airport_name in self.airport_codes:

            print(f'Collecting information for airport {airport_name}...')

            airport = Airport(airport_name, departure=departure)

            if not airport.is_created():
                _ = airport.flights()

            flights = Flights(airport_name, departure=departure)
            flights.statuses()

            time.sleep(4.7)
Beispiel #26
0
def create_airports(log: List[List[str]]) -> List[Airport]:
    """ Return a list of Airports with all applicable data, based
    on the input dataset stored in the <log>.

    Precondition:
    - The <log> list contains the input data in the correct format.
    >>> a = import_data('data/airports.csv', 'data/segments.csv',
    'data/customers.csv', 'data/trips.csv')
    >>> create_airports(a[0])
    []
    """
    final = []
    for line in log:
        final.append(
            Airport(line[0], line[1], (float(line[2]), float(line[3]))))
    return final
Beispiel #27
0
    def __init__(self):

        params = Config.params

        # Setups the logger
        self.logger = logging.getLogger(__name__)

        # Setups the clock
        self.clock = Clock()

        # Sets up the airport
        airport_name = params["airport"]
        self.airport = Airport.create(airport_name)

        # Sets up the scenario
        self.scenario = Scenario.create(
            airport_name, self.airport.surface)

        # Sets up the routing expert monitoring the airport surface
        self.routing_expert = RoutingExpert(self.airport.surface.links,
                                            self.airport.surface.nodes,
                                            params["simulation"]["cache"])

        # Sets up the uncertainty module
        self.uncertainty = (Uncertainty(params["uncertainty"]["prob_hold"],
                                        params["uncertainty"]["speed_bias_sigma"],
                                        params["uncertainty"]["speed_bias_mu"])
                            if params["uncertainty"]["enabled"] else None)

        # Loads the requested scheduler
        self.scheduler = get_scheduler()

        if not params["simulator"]["test_mode"]:
            # Sets up the analyst
            self.analyst = Analyst(self)

            # Sets up the state logger
            self.state_logger = StateLogger()

        # Initializes the previous schedule time
        self.last_schedule_time = None

        # Initializes the last execution time for rescheduling to None
        self.last_schedule_exec_time = None

        self.__print_stats()
   def read_airports_from_csv(cls, csv_filename):
       """
       Read airports from specified csv file
       """
       airports_df = pd.read_csv(csv_filename)
       airports = []
       
       for row in airports_df.itertuples(index=False, name="Airport"):
           airports.append(
               Airport(
                   row.icao,
                   row.latitude,
                   row.longitude,
                   row.city
               )
           )
 
       return airports
 def test_in_order_traversal(self):
     print("Running test_in_order_traversal")
     airport = Airport(100)
     a1 = airport.bounded_insert(2000, "TOP")
     a2 = airport.bounded_insert(1000, "TIP")
     a3 = airport.bounded_insert(2500, "RIC")
     a4 = airport.bounded_insert(500, "KRO")
     a5 = airport.bounded_insert(1800, "LLE")
     order = airport.in_order_traversal()
     ground_truth = [a4, a2, a5, a1, a3]
     for element in order:
         # Check if there are still elements that could be processed
         self.assertTrue(len(ground_truth) > 0)
         gt = ground_truth.pop(0)
         self.assertEqual(element, gt)
     # All elements should have been processed.
     self.assertTrue(len(ground_truth) == 0)
    def get_nearby_airports(self):
        '''
        Defines the coordinates of the given city.
        Searches for nearby airports using API_location
        Saves result of the research in  dynamic array

        airports_nearby: array of Airport objects - airports
                         found using API_location
        '''
        geolocator = Nominatim(user_agent="airport finder")
        location = geolocator.geocode(self._cityname)
        self._location = API_location(location.latitude, location.longitude,
                                      50, 10)

        for airport in self._location['items']:
            name = airport['name']
            icao = airport['icao']
            location = airport['location']
            self._airports_nearby.append(Airport(name, location, icao))
    def test_simple_data(self):
        airport_code = "simple"

        # Sets up the airport
        self.airport = Airport.create(airport_code)

        # Sets up the scenario
        self.scenario = Scenario.create(airport_code, self.airport.surface)

        links = self.airport.surface.links
        nodes = self.airport.surface.nodes

        # Sets up the routing expert monitoring the airport surface
        routing_expert = RoutingExpert(links, nodes, False)

        routeG3toR1 = routing_expert.get_shortest_route(
            nodes[2], links[0].start)

        self.assertEqual(len(routeG3toR1.nodes), 8)
        self.assertAlmostEqual(routeG3toR1.distance, 1352.6500035604972, 5)
    def get_routes_available(self):
        '''
        Searches for avaliable routes and average 
        number of daily flights  from the chosen airport
        (ICAO identifier)in these directions using API_destination
        If any of the parameters (name, location, average flights)
        is absent, the route is skipped

        routes_available: array of Airport objects - directions
                          available for travelling                        
        '''
        self._destinations = API_destination(self._icao)

        for route in self._destinations['routes']:
            try:
                location = route['destination']['location']
                name = route['destination']['name']
                average_flights = route['averageDailyFlights']
                self._routes_available.append(
                    Airport(name, location, average_fligths=average_flights))
            except KeyError:
                pass
    def storeAirpotsDB(self):
        airports_list = []
        airports = self.getAirportsFromUrl()

        for airport in airports:
            iata = airports[airport]['iata']

            try:
                session.query(Airport).filter_by(iata=iata).one()
            except NoResultFound:
                city_name = airports[airport]['city']

                try:
                    city = session.query(City).filter_by(name=city_name).one()
                except NoResultFound:
                    try:
                        state_cod = airports[airport]['state'].strip()
                        try:
                            state = session.query(State).filter_by(cod=state_cod).one()
                        except NoResultFound:
                            raise ValueError('State does not match any record in the database!')

                    except Exception as error:
                        print('Error: ' + repr(error))
                        return 0

                    else:
                        city = City(name=city_name, state_id=state.state_id)
                        session.add(city)
                        session.commit()

                coord = "SRID=4674;POINT(%s %s)" % (airports[airport]["lat"], airports[airport]["lon"])
                airport = Airport(iata=iata, city=city.city_id, geom=coord)
                airports_list.append(airport)
                session.add(airport)
                session.commit()

        return airports_list
    def test_real_west_all_terminals_furthest(self):
        airport_code = "real-west-all-terminals"

        # Sets up the airport
        self.airport = Airport.create(airport_code)

        # Sets up the scenario
        self.scenario = Scenario.create(airport_code, self.airport.surface)

        links = self.airport.surface.links
        nodes = self.airport.surface.nodes

        routing_expert = RoutingExpert(links, nodes, True)
        runway_start = self.airport.surface.get_link("10R/28L").start

        # Checks the gate that is far from the runway (G53)
        gate_53 = self.airport.surface.get_node("53")

        routeG53to10R = \
            routing_expert.get_shortest_route(gate_53, runway_start)
        self.assertAlmostEqual(routeG53to10R.distance, 17167.291795099998, 5)
        self.assertEqual(len(routeG53to10R.nodes), 19)
        self.assertEqual(len(routeG53to10R.links), 18)
class WeatherGrapper:
	def __init__(self, src, dest, departure_time):
		self._owm = pyowm.OWM(API_KEY)
		self._src = Airport(src)
		self._dest = Airport(dest)
		self._dep_hour, self._dep_minute = departure_time.split(":")
		distance_btn_src_dst = vincenty(self._src.lat_lng(), self._dest.lat_lng()).miles
		self._approx_duration = distance_btn_src_dst/COMMERCIAL_AIRPLANE_SPEED + TIME_FOR_TAKING_OFF_AND_LANDING

	def src_weather(self):
		forecast = self._owm.daily_forecast(self._src.location())
		t = datetime.today()
		wanted_time = datetime(t.year, t.month, t.day, int(self._dep_hour), int(self._dep_minute))
		return (forecast.get_weather_at(wanted_time), grab_visibility(self._src.icao()))

	def dest_weather(self):
		forecast = self._owm.daily_forecast(self._dest.location())
		t = datetime.today()
		wanted_time = datetime(t.year, t.month, t.day, int(self._dep_hour), int(self._dep_minute)) + timedelta(hours=self._approx_duration)
		return (forecast.get_weather_at(wanted_time), grab_visibility(self._dest.icao()))
 def test_airport_storing_planes(self):
     airport = Airport()
     plane = Mock()
     airport.land_plane(plane)
     self.assertEqual(airport.planes,[plane])
Beispiel #37
0
 def test_planes_can_be_overriden(self):
     self.airport = Airport(20, [self.plane])
     self.assertEqual(self.airport.planes,[self.plane])
Beispiel #38
0
 def test_capacity_can_be_overriden(self):
     self.random_capacity = 100
     self.airport = Airport(self.random_capacity)
     self.assertEqual(self.airport.capacity, self.random_capacity)
Beispiel #39
0
 def test_isFull_returns_true_when_airport_at_capacity(self):
     self.airport = Airport(1, [self.plane])
     self.assertTrue(self.airport.is_full())
Beispiel #40
0
 def test_land_plane_prevented_when_is_full_True(self):
     self.airport = Airport(1, [self.plane])
     with self.assertRaisesRegexp(Exception, 'Airport is Full'):
         self.airport.land_plane(self.plane)
Beispiel #41
0
 def setUp(self):
     self.airport = Airport(20,[])
     self.plane = MagicMock()
 def test_airport_land_plane(self):
     airport = Airport()
     plane = Mock()
     airport.land_plane(plane)
     plane.land.assert_called_once_with()
 def test_stormy_weather(self):
     airport = Airport()
     plane = Mock()
     weather = Mock(stormy=True)
     airport.planes = [plane]
     self.assertEqual(airport.release_plane(plane,weather), "Weather is Stormy")