File: test_html_mode.py

package info (click to toggle)
litestar 2.21.0-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 12,568 kB
  • sloc: python: 70,588; makefile: 254; javascript: 104; sh: 60
file content (55 lines) | stat: -rw-r--r-- 2,449 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
from __future__ import annotations

from typing import TYPE_CHECKING

from litestar.static_files import StaticFilesConfig
from litestar.status_codes import HTTP_200_OK, HTTP_404_NOT_FOUND
from litestar.testing import create_test_client
from tests.unit.test_static_files.conftest import MakeConfig

if TYPE_CHECKING:
    from pathlib import Path

    from litestar.types import FileSystemProtocol


def test_staticfiles_is_html_mode(tmpdir: Path, file_system: FileSystemProtocol, make_config: MakeConfig) -> None:
    path = tmpdir / "index.html"
    path.write_text("content", "utf-8")
    static_files_config, handlers = make_config(
        StaticFilesConfig(path="/static", directories=[tmpdir], html_mode=True, file_system=file_system)
    )

    with create_test_client(handlers, static_files_config=static_files_config) as client:
        response = client.get("/static")
        assert response.status_code == HTTP_200_OK
        assert response.text == "content"
        assert response.headers["content-type"] == "text/html; charset=utf-8"
        assert response.headers["content-disposition"].startswith("inline")


def test_staticfiles_is_html_mode_serves_404_when_present(
    tmpdir: Path, file_system: FileSystemProtocol, make_config: MakeConfig
) -> None:
    path = tmpdir / "404.html"
    path.write_text("not found", "utf-8")
    static_files_config, handlers = make_config(
        StaticFilesConfig(path="/static", directories=[tmpdir], html_mode=True, file_system=file_system)
    )
    with create_test_client(handlers, static_files_config=static_files_config) as client:
        response = client.get("/static")
        assert response.status_code == HTTP_404_NOT_FOUND
        assert response.text == "not found"
        assert response.headers["content-type"] == "text/html; charset=utf-8"


def test_staticfiles_is_html_mode_raises_exception_when_no_404_html_is_present(
    tmpdir: Path, file_system: FileSystemProtocol, make_config: MakeConfig
) -> None:
    static_files_config, handlers = make_config(
        StaticFilesConfig(path="/static", directories=[tmpdir], html_mode=True, file_system=file_system)
    )
    with create_test_client(handlers, static_files_config=static_files_config) as client:
        response = client.get("/static")
        assert response.status_code == HTTP_404_NOT_FOUND
        assert response.json() == {"status_code": 404, "detail": "no file or directory match the path . was found"}