class IntegrationTestsSoilData(unittest.TestCase):

    __owm = OWM25(parsers, os.getenv('OWM_API_KEY', DEFAULT_API_KEY))

    def test_call_soil_data(self):

        mgr = self.__owm.agro_manager()

        # check if any previous polygon exists on this account
        n_old_polygons = len(mgr.get_polygons())

        # create pol1
        geopol1 = GeoPolygon([[[-121.1958, 37.6683], [-121.1779, 37.6687],
                               [-121.1773, 37.6792], [-121.1958, 37.6792],
                               [-121.1958, 37.6683]]])
        test_pol = mgr.create_polygon(geopol1, 'soil_data_test_pol')

        soil = mgr.soil_data(test_pol)

        self.assertTrue(isinstance(soil, Soil))
        self.assertEqual(test_pol.id, soil.polygon_id)

        # Delete test polygon
        mgr.delete_polygon(test_pol)
        polygons = mgr.get_polygons()
        self.assertEqual(n_old_polygons, len(polygons))
class TesIntegrationTileManager(unittest.TestCase):

    __owm = OWM25(parsers, os.getenv('OWM_API_KEY', DEFAULT_API_KEY))

    def test_tiles_fetch(self):
        mgr = self.__owm.tile_manager(MapLayerEnum.PRECIPITATION)
        tile = mgr.get_tile(3, 6, 7)
        self.assertIsInstance(tile, Tile)
Beispiel #3
0
class IntegrationTestsPollutionAPI30(unittest.TestCase):

    __owm = OWM25(parsers, os.getenv('OWM_API_KEY', DEFAULT_API_KEY))



    def test_coindex_around_coords(self):
        """
        Test feature: get CO index around geo-coordinates.
        """
        u = self.__owm.coindex_around_coords(45, 9)
        self.assertIsNotNone(u)
        self.assertIsNotNone(u.get_co_samples())
        self.assertIsNotNone(u.get_reception_time())
        self.assertIsNotNone(u.get_reference_time())
        self.assertIsNotNone(u.get_interval())
        self.assertIsNotNone(u.get_location())

    def test_ozone_around_coords(self):
        """
        Test feature: get ozone around geo-coordinates.
        """
        u = self.__owm.ozone_around_coords(0.0, 10.0, start='2016-12-31 12:55:55+00')
        self.assertIsNotNone(u)
        self.assertIsNotNone(u.get_du_value())
        self.assertIsNotNone(u.get_reception_time())
        self.assertIsNotNone(u.get_reference_time())
        self.assertIsNotNone(u.get_interval())
        self.assertIsNotNone(u.get_location())

    def test_no2index_around_coords(self):
        """
        Test feature: get NO2 index around geo-coordinates.
        """
        u = self.__owm.no2index_around_coords(0.0, 10.0, start='2016-12-31 12:55:55+00')
        self.assertIsNotNone(u)
        self.assertIsNotNone(u.get_no2_samples())
        self.assertIsNotNone(u.get_reception_time())
        self.assertIsNotNone(u.get_reference_time())
        self.assertIsNotNone(u.get_interval())
        self.assertIsNotNone(u.get_location())

    def test_so2index_around_coords(self):
        """
        Test feature: get SO2 index around geo-coordinates.
        """
        u = self.__owm.so2index_around_coords(0.0, 10.0, start='2016-12-31 12:55:55+00')
        self.assertIsNotNone(u)
        self.assertIsNotNone(u.get_so2_samples())
        self.assertIsNotNone(u.get_reception_time())
        self.assertIsNotNone(u.get_reference_time())
        self.assertIsNotNone(u.get_interval())
        self.assertIsNotNone(u.get_location())
Beispiel #4
0
def OWM(API_key=constants.DEFAULT_API_KEY,
        version=constants.LATEST_OWM_API_VERSION,
        config_module=None,
        language=None,
        subscription_type=None,
        use_ssl=None):
    """
    A parametrized factory method returning a global OWM instance that
    represents the desired OWM Weather API version (or the currently supported one
    if no version number is specified)

    :param API_key: the OWM Weather API key (defaults to a test value)
    :type API_key: str
    :param version: the OWM Weather API version. Defaults to ``None``, which means
        use the latest web API version
    :type version: str
    :param config_module: the Python path of the configuration module you want
        to provide for instantiating the library. Defaults to ``None``, which
        means use the default configuration values for the web API version
        support you are currently requesting. Please be aware that malformed
        user-defined configuration modules can lead to unwanted behaviour!
    :type config_module: str (eg: 'mypackage.mysubpackage.myconfigmodule')
    :param language: the language in which you want text results to be returned.
          It's a two-characters string, eg: "en", "ru", "it". Defaults to:
          ``None``, which means use the default language.
    :type language: str
    :param subscription_type: the type of OWM Weather API subscription to be wrapped.
           Can be 'free' (free subscription) or 'pro' (paid subscription),
           Defaults to: 'free'
    :type subscription_type: str
    :param use_ssl: whether API calls should be made via SSL or not.
           Defaults to: False
    :type use_ssl: bool
    :returns: an instance of a proper *OWM* subclass
    :raises: *ValueError* when unsupported OWM API versions are provided
    """
    if version == '2.5':
        if config_module is None:
            config_module = "pyowm.weatherapi25.configuration25"
        cfg_module = __import__(config_module, fromlist=[''])
        from pyowm.weatherapi25.owm25 import OWM25
        if language is None:
            language = cfg_module.language
        if subscription_type is None:
            subscription_type = cfg_module.API_SUBSCRIPTION_TYPE
            if subscription_type not in ['free', 'pro']:
                subscription_type = 'free'
        if use_ssl is None:
            use_ssl = cfg_module.USE_SSL
        return OWM25(cfg_module.parsers, API_key, cfg_module.cache, language,
                     subscription_type, use_ssl)
    raise ValueError("Unsupported OWM Weather API version")
Beispiel #5
0
    def test_ssl(self):

        # Try to call the OWM API using SSL and certificate validation
        owm = OWM25(parsers, API_key=self.__API_key, use_ssl=True)
        try:
            # weather API
            owm.weather_at_place('London,GB')

            # pollution API
            owm.uvindex_around_coords(-22.57, -43.12)

            # stations API
            mgr = owm.stations_manager()
            mgr.get_stations()

        except Exception as e:
            self.fail(str(e))
Beispiel #6
0
 def test_caching_times(self):
     """
     Test that subsequent calls to the same endpoint and with the same
     query parameters are cached if OWM instance is configured with a 
     non-null cache.
     """
     cache = LRUCache(20, 1000 * 60 * 60)
     owm = OWM25(parsers, API_key=self.API_KEY, cache=cache)
     before_request = time()
     o1 = owm.weather_at_place('London,GB')  # Comes from OWM Weather API
     after_request = time()
     o2 = owm.weather_at_place('London,GB')  # Comes from cache
     after_cache_hit_1 = time()
     owm.weather_at_place('Kiev')  # Comes from OWM Weather API
     owm.weather_at_coords(-33.936524,
                           18.503723)  # Comes from OWM Weather API
     owm.weather_at_coords(-33.936524, 18.503723)  # Cached, we don't care
     owm.weather_at_coords(-33.936524, 18.503723)  # Cached, we don't care
     before_cache_hit_2 = time()
     o3 = owm.weather_at_place('London,GB')  # Comes from cache
     after_cache_hit_2 = time()
     #Check results: difference in reception time should not be less than 20 sec
     self.assertAlmostEqual(o1.get_reception_time(),
                            o2.get_reception_time(),
                            places=None,
                            msg=None,
                            delta=20)
     self.assertAlmostEqual(o1.get_reception_time(),
                            o3.get_reception_time(),
                            places=None,
                            msg=None,
                            delta=20)
     #Check times: all cache hit times must be less than the former OWM web
     #API request time and ratio between cache hit times and request time
     #should be far less than 1
     req_delay = after_request - before_request
     cache_hit_1_delay = after_cache_hit_1 - after_request
     cache_hit_2_delay = after_cache_hit_2 - before_cache_hit_2
     self.assertTrue(cache_hit_1_delay < req_delay)
     self.assertTrue(cache_hit_2_delay < req_delay)
     self.assertTrue(cache_hit_1_delay / req_delay < 1)
     self.assertTrue(cache_hit_2_delay / req_delay < 1)
Beispiel #7
0
 def test_cache_limits(self):
     """
     Test that when cache is full, cached elements undergo a turnover and
     the real OWM Weather API is invoked
     """
     cache = LRUCache(3, 1000 * 60 * 60)  # Only three cacheable elements!
     wrapped_cache = CacheWrapper(cache)
     owm = OWM25(parsers, API_key=self.API_KEY, cache=wrapped_cache)
     owm.weather_at_place('London,GB')  # Comes from OWM Weather API
     owm.weather_at_place('Kiev')  # Comes from OWM Weather API
     owm.weather_at_place('Madrid')  # Comes from OWM Weather API
     self.assertEqual(3, wrapped_cache.api_calls())
     owm.weather_at_place('London,GB')  # Comes from cache
     owm.weather_at_place('Kiev')  # Comes from cache
     self.assertEqual(3, wrapped_cache.api_calls())
     owm.weather_at_place('Tokyo')
     self.assertEqual(4, wrapped_cache.api_calls())
     owm.weather_at_place(
         'Madrid')  # Now Madrid should have been pulled out of cache
     self.assertEqual(5, wrapped_cache.api_calls())
class IntegrationTestsUVIndexAPI30(unittest.TestCase):

    __owm = OWM25(parsers, os.getenv('OWM_API_KEY', DEFAULT_API_KEY))

    def test_uvindex_around_coords(self):
        """
        Test feature: get UV index around geo-coordinates.
        """
        u = self.__owm.uvindex_around_coords(45, 9)
        self.assertIsNotNone(u)
        self.assertIsNotNone(u.get_value())
        self.assertIsNotNone(u.get_reception_time())
        self.assertIsNotNone(u.get_location())

    def test_uvindex_forecast_around_coords(self):
        """
        Test feature: get UV index forecast around geo-coordinates.
        """
        uv_list = self.__owm.uvindex_forecast_around_coords(45, 9)
        self.assertIsInstance(uv_list, list)
        for item in uv_list:
            self.assertIsNotNone(item.get_value())
            self.assertIsNotNone(item.get_reception_time())
            self.assertIsNotNone(item.get_location())

    def test_uvindex_history_around_coords(self):
        """
        Test feature: get UV index history around geo-coordinates.
        """
        start = datetime(2017, 6, 21)
        end = datetime(2017, 6, 27)
        uv_list = self.__owm.uvindex_history_around_coords(37.7,
                                                           -122.37,
                                                           start,
                                                           end=end)
        self.assertIsInstance(uv_list, list)
        for item in uv_list:
            self.assertIsNotNone(item.get_value())
            self.assertIsNotNone(item.get_reception_time())
            self.assertIsNotNone(item.get_location())
Beispiel #9
0
 def test_caching_prevents_API_calls(self):
     cache = LRUCache(20, 1000 * 60 * 60)
     wrapped_cache = CacheWrapper(cache)
     owm = OWM25(parsers, API_key=self.API_KEY, cache=wrapped_cache)
     self.assertFalse(wrapped_cache.last_request_was_hit())
     self.assertEqual(0, wrapped_cache.api_calls())
     owm.weather_at_place('London,GB')  # Comes from OWM Weather API
     self.assertFalse(wrapped_cache.last_request_was_hit())
     self.assertEqual(1, wrapped_cache.api_calls())
     owm.weather_at_place('London,GB')  # Comes from cache
     self.assertTrue(wrapped_cache.last_request_was_hit())
     self.assertEqual(1, wrapped_cache.api_calls())
     owm.weather_at_place('London,GB')  # Comes from cache again
     self.assertTrue(wrapped_cache.last_request_was_hit())
     self.assertEqual(1, wrapped_cache.api_calls())
     owm.weather_at_place('Kiev')  # Comes from OWM Weather API
     self.assertFalse(wrapped_cache.last_request_was_hit())
     self.assertEqual(2, wrapped_cache.api_calls())
     owm.weather_at_place('Kiev')  # Comes from cache
     self.assertTrue(wrapped_cache.last_request_was_hit())
     self.assertEqual(2, wrapped_cache.api_calls())
     owm.weather_at_place('London,GB')  # Comes from cache
     self.assertTrue(wrapped_cache.last_request_was_hit())
     self.assertEqual(2, wrapped_cache.api_calls())
Beispiel #10
0
class IntegrationTestsSatelliteImageryStats(unittest.TestCase):

    __owm = OWM25(parsers, os.getenv('OWM_API_KEY', DEFAULT_API_KEY))
    __polygon = None
    __acquired_from = 1500336000  # 18 July 2017
    __acquired_to = 1508976000  # 26 October 2017

    @classmethod
    def setUpClass(cls):
        # create a polygon
        mgr = cls.__owm.agro_manager()
        geopol = GeoPolygon([[[-121.1958, 37.6683], [-121.1779, 37.6687],
                              [-121.1773, 37.6792], [-121.1958, 37.6792],
                              [-121.1958, 37.6683]]])
        cls.__polygon = mgr.create_polygon(geopol, 'stats_test_polygon')

    @classmethod
    def tearDownClass(cls):
        # delete the polygon
        mgr = cls.__owm.agro_manager()
        mgr.delete_polygon(cls.__polygon)

    def test_stats_for_satellite_image(self):
        mgr = self.__owm.agro_manager()

        # search all Landsat 8 images in the specified time frame and with high valid data percentage
        result_set = mgr.search_satellite_imagery(
            self.__polygon.id, self.__acquired_from, self.__acquired_to, None,
            None, None, None, SatelliteEnum.LANDSAT_8.symbol, None, 0.5, 99.5,
            None)
        self.assertIsInstance(result_set, list)
        self.assertTrue(
            all([
                isinstance(i, MetaImage)
                and i.satellite_name == SatelliteEnum.LANDSAT_8.name
                for i in result_set
            ]))

        # only keep EVI and NDVI ones
        ndvi_only = [
            mimg for mimg in result_set if mimg.preset == PresetEnum.NDVI
        ]
        evi_only = [
            mimg for mimg in result_set if mimg.preset == PresetEnum.EVI
        ]

        self.assertTrue(len(ndvi_only) > 1)
        self.assertTrue(len(evi_only) > 1)

        # now search for stats for both types
        stats_ndvi = mgr.stats_for_satellite_image(ndvi_only[0])
        stats_evi = mgr.stats_for_satellite_image(evi_only[0])
        self.assertIsInstance(stats_ndvi, dict)
        self.assertIsInstance(stats_evi, dict)

        # try to search for stats of a non NDVI or EVI image
        falsecolor_only = [
            mimg for mimg in result_set
            if mimg.preset == PresetEnum.FALSE_COLOR
        ]
        with self.assertRaises(ValueError):
            mgr.stats_for_satellite_image(falsecolor_only[0])
Beispiel #11
0
class IntegrationTestsWebAPI25(unittest.TestCase):

    __owm = OWM25(parsers, os.getenv('OWM_API_KEY', DEFAULT_API_KEY))

    def test_is_API_online(self):
        self.assertTrue(self.__owm.is_API_online())

    def test_weather_at_place(self):
        """
        Test feature: get currently observed weather at specific location
        """
        o1 = self.__owm.weather_at_place('London,uk')
        o2 = self.__owm.weather_at_place('Kiev')
        self.assertTrue(o1 is not None)
        self.assertTrue(o1.get_reception_time() is not None)
        loc = o1.get_location()
        self.assertTrue(loc is not None)
        self.assertTrue(all(v is not None for v in loc.__dict__.values()))
        weat = o1.get_weather()
        self.assertTrue(weat is not None)
        self.assertTrue(o2 is not None)
        self.assertTrue(o2.get_reception_time() is not None)
        loc = o2.get_location()
        self.assertTrue(loc is not None)
        self.assertTrue(all(v is not None for v in loc.__dict__.values()))
        weat = o2.get_weather()
        self.assertTrue(weat is not None)

    def test_weather_at_coords(self):
        """
        Test feature: get currently observed weather at specific coordinates
        """
        o1 = self.__owm.weather_at_coords(41.896144, 12.484589)  # Rome
        o2 = self.__owm.weather_at_coords(-33.936524, 18.503723)  # Cape Town
        self.assertTrue(o1)
        self.assertTrue(o1.get_reception_time())
        loc = o1.get_location()
        self.assertTrue(loc)
        self.assertTrue(all(v is not None for v in loc.__dict__.values()))
        weat = o1.get_weather()
        self.assertTrue(weat)
        self.assertTrue(o2)
        self.assertTrue(o2.get_reception_time())
        loc = o2.get_location()
        self.assertTrue(loc)
        self.assertTrue(all(v is not None for v in loc.__dict__.values()))
        weat = o2.get_weather()
        self.assertTrue(weat)

    def test_weather_at_zipcode(self):
        """
        Test feature: get currently observed weather at specific postcode
        """
        o1 = self.__owm.weather_at_zip_code("94040", "US")
        self.assertTrue(o1)
        self.assertTrue(o1.get_reception_time())
        loc = o1.get_location()
        self.assertTrue(loc)
        self.assertTrue(all(v is not None for v in loc.__dict__.values()))
        weat = o1.get_weather()
        self.assertTrue(weat)

    def test_weather_at_id(self):
        o1 = self.__owm.weather_at_id(5128581) # New York
        o2 = self.__owm.weather_at_id(703448) # Kiev'
        self.assertTrue(o1 is not None)
        self.assertTrue(o1.get_reception_time() is not None)
        loc = o1.get_location()
        self.assertTrue(loc is not None)
        self.assertTrue(all(v is not None for v in loc.__dict__.values()))
        weat = o1.get_weather()
        self.assertTrue(weat is not None)
        self.assertTrue(o2 is not None)
        self.assertTrue(o2.get_reception_time() is not None)
        loc = o2.get_location()
        self.assertTrue(loc is not None)
        self.assertTrue(all(v is not None for v in loc.__dict__.values()))
        weat = o2.get_weather()
        self.assertTrue(weat is not None)

    def test_weather_at_ids(self):
        # New York, Kiev
        observations = self.__owm.weather_at_ids([5128581,703448])
        o1 = observations[0]
        o2 = observations[1]
        self.assertTrue(o1 is not None)
        self.assertTrue(o1.get_reception_time() is not None)
        loc = o1.get_location()
        self.assertTrue(loc is not None)
        self.assertTrue(all(v is not None for v in loc.__dict__.values()))
        weat = o1.get_weather()
        self.assertTrue(weat is not None)
        self.assertTrue(o2 is not None)
        self.assertTrue(o2.get_reception_time() is not None)
        loc = o2.get_location()
        self.assertTrue(loc is not None)
        self.assertTrue(all(v is not None for v in loc.__dict__.values()))
        weat = o2.get_weather()
        self.assertTrue(weat is not None)

    def test_weather_at_places(self):
        """
        Test feature: find currently observed weather for locations matching
        the specified text search pattern
        """
        # Test using searchtype=accurate
        o1 = self.__owm.weather_at_places("London", "accurate")
        o2 = self.__owm.weather_at_places("Paris", "accurate", 2)
        self.assertTrue(isinstance(o1, list))
        for item in o1:
            self.assertTrue(item)
            self.assertTrue(item.get_reception_time())
            loc = item.get_location()
            self.assertTrue(loc is not None)
            self.assertTrue(all(v is not None for v in loc.__dict__.values()))
            weat = item.get_weather()
            self.assertTrue(weat is not None)
        self.assertTrue(isinstance(o2, list))
        self.assertFalse(len(o2) > 2)
        for item in o2:
            self.assertTrue(item)
            self.assertTrue(item.get_reception_time())
            loc = item.get_location()
            self.assertTrue(loc is not None)
            self.assertTrue(all(v is not None for v in loc.__dict__.values()))
            weat = item.get_weather()
            self.assertTrue(weat is not None)

        # Test using searchtype=like
        o3 = self.__owm.weather_at_places("London", "like")
        o4 = self.__owm.weather_at_places("Paris", "like", 2)
        self.assertTrue(isinstance(o3, list))
        for item in o3:
            self.assertTrue(item)
            self.assertTrue(item.get_reception_time())
            loc = item.get_location()
            self.assertTrue(loc is not None)
            self.assertTrue(all(v is not None for v in loc.__dict__.values()))
            weat = item.get_weather()
            self.assertTrue(weat is not None)
        self.assertTrue(isinstance(o4, list))
        self.assertFalse(len(o4) > 2)
        for item in o4:
            self.assertTrue(item)
            self.assertTrue(item.get_reception_time())
            loc = item.get_location()
            self.assertTrue(loc is not None)
            self.assertTrue(all(v is not None for v in loc.__dict__.values()))
            weat = item.get_weather()
            self.assertTrue(weat is not None)

    def test_weather_around_coords(self):
        """
        Test feature: find currently observed weather for locations that are
        nearby the specified coordinates
        """
        o2 = self.__owm.weather_around_coords(57.0, -2.15)  # Scotland
        self.assertTrue(isinstance(o2, list))
        for item in o2:
            self.assertTrue(item is not None)
            self.assertTrue(item.get_reception_time() is not None)
            loc = item.get_location()
            self.assertTrue(loc is not None)
            self.assertTrue(all(v is not None for v in loc.__dict__.values()))
            weat = item.get_weather()
            self.assertTrue(weat is not None)
        o1 = self.__owm.weather_around_coords(57.0, -2.15, 2)  # Scotland
        self.assertTrue(isinstance(o1, list))
        for item in o1:
            self.assertTrue(item is not None)
            self.assertTrue(item.get_reception_time() is not None)
            loc = item.get_location()
            self.assertTrue(loc is not None)
            self.assertTrue(all(v is not None for v in loc.__dict__.values()))
            weat = item.get_weather()
            self.assertTrue(weat is not None)

    def test_three_hours_forecast(self):
        """
        Test feature: get 3 hours forecast for a specific location
        """
        fc1 = self.__owm.three_hours_forecast("London,uk")
        fc2 = self.__owm.three_hours_forecast('Kiev')
        self.assertTrue(fc1)
        f1 = fc1.get_forecast()
        self.assertTrue(f1 is not None)
        self.assertTrue(f1.get_reception_time() is not None)
        loc = f1.get_location()
        self.assertTrue(loc is not None)
        self.assertTrue(all(v is not None for v in loc.__dict__.values()))
        for weather in f1:
            self.assertTrue(weather is not None)
        self.assertTrue(fc2 is not None)
        f2 = fc2.get_forecast()
        self.assertTrue(f2 is not None)
        self.assertTrue(f2.get_reception_time() is not None)
        loc = f2.get_location()
        self.assertTrue(loc is not None)
        self.assertTrue(all(v is not None for v in loc.__dict__.values()))
        for weather in f2:
            self.assertTrue(weather is not None)

    def test_three_hours_forecast_at_coords(self):
        """
        Test feature: get 3 hours forecast at a specific geographic coordinate
        """
        # London,uk
        fc1 = self.__owm.three_hours_forecast_at_coords(51.5073509, -0.1277583)
        # Kiev
        fc2 = self.__owm.three_hours_forecast_at_coords(50.4501, 30.5234)
        self.assertTrue(fc1)
        f1 = fc1.get_forecast()
        self.assertTrue(f1 is not None)
        self.assertTrue(f1.get_reception_time() is not None)
        loc = f1.get_location()
        self.assertTrue(loc is not None)
        self.assertTrue(all(v is not None for v in loc.__dict__.values()))
        for weather in f1:
            self.assertTrue(weather is not None)
        self.assertTrue(fc2 is not None)
        f2 = fc2.get_forecast()
        self.assertTrue(f2 is not None)
        self.assertTrue(f2.get_reception_time() is not None)
        loc = f2.get_location()
        self.assertTrue(loc is not None)
        self.assertTrue(all(v is not None for v in loc.__dict__.values()))
        for weather in f2:
            self.assertTrue(weather is not None)
        with self.assertRaises(ValueError):
            self.__owm.three_hours_forecast_at_coords(199, 199)

    def test_three_hours_forecast_at_id(self):
        """
        Test feature: get 3 hours forecast for city ID
        """
        # London,uk
        fc1 = self.__owm.three_hours_forecast_at_id(2643743)
        # Kiev
        fc2 = self.__owm.three_hours_forecast_at_id(703448)
        self.assertTrue(fc1)
        f1 = fc1.get_forecast()
        self.assertTrue(f1 is not None)
        self.assertTrue(f1.get_reception_time() is not None)
        loc = f1.get_location()
        self.assertTrue(loc is not None)
        self.assertTrue(all(v is not None for v in loc.__dict__.values()))
        for weather in f1:
            self.assertTrue(weather is not None)
        self.assertTrue(fc2 is not None)
        f2 = fc2.get_forecast()
        self.assertTrue(f2 is not None)
        self.assertTrue(f2.get_reception_time() is not None)
        loc = f2.get_location()
        self.assertTrue(loc is not None)
        self.assertTrue(all(v is not None for v in loc.__dict__.values()))
        for weather in f2:
            self.assertTrue(weather is not None)
        # Unexistent
        try:
            fc3 = self.__owm.three_hours_forecast_at_id(99999999999999)
            self.fail()
        except api_response_error.NotFoundError:
            pass # ok

    def test_daily_forecast(self):
        """
        Test feature: get daily forecast for a specific location
        """
        fc1 = self.__owm.daily_forecast("London,uk")
        fc2 = self.__owm.daily_forecast('Kiev')
        self.assertTrue(fc1)
        f1 = fc1.get_forecast()
        self.assertTrue(f1 is not None)
        self.assertTrue(f1.get_reception_time() is not None)
        loc = f1.get_location()
        self.assertTrue(loc is not None)
        self.assertTrue(all(v is not None for v in loc.__dict__.values()))
        for weather in f1:
            self.assertTrue(weather is not None)
        self.assertTrue(fc2 is not None)
        f2 = fc2.get_forecast()
        self.assertTrue(f2 is not None)
        self.assertTrue(f2.get_reception_time() is not None)
        loc = f2.get_location()
        self.assertTrue(loc is not None)
        self.assertTrue(all(v is not None for v in loc.__dict__.values()))
        for weather in f2:
            self.assertTrue(weather is not None)

    def test_daily_forecast_at_coords(self):
        """
        Test feature: get daily forecast at a specific geographic coordinate
        """
        fc1 = self.__owm.daily_forecast_at_coords(51.5073509, -0.1277583) # London,uk
        self.assertTrue(fc1)
        f1 = fc1.get_forecast()
        self.assertTrue(f1 is not None)
        self.assertTrue(f1.get_reception_time() is not None)
        loc = f1.get_location()
        self.assertTrue(loc is not None)
        self.assertTrue(all(v is not None for v in loc.__dict__.values()))
        for weather in f1:
            self.assertTrue(weather is not None)
        with self.assertRaises(ValueError):
            self.__owm.daily_forecast_at_coords(199, 199)

    def test_daily_forecast_at_id(self):
        """
        Test feature: get daily forecast for a specific city ID
        """
        # London,uk
        fc1 = self.__owm.daily_forecast_at_id(2643743)
        # Kiev
        fc2 = self.__owm.daily_forecast_at_id(703448)
        try:
            fc3 = self.__owm.daily_forecast_at_id(99999999)
            raise AssertionError("APICallError was expected here")
        except api_response_error.NotFoundError:
            pass  # Ok!
        self.assertTrue(fc1)
        f1 = fc1.get_forecast()
        self.assertTrue(f1 is not None)
        self.assertTrue(f1.get_reception_time() is not None)
        loc = f1.get_location()
        self.assertTrue(loc is not None)
        self.assertTrue(all(v is not None for v in loc.__dict__.values()))
        for weather in f1:
            self.assertTrue(weather is not None)
        self.assertTrue(fc2 is not None)
        f2 = fc2.get_forecast()
        self.assertTrue(f2 is not None)
        self.assertTrue(f2.get_reception_time() is not None)
        loc = f2.get_location()
        self.assertTrue(loc is not None)
        self.assertTrue(all(v is not None for v in loc.__dict__.values()))
        for weather in f2:
            self.assertTrue(weather is not None)

    def test_weather_history_at_place(self):
        """
        Test feature: get weather history for a specific location
        """
        start_iso = "2013-09-06 09:20:00+00"
        start_unix = 1378459200
        start_date = datetime(2013, 9, 6, 9, 20, 0)
        end_iso = "2013-09-06 20:26:40+00"
        end_unix = 1378499200
        end_date = datetime(2013, 9, 6, 20, 26, 40)
        try:
            l1 = self.__owm.weather_history_at_place("London,UK")
            if l1 is not None:
                for weather in l1:
                    self.assertTrue(weather is not None)
            l2 = self.__owm.weather_history_at_place('Kiev', start_unix, end_unix)
            if l2 is not None:
                for weather in l2:
                    self.assertTrue(weather is not None)
            l3 = self.__owm.weather_history_at_place('Rome', start_iso, end_iso)
            if l3 is not None:
                for weather in l3:
                    self.assertTrue(weather is not None)
            l4 = self.__owm.weather_history_at_place('Berlin', start_date, end_date)
            if l4 is not None:
                for weather in l4:
                    self.assertTrue(weather is not None)
            l5 = self.__owm.weather_history_at_place('QmFoPIlbf')  # Shall be None
            self.assertTrue(l5 is None)
        except api_response_error.UnauthorizedError:
            pass  # it's a paid-level API feature

    def test_weather_history_at_coords(self):
        try:
            l1 = self.__owm.weather_history_at_coords(51.5073509, -0.1277583)
            if l1 is not None:
                for weather in l1:
                    self.assertTrue(weather is not None)

        except api_response_error.UnauthorizedError:
            pass  # it's a paid-level API feature

    def test_weather_history_at_id(self):
        """
        Test feature: get weather history for a specific city ID
        """
        try:
            start_iso = "2013-09-06 09:20:00+00"
            start_unix = 1378459200
            start_date = datetime(2013, 9, 6, 9, 20, 0)
            end_iso = "2013-09-06 20:26:40+00"
            end_unix = 1378499200
            end_date = datetime(2013, 9, 6, 20, 26, 40)
            l1 = self.__owm.weather_history_at_id(2756723) # Dongen
            if l1 is not None:
                for weather in l1:
                    self.assertTrue(weather is not None)
            l2 = self.__owm.weather_history_at_id(2756723, start_unix, end_unix)
            if l2 is not None:
                for weather in l2:
                    self.assertTrue(weather is not None)
            l3 = self.__owm.weather_history_at_id(2756723, start_iso, end_iso)
            if l3 is not None:
                for weather in l3:
                    self.assertTrue(weather is not None)
            l4 = self.__owm.weather_history_at_id(2756723, start_date, end_date)
            if l4 is not None:
                for weather in l4:
                    self.assertTrue(weather is not None)
        except api_response_error.UnauthorizedError:
            pass  # it's a paid-level API feature

    def test_station_at_coords(self):
        """
        Test feature: get a list of meteostations nearest to a geographical
        point
        """
        s1 = self.__owm.station_at_coords(51.5073509, -0.1277583, 2)
        self.assertEqual(2, len(s1))
        for station in s1:
            self.assertTrue(station is not None)
            self.assertTrue(
                    all(v is not None for v in station.__dict__.values()))
        with self.assertRaises(ValueError):
            self.__owm.station_at_coords(51.5073509, 220)
        with self.assertRaises(ValueError):
            self.__owm.station_at_coords(220, -0.1277583)
        with self.assertRaises(ValueError):
            self.__owm.station_at_coords(51.5073509, -0.1277583, -3)
        with self.assertRaises(AssertionError):
            self.__owm.station_at_coords(51.5073509, -0.1277582, 'foo')

    def test_station_tick_history(self):
        """
        Test feature: get station tick weather history for a specific
        meteostation
        """
        try:
            h1 = self.__owm.station_tick_history(39276)
            if h1 is not None:
                sh1 = h1.get_station_history()
                self.assertTrue(sh1 is not None)
                data1 = sh1.get_measurements()
                self.assertTrue(data1 is not None)
                self.assertFalse(0, len(data1))
                h2 = self.__owm.station_tick_history(39276, limit=2)
                self.assertTrue(h2 is not None)
                sh2 = h2.get_station_history()
                self.assertTrue(sh2 is not None)
                data2 = sh2.get_measurements()
                self.assertTrue(data2 is not None)
                self.assertFalse(len(data2) > 2)
                h3 = self.__owm.station_tick_history(987654)  # Shall be None
                self.assertFalse(h3 is not None)
        except api_response_error.UnauthorizedError:
            pass  # it's a paid-level API feature

    def test_station_hour_history(self):
        """
        Test feature: get station hour weather history for a specific
        meteostation
        """
        try:
            h1 = self.__owm.station_hour_history(123)
            if h1 is not None:
                sh1 = h1.get_station_history()
                self.assertTrue(sh1 is not None)
                data1 = sh1.get_measurements()
                self.assertTrue(data1 is not None)
                self.assertFalse(0, len(data1))
                h2 = self.__owm.station_hour_history(987654)  # Shall be None
                self.assertFalse(h2 is not None)
        except api_response_error.UnauthorizedError:
            pass  # it's a paid-level API feature

    def test_station_day_history(self):
        """
        Test feature: get station hour weather history for a specific
        meteostation
        """
        try:
            h1 = self.__owm.station_day_history(123)
            if h1 is not None:
                sh1 = h1.get_station_history()
                self.assertTrue(sh1 is not None)
                data1 = sh1.get_measurements()
                self.assertTrue(data1 is not None)
                self.assertFalse(0, len(data1))
                h2 = self.__owm.station_day_history(123, limit=3)
                self.assertTrue(h2 is not None)
                sh2 = h2.get_station_history()
                self.assertTrue(sh2 is not None)
                data2 = sh2.get_measurements()
                self.assertTrue(data2 is not None)
                h3 = self.__owm.station_day_history(987654)  # Shall be None
                self.assertFalse(h3 is not None)
        except api_response_error.UnauthorizedError:
            pass  # it's a paid-level API feature

    def test_weather_at_station(self):
        """
        Test feature: get current weather measurement for a specific
        meteostation
        """
        o = self.__owm.weather_at_station(1000)
        self.assertTrue(o is not None)
        self.assertTrue(o.get_reception_time() is not None)
        weat = o.get_weather()
        self.assertTrue(weat is not None)

    def test_weather_at_stations_in_bbox(self):
        """
        Test feature: get current weather observations from meteostations
        inside of a bounding box determined by geo-coordinates.
        """
        o = self.__owm.weather_at_stations_in_bbox(47.013855, -126.039644,
                                                   33.772746, -115.187844)
        self.assertTrue(isinstance(o, list))
        for item in o:
            self.assertTrue(item is not None)
            self.assertTrue(item.get_reception_time() is not None)
            loc = item.get_location()
            self.assertTrue(loc is not None)
            weat = item.get_weather()
            self.assertTrue(weat is not None)

    def test_weather_at_places_in_bbox(self):
        o = self.__owm.weather_at_places_in_bbox(0.734720, 38.422663, 1.964651, 39.397204, 10, False)  # Ibiza
        self.assertTrue(isinstance(o, list))
        for item in o:
            self.assertTrue(item is not None)
            self.assertTrue(item.get_reception_time() is not None)
            loc = item.get_location()
            self.assertTrue(loc is not None)
            weat = item.get_weather()
            self.assertTrue(weat is not None)
class IntegrationTestsAlertAPI30(unittest.TestCase):

    __owm = OWM25(parsers, os.getenv('OWM_API_KEY', DEFAULT_API_KEY))

    cond1 = Condition(WeatherParametersEnum.HUMIDITY, OperatorsEnum.LESS_THAN,
                      10)
    cond2 = Condition(WeatherParametersEnum.CLOUDS, OperatorsEnum.LESS_THAN,
                      90)
    start = '2019-07-01 14:17:00+00'
    end = '2019-07-02 14:17:00+00'
    # a rectangle around the city of Moscow
    area1 = geo.Polygon.from_dict({
        "type":
        "Polygon",
        "coordinates": [[[36.826171875, 55.17259379606185],
                         [39.012451171875, 55.17259379606185],
                         [39.012451171875, 56.15778819063682],
                         [36.826171875, 56.15778819063682],
                         [36.826171875, 55.17259379606185]]]
    })
    # somewhere in Dubai

    area2 = geo.Point.from_dict({
        "type":
        "Point",
        "coordinates": [55.29693603515625, 25.186301620540558]
    })

    def test_triggers_CRUD(self):

        mgr = self.__owm.alert_manager()

        # check if any previous triggers exist on this account
        n_old_triggers = len(mgr.get_triggers())

        # create trigger1
        trigger1 = mgr.create_trigger(self.start,
                                      self.end,
                                      conditions=[self.cond1],
                                      area=[self.area1])

        # create trigger2
        trigger2 = mgr.create_trigger(self.start,
                                      self.end,
                                      conditions=[self.cond2],
                                      area=[self.area2])

        # Read all created triggers
        triggers = mgr.get_triggers()
        self.assertEqual(n_old_triggers + 2, len(triggers))

        # Read one by one
        result = mgr.get_trigger(trigger1.id)
        self.assertEqual(trigger1.id, result.id)
        self.assertEqual(trigger1.start_after_millis,
                         result.start_after_millis)
        self.assertEqual(trigger1.end_after_millis, result.end_after_millis)
        self.assertEqual(len(trigger1.conditions), len(result.conditions))
        self.assertEqual(len(trigger1.area), len(result.area))

        result = mgr.get_trigger(trigger2.id)
        self.assertEqual(trigger2.id, result.id)
        self.assertEqual(trigger2.start_after_millis,
                         result.start_after_millis)
        self.assertEqual(trigger2.end_after_millis, result.end_after_millis)
        self.assertEqual(len(trigger2.conditions), len(result.conditions))
        self.assertEqual(len(trigger2.area), len(result.area))

        # Update a trigger
        modified_trigger2 = copy.deepcopy(trigger2)
        modified_trigger2.conditions = [self.cond1, self.cond2]

        mgr.update_trigger(modified_trigger2)
        result = mgr.get_trigger(modified_trigger2.id)

        self.assertEqual(modified_trigger2.id, result.id)
        self.assertEqual(modified_trigger2.start_after_millis,
                         result.start_after_millis)
        self.assertEqual(modified_trigger2.end_after_millis,
                         result.end_after_millis)
        self.assertEqual(len(modified_trigger2.area), len(result.area))
        # of course, conditions have been modified with respect to former trigger 2
        self.assertNotEqual(len(trigger2.conditions), len(result.conditions))
        self.assertEqual(len(modified_trigger2.conditions),
                         len(result.conditions))

        # Delete triggers one by one
        mgr.delete_trigger(trigger1)
        triggers = mgr.get_triggers()
        self.assertEqual(n_old_triggers + 1, len(triggers))

        mgr.delete_trigger(modified_trigger2)
        triggers = mgr.get_triggers()
        self.assertEqual(n_old_triggers, len(triggers))
class IntegrationTestsPolygonsAPISubset(unittest.TestCase):

    __owm = OWM25(parsers, os.getenv('OWM_API_KEY', DEFAULT_API_KEY))

    def test_polygons_CRUD(self):

        mgr = self.__owm.agro_manager()

        # check if any previous polygon exists on this account
        n_old_polygons = len(mgr.get_polygons())

        # create pol1
        geopol1 = GeoPolygon([[[-121.1958, 37.6683], [-121.1779, 37.6687],
                               [-121.1773, 37.6792], [-121.1958, 37.6792],
                               [-121.1958, 37.6683]]])
        pol1 = mgr.create_polygon(geopol1, 'polygon_1')

        # create pol2
        geopol2 = GeoPolygon([[[-141.1958, 27.6683], [-141.1779, 27.6687],
                               [-141.1773, 27.6792], [-141.1958, 27.6792],
                               [-141.1958, 27.6683]]])
        pol2 = mgr.create_polygon(geopol2, 'polygon_2')

        # Read all
        polygons = mgr.get_polygons()
        self.assertEqual(n_old_polygons + 2, len(polygons))
        self.assertTrue(all([isinstance(p, Polygon) for p in polygons]))

        # Read one by one
        result = mgr.get_polygon(pol1.id)
        self.assertEqual(pol1.id, result.id)
        self.assertEqual(pol1.name, pol1.name)
        self.assertEqual(pol1.area, result.area)
        self.assertEqual(pol1.user_id, result.user_id)
        self.assertEqual(pol1.center.lon, result.center.lon)
        self.assertEqual(pol1.center.lat, result.center.lat)
        self.assertEqual(pol1.geopolygon.geojson(),
                         result.geopolygon.geojson())

        result = mgr.get_polygon(pol2.id)
        self.assertEqual(pol2.id, result.id)
        self.assertEqual(pol2.name, result.name)
        self.assertEqual(pol2.area, result.area)
        self.assertEqual(pol2.user_id, result.user_id)
        self.assertEqual(pol2.center.lon, result.center.lon)
        self.assertEqual(pol2.center.lat, result.center.lat)
        self.assertEqual(pol2.geopolygon.geojson(),
                         result.geopolygon.geojson())

        # Update a polygon
        pol2.name = 'a better name'
        mgr.update_polygon(pol2)
        result = mgr.get_polygon(pol2.id)
        self.assertEqual(pol2.id, result.id)
        self.assertEqual(pol2.area, result.area)
        self.assertEqual(pol2.user_id, result.user_id)
        self.assertEqual(pol2.center.lon, result.center.lon)
        self.assertEqual(pol2.center.lat, result.center.lat)
        self.assertEqual(pol2.geopolygon.geojson(),
                         result.geopolygon.geojson())
        self.assertNotEqual(pol2.name,
                            pol1.name)  # of course, the name has changed

        # Delete polygons one by one
        mgr.delete_polygon(pol1)
        polygons = mgr.get_polygons()
        self.assertEqual(n_old_polygons + 1, len(polygons))

        mgr.delete_polygon(pol2)
        polygons = mgr.get_polygons()
        self.assertEqual(n_old_polygons, len(polygons))
Beispiel #14
0
class IntegrationTestsStationsAPI30(unittest.TestCase):

    __owm = OWM25(parsers, os.getenv('OWM_API_KEY', DEFAULT_API_KEY))

    def test_stations_CRUD(self):

        mgr = self.__owm.stations_manager()

        # check if any previous station exists on this account
        n_old_stations = len(mgr.get_stations())

        # create stat1
        stat1 = mgr.create_station('PYOWM1', 'pyowm_test_station_1', 45.0, 9.0,
                                   189.0)

        # create stat2
        stat2 = mgr.create_station('PYOWM2', 'pyowm_test_station_2', 46.0,
                                   18.0, 50.0)

        # Read all
        stations = mgr.get_stations()
        self.assertEqual(n_old_stations + 2, len(stations))

        # Read one by one
        result = mgr.get_station(stat1.id)
        self.assertEqual(stat1.id, result.id)
        self.assertEqual(stat1.external_id, result.external_id)
        self.assertEqual(stat1.name, result.name)
        self.assertEqual(stat1.lat, result.lat)
        self.assertEqual(stat1.lon, result.lon)
        self.assertEqual(stat1.alt, result.alt)

        result = mgr.get_station(stat2.id)
        self.assertEqual(stat2.id, result.id)
        self.assertEqual(stat2.external_id, result.external_id)
        self.assertEqual(stat2.name, result.name)
        self.assertEqual(stat2.lat, result.lat)
        self.assertEqual(stat2.lon, result.lon)
        self.assertEqual(stat2.alt, result.alt)

        # Update a station
        modified_stat2 = copy.deepcopy(stat2)
        modified_stat2.eternal = 'modified_pyowm_test_station_2'
        modified_stat2.lat = 30.6
        mgr.update_station(modified_stat2)
        result = mgr.get_station(modified_stat2.id)
        self.assertEqual(modified_stat2.id, result.id)
        self.assertEqual(modified_stat2.external_id, result.external_id)
        self.assertEqual(modified_stat2.name, result.name)
        # of course, lat had been modified
        self.assertEqual(modified_stat2.lon, result.lon)
        self.assertEqual(modified_stat2.alt, result.alt)

        # Delete stations one by one
        mgr.delete_station(stat1)
        stations = mgr.get_stations()
        self.assertEqual(n_old_stations + 1, len(stations))

        mgr.delete_station(modified_stat2)
        stations = mgr.get_stations()
        self.assertEqual(n_old_stations, len(stations))

    def test_measurements_and_buffers(self):
        mgr = self.__owm.stations_manager()

        # check if any previous station exists on this account
        n_old_stations = len(mgr.get_stations())

        # create station
        test_station = mgr.create_station('PYOWM_TEST_BUFFERS',
                                          'pyowm_test_buffers', 45.0, 9.0,
                                          189.0)

        # create and bufferize some measurements for the test station
        buf = Buffer(test_station.id)
        buf.append_from_dict(
            dict(station_id=test_station.id,
                 timestamp=1505231630,
                 temperature=100,
                 wind_speed=2.1,
                 wind_gust=67,
                 humidex=77))
        buf.append_from_dict(
            dict(station_id=test_station.id,
                 timestamp=1505429694,
                 temperature=100,
                 wind_speed=2.1,
                 wind_gust=67,
                 humidex=77))
        mgr.send_buffer(buf)

        # now directly send measurements
        measurement = Measurement.from_dict(
            dict(station_id=test_station.id,
                 timestamp=1505415230,
                 temperature=100,
                 wind_speed=2.1,
                 wind_gust=67,
                 humidex=77))
        measurements_list = [
            Measurement.from_dict(
                dict(station_id=test_station.id,
                     timestamp=1505315230,
                     temperature=100,
                     wind_speed=2.1,
                     wind_gust=67,
                     humidex=77))
        ]
        mgr.send_measurement(measurement)
        mgr.send_measurements(measurements_list)

        # read the measurements for station
        msmts = mgr.get_measurements(test_station.id, 'd', 1505200000,
                                     1505430000)
        for m in msmts:
            self.assertEqual(test_station.id, m.station_id)
            self.assertEqual('d', m.aggregated_on)

        # Delete stations one by one
        mgr.delete_station(test_station)
        stations = mgr.get_stations()
        self.assertEqual(n_old_stations, len(stations))
Beispiel #15
0
class IntegrationTestsSatelliteImageryDownload(unittest.TestCase):

    __owm = OWM25(parsers, os.getenv('OWM_API_KEY', DEFAULT_API_KEY))
    __polygon = None
    __acquired_from = 1500336000  # 18 July 2017
    __acquired_to = 1508976000  # 26 October 2017

    @classmethod
    def setUpClass(cls):
        # create a polygon
        mgr = cls.__owm.agro_manager()
        geopol = GeoPolygon([[[-121.1958, 37.6683], [-121.1779, 37.6687],
                              [-121.1773, 37.6792], [-121.1958, 37.6792],
                              [-121.1958, 37.6683]]])
        cls.__polygon = mgr.create_polygon(geopol, 'search_test_polygon')

    @classmethod
    def tearDownClass(cls):
        # delete the polygon
        mgr = cls.__owm.agro_manager()
        mgr.delete_polygon(cls.__polygon)

    # Test methods

    def test_download_png(self):
        mgr = self.__owm.agro_manager()

        # search PNG, truecolor, non-tile images acquired by Landsat 8
        result_set = mgr.search_satellite_imagery(
            self.__polygon.id, self.__acquired_from, self.__acquired_to,
            ImageTypeEnum.PNG, PresetEnum.TRUE_COLOR, None, None,
            SatelliteEnum.LANDSAT_8.symbol, None, None, None, None)
        self.assertIsInstance(result_set, list)
        self.assertEqual(len(result_set), 14)

        # just keep the non-tile images
        non_tile_pngs = [
            mimg for mimg in result_set if isinstance(mimg, MetaPNGImage)
        ]
        self.assertEqual(len(non_tile_pngs), 7)

        # download one
        result = mgr.download_satellite_image(non_tile_pngs[0])

        self.assertIsInstance(result, SatelliteImage)
        self.assertIsInstance(result.metadata, MetaPNGImage)
        img = result.data
        self.assertIsInstance(img, Image)
        self.assertEqual(img.image_type, ImageTypeEnum.PNG)
        self.assertNotEqual(len(img.data), 0)

    def test_download_geotiff(self):
        mgr = self.__owm.agro_manager()

        # search GeoTiff, EVIimages acquired by Landsat 8
        result_set = mgr.search_satellite_imagery(
            self.__polygon.id, self.__acquired_from, self.__acquired_to,
            ImageTypeEnum.GEOTIFF, PresetEnum.EVI, None, None,
            SatelliteEnum.LANDSAT_8.symbol, None, None, None, None)
        self.assertIsInstance(result_set, list)
        self.assertEqual(len(result_set), 7)

        # download one
        result = mgr.download_satellite_image(
            result_set[0], palette=PaletteEnum.CONTRAST_SHIFTED)

        self.assertIsInstance(result, SatelliteImage)
        self.assertIsInstance(result.metadata, MetaGeoTiffImage)
        img = result.data
        self.assertIsInstance(img, Image)
        self.assertEqual(img.image_type, ImageTypeEnum.GEOTIFF)
        self.assertNotEqual(len(img.data), 0)

    def test_download_tile(self):
        mgr = self.__owm.agro_manager()

        # search PNG, truecolor, tile images acquired by Landsat 8
        result_set = mgr.search_satellite_imagery(
            self.__polygon.id, self.__acquired_from, self.__acquired_to,
            ImageTypeEnum.PNG, PresetEnum.TRUE_COLOR, None, None,
            SatelliteEnum.LANDSAT_8.symbol, None, None, None, None)
        self.assertIsInstance(result_set, list)
        self.assertEqual(len(result_set), 14)

        # just keep the tiles
        tile_pngs = [mimg for mimg in result_set if isinstance(mimg, MetaTile)]
        self.assertEqual(len(tile_pngs), 7)

        # try to download one without specifying x, y and zoom
        with self.assertRaises(AssertionError):
            mgr.download_satellite_image(tile_pngs[0])
        with self.assertRaises(AssertionError):
            mgr.download_satellite_image(tile_pngs[0], x=1)
        with self.assertRaises(AssertionError):
            mgr.download_satellite_image(tile_pngs[0], x=1, y=2)

        # download one
        result = mgr.download_satellite_image(tile_pngs[1], x=1, y=2, zoom=5)

        self.assertIsInstance(result, SatelliteImage)
        self.assertIsInstance(result.metadata, MetaTile)
        img = result.data
        self.assertIsInstance(img, Image)
        self.assertEqual(img.image_type, ImageTypeEnum.PNG)
        self.assertNotEqual(len(img.data), 0)

    def test_persisting_to_disk(self):
        path = '%s.tif' % uuid.uuid4()
        mgr = self.__owm.agro_manager()

        # search GeoTiff, EVIimages acquired by Landsat 8
        result_set = mgr.search_satellite_imagery(
            self.__polygon.id, self.__acquired_from, self.__acquired_to,
            ImageTypeEnum.GEOTIFF, PresetEnum.EVI, None, None,
            SatelliteEnum.LANDSAT_8.symbol, None, None, None, None)
        self.assertTrue(len(result_set) > 1)
        metaimg = result_set[0]
        sat_img = mgr.download_satellite_image(metaimg)
        try:
            self.assertFalse(os.path.isfile(path))
            sat_img.persist(path)
            self.assertTrue(os.path.isfile(path))
        except:
            self.fail()
        finally:
            os.remove(path)
class IntegrationTestsSatelliteImagerySearch(unittest.TestCase):

    __owm = OWM25(parsers, os.getenv('OWM_API_KEY', DEFAULT_API_KEY))
    __polygon = None
    __acquired_from = 1500336000  # 18 July 2017
    __acquired_to = 1508976000  # 26 October 2017

    @classmethod
    def setUpClass(cls):
        # create a polygon
        mgr = cls.__owm.agro_manager()
        geopol = GeoPolygon([[[-121.1958, 37.6683], [-121.1779, 37.6687],
                              [-121.1773, 37.6792], [-121.1958, 37.6792],
                              [-121.1958, 37.6683]]])
        cls.__polygon = mgr.create_polygon(geopol, 'search_test_polygon')

    @classmethod
    def tearDownClass(cls):
        # delete the polygon
        mgr = cls.__owm.agro_manager()
        mgr.delete_polygon(cls.__polygon)

    # Test methods

    def test_search_all(self):
        mgr = self.__owm.agro_manager()

        # search all images in the specified time frame
        result_set = mgr.search_satellite_imagery(self.__polygon.id,
                                                  self.__acquired_from,
                                                  self.__acquired_to)
        self.assertIsInstance(result_set, list)
        self.assertEqual(len(result_set), 132)
        self.assertTrue(all([isinstance(i, MetaImage) for i in result_set]))

    def test_search_for_one_satellite(self):
        mgr = self.__owm.agro_manager()

        # search all Landsat 8 images in the specified time frame
        result_set = mgr.search_satellite_imagery(
            self.__polygon.id, self.__acquired_from, self.__acquired_to, None,
            None, None, None, SatelliteEnum.LANDSAT_8.symbol, None, None, None,
            None)
        self.assertIsInstance(result_set, list)
        self.assertEqual(len(result_set), 84)
        self.assertTrue(
            all([
                isinstance(i, MetaImage)
                and i.satellite_name == SatelliteEnum.LANDSAT_8.name
                for i in result_set
            ]))

    def test_search_for_geotiff_type_only(self):
        mgr = self.__owm.agro_manager()

        # search all geotiff images in the specified time frame
        result_set = mgr.search_satellite_imagery(self.__polygon.id,
                                                  self.__acquired_from,
                                                  self.__acquired_to,
                                                  ImageTypeEnum.GEOTIFF, None,
                                                  None, None, None, None, None,
                                                  None, None)
        self.assertIsInstance(result_set, list)
        self.assertEqual(len(result_set), 44)
        self.assertTrue(
            all([
                isinstance(i, MetaImage)
                and i.image_type == ImageTypeEnum.GEOTIFF for i in result_set
            ]))

    def test_search_for_ndvi_preset_only(self):
        mgr = self.__owm.agro_manager()

        # search all NDVI images in the specified time frame
        result_set = mgr.search_satellite_imagery(self.__polygon.id,
                                                  self.__acquired_from,
                                                  self.__acquired_to, None,
                                                  PresetEnum.NDVI, None, None,
                                                  None, None, None, None, None)
        self.assertIsInstance(result_set, list)
        self.assertEqual(len(result_set), 33)
        self.assertTrue(
            all([
                isinstance(i, MetaImage) and i.preset == PresetEnum.NDVI
                for i in result_set
            ]))

    def test_search_for_falsecolor_png_only(self):
        mgr = self.__owm.agro_manager()

        # search all PNG images in falsecolor in the specified time frame
        result_set = mgr.search_satellite_imagery(
            self.__polygon.id, self.__acquired_from, self.__acquired_to,
            ImageTypeEnum.PNG, PresetEnum.FALSE_COLOR, None, None, None, None,
            None, None, None)
        self.assertIsInstance(result_set, list)
        self.assertEqual(len(result_set), 22)
        self.assertTrue(
            all([
                isinstance(i, MetaImage) and i.preset == PresetEnum.FALSE_COLOR
                and i.image_type == ImageTypeEnum.PNG for i in result_set
            ]))

    def test_detailed_search(self):
        mgr = self.__owm.agro_manager()

        # in the specified time frame, search all PNG images in truecolor acquired by Sentinel 2
        # and with a max cloud coverage of 5% and at least 90% of valid data coverage
        result_set = mgr.search_satellite_imagery(
            self.__polygon.id, self.__acquired_from, self.__acquired_to,
            ImageTypeEnum.PNG, PresetEnum.TRUE_COLOR, None, None,
            SatelliteEnum.SENTINEL_2.symbol, None, 5, 90, None)
        self.assertIsInstance(result_set, list)
        self.assertEqual(len(result_set), 8)
        self.assertTrue(
            all([
                isinstance(i, MetaImage) and i.preset == PresetEnum.TRUE_COLOR
                and i.image_type == ImageTypeEnum.PNG
                and i.satellite_name == SatelliteEnum.SENTINEL_2.name
                and i.cloud_coverage_percentage <= 5
                and i.valid_data_percentage >= 90 for i in result_set
            ]))