test_vocabulary.py

tests/test_vocabulary.py

Tests for the central schema vocabulary (clew.vocabulary).

test_apostrophe_is_escaped_by_doubling

None test_vocabulary.test_apostrophe_is_escaped_by_doubling()

`repr` quotes an apostrophe-bearing value with DOUBLE quotes, which SQLite reads as an identifier, not a string. No shipped value contains one today; the generator must not be the reason it can never be added.

tests/test_vocabulary.py:332

Show on the map →

Called by none

Calls none

Checks

  • assert vocab.check("c") == "CHECK(c IN ('it''s', 'plain'))"

Result: passed

Verifies

requirementlinkedpath to the implementer
REQ-DDB-SCHEMA-012measured
Source · 14 lines
def test_apostrophe_is_escaped_by_doubling() -> None:
    """`repr` quotes an apostrophe-bearing value with DOUBLE quotes, which
    SQLite reads as an identifier, not a string. No shipped value contains one
    today; the generator must not be the reason it can never be added."""
    vocab = Vocabulary(id="t", values=("it's", "plain"), means="test")
    assert vocab.check("c") == "CHECK(c IN ('it''s', 'plain'))"
    conn = sqlite3.connect(":memory:")
    conn.execute(f"CREATE TABLE t (c TEXT {vocab.check('c')})")
    conn.execute('INSERT INTO t VALUES ("it\'s")')
    with pytest.raises(sqlite3.IntegrityError):
        conn.execute("INSERT INTO t VALUES ('nope')")
    conn.close()

Activity · 8 steps
lines 336–336vocab = Vocabulary(id="t", values=("it's", "plain"), means="test")lines 337–337assert vocab.check("c") == "CHECK(c IN ('it''s', 'plain'))"lines 338–338conn = sqlite3.connect(":memory:")lines 339–339conn.execute(f"CREATE TABLE t (c TEXT {vocab.check('c')})")lines 340–340conn.execute('INSERT INTO t VALUES ("it\'s")')lines 341–341with pytest.raises(sqlite3.IntegrityError)lines 342–342conn.execute("INSERT INTO t VALUES ('nope')")lines 343–343conn.close()

test_every_registered_column_has_a_registered_vocabulary

None test_vocabulary.test_every_registered_column_has_a_registered_vocabulary()

`check()` refuses an unregistered column instead of returning an empty string: a silently-absent CHECK is the hole this module exists to close.

tests/test_vocabulary.py:433

Show on the map →

Called by none

Calls none

Checks

  • assert check(table, column).startswith("CHECK(") with pytest.raises(KeyError): check("call_edges", "not_a_column")

Result: passed

Verifies

requirementlinkedpath to the implementer
REQ-DDB-SCHEMA-012measured
Source · 9 lines
def test_every_registered_column_has_a_registered_vocabulary() -> None:
    """`check()` refuses an unregistered column instead of returning an empty
    string: a silently-absent CHECK is the hole this module exists to close."""
    for table, column in COLUMNS:
        assert check(table, column).startswith("CHECK(")
    with pytest.raises(KeyError):
        check("call_edges", "not_a_column")

Activity · 4 steps
lines 436–436◇ for table, column in COLUMNSlines 437–437assert check(table, column).startswith("CHECK(")lines 438–438with pytest.raises(KeyError)lines 439–439check("call_edges", "not_a_column")

test_every_registry_value_satisfies_its_generated_check

None test_vocabulary.test_every_registry_value_satisfies_its_generated_check()

Round-trip: every registered value is accepted by the clause generated for it, and a non-member is rejected. Catches a registry that is a superset of what the SQL actually admits.

tests/test_vocabulary.py:346

Show on the map →

Called by none

Calls none

Checks

  • assert conn.execute("SELECT COUNT(*) FROM probe").fetchone()[0] == len(vocab.values), (f"{table}.{column} lost a value round-tripping" )

Result: passed

Verifies

requirementlinkedpath to the implementer
REQ-DDB-SCHEMA-012measured
Source · 18 lines
def test_every_registry_value_satisfies_its_generated_check() -> None:
    """Round-trip: every registered value is accepted by the clause generated
    for it, and a non-member is rejected. Catches a registry that is a superset
    of what the SQL actually admits."""
    conn = sqlite3.connect(":memory:")
    for (table, column), vocab in COLUMNS.items():
        conn.execute(f"CREATE TABLE probe (c TEXT {vocab.check('c')})")
        for value in vocab.values:
            conn.execute("INSERT INTO probe VALUES (?)", (value,))
        with pytest.raises(sqlite3.IntegrityError, match="CHECK constraint failed"):
            conn.execute("INSERT INTO probe VALUES ('__not_a_member__')")
        assert conn.execute("SELECT COUNT(*) FROM probe").fetchone()[0] == len(vocab.values), (
            f"{table}.{column} lost a value round-tripping"
        )
        conn.execute("DROP TABLE probe")
    conn.close()

Activity · 10 steps
lines 350–350conn = sqlite3.connect(":memory:")lines 351–351◇ for (table, column), vocab in COLUMNS.items()lines 352–352conn.execute(f"CREATE TABLE probe (c TEXT {vocab.check('c')})")lines 353–353◇ for value in vocab.valueslines 354–354conn.execute("INSERT INTO probe VALUES (?)", (value,))lines 355–355with pytest.raises(sqlite3.IntegrityError, match="CHECK constraint failed")lines 356–356conn.execute("INSERT INTO probe VALUES ('__not_a_member__')")lines 357–359assert conn.execute("SELECT COUNT(*) FROM probe").fetchone()[0] == len(vocab.values), ( f"{table}.{column} lost a value round-tripping" )lines 360–360conn.execute("DROP TABLE probe")lines 361–361conn.close()

test_single_value_vocabulary_generates_valid_sql

None test_vocabulary.test_single_value_vocabulary_generates_valid_sql()

The idiom this replaces used `{tuple!r}`, which emits `IN ('x',)` for a one-value set — SQLite rejects the trailing comma. It survived only because every set it was applied to happened to have >= 2 values; `boundary_source` was the live one-value case until the declared-dispatch terminus widened it.

tests/test_vocabulary.py:291

Show on the map →

Called by none

Calls none

Checks

  • assert one.check("c") == "CHECK(c IN ('only'))"

Result: passed

Verifies

requirementlinkedpath to the implementer
REQ-DDB-SCHEMA-012measured
Source · 24 lines
def test_single_value_vocabulary_generates_valid_sql() -> None:
    """The idiom this replaces used `{tuple!r}`, which emits `IN ('x',)` for a
    one-value set — SQLite rejects the trailing comma. It survived only because
    every set it was applied to happened to have >= 2 values; `boundary_source`
    was the live one-value case until the declared-dispatch terminus widened it.

    So the case is exercised SYNTHETICALLY now, not through whichever registry
    entry happens to be short this week — the generator is what is under test,
    and binding the assertion to a real vocabulary made a legitimate widening
    look like a regression. Every registered one-value vocabulary is still
    checked, so the real case is covered the moment one exists again.
    """
    one = Vocabulary(id="one", values=("only",), means="test")
    assert one.check("c") == "CHECK(c IN ('only'))"
    conn = sqlite3.connect(":memory:")
    for vocab in [one, *(v for v in VOCABULARIES.values() if len(v.values) == 1)]:
        conn.execute(f"CREATE TABLE probe (c TEXT {vocab.check('c')})")
        conn.execute("INSERT INTO probe VALUES (?)", (vocab.values[0],))
        with pytest.raises(sqlite3.IntegrityError):
            conn.execute("INSERT INTO probe VALUES ('__not_a_member__')")
        conn.execute("DROP TABLE probe")
    conn.close()

Activity · 10 steps
lines 303–303one = Vocabulary(id="one", values=("only",), means="test")lines 304–304assert one.check("c") == "CHECK(c IN ('only'))"lines 305–305conn = sqlite3.connect(":memory:")lines 306–306◇ for vocab in [one, *(v for v in VOCABULARIES.values() if len(v.values) == 1)]lines 307–307conn.execute(f"CREATE TABLE probe (c TEXT {vocab.check('c')})")lines 308–308conn.execute("INSERT INTO probe VALUES (?)", (vocab.values[0],))lines 309–309with pytest.raises(sqlite3.IntegrityError)lines 310–310conn.execute("INSERT INTO probe VALUES ('__not_a_member__')")lines 311–311conn.execute("DROP TABLE probe")lines 312–312conn.close()

test_the_five_strength_vocabularies_are_distinct_objects

None test_vocabulary.test_the_five_strength_vocabularies_are_distinct_objects()

Five columns share the tuple ('low','medium','high') and mean five different things — spawn-detection strength, inferred-vs-declared provenance, lock-identity certainty, acquisition-resolution success, and a constant on external_boundaries. One shared object would mean adding a value for ONE silently widens the CHECK on the other four, with every registry-vs-registry test still green.

tests/test_vocabulary.py:408

Show on the map →

Called by none

Calls all

Checks

  • assert all(v.values == ("low", "medium", "high") for v in five)
  • assert len({id(v) for v in five}) == 5
  • assert len({v.id for v in five}) == 5
  • assert len({v.means for v in five}) == 5

Result: passed

Verifies

requirementlinkedpath to the implementer
REQ-DDB-WIKI-054inferredtest_the_five_strength_vocabularies_are_distinct_objects → all
Source · 14 lines
def test_the_five_strength_vocabularies_are_distinct_objects() -> None:
    """Five columns share the tuple ('low','medium','high') and mean five
    different things — spawn-detection strength, inferred-vs-declared
    provenance, lock-identity certainty, acquisition-resolution success, and a
    constant on external_boundaries. One shared object would mean adding a value
    for ONE silently widens the CHECK on the other four, with every
    registry-vs-registry test still green."""
    five = [THREAD_STRENGTH, KEY_STRENGTH, LOCK_IDENTITY, ACQ_STRENGTH, BOUNDARY_STRENGTH]
    assert all(v.values == ("low", "medium", "high") for v in five)
    assert len({id(v) for v in five}) == 5
    assert len({v.id for v in five}) == 5
    assert len({v.means for v in five}) == 5

Activity · 5 steps
lines 415–415five = [THREAD_STRENGTH, KEY_STRENGTH, LOCK_IDENTITY, ACQ_STRENGTH, BOUNDARY_STRENGTH]lines 416–416assert all(v.values == ("low", "medium", "high") for v in five)lines 417–417assert len({id(v) for v in five}) == 5lines 418–418assert len({v.id for v in five}) == 5lines 419–419assert len({v.means for v in five}) == 5

test_validated_returns_members_and_raises_on_anything_else

None test_vocabulary.test_validated_returns_members_and_raises_on_anything_else()

The message must name the origin, the token and the full allowed set — that triple is what makes a fail-closed refusal cheaper to fix than a silent normalization.

tests/test_vocabulary.py:442

Show on the map →

Called by none

Calls none

Checks

  • assert THREAD_KIND.validated("pthread", owner="x", field="kind") == "pthread"
  • assert ".clew.yaml [thread_patterns]" in message
  • assert "'pthred'" in message
  • assert "task, pthread, win32, timer, isr, main, oneshot, process, coroutine, unknown" in message

Result: passed

Verifies

requirementlinkedpath to the implementer
REQ-DDB-SCHEMA-012measured
Source · 19 lines
def test_validated_returns_members_and_raises_on_anything_else() -> None:
    """The message must name the origin, the token and the full allowed set —
    that triple is what makes a fail-closed refusal cheaper to fix than a
    silent normalization."""
    assert THREAD_KIND.validated("pthread", owner="x", field="kind") == "pthread"
    with pytest.raises(DeclarationError) as exc:
        THREAD_KIND.validated("pthred", owner=".clew.yaml [thread_patterns]", field="kind")
    message = str(exc.value)
    assert ".clew.yaml [thread_patterns]" in message
    assert "'pthred'" in message
    # Spelled out in full, in declared order, and updated DELIBERATELY when the
    # vocabulary grows — #58 added `process`/`coroutine` for Python's spawn
    # primitives, and `win32` arrived with the Windows ones. The point of the
    # literal is that widening a fail-closed vocabulary is a decision someone has
    # to make on purpose, not a diff that slips through because the assertion was
    # derived from the thing it checks.
    assert "task, pthread, win32, timer, isr, main, oneshot, process, coroutine, unknown" in message

Activity · 7 steps
lines 446–446assert THREAD_KIND.validated("pthread", owner="x", field="kind") == "pthread"lines 447–447with pytest.raises(DeclarationError) as exclines 448–448THREAD_KIND.validated("pthred", owner=".clew.yaml [thread_patterns]", field="kind")lines 449–449message = str(exc.value)lines 450–450assert ".clew.yaml [thread_patterns]" in messagelines 451–451assert "'pthred'" in messagelines 458–458assert "task, pthread, win32, timer, isr, main, oneshot, process, coroutine, unknown" in message