2017-11-10 10:48:16 -08:00
"""
Tests for various datasette helper functions .
"""
2024-01-30 19:55:26 -08:00
2026-07-25 15:47:08 -07:00
import hashlib
import json
import os
import pathlib
import tempfile
from unittest . mock import patch
import pytest
2017-11-10 11:25:54 -08:00
from datasette import utils
2026-07-25 15:47:08 -07:00
from datasette . app import Datasette
2019-06-23 20:13:09 -07:00
from datasette . utils . asgi import Request
2026-05-31 16:15:34 -07:00
from datasette . utils . sqlite import (
sqlite3 ,
sqlite_hidden_table_names ,
sqlite_table_type ,
supports_returning ,
)
2017-10-23 22:54:58 -07:00
@pytest.mark.parametrize (
" path,expected " ,
[
( " foo " , [ " foo " ] ) ,
( " foo,bar " , [ " foo " , " bar " ] ) ,
( " 123,433,112 " , [ " 123 " , " 433 " , " 112 " ] ) ,
2022-03-15 11:01:57 -07:00
( " 123~2C433,112 " , [ " 123,433 " , " 112 " ] ) ,
( " 123~2F433~2F112 " , [ " 123/433/112 " ] ) ,
2017-10-23 22:54:58 -07:00
] ,
)
2018-04-08 17:06:10 -07:00
def test_urlsafe_components ( path , expected ) :
assert expected == utils . urlsafe_components ( path )
2017-10-23 22:54:58 -07:00
2018-05-12 18:35:25 -03:00
@pytest.mark.parametrize (
" path,added_args,expected " ,
[
( " /foo " , { " bar " : 1 } , " /foo?bar=1 " ) ,
( " /foo?bar=1 " , { " baz " : 2 } , " /foo?bar=1&baz=2 " ) ,
( " /foo?bar=1&bar=2 " , { " baz " : 3 } , " /foo?bar=1&bar=2&baz=3 " ) ,
( " /foo?bar=1 " , { " bar " : None } , " /foo " ) ,
# Test order is preserved
2018-05-14 00:02:07 -03:00
(
" /?_facet=prim_state&_facet=area_name " ,
( ( " prim_state " , " GA " ) , ) ,
" /?_facet=prim_state&_facet=area_name&prim_state=GA " ,
) ,
(
" /?_facet=state&_facet=city&state=MI " ,
( ( " city " , " Detroit " ) , ) ,
" /?_facet=state&_facet=city&state=MI&city=Detroit " ,
) ,
2018-05-14 19:09:09 -03:00
(
" /?_facet=state&_facet=city " ,
2018-05-15 10:52:02 -05:00
( ( " _facet " , " planet_int " ) , ) ,
" /?_facet=state&_facet=city&_facet=planet_int " ,
) ,
2018-05-12 18:35:25 -03:00
] ,
)
def test_path_with_added_args ( path , added_args , expected ) :
2019-06-23 20:13:09 -07:00
request = Request . fake ( path )
2018-05-12 18:35:25 -03:00
actual = utils . path_with_added_args ( request , added_args )
assert expected == actual
2018-05-14 17:42:10 -03:00
@pytest.mark.parametrize (
" path,args,expected " ,
[
( " /foo?bar=1 " , { " bar " } , " /foo " ) ,
( " /foo?bar=1&baz=2 " , { " bar " } , " /foo?baz=2 " ) ,
2018-05-15 07:11:52 -03:00
( " /foo?bar=1&bar=2&bar=3 " , { " bar " : " 2 " } , " /foo?bar=1&bar=3 " ) ,
2018-05-14 17:42:10 -03:00
] ,
)
def test_path_with_removed_args ( path , args , expected ) :
2019-06-23 20:13:09 -07:00
request = Request . fake ( path )
2018-05-14 17:42:10 -03:00
actual = utils . path_with_removed_args ( request , args )
assert expected == actual
2019-03-17 15:55:04 -07:00
# Run the test again but this time use the path= argument
2019-06-23 20:13:09 -07:00
request = Request . fake ( " / " )
2019-03-17 15:55:04 -07:00
actual = utils . path_with_removed_args ( request , args , path = path )
assert expected == actual
2018-05-14 17:42:10 -03:00
2018-05-15 06:34:45 -03:00
@pytest.mark.parametrize (
" path,args,expected " ,
[
( " /foo?bar=1 " , { " bar " : 2 } , " /foo?bar=2 " ) ,
( " /foo?bar=1&baz=2 " , { " bar " : None } , " /foo?baz=2 " ) ,
] ,
)
def test_path_with_replaced_args ( path , args , expected ) :
2019-06-23 20:13:09 -07:00
request = Request . fake ( path )
2018-05-15 06:34:45 -03:00
actual = utils . path_with_replaced_args ( request , args )
assert expected == actual
2018-06-21 07:56:28 -07:00
@pytest.mark.parametrize (
" row,pks,expected_path " ,
[
( { " A " : " foo " , " B " : " bar " } , [ " A " , " B " ] , " foo,bar " ) ,
2022-03-15 11:01:57 -07:00
( { " A " : " f,o " , " B " : " bar " } , [ " A " , " B " ] , " f~2Co,bar " ) ,
2018-06-21 07:56:28 -07:00
( { " A " : 123 } , [ " A " ] , " 123 " ) ,
(
utils . CustomRow (
[ " searchable_id " , " tag " ] ,
[
( " searchable_id " , { " value " : 1 , " label " : " 1 " } ) ,
( " tag " , { " value " : " feline " , " label " : " feline " } ) ,
] ,
) ,
[ " searchable_id " , " tag " ] ,
" 1,feline " ,
) ,
] ,
)
2017-10-23 22:54:58 -07:00
def test_path_from_row_pks ( row , pks , expected_path ) :
2017-11-10 11:25:54 -08:00
actual_path = utils . path_from_row_pks ( row , pks , False )
2017-10-23 22:54:58 -07:00
assert expected_path == actual_path
2017-10-24 07:58:41 -07:00
@pytest.mark.parametrize (
" obj,expected " ,
[
(
{
" Description " : " Soft drinks " ,
" Picture " : b " \x15 \x1c \x02 \xc7 \xad \x05 \xfe " ,
" CategoryID " : 1 ,
} ,
"""
{ " CategoryID " : 1 , " Description " : " Soft drinks " , " Picture " : { " $base64 " : true , " encoded " : " FRwCx60F/g== " } }
""" .strip(),
2026-07-03 16:09:27 -07:00
) ,
(
{ " message " : b " hello " } ,
' { " message " : { " $base64 " : true, " encoded " : " aGVsbG8= " }} ' ,
) ,
2017-10-24 07:58:41 -07:00
] ,
2019-05-03 22:15:14 -04:00
)
2017-10-24 07:58:41 -07:00
def test_custom_json_encoder ( obj , expected ) :
2017-11-10 11:25:54 -08:00
actual = json . dumps ( obj , cls = utils . CustomJSONEncoder , sort_keys = True )
2017-10-24 07:58:41 -07:00
assert expected == actual
2017-10-24 17:06:23 -07:00
2017-11-04 19:49:18 -07:00
@pytest.mark.parametrize (
" bad_sql " ,
[
" update blah; " ,
2020-02-04 20:13:24 -06:00
" -- sql comment to skip \n update blah; " ,
" update blah set some_column= ' # Hello there \n \n * This is a list \n * of items \n -- \n [And a link](https://github.com/simonw/datasette-render-markdown). ' \n as demo_markdown " ,
2020-05-06 10:18:31 -07:00
" PRAGMA case_sensitive_like = true " ,
" SELECT * FROM pragma_not_on_allow_list( ' idx52 ' ) " ,
2022-10-26 14:34:33 -07:00
" /* This comment is not valid. select 1 " ,
2022-10-27 11:47:41 -07:00
" /**/ \n update foo set bar = 1 \n /* test */ select 1 " ,
2017-11-04 19:49:18 -07:00
] ,
)
def test_validate_sql_select_bad ( bad_sql ) :
2017-11-10 11:25:54 -08:00
with pytest . raises ( utils . InvalidSql ) :
utils . validate_sql_select ( bad_sql )
2017-11-04 19:49:18 -07:00
@pytest.mark.parametrize (
" good_sql " ,
[
" select count(*) from airports " ,
" select foo from bar " ,
2020-02-04 20:13:24 -06:00
" --sql comment to skip \n select foo from bar " ,
" select ' # Hello there \n \n * This is a list \n * of items \n -- \n [And a link](https://github.com/simonw/datasette-render-markdown). ' \n as demo_markdown " ,
2017-11-04 19:49:18 -07:00
" select 1 + 1 " ,
2019-10-06 10:23:58 -07:00
" explain select 1 + 1 " ,
2022-01-13 12:34:55 -08:00
" explain \n select 1 + 1 " ,
2019-10-06 10:23:58 -07:00
" explain query plan select 1 + 1 " ,
2022-01-13 12:34:55 -08:00
" explain query plan \n select 1 + 1 " ,
2017-12-03 20:51:31 -08:00
" SELECT \n blah FROM foo " ,
" WITH RECURSIVE cnt(x) AS (SELECT 1 UNION ALL SELECT x+1 FROM cnt LIMIT 10) SELECT x FROM cnt; " ,
2019-10-06 10:23:58 -07:00
" explain WITH RECURSIVE cnt(x) AS (SELECT 1 UNION ALL SELECT x+1 FROM cnt LIMIT 10) SELECT x FROM cnt; " ,
" explain query plan WITH RECURSIVE cnt(x) AS (SELECT 1 UNION ALL SELECT x+1 FROM cnt LIMIT 10) SELECT x FROM cnt; " ,
2020-05-06 10:18:31 -07:00
" SELECT * FROM pragma_index_info( ' idx52 ' ) " ,
" select * from pragma_table_xinfo( ' table ' ) " ,
2022-10-26 14:34:33 -07:00
# Various types of comment
" -- comment \n select 1 " ,
" -- one line \n -- two line \n select 1 " ,
" /* comment */ \n select 1 " ,
" /* comment */select 1 " ,
" /* comment */ \n -- another \n /* one more */ select 1 " ,
2022-10-27 11:50:54 -07:00
" /* This comment \n has multiple lines */ \n select 1 " ,
2017-11-04 19:49:18 -07:00
] ,
)
def test_validate_sql_select_good ( good_sql ) :
2017-11-10 11:25:54 -08:00
utils . validate_sql_select ( good_sql )
2017-11-19 08:59:26 -08:00
2019-09-02 17:32:27 -07:00
@pytest.mark.parametrize ( " open_quote,close_quote " , [ ( ' " ' , ' " ' ) , ( " [ " , " ] " ) ] )
def test_detect_fts ( open_quote , close_quote ) :
2026-07-25 15:47:08 -07:00
sql = f """
2017-11-19 08:59:26 -08:00
CREATE TABLE " Dumb_Table " (
" TreeID " INTEGER ,
" qSpecies " TEXT
) ;
CREATE TABLE " Street_Tree_List " (
" TreeID " INTEGER ,
" qSpecies " TEXT ,
" qAddress " TEXT ,
" SiteOrder " INTEGER ,
" qSiteInfo " TEXT ,
" PlantType " TEXT ,
" qCaretaker " TEXT
) ;
2017-11-24 14:51:00 -08:00
CREATE VIEW Test_View AS SELECT * FROM Dumb_Table ;
2026-07-25 15:47:08 -07:00
CREATE VIRTUAL TABLE { open_quote } Street_Tree_List_fts { close_quote } USING FTS4 ( " qAddress " , " qCaretaker " , " qSpecies " , content = { open_quote } Street_Tree_List { close_quote } ) ;
2017-12-06 20:54:25 -08:00
CREATE VIRTUAL TABLE r USING rtree ( a , b , c ) ;
2026-07-25 15:47:08 -07:00
"""
2018-08-15 17:58:56 -07:00
conn = utils . sqlite3 . connect ( " :memory: " )
2017-11-19 08:59:26 -08:00
conn . executescript ( sql )
assert None is utils . detect_fts ( conn , " Dumb_Table " )
2017-11-24 14:51:00 -08:00
assert None is utils . detect_fts ( conn , " Test_View " )
2017-12-06 20:54:25 -08:00
assert None is utils . detect_fts ( conn , " r " )
2017-11-19 08:59:26 -08:00
assert " Street_Tree_List_fts " == utils . detect_fts ( conn , " Street_Tree_List " )
2025-12-12 22:38:04 -08:00
conn . close ( )
2019-05-03 22:15:14 -04:00
2026-06-10 23:15:18 -07:00
@pytest.mark.parametrize (
" identifier,expected " ,
(
( " plain " , " plain " ) ,
2026-06-23 14:04:20 -07:00
( " select " , ' " select " ' ) ,
( " has space " , ' " has space " ' ) ,
( " has ' quote " , ' " has \' quote " ' ) ,
( ' has " dquote ' , ' " has " " dquote " ' ) ,
2026-06-10 23:15:18 -07:00
( " has]bracket " , ' " has]bracket " ' ) ,
( ' has " dquote] ' , ' " has " " dquote] " ' ) ,
) ,
)
def test_escape_sqlite ( identifier , expected ) :
assert utils . escape_sqlite ( identifier ) == expected
2026-06-23 14:04:20 -07:00
def test_escape_sqlite_double_quotes_work_in_query ( ) :
conn = utils . sqlite3 . connect ( " :memory: " )
table = ' table with " double quotes " '
column = " select "
escaped_table = utils . escape_sqlite ( table )
escaped_column = utils . escape_sqlite ( column )
conn . execute ( f " CREATE TABLE { escaped_table } ( { escaped_column } TEXT) " )
create_sql = conn . execute (
" SELECT sql FROM sqlite_master WHERE type = ' table ' AND name = ? " , ( table , )
) . fetchone ( ) [ 0 ]
assert create_sql == ' CREATE TABLE " table with " " double quotes " " " ( " select " TEXT) '
conn . execute (
f " INSERT INTO { escaped_table } ( { escaped_column } ) VALUES (?) " , ( " hello " , )
)
results = conn . execute ( f " SELECT { escaped_column } FROM { escaped_table } " ) . fetchall ( )
conn . close ( )
assert results == [ ( " hello " , ) ]
2026-06-10 23:15:18 -07:00
def test_escape_sqlite_prevents_injection ( ) :
# https://github.com/simonw/datasette/issues/2677
conn = utils . sqlite3 . connect ( " :memory: " )
conn . execute ( " CREATE TABLE users (id INTEGER, password TEXT) " )
conn . execute ( " INSERT INTO users VALUES (1, ' super_secret_password ' ) " )
malicious = " users] UNION SELECT password FROM users-- "
2026-07-25 15:47:08 -07:00
conn . execute ( f ' CREATE TABLE " { malicious } " (id INTEGER) ' )
sql = f " select count(*) from { utils . escape_sqlite ( malicious ) } "
2026-06-10 23:15:18 -07:00
results = conn . execute ( sql ) . fetchall ( )
conn . close ( )
# The injected UNION must not execute - only the empty malicious table
# is queried, so we get a single count row and no leaked password
assert results == [ ( 0 , ) ]
2021-06-01 20:27:04 -07:00
@pytest.mark.parametrize ( " table " , ( " regular " , " has ' single quote " ) )
def test_detect_fts_different_table_names ( table ) :
2026-07-25 15:47:08 -07:00
sql = f """
2021-06-01 20:27:04 -07:00
CREATE TABLE [ { table } ] (
" TreeID " INTEGER ,
" qSpecies " TEXT
) ;
CREATE VIRTUAL TABLE [ { table } _fts ] USING FTS4 ( " qSpecies " , content = " {table} " ) ;
2026-07-25 15:47:08 -07:00
"""
2021-06-01 20:27:04 -07:00
conn = utils . sqlite3 . connect ( " :memory: " )
conn . executescript ( sql )
2026-07-25 15:47:08 -07:00
assert f " { table } _fts " == utils . detect_fts ( conn , table )
2025-12-12 22:38:04 -08:00
conn . close ( )
2021-06-01 20:27:04 -07:00
2026-05-31 16:15:34 -07:00
def test_supports_returning ( ) :
conn = utils . sqlite3 . connect ( " :memory: " )
try :
conn . execute ( " create table t (id integer primary key) " )
conn . execute ( " insert into t default values returning id " ) . fetchone ( )
expected = True
except sqlite3 . DatabaseError :
expected = False
finally :
conn . close ( )
assert supports_returning ( ) is expected
2026-05-28 08:36:59 -07:00
@pytest.mark.parametrize ( " use_fallback " , ( False , True ) )
def test_sqlite_table_type_detects_virtual_and_shadow_tables ( monkeypatch , use_fallback ) :
if use_fallback :
monkeypatch . setattr ( " datasette.utils.sqlite.sqlite_version " , lambda : ( 3 , 25 , 0 ) )
conn = utils . sqlite3 . connect ( " :memory: " )
try :
conn . executescript ( """
create table dogs ( id integer primary key , name text ) ;
create view dog_names as select name from dogs ;
create virtual table search_index using fts5 ( title , body ) ;
create virtual table boxes using rtree ( id , minx , maxx , miny , maxy ) ;
""" )
assert sqlite_table_type ( conn , " dogs " ) == " table "
assert sqlite_table_type ( conn , " dog_names " ) == " view "
assert sqlite_table_type ( conn , " search_index " ) == " virtual "
assert sqlite_table_type ( conn , " search_index_config " ) == " shadow "
assert sqlite_table_type ( conn , " boxes " ) == " virtual "
assert sqlite_table_type ( conn , " boxes_node " ) == " shadow "
assert sqlite_table_type ( conn , " missing " ) is None
2026-05-28 08:42:06 -07:00
assert sqlite_hidden_table_names ( conn ) == [
" boxes_node " ,
" boxes_parent " ,
" boxes_rowid " ,
" search_index_config " ,
" search_index_content " ,
" search_index_data " ,
" search_index_docsize " ,
" search_index_idx " ,
]
2026-05-28 08:36:59 -07:00
finally :
conn . close ( )
@pytest.mark.parametrize ( " use_fallback " , ( False , True ) )
def test_sqlite_table_type_detects_attached_database_tables ( monkeypatch , use_fallback ) :
if use_fallback :
monkeypatch . setattr ( " datasette.utils.sqlite.sqlite_version " , lambda : ( 3 , 25 , 0 ) )
conn = utils . sqlite3 . connect ( " :memory: " )
try :
conn . executescript ( """
attach database ' :memory: ' as extra ;
create table extra . cats ( id integer primary key , name text ) ;
create virtual table extra . cat_search using fts5 ( name ) ;
""" )
assert sqlite_table_type ( conn , " cats " , schema = " extra " ) == " table "
assert sqlite_table_type ( conn , " cat_search " , schema = " extra " ) == " virtual "
assert sqlite_table_type ( conn , " cat_search_data " , schema = " extra " ) == " shadow "
finally :
conn . close ( )
2026-05-28 09:03:10 -07:00
def test_sqlite_hidden_table_names_hides_multiline_content_fts_table ( ) :
conn = utils . sqlite3 . connect ( " :memory: " )
try :
conn . executescript ( """
create table searchable ( id integer primary key , body text ) ;
create virtual table searchable_fts
using fts5 ( body , content = ' searchable ' , content_rowid = ' id ' ) ;
""" )
assert " searchable_fts " in sqlite_hidden_table_names ( conn )
finally :
conn . close ( )
2017-11-29 09:05:24 -08:00
@pytest.mark.parametrize (
" url,expected " ,
[
( " http://www.google.com/ " , True ) ,
( " https://example.com/ " , True ) ,
( " www.google.com " , False ) ,
( " http://www.google.com/ is a search engine " , False ) ,
] ,
)
def test_is_url ( url , expected ) :
assert expected == utils . is_url ( url )
2017-11-29 23:09:54 -08:00
@pytest.mark.parametrize (
" s,expected " ,
[
( " simple " , " simple " ) ,
( " MixedCase " , " MixedCase " ) ,
( " -no-leading-hyphens " , " no-leading-hyphens-65bea6 " ) ,
( " _no-leading-underscores " , " no-leading-underscores-b921bc " ) ,
( " no spaces " , " no-spaces-7088d7 " ) ,
( " - " , " 336d5e " ) ,
( " no $ characters " , " no--characters-59e024 " ) ,
] ,
)
def test_to_css_class ( s , expected ) :
assert expected == utils . to_css_class ( s )
2017-12-08 08:06:24 -08:00
def test_temporary_docker_directory_uses_hard_link ( ) :
with tempfile . TemporaryDirectory ( ) as td :
os . chdir ( td )
2021-03-11 17:15:49 +01:00
with open ( " hello " , " w " ) as fp :
fp . write ( " world " )
2017-12-08 08:06:24 -08:00
# Default usage of this should use symlink
with utils . temporary_docker_directory (
files = [ " hello " ] ,
name = " t " ,
metadata = None ,
2017-12-09 10:38:04 -08:00
extra_options = None ,
branch = None ,
template_dir = None ,
2018-04-15 22:22:01 -07:00
plugins_dir = None ,
2017-12-09 10:38:04 -08:00
static = [ ] ,
2018-04-18 07:48:34 -07:00
install = [ ] ,
2018-05-31 07:47:22 -07:00
spatialite = False ,
2018-06-17 13:14:55 -07:00
version_note = None ,
2020-06-11 09:02:03 -07:00
secret = " secret " ,
2017-12-08 08:06:24 -08:00
) as temp_docker :
hello = os . path . join ( temp_docker , " hello " )
2021-03-11 17:15:49 +01:00
with open ( hello ) as fp :
assert " world " == fp . read ( )
2017-12-08 08:06:24 -08:00
# It should be a hard link
assert 2 == os . stat ( hello ) . st_nlink
@patch ( " os.link " )
def test_temporary_docker_directory_uses_copy_if_hard_link_fails ( mock_link ) :
# Copy instead if os.link raises OSError (normally due to different device)
mock_link . side_effect = OSError
with tempfile . TemporaryDirectory ( ) as td :
os . chdir ( td )
2021-03-11 17:15:49 +01:00
with open ( " hello " , " w " ) as fp :
fp . write ( " world " )
2017-12-08 08:06:24 -08:00
# Default usage of this should use symlink
with utils . temporary_docker_directory (
files = [ " hello " ] ,
name = " t " ,
metadata = None ,
2017-12-09 10:38:04 -08:00
extra_options = None ,
branch = None ,
template_dir = None ,
2018-04-15 22:22:01 -07:00
plugins_dir = None ,
2017-12-09 10:38:04 -08:00
static = [ ] ,
2018-04-18 07:48:34 -07:00
install = [ ] ,
2018-05-31 07:47:22 -07:00
spatialite = False ,
2018-06-17 13:14:55 -07:00
version_note = None ,
2020-06-11 09:02:03 -07:00
secret = None ,
2017-12-08 08:06:24 -08:00
) as temp_docker :
hello = os . path . join ( temp_docker , " hello " )
2021-03-11 17:15:49 +01:00
with open ( hello ) as fp :
assert " world " == fp . read ( )
2017-12-08 08:06:24 -08:00
# It should be a copy, not a hard link
assert 1 == os . stat ( hello ) . st_nlink
2018-03-29 22:10:09 -07:00
2019-05-03 15:59:01 +02:00
def test_temporary_docker_directory_quotes_args ( ) :
with tempfile . TemporaryDirectory ( ) as td :
os . chdir ( td )
2021-03-11 17:15:49 +01:00
with open ( " hello " , " w " ) as fp :
fp . write ( " world " )
2019-05-03 15:59:01 +02:00
with utils . temporary_docker_directory (
files = [ " hello " ] ,
name = " t " ,
metadata = None ,
extra_options = " --$HOME " ,
branch = None ,
template_dir = None ,
plugins_dir = None ,
static = [ ] ,
install = [ ] ,
spatialite = False ,
version_note = " $PWD " ,
2020-06-11 09:02:03 -07:00
secret = " secret " ,
2019-05-03 15:59:01 +02:00
) as temp_docker :
df = os . path . join ( temp_docker , " Dockerfile " )
2021-03-11 17:15:49 +01:00
with open ( df ) as fp :
df_contents = fp . read ( )
2019-05-03 15:59:01 +02:00
assert " ' $PWD ' " in df_contents
assert " ' --$HOME ' " in df_contents
2020-06-11 09:02:03 -07:00
assert " ENV DATASETTE_SECRET ' secret ' " in df_contents
2019-05-03 15:59:01 +02:00
2018-03-29 22:10:09 -07:00
def test_compound_keys_after_sql ( ) :
2018-04-03 06:39:50 -07:00
assert " ((a > :p0)) " == utils . compound_keys_after_sql ( [ " a " ] )
2018-03-29 22:10:09 -07:00
assert """
2018-04-03 06:39:50 -07:00
( ( a > : p0 )
2018-03-29 22:10:09 -07:00
or
2018-04-03 06:39:50 -07:00
( a = : p0 and b > : p1 ) )
2026-02-17 13:30:24 -08:00
""" .strip() == utils.compound_keys_after_sql([ " a " , " b " ])
2018-03-29 22:10:09 -07:00
assert """
2018-04-03 06:39:50 -07:00
( ( a > : p0 )
2018-03-29 22:10:09 -07:00
or
2018-04-03 06:39:50 -07:00
( a = : p0 and b > : p1 )
2018-03-29 22:10:09 -07:00
or
2018-04-03 06:39:50 -07:00
( a = : p0 and b = : p1 and c > : p2 ) )
2026-02-17 13:30:24 -08:00
""" .strip() == utils.compound_keys_after_sql([ " a " , " b " , " c " ])
2018-06-14 23:51:23 -07:00
2019-04-06 18:58:51 -07:00
def test_table_columns ( ) :
conn = sqlite3 . connect ( " :memory: " )
2026-02-17 13:30:24 -08:00
conn . executescript ( """
2019-04-06 18:58:51 -07:00
create table places ( id integer primary key , name text , bob integer )
2026-02-17 13:30:24 -08:00
""" )
2019-04-06 18:58:51 -07:00
assert [ " id " , " name " , " bob " ] == utils . table_columns ( conn , " places " )
2025-12-12 22:38:04 -08:00
conn . close ( )
2019-04-06 18:58:51 -07:00
2018-06-14 23:51:23 -07:00
@pytest.mark.parametrize (
" path,format,extra_qs,expected " ,
[
( " /foo?sql=select+1 " , " csv " , { } , " /foo.csv?sql=select+1 " ) ,
( " /foo?sql=select+1 " , " json " , { } , " /foo.json?sql=select+1 " ) ,
( " /foo/bar " , " json " , { } , " /foo/bar.json " ) ,
( " /foo/bar " , " csv " , { } , " /foo/bar.csv " ) ,
( " /foo/bar " , " csv " , { " _dl " : 1 } , " /foo/bar.csv?_dl=1 " ) ,
(
" /sf-trees/Street_Tree_List?_search=cherry&_size=1000 " ,
" csv " ,
{ " _dl " : 1 } ,
" /sf-trees/Street_Tree_List.csv?_search=cherry&_size=1000&_dl=1 " ,
) ,
] ,
)
def test_path_with_format ( path , format , extra_qs , expected ) :
2019-06-23 20:13:09 -07:00
request = Request . fake ( path )
2020-10-31 11:16:28 -07:00
actual = utils . path_with_format ( request = request , format = format , extra_qs = extra_qs )
2018-06-14 23:51:23 -07:00
assert expected == actual
2019-02-05 20:53:44 -08:00
2026-05-30 22:40:45 -07:00
def test_path_with_format_can_override_request_path ( ) :
request = Request . fake ( " /prefix/foo?x=1 " )
actual = utils . path_with_format ( request = request , path = " /foo " , format = " json " )
assert " /foo.json?x=1 " == actual
2019-02-05 20:53:44 -08:00
@pytest.mark.parametrize (
" bytes,expected " ,
[
( 120 , " 120 bytes " ) ,
( 1024 , " 1.0 KB " ) ,
( 1024 * 1024 , " 1.0 MB " ) ,
( 1024 * 1024 * 1024 , " 1.0 GB " ) ,
( 1024 * 1024 * 1024 * 1.3 , " 1.3 GB " ) ,
( 1024 * 1024 * 1024 * 1024 , " 1.0 TB " ) ,
] ,
)
def test_format_bytes ( bytes , expected ) :
assert expected == utils . format_bytes ( bytes )
2019-12-29 18:48:13 +00:00
@pytest.mark.parametrize (
" query,expected " ,
[
( " dog " , ' " dog " ' ) ,
( " cat, " , ' " cat, " ' ) ,
( " cat dog " , ' " cat " " dog " ' ) ,
# If a phrase is already double quoted, leave it so
( ' " cat dog " ' , ' " cat dog " ' ) ,
( ' " cat dog " fish ' , ' " cat dog " " fish " ' ) ,
# Sensibly handle unbalanced double quotes
( ' cat " ' , ' " cat " ' ) ,
( ' " cat dog " " fish ' , ' " cat dog " " fish " ' ) ,
] ,
)
def test_escape_fts ( query , expected ) :
assert expected == utils . escape_fts ( query )
2020-02-15 09:56:48 -08:00
2020-09-28 15:42:31 -07:00
@pytest.mark.parametrize (
" input,expected " ,
[
( " dog " , " dog " ) ,
( ' dateutil_parse( " 1/2/2020 " ) ' , r " dateutil_parse( \ 0000221/2/2020 \ 000022) " ) ,
2020-09-29 12:16:30 -07:00
( " this \r \n and \r \n that " , r " this \ 00000Aand \ 00000Athat " ) ,
2020-09-28 15:42:31 -07:00
] ,
)
def test_escape_css_string ( input , expected ) :
assert expected == utils . escape_css_string ( input )
2020-02-15 09:56:48 -08:00
def test_check_connection_spatialite_raises ( ) :
path = str ( pathlib . Path ( __file__ ) . parent / " spatialite.db " )
conn = sqlite3 . connect ( path )
with pytest . raises ( utils . SpatialiteConnectionProblem ) :
utils . check_connection ( conn )
2025-12-12 22:38:04 -08:00
conn . close ( )
2020-02-15 09:56:48 -08:00
def test_check_connection_passes ( ) :
conn = sqlite3 . connect ( " :memory: " )
utils . check_connection ( conn )
2025-12-12 22:38:04 -08:00
conn . close ( )
2020-03-16 19:47:37 -07:00
2020-05-27 12:25:52 -07:00
def test_call_with_supported_arguments ( ) :
def foo ( a , b ) :
2020-11-15 15:24:22 -08:00
return f " { a } + { b } "
2020-05-27 12:25:52 -07:00
assert " 1+2 " == utils . call_with_supported_arguments ( foo , a = 1 , b = 2 )
assert " 1+2 " == utils . call_with_supported_arguments ( foo , a = 1 , b = 2 , c = 3 )
with pytest . raises ( TypeError ) :
utils . call_with_supported_arguments ( foo , a = 1 )
2020-06-05 10:52:50 -07:00
2020-06-05 12:05:57 -07:00
@pytest.mark.parametrize (
" data,should_raise " ,
[
( [ [ " foo " , " bar " ] , [ " foo " , " baz " ] ] , False ) ,
( [ ( " foo " , " bar " ) , ( " foo " , " baz " ) ] , False ) ,
( ( [ " foo " , " bar " ] , [ " foo " , " baz " ] ) , False ) ,
( [ [ " foo " , " bar " ] , [ " foo " , " baz " , " bax " ] ] , True ) ,
( { " foo " : [ " bar " , " baz " ] } , False ) ,
( { " foo " : ( " bar " , " baz " ) } , False ) ,
( { " foo " : " bar " } , True ) ,
2020-06-05 16:46:37 -07:00
] ,
2020-06-05 12:05:57 -07:00
)
2020-06-05 11:01:06 -07:00
def test_multi_params ( data , should_raise ) :
if should_raise :
with pytest . raises ( AssertionError ) :
utils . MultiParams ( data )
return
p1 = utils . MultiParams ( data )
2020-06-05 10:52:50 -07:00
assert " bar " == p1 [ " foo " ]
2020-06-05 11:01:06 -07:00
assert [ " bar " , " baz " ] == list ( p1 . getlist ( " foo " ) )
2020-06-06 11:39:11 -07:00
@pytest.mark.parametrize (
" actor,allow,expected " ,
[
2020-06-10 16:56:53 -07:00
# Default is to allow:
2020-06-06 12:05:22 -07:00
( None , None , True ) ,
2020-06-10 16:56:53 -07:00
# {} means deny-all:
2020-06-06 12:05:22 -07:00
( None , { } , False ) ,
2020-06-09 10:01:03 -07:00
( { " id " : " root " } , { } , False ) ,
2020-07-24 17:04:06 -07:00
# true means allow-all
( { " id " : " root " } , True , True ) ,
( None , True , True ) ,
# false means deny-all
( { " id " : " root " } , False , False ) ,
( None , False , False ) ,
2020-06-09 10:01:03 -07:00
# Special case for "unauthenticated": true
( None , { " unauthenticated " : True } , True ) ,
( None , { " unauthenticated " : False } , False ) ,
2020-06-10 16:56:53 -07:00
# Match on just one property:
( None , { " id " : " root " } , False ) ,
( { " id " : " root " } , None , True ) ,
( { " id " : " simon " , " staff " : True } , { " staff " : True } , True ) ,
( { " id " : " simon " , " staff " : False } , { " staff " : True } , False ) ,
2020-06-06 11:39:11 -07:00
# Special "*" value for any key:
( { " id " : " root " } , { " id " : " * " } , True ) ,
( { } , { " id " : " * " } , False ) ,
( { " name " : " root " } , { " id " : " * " } , False ) ,
# Supports single strings or list of values:
( { " id " : " root " } , { " id " : " bob " } , False ) ,
( { " id " : " root " } , { " id " : [ " bob " ] } , False ) ,
( { " id " : " root " } , { " id " : " root " } , True ) ,
( { " id " : " root " } , { " id " : [ " root " ] } , True ) ,
# Any matching role will work:
( { " id " : " garry " , " roles " : [ " staff " , " dev " ] } , { " roles " : [ " staff " ] } , True ) ,
( { " id " : " garry " , " roles " : [ " staff " , " dev " ] } , { " roles " : [ " dev " ] } , True ) ,
( { " id " : " garry " , " roles " : [ " staff " , " dev " ] } , { " roles " : [ " otter " ] } , False ) ,
( { " id " : " garry " , " roles " : [ " staff " , " dev " ] } , { " roles " : [ " dev " , " otter " ] } , True ) ,
( { " id " : " garry " , " roles " : [ ] } , { " roles " : [ " staff " ] } , False ) ,
( { " id " : " garry " } , { " roles " : [ " staff " ] } , False ) ,
2020-06-11 15:47:19 -07:00
# Any single matching key works:
( { " id " : " root " } , { " bot_id " : " my-bot " , " id " : [ " root " ] } , True ) ,
2020-06-06 11:39:11 -07:00
] ,
)
def test_actor_matches_allow ( actor , allow , expected ) :
assert expected == utils . actor_matches_allow ( actor , allow )
2020-06-11 17:21:48 -07:00
@pytest.mark.parametrize (
" config,expected " ,
[
( { " foo " : " bar " } , { " foo " : " bar " } ) ,
( { " $env " : " FOO " } , " x " ) ,
( { " k " : { " $env " : " FOO " } } , { " k " : " x " } ) ,
( [ { " k " : { " $env " : " FOO " } } , { " z " : { " $env " : " FOO " } } ] , [ { " k " : " x " } , { " z " : " x " } ] ) ,
( { " k " : [ { " in_a_list " : { " $env " : " FOO " } } ] } , { " k " : [ { " in_a_list " : " x " } ] } ) ,
] ,
)
def test_resolve_env_secrets ( config , expected ) :
assert expected == utils . resolve_env_secrets ( config , { " FOO " : " x " } )
2020-06-29 11:40:40 -07:00
@pytest.mark.parametrize (
" actor,expected " ,
[
( { " id " : " blah " } , " blah " ) ,
( { " id " : " blah " , " login " : " l " } , " l " ) ,
( { " id " : " blah " , " login " : " l " , " username " : " u " } , " u " ) ,
( { " login " : " l " , " name " : " n " } , " n " ) ,
(
{ " id " : " blah " , " login " : " l " , " username " : " u " , " name " : " n " , " display " : " d " } ,
" d " ,
) ,
( { " weird " : " shape " } , " { ' weird ' : ' shape ' } " ) ,
] ,
)
def test_display_actor ( actor , expected ) :
assert expected == utils . display_actor ( actor )
2020-10-25 22:06:20 -07:00
@pytest.mark.asyncio
@pytest.mark.parametrize (
" dbs,expected_path " ,
[
( [ " one_table " ] , " /one/one " ) ,
( [ " two_tables " ] , " /two " ) ,
( [ " one_table " , " two_tables " ] , " / " ) ,
] ,
)
async def test_initial_path_for_datasette ( tmp_path_factory , dbs , expected_path ) :
db_dir = tmp_path_factory . mktemp ( " dbs " )
one_table = str ( db_dir / " one.db " )
2025-12-12 22:38:04 -08:00
conn1 = sqlite3 . connect ( one_table )
conn1 . execute ( " create table one (id integer primary key) " )
conn1 . close ( )
2020-10-25 22:06:20 -07:00
two_tables = str ( db_dir / " two.db " )
2025-12-12 22:38:04 -08:00
conn2 = sqlite3 . connect ( two_tables )
conn2 . execute ( " create table two (id integer primary key) " )
conn2 . execute ( " create table three (id integer primary key) " )
conn2 . close ( )
2020-10-25 22:06:20 -07:00
datasette = Datasette (
[ { " one_table " : one_table , " two_tables " : two_tables } [ db ] for db in dbs ]
)
path = await utils . initial_path_for_datasette ( datasette )
assert path == expected_path
2021-07-29 16:30:12 -07:00
@pytest.mark.parametrize (
" content,expected " ,
(
( " title: Hello " , { " title " : " Hello " } ) ,
( ' { " title " : " Hello " } ' , { " title " : " Hello " } ) ,
( " {{ this }} is {{ bad }} " , None ) ,
) ,
)
def test_parse_metadata ( content , expected ) :
if expected is None :
with pytest . raises ( utils . BadMetadataError ) :
utils . parse_metadata ( content )
else :
assert utils . parse_metadata ( content ) == expected
2021-08-08 20:21:13 -07:00
@pytest.mark.asyncio
2021-08-08 20:26:08 -07:00
@pytest.mark.parametrize (
" sql,expected " ,
(
( " select 1 " , [ ] ) ,
( " select 1 + :one " , [ " one " ] ) ,
( " select 1 + :one + :two " , [ " one " , " two " ] ) ,
( " select ' bob ' || ' 0:00 ' || :cat " , [ " cat " ] ) ,
( " select this is invalid :one, :two, :three " , [ " one " , " two " , " three " ] ) ,
2026-07-08 06:23:31 +09:00
# A string literal containing a comment marker should not hide
# parameters that come after it
( " select * from t where note = ' -- TODO ' and id = :id " , [ " id " ] ) ,
( " select ' -- ' || :y " , [ " y " ] ) ,
( " select * from t where note = ' /* x */ ' and id = :id " , [ " id " ] ) ,
# Parameters that live inside a comment should be ignored
( " select :x -- and :ignored " , [ " x " ] ) ,
( " select :x /* and :ignored */ from t " , [ " x " ] ) ,
2026-07-07 14:26:34 -07:00
( " select :x /* and :ignored " , [ " x " ] ) ,
# Parameters inside quoted identifiers should be ignored
( " select [a:b] from t where id = :id " , [ " id " ] ) ,
( " select `a:b` from t where id = :id " , [ " id " ] ) ,
( " select `a``:b` from t where id = :id " , [ " id " ] ) ,
2026-07-08 06:23:31 +09:00
# Parameters inside a string literal should be ignored
( " select ' :ignored ' || :real " , [ " real " ] ) ,
2021-08-08 20:26:08 -07:00
) ,
)
2024-06-12 16:51:07 -07:00
@pytest.mark.parametrize ( " use_async_version " , ( False , True ) )
async def test_named_parameters ( sql , expected , use_async_version ) :
2021-08-08 20:21:13 -07:00
ds = Datasette ( [ ] , memory = True )
db = ds . get_database ( " _memory " )
2024-06-12 16:51:07 -07:00
if use_async_version :
params = await utils . derive_named_parameters ( db , sql )
else :
params = utils . named_parameters ( sql )
2021-08-08 20:21:13 -07:00
assert params == expected
2022-03-07 07:38:29 -08:00
@pytest.mark.parametrize (
" original,expected " ,
(
( " abc " , " abc " ) ,
2022-03-15 11:01:57 -07:00
( " /foo/bar " , " ~2Ffoo~2Fbar " ) ,
( " /-/bar " , " ~2F-~2Fbar " ) ,
( " -/db-/table.csv " , " -~2Fdb-~2Ftable~2Ecsv " ) ,
( r " % ~-/ " , " ~25~7E-~2F " ) ,
( " ~25~7E~2D~2F " , " ~7E25~7E7E~7E2D~7E2F " ) ,
2022-04-06 08:55:01 -07:00
( " with space " , " with+space " ) ,
2022-03-07 07:38:29 -08:00
) ,
)
2022-03-15 11:01:57 -07:00
def test_tilde_encoding ( original , expected ) :
actual = utils . tilde_encode ( original )
2022-03-07 07:38:29 -08:00
assert actual == expected
# And test round-trip
2022-03-15 11:01:57 -07:00
assert original == utils . tilde_decode ( actual )
2022-09-06 16:50:43 -07:00
@pytest.mark.parametrize (
" url,length,expected " ,
(
( " https://example.com/ " , 5 , " http… " ) ,
( " https://example.com/foo/bar " , 15 , " https://exampl… " ) ,
( " https://example.com/foo/bar/baz.jpg " , 30 , " https://example.com/foo/ba….jpg " ) ,
# Extensions longer than 4 characters are not treated specially:
( " https://example.com/foo/bar/baz.jpeg2 " , 30 , " https://example.com/foo/bar/b… " ) ,
(
" https://example.com/foo/bar/baz.jpeg2 " ,
None ,
" https://example.com/foo/bar/baz.jpeg2 " ,
) ,
) ,
)
def test_truncate_url ( url , length , expected ) :
actual = utils . truncate_url ( url , length )
assert actual == expected
2023-08-24 11:21:15 -07:00
@pytest.mark.parametrize (
" pairs,expected " ,
(
# Simple nested objects
( [ ( " a " , " b " ) ] , { " a " : " b " } ) ,
( [ ( " a.b " , " c " ) ] , { " a " : { " b " : " c " } } ) ,
# JSON literals
( [ ( " a.b " , " true " ) ] , { " a " : { " b " : True } } ) ,
( [ ( " a.b " , " false " ) ] , { " a " : { " b " : False } } ) ,
( [ ( " a.b " , " null " ) ] , { " a " : { " b " : None } } ) ,
( [ ( " a.b " , " 1 " ) ] , { " a " : { " b " : 1 } } ) ,
( [ ( " a.b " , " 1.1 " ) ] , { " a " : { " b " : 1.1 } } ) ,
# Nested JSON literals
( [ ( " a.b " , ' { " foo " : " bar " } ' ) ] , { " a " : { " b " : { " foo " : " bar " } } } ) ,
( [ ( " a.b " , " [1, 2, 3] " ) ] , { " a " : { " b " : [ 1 , 2 , 3 ] } } ) ,
# JSON strings are preserved
( [ ( " a.b " , ' " true " ' ) ] , { " a " : { " b " : " true " } } ) ,
( [ ( " a.b " , ' " [1, 2, 3] " ' ) ] , { " a " : { " b " : " [1, 2, 3] " } } ) ,
# Later keys over-ride the previous
(
[
( " a " , " b " ) ,
( " a.b " , " c " ) ,
] ,
{ " a " : { " b " : " c " } } ,
) ,
(
[
Remove the hand-rolled tracer now that OpenTelemetry covers the same ground
Datasette had two tracing systems since the OpenTelemetry spans landed. The
hand-rolled one measures the wrong thing - issue 1730, open since 2022, is
about exactly that - and it cannot be rebuilt on top of the new spans without
core owning a TracerProvider, which is the one thing the OTel design refuses
to do. Rather than carry duplicate instrumentation on the db.execute() hot
path indefinitely, the old system goes.
Deleted: datasette/tracer.py, the trace_debug setting, the AsgiTracer
response-rewriting middleware and the ?_trace=1 query-string argument.
- datasette/database.py: the four `with trace(...)` wrappers PR 1 deliberately
nested the OTel spans inside are removed and the bodies dedented. That also
retires the `# noqa: SIM117` comments those wrappers required - a leftover
unnecessary noqa trips ruff's RUF100 - and `kwargs["count"] = count` in
execute_write_many, which fed the old tracer only. `git diff -w` on this file
shows nothing but the deleted lines.
- datasette/views/base.py: stream_csv() still read ?_trace=1 to wrap CSV output
in an HTML <textarea> debug page. That whole branch, including the
EscapeHtmlWriter selection and the conditional content-type, is gone. The
EscapeHtmlWriter class itself stays in datasette.utils - it is an importable
public name and removing it would widen the API break.
- .github/workflows/deploy-latest.yml no longer passes --setting trace_debug 1.
Worth stating precisely, because the ticket claimed otherwise: this would not
have broken the deploy. Setting.convert() in cli.py only rewrites a bare name
to settings.<name> for *known* settings, so `--setting trace_debug 1` would
have been silently accepted as a meaningless top-level config key. The flag is
removed because it is dead, not because it errors.
Tests. tests/test_tracer.py is deleted outright (6 items). Four other tests used
?_trace=1 as an assertion instrument rather than testing tracing:
- test_csv_trace tested the trace mechanism itself - deleted.
- test_table_csv_stream_does_not_calculate_facets,
test_table_csv_stream_does_not_calculate_counts and
test_nocount_nofacet_if_shape_is_object test real behaviour, and are rebuilt
against captured spans. All three had silently stopped being able to fail: the
facets test looked for "select content, count(*) as n", which facet suggestion
has not emitted since it moved to a `with limited as (...)` CTE, and none of
the three requested the count or facet work whose suppression they claim to
check. The rebuilt versions ask for it explicitly, match strings the current
SQL contains, and carry a guard assertion so an empty span list cannot
masquerade as a pass. Each was confirmed to fail with the covered code broken.
- test_trace_correctly_escaped is kept, renamed test_query_page_escapes_sql,
with ?_trace=1 dropped. It ran against ds_client, which has no trace_debug, so
it never exercised the tracer - what it actually covered is the query page
echoing user SQL into HTML, the surface of the two reflected-XSS advisories in
issue 1360, and nothing else in the suite covers it. Deleting it would have
quietly dropped that.
tests/test_utils.py's pairs_to_nested_config case used settings.trace_debug to
check that a later key overrides an earlier one; it now uses template_debug
rather than losing the case.
Docs: the datasette.tracer section of internals.rst, the trace_debug section of
settings.rst, the ?_trace=1 entries in json_api.rst and introspection.rst, and
the regenerated cli-reference.rst. changelog.rst gets a breaking-change entry
and keeps all its historical ?_trace=1 entries - two of them had to lose a
:ref: role pointing at a label this commit deletes, or Sphinx warns on every
build.
2368 passed, 39 skipped, 6 xfailed, 15 xpassed, 140 subtests, against 2375 /
141 before. Net -7 tests, fully accounted for: -6 test_tracer.py, -1
test_csv_trace, -1 test_trace_correctly_escaped, +1 test_query_page_escapes_sql.
The lost subtest is the per-setting case trace_debug generated in
test_settings_are_documented.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-30 20:14:08 -07:00
( " settings.template_debug " , " true " ) ,
2023-08-24 11:21:15 -07:00
( " plugins.datasette-ripgrep.path " , " /etc " ) ,
Remove the hand-rolled tracer now that OpenTelemetry covers the same ground
Datasette had two tracing systems since the OpenTelemetry spans landed. The
hand-rolled one measures the wrong thing - issue 1730, open since 2022, is
about exactly that - and it cannot be rebuilt on top of the new spans without
core owning a TracerProvider, which is the one thing the OTel design refuses
to do. Rather than carry duplicate instrumentation on the db.execute() hot
path indefinitely, the old system goes.
Deleted: datasette/tracer.py, the trace_debug setting, the AsgiTracer
response-rewriting middleware and the ?_trace=1 query-string argument.
- datasette/database.py: the four `with trace(...)` wrappers PR 1 deliberately
nested the OTel spans inside are removed and the bodies dedented. That also
retires the `# noqa: SIM117` comments those wrappers required - a leftover
unnecessary noqa trips ruff's RUF100 - and `kwargs["count"] = count` in
execute_write_many, which fed the old tracer only. `git diff -w` on this file
shows nothing but the deleted lines.
- datasette/views/base.py: stream_csv() still read ?_trace=1 to wrap CSV output
in an HTML <textarea> debug page. That whole branch, including the
EscapeHtmlWriter selection and the conditional content-type, is gone. The
EscapeHtmlWriter class itself stays in datasette.utils - it is an importable
public name and removing it would widen the API break.
- .github/workflows/deploy-latest.yml no longer passes --setting trace_debug 1.
Worth stating precisely, because the ticket claimed otherwise: this would not
have broken the deploy. Setting.convert() in cli.py only rewrites a bare name
to settings.<name> for *known* settings, so `--setting trace_debug 1` would
have been silently accepted as a meaningless top-level config key. The flag is
removed because it is dead, not because it errors.
Tests. tests/test_tracer.py is deleted outright (6 items). Four other tests used
?_trace=1 as an assertion instrument rather than testing tracing:
- test_csv_trace tested the trace mechanism itself - deleted.
- test_table_csv_stream_does_not_calculate_facets,
test_table_csv_stream_does_not_calculate_counts and
test_nocount_nofacet_if_shape_is_object test real behaviour, and are rebuilt
against captured spans. All three had silently stopped being able to fail: the
facets test looked for "select content, count(*) as n", which facet suggestion
has not emitted since it moved to a `with limited as (...)` CTE, and none of
the three requested the count or facet work whose suppression they claim to
check. The rebuilt versions ask for it explicitly, match strings the current
SQL contains, and carry a guard assertion so an empty span list cannot
masquerade as a pass. Each was confirmed to fail with the covered code broken.
- test_trace_correctly_escaped is kept, renamed test_query_page_escapes_sql,
with ?_trace=1 dropped. It ran against ds_client, which has no trace_debug, so
it never exercised the tracer - what it actually covered is the query page
echoing user SQL into HTML, the surface of the two reflected-XSS advisories in
issue 1360, and nothing else in the suite covers it. Deleting it would have
quietly dropped that.
tests/test_utils.py's pairs_to_nested_config case used settings.trace_debug to
check that a later key overrides an earlier one; it now uses template_debug
rather than losing the case.
Docs: the datasette.tracer section of internals.rst, the trace_debug section of
settings.rst, the ?_trace=1 entries in json_api.rst and introspection.rst, and
the regenerated cli-reference.rst. changelog.rst gets a breaking-change entry
and keeps all its historical ?_trace=1 entries - two of them had to lose a
:ref: role pointing at a label this commit deletes, or Sphinx warns on every
build.
2368 passed, 39 skipped, 6 xfailed, 15 xpassed, 140 subtests, against 2375 /
141 before. Net -7 tests, fully accounted for: -6 test_tracer.py, -1
test_csv_trace, -1 test_trace_correctly_escaped, +1 test_query_page_escapes_sql.
The lost subtest is the per-setting case trace_debug generated in
test_settings_are_documented.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-30 20:14:08 -07:00
( " settings.template_debug " , " false " ) ,
2023-08-24 11:21:15 -07:00
] ,
{
" settings " : {
Remove the hand-rolled tracer now that OpenTelemetry covers the same ground
Datasette had two tracing systems since the OpenTelemetry spans landed. The
hand-rolled one measures the wrong thing - issue 1730, open since 2022, is
about exactly that - and it cannot be rebuilt on top of the new spans without
core owning a TracerProvider, which is the one thing the OTel design refuses
to do. Rather than carry duplicate instrumentation on the db.execute() hot
path indefinitely, the old system goes.
Deleted: datasette/tracer.py, the trace_debug setting, the AsgiTracer
response-rewriting middleware and the ?_trace=1 query-string argument.
- datasette/database.py: the four `with trace(...)` wrappers PR 1 deliberately
nested the OTel spans inside are removed and the bodies dedented. That also
retires the `# noqa: SIM117` comments those wrappers required - a leftover
unnecessary noqa trips ruff's RUF100 - and `kwargs["count"] = count` in
execute_write_many, which fed the old tracer only. `git diff -w` on this file
shows nothing but the deleted lines.
- datasette/views/base.py: stream_csv() still read ?_trace=1 to wrap CSV output
in an HTML <textarea> debug page. That whole branch, including the
EscapeHtmlWriter selection and the conditional content-type, is gone. The
EscapeHtmlWriter class itself stays in datasette.utils - it is an importable
public name and removing it would widen the API break.
- .github/workflows/deploy-latest.yml no longer passes --setting trace_debug 1.
Worth stating precisely, because the ticket claimed otherwise: this would not
have broken the deploy. Setting.convert() in cli.py only rewrites a bare name
to settings.<name> for *known* settings, so `--setting trace_debug 1` would
have been silently accepted as a meaningless top-level config key. The flag is
removed because it is dead, not because it errors.
Tests. tests/test_tracer.py is deleted outright (6 items). Four other tests used
?_trace=1 as an assertion instrument rather than testing tracing:
- test_csv_trace tested the trace mechanism itself - deleted.
- test_table_csv_stream_does_not_calculate_facets,
test_table_csv_stream_does_not_calculate_counts and
test_nocount_nofacet_if_shape_is_object test real behaviour, and are rebuilt
against captured spans. All three had silently stopped being able to fail: the
facets test looked for "select content, count(*) as n", which facet suggestion
has not emitted since it moved to a `with limited as (...)` CTE, and none of
the three requested the count or facet work whose suppression they claim to
check. The rebuilt versions ask for it explicitly, match strings the current
SQL contains, and carry a guard assertion so an empty span list cannot
masquerade as a pass. Each was confirmed to fail with the covered code broken.
- test_trace_correctly_escaped is kept, renamed test_query_page_escapes_sql,
with ?_trace=1 dropped. It ran against ds_client, which has no trace_debug, so
it never exercised the tracer - what it actually covered is the query page
echoing user SQL into HTML, the surface of the two reflected-XSS advisories in
issue 1360, and nothing else in the suite covers it. Deleting it would have
quietly dropped that.
tests/test_utils.py's pairs_to_nested_config case used settings.trace_debug to
check that a later key overrides an earlier one; it now uses template_debug
rather than losing the case.
Docs: the datasette.tracer section of internals.rst, the trace_debug section of
settings.rst, the ?_trace=1 entries in json_api.rst and introspection.rst, and
the regenerated cli-reference.rst. changelog.rst gets a breaking-change entry
and keeps all its historical ?_trace=1 entries - two of them had to lose a
:ref: role pointing at a label this commit deletes, or Sphinx warns on every
build.
2368 passed, 39 skipped, 6 xfailed, 15 xpassed, 140 subtests, against 2375 /
141 before. Net -7 tests, fully accounted for: -6 test_tracer.py, -1
test_csv_trace, -1 test_trace_correctly_escaped, +1 test_query_page_escapes_sql.
The lost subtest is the per-setting case trace_debug generated in
test_settings_are_documented.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-30 20:14:08 -07:00
" template_debug " : False ,
2023-08-24 11:21:15 -07:00
} ,
" plugins " : {
" datasette-ripgrep " : {
" path " : " /etc " ,
}
} ,
} ,
) ,
) ,
)
def test_pairs_to_nested_config ( pairs , expected ) :
actual = utils . pairs_to_nested_config ( pairs )
assert actual == expected
2024-03-17 16:18:40 -03:00
2026-06-23 13:44:58 -07:00
def test_sha256_file ( tmp_path ) :
path = tmp_path / " test.txt "
path . write_text ( " hello " )
assert utils . sha256_file ( path , chunk_size = 2 ) == hashlib . sha256 ( b " hello " ) . hexdigest ( )
2024-03-17 16:18:40 -03:00
@pytest.mark.asyncio
async def test_calculate_etag ( tmp_path ) :
path = tmp_path / " test.txt "
path . write_text ( " hello " )
etag = ' " 5d41402abc4b2a76b9719d911017c592 " '
assert etag == await utils . calculate_etag ( path )
assert utils . _etag_cache [ path ] == etag
utils . _etag_cache [ path ] = " hash "
assert " hash " == await utils . calculate_etag ( path )
utils . _etag_cache . clear ( )
2024-08-14 14:28:48 -07:00
@pytest.mark.parametrize (
" dict1,dict2,expected " ,
[
# Basic update
( { " a " : 1 , " b " : 2 } , { " b " : 3 , " c " : 4 } , { " a " : 1 , " b " : 3 , " c " : 4 } ) ,
# Nested dictionary update
(
{ " a " : 1 , " b " : { " x " : 10 , " y " : 20 } } ,
{ " b " : { " y " : 30 , " z " : 40 } } ,
{ " a " : 1 , " b " : { " x " : 10 , " y " : 30 , " z " : 40 } } ,
) ,
# Deep nested update
(
{ " a " : { " b " : { " c " : 1 } } } ,
{ " a " : { " b " : { " d " : 2 } } } ,
{ " a " : { " b " : { " c " : 1 , " d " : 2 } } } ,
) ,
# Update with mixed types
(
{ " a " : 1 , " b " : { " x " : 10 } } ,
{ " b " : { " y " : 20 } , " c " : [ 1 , 2 , 3 ] } ,
{ " a " : 1 , " b " : { " x " : 10 , " y " : 20 } , " c " : [ 1 , 2 , 3 ] } ,
) ,
] ,
)
def test_deep_dict_update ( dict1 , dict2 , expected ) :
result = utils . deep_dict_update ( dict1 , dict2 )
assert result == expected
# Check that the original dict1 was modified
assert dict1 == expected