class TestMeasurement(unittest.TestCase):

    ts = 1378459200
    iso_ts = "2013-09-06 09:20:00+00"
    date_ts = dt.strptime(iso_ts, '%Y-%m-%d %H:%M:%S+00').replace(tzinfo=UTC())

    _test_instance = Measurement('mytest', ts, temperature=dict(min=0, max=100),
        wind_speed=2.1, wind_gust=67, humidex=77, weather_other=dict(key='val'))

    def test_assertions_on_instantation(self):
        with self.assertRaises(AssertionError):
            Measurement(None, self.ts, temperature=dict(min=0, max=100),
                    wind_speed=2.1, wind_gust=67, humidex=77,
                    weather_other=dict(key='val'))
        with self.assertRaises(AssertionError):
            Measurement(None, '12345', temperature=dict(min=0, max=100),
                    wind_speed=2.1, wind_gust=67, humidex=77,
                    weather_other=dict(key='val'))
        with self.assertRaises(AssertionError):
            Measurement(None, -123, temperature=dict(min=0, max=100),
                    wind_speed=2.1, wind_gust=67, humidex=77,
                    weather_other=dict(key='val'))

    def test_creation_time(self):
        result = self._test_instance.creation_time()
        self.assertEqual(self.ts, result)
        result = self._test_instance.creation_time(timeformat='iso')
        self.assertEqual(self.iso_ts, result)
        result = self._test_instance.creation_time(timeformat='date')
        self.assertEqual(self.date_ts, result)
        with self.assertRaises(ValueError):
            self._test_instance.creation_time(timeformat='unknown')

        test_instance_none_timestamp = copy.deepcopy(self._test_instance)
        test_instance_none_timestamp.timestamp = None
        self.assertIsNone(test_instance_none_timestamp.creation_time())

    def test_from_dict(self):
        _the_dict = dict(station_id='mytest', timestamp=1378459200,
                         temperature=dict(min=0, max=100), wind_speed=2.1,
                         wind_gust=67, humidex=77, weather_other=dict(key='val'))
        result = Measurement.from_dict(_the_dict)
        self.assertEqual(self._test_instance.station_id, result.station_id)
        self.assertEqual(self._test_instance.timestamp, result.timestamp)
        self.assertEqual(self._test_instance.temperature, result.temperature)
        self.assertEqual(self._test_instance.wind_gust, result.wind_gust)
        self.assertEqual(self._test_instance.wind_speed, result.wind_speed)
        self.assertEqual(self._test_instance.humidex, result.humidex)
        self.assertEqual(self._test_instance.weather_other, result.weather_other)

    def test_from_dict_with_missing_values(self):
        with self.assertRaises(KeyError):
            Measurement.from_dict(dict(timestamp=123456789))
        with self.assertRaises(KeyError):
            Measurement.from_dict(dict(station_id='mytest'))

    def test_to_dict(self):
        expected_dict = {
            "station_id": "mytest",
            "timestamp": 1378459200,
            "temperature": {"min":0, "max": 100},
            "wind_speed": 2.1,
            "wind_gust": 67,
            "humidex": 77,
            "weather_other": {"key": "val"}}
        result_dict = self._test_instance.to_dict()
        self.assertTrue(all(item in result_dict.items()
                            for item in expected_dict.items()))

    def test_to_JSON(self):
        expected = '''
        {"station_id": "mytest",
        "timestamp": 1378459200,
        "temperature":{"min":0, "max": 100},
        "wind_speed":2.1,
        "wind_gust":67,
        "humidex":77,
        "weather_other":{"key":"val"}}
        '''
        result_dict = json.loads(self._test_instance.to_JSON())
        expected_dict = json.loads(expected)
        self.assertTrue(all(item in result_dict.items()
                            for item in expected_dict.items()))

    def test_repr(self):
        str(self._test_instance)
class TestAggregatedMeasurement(unittest.TestCase):

    ts = 1378459200
    iso_ts = "2013-09-06 09:20:00+00"
    date_ts = dt.strptime(iso_ts, '%Y-%m-%d %H:%M:%S+00').replace(tzinfo=UTC())

    _test_instance = AggregatedMeasurement('mytest', ts, 'm',
                                           temp=dict(min=0, max=100),
                                           humidity=dict(min=10, max=110),
                                           wind=dict(speed=2.1, gust=67),
                                           pressure=None,
                                           precipitation=None)

    def test_assertions_on_instantation(self):
        with self.assertRaises(AssertionError):
            AggregatedMeasurement(None, self.ts, 'h', temp=None, humidity=None,
                                  wind=None, pressure=None, precipitation=None)
        with self.assertRaises(AssertionError):
            AggregatedMeasurement('test', None, 'h', temp=None, humidity=None,
                                  wind=None, pressure=None, precipitation=None)
        with self.assertRaises(AssertionError):
            AggregatedMeasurement('test', '1234', 'h', temp=None, humidity=None,
                                  wind=None, pressure=None, precipitation=None)
        with self.assertRaises(AssertionError):
            AggregatedMeasurement('test', -123, 'h', temp=None, humidity=None,
                                  wind=None, pressure=None, precipitation=None)
        with self.assertRaises(AssertionError):
            AggregatedMeasurement('test', self.ts, None, temp=None, humidity=None,
                                  wind=None, pressure=None, precipitation=None)

    def test_aggregated_on_with_wrong_values(self):
        with self.assertRaises(ValueError):
            wrong = 'xyz'
            AggregatedMeasurement('mytest', self.ts, wrong,
                                   temp=dict(min=0, max=100),
                                   humidity=dict(min=10, max=110),
                                   wind=dict(speed=2.1, gust=67),
                                   pressure=None,
                                   precipitation=None)

    def test_creation_time(self):
        result = self._test_instance.creation_time()
        self.assertEqual(self.ts, result)
        result = self._test_instance.creation_time(timeformat='iso')
        self.assertEqual(self.iso_ts, result)
        result = self._test_instance.creation_time(timeformat='date')
        self.assertEqual(self.date_ts, result)
        with self.assertRaises(ValueError):
            self._test_instance.creation_time(timeformat='unknown')

        test_instance_none_timestamp = copy.deepcopy(self._test_instance)
        test_instance_none_timestamp.timestamp = None
        self.assertIsNone(test_instance_none_timestamp.creation_time())

    def test_from_dict(self):
        the_dict = {
            "station_id": "mytest",
            "date": 123456789,
            "type": "m",
            "temp":{"min": 0, "max": 100},
            "humidity": {"min": 10, "max": 110},
            "wind": {"speed": 2.1,"gust": 67},
            "pressure": {},
            "precipitation": {}}

        expected = AggregatedMeasurement('mytest', 123456789, 'm',
                                          temp=dict(min=0, max=100),
                                          humidity=dict(min=10, max=110),
                                          wind=dict(speed=2.1, gust=67),
                                          pressure=None,
                                          precipitation=None)

        result = AggregatedMeasurement.from_dict(the_dict)
        self.assertTrue(isinstance(result, AggregatedMeasurement))

        self.assertEqual(expected.station_id, result.station_id)
        self.assertEqual(expected.timestamp, result.timestamp)
        self.assertEqual(expected.aggregated_on, result.aggregated_on)
        self.assertEqual(expected.temp, result.temp)
        self.assertEqual(expected.humidity, result.humidity)
        self.assertEqual(expected.wind, result.wind)
        self.assertEqual(expected.pressure, result.pressure)
        self.assertEqual(expected.precipitation, result.precipitation)

        with self.assertRaises(pyowm.commons.exceptions.ParseAPIResponseError):
            AggregatedMeasurement.from_dict(None)

        with self.assertRaises(AssertionError):
            none_timestamp = copy.deepcopy(the_dict)
            none_timestamp['date'] = None
            AggregatedMeasurement.from_dict(none_timestamp)

    def test_to_dict(self):
        expected_dict = {
            "station_id": "mytest",
            "timestamp": 1378459200,
            "aggregated_on": "m",
            "temp":{"min": 0, "max": 100},
            "humidity": {"min": 10, "max": 110},
            "wind": {"speed": 2.1,"gust": 67},
            "pressure": {},
            "precipitation": {}}
        result_dict = self._test_instance.to_dict()
        self.assertTrue(all(item in result_dict.items()
                            for item in expected_dict.items()))
class TestSoil(unittest.TestCase):

    test_reference_time = 1378459200
    test_iso_reference_time = "2013-09-06 09:20:00+00:00"
    test_date_reference_time = datetime.strptime(
        test_iso_reference_time,
        '%Y-%m-%d %H:%M:%S+00:00').replace(tzinfo=UTC())
    test_temperature = 294.199
    test_celsius_temperature = 21.049
    test_fahrenheit_temperature = 69.888
    test_moisture = 45.6
    test_polygon_id = 'my-polygon'
    test_instance = Soil(test_reference_time, test_temperature,
                         test_temperature, test_moisture, test_polygon_id)

    def test_soil_fails_with_wrong_parameters(self):
        self.assertRaises(AssertionError, Soil, None, 12.4, 11.8, 80.2,
                          'my-polygon')
        self.assertRaises(AssertionError, Soil, 'wrong', 12.4, 11.8, 80.2,
                          'my-polygon')
        self.assertRaises(ValueError, Soil, -345, 12.4, 11.8, 80.2,
                          'my-polygon')
        self.assertRaises(AssertionError, Soil, 1234567, None, 11.8, 80.2,
                          'my-polygon')
        self.assertRaises(AssertionError, Soil, 1234567, 'wrong', 11.8, 80.2,
                          'my-polygon')
        self.assertRaises(AssertionError, Soil, 1234567, 12.4, None, 80.2,
                          'my-polygon')
        self.assertRaises(AssertionError, Soil, 1234567, 12.4, 'wrong', 80.2,
                          'my-polygon')
        self.assertRaises(AssertionError, Soil, 1234567, 12.4, 11.8, None,
                          'my-polygon')
        self.assertRaises(AssertionError, Soil, 1234567, 12.4, 11.8, "'wrong",
                          'my-polygon')
        self.assertRaises(ValueError, Soil, 1234567, 12.4, 11.8, -45.6,
                          'my-polygon')

    def test_reference_time_returning_different_formats(self):

        self.assertEqual(self.test_instance.reference_time(timeformat='unix'),
                         self.test_reference_time)
        self.assertEqual(self.test_instance.reference_time(timeformat='iso'),
                         self.test_iso_reference_time)
        self.assertEqual(self.test_instance.reference_time(timeformat='date'),
                         self.test_date_reference_time)

    def test_reference_time_fails_with_unknown_timeformat(self):
        self.assertRaises(ValueError, Soil.reference_time, self.test_instance,
                          'xyz')

    def test_from_dict(self):
        ref_time = 12345567
        surf_temp = 11.2
        ten_cm_temp = 9.5
        moisture = 8.2
        pol_id = "5abb9fb82c8897000bde3e87"
        the_dict = {
            "reference_time": ref_time,
            "surface_temp": surf_temp,
            "ten_cm_temp": ten_cm_temp,
            "moisture": moisture,
            "polygon_id": pol_id
        }
        expected = Soil(ref_time, surf_temp, ten_cm_temp, moisture, pol_id)
        result = Soil.from_dict(the_dict)
        self.assertEqual(expected.reference_time(), result.reference_time())
        self.assertEqual(expected.surface_temp(), result.surface_temp())
        self.assertEqual(expected.ten_cm_temp(), result.ten_cm_temp())
        self.assertEqual(expected.moisture, result.moisture)
        self.assertEqual(expected.polygon_id, result.polygon_id)

    def test_to_dict(self):
        expected = dict(reference_time=self.test_reference_time,
                        surface_temp=self.test_temperature,
                        ten_cm_temp=self.test_temperature,
                        moisture=self.test_moisture,
                        polygon_id=self.test_polygon_id)
        result = self.test_instance.to_dict()
        self.assertEqual(expected, result)

    def test_returning_different_units_for_temperatures(self):
        # Surface temp
        result_kelvin = self.test_instance.surface_temp(unit='kelvin')
        result_celsius = self.test_instance.surface_temp(unit='celsius')
        result_fahrenheit = self.test_instance.surface_temp(unit='fahrenheit')
        self.assertAlmostEqual(result_kelvin, self.test_temperature, delta=0.1)
        self.assertAlmostEqual(result_celsius,
                               self.test_celsius_temperature,
                               delta=0.1)
        self.assertAlmostEqual(result_fahrenheit,
                               self.test_fahrenheit_temperature,
                               delta=0.1)

        # 10 cm temp
        result_kelvin = self.test_instance.ten_cm_temp(unit='kelvin')
        result_celsius = self.test_instance.ten_cm_temp(unit='celsius')
        result_fahrenheit = self.test_instance.ten_cm_temp(unit='fahrenheit')
        self.assertAlmostEqual(result_kelvin, self.test_temperature, delta=0.1)
        self.assertAlmostEqual(result_celsius,
                               self.test_celsius_temperature,
                               delta=0.1)
        self.assertAlmostEqual(result_fahrenheit,
                               self.test_fahrenheit_temperature,
                               delta=0.1)

    def test_trying_unknown_units_for_temperatures(self):
        self.assertRaises(ValueError, Soil.surface_temp, self.test_instance,
                          'xyz')
        self.assertRaises(ValueError, Soil.ten_cm_temp, self.test_instance,
                          'xyz')

    def test_repr(self):
        instance = Soil(1234567, 12.4, 11.8, 80.2, 'my-polygon')
        repr(instance)
        instance = Soil(1234567, 12.4, 11.8, 80.2, None)
        repr(instance)
Ejemplo n.º 4
0
class TestWeather(unittest.TestCase):
    __test_reference_time = 1378459200
    __test_iso_reference_time = "2013-09-06 09:20:00+00"
    __test_date_reference_time = datetime.strptime(__test_iso_reference_time,
                                                   '%Y-%m-%d %H:%M:%S+00').replace(tzinfo=UTC())
    __test_sunset_time = 1378496400
    __test_iso_sunset_time = "2013-09-06 19:40:00+00"
    __test_date_sunset_time = datetime.strptime(__test_iso_sunset_time,
                                                '%Y-%m-%d %H:%M:%S+00').replace(tzinfo=UTC())
    __test_sunrise_time = 1378449600
    __test_iso_sunrise_time = "2013-09-06 06:40:00+00"
    __test_date_sunrise_time = datetime.strptime(__test_iso_sunrise_time,
                                                 '%Y-%m-%d %H:%M:%S+00').replace(tzinfo=UTC())
    __test_clouds = 67
    __test_rain = {"all": 20}
    __test_snow = {"all": 0}
    __test_wind = {"deg": 252.002, "speed": 1.100, "gust": 2.09}
    __test_imperial_wind = {"deg": 252.002, "speed": 2.460634, "gust": 4.6752046}
    __test_knots_wind = {'deg': 252.002, 'speed': 2.138224, 'gust': 4.0626256}
    __test_beaufort_wind = {"deg": 252.002, "speed": 1, "gust": 2}
    __test_kmh_wind = {'deg': 252.002, 'speed': 3.9600000000000004, 'gust': 7.524}
    __test_humidity = 57
    __test_pressure = {"press": 1030.119, "sea_level": 1038.589, "grnd_level": 1038.773}
    __test_temperature = {"temp": 294.199, "temp_kf": -1.899,
                          "temp_max": 296.098, "temp_min": 294.199,
                          "feels_like": 298.0}
    __test_celsius_temperature = {"temp": 21.049, "temp_kf": -1.899,
                                  "temp_max": 22.948, "temp_min": 21.049,
                                  "feels_like": 24.85}
    __test_fahrenheit_temperature = {"temp": 69.888, "temp_kf": -1.899,
                                     "temp_max": 73.306, "temp_min": 69.888,
                                     "feels_like": 76.73}
    __test_status = "Clouds"
    __test_detailed_status = "Overcast clouds"
    __test_weather_code = 804
    __test_weather_icon_name = "04d"
    __test_visibility_distance = 1000
    __test_dewpoint = 300.0
    __test_humidex = 298.0
    __test_heat_index = 40.0

    __test_instance = Weather(__test_reference_time, __test_sunset_time,
                              __test_sunrise_time, __test_clouds, __test_rain,
                              __test_snow, __test_wind, __test_humidity,
                              __test_pressure, __test_temperature,
                              __test_status, __test_detailed_status,
                              __test_weather_code, __test_weather_icon_name,
                              __test_visibility_distance, __test_dewpoint,
                              __test_humidex, __test_heat_index)

    __bad_json = '{"a": "test", "b": 1.234, "c": [ "hello", "world"] }'
    __bad_json_2 = '{"list": [{"test":"fake"}] }'
    __no_items_json = '{"cnt": "0"}'

    WEATHER_JSON_DUMP = '{"status": "Clouds", "visibility_distance": 1000, ' \
                        '"clouds": 67, "temperature": {"temp_kf": -1.899, ' \
                        '"temp_min": 294.199, "temp": 294.199, "temp_max": 296.098, "feels_like": 298.0},' \
                        ' "dewpoint": 300.0, "humidex": 298.0, "detailed_status": ' \
                        '"Overcast clouds", "reference_time": 1378459200, ' \
                        '"weather_code": 804, "sunset_time": 1378496400, "rain": ' \
                        '{"all": 20}, "snow": {"all": 0}, "pressure": ' \
                        '{"press": 1030.119, "sea_level": 1038.589, "grnd_level": 1038.773}, ' \
                        '"sunrise_time": 1378449600, "heat_index": 40.0, ' \
                        '"weather_icon_name": "04d", "humidity": 57, "wind": ' \
                        '{"speed": 1.1, "deg": 252.002, "gust": 2.09}, "utc_offset": null, "uvi": null}'

    def test_init_fails_when_wrong_data_provided(self):
        self.assertRaises(ValueError, Weather, -9876543210,
                          self.__test_sunset_time, self.__test_sunrise_time, self.__test_clouds,
                          self.__test_rain, self.__test_snow, self.__test_wind,
                          self.__test_humidity, self.__test_pressure, self.__test_temperature,
                          self.__test_status, self.__test_detailed_status,
                          self.__test_weather_code, self.__test_weather_icon_name,
                          self.__test_visibility_distance, self.__test_dewpoint,
                          self.__test_humidex, self.__test_heat_index)
        self.assertRaises(ValueError, Weather, self.__test_reference_time,
                          self.__test_sunset_time, self.__test_sunrise_time, -45,
                          self.__test_rain, self.__test_snow, self.__test_wind,
                          self.__test_humidity, self.__test_pressure, self.__test_temperature,
                          self.__test_status, self.__test_detailed_status,
                          self.__test_weather_code, self.__test_weather_icon_name,
                          self.__test_visibility_distance, self.__test_dewpoint,
                          self.__test_humidex, self.__test_heat_index)
        self.assertRaises(ValueError, Weather, self.__test_reference_time,
                          self.__test_sunset_time, self.__test_sunrise_time,
                          self.__test_clouds, self.__test_rain, self.__test_snow,
                          self.__test_wind, -16, self.__test_pressure, self.__test_temperature,
                          self.__test_status, self.__test_detailed_status,
                          self.__test_weather_code, self.__test_weather_icon_name,
                          self.__test_visibility_distance, self.__test_dewpoint,
                          self.__test_humidex, self.__test_heat_index)
        self.assertRaises(ValueError, Weather, self.__test_reference_time,
                          self.__test_sunset_time, self.__test_sunrise_time,
                          self.__test_clouds, self.__test_rain, self.__test_snow,
                          self.__test_wind, self.__test_humidity,
                          self.__test_pressure, self.__test_temperature,
                          self.__test_status, self.__test_detailed_status,
                          self.__test_weather_code, self.__test_weather_icon_name,
                          -12, self.__test_dewpoint,
                          self.__test_humidex, self.__test_heat_index)
        self.assertRaises(ValueError, Weather, self.__test_reference_time,
                          self.__test_sunset_time, self.__test_sunrise_time,
                          self.__test_clouds, self.__test_rain, self.__test_snow,
                          self.__test_wind, self.__test_humidity,
                          self.__test_pressure, self.__test_temperature,
                          self.__test_status, self.__test_detailed_status,
                          self.__test_weather_code, self.__test_weather_icon_name,
                          self.__test_visibility_distance, self.__test_dewpoint,
                          -10.0, self.__test_heat_index)
        self.assertRaises(ValueError, Weather, self.__test_reference_time,
                          self.__test_sunset_time, self.__test_sunrise_time,
                          self.__test_clouds, self.__test_rain, self.__test_snow,
                          self.__test_wind, self.__test_humidity,
                          self.__test_pressure, self.__test_temperature,
                          self.__test_status, self.__test_detailed_status,
                          self.__test_weather_code, self.__test_weather_icon_name,
                          self.__test_visibility_distance, self.__test_dewpoint,
                          self.__test_humidex, -10.0)
        self.assertRaises(ValueError, Weather, self.__test_reference_time,
                          self.__test_sunset_time, self.__test_sunrise_time,
                          self.__test_clouds, self.__test_rain, self.__test_snow,
                          self.__test_wind, self.__test_humidity,
                          self.__test_pressure, self.__test_temperature,
                          self.__test_status, self.__test_detailed_status,
                          self.__test_weather_code, self.__test_weather_icon_name,
                          self.__test_visibility_distance, self.__test_dewpoint,
                          self.__test_humidex, self.__test_heat_index, uvi=-1)

    def test_init_when_wind_is_none(self):
        instance = Weather(self.__test_reference_time,
                           self.__test_sunset_time, self.__test_sunrise_time,
                           self.__test_clouds,
                           self.__test_rain, self.__test_snow,
                           None,
                           self.__test_humidity, self.__test_pressure,
                           self.__test_temperature,
                           self.__test_status, self.__test_detailed_status,
                           self.__test_weather_code,
                           self.__test_weather_icon_name,
                           self.__test_visibility_distance,
                           self.__test_dewpoint,
                           self.__test_humidex, self.__test_heat_index)

        self.assertIsNone(instance.wind())

    def test_init_stores_negative_sunset_time_as_none(self):
        instance = Weather(self.__test_reference_time,
                           -9876543210, self.__test_sunrise_time,
                           self.__test_clouds,
                           self.__test_rain, self.__test_snow, self.__test_wind,
                           self.__test_humidity, self.__test_pressure,
                           self.__test_temperature,
                           self.__test_status, self.__test_detailed_status,
                           self.__test_weather_code,
                           self.__test_weather_icon_name,
                           self.__test_visibility_distance, self.__test_dewpoint,
                           self.__test_humidex, self.__test_heat_index)
        self.assertIsNone(instance.sunset_time())

    def test_init_stores_negative_sunrise_time_as_none(self):
        instance = Weather(self.__test_reference_time,
                           self.__test_sunset_time, -9876543210, self.__test_clouds,
                           self.__test_rain, self.__test_snow, self.__test_wind,
                           self.__test_humidity, self.__test_pressure,
                           self.__test_temperature,
                           self.__test_status, self.__test_detailed_status,
                           self.__test_weather_code, self.__test_weather_icon_name,
                           self.__test_visibility_distance, self.__test_dewpoint,
                           self.__test_humidex, self.__test_heat_index)
        self.assertIsNone(instance.sunrise_time())

    def test_init_fails_with_non_integer_utc_offset(self):
        self.assertRaises(AssertionError, Weather, self.__test_reference_time,
                          self.__test_sunset_time, self.__test_sunrise_time,
                          self.__test_clouds, self.__test_rain, self.__test_snow,
                          self.__test_wind, self.__test_humidity,
                          self.__test_pressure, self.__test_temperature,
                          self.__test_status, self.__test_detailed_status,
                          self.__test_weather_code, self.__test_weather_icon_name,
                          self.__test_visibility_distance, self.__test_dewpoint,
                          self.__test_humidex, self.__test_heat_index,
                          'non_string_utc_offset')

    def test_from_dict_fails_when_dict_is_none(self):
        self.assertRaises(ParseAPIResponseError, Weather.from_dict, None)

    def test_from_dict(self):
        dict1 = {'clouds': {'all': 92}, 'name': 'London',
                 'coord': {'lat': 51.50853, 'lon': -0.12574},
                 'sys': {'country': 'GB', 'sunset': 1378923812,
                         'sunrise': 1378877413
                         },
                 'weather': [
                     {'main': 'Clouds', 'id': 804, 'icon': '04d',
                      'description': 'overcastclouds'}
                 ],
                 'cod': 200, 'base': 'gdpsstations', 'dt': 1378895177,
                 'main': {
                     'pressure': 1022,
                     'humidity': 75,
                     'temp_max': 289.82,
                     'temp': 288.44,
                     'temp_min': 287.59
                 },
                 'id': 2643743,
                 'wind': {'gust': 2.57, 'speed': 1.54, 'deg': 31},
                 'visibility': {'distance': 1000},
                 'calc': {
                     'dewpoint': 300.0,
                     'humidex': 298.0,
                     'heatindex': 296.0
                 }
         }
        dict2 = {"dt": 1378897200,
                 "temp": {"day": 289.37, "min": 284.88, "max": 289.37,
                          "night": 284.88, "eve": 287.53, "morn": 289.37
                          },
                 "pressure": 1025.35,
                 "humidity": 71,
                 "weather": [
                     {"id": 500, "main": "Rain", "description": "light rain",
                      "icon": "u10d"}
                 ], "speed": 3.76, "deg": 338, "clouds": 48, "rain": 3
                 }
        dict3 = {"station": {
            "name": "KPPQ",
            "type": 1,
            "status": 50,
            "id": 1000,
            "coord": {"lon": -90.47, "lat": 39.38}
        },
            "last": {
                "main": {
                    "temp": 276.15,
                    "pressure": 1031},
                "wind": {
                    "speed": 3.1,
                    "deg": 140
                },
                "visibility": {
                    "distance": 11265,
                    "prefix": 0
                },
                "calc": {
                    "dewpoint": 273.15,
                    "humidex": 57.8,
                    "heatindex": 1.2
                },
                "clouds": [
                    {"distance": 427,
                     "condition": "SCT"}
                ],
                "dt": 1417977300
            },
            "params": ["temp", "pressure", "wind", "visibility"],
            "timezone": 1234567
        }
        dict4 = {'clouds': {'all': 92}, 'name': 'London',
                 'coord': {'lat': 51.50853, 'lon': -0.12574},
                 'sys': {'country': 'GB', 'sunset': 1378923812,
                         'sunrise': 1378877413
                         },
                 'weather': [
                     {'main': 'Clouds', 'id': 804, 'icon': '04d',
                      'description': 'overcastclouds'}
                 ],
                 'cod': 200, 'base': 'gdpsstations',
                 'main': {
                     'pressure': 1022,
                     'humidity': 75,
                     'temp_max': 289.82,
                     'temp': 288.44,
                     'temp_min': 287.59
                 },
                 'id': 2643743,
                 'wind': {'gust': 2.57, 'speed': 1.54, 'deg': 31},
                 'calc': {},
                 'last': {},
                 'snow': {'tot': 76.3}
         }
        dict5 = {'clouds': {'all': 92}, 'name': 'London',
                 'coord': {'lat': 51.50853, 'lon': -0.12574},
                 'sys': {'country': 'GB', 'sunset': 1378923812,
                         'sunrise': 1378877413
                         },
                 'weather': [
                     {'main': 'Clouds', 'id': 804, 'icon': '04d',
                      'description': 'overcastclouds'}
                 ],
                 'cod': 200, 'base': 'gdpsstations',
                 'main': {
                     'pressure': 1022,
                     'humidity': 75,
                     'temp_max': 289.82,
                     'temp': 288.44,
                     'temp_min': 287.59
                 },
                 'id': 2643743,
                 'wind': {'gust': 2.57, 'speed': 1.54, 'deg': 31},
                 'visibility': {'distance': 1000},
                 "last": {}
         }
        dict6 = {'clouds': {'all': 92}, 'name': 'London',
                 'coord': {'lat': 51.50853, 'lon': -0.12574},
                 'sys': {'country': 'GB', 'sunset': 1378923812,
                         'sunrise': 1378877413
                         },
                 'weather': [
                     {'main': 'Clouds', 'id': 804, 'icon': '04d',
                      'description': 'overcastclouds'}
                 ],
                 'cod': 200, 'base': 'gdpsstations', 'dt': 1378895177,
                 'main': {
                     'pressure': 1022,
                     'temp_max': 289.82,
                     'temp': 288.44,
                     'temp_min': 287.59
                 },
                 'id': 2643743,
                 'wind': {'gust': 2.57, 'speed': 1.54, 'deg': 31},
                 'last': {
                     "dt": 1417977300,
                     "calc": {},
                     'visibility': 2.34,
                     'main': {
                         "humidity": 77.2
                     }
                 },
                 'snow': 66.1
         }
        result1 = Weather.from_dict(dict1)
        self.assertTrue(isinstance(result1, Weather))
        result2 = Weather.from_dict(dict2)
        self.assertTrue(isinstance(result2, Weather))
        result3 = Weather.from_dict(dict3)
        self.assertTrue(isinstance(result3, Weather))
        result4 = Weather.from_dict(dict4)
        self.assertTrue(isinstance(result4, Weather))
        result5 = Weather.from_dict(dict5)
        self.assertTrue(isinstance(result5, Weather))
        result6 = Weather.from_dict(dict6)
        self.assertTrue(isinstance(result6, Weather))

    def test_from_dict_when_data_fields_are_none(self):
        dict1 = {'clouds': {'all': 92}, 'name': 'London',
                 'coord': {'lat': 51.50853, 'lon': -0.12574},
                 'sys': {'country': 'GB', 'sunset': 1378923812,
                         'sunrise': 1378877413
                         },
                 'weather': [
                     {'main': 'Clouds', 'id': 804, 'icon': '04d',
                      'description': 'overcastclouds'}
                 ],
                 'cod': 200, 'base': 'gdpsstations', 'dt': 1378895177,
                 'main': {
                     'pressure': 1022,
                     'humidity': 75,
                     'temp_max': 289.82,
                     'temp': 288.44,
                     'temp_min': 287.59
                 },
                 'id': 2643743,
                 'wind': None,
                 'visibility': {'distance': 1000},
                 'calc': {
                     'dewpoint': 300.0,
                     'humidex': 298.0,
                     'heatindex': 296.0
                 },
                 'rain': None,
                 'snow': None
                 }
        result1 = Weather.from_dict(dict1)
        self.assertTrue(isinstance(result1, Weather))
        self.assertEqual(0, len(result1.wind()))
        self.assertEqual(0, len(result1.rain))
        self.assertEqual(0, len(result1.snow))

        dict2 = {"station": {
            "name": "KPPQ",
            "type": 1,
            "status": 50,
            "id": 1000,
            "coord": {"lon": -90.47, "lat": 39.38}
        },
            "last": {
                "main": {
                    "temp": 276.15,
                    "pressure": 1031},
                "wind": None,
                "visibility": {
                    "distance": 11265,
                    "prefix": 0
                },
                "calc": {
                    "dewpoint": 273.15
                },
                "clouds": [
                    {"distance": 427,
                     "condition": "SCT"}
                ],
                "dt": 1417977300
            },
            "params": ["temp", "pressure", "wind", "visibility"]
        }
        result2 = Weather.from_dict(dict2)
        self.assertTrue(isinstance(result2, Weather))
        self.assertEqual(0, len(result2.wind()))

    def test_to_dict(self):
        expected = json.loads(self.WEATHER_JSON_DUMP)
        result = self.__test_instance.to_dict()
        self.assertEqual(expected, result)

    def test_from_dict_of_lists(self):
        result = Weather.from_dict_of_lists(json.loads(CITY_WEATHER_HISTORY_JSON))
        self.assertTrue(result)
        self.assertTrue(isinstance(result, list))
        for weather in result:
            self.assertTrue(weather is not None)

    def test_from_dict_of_lists_fails_when_JSON_data_is_None(self):
        self.assertRaises(ParseAPIResponseError, Weather.from_dict_of_lists, None)

    def test_from_dict_of_lists_with_malformed_JSON_data(self):
        self.assertRaises(ParseAPIResponseError, Weather.from_dict_of_lists, json.loads(self.__bad_json))
        self.assertRaises(ParseAPIResponseError, Weather.from_dict_of_lists, json.loads(self.__bad_json_2))

    def test_from_dict_of_lists_when_no_results(self):
        result = Weather.from_dict_of_lists(json.loads(CITY_WEATHER_HISTORY_NO_RESULTS_JSON))
        self.assertTrue(isinstance(result, list))
        self.assertEqual(0, len(result))
        result = Weather.from_dict_of_lists(json.loads(self.__no_items_json))
        self.assertTrue(isinstance(result, list))
        self.assertEqual(0, len(result))

    def test_parse_JSON_when_location_not_found(self):
        self.assertFalse(Weather.from_dict_of_lists(json.loads(CITY_WEATHER_HISTORY_NOT_FOUND_JSON)))

    def test_parse_JSON_when_server_error(self):
        self.assertRaises(APIResponseError, Weather.from_dict_of_lists, json.loads(INTERNAL_SERVER_ERROR_JSON))

    def test_reference_time_returning_different_formats(self):
        self.assertEqual(self.__test_instance.reference_time(timeformat='iso'),
                         self.__test_iso_reference_time)
        self.assertEqual(self.__test_instance.reference_time(timeformat='unix'),
                         self.__test_reference_time)
        self.assertEqual(self.__test_instance.reference_time(timeformat='date'),
                         self.__test_date_reference_time)

    def test_sunset_time_returning_different_formats(self):
        self.assertEqual(self.__test_instance.sunset_time(timeformat='iso'),
                         self.__test_iso_sunset_time)
        self.assertEqual(self.__test_instance.sunset_time(timeformat='unix'),
                         self.__test_sunset_time)
        self.assertEqual(self.__test_instance.sunset_time(timeformat='date'),
                         self.__test_date_sunset_time)

    def test_sunrise_time_returning_different_formats(self):
        self.assertEqual(self.__test_instance.sunrise_time(timeformat='iso'),
                         self.__test_iso_sunrise_time)
        self.assertEqual(self.__test_instance.sunrise_time(timeformat='unix'),
                         self.__test_sunrise_time)
        self.assertEqual(self.__test_instance.sunrise_time(timeformat='date'),
                         self.__test_date_sunrise_time)

    def test_get_reference_time_fails_with_unknown_timeformat(self):
        self.assertRaises(ValueError, Weather.reference_time,
                          self.__test_instance, 'xyz')

    def test_sunset_time_fails_with_unknown_timeformat(self):
        self.assertRaises(ValueError, Weather.sunset_time,
                          self.__test_instance, 'xyz')

    def test_sunrise_time_fails_with_unknown_timeformat(self):
        self.assertRaises(ValueError, Weather.sunrise_time,
                          self.__test_instance, 'xyz')

    def test_returning_different_units_for_temperatures(self):
        result_kelvin = self.__test_instance.temperature(unit='kelvin')
        result_celsius = self.__test_instance.temperature(unit='celsius')
        result_fahrenheit = self.__test_instance.temperature(
            unit='fahrenheit')
        for item in self.__test_temperature:
            self.assertAlmostEqual(result_kelvin[item],
                                   self.__test_temperature[item], delta=0.1)
            self.assertAlmostEqual(result_celsius[item],
                                   self.__test_celsius_temperature[item],
                                   delta=0.1)
            self.assertAlmostEqual(result_fahrenheit[item],
                                   self.__test_fahrenheit_temperature[item],
                                   delta=0.1)

    def test_get_temperature_fails_with_unknown_units(self):
        self.assertRaises(ValueError, Weather.temperature,
                          self.__test_instance, 'xyz')

    def test_returning_different_units_for_wind_values(self):
        result_imperial = self.__test_instance.wind(unit='miles_hour')
        result_metric_ms = self.__test_instance.wind(unit='meters_sec')
        result_metric_kmh = self.__test_instance.wind(unit='km_hour')
        result_knots = self.__test_instance.wind(unit='knots')
        result_beaufort = self.__test_instance.wind(unit='beaufort')
        result_unspecified = self.__test_instance.wind()
        self.assertEqual(result_unspecified, result_metric_ms)
        self.assertDictEqual(result_metric_kmh, self.__test_kmh_wind)
        for item in self.__test_wind:
            self.assertEqual(result_metric_ms[item],
                             self.__test_wind[item])
            self.assertEqual(result_imperial[item],
                             self.__test_imperial_wind[item])
            self.assertEqual(result_knots[item],
                             self.__test_knots_wind[item])
            self.assertEqual(result_beaufort[item],
                             self.__test_beaufort_wind[item])

    def test_get_wind_fails_with_unknown_units(self):
        self.assertRaises(ValueError, Weather.wind, self.__test_instance, 'xyz')

    def test_weather_icon_url(self):
        expected = ICONS_BASE_URI % self.__test_instance.weather_icon_name
        result = self.__test_instance.weather_icon_url()
        self.assertEqual(expected, result)

    def test_repr(self):
        print(self.__test_instance)

    def test_one_call_current_from_dic(self):
        current1 = {
            "dt": 1586001851,
            "sunrise": 1586003020,
            "sunset": 1586048382,
            "temp": 280.15,
            "feels_like": 277.75,
            "pressure": 1017,
            "humidity": 93,
            "uvi": 9.63,
            "clouds": 90,
            "visibility": 6437,
            "wind_speed": 2.1,
            "wind_deg": 70,
            "weather": [
                {
                    "id": 501,
                    "main": "Rain",
                    "description": "moderate rain",
                    "icon": "10n"
                },
                {
                    "id": 701,
                    "main": "Mist",
                    "description": "mist",
                    "icon": "50n"
                }
            ],
            "rain": {
                "1h": 1.02
            }
        }

        result1 = Weather.from_dict(current1)
        self.assertTrue(isinstance(result1, Weather))
        self.assertEqual(9.63, result1.uvi)
        self.assertEqual(501, result1.weather_code)
        self.assertEqual(1.02, result1.rain["1h"])
        self.assertEqual(280.15, result1.temperature()["temp"])
        self.assertEqual(277.75, result1.temperature()["feels_like"])

        current2 = {
            "dt": 1587678355,
            "sunrise": 1587615127,
            "sunset": 1587665513,
            "temp": 281.78,
            "feels_like": 277.4,
            "pressure": 1017,
            "humidity": 39,
            "dew_point": 269.13,
            "uvi": 7.52,
            "clouds": 2,
            "visibility": 10000,
            "wind_speed": 2.6,
            "wind_deg": 170,
            "weather": [
                {
                    "id": 800,
                    "main": "Clear",
                    "description": "clear sky",
                    "icon": "01n"
                }
            ]
        }

        result2 = Weather.from_dict(current2)
        self.assertTrue(isinstance(result2, Weather))
        self.assertEqual(7.52, result2.uvi)
        self.assertEqual(800, result2.weather_code)
        self.assertEqual(170, result2.wind()["deg"])
        self.assertEqual(0, len(result2.rain))
        self.assertEqual(281.78, result2.temperature()["temp"])
        self.assertEqual(277.4, result2.temperature()["feels_like"])

    def test_one_call_hourly_from_dic(self):
        hourly1 = {
            "dt": 1587675600,
            "temp": 294.16,
            "feels_like": 292.47,
            "pressure": 1009,
            "humidity": 88,
            "dew_point": 292.1,
            "clouds": 90,
            "wind_speed": 7,
            "wind_deg": 189,
            "weather": [
                {
                    "id": 501,
                    "main": "Rain",
                    "description": "moderate rain",
                    "icon": "10d"
                }
            ],
            "rain": {
                "1h": 2.28
            }
        }

        result1 = Weather.from_dict(hourly1)
        self.assertTrue(isinstance(result1, Weather))
        self.assertEqual(292.47, result1.temperature()["feels_like"])
        self.assertEqual(501, result1.weather_code)
        self.assertEqual(2.28, result1.rain["1h"])
        self.assertEqual(294.16, result1.temperature()["temp"])
        self.assertEqual(292.47, result1.temperature()["feels_like"])

        hourly2 = {
            "dt": 1587682800,
            "temp": 279.64,
            "feels_like": 276.77,
            "pressure": 1020,
            "humidity": 54,
            "dew_point": 271.26,
            "clouds": 3,
            "wind_speed": 0.84,
            "wind_deg": 119,
            "weather": [
                {
                    "id": 800,
                    "main": "Clear",
                    "description": "clear sky",
                    "icon": "01n"
                }
            ]
        }

        result2 = Weather.from_dict(hourly2)
        self.assertTrue(isinstance(result2, Weather))
        self.assertEqual(3, result2.clouds)
        self.assertEqual(800, result2.weather_code)
        self.assertEqual(119, result2.wind()["deg"])
        self.assertEqual(0, len(result2.rain))
        self.assertEqual(279.64, result2.temperature()["temp"])
        self.assertEqual(276.77, result2.temperature()["feels_like"])

    def test_one_call_daily_from_dic(self):
        daily1 = {
            "dt": 1587747600,
            "sunrise": 1587725080,
            "sunset": 1587772792,
            "temp": {
                "day": 300.75,
                "min": 290.76,
                "max": 300.75,
                "night": 290.76,
                "eve": 295.22,
                "morn": 291.44
            },
            "feels_like": {
                "day": 300.69,
                "night": 291.63,
                "eve": 296.8,
                "morn": 292.73
            },
            "pressure": 1009,
            "humidity": 55,
            "dew_point": 291.24,
            "wind_speed": 3.91,
            "wind_deg": 262,
            "weather": [
                {
                    "id": 500,
                    "main": "Rain",
                    "description": "light rain",
                    "icon": "10d"
                }
            ],
            "clouds": 95,
            "rain": 0.82,
            "uvi": 9.46
        }

        result1 = Weather.from_dict(daily1)
        self.assertTrue(isinstance(result1, Weather))
        self.assertEqual(9.46, result1.uvi)
        self.assertEqual(500, result1.weather_code)
        self.assertEqual(262, result1.wind()["deg"])
        self.assertEqual(0.82, result1.rain["all"])
        self.assertRaises(KeyError, lambda: result1.temperature()["temp"])
        self.assertRaises(KeyError, lambda: result1.temperature()["feels_like"])
        self.assertEqual(300.75, result1.temperature()["day"])
        self.assertEqual(290.76, result1.temperature()["min"])
        self.assertEqual(300.75, result1.temperature()["max"])
        self.assertEqual(290.76, result1.temperature()["night"])
        self.assertEqual(295.22, result1.temperature()["eve"])
        self.assertEqual(291.44, result1.temperature()["morn"])
        self.assertEqual(300.69, result1.temperature()["feels_like_day"])
        self.assertEqual(291.63, result1.temperature()["feels_like_night"])
        self.assertEqual(296.8, result1.temperature()["feels_like_eve"])
        self.assertEqual(292.73, result1.temperature()["feels_like_morn"])

        daily2 = {
            "dt": 1587639600,
            "sunrise": 1587615127,
            "sunset": 1587665513,
            "temp": {
                "day": 281.78,
                "min": 279.88,
                "max": 281.78,
                "night": 279.88,
                "eve": 281.78,
                "morn": 281.78
            },
            "feels_like": {
                "day": 278.55,
                "night": 276.84,
                "eve": 278.55,
                "morn": 278.55
            },
            "pressure": 1017,
            "humidity": 39,
            "dew_point": 269.13,
            "wind_speed": 0.96,
            "wind_deg": 116,
            "weather": [
                {
                    "id": 800,
                    "main": "Clear",
                    "description": "clear sky",
                    "icon": "01n"
                }
            ],
            "clouds": 2,
            "uvi": 7.52
        }

        result2 = Weather.from_dict(daily2)
        self.assertTrue(isinstance(result2, Weather))
        self.assertEqual(7.52, result2.uvi)
        self.assertEqual(800, result2.weather_code)
        self.assertEqual(116, result2.wind()["deg"])
        self.assertEqual(0, len(result2.rain))
        self.assertRaises(KeyError, lambda: result2.temperature()["temp"])
        self.assertRaises(KeyError, lambda: result2.temperature()["feels_like"])
        self.assertEqual(281.78, result2.temperature()["day"])
        self.assertEqual(279.88, result2.temperature()["min"])
        self.assertEqual(281.78, result2.temperature()["max"])
        self.assertEqual(279.88, result2.temperature()["night"])
        self.assertEqual(281.78, result2.temperature()["eve"])
        self.assertEqual(281.78, result2.temperature()["morn"])
        self.assertEqual(278.55, result2.temperature()["feels_like_day"])
        self.assertEqual(276.84, result2.temperature()["feels_like_night"])
        self.assertEqual(278.55, result2.temperature()["feels_like_eve"])
        self.assertEqual(278.55, result2.temperature()["feels_like_morn"])
class TestObservation(unittest.TestCase):

    __test_reception_time = 1234567
    __test_iso_reception_time = "1970-01-15 06:56:07+00"
    __test_date_reception_time = datetime.strptime(__test_iso_reception_time,
                               '%Y-%m-%d %H:%M:%S+00').replace(tzinfo=UTC())
    __test_location = Location('test', 12.3, 43.7, 987, 'UK')
    __test_weather = Weather(1378459200, 1378496400, 1378449600, 67, {"all": 20},
            {"all": 0}, {"deg": 252.002, "speed": 1.100}, 57,
            {"press": 1030.119, "sea_level": 1038.589},
            {"temp": 294.199, "temp_kf": -1.899, "temp_max": 296.098,
                "temp_min": 294.199
            },
            "Clouds", "Overcast clouds", 804, "04d", 1000, 300.0, 298.0, 296.0)
    __test_instance = Observation(__test_reception_time, __test_location,
                                  __test_weather)

    __bad_json = '{"a": "test", "b": 1.234, "c": [ "hello", "world"] }'
    __bad_json_2 = '{"message": "test", "cod": "500"}'
    __no_items_json = '{"cod": "200", "count": "0" }'
    __404_json = '{"cod": "404" }'

    OBSERVATION_JSON_DUMP = '{"reception_time": 1234567, "location": ' \
                            '{"country": "UK", "name": "test", "coordinates": ' \
                            '{"lat": 43.7, "lon": 12.3}, "ID": 987}, "weather": ' \
                            '{"status": "Clouds", "visibility_distance": 1000, ' \
                            '"humidity": 57, "clouds": 67, "temperature": ' \
                            '{"temp_kf": -1.899, "temp_max": 296.098, ' \
                            '"temp": 294.199, "temp_min": 294.199}, ' \
                            '"dewpoint": 300.0, "snow": {"all": 0}, ' \
                            '"detailed_status": "Overcast clouds", ' \
                            '"reference_time": 1378459200, "weather_code": 804, ' \
                            '"humidex": 298.0, "rain": {"all": 20}, ' \
                            '"sunset_time": 1378496400, "pressure": ' \
                            '{"press": 1030.119, "sea_level": 1038.589}, ' \
                            '"sunrise_time": 1378449600, "heat_index": 296.0, ' \
                            '"weather_icon_name": "04d", "wind": ' \
                            '{"speed": 1.1, "deg": 252.002}, "utc_offset": null, ' \
                            '"uvi": null}}'

    def test_init_fails_when_reception_time_is_negative(self):
        self.assertRaises(ValueError, Observation, -1234567, \
                          self.__test_location, self.__test_weather)

    def test_getters_return_expected_data(self):
        self.assertEqual(self.__test_instance.reception_time(),
                         self.__test_reception_time)
        self.assertEqual(self.__test_instance.location,
                         self.__test_location)
        self.assertEqual(self.__test_instance.weather,
                         self.__test_weather)

    def test_returning_different_formats_for_reception_time(self):
        self.assertEqual(self.__test_instance.reception_time(timeformat='iso'), \
                         self.__test_iso_reception_time)
        self.assertEqual(self.__test_instance.reception_time(timeformat='unix'), \
                         self.__test_reception_time)
        self.assertEqual(self.__test_instance.reception_time(timeformat='date'), \
                         self.__test_date_reception_time)

    def test_from_dict(self):
        d = json.loads(OBSERVATION_JSON)
        result = Observation.from_dict(d)
        self.assertTrue(result is not None)
        self.assertFalse(result.reception_time() is None)
        loc = result.location
        self.assertFalse(loc is None)
        self.assertTrue(all(v is not None for v in loc.__dict__.values()))
        weat = result.weather
        self.assertFalse(weat is None)

    def test_from_dict_fails_when_JSON_data_is_None(self):
        with self.assertRaises(ParseAPIResponseError):
            Observation.from_dict(None)

    def test_from_dict_fails_with_malformed_JSON_data(self):
        with self.assertRaises(ParseAPIResponseError):
            Observation.from_dict(json.loads(self.__bad_json))
        with self.assertRaises(APIResponseError):
            Observation.from_dict(json.loads(self.__bad_json_2))
        with self.assertRaises(ParseAPIResponseError):
            Observation.from_dict(json.loads(OBSERVATION_MALFORMED_JSON))

    def test_from_dict_when_server_error(self):
        result = self.__test_instance.from_dict(json.loads(OBSERVATION_NOT_FOUND_JSON))
        self.assertTrue(result is None)

    def test_to_dict(self):
        expected = json.loads(self.OBSERVATION_JSON_DUMP)
        result = self.__test_instance.to_dict()
        self.assertEqual(expected, result)

    def test_from_dict_of_lists(self):
        result = self.__test_instance.from_dict_of_lists(json.loads(SEARCH_RESULTS_JSON))
        self.assertFalse(result is None)
        self.assertTrue(isinstance(result, list))
        for item in result:
            self.assertFalse(item is None)
            self.assertFalse(item.reception_time() is None)
            loc = item.location
            self.assertFalse(loc is None)
            self.assertTrue(all(v is not None for v in loc.__dict__.values()))
            weat = item.weather
            self.assertFalse(weat is None)

    def test_from_dict_of_lists_fails_when_JSON_data_is_None(self):
        with self.assertRaises(ParseAPIResponseError):
            Observation.from_dict_of_lists(None)

    def test_from_dict_of_lists_with_malformed_JSON_data(self):
        with self.assertRaises(ParseAPIResponseError):
            Observation.from_dict_of_lists(json.loads(self.__bad_json))
        with self.assertRaises(APIResponseError):
            Observation.from_dict_of_lists(json.loads(self.__bad_json_2))
        with self.assertRaises(ParseAPIResponseError):
            Observation.from_dict_of_lists(json.loads(OBSERVATION_MALFORMED_JSON))

    def test_from_dict_of_lists_when_no_items_returned(self):
        self.assertFalse(Observation.from_dict_of_lists(json.loads(self.__no_items_json)))

    def test_from_dict_of_lists_when_resource_not_found(self):
        self.assertIsNone(Observation.from_dict_of_lists(json.loads(self.__404_json)))

    def test_from_dict_of_lists_when_no_results(self):
        result = Observation.from_dict_of_lists(json.loads(SEARCH_WITH_NO_RESULTS_1_JSON))
        self.assertTrue(isinstance(result, list))
        self.assertEqual(0, len(result))

        result = Observation.from_dict_of_lists(json.loads(SEARCH_WITH_NO_RESULTS_2_JSON))
        self.assertTrue(isinstance(result, list))
        self.assertEqual(0, len(result))

    def test_from_dict_of_lists_when_server_error(self):
        with self.assertRaises(APIResponseError):
            Observation.from_dict_of_lists(json.loads(INTERNAL_SERVER_ERROR_JSON))

    def test__repr(self):
        print(self.__test_instance)
class TestSO2Index(unittest.TestCase):

    __test_reception_time = 1475283600
    __test_iso_reception_time = "2016-10-01 01:00:00+00"
    __test_date_reception_time = datetime.strptime(
        __test_iso_reception_time,
        '%Y-%m-%d %H:%M:%S+00').replace(tzinfo=UTC())

    __test_reference_time = 1234567
    __test_iso_reference_time = "1970-01-15 06:56:07+00"
    __test_date_reference_time = datetime.strptime(
        __test_iso_reference_time,
        '%Y-%m-%d %H:%M:%S+00').replace(tzinfo=UTC())
    __test_location = Location('test', 12.3, 43.7, 987, 'UK')
    __test_so2_samples = [{
        "precision": -4.999999987376214e-7,
        "pressure": 1000,
        "value": 8.168363052618588e-8
    }, {
        "precision": -4.999999987376214e-7,
        "pressure": 681.2920532226562,
        "value": 8.686949115599418e-8
    }, {
        "precision": -4.999999987376214e-7,
        "pressure": 464.15887451171875,
        "value": 8.871462853221601e-8
    }]
    __test_interval = 'day'
    __test_instance = SO2Index(__test_reference_time, __test_location,
                               __test_interval, __test_so2_samples,
                               __test_reception_time)

    def test_init_fails_when_reference_time_is_negative(self):
        self.assertRaises(ValueError, SO2Index, -1234567, self.__test_location,
                          self.__test_interval, self.__test_so2_samples,
                          self.__test_reception_time)

    def test_init_fails_when_reception_time_is_negative(self):
        self.assertRaises(ValueError, SO2Index, self.__test_reference_time,
                          self.__test_location, self.__test_interval,
                          self.__test_so2_samples, -1234567)

    def test_init_fails_when_so2_samples_is_not_a_list(self):
        self.assertRaises(ValueError, SO2Index, self.__test_reference_time,
                          self.__test_location, self.__test_interval, 'test',
                          self.__test_reception_time)

    def test_returning_different_formats_for_reference_time(self):
        self.assertEqual(self.__test_instance.reference_time(timeformat='iso'), \
                         self.__test_iso_reference_time)
        self.assertEqual(self.__test_instance.reference_time(timeformat='unix'), \
                         self.__test_reference_time)
        self.assertEqual(self.__test_instance.reference_time(timeformat='date'), \
                         self.__test_date_reference_time)

    def test_returning_different_formats_for_reception_time(self):
        self.assertEqual(self.__test_instance.reception_time(timeformat='iso'), \
                         self.__test_iso_reception_time)
        self.assertEqual(self.__test_instance.reception_time(timeformat='unix'), \
                         self.__test_reception_time)
        self.assertEqual(self.__test_instance.reception_time(timeformat='date'), \
                         self.__test_date_reception_time)

    def test_is_forecast(self):
        self.assertFalse(self.__test_instance.is_forecast())
        in_a_year = datetime_to_UNIXtime(datetime.utcnow()) + 31536000
        uvindex = SO2Index(in_a_year, self.__test_location,
                           self.__test_interval, [],
                           self.__test_reception_time)
        self.assertTrue(uvindex.is_forecast())

    def test_from_dict(self):
        result = SO2Index.from_dict(json.loads(SO2INDEX_JSON))
        self.assertIsNotNone(result)
        self.assertIsNotNone(result.reference_time())
        self.assertIsNotNone(result.reference_time())
        loc = result.location
        self.assertIsNotNone(loc)
        self.assertIsNone(loc.name)
        self.assertIsNone(loc.id)
        self.assertIsNotNone(loc.lon)
        self.assertIsNotNone(loc.lat)
        self.assertIsNone(result.interval)
        self.assertNotEqual(0, len(result.so2_samples))

    def test_parse_JSON_fails_when_JSON_data_is_None(self):
        self.assertRaises(ParseAPIResponseError, SO2Index.from_dict, None)

    def test_parse_JSON_fails_with_malformed_JSON_data(self):
        self.assertRaises(ParseAPIResponseError, SO2Index.from_dict,
                          json.loads(SO2INDEX_MALFORMED_JSON))

    def test_to_dict(self):
        expected = json.loads(SO2INDEX_JSON_DUMP)
        result = self.__test_instance.to_dict()
        self.assertEqual(expected, result)

    def test_repr(self):
        print(self.__test_instance)
class TestForecaster(unittest.TestCase):

    __test_time_1 = 1379090800
    __test_start_coverage_iso = "2013-09-13 16:46:40+00"
    __test_date_start_coverage = datetime.strptime(
        __test_start_coverage_iso,
        '%Y-%m-%d %H:%M:%S+00').replace(tzinfo=UTC())
    __test_middle_1_coverage = 1379226100
    __test_middle_1_coverage_iso = "2013-09-15 06:21:40+00"
    __test_date_middle_1_coverage = datetime.strptime(
        __test_middle_1_coverage_iso,
        '%Y-%m-%d %H:%M:%S+00').replace(tzinfo=UTC())
    __test_time_2 = 1379361400
    __test_middle_2_coverage_iso = "2013-09-16 19:56:40+00"
    __test_date_middle_2_coverage = datetime.strptime(
        __test_middle_2_coverage_iso,
        '%Y-%m-%d %H:%M:%S+00').replace(tzinfo=UTC())
    __test_end_coverage = 1379902600
    __test_end_coverage_iso = "2013-09-23 02:16:40+00"
    __test_date_end_coverage = datetime.strptime(
        __test_end_coverage_iso, '%Y-%m-%d %H:%M:%S+00').replace(tzinfo=UTC())

    __test_location = Location('test', 12.3, 43.7, 987, 'IT')

    __test_weather_rainsnow = Weather(__test_time_1, 1378496400, 1378449600,
                                      67, {"all": 30}, {"all": 1}, {
                                          "deg": 252.002,
                                          "speed": 4.100
                                      }, 57, {
                                          "press": 1030.119,
                                          "sea_level": 1038.589
                                      }, {
                                          "temp": 294.199,
                                          "temp_kf": -1.899,
                                          "temp_max": 296.098,
                                          "temp_min": 294.199
                                      }, "Rain", "Light rain", 500, "10d",
                                      1000, 300.0, 298.0, 296.0)
    __test_weather_clouds = Weather(__test_middle_1_coverage, 1378496480,
                                    1378449510, 23, {"all": 0}, {}, {
                                        "deg": 103.4,
                                        "speed": 1.2
                                    }, 12, {
                                        "press": 1070.119,
                                        "sea_level": 1078.589
                                    }, {
                                        "temp": 297.199,
                                        "temp_kf": -1.899,
                                        "temp_max": 299.0,
                                        "temp_min": 295.6
                                    }, "Clouds", "Overcast clouds", 804, "02d",
                                    1000, 300.0, 298.0, 296.0)
    __test_weather_sun_1 = Weather(__test_time_2, 1378496480, 1378449510, 5,
                                   {"all": 0}, {}, {
                                       "deg": 103.4,
                                       "speed": 1.2
                                   }, 12, {
                                       "press": 1090.119,
                                       "sea_level": 1078.589
                                   }, {
                                       "temp": 299.199,
                                       "temp_kf": -1.899,
                                       "temp_max": 301.0,
                                       "temp_min": 297.6
                                   }, "Clear", "Sky is clear", 800, "01d",
                                   1000, 300.0, 298.0, 296.0)
    __test_weather_sun_2 = Weather(__test_end_coverage, 1378496480, 1378449510,
                                   5, {"all": 0}, {}, {
                                       "deg": 99.4,
                                       "speed": 0.8
                                   }, 7, {
                                       "press": 1091.119,
                                       "sea_level": 1079.589
                                   }, {
                                       "temp": 299.599,
                                       "temp_kf": -1.899,
                                       "temp_max": 301.9,
                                       "temp_min": 298.0
                                   }, "Clear", "Sky is clear", 800, "01d",
                                   1000, 300.0, 298.0, 296.0)

    __test_weather_storm = Weather(__test_end_coverage, 1378496480, 1378449510,
                                   5, {"all": 0}, {}, {
                                       "deg": 99.4,
                                       "speed": 0.8
                                   }, 7, {
                                       "press": 1071.119,
                                       "sea_level": 1059.589
                                   }, {
                                       "temp": 299.599,
                                       "temp_kf": -1.899,
                                       "temp_max": 301.9,
                                       "temp_min": 298.0
                                   }, "Storm", "Violent storm", 961, "01d",
                                   1000, 300.0, 298.0, 296.0)

    __test_weather_hurricane = Weather(__test_end_coverage, 1378496480,
                                       1378449510, 5, {"all": 0}, {}, {
                                           "deg": 99.4,
                                           "speed": 0.8
                                       }, 7, {
                                           "press": 1071.119,
                                           "sea_level": 1059.589
                                       }, {
                                           "temp": 299.599,
                                           "temp_kf": -1.899,
                                           "temp_max": 301.9,
                                           "temp_min": 298.0
                                       }, "Hurricane", "Hurricane", 962, "01d",
                                       1000, 300.0, 298.0, 296.0)

    __test_none_values = Weather(__test_end_coverage, 1378496480, 1378449510,
                                 5, {}, {}, {}, 7, {
                                     "press": 1091.119,
                                     "sea_level": 1079.589
                                 }, {
                                     "temp": 299.599,
                                     "temp_kf": -1.899
                                 }, "Clear", "Sky is clear", 800, "01d", 1000,
                                 300.0, 298.0, 296.0)
    __test_weathers = [
        __test_weather_rainsnow, __test_weather_clouds, __test_weather_sun_1,
        __test_weather_sun_2, __test_weather_storm, __test_weather_hurricane
    ]

    __test_forecast = Forecast("daily", 1379089800, __test_location,
                               __test_weathers)

    __test_instance = Forecaster(__test_forecast)

    def test_getter_returns_expected_data(self):
        self.assertEqual(self.__test_instance.forecast, self.__test_forecast)

    def test_when_starts_returning_different_timeformats(self):
        self.assertEqual(self.__test_instance.when_starts(timeformat='iso'),
                         self.__test_start_coverage_iso)
        self.assertEqual(self.__test_instance.when_starts(timeformat='unix'),
                         self.__test_time_1)
        self.assertEqual(self.__test_instance.when_starts(timeformat='date'),
                         self.__test_date_start_coverage)

    def test_when_ends_returning_different_timeformats(self):
        self.assertEqual(self.__test_instance.when_ends(timeformat='iso'),
                         self.__test_end_coverage_iso)
        self.assertEqual(self.__test_instance.when_ends(timeformat='unix'),
                         self.__test_end_coverage)
        self.assertEqual(self.__test_instance.when_ends(timeformat='date'),
                         self.__test_date_end_coverage)

    def test_will_have_rain(self):
        self.assertTrue(self.__test_instance.will_have_rain())

    def test_will_have_clear(self):
        self.assertTrue(self.__test_instance.will_have_clear())

    def test_will_have_clouds(self):
        self.assertTrue(self.__test_instance.will_have_clouds())

    def test_will_have_fog(self):
        self.assertFalse(self.__test_instance.will_have_fog())

    def test_will_have_snow(self):
        self.assertFalse(self.__test_instance.will_have_snow())

    def test_will_have_storm(self):
        self.assertTrue(self.__test_instance.will_have_storm())

    def test_will_have_tornado(self):
        self.assertFalse(self.__test_instance.will_have_tornado())

    def test_will_have_hurricane(self):
        self.assertTrue(self.__test_instance.will_have_hurricane())

    def test_when_rain(self):
        self.assertEqual([self.__test_weather_rainsnow],
                         self.__test_instance.when_rain())

    def test_when_clear(self):
        self.assertEqual(
            [self.__test_weather_sun_1, self.__test_weather_sun_2],
            self.__test_instance.when_clear())

    def test_when_clouds(self):
        self.assertEqual([self.__test_weather_clouds],
                         self.__test_instance.when_clouds())

    def test_when_fog(self):
        self.assertFalse(self.__test_instance.when_fog())

    def test_when_snow(self):
        self.assertFalse(self.__test_instance.when_snow())

    def test_when_storm(self):
        self.assertTrue(self.__test_instance.when_storm())

    def test_when_tornado(self):
        self.assertFalse(self.__test_instance.when_tornado())

    def test_when_hurricane(self):
        self.assertTrue(self.__test_instance.when_hurricane())

    def test_will_be_rainy_at(self):
        time_1 = datetime(2013, 9, 13, 16, 47, 0)
        time_2 = 1379226110
        time_3 = "2013-09-16 19:56:50+00"
        self.assertTrue(self.__test_instance.will_be_rainy_at(time_1))
        self.assertFalse(self.__test_instance.will_be_rainy_at(time_2))
        self.assertFalse(self.__test_instance.will_be_rainy_at(time_3))

    def test_will_be_rainy_at_fails_with_bad_parameters(self):
        self.assertRaises(TypeError, Forecaster.will_be_rainy_at,
                          self.__test_instance, 45.7)

    def test_will_be_clear_at(self):
        time_1 = datetime(2013, 9, 13, 16, 47, 0)
        time_2 = 1379226110
        time_3 = "2013-09-16 19:56:50+00"
        self.assertFalse(self.__test_instance.will_be_clear_at(time_1))
        self.assertFalse(self.__test_instance.will_be_clear_at(time_2))
        self.assertTrue(self.__test_instance.will_be_clear_at(time_3))

    def test_will_be_clear_at_fails_with_bad_parameters(self):
        self.assertRaises(TypeError, Forecaster.will_be_clear_at,
                          self.__test_instance, 45.7)

    def test_will_be_snowy_at(self):
        time_1 = datetime(2013, 9, 13, 16, 47, 0)
        time_2 = 1379226110
        time_3 = "2013-09-16 19:56:50+00"
        self.assertFalse(self.__test_instance.will_be_snowy_at(time_1))
        self.assertFalse(self.__test_instance.will_be_snowy_at(time_2))
        self.assertFalse(self.__test_instance.will_be_snowy_at(time_3))

    def test_will_be_snowy_at_fails_with_bad_parameters(self):
        self.assertRaises(TypeError, Forecaster.will_be_snowy_at,
                          self.__test_instance, 45.7)

    def test_will_be_cloudy_at(self):
        time_1 = datetime(2013, 9, 13, 16, 47, 0)
        time_2 = 1379226110
        time_3 = "2013-09-16 19:56:50+00"
        self.assertFalse(self.__test_instance.will_be_cloudy_at(time_1))
        self.assertTrue(self.__test_instance.will_be_cloudy_at(time_2))
        self.assertFalse(self.__test_instance.will_be_cloudy_at(time_3))

    def test_will_be_cloudy_at_fails_with_bad_parameters(self):
        self.assertRaises(TypeError, Forecaster.will_be_cloudy_at,
                          self.__test_instance, 45.7)

    def test_will_be_foggy_at(self):
        time_1 = datetime(2013, 9, 13, 16, 47, 0)
        time_2 = 1379226110
        time_3 = "2013-09-16 19:56:50+00"
        self.assertFalse(self.__test_instance.will_be_foggy_at(time_1))
        self.assertFalse(self.__test_instance.will_be_foggy_at(time_2))
        self.assertFalse(self.__test_instance.will_be_foggy_at(time_3))

    def test_will_be_foggy_at_fails_with_bad_parameters(self):
        self.assertRaises(TypeError, Forecaster.will_be_foggy_at,
                          self.__test_instance, 45.7)

    def test_will_be_stormy_at(self):
        time_1 = datetime(2013, 9, 13, 16, 47, 0)
        time_2 = 1379226110
        time_3 = "2013-09-16 19:56:50+00"
        self.assertFalse(self.__test_instance.will_be_stormy_at(time_1))
        self.assertFalse(self.__test_instance.will_be_stormy_at(time_2))
        self.assertFalse(self.__test_instance.will_be_stormy_at(time_3))

    def test_will_be_stormy_at_fails_with_bad_parameters(self):
        self.assertRaises(TypeError, Forecaster.will_be_stormy_at,
                          self.__test_instance, 45.7)

    def test_will_be_tornado_at(self):
        time_1 = datetime(2013, 9, 13, 16, 47, 0)
        time_2 = 1379226110
        time_3 = "2013-09-16 19:56:50+00"
        self.assertFalse(self.__test_instance.will_be_tornado_at(time_1))
        self.assertFalse(self.__test_instance.will_be_tornado_at(time_2))
        self.assertFalse(self.__test_instance.will_be_tornado_at(time_3))

    def test_will_be_tornado_at_fails_with_bad_parameters(self):
        self.assertRaises(TypeError, Forecaster.will_be_tornado_at,
                          self.__test_instance, 45.7)

    def test_will_be_hurricane_at(self):
        time_1 = datetime(2013, 9, 13, 16, 47, 0)
        time_2 = 1379226110
        time_3 = "2013-09-16 19:56:50+00"
        self.assertFalse(self.__test_instance.will_be_hurricane_at(time_1))
        self.assertFalse(self.__test_instance.will_be_hurricane_at(time_2))
        self.assertFalse(self.__test_instance.will_be_hurricane_at(time_3))

    def test_will_be_hurricane_at_fails_with_bad_parameters(self):
        self.assertRaises(TypeError, Forecaster.will_be_hurricane_at,
                          self.__test_instance, 45.7)

    def test_get_weather_at(self):
        time_1 = datetime(2013, 9, 13, 16, 47, 0)
        time_2 = 1379226110
        time_3 = "2013-09-16 19:56:50+00"
        self.assertEqual(self.__test_instance.get_weather_at(time_1),
                         self.__test_weather_rainsnow)
        self.assertEqual(self.__test_instance.get_weather_at(time_2),
                         self.__test_weather_clouds)
        self.assertEqual(self.__test_instance.get_weather_at(time_3),
                         self.__test_weather_sun_1)

    def test_get_weather_at_fails_with_bad_parameter(self):
        self.assertRaises(TypeError, Forecaster.get_weather_at,
                          self.__test_instance, 45.7)

    def test_most_hot(self):
        self.assertEqual(self.__test_weather_sun_2,
                         self.__test_instance.most_hot())

    def test_most_hot_returning_None(self):
        fcstr = Forecaster(
            Forecast("daily", 1379089800, self.__test_location,
                     [self.__test_none_values]))
        self.assertFalse(fcstr.most_hot())

    def test_most_cold(self):
        self.assertEqual(self.__test_weather_rainsnow,
                         self.__test_instance.most_cold())

    def test_most_cold_returning_None(self):
        fcstr = Forecaster(
            Forecast("daily", 1379089800, self.__test_location,
                     [self.__test_none_values]))
        self.assertFalse(fcstr.most_hot())

    def test_most_humid(self):
        self.assertEqual(self.__test_weather_rainsnow,
                         self.__test_instance.most_humid())

    def test_most_rainy(self):
        self.assertEqual(self.__test_weather_rainsnow,
                         self.__test_instance.most_rainy())

    def test_most_snowy(self):
        self.assertEqual(self.__test_weather_rainsnow,
                         self.__test_instance.most_snowy())

    def test_most_rainy_returning_None(self):
        fcstr = Forecaster(
            Forecast("daily", 1379089800, self.__test_location,
                     [self.__test_none_values]))
        self.assertFalse(fcstr.most_rainy())

    def test_most_windy(self):
        self.assertEqual(self.__test_weather_rainsnow,
                         self.__test_instance.most_windy())

    def test_most_windy_returning_None(self):
        fcstr = Forecaster(
            Forecast("daily", 1379089800, self.__test_location,
                     [self.__test_none_values]))
        self.assertFalse(fcstr.most_windy())

    def test__repr(self):
        print(self.__test_instance)
class TestBuffer(unittest.TestCase):

    ts = 1378459200
    iso_ts = "2013-09-06 09:20:00+00"
    date_ts = dt.strptime(iso_ts, '%Y-%m-%d %H:%M:%S+00').replace(tzinfo=UTC())

    station_id = 'mytest'

    m1 = Measurement(station_id,
                     ts,
                     temperature=dict(min=0, max=100),
                     wind_speed=2.1,
                     wind_gust=67,
                     humidex=77,
                     weather_other=dict(key='val'))
    m2 = Measurement(station_id,
                     ts + 500,
                     temperature=dict(min=30, max=800),
                     wind_speed=8.5,
                     wind_gust=0,
                     humidex=0)
    m3 = Measurement(station_id,
                     ts - 1000,
                     temperature=dict(min=0, max=20),
                     wind_speed=4.4,
                     wind_gust=-12,
                     humidex=2)

    def test_assertions_on_instantiation(self):
        with self.assertRaises(AssertionError):
            Buffer(None)

    def test_creation_time(self):
        buf = Buffer(self.station_id)
        ts = buf.creation_time()
        iso_result = buf.creation_time(timeformat='iso')
        self.assertEqual(to_ISO8601(ts), iso_result)
        date_result = buf.creation_time(timeformat='date')
        self.assertEqual(to_date(ts), date_result)
        with self.assertRaises(ValueError):
            buf.creation_time(timeformat='unknown')

        buf.created_at = None
        self.assertIsNone(buf.creation_time())

    def test_append(self):
        buf = Buffer(self.station_id)
        self.assertEqual(0, len(buf))
        buf.append(self.m1)
        self.assertEqual(1, len(buf))
        self.assertTrue(self.m1 in buf)

        buf = Buffer(self.station_id)

        with self.assertRaises(AssertionError):
            buf.append('not_a_measurement')

        msmt = deepcopy(self.m1)
        msmt.station_id = 'another_id'
        with self.assertRaises(AssertionError):
            buf.append(msmt)

    def test_append_from_dict(self):
        buf = Buffer(self.station_id)
        self.assertEqual(0, len(buf))
        the_dict = dict(station_id='mytest',
                        timestamp=1378459200,
                        temperature=dict(min=0, max=100),
                        wind_speed=2.1,
                        wind_gust=67,
                        humidex=77,
                        weather_other=dict(key='val'))
        buf.append_from_dict(the_dict)
        self.assertEqual(1, len(buf))

    def test_append_from_json(self):
        buf = Buffer(self.station_id)
        self.assertEqual(0, len(buf))
        the_dict = dict(station_id='mytest',
                        timestamp=1378459200,
                        temperature=dict(min=0, max=100),
                        wind_speed=2.1,
                        wind_gust=67,
                        humidex=77,
                        weather_other=dict(key='val'))
        json_str = json.dumps(the_dict)
        buf.append_from_json(json_str)
        self.assertEqual(1, len(buf))

    def test_empty(self):
        buf = Buffer(self.station_id)
        self.assertEqual(0, len(buf))
        buf.append(self.m1)
        buf.append(self.m2)
        buf.append(self.m3)
        self.assertEqual(3, len(buf))
        self.assertTrue(self.m1 in buf)
        self.assertTrue(self.m2 in buf)
        self.assertTrue(self.m3 in buf)
        buf.empty()
        self.assertEqual(0, len(buf))

    def test_sort_chronologically(self):
        ordered_chrono = [self.m3, self.m1, self.m2]
        buf = Buffer(station_id=self.station_id)
        buf.append(self.m1)
        buf.append(self.m2)
        buf.append(self.m3)
        self.assertNotEqual(buf.measurements, ordered_chrono)
        buf.sort_chronologically()
        self.assertEqual(buf.measurements, ordered_chrono)

    def test_sort_reverse_chronologically(self):
        ordered_reverse_chrono = [self.m2, self.m1, self.m3]
        buf = Buffer(station_id=self.station_id)
        buf.append(self.m1)
        buf.append(self.m2)
        buf.append(self.m3)
        self.assertNotEqual(buf.measurements, ordered_reverse_chrono)
        buf.sort_reverse_chronologically()
        self.assertEqual(buf.measurements, ordered_reverse_chrono)

    def test_iteration(self):
        buf = Buffer(station_id=self.station_id)
        buf.append(self.m1)
        buf.append(self.m2)
        buf.append(self.m3)
        for item in buf:
            self.assertTrue(isinstance(item, Measurement))
            self.assertTrue(item in [self.m1, self.m2, self.m3])

    def test_contains(self):
        buf = Buffer(station_id=self.station_id)
        buf.append(self.m1)
        self.assertFalse(self.m3 in buf)
        self.assertTrue(self.m1 in buf)
        self.assertFalse(self.m2 in buf)

    def test_add(self):
        buf1 = Buffer(station_id=self.station_id)
        buf1.append(self.m1)
        buf2 = Buffer(station_id=self.station_id)
        buf2.append(self.m2)
        buf2.append(self.m3)
        result = buf1 + buf2
        self.assertEquals(3, len(result))

    def test_repr(self):
        buf = Buffer(self.station_id)
        buf.append(self.m2)
        str(buf)
class TestUVIndex(unittest.TestCase):

    __test_reception_time = 1475283600
    __test_iso_reception_time = "2016-10-01 01:00:00+00"
    __test_date_reception_time = datetime.strptime(__test_iso_reception_time,
                               '%Y-%m-%d %H:%M:%S+00').replace(tzinfo=UTC())

    __test_reference_time = 1234567
    __test_iso_reference_time = "1970-01-15 06:56:07+00"
    __test_date_reference_time = datetime.strptime(__test_iso_reference_time,
                               '%Y-%m-%d %H:%M:%S+00').replace(tzinfo=UTC())

    __test_location = Location('test', 12.3, 43.7, 987, 'UK')
    __test_uv_intensity = 6.8
    __test_exposure_risk = 'high'
    __test_instance = uvindex.UVIndex(
        __test_reference_time, __test_location, __test_uv_intensity,
        __test_reception_time)

    def test_init_fails_when_reference_time_is_negative(self):
        self.assertRaises(ValueError, uvindex.UVIndex, -1234567,
                          self.__test_location,
                          self.__test_uv_intensity,
                          self.__test_reception_time)

    def test_init_fails_when_reception_time_is_negative(self):
        self.assertRaises(ValueError, uvindex.UVIndex,
                            self.__test_reference_time,
                            self.__test_location,
                            self.__test_uv_intensity,
                            -1234567)

    def test_init_fails_when_uv_intensity_is_negative(self):
        self.assertRaises(ValueError, uvindex.UVIndex, self.__test_reference_time,
                          self.__test_location, -8.9,
                          self.__test_reception_time)

    def test_returning_different_formats_for_reception_time(self):
        self.assertEqual(self.__test_instance.reception_time(timeformat='iso'), \
                         self.__test_iso_reception_time)
        self.assertEqual(self.__test_instance.reception_time(timeformat='unix'), \
                         self.__test_reception_time)
        self.assertEqual(self.__test_instance.reception_time(timeformat='date'), \
                         self.__test_date_reception_time)

    def test_returning_different_formats_for_reference_time(self):
        self.assertEqual(self.__test_instance.reference_time(timeformat='iso'), \
                         self.__test_iso_reference_time)
        self.assertEqual(self.__test_instance.reference_time(timeformat='unix'), \
                         self.__test_reference_time)
        self.assertEqual(self.__test_instance.reference_time(timeformat='date'), \
                         self.__test_date_reference_time)

    def test_uv_intensity_to_exposure_risk(self):
        self.assertEqual(uvindex.uv_intensity_to_exposure_risk(0.5), 'low')
        self.assertEqual(uvindex.uv_intensity_to_exposure_risk(3.5), 'moderate')
        self.assertEqual(uvindex.uv_intensity_to_exposure_risk(6.5), 'high')
        self.assertEqual(uvindex.uv_intensity_to_exposure_risk(8.5), 'very high')
        self.assertEqual(uvindex.uv_intensity_to_exposure_risk(30.5), 'extreme')

    def test_to_dict(self):
        expected = json.loads(UVINDEX_JSON_DUMP)
        result = self.__test_instance.to_dict()
        self.assertEqual(expected, result)

    def test_from_dict(self):
        result = uvindex.UVIndex.from_dict(json.loads(UVINDEX_JSON))
        self.assertIsNotNone(result)
        self.assertIsNotNone(result.reference_time())
        self.assertIsNotNone(result.reception_time())
        loc = result.location
        self.assertIsNotNone(loc)
        self.assertIsNone(loc.name)
        self.assertIsNone(loc.id)
        self.assertIsNotNone(loc.lon)
        self.assertIsNotNone(loc.lat)
        self.assertIsNotNone(result.value)

    def test_from_dict_fails_when_JSON_data_is_None(self):
        self.assertRaises(pyowm.commons.exceptions.ParseAPIResponseError, uvindex.UVIndex.from_dict, None)

    def test_from_dict_fails_with_malformed_JSON_data(self):
        self.assertRaises(pyowm.commons.exceptions.ParseAPIResponseError,uvindex. UVIndex.from_dict,
                          json.loads(UVINDEX_MALFORMED_JSON))

    def test_get_exposure_risk(self):
        with patch.object(uvindex, 'uv_intensity_to_exposure_risk') as mock:
            self.__test_instance.get_exposure_risk()

        mock.assert_called_once_with(self.__test_uv_intensity)

    def test_repr(self):
        print(self.__test_instance)
Ejemplo n.º 10
0
class TestSatelliteImagerySearchResultSet(unittest.TestCase):

    test_data = json.loads('''[{
    "dt":1500940800,
    "type":"Landsat 8",
    "dc":100,
    "cl":1.56,
    "sun":{  
       "azimuth":126.742,
       "elevation":63.572},
    "image":{  
       "truecolor":"http://api.agromonitoring.com/image/1.0/00059768a00/5ac22f004b1ae4000b5b97cf?appid=bb0664ed43c153aa072c760594d775a7",
       "falsecolor":"http://api.agromonitoring.com/image/1.0/01059768a00/5ac22f004b1ae4000b5b97cf?appid=bb0664ed43c153aa072c760594d775a7",
       "ndvi":"http://api.agromonitoring.com/image/1.0/02059768a00/5ac22f004b1ae4000b5b97cf?appid=bb0664ed43c153aa072c760594d775a7",
       "evi":"http://api.agromonitoring.com/image/1.0/03059768a00/5ac22f004b1ae4000b5b97cf?appid=bb0664ed43c153aa072c760594d775a7"},
    "tile":{  
       "truecolor":"http://api.agromonitoring.com/tile/1.0/{z}/{x}/{y}/00059768a00/5ac22f004b1ae4000b5b97cf?appid=bb0664ed43c153aa072c760594d775a7",
       "falsecolor":"http://api.agromonitoring.com/tile/1.0/{z}/{x}/{y}/01059768a00/5ac22f004b1ae4000b5b97cf?appid=bb0664ed43c153aa072c760594d775a7",
       "ndvi":"http://api.agromonitoring.com/tile/1.0/{z}/{x}/{y}/02059768a00/5ac22f004b1ae4000b5b97cf?appid=bb0664ed43c153aa072c760594d775a7",
       "evi":"http://api.agromonitoring.com/tile/1.0/{z}/{x}/{y}/03059768a00/5ac22f004b1ae4000b5b97cf?appid=bb0664ed43c153aa072c760594d775a7"},
    "stats":{  
       "ndvi":"http://api.agromonitoring.com/stats/1.0/02359768a00/5ac22f004b1ae4000b5b97cf?appid=bb0664ed43c153aa072c760594d775a7",
       "evi":"http://api.agromonitoring.com/stats/1.0/03359768a00/5ac22f004b1ae4000b5b97cf?appid=bb0664ed43c153aa072c760594d775a7"},
    "data":{  
       "truecolor":"http://api.agromonitoring.com/data/1.0/00159768a00/5ac22f004b1ae4000b5b97cf?appid=bb0664ed43c153aa072c760594d775a7",
       "falsecolor":"http://api.agromonitoring.com/data/1.0/01159768a00/5ac22f004b1ae4000b5b97cf?appid=bb0664ed43c153aa072c760594d775a7",
       "ndvi":"http://api.agromonitoring.com/data/1.0/02259768a00/5ac22f004b1ae4000b5b97cf?appid=bb0664ed43c153aa072c760594d775a7",
       "evi":"http://api.agromonitoring.com/data/1.0/03259768a00/5ac22f004b1ae4000b5b97cf?appid=bb0664ed43c153aa072c760594d775a7"}}]''')
    test_issuing_time = 1378459200
    test_iso_issuing_time = "2013-09-06 09:20:00+00"
    test_date_issuing_time = datetime.strptime(test_iso_issuing_time, '%Y-%m-%d %H:%M:%S+00').replace(tzinfo=UTC())

    test_instance = SatelliteImagerySearchResultSet('my_polygon', test_data, test_issuing_time)

    def test_instantiation_fails_with_wrong_arguments(self):
        self.assertRaises(AssertionError, SatelliteImagerySearchResultSet, None, [], 1234567)
        self.assertRaises(AssertionError, SatelliteImagerySearchResultSet, 'my_polygon', None, 1234567)
        self.assertRaises(AssertionError, SatelliteImagerySearchResultSet, 'my_polygon', [], None)

    def test_instantiation(self):
        self.assertEqual(12, self.test_instance.__len__())
        self.assertTrue(all([mi.stats_url is not None for mi in self.test_instance.metaimages if mi.preset in
                             [PresetEnum.EVI, PresetEnum.NDVI]]))

    def test_empty_metaimages_init(self):
        test_data = self.test_data[0]
        for dictionary in ['image', 'stats', 'tile', 'data']:
            for key in test_data[dictionary].keys():
                test_data[dictionary][key] = None

        test_data = [test_data]
        test_instance = SatelliteImagerySearchResultSet('my_polygon', test_data, self.test_issuing_time)
        self.assertFalse(len(test_instance.metaimages))

    def test_issued_on_returning_different_formats(self):
        self.assertEqual(self.test_instance.issued_on(timeformat='unix'),
                         self.test_issuing_time)
        self.assertEqual(self.test_instance.issued_on(timeformat='iso'),
                         self.test_iso_issuing_time)
        self.assertEqual(self.test_instance.issued_on(timeformat='date'),
                         self.test_date_issuing_time)

    def test_issued_on_fails_with_unknown_timeformat(self):
        self.assertRaises(ValueError, SatelliteImagerySearchResultSet.issued_on, self.test_instance, 'xyz')

    def test_all(self):
        result = self.test_instance.all()
        self.assertEqual(result, self.test_instance.metaimages)

    def test_with_img_type(self):
        # failure
        with self.assertRaises(AssertionError):
            self.test_instance.with_img_type(1234)

        # success
        result = self.test_instance.with_img_type(ImageTypeEnum.PNG)
        self.assertEqual(8, len(result))
        result = self.test_instance.with_img_type(ImageTypeEnum.GEOTIFF)
        self.assertEqual(4, len(result))

    def test_with_preset(self):
        # failure
        with self.assertRaises(AssertionError):
            self.test_instance.with_preset(1234)

        # success
        result = self.test_instance.with_preset(PresetEnum.TRUE_COLOR)
        self.assertEqual(3, len(result))
        result = self.test_instance.with_preset(PresetEnum.FALSE_COLOR)
        self.assertEqual(3, len(result))
        result = self.test_instance.with_preset(PresetEnum.NDVI)
        self.assertEqual(3, len(result))
        result = self.test_instance.with_preset(PresetEnum.EVI)
        self.assertEqual(3, len(result))

    def test_with_img_type_and_preset(self):
        # failure
        with self.assertRaises(AssertionError):
            self.test_instance.with_img_type_and_preset(1234, 1234)
        with self.assertRaises(AssertionError):
            self.test_instance.with_img_type_and_preset(1234, PresetEnum.TRUE_COLOR)
        with self.assertRaises(AssertionError):
            self.test_instance.with_img_type_and_preset(ImageTypeEnum.PNG, 1234)

        # success
        result = self.test_instance.with_img_type_and_preset(ImageTypeEnum.PNG, PresetEnum.TRUE_COLOR)
        self.assertEqual(2, len(result))
        result = self.test_instance.with_img_type_and_preset(ImageTypeEnum.GEOTIFF, PresetEnum.EVI)
        self.assertEqual(1, len(result))
        result = self.test_instance.with_img_type_and_preset(ImageTypeEnum.GEOTIFF, PresetEnum.FALSE_COLOR)
        self.assertEqual(1, len(result))

    def test_repr(self):
        self.assertEqual('<pyowm.agroapi10.search.SatelliteImagerySearchResultSet'
                         ' - 12 results for query issued on polygon_id=my_polygon at 2013-09-06 09:20:00+00>',
                         self.test_instance.__repr__())
class TestOzone(unittest.TestCase):

    __test_reception_time = 1475283600
    __test_iso_reception_time = "2016-10-01 01:00:00+00"
    __test_date_reception_time = datetime.strptime(
        __test_iso_reception_time,
        '%Y-%m-%d %H:%M:%S+00').replace(tzinfo=UTC())

    __test_reference_time = 1234567
    __test_iso_reference_time = "1970-01-15 06:56:07+00"
    __test_date_reference_time = datetime.strptime(
        __test_iso_reference_time,
        '%Y-%m-%d %H:%M:%S+00').replace(tzinfo=UTC())

    __test_location = Location('test', 12.3, 43.7, 987, 'UK')
    __test_du_value = 6.8
    __test_interval = 'day'
    __test_exposure_risk = 'high'
    __test_instance = Ozone(__test_reference_time, __test_location,
                            __test_interval, __test_du_value,
                            __test_reception_time)

    def test_init_fails_when_reference_time_is_negative(self):
        self.assertRaises(ValueError, Ozone, -1234567, self.__test_location,
                          self.__test_interval, self.__test_du_value,
                          self.__test_reception_time)

    def test_init_fails_when_reception_time_is_negative(self):
        self.assertRaises(ValueError, Ozone, self.__test_reference_time,
                          self.__test_location, self.__test_interval,
                          self.__test_du_value, -1234567)

    def test_init_fails_when_uv_intensity_is_negative(self):
        self.assertRaises(ValueError, Ozone, self.__test_reference_time,
                          self.__test_location, self.__test_interval, -8.9,
                          self.__test_reception_time)

    def test_returning_different_formats_for_reception_time(self):
        self.assertEqual(self.__test_instance.reception_time(timeformat='iso'), \
                         self.__test_iso_reception_time)
        self.assertEqual(self.__test_instance.reception_time(timeformat='unix'), \
                         self.__test_reception_time)
        self.assertEqual(self.__test_instance.reception_time(timeformat='date'), \
                         self.__test_date_reception_time)

    def test_returning_different_formats_for_reference_time(self):
        self.assertEqual(self.__test_instance.reference_time(timeformat='iso'), \
                         self.__test_iso_reference_time)
        self.assertEqual(self.__test_instance.reference_time(timeformat='unix'), \
                         self.__test_reference_time)
        self.assertEqual(self.__test_instance.reference_time(timeformat='date'), \
                         self.__test_date_reference_time)

    def test_is_forecast(self):
        self.assertFalse(self.__test_instance.is_forecast())
        in_a_year = datetime_to_UNIXtime(datetime.utcnow()) + 31536000
        uvindex = Ozone(in_a_year, self.__test_location, self.__test_interval,
                        self.__test_du_value, self.__test_reception_time)
        self.assertTrue(uvindex.is_forecast())

    def test_from_dict(self):
        d = json.loads(OZONE_JSON)
        result = Ozone.from_dict(d)
        self.assertIsNotNone(result)
        self.assertIsNotNone(result.reference_time())
        self.assertIsNotNone(result.reception_time())
        loc = result.location
        self.assertIsNotNone(loc)
        self.assertIsNone(loc.name)
        self.assertIsNone(loc.id)
        self.assertIsNotNone(loc.lon)
        self.assertIsNotNone(loc.lat)
        self.assertIsNone(result.interval)
        self.assertIsNotNone(result.du_value)

    def test_from_dict_fails_when_no_du_specified(self):
        self.assertRaises(ValueError, Ozone.from_dict,
                          json.loads(OZONE_WITHOUT_DU_JSON))

    def test_from_dict_fails_when_JSON_data_is_None(self):
        self.assertRaises(pyowm.commons.exceptions.ParseAPIResponseError,
                          Ozone.from_dict, None)

    def test_from_dict_fails_with_malformed_JSON_data(self):
        self.assertRaises(pyowm.commons.exceptions.ParseAPIResponseError,
                          Ozone.from_dict, json.loads(OZONE_MALFORMED_JSON))

    def test_to_dict(self):
        expected = json.loads(OZONE_JSON_DUMP)
        result = self.__test_instance.to_dict()
        self.assertEqual(expected, result)

    def test_repr(self):
        print(self.__test_instance)
Ejemplo n.º 12
0
class TestForecast(unittest.TestCase):
    __test_reception_time = 1234567
    __test_iso_reception_time = "1970-01-15 06:56:07+00"
    __test_date_reception_time = datetime.strptime(
        __test_iso_reception_time,
        '%Y-%m-%d %H:%M:%S+00').replace(tzinfo=UTC())
    __test_location = Location('test', 12.3, 43.7, 987, 'IT')
    __test_weathers = [
        Weather(1378459200, 1378496400, 1378449600, 67, {"all": 20},
                {"all": 0}, {
                    "deg": 252.002,
                    "speed": 1.100
                }, 57, {
                    "press": 1030.119,
                    "sea_level": 1038.589
                }, {
                    "temp": 294.199,
                    "temp_kf": -1.899,
                    "temp_max": 296.098,
                    "temp_min": 294.199
                }, "Clouds", "Overcast clouds", 804, "04d", 1000, 300.0, 298.0,
                296.0),
        Weather(1378459690, 1378496480, 1378449510, 23, {"all": 10},
                {"all": 0}, {
                    "deg": 103.4,
                    "speed": 4.2
                }, 12, {
                    "press": 1070.119,
                    "sea_level": 1078.589
                }, {
                    "temp": 297.199,
                    "temp_kf": -1.899,
                    "temp_max": 299.0,
                    "temp_min": 295.6
                }, "Clear", "Sky is clear", 804, "02d", 1000, 300.0, 298.0,
                296.0)
    ]
    __test_n_weathers = len(__test_weathers)
    __test_instance = Forecast("daily", __test_reception_time, __test_location,
                               __test_weathers)
    __bad_json = '{"a": "test", "b": 1.234, "c": [ "hello", "world"] }'
    __bad_json_2 = '{ "city": {"id": 2643743,' \
                   '"name": "London","coord": {"lon": -0.12574,"lat": 51.50853},"country": ' \
                   '"GB","population": 1000000} }'
    __no_items_found_json = '{"count": "0", "city": {"id": 2643743,' \
                            '"name": "London","coord": {"lon": -0.12574,"lat": 51.50853},"country": ' \
                            '"GB","population": 1000000} }'

    FORECAST_JSON_DUMP = '{"reception_time": 1234567, "interval": "daily", ' \
                         '"location": {"country": "IT", "name": "test", ' \
                         '"coordinates": {"lat": 43.7, "lon": 12.3}, "ID": 987}, ' \
                         '"weathers": [{"status": "Clouds", ' \
                         '"visibility_distance": 1000, "humidity": 57, "clouds": 67,' \
                         ' "temperature": {"temp_kf": -1.899, "temp_max": 296.098, ' \
                         '"temp": 294.199, "temp_min": 294.199}, "dewpoint": 300.0,' \
                         ' "snow": {"all": 0}, "detailed_status": "Overcast clouds",' \
                         ' "reference_time": 1378459200, "weather_code": 804, ' \
                         '"humidex": 298.0, "rain": {"all": 20}, ' \
                         '"sunset_time": 1378496400, "pressure": {"press": 1030.119,' \
                         ' "sea_level": 1038.589}, "sunrise_time": 1378449600, ' \
                         '"heat_index": 296.0, "weather_icon_name": "04d", "wind": ' \
                         '{"speed": 1.1, "deg": 252.002}, "utc_offset": null, "uvi": null}, {"status": "Clear", ' \
                         '"visibility_distance": 1000, "humidity": 12, ' \
                         '"clouds": 23, "temperature": {"temp_kf": -1.899, ' \
                         '"temp_max": 299.0, "temp": 297.199, "temp_min": 295.6}, ' \
                         '"dewpoint": 300.0, "snow": {"all": 0}, "detailed_status": ' \
                         '"Sky is clear", "reference_time": 1378459690, ' \
                         '"weather_code": 804, "humidex": 298.0, "rain": {"all": 10},' \
                         ' "sunset_time": 1378496480, "pressure": ' \
                         '{"press": 1070.119, "sea_level": 1078.589}, ' \
                         '"sunrise_time": 1378449510, "heat_index": 296.0, ' \
                         '"weather_icon_name": "02d", "wind": {"speed": 4.2, ' \
                         '"deg": 103.4}, "utc_offset": null, "uvi": null}]}'

    def test_actualize(self):
        weathers = [
            Weather(1378459200, 1378496400, 1378449600, 67, {"all": 20},
                    {"all": 0}, {
                        "deg": 252.002,
                        "speed": 1.100
                    }, 57, {
                        "press": 1030.119,
                        "sea_level": 1038.589
                    }, {
                        "temp": 294.199,
                        "temp_kf": -1.899,
                        "temp_max": 296.098,
                        "temp_min": 294.199
                    }, "Clouds", "Overcast clouds", 804, "04d", 1000, 300.0,
                    298.0, 296.0),
            # will this time ever be reached?
            Weather(9999999999, 1378496480, 1378449510, 23, {"all": 10},
                    {"all": 0}, {
                        "deg": 103.4,
                        "speed": 4.2
                    }, 12, {
                        "press": 1070.119,
                        "sea_level": 1078.589
                    }, {
                        "temp": 297.199,
                        "temp_kf": -1.899,
                        "temp_max": 299.0,
                        "temp_min": 295.6
                    }, "Clear", "Sky is clear", 804, "02d", 1000, 300.0, 298.0,
                    296.0)
        ]
        f = Forecast("daily", self.__test_reception_time, self.__test_location,
                     weathers)
        self.assertEqual(2, len(f))
        f.actualize()
        self.assertEqual(1, len(f))

    def test_init_fails_when_reception_time_is_negative(self):
        self.assertRaises(ValueError, Forecast, "3h", -1234567,
                          self.__test_location, self.__test_weathers)

    def test_get(self):
        index = 1
        self.assertEqual(self.__test_weathers[index],
                         self.__test_instance.get(index))

    def test_getters_return_expected_3h_data(self):
        """
        Test either for "3h" forecast and "daily" ones
        """
        instance = Forecast("3h", self.__test_reception_time,
                            self.__test_location, self.__test_weathers)
        self.assertEqual(instance.interval, "3h")
        self.assertEqual(instance.reception_time(), self.__test_reception_time)
        self.assertEqual(instance.location, self.__test_location)
        self.assertEqual(instance.weathers, self.__test_weathers)

    def test_getters_return_expected_daily_data(self):
        instance = Forecast("daily", self.__test_reception_time,
                            self.__test_location, self.__test_weathers)
        self.assertEqual(instance.interval, "daily")
        self.assertEqual(instance.reception_time(), self.__test_reception_time)
        self.assertEqual(instance.location, self.__test_location)
        self.assertEqual(instance.weathers, self.__test_weathers)

    def test_returning_different_formats_for_reception_time(self):
        instance = self.__test_instance
        self.assertEqual(instance.reception_time(timeformat='iso'),
                         self.__test_iso_reception_time)
        self.assertEqual(instance.reception_time(timeformat='unix'),
                         self.__test_reception_time)
        self.assertEqual(instance.reception_time(timeformat='date'),
                         self.__test_date_reception_time)

    def test__iter__(self):
        instance = self.__test_instance
        counter = 0
        for weather in instance:
            self.assertTrue(isinstance(weather, Weather))
            counter += 1
        self.assertEqual(len(instance.weathers), counter)

    def test__len__(self):
        self.assertEqual(len(self.__test_instance), len(self.__test_weathers))

    def test_from_dict(self):
        result = self.__test_instance.from_dict(
            json.loads(THREE_HOURS_FORECAST_JSON))
        self.assertTrue(result is not None)
        self.assertTrue(result.reception_time() is not None)
        self.assertFalse(result.interval is not None)
        loc = result.location
        self.assertTrue(loc is not None)
        self.assertTrue(all(v is not None for v in loc.__dict__.values()))
        self.assertTrue(isinstance(result.weathers, list))
        for weather in result:
            self.assertTrue(weather is not None)

    def test_from_dict_fails_when_JSON_data_is_None(self):
        with self.assertRaises(ParseAPIResponseError):
            Forecast.from_dict(None)

    def test_from_dict_with_malformed_JSON_data(self):
        with self.assertRaises(ParseAPIResponseError):
            Forecast.from_dict(json.loads(self.__bad_json))
        with self.assertRaises(ParseAPIResponseError):
            Forecast.from_dict(json.loads(self.__bad_json_2))
        with self.assertRaises(ParseAPIResponseError):
            Forecast.from_dict(json.loads(FORECAST_MALFORMED_JSON))

    def test_from_dict_when_no_results(self):
        result = Forecast.from_dict(json.loads(FORECAST_NOT_FOUND_JSON))
        self.assertFalse(result is None)
        self.assertEqual(0, len(result))
        result = Forecast.from_dict(json.loads(self.__no_items_found_json))
        self.assertEqual(0, len(result))

    def test_from_dict_when_server_error(self):
        with self.assertRaises(APIResponseError):
            Forecast.from_dict(json.loads(INTERNAL_SERVER_ERROR_JSON))

    def test_to_dict(self):
        expected = json.loads(self.FORECAST_JSON_DUMP)
        result = self.__test_instance.to_dict()
        self.assertEqual(expected, result)

    def test__repr(self):
        print(self.__test_instance)
Ejemplo n.º 13
0
class TestStationHistory(unittest.TestCase):

    __test_station_ID = 2865
    __test_interval = "tick"
    __test_reception_time = 1378684800
    __test_reception_time_iso = '2013-09-09 00:00:00+00'
    __test_date_reception_time = datetime.strptime(
        __test_reception_time_iso,
        '%Y-%m-%d %H:%M:%S+00').replace(tzinfo=UTC())
    __test_measurements = {
        '1362933983': {
            "temperature": 266.25,
            "humidity": 27.3,
            "pressure": 1010.02,
            "rain": None,
            "wind": 4.7
        },
        '1362934043': {
            "temperature": 266.85,
            "humidity": 27.7,
            "pressure": 1010.09,
            "rain": None,
            "wind": 4.7
        }
    }

    __test_instance = StationHistory(__test_station_ID, 'tick',
                                     __test_reception_time,
                                     __test_measurements)

    __bad_json = '{"a": "test", "b": 1.234, "c": [ "hello", "world"] }'

    STATIONHISTORY_JSON_DUMP = '{"reception_time": 1378684800, "interval": ' \
                               + '"tick", "measurements": {"1362934043": {"wind": 4.7, "pressure": ' \
                               + '1010.09, "temperature": 266.85, "rain": null, "humidity": 27.7}, ' \
                               + '"1362933983": {"wind": 4.7, "pressure": 1010.02, "temperature": ' \
                               + '266.25, "rain": null, "humidity": 27.3}}, "station_ID": 2865}'

    def test_init_fails_when_negative_reception_time(self):
        self.assertRaises(ValueError, StationHistory, 1234, 'tick', -1234567,
                          self.__test_measurements)

    def test_returning_different_formats_for_reception_time(self):
        """
        Test get_reception_time returns timestamps in the expected formats
        """
        self.assertEqual(self.__test_instance.reception_time(timeformat='iso'),
                         self.__test_reception_time_iso)
        self.assertEqual(
            self.__test_instance.reception_time(timeformat='unix'),
            self.__test_reception_time)
        self.assertEqual(self.__test_instance.reception_time(timeformat='date'), \
                         self.__test_date_reception_time)

    def test_from_dict(self):
        result = StationHistory.from_dict(
            json.loads(STATION_TICK_WEATHER_HISTORY_JSON))
        self.assertTrue(result)
        self.assertTrue(isinstance(result, StationHistory))
        self.assertTrue(result.measurements)

    def test_from_dict_fails_when_JSON_data_is_None(self):
        self.assertRaises(ParseAPIResponseError, StationHistory.from_dict,
                          None)

    def test_from_dict_with_malformed_JSON_data(self):
        self.assertRaises(ParseAPIResponseError, StationHistory.from_dict,
                          json.loads(self.__bad_json))

    def test_from_dict_with_empty_data(self):
        json_data = '{"message": "","cod": "200","type": "hour","station_id": ' \
            '35579,"calctime": 0.1122,"cnt": 1,"list": [{"main": "test","dt": ' \
            '1381140000}]}'
        result = StationHistory.from_dict(json.loads(json_data))
        datapoints = result.measurements
        for datapoint in datapoints:
            self.assertTrue(all(value is None for value \
                                in datapoints[datapoint].values()))

    def test_from_dict_when_station_not_found(self):
        self.assertFalse(
            StationHistory.from_dict(
                json.loads(STATION_WEATHER_HISTORY_NOT_FOUND_JSON)))

    def test_from_dict_when_server_error(self):
        self.assertRaises(APIResponseError, StationHistory.from_dict,
                          json.loads(INTERNAL_SERVER_ERROR_JSON))

    def test_to_dict(self):
        expected = json.loads(self.STATIONHISTORY_JSON_DUMP)
        result = self.__test_instance.to_dict()
        self.assertEqual(expected, result)

    def test__repr(self):
        print(self.__test_instance)