def test_locations_for_restricted_to_country(self): ref_to_original = CityIDRegistry._get_lines CityIDRegistry._get_lines = self._mock_get_lines_with_homonymies result = self._instance.locations_for("Abbeville", country='JP') self.assertEqual(0, len(result)) result = self._instance.locations_for("Abbeville", country='US') self.assertEqual(4, len(result)) self._assertLocationsEqual( Location('Abbeville', -83.306824, 31.992121, 4178992, 'US'), result[0]) self._assertLocationsEqual( Location('Abbeville', -92.134293, 29.974649, 4314295, 'US'), result[1]) self._assertLocationsEqual( Location('Abbeville', -82.379013, 34.178169, 4568985, 'US'), result[2]) self._assertLocationsEqual( Location('Abbeville', -85.250488, 31.57184, 4829449, 'US'), result[3]) result = self._instance.locations_for("Abbeville", country='FR') self.assertEqual(1, len(result)) self._assertLocationsEqual( Location("Abbeville", 1.83333, 50.099998, 3038789, 'FR'), result[0]) CityIDRegistry._get_lines = ref_to_original
def test_geopoints_for(self): ref_to_original = CityIDRegistry._get_lines CityIDRegistry._get_lines = self._mock_get_lines_with_homonymies # No matches result = self._instance.geopoints_for('aaaaaaaaaa') self.assertEqual(0, len(result)) # One match expected = Location('Bologna', -83.250488, 30.57184, 2829449, 'IT').to_geopoint() result = self._instance.geopoints_for("Bologna") self.assertEqual(1, len(result)) self._assertGeopointsEqual(expected, result[0]) # Multiple matches expected1 = Location('Abbans-Dessus', 5.88188, 47.120548, 3038800, 'FR').to_geopoint() expected2 = Location('Abbans-Dessus', 5.88333, 47.116669, 6452202, 'FR').to_geopoint() result = self._instance.geopoints_for("Abbans-Dessus") self.assertEqual(2, len(result)) self._assertGeopointsEqual(expected1, result[0]) self._assertGeopointsEqual(expected2, result[1]) CityIDRegistry._get_lines = ref_to_original
def test_locations_for_matching_criteria(self): original_get_lines = CityIDRegistry._get_lines original_get_all_lines = CityIDRegistry._get_all_lines CityIDRegistry._get_lines = self._mock_get_lines_with_homonymies CityIDRegistry._get_all_lines = self._mock_get_all_lines # look for an empty name result = self._instance.locations_for("") self.assertEqual(0, len(result)) # country string is too long with self.assertRaises(ValueError): self._instance.locations_for("place", country="a_country", matching="nocase") # unknown matching type with self.assertRaises(ValueError): self._instance.locations_for("place", country="IT", matching="impossible") expected = Location('Bologna', -83.250488, 30.57184, 2829449, 'IT') # case sensitive result = self._instance.locations_for("bologna", matching='exact') self.assertEqual(0, len(result)) result = self._instance.locations_for("Bologna", matching='exact') self.assertEqual(1, len(result)) self._assertLocationsEqual(expected, result[0]) # case insensitive result = self._instance.locations_for("bologna", matching='nocase') self.assertEqual(1, len(result)) self._assertLocationsEqual(expected, result[0]) result = self._instance.locations_for("Bologna", matching='nocase') self.assertEqual(1, len(result)) self._assertLocationsEqual(expected, result[0]) # like expected1 = Location('Abbans-Dessus', 5.88188, 47.120548, 3038800, 'FR') expected2 = Location('Abbans-Dessus', 5.88333, 47.116669, 6452202, 'FR') result = self._instance.locations_for("abbans", matching='like') self.assertEqual(2, len(result)) self._assertLocationsEqual(expected1, result[0]) self._assertLocationsEqual(expected2, result[1]) result = self._instance.locations_for("Dessus", matching='like') self.assertEqual(2, len(result)) self._assertLocationsEqual(expected1, result[0]) self._assertLocationsEqual(expected2, result[1]) CityIDRegistry._get_lines = original_get_lines CityIDRegistry._get_all_lines = original_get_all_lines
def test_locations_for_more_cases(self): expected1 = Location('Abbans-Dessus', 5.88188, 47.120548, 3038800, 'FR') expected2 = Location('Abbans-Dessus', 5.88333, 47.116669, 6452202, 'FR') result = self._instance.locations_for("Abbans-Dessus") self.assertEqual(2, len(result)) for l in result: self.assertTrue(isinstance(l, Location)) self.assertTrue(l.id in [expected1.id, expected2.id])
def test_locations_for(self): expected1 = Location('Abbans-Dessus', 5.88188, 47.120548, 3038800, 'FR') expected2 = Location('Abbans-Dessus', 5.88333, 47.116669, 6452202, 'FR') result = self._instance.locations_for("Abbans-Dessus") self.assertEqual(2, len(result)) for l in result: self.assertTrue(isinstance(l, Location)) self.assertTrue(l.get_ID() in [expected1.get_ID(), expected2.get_ID()])
def test_locations_for_with_commas_in_city_names_like(self): ref_to_original = CityIDRegistry._get_lines CityIDRegistry._get_lines = self._mock_test_file_contents_with_commas_in_names result = self._instance.locations_for("Pitcai", matching="like") self._assertLocationsEqual( result[0], Location('Pitcairn', -79.778099, 40.403118, 5206361, 'PA')) self._assertLocationsEqual( result[1], Location('Pitcairn, Henderson, Ducie and Oeno Islands', -130.100006, -25.066669, 4030699, 'PN')) CityIDRegistry._get_lines = ref_to_original
def locations_for(self, city_name, country=None, matching='nocase'): """ Returns a list of Location objects corresponding to the int IDs and relative toponyms and 2-chars country of the cities matching the provided city name. The rule for identifying matchings is according to the provided `matching` parameter value. If `country` is provided, the search is restricted to the cities of the specified country. :param country: two character str representing the country where to search for the city. Defaults to `None`, which means: search in all countries. :param matching: str. Default is `nocase`. Possible values: `exact` - literal, case-sensitive matching, `nocase` - literal, case-insensitive matching, `like` - matches cities whose name contains, as a substring, the string fed to the function, case-insensitive, `startswith` - matches cities whose names start with the string fed to the function, case-insensitive. :raises ValueError if the value for `matching` is unknown :return: list of `weatherapi25.location.Location` objects """ if not city_name: return [] if matching not in self.MATCHINGS: raise ValueError("Unknown type of matching: " "allowed values are %s" % ", ".join(self.MATCHINGS)) if country is not None and len(country) != 2: raise ValueError("Country must be a 2-char string") splits = self._filter_matching_lines(city_name, country, matching) return [ Location(item[0], float(item[3]), float(item[2]), int(item[1]), item[4]) for item in splits ]
def locations_for(self, city_name, country=None, state=None, matching='like'): """ Returns a list of `Location` objects The rule for querying follows the provided `matching` parameter value. If `country` is provided, the search is restricted to the cities of the specified country, and an even stricter search when `state` is provided as well :param city_name: the string toponym of the city to search :param country: two character str representing the country where to search for the city. Defaults to `None`, which means: search in all countries. :param state: two character str representing the state where to search for the city. Defaults to `None`. When not `None` also `state` must be specified :param matching: str. Default is `like`. Possible values: `exact` - literal, case-sensitive matching `like` - matches cities whose name contains, as a substring, the string fed to the function, case-insensitive, :raises ValueError if the value for `matching` is unknown :return: list of `Location` objects """ items = self.ids_for(city_name, country=country, state=state, matching=matching) return [ Location(item[1], item[5], item[4], item[0], country=item[2]) for item in items ]
def test_locations_for_matching_criteria(self): original_get_lines = CityIDRegistry._get_lines original_get_all_lines = CityIDRegistry._get_all_lines CityIDRegistry._get_lines = self._mock_get_lines_with_homonymies CityIDRegistry._get_all_lines = self._mock_get_all_lines # look for an empty name result = self._instance.locations_for("") self.assertEquals(0, len(result)) expected = Location('Bologna', -83.250488, 30.57184, 2829449, 'IT') # case sensitive result = self._instance.locations_for("bologna", matching='exact') self.assertEquals(0, len(result)) result = self._instance.locations_for("Bologna", matching='exact') self.assertEquals(1, len(result)) self._assertLocationsEqual(expected, result[0]) # case insensitive result = self._instance.locations_for("bologna", matching='nocase') self.assertEquals(1, len(result)) self._assertLocationsEqual(expected, result[0]) result = self._instance.locations_for("Bologna", matching='nocase') self.assertEquals(1, len(result)) self._assertLocationsEqual(expected, result[0]) # like expected1 = Location('Abbans-Dessus', 5.88188, 47.120548, 3038800, 'FR') expected2 = Location('Abbans-Dessus', 5.88333, 47.116669, 6452202, 'FR') result = self._instance.locations_for("abbans", matching='like') self.assertEquals(2, len(result)) self._assertLocationsEqual(expected1, result[0]) self._assertLocationsEqual(expected2, result[1]) result = self._instance.locations_for("Dessus", matching='like') self.assertEquals(2, len(result)) self._assertLocationsEqual(expected1, result[0]) self._assertLocationsEqual(expected2, result[1]) CityIDRegistry._get_lines = original_get_lines CityIDRegistry._get_all_lines = original_get_all_lines
def test_from_dict_holds_the_lack_of_geocoords(self): dict1 = {"station": {"coord": {}}} dict2 = {"coord": {}} result1 = Location.from_dict(dict1) self.assertTrue(isinstance(result1, Location)) self.assertEqual(result1.lat, 0.0) self.assertEqual(result1.lon, 0.0) self.assertTrue(result1.country is None) self.assertTrue(result1.name is None) self.assertTrue(result1.id is None) result2 = Location.from_dict(dict2) self.assertTrue(isinstance(result2, Location)) self.assertEqual(result2.lat, 0.0) self.assertEqual(result2.lon, 0.0) self.assertTrue(result2.country is None) self.assertTrue(result2.name is None) self.assertTrue(result2.id is None)
def test_locations_for_with_commas_in_city_names(self): ref_to_original = CityIDRegistry._get_lines CityIDRegistry._get_lines = self._mock_test_file_contents_with_commas_in_names result = self._instance.locations_for("Thale, Stadt") self.assertEqual(1, len(result)) self._assertLocationsEqual( Location('Thale, Stadt', 11.058, 51.7528, 6550950, 'DE'), result[0]) result = self._instance.locations_for( "Pitcairn, Henderson, Ducie and Oeno Islands") self.assertEqual(1, len(result)) self._assertLocationsEqual( Location('Pitcairn, Henderson, Ducie and Oeno Islands', -130.100006, -25.066669, 4030699, 'PN'), result[0]) CityIDRegistry._get_lines = ref_to_original
def test_getters_return_expected_data(self): instance = Location(self.__test_name, self.__test_lon, self.__test_lat, self.__test_ID, self.__test_country) self.assertEqual(instance.get_name(), self.__test_name) self.assertEqual(instance.get_lon(), self.__test_lon) self.assertEqual(instance.get_lat(), self.__test_lat) self.assertEqual(instance.get_ID(), self.__test_ID) self.assertEqual(instance.get_country(), self.__test_country)
def test_to_geopoint(self): loc_1 = Location(self.__test_name, self.__test_lon, self.__test_lat, self.__test_ID, self.__test_country) loc_1.lat = None self.assertIsNone(loc_1.to_geopoint()) loc_1.lon = None self.assertIsNone(loc_1.to_geopoint()) loc_2 = Location(self.__test_name, self.__test_lon, self.__test_lat, self.__test_ID, self.__test_country) result = loc_2.to_geopoint() self.assertTrue(isinstance(result, Point)) expected_geojson = json.dumps({ "coordinates": [12.3, 43.7], "type": "Point" }) self.assertEqual(sorted(expected_geojson), sorted(result.geojson()))
def test_location_for(self): expected = Location('Dongen', 4.938890, 51.626671, 2756723, 'NL') result = self._instance.location_for('dongen') self.assertEqual(result.get_name(), expected.get_name()) self.assertEqual(result.get_country(), expected.get_country()) self.assertEqual(result.get_ID(), expected.get_ID()) self.assertEqual(result.get_lat(), expected.get_lat()) self.assertEqual(result.get_lon(), expected.get_lon()) self.assertTrue(self._instance.location_for('aaaaaaaaaa') is None)
def test_locations_for(self): expected = Location('Dongen', 4.938890, 51.626671, 2756723, 'NL') result_list = self._instance.locations_for('dongen') self.assertEqual(1, len(result_list)) result = result_list[0] self.assertEqual(result.name, expected.name) self.assertEqual(result.country, expected.country) self.assertEqual(result.id, expected.id) self.assertEqual(result.lat, expected.lat) self.assertEqual(result.lon, expected.lon) self.assertEqual([], self._instance.locations_for('aaaaaaaaaa'))
def test_locations_for_with_commas_in_city_names(self): ref_to_original = CityIDRegistry._get_lines CityIDRegistry._get_lines = self._mock_test_file_contents_with_commas_in_names result = self._instance.locations_for("Thale, Stadt") self.assertEquals(1, len(result)) self._assertLocationsEqual( Location('Thale, Stadt', 11.058, 51.7528, 6550950, 'DE'), result[0]) CityIDRegistry._get_lines = ref_to_original
def test_geopoints_for(self): # No matches self.assertEqual([], self._instance.geopoints_for('aaaaaaaaaa')) # One match expected = Location('Milano', 9.19199, 45.464161, 6542283, country='IT').to_geopoint() result = self._instance.geopoints_for("Milano", country="IT", matching="exact") self.assertEqual(1, len(result)) self._assertGeopointsEqual(expected, result[0]) # Multiple matches expected1 = Location('Bologna', 11.43333, 44.466671, 3181927, country='IT').to_geopoint() expected2 = Location('Bologna', 11.33875, 44.493809, 3181928, country='IT').to_geopoint() expected3 = Location('Bologna', 11.35041, 44.506569, 6541998, country='IT').to_geopoint() result = self._instance.geopoints_for("Bologna", country="IT", matching="exact") self.assertEqual(3, len(result)) self._assertGeopointsEqual(expected1, result[0]) self._assertGeopointsEqual(expected2, result[1]) self._assertGeopointsEqual(expected3, result[2])
def test_getters_return_expected_data(self): instance = Location(self.__test_name, self.__test_lon, self.__test_lat, self.__test_ID, self.__test_country) self.assertEqual(instance.get_name(), self.__test_name) self.assertEqual(instance.get_lon(), self.__test_lon) self.assertEqual(instance.get_lat(), self.__test_lat) self.assertEqual(instance.get_ID(), self.__test_ID) self.assertEqual(instance.get_country(), self.__test_country)
def reverse_geocode(self, lat, lon, limit=None): geo.assert_is_lon(lon) geo.assert_is_lat(lat) if limit is not None: assert isinstance(limit, int) assert limit > 0 params = {'lat': lat, 'lon': lon} if limit is not None: params['limit'] = limit _, json_data = self.http_client.get_json(REVERSE_GEOCODING_URI, params=params) return [Location.from_dict(item) for item in json_data]
def test_location_for(self): ref_to_original = CityIDRegistry._get_lines CityIDRegistry._get_lines = self._mock_get_lines expected = Location('dongdu', 117.699997, 35.849998, 1812597, 'CN') result_1 = self._instance.location_for('dongdu') result_2 = self._instance.location_for('aaaaaaaaaa') CityIDRegistry._get_lines = ref_to_original self.assertEqual(result_1.get_name(), expected.get_name()) self.assertEqual(result_1.get_country(), expected.get_country()) self.assertEqual(result_1.get_ID(), expected.get_ID()) self.assertEqual(result_1.get_lat(), expected.get_lat()) self.assertEqual(result_1.get_lon(), expected.get_lon()) self.assertTrue(result_2 is None)
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) 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.get_reception_time(), self.__test_reception_time) self.assertEqual(self.__test_instance.get_location(), self.__test_location) self.assertEqual(self.__test_instance.get_weather(), self.__test_weather) def test_returning_different_formats_for_reception_time(self): self.assertEqual(self.__test_instance.get_reception_time(timeformat='iso'), \ self.__test_iso_reception_time) self.assertEqual(self.__test_instance.get_reception_time(timeformat='unix'), \ self.__test_reception_time) self.assertEqual(self.__test_instance.get_reception_time(timeformat='date'), \ self.__test_date_reception_time) # Test JSON and XML comparisons by ordering strings (this overcomes # interpeter-dependant serialization of XML/JSON objects) def test_to_JSON(self): ordered_base_json = ''.join(sorted(OBSERVATION_JSON_DUMP)) ordered_actual_json = ''.join(sorted(self.__test_instance.to_JSON())) self.assertEqual(ordered_base_json, ordered_actual_json) def test_to_XML(self): ordered_base_xml = ''.join(sorted(OBSERVATION_XML_DUMP)) ordered_actual_xml = ''.join(sorted(self.__test_instance.to_XML())) self.assertEqual(ordered_base_xml, ordered_actual_xml)
def test_from_dict(self): try: Location.from_dict(None) self.fail() except exceptions.ParseAPIResponseError: pass dict1 = { "coord": { "lon": -0.12574, "lat": 51.50853 }, "id": 2643743, "name": "London", "cnt": 9 } dict2 = { "city": { "coord": { "lat": 51.50853, "lon": -0.125739 }, "country": "GB", "id": 2643743, "name": "London", "population": 1000000 } } dict3 = {"station": {"coord": {"lon": -90.47, "lat": 39.38}}} dict4 = {"station": {"coord": {"lng": -90.47, "lat": 39.38}}} dict5 = {"station": {}} result1 = Location.from_dict(dict1) result2 = Location.from_dict(dict2) result3 = Location.from_dict(dict3) result4 = Location.from_dict(dict4) self.assertTrue(isinstance(result1, Location)) self.assertTrue(isinstance(result2, Location)) self.assertFalse(result1.country is not None) self.assertTrue(result1.id is not None) self.assertTrue(result1.lat is not None) self.assertTrue(result1.lon is not None) self.assertTrue(result1.name is not None) self.assertTrue(result2.country is not None) self.assertTrue(result2.id is not None) self.assertTrue(result2.lat is not None) self.assertTrue(result2.lon is not None) self.assertTrue(result2.name is not None) self.assertTrue(result3.lat is not None) self.assertTrue(result3.lon is not None) self.assertTrue(result3.country is None) self.assertTrue(result3.name is None) self.assertTrue(result3.id is None) self.assertIsInstance(result4, Location) self.assertRaises(KeyError, Location.from_dict, dict5)
def test_locations_for_with_commas_in_city_names_startswith_country(self): ref_to_original = CityIDRegistry._get_lines CityIDRegistry._get_lines = self._mock_test_file_contents_with_commas_in_names result = self._instance.locations_for("Pit", country='PA', matching="startswith") self._assertLocationsEqual( result[0], Location('Pitcairn', -79.778099, 40.403118, 5206361, 'PA')) result = self._instance.locations_for("Ducie", country='PN', matching="startswith") self.assertEqual(0, len(result)) CityIDRegistry._get_lines = ref_to_original
def test_location_for(self): ref_to_original = CityIDRegistry._get_lines CityIDRegistry._get_lines = self._mock_get_lines expected = Location('dongdu', 117.699997, 35.849998, 1812597, 'CN') result_1 = self._instance.location_for('dongdu') result_2 = self._instance.location_for('aaaaaaaaaa') CityIDRegistry._get_lines = ref_to_original self.assertEqual(result_1.get_name(), expected.get_name()) self.assertEqual(result_1.get_country(), expected.get_country()) self.assertEqual(result_1.get_ID(), expected.get_ID()) self.assertEqual(result_1.get_lat(), expected.get_lat()) self.assertEqual(result_1.get_lon(), expected.get_lon()) self.assertTrue(result_2 is None)
def location_for(self, city_name): """ Returns the *Location* object corresponding to the first city found that matches the provided city name. The lookup is case insensitive. :param city_name: the city name you want a *Location* for :type city_name: str :returns: a *Location* instance or ``None`` if the lookup fails .. deprecated:: 3.0.0 Use :func:`locations_for` instead. """ line = self._lookup_line_by_city_name(city_name) if line is None: return None tokens = line.split(",") return Location(tokens[0], float(tokens[3]), float(tokens[2]), int(tokens[1]), tokens[4])
def geocode(self, toponym, country=None, state_code=None, limit=None): """ Invokes the direct geocoding API endpoint :param toponym: the name of the location :type toponym: `str` :param country: the 2-chars ISO symbol of the country :type country: `str` or `None` :param state_code: the 2-chars ISO symbol of state (only useful in case the country is US) :type state_code: `str` or `None` :param limit: the max number of results to be returned in case of multiple matchings (no limits by default) :type limit: `int` or `None` :returns: a list of *Location* instances :raises: *AssertionError*, *ValueError*, *APIRequestError* """ assert toponym, 'Toponym must be specified' if country is not None and len(country) != 2: raise ValueError("Country must be a 2-char string") if state_code is not None and len(state_code) != 2: raise ValueError("State Code must be a 2-char string") if limit is not None: assert isinstance(limit, int) assert limit > 0 query = toponym if state_code is not None: query += ',' + state_code if country is not None: query += ',' + country params = {'q': query} if limit is not None: params['limit'] = limit _, json_data = self.http_client.get_json(DIRECT_GEOCODING_URI, params=params) return [Location.from_dict(item) for item in json_data]
def to_geopoint(self): loc_1 = Location(self.__test_name, None, self.__test_lat, self.__test_ID, self.__test_country) loc_2 = Location(self.__test_name, self.__test_lon, None, self.__test_ID, self.__test_country) loc_3 = Location(self.__test_name, self.__test_lon, self.__test_lat, self.__test_ID, self.__test_country) self.assertIsNone(loc_1.to_geopoint()) self.assertIsNone(loc_2.to_geopoint()) result = loc_3.to_geopoint() self.assertTrue(isinstance(result, Point)) expected_geojson = json.dumps({ "coordinates": [12.3, 43.7], "type": "Point" }) self.assertEqual(sorted(expected_geojson), sorted(result.geojson()))
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_getters_return_expected_data(self): self.assertEqual(self.__test_instance.get_reception_time(), self.__test_reception_time) self.assertEqual(self.__test_instance.get_reference_time(), self.__test_reference_time) self.assertEqual(self.__test_instance.get_location(), self.__test_location) self.assertEqual(self.__test_instance.get_du_value(), self.__test_du_value) self.assertEqual(self.__test_instance.get_interval(), self.__test_interval) def test_returning_different_formats_for_reception_time(self): self.assertEqual(self.__test_instance.get_reception_time(timeformat='iso'), \ self.__test_iso_reception_time) self.assertEqual(self.__test_instance.get_reception_time(timeformat='unix'), \ self.__test_reception_time) self.assertEqual(self.__test_instance.get_reception_time(timeformat='date'), \ self.__test_date_reception_time) def test_returning_different_formats_for_reference_time(self): self.assertEqual(self.__test_instance.get_reference_time(timeformat='iso'), \ self.__test_iso_reference_time) self.assertEqual(self.__test_instance.get_reference_time(timeformat='unix'), \ self.__test_reference_time) self.assertEqual(self.__test_instance.get_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()) # Test JSON and XML comparisons by ordering strings (this overcomes # interpeter-dependant serialization of XML/JSON objects) def test_to_JSON(self): ordered_base_json = ''.join(sorted(OZONE_JSON_DUMP)) ordered_actual_json = ''.join(sorted(self.__test_instance.to_JSON())) self.assertEqual(ordered_base_json, ordered_actual_json) def test_to_XML(self): ordered_base_xml = ''.join(sorted(OZONE_XML_DUMP)) ordered_actual_xml = ''.join(sorted(self.__test_instance.to_XML())) self.assertEqual(ordered_base_xml, ordered_actual_xml)
class TestForecast(unittest.TestCase): __test_reception_time = 1234567 __test_iso_reception_time = "1970-01-15 06:56:07+00:00" __test_date_reception_time = datetime.fromisoformat( __test_iso_reception_time) __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)
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.get_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_sun(self): self.assertTrue(self.__test_instance.will_have_sun()) 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_sun(self): self.assertEqual( [self.__test_weather_sun_1, self.__test_weather_sun_2], self.__test_instance.when_sun()) 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_sunny_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_sunny_at(time_1)) self.assertFalse(self.__test_instance.will_be_sunny_at(time_2)) self.assertTrue(self.__test_instance.will_be_sunny_at(time_3)) def test_will_be_sunny_at_fails_with_bad_parameters(self): self.assertRaises(TypeError, Forecaster.will_be_sunny_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())
class TestUVIndex(unittest.TestCase): __test_reception_time = 1475283600 __test_iso_reception_time = "2016-10-01 01:00:00+00:00" __test_date_reception_time = datetime.fromisoformat( __test_iso_reception_time) __test_reference_time = 1234567 __test_iso_reference_time = "1970-01-15 06:56:07+00:00" __test_date_reference_time = datetime.fromisoformat( __test_iso_reference_time) __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)
class TestAirStatus(unittest.TestCase): __test_reception_time = 1475283600 __test_iso_reception_time = "2016-10-01 01:00:00+00:00" __test_date_reception_time = datetime.fromisoformat( __test_iso_reception_time) __test_reference_time = 1234567 __test_iso_reference_time = "1970-01-15 06:56:07+00:00" __test_date_reference_time = datetime.fromisoformat( __test_iso_reference_time) __test_location = Location('test', 12.3, 43.7, 987, 'UK') __test_air_quality_data = { "aqi": 1, "co": 250.34, "no": 0.19, "no2": 35.99, "o3": 30.76, "so2": 8.11, "pm2_5": 3.15, "pm10": 3.81, "nh3": 0.74 } __test_interval = 'day' __test_instance = AirStatus(__test_reference_time, __test_location, __test_air_quality_data, __test_reception_time) def test_init_fails_when_reference_time_is_negative(self): self.assertRaises(ValueError, AirStatus, -1234567, self.__test_location, self.__test_air_quality_data, self.__test_reception_time) def test_init_fails_when_reception_time_is_negative(self): self.assertRaises(ValueError, AirStatus, self.__test_reference_time, self.__test_location, self.__test_air_quality_data, -1234567) def test_init_fails_when_air_quality_data_is_not_a_dict(self): self.assertRaises(ValueError, AirStatus, self.__test_reference_time, self.__test_location, '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_from_dict(self): # one item d = json.loads(AIRSTATUS_JSON) result = AirStatus.from_dict(d) self.assertIsNotNone(result) 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) for key in self.__test_air_quality_data: getattr(result, key) # multiple items d = json.loads(AIRSTATUS_MULTIPLE_JSON) result = AirStatus.from_dict(d) self.assertIsInstance(result, list) for item in result: self.assertIsInstance(item, AirStatus) self.assertIsNotNone(item.reference_time()) loc = item.location self.assertIsNotNone(loc) self.assertIsNone(loc.name) self.assertIsNone(loc.id) self.assertIsNotNone(loc.lon) self.assertIsNotNone(loc.lat) for key in self.__test_air_quality_data: getattr(item, key) def test_from_dict_fails_when_JSON_data_is_None(self): self.assertRaises(pyowm.commons.exceptions.ParseAPIResponseError, AirStatus.from_dict, None) def test_from_dict_fails_with_malformed_JSON_data(self): self.assertRaises(pyowm.commons.exceptions.ParseAPIResponseError, AirStatus.from_dict, json.loads(AIRSTATUS_MALFORMED_JSON)) def test_to_dict(self): expected = json.loads(AIRSTATUS_JSON_DUMP) result = self.__test_instance.to_dict() ordered_str_expected = sorted(str(expected)) ordered_str_result = sorted(str(result)) self.assertEqual(ordered_str_expected, ordered_str_result) def test_repr(self): print(self.__test_instance)
class TestLocation(unittest.TestCase): __test_name = 'London' __test_lon = 12.3 __test_lat = 43.7 __test_ID = 1234 __test_country = 'UK' __test_instance = Location(__test_name, __test_lon, __test_lat, __test_ID, __test_country) LOCATION_JSON_DUMP = '{"country": "UK", "name": "London", "coordinates": ' \ + '{"lat": 43.7, "lon": 12.3}, "ID": 1234}' def test_init_fails_when_lat_or_lon_are_none(self): self.assertRaises(ValueError, Location, 'London', None, 43.7, 1234) self.assertRaises(ValueError, Location, 'London', 200.0, None, 1234) def test_init_fails_when_coordinates_are_out_of_bounds(self): """ Test failure when providing: lon < -180, lon > 180, lat < -90, lat > 90 """ self.assertRaises(ValueError, Location, 'London', -200.0, 43.7, 1234) self.assertRaises(ValueError, Location, 'London', 200.0, 43.7, 1234) self.assertRaises(ValueError, Location, 'London', 12.3, -100.0, 1234) self.assertRaises(ValueError, Location, 'London', 12.3, 100.0, 1234) def test_from_dict(self): try: Location.from_dict(None) self.fail() except exceptions.ParseAPIResponseError: pass dict1 = { "coord": { "lon": -0.12574, "lat": 51.50853 }, "id": 2643743, "name": "London", "cnt": 9 } dict2 = { "city": { "coord": { "lat": 51.50853, "lon": -0.125739 }, "country": "GB", "id": 2643743, "name": "London", "population": 1000000 } } dict3 = {"station": {"coord": {"lon": -90.47, "lat": 39.38}}} dict4 = {"station": {"coord": {"lng": -90.47, "lat": 39.38}}} dict5 = {"station": {}} result1 = Location.from_dict(dict1) result2 = Location.from_dict(dict2) result3 = Location.from_dict(dict3) result4 = Location.from_dict(dict4) self.assertTrue(isinstance(result1, Location)) self.assertTrue(isinstance(result2, Location)) self.assertFalse(result1.country is not None) self.assertTrue(result1.id is not None) self.assertTrue(result1.lat is not None) self.assertTrue(result1.lon is not None) self.assertTrue(result1.name is not None) self.assertTrue(result2.country is not None) self.assertTrue(result2.id is not None) self.assertTrue(result2.lat is not None) self.assertTrue(result2.lon is not None) self.assertTrue(result2.name is not None) self.assertTrue(result3.lat is not None) self.assertTrue(result3.lon is not None) self.assertTrue(result3.country is None) self.assertTrue(result3.name is None) self.assertTrue(result3.id is None) self.assertIsInstance(result4, Location) self.assertRaises(KeyError, Location.from_dict, dict5) def test_from_dict_holds_the_lack_of_geocoords(self): dict1 = {"station": {"coord": {}}} dict2 = {"coord": {}} result1 = Location.from_dict(dict1) self.assertTrue(isinstance(result1, Location)) self.assertEqual(result1.lat, 0.0) self.assertEqual(result1.lon, 0.0) self.assertTrue(result1.country is None) self.assertTrue(result1.name is None) self.assertTrue(result1.id is None) result2 = Location.from_dict(dict2) self.assertTrue(isinstance(result2, Location)) self.assertEqual(result2.lat, 0.0) self.assertEqual(result2.lon, 0.0) self.assertTrue(result2.country is None) self.assertTrue(result2.name is None) self.assertTrue(result2.id is None) def test_to_dict(self): expected = json.loads(self.LOCATION_JSON_DUMP) result = self.__test_instance.to_dict() self.assertEqual(expected, result) def test_to_geopoint(self): loc_1 = Location(self.__test_name, self.__test_lon, self.__test_lat, self.__test_ID, self.__test_country) loc_1.lat = None self.assertIsNone(loc_1.to_geopoint()) loc_1.lon = None self.assertIsNone(loc_1.to_geopoint()) loc_2 = Location(self.__test_name, self.__test_lon, self.__test_lat, self.__test_ID, self.__test_country) result = loc_2.to_geopoint() self.assertTrue(isinstance(result, Point)) expected_geojson = json.dumps({ "coordinates": [12.3, 43.7], "type": "Point" }) self.assertEqual(sorted(expected_geojson), sorted(result.geojson())) 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)