Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,13 @@ Issues and pull requests are more than welcome: https://github.com/developmentse
```bash
$ git clone https://github.com/developmentseed/tifeatures.git
$ cd tifeatures
$ pip install -e .[dev]
$ pip install -e .["test,dev"]
```

You can then run the tests with the following command:

```sh
python -m pytest --cov tifeatures --cov-report term-missing
```

**pre-commit**
Expand Down
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ dynamic = ["version"]
dependencies = [
"asyncpg>=0.23.0",
"buildpg>=0.3",
"fastapi>=0.73",
"fastapi>=0.77",
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

we need starlette >= 0.18, so updating fastapi

"jinja2>=2.11.2,<4.0.0",
"geojson-pydantic",
"starlette-cramjam>=0.1.0,<0.2",
Expand Down
7 changes: 7 additions & 0 deletions tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,9 +32,16 @@ def database_url(test_db):
def app(database_url, monkeypatch):
"""Create app with connection to the pytest database."""
monkeypatch.setenv("DATABASE_URL", str(database_url))
monkeypatch.setenv(
"TIFEATURES_TEMPLATE_DIRECTORY", os.path.join(DATA_DIR, "templates")
)

from tifeatures.main import app

# Remove middlewares https://github.com/encode/starlette/issues/472
app.user_middleware = []
app.middleware_stack = app.build_middleware_stack()
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There is a bug with TestClient and TemplateResponse so we need to 🔪 middleware for testing

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.


# register functions to app.state.function_catalog here

with TestClient(app) as app:
Expand Down
26 changes: 26 additions & 0 deletions tests/fixtures/templates/collections.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
{% include "header.html" %}

<h1>Custom Collections</h1>

<div class="table-responsive">
<table class="table" style="width:100%;">
<thead class="thead-light">
<tr>
<th>Title</th>
<th>Type</th>
<th>Description</th>
</tr>
</thead>
<tbody>
{% for collection in response.collections %}
<tr>
<td><a href="{{ template.api_root }}/collections/{{ collection.id }}?f=html">{{ collection.title or collection.id }}</a></td>
<td>{{ collection.itemType }}</td>
<td>{{ collection.description or collection.title or collection.id }}</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>

{% include "footer.html" %}
11 changes: 11 additions & 0 deletions tests/routes/test_templates.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
"""Test HTML templates."""


def test_custom_templates(app):
"""Test /collections endpoint."""
response = app.get("/collections")
assert response.status_code == 200

response = app.get("/collections?f=html")
assert response.status_code == 200
assert "Custom Collections" in response.text
24 changes: 18 additions & 6 deletions tifeatures/factory.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
"""tifeatures.factory: router factories."""

import json
import pathlib
from dataclasses import dataclass, field
from typing import Any, Callable, List, Optional

import jinja2

from tifeatures import model
from tifeatures.dependencies import (
CollectionParams,
Expand All @@ -19,20 +20,31 @@
from tifeatures.settings import APISettings

from fastapi import APIRouter, Depends, Path, Query
from fastapi.templating import Jinja2Templates

from starlette.datastructures import QueryParams
from starlette.requests import Request
from starlette.responses import HTMLResponse
from starlette.templating import Jinja2Templates, _TemplateResponse

template_dir = str(pathlib.Path(__file__).parent.joinpath("templates"))
templates = Jinja2Templates(directory=template_dir)
settings = APISettings()

# custom template directory
templates_location: List[Any] = (
[jinja2.FileSystemLoader(settings.template_directory)]
if settings.template_directory
else []
)
# default template directory
templates_location.append(jinja2.PackageLoader(__package__, "templates"))

templates = Jinja2Templates(
directory="", # we need to set a dummy directory variable, see https://github.com/encode/starlette/issues/1214
loader=jinja2.ChoiceLoader(templates_location),
)


def create_html_response(
request: Request, data: str, template_name: str
) -> HTMLResponse:
) -> _TemplateResponse:
"""Create Template response."""
urlpath = request.url.path
crumbs = []
Expand Down
1 change: 1 addition & 0 deletions tifeatures/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ class _APISettings(pydantic.BaseSettings):
name: str = "TiFeatures"
cors_origins: str = "*"
cachecontrol: str = "public, max-age=3600"
template_directory: Optional[str] = None

@pydantic.validator("cors_origins")
def parse_cors_origin(cls, v):
Expand Down