askrobots / dbbasic-object-server
Public
Runs live, versioned Python application objects on one VM, with a suite of apps: projects, notes, tasks, files and more.
test_dron_regex.py · 18.8 KB · 412 lines
| 1 | """The DRON regular-expression dialect (docs/dron.md, "Regular expressions"). |
| 2 | |
| 3 | A `validation.pattern` is written in a subset Python's `re` and ECMAScript |
| 4 | read alike, and means one thing: the whole value matches. This file holds |
| 5 | |
| 6 | - the table of patterns with the verdict (in the dialect or not, and why); |
| 7 | - the agreement: for every pattern in the dialect, the engine's answer on each |
| 8 | sample equals ECMAScript's, `new RegExp("^(?:" + pattern + ")$", "u")`. |
| 9 | ECMAScript's answers are in tests/dron_regex_ecmascript.json, written by |
| 10 | Node from this file's cases (tests/dron_regex_reference.js says how); when |
| 11 | `node` is installed the test also runs it afresh; |
| 12 | - the places Python's own reading differs, each shown to differ; |
| 13 | - every pattern shipped in a package or in dron/*.schema.json. |
| 14 | |
| 15 | Run as a script, it prints the cases for the reference script. |
| 16 | """ |
| 17 | |
| 18 | from __future__ import annotations |
| 19 | |
| 20 | import json |
| 21 | import re |
| 22 | import shutil |
| 23 | import subprocess |
| 24 | import sys |
| 25 | from pathlib import Path |
| 26 | |
| 27 | import pytest |
| 28 | |
| 29 | ROOT = Path(__file__).resolve().parent.parent |
| 30 | if __name__ == "__main__": |
| 31 | sys.path.insert(0, str(ROOT)) |
| 32 | |
| 33 | import object_records # noqa: E402 |
| 34 | import object_schemas # noqa: E402 |
| 35 | |
| 36 | REFERENCE = Path(__file__).with_name("dron_regex_ecmascript.json") |
| 37 | REFERENCE_SCRIPT = Path(__file__).with_name("dron_regex_reference.js") |
| 38 | |
| 39 | |
| 40 | def _walk_patterns(node): |
| 41 | if isinstance(node, dict): |
| 42 | for key, value in node.items(): |
| 43 | if key == "pattern" and isinstance(value, str): |
| 44 | yield value |
| 45 | elif key == "patternProperties" and isinstance(value, dict): |
| 46 | yield from value |
| 47 | yield from _walk_patterns(value) |
| 48 | else: |
| 49 | yield from _walk_patterns(value) |
| 50 | elif isinstance(node, list): |
| 51 | for value in node: |
| 52 | yield from _walk_patterns(value) |
| 53 | |
| 54 | |
| 55 | def _patterns_in(paths) -> dict[str, list[str]]: |
| 56 | """pattern -> the files that hold it.""" |
| 57 | found: dict[str, list[str]] = {} |
| 58 | for path in paths: |
| 59 | for pattern in _walk_patterns(json.loads(path.read_text(encoding="utf-8"))): |
| 60 | found.setdefault(pattern, []).append(str(path.relative_to(ROOT))) |
| 61 | return found |
| 62 | |
| 63 | |
| 64 | PACKAGE_PATTERNS = _patterns_in(sorted(ROOT.glob("packages*/*/schemas/*.json"))) |
| 65 | SCHEMA_FILE_PATTERNS = _patterns_in(sorted((ROOT / "dron").glob("*.schema.json"))) |
| 66 | |
| 67 | # In the dialect, one of each construct. The shipped patterns are added below. |
| 68 | ALLOWED = [ |
| 69 | # literals and the empty pattern |
| 70 | "", "a", "abc", "a b", "é", "😀", "a-b", "-", "#", "=!<>:,@%&~'\"`;_", "&&", "--", |
| 71 | # any character |
| 72 | ".", ".*", "a.b", ".{2}", ".+", |
| 73 | # classes and ranges |
| 74 | "[a-z]+", "[^a-z]+", "[A-Za-z0-9_]{1,64}", "[-a]+", "[a-]+", "[^-a]+", r"[a\-z]+", r"[\]\[]+", |
| 75 | r"[\^a]+", "[a^]+", "[.]", "[$]", "[(){}|/*+?]+", "[+--]+", "[--a]+", "[à-ÿ]+", "[😀]", "[ ]+", |
| 76 | r"[\x00-\x1f]", r"[\u2028]", r"[\u00e0-\u00ff]+", r"[\t\n\r\f\v]+", r"[\\]", r"[\/]", "[&|~]+", |
| 77 | # the class escapes, outside and inside a class |
| 78 | r"\d+", r"\D+", r"\w+", r"\W+", r"\s+", r"\S+", r"[\s]+", r"[^\s]+", r"[\d.]+", r"[^\d]+", |
| 79 | r"[\w-]+", r"[^\w]+", r"[\D]+", r"[\W]+", r"[\s\d]+", r"[^\s@]+@[^\s@]+", r"[-\d]+", |
| 80 | # character escapes |
| 81 | r"\t", r"\n", r"\r", r"\f", r"\v", r"\x41", r"\u00e9", r"\u0041+", r"\.", r"\/", r"\\", |
| 82 | r"\{value\}", r"\(\)", r"\[\]", r"\^\$", r"\*\+\?\|", r"\u2028", r"\xa0", |
| 83 | # anchors |
| 84 | "^a$", "^", "$", "^$", "a$|b", "a|^b", r"a$\n", r"(?=[a\n]$)[a\n]+", "(^a)|(b$)", |
| 85 | # groups, alternation, lookahead |
| 86 | "a|b", "a|b|", "|a", "(a|b)+", "(?:ab)*", "((a)(b))+", "()", "(?=a)\\w+", "(?!a)\\w+", |
| 87 | "(?=.{1,3}$)[a-z]+", "(?!.*aa)[ab]+", "(a|ab)(c|bcd)", "(?:a|b)(?:c|d)?", |
| 88 | # quantifiers, greedy and lazy |
| 89 | "a?", "a*", "a+", "a{2}", "a{2,}", "a{1,2}", "a{0}", "a{0,0}", "a+?b", "a*?", "a??", "a{2}?", |
| 90 | "a{1,}?b", "(ab){2}", "[ab]{2,3}", r"\d{4}-\d{2}-\d{2}", "(a*)*", "(a|)+", "(a?)+b", |
| 91 | ] |
| 92 | PATTERNS = list(dict.fromkeys(ALLOWED + sorted(PACKAGE_PATTERNS) + sorted(SCHEMA_FILE_PATTERNS))) |
| 93 | |
| 94 | # Outside the dialect, with the words the refusal must hold. |
| 95 | REFUSED = [ |
| 96 | # does not parse anywhere |
| 97 | ("(", "the ( at position 0 is never closed"), |
| 98 | ("a)", "the ) at position 1 closes nothing"), |
| 99 | ("[a-", "the [ at position 0 is never closed"), |
| 100 | ("[a", "the [ at position 0 is never closed"), |
| 101 | ("*a", "the * at position 0 has nothing to repeat"), |
| 102 | ("a|*", "has nothing to repeat"), |
| 103 | ("a**", "it follows another quantifier"), |
| 104 | ("a{2}{3}", "it follows another quantifier"), |
| 105 | ("a{3,2}", "has its numbers out of order"), |
| 106 | ("[z-a]", "the range z-a at position 1 is out of order"), |
| 107 | ("a\\", "it ends in a backslash"), |
| 108 | # the forms the two engines read differently, or only one reads |
| 109 | ("(?<=a)b", "a lookbehind"), |
| 110 | ("(?<!a)b", "a lookbehind"), |
| 111 | ("(?<name>a)", "a named group"), |
| 112 | ("(?P<name>a)", "a named group"), |
| 113 | ("(?P=name)", "a named group"), |
| 114 | ("(?i)abc", "an inline flag"), |
| 115 | ("(?i:abc)", "an inline flag"), |
| 116 | ("(?s).", "an inline flag"), |
| 117 | ("(?m)^a$", "an inline flag"), |
| 118 | ("(?x) a", "an inline flag"), |
| 119 | ("(?-i:a)", "an inline flag"), |
| 120 | ("(?#note)a", "a comment"), |
| 121 | ("(?>a+)b", "an atomic group"), |
| 122 | ("(?(1)a|b)", "a conditional"), |
| 123 | (r"(a)\1", "a backreference"), |
| 124 | (r"(?:a)\9", "a backreference"), |
| 125 | (r"\k<name>", "a named backreference"), |
| 126 | ("a++", "a possessive quantifier"), |
| 127 | ("a*+", "a possessive quantifier"), |
| 128 | ("a?+", "a possessive quantifier"), |
| 129 | ("a{2}+", "a possessive quantifier"), |
| 130 | (r"\bword\b", "\\b (a word boundary) is not in the dialect"), |
| 131 | (r"a\B", "\\B (not a word boundary) is not in the dialect"), |
| 132 | (r"\Aabc", "\\A is not in the dialect; write ^"), |
| 133 | (r"abc\Z", "\\Z is not in the dialect; write $"), |
| 134 | (r"abc\z", "\\z is not in the dialect; write $"), |
| 135 | (r"\p{L}+", "a Unicode property"), |
| 136 | (r"\P{L}+", "a Unicode property"), |
| 137 | (r"\N{DASH}", "a named character"), |
| 138 | (r"\cA", "a control escape"), |
| 139 | (r"\0", "write \\x00"), |
| 140 | (r"\a", "write \\x07"), |
| 141 | (r"\e", "write \\x1b"), |
| 142 | (r"\U0001F600", "write the character itself"), |
| 143 | (r"\u{1F600}", "write \\uXXXX or the character itself"), |
| 144 | (r"\ud83d\ude00", "half of a surrogate pair"), |
| 145 | (r"\u12", "exactly 4 hexadecimal digits"), |
| 146 | (r"\x4", "exactly 2 hexadecimal digits"), |
| 147 | (r"\q", "the escape \\q at position 0 is not in the dialect"), |
| 148 | (r"a\-b", "write '-' without the backslash"), |
| 149 | (r"a\@b", "write '@' without the backslash"), |
| 150 | (r"a\ b", "write ' ' without the backslash"), |
| 151 | (r"\_", "write '_' without the backslash"), |
| 152 | ("a{,3}", "is not a count such as {2}, {2,} or {2,5}"), |
| 153 | ("a{x}", "write \\{ for a literal {"), |
| 154 | ("{value}", "write \\{ for a literal {"), |
| 155 | ("a}", "a literal } is written \\}"), |
| 156 | ("a]", "a literal ] is written \\]"), |
| 157 | ("^*", "an anchor cannot be repeated"), |
| 158 | ("$+", "an anchor cannot be repeated"), |
| 159 | ("(?=a)*a", "a lookahead cannot be repeated"), |
| 160 | ("(?!a)?b", "a lookahead cannot be repeated"), |
| 161 | # classes |
| 162 | ("[]a]", "is empty, or starts with a ]"), |
| 163 | ("[^]a]", "is empty, or starts with a ]"), |
| 164 | ("[]", "is empty, or starts with a ]"), |
| 165 | ("[a[b]", "a literal [ inside a class is written \\["), |
| 166 | ("[[:alpha:]]", "a literal [ inside a class is written \\["), |
| 167 | ("[a-z&&[^b]]", "&& inside a class"), |
| 168 | ("[a||b]", "|| inside a class"), |
| 169 | ("[a~~b]", "~~ inside a class"), |
| 170 | ("[a-z-9]", "a literal - inside a class is written first, last or as \\-"), |
| 171 | (r"[\w-z]", "\\w cannot start a range"), |
| 172 | (r"[a-\d]", "\\d cannot end a range"), |
| 173 | (r"[\S]", "\\S inside a class is not in the dialect"), |
| 174 | (r"[\b]", "write \\x08 for a backspace"), |
| 175 | (r"[\q]", "the escape \\q"), |
| 176 | ("\ud800", "half of a surrogate pair"), |
| 177 | ("[\udfff]", "half of a surrogate pair"), |
| 178 | ] |
| 179 | |
| 180 | SAMPLES = [ |
| 181 | "", "a", "b", "ab", "ba", "abc", "aa", "aaa", "abab", "ABC", "USD", "usd", "USD\n", "a\n", "\n", "\n\n", |
| 182 | "a\nb", "a\rb", "\r", "\r\n", "a\u2028b", "\u2028", "\u2029", " ", " ", "a b", "\t", "\v", "\f", |
| 183 | "\u00a0", "a\u00a0b", "\u1680", "\u2003", "\u202f", "\u205f", "\u3000", "\ufeff", "\u180e", "\u200b", |
| 184 | "\x1c", "\x1f", "\x85", "\x00", "\x08", "\x07", "1", "12", "2026-12-03", "2026-12-03T10:00:00Z", "١٢", "٣", |
| 185 | "12", "é", "É", "ß", "ſ", "K", "ÿ", "à", "😀", "a😀", "😀😀", "_", "-", "--", "a-b", "a-", "+", ",", ".", |
| 186 | "a.b", "a/b", "/", "/a b", "/a", "^", "$", "^$", "\\", "[", "]", "[]", "(", ")", "()", "{", "}", "|", "*", |
| 187 | "*+?|", "{value}", "x {value} y", "{other}", "&&", "&", "~", "#", "@", "x@y", "x y@z", "A", "Z", "z9_", |
| 188 | "foo.bar_1", "foo", "Foo", "foo-bar", "https://example.test/x", "http://example.test/a b", |
| 189 | "https://example.test/x\n", "ftp://example.test", "void,refund", "void,", "acd", "abcd", "abbcd", "bc", "bd", |
| 190 | "1.5e3", " 12 ", "1_0", "+.5", "example.test", "a..b", "role:admin", "user:", "public", "$x", "x$", |
| 191 | "0.2", "01.2", "0 0 * * *", "0 0 * * * *", "é" * 3, "e\u0301", "=!<>:,@%&~'\"`;_", "A" * 64, "A" * 65, |
| 192 | "0123456789abcdef" * 4, "collection/id", "a/b/c", |
| 193 | ] |
| 194 | |
| 195 | |
| 196 | def _cases() -> dict: |
| 197 | return {"patterns": PATTERNS, "refused": [pattern for pattern, _ in REFUSED], "samples": SAMPLES} |
| 198 | |
| 199 | |
| 200 | def _engine(pattern: str) -> list[int]: |
| 201 | return [index for index, sample in enumerate(SAMPLES) if object_schemas.pattern_matches(pattern, sample)] |
| 202 | |
| 203 | |
| 204 | def _disagreements(reference: dict) -> list[str]: |
| 205 | assert reference["samples"] == SAMPLES, ( |
| 206 | "the samples changed: regenerate tests/dron_regex_ecmascript.json (see dron_regex_reference.js)") |
| 207 | assert list(reference["matches"]) == PATTERNS, ( |
| 208 | "the patterns changed: regenerate tests/dron_regex_ecmascript.json (see dron_regex_reference.js)") |
| 209 | problems = [] |
| 210 | for pattern in PATTERNS: |
| 211 | ours, theirs = set(_engine(pattern)), set(reference["matches"][pattern]) |
| 212 | for index in sorted(ours ^ theirs): |
| 213 | problems.append( |
| 214 | f"{pattern!r} on {SAMPLES[index]!r}: engine {index in ours}, ECMAScript {index in theirs}") |
| 215 | return problems |
| 216 | |
| 217 | |
| 218 | # -- the table ------------------------------------------------------------- |
| 219 | |
| 220 | |
| 221 | def test_every_pattern_in_the_table_of_allowed_ones_is_in_the_dialect(): |
| 222 | refused = {pattern: object_schemas.pattern_problem(pattern) for pattern in PATTERNS} |
| 223 | assert {pattern: why for pattern, why in refused.items() if why} == {} |
| 224 | |
| 225 | |
| 226 | def test_every_pattern_in_the_table_of_refused_ones_is_refused_and_says_why(): |
| 227 | wrong = [] |
| 228 | for pattern, expected in REFUSED: |
| 229 | problem = object_schemas.pattern_problem(pattern) |
| 230 | if problem is None or expected not in problem: |
| 231 | wrong.append((pattern, expected, problem)) |
| 232 | assert wrong == [] |
| 233 | |
| 234 | |
| 235 | def test_a_pattern_that_is_not_text_is_not_one(): |
| 236 | for value in (5, None, ["a"], True): |
| 237 | assert "it must be text" in object_schemas.pattern_problem(value) |
| 238 | |
| 239 | |
| 240 | def test_a_count_too_large_to_compile_is_refused_not_raised(): |
| 241 | assert "does not compile" in object_schemas.pattern_problem("a{99999999999999999999}") |
| 242 | |
| 243 | |
| 244 | def test_the_refused_table_covers_what_the_page_says_is_left_out(): |
| 245 | words = " ".join(expected for _, expected in REFUSED) |
| 246 | for kind in ("lookbehind", "named group", "inline flag", "backreference", "possessive", "atomic", |
| 247 | "conditional", "comment", "word boundary", "\\A", "\\Z", "Unicode property", "control escape"): |
| 248 | assert kind in words, kind |
| 249 | |
| 250 | |
| 251 | # -- agreement with ECMAScript --------------------------------------------- |
| 252 | |
| 253 | |
| 254 | def test_the_engine_agrees_with_ecmascript_on_every_allowed_pattern_and_sample(): |
| 255 | assert _disagreements(json.loads(REFERENCE.read_text(encoding="utf-8"))) == [] |
| 256 | |
| 257 | |
| 258 | def test_the_recorded_ecmascript_answers_are_what_node_gives_today(): |
| 259 | node = shutil.which("node") |
| 260 | if node is None: |
| 261 | pytest.skip("node is not installed; the recorded answers are compared in the test above") |
| 262 | done = subprocess.run( |
| 263 | [node, str(REFERENCE_SCRIPT)], input=json.dumps(_cases()), capture_output=True, text=True, |
| 264 | encoding="utf-8", timeout=120, check=True) |
| 265 | assert json.loads(done.stdout) == json.loads(REFERENCE.read_text(encoding="utf-8")) |
| 266 | |
| 267 | |
| 268 | def test_the_agreement_is_not_empty(): |
| 269 | # Each allowed pattern but the ones nothing here can match is exercised |
| 270 | # both ways, so an engine that answered False to everything would fail. |
| 271 | reference = json.loads(REFERENCE.read_text(encoding="utf-8")) |
| 272 | matched = [pattern for pattern in PATTERNS if reference["matches"][pattern]] |
| 273 | assert len(matched) >= len(PATTERNS) - 3 |
| 274 | assert all(len(reference["matches"][pattern]) < len(SAMPLES) for pattern in PATTERNS) |
| 275 | assert len(PATTERNS) > 150 and len(SAMPLES) > 120 |
| 276 | |
| 277 | |
| 278 | # -- where Python's own reading differs, and the dialect's does not --------- |
| 279 | |
| 280 | # (pattern, value, what Python's re.fullmatch says, what the dialect and ECMAScript say) |
| 281 | PYTHON_DIFFERS = [ |
| 282 | # `$` also matches before a final newline in Python. |
| 283 | (r"a$\n", "a\n", True, False), |
| 284 | (r"(?=[a\n]$)[a\n]+", "a\n", True, False), |
| 285 | (r"(?=.*$)[^x]+", "ab\n", True, False), |
| 286 | # `\d` and `\w` are every Unicode digit and letter in Python. |
| 287 | (r"\d+", "١٢", True, False), |
| 288 | (r"\d+", "12", True, False), |
| 289 | (r"\w+", "é", True, False), |
| 290 | (r"[\w-]+", "naïve", True, False), |
| 291 | (r"\W", "é", False, True), |
| 292 | (r"\D", "٣", False, True), |
| 293 | # `\s`: Python counts the separators U+001C to U+001F and U+0085, ECMAScript |
| 294 | # counts U+FEFF; re.ASCII would count neither, nor a no-break space. |
| 295 | (r"\s", "\x1c", True, False), |
| 296 | (r"\s", "\x85", True, False), |
| 297 | (r"\S", "\x1f", False, True), |
| 298 | (r"\s", "\ufeff", False, True), |
| 299 | (r"[^\s@]+@[^\s@]+", "x\ufeff@y", True, False), |
| 300 | # `.` leaves out only \n in Python; ECMAScript leaves out \r, U+2028 and U+2029 too. |
| 301 | (r"a.b", "a\rb", True, False), |
| 302 | (r".", "\u2028", True, False), |
| 303 | (r".*", "a\u2029b", True, False), |
| 304 | ] |
| 305 | |
| 306 | |
| 307 | def test_each_documented_difference_is_real_and_the_dialect_takes_the_ecmascript_side(): |
| 308 | wrong = [] |
| 309 | for pattern, value, python_says, dialect_says in PYTHON_DIFFERS: |
| 310 | if (re.fullmatch(pattern, value) is not None) != python_says: |
| 311 | wrong.append(("python", pattern, value)) |
| 312 | if object_schemas.pattern_matches(pattern, value) != dialect_says: |
| 313 | wrong.append(("dialect", pattern, value)) |
| 314 | assert wrong == [] |
| 315 | |
| 316 | |
| 317 | def test_re_ascii_alone_would_not_give_ecmascript_white_space(): |
| 318 | # Why `\s` is spelt out instead of left to re.ASCII. |
| 319 | for space in ("\u00a0", "\u2028", "\u3000", "\ufeff"): |
| 320 | assert re.fullmatch(r"\s", space, re.ASCII) is None |
| 321 | assert object_schemas.pattern_matches(r"\s", space) |
| 322 | for pattern, value, _, dialect_says in PYTHON_DIFFERS: |
| 323 | assert pattern in PATTERNS or object_schemas.pattern_problem(pattern) is None |
| 324 | |
| 325 | |
| 326 | def test_a_value_ending_in_a_newline_does_not_match_a_pattern_ending_in_dollar(): |
| 327 | for pattern in ("^[A-Z]{3}$", "[A-Z]{3}$", "^https?://\\S+$", "^[a-z][a-z0-9_]*$", "^.*$", "^[^x]*$"): |
| 328 | value = {"^https?://\\S+$": "https://example.test/x"}.get(pattern, "USD" if "A-Z" in pattern else "usd") |
| 329 | assert object_schemas.pattern_matches(pattern, value), pattern |
| 330 | if pattern != "^[^x]*$": # a class that admits a newline admits it |
| 331 | assert not object_schemas.pattern_matches(pattern, value + "\n"), pattern |
| 332 | assert object_schemas.pattern_matches("^[^x]*$", "usd\n") |
| 333 | # Searching, as a JSON Schema validator does: Python's `$` would find a match. |
| 334 | assert re.search("^[A-Z]{3}$", "USD\n") is not None |
| 335 | source = object_schemas.portable_pattern_source("^[A-Z]{3}$") |
| 336 | assert re.compile(source, re.ASCII).search("USD\n") is None |
| 337 | assert re.compile(source, re.ASCII).search("USD") is not None |
| 338 | |
| 339 | |
| 340 | def test_the_whole_value_must_match_with_or_without_anchors(): |
| 341 | assert object_schemas.pattern_matches("[a-z]+", "abc") |
| 342 | assert not object_schemas.pattern_matches("[a-z]+", "abc1") |
| 343 | assert not object_schemas.pattern_matches("a|ab", "abc") |
| 344 | assert object_schemas.pattern_matches("a|ab", "ab") |
| 345 | |
| 346 | |
| 347 | # -- the engine ------------------------------------------------------------ |
| 348 | |
| 349 | |
| 350 | def _field(pattern): |
| 351 | return {"name": "code", "validation": {"pattern": pattern}} |
| 352 | |
| 353 | |
| 354 | def test_a_write_is_judged_with_the_dialects_meaning(): |
| 355 | object_records._validate_field_rules(_field(r"\d+"), "12") |
| 356 | for pattern, value in ((r"\d+", "١٢"), (r"a$\n", "a\n"), ("a.b", "a\rb"), (r"\S+", "a\ufeffb")): |
| 357 | with pytest.raises(object_records.InvalidRecordPayloadError, match="does not match pattern"): |
| 358 | object_records._validate_field_rules(_field(pattern), value) |
| 359 | |
| 360 | |
| 361 | def test_a_stored_pattern_outside_the_dialect_is_still_read_as_python_read_it(): |
| 362 | # A schema already on the box (or saved through the schema API) is not |
| 363 | # refused: its pattern keeps the meaning it had. |
| 364 | for pattern, good, bad in ((r"(?i)usd", "UsD", "eur"), (r"(?<=a)b|\bab\b", "ab", "abc"), |
| 365 | (r"(?P<y>\d{4})-(?P=y)", "٢٠٢٦-٢٠٢٦", "2026-2025")): |
| 366 | assert object_schemas.pattern_problem(pattern) |
| 367 | object_records._validate_field_rules(_field(pattern), good) |
| 368 | with pytest.raises(object_records.InvalidRecordPayloadError, match="does not match pattern"): |
| 369 | object_records._validate_field_rules(_field(pattern), bad) |
| 370 | with pytest.raises(object_records.InvalidRecordPayloadError, match="validation pattern is invalid"): |
| 371 | object_records._validate_field_rules(_field("("), "a") |
| 372 | # The stored synonym is read the same way. |
| 373 | object_records._validate_field_rules({"name": "code", "validation": {"regex": "[a-z]+$"}}, "abc") |
| 374 | |
| 375 | |
| 376 | def test_normalizing_a_stored_schema_does_not_refuse_a_pattern_outside_the_dialect(): |
| 377 | schema = object_schemas.normalize_schema( |
| 378 | "widgets", {"name": "widgets", "fields": [{"name": "id"}, _field(r"(?i)\bab\b")]}) |
| 379 | assert schema["fields"][1]["validation"]["pattern"] == r"(?i)\bab\b" |
| 380 | |
| 381 | |
| 382 | def test_a_declaration_with_a_pattern_outside_the_dialect_is_refused_by_name(): |
| 383 | with pytest.raises(ValueError) as refused: |
| 384 | object_schemas.normalize_declaration( |
| 385 | "widgets", {"name": "widgets", "fields": [{"name": "id"}, _field(r"(?i)\bab\b")]}) |
| 386 | assert str(refused.value).endswith( |
| 387 | "field 'code' validation: pattern '(?i)\\\\bab\\\\b' is not a DRON regular expression: an inline flag " |
| 388 | "((?i at position 0) is not in the dialect; write both cases, as in [Aa]. " |
| 389 | 'The dialect is in docs/dron.md, "Regular expressions"') |
| 390 | |
| 391 | |
| 392 | # -- what is shipped -------------------------------------------------------- |
| 393 | |
| 394 | |
| 395 | def test_every_pattern_a_shipped_package_declares_is_in_the_dialect(): |
| 396 | assert len(PACKAGE_PATTERNS) >= 10 |
| 397 | outside = {pattern: (object_schemas.pattern_problem(pattern), files) |
| 398 | for pattern, files in PACKAGE_PATTERNS.items() if object_schemas.pattern_problem(pattern)} |
| 399 | assert outside == {} |
| 400 | |
| 401 | |
| 402 | def test_every_pattern_in_the_dron_schema_files_is_in_the_dialect(): |
| 403 | # A JSON Schema validator searches, and these say so with their own |
| 404 | # anchors; the dialect is what makes the anchors mean one thing. |
| 405 | assert len(SCHEMA_FILE_PATTERNS) >= 25 |
| 406 | outside = {pattern: (object_schemas.pattern_problem(pattern), files) |
| 407 | for pattern, files in SCHEMA_FILE_PATTERNS.items() if object_schemas.pattern_problem(pattern)} |
| 408 | assert outside == {} |
| 409 | |
| 410 | |
| 411 | if __name__ == "__main__": |
| 412 | json.dump(_cases(), sys.stdout) |