Skip to content

Commit

Permalink
add tests
Browse files Browse the repository at this point in the history
  • Loading branch information
vincentsarago committed Mar 21, 2024
1 parent d19ad05 commit e6e8820
Show file tree
Hide file tree
Showing 11 changed files with 370 additions and 3 deletions.
1 change: 1 addition & 0 deletions tests/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
"""titiler.stacapi tests."""
17 changes: 17 additions & 0 deletions tests/conftest.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,13 @@
"""titiler.stacapi tests configuration."""

import os

import pytest
import rasterio
from fastapi.testclient import TestClient

DATA_DIR = os.path.join(os.path.dirname(__file__), "fixtures")


@pytest.fixture
def app(monkeypatch):
Expand All @@ -13,3 +18,15 @@ def app(monkeypatch):

with TestClient(app) as client:
yield client


def mock_rasterio_open(asset):
"""Mock rasterio Open."""
assert asset.startswith(
"https://noaa-eri-pds.s3.us-east-1.amazonaws.com/2020_Nashville_Tornado/20200307a_RGB/"
)
asset = asset.replace(
"https://noaa-eri-pds.s3.us-east-1.amazonaws.com/2020_Nashville_Tornado/20200307a_RGB",
DATA_DIR,
)
return rasterio.open(asset)
1 change: 1 addition & 0 deletions tests/fixtures/20200307aC0853900w361030.json
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{"type":"Feature","stac_version":"1.0.0","id":"20200307aC0853900w361030","properties":{"event":"Nashville Tornado","datetime":"2020-03-07T00:00:00Z"},"geometry":{"type":"Polygon","coordinates":[[[-85.6501,36.1751],[-85.6501,36.1499],[-85.6249,36.1499],[-85.6249,36.1751],[-85.6501,36.1751]]]},"links":[{"rel":"collection","href":"noaa-emergency-response","type":"application/json"}],"assets":{"cog":{"href":"https://noaa-eri-pds.s3.us-east-1.amazonaws.com/2020_Nashville_Tornado/20200307a_RGB/20200307aC0853900w361030n.tif","type":"image/tiff; application=geotiff; profile=cloud-optimized"}},"bbox":[-85.6501,36.1499,-85.6249,36.1751],"stac_extensions":[],"collection":"noaa-emergency-response"}
Binary file added tests/fixtures/20200307aC0853900w361030n.tif
Binary file not shown.
1 change: 1 addition & 0 deletions tests/fixtures/noaa-emergency-response.json
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{"id":"noaa-emergency-response", "title": "NOAA Emergency Response Imagery", "description":"NOAA Emergency Response Imagery hosted on AWS Public Dataset.","stac_version":"1.0.0","license":"public-domain","links":[],"extent":{"spatial":{"bbox":[[-180,-90,180,90]]},"temporal":{"interval":[["2005-01-01T00:00:00Z",null]]}}}
163 changes: 163 additions & 0 deletions tests/fixtures/noaa-eri-nashville2020.json

Large diffs are not rendered by default.

50 changes: 50 additions & 0 deletions tests/test_backend.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
"""test titiler-stacapi mosaic backend."""

import json
import os
from unittest.mock import patch

from geojson_pydantic import Polygon

from titiler.stacapi.backend import STACAPIBackend

from .conftest import mock_rasterio_open

item_json = os.path.join(
os.path.dirname(__file__), "fixtures", "20200307aC0853900w361030.json"
)


@patch("rio_tiler.io.rasterio.rasterio")
@patch("titiler.stacapi.backend.STACAPIBackend.get_assets")
def test_stac_backend(get_assets, rio):
"""test STACAPIBackend."""
rio.open = mock_rasterio_open

with open(item_json, "r") as f:
get_assets.return_value = [json.loads(f.read())]

with STACAPIBackend("http://endpoint.stac") as stac:
pass

with STACAPIBackend("http://endpoint.stac") as stac:
assets = stac.assets_for_tile(0, 0, 0)
assert len(assets) == 1
assert isinstance(get_assets.call_args.args[0], Polygon)
assert not get_assets.call_args.kwargs

with STACAPIBackend("http://endpoint.stac") as stac:
img, assets = stac.tile(
8589,
12849,
15,
search_query={"collections": ["col"], "ids": ["20200307aC0853900w361030"]},
assets=["cog"],
)
assert assets[0]["id"] == "20200307aC0853900w361030"
assert isinstance(get_assets.call_args.args[0], Polygon)
assert get_assets.call_args.kwargs["search_query"] == {
"collections": ["col"],
"ids": ["20200307aC0853900w361030"],
}
assert img.metadata["timings"]
44 changes: 44 additions & 0 deletions tests/test_collections.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
"""Test titiler.stacapi Item endpoints."""

import json
import os
from unittest.mock import patch

from .conftest import mock_rasterio_open

item_json = os.path.join(
os.path.dirname(__file__), "fixtures", "20200307aC0853900w361030.json"
)


@patch("titiler.stacapi.factory.STACAPIBackend.get_assets")
@patch("rio_tiler.io.rasterio.rasterio")
def test_stac_collections(rio, get_assets, app):
"""test STAC items endpoints."""
rio.open = mock_rasterio_open

with open(item_json, "r") as f:
get_assets.return_value = [json.loads(f.read())]

response = app.get(
"/collections/noaa-emergency-response/tiles/WebMercatorQuad/15/8589/12849.png",
params={
"assets": "cog",
"datetime": "2024-01-01",
},
)
assert response.status_code == 200

response = app.get(
"/collections/noaa-emergency-response/WebMercatorQuad/tilejson.json",
params={
"assets": "cog",
"minzoom": 12,
"maxzoom": 14,
},
)
assert response.status_code == 200
resp = response.json()
assert resp["minzoom"] == 12
assert resp["maxzoom"] == 14
assert "?assets=cog" in resp["tiles"][0]
87 changes: 87 additions & 0 deletions tests/test_items.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
"""Test titiler.stacapi Item endpoints."""

import json
import os
from unittest.mock import patch

import pystac
import pytest
from httpx import HTTPStatusError, RequestError

from titiler.stacapi.dependencies import get_stac_item

from .conftest import mock_rasterio_open

item_json = os.path.join(
os.path.dirname(__file__), "fixtures", "20200307aC0853900w361030.json"
)


class MockResponse:
"""Mock HTTX response."""

def __init__(self, data):
"""init."""
self.data = data

def raise_for_status(self):
"""raise_for_status"""
pass

@property
def content(self):
"""return content."""
return self.data

def json(self):
"""return json."""
return json.loads(self.data)


@patch("titiler.stacapi.dependencies.httpx")
def test_get_stac_item(httpx):
"""test get_stac_item."""

with open(item_json, "r") as f:
httpx.get.return_value = MockResponse(f.read())
httpx.HTTPStatusError = HTTPStatusError
httpx.RequestError = RequestError

item = get_stac_item(
"http://endpoint.stac", "noaa-emergency-response", "20200307aC0853900w361030"
)
assert isinstance(item, pystac.Item)
assert item.id == "20200307aC0853900w361030"
assert item.collection_id == "noaa-emergency-response"


@patch("rio_tiler.io.rasterio.rasterio")
@patch("titiler.stacapi.dependencies.httpx")
def test_stac_items(httpx, rio, app):
"""test STAC items endpoints."""
rio.open = mock_rasterio_open

with open(item_json, "r") as f:
httpx.get.return_value = MockResponse(f.read())
httpx.HTTPStatusError = HTTPStatusError
httpx.RequestError = RequestError

response = app.get(
"/collections/noaa-emergency-response/items/20200307aC0853900w361030/assets",
)
assert response.status_code == 200
assert response.json() == ["cog"]

with pytest.warns(UserWarning):
response = app.get(
"/collections/noaa-emergency-response/items/20200307aC0853900w361030/info",
)
assert response.status_code == 200
assert response.json()["cog"]

response = app.get(
"/collections/noaa-emergency-response/items/20200307aC0853900w361030/info",
params={"assets": "cog"},
)
assert response.status_code == 200
assert response.json()["cog"]
3 changes: 1 addition & 2 deletions titiler/stacapi/backend.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,12 +24,11 @@
from rio_tiler.mosaic import mosaic_reader
from rio_tiler.types import AssetInfo, BBox

from titiler.stacapi.settings import CacheSettings, RetrySettings, STACAPISettings
from titiler.stacapi.settings import CacheSettings, RetrySettings
from titiler.stacapi.utils import Timer, retry

cache_config = CacheSettings()
retry_config = RetrySettings()
stacapi_config = STACAPISettings()


@attr.s
Expand Down
6 changes: 5 additions & 1 deletion titiler/stacapi/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,11 @@ class CacheSettings(BaseSettings):
# Whether or not caching is enabled
disable: bool = False

model_config = {"env_prefix": "TITILER_STACAPI_CACHE_", "env_file": ".env"}
model_config = {
"env_prefix": "TITILER_STACAPI_CACHE_",
"env_file": ".env",
"extra": "ignore",
}

@model_validator(mode="after")
def check_enable(self):
Expand Down

0 comments on commit e6e8820

Please sign in to comment.