from bs4 import BeautifulSoup as Soup from datasette.app import Datasette from datasette.utils import allowed_pragmas from .fixtures import make_app_client from .utils import assert_footer_links, inner_html import copy import json import pathlib import pytest import re import urllib.parse def test_homepage(app_client_two_attached_databases): response = app_client_two_attached_databases.get("/") assert response.status_code == 200 assert "text/html; charset=utf-8" == response.headers["content-type"] # Should have a html lang="en" attribute assert '' in response.text soup = Soup(response.content, "html.parser") assert "Datasette Fixtures" == soup.find("h1").text assert ( "An example SQLite database demonstrating Datasette. Sign in as root user" == soup.select(".metadata-description")[0].text.strip() ) # Should be two attached databases assert [ {"href": "/extra+database", "text": "extra database"}, {"href": "/fixtures", "text": "fixtures"}, ] == [{"href": a["href"], "text": a.text.strip()} for a in soup.select("h2 a")] # Database should show count text and attached tables h2 = soup.select("h2")[0] assert "extra database" == h2.text.strip() counts_p, links_p = h2.find_all_next("p")[:2] assert ( "2 rows in 1 table, 5 rows in 4 hidden tables, 1 view" == counts_p.text.strip() ) # We should only show visible, not hidden tables here: table_links = [ {"href": a["href"], "text": a.text.strip()} for a in links_p.find_all("a") ] assert [ {"href": r"/extra+database/searchable", "text": "searchable"}, {"href": r"/extra+database/searchable_view", "text": "searchable_view"}, ] == table_links @pytest.mark.asyncio @pytest.mark.parametrize("path", ("/", "/-/")) async def test_homepage_alternative_location(path, tmp_path_factory): template_dir = tmp_path_factory.mktemp("templates") (template_dir / "index.html").write_text("Custom homepage", "utf-8") datasette = Datasette(template_dir=str(template_dir)) response = await datasette.client.get(path) assert response.status_code == 200 html = response.text if path == "/": assert html == "Custom homepage" else: assert '' in html @pytest.mark.asyncio async def test_homepage_alternative_redirect(ds_client): response = await ds_client.get("/-") assert response.status_code == 301 @pytest.mark.asyncio async def test_http_head(ds_client): response = await ds_client.head("/") assert response.status_code == 200 @pytest.mark.asyncio async def test_homepage_options(ds_client): response = await ds_client.options("/") assert response.status_code == 200 assert response.text == "ok" @pytest.mark.asyncio async def test_favicon(ds_client): response = await ds_client.get("/favicon.ico") assert response.status_code == 200 assert response.headers["cache-control"] == "max-age=3600, immutable, public" assert int(response.headers["content-length"]) > 100 assert response.headers["content-type"] == "image/png" @pytest.mark.asyncio async def test_static(ds_client): response = await ds_client.get("/-/static/app2.css") assert response.status_code == 404 response = await ds_client.get("/-/static/app.css") assert response.status_code == 200 assert "text/css" == response.headers["content-type"] assert "etag" in response.headers etag = response.headers.get("etag") response = await ds_client.get("/-/static/app.css", headers={"if-none-match": etag}) assert response.status_code == 304 def test_static_mounts(): with make_app_client( static_mounts=[("custom-static", str(pathlib.Path(__file__).parent))] ) as client: response = client.get("/custom-static/test_html.py") assert response.status_code == 200 response = client.get("/custom-static/not_exists.py") assert response.status_code == 404 response = client.get("/custom-static/../LICENSE") assert response.status_code == 404 def test_memory_database_page(): with make_app_client(memory=True) as client: response = client.get("/_memory") assert response.status_code == 200 def test_not_allowed_methods(): with make_app_client(memory=True) as client: for method in ("post", "put", "patch", "delete"): response = client.request(path="/_memory", method=method.upper()) assert response.status_code == 405 @pytest.mark.asyncio async def test_database_page(ds_client): response = await ds_client.get("/fixtures") soup = Soup(response.text, "html.parser") # Should have a ', ] for expected_html_fragment in expected_html_fragments: assert expected_html_fragment in response.text def test_row_page_does_not_truncate(): with make_app_client(settings={"truncate_cells_html": 5}) as client: response = client.get("/fixtures/facetable/1") assert response.status_code == 200 table = Soup(response.content, "html.parser").find("table") assert table["class"] == ["rows-and-columns"] assert ["Mission"] == [ td.string for td in table.find_all("td", {"class": "col-neighborhood-b352a7"}) ] def test_query_page_truncates(): with make_app_client(settings={"truncate_cells_html": 5}) as client: response = client.get( "/fixtures/-/query?" + urllib.parse.urlencode( { "sql": "select 'this is longer than 5' as a, 'https://example.com/' as b" } ) ) assert response.status_code == 200 table = Soup(response.content, "html.parser").find("table") tds = table.find_all("td") assert [str(td) for td in tds] == [ 'this …', 'http…', ] @pytest.mark.asyncio async def test_query_page_with_no_sql(ds_client): # https://github.com/simonw/datasette/issues/2743 response = await ds_client.get("/fixtures/-/query") assert response.status_code == 200 assert '" in html assert "0 results" not in html def test_config_template_debug_on(): with make_app_client(settings={"template_debug": True}) as client: response = client.get("/fixtures/facetable?_context=1") assert response.status_code == 200 assert response.text.startswith("
{")


@pytest.mark.asyncio
async def test_config_template_debug_off(ds_client):
    response = await ds_client.get("/fixtures/facetable?_context=1")
    assert response.status_code == 200
    assert not response.text.startswith("
{")


def test_debug_context_includes_extra_template_vars():
    # https://github.com/simonw/datasette/issues/693
    with make_app_client(settings={"template_debug": True}) as client:
        response = client.get("/fixtures/facetable?_context=1")
        # scope_path is added by PLUGIN1
        assert "scope_path" in response.text


@pytest.mark.parametrize(
    "path",
    [
        "/",
        "/fixtures",
        "/fixtures/compound_three_primary_keys",
        "/fixtures/compound_three_primary_keys/a,a,a",
        "/fixtures/paginated_view",
        "/fixtures/facetable",
        "/fixtures/facetable?_facet=state",
        "/fixtures/-/query?sql=select+1",
    ],
)
@pytest.mark.parametrize("use_prefix", (True, False))
def test_base_url_config(app_client_base_url_prefix, path, use_prefix):
    client = app_client_base_url_prefix
    path_to_get = path
    if use_prefix:
        path_to_get = "/prefix/" + path.lstrip("/")
    response = client.get(path_to_get)
    soup = Soup(response.content, "html.parser")
    for form in soup.select("form"):
        action = form.get("action")
        if action is None:
            assert form.get("method") == "dialog", json.dumps(
                {
                    "path": path,
                    "path_to_get": path_to_get,
                    "form": str(form),
                },
                indent=4,
                default=repr,
            )
            continue
        assert action.startswith("/prefix"), json.dumps(
            {
                "path": path,
                "path_to_get": path_to_get,
                "action": action,
                "form": str(form),
            },
            indent=4,
            default=repr,
        )
    for el in soup.find_all(["a", "link", "script"]):
        if "href" in el.attrs:
            href = el["href"]
        elif "src" in el.attrs:
            href = el["src"]
        else:
            continue  # Could be a 
        if (
            not href.startswith("#")
            and href
            not in {
                "https://datasette.io/",
                "https://github.com/simonw/datasette",
                "https://github.com/simonw/datasette/blob/main/LICENSE",
                "https://github.com/simonw/datasette/blob/main/tests/fixtures.py",
                "/login-as-root",  # Only used for the latest.datasette.io demo
            }
            and not href.startswith("https://plugin-example.datasette.io/")
        ):
            # If this has been made absolute it may start http://localhost/
            if href.startswith("http://localhost/"):
                href = href[len("http://localost/") :]
            assert href.startswith("/prefix/"), json.dumps(
                {
                    "path": path,
                    "path_to_get": path_to_get,
                    "href_or_src": href,
                    "element_parent": str(el.parent),
                },
                indent=4,
                default=repr,
            )


def test_base_url_affects_filter_redirects(app_client_base_url_prefix):
    path = "/fixtures/binary_data?_filter_column=rowid&_filter_op=exact&_filter_value=1&_sort=rowid"
    response = app_client_base_url_prefix.get(path)
    assert response.status_code == 302
    assert (
        response.headers["location"]
        == "/prefix/fixtures/binary_data?_sort=rowid&rowid__exact=1"
    )


def test_base_url_affects_metadata_extra_css_urls(app_client_base_url_prefix):
    html = app_client_base_url_prefix.get("/").text
    assert '' in html


@pytest.mark.asyncio
@pytest.mark.parametrize(
    "path,expected",
    [
        (
            "/fixtures/neighborhood_search",
            "/fixtures/-/query?sql=%0Aselect+_neighborhood%2C+facet_cities.name%2C+state%0Afrom+facetable%0A++++join+facet_cities%0A++++++++on+facetable._city_id+%3D+facet_cities.id%0Awhere+_neighborhood+like+%27%25%27+%7C%7C+%3Atext+%7C%7C+%27%25%27%0Aorder+by+_neighborhood%3B%0A&text=",
        ),
        (
            "/fixtures/neighborhood_search?text=ber",
            "/fixtures/-/query?sql=%0Aselect+_neighborhood%2C+facet_cities.name%2C+state%0Afrom+facetable%0A++++join+facet_cities%0A++++++++on+facetable._city_id+%3D+facet_cities.id%0Awhere+_neighborhood+like+%27%25%27+%7C%7C+%3Atext+%7C%7C+%27%25%27%0Aorder+by+_neighborhood%3B%0A&text=ber",
        ),
        ("/fixtures/pragma_cache_size", None),
        (
            # /fixtures/𝐜𝐢𝐭𝐢𝐞𝐬
            "/fixtures/~F0~9D~90~9C~F0~9D~90~A2~F0~9D~90~AD~F0~9D~90~A2~F0~9D~90~9E~F0~9D~90~AC",
            "/fixtures/-/query?sql=select+id%2C+name+from+facet_cities+order+by+id+limit+1%3B",
        ),
        ("/fixtures/magic_parameters", None),
    ],
)
async def test_edit_sql_link_on_stored_queries(ds_client, path, expected):
    response = await ds_client.get(path)
    assert response.status_code == 200
    expected_link = f'Edit SQL'
    if expected:
        assert expected_link in response.text
    else:
        assert "Edit SQL" not in response.text


@pytest.mark.parametrize(
    "has_permission",
    [
        pytest.param(
            True,
        ),
        False,
    ],
)
def test_edit_sql_link_not_shown_if_user_lacks_permission(has_permission):
    with make_app_client(
        config={
            "allow_sql": None if has_permission else {"id": "not-you"},
            "databases": {"fixtures": {"queries": {"simple": "select 1 + 1"}}},
        }
    ) as client:
        response = client.get("/fixtures/simple")
        if has_permission:
            assert "Edit SQL" in response.text
        else:
            assert "Edit SQL" not in response.text


@pytest.mark.asyncio
@pytest.mark.parametrize(
    "actor_id,should_have_links,should_not_have_links",
    [
        (None, None, None),
        ("test", None, ["/-/permissions"]),
        ("root", None, ["/-/permissions", "/-/allow-debug"]),
    ],
)
async def test_navigation_menu_links(
    ds_client, actor_id, should_have_links, should_not_have_links
):
    # Enable root user if testing with root actor
    if actor_id == "root":
        ds_client.ds.root_enabled = True
    kwargs = {}
    if actor_id:
        kwargs["actor"] = {"id": actor_id}
    html = (await ds_client.get("/", **kwargs)).text
    soup = Soup(html, "html.parser")
    details = soup.find("nav").find("details", {"class": "nav-menu"})
    assert details is not None
    search_button = details.find("button", {"data-navigation-search-open": True})
    assert search_button is not None
    assert search_button.text.strip() == "Jump to... /"
    assert search_button.find("kbd", {"class": "keyboard-shortcut"}).text == "/"
    assert search_button.find("kbd")["aria-hidden"] == "true"
    assert (
        search_button.find("kbd")["title"]
        == "Keyboard shortcut: press / to open Jump to"
    )
    navigation_search_script = soup.find(
        "script", {"src": re.compile(r"navigation-search\.js")}
    )
    assert navigation_search_script["src"] == "/-/static/navigation-search.js"
    assert details.find("li").find("button") == search_button
    if not actor_id:
        # The app menu is always visible, but anonymous users do not see logout
        # or debug links.
        assert details.find("form") is None
        return
    # They are logged in: should show a menu
    assert details is not None
    # And a logout form
    assert details.find("form") is not None
    if should_have_links:
        for link in should_have_links:
            assert (
                details.find("a", {"href": link}) is not None
            ), f"{link} expected but missing from nav menu"

    if should_not_have_links:
        for link in should_not_have_links:
            assert (
                details.find("a", {"href": link}) is None
            ), f"{link} found but should not have been in nav menu"


@pytest.mark.asyncio
async def test_trace_correctly_escaped(ds_client):
    response = await ds_client.get("/fixtures/-/query?sql=select+'

Hello'&_trace=1") assert "select '

Hello" not in response.text assert "select '<h1>Hello" in response.text @pytest.mark.asyncio @pytest.mark.parametrize( "path,expected", ( # Instance index page ("/", "http://localhost/.json"), # Table page ("/fixtures/facetable", "http://localhost/fixtures/facetable.json"), ( "/fixtures/table~2Fwith~2Fslashes~2Ecsv", "http://localhost/fixtures/table~2Fwith~2Fslashes~2Ecsv.json", ), # Row page ( "/fixtures/no_primary_key/1", "http://localhost/fixtures/no_primary_key/1.json", ), # Database index page ( "/fixtures", "http://localhost/fixtures.json", ), # Custom query page ( "/fixtures/-/query?sql=select+*+from+facetable", "http://localhost/fixtures/-/query.json?sql=select+*+from+facetable", ), # Stored query page ( "/fixtures/neighborhood_search?text=town", "http://localhost/fixtures/neighborhood_search.json?text=town", ), # /-/ pages ( "/-/plugins", "http://localhost/-/plugins.json", ), ), ) async def test_alternate_url_json(ds_client, path, expected): response = await ds_client.get(path) assert response.status_code == 200 link = response.headers["link"] assert link == '<{}>; rel="alternate"; type="application/json+datasette"'.format( expected ) assert ( ''.format( expected ) in response.text ) @pytest.mark.asyncio @pytest.mark.parametrize( "path", ("/-/patterns", "/-/messages", "/-/allow-debug", "/fixtures.db"), ) async def test_no_alternate_url_json(ds_client, path): response = await ds_client.get(path) assert "link" not in response.headers assert ( 'Name" in response.text assert "view-instance" in response.text assert "view-database" in response.text finally: ds_client.ds.root_enabled = original_root_enabled @pytest.mark.asyncio async def test_actions_page_does_not_display_none_string(ds_client): """Ensure the Resource column doesn't display the string 'None' for null values.""" # https://github.com/simonw/datasette/issues/2599 original_root_enabled = ds_client.ds.root_enabled try: ds_client.ds.root_enabled = True response = await ds_client.get("/-/actions", actor={"id": "root"}) assert response.status_code == 200 assert "None" not in response.text finally: ds_client.ds.root_enabled = original_root_enabled @pytest.mark.asyncio async def test_permission_debug_tabs_with_query_string(ds_client): """Test that navigation tabs persist query strings across Check, Allowed, and Rules pages""" original_root_enabled = ds_client.ds.root_enabled try: ds_client.ds.root_enabled = True actor = {"id": "root"} # Test /-/allowed with query string response = await ds_client.get( "/-/allowed?action=view-table&page_size=50", actor=actor ) assert response.status_code == 200 # Check that Rules and Check tabs have the query string assert 'href="/-/rules?action=view-table&page_size=50"' in response.text assert 'href="/-/check?action=view-table&page_size=50"' in response.text # Playground and Actions should not have query string assert 'href="/-/permissions"' in response.text assert 'href="/-/actions"' in response.text # Test /-/rules with query string response = await ds_client.get( "/-/rules?action=view-database&parent=test", actor=actor ) assert response.status_code == 200 # Check that Allowed and Check tabs have the query string assert 'href="/-/allowed?action=view-database&parent=test"' in response.text assert 'href="/-/check?action=view-database&parent=test"' in response.text # Test /-/check with query string response = await ds_client.get("/-/check?action=execute-sql", actor=actor) assert response.status_code == 200 # Check that Allowed and Rules tabs have the query string assert 'href="/-/allowed?action=execute-sql"' in response.text assert 'href="/-/rules?action=execute-sql"' in response.text finally: ds_client.ds.root_enabled = original_root_enabled