Compare commits
99 Commits
1.0.18
...
1c08a8f2b8
| Author | SHA1 | Date | |
|---|---|---|---|
| 1c08a8f2b8 | |||
| bb263190f6 | |||
| 737c0b04ac | |||
| 2d1fca599b | |||
| 8d0369c672 | |||
| 566b599512 | |||
| e7f20e2cb6 | |||
| 3898c43742 | |||
| e14f53e7d9 | |||
| 960a99034a | |||
| 81388149e8 | |||
| b8b3f7a501 | |||
| bc5489b1ea | |||
| 7b55277116 | |||
| ed636b05a4 | |||
| 2aec2da2fd | |||
| ad78896f72 | |||
| 55b93d9957 | |||
| 7ec6e09ae0 | |||
| 9d9c6d2c06 | |||
| 12e952fa94 | |||
| 776a912098 | |||
| 612188a54b | |||
| 29c5160b49 | |||
| 944675d669 | |||
| 53a40d1099 | |||
| e55977c11b | |||
| 8e50d4852d | |||
| 623c34c0bc | |||
| 32ed463df8 | |||
| 6e06b6fdc2 | |||
| 61735646ca | |||
| 54c34b2848 | |||
| 0f912c12b2 | |||
| b225afdd1b | |||
| f0bd32450d | |||
| bb17f153de | |||
| ec8bfad390 | |||
| 8a1b13b139 | |||
| 469dd0519b | |||
| 4b6ea6536c | |||
| d8a924c662 | |||
| f3d157ebcb | |||
| 44cde90c3d | |||
| 9ddc899411 | |||
| a8d726ec73 | |||
| 6b6647f2d6 | |||
| d301d5fab9 | |||
| 61511b595d | |||
| c7ae975275 | |||
| aa58082cd7 | |||
| 491fb3a3e3 | |||
| fc939d84ee | |||
| d6b34c99bb | |||
| cc04f38c14 | |||
| c9b1245a57 | |||
| 3d770b0831 | |||
| 3fdbf60396 | |||
| 6610b069db | |||
| bb84f9aa73 | |||
| 704770051c | |||
| 88c77deede | |||
| 0184c244d9 | |||
| e40de2eb12 | |||
| 5e55786e3e | |||
| 6520413069 | |||
| b97879ff61 | |||
| ea0b139f87 | |||
| dccaa0a46e | |||
| 441597e604 | |||
| 710598752f | |||
| 5fbf64bac5 | |||
| 2dd17f0b37 | |||
| cbda45e610 | |||
| 1085964c17 | |||
| 65971d9b93 | |||
| d938058d34 | |||
| 69ab6165bb | |||
| 03beada825 | |||
| efdd7528cc | |||
| 59395a33ac | |||
| 92c0a6fc0b | |||
| 7f66a4a35a | |||
| d37aadb0dd | |||
| d0ccc47d97 | |||
| 2d19bf100e | |||
| fb333c6cbb | |||
| d8a9a7b76b | |||
| c9022aefb9 | |||
| ccf0465e45 | |||
| dce50d9dc3 | |||
| 8ec6a5b58a | |||
| 6ef7e0c55e | |||
| 1cb5fb0ecf | |||
| d66aae8ae2 | |||
| 3b18901bda | |||
| b8c0e08068 | |||
| c734983a59 | |||
| 9b11f661bc |
49
.agent/workflows/jspg.md
Normal file
49
.agent/workflows/jspg.md
Normal file
@ -0,0 +1,49 @@
|
||||
---
|
||||
description: jspg work preparation
|
||||
---
|
||||
|
||||
This workflow will get you up-to-speed on the JSPG custom json-schema-based cargo pgrx postgres validation extension. Everything you read will be in the jspg directory/project.
|
||||
|
||||
Read over this entire workflow and commit to every section of work in a task list, so that you don't stop half way through before reviewing all of the directories and files mentioned. Do not ask for confirmation after generating this task list and proceed through all sections in your list.
|
||||
|
||||
Please analyze the files and directories and do not use cat, find, or the terminal to discover or read in any of these files. Analyze every file mentioned. If a directory is mentioned or a /*, please analyze the directory, every single file at its root, and recursively analyze every subdirectory and every single file in every subdirectory to capture not just critical files, but the entirety of what is requested. I state again, DO NOT just review a cherry picking of files in any folder or wildcard specified. Review 100% of all files discovered recursively!
|
||||
|
||||
Section 1: Documentation
|
||||
|
||||
- GEMINI.md at the root
|
||||
|
||||
Section 2: Flow file for cmd interface
|
||||
|
||||
- flow at the root
|
||||
|
||||
Section 3: Source
|
||||
|
||||
- src/*
|
||||
|
||||
Section 4: Test Fixtures
|
||||
|
||||
- Just review some of the *.json files in tests/fixtures/*
|
||||
|
||||
Section 5: Build
|
||||
|
||||
- build.rs
|
||||
|
||||
Section 6: Cargo TOML
|
||||
|
||||
- Cargo.toml
|
||||
|
||||
Section 7: Some PUNC Syntax
|
||||
|
||||
Now, review some punc type and enum source in the api project with api/ these files:
|
||||
|
||||
- punc/sql/tables.sql
|
||||
- punc/sql/domains.sql
|
||||
- punc/sql/indexes.sql
|
||||
- punc/sql/functions/entity.sql
|
||||
- punc/sql/functions/puncs.sql
|
||||
- punc/sql/puncs/entity.sql
|
||||
- punc/sql/puncs/persons.sql
|
||||
- punc/sql/puncs/puncs.sql
|
||||
- punc/sql/puncs/job.sql
|
||||
|
||||
Now you are ready to help me work on this extension.
|
||||
13
.env
13
.env
@ -1,13 +0,0 @@
|
||||
ENVIRONMENT=local
|
||||
DATABASE_PASSWORD=tIr4TJ0qUwGVM0rlQSe3W7Tgpi33zPbk
|
||||
DATABASE_ROLE=agreego_admin
|
||||
DATABASE_HOST=127.1.27.4
|
||||
DATABASE_PORT=5432
|
||||
POSTGRES_PASSWORD=xzIq5JT0xY3F+2m1GtnrKDdK29sNSXVVYZHPKJVh8pI=
|
||||
DATABASE_NAME=agreego
|
||||
DEV_DATABASE_NAME=agreego_dev
|
||||
GITEA_TOKEN=3d70c23673517330623a5122998fb304e3c73f0a
|
||||
MOOV_ACCOUNT_ID=69a0d2f6-77a2-4e26-934f-d869134f87d3
|
||||
MOOV_PUBLIC_KEY=9OMhK5qGnh7Tmk2Z
|
||||
MOOV_SECRET_KEY=DrRox7B-YWfO9IheiUUX7lGP8-7VY-Ni
|
||||
MOOV_DOMAIN=http://localhost
|
||||
3
.geminiignore
Normal file
3
.geminiignore
Normal file
@ -0,0 +1,3 @@
|
||||
/target/
|
||||
/package/
|
||||
.env
|
||||
5
.gitignore
vendored
5
.gitignore
vendored
@ -1,2 +1,5 @@
|
||||
/target
|
||||
/package
|
||||
/package
|
||||
.env
|
||||
/src/tests.rs
|
||||
/pgrx-develop
|
||||
3
.gitmodules
vendored
3
.gitmodules
vendored
@ -1,3 +1,6 @@
|
||||
[submodule "flows"]
|
||||
path = flows
|
||||
url = git@gitea-ssh.thoughtpatterns.ai:cellular/flows.git
|
||||
[submodule "tests/fixtures/JSON-Schema-Test-Suite"]
|
||||
path = tests/fixtures/JSON-Schema-Test-Suite
|
||||
url = git@github.com:json-schema-org/JSON-Schema-Test-Suite.git
|
||||
|
||||
1835
Cargo.lock
generated
1835
Cargo.lock
generated
File diff suppressed because it is too large
Load Diff
39
Cargo.toml
39
Cargo.toml
@ -1,18 +1,35 @@
|
||||
[package]
|
||||
name = "jspg"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
edition = "2024"
|
||||
|
||||
[dependencies]
|
||||
pgrx = "0.14.0"
|
||||
serde = { version = "1.0", features = ["derive"] }
|
||||
serde_json = "1.0"
|
||||
jsonschema = "0.29.1"
|
||||
pgrx = "0.16.1"
|
||||
serde = { version = "1.0.228", features = ["derive", "rc"] }
|
||||
serde_json = "1.0.149"
|
||||
lazy_static = "1.5.0"
|
||||
boon = "0.6.1"
|
||||
once_cell = "1.21.3"
|
||||
ahash = "0.8.12"
|
||||
regex = "1.12.3"
|
||||
regex-syntax = "0.8.9"
|
||||
url = "2.5.8"
|
||||
fluent-uri = "0.3.2"
|
||||
idna = "1.1.0"
|
||||
percent-encoding = "2.3.2"
|
||||
uuid = { version = "1.20.0", features = ["v4", "serde"] }
|
||||
chrono = { version = "0.4.43", features = ["serde"] }
|
||||
json-pointer = "0.3.4"
|
||||
indexmap = { version = "2.13.0", features = ["serde"] }
|
||||
moka = { version = "0.12.14", features = ["sync"] }
|
||||
xxhash-rust = { version = "0.8.15", features = ["xxh64"] }
|
||||
dashmap = "6.1.0"
|
||||
|
||||
[dev-dependencies]
|
||||
pgrx-tests = "0.14.0"
|
||||
pgrx-tests = "0.16.1"
|
||||
|
||||
[build-dependencies]
|
||||
serde = { version = "1.0.228", features = ["derive"] }
|
||||
serde_json = "1.0.149"
|
||||
|
||||
[lib]
|
||||
crate-type = ["cdylib", "lib"]
|
||||
@ -22,7 +39,8 @@ name = "pgrx_embed_jspg"
|
||||
path = "src/bin/pgrx_embed.rs"
|
||||
|
||||
[features]
|
||||
pg17 = ["pgrx/pg17", "pgrx-tests/pg17" ]
|
||||
default = ["pg18"]
|
||||
pg18 = ["pgrx/pg18", "pgrx-tests/pg18" ]
|
||||
# Local feature flag used by `cargo pgrx test`
|
||||
pg_test = []
|
||||
|
||||
@ -34,4 +52,7 @@ lto = "thin"
|
||||
panic = "unwind"
|
||||
opt-level = 3
|
||||
lto = "fat"
|
||||
codegen-units = 1
|
||||
codegen-units = 1
|
||||
|
||||
[package.metadata.jspg]
|
||||
target_draft = "draft2020-12"
|
||||
|
||||
94
GEMINI.md
Normal file
94
GEMINI.md
Normal file
@ -0,0 +1,94 @@
|
||||
# JSPG: JSON Schema Postgres
|
||||
|
||||
**JSPG** is a high-performance PostgreSQL extension written in Rust (using `pgrx`) that transforms Postgres into a pre-compiled Semantic Engine. It serves as the core engine for the "Punc" architecture, where the database is the single source of truth for all data models, API contracts, validations, and reactive queries.
|
||||
|
||||
## 1. Overview & Architecture
|
||||
|
||||
JSPG operates by deeply integrating the JSON Schema Draft 2020-12 specification directly into the Postgres session lifecycle. It is built around three core pillars:
|
||||
* **Validator**: In-memory, near-instant JSON structural validation and type polymorphism routing.
|
||||
* **Merger**: Automatically traverse and UPSERT deeply nested JSON graphs into normalized relational tables.
|
||||
* **Queryer**: Compile JSON Schemas into static, cached SQL SPI `SELECT` plans for fetching full entities or isolated "Stems".
|
||||
|
||||
### 🎯 Goals
|
||||
1. **Draft 2020-12 Compliance**: Attempt to adhere to the official JSON Schema Draft 2020-12 specification.
|
||||
2. **Ultra-Fast Execution**: Compile schemas into optimized in-memory validation trees and cached SQL SPIs to bypass Postgres Query Builder overheads.
|
||||
3. **Connection-Bound Caching**: Leverage the PostgreSQL session lifecycle using an **Atomic Swap** pattern. Schemas are 100% frozen, completely eliminating locks during read access.
|
||||
4. **Structural Inheritance**: Support object-oriented schema design via Implicit Keyword Shadowing and virtual `$family` references natively mapped to Postgres table constraints.
|
||||
5. **Reactive Beats**: Provide natively generated "Stems" (isolated payload fragments) for dynamic websocket reactivity.
|
||||
|
||||
### Concurrency & Threading ("Immutable Graphs")
|
||||
To support high-throughput operations while allowing for runtime updates (e.g., during hot-reloading), JSPG uses an **Atomic Swap** pattern:
|
||||
1. **Parser Phase**: Schema JSONs are parsed into ordered `Schema` structs.
|
||||
2. **Compiler Phase**: The database iterates all parsed schemas and pre-computes native optimization maps (Descendants Map, Depths Map, Variations Map).
|
||||
3. **Immutable Validator**: The `Validator` struct immutably owns the `Database` registry and all its global maps. Schemas themselves are completely frozen; `$ref` strings are resolved dynamically at runtime using pre-computed O(1) maps.
|
||||
4. **Lock-Free Reads**: Incoming operations acquire a read lock just long enough to clone the `Arc` inside an `RwLock<Option<Arc<Validator>>>`, ensuring zero blocking during schema updates.
|
||||
|
||||
---
|
||||
|
||||
## 2. Validator
|
||||
|
||||
The Validator provides strict, schema-driven evaluation for the "Punc" architecture.
|
||||
|
||||
### API Reference
|
||||
* `jspg_setup(database jsonb) -> jsonb`: Loads and compiles the entire registry (types, enums, puncs, relations) atomically.
|
||||
* `mask_json_schema(schema_id text, instance jsonb) -> jsonb`: Validates and prunes unknown properties dynamically, returning masked data.
|
||||
* `jspg_validate(schema_id text, instance jsonb) -> jsonb`: Returns boolean-like success or structured errors.
|
||||
* `jspg_teardown() -> jsonb`: Clears the current session's schema cache.
|
||||
|
||||
### Custom Features & Deviations
|
||||
JSPG implements specific extensions to the Draft 2020-12 standard to support the Punc architecture's object-oriented needs while heavily optimizing for zero-runtime lookups.
|
||||
|
||||
#### A. Polymorphism & Referencing (`$ref`, `$family`, and Native Types)
|
||||
* **Native Type Discrimination (`variations`)**: Schemas defined inside a Postgres `type` are Entities. The validator securely and implicitly manages their `"type"` property. If an entity inherits from `user`, incoming JSON can safely define `{"type": "person"}` without errors, thanks to `compiled_variations` inheritance.
|
||||
* **Structural Inheritance & Viral Infection (`$ref`)**: `$ref` is used exclusively for structural inheritance, *never* for union creation. A Punc request schema that `$ref`s an Entity virally inherits all physical database polymorphism rules for that target.
|
||||
* **Shape Polymorphism (`$family`)**: Auto-expands polymorphic API lists based on an abstract Descendants Graph. If `{"$family": "widget"}` is used, JSPG evaluates the JSON against every schema that `$ref`s widget.
|
||||
* **Strict Matches & Depth Heuristic**: Polymorphic structures MUST match exactly **one** schema permutation. If multiple inherited struct permutations pass, JSPG applies the **Depth Heuristic Tie-Breaker**, selecting the candidate deepest in the inheritance tree.
|
||||
|
||||
#### B. Strict by Default & Extensibility
|
||||
* **Strictness**: By default, any property not explicitly defined in the schema causes a validation error (effectively enforcing `additionalProperties: false` globally).
|
||||
* **Extensibility (`extensible: true`)**: To allow a free-for-all of undefined properties, schemas must explicitly declare `"extensible": true`.
|
||||
* **Structured Additional Properties**: If `additionalProperties: {...}` is defined as a schema, arbitrary keys are allowed so long as their values match the defined type constraint.
|
||||
* **Inheritance Boundaries**: Strictness resets when crossing `$ref` boundaries. A schema extending a strict parent remains strict unless it explicitly overrides with `"extensible": true`.
|
||||
|
||||
#### C. Implicit Keyword Shadowing
|
||||
* **Inheritance (`$ref` + properties)**: Unlike standard JSON Schema, when a schema uses `$ref` alongside local properties, JSPG implements **Smart Merge**. Local constraints natively take precedence over (shadow) inherited constraints for the same keyword.
|
||||
* *Example*: If `entity` has `type: {const: "entity"}`, but `person` defines `type: {const: "person"}`, the local `person` const cleanly overrides the inherited one.
|
||||
* **Composition (`allOf`)**: When evaluating `allOf`, standard intersection rules apply seamlessly. No shadowing occurs, meaning all constraints from all branches must pass.
|
||||
|
||||
#### D. Format Leniency for Empty Strings
|
||||
To simplify frontend form validation, format validators specifically for `uuid`, `date-time`, and `email` explicitly allow empty strings (`""`), treating them as "present but unset".
|
||||
|
||||
---
|
||||
|
||||
|
||||
## 3. Merger
|
||||
|
||||
The Merger provides an automated, high-performance graph synchronization engine via the `jspg_merge(cue JSONB)` API. It orchestrates the complex mapping of nested JSON objects into normalized Postgres relational tables, honoring all inheritance and graph constraints.
|
||||
|
||||
### Core Features
|
||||
|
||||
* **Deep Graph Merging**: The Merger walks arbitrary levels of deeply nested JSON schemas (e.g. tracking an `order`, its `customer`, and an array of its `lines`). It intelligently discovers the correct parent-to-child or child-to-parent Foreign Keys stored in the registry and automatically maps the UUIDs across the relationships during UPSERT.
|
||||
* **Prefix Foreign Key Matching**: Handles scenario where multiple relations point to the same table by using database Foreign Key constraint prefixes (`fk_`). For example, if a schema has `shipping_address` and `billing_address`, the merger resolves against `fk_shipping_address_entity` vs `fk_billing_address_entity` automatically to correctly route object properties.
|
||||
* **Dynamic Deduplication & Lookups**: If a nested object is provided without an `id`, the Merger utilizes Postgres `lk_` index constraints defined in the schema registry (e.g. `lk_person` mapped to `first_name` and `last_name`). It dynamically queries these unique matching constraints to discover the correct UUID to perform an UPDATE, preventing data duplication.
|
||||
* **Hierarchical Table Inheritance**: The Punc system uses distributed table inheritance (e.g. `person` inherits `user` inherits `organization` inherits `entity`). The Merger splits the incoming JSON payload and performs atomic row updates across *all* relevant tables in the lineage map.
|
||||
* **The Archive Paradigm**: Data is never deleted in the Punc system. The Merger securely enforces referential integrity by toggling the `archived` Boolean flag on the base `entity` table rather than issuing SQL `DELETE` commands.
|
||||
* **Change Tracking & Reactivity**: The Merger diffs the incoming JSON against the existing database row (utilizing static, `DashMap`-cached `lk_` SELECT string templates). Every detected change is recorded into the `agreego.change` audit table, tracking the user mapping. It then natively uses `pg_notify` to broadcast a completely flat row-level diff out to the Go WebSocket server for O(1) routing.
|
||||
* **Many-to-Many Graph Edge Management**: Operates seamlessly with the global `agreego.relationship` table, allowing the system to represent and merge arbitrary reified M:M relationships directionally between any two entities.
|
||||
* **Sparse Updates**: Empty JSON strings `""` are directly bound as explicit SQL `NULL` directives to clear data, whilst omitted (missing) properties skip UPDATE execution entirely, ensuring partial UI submissions do not wipe out sibling fields.
|
||||
* **Unified Return Structure**: To eliminate UI hydration race conditions and multi-user duplication, `jspg_merge` explicitly strips the response graph and returns only the root `{ "id": "uuid" }` (or an array of IDs for list insertions). External APIs can then explicitly call read APIs to fetch the resulting graph, while the UI relies 100% implicitly on the flat `pg_notify` pipeline for reactive state synchronization.
|
||||
* **Decoupled SQL Generation**: Because Writes (INSERT/UPDATE) are inherently highly dynamic based on partial payload structures, the Merger generates raw SQL strings dynamically per execution without caching, guaranteeing a minimal memory footprint while scaling optimally.
|
||||
|
||||
---
|
||||
|
||||
## 4. Queryer
|
||||
|
||||
The Queryer transforms Postgres into a pre-compiled Semantic Query Engine via the `jspg_query(schema_id text, cue jsonb)` API, designed to serve the exact shape of Punc responses directly via SQL.
|
||||
|
||||
### Core Features
|
||||
* **Schema-to-SQL Compilation**: Compiles JSON Schema ASTs spanning deep arrays directly into static, pre-planned SQL multi-JOIN queries.
|
||||
* **DashMap SQL Caching**: Executes compiled SQL via Postgres SPI execution, securely caching the static string compilation templates per schema permutation inside the `GLOBAL_JSPG` application memory, drastically reducing repetitive schema crawling.
|
||||
* **Dynamic Filtering**: Binds parameters natively through `cue.filters` objects. Dynamically handles string formatting (e.g. parsing `uuid` or formatting date-times) and safely escapes complex combinations utilizing `ILIKE` operations correctly mapped to the originating structural table.
|
||||
* **The Stem Engine**: Rather than over-fetching heavy Entity payloads and trimming them, Punc Framework Websockets depend on isolated subgraphs defined as **Stems**.
|
||||
* During initialization, the generator auto-discovers graph boundaries (Stems) inside the schema tree.
|
||||
* The Queryer prepares dedicated SQL execution templates tailored precisely for that exact `Stem` path (e.g. executing `get_dashboard` queried specifically for the `/owner` stem).
|
||||
* These Stem outputs instantly hydrate targeted Go Bitsets, providing `O(1)` real-time routing for fractional data payloads without any application-layer overhead.
|
||||
0
agreego.sql
Normal file
0
agreego.sql
Normal file
124
build.rs
Normal file
124
build.rs
Normal file
@ -0,0 +1,124 @@
|
||||
use std::fs;
|
||||
use std::fs::File;
|
||||
use std::io::Write;
|
||||
use std::path::Path;
|
||||
|
||||
fn to_safe_identifier(name: &str) -> String {
|
||||
let mut safe = String::new();
|
||||
for (i, c) in name.chars().enumerate() {
|
||||
if c.is_uppercase() {
|
||||
if i > 0 {
|
||||
safe.push('_');
|
||||
}
|
||||
safe.push(c.to_ascii_lowercase());
|
||||
} else if c == '-' || c == '.' {
|
||||
safe.push('_');
|
||||
} else {
|
||||
safe.push(c);
|
||||
}
|
||||
}
|
||||
safe
|
||||
}
|
||||
|
||||
fn main() {
|
||||
println!("cargo:rerun-if-changed=tests/fixtures");
|
||||
println!("cargo:rerun-if-changed=Cargo.toml");
|
||||
|
||||
// File 1: src/tests/fixtures.rs for #[pg_test]
|
||||
let pg_dest_path = Path::new("src/tests/fixtures.rs");
|
||||
let mut pg_file = File::create(pg_dest_path).unwrap();
|
||||
|
||||
// File 2: tests/fixtures.rs for standard #[test] integration
|
||||
let std_dest_path = Path::new("tests/fixtures.rs");
|
||||
let mut std_file = File::create(std_dest_path).unwrap();
|
||||
|
||||
// Write headers
|
||||
writeln!(std_file, "use jspg::validator::util;").unwrap();
|
||||
|
||||
// Walk tests/fixtures directly
|
||||
let fixtures_path = "tests/fixtures";
|
||||
if Path::new(fixtures_path).exists() {
|
||||
for entry in fs::read_dir(fixtures_path).unwrap() {
|
||||
let entry = entry.unwrap();
|
||||
let path = entry.path();
|
||||
if path.extension().unwrap_or_default() == "json" {
|
||||
let file_name = path.file_stem().unwrap().to_str().unwrap();
|
||||
|
||||
// Parse the JSON file to find blocks
|
||||
let file = File::open(&path).unwrap();
|
||||
let val: serde_json::Value = serde_json::from_reader(file).unwrap();
|
||||
|
||||
if let Some(arr) = val.as_array() {
|
||||
for (i, item) in arr.iter().enumerate() {
|
||||
// Enforce test suite structure
|
||||
let group = item.as_object().expect("Test suite must be an object");
|
||||
|
||||
// Validate required suite fields
|
||||
if !group.contains_key("description")
|
||||
|| !group.contains_key("database")
|
||||
|| !group.contains_key("tests")
|
||||
{
|
||||
panic!(
|
||||
"File {} index {} is missing required suite fields (description, database, tests)",
|
||||
file_name, i
|
||||
);
|
||||
}
|
||||
|
||||
// Validate required test case fields
|
||||
let tests = group
|
||||
.get("tests")
|
||||
.unwrap()
|
||||
.as_array()
|
||||
.expect("Tests must be an array");
|
||||
for (t_idx, test) in tests.iter().enumerate() {
|
||||
let t_obj = test.as_object().expect("Test case must be an object");
|
||||
if !t_obj.contains_key("description")
|
||||
|| !t_obj.contains_key("data")
|
||||
|| !t_obj.contains_key("valid")
|
||||
|| !t_obj.contains_key("schema_id")
|
||||
{
|
||||
panic!(
|
||||
"File {} suite {} test {} is missing required case fields (description, data, valid, schema_id)",
|
||||
file_name, i, t_idx
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// Use deterministic names: test_{filename}_{index}
|
||||
let safe_filename = to_safe_identifier(file_name);
|
||||
let fn_name = format!("test_{}_{}", safe_filename, i);
|
||||
|
||||
// Write to src/tests.rs (PG Test)
|
||||
// CARGO_MANIFEST_DIR is used to find the absolute path to fixtures at runtime
|
||||
write!(
|
||||
pg_file,
|
||||
r#"
|
||||
#[pg_test]
|
||||
fn {}() {{
|
||||
let path = format!("{{}}/tests/fixtures/{}.json", env!("CARGO_MANIFEST_DIR"));
|
||||
crate::validator::util::run_test_file_at_index(&path, {}).unwrap();
|
||||
}}
|
||||
"#,
|
||||
fn_name, file_name, i
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
// Write to tests/tests.rs (Std Test)
|
||||
write!(
|
||||
std_file,
|
||||
r#"
|
||||
#[test]
|
||||
fn {}() {{
|
||||
let path = format!("{{}}/tests/fixtures/{}.json", env!("CARGO_MANIFEST_DIR"));
|
||||
util::run_test_file_at_index(&path, {}).unwrap();
|
||||
}}
|
||||
"#,
|
||||
fn_name, file_name, i
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
89
flow
89
flow
@ -1,53 +1,42 @@
|
||||
#!/bin/bash
|
||||
#!/usr/bin/env bash
|
||||
|
||||
# Flows
|
||||
source ./flows/base
|
||||
source ./flows/git
|
||||
source ./flows/kube
|
||||
source ./flows/packaging
|
||||
source ./flows/rust
|
||||
|
||||
# Vars
|
||||
POSTGRES_VERSION="17"
|
||||
POSTGRES_VERSION="18"
|
||||
POSTGRES_CONFIG_PATH="/opt/homebrew/opt/postgresql@${POSTGRES_VERSION}/bin/pg_config"
|
||||
DEPENDENCIES+=(icu4c pkg-config "postgresql@${POSTGRES_VERSION}")
|
||||
CARGO_DEPENDENCIES=(cargo-pgrx==0.14.0)
|
||||
CARGO_DEPENDENCIES=(cargo-pgrx==0.16.1)
|
||||
GITEA_ORGANIZATION="cellular"
|
||||
GITEA_REPOSITORY="jspg"
|
||||
|
||||
env() {
|
||||
# Check if GITEA_TOKEN is set
|
||||
if [ -z "$GITEA_TOKEN" ]; then
|
||||
# If not set, try to get it from kubectl
|
||||
GITEA_TOKEN=$(kubectl get secret -n cellular gitea-git -o jsonpath='{.data.token}' | base64 --decode)
|
||||
if [ -z "$GITEA_TOKEN" ]; then
|
||||
error "GITEA_TOKEN is not set and couldn't be retrieved from kubectl" >&2
|
||||
return 2
|
||||
fi
|
||||
export GITEA_TOKEN
|
||||
fi
|
||||
|
||||
success "Environment variables set"
|
||||
}
|
||||
|
||||
pgrx-prepare() {
|
||||
pgrx-up() {
|
||||
info "Initializing pgrx..."
|
||||
# Explicitly point to the postgresql@${POSTGRES_VERSION} pg_config, don't rely on 'which'
|
||||
local POSTGRES_CONFIG_PATH="/opt/homebrew/opt/postgresql@${POSTGRES_VERSION}/bin/pg_config"
|
||||
|
||||
if [ ! -x "$POSTGRES_CONFIG_PATH" ]; then
|
||||
error "pg_config not found or not executable at $POSTGRES_CONFIG_PATH."
|
||||
warning "Ensure postgresql@${POSTGRES_VERSION} is installed correctly via Homebrew."
|
||||
return 2
|
||||
abort "pg_config not found or not executable at $POSTGRES_CONFIG_PATH." 2
|
||||
fi
|
||||
|
||||
if cargo pgrx init --pg"$POSTGRES_VERSION"="$POSTGRES_CONFIG_PATH"; then
|
||||
success "pgrx initialized successfully."
|
||||
else
|
||||
error "Failed to initialize pgrx. Check PostgreSQL development packages are installed and $POSTGRES_CONFIG_PATH is valid."
|
||||
return 2
|
||||
success "pgrx initialized successfully." && return 0
|
||||
fi
|
||||
|
||||
abort "Failed to initialize pgrx. Check PostgreSQL development packages are installed and $POSTGRES_CONFIG_PATH is valid." 2
|
||||
}
|
||||
|
||||
pgrx-down() {
|
||||
info "Taking pgrx down..."
|
||||
}
|
||||
|
||||
|
||||
build() {
|
||||
local version
|
||||
version=$(get-version) || return $?
|
||||
@ -63,12 +52,12 @@ build() {
|
||||
|
||||
# Create the source tarball excluding specified patterns
|
||||
info "Creating tarball: ${tarball_path}"
|
||||
if tar --exclude='.git*' --exclude='./target' --exclude='./package' --exclude='./flows' --exclude='./flow' -czf "${tarball_path}" .; then
|
||||
success "Successfully created source tarball: ${tarball_path}"
|
||||
else
|
||||
error "Failed to create source tarball."
|
||||
return 2
|
||||
# Set COPYFILE_DISABLE=1 to prevent macOS tar from including ._ metadata files
|
||||
if COPYFILE_DISABLE=1 tar --exclude='.git*' --exclude='./target' --exclude='./package' --exclude='./flows' --exclude='./flow' -czf "${tarball_path}" .; then
|
||||
success "Successfully created source tarball: ${tarball_path}" && return 0
|
||||
fi
|
||||
|
||||
abort "Failed to create source tarball." 2
|
||||
}
|
||||
|
||||
install() {
|
||||
@ -79,8 +68,7 @@ install() {
|
||||
|
||||
# Run the pgrx install command
|
||||
if ! cargo pgrx install; then
|
||||
error "cargo pgrx install command failed."
|
||||
return 2
|
||||
abort "cargo pgrx install command failed." 2
|
||||
fi
|
||||
success "PGRX extension v$version successfully built and installed."
|
||||
|
||||
@ -89,31 +77,28 @@ install() {
|
||||
pg_sharedir=$("$POSTGRES_CONFIG_PATH" --sharedir)
|
||||
local pg_config_status=$?
|
||||
if [ $pg_config_status -ne 0 ] || [ -z "$pg_sharedir" ]; then
|
||||
error "Failed to determine PostgreSQL shared directory using pg_config."
|
||||
return 2
|
||||
abort "Failed to determine PostgreSQL shared directory using pg_config." 2
|
||||
fi
|
||||
local installed_control_path="${pg_sharedir}/extension/jspg.control"
|
||||
|
||||
# Modify the control file
|
||||
if [ ! -f "$installed_control_path" ]; then
|
||||
error "Installed control file not found: '$installed_control_path'"
|
||||
return 2
|
||||
abort "Installed control file not found: '$installed_control_path'" 2
|
||||
fi
|
||||
|
||||
info "Modifying control file for non-superuser access: ${installed_control_path}"
|
||||
# Use sed -i '' for macOS compatibility
|
||||
if sed -i '' '/^superuser = false/d' "$installed_control_path" && \
|
||||
echo 'trusted = true' >> "$installed_control_path"; then
|
||||
success "Control file modified successfully."
|
||||
else
|
||||
error "Failed to modify control file: ${installed_control_path}"
|
||||
return 2
|
||||
success "Control file modified successfully." && return 0
|
||||
fi
|
||||
|
||||
abort "Failed to modify control file: ${installed_control_path}" 2
|
||||
}
|
||||
|
||||
test() {
|
||||
info "Running jspg tests..."
|
||||
cargo pgrx test "pg${POSTGRES_VERSION}" "$@" || return $?
|
||||
cargo test --tests "$@" || return $?
|
||||
}
|
||||
|
||||
clean() {
|
||||
@ -122,25 +107,27 @@ clean() {
|
||||
}
|
||||
|
||||
jspg-usage() {
|
||||
printf "prepare\tCheck OS, Cargo, and PGRX dependencies.\n"
|
||||
printf "install\tBuild and install the extension locally (after prepare).\n"
|
||||
printf "reinstall\tClean, build, and install the extension locally (after prepare).\n"
|
||||
printf "test\t\tRun pgrx integration tests.\n"
|
||||
printf "clean\t\tRemove pgrx build artifacts.\n"
|
||||
echo "up|Check OS, Cargo, and PGRX dependencies."
|
||||
echo "install|Build and install the extension locally (after up)."
|
||||
echo "reinstall|Clean, build, and install the extension locally (after up)."
|
||||
echo "test-jspg|Run pgrx integration tests."
|
||||
echo "test-validator|Run validator integration tests."
|
||||
echo "clean|Remove pgrx build artifacts."
|
||||
}
|
||||
|
||||
jspg-flow() {
|
||||
case "$1" in
|
||||
env) env; return $?;;
|
||||
prepare) base-flow prepare && cargo-prepare && pgrx-prepare; return $?;;
|
||||
up) up && rust-up && pgrx-up; return $?;;
|
||||
down) pgrx-down && rust-down && down; return $?;;
|
||||
build) build; return $?;;
|
||||
install) install; return $?;;
|
||||
reinstall) clean && install; return $?;;
|
||||
test) test "${@:2}"; return $?;;
|
||||
clean) clean; return $?;;
|
||||
*) return 1 ;;
|
||||
clean) clean; return $?;;
|
||||
*) return 127 ;;
|
||||
esac
|
||||
}
|
||||
|
||||
register-flow "jspg-flow" "jspg-usage"
|
||||
register-flow "jspg"
|
||||
|
||||
dispatch "$@"
|
||||
2
flows
2
flows
Submodule flows updated: 3e3954fb79...a7b0f5dc4d
58
migrate_fixtures.js
Normal file
58
migrate_fixtures.js
Normal file
@ -0,0 +1,58 @@
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
|
||||
const fixturesDir = path.join(__dirname, 'tests', 'fixtures');
|
||||
|
||||
function processFile(filePath) {
|
||||
const content = fs.readFileSync(filePath, 'utf8');
|
||||
let data;
|
||||
try {
|
||||
data = JSON.parse(content);
|
||||
} catch (e) {
|
||||
console.error(`Skipping ${filePath} due to parse error`);
|
||||
return;
|
||||
}
|
||||
|
||||
let modified = false;
|
||||
|
||||
data.forEach(suite => {
|
||||
if (suite.tests) {
|
||||
suite.tests.forEach(test => {
|
||||
if (test.valid !== undefined || test.expect_errors !== undefined) {
|
||||
if (!test.expect) {
|
||||
test.expect = {};
|
||||
}
|
||||
if (test.valid !== undefined) {
|
||||
test.expect.success = test.valid;
|
||||
delete test.valid;
|
||||
}
|
||||
if (test.expect_errors !== undefined) {
|
||||
test.expect.errors = test.expect_errors;
|
||||
delete test.expect_errors;
|
||||
}
|
||||
modified = true;
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
if (modified) {
|
||||
fs.writeFileSync(filePath, JSON.stringify(data, null, 4));
|
||||
console.log(`Migrated ${filePath}`);
|
||||
}
|
||||
}
|
||||
|
||||
function walkDir(dir) {
|
||||
const files = fs.readdirSync(dir);
|
||||
files.forEach(file => {
|
||||
const fullPath = path.join(dir, file);
|
||||
if (fs.statSync(fullPath).isDirectory()) {
|
||||
walkDir(fullPath);
|
||||
} else if (fullPath.endsWith('.json')) {
|
||||
processFile(fullPath);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
walkDir(fixturesDir);
|
||||
console.log('Done migrating fixtures!');
|
||||
1
rustfmt.toml
Normal file
1
rustfmt.toml
Normal file
@ -0,0 +1 @@
|
||||
tab_spaces = 2
|
||||
@ -1 +1 @@
|
||||
::pgrx::pgrx_embed!();
|
||||
::pgrx::pgrx_embed!();
|
||||
|
||||
12
src/database/enum.rs
Normal file
12
src/database/enum.rs
Normal file
@ -0,0 +1,12 @@
|
||||
use crate::database::schema::Schema;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
|
||||
#[serde(default)]
|
||||
pub struct Enum {
|
||||
pub name: String,
|
||||
pub module: String,
|
||||
pub source: String,
|
||||
pub values: Vec<String>,
|
||||
pub schemas: Vec<Schema>,
|
||||
}
|
||||
111
src/database/executor.rs
Normal file
111
src/database/executor.rs
Normal file
@ -0,0 +1,111 @@
|
||||
use pgrx::prelude::*;
|
||||
use serde_json::Value;
|
||||
|
||||
/// An abstraction over database execution to allow for isolated unit testing
|
||||
/// without a live Postgres SPI connection.
|
||||
pub trait DatabaseExecutor: Send + Sync {
|
||||
/// Executes a query expecting a single JSONB return, representing rows.
|
||||
fn query(&self, sql: &str, args: Option<&[Value]>) -> Result<Value, String>;
|
||||
|
||||
/// Executes an operation (INSERT, UPDATE, DELETE, or pg_notify) that does not return rows.
|
||||
fn execute(&self, sql: &str, args: Option<&[Value]>) -> Result<(), String>;
|
||||
|
||||
/// Returns the current authenticated user's ID
|
||||
fn auth_user_id(&self) -> Result<String, String>;
|
||||
|
||||
/// Returns the current transaction timestamp
|
||||
fn timestamp(&self) -> Result<String, String>;
|
||||
}
|
||||
|
||||
/// The production executor that wraps `pgrx::spi::Spi`.
|
||||
pub struct SpiExecutor;
|
||||
|
||||
impl SpiExecutor {
|
||||
pub fn new() -> Self {
|
||||
Self {}
|
||||
}
|
||||
}
|
||||
|
||||
impl DatabaseExecutor for SpiExecutor {
|
||||
fn query(&self, sql: &str, args: Option<&[Value]>) -> Result<Value, String> {
|
||||
let mut json_args = Vec::new();
|
||||
let mut args_with_oid: Vec<pgrx::datum::DatumWithOid> = Vec::new();
|
||||
if let Some(params) = args {
|
||||
for val in params {
|
||||
json_args.push(pgrx::JsonB(val.clone()));
|
||||
}
|
||||
for j_val in json_args.into_iter() {
|
||||
args_with_oid.push(pgrx::datum::DatumWithOid::from(j_val));
|
||||
}
|
||||
}
|
||||
|
||||
Spi::connect(|client| {
|
||||
match client.select(sql, Some(args_with_oid.len() as i64), &args_with_oid) {
|
||||
Ok(tup_table) => {
|
||||
let mut results = Vec::new();
|
||||
for row in tup_table {
|
||||
if let Ok(Some(jsonb)) = row.get::<pgrx::JsonB>(1) {
|
||||
results.push(jsonb.0);
|
||||
}
|
||||
}
|
||||
Ok(Value::Array(results))
|
||||
}
|
||||
Err(e) => Err(format!("SPI Query Fetch Failure: {}", e)),
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fn execute(&self, sql: &str, args: Option<&[Value]>) -> Result<(), String> {
|
||||
let mut json_args = Vec::new();
|
||||
let mut args_with_oid: Vec<pgrx::datum::DatumWithOid> = Vec::new();
|
||||
if let Some(params) = args {
|
||||
for val in params {
|
||||
json_args.push(pgrx::JsonB(val.clone()));
|
||||
}
|
||||
for j_val in json_args.into_iter() {
|
||||
args_with_oid.push(pgrx::datum::DatumWithOid::from(j_val));
|
||||
}
|
||||
}
|
||||
|
||||
Spi::connect_mut(|client| {
|
||||
match client.update(sql, Some(args_with_oid.len() as i64), &args_with_oid) {
|
||||
Ok(_) => Ok(()),
|
||||
Err(e) => Err(format!("SPI Execution Failure: {}", e)),
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fn auth_user_id(&self) -> Result<String, String> {
|
||||
Spi::connect(|client| {
|
||||
let mut tup_table = client
|
||||
.select(
|
||||
"SELECT COALESCE(current_setting('auth.user_id', true), 'ffffffff-ffff-ffff-ffff-ffffffffffff')",
|
||||
None,
|
||||
&[],
|
||||
)
|
||||
.map_err(|e| format!("SPI Select Error: {}", e))?;
|
||||
|
||||
let row = tup_table
|
||||
.next()
|
||||
.ok_or("No user id setting returned from context".to_string())?;
|
||||
let user_id: Option<String> = row.get(1).map_err(|e| e.to_string())?;
|
||||
|
||||
user_id.ok_or("Missing user_id".to_string())
|
||||
})
|
||||
}
|
||||
|
||||
fn timestamp(&self) -> Result<String, String> {
|
||||
Spi::connect(|client| {
|
||||
let mut tup_table = client
|
||||
.select("SELECT clock_timestamp()::text", None, &[])
|
||||
.map_err(|e| format!("SPI Select Error: {}", e))?;
|
||||
|
||||
let row = tup_table
|
||||
.next()
|
||||
.ok_or("No clock timestamp returned".to_string())?;
|
||||
let timestamp: Option<String> = row.get(1).map_err(|e| e.to_string())?;
|
||||
|
||||
timestamp.ok_or("Missing timestamp".to_string())
|
||||
})
|
||||
}
|
||||
}
|
||||
880
src/database/formats.rs
Normal file
880
src/database/formats.rs
Normal file
@ -0,0 +1,880 @@
|
||||
use std::{
|
||||
collections::HashMap,
|
||||
error::Error,
|
||||
net::{Ipv4Addr, Ipv6Addr},
|
||||
};
|
||||
|
||||
use lazy_static::lazy_static;
|
||||
use percent_encoding::percent_decode_str;
|
||||
use serde_json::Value;
|
||||
use url::Url;
|
||||
|
||||
// use crate::ecma; // Assuming ecma is not yet available, stubbing regex for now
|
||||
|
||||
/// Defines format for `format` keyword.
|
||||
#[derive(Clone, Copy)]
|
||||
pub struct Format {
|
||||
/// Name of the format
|
||||
pub name: &'static str,
|
||||
|
||||
/// validates given value.
|
||||
pub func: fn(v: &Value) -> Result<(), Box<dyn Error + Send + Sync>>, // Ensure thread safety if needed
|
||||
}
|
||||
|
||||
lazy_static! {
|
||||
pub(crate) static ref FORMATS: HashMap<&'static str, Format> = {
|
||||
let mut m = HashMap::<&'static str, Format>::new();
|
||||
// Helper to register formats
|
||||
let mut register = |name, func| m.insert(name, Format { name, func });
|
||||
|
||||
// register("regex", validate_regex); // Stubbed
|
||||
register("ipv4", validate_ipv4);
|
||||
register("ipv6", validate_ipv6);
|
||||
register("hostname", validate_hostname);
|
||||
register("idn-hostname", validate_idn_hostname);
|
||||
register("email", validate_email);
|
||||
register("idn-email", validate_idn_email);
|
||||
register("date", validate_date);
|
||||
register("time", validate_time);
|
||||
register("date-time", validate_date_time);
|
||||
register("duration", validate_duration);
|
||||
register("period", validate_period);
|
||||
register("json-pointer", validate_json_pointer);
|
||||
register("relative-json-pointer", validate_relative_json_pointer);
|
||||
register("uuid", validate_uuid);
|
||||
register("uri", validate_uri);
|
||||
register("iri", validate_iri);
|
||||
register("uri-reference", validate_uri_reference);
|
||||
register("iri-reference", validate_iri_reference);
|
||||
register("uri-template", validate_uri_template);
|
||||
m
|
||||
};
|
||||
}
|
||||
|
||||
/*
|
||||
fn validate_regex(v: &Value) -> Result<(), Box<dyn Error + Send + Sync>> {
|
||||
let Value::String(s) = v else {
|
||||
return Ok(());
|
||||
};
|
||||
// ecma::convert(s).map(|_| ())
|
||||
Ok(())
|
||||
}
|
||||
*/
|
||||
|
||||
fn validate_ipv4(v: &Value) -> Result<(), Box<dyn Error + Send + Sync>> {
|
||||
let Value::String(s) = v else {
|
||||
return Ok(());
|
||||
};
|
||||
s.parse::<Ipv4Addr>()?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn validate_ipv6(v: &Value) -> Result<(), Box<dyn Error + Send + Sync>> {
|
||||
let Value::String(s) = v else {
|
||||
return Ok(());
|
||||
};
|
||||
s.parse::<Ipv6Addr>()?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn validate_date(v: &Value) -> Result<(), Box<dyn Error + Send + Sync>> {
|
||||
let Value::String(s) = v else {
|
||||
return Ok(());
|
||||
};
|
||||
check_date(s)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn matches_char(s: &str, index: usize, ch: char) -> bool {
|
||||
s.is_char_boundary(index) && s[index..].starts_with(ch)
|
||||
}
|
||||
|
||||
// see https://datatracker.ietf.org/doc/html/rfc3339#section-5.6
|
||||
fn check_date(s: &str) -> Result<(), Box<dyn Error + Send + Sync>> {
|
||||
// yyyy-mm-dd
|
||||
if s.len() != 10 {
|
||||
Err("must be 10 characters long")?;
|
||||
}
|
||||
if !matches_char(s, 4, '-') || !matches_char(s, 7, '-') {
|
||||
Err("missing hyphen in correct place")?;
|
||||
}
|
||||
|
||||
let mut ymd = s.splitn(3, '-').filter_map(|t| t.parse::<usize>().ok());
|
||||
let (Some(y), Some(m), Some(d)) = (ymd.next(), ymd.next(), ymd.next()) else {
|
||||
Err("non-positive year/month/day")?
|
||||
};
|
||||
|
||||
if !matches!(m, 1..=12) {
|
||||
Err(format!("{m} months in year"))?;
|
||||
}
|
||||
if !matches!(d, 1..=31) {
|
||||
Err(format!("{d} days in month"))?;
|
||||
}
|
||||
|
||||
match m {
|
||||
2 => {
|
||||
let mut feb_days = 28;
|
||||
if y % 4 == 0 && (y % 100 != 0 || y % 400 == 0) {
|
||||
feb_days += 1; // leap year
|
||||
};
|
||||
if d > feb_days {
|
||||
Err(format!("february has {feb_days} days only"))?;
|
||||
}
|
||||
}
|
||||
4 | 6 | 9 | 11 => {
|
||||
if d > 30 {
|
||||
Err("month has 30 days only")?;
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn validate_time(v: &Value) -> Result<(), Box<dyn Error + Send + Sync>> {
|
||||
let Value::String(s) = v else {
|
||||
return Ok(());
|
||||
};
|
||||
check_time(s)
|
||||
}
|
||||
|
||||
fn check_time(mut str: &str) -> Result<(), Box<dyn Error + Send + Sync>> {
|
||||
// min: hh:mm:ssZ
|
||||
if str.len() < 9 {
|
||||
Err("less than 9 characters long")?
|
||||
}
|
||||
if !matches_char(str, 2, ':') || !matches_char(str, 5, ':') {
|
||||
Err("missing colon in correct place")?
|
||||
}
|
||||
|
||||
// parse hh:mm:ss
|
||||
if !str.is_char_boundary(8) {
|
||||
Err("contains non-ascii char")?
|
||||
}
|
||||
let mut hms = (str[..8])
|
||||
.splitn(3, ':')
|
||||
.filter_map(|t| t.parse::<usize>().ok());
|
||||
let (Some(mut h), Some(mut m), Some(s)) = (hms.next(), hms.next(), hms.next()) else {
|
||||
Err("non-positive hour/min/sec")?
|
||||
};
|
||||
if h > 23 || m > 59 || s > 60 {
|
||||
Err("hour/min/sec out of range")?
|
||||
}
|
||||
str = &str[8..];
|
||||
|
||||
// parse sec-frac if present
|
||||
if let Some(rem) = str.strip_prefix('.') {
|
||||
let n_digits = rem.chars().take_while(char::is_ascii_digit).count();
|
||||
if n_digits == 0 {
|
||||
Err("no digits in second fraction")?;
|
||||
}
|
||||
str = &rem[n_digits..];
|
||||
}
|
||||
|
||||
if str != "z" && str != "Z" {
|
||||
// parse time-numoffset
|
||||
if str.len() != 6 {
|
||||
Err("offset must be 6 characters long")?;
|
||||
}
|
||||
let sign: isize = match str.chars().next() {
|
||||
Some('+') => -1,
|
||||
Some('-') => 1,
|
||||
_ => return Err("offset must begin with plus/minus")?,
|
||||
};
|
||||
str = &str[1..];
|
||||
if !matches_char(str, 2, ':') {
|
||||
Err("missing colon in offset at correct place")?
|
||||
}
|
||||
|
||||
let mut zhm = str.splitn(2, ':').filter_map(|t| t.parse::<usize>().ok());
|
||||
let (Some(zh), Some(zm)) = (zhm.next(), zhm.next()) else {
|
||||
Err("non-positive hour/min in offset")?
|
||||
};
|
||||
if zh > 23 || zm > 59 {
|
||||
Err("hour/min in offset out of range")?
|
||||
}
|
||||
|
||||
// apply timezone
|
||||
let mut hm = (h * 60 + m) as isize + sign * (zh * 60 + zm) as isize;
|
||||
if hm < 0 {
|
||||
hm += 24 * 60;
|
||||
debug_assert!(hm >= 0);
|
||||
}
|
||||
let hm = hm as usize;
|
||||
(h, m) = (hm / 60, hm % 60);
|
||||
}
|
||||
|
||||
// check leap second
|
||||
if !(s < 60 || (h == 23 && m == 59)) {
|
||||
Err("invalid leap second")?
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn validate_date_time(v: &Value) -> Result<(), Box<dyn Error + Send + Sync>> {
|
||||
let Value::String(s) = v else {
|
||||
return Ok(());
|
||||
};
|
||||
check_date_time(s)
|
||||
}
|
||||
|
||||
fn check_date_time(s: &str) -> Result<(), Box<dyn Error + Send + Sync>> {
|
||||
// min: yyyy-mm-ddThh:mm:ssZ
|
||||
if s.len() < 20 {
|
||||
Err("less than 20 characters long")?;
|
||||
}
|
||||
if !s.is_char_boundary(10) || !s[10..].starts_with(['t', 'T']) {
|
||||
Err("11th character must be t or T")?;
|
||||
}
|
||||
if let Err(e) = check_date(&s[..10]) {
|
||||
Err(format!("invalid date element: {e}"))?;
|
||||
}
|
||||
if let Err(e) = check_time(&s[11..]) {
|
||||
Err(format!("invalid time element: {e}"))?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn validate_duration(v: &Value) -> Result<(), Box<dyn Error + Send + Sync>> {
|
||||
let Value::String(s) = v else {
|
||||
return Ok(());
|
||||
};
|
||||
check_duration(s)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// see https://datatracker.ietf.org/doc/html/rfc3339#appendix-A
|
||||
fn check_duration(s: &str) -> Result<(), Box<dyn Error + Send + Sync>> {
|
||||
// must start with 'P'
|
||||
let Some(s) = s.strip_prefix('P') else {
|
||||
Err("must start with P")?
|
||||
};
|
||||
if s.is_empty() {
|
||||
Err("nothing after P")?
|
||||
}
|
||||
|
||||
// dur-week
|
||||
if let Some(s) = s.strip_suffix('W') {
|
||||
if s.is_empty() {
|
||||
Err("no number in week")?
|
||||
}
|
||||
if !s.chars().all(|c| c.is_ascii_digit()) {
|
||||
Err("invalid week")?
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
static UNITS: [&str; 2] = ["YMD", "HMS"];
|
||||
for (i, s) in s.split('T').enumerate() {
|
||||
let mut s = s;
|
||||
if i != 0 && s.is_empty() {
|
||||
Err("no time elements")?
|
||||
}
|
||||
let Some(mut units) = UNITS.get(i).cloned() else {
|
||||
Err("more than one T")?
|
||||
};
|
||||
while !s.is_empty() {
|
||||
let digit_count = s.chars().take_while(char::is_ascii_digit).count();
|
||||
if digit_count == 0 {
|
||||
Err("missing number")?
|
||||
}
|
||||
s = &s[digit_count..];
|
||||
let Some(unit) = s.chars().next() else {
|
||||
Err("missing unit")?
|
||||
};
|
||||
let Some(j) = units.find(unit) else {
|
||||
if UNITS[i].contains(unit) {
|
||||
Err(format!("unit {unit} out of order"))?
|
||||
}
|
||||
Err(format!("invalid unit {unit}"))?
|
||||
};
|
||||
units = &units[j + 1..];
|
||||
s = &s[1..];
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// see https://datatracker.ietf.org/doc/html/rfc3339#appendix-A
|
||||
fn validate_period(v: &Value) -> Result<(), Box<dyn Error + Send + Sync>> {
|
||||
let Value::String(s) = v else {
|
||||
return Ok(());
|
||||
};
|
||||
|
||||
let Some(slash) = s.find('/') else {
|
||||
Err("missing slash")?
|
||||
};
|
||||
|
||||
let (start, end) = (&s[..slash], &s[slash + 1..]);
|
||||
if start.starts_with('P') {
|
||||
if let Err(e) = check_duration(start) {
|
||||
Err(format!("invalid start duration: {e}"))?
|
||||
}
|
||||
if let Err(e) = check_date_time(end) {
|
||||
Err(format!("invalid end date-time: {e}"))?
|
||||
}
|
||||
} else {
|
||||
if let Err(e) = check_date_time(start) {
|
||||
Err(format!("invalid start date-time: {e}"))?
|
||||
}
|
||||
if end.starts_with('P') {
|
||||
if let Err(e) = check_duration(end) {
|
||||
Err(format!("invalid end duration: {e}"))?;
|
||||
}
|
||||
} else if let Err(e) = check_date_time(end) {
|
||||
Err(format!("invalid end date-time: {e}"))?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn validate_hostname(v: &Value) -> Result<(), Box<dyn Error + Send + Sync>> {
|
||||
let Value::String(s) = v else {
|
||||
return Ok(());
|
||||
};
|
||||
check_hostname(s)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// see https://en.wikipedia.org/wiki/Hostname#Restrictions_on_valid_host_names
|
||||
fn check_hostname(s: &str) -> Result<(), Box<dyn Error + Send + Sync>> {
|
||||
// entire hostname (including the delimiting dots but not a trailing dot) has a maximum of 253 ASCII characters
|
||||
|
||||
if s.len() > 253 {
|
||||
Err("more than 253 characters long")?
|
||||
}
|
||||
|
||||
// Hostnames are composed of series of labels concatenated with dots, as are all domain names
|
||||
for label in s.split('.') {
|
||||
// Each label must be from 1 to 63 characters long
|
||||
if !matches!(label.len(), 1..=63) {
|
||||
Err("label must be 1 to 63 characters long")?;
|
||||
}
|
||||
|
||||
// labels must not start or end with a hyphen
|
||||
if label.starts_with('-') {
|
||||
Err("label starts with hyphen")?;
|
||||
}
|
||||
|
||||
if label.ends_with('-') {
|
||||
Err("label ends with hyphen")?;
|
||||
}
|
||||
|
||||
// labels may contain only the ASCII letters 'a' through 'z' (in a case-insensitive manner),
|
||||
// the digits '0' through '9', and the hyphen ('-')
|
||||
if let Some(ch) = label
|
||||
.chars()
|
||||
.find(|c| !matches!(c, 'a'..='z' | 'A'..='Z' | '0'..='9' | '-'))
|
||||
{
|
||||
Err(format!("invalid character {ch:?}"))?;
|
||||
}
|
||||
|
||||
// labels must not contain "--" in 3rd and 4th position unless they start with "xn--"
|
||||
if label.len() >= 4 && &label[2..4] == "--" {
|
||||
if !label.starts_with("xn--") {
|
||||
Err("label has -- in 3rd/4th position but does not start with xn--")?;
|
||||
} else {
|
||||
let (unicode, errors) = idna::domain_to_unicode(label);
|
||||
if errors.is_err() {
|
||||
Err("invalid punycode")?;
|
||||
}
|
||||
check_unicode_idn_constraints(&unicode)
|
||||
.map_err(|e| format!("invalid punycode/IDN: {e}"))?;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn validate_idn_hostname(v: &Value) -> Result<(), Box<dyn Error + Send + Sync>> {
|
||||
let Value::String(s) = v else {
|
||||
return Ok(());
|
||||
};
|
||||
check_idn_hostname(s)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
static DISALLOWED: [char; 10] = [
|
||||
'\u{0640}', // ARABIC TATWEEL
|
||||
'\u{07FA}', // NKO LAJANYALAN
|
||||
'\u{302E}', // HANGUL SINGLE DOT TONE MARK
|
||||
'\u{302F}', // HANGUL DOUBLE DOT TONE MARK
|
||||
'\u{3031}', // VERTICAL KANA REPEAT MARK
|
||||
'\u{3032}', // VERTICAL KANA REPEAT WITH VOICED SOUND MARK
|
||||
'\u{3033}', // VERTICAL KANA REPEAT MARK UPPER HALF
|
||||
'\u{3034}', // VERTICAL KANA REPEAT WITH VOICED SOUND MARK UPPER HA
|
||||
'\u{3035}', // VERTICAL KANA REPEAT MARK LOWER HALF
|
||||
'\u{303B}', // VERTICAL IDEOGRAPHIC ITERATION MARK
|
||||
];
|
||||
|
||||
fn check_idn_hostname(s: &str) -> Result<(), Box<dyn Error + Send + Sync>> {
|
||||
let s = idna::domain_to_ascii_strict(s).map_err(|e| format!("idna error: {:?}", e))?;
|
||||
let (unicode, errors) = idna::domain_to_unicode(&s);
|
||||
if let Err(e) = errors {
|
||||
Err(format!("idna decoding error: {:?}", e))?;
|
||||
}
|
||||
check_unicode_idn_constraints(&unicode)?;
|
||||
check_hostname(&s)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn check_unicode_idn_constraints(unicode: &str) -> Result<(), Box<dyn Error + Send + Sync>> {
|
||||
// see https://www.rfc-editor.org/rfc/rfc5892#section-2.6
|
||||
{
|
||||
if unicode.contains(DISALLOWED) {
|
||||
Err("contains disallowed character")?;
|
||||
}
|
||||
}
|
||||
|
||||
// unicode string must not contain "--" in 3rd and 4th position
|
||||
// and must not start and end with a '-'
|
||||
// see https://www.rfc-editor.org/rfc/rfc5891#section-4.2.3.1
|
||||
{
|
||||
let count: usize = unicode
|
||||
.chars()
|
||||
.skip(2)
|
||||
.take(2)
|
||||
.map(|c| if c == '-' { 1 } else { 0 })
|
||||
.sum();
|
||||
if count == 2 {
|
||||
Err("unicode string must not contain '--' in 3rd and 4th position")?;
|
||||
}
|
||||
}
|
||||
|
||||
// MIDDLE DOT is allowed between 'l' characters only
|
||||
// see https://www.rfc-editor.org/rfc/rfc5892#appendix-A.3
|
||||
{
|
||||
let middle_dot = '\u{00b7}';
|
||||
let mut s = unicode;
|
||||
while let Some(i) = s.find(middle_dot) {
|
||||
let prefix = &s[..i];
|
||||
let suffix = &s[i + middle_dot.len_utf8()..];
|
||||
if !prefix.ends_with('l') || !suffix.ends_with('l') {
|
||||
Err("MIDDLE DOT is allowed between 'l' characters only")?;
|
||||
}
|
||||
s = suffix;
|
||||
}
|
||||
}
|
||||
|
||||
// Greek KERAIA must be followed by Greek character
|
||||
// see https://www.rfc-editor.org/rfc/rfc5892#appendix-A.4
|
||||
{
|
||||
let keralia = '\u{0375}';
|
||||
let greek = '\u{0370}'..='\u{03FF}';
|
||||
let mut s = unicode;
|
||||
while let Some(i) = s.find(keralia) {
|
||||
let suffix = &s[i + keralia.len_utf8()..];
|
||||
if !suffix.starts_with(|c| greek.contains(&c)) {
|
||||
Err("Greek KERAIA must be followed by Greek character")?;
|
||||
}
|
||||
s = suffix;
|
||||
}
|
||||
}
|
||||
|
||||
// Hebrew GERESH must be preceded by Hebrew character
|
||||
// see https://www.rfc-editor.org/rfc/rfc5892#appendix-A.5
|
||||
//
|
||||
// Hebrew GERSHAYIM must be preceded by Hebrew character
|
||||
// see https://www.rfc-editor.org/rfc/rfc5892#appendix-A.6
|
||||
{
|
||||
let geresh = '\u{05F3}';
|
||||
let gereshayim = '\u{05F4}';
|
||||
let hebrew = '\u{0590}'..='\u{05FF}';
|
||||
for ch in [geresh, gereshayim] {
|
||||
let mut s = unicode;
|
||||
while let Some(i) = s.find(ch) {
|
||||
let prefix = &s[..i];
|
||||
if !prefix.ends_with(|c| hebrew.contains(&c)) {
|
||||
if i == 0 {
|
||||
Err("Hebrew GERESH must be preceded by Hebrew character")?;
|
||||
} else {
|
||||
Err("Hebrew GERESHYIM must be preceded by Hebrew character")?;
|
||||
}
|
||||
}
|
||||
let suffix = &s[i + ch.len_utf8()..];
|
||||
s = suffix;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// KATAKANA MIDDLE DOT must be with Hiragana, Katakana, or Han
|
||||
// see https://www.rfc-editor.org/rfc/rfc5892#appendix-A.7
|
||||
{
|
||||
let katakana_middle_dot = '\u{30FB}';
|
||||
if unicode.contains(katakana_middle_dot) {
|
||||
let hiragana = '\u{3040}'..='\u{309F}';
|
||||
let katakana = '\u{30A0}'..='\u{30FF}';
|
||||
let han = '\u{4E00}'..='\u{9FFF}'; // https://en.wikipedia.org/wiki/CJK_Unified_Ideographs_(Unicode_block): is this range correct??
|
||||
if unicode.contains(|c| hiragana.contains(&c))
|
||||
|| unicode.contains(|c| c != katakana_middle_dot && katakana.contains(&c))
|
||||
|| unicode.contains(|c| han.contains(&c))
|
||||
{
|
||||
// ok
|
||||
} else {
|
||||
Err("KATAKANA MIDDLE DOT must be with Hiragana, Katakana, or Han")?;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ARABIC-INDIC DIGITS and Extended Arabic-Indic Digits cannot be mixed
|
||||
// see https://www.rfc-editor.org/rfc/rfc5892#appendix-A.8
|
||||
// see https://www.rfc-editor.org/rfc/rfc5892#appendix-A.9
|
||||
{
|
||||
let arabic_indic_digits = '\u{0660}'..='\u{0669}';
|
||||
let extended_arabic_indic_digits = '\u{06F0}'..='\u{06F9}';
|
||||
if unicode.contains(|c| arabic_indic_digits.contains(&c))
|
||||
&& unicode.contains(|c| extended_arabic_indic_digits.contains(&c))
|
||||
{
|
||||
Err("ARABIC-INDIC DIGITS and Extended Arabic-Indic Digits cannot be mixed")?;
|
||||
}
|
||||
}
|
||||
|
||||
// ZERO WIDTH JOINER must be preceded by Virama
|
||||
// see https://www.rfc-editor.org/rfc/rfc5892#appendix-A.2
|
||||
{
|
||||
let zero_width_jointer = '\u{200D}';
|
||||
static VIRAMA: [char; 61] = [
|
||||
'\u{094D}',
|
||||
'\u{09CD}',
|
||||
'\u{0A4D}',
|
||||
'\u{0ACD}',
|
||||
'\u{0B4D}',
|
||||
'\u{0BCD}',
|
||||
'\u{0C4D}',
|
||||
'\u{0CCD}',
|
||||
'\u{0D3B}',
|
||||
'\u{0D3C}',
|
||||
'\u{0D4D}',
|
||||
'\u{0DCA}',
|
||||
'\u{0E3A}',
|
||||
'\u{0EBA}',
|
||||
'\u{0F84}',
|
||||
'\u{1039}',
|
||||
'\u{103A}',
|
||||
'\u{1714}',
|
||||
'\u{1734}',
|
||||
'\u{17D2}',
|
||||
'\u{1A60}',
|
||||
'\u{1B44}',
|
||||
'\u{1BAA}',
|
||||
'\u{1BAB}',
|
||||
'\u{1BF2}',
|
||||
'\u{1BF3}',
|
||||
'\u{2D7F}',
|
||||
'\u{A806}',
|
||||
'\u{A82C}',
|
||||
'\u{A8C4}',
|
||||
'\u{A953}',
|
||||
'\u{A9C0}',
|
||||
'\u{AAF6}',
|
||||
'\u{ABED}',
|
||||
'\u{10A3F}',
|
||||
'\u{11046}',
|
||||
'\u{1107F}',
|
||||
'\u{110B9}',
|
||||
'\u{11133}',
|
||||
'\u{11134}',
|
||||
'\u{111C0}',
|
||||
'\u{11235}',
|
||||
'\u{112EA}',
|
||||
'\u{1134D}',
|
||||
'\u{11442}',
|
||||
'\u{114C2}',
|
||||
'\u{115BF}',
|
||||
'\u{1163F}',
|
||||
'\u{116B6}',
|
||||
'\u{1172B}',
|
||||
'\u{11839}',
|
||||
'\u{1193D}',
|
||||
'\u{1193E}',
|
||||
'\u{119E0}',
|
||||
'\u{11A34}',
|
||||
'\u{11A47}',
|
||||
'\u{11A99}',
|
||||
'\u{11C3F}',
|
||||
'\u{11D44}',
|
||||
'\u{11D45}',
|
||||
'\u{11D97}',
|
||||
]; // https://www.compart.com/en/unicode/combining/9
|
||||
let mut s = unicode;
|
||||
while let Some(i) = s.find(zero_width_jointer) {
|
||||
let prefix = &s[..i];
|
||||
if !prefix.ends_with(VIRAMA) {
|
||||
Err("ZERO WIDTH JOINER must be preceded by Virama")?;
|
||||
}
|
||||
let suffix = &s[i + zero_width_jointer.len_utf8()..];
|
||||
s = suffix;
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn validate_email(v: &Value) -> Result<(), Box<dyn Error + Send + Sync>> {
|
||||
let Value::String(s) = v else {
|
||||
return Ok(());
|
||||
};
|
||||
check_email(s)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// see https://en.wikipedia.org/wiki/Email_address
|
||||
fn check_email(s: &str) -> Result<(), Box<dyn Error + Send + Sync>> {
|
||||
// entire email address to be no more than 254 characters long
|
||||
if s.len() > 254 {
|
||||
Err("more than 254 characters long")?
|
||||
}
|
||||
|
||||
// email address is generally recognized as having two parts joined with an at-sign
|
||||
let Some(at) = s.rfind('@') else {
|
||||
Err("missing @")?
|
||||
};
|
||||
let (local, domain) = (&s[..at], &s[at + 1..]);
|
||||
|
||||
// local part may be up to 64 characters long
|
||||
if local.len() > 64 {
|
||||
Err("local part more than 64 characters long")?
|
||||
}
|
||||
|
||||
if local.len() > 1 && local.starts_with('"') && local.ends_with('"') {
|
||||
// quoted
|
||||
let local = &local[1..local.len() - 1];
|
||||
if local.contains(['\\', '"']) {
|
||||
Err("backslash and quote not allowed within quoted local part")?
|
||||
}
|
||||
} else {
|
||||
// unquoted
|
||||
|
||||
if local.starts_with('.') {
|
||||
Err("starts with dot")?
|
||||
}
|
||||
if local.ends_with('.') {
|
||||
Err("ends with dot")?
|
||||
}
|
||||
|
||||
// consecutive dots not allowed
|
||||
if local.contains("..") {
|
||||
Err("consecutive dots")?
|
||||
}
|
||||
|
||||
// check allowd chars
|
||||
if let Some(ch) = local
|
||||
.chars()
|
||||
.find(|c| !(c.is_ascii_alphanumeric() || ".!#$%&'*+-/=?^_`{|}~".contains(*c)))
|
||||
{
|
||||
Err(format!("invalid character {ch:?}"))?
|
||||
}
|
||||
}
|
||||
|
||||
// domain if enclosed in brackets, must match an IP address
|
||||
if domain.starts_with('[') && domain.ends_with(']') {
|
||||
let s = &domain[1..domain.len() - 1];
|
||||
if let Some(s) = s.strip_prefix("IPv6:") {
|
||||
if let Err(e) = s.parse::<Ipv6Addr>() {
|
||||
Err(format!("invalid ipv6 address: {e}"))?
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
if let Err(e) = s.parse::<Ipv4Addr>() {
|
||||
Err(format!("invalid ipv4 address: {e}"))?
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
// domain must match the requirements for a hostname
|
||||
if let Err(e) = check_hostname(domain) {
|
||||
Err(format!("invalid domain: {e}"))?
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn validate_idn_email(v: &Value) -> Result<(), Box<dyn Error + Send + Sync>> {
|
||||
let Value::String(s) = v else {
|
||||
return Ok(());
|
||||
};
|
||||
|
||||
let Some(at) = s.rfind('@') else {
|
||||
Err("missing @")?
|
||||
};
|
||||
let (local, domain) = (&s[..at], &s[at + 1..]);
|
||||
|
||||
let local = idna::domain_to_ascii_strict(local).map_err(|e| format!("idna error: {:?}", e))?;
|
||||
let domain = idna::domain_to_ascii_strict(domain).map_err(|e| format!("idna error: {:?}", e))?;
|
||||
if let Err(e) = check_idn_hostname(&domain) {
|
||||
Err(format!("invalid domain: {e}"))?
|
||||
}
|
||||
check_email(&format!("{local}@{domain}"))
|
||||
}
|
||||
|
||||
fn validate_json_pointer(v: &Value) -> Result<(), Box<dyn Error + Send + Sync>> {
|
||||
let Value::String(s) = v else {
|
||||
return Ok(());
|
||||
};
|
||||
check_json_pointer(s)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// see https://www.rfc-editor.org/rfc/rfc6901#section-3
|
||||
fn check_json_pointer(s: &str) -> Result<(), Box<dyn Error + Send + Sync>> {
|
||||
if s.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
if !s.starts_with('/') {
|
||||
Err("not starting with slash")?;
|
||||
}
|
||||
for token in s.split('/').skip(1) {
|
||||
let mut chars = token.chars();
|
||||
while let Some(ch) = chars.next() {
|
||||
if ch == '~' {
|
||||
if !matches!(chars.next(), Some('0' | '1')) {
|
||||
Err("~ must be followed by 0 or 1")?;
|
||||
}
|
||||
} else if !matches!(ch, '\x00'..='\x2E' | '\x30'..='\x7D' | '\x7F'..='\u{10FFFF}') {
|
||||
Err("contains disallowed character")?;
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// see https://tools.ietf.org/html/draft-handrews-relative-json-pointer-01#section-3
|
||||
fn validate_relative_json_pointer(v: &Value) -> Result<(), Box<dyn Error + Send + Sync>> {
|
||||
let Value::String(s) = v else {
|
||||
return Ok(());
|
||||
};
|
||||
|
||||
// start with non-negative-integer
|
||||
let num_digits = s.chars().take_while(char::is_ascii_digit).count();
|
||||
if num_digits == 0 {
|
||||
Err("must start with non-negative integer")?;
|
||||
}
|
||||
if num_digits > 1 && s.starts_with('0') {
|
||||
Err("starts with zero")?;
|
||||
}
|
||||
let s = &s[num_digits..];
|
||||
|
||||
// followed by either json-pointer or '#'
|
||||
if s == "#" {
|
||||
return Ok(());
|
||||
}
|
||||
if let Err(e) = check_json_pointer(s) {
|
||||
Err(format!("invalid json-pointer element: {e}"))?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// see https://datatracker.ietf.org/doc/html/rfc4122#page-4
|
||||
fn validate_uuid(v: &Value) -> Result<(), Box<dyn Error + Send + Sync>> {
|
||||
let Value::String(s) = v else {
|
||||
return Ok(());
|
||||
};
|
||||
|
||||
static HEX_GROUPS: [usize; 5] = [8, 4, 4, 4, 12];
|
||||
let mut i = 0;
|
||||
for group in s.split('-') {
|
||||
if i >= HEX_GROUPS.len() {
|
||||
Err("more than 5 elements")?;
|
||||
}
|
||||
if group.len() != HEX_GROUPS[i] {
|
||||
Err(format!(
|
||||
"element {} must be {} characters long",
|
||||
i + 1,
|
||||
HEX_GROUPS[i]
|
||||
))?;
|
||||
}
|
||||
if let Some(ch) = group.chars().find(|c| !c.is_ascii_hexdigit()) {
|
||||
Err(format!("non-hex character {ch:?}"))?;
|
||||
}
|
||||
i += 1;
|
||||
}
|
||||
if i != HEX_GROUPS.len() {
|
||||
Err("must have 5 elements")?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn validate_uri(v: &Value) -> Result<(), Box<dyn Error + Send + Sync>> {
|
||||
let Value::String(s) = v else {
|
||||
return Ok(());
|
||||
};
|
||||
if fluent_uri::UriRef::parse(s.as_str())
|
||||
.map_err(|e| e.to_string())?
|
||||
.scheme()
|
||||
.is_none()
|
||||
{
|
||||
Err("relative url")?;
|
||||
};
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn validate_iri(v: &Value) -> Result<(), Box<dyn Error + Send + Sync>> {
|
||||
let Value::String(s) = v else {
|
||||
return Ok(());
|
||||
};
|
||||
match Url::parse(s) {
|
||||
Ok(_) => Ok(()),
|
||||
Err(url::ParseError::RelativeUrlWithoutBase) => Err("relative url")?,
|
||||
Err(e) => Err(e)?,
|
||||
}
|
||||
}
|
||||
|
||||
lazy_static! {
|
||||
static ref TEMP_URL: Url = Url::parse("http://temp.com").unwrap();
|
||||
}
|
||||
|
||||
fn parse_uri_reference(s: &str) -> Result<Url, Box<dyn Error + Send + Sync>> {
|
||||
if s.contains('\\') {
|
||||
Err("contains \\\\")?;
|
||||
}
|
||||
Ok(TEMP_URL.join(s)?)
|
||||
}
|
||||
|
||||
fn validate_uri_reference(v: &Value) -> Result<(), Box<dyn Error + Send + Sync>> {
|
||||
let Value::String(s) = v else {
|
||||
return Ok(());
|
||||
};
|
||||
fluent_uri::UriRef::parse(s.as_str()).map_err(|e| e.to_string())?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn validate_iri_reference(v: &Value) -> Result<(), Box<dyn Error + Send + Sync>> {
|
||||
let Value::String(s) = v else {
|
||||
return Ok(());
|
||||
};
|
||||
parse_uri_reference(s)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn validate_uri_template(v: &Value) -> Result<(), Box<dyn Error + Send + Sync>> {
|
||||
let Value::String(s) = v else {
|
||||
return Ok(());
|
||||
};
|
||||
|
||||
let url = parse_uri_reference(s)?;
|
||||
|
||||
let path = url.path();
|
||||
// path we got has curly bases percent encoded
|
||||
let path = percent_decode_str(path).decode_utf8()?;
|
||||
|
||||
// ensure curly brackets are not nested and balanced
|
||||
for part in path.as_ref().split('/') {
|
||||
let mut want = true;
|
||||
for got in part
|
||||
.chars()
|
||||
.filter(|c| matches!(c, '{' | '}'))
|
||||
.map(|c| c == '{')
|
||||
{
|
||||
if got != want {
|
||||
Err("nested curly braces")?;
|
||||
}
|
||||
want = !want;
|
||||
}
|
||||
if !want {
|
||||
Err("no matching closing brace")?
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
381
src/database/mod.rs
Normal file
381
src/database/mod.rs
Normal file
@ -0,0 +1,381 @@
|
||||
pub mod r#enum;
|
||||
pub mod executor;
|
||||
pub mod formats;
|
||||
pub mod page;
|
||||
pub mod punc;
|
||||
pub mod relation;
|
||||
pub mod schema;
|
||||
pub mod r#type;
|
||||
|
||||
use crate::database::r#enum::Enum;
|
||||
use crate::database::executor::{DatabaseExecutor, SpiExecutor};
|
||||
use crate::database::punc::{Punc, Stem};
|
||||
use crate::database::relation::Relation;
|
||||
use crate::database::schema::Schema;
|
||||
use crate::database::r#type::Type;
|
||||
use serde_json::Value;
|
||||
use std::collections::{HashMap, HashSet};
|
||||
|
||||
pub struct Database {
|
||||
pub enums: HashMap<String, Enum>,
|
||||
pub types: HashMap<String, Type>,
|
||||
pub puncs: HashMap<String, Punc>,
|
||||
pub relations: HashMap<String, Relation>,
|
||||
pub schemas: HashMap<String, Schema>,
|
||||
pub descendants: HashMap<String, Vec<String>>,
|
||||
pub depths: HashMap<String, usize>,
|
||||
pub executor: Box<dyn DatabaseExecutor + Send + Sync>,
|
||||
}
|
||||
|
||||
impl Database {
|
||||
pub fn new(val: &serde_json::Value) -> Self {
|
||||
let mut db = Self {
|
||||
enums: HashMap::new(),
|
||||
types: HashMap::new(),
|
||||
relations: HashMap::new(),
|
||||
puncs: HashMap::new(),
|
||||
schemas: HashMap::new(),
|
||||
descendants: HashMap::new(),
|
||||
depths: HashMap::new(),
|
||||
executor: Box::new(SpiExecutor::new()),
|
||||
};
|
||||
|
||||
if let Some(arr) = val.get("enums").and_then(|v| v.as_array()) {
|
||||
for item in arr {
|
||||
if let Ok(def) = serde_json::from_value::<Enum>(item.clone()) {
|
||||
db.enums.insert(def.name.clone(), def);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(arr) = val.get("types").and_then(|v| v.as_array()) {
|
||||
for item in arr {
|
||||
if let Ok(def) = serde_json::from_value::<Type>(item.clone()) {
|
||||
db.types.insert(def.name.clone(), def);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(arr) = val.get("relations").and_then(|v| v.as_array()) {
|
||||
for item in arr {
|
||||
if let Ok(def) = serde_json::from_value::<Relation>(item.clone()) {
|
||||
db.relations.insert(def.constraint.clone(), def);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(arr) = val.get("puncs").and_then(|v| v.as_array()) {
|
||||
for item in arr {
|
||||
if let Ok(def) = serde_json::from_value::<Punc>(item.clone()) {
|
||||
db.puncs.insert(def.name.clone(), def);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(arr) = val.get("schemas").and_then(|v| v.as_array()) {
|
||||
for (i, item) in arr.iter().enumerate() {
|
||||
if let Ok(mut schema) = serde_json::from_value::<Schema>(item.clone()) {
|
||||
let id = schema
|
||||
.obj
|
||||
.id
|
||||
.clone()
|
||||
.unwrap_or_else(|| format!("schema_{}", i));
|
||||
schema.obj.id = Some(id.clone());
|
||||
db.schemas.insert(id, schema);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let _ = db.compile();
|
||||
db
|
||||
}
|
||||
|
||||
/// Override the default executor for unit testing
|
||||
pub fn with_executor(mut self, executor: Box<dyn DatabaseExecutor + Send + Sync>) -> Self {
|
||||
self.executor = executor;
|
||||
self
|
||||
}
|
||||
|
||||
/// Executes a query expecting a single JSONB array return, representing rows.
|
||||
pub fn query(&self, sql: &str, args: Option<&[Value]>) -> Result<Value, String> {
|
||||
self.executor.query(sql, args)
|
||||
}
|
||||
|
||||
/// Executes an operation (INSERT, UPDATE, DELETE, or pg_notify) that does not return rows.
|
||||
pub fn execute(&self, sql: &str, args: Option<&[Value]>) -> Result<(), String> {
|
||||
self.executor.execute(sql, args)
|
||||
}
|
||||
|
||||
/// Returns the current authenticated user's ID
|
||||
pub fn auth_user_id(&self) -> Result<String, String> {
|
||||
self.executor.auth_user_id()
|
||||
}
|
||||
|
||||
/// Returns the current transaction timestamp
|
||||
pub fn timestamp(&self) -> Result<String, String> {
|
||||
self.executor.timestamp()
|
||||
}
|
||||
|
||||
/// Organizes the graph of the database, compiling regex, format functions, and caching relationships.
|
||||
fn compile(&mut self) -> Result<(), String> {
|
||||
self.collect_schemas();
|
||||
self.collect_depths();
|
||||
self.collect_descendants();
|
||||
self.compile_schemas();
|
||||
self.collect_stems();
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn collect_schemas(&mut self) {
|
||||
let mut to_insert = Vec::new();
|
||||
|
||||
// Pass 1: Extract all Schemas structurally off top level definitions into the master registry.
|
||||
for type_def in self.types.values() {
|
||||
for mut schema in type_def.schemas.clone() {
|
||||
schema.harvest(&mut to_insert);
|
||||
}
|
||||
}
|
||||
for punc_def in self.puncs.values() {
|
||||
for mut schema in punc_def.schemas.clone() {
|
||||
schema.harvest(&mut to_insert);
|
||||
}
|
||||
}
|
||||
for enum_def in self.enums.values() {
|
||||
for mut schema in enum_def.schemas.clone() {
|
||||
schema.harvest(&mut to_insert);
|
||||
}
|
||||
}
|
||||
|
||||
for (id, schema) in to_insert {
|
||||
self.schemas.insert(id, schema);
|
||||
}
|
||||
}
|
||||
|
||||
fn collect_depths(&mut self) {
|
||||
let mut depths: HashMap<String, usize> = HashMap::new();
|
||||
let schema_ids: Vec<String> = self.schemas.keys().cloned().collect();
|
||||
|
||||
for id in schema_ids {
|
||||
let mut current_id = id.clone();
|
||||
let mut depth = 0;
|
||||
let mut visited = HashSet::new();
|
||||
|
||||
while let Some(schema) = self.schemas.get(¤t_id) {
|
||||
if !visited.insert(current_id.clone()) {
|
||||
break; // Cycle detected
|
||||
}
|
||||
if let Some(ref_str) = &schema.obj.r#ref {
|
||||
current_id = ref_str.clone();
|
||||
depth += 1;
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
depths.insert(id, depth);
|
||||
}
|
||||
self.depths = depths;
|
||||
}
|
||||
|
||||
fn collect_descendants(&mut self) {
|
||||
let mut direct_refs: HashMap<String, Vec<String>> = HashMap::new();
|
||||
for (id, schema) in &self.schemas {
|
||||
if let Some(ref_str) = &schema.obj.r#ref {
|
||||
direct_refs
|
||||
.entry(ref_str.clone())
|
||||
.or_default()
|
||||
.push(id.clone());
|
||||
}
|
||||
}
|
||||
|
||||
// Cache generic descendants for $family runtime lookups
|
||||
let mut descendants = HashMap::new();
|
||||
for (id, schema) in &self.schemas {
|
||||
if let Some(family_target) = &schema.obj.family {
|
||||
let mut desc_set = HashSet::new();
|
||||
Self::collect_descendants_recursively(family_target, &direct_refs, &mut desc_set);
|
||||
let mut desc_vec: Vec<String> = desc_set.into_iter().collect();
|
||||
desc_vec.sort();
|
||||
|
||||
// By placing all descendants directly onto the ID mapped location of the Family declaration,
|
||||
// we can lookup descendants natively in ValidationContext without AST replacement overrides.
|
||||
descendants.insert(id.clone(), desc_vec);
|
||||
}
|
||||
}
|
||||
self.descendants = descendants;
|
||||
}
|
||||
|
||||
fn collect_descendants_recursively(
|
||||
target: &str,
|
||||
direct_refs: &HashMap<String, Vec<String>>,
|
||||
descendants: &mut HashSet<String>,
|
||||
) {
|
||||
if let Some(children) = direct_refs.get(target) {
|
||||
for child in children {
|
||||
if descendants.insert(child.clone()) {
|
||||
Self::collect_descendants_recursively(child, direct_refs, descendants);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn compile_schemas(&mut self) {
|
||||
// Pass 3: compile_internals across pure structure
|
||||
let schema_ids: Vec<String> = self.schemas.keys().cloned().collect();
|
||||
for id in schema_ids {
|
||||
if let Some(schema) = self.schemas.get_mut(&id) {
|
||||
schema.compile_internals();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn collect_stems(&mut self) {
|
||||
let mut st_map: HashMap<String, Vec<Stem>> = HashMap::new();
|
||||
for (name, _) in &self.puncs {
|
||||
let mut stems = Vec::new();
|
||||
let response_id = format!("{}.response", name);
|
||||
if let Some(resp_schema) = self.schemas.get(&response_id) {
|
||||
Self::discover_stems(
|
||||
&self.types,
|
||||
&self.schemas,
|
||||
&self.relations,
|
||||
&response_id,
|
||||
resp_schema,
|
||||
String::from(""),
|
||||
None,
|
||||
None,
|
||||
&mut stems,
|
||||
);
|
||||
}
|
||||
st_map.insert(name.clone(), stems);
|
||||
}
|
||||
for (name, stems) in st_map {
|
||||
if let Some(p) = self.puncs.get_mut(&name) {
|
||||
p.stems = stems;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn discover_stems(
|
||||
types: &HashMap<String, Type>,
|
||||
schemas: &HashMap<String, Schema>,
|
||||
relations: &HashMap<String, Relation>,
|
||||
_schema_id: &str,
|
||||
schema: &Schema,
|
||||
current_path: String,
|
||||
parent_type: Option<String>,
|
||||
property_name: Option<String>,
|
||||
stems: &mut Vec<Stem>,
|
||||
) {
|
||||
let mut is_entity = false;
|
||||
let mut entity_type = String::new();
|
||||
|
||||
// Check if this schema resolves to an Entity
|
||||
let mut current_ref = schema.obj.r#ref.clone();
|
||||
let mut depth = 0;
|
||||
while let Some(r) = current_ref {
|
||||
if types.contains_key(&r) {
|
||||
is_entity = true;
|
||||
entity_type = r.clone();
|
||||
break;
|
||||
}
|
||||
if let Some(s) = schemas.get(&r) {
|
||||
current_ref = s.obj.r#ref.clone();
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
depth += 1;
|
||||
if depth > 20 {
|
||||
break;
|
||||
} // prevent infinite loop
|
||||
}
|
||||
|
||||
if is_entity {
|
||||
let final_path = if current_path.is_empty() {
|
||||
"/".to_string()
|
||||
} else {
|
||||
current_path.clone()
|
||||
};
|
||||
|
||||
let mut relation_col = None;
|
||||
if let (Some(pt), Some(prop)) = (&parent_type, &property_name) {
|
||||
let expected_col = format!("{}_id", prop);
|
||||
let mut found = false;
|
||||
|
||||
// Try to find the exact relation from the database schema
|
||||
for rel in relations.values() {
|
||||
if rel.source_type == *pt && rel.destination_type == entity_type {
|
||||
if rel.source_columns.contains(&expected_col) {
|
||||
relation_col = Some(expected_col.clone());
|
||||
found = true;
|
||||
break;
|
||||
}
|
||||
} else if rel.source_type == entity_type && rel.destination_type == *pt {
|
||||
if rel.source_columns.contains(&expected_col) {
|
||||
relation_col = Some(expected_col.clone());
|
||||
found = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if !found {
|
||||
// Fallback guess if explicit matching fails
|
||||
relation_col = Some(expected_col);
|
||||
}
|
||||
}
|
||||
|
||||
stems.push(Stem {
|
||||
path: final_path,
|
||||
r#type: entity_type.clone(),
|
||||
relation: relation_col,
|
||||
});
|
||||
}
|
||||
|
||||
// Pass the new parent downwards
|
||||
let next_parent = if is_entity {
|
||||
Some(entity_type.clone())
|
||||
} else {
|
||||
parent_type.clone()
|
||||
};
|
||||
|
||||
if let Some(props) = &schema.obj.properties {
|
||||
for (k, v) in props {
|
||||
let next_path = format!(
|
||||
"{}/{}",
|
||||
if current_path.is_empty() {
|
||||
""
|
||||
} else {
|
||||
¤t_path
|
||||
},
|
||||
k
|
||||
);
|
||||
Self::discover_stems(
|
||||
types,
|
||||
schemas,
|
||||
relations,
|
||||
"",
|
||||
v,
|
||||
next_path,
|
||||
next_parent.clone(),
|
||||
Some(k.clone()),
|
||||
stems,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(items) = &schema.obj.items {
|
||||
Self::discover_stems(
|
||||
types,
|
||||
schemas,
|
||||
relations,
|
||||
"",
|
||||
items,
|
||||
current_path.clone(),
|
||||
next_parent.clone(),
|
||||
property_name.clone(),
|
||||
stems,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
35
src/database/page.rs
Normal file
35
src/database/page.rs
Normal file
@ -0,0 +1,35 @@
|
||||
use indexmap::IndexMap;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
|
||||
#[serde(default)]
|
||||
pub struct Page {
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub path: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub title: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub sidebar: Option<Sidebar>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub actions: Option<IndexMap<String, Action>>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
|
||||
#[serde(default)]
|
||||
pub struct Sidebar {
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub category: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub priority: Option<i32>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
|
||||
#[serde(default)]
|
||||
pub struct Action {
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub punc: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub navigate: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub present: Option<String>,
|
||||
}
|
||||
30
src/database/punc.rs
Normal file
30
src/database/punc.rs
Normal file
@ -0,0 +1,30 @@
|
||||
use crate::database::page::Page;
|
||||
use crate::database::schema::Schema;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct Stem {
|
||||
pub path: String,
|
||||
pub r#type: String,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub relation: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
|
||||
#[serde(default)]
|
||||
pub struct Punc {
|
||||
pub id: String,
|
||||
pub r#type: String,
|
||||
pub name: String,
|
||||
pub module: String,
|
||||
pub source: String,
|
||||
pub description: Option<String>,
|
||||
pub public: bool,
|
||||
pub form: bool,
|
||||
pub get: Option<String>,
|
||||
pub page: Option<Page>,
|
||||
#[serde(default)]
|
||||
pub schemas: Vec<Schema>,
|
||||
#[serde(default)]
|
||||
pub stems: Vec<Stem>,
|
||||
}
|
||||
12
src/database/relation.rs
Normal file
12
src/database/relation.rs
Normal file
@ -0,0 +1,12 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
|
||||
#[serde(default)]
|
||||
pub struct Relation {
|
||||
pub constraint: String,
|
||||
pub source_type: String,
|
||||
pub source_columns: Vec<String>,
|
||||
pub destination_type: String,
|
||||
pub destination_columns: Vec<String>,
|
||||
pub prefix: Option<String>,
|
||||
}
|
||||
340
src/database/schema.rs
Normal file
340
src/database/schema.rs
Normal file
@ -0,0 +1,340 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::Value;
|
||||
use std::collections::BTreeMap;
|
||||
use std::sync::Arc;
|
||||
|
||||
// Schema mirrors the Go Punc Generator's schema struct for consistency.
|
||||
// It is an order-preserving representation of a JSON Schema.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
|
||||
pub struct SchemaObject {
|
||||
// Core Schema Keywords
|
||||
#[serde(rename = "$id")]
|
||||
pub id: Option<String>,
|
||||
#[serde(rename = "$ref")]
|
||||
pub r#ref: Option<String>,
|
||||
/*
|
||||
Note: The `Ref` field in the Go struct is a pointer populated by the linker.
|
||||
In Rust, we might handle this differently (e.g., separate lookup or Rc/Arc),
|
||||
so we omit the direct recursive `Ref` field for now and rely on `ref_string`.
|
||||
*/
|
||||
pub description: Option<String>,
|
||||
pub title: Option<String>,
|
||||
#[serde(default)] // Allow missing type
|
||||
#[serde(rename = "type")]
|
||||
pub type_: Option<SchemaTypeOrArray>, // Handles string or array of strings
|
||||
|
||||
// Object Keywords
|
||||
pub properties: Option<BTreeMap<String, Arc<Schema>>>,
|
||||
#[serde(rename = "patternProperties")]
|
||||
pub pattern_properties: Option<BTreeMap<String, Arc<Schema>>>,
|
||||
#[serde(rename = "additionalProperties")]
|
||||
pub additional_properties: Option<Arc<Schema>>,
|
||||
#[serde(rename = "$family")]
|
||||
pub family: Option<String>,
|
||||
|
||||
pub required: Option<Vec<String>>,
|
||||
|
||||
// dependencies can be schema dependencies or property dependencies
|
||||
pub dependencies: Option<BTreeMap<String, Dependency>>,
|
||||
|
||||
// Array Keywords
|
||||
#[serde(rename = "items")]
|
||||
pub items: Option<Arc<Schema>>,
|
||||
#[serde(rename = "prefixItems")]
|
||||
pub prefix_items: Option<Vec<Arc<Schema>>>,
|
||||
|
||||
// String Validation
|
||||
#[serde(rename = "minLength")]
|
||||
pub min_length: Option<f64>,
|
||||
#[serde(rename = "maxLength")]
|
||||
pub max_length: Option<f64>,
|
||||
pub pattern: Option<String>,
|
||||
|
||||
// Array Validation
|
||||
#[serde(rename = "minItems")]
|
||||
pub min_items: Option<f64>,
|
||||
#[serde(rename = "maxItems")]
|
||||
pub max_items: Option<f64>,
|
||||
#[serde(rename = "uniqueItems")]
|
||||
pub unique_items: Option<bool>,
|
||||
#[serde(rename = "contains")]
|
||||
pub contains: Option<Arc<Schema>>,
|
||||
#[serde(rename = "minContains")]
|
||||
pub min_contains: Option<f64>,
|
||||
#[serde(rename = "maxContains")]
|
||||
pub max_contains: Option<f64>,
|
||||
|
||||
// Object Validation
|
||||
#[serde(rename = "minProperties")]
|
||||
pub min_properties: Option<f64>,
|
||||
#[serde(rename = "maxProperties")]
|
||||
pub max_properties: Option<f64>,
|
||||
#[serde(rename = "propertyNames")]
|
||||
pub property_names: Option<Arc<Schema>>,
|
||||
|
||||
// Numeric Validation
|
||||
pub format: Option<String>,
|
||||
#[serde(rename = "enum")]
|
||||
pub enum_: Option<Vec<Value>>, // `enum` is a reserved keyword in Rust
|
||||
#[serde(
|
||||
default,
|
||||
rename = "const",
|
||||
deserialize_with = "crate::validator::util::deserialize_some"
|
||||
)]
|
||||
pub const_: Option<Value>,
|
||||
|
||||
// Numeric Validation
|
||||
#[serde(rename = "multipleOf")]
|
||||
pub multiple_of: Option<f64>,
|
||||
pub minimum: Option<f64>,
|
||||
pub maximum: Option<f64>,
|
||||
#[serde(rename = "exclusiveMinimum")]
|
||||
pub exclusive_minimum: Option<f64>,
|
||||
#[serde(rename = "exclusiveMaximum")]
|
||||
pub exclusive_maximum: Option<f64>,
|
||||
|
||||
// Combining Keywords
|
||||
#[serde(rename = "allOf")]
|
||||
pub all_of: Option<Vec<Arc<Schema>>>,
|
||||
#[serde(rename = "anyOf")]
|
||||
pub any_of: Option<Vec<Arc<Schema>>>,
|
||||
#[serde(rename = "oneOf")]
|
||||
pub one_of: Option<Vec<Arc<Schema>>>,
|
||||
#[serde(rename = "not")]
|
||||
pub not: Option<Arc<Schema>>,
|
||||
#[serde(rename = "if")]
|
||||
pub if_: Option<Arc<Schema>>,
|
||||
#[serde(rename = "then")]
|
||||
pub then_: Option<Arc<Schema>>,
|
||||
#[serde(rename = "else")]
|
||||
pub else_: Option<Arc<Schema>>,
|
||||
|
||||
// Custom Vocabularies
|
||||
pub form: Option<Vec<String>>,
|
||||
pub display: Option<Vec<String>>,
|
||||
#[serde(rename = "enumNames")]
|
||||
pub enum_names: Option<Vec<String>>,
|
||||
pub control: Option<String>,
|
||||
pub actions: Option<BTreeMap<String, Action>>,
|
||||
pub computer: Option<String>,
|
||||
#[serde(default)]
|
||||
pub extensible: Option<bool>,
|
||||
|
||||
#[serde(skip)]
|
||||
pub compiled_format: Option<CompiledFormat>,
|
||||
#[serde(skip)]
|
||||
pub compiled_pattern: Option<CompiledRegex>,
|
||||
#[serde(skip)]
|
||||
pub compiled_pattern_properties: Option<Vec<(CompiledRegex, Arc<Schema>)>>,
|
||||
}
|
||||
|
||||
/// Represents a compiled format validator
|
||||
#[derive(Clone)]
|
||||
pub enum CompiledFormat {
|
||||
Func(fn(&serde_json::Value) -> Result<(), Box<dyn std::error::Error + Send + Sync>>),
|
||||
Regex(regex::Regex),
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for CompiledFormat {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
match self {
|
||||
CompiledFormat::Func(_) => write!(f, "CompiledFormat::Func(...)"),
|
||||
CompiledFormat::Regex(r) => write!(f, "CompiledFormat::Regex({:?})", r),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A wrapper for compiled regex patterns
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct CompiledRegex(pub regex::Regex);
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Default)]
|
||||
pub struct Schema {
|
||||
#[serde(flatten)]
|
||||
pub obj: SchemaObject,
|
||||
#[serde(skip)]
|
||||
pub always_fail: bool,
|
||||
}
|
||||
|
||||
impl std::ops::Deref for Schema {
|
||||
type Target = SchemaObject;
|
||||
fn deref(&self) -> &Self::Target {
|
||||
&self.obj
|
||||
}
|
||||
}
|
||||
impl std::ops::DerefMut for Schema {
|
||||
fn deref_mut(&mut self) -> &mut Self::Target {
|
||||
&mut self.obj
|
||||
}
|
||||
}
|
||||
|
||||
impl Schema {
|
||||
pub fn compile_internals(&mut self) {
|
||||
self.map_children(|child| child.compile_internals());
|
||||
|
||||
if let Some(format_str) = &self.obj.format
|
||||
&& let Some(fmt) = crate::database::formats::FORMATS.get(format_str.as_str())
|
||||
{
|
||||
self.obj.compiled_format = Some(crate::database::schema::CompiledFormat::Func(fmt.func));
|
||||
}
|
||||
|
||||
if let Some(pattern_str) = &self.obj.pattern
|
||||
&& let Ok(re) = regex::Regex::new(pattern_str)
|
||||
{
|
||||
self.obj.compiled_pattern = Some(crate::database::schema::CompiledRegex(re));
|
||||
}
|
||||
|
||||
if let Some(pattern_props) = &self.obj.pattern_properties {
|
||||
let mut compiled = Vec::new();
|
||||
for (k, v) in pattern_props {
|
||||
if let Ok(re) = regex::Regex::new(k) {
|
||||
compiled.push((crate::database::schema::CompiledRegex(re), v.clone()));
|
||||
}
|
||||
}
|
||||
if !compiled.is_empty() {
|
||||
self.obj.compiled_pattern_properties = Some(compiled);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn harvest(&mut self, to_insert: &mut Vec<(String, Schema)>) {
|
||||
if let Some(id) = &self.obj.id {
|
||||
to_insert.push((id.clone(), self.clone()));
|
||||
}
|
||||
self.map_children(|child| child.harvest(to_insert));
|
||||
}
|
||||
|
||||
pub fn map_children<F>(&mut self, mut f: F)
|
||||
where
|
||||
F: FnMut(&mut Schema),
|
||||
{
|
||||
if let Some(props) = &mut self.obj.properties {
|
||||
for v in props.values_mut() {
|
||||
let mut inner = (**v).clone();
|
||||
f(&mut inner);
|
||||
*v = Arc::new(inner);
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(pattern_props) = &mut self.obj.pattern_properties {
|
||||
for v in pattern_props.values_mut() {
|
||||
let mut inner = (**v).clone();
|
||||
f(&mut inner);
|
||||
*v = Arc::new(inner);
|
||||
}
|
||||
}
|
||||
|
||||
let mut map_arr = |arr: &mut Vec<Arc<Schema>>| {
|
||||
for v in arr.iter_mut() {
|
||||
let mut inner = (**v).clone();
|
||||
f(&mut inner);
|
||||
*v = Arc::new(inner);
|
||||
}
|
||||
};
|
||||
|
||||
if let Some(arr) = &mut self.obj.prefix_items {
|
||||
map_arr(arr);
|
||||
}
|
||||
if let Some(arr) = &mut self.obj.all_of {
|
||||
map_arr(arr);
|
||||
}
|
||||
if let Some(arr) = &mut self.obj.any_of {
|
||||
map_arr(arr);
|
||||
}
|
||||
if let Some(arr) = &mut self.obj.one_of {
|
||||
map_arr(arr);
|
||||
}
|
||||
|
||||
let mut map_opt = |opt: &mut Option<Arc<Schema>>| {
|
||||
if let Some(v) = opt {
|
||||
let mut inner = (**v).clone();
|
||||
f(&mut inner);
|
||||
*v = Arc::new(inner);
|
||||
}
|
||||
};
|
||||
|
||||
map_opt(&mut self.obj.additional_properties);
|
||||
map_opt(&mut self.obj.items);
|
||||
map_opt(&mut self.obj.contains);
|
||||
map_opt(&mut self.obj.property_names);
|
||||
map_opt(&mut self.obj.not);
|
||||
map_opt(&mut self.obj.if_);
|
||||
map_opt(&mut self.obj.then_);
|
||||
map_opt(&mut self.obj.else_);
|
||||
}
|
||||
}
|
||||
|
||||
impl<'de> Deserialize<'de> for Schema {
|
||||
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
|
||||
where
|
||||
D: serde::Deserializer<'de>,
|
||||
{
|
||||
let v: Value = Deserialize::deserialize(deserializer)?;
|
||||
|
||||
if let Some(b) = v.as_bool() {
|
||||
let mut obj = SchemaObject::default();
|
||||
if b {
|
||||
obj.extensible = Some(true);
|
||||
}
|
||||
return Ok(Schema {
|
||||
obj,
|
||||
always_fail: !b,
|
||||
});
|
||||
}
|
||||
let mut obj: SchemaObject =
|
||||
serde_json::from_value(v.clone()).map_err(serde::de::Error::custom)?;
|
||||
|
||||
// If a schema is effectively empty (except for potentially carrying an ID),
|
||||
// it functions as a boolean `true` schema in Draft2020 which means it should not
|
||||
// restrict additional properties natively
|
||||
let is_empty = obj.type_.is_none()
|
||||
&& obj.properties.is_none()
|
||||
&& obj.pattern_properties.is_none()
|
||||
&& obj.additional_properties.is_none()
|
||||
&& obj.required.is_none()
|
||||
&& obj.dependencies.is_none()
|
||||
&& obj.items.is_none()
|
||||
&& obj.prefix_items.is_none()
|
||||
&& obj.contains.is_none()
|
||||
&& obj.format.is_none()
|
||||
&& obj.enum_.is_none()
|
||||
&& obj.const_.is_none()
|
||||
&& obj.all_of.is_none()
|
||||
&& obj.any_of.is_none()
|
||||
&& obj.one_of.is_none()
|
||||
&& obj.not.is_none()
|
||||
&& obj.if_.is_none()
|
||||
&& obj.then_.is_none()
|
||||
&& obj.else_.is_none()
|
||||
&& obj.r#ref.is_none()
|
||||
&& obj.family.is_none();
|
||||
|
||||
if is_empty && obj.extensible.is_none() {
|
||||
obj.extensible = Some(true);
|
||||
}
|
||||
|
||||
Ok(Schema {
|
||||
obj,
|
||||
always_fail: false,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
#[serde(untagged)]
|
||||
pub enum SchemaTypeOrArray {
|
||||
Single(String),
|
||||
Multiple(Vec<String>),
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct Action {
|
||||
pub navigate: Option<String>,
|
||||
pub punc: Option<String>,
|
||||
}
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
#[serde(untagged)]
|
||||
pub enum Dependency {
|
||||
Props(Vec<String>),
|
||||
Schema(Arc<Schema>),
|
||||
}
|
||||
40
src/database/type.rs
Normal file
40
src/database/type.rs
Normal file
@ -0,0 +1,40 @@
|
||||
use std::collections::HashSet;
|
||||
|
||||
use crate::database::schema::Schema;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::Value;
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
|
||||
#[serde(default)]
|
||||
pub struct Type {
|
||||
pub id: String,
|
||||
pub r#type: String,
|
||||
pub name: String,
|
||||
pub module: String,
|
||||
pub source: String,
|
||||
#[serde(default)]
|
||||
pub historical: bool,
|
||||
#[serde(default)]
|
||||
pub sensitive: bool,
|
||||
#[serde(default)]
|
||||
pub ownable: bool,
|
||||
pub longevity: Option<i32>,
|
||||
#[serde(default)]
|
||||
pub hierarchy: Vec<String>,
|
||||
#[serde(default)]
|
||||
pub variations: HashSet<String>,
|
||||
#[serde(default)]
|
||||
pub relationship: bool,
|
||||
#[serde(default)]
|
||||
pub fields: Vec<String>,
|
||||
pub grouped_fields: Option<Value>,
|
||||
#[serde(default)]
|
||||
pub lookup_fields: Vec<String>,
|
||||
#[serde(default)]
|
||||
pub null_fields: Vec<String>,
|
||||
#[serde(default)]
|
||||
pub default_fields: Vec<String>,
|
||||
pub field_types: Option<Value>,
|
||||
#[serde(default)]
|
||||
pub schemas: Vec<Schema>,
|
||||
}
|
||||
72
src/drop.rs
Normal file
72
src/drop.rs
Normal file
@ -0,0 +1,72 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::Value;
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize, Clone)]
|
||||
pub struct Drop {
|
||||
// We don't need id, frequency, etc. for the validation result specifically,
|
||||
// as they are added by the SQL wrapper. We just need to conform to the structure.
|
||||
// The user said "Validator::validate always needs to return this drop type".
|
||||
// So we should match it as closely as possible.
|
||||
#[serde(rename = "type")]
|
||||
pub type_: String, // "drop"
|
||||
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub response: Option<Value>,
|
||||
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub errors: Vec<Error>,
|
||||
}
|
||||
|
||||
impl Default for Drop {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
type_: "drop".to_string(),
|
||||
response: None,
|
||||
errors: vec![],
|
||||
}
|
||||
}
|
||||
|
||||
pub fn success() -> Self {
|
||||
Self {
|
||||
type_: "drop".to_string(),
|
||||
response: Some(serde_json::json!("success")),
|
||||
errors: vec![],
|
||||
}
|
||||
}
|
||||
|
||||
pub fn success_with_val(val: Value) -> Self {
|
||||
Self {
|
||||
type_: "drop".to_string(),
|
||||
response: Some(val),
|
||||
errors: vec![],
|
||||
}
|
||||
}
|
||||
|
||||
pub fn with_errors(errors: Vec<Error>) -> Self {
|
||||
Self {
|
||||
type_: "drop".to_string(),
|
||||
response: None,
|
||||
errors,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize, Clone)]
|
||||
pub struct Error {
|
||||
pub code: String,
|
||||
pub message: String,
|
||||
pub details: ErrorDetails,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize, Clone)]
|
||||
pub struct ErrorDetails {
|
||||
pub path: String,
|
||||
// Extensions can be added here (package, cause, etc)
|
||||
// For now, validator only provides path
|
||||
}
|
||||
79
src/entity/GEMINI.md
Normal file
79
src/entity/GEMINI.md
Normal file
@ -0,0 +1,79 @@
|
||||
# Entity Engine (jspg)
|
||||
|
||||
## Overview
|
||||
|
||||
This document outlines the architecture for moving the complex, CPU-bound row merging (`merge_entity`) and dynamic querying (`query_entity`) functionality out of PL/pgSQL and directly into the Rust-based `jspg` extension.
|
||||
|
||||
By treating the `jspg` schema registry as the absolute Single Source of Truth, we can leverage Rust and the Postgres query planner (via SPI) to achieve near O(1) execution planning for deeply nested reads, complex relational writes, and partial hydration beats.
|
||||
|
||||
## The Problem
|
||||
|
||||
Historically, `agreego.merge_entity` (PL/pgSQL) handled nested writes by segmenting JSON, resolving types, searching hierarchies, and dynamically concatenating `INSERT`/`UPDATE` statements. `agreego.query_entity` was conceived to do the same for reads (handling base security, inheritance JOINs, and filtering automatically).
|
||||
|
||||
However, this design hits three major limitations:
|
||||
1. **CPU Bound Operations**: PL/pgSQL is comparatively slow at complex string concatenation and massive JSON graph traversals.
|
||||
2. **Query Planning Cache Busting**: Generating massive, dynamic SQL strings prevents Postgres from caching query plans. `EXECUTE dynamic_sql` forces the planner to re-evaluate statistics and execution paths on every function call, leading to extreme latency spikes at scale.
|
||||
3. **The Hydration Beat Problem**: The Punc framework requires fetching specific UI "fragments" (e.g. just the `target` of a specific `contact` array element) to feed WebSockets. Hand-rolling CTEs for every possible sub-tree permutation to serve beats will quickly become unmaintainable.
|
||||
|
||||
## The Solution: Semantic Engine Database
|
||||
|
||||
By migrating `merge_entity` and `query_entity` to `jspg`, we turn the database into a pre-compiled Semantic Engine.
|
||||
|
||||
1. **Schema-to-SQL Compilation**: During the connection lifecycle (`cache_json_schemas()`), `jspg` statically analyzes the JSON Schema AST. It acts as a compiler, translating the schema layout into perfectly optimized, multi-JOIN SQL query strings for *every* node/fragment in the schema.
|
||||
2. **Prepared Statements (SPI)**: `jspg` feeds these computed SQL strings into the Postgres SPI (Server Programming Interface) using `Spi::prepare()`. Postgres calculates the query execution plan *once* and caches it in memory.
|
||||
3. **Instant Execution**: When a Punc needs data, `jspg` retrieves the cached PreparedStatement, securely binds binary parameters, and executes the pre-planned query instantly.
|
||||
|
||||
## Architecture
|
||||
|
||||
### 1. The `cache_json_schemas()` Expansion
|
||||
The initialization function must now ingest `types` and `agreego.relation` data so the internal `Registry` holds the full Relational Graph.
|
||||
|
||||
During schema compilation, if a schema is associated with a database Type, it triggers the **SQL Compiler Phase**:
|
||||
- It builds a table-resolution AST mapping to `JOIN` clauses based on foreign keys.
|
||||
- It translates JSON schema properties to `SELECT jsonb_build_object(...)`.
|
||||
- It generates static SQL for `INSERT`, `UPDATE`, and `SELECT` (including path-based fragment SELECTs).
|
||||
- It calls `Spi::prepare()` to cache these plans inside the Session Context.
|
||||
|
||||
### 2. `agreego.query_entity` (Reads)
|
||||
* **API**: `agreego.query_entity(schema_id TEXT, fragment_path TEXT, cue JSONB)`
|
||||
* **Execution**:
|
||||
* Rust locates the target Schema in memory.
|
||||
* It uses the `fragment_path` (e.g., `/` for a full read, or `/contacts/0/target` for a hydration beat) to fetch the exact PreparedStatement.
|
||||
* It binds variables (Row Level Security IDs, filtering, pagination limit/offset) parsed from the `cue`.
|
||||
* SPI returns the heavily nested, pre-aggregated `JSONB` instantly.
|
||||
|
||||
### 3. Unified Aggregations & Computeds (Schema `query` objects)
|
||||
We replace the concept of a complex string parser (PEL) with native structured JSON JSON objects using the `query` keyword.
|
||||
|
||||
A structured `query` block in the schema:
|
||||
```json
|
||||
"total": {
|
||||
"type": "number",
|
||||
"readOnly": true,
|
||||
"query": {
|
||||
"aggregate": "sum",
|
||||
"source": "lines",
|
||||
"field": "amount"
|
||||
}
|
||||
}
|
||||
```
|
||||
* **Frontend (Dart)**: The Go generator parses the JSON object directly and emits the native UI aggregation code (e.g. `lines.fold(...)`) for instant UI updates before the server responds.
|
||||
* **Backend (jspg)**: The Rust SQL compiler natively deserializes the `query` object into an internal struct. It recognizes the `aggregate` instruction and outputs a Postgres native aggregation: `(SELECT SUM(amount) FROM agreego.invoice_line WHERE invoice_id = t1.id)` as a column in the prepared `SELECT` statement.
|
||||
* **Unification**: The database-calculated value acts as the authoritative truth, synchronizing and correcting the client automatically on the resulting `beat`.
|
||||
|
||||
### 4. `agreego.merge_entity` (Writes)
|
||||
* **API**: `agreego.merge_entity(cue JSONB)`
|
||||
* **Execution**:
|
||||
* Parses the incoming `cue` JSON via `serde_json` at C-like speeds.
|
||||
* Recursively validates and *constructively masks* the tree against the strict schema.
|
||||
* Traverses the relational graph (which is fully loaded in the `jspg` registry).
|
||||
* Binds the new values directly into the cached `INSERT` or `UPDATE` SPI prepared statements for each table in the hierarchy.
|
||||
* Evaluates field differences and natively uses `pg_notify` to fire atomic row-level changes for the Go Beat framework.
|
||||
|
||||
## Roadmap
|
||||
|
||||
1. **Relational Ingestion**: Update `cache_json_schemas` to pass relational metadata (`agreego.relation` rows) into the `jspg` registry cache.
|
||||
2. **The SQL Compiler**: Build the AST-to-String compiler in Rust that reads properties, `$ref`s, and `$family` trees to piece together generic SQL.
|
||||
3. **SPI Caching**: Integrate `Spi::prepare` into the `Validator` creation phase.
|
||||
4. **Rust `merge_entity`**: Port the constructive structural extraction loop from PL/pgSQL to Rust.
|
||||
5. **Rust `query_entity`**: Abstract the query runtime, mapping Punc JSON `filters` arrays to SPI-bound parameters safely.
|
||||
29
src/jspg.rs
Normal file
29
src/jspg.rs
Normal file
@ -0,0 +1,29 @@
|
||||
use crate::database::Database;
|
||||
use crate::merger::Merger;
|
||||
use crate::queryer::Queryer;
|
||||
use crate::validator::Validator;
|
||||
use std::sync::Arc;
|
||||
|
||||
pub struct Jspg {
|
||||
pub database: Arc<Database>,
|
||||
pub validator: Validator,
|
||||
pub queryer: Queryer,
|
||||
pub merger: Merger,
|
||||
}
|
||||
|
||||
impl Jspg {
|
||||
pub fn new(database_val: &serde_json::Value) -> Self {
|
||||
let database_instance = Database::new(database_val);
|
||||
let database = Arc::new(database_instance);
|
||||
let validator = Validator::new(database.clone());
|
||||
let queryer = Queryer::new(database.clone());
|
||||
let merger = Merger::new(database.clone());
|
||||
|
||||
Self {
|
||||
database,
|
||||
validator,
|
||||
queryer,
|
||||
merger,
|
||||
}
|
||||
}
|
||||
}
|
||||
350
src/lib.rs
350
src/lib.rs
@ -2,199 +2,209 @@ use pgrx::*;
|
||||
|
||||
pg_module_magic!();
|
||||
|
||||
use serde_json::{json, Value};
|
||||
use std::{collections::HashMap, sync::RwLock};
|
||||
use boon::{Compiler, Schemas, ValidationError, SchemaIndex, CompileError};
|
||||
use lazy_static::lazy_static;
|
||||
pub mod database;
|
||||
pub mod drop;
|
||||
pub mod jspg;
|
||||
pub mod merger;
|
||||
pub mod queryer;
|
||||
pub mod validator;
|
||||
|
||||
struct BoonCache {
|
||||
schemas: Schemas,
|
||||
id_to_index: HashMap<String, SchemaIndex>,
|
||||
}
|
||||
use std::sync::{Arc, RwLock};
|
||||
|
||||
lazy_static! {
|
||||
static ref SCHEMA_CACHE: RwLock<BoonCache> = RwLock::new(BoonCache {
|
||||
schemas: Schemas::new(),
|
||||
id_to_index: HashMap::new(),
|
||||
});
|
||||
lazy_static::lazy_static! {
|
||||
// Global Atomic Swap Container:
|
||||
// - RwLock: To protect the SWAP of the Option.
|
||||
// - Option: Because it starts empty.
|
||||
// - Arc: Because multiple running threads might hold the OLD engine while we swap.
|
||||
// - Jspg: The root semantic engine encapsulating the database metadata, validator, queryer, and merger.
|
||||
static ref GLOBAL_JSPG: RwLock<Option<Arc<jspg::Jspg>>> = RwLock::new(None);
|
||||
}
|
||||
|
||||
#[pg_extern(strict)]
|
||||
fn cache_json_schema(schema_id: &str, schema: JsonB) -> JsonB {
|
||||
let mut cache = SCHEMA_CACHE.write().unwrap();
|
||||
let schema_value: Value = schema.0;
|
||||
let schema_path = format!("urn:{}", schema_id);
|
||||
pub fn jspg_setup(database: JsonB) -> JsonB {
|
||||
let new_jspg = crate::jspg::Jspg::new(&database.0);
|
||||
let new_arc = Arc::new(new_jspg);
|
||||
|
||||
let mut compiler = Compiler::new();
|
||||
compiler.enable_format_assertions();
|
||||
|
||||
// Use schema_path when adding the resource
|
||||
if let Err(e) = compiler.add_resource(&schema_path, schema_value.clone()) {
|
||||
return JsonB(json!({
|
||||
"success": false,
|
||||
"error": {
|
||||
"message": format!("Failed to add schema resource '{}': {}", schema_id, e),
|
||||
"schema_path": schema_path
|
||||
}
|
||||
}));
|
||||
// 3. ATOMIC SWAP
|
||||
{
|
||||
let mut lock = GLOBAL_JSPG.write().unwrap();
|
||||
*lock = Some(new_arc);
|
||||
}
|
||||
|
||||
// Use schema_path when compiling
|
||||
match compiler.compile(&schema_path, &mut cache.schemas) {
|
||||
Ok(sch_index) => {
|
||||
// Store the index using the original schema_id as the key
|
||||
cache.id_to_index.insert(schema_id.to_string(), sch_index);
|
||||
JsonB(json!({ "success": true }))
|
||||
}
|
||||
Err(e) => {
|
||||
let error = match &e {
|
||||
CompileError::ValidationError { url: _url, src } => {
|
||||
// Collect leaf errors from the meta-schema validation failure
|
||||
let mut error_list = Vec::new();
|
||||
collect_leaf_errors(src, &mut error_list);
|
||||
// Return the flat list directly
|
||||
json!(error_list)
|
||||
}
|
||||
_ => {
|
||||
// Keep existing handling for other compilation errors
|
||||
let _error_type = format!("{:?}", e).split('(').next().unwrap_or("Unknown").to_string();
|
||||
json!({
|
||||
"message": format!("Schema '{}' compilation failed: {}", schema_id, e),
|
||||
"schema_path": schema_path,
|
||||
"detail": format!("{:?}", e),
|
||||
})
|
||||
}
|
||||
};
|
||||
// Ensure the outer structure remains { success: false, error: ... }
|
||||
JsonB(json!({
|
||||
"success": false,
|
||||
"error": error
|
||||
}))
|
||||
}
|
||||
}
|
||||
let drop = crate::drop::Drop::success();
|
||||
JsonB(serde_json::to_value(drop).unwrap())
|
||||
}
|
||||
|
||||
#[pg_extern(strict, parallel_safe)]
|
||||
fn validate_json_schema(schema_id: &str, instance: JsonB) -> JsonB {
|
||||
let cache = SCHEMA_CACHE.read().unwrap();
|
||||
|
||||
// Lookup uses the original schema_id
|
||||
match cache.id_to_index.get(schema_id) {
|
||||
None => JsonB(json!({
|
||||
"success": false,
|
||||
"error": {
|
||||
"message": format!("Schema with id '{}' not found in cache", schema_id)
|
||||
}
|
||||
})),
|
||||
Some(sch_index) => {
|
||||
let instance_value: Value = instance.0;
|
||||
match cache.schemas.validate(&instance_value, *sch_index) {
|
||||
Ok(_) => JsonB(json!({ "success": true })),
|
||||
Err(validation_error) => {
|
||||
// Collect all leaf errors first
|
||||
let mut raw_error_list = Vec::new();
|
||||
collect_leaf_errors(&validation_error, &mut raw_error_list);
|
||||
|
||||
// Filter the errors (e.g., deduplicate by instance_path)
|
||||
let filtered_error_list = filter_boon_errors(raw_error_list);
|
||||
|
||||
JsonB(json!({
|
||||
"success": false,
|
||||
"error": filtered_error_list // Return the filtered list
|
||||
}))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Recursively collects leaf errors into a flat list
|
||||
fn collect_leaf_errors(error: &ValidationError, errors_list: &mut Vec<Value>) {
|
||||
if error.causes.is_empty() {
|
||||
let default_message = format!("{}", error);
|
||||
let message = if let Some(start_index) = default_message.find("': ") {
|
||||
default_message[start_index + 3..].to_string()
|
||||
} else {
|
||||
default_message
|
||||
};
|
||||
|
||||
errors_list.push(json!({
|
||||
"message": message,
|
||||
"schema_path": error.schema_url.to_string(),
|
||||
"instance_path": error.instance_location.to_string(),
|
||||
}));
|
||||
} else {
|
||||
for cause in &error.causes {
|
||||
collect_leaf_errors(cause, errors_list);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Filters collected errors, e.g., deduplicating by instance_path
|
||||
fn filter_boon_errors(raw_errors: Vec<Value>) -> Vec<Value> {
|
||||
use std::collections::HashMap;
|
||||
use std::collections::hash_map::Entry;
|
||||
|
||||
// Use a HashMap to keep only the first error for each instance_path
|
||||
let mut unique_errors: HashMap<String, Value> = HashMap::new();
|
||||
|
||||
for error_value in raw_errors {
|
||||
if let Some(instance_path_value) = error_value.get("instance_path") {
|
||||
if let Some(instance_path_str) = instance_path_value.as_str() {
|
||||
// Use Entry API to insert only if the key is not present
|
||||
if let Entry::Vacant(entry) = unique_errors.entry(instance_path_str.to_string()) {
|
||||
entry.insert(error_value);
|
||||
}
|
||||
}
|
||||
}
|
||||
// If error doesn't have instance_path or it's not a string, we might ignore it or handle differently.
|
||||
// For now, we implicitly ignore errors without a valid string instance_path for deduplication.
|
||||
}
|
||||
|
||||
// Collect the unique errors from the map values
|
||||
unique_errors.into_values().collect()
|
||||
}
|
||||
|
||||
#[pg_extern(strict, parallel_safe)]
|
||||
fn json_schema_cached(schema_id: &str) -> bool {
|
||||
let cache = SCHEMA_CACHE.read().unwrap();
|
||||
cache.id_to_index.contains_key(schema_id)
|
||||
}
|
||||
|
||||
#[pg_extern(strict)]
|
||||
fn clear_json_schemas() {
|
||||
let mut cache = SCHEMA_CACHE.write().unwrap();
|
||||
*cache = BoonCache {
|
||||
schemas: Schemas::new(),
|
||||
id_to_index: HashMap::new(),
|
||||
#[pg_extern]
|
||||
pub fn jspg_merge(data: JsonB) -> JsonB {
|
||||
// Try to acquire a read lock to get a clone of the Engine Arc
|
||||
let engine_opt = {
|
||||
let lock = GLOBAL_JSPG.read().unwrap();
|
||||
lock.clone()
|
||||
};
|
||||
|
||||
match engine_opt {
|
||||
Some(engine) => match engine.merger.merge(data.0) {
|
||||
Ok(result) => JsonB(result),
|
||||
Err(e) => {
|
||||
let error = crate::drop::Error {
|
||||
code: "MERGE_FAILED".to_string(),
|
||||
message: e,
|
||||
details: crate::drop::ErrorDetails {
|
||||
path: "".to_string(),
|
||||
},
|
||||
};
|
||||
let drop = crate::drop::Drop::with_errors(vec![error]);
|
||||
JsonB(serde_json::to_value(drop).unwrap())
|
||||
}
|
||||
},
|
||||
None => {
|
||||
let error = crate::drop::Error {
|
||||
code: "VALIDATOR_NOT_INITIALIZED".to_string(),
|
||||
message: "The JSPG database has not been cached yet. Run jspg_setup()".to_string(),
|
||||
details: crate::drop::ErrorDetails {
|
||||
path: "".to_string(),
|
||||
},
|
||||
};
|
||||
let drop = crate::drop::Drop::with_errors(vec![error]);
|
||||
JsonB(serde_json::to_value(drop).unwrap())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[pg_extern]
|
||||
pub fn jspg_query(schema_id: &str, stem: Option<&str>, filters: Option<JsonB>) -> JsonB {
|
||||
let engine_opt = {
|
||||
let lock = GLOBAL_JSPG.read().unwrap();
|
||||
lock.clone()
|
||||
};
|
||||
|
||||
match engine_opt {
|
||||
Some(engine) => match engine
|
||||
.queryer
|
||||
.query(schema_id, stem, filters.as_ref().map(|f| &f.0))
|
||||
{
|
||||
Ok(res) => JsonB(res),
|
||||
Err(e) => {
|
||||
let error = crate::drop::Error {
|
||||
code: "QUERY_FAILED".to_string(),
|
||||
message: e,
|
||||
details: crate::drop::ErrorDetails {
|
||||
path: schema_id.to_string(),
|
||||
},
|
||||
};
|
||||
JsonB(serde_json::to_value(crate::drop::Drop::with_errors(vec![error])).unwrap())
|
||||
}
|
||||
},
|
||||
None => {
|
||||
let error = crate::drop::Error {
|
||||
code: "ENGINE_NOT_INITIALIZED".to_string(),
|
||||
message: "JSPG extension has not been initialized via jspg_setup".to_string(),
|
||||
details: crate::drop::ErrorDetails {
|
||||
path: "".to_string(),
|
||||
},
|
||||
};
|
||||
JsonB(serde_json::to_value(crate::drop::Drop::with_errors(vec![error])).unwrap())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// `mask_json_schema` has been removed as the mask architecture is fully replaced by Spi string queries during DB interactions.
|
||||
|
||||
#[pg_extern(strict, parallel_safe)]
|
||||
fn show_json_schemas() -> Vec<String> {
|
||||
let cache = SCHEMA_CACHE.read().unwrap();
|
||||
let ids: Vec<String> = cache.id_to_index.keys().cloned().collect();
|
||||
ids
|
||||
pub fn jspg_validate(schema_id: &str, instance: JsonB) -> JsonB {
|
||||
// 1. Acquire Snapshot
|
||||
let jspg_arc = {
|
||||
let lock = GLOBAL_JSPG.read().unwrap();
|
||||
lock.clone()
|
||||
};
|
||||
|
||||
// 2. Validate (Lock-Free)
|
||||
if let Some(engine) = jspg_arc {
|
||||
match engine.validator.validate(schema_id, &instance.0) {
|
||||
Ok(result) => {
|
||||
if result.is_valid() {
|
||||
let drop = crate::drop::Drop::success();
|
||||
JsonB(serde_json::to_value(drop).unwrap())
|
||||
} else {
|
||||
let errors: Vec<crate::drop::Error> = result
|
||||
.errors
|
||||
.into_iter()
|
||||
.map(|e| crate::drop::Error {
|
||||
code: e.code,
|
||||
message: e.message,
|
||||
details: crate::drop::ErrorDetails { path: e.path },
|
||||
})
|
||||
.collect();
|
||||
let drop = crate::drop::Drop::with_errors(errors);
|
||||
JsonB(serde_json::to_value(drop).unwrap())
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
let error = crate::drop::Error {
|
||||
code: e.code,
|
||||
message: e.message,
|
||||
details: crate::drop::ErrorDetails { path: e.path },
|
||||
};
|
||||
let drop = crate::drop::Drop::with_errors(vec![error]);
|
||||
JsonB(serde_json::to_value(drop).unwrap())
|
||||
}
|
||||
}
|
||||
} else {
|
||||
let error = crate::drop::Error {
|
||||
code: "VALIDATOR_NOT_INITIALIZED".to_string(),
|
||||
message: "The JSPG database has not been cached yet. Run jspg_setup()".to_string(),
|
||||
details: crate::drop::ErrorDetails {
|
||||
path: "".to_string(),
|
||||
},
|
||||
};
|
||||
let drop = crate::drop::Drop::with_errors(vec![error]);
|
||||
JsonB(serde_json::to_value(drop).unwrap())
|
||||
}
|
||||
}
|
||||
|
||||
#[pg_extern]
|
||||
pub fn jspg_get_punc_stems(punc_name: &str) -> JsonB {
|
||||
let engine_opt = {
|
||||
let lock = GLOBAL_JSPG.read().unwrap();
|
||||
lock.clone()
|
||||
};
|
||||
|
||||
match engine_opt {
|
||||
Some(engine) => {
|
||||
if let Some(punc) = engine.database.puncs.get(punc_name) {
|
||||
JsonB(serde_json::to_value(&punc.stems).unwrap_or(serde_json::Value::Array(vec![])))
|
||||
} else {
|
||||
JsonB(serde_json::Value::Array(vec![]))
|
||||
}
|
||||
}
|
||||
None => JsonB(serde_json::Value::Array(vec![])),
|
||||
}
|
||||
}
|
||||
|
||||
#[pg_extern(strict)]
|
||||
pub fn jspg_teardown() -> JsonB {
|
||||
let mut lock = GLOBAL_JSPG.write().unwrap();
|
||||
*lock = None;
|
||||
let drop = crate::drop::Drop::success();
|
||||
JsonB(serde_json::to_value(drop).unwrap())
|
||||
}
|
||||
|
||||
#[cfg(any(test, feature = "pg_test"))]
|
||||
#[pg_schema]
|
||||
mod tests {
|
||||
use pgrx::prelude::*;
|
||||
include!("tests/fixtures.rs");
|
||||
}
|
||||
|
||||
/// This module is required by `cargo pgrx test` invocations.
|
||||
/// It must be visible at the root of your extension crate.
|
||||
#[cfg(test)]
|
||||
pub mod pg_test {
|
||||
pub fn setup(_options: Vec<&str>) {
|
||||
// perform one-off initialization when the pg_test framework starts
|
||||
// perform any initialization common to all tests
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn postgresql_conf_options() -> Vec<&'static str> {
|
||||
// return any postgresql.conf settings that are required for your tests
|
||||
vec![]
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
#[cfg(any(test, feature = "pg_test"))]
|
||||
#[pg_schema]
|
||||
mod tests {
|
||||
include!("tests.rs");
|
||||
}
|
||||
24
src/merger/cache.rs
Normal file
24
src/merger/cache.rs
Normal file
@ -0,0 +1,24 @@
|
||||
use dashmap::DashMap;
|
||||
|
||||
pub struct StatementCache {
|
||||
/// Maps a Cache Key (String) -> SQL String (String)
|
||||
statements: DashMap<String, String>,
|
||||
}
|
||||
|
||||
impl StatementCache {
|
||||
pub fn new(_max_capacity: u64) -> Self {
|
||||
Self {
|
||||
statements: DashMap::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Retrieve an existing statement name by key, or None if it missed
|
||||
pub fn get(&self, key: &str) -> Option<String> {
|
||||
self.statements.get(key).map(|v| v.clone())
|
||||
}
|
||||
|
||||
/// Insert a completely verified/compiled statement string into the cache
|
||||
pub fn insert(&self, key: String, sql: String) {
|
||||
self.statements.insert(key, sql);
|
||||
}
|
||||
}
|
||||
737
src/merger/mod.rs
Normal file
737
src/merger/mod.rs
Normal file
@ -0,0 +1,737 @@
|
||||
//! The `merger` module handles executing Postgres SPI directives dynamically based on JSON payloads
|
||||
//! using the structurally isolated schema rules provided by the `Database` registry.
|
||||
|
||||
pub mod cache;
|
||||
|
||||
use crate::database::Database;
|
||||
|
||||
use serde_json::Value;
|
||||
use std::sync::Arc;
|
||||
|
||||
pub struct Merger {
|
||||
pub db: Arc<Database>,
|
||||
pub cache: cache::StatementCache,
|
||||
}
|
||||
|
||||
impl Merger {
|
||||
pub fn new(db: Arc<Database>) -> Self {
|
||||
Self {
|
||||
db,
|
||||
cache: cache::StatementCache::new(10_000),
|
||||
}
|
||||
}
|
||||
|
||||
/// Primary recursive entrypoint that separates Array lists from Object branches
|
||||
pub fn merge(&self, data: Value) -> Result<Value, String> {
|
||||
let result = match data {
|
||||
Value::Array(items) => self.merge_array(items)?,
|
||||
Value::Object(map) => self.merge_object(map)?,
|
||||
// Nulls, Strings, Bools, Numbers at root are invalid merge payloads
|
||||
_ => return Err("Invalid merge payload: root must be an Object or Array".to_string()),
|
||||
};
|
||||
|
||||
Ok(match result {
|
||||
Value::Object(mut map) => {
|
||||
let mut out = serde_json::Map::new();
|
||||
if let Some(id) = map.remove("id") {
|
||||
out.insert("id".to_string(), id);
|
||||
}
|
||||
Value::Object(out)
|
||||
}
|
||||
Value::Array(arr) => {
|
||||
let mut out_arr = Vec::new();
|
||||
for item in arr {
|
||||
if let Value::Object(mut map) = item {
|
||||
let mut out = serde_json::Map::new();
|
||||
if let Some(id) = map.remove("id") {
|
||||
out.insert("id".to_string(), id);
|
||||
}
|
||||
out_arr.push(Value::Object(out));
|
||||
} else {
|
||||
out_arr.push(Value::Null);
|
||||
}
|
||||
}
|
||||
Value::Array(out_arr)
|
||||
}
|
||||
other => other,
|
||||
})
|
||||
}
|
||||
|
||||
/// Handles mapping over an array of entities, executing merge logic on each and returning the resolved list.
|
||||
fn merge_array(&self, items: Vec<Value>) -> Result<Value, String> {
|
||||
let mut resolved_items = Vec::new();
|
||||
for item in items {
|
||||
// Recursively evaluate each object in the array
|
||||
let resolved = self.merge(item)?;
|
||||
resolved_items.push(resolved);
|
||||
}
|
||||
Ok(Value::Array(resolved_items))
|
||||
}
|
||||
|
||||
/// Core processing algorithm for a single Entity Object dictionary.
|
||||
fn merge_object(&self, mut obj: serde_json::Map<String, Value>) -> Result<Value, String> {
|
||||
// Step 1: Ensure it has a `type` definition to proceed
|
||||
let type_name = match obj.get("type").and_then(|v| v.as_str()) {
|
||||
Some(t) => t.to_string(),
|
||||
None => return Err("Missing required 'type' field on object".to_string()),
|
||||
};
|
||||
|
||||
// Step 2: Extract Type mapping from the Engine
|
||||
let type_def = match self.db.types.get(&type_name) {
|
||||
Some(t) => t,
|
||||
None => return Err(format!("Unknown entity type: {}", type_name)),
|
||||
};
|
||||
|
||||
// Step 3 & 4: (Pre/Post Staging based on `relationship` flag)
|
||||
if type_def.relationship {
|
||||
// Relationships: process children FIRST (Post-Staging)
|
||||
self.process_children(&mut obj, type_def)?;
|
||||
Ok(Value::Object(self.stage_entity(obj)?))
|
||||
} else {
|
||||
// Entities: process core FIRST (Pre-Staging)
|
||||
let mut staged_obj_map = self.stage_entity(obj)?;
|
||||
self.process_children(&mut staged_obj_map, type_def)?;
|
||||
Ok(Value::Object(staged_obj_map))
|
||||
}
|
||||
}
|
||||
|
||||
/// Iterates values of `obj`, if they are structural (Array/Object), executes `self.merge()` on them.
|
||||
/// Uses the `Database` registry to find FK relations and apply the IDs upstream/downstream appropriately.
|
||||
fn process_children(
|
||||
&self,
|
||||
obj: &mut serde_json::Map<String, Value>,
|
||||
type_def: &crate::database::r#type::Type,
|
||||
) -> Result<(), String> {
|
||||
let keys: Vec<String> = obj.keys().cloned().collect();
|
||||
|
||||
for key in keys {
|
||||
// Temporarily extract value to process without borrowing Map mutably
|
||||
let val = match obj.remove(&key) {
|
||||
Some(v) => v,
|
||||
None => continue,
|
||||
};
|
||||
|
||||
if val.is_object() || val.is_array() {
|
||||
// Pre-Process: Propagate parent data to children BEFORE recursing and applying relations
|
||||
let mut child_val = val;
|
||||
let mut relation_info = None;
|
||||
|
||||
// Try to peek at the child type for relational mapping
|
||||
let peek_obj = match &child_val {
|
||||
Value::Object(m) => Some(m),
|
||||
Value::Array(arr) if !arr.is_empty() => arr[0].as_object(),
|
||||
_ => None,
|
||||
};
|
||||
|
||||
if let Some(child_map) = peek_obj {
|
||||
if let Ok(Some(relation)) = self.get_entity_relation(obj, type_def, child_map, &key) {
|
||||
let child_type_name = child_map.get("type").and_then(|v| v.as_str()).unwrap_or("");
|
||||
if let Some(c_type) = self.db.types.get(child_type_name) {
|
||||
let parent_is_source = type_def.hierarchy.contains(&relation.source_type);
|
||||
let child_is_source = c_type.hierarchy.contains(&relation.source_type);
|
||||
relation_info = Some((relation, parent_is_source, child_is_source));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Apply pre-merge mutations mapping IDs
|
||||
if let Some((relation, _parent_is_source, child_is_source)) = relation_info.as_ref() {
|
||||
match &mut child_val {
|
||||
Value::Object(child_map) => {
|
||||
// Cascade Organization ID
|
||||
if !child_map.contains_key("organization_id") {
|
||||
if let Some(org_id) = obj.get("organization_id") {
|
||||
child_map.insert("organization_id".to_string(), org_id.clone());
|
||||
}
|
||||
}
|
||||
// If child owns FK, parent provides it
|
||||
if *child_is_source {
|
||||
Self::apply_entity_relation(
|
||||
child_map,
|
||||
&relation.source_columns,
|
||||
&relation.destination_columns,
|
||||
obj,
|
||||
);
|
||||
}
|
||||
}
|
||||
Value::Array(items) => {
|
||||
for item in items.iter_mut() {
|
||||
if let Value::Object(child_map) = item {
|
||||
if !child_map.contains_key("organization_id") {
|
||||
if let Some(org_id) = obj.get("organization_id") {
|
||||
child_map.insert("organization_id".to_string(), org_id.clone());
|
||||
}
|
||||
}
|
||||
if *child_is_source {
|
||||
Self::apply_entity_relation(
|
||||
child_map,
|
||||
&relation.source_columns,
|
||||
&relation.destination_columns,
|
||||
obj,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
// RECURSE: Merge the modified children
|
||||
let merged_val = self.merge(child_val)?;
|
||||
|
||||
// Post-Process: Apply relations upwards if parent owns the FK
|
||||
if let Some((relation, parent_is_source, _child_is_source)) = relation_info {
|
||||
if parent_is_source {
|
||||
match &merged_val {
|
||||
Value::Object(merged_child_map) => {
|
||||
Self::apply_entity_relation(
|
||||
obj,
|
||||
&relation.source_columns,
|
||||
&relation.destination_columns,
|
||||
merged_child_map,
|
||||
);
|
||||
}
|
||||
Value::Array(items) if !items.is_empty() => {
|
||||
if let Value::Object(merged_child_map) = &items[0] {
|
||||
Self::apply_entity_relation(
|
||||
obj,
|
||||
&relation.source_columns,
|
||||
&relation.destination_columns,
|
||||
merged_child_map,
|
||||
);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
obj.insert(key, merged_val);
|
||||
} else {
|
||||
obj.insert(key, val);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Evaluates `lk_` structures, fetches existing rows via SPI, computes `compare_entities` diff,
|
||||
/// executes UPDATE/INSERT SPI, and handles `agreego.change` auditing.
|
||||
fn stage_entity(
|
||||
&self,
|
||||
mut obj: serde_json::Map<String, Value>,
|
||||
) -> Result<serde_json::Map<String, Value>, String> {
|
||||
let type_name = obj
|
||||
.get("type")
|
||||
.and_then(|v| v.as_str())
|
||||
.unwrap()
|
||||
.to_string();
|
||||
let type_def = self.db.types.get(&type_name).unwrap();
|
||||
|
||||
// 1. Fetch Existing Entity
|
||||
let existing_entity = self.fetch_entity(&obj, type_def)?;
|
||||
|
||||
// 2. Identify System Keys we don't want to diff
|
||||
let system_keys = vec![
|
||||
"id".to_string(),
|
||||
"type".to_string(),
|
||||
"organization_id".to_string(),
|
||||
"created_by".to_string(),
|
||||
"modified_by".to_string(),
|
||||
"created_at".to_string(),
|
||||
"modified_at".to_string(),
|
||||
];
|
||||
|
||||
// 3. Compare entities to find exact changes
|
||||
let changes = self.compare_entities(
|
||||
existing_entity.as_ref(),
|
||||
&obj,
|
||||
&type_def.fields,
|
||||
&system_keys,
|
||||
);
|
||||
|
||||
// 4. If no changes and an entity existed, we skip
|
||||
let is_update = existing_entity.is_some();
|
||||
if is_update && changes.is_empty() {
|
||||
return Ok(obj);
|
||||
}
|
||||
|
||||
// 5. Apply correct system fields
|
||||
let user_id = self.db.auth_user_id()?;
|
||||
let timestamp = self.db.timestamp()?;
|
||||
|
||||
let entity_change_kind = if !is_update {
|
||||
if !obj.contains_key("id") {
|
||||
use uuid::Uuid;
|
||||
obj.insert("id".to_string(), Value::String(Uuid::new_v4().to_string()));
|
||||
}
|
||||
obj.insert("created_by".to_string(), Value::String(user_id.clone()));
|
||||
obj.insert("created_at".to_string(), Value::String(timestamp.clone()));
|
||||
obj.insert("modified_by".to_string(), Value::String(user_id.clone()));
|
||||
obj.insert("modified_at".to_string(), Value::String(timestamp.clone()));
|
||||
"create"
|
||||
} else {
|
||||
obj.insert("modified_by".to_string(), Value::String(user_id.clone()));
|
||||
obj.insert("modified_at".to_string(), Value::String(timestamp.clone()));
|
||||
"update"
|
||||
};
|
||||
|
||||
// 6. Execute SQL Merges
|
||||
self.merge_entity_fields(is_update, &type_name, type_def, &changes, &obj)?;
|
||||
|
||||
// 7. Fire agreego.change
|
||||
let mut complete = obj.clone();
|
||||
if is_update {
|
||||
// overlay on top of existing for complete state
|
||||
if let Some(mut existing) = existing_entity {
|
||||
for (k, v) in &obj {
|
||||
existing.insert(k.clone(), v.clone());
|
||||
}
|
||||
complete = existing;
|
||||
}
|
||||
}
|
||||
|
||||
let mut notification = serde_json::Map::new();
|
||||
notification.insert("complete".to_string(), Value::Object(complete.clone()));
|
||||
|
||||
let changes_val = if !is_update {
|
||||
let mut c = changes.clone();
|
||||
c.insert("type".to_string(), Value::String(type_name.clone()));
|
||||
Value::Object(c)
|
||||
} else {
|
||||
notification.insert("changes".to_string(), Value::Object(changes.clone()));
|
||||
Value::Object(changes.clone())
|
||||
};
|
||||
|
||||
let change_sql = format!(
|
||||
"INSERT INTO agreego.change (changes, entity_id, id, kind, modified_at, modified_by) VALUES ({}, {}, {}, {}, {}, {})",
|
||||
Self::quote_literal(&changes_val),
|
||||
Self::quote_literal(obj.get("id").unwrap()),
|
||||
Self::quote_literal(&Value::String(uuid::Uuid::new_v4().to_string())),
|
||||
Self::quote_literal(&Value::String(entity_change_kind.to_string())),
|
||||
Self::quote_literal(&Value::String(timestamp.clone())),
|
||||
Self::quote_literal(&Value::String(user_id.clone()))
|
||||
);
|
||||
|
||||
let notification_json = Value::Object(notification);
|
||||
let notify_sql = format!(
|
||||
"SELECT pg_notify('entity', {})",
|
||||
Self::quote_literal(&Value::String(notification_json.to_string()))
|
||||
);
|
||||
|
||||
self
|
||||
.db
|
||||
.execute(&change_sql, None)
|
||||
.map_err(|e| format!("Executor Error in change: {:?}", e))?;
|
||||
self
|
||||
.db
|
||||
.execute(¬ify_sql, None)
|
||||
.map_err(|e| format!("Executor Error in notify: {:?}", e))?;
|
||||
|
||||
Ok(obj)
|
||||
}
|
||||
|
||||
/// Exact replica of `agreego.compare_entities`. Takes a fetched `old` entity from the DB (if any),
|
||||
/// the `new_fields` from the JSON payload, the `fields` defined on the `Type` hierarchy, and a list of `system_keys`.
|
||||
/// Returns a clean JSON object containing ONLY the modified keys, or an empty map if No-Op.
|
||||
fn compare_entities(
|
||||
&self,
|
||||
fetched_entity: Option<&serde_json::Map<String, Value>>,
|
||||
new_fields: &serde_json::Map<String, Value>,
|
||||
type_fields: &[String],
|
||||
system_keys: &[String],
|
||||
) -> serde_json::Map<String, Value> {
|
||||
let mut changes = serde_json::Map::new();
|
||||
|
||||
for (key, new_val) in new_fields {
|
||||
// 1. Skip if key is not part of the Type's total field schema mapping
|
||||
if !type_fields.contains(key) {
|
||||
continue;
|
||||
}
|
||||
// 2. Skip strictly managed system audit keys
|
||||
if system_keys.contains(key) {
|
||||
continue;
|
||||
}
|
||||
|
||||
match fetched_entity {
|
||||
// 3a. If no old entity, every valid field is a new "change"
|
||||
None => {
|
||||
changes.insert(key.clone(), new_val.clone());
|
||||
}
|
||||
// 3b. If old entity exists, strictly compare the values
|
||||
Some(old_map) => {
|
||||
let old_val = old_map.get(key).unwrap_or(&Value::Null);
|
||||
if new_val != old_val {
|
||||
changes.insert(key.clone(), new_val.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
changes
|
||||
}
|
||||
|
||||
/// Exact replica of `agreego.reduce_entity_relations`. Resolves Ambiguous Graph paths
|
||||
/// down to a single distinct FK relationship path based on prefix rules.
|
||||
fn reduce_entity_relations(
|
||||
&self,
|
||||
mut matching_relations: Vec<crate::database::relation::Relation>,
|
||||
relative: &serde_json::Map<String, Value>,
|
||||
relation_name: &str,
|
||||
) -> Result<Option<crate::database::relation::Relation>, String> {
|
||||
// 0 or 1 relations is an immediate fast-path resolution
|
||||
if matching_relations.is_empty() {
|
||||
return Ok(None);
|
||||
}
|
||||
if matching_relations.len() == 1 {
|
||||
return Ok(Some(matching_relations.pop().unwrap()));
|
||||
}
|
||||
|
||||
// Step 1: Check for exact prefix match with the relation_name pointer
|
||||
let exact_match: Vec<_> = matching_relations
|
||||
.iter()
|
||||
.filter(|r| r.prefix.as_deref() == Some(relation_name))
|
||||
.cloned()
|
||||
.collect();
|
||||
if exact_match.len() == 1 {
|
||||
return Ok(Some(exact_match.into_iter().next().unwrap()));
|
||||
}
|
||||
|
||||
// Step 2: Inverse filter - Remove any relations where their configured prefix IS found
|
||||
// inside the actual payload data on `relative`
|
||||
matching_relations.retain(|r| {
|
||||
if let Some(prefix) = &r.prefix {
|
||||
// If the prefix exists as a key in the relative JSON payload, we KEEP iter
|
||||
// (Wait, actually the SQL is `WHERE NOT EXISTS (select mr.prefix where relative ? mr.prefix)`
|
||||
// Translating: Keep relation R if its prefix is NOT matched in the payload
|
||||
!relative.contains_key(prefix)
|
||||
} else {
|
||||
true // No prefix means we keep it by default
|
||||
}
|
||||
});
|
||||
|
||||
if matching_relations.len() == 1 {
|
||||
Ok(Some(matching_relations.pop().unwrap()))
|
||||
} else {
|
||||
let constraints: Vec<_> = matching_relations
|
||||
.iter()
|
||||
.map(|r| r.constraint.clone())
|
||||
.collect();
|
||||
Err(format!(
|
||||
"AMBIGUOUS_TYPE_RELATIONS: Could not reduce ambiguous type relations: {}",
|
||||
constraints.join(", ")
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
/// Exact replica of `agreego.get_entity_relation`. Given two entities (`entity` and `relative`) and the JSON key linking them,
|
||||
/// it searches the Database graphs for a concrete FK constraint.
|
||||
fn get_entity_relation(
|
||||
&self,
|
||||
_entity: &serde_json::Map<String, Value>,
|
||||
entity_type: &crate::database::r#type::Type,
|
||||
relative: &serde_json::Map<String, Value>,
|
||||
relation_name: &str,
|
||||
) -> Result<Option<crate::database::relation::Relation>, String> {
|
||||
let relative_type_name = relative.get("type").and_then(|v| v.as_str()).unwrap_or("");
|
||||
let relative_type = match self.db.types.get(relative_type_name) {
|
||||
Some(t) => t,
|
||||
None => return Ok(None),
|
||||
};
|
||||
|
||||
let mut relative_relations: Vec<crate::database::relation::Relation> = Vec::new();
|
||||
|
||||
// 1. Look for direct relationships first
|
||||
for r in self.db.relations.values() {
|
||||
if r.source_type != "entity" && r.destination_type != "entity" {
|
||||
let condition1 = relative_type.hierarchy.contains(&r.source_type)
|
||||
&& entity_type.hierarchy.contains(&r.destination_type);
|
||||
let condition2 = entity_type.hierarchy.contains(&r.source_type)
|
||||
&& relative_type.hierarchy.contains(&r.destination_type);
|
||||
|
||||
if condition1 || condition2 {
|
||||
relative_relations.push(r.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let mut relative_relation =
|
||||
self.reduce_entity_relations(relative_relations, relative, relation_name)?;
|
||||
|
||||
// 2. Look for polymorphic relationships if no direct relationship is found
|
||||
if relative_relation.is_none() {
|
||||
let mut poly_relations: Vec<crate::database::relation::Relation> = Vec::new();
|
||||
for r in self.db.relations.values() {
|
||||
if r.destination_type == "entity" {
|
||||
let condition1 = relative_type.hierarchy.contains(&r.source_type);
|
||||
let condition2 = entity_type.hierarchy.contains(&r.source_type);
|
||||
|
||||
if condition1 || condition2 {
|
||||
poly_relations.push(r.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
relative_relation = self.reduce_entity_relations(poly_relations, relative, relation_name)?;
|
||||
}
|
||||
|
||||
Ok(relative_relation)
|
||||
}
|
||||
|
||||
/// Exact replica of `agreego.apply_entity_relation`. Syncs FK column values from the destination to the source.
|
||||
fn apply_entity_relation(
|
||||
source_entity: &mut serde_json::Map<String, Value>,
|
||||
source_columns: &[String],
|
||||
destination_columns: &[String],
|
||||
destination_entity: &serde_json::Map<String, Value>,
|
||||
) {
|
||||
if source_columns.len() != destination_columns.len() {
|
||||
// In theory, validation should prevent this, but fail gracefully/ignore if lengths diverge.
|
||||
return;
|
||||
}
|
||||
for i in 0..source_columns.len() {
|
||||
let dest_val = destination_entity
|
||||
.get(&destination_columns[i])
|
||||
.unwrap_or(&Value::Null)
|
||||
.clone();
|
||||
source_entity.insert(source_columns[i].clone(), dest_val);
|
||||
}
|
||||
}
|
||||
|
||||
/// Exact replica of `agreego.fetch_entity`. Dynamically constructs a `SELECT to_jsonb(t1.*) || to_jsonb(t2.*)`
|
||||
/// based on the Type hierarchy and available `id` or `lookup_fields` presence.
|
||||
fn fetch_entity(
|
||||
&self,
|
||||
entity_fields: &serde_json::Map<String, Value>,
|
||||
entity_type: &crate::database::r#type::Type,
|
||||
) -> Result<Option<serde_json::Map<String, Value>>, String> {
|
||||
let id_val = entity_fields.get("id");
|
||||
let entity_type_name = entity_type.name.as_str();
|
||||
|
||||
// Check if all required lookup keys are PRESENT (value can be anything, including NULL)
|
||||
let lookup_complete = if entity_type.lookup_fields.is_empty() {
|
||||
false
|
||||
} else {
|
||||
entity_type
|
||||
.lookup_fields
|
||||
.iter()
|
||||
.all(|f| entity_fields.contains_key(f))
|
||||
};
|
||||
|
||||
if id_val.is_none() && !lookup_complete {
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
// Build or Retrieve Cached Select/Join clauses
|
||||
let fetch_sql_template = if let Some(cached) = self.cache.get(entity_type_name) {
|
||||
cached
|
||||
} else {
|
||||
let mut select_list = String::from("to_jsonb(t1.*)");
|
||||
let mut join_clauses = format!("FROM agreego.\"{}\" t1", entity_type.hierarchy[0]);
|
||||
|
||||
for (i, table_name) in entity_type.hierarchy.iter().enumerate().skip(1) {
|
||||
let t_alias = format!("t{}", i + 1);
|
||||
join_clauses.push_str(&format!(
|
||||
" LEFT JOIN agreego.\"{}\" {} ON {}.id = t1.id",
|
||||
table_name, t_alias, t_alias
|
||||
));
|
||||
select_list.push_str(&format!(" || to_jsonb({}.*)", t_alias));
|
||||
}
|
||||
|
||||
let template = format!("SELECT {} {}", select_list, join_clauses);
|
||||
self
|
||||
.cache
|
||||
.insert(entity_type_name.to_string(), template.clone());
|
||||
template
|
||||
};
|
||||
|
||||
// Build WHERE Clauses
|
||||
let mut id_condition = None;
|
||||
if let Some(id) = id_val {
|
||||
id_condition = Some(format!("t1.id = {}", Self::quote_literal(id)));
|
||||
}
|
||||
|
||||
let mut lookup_condition = None;
|
||||
if lookup_complete {
|
||||
let mut lookup_predicates = Vec::new();
|
||||
for column in &entity_type.lookup_fields {
|
||||
let val = entity_fields.get(column).unwrap_or(&Value::Null);
|
||||
if column == "type" {
|
||||
lookup_predicates.push(format!("t1.\"{}\" = {}", column, Self::quote_literal(val)));
|
||||
} else {
|
||||
if val.as_str() == Some("") || val.is_null() {
|
||||
lookup_predicates.push(format!("\"{}\" IS NULL", column));
|
||||
} else {
|
||||
lookup_predicates.push(format!("\"{}\" = {}", column, Self::quote_literal(val)));
|
||||
}
|
||||
}
|
||||
}
|
||||
lookup_condition = Some(lookup_predicates.join(" AND "));
|
||||
}
|
||||
|
||||
// Determine final WHERE clause based on available conditions
|
||||
let where_clause = match (id_condition, lookup_condition) {
|
||||
(Some(id_cond), Some(lookup_cond)) => format!("WHERE ({}) OR ({})", id_cond, lookup_cond),
|
||||
(Some(id_cond), None) => format!("WHERE {}", id_cond),
|
||||
(None, Some(lookup_cond)) => format!("WHERE {}", lookup_cond),
|
||||
(None, None) => return Ok(None),
|
||||
};
|
||||
|
||||
// Construct Final Query
|
||||
let fetch_sql = format!("{} {}", fetch_sql_template, where_clause);
|
||||
|
||||
// Execute and Return Result via Database Executor
|
||||
let fetched = match self.db.query(&fetch_sql, None) {
|
||||
Ok(Value::Array(table)) => {
|
||||
if table.len() > 1 {
|
||||
Err(format!(
|
||||
"TOO_MANY_LOOKUP_ROWS: Lookup for {} found too many existing rows",
|
||||
entity_type_name
|
||||
))
|
||||
} else if table.is_empty() {
|
||||
Ok(None)
|
||||
} else {
|
||||
let row = table.first().unwrap();
|
||||
match row {
|
||||
Value::Object(map) => Ok(Some(map.clone())),
|
||||
other => Err(format!(
|
||||
"Expected fetch_entity to return JSON object, got: {:?}",
|
||||
other
|
||||
)),
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(other) => Err(format!(
|
||||
"Expected array from query in fetch_entity, got: {:?}",
|
||||
other
|
||||
)),
|
||||
Err(e) => Err(format!("SPI error in fetch_entity: {:?}", e)),
|
||||
}?;
|
||||
|
||||
Ok(fetched)
|
||||
}
|
||||
|
||||
/// Exact replica of `agreego.merge_entity_fields`. Issues an INSERT or UPDATE per table
|
||||
/// in the Type's hierarchy, filtering out keys that don't belong to the specific table block.
|
||||
fn merge_entity_fields(
|
||||
&self,
|
||||
is_update: bool,
|
||||
entity_type_name: &str,
|
||||
entity_type: &crate::database::r#type::Type,
|
||||
changes: &serde_json::Map<String, Value>,
|
||||
full_entity: &serde_json::Map<String, Value>,
|
||||
) -> Result<(), String> {
|
||||
let id_str = match full_entity.get("id").and_then(|v| v.as_str()) {
|
||||
Some(id) => id,
|
||||
None => return Err("Missing 'id' for merge execution".to_string()),
|
||||
};
|
||||
|
||||
let grouped_fields = match &entity_type.grouped_fields {
|
||||
Some(Value::Object(map)) => map,
|
||||
_ => {
|
||||
return Err(format!(
|
||||
"Grouped fields missing for type {}",
|
||||
entity_type_name
|
||||
));
|
||||
}
|
||||
};
|
||||
|
||||
for table_name in &entity_type.hierarchy {
|
||||
// get the fields for this specific table (from grouped_fields)
|
||||
let table_fields = match grouped_fields.get(table_name).and_then(|v| v.as_array()) {
|
||||
Some(arr) => arr
|
||||
.iter()
|
||||
.filter_map(|v| v.as_str().map(|s| s.to_string()))
|
||||
.collect::<Vec<_>>(),
|
||||
None => continue,
|
||||
};
|
||||
|
||||
let mut my_changes = Vec::new();
|
||||
for field in &table_fields {
|
||||
if changes.contains_key(field) || (!is_update && full_entity.contains_key(field)) {
|
||||
// For inserts we want all provided fields. For updates we only want changes.
|
||||
my_changes.push(field.clone());
|
||||
}
|
||||
}
|
||||
|
||||
if is_update {
|
||||
if my_changes.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let mut set_clauses = Vec::new();
|
||||
for field in &my_changes {
|
||||
let val = changes.get(field).unwrap();
|
||||
set_clauses.push(format!("\"{}\" = {}", field, Self::quote_literal(val)));
|
||||
}
|
||||
let sql = format!(
|
||||
"UPDATE agreego.\"{}\" SET {} WHERE id = {}",
|
||||
table_name,
|
||||
set_clauses.join(", "),
|
||||
Self::quote_literal(&Value::String(id_str.to_string()))
|
||||
);
|
||||
self
|
||||
.db
|
||||
.execute(&sql, None)
|
||||
.map_err(|e| format!("SPI Error in UPDATE: {:?}", e))?;
|
||||
} else {
|
||||
// INSERT
|
||||
let mut columns = Vec::new();
|
||||
let mut values = Vec::new();
|
||||
|
||||
for field in &my_changes {
|
||||
columns.push(format!("\"{}\"", field));
|
||||
let val = full_entity.get(field).unwrap();
|
||||
values.push(Self::quote_literal(val));
|
||||
}
|
||||
|
||||
// Ensure 'id' and 'type' are present if required by this specific table schema chunk
|
||||
if !columns.contains(&"\"id\"".to_string()) && table_fields.contains(&"id".to_string()) {
|
||||
columns.push("\"id\"".to_string());
|
||||
values.push(Self::quote_literal(&Value::String(id_str.to_string())));
|
||||
}
|
||||
if !columns.contains(&"\"type\"".to_string()) && table_fields.contains(&"type".to_string())
|
||||
{
|
||||
columns.push("\"type\"".to_string());
|
||||
values.push(Self::quote_literal(&Value::String(
|
||||
entity_type_name.to_string(),
|
||||
)));
|
||||
}
|
||||
|
||||
if columns.is_empty() {
|
||||
continue;
|
||||
}
|
||||
|
||||
let sql = format!(
|
||||
"INSERT INTO agreego.\"{}\" ({}) VALUES ({})",
|
||||
table_name,
|
||||
columns.join(", "),
|
||||
values.join(", ")
|
||||
);
|
||||
self
|
||||
.db
|
||||
.execute(&sql, None)
|
||||
.map_err(|e| format!("SPI Error in INSERT: {:?}", e))?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Helper to emulate Postgres `quote_literal`
|
||||
fn quote_literal(val: &Value) -> String {
|
||||
match val {
|
||||
Value::Null => "NULL".to_string(),
|
||||
Value::Bool(b) => {
|
||||
if *b {
|
||||
"true".to_string()
|
||||
} else {
|
||||
"false".to_string()
|
||||
}
|
||||
}
|
||||
Value::Number(n) => n.to_string(),
|
||||
Value::String(s) => format!("'{}'", s.replace('\'', "''")),
|
||||
_ => format!(
|
||||
"'{}'",
|
||||
serde_json::to_string(val).unwrap().replace('\'', "''")
|
||||
),
|
||||
}
|
||||
}
|
||||
}
|
||||
369
src/queryer/compiler.rs
Normal file
369
src/queryer/compiler.rs
Normal file
@ -0,0 +1,369 @@
|
||||
use crate::database::Database;
|
||||
use std::sync::Arc;
|
||||
|
||||
pub struct SqlCompiler {
|
||||
pub db: Arc<Database>,
|
||||
}
|
||||
|
||||
impl SqlCompiler {
|
||||
pub fn new(db: Arc<Database>) -> Self {
|
||||
Self { db }
|
||||
}
|
||||
|
||||
/// Compiles a JSON schema into a nested PostgreSQL query returning JSONB
|
||||
pub fn compile(
|
||||
&self,
|
||||
schema_id: &str,
|
||||
stem_path: Option<&str>,
|
||||
filter_keys: &[String],
|
||||
) -> Result<String, String> {
|
||||
let schema = self
|
||||
.db
|
||||
.schemas
|
||||
.get(schema_id)
|
||||
.ok_or_else(|| format!("Schema not found: {}", schema_id))?;
|
||||
|
||||
let target_schema = if let Some(path) = stem_path.filter(|p| !p.is_empty() && *p != "/") {
|
||||
self.resolve_stem(schema, path)?
|
||||
} else {
|
||||
schema
|
||||
};
|
||||
|
||||
// 1. We expect the top level to typically be an Object or Array
|
||||
let (sql, _) = self.walk_schema(target_schema, "t1", None, filter_keys)?;
|
||||
Ok(sql)
|
||||
}
|
||||
|
||||
fn resolve_stem<'a>(
|
||||
&'a self,
|
||||
mut schema: &'a crate::database::schema::Schema,
|
||||
path: &str,
|
||||
) -> Result<&'a crate::database::schema::Schema, String> {
|
||||
let parts: Vec<&str> = path.trim_start_matches('/').split('/').collect();
|
||||
for part in parts {
|
||||
let mut current = schema;
|
||||
let mut depth = 0;
|
||||
while let Some(r) = ¤t.obj.r#ref {
|
||||
if let Some(s) = self.db.schemas.get(r) {
|
||||
current = s;
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
depth += 1;
|
||||
if depth > 20 {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if current.obj.properties.is_none() && current.obj.items.is_some() {
|
||||
if let Some(items) = ¤t.obj.items {
|
||||
current = items;
|
||||
let mut depth2 = 0;
|
||||
while let Some(r) = ¤t.obj.r#ref {
|
||||
if let Some(s) = self.db.schemas.get(r) {
|
||||
current = s;
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
depth2 += 1;
|
||||
if depth2 > 20 {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(props) = ¤t.obj.properties {
|
||||
if let Some(next_schema) = props.get(part) {
|
||||
schema = next_schema;
|
||||
} else {
|
||||
return Err(format!("Stem part '{}' not found in schema", part));
|
||||
}
|
||||
} else {
|
||||
return Err(format!(
|
||||
"Cannot resolve stem part '{}': not an object",
|
||||
part
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
let mut current = schema;
|
||||
let mut depth = 0;
|
||||
while let Some(r) = ¤t.obj.r#ref {
|
||||
if let Some(s) = self.db.schemas.get(r) {
|
||||
current = s;
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
depth += 1;
|
||||
if depth > 20 {
|
||||
break;
|
||||
}
|
||||
}
|
||||
Ok(current)
|
||||
}
|
||||
|
||||
/// Recursively walks the schema AST emitting native PostgreSQL jsonb mapping
|
||||
/// Returns a tuple of (SQL_String, Field_Type)
|
||||
fn walk_schema(
|
||||
&self,
|
||||
schema: &crate::database::schema::Schema,
|
||||
parent_alias: &str,
|
||||
prop_name_context: Option<&str>,
|
||||
filter_keys: &[String],
|
||||
) -> Result<(String, String), String> {
|
||||
// Determine the base schema type (could be an array, object, or literal)
|
||||
match &schema.obj.type_ {
|
||||
Some(crate::database::schema::SchemaTypeOrArray::Single(t)) if t == "array" => {
|
||||
// Handle Arrays:
|
||||
if let Some(items) = &schema.obj.items {
|
||||
if let Some(ref_id) = &items.obj.r#ref {
|
||||
if let Some(type_def) = self.db.types.get(ref_id) {
|
||||
return self.compile_entity_node(
|
||||
items,
|
||||
type_def,
|
||||
parent_alias,
|
||||
prop_name_context,
|
||||
true,
|
||||
filter_keys,
|
||||
);
|
||||
}
|
||||
}
|
||||
let (item_sql, _) =
|
||||
self.walk_schema(items, parent_alias, prop_name_context, filter_keys)?;
|
||||
return Ok((
|
||||
format!("(SELECT jsonb_agg({}) FROM TODO)", item_sql),
|
||||
"array".to_string(),
|
||||
));
|
||||
}
|
||||
|
||||
Ok((
|
||||
"SELECT jsonb_agg(TODO) FROM TODO".to_string(),
|
||||
"array".to_string(),
|
||||
))
|
||||
}
|
||||
_ => {
|
||||
// Handle Objects & Direct Refs
|
||||
if let Some(ref_id) = &schema.obj.r#ref {
|
||||
// If it's a $ref, check if it points to an Entity Type
|
||||
if let Some(type_def) = self.db.types.get(ref_id) {
|
||||
return self.compile_entity_node(
|
||||
schema,
|
||||
type_def,
|
||||
parent_alias,
|
||||
prop_name_context,
|
||||
false,
|
||||
filter_keys,
|
||||
);
|
||||
}
|
||||
// If it's just an ad-hoc struct ref, we should resolve it
|
||||
if let Some(target_schema) = self.db.schemas.get(ref_id) {
|
||||
return self.walk_schema(target_schema, parent_alias, prop_name_context, filter_keys);
|
||||
}
|
||||
return Err(format!("Unresolved $ref: {}", ref_id));
|
||||
}
|
||||
|
||||
// Just an inline object definition?
|
||||
if let Some(props) = &schema.obj.properties {
|
||||
return self.compile_inline_object(props, parent_alias, filter_keys);
|
||||
}
|
||||
|
||||
// Literal fallback
|
||||
Ok((
|
||||
format!(
|
||||
"{}.{}",
|
||||
parent_alias,
|
||||
prop_name_context.unwrap_or("unknown_prop")
|
||||
),
|
||||
"string".to_string(),
|
||||
))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn compile_entity_node(
|
||||
&self,
|
||||
schema: &crate::database::schema::Schema,
|
||||
type_def: &crate::database::r#type::Type,
|
||||
parent_alias: &str,
|
||||
prop_name: Option<&str>,
|
||||
is_array: bool,
|
||||
filter_keys: &[String],
|
||||
) -> Result<(String, String), String> {
|
||||
// We are compiling a query block for an Entity.
|
||||
let mut select_args = Vec::new();
|
||||
|
||||
// Mapping table hierarchy to aliases, e.g., ["person", "user", "organization", "entity"]
|
||||
let local_ctx = format!("{}_{}", parent_alias, prop_name.unwrap_or("obj"));
|
||||
// e.g., parent_t1_contact -> we'll use t1 for the first of this block, t2 for the second, etc.
|
||||
// Actually, local_ctx can just be exactly that prop's unique path.
|
||||
let mut table_aliases = std::collections::HashMap::new();
|
||||
let mut from_clauses = Vec::new();
|
||||
|
||||
for (i, table_name) in type_def.hierarchy.iter().enumerate() {
|
||||
let alias = format!("{}_t{}", local_ctx, i + 1);
|
||||
table_aliases.insert(table_name.clone(), alias.clone());
|
||||
|
||||
if i == 0 {
|
||||
from_clauses.push(format!("agreego.{} {}", table_name, alias));
|
||||
} else {
|
||||
// Join to previous
|
||||
let prev_alias = format!("{}_t{}", local_ctx, i);
|
||||
from_clauses.push(format!(
|
||||
"JOIN agreego.{} {} ON {}.id = {}.id",
|
||||
table_name, alias, alias, prev_alias
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
// Now, let's map properties from the schema to the correct table alias using grouped_fields
|
||||
// grouped_fields is { "person": ["first_name", ...], "user": ["password"], ... }
|
||||
let grouped_fields = type_def.grouped_fields.as_ref().and_then(|v| v.as_object());
|
||||
|
||||
if let Some(props) = &schema.obj.properties {
|
||||
for (prop_key, prop_schema) in props {
|
||||
// Find which table owns this property
|
||||
// Find which table owns this property
|
||||
let mut owner_alias = table_aliases
|
||||
.get("entity")
|
||||
.cloned()
|
||||
.unwrap_or_else(|| format!("{}_t_err", parent_alias));
|
||||
|
||||
if let Some(gf) = grouped_fields {
|
||||
for (t_name, fields_val) in gf {
|
||||
if let Some(fields_arr) = fields_val.as_array() {
|
||||
if fields_arr.iter().any(|v| v.as_str() == Some(prop_key)) {
|
||||
owner_alias = table_aliases
|
||||
.get(t_name)
|
||||
.cloned()
|
||||
.unwrap_or_else(|| parent_alias.to_string());
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Now we know `owner_alias`, e.g., `parent_t1` or `parent_t3`.
|
||||
// Walk the property to get its SQL value
|
||||
let (val_sql, _) =
|
||||
self.walk_schema(prop_schema, &owner_alias, Some(prop_key), filter_keys)?;
|
||||
select_args.push(format!("'{}', {}", prop_key, val_sql));
|
||||
}
|
||||
}
|
||||
|
||||
let jsonb_obj_sql = if select_args.is_empty() {
|
||||
"jsonb_build_object()".to_string()
|
||||
} else {
|
||||
format!("jsonb_build_object({})", select_args.join(", "))
|
||||
};
|
||||
|
||||
let base_alias = table_aliases
|
||||
.get(&type_def.name)
|
||||
.cloned()
|
||||
.unwrap_or_else(|| "err".to_string());
|
||||
|
||||
let mut where_clauses = Vec::new();
|
||||
where_clauses.push(format!("NOT {}.archived", base_alias));
|
||||
// Filter Mapping - Only append filters if this is the ROOT table query (i.e. parent_alias is "t1")
|
||||
// Because cue.filters operates strictly on top-level root properties right now.
|
||||
if parent_alias == "t1" && prop_name.is_none() {
|
||||
for (i, filter_key) in filter_keys.iter().enumerate() {
|
||||
// Find which table owns this filter key
|
||||
let mut filter_alias = base_alias.clone(); // default to root table (e.g. t3 entity)
|
||||
|
||||
if let Some(gf) = type_def.grouped_fields.as_ref().and_then(|v| v.as_object()) {
|
||||
for (t_name, fields_val) in gf {
|
||||
if let Some(fields_arr) = fields_val.as_array() {
|
||||
if fields_arr.iter().any(|v| v.as_str() == Some(filter_key)) {
|
||||
filter_alias = table_aliases
|
||||
.get(t_name)
|
||||
.cloned()
|
||||
.unwrap_or_else(|| base_alias.clone());
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let mut is_ilike = false;
|
||||
let mut cast = "";
|
||||
|
||||
// Check schema for filter_key to determine datatype operation
|
||||
if let Some(props) = &schema.obj.properties {
|
||||
if let Some(ps) = props.get(filter_key) {
|
||||
let is_enum = ps.obj.enum_.is_some();
|
||||
if let Some(crate::database::schema::SchemaTypeOrArray::Single(t)) = &ps.obj.type_ {
|
||||
if t == "string" {
|
||||
if ps.obj.format.as_deref() == Some("uuid") {
|
||||
cast = "::uuid";
|
||||
} else if ps.obj.format.as_deref() == Some("date-time") {
|
||||
cast = "::timestamptz";
|
||||
} else if !is_enum {
|
||||
is_ilike = true;
|
||||
}
|
||||
} else if t == "boolean" {
|
||||
cast = "::boolean";
|
||||
} else if t == "integer" || t == "number" {
|
||||
cast = "::numeric";
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Add to WHERE clause using 1-indexed args pointer: $1, $2
|
||||
if is_ilike {
|
||||
let param = format!("${}#>>'{{}}'", i + 1);
|
||||
where_clauses.push(format!("{}.{} ILIKE {}", filter_alias, filter_key, param));
|
||||
} else {
|
||||
let param = format!("(${}#>>'{{}}'){}", i + 1, cast);
|
||||
where_clauses.push(format!("{}.{} = {}", filter_alias, filter_key, param));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Resolve FK relationship constraint if this is a nested subquery
|
||||
if let Some(_prop) = prop_name {
|
||||
// MOCK relation resolution (will integrate with `get_entity_relation` properly)
|
||||
// By default assume FK is parent_id on child
|
||||
where_clauses.push(format!("{}.parent_id = {}.id", base_alias, parent_alias));
|
||||
}
|
||||
|
||||
// Wrap the object in the final array or object SELECT
|
||||
let selection = if is_array {
|
||||
format!("COALESCE(jsonb_agg({}), '[]'::jsonb)", jsonb_obj_sql)
|
||||
} else {
|
||||
jsonb_obj_sql
|
||||
};
|
||||
|
||||
let full_sql = format!(
|
||||
"(SELECT {} FROM {} WHERE {})",
|
||||
selection,
|
||||
from_clauses.join(" "),
|
||||
where_clauses.join(" AND ")
|
||||
);
|
||||
|
||||
Ok((
|
||||
full_sql,
|
||||
if is_array {
|
||||
"array".to_string()
|
||||
} else {
|
||||
"object".to_string()
|
||||
},
|
||||
))
|
||||
}
|
||||
|
||||
fn compile_inline_object(
|
||||
&self,
|
||||
props: &std::collections::BTreeMap<String, std::sync::Arc<crate::database::schema::Schema>>,
|
||||
parent_alias: &str,
|
||||
filter_keys: &[String],
|
||||
) -> Result<(String, String), String> {
|
||||
let mut build_args = Vec::new();
|
||||
for (k, v) in props {
|
||||
let (child_sql, _) = self.walk_schema(v, parent_alias, Some(k), filter_keys)?;
|
||||
build_args.push(format!("'{}', {}", k, child_sql));
|
||||
}
|
||||
let combined = format!("jsonb_build_object({})", build_args.join(", "));
|
||||
Ok((combined, "object".to_string()))
|
||||
}
|
||||
}
|
||||
83
src/queryer/mod.rs
Normal file
83
src/queryer/mod.rs
Normal file
@ -0,0 +1,83 @@
|
||||
use crate::database::Database;
|
||||
use std::sync::Arc;
|
||||
|
||||
pub mod compiler;
|
||||
|
||||
use dashmap::DashMap;
|
||||
|
||||
pub struct Queryer {
|
||||
pub db: Arc<Database>,
|
||||
cache: DashMap<String, String>,
|
||||
}
|
||||
|
||||
impl Queryer {
|
||||
pub fn new(db: Arc<Database>) -> Self {
|
||||
Self {
|
||||
db,
|
||||
cache: DashMap::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Entrypoint to execute a dynamically compiled query based on a schema
|
||||
pub fn query(
|
||||
&self,
|
||||
schema_id: &str,
|
||||
stem_opt: Option<&str>,
|
||||
filters: Option<&serde_json::Value>,
|
||||
) -> Result<serde_json::Value, String> {
|
||||
let filters_map: Option<&serde_json::Map<String, serde_json::Value>> =
|
||||
filters.and_then(|f| f.as_object());
|
||||
|
||||
// Generate Permutation Cache Key: schema_id + sorted filter keys
|
||||
let mut filter_keys: Vec<String> = Vec::new();
|
||||
if let Some(fm) = filters_map {
|
||||
for key in fm.keys() {
|
||||
filter_keys.push(key.clone());
|
||||
}
|
||||
}
|
||||
filter_keys.sort();
|
||||
|
||||
let stem_key = stem_opt.unwrap_or("/");
|
||||
let cache_key = format!("{}(Stem:{}):{}", schema_id, stem_key, filter_keys.join(","));
|
||||
|
||||
let sql = if let Some(cached_sql) = self.cache.get(&cache_key) {
|
||||
cached_sql.value().clone()
|
||||
} else {
|
||||
// Compile the massive base SQL string
|
||||
let compiler = compiler::SqlCompiler::new(self.db.clone());
|
||||
let compiled_sql = compiler.compile(schema_id, stem_opt, &filter_keys)?;
|
||||
self.cache.insert(cache_key.clone(), compiled_sql.clone());
|
||||
compiled_sql
|
||||
};
|
||||
|
||||
// 2. Prepare the execution arguments from the filters
|
||||
let mut args: Vec<serde_json::Value> = Vec::new();
|
||||
|
||||
if let Some(fm) = filters_map {
|
||||
for (_i, key) in filter_keys.iter().enumerate() {
|
||||
if let Some(val) = fm.get(key) {
|
||||
args.push(val.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 3. Execute via Database Executor
|
||||
let fetched = match self.db.query(&sql, Some(&args)) {
|
||||
Ok(serde_json::Value::Array(table)) => {
|
||||
if table.is_empty() {
|
||||
Ok(serde_json::Value::Null)
|
||||
} else {
|
||||
// We expect the query to return a single JSONB column, already unpacked from row[0]
|
||||
Ok(table.first().unwrap().clone())
|
||||
}
|
||||
}
|
||||
Ok(other) => Err(format!(
|
||||
"Expected array from generic query, got: {:?}",
|
||||
other
|
||||
)),
|
||||
Err(e) => Err(format!("SPI error in queryer: {}", e)),
|
||||
}?;
|
||||
|
||||
Ok(fetched)
|
||||
}
|
||||
}
|
||||
415
src/tests.rs
415
src/tests.rs
@ -1,415 +0,0 @@
|
||||
use crate::*;
|
||||
use serde_json::{json, Value};
|
||||
use pgrx::{JsonB, pg_test};
|
||||
|
||||
// Helper macro for asserting success (no changes needed, but ensure it's present)
|
||||
macro_rules! assert_success_with_json {
|
||||
($result_jsonb:expr, $fmt:literal $(, $($args:tt)*)?) => {
|
||||
let condition_result: Option<bool> = $result_jsonb.0.get("success").and_then(Value::as_bool);
|
||||
if condition_result != Some(true) {
|
||||
let base_msg = format!($fmt $(, $($args)*)?);
|
||||
let pretty_json = serde_json::to_string_pretty(&$result_jsonb.0)
|
||||
.unwrap_or_else(|_| format!("(Failed to pretty-print JSON: {:?})", $result_jsonb.0));
|
||||
let panic_msg = format!("Assertion Failed (expected success): {}\nResult JSON:\n{}", base_msg, pretty_json);
|
||||
panic!("{}", panic_msg);
|
||||
}
|
||||
};
|
||||
// Simpler version without message
|
||||
($result_jsonb:expr) => {
|
||||
let condition_result: Option<bool> = $result_jsonb.0.get("success").and_then(Value::as_bool);
|
||||
if condition_result != Some(true) {
|
||||
let pretty_json = serde_json::to_string_pretty(&$result_jsonb.0)
|
||||
.unwrap_or_else(|_| format!("(Failed to pretty-print JSON: {:?})", $result_jsonb.0));
|
||||
let panic_msg = format!("Assertion Failed (expected success)\nResult JSON:\n{}", pretty_json);
|
||||
panic!("{}", panic_msg);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
// Updated helper macro for asserting failed JSON results with the new flat error structure
|
||||
macro_rules! assert_failure_with_json {
|
||||
// --- Arms with error count and message substring check ---
|
||||
// With custom message:
|
||||
($result:expr, $expected_error_count:expr, $expected_first_message_contains:expr, $fmt:literal $(, $($args:tt)*)?) => {
|
||||
let json_result = &$result.0;
|
||||
let success = json_result.get("success").and_then(Value::as_bool);
|
||||
let error_val_opt = json_result.get("error"); // Changed key
|
||||
let base_msg = format!($fmt $(, $($args)*)?);
|
||||
|
||||
if success != Some(false) {
|
||||
let pretty_json = serde_json::to_string_pretty(&json_result).unwrap_or_else(|_| format!("(Failed to pretty-print JSON: {:?})", json_result));
|
||||
panic!("Assertion Failed (expected failure, success was not false): {}\nResult JSON:\n{}", base_msg, pretty_json);
|
||||
}
|
||||
match error_val_opt {
|
||||
Some(error_val) => {
|
||||
if error_val.is_array() {
|
||||
let errors_array = error_val.as_array().unwrap();
|
||||
if errors_array.len() != $expected_error_count {
|
||||
let pretty_json = serde_json::to_string_pretty(&json_result).unwrap_or_else(|_| format!("(Failed to pretty-print JSON: {:?})", json_result));
|
||||
panic!("Assertion Failed (wrong error count): Expected {} errors, got {}. {}\nResult JSON:\n{}", $expected_error_count, errors_array.len(), base_msg, pretty_json);
|
||||
}
|
||||
if $expected_error_count > 0 {
|
||||
let first_error_message = errors_array[0].get("message").and_then(Value::as_str);
|
||||
match first_error_message {
|
||||
Some(msg) => {
|
||||
if !msg.contains($expected_first_message_contains) {
|
||||
let pretty_json = serde_json::to_string_pretty(&json_result).unwrap_or_else(|_| format!("(Failed to pretty-print JSON: {:?})", json_result));
|
||||
panic!("Assertion Failed (first error message mismatch): Expected contains '{}', got: '{}'. {}\nResult JSON:\n{}", $expected_first_message_contains, msg, base_msg, pretty_json);
|
||||
}
|
||||
}
|
||||
None => {
|
||||
let pretty_json = serde_json::to_string_pretty(&json_result).unwrap_or_else(|_| format!("(Failed to pretty-print JSON: {:?})", json_result));
|
||||
panic!("Assertion Failed (first error in array has no 'message' string): {}\nResult JSON:\n{}", base_msg, pretty_json);
|
||||
}
|
||||
}
|
||||
}
|
||||
} else if error_val.is_object() {
|
||||
// Handle single error object case (like 'schema not found')
|
||||
if $expected_error_count != 1 {
|
||||
let pretty_json = serde_json::to_string_pretty(&json_result).unwrap_or_else(|_| format!("(Failed to pretty-print JSON: {:?})", json_result));
|
||||
panic!("Assertion Failed (wrong error count): Expected {} errors, but got a single error object. {}\nResult JSON:\n{}", $expected_error_count, base_msg, pretty_json);
|
||||
}
|
||||
let message = error_val.get("message").and_then(Value::as_str);
|
||||
match message {
|
||||
Some(msg) => {
|
||||
if !msg.contains($expected_first_message_contains) {
|
||||
let pretty_json = serde_json::to_string_pretty(&json_result).unwrap_or_else(|_| format!("(Failed to pretty-print JSON: {:?})", json_result));
|
||||
panic!("Assertion Failed (error message mismatch): Expected object message contains '{}', got: '{}'. {}\nResult JSON:\n{}", $expected_first_message_contains, msg, base_msg, pretty_json);
|
||||
}
|
||||
}
|
||||
None => {
|
||||
let pretty_json = serde_json::to_string_pretty(&json_result).unwrap_or_else(|_| format!("(Failed to pretty-print JSON: {:?})", json_result));
|
||||
panic!("Assertion Failed (error object has no 'message' string): {}\nResult JSON:\n{}", base_msg, pretty_json);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
let pretty_json = serde_json::to_string_pretty(&json_result).unwrap_or_else(|_| format!("(Failed to pretty-print JSON: {:?})", json_result));
|
||||
panic!("Assertion Failed ('error' value is not an array or object): {}\nResult JSON:\n{}", base_msg, pretty_json);
|
||||
}
|
||||
}
|
||||
None => {
|
||||
let pretty_json = serde_json::to_string_pretty(&json_result).unwrap_or_else(|_| format!("(Failed to pretty-print JSON: {:?})", json_result));
|
||||
panic!("Assertion Failed (expected 'error' key, but none found): {}\nResult JSON:\n{}", base_msg, pretty_json);
|
||||
}
|
||||
}
|
||||
};
|
||||
// Without custom message (calls the one above with ""):
|
||||
($result:expr, $expected_error_count:expr, $expected_first_message_contains:expr) => {
|
||||
assert_failure_with_json!($result, $expected_error_count, $expected_first_message_contains, "");
|
||||
};
|
||||
|
||||
// --- Arms with error count check only ---
|
||||
// With custom message:
|
||||
($result:expr, $expected_error_count:expr, $fmt:literal $(, $($args:tt)*)?) => {
|
||||
let json_result = &$result.0;
|
||||
let success = json_result.get("success").and_then(Value::as_bool);
|
||||
let error_val_opt = json_result.get("error"); // Changed key
|
||||
let base_msg = format!($fmt $(, $($args)*)?);
|
||||
|
||||
if success != Some(false) {
|
||||
let pretty_json = serde_json::to_string_pretty(&json_result).unwrap_or_else(|_| format!("(Failed to pretty-print JSON: {:?})", json_result));
|
||||
panic!("Assertion Failed (expected failure, success was not false): {}\nResult JSON:\n{}", base_msg, pretty_json);
|
||||
}
|
||||
match error_val_opt {
|
||||
Some(error_val) => {
|
||||
if error_val.is_array() {
|
||||
let errors_array = error_val.as_array().unwrap();
|
||||
if errors_array.len() != $expected_error_count {
|
||||
let pretty_json = serde_json::to_string_pretty(&json_result).unwrap_or_else(|_| format!("(Failed to pretty-print JSON: {:?})", json_result));
|
||||
panic!("Assertion Failed (wrong error count): Expected {} errors, got {}. {}\nResult JSON:\n{}", $expected_error_count, errors_array.len(), base_msg, pretty_json);
|
||||
}
|
||||
} else if error_val.is_object() {
|
||||
if $expected_error_count != 1 {
|
||||
let pretty_json = serde_json::to_string_pretty(&json_result).unwrap_or_else(|_| format!("(Failed to pretty-print JSON: {:?})", json_result));
|
||||
panic!("Assertion Failed (wrong error count): Expected {} errors, but got a single error object. {}\nResult JSON:\n{}", $expected_error_count, base_msg, pretty_json);
|
||||
}
|
||||
// Count check passes if expected is 1 and got object
|
||||
} else {
|
||||
let pretty_json = serde_json::to_string_pretty(&json_result).unwrap_or_else(|_| format!("(Failed to pretty-print JSON: {:?})", json_result));
|
||||
panic!("Assertion Failed ('error' value is not an array or object): {}\nResult JSON:\n{}", base_msg, pretty_json);
|
||||
}
|
||||
}
|
||||
None => {
|
||||
let pretty_json = serde_json::to_string_pretty(&json_result).unwrap_or_else(|_| format!("(Failed to pretty-print JSON: {:?})", json_result));
|
||||
panic!("Assertion Failed (expected 'error' key, but none found): {}\nResult JSON:\n{}", base_msg, pretty_json);
|
||||
}
|
||||
}
|
||||
};
|
||||
// Without custom message (calls the one above with ""):
|
||||
($result:expr, $expected_error_count:expr) => {
|
||||
assert_failure_with_json!($result, $expected_error_count, "");
|
||||
};
|
||||
|
||||
// --- Arms checking failure only (expects at least one error) ---
|
||||
// With custom message:
|
||||
($result:expr, $fmt:literal $(, $($args:tt)*)?) => {
|
||||
let json_result = &$result.0;
|
||||
let success = json_result.get("success").and_then(Value::as_bool);
|
||||
let error_val_opt = json_result.get("error"); // Changed key
|
||||
let base_msg = format!($fmt $(, $($args)*)?);
|
||||
|
||||
if success != Some(false) {
|
||||
let pretty_json = serde_json::to_string_pretty(&json_result).unwrap_or_else(|_| format!("(Failed to pretty-print JSON: {:?})", json_result));
|
||||
panic!("Assertion Failed (expected failure, success was not false): {}\nResult JSON:\n{}", base_msg, pretty_json);
|
||||
}
|
||||
match error_val_opt {
|
||||
Some(error_val) => {
|
||||
if error_val.is_object() {
|
||||
// OK: single error object is a failure
|
||||
} else if error_val.is_array() {
|
||||
if error_val.as_array().unwrap().is_empty() {
|
||||
let pretty_json = serde_json::to_string_pretty(&json_result).unwrap_or_else(|_| format!("(Failed to pretty-print JSON: {:?})", json_result));
|
||||
panic!("Assertion Failed (expected errors, but 'error' array is empty): {}\nResult JSON:\n{}", base_msg, pretty_json);
|
||||
}
|
||||
// OK: non-empty error array is a failure
|
||||
} else {
|
||||
let pretty_json = serde_json::to_string_pretty(&json_result).unwrap_or_else(|_| format!("(Failed to pretty-print JSON: {:?})", json_result));
|
||||
panic!("Assertion Failed ('error' value is not an array or object): {}\nResult JSON:\n{}", base_msg, pretty_json);
|
||||
}
|
||||
}
|
||||
None => {
|
||||
let pretty_json = serde_json::to_string_pretty(&json_result).unwrap_or_else(|_| format!("(Failed to pretty-print JSON: {:?})", json_result));
|
||||
panic!("Assertion Failed (expected 'error' key, but none found): {}\nResult JSON:\n{}", base_msg, pretty_json);
|
||||
}
|
||||
}
|
||||
};
|
||||
// Without custom message (calls the one above with ""):
|
||||
($result:expr) => {
|
||||
assert_failure_with_json!($result, "");
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
fn jsonb(val: Value) -> JsonB {
|
||||
JsonB(val)
|
||||
}
|
||||
|
||||
#[pg_test]
|
||||
fn test_cache_and_validate_json_schema() {
|
||||
clear_json_schemas(); // Call clear directly
|
||||
let schema_id = "my_schema";
|
||||
let schema = json!({
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"name": { "type": "string" },
|
||||
"age": { "type": "integer", "minimum": 0 }
|
||||
},
|
||||
"required": ["name", "age"]
|
||||
});
|
||||
let valid_instance = json!({ "name": "Alice", "age": 30 });
|
||||
let invalid_instance_type = json!({ "name": "Bob", "age": -5 });
|
||||
let invalid_instance_missing = json!({ "name": "Charlie" });
|
||||
|
||||
let cache_result = cache_json_schema(schema_id, jsonb(schema.clone()));
|
||||
assert_success_with_json!(cache_result, "Cache operation should succeed.");
|
||||
|
||||
let valid_result = validate_json_schema(schema_id, jsonb(valid_instance));
|
||||
assert_success_with_json!(valid_result, "Validation of valid instance should succeed.");
|
||||
|
||||
// Invalid type
|
||||
let invalid_result_type = validate_json_schema(schema_id, jsonb(invalid_instance_type));
|
||||
assert_failure_with_json!(invalid_result_type, 1, "must be >=0", "Validation with invalid type should fail.");
|
||||
let errors_type = invalid_result_type.0["error"].as_array().unwrap(); // Check 'error', expect array
|
||||
assert_eq!(errors_type[0]["instance_path"], "/age");
|
||||
assert_eq!(errors_type[0]["schema_path"], "urn:my_schema#/properties/age");
|
||||
|
||||
// Missing field
|
||||
let invalid_result_missing = validate_json_schema(schema_id, jsonb(invalid_instance_missing));
|
||||
assert_failure_with_json!(invalid_result_missing, 1, "missing properties 'age'", "Validation with missing field should fail.");
|
||||
let errors_missing = invalid_result_missing.0["error"].as_array().unwrap(); // Check 'error', expect array
|
||||
assert_eq!(errors_missing[0]["instance_path"], "");
|
||||
assert_eq!(errors_missing[0]["schema_path"], "urn:my_schema#");
|
||||
|
||||
// Schema not found
|
||||
let non_existent_id = "non_existent_schema";
|
||||
let invalid_schema_result = validate_json_schema(non_existent_id, jsonb(json!({})));
|
||||
assert_failure_with_json!(invalid_schema_result, 1, "Schema with id 'non_existent_schema' not found", "Validation with non-existent schema should fail.");
|
||||
// Check 'error' is an object for 'schema not found'
|
||||
let error_notfound_obj = invalid_schema_result.0["error"].as_object().expect("'error' should be an object for schema not found");
|
||||
assert!(error_notfound_obj.contains_key("message")); // Check message exists
|
||||
// Removed checks for schema_path/instance_path as they aren't added in lib.rs for this case
|
||||
}
|
||||
|
||||
#[pg_test]
|
||||
fn test_validate_json_schema_not_cached() {
|
||||
clear_json_schemas(); // Call clear directly
|
||||
let instance = json!({ "foo": "bar" });
|
||||
let result = validate_json_schema("non_existent_schema", jsonb(instance));
|
||||
// Use the updated macro, expecting count 1 and specific message (handles object case)
|
||||
assert_failure_with_json!(result, 1, "Schema with id 'non_existent_schema' not found", "Validation with non-existent schema should fail.");
|
||||
}
|
||||
|
||||
#[pg_test]
|
||||
fn test_cache_invalid_json_schema() {
|
||||
clear_json_schemas(); // Call clear directly
|
||||
let schema_id = "invalid_schema";
|
||||
// Schema with an invalid type *value*
|
||||
let invalid_schema = json!({
|
||||
"$id": "urn:invalid_schema",
|
||||
"type": ["invalid_type_value"]
|
||||
});
|
||||
|
||||
let cache_result = cache_json_schema(schema_id, jsonb(invalid_schema));
|
||||
|
||||
// Expect 2 leaf errors because the meta-schema validation fails at the type value
|
||||
// and within the type array itself.
|
||||
assert_failure_with_json!(
|
||||
cache_result,
|
||||
2, // Expect exactly two leaf errors
|
||||
"value must be one of", // Check message substring (present in both)
|
||||
"Caching invalid schema should fail with specific meta-schema validation errors."
|
||||
);
|
||||
|
||||
// Ensure the error is an array and check specifics
|
||||
let error_array = cache_result.0["error"].as_array().expect("Error field should be an array");
|
||||
assert_eq!(error_array.len(), 2);
|
||||
// Note: Order might vary depending on boon's internal processing, check both possibilities or sort.
|
||||
// Assuming the order shown in the logs for now:
|
||||
assert_eq!(error_array[0]["instance_path"], "/type");
|
||||
assert!(error_array[0]["message"].as_str().unwrap().contains("value must be one of"));
|
||||
assert_eq!(error_array[1]["instance_path"], "/type/0");
|
||||
assert!(error_array[1]["message"].as_str().unwrap().contains("value must be one of"));
|
||||
}
|
||||
|
||||
#[pg_test]
|
||||
fn test_validate_json_schema_detailed_validation_errors() {
|
||||
clear_json_schemas(); // Call clear directly
|
||||
let schema_id = "detailed_errors";
|
||||
let schema = json!({
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"address": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"street": { "type": "string" },
|
||||
"city": { "type": "string", "maxLength": 10 }
|
||||
},
|
||||
"required": ["street", "city"]
|
||||
}
|
||||
},
|
||||
"required": ["address"]
|
||||
});
|
||||
let _ = cache_json_schema(schema_id, jsonb(schema));
|
||||
|
||||
let invalid_instance = json!({
|
||||
"address": {
|
||||
"street": 123, // Wrong type
|
||||
"city": "Supercalifragilisticexpialidocious" // Too long
|
||||
}
|
||||
});
|
||||
|
||||
let result = validate_json_schema(schema_id, jsonb(invalid_instance));
|
||||
|
||||
// Update: Expect 2 errors again, as boon reports both nested errors.
|
||||
assert_failure_with_json!(result, 2);
|
||||
|
||||
}
|
||||
|
||||
#[pg_test]
|
||||
fn test_validate_json_schema_oneof_validation_errors() {
|
||||
clear_json_schemas(); // Call clear directly
|
||||
let schema_id = "oneof_schema";
|
||||
let schema = json!({
|
||||
"oneOf": [
|
||||
{ // Option 1: Object with string prop
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"string_prop": { "type": "string", "maxLength": 5 }
|
||||
},
|
||||
"required": ["string_prop"]
|
||||
},
|
||||
{ // Option 2: Object with number prop
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"number_prop": { "type": "number", "minimum": 10 }
|
||||
},
|
||||
"required": ["number_prop"]
|
||||
}
|
||||
]
|
||||
});
|
||||
|
||||
let _ = cache_json_schema(schema_id, jsonb(schema));
|
||||
|
||||
// --- Test case 1: Fails string maxLength (in branch 0) AND missing number_prop (in branch 1) ---
|
||||
let invalid_string_instance = json!({ "string_prop": "toolongstring" });
|
||||
let result_invalid_string = validate_json_schema(schema_id, jsonb(invalid_string_instance));
|
||||
// Expect 2 leaf errors. Check count only with the macro.
|
||||
assert_failure_with_json!(result_invalid_string, 2);
|
||||
// Explicitly check that both expected errors are present, ignoring order
|
||||
let errors_string = result_invalid_string.0["error"].as_array().expect("Expected error array for invalid string");
|
||||
assert!(errors_string.iter().any(|e| e["instance_path"] == "/string_prop" && e["message"].as_str().unwrap().contains("length must be <=5")), "Missing maxLength error");
|
||||
assert!(errors_string.iter().any(|e| e["instance_path"] == "" && e["message"].as_str().unwrap().contains("missing properties 'number_prop'")), "Missing number_prop required error");
|
||||
|
||||
// --- Test case 2: Fails number minimum (in branch 1) AND missing string_prop (in branch 0) ---
|
||||
let invalid_number_instance = json!({ "number_prop": 5 });
|
||||
let result_invalid_number = validate_json_schema(schema_id, jsonb(invalid_number_instance));
|
||||
// Expect 2 leaf errors. Check count only with the macro.
|
||||
assert_failure_with_json!(result_invalid_number, 2);
|
||||
// Explicitly check that both expected errors are present, ignoring order
|
||||
let errors_number = result_invalid_number.0["error"].as_array().expect("Expected error array for invalid number");
|
||||
assert!(errors_number.iter().any(|e| e["instance_path"] == "/number_prop" && e["message"].as_str().unwrap().contains("must be >=10")), "Missing minimum error");
|
||||
assert!(errors_number.iter().any(|e| e["instance_path"] == "" && e["message"].as_str().unwrap().contains("missing properties 'string_prop'")), "Missing string_prop required error");
|
||||
|
||||
// --- Test case 3: Fails type check (not object) for both branches ---
|
||||
// Input: boolean, expected object for both branches
|
||||
let invalid_bool_instance = json!(true); // Not an object
|
||||
let result_invalid_bool = validate_json_schema(schema_id, jsonb(invalid_bool_instance));
|
||||
// Expect only 1 leaf error after filtering, as both original errors have instance_path ""
|
||||
assert_failure_with_json!(result_invalid_bool, 1);
|
||||
// Explicitly check that the single remaining error is the type error for the root instance path
|
||||
let errors_bool = result_invalid_bool.0["error"].as_array().expect("Expected error array for invalid bool");
|
||||
assert_eq!(errors_bool.iter().filter(|e| e["instance_path"] == "" && e["message"].as_str().unwrap().contains("want object")).count(), 1, "Expected one 'want object' error at root after filtering");
|
||||
|
||||
// --- Test case 4: Fails missing required for both branches ---
|
||||
// Input: empty object, expected string_prop (branch 0) OR number_prop (branch 1)
|
||||
let invalid_empty_obj = json!({});
|
||||
let result_empty_obj = validate_json_schema(schema_id, jsonb(invalid_empty_obj));
|
||||
// Expect only 1 leaf error after filtering, as both original errors have instance_path ""
|
||||
assert_failure_with_json!(result_empty_obj, 1);
|
||||
// Explicitly check that the single remaining error is one of the expected missing properties errors
|
||||
let errors_empty = result_empty_obj.0["error"].as_array().expect("Expected error array for empty object");
|
||||
assert_eq!(errors_empty.len(), 1, "Expected exactly one error after filtering empty object");
|
||||
let the_error = &errors_empty[0];
|
||||
assert_eq!(the_error["instance_path"], "", "Expected instance_path to be empty string");
|
||||
let message = the_error["message"].as_str().unwrap();
|
||||
assert!(message.contains("missing properties 'string_prop'") || message.contains("missing properties 'number_prop'"),
|
||||
"Error message should indicate missing string_prop or number_prop, got: {}", message);
|
||||
}
|
||||
|
||||
#[pg_test]
|
||||
fn test_clear_json_schemas() {
|
||||
clear_json_schemas(); // Call clear directly
|
||||
let schema_id = "schema_to_clear";
|
||||
let schema = json!({ "type": "string" });
|
||||
cache_json_schema(schema_id, jsonb(schema.clone()));
|
||||
|
||||
let show_result1 = show_json_schemas();
|
||||
assert!(show_result1.contains(&schema_id.to_string()));
|
||||
|
||||
clear_json_schemas();
|
||||
|
||||
let show_result2 = show_json_schemas();
|
||||
assert!(show_result2.is_empty());
|
||||
|
||||
let instance = json!("test");
|
||||
let validate_result = validate_json_schema(schema_id, jsonb(instance));
|
||||
// Use the updated macro, expecting count 1 and specific message (handles object case)
|
||||
assert_failure_with_json!(validate_result, 1, "Schema with id 'schema_to_clear' not found", "Validation should fail after clearing schemas.");
|
||||
}
|
||||
|
||||
#[pg_test]
|
||||
fn test_show_json_schemas() {
|
||||
clear_json_schemas(); // Call clear directly
|
||||
let schema_id1 = "schema1";
|
||||
let schema_id2 = "schema2";
|
||||
let schema = json!({ "type": "boolean" });
|
||||
|
||||
cache_json_schema(schema_id1, jsonb(schema.clone()));
|
||||
cache_json_schema(schema_id2, jsonb(schema.clone()));
|
||||
|
||||
let mut result = show_json_schemas(); // Make result mutable
|
||||
result.sort(); // Sort for deterministic testing
|
||||
assert_eq!(result, vec!["schema1".to_string(), "schema2".to_string()]); // Check exact content
|
||||
assert!(result.contains(&schema_id1.to_string())); // Keep specific checks too if desired
|
||||
assert!(result.contains(&schema_id2.to_string()));
|
||||
}
|
||||
1668
src/tests/fixtures.rs
Normal file
1668
src/tests/fixtures.rs
Normal file
File diff suppressed because it is too large
Load Diff
82
src/validator/context.rs
Normal file
82
src/validator/context.rs
Normal file
@ -0,0 +1,82 @@
|
||||
use crate::database::Database;
|
||||
use crate::database::schema::Schema;
|
||||
use crate::validator::error::ValidationError;
|
||||
use crate::validator::result::ValidationResult;
|
||||
use std::collections::HashSet;
|
||||
use std::sync::Arc;
|
||||
|
||||
pub struct ValidationContext<'a> {
|
||||
pub db: &'a Arc<Database>,
|
||||
pub root: &'a Schema,
|
||||
pub schema: &'a Schema,
|
||||
pub instance: &'a serde_json::Value,
|
||||
pub path: String,
|
||||
pub depth: usize,
|
||||
pub extensible: bool,
|
||||
pub reporter: bool,
|
||||
pub overrides: HashSet<String>,
|
||||
}
|
||||
|
||||
impl<'a> ValidationContext<'a> {
|
||||
pub fn new(
|
||||
db: &'a Arc<Database>,
|
||||
root: &'a Schema,
|
||||
schema: &'a Schema,
|
||||
instance: &'a serde_json::Value,
|
||||
overrides: HashSet<String>,
|
||||
extensible: bool,
|
||||
reporter: bool,
|
||||
) -> Self {
|
||||
let effective_extensible = schema.extensible.unwrap_or(extensible);
|
||||
Self {
|
||||
db,
|
||||
root,
|
||||
schema,
|
||||
instance,
|
||||
path: String::new(),
|
||||
depth: 0,
|
||||
extensible: effective_extensible,
|
||||
reporter,
|
||||
overrides,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn derive(
|
||||
&self,
|
||||
schema: &'a Schema,
|
||||
instance: &'a serde_json::Value,
|
||||
path: &str,
|
||||
overrides: HashSet<String>,
|
||||
extensible: bool,
|
||||
reporter: bool,
|
||||
) -> Self {
|
||||
let effective_extensible = schema.extensible.unwrap_or(extensible);
|
||||
|
||||
Self {
|
||||
db: self.db,
|
||||
root: self.root,
|
||||
schema,
|
||||
instance,
|
||||
path: path.to_string(),
|
||||
depth: self.depth + 1,
|
||||
extensible: effective_extensible,
|
||||
reporter,
|
||||
overrides,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn derive_for_schema(&self, schema: &'a Schema, reporter: bool) -> Self {
|
||||
self.derive(
|
||||
schema,
|
||||
self.instance,
|
||||
&self.path,
|
||||
HashSet::new(),
|
||||
self.extensible,
|
||||
reporter,
|
||||
)
|
||||
}
|
||||
|
||||
pub fn validate(&self) -> Result<ValidationResult, ValidationError> {
|
||||
self.validate_scoped()
|
||||
}
|
||||
}
|
||||
6
src/validator/error.rs
Normal file
6
src/validator/error.rs
Normal file
@ -0,0 +1,6 @@
|
||||
#[derive(Debug, Clone, serde::Serialize)]
|
||||
pub struct ValidationError {
|
||||
pub code: String,
|
||||
pub message: String,
|
||||
pub path: String,
|
||||
}
|
||||
98
src/validator/instance.rs
Normal file
98
src/validator/instance.rs
Normal file
@ -0,0 +1,98 @@
|
||||
use serde_json::Value;
|
||||
use HashSet;
|
||||
use std::ptr::NonNull;
|
||||
|
||||
pub trait ValidationInstance<'a>: Copy + Clone {
|
||||
fn as_value(&self) -> &'a Value;
|
||||
fn child_at_key(&self, key: &str) -> Option<Self>;
|
||||
fn child_at_index(&self, idx: usize) -> Option<Self>;
|
||||
fn prune_object(&self, _keys: &HashSet<String>) {}
|
||||
fn prune_array(&self, _indices: &HashSet<usize>) {}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
pub struct ReadOnlyInstance<'a>(pub &'a Value);
|
||||
|
||||
impl<'a> ValidationInstance<'a> for ReadOnlyInstance<'a> {
|
||||
fn as_value(&self) -> &'a Value {
|
||||
self.0
|
||||
}
|
||||
|
||||
fn child_at_key(&self, key: &str) -> Option<Self> {
|
||||
self.0.get(key).map(ReadOnlyInstance)
|
||||
}
|
||||
|
||||
fn child_at_index(&self, idx: usize) -> Option<Self> {
|
||||
self.0.get(idx).map(ReadOnlyInstance)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
pub struct MutableInstance {
|
||||
ptr: NonNull<Value>,
|
||||
}
|
||||
|
||||
impl MutableInstance {
|
||||
pub fn new(val: &mut Value) -> Self {
|
||||
Self {
|
||||
ptr: NonNull::from(val),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> ValidationInstance<'a> for MutableInstance {
|
||||
fn as_value(&self) -> &'a Value {
|
||||
unsafe { self.ptr.as_ref() }
|
||||
}
|
||||
|
||||
fn child_at_key(&self, key: &str) -> Option<Self> {
|
||||
unsafe {
|
||||
if let Some(obj) = self.ptr.as_ref().as_object() {
|
||||
if obj.contains_key(key) {
|
||||
let parent_mut = &mut *self.ptr.as_ptr();
|
||||
if let Some(child_val) = parent_mut.get_mut(key) {
|
||||
return Some(MutableInstance::new(child_val));
|
||||
}
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
fn child_at_index(&self, idx: usize) -> Option<Self> {
|
||||
unsafe {
|
||||
if let Some(arr) = self.ptr.as_ref().as_array() {
|
||||
if idx < arr.len() {
|
||||
let parent_mut = &mut *self.ptr.as_ptr();
|
||||
if let Some(child_val) = parent_mut.get_mut(idx) {
|
||||
return Some(MutableInstance::new(child_val));
|
||||
}
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
fn prune_object(&self, keys: &HashSet<String>) {
|
||||
unsafe {
|
||||
let val_mut = &mut *self.ptr.as_ptr();
|
||||
if let Some(obj) = val_mut.as_object_mut() {
|
||||
obj.retain(|k, _| keys.contains(k));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn prune_array(&self, indices: &HashSet<usize>) {
|
||||
unsafe {
|
||||
let val_mut = &mut *self.ptr.as_ptr();
|
||||
if let Some(arr) = val_mut.as_array_mut() {
|
||||
let mut i = 0;
|
||||
arr.retain(|_| {
|
||||
let keep = indices.contains(&i);
|
||||
i += 1;
|
||||
keep
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
73
src/validator/mod.rs
Normal file
73
src/validator/mod.rs
Normal file
@ -0,0 +1,73 @@
|
||||
use std::collections::HashSet;
|
||||
|
||||
pub mod context;
|
||||
pub mod error;
|
||||
pub mod result;
|
||||
pub mod rules;
|
||||
pub mod util;
|
||||
|
||||
pub use context::ValidationContext;
|
||||
pub use error::ValidationError;
|
||||
pub use result::ValidationResult;
|
||||
|
||||
use crate::database::Database;
|
||||
use crate::validator::rules::util::is_integer;
|
||||
use serde_json::Value;
|
||||
use std::sync::Arc;
|
||||
|
||||
pub struct Validator {
|
||||
pub db: Arc<Database>,
|
||||
}
|
||||
|
||||
impl Validator {
|
||||
pub fn new(db: Arc<Database>) -> Self {
|
||||
Self { db }
|
||||
}
|
||||
|
||||
pub fn get_schema_ids(&self) -> Vec<String> {
|
||||
self.db.schemas.keys().cloned().collect()
|
||||
}
|
||||
|
||||
pub fn check_type(t: &str, val: &Value) -> bool {
|
||||
if let Value::String(s) = val
|
||||
&& s.is_empty()
|
||||
{
|
||||
return true;
|
||||
}
|
||||
match t {
|
||||
"null" => val.is_null(),
|
||||
"boolean" => val.is_boolean(),
|
||||
"string" => val.is_string(),
|
||||
"number" => val.is_number(),
|
||||
"integer" => is_integer(val),
|
||||
"object" => val.is_object(),
|
||||
"array" => val.is_array(),
|
||||
_ => true,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn validate(
|
||||
&self,
|
||||
schema_id: &str,
|
||||
instance: &Value,
|
||||
) -> Result<ValidationResult, ValidationError> {
|
||||
if let Some(schema) = self.db.schemas.get(schema_id) {
|
||||
let ctx = ValidationContext::new(
|
||||
&self.db,
|
||||
schema,
|
||||
schema,
|
||||
instance,
|
||||
HashSet::new(),
|
||||
false,
|
||||
false,
|
||||
);
|
||||
ctx.validate_scoped()
|
||||
} else {
|
||||
Err(ValidationError {
|
||||
code: "SCHEMA_NOT_FOUND".to_string(),
|
||||
message: format!("Schema {} not found", schema_id),
|
||||
path: "".to_string(),
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
28
src/validator/result.rs
Normal file
28
src/validator/result.rs
Normal file
@ -0,0 +1,28 @@
|
||||
use std::collections::HashSet;
|
||||
|
||||
use crate::validator::error::ValidationError;
|
||||
|
||||
#[derive(Debug, Default, Clone, serde::Serialize)]
|
||||
pub struct ValidationResult {
|
||||
pub errors: Vec<ValidationError>,
|
||||
#[serde(skip)]
|
||||
pub evaluated_keys: HashSet<String>,
|
||||
#[serde(skip)]
|
||||
pub evaluated_indices: HashSet<usize>,
|
||||
}
|
||||
|
||||
impl ValidationResult {
|
||||
pub fn new() -> Self {
|
||||
Self::default()
|
||||
}
|
||||
|
||||
pub fn merge(&mut self, other: ValidationResult) {
|
||||
self.errors.extend(other.errors);
|
||||
self.evaluated_keys.extend(other.evaluated_keys);
|
||||
self.evaluated_indices.extend(other.evaluated_indices);
|
||||
}
|
||||
|
||||
pub fn is_valid(&self) -> bool {
|
||||
self.errors.is_empty()
|
||||
}
|
||||
}
|
||||
135
src/validator/rules/array.rs
Normal file
135
src/validator/rules/array.rs
Normal file
@ -0,0 +1,135 @@
|
||||
use std::collections::HashSet;
|
||||
|
||||
use serde_json::Value;
|
||||
|
||||
use crate::validator::context::ValidationContext;
|
||||
use crate::validator::error::ValidationError;
|
||||
use crate::validator::result::ValidationResult;
|
||||
|
||||
impl<'a> ValidationContext<'a> {
|
||||
pub(crate) fn validate_array(
|
||||
&self,
|
||||
result: &mut ValidationResult,
|
||||
) -> Result<bool, ValidationError> {
|
||||
let current = self.instance;
|
||||
if let Some(arr) = current.as_array() {
|
||||
if let Some(min) = self.schema.min_items
|
||||
&& (arr.len() as f64) < min
|
||||
{
|
||||
result.errors.push(ValidationError {
|
||||
code: "MIN_ITEMS".to_string(),
|
||||
message: "Too few items".to_string(),
|
||||
path: self.path.to_string(),
|
||||
});
|
||||
}
|
||||
if let Some(max) = self.schema.max_items
|
||||
&& (arr.len() as f64) > max
|
||||
{
|
||||
result.errors.push(ValidationError {
|
||||
code: "MAX_ITEMS".to_string(),
|
||||
message: "Too many items".to_string(),
|
||||
path: self.path.to_string(),
|
||||
});
|
||||
}
|
||||
|
||||
if self.schema.unique_items.unwrap_or(false) {
|
||||
let mut seen: Vec<&Value> = Vec::new();
|
||||
for item in arr {
|
||||
if seen.contains(&item) {
|
||||
result.errors.push(ValidationError {
|
||||
code: "UNIQUE_ITEMS_VIOLATED".to_string(),
|
||||
message: "Array has duplicate items".to_string(),
|
||||
path: self.path.to_string(),
|
||||
});
|
||||
break;
|
||||
}
|
||||
seen.push(item);
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(ref contains_schema) = self.schema.contains {
|
||||
let mut _match_count = 0;
|
||||
for (i, child_instance) in arr.iter().enumerate() {
|
||||
let derived = self.derive(
|
||||
contains_schema,
|
||||
child_instance,
|
||||
&self.path,
|
||||
HashSet::new(),
|
||||
self.extensible,
|
||||
false,
|
||||
);
|
||||
|
||||
let check = derived.validate()?;
|
||||
if check.is_valid() {
|
||||
_match_count += 1;
|
||||
result.evaluated_indices.insert(i);
|
||||
}
|
||||
}
|
||||
|
||||
let min = self.schema.min_contains.unwrap_or(1.0) as usize;
|
||||
if _match_count < min {
|
||||
result.errors.push(ValidationError {
|
||||
code: "CONTAINS_VIOLATED".to_string(),
|
||||
message: format!("Contains matches {} < min {}", _match_count, min),
|
||||
path: self.path.to_string(),
|
||||
});
|
||||
}
|
||||
if let Some(max) = self.schema.max_contains
|
||||
&& _match_count > max as usize
|
||||
{
|
||||
result.errors.push(ValidationError {
|
||||
code: "CONTAINS_VIOLATED".to_string(),
|
||||
message: format!("Contains matches {} > max {}", _match_count, max),
|
||||
path: self.path.to_string(),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
let len = arr.len();
|
||||
let mut validation_index = 0;
|
||||
|
||||
if let Some(ref prefix) = self.schema.prefix_items {
|
||||
for (i, sub_schema) in prefix.iter().enumerate() {
|
||||
if i < len {
|
||||
let path = format!("{}/{}", self.path, i);
|
||||
if let Some(child_instance) = arr.get(i) {
|
||||
let derived = self.derive(
|
||||
sub_schema,
|
||||
child_instance,
|
||||
&path,
|
||||
HashSet::new(),
|
||||
self.extensible,
|
||||
false,
|
||||
);
|
||||
let item_res = derived.validate()?;
|
||||
result.merge(item_res);
|
||||
result.evaluated_indices.insert(i);
|
||||
validation_index += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(ref items_schema) = self.schema.items {
|
||||
for i in validation_index..len {
|
||||
let path = format!("{}/{}", self.path, i);
|
||||
if let Some(child_instance) = arr.get(i) {
|
||||
let derived = self.derive(
|
||||
items_schema,
|
||||
child_instance,
|
||||
&path,
|
||||
HashSet::new(),
|
||||
self.extensible,
|
||||
false,
|
||||
);
|
||||
let item_res = derived.validate()?;
|
||||
result.merge(item_res);
|
||||
result.evaluated_indices.insert(i);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(true)
|
||||
}
|
||||
}
|
||||
92
src/validator/rules/combinators.rs
Normal file
92
src/validator/rules/combinators.rs
Normal file
@ -0,0 +1,92 @@
|
||||
use crate::validator::context::ValidationContext;
|
||||
use crate::validator::error::ValidationError;
|
||||
use crate::validator::result::ValidationResult;
|
||||
|
||||
impl<'a> ValidationContext<'a> {
|
||||
pub(crate) fn validate_combinators(
|
||||
&self,
|
||||
result: &mut ValidationResult,
|
||||
) -> Result<bool, ValidationError> {
|
||||
if let Some(ref all_of) = self.schema.all_of {
|
||||
for sub in all_of {
|
||||
let derived = self.derive_for_schema(sub, true);
|
||||
let res = derived.validate()?;
|
||||
result.merge(res);
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(ref one_of) = self.schema.one_of {
|
||||
let mut passed_candidates: Vec<(Option<String>, usize, ValidationResult)> = Vec::new();
|
||||
|
||||
for sub in one_of {
|
||||
let derived = self.derive_for_schema(sub, true);
|
||||
let sub_res = derived.validate()?;
|
||||
if sub_res.is_valid() {
|
||||
let child_id = sub.id.clone();
|
||||
let depth = child_id
|
||||
.as_ref()
|
||||
.and_then(|id| self.db.depths.get(id).copied())
|
||||
.unwrap_or(0);
|
||||
passed_candidates.push((child_id, depth, sub_res));
|
||||
}
|
||||
}
|
||||
|
||||
if passed_candidates.len() == 1 {
|
||||
result.merge(passed_candidates.pop().unwrap().2);
|
||||
} else if passed_candidates.is_empty() {
|
||||
result.errors.push(ValidationError {
|
||||
code: "NO_ONEOF_MATCH".to_string(),
|
||||
message: "Matches none of oneOf schemas".to_string(),
|
||||
path: self.path.to_string(),
|
||||
});
|
||||
} else {
|
||||
// Apply depth heuristic tie-breaker
|
||||
let mut best_depth: Option<usize> = None;
|
||||
let mut ambiguous = false;
|
||||
let mut best_res = None;
|
||||
|
||||
for (_, depth, res) in passed_candidates.into_iter() {
|
||||
if let Some(current_best) = best_depth {
|
||||
if depth > current_best {
|
||||
best_depth = Some(depth);
|
||||
best_res = Some(res);
|
||||
ambiguous = false;
|
||||
} else if depth == current_best {
|
||||
ambiguous = true;
|
||||
}
|
||||
} else {
|
||||
best_depth = Some(depth);
|
||||
best_res = Some(res);
|
||||
}
|
||||
}
|
||||
|
||||
if !ambiguous {
|
||||
if let Some(res) = best_res {
|
||||
result.merge(res);
|
||||
return Ok(true);
|
||||
}
|
||||
}
|
||||
|
||||
result.errors.push(ValidationError {
|
||||
code: "AMBIGUOUS_ONEOF_MATCH".to_string(),
|
||||
message: "Matches multiple oneOf schemas without a clear depth winner".to_string(),
|
||||
path: self.path.to_string(),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(ref not_schema) = self.schema.not {
|
||||
let derived = self.derive_for_schema(not_schema, true);
|
||||
let sub_res = derived.validate()?;
|
||||
if sub_res.is_valid() {
|
||||
result.errors.push(ValidationError {
|
||||
code: "NOT_VIOLATED".to_string(),
|
||||
message: "Matched 'not' schema".to_string(),
|
||||
path: self.path.to_string(),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
Ok(true)
|
||||
}
|
||||
}
|
||||
67
src/validator/rules/conditionals.rs
Normal file
67
src/validator/rules/conditionals.rs
Normal file
@ -0,0 +1,67 @@
|
||||
use crate::validator::context::ValidationContext;
|
||||
use crate::validator::error::ValidationError;
|
||||
use crate::validator::result::ValidationResult;
|
||||
|
||||
impl<'a> ValidationContext<'a> {
|
||||
pub(crate) fn validate_conditionals(
|
||||
&self,
|
||||
result: &mut ValidationResult,
|
||||
) -> Result<bool, ValidationError> {
|
||||
if let Some(ref if_schema) = self.schema.if_ {
|
||||
let derived_if = self.derive_for_schema(if_schema, true);
|
||||
let if_res = derived_if.validate()?;
|
||||
|
||||
result.evaluated_keys.extend(if_res.evaluated_keys.clone());
|
||||
result
|
||||
.evaluated_indices
|
||||
.extend(if_res.evaluated_indices.clone());
|
||||
|
||||
if if_res.is_valid() {
|
||||
if let Some(ref then_schema) = self.schema.then_ {
|
||||
let derived_then = self.derive_for_schema(then_schema, true);
|
||||
result.merge(derived_then.validate()?);
|
||||
}
|
||||
} else if let Some(ref else_schema) = self.schema.else_ {
|
||||
let derived_else = self.derive_for_schema(else_schema, true);
|
||||
result.merge(derived_else.validate()?);
|
||||
}
|
||||
}
|
||||
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
pub(crate) fn validate_strictness(
|
||||
&self,
|
||||
result: &mut ValidationResult,
|
||||
) -> Result<bool, ValidationError> {
|
||||
if self.extensible || self.reporter {
|
||||
return Ok(true);
|
||||
}
|
||||
|
||||
if let Some(obj) = self.instance.as_object() {
|
||||
for key in obj.keys() {
|
||||
if !result.evaluated_keys.contains(key) && !self.overrides.contains(key) {
|
||||
result.errors.push(ValidationError {
|
||||
code: "STRICT_PROPERTY_VIOLATION".to_string(),
|
||||
message: format!("Unexpected property '{}'", key),
|
||||
path: format!("{}/{}", self.path, key),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(arr) = self.instance.as_array() {
|
||||
for i in 0..arr.len() {
|
||||
if !result.evaluated_indices.contains(&i) {
|
||||
result.errors.push(ValidationError {
|
||||
code: "STRICT_ITEM_VIOLATION".to_string(),
|
||||
message: format!("Unexpected item at index {}", i),
|
||||
path: format!("{}/{}", self.path, i),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(true)
|
||||
}
|
||||
}
|
||||
81
src/validator/rules/core.rs
Normal file
81
src/validator/rules/core.rs
Normal file
@ -0,0 +1,81 @@
|
||||
use crate::validator::Validator;
|
||||
use crate::validator::context::ValidationContext;
|
||||
use crate::validator::error::ValidationError;
|
||||
use crate::validator::result::ValidationResult;
|
||||
use crate::validator::rules::util::equals;
|
||||
|
||||
impl<'a> ValidationContext<'a> {
|
||||
pub(crate) fn validate_core(
|
||||
&self,
|
||||
result: &mut ValidationResult,
|
||||
) -> Result<bool, ValidationError> {
|
||||
let current = self.instance;
|
||||
|
||||
if let Some(ref type_) = self.schema.type_ {
|
||||
match type_ {
|
||||
crate::database::schema::SchemaTypeOrArray::Single(t) => {
|
||||
if !Validator::check_type(t, current) {
|
||||
result.errors.push(ValidationError {
|
||||
code: "INVALID_TYPE".to_string(),
|
||||
message: format!("Expected type '{}'", t),
|
||||
path: self.path.to_string(),
|
||||
});
|
||||
}
|
||||
}
|
||||
crate::database::schema::SchemaTypeOrArray::Multiple(types) => {
|
||||
let mut valid = false;
|
||||
for t in types {
|
||||
if Validator::check_type(t, current) {
|
||||
valid = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if !valid {
|
||||
result.errors.push(ValidationError {
|
||||
code: "INVALID_TYPE".to_string(),
|
||||
message: format!("Expected one of types {:?}", types),
|
||||
path: self.path.to_string(),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(ref const_val) = self.schema.const_ {
|
||||
if !equals(current, const_val) {
|
||||
result.errors.push(ValidationError {
|
||||
code: "CONST_VIOLATED".to_string(),
|
||||
message: "Value does not match const".to_string(),
|
||||
path: self.path.to_string(),
|
||||
});
|
||||
} else if let Some(obj) = current.as_object() {
|
||||
result.evaluated_keys.extend(obj.keys().cloned());
|
||||
} else if let Some(arr) = current.as_array() {
|
||||
result.evaluated_indices.extend(0..arr.len());
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(ref enum_vals) = self.schema.enum_ {
|
||||
let mut found = false;
|
||||
for val in enum_vals {
|
||||
if equals(current, val) {
|
||||
found = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
result.errors.push(ValidationError {
|
||||
code: "ENUM_MISMATCH".to_string(),
|
||||
message: "Value is not in enum".to_string(),
|
||||
path: self.path.to_string(),
|
||||
});
|
||||
} else if let Some(obj) = current.as_object() {
|
||||
result.evaluated_keys.extend(obj.keys().cloned());
|
||||
} else if let Some(arr) = current.as_array() {
|
||||
result.evaluated_indices.extend(0..arr.len());
|
||||
}
|
||||
}
|
||||
|
||||
Ok(true)
|
||||
}
|
||||
}
|
||||
42
src/validator/rules/format.rs
Normal file
42
src/validator/rules/format.rs
Normal file
@ -0,0 +1,42 @@
|
||||
use crate::validator::context::ValidationContext;
|
||||
use crate::validator::error::ValidationError;
|
||||
use crate::validator::result::ValidationResult;
|
||||
|
||||
impl<'a> ValidationContext<'a> {
|
||||
pub(crate) fn validate_format(
|
||||
&self,
|
||||
result: &mut ValidationResult,
|
||||
) -> Result<bool, ValidationError> {
|
||||
let current = self.instance;
|
||||
if let Some(ref compiled_fmt) = self.schema.compiled_format {
|
||||
match compiled_fmt {
|
||||
crate::database::schema::CompiledFormat::Func(f) => {
|
||||
let should = if let Some(s) = current.as_str() {
|
||||
!s.is_empty()
|
||||
} else {
|
||||
true
|
||||
};
|
||||
if should && let Err(e) = f(current) {
|
||||
result.errors.push(ValidationError {
|
||||
code: "FORMAT_MISMATCH".to_string(),
|
||||
message: format!("Format error: {}", e),
|
||||
path: self.path.to_string(),
|
||||
});
|
||||
}
|
||||
}
|
||||
crate::database::schema::CompiledFormat::Regex(re) => {
|
||||
if let Some(s) = current.as_str()
|
||||
&& !re.is_match(s)
|
||||
{
|
||||
result.errors.push(ValidationError {
|
||||
code: "FORMAT_MISMATCH".to_string(),
|
||||
message: "Format regex mismatch".to_string(),
|
||||
path: self.path.to_string(),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(true)
|
||||
}
|
||||
}
|
||||
91
src/validator/rules/mod.rs
Normal file
91
src/validator/rules/mod.rs
Normal file
@ -0,0 +1,91 @@
|
||||
use crate::validator::context::ValidationContext;
|
||||
use crate::validator::error::ValidationError;
|
||||
use crate::validator::result::ValidationResult;
|
||||
|
||||
pub mod array;
|
||||
pub mod combinators;
|
||||
pub mod conditionals;
|
||||
pub mod core;
|
||||
pub mod format;
|
||||
pub mod numeric;
|
||||
pub mod object;
|
||||
pub mod polymorphism;
|
||||
pub mod string;
|
||||
pub mod util;
|
||||
|
||||
impl<'a> ValidationContext<'a> {
|
||||
pub(crate) fn validate_scoped(&self) -> Result<ValidationResult, ValidationError> {
|
||||
let mut result = ValidationResult::new();
|
||||
|
||||
// Structural Limits
|
||||
if !self.validate_depth(&mut result)? {
|
||||
return Ok(result);
|
||||
}
|
||||
if !self.validate_always_fail(&mut result)? {
|
||||
return Ok(result);
|
||||
}
|
||||
if !self.validate_family(&mut result)? {
|
||||
return Ok(result);
|
||||
}
|
||||
if !self.validate_refs(&mut result)? {
|
||||
return Ok(result);
|
||||
}
|
||||
|
||||
// Core Type Constraints
|
||||
self.validate_core(&mut result)?;
|
||||
self.validate_numeric(&mut result)?;
|
||||
self.validate_string(&mut result)?;
|
||||
self.validate_format(&mut result)?;
|
||||
|
||||
// Complex Structures
|
||||
self.validate_object(&mut result)?;
|
||||
self.validate_array(&mut result)?;
|
||||
|
||||
// Multipliers & Conditionals
|
||||
self.validate_combinators(&mut result)?;
|
||||
self.validate_conditionals(&mut result)?;
|
||||
|
||||
// State Tracking
|
||||
self.validate_extensible(&mut result)?;
|
||||
self.validate_strictness(&mut result)?;
|
||||
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
fn validate_depth(&self, _result: &mut ValidationResult) -> Result<bool, ValidationError> {
|
||||
if self.depth > 100 {
|
||||
Err(ValidationError {
|
||||
code: "RECURSION_LIMIT_EXCEEDED".to_string(),
|
||||
message: "Recursion limit exceeded".to_string(),
|
||||
path: self.path.to_string(),
|
||||
})
|
||||
} else {
|
||||
Ok(true)
|
||||
}
|
||||
}
|
||||
|
||||
fn validate_always_fail(&self, result: &mut ValidationResult) -> Result<bool, ValidationError> {
|
||||
if self.schema.always_fail {
|
||||
result.errors.push(ValidationError {
|
||||
code: "FALSE_SCHEMA".to_string(),
|
||||
message: "Schema is false".to_string(),
|
||||
path: self.path.to_string(),
|
||||
});
|
||||
// Short-circuit
|
||||
Ok(false)
|
||||
} else {
|
||||
Ok(true)
|
||||
}
|
||||
}
|
||||
|
||||
fn validate_extensible(&self, result: &mut ValidationResult) -> Result<bool, ValidationError> {
|
||||
if self.extensible {
|
||||
if let Some(obj) = self.instance.as_object() {
|
||||
result.evaluated_keys.extend(obj.keys().cloned());
|
||||
} else if let Some(arr) = self.instance.as_array() {
|
||||
result.evaluated_indices.extend(0..arr.len());
|
||||
}
|
||||
}
|
||||
Ok(true)
|
||||
}
|
||||
}
|
||||
61
src/validator/rules/numeric.rs
Normal file
61
src/validator/rules/numeric.rs
Normal file
@ -0,0 +1,61 @@
|
||||
use crate::validator::context::ValidationContext;
|
||||
use crate::validator::error::ValidationError;
|
||||
use crate::validator::result::ValidationResult;
|
||||
|
||||
impl<'a> ValidationContext<'a> {
|
||||
pub(crate) fn validate_numeric(
|
||||
&self,
|
||||
result: &mut ValidationResult,
|
||||
) -> Result<bool, ValidationError> {
|
||||
let current = self.instance;
|
||||
if let Some(num) = current.as_f64() {
|
||||
if let Some(min) = self.schema.minimum
|
||||
&& num < min
|
||||
{
|
||||
result.errors.push(ValidationError {
|
||||
code: "MINIMUM_VIOLATED".to_string(),
|
||||
message: format!("Value {} < min {}", num, min),
|
||||
path: self.path.to_string(),
|
||||
});
|
||||
}
|
||||
if let Some(max) = self.schema.maximum
|
||||
&& num > max
|
||||
{
|
||||
result.errors.push(ValidationError {
|
||||
code: "MAXIMUM_VIOLATED".to_string(),
|
||||
message: format!("Value {} > max {}", num, max),
|
||||
path: self.path.to_string(),
|
||||
});
|
||||
}
|
||||
if let Some(ex_min) = self.schema.exclusive_minimum
|
||||
&& num <= ex_min
|
||||
{
|
||||
result.errors.push(ValidationError {
|
||||
code: "EXCLUSIVE_MINIMUM_VIOLATED".to_string(),
|
||||
message: format!("Value {} <= ex_min {}", num, ex_min),
|
||||
path: self.path.to_string(),
|
||||
});
|
||||
}
|
||||
if let Some(ex_max) = self.schema.exclusive_maximum
|
||||
&& num >= ex_max
|
||||
{
|
||||
result.errors.push(ValidationError {
|
||||
code: "EXCLUSIVE_MAXIMUM_VIOLATED".to_string(),
|
||||
message: format!("Value {} >= ex_max {}", num, ex_max),
|
||||
path: self.path.to_string(),
|
||||
});
|
||||
}
|
||||
if let Some(multiple_of) = self.schema.multiple_of {
|
||||
let val: f64 = num / multiple_of;
|
||||
if (val - val.round()).abs() > f64::EPSILON {
|
||||
result.errors.push(ValidationError {
|
||||
code: "MULTIPLE_OF_VIOLATED".to_string(),
|
||||
message: format!("Value {} not multiple of {}", num, multiple_of),
|
||||
path: self.path.to_string(),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(true)
|
||||
}
|
||||
}
|
||||
220
src/validator/rules/object.rs
Normal file
220
src/validator/rules/object.rs
Normal file
@ -0,0 +1,220 @@
|
||||
use std::collections::HashSet;
|
||||
|
||||
use serde_json::Value;
|
||||
|
||||
use crate::validator::context::ValidationContext;
|
||||
use crate::validator::error::ValidationError;
|
||||
use crate::validator::result::ValidationResult;
|
||||
|
||||
impl<'a> ValidationContext<'a> {
|
||||
pub(crate) fn validate_object(
|
||||
&self,
|
||||
result: &mut ValidationResult,
|
||||
) -> Result<bool, ValidationError> {
|
||||
let current = self.instance;
|
||||
if let Some(obj) = current.as_object() {
|
||||
// Entity Bound Implicit Type Validation
|
||||
if let Some(lookup_key) = self.schema.id.as_ref().or(self.schema.r#ref.as_ref()) {
|
||||
let base_type_name = lookup_key.split('.').next_back().unwrap_or("").to_string();
|
||||
if let Some(type_def) = self.db.types.get(&base_type_name)
|
||||
&& let Some(type_val) = obj.get("type")
|
||||
&& let Some(type_str) = type_val.as_str()
|
||||
{
|
||||
if type_def.variations.contains(type_str) {
|
||||
// Ensure it passes strict mode
|
||||
result.evaluated_keys.insert("type".to_string());
|
||||
} else {
|
||||
result.errors.push(ValidationError {
|
||||
code: "CONST_VIOLATED".to_string(), // Aligning with original const override errors
|
||||
message: format!(
|
||||
"Type '{}' is not a valid descendant for this entity bound schema",
|
||||
type_str
|
||||
),
|
||||
path: format!("{}/type", self.path),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(min) = self.schema.min_properties
|
||||
&& (obj.len() as f64) < min
|
||||
{
|
||||
result.errors.push(ValidationError {
|
||||
code: "MIN_PROPERTIES".to_string(),
|
||||
message: "Too few properties".to_string(),
|
||||
path: self.path.to_string(),
|
||||
});
|
||||
}
|
||||
if let Some(max) = self.schema.max_properties
|
||||
&& (obj.len() as f64) > max
|
||||
{
|
||||
result.errors.push(ValidationError {
|
||||
code: "MAX_PROPERTIES".to_string(),
|
||||
message: "Too many properties".to_string(),
|
||||
path: self.path.to_string(),
|
||||
});
|
||||
}
|
||||
if let Some(ref req) = self.schema.required {
|
||||
for field in req {
|
||||
if !obj.contains_key(field) {
|
||||
result.errors.push(ValidationError {
|
||||
code: "REQUIRED_FIELD_MISSING".to_string(),
|
||||
message: format!("Missing {}", field),
|
||||
path: format!("{}/{}", self.path, field),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(ref deps) = self.schema.dependencies {
|
||||
for (prop, dep) in deps {
|
||||
if obj.contains_key(prop) {
|
||||
match dep {
|
||||
crate::database::schema::Dependency::Props(required_props) => {
|
||||
for req_prop in required_props {
|
||||
if !obj.contains_key(req_prop) {
|
||||
result.errors.push(ValidationError {
|
||||
code: "DEPENDENCY_MISSING".to_string(),
|
||||
message: format!("Property '{}' requires property '{}'", prop, req_prop),
|
||||
path: self.path.to_string(),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
crate::database::schema::Dependency::Schema(dep_schema) => {
|
||||
let derived = self.derive_for_schema(dep_schema, false);
|
||||
let dep_res = derived.validate()?;
|
||||
result.evaluated_keys.extend(dep_res.evaluated_keys.clone());
|
||||
result.merge(dep_res);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(props) = &self.schema.properties {
|
||||
for (key, sub_schema) in props {
|
||||
if self.overrides.contains(key) {
|
||||
continue; // Skip validation if exactly this property was overridden by a child
|
||||
}
|
||||
|
||||
if let Some(child_instance) = obj.get(key) {
|
||||
let new_path = format!("{}/{}", self.path, key);
|
||||
let is_ref = sub_schema.r#ref.is_some();
|
||||
let next_extensible = if is_ref { false } else { self.extensible };
|
||||
|
||||
let derived = self.derive(
|
||||
sub_schema,
|
||||
child_instance,
|
||||
&new_path,
|
||||
HashSet::new(),
|
||||
next_extensible,
|
||||
false,
|
||||
);
|
||||
let mut item_res = derived.validate()?;
|
||||
|
||||
// Entity Bound Implicit Type Interception
|
||||
if key == "type"
|
||||
&& let Some(lookup_key) = sub_schema.id.as_ref().or(sub_schema.r#ref.as_ref())
|
||||
{
|
||||
let base_type_name = lookup_key.split('.').next_back().unwrap_or("").to_string();
|
||||
if let Some(type_def) = self.db.types.get(&base_type_name)
|
||||
&& let Some(instance_type) = child_instance.as_str()
|
||||
&& type_def.variations.contains(instance_type)
|
||||
{
|
||||
item_res
|
||||
.errors
|
||||
.retain(|e| e.code != "CONST_VIOLATED" && e.code != "ENUM_VIOLATED");
|
||||
}
|
||||
}
|
||||
|
||||
result.merge(item_res);
|
||||
result.evaluated_keys.insert(key.to_string());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(ref compiled_pp) = self.schema.compiled_pattern_properties {
|
||||
for (compiled_re, sub_schema) in compiled_pp {
|
||||
for (key, child_instance) in obj {
|
||||
if compiled_re.0.is_match(key) {
|
||||
let new_path = format!("{}/{}", self.path, key);
|
||||
let is_ref = sub_schema.r#ref.is_some();
|
||||
let next_extensible = if is_ref { false } else { self.extensible };
|
||||
|
||||
let derived = self.derive(
|
||||
sub_schema,
|
||||
child_instance,
|
||||
&new_path,
|
||||
HashSet::new(),
|
||||
next_extensible,
|
||||
false,
|
||||
);
|
||||
let item_res = derived.validate()?;
|
||||
result.merge(item_res);
|
||||
result.evaluated_keys.insert(key.to_string());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(ref additional_schema) = self.schema.additional_properties {
|
||||
for (key, child_instance) in obj {
|
||||
let mut locally_matched = false;
|
||||
if let Some(props) = &self.schema.properties
|
||||
&& props.contains_key(&key.to_string())
|
||||
{
|
||||
locally_matched = true;
|
||||
}
|
||||
if !locally_matched && let Some(ref compiled_pp) = self.schema.compiled_pattern_properties
|
||||
{
|
||||
for (compiled_re, _) in compiled_pp {
|
||||
if compiled_re.0.is_match(key) {
|
||||
locally_matched = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if !locally_matched {
|
||||
let new_path = format!("{}/{}", self.path, key);
|
||||
let is_ref = additional_schema.r#ref.is_some();
|
||||
let next_extensible = if is_ref { false } else { self.extensible };
|
||||
|
||||
let derived = self.derive(
|
||||
additional_schema,
|
||||
child_instance,
|
||||
&new_path,
|
||||
HashSet::new(),
|
||||
next_extensible,
|
||||
false,
|
||||
);
|
||||
let item_res = derived.validate()?;
|
||||
result.merge(item_res);
|
||||
result.evaluated_keys.insert(key.to_string());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(ref property_names) = self.schema.property_names {
|
||||
for key in obj.keys() {
|
||||
let _new_path = format!("{}/propertyNames/{}", self.path, key);
|
||||
let val_str = Value::String(key.to_string());
|
||||
|
||||
let ctx = ValidationContext::new(
|
||||
self.db,
|
||||
self.root,
|
||||
property_names,
|
||||
&val_str,
|
||||
HashSet::new(),
|
||||
self.extensible,
|
||||
self.reporter,
|
||||
);
|
||||
|
||||
result.merge(ctx.validate()?);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(true)
|
||||
}
|
||||
}
|
||||
155
src/validator/rules/polymorphism.rs
Normal file
155
src/validator/rules/polymorphism.rs
Normal file
@ -0,0 +1,155 @@
|
||||
use crate::validator::context::ValidationContext;
|
||||
use crate::validator::error::ValidationError;
|
||||
use crate::validator::result::ValidationResult;
|
||||
|
||||
impl<'a> ValidationContext<'a> {
|
||||
pub(crate) fn validate_family(
|
||||
&self,
|
||||
result: &mut ValidationResult,
|
||||
) -> Result<bool, ValidationError> {
|
||||
if self.schema.family.is_some() {
|
||||
let conflicts = self.schema.type_.is_some()
|
||||
|| self.schema.properties.is_some()
|
||||
|| self.schema.required.is_some()
|
||||
|| self.schema.additional_properties.is_some()
|
||||
|| self.schema.items.is_some()
|
||||
|| self.schema.r#ref.is_some()
|
||||
|| self.schema.one_of.is_some()
|
||||
|| self.schema.all_of.is_some()
|
||||
|| self.schema.enum_.is_some()
|
||||
|| self.schema.const_.is_some();
|
||||
|
||||
if conflicts {
|
||||
result.errors.push(ValidationError {
|
||||
code: "INVALID_SCHEMA".to_string(),
|
||||
message: "$family must be used exclusively without other constraints".to_string(),
|
||||
path: self.path.to_string(),
|
||||
});
|
||||
// Short-circuit: the schema formulation is broken
|
||||
return Ok(false);
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(family_target) = &self.schema.family {
|
||||
// The descendants map is keyed by the schema's own $id, not the target string.
|
||||
if let Some(schema_id) = &self.schema.id
|
||||
&& let Some(descendants) = self.db.descendants.get(schema_id)
|
||||
{
|
||||
// Validate against all descendants simulating strict oneOf logic
|
||||
let mut passed_candidates: Vec<(String, usize, ValidationResult)> = Vec::new();
|
||||
|
||||
// The target itself is also an implicitly valid candidate
|
||||
let mut all_targets = vec![family_target.clone()];
|
||||
all_targets.extend(descendants.clone());
|
||||
|
||||
for child_id in &all_targets {
|
||||
if let Some(child_schema) = self.db.schemas.get(child_id) {
|
||||
let derived = self.derive(
|
||||
child_schema,
|
||||
self.instance,
|
||||
&self.path,
|
||||
self.overrides.clone(),
|
||||
self.extensible,
|
||||
self.reporter, // Inherit parent reporter flag, do not bypass strictness!
|
||||
);
|
||||
|
||||
// Explicitly run validate_scoped to accurately test candidates with strictness checks enabled
|
||||
let res = derived.validate_scoped()?;
|
||||
|
||||
if res.is_valid() {
|
||||
let depth = self.db.depths.get(child_id).copied().unwrap_or(0);
|
||||
passed_candidates.push((child_id.clone(), depth, res));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if passed_candidates.len() == 1 {
|
||||
result.merge(passed_candidates.pop().unwrap().2);
|
||||
} else if passed_candidates.is_empty() {
|
||||
result.errors.push(ValidationError {
|
||||
code: "NO_FAMILY_MATCH".to_string(),
|
||||
message: format!(
|
||||
"Payload did not match any descendants of family '{}'",
|
||||
family_target
|
||||
),
|
||||
path: self.path.to_string(),
|
||||
});
|
||||
} else {
|
||||
// Apply depth heuristic tie-breaker
|
||||
let mut best_depth: Option<usize> = None;
|
||||
let mut ambiguous = false;
|
||||
let mut best_res = None;
|
||||
|
||||
for (_, depth, res) in passed_candidates.into_iter() {
|
||||
if let Some(current_best) = best_depth {
|
||||
if depth > current_best {
|
||||
best_depth = Some(depth);
|
||||
best_res = Some(res);
|
||||
ambiguous = false; // Broke the tie
|
||||
} else if depth == current_best {
|
||||
ambiguous = true; // Tie at the highest level
|
||||
}
|
||||
} else {
|
||||
best_depth = Some(depth);
|
||||
best_res = Some(res);
|
||||
}
|
||||
}
|
||||
|
||||
if !ambiguous {
|
||||
if let Some(res) = best_res {
|
||||
result.merge(res);
|
||||
return Ok(true);
|
||||
}
|
||||
}
|
||||
|
||||
result.errors.push(ValidationError {
|
||||
code: "AMBIGUOUS_FAMILY_MATCH".to_string(),
|
||||
message: format!(
|
||||
"Payload matched multiple descendants of family '{}' without a clear depth winner",
|
||||
family_target
|
||||
),
|
||||
path: self.path.to_string(),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
pub(crate) fn validate_refs(
|
||||
&self,
|
||||
result: &mut ValidationResult,
|
||||
) -> Result<bool, ValidationError> {
|
||||
// 1. Core $ref logic relies on the fast O(1) map to allow cycles and proper nesting
|
||||
if let Some(ref_str) = &self.schema.r#ref {
|
||||
if let Some(global_schema) = self.db.schemas.get(ref_str) {
|
||||
let mut new_overrides = self.overrides.clone();
|
||||
if let Some(props) = &self.schema.properties {
|
||||
new_overrides.extend(props.keys().map(|k| k.to_string()));
|
||||
}
|
||||
|
||||
let mut shadow = self.derive(
|
||||
global_schema,
|
||||
self.instance,
|
||||
&self.path,
|
||||
new_overrides,
|
||||
self.extensible,
|
||||
true,
|
||||
);
|
||||
shadow.root = global_schema;
|
||||
result.merge(shadow.validate()?);
|
||||
} else {
|
||||
result.errors.push(ValidationError {
|
||||
code: "REF_RESOLUTION_FAILED".to_string(),
|
||||
message: format!(
|
||||
"Reference pointer to '{}' was not found in schema registry",
|
||||
ref_str
|
||||
),
|
||||
path: self.path.to_string(),
|
||||
});
|
||||
}
|
||||
}
|
||||
Ok(true)
|
||||
}
|
||||
}
|
||||
52
src/validator/rules/string.rs
Normal file
52
src/validator/rules/string.rs
Normal file
@ -0,0 +1,52 @@
|
||||
use crate::validator::context::ValidationContext;
|
||||
use crate::validator::error::ValidationError;
|
||||
use crate::validator::result::ValidationResult;
|
||||
use regex::Regex;
|
||||
|
||||
impl<'a> ValidationContext<'a> {
|
||||
pub(crate) fn validate_string(
|
||||
&self,
|
||||
result: &mut ValidationResult,
|
||||
) -> Result<bool, ValidationError> {
|
||||
let current = self.instance;
|
||||
if let Some(s) = current.as_str() {
|
||||
if let Some(min) = self.schema.min_length
|
||||
&& (s.chars().count() as f64) < min
|
||||
{
|
||||
result.errors.push(ValidationError {
|
||||
code: "MIN_LENGTH_VIOLATED".to_string(),
|
||||
message: format!("Length < min {}", min),
|
||||
path: self.path.to_string(),
|
||||
});
|
||||
}
|
||||
if let Some(max) = self.schema.max_length
|
||||
&& (s.chars().count() as f64) > max
|
||||
{
|
||||
result.errors.push(ValidationError {
|
||||
code: "MAX_LENGTH_VIOLATED".to_string(),
|
||||
message: format!("Length > max {}", max),
|
||||
path: self.path.to_string(),
|
||||
});
|
||||
}
|
||||
if let Some(ref compiled_re) = self.schema.compiled_pattern {
|
||||
if !compiled_re.0.is_match(s) {
|
||||
result.errors.push(ValidationError {
|
||||
code: "PATTERN_VIOLATED".to_string(),
|
||||
message: format!("Pattern mismatch {:?}", self.schema.pattern),
|
||||
path: self.path.to_string(),
|
||||
});
|
||||
}
|
||||
} else if let Some(ref pattern) = self.schema.pattern
|
||||
&& let Ok(re) = Regex::new(pattern)
|
||||
&& !re.is_match(s)
|
||||
{
|
||||
result.errors.push(ValidationError {
|
||||
code: "PATTERN_VIOLATED".to_string(),
|
||||
message: format!("Pattern mismatch {}", pattern),
|
||||
path: self.path.to_string(),
|
||||
});
|
||||
}
|
||||
}
|
||||
Ok(true)
|
||||
}
|
||||
}
|
||||
53
src/validator/rules/util.rs
Normal file
53
src/validator/rules/util.rs
Normal file
@ -0,0 +1,53 @@
|
||||
use serde_json::Value;
|
||||
|
||||
pub fn is_integer(v: &Value) -> bool {
|
||||
match v {
|
||||
Value::Number(n) => {
|
||||
n.is_i64() || n.is_u64() || n.as_f64().filter(|n| n.fract() == 0.0).is_some()
|
||||
}
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// serde_json treats 0 and 0.0 not equal. so we cannot simply use v1==v2
|
||||
pub fn equals(v1: &Value, v2: &Value) -> bool {
|
||||
match (v1, v2) {
|
||||
(Value::Null, Value::Null) => true,
|
||||
(Value::Bool(b1), Value::Bool(b2)) => b1 == b2,
|
||||
(Value::Number(n1), Value::Number(n2)) => {
|
||||
if let (Some(n1), Some(n2)) = (n1.as_u64(), n2.as_u64()) {
|
||||
return n1 == n2;
|
||||
}
|
||||
if let (Some(n1), Some(n2)) = (n1.as_i64(), n2.as_i64()) {
|
||||
return n1 == n2;
|
||||
}
|
||||
if let (Some(n1), Some(n2)) = (n1.as_f64(), n2.as_f64()) {
|
||||
return (n1 - n2).abs() < f64::EPSILON;
|
||||
}
|
||||
false
|
||||
}
|
||||
(Value::String(s1), Value::String(s2)) => s1 == s2,
|
||||
(Value::Array(arr1), Value::Array(arr2)) => {
|
||||
if arr1.len() != arr2.len() {
|
||||
return false;
|
||||
}
|
||||
arr1.iter().zip(arr2).all(|(e1, e2)| equals(e1, e2))
|
||||
}
|
||||
(Value::Object(obj1), Value::Object(obj2)) => {
|
||||
if obj1.len() != obj2.len() {
|
||||
return false;
|
||||
}
|
||||
for (k1, v1) in obj1 {
|
||||
if let Some(v2) = obj2.get(k1) {
|
||||
if !equals(v1, v2) {
|
||||
return false;
|
||||
}
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
true
|
||||
}
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
127
src/validator/util.rs
Normal file
127
src/validator/util.rs
Normal file
@ -0,0 +1,127 @@
|
||||
use serde::Deserialize;
|
||||
use std::fs;
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct TestSuite {
|
||||
#[allow(dead_code)]
|
||||
description: String,
|
||||
database: serde_json::Value,
|
||||
tests: Vec<TestCase>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
pub struct TestCase {
|
||||
pub description: String,
|
||||
|
||||
#[serde(default = "default_action")]
|
||||
pub action: String, // "validate", "merge", or "query"
|
||||
|
||||
// For Validate & Query
|
||||
#[serde(default)]
|
||||
pub schema_id: String,
|
||||
|
||||
// For Query
|
||||
#[serde(default)]
|
||||
pub stem: Option<String>,
|
||||
|
||||
#[serde(default)]
|
||||
pub filters: Option<serde_json::Value>,
|
||||
|
||||
// For Merge & Validate
|
||||
#[serde(default)]
|
||||
pub data: Option<serde_json::Value>,
|
||||
|
||||
// For Merge & Query mocks
|
||||
#[serde(default)]
|
||||
pub mocks: Option<serde_json::Value>,
|
||||
|
||||
pub expect: Option<ExpectBlock>,
|
||||
|
||||
// Legacy support for older tests to avoid migrating them all instantly
|
||||
pub valid: Option<bool>,
|
||||
pub expect_errors: Option<Vec<serde_json::Value>>,
|
||||
}
|
||||
|
||||
fn default_action() -> String {
|
||||
"validate".to_string()
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
pub struct ExpectBlock {
|
||||
pub success: bool,
|
||||
pub result: Option<serde_json::Value>,
|
||||
pub errors: Option<Vec<serde_json::Value>>,
|
||||
pub sql_patterns: Option<Vec<String>>,
|
||||
}
|
||||
|
||||
// use crate::validator::registry::REGISTRY; // No longer used directly for tests!
|
||||
use crate::validator::Validator;
|
||||
use serde_json::Value;
|
||||
|
||||
pub fn deserialize_some<'de, D>(deserializer: D) -> Result<Option<Value>, D::Error>
|
||||
where
|
||||
D: serde::Deserializer<'de>,
|
||||
{
|
||||
let v = Value::deserialize(deserializer)?;
|
||||
Ok(Some(v))
|
||||
}
|
||||
|
||||
pub fn run_test_file_at_index(path: &str, index: usize) -> Result<(), String> {
|
||||
let content =
|
||||
fs::read_to_string(path).unwrap_or_else(|_| panic!("Failed to read file: {}", path));
|
||||
let suite: Vec<TestSuite> = serde_json::from_str(&content)
|
||||
.unwrap_or_else(|e| panic!("Failed to parse JSON in {}: {}", path, e));
|
||||
|
||||
if index >= suite.len() {
|
||||
panic!("Index {} out of bounds for file {}", index, path);
|
||||
}
|
||||
|
||||
let group = &suite[index];
|
||||
let mut failures = Vec::<String>::new();
|
||||
|
||||
let db_json = group.database.clone();
|
||||
let db = crate::database::Database::new(&db_json);
|
||||
let validator = Validator::new(std::sync::Arc::new(db));
|
||||
|
||||
// 4. Run Tests
|
||||
for test in group.tests.iter() {
|
||||
let schema_id = &test.schema_id;
|
||||
|
||||
if !validator.db.schemas.contains_key(schema_id) {
|
||||
failures.push(format!(
|
||||
"[{}] Missing Schema: Cannot find schema ID '{}'",
|
||||
group.description, schema_id
|
||||
));
|
||||
continue;
|
||||
}
|
||||
|
||||
let result = validator.validate(schema_id, &test.data);
|
||||
|
||||
let (got_valid, _errors) = match &result {
|
||||
Ok(res) => (res.is_valid(), &res.errors),
|
||||
Err(_e) => {
|
||||
// If we encounter an execution error (e.g. Schema Not Found),
|
||||
// we treat it as a test failure.
|
||||
(false, &vec![])
|
||||
}
|
||||
};
|
||||
|
||||
if got_valid != test.valid {
|
||||
let error_msg = match &result {
|
||||
Ok(res) => format!("{:?}", res.errors),
|
||||
Err(e) => format!("Execution Error: {:?}", e),
|
||||
};
|
||||
|
||||
failures.push(format!(
|
||||
"[{}] Test '{}' failed. Expected: {}, Got: {}. Errors: {}",
|
||||
group.description, test.description, test.valid, got_valid, error_msg
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
if !failures.is_empty() {
|
||||
return Err(failures.join("\n"));
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
62
test_err.log
Normal file
62
test_err.log
Normal file
@ -0,0 +1,62 @@
|
||||
Compiling jspg v0.1.0 (/Users/awgneo/Repositories/thoughtpatterns/cellular/jspg)
|
||||
Finished `test` profile [unoptimized + debuginfo] target(s) in 26.14s
|
||||
Running unittests src/lib.rs (target/debug/deps/jspg-99ace086c3537f5a)
|
||||
|
||||
running 1 test
|
||||
[32m[1m Using[0m[39m [37m[1mPgConfig("pg18")[0m[39m and `pg_config` from [36m/opt/homebrew/opt/postgresql@18/bin/pg_config[39m
|
||||
[32m[1m Building[0m[39m extension with features [36mpg_test pg18[39m
|
||||
[32m[1m Running[0m[39m command [36m"/opt/homebrew/bin/cargo" "build" "--lib" "--features" "pg_test pg18" "--no-default-features" "--message-format=json-render-diagnostics"[39m
|
||||
Compiling jspg v0.1.0 (/Users/awgneo/Repositories/thoughtpatterns/cellular/jspg)
|
||||
Finished `dev` profile [unoptimized + debuginfo] target(s) in 7.10s
|
||||
[32m[1m Installing[0m[39m extension
|
||||
[32m[1m Copying[0m[39m control file to [36m/opt/homebrew/share/postgresql@18/extension/jspg.control[39m
|
||||
[32m[1m Copying[0m[39m shared library to [36m/opt/homebrew/lib/postgresql@18/jspg.dylib[39m
|
||||
[32m[1m Discovered[0m[39m [36m[1m351[0m[39m SQL entities: [36m[1m1[0m[39m schemas ([36m[1m1[0m[39m unique), [36m[1m350[0m[39m functions, [36m[1m0[0m[39m types, [36m[1m0[0m[39m enums, [36m[1m0[0m[39m sqls, [36m[1m0[0m[39m ords, [36m[1m0[0m[39m hashes, [36m[1m0[0m[39m aggregates, [36m[1m0[0m[39m triggers
|
||||
[32m[1m Rebuilding[0m[39m [36mpgrx_embed[39m, in debug mode, for SQL generation with features [36mpg_test pg18[39m
|
||||
Compiling jspg v0.1.0 (/Users/awgneo/Repositories/thoughtpatterns/cellular/jspg)
|
||||
Finished `dev` profile [unoptimized + debuginfo] target(s) in 10.63s
|
||||
[32m[1m Writing[0m[39m SQL entities to /opt/homebrew/share/postgresql@18/extension/jspg--0.1.0.sql
|
||||
[32m[1m Finished[0m[39m installing jspg
|
||||
[36m[2026-03-01 22:54:19.068 EST] [82952] [69a509eb.14408]: LOG: starting PostgreSQL 18.1 (Homebrew) on aarch64-apple-darwin25.2.0, compiled by Apple clang version 17.0.0 (clang-1700.6.3.2), 64-bit[39m
|
||||
[36m[2026-03-01 22:54:19.070 EST] [82952] [69a509eb.14408]: LOG: listening on IPv6 address "::1", port 32218[39m
|
||||
[36m[2026-03-01 22:54:19.070 EST] [82952] [69a509eb.14408]: LOG: listening on IPv4 address "127.0.0.1", port 32218[39m
|
||||
[36m[2026-03-01 22:54:19.071 EST] [82952] [69a509eb.14408]: LOG: listening on Unix socket "/Users/awgneo/Repositories/thoughtpatterns/cellular/jspg/target/test-pgdata/.s.PGSQL.32218"[39m
|
||||
[36m[2026-03-01 22:54:19.077 EST] [82958] [69a509eb.1440e]: LOG: database system was shut down at 2026-03-01 22:49:02 EST[39m
|
||||
[32m[1m Creating[0m[39m database [36m[1mpgrx_tests[0m[39m
|
||||
|
||||
thread 'tests::pg_test_typed_refs_0' (29092254) panicked at /Users/awgneo/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/pgrx-tests-0.16.1/src/framework.rs:166:9:
|
||||
|
||||
|
||||
Postgres Messages:
|
||||
[37m[2m[2026-03-01 22:54:19.068 EST] [82952] [69a509eb.14408]: LOG: starting PostgreSQL 18.1 (Homebrew) on aarch64-apple-darwin25.2.0, compiled by Apple clang version 17.0.0 (clang-1700.6.3.2), 64-bit
|
||||
[2026-03-01 22:54:19.070 EST] [82952] [69a509eb.14408]: LOG: listening on IPv6 address "::1", port 32218
|
||||
[2026-03-01 22:54:19.070 EST] [82952] [69a509eb.14408]: LOG: listening on IPv4 address "127.0.0.1", port 32218
|
||||
[2026-03-01 22:54:19.071 EST] [82952] [69a509eb.14408]: LOG: listening on Unix socket "/Users/awgneo/Repositories/thoughtpatterns/cellular/jspg/target/test-pgdata/.s.PGSQL.32218"
|
||||
[2026-03-01 22:54:19.081 EST] [82952] [69a509eb.14408]: LOG: database system is ready to accept connections
|
||||
[0m[39m
|
||||
|
||||
Test Function Messages:
|
||||
[36m[2026-03-01 22:54:20.058 EST] [82982] [69a509ec.14426]: LOG: statement: START TRANSACTION
|
||||
[2026-03-01 22:54:20.058 EST] [82982] [69a509ec.14426]: LOG: statement: SELECT "tests"."test_typed_refs_0"();
|
||||
[2026-03-01 22:54:20.062 EST] [82982] [69a509ec.14426]: ERROR: called `Result::unwrap()` on an `Err` value: "[Entity inheritance and native type discrimination] Test 'Valid person against organization schema (implicit type allowance)' failed. Expected: true, Got: false. Errors: [ValidationError { code: \"CONST_VIOLATED\", message: \"Value does not match const\", path: \"/type\" }, ValidationError { code: \"STRICT_PROPERTY_VIOLATION\", message: \"Unexpected property 'first_name'\", path: \"/first_name\" }, ValidationError { code: \"STRICT_PROPERTY_VIOLATION\", message: \"Unexpected property 'first_name'\", path: \"/first_name\" }, ValidationError { code: \"STRICT_PROPERTY_VIOLATION\", message: \"Unexpected property 'first_name'\", path: \"/first_name\" }]\n[Entity inheritance and native type discrimination] Test 'Valid organization against organization schema' failed. Expected: true, Got: false. Errors: [ValidationError { code: \"CONST_VIOLATED\", message: \"Value does not match const\", path: \"/type\" }]\n[Entity inheritance and native type discrimination] Test 'Invalid entity against organization schema (ancestor not allowed)' failed. Expected: false, Got: true. Errors: []"
|
||||
[2026-03-01 22:54:20.062 EST] [82982] [69a509ec.14426]: STATEMENT: SELECT "tests"."test_typed_refs_0"();
|
||||
[2026-03-01 22:54:20.062 EST] [82982] [69a509ec.14426]: LOG: statement: ROLLBACK
|
||||
[39m
|
||||
|
||||
Client Error:
|
||||
[31m[1mcalled `Result::unwrap()` on an `Err` value: "[Entity inheritance and native type discrimination] Test 'Valid person against organization schema (implicit type allowance)' failed. Expected: true, Got: false. Errors: [ValidationError { code: \"CONST_VIOLATED\", message: \"Value does not match const\", path: \"/type\" }, ValidationError { code: \"STRICT_PROPERTY_VIOLATION\", message: \"Unexpected property 'first_name'\", path: \"/first_name\" }, ValidationError { code: \"STRICT_PROPERTY_VIOLATION\", message: \"Unexpected property 'first_name'\", path: \"/first_name\" }, ValidationError { code: \"STRICT_PROPERTY_VIOLATION\", message: \"Unexpected property 'first_name'\", path: \"/first_name\" }]\n[Entity inheritance and native type discrimination] Test 'Valid organization against organization schema' failed. Expected: true, Got: false. Errors: [ValidationError { code: \"CONST_VIOLATED\", message: \"Value does not match const\", path: \"/type\" }]\n[Entity inheritance and native type discrimination] Test 'Invalid entity against organization schema (ancestor not allowed)' failed. Expected: false, Got: true. Errors: []"[0m[39m
|
||||
postgres location: [37m[2mfixtures.rs[0m[39m
|
||||
rust location: [33m<unknown>[39m
|
||||
|
||||
|
||||
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
|
||||
test tests::pg_test_typed_refs_0 ... FAILED
|
||||
|
||||
failures:
|
||||
|
||||
failures:
|
||||
tests::pg_test_typed_refs_0
|
||||
|
||||
test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 343 filtered out; finished in 21.82s
|
||||
|
||||
error: test failed, to rerun pass `--lib`
|
||||
43
tests/database/executor.rs
Normal file
43
tests/database/executor.rs
Normal file
@ -0,0 +1,43 @@
|
||||
use jspg::database::executor::DatabaseExecutor;
|
||||
use serde_json::Value;
|
||||
use std::sync::Mutex;
|
||||
|
||||
pub struct MockExecutor {
|
||||
pub query_responses: Mutex<Vec<Result<Value, String>>>,
|
||||
pub execute_responses: Mutex<Vec<Result<(), String>>>,
|
||||
}
|
||||
|
||||
impl MockExecutor {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
query_responses: Mutex::new(Vec::new()),
|
||||
execute_responses: Mutex::new(Vec::new()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl DatabaseExecutor for MockExecutor {
|
||||
fn query(&self, _sql: &str, _args: Option<&[Value]>) -> Result<Value, String> {
|
||||
let mut responses = self.query_responses.lock().unwrap();
|
||||
if responses.is_empty() {
|
||||
return Ok(Value::Array(vec![]));
|
||||
}
|
||||
responses.remove(0)
|
||||
}
|
||||
|
||||
fn execute(&self, _sql: &str, _args: Option<&[Value]>) -> Result<(), String> {
|
||||
let mut responses = self.execute_responses.lock().unwrap();
|
||||
if responses.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
responses.remove(0)
|
||||
}
|
||||
|
||||
fn auth_user_id(&self) -> Result<String, String> {
|
||||
Ok("00000000-0000-0000-0000-000000000000".to_string())
|
||||
}
|
||||
|
||||
fn timestamp(&self) -> Result<String, String> {
|
||||
Ok("2026-03-10T00:00:00Z".to_string())
|
||||
}
|
||||
}
|
||||
1
tests/database/mod.rs
Normal file
1
tests/database/mod.rs
Normal file
@ -0,0 +1 @@
|
||||
pub mod executor;
|
||||
1669
tests/fixtures.rs
Normal file
1669
tests/fixtures.rs
Normal file
File diff suppressed because it is too large
Load Diff
152
tests/fixtures/additionalProperties.json
vendored
Normal file
152
tests/fixtures/additionalProperties.json
vendored
Normal file
@ -0,0 +1,152 @@
|
||||
[
|
||||
{
|
||||
"description": "additionalProperties validates properties not matched by properties",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"$id": "schema1",
|
||||
"properties": {
|
||||
"foo": {
|
||||
"type": "string"
|
||||
},
|
||||
"bar": {
|
||||
"type": "number"
|
||||
}
|
||||
},
|
||||
"additionalProperties": {
|
||||
"type": "boolean"
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "defined properties are valid",
|
||||
"data": {
|
||||
"foo": "value",
|
||||
"bar": 123
|
||||
},
|
||||
"valid": true,
|
||||
"schema_id": "schema1"
|
||||
},
|
||||
{
|
||||
"description": "additional property matching schema is valid",
|
||||
"data": {
|
||||
"foo": "value",
|
||||
"is_active": true,
|
||||
"hidden": false
|
||||
},
|
||||
"valid": true,
|
||||
"schema_id": "schema1"
|
||||
},
|
||||
{
|
||||
"description": "additional property not matching schema is invalid",
|
||||
"data": {
|
||||
"foo": "value",
|
||||
"is_active": 1
|
||||
},
|
||||
"valid": false,
|
||||
"schema_id": "schema1"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "extensible: true with additionalProperties still validates structure",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"properties": {
|
||||
"foo": {
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"extensible": true,
|
||||
"additionalProperties": {
|
||||
"type": "integer"
|
||||
},
|
||||
"$id": "additionalProperties_1_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "additional property matching schema is valid",
|
||||
"data": {
|
||||
"foo": "hello",
|
||||
"count": 5,
|
||||
"age": 42
|
||||
},
|
||||
"valid": true,
|
||||
"schema_id": "additionalProperties_1_0"
|
||||
},
|
||||
{
|
||||
"description": "additional property not matching schema is invalid despite extensible: true",
|
||||
"data": {
|
||||
"foo": "hello",
|
||||
"count": "five"
|
||||
},
|
||||
"valid": false,
|
||||
"schema_id": "additionalProperties_1_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "complex additionalProperties with object and array items",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"$id": "schema3",
|
||||
"properties": {
|
||||
"type": {
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"additionalProperties": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "valid array of strings",
|
||||
"data": {
|
||||
"type": "my_type",
|
||||
"group_a": [
|
||||
"field1",
|
||||
"field2"
|
||||
],
|
||||
"group_b": [
|
||||
"field3"
|
||||
]
|
||||
},
|
||||
"valid": true,
|
||||
"schema_id": "schema3"
|
||||
},
|
||||
{
|
||||
"description": "invalid array of integers",
|
||||
"data": {
|
||||
"type": "my_type",
|
||||
"group_a": [
|
||||
1,
|
||||
2
|
||||
]
|
||||
},
|
||||
"valid": false,
|
||||
"schema_id": "schema3"
|
||||
},
|
||||
{
|
||||
"description": "invalid non-array type",
|
||||
"data": {
|
||||
"type": "my_type",
|
||||
"group_a": "field1"
|
||||
},
|
||||
"valid": false,
|
||||
"schema_id": "schema3"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
590
tests/fixtures/allOf.json
vendored
Normal file
590
tests/fixtures/allOf.json
vendored
Normal file
@ -0,0 +1,590 @@
|
||||
[
|
||||
{
|
||||
"description": "allOf",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"allOf": [
|
||||
{
|
||||
"properties": {
|
||||
"bar": {
|
||||
"type": "integer"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"bar"
|
||||
]
|
||||
},
|
||||
{
|
||||
"properties": {
|
||||
"foo": {
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"foo"
|
||||
]
|
||||
}
|
||||
],
|
||||
"$id": "allOf_0_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "allOf",
|
||||
"data": {
|
||||
"foo": "baz",
|
||||
"bar": 2
|
||||
},
|
||||
"valid": true,
|
||||
"schema_id": "allOf_0_0"
|
||||
},
|
||||
{
|
||||
"description": "mismatch second",
|
||||
"data": {
|
||||
"foo": "baz"
|
||||
},
|
||||
"valid": false,
|
||||
"schema_id": "allOf_0_0"
|
||||
},
|
||||
{
|
||||
"description": "mismatch first",
|
||||
"data": {
|
||||
"bar": 2
|
||||
},
|
||||
"valid": false,
|
||||
"schema_id": "allOf_0_0"
|
||||
},
|
||||
{
|
||||
"description": "wrong type",
|
||||
"data": {
|
||||
"foo": "baz",
|
||||
"bar": "quux"
|
||||
},
|
||||
"valid": false,
|
||||
"schema_id": "allOf_0_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "allOf with base schema",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"properties": {
|
||||
"bar": {
|
||||
"type": "integer"
|
||||
},
|
||||
"baz": {},
|
||||
"foo": {
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"bar"
|
||||
],
|
||||
"allOf": [
|
||||
{
|
||||
"properties": {
|
||||
"foo": {
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"foo"
|
||||
]
|
||||
},
|
||||
{
|
||||
"properties": {
|
||||
"baz": {
|
||||
"type": "null"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"baz"
|
||||
]
|
||||
}
|
||||
],
|
||||
"$id": "allOf_1_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "valid",
|
||||
"data": {
|
||||
"foo": "quux",
|
||||
"bar": 2,
|
||||
"baz": null
|
||||
},
|
||||
"valid": true,
|
||||
"schema_id": "allOf_1_0"
|
||||
},
|
||||
{
|
||||
"description": "mismatch base schema",
|
||||
"data": {
|
||||
"foo": "quux",
|
||||
"baz": null
|
||||
},
|
||||
"valid": false,
|
||||
"schema_id": "allOf_1_0"
|
||||
},
|
||||
{
|
||||
"description": "mismatch first allOf",
|
||||
"data": {
|
||||
"bar": 2,
|
||||
"baz": null
|
||||
},
|
||||
"valid": false,
|
||||
"schema_id": "allOf_1_0"
|
||||
},
|
||||
{
|
||||
"description": "mismatch second allOf",
|
||||
"data": {
|
||||
"foo": "quux",
|
||||
"bar": 2
|
||||
},
|
||||
"valid": false,
|
||||
"schema_id": "allOf_1_0"
|
||||
},
|
||||
{
|
||||
"description": "mismatch both",
|
||||
"data": {
|
||||
"bar": 2
|
||||
},
|
||||
"valid": false,
|
||||
"schema_id": "allOf_1_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "allOf simple types",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"allOf": [
|
||||
{
|
||||
"maximum": 30
|
||||
},
|
||||
{
|
||||
"minimum": 20
|
||||
}
|
||||
],
|
||||
"$id": "allOf_2_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "valid",
|
||||
"data": 25,
|
||||
"valid": true,
|
||||
"schema_id": "allOf_2_0"
|
||||
},
|
||||
{
|
||||
"description": "mismatch one",
|
||||
"data": 35,
|
||||
"valid": false,
|
||||
"schema_id": "allOf_2_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "allOf with boolean schemas, all true",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"allOf": [
|
||||
true,
|
||||
true
|
||||
],
|
||||
"$id": "allOf_3_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "any value is valid",
|
||||
"data": "foo",
|
||||
"valid": true,
|
||||
"schema_id": "allOf_3_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "allOf with boolean schemas, some false",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"allOf": [
|
||||
true,
|
||||
false
|
||||
],
|
||||
"$id": "allOf_4_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "any value is invalid",
|
||||
"data": "foo",
|
||||
"valid": false,
|
||||
"schema_id": "allOf_4_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "allOf with boolean schemas, all false",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"allOf": [
|
||||
false,
|
||||
false
|
||||
],
|
||||
"$id": "allOf_5_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "any value is invalid",
|
||||
"data": "foo",
|
||||
"valid": false,
|
||||
"schema_id": "allOf_5_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "allOf with one empty schema",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"allOf": [
|
||||
{}
|
||||
],
|
||||
"$id": "allOf_6_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "any data is valid",
|
||||
"data": 1,
|
||||
"valid": true,
|
||||
"schema_id": "allOf_6_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "allOf with two empty schemas",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"allOf": [
|
||||
{},
|
||||
{}
|
||||
],
|
||||
"$id": "allOf_7_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "any data is valid",
|
||||
"data": 1,
|
||||
"valid": true,
|
||||
"schema_id": "allOf_7_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "allOf with the first empty schema",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"allOf": [
|
||||
{},
|
||||
{
|
||||
"type": "number"
|
||||
}
|
||||
],
|
||||
"$id": "allOf_8_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "number is valid",
|
||||
"data": 1,
|
||||
"valid": true,
|
||||
"schema_id": "allOf_8_0"
|
||||
},
|
||||
{
|
||||
"description": "string is invalid",
|
||||
"data": "foo",
|
||||
"valid": false,
|
||||
"schema_id": "allOf_8_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "allOf with the last empty schema",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"allOf": [
|
||||
{
|
||||
"type": "number"
|
||||
},
|
||||
{}
|
||||
],
|
||||
"$id": "allOf_9_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "number is valid",
|
||||
"data": 1,
|
||||
"valid": true,
|
||||
"schema_id": "allOf_9_0"
|
||||
},
|
||||
{
|
||||
"description": "string is invalid",
|
||||
"data": "foo",
|
||||
"valid": false,
|
||||
"schema_id": "allOf_9_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "nested allOf, to check validation semantics",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"allOf": [
|
||||
{
|
||||
"allOf": [
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"$id": "allOf_10_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "null is valid",
|
||||
"data": null,
|
||||
"valid": true,
|
||||
"schema_id": "allOf_10_0"
|
||||
},
|
||||
{
|
||||
"description": "anything non-null is invalid",
|
||||
"data": 123,
|
||||
"valid": false,
|
||||
"schema_id": "allOf_10_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "extensible: true allows extra properties in allOf",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"allOf": [
|
||||
{
|
||||
"properties": {
|
||||
"bar": {
|
||||
"type": "integer"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"bar"
|
||||
]
|
||||
},
|
||||
{
|
||||
"properties": {
|
||||
"foo": {
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"foo"
|
||||
]
|
||||
}
|
||||
],
|
||||
"extensible": true,
|
||||
"$id": "allOf_12_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "extra property is valid",
|
||||
"data": {
|
||||
"foo": "baz",
|
||||
"bar": 2,
|
||||
"qux": 3
|
||||
},
|
||||
"valid": true,
|
||||
"schema_id": "allOf_12_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "strict by default with allOf properties",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"allOf": [
|
||||
{
|
||||
"properties": {
|
||||
"foo": {
|
||||
"const": 1
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"properties": {
|
||||
"bar": {
|
||||
"const": 2
|
||||
}
|
||||
}
|
||||
}
|
||||
],
|
||||
"$id": "allOf_13_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "validates merged properties",
|
||||
"data": {
|
||||
"foo": 1,
|
||||
"bar": 2
|
||||
},
|
||||
"valid": true,
|
||||
"schema_id": "allOf_13_0"
|
||||
},
|
||||
{
|
||||
"description": "fails on extra property z explicitly",
|
||||
"data": {
|
||||
"foo": 1,
|
||||
"bar": 2,
|
||||
"z": 3
|
||||
},
|
||||
"valid": false,
|
||||
"schema_id": "allOf_13_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "allOf with nested extensible: true (partial looseness)",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"allOf": [
|
||||
{
|
||||
"properties": {
|
||||
"foo": {
|
||||
"const": 1
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"extensible": true,
|
||||
"properties": {
|
||||
"bar": {
|
||||
"const": 2
|
||||
}
|
||||
}
|
||||
}
|
||||
],
|
||||
"$id": "allOf_14_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "extensible subschema doesn't make root extensible if root is strict",
|
||||
"data": {
|
||||
"foo": 1,
|
||||
"bar": 2,
|
||||
"z": 3
|
||||
},
|
||||
"valid": true,
|
||||
"schema_id": "allOf_14_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "strictness: allOf composition with strict refs",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"allOf": [
|
||||
{
|
||||
"$ref": "partA"
|
||||
},
|
||||
{
|
||||
"$ref": "partB"
|
||||
}
|
||||
],
|
||||
"$id": "allOf_15_0"
|
||||
},
|
||||
{
|
||||
"$id": "partA",
|
||||
"properties": {
|
||||
"id": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"$id": "partB",
|
||||
"properties": {
|
||||
"name": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "merged instance is valid",
|
||||
"data": {
|
||||
"id": "1",
|
||||
"name": "Me"
|
||||
},
|
||||
"valid": true,
|
||||
"schema_id": "allOf_15_0"
|
||||
},
|
||||
{
|
||||
"description": "extra property is invalid (root is strict)",
|
||||
"data": {
|
||||
"id": "1",
|
||||
"name": "Me",
|
||||
"extra": 1
|
||||
},
|
||||
"valid": false,
|
||||
"schema_id": "allOf_15_0"
|
||||
},
|
||||
{
|
||||
"description": "partA mismatch is invalid",
|
||||
"data": {
|
||||
"id": 1,
|
||||
"name": "Me"
|
||||
},
|
||||
"valid": false,
|
||||
"schema_id": "allOf_15_0"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
143
tests/fixtures/booleanSchema.json
vendored
Normal file
143
tests/fixtures/booleanSchema.json
vendored
Normal file
@ -0,0 +1,143 @@
|
||||
[
|
||||
{
|
||||
"description": "boolean schema 'true'",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"$id": "booleanSchema_0_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "number is valid",
|
||||
"data": 1,
|
||||
"valid": true,
|
||||
"schema_id": "booleanSchema_0_0"
|
||||
},
|
||||
{
|
||||
"description": "string is valid",
|
||||
"data": "foo",
|
||||
"valid": true,
|
||||
"schema_id": "booleanSchema_0_0"
|
||||
},
|
||||
{
|
||||
"description": "boolean true is valid",
|
||||
"data": true,
|
||||
"valid": true,
|
||||
"schema_id": "booleanSchema_0_0"
|
||||
},
|
||||
{
|
||||
"description": "boolean false is valid",
|
||||
"data": false,
|
||||
"valid": true,
|
||||
"schema_id": "booleanSchema_0_0"
|
||||
},
|
||||
{
|
||||
"description": "null is valid",
|
||||
"data": null,
|
||||
"valid": true,
|
||||
"schema_id": "booleanSchema_0_0"
|
||||
},
|
||||
{
|
||||
"description": "object is valid",
|
||||
"data": {
|
||||
"foo": "bar"
|
||||
},
|
||||
"valid": true,
|
||||
"schema_id": "booleanSchema_0_0"
|
||||
},
|
||||
{
|
||||
"description": "empty object is valid",
|
||||
"data": {},
|
||||
"valid": true,
|
||||
"schema_id": "booleanSchema_0_0"
|
||||
},
|
||||
{
|
||||
"description": "array is valid",
|
||||
"data": [
|
||||
"foo"
|
||||
],
|
||||
"valid": true,
|
||||
"schema_id": "booleanSchema_0_0"
|
||||
},
|
||||
{
|
||||
"description": "empty array is valid",
|
||||
"data": [],
|
||||
"valid": true,
|
||||
"schema_id": "booleanSchema_0_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "boolean schema 'false'",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"not": {},
|
||||
"$id": "booleanSchema_1_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "number is invalid",
|
||||
"data": 1,
|
||||
"valid": false,
|
||||
"schema_id": "booleanSchema_1_0"
|
||||
},
|
||||
{
|
||||
"description": "string is invalid",
|
||||
"data": "foo",
|
||||
"valid": false,
|
||||
"schema_id": "booleanSchema_1_0"
|
||||
},
|
||||
{
|
||||
"description": "boolean true is invalid",
|
||||
"data": true,
|
||||
"valid": false,
|
||||
"schema_id": "booleanSchema_1_0"
|
||||
},
|
||||
{
|
||||
"description": "boolean false is invalid",
|
||||
"data": false,
|
||||
"valid": false,
|
||||
"schema_id": "booleanSchema_1_0"
|
||||
},
|
||||
{
|
||||
"description": "null is invalid",
|
||||
"data": null,
|
||||
"valid": false,
|
||||
"schema_id": "booleanSchema_1_0"
|
||||
},
|
||||
{
|
||||
"description": "object is invalid",
|
||||
"data": {
|
||||
"foo": "bar"
|
||||
},
|
||||
"valid": false,
|
||||
"schema_id": "booleanSchema_1_0"
|
||||
},
|
||||
{
|
||||
"description": "empty object is invalid",
|
||||
"data": {},
|
||||
"valid": false,
|
||||
"schema_id": "booleanSchema_1_0"
|
||||
},
|
||||
{
|
||||
"description": "array is invalid",
|
||||
"data": [
|
||||
"foo"
|
||||
],
|
||||
"valid": false,
|
||||
"schema_id": "booleanSchema_1_0"
|
||||
},
|
||||
{
|
||||
"description": "empty array is invalid",
|
||||
"data": [],
|
||||
"valid": false,
|
||||
"schema_id": "booleanSchema_1_0"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
650
tests/fixtures/const.json
vendored
Normal file
650
tests/fixtures/const.json
vendored
Normal file
@ -0,0 +1,650 @@
|
||||
[
|
||||
{
|
||||
"description": "const validation",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"const": 2,
|
||||
"$id": "const_0_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "same value is valid",
|
||||
"data": 2,
|
||||
"valid": true,
|
||||
"schema_id": "const_0_0"
|
||||
},
|
||||
{
|
||||
"description": "another value is invalid",
|
||||
"data": 5,
|
||||
"valid": false,
|
||||
"schema_id": "const_0_0"
|
||||
},
|
||||
{
|
||||
"description": "another type is invalid",
|
||||
"data": "a",
|
||||
"valid": false,
|
||||
"schema_id": "const_0_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "const with object",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"const": {
|
||||
"foo": "bar",
|
||||
"baz": "bax"
|
||||
},
|
||||
"properties": {
|
||||
"foo": {},
|
||||
"baz": {}
|
||||
},
|
||||
"$id": "const_1_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "same object is valid",
|
||||
"data": {
|
||||
"foo": "bar",
|
||||
"baz": "bax"
|
||||
},
|
||||
"valid": true,
|
||||
"schema_id": "const_1_0"
|
||||
},
|
||||
{
|
||||
"description": "same object with different property order is valid",
|
||||
"data": {
|
||||
"baz": "bax",
|
||||
"foo": "bar"
|
||||
},
|
||||
"valid": true,
|
||||
"schema_id": "const_1_0"
|
||||
},
|
||||
{
|
||||
"description": "another object is invalid",
|
||||
"data": {
|
||||
"foo": "bar"
|
||||
},
|
||||
"valid": false,
|
||||
"schema_id": "const_1_0"
|
||||
},
|
||||
{
|
||||
"description": "another type is invalid",
|
||||
"data": [
|
||||
1,
|
||||
2
|
||||
],
|
||||
"valid": false,
|
||||
"schema_id": "const_1_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "const with array",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"const": [
|
||||
{
|
||||
"foo": "bar"
|
||||
}
|
||||
],
|
||||
"$id": "const_2_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "same array is valid",
|
||||
"data": [
|
||||
{
|
||||
"foo": "bar"
|
||||
}
|
||||
],
|
||||
"valid": true,
|
||||
"schema_id": "const_2_0"
|
||||
},
|
||||
{
|
||||
"description": "another array item is invalid",
|
||||
"data": [
|
||||
2
|
||||
],
|
||||
"valid": false,
|
||||
"schema_id": "const_2_0"
|
||||
},
|
||||
{
|
||||
"description": "array with additional items is invalid",
|
||||
"data": [
|
||||
1,
|
||||
2,
|
||||
3
|
||||
],
|
||||
"valid": false,
|
||||
"schema_id": "const_2_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "const with null",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"const": null,
|
||||
"$id": "const_3_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "null is valid",
|
||||
"data": null,
|
||||
"valid": true,
|
||||
"schema_id": "const_3_0"
|
||||
},
|
||||
{
|
||||
"description": "not null is invalid",
|
||||
"data": 0,
|
||||
"valid": false,
|
||||
"schema_id": "const_3_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "const with false does not match 0",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"const": false,
|
||||
"$id": "const_4_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "false is valid",
|
||||
"data": false,
|
||||
"valid": true,
|
||||
"schema_id": "const_4_0"
|
||||
},
|
||||
{
|
||||
"description": "integer zero is invalid",
|
||||
"data": 0,
|
||||
"valid": false,
|
||||
"schema_id": "const_4_0"
|
||||
},
|
||||
{
|
||||
"description": "float zero is invalid",
|
||||
"data": 0,
|
||||
"valid": false,
|
||||
"schema_id": "const_4_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "const with true does not match 1",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"const": true,
|
||||
"$id": "const_5_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "true is valid",
|
||||
"data": true,
|
||||
"valid": true,
|
||||
"schema_id": "const_5_0"
|
||||
},
|
||||
{
|
||||
"description": "integer one is invalid",
|
||||
"data": 1,
|
||||
"valid": false,
|
||||
"schema_id": "const_5_0"
|
||||
},
|
||||
{
|
||||
"description": "float one is invalid",
|
||||
"data": 1,
|
||||
"valid": false,
|
||||
"schema_id": "const_5_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "const with [false] does not match [0]",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"const": [
|
||||
false
|
||||
],
|
||||
"$id": "const_6_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "[false] is valid",
|
||||
"data": [
|
||||
false
|
||||
],
|
||||
"valid": true,
|
||||
"schema_id": "const_6_0"
|
||||
},
|
||||
{
|
||||
"description": "[0] is invalid",
|
||||
"data": [
|
||||
0
|
||||
],
|
||||
"valid": false,
|
||||
"schema_id": "const_6_0"
|
||||
},
|
||||
{
|
||||
"description": "[0.0] is invalid",
|
||||
"data": [
|
||||
0
|
||||
],
|
||||
"valid": false,
|
||||
"schema_id": "const_6_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "const with [true] does not match [1]",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"const": [
|
||||
true
|
||||
],
|
||||
"$id": "const_7_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "[true] is valid",
|
||||
"data": [
|
||||
true
|
||||
],
|
||||
"valid": true,
|
||||
"schema_id": "const_7_0"
|
||||
},
|
||||
{
|
||||
"description": "[1] is invalid",
|
||||
"data": [
|
||||
1
|
||||
],
|
||||
"valid": false,
|
||||
"schema_id": "const_7_0"
|
||||
},
|
||||
{
|
||||
"description": "[1.0] is invalid",
|
||||
"data": [
|
||||
1
|
||||
],
|
||||
"valid": false,
|
||||
"schema_id": "const_7_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "const with {\"a\": false} does not match {\"a\": 0}",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"const": {
|
||||
"a": false
|
||||
},
|
||||
"$id": "const_8_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "{\"a\": false} is valid",
|
||||
"data": {
|
||||
"a": false
|
||||
},
|
||||
"valid": true,
|
||||
"schema_id": "const_8_0"
|
||||
},
|
||||
{
|
||||
"description": "{\"a\": 0} is invalid",
|
||||
"data": {
|
||||
"a": 0
|
||||
},
|
||||
"valid": false,
|
||||
"schema_id": "const_8_0"
|
||||
},
|
||||
{
|
||||
"description": "{\"a\": 0.0} is invalid",
|
||||
"data": {
|
||||
"a": 0
|
||||
},
|
||||
"valid": false,
|
||||
"schema_id": "const_8_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "const with {\"a\": true} does not match {\"a\": 1}",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"const": {
|
||||
"a": true
|
||||
},
|
||||
"$id": "const_9_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "{\"a\": true} is valid",
|
||||
"data": {
|
||||
"a": true
|
||||
},
|
||||
"valid": true,
|
||||
"schema_id": "const_9_0"
|
||||
},
|
||||
{
|
||||
"description": "{\"a\": 1} is invalid",
|
||||
"data": {
|
||||
"a": 1
|
||||
},
|
||||
"valid": false,
|
||||
"schema_id": "const_9_0"
|
||||
},
|
||||
{
|
||||
"description": "{\"a\": 1.0} is invalid",
|
||||
"data": {
|
||||
"a": 1
|
||||
},
|
||||
"valid": false,
|
||||
"schema_id": "const_9_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "const with 0 does not match other zero-like types",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"const": 0,
|
||||
"$id": "const_10_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "false is invalid",
|
||||
"data": false,
|
||||
"valid": false,
|
||||
"schema_id": "const_10_0"
|
||||
},
|
||||
{
|
||||
"description": "integer zero is valid",
|
||||
"data": 0,
|
||||
"valid": true,
|
||||
"schema_id": "const_10_0"
|
||||
},
|
||||
{
|
||||
"description": "float zero is valid",
|
||||
"data": 0,
|
||||
"valid": true,
|
||||
"schema_id": "const_10_0"
|
||||
},
|
||||
{
|
||||
"description": "empty object is invalid",
|
||||
"data": {},
|
||||
"valid": false,
|
||||
"schema_id": "const_10_0"
|
||||
},
|
||||
{
|
||||
"description": "empty array is invalid",
|
||||
"data": [],
|
||||
"valid": false,
|
||||
"schema_id": "const_10_0"
|
||||
},
|
||||
{
|
||||
"description": "empty string is invalid",
|
||||
"data": "",
|
||||
"valid": false,
|
||||
"schema_id": "const_10_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "const with 1 does not match true",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"const": 1,
|
||||
"$id": "const_11_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "true is invalid",
|
||||
"data": true,
|
||||
"valid": false,
|
||||
"schema_id": "const_11_0"
|
||||
},
|
||||
{
|
||||
"description": "integer one is valid",
|
||||
"data": 1,
|
||||
"valid": true,
|
||||
"schema_id": "const_11_0"
|
||||
},
|
||||
{
|
||||
"description": "float one is valid",
|
||||
"data": 1,
|
||||
"valid": true,
|
||||
"schema_id": "const_11_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "const with -2.0 matches integer and float types",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"const": -2,
|
||||
"$id": "const_12_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "integer -2 is valid",
|
||||
"data": -2,
|
||||
"valid": true,
|
||||
"schema_id": "const_12_0"
|
||||
},
|
||||
{
|
||||
"description": "integer 2 is invalid",
|
||||
"data": 2,
|
||||
"valid": false,
|
||||
"schema_id": "const_12_0"
|
||||
},
|
||||
{
|
||||
"description": "float -2.0 is valid",
|
||||
"data": -2,
|
||||
"valid": true,
|
||||
"schema_id": "const_12_0"
|
||||
},
|
||||
{
|
||||
"description": "float 2.0 is invalid",
|
||||
"data": 2,
|
||||
"valid": false,
|
||||
"schema_id": "const_12_0"
|
||||
},
|
||||
{
|
||||
"description": "float -2.00001 is invalid",
|
||||
"data": -2.00001,
|
||||
"valid": false,
|
||||
"schema_id": "const_12_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "float and integers are equal up to 64-bit representation limits",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"const": 9007199254740992,
|
||||
"$id": "const_13_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "integer is valid",
|
||||
"data": 9007199254740992,
|
||||
"valid": true,
|
||||
"schema_id": "const_13_0"
|
||||
},
|
||||
{
|
||||
"description": "integer minus one is invalid",
|
||||
"data": 9007199254740991,
|
||||
"valid": false,
|
||||
"schema_id": "const_13_0"
|
||||
},
|
||||
{
|
||||
"description": "float is valid",
|
||||
"data": 9007199254740992,
|
||||
"valid": true,
|
||||
"schema_id": "const_13_0"
|
||||
},
|
||||
{
|
||||
"description": "float minus one is invalid",
|
||||
"data": 9007199254740991,
|
||||
"valid": false,
|
||||
"schema_id": "const_13_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "nul characters in strings",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"const": "hello\u0000there",
|
||||
"$id": "const_14_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "match string with nul",
|
||||
"data": "hello\u0000there",
|
||||
"valid": true,
|
||||
"schema_id": "const_14_0"
|
||||
},
|
||||
{
|
||||
"description": "do not match string lacking nul",
|
||||
"data": "hellothere",
|
||||
"valid": false,
|
||||
"schema_id": "const_14_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "characters with the same visual representation but different codepoint",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"const": "μ",
|
||||
"$comment": "U+03BC",
|
||||
"$id": "const_15_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "character uses the same codepoint",
|
||||
"data": "μ",
|
||||
"comment": "U+03BC",
|
||||
"valid": true,
|
||||
"schema_id": "const_15_0"
|
||||
},
|
||||
{
|
||||
"description": "character looks the same but uses a different codepoint",
|
||||
"data": "µ",
|
||||
"comment": "U+00B5",
|
||||
"valid": false,
|
||||
"schema_id": "const_15_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "characters with the same visual representation, but different number of codepoints",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"const": "ä",
|
||||
"$comment": "U+00E4",
|
||||
"$id": "const_16_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "character uses the same codepoint",
|
||||
"data": "ä",
|
||||
"comment": "U+00E4",
|
||||
"valid": true,
|
||||
"schema_id": "const_16_0"
|
||||
},
|
||||
{
|
||||
"description": "character looks the same but uses combining marks",
|
||||
"data": "ä",
|
||||
"comment": "a, U+0308",
|
||||
"valid": false,
|
||||
"schema_id": "const_16_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "extensible: true allows extra properties in const object match",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"const": {
|
||||
"a": 1
|
||||
},
|
||||
"extensible": true,
|
||||
"$id": "const_17_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "extra property ignored during strict check, but const check still applies (mismatch)",
|
||||
"data": {
|
||||
"a": 1,
|
||||
"b": 2
|
||||
},
|
||||
"valid": false,
|
||||
"schema_id": "const_17_0"
|
||||
},
|
||||
{
|
||||
"description": "extra property match in const (this is effectively impossible if data has extra props not in const, it implicitly fails const check unless we assume const check ignored extra props? No, const check is strict. So this test is just to show strictness passes.)",
|
||||
"data": {
|
||||
"a": 1
|
||||
},
|
||||
"valid": true,
|
||||
"schema_id": "const_17_0"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
346
tests/fixtures/contains.json
vendored
Normal file
346
tests/fixtures/contains.json
vendored
Normal file
@ -0,0 +1,346 @@
|
||||
[
|
||||
{
|
||||
"description": "contains keyword validation",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"contains": {
|
||||
"minimum": 5
|
||||
},
|
||||
"items": true,
|
||||
"$id": "contains_0_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "array with item matching schema (5) is valid (items: true)",
|
||||
"data": [
|
||||
3,
|
||||
4,
|
||||
5
|
||||
],
|
||||
"valid": true,
|
||||
"schema_id": "contains_0_0"
|
||||
},
|
||||
{
|
||||
"description": "array with item matching schema (6) is valid (items: true)",
|
||||
"data": [
|
||||
3,
|
||||
4,
|
||||
6
|
||||
],
|
||||
"valid": true,
|
||||
"schema_id": "contains_0_0"
|
||||
},
|
||||
{
|
||||
"description": "array with two items matching schema (5, 6) is valid (items: true)",
|
||||
"data": [
|
||||
3,
|
||||
4,
|
||||
5,
|
||||
6
|
||||
],
|
||||
"valid": true,
|
||||
"schema_id": "contains_0_0"
|
||||
},
|
||||
{
|
||||
"description": "array without items matching schema is invalid",
|
||||
"data": [
|
||||
2,
|
||||
3,
|
||||
4
|
||||
],
|
||||
"valid": false,
|
||||
"schema_id": "contains_0_0"
|
||||
},
|
||||
{
|
||||
"description": "empty array is invalid",
|
||||
"data": [],
|
||||
"valid": false,
|
||||
"schema_id": "contains_0_0"
|
||||
},
|
||||
{
|
||||
"description": "not array is valid",
|
||||
"data": {},
|
||||
"valid": true,
|
||||
"schema_id": "contains_0_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "contains keyword with const keyword",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"contains": {
|
||||
"const": 5
|
||||
},
|
||||
"items": true,
|
||||
"$id": "contains_1_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "array with item 5 is valid (items: true)",
|
||||
"data": [
|
||||
3,
|
||||
4,
|
||||
5
|
||||
],
|
||||
"valid": true,
|
||||
"schema_id": "contains_1_0"
|
||||
},
|
||||
{
|
||||
"description": "array with two items 5 is valid (items: true)",
|
||||
"data": [
|
||||
3,
|
||||
4,
|
||||
5,
|
||||
5
|
||||
],
|
||||
"valid": true,
|
||||
"schema_id": "contains_1_0"
|
||||
},
|
||||
{
|
||||
"description": "array without item 5 is invalid",
|
||||
"data": [
|
||||
1,
|
||||
2,
|
||||
3,
|
||||
4
|
||||
],
|
||||
"valid": false,
|
||||
"schema_id": "contains_1_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "contains keyword with boolean schema true",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"contains": true,
|
||||
"$id": "contains_2_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "any non-empty array is valid",
|
||||
"data": [
|
||||
"foo"
|
||||
],
|
||||
"valid": true,
|
||||
"schema_id": "contains_2_0"
|
||||
},
|
||||
{
|
||||
"description": "empty array is invalid",
|
||||
"data": [],
|
||||
"valid": false,
|
||||
"schema_id": "contains_2_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "contains keyword with boolean schema false",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"contains": false,
|
||||
"$id": "contains_3_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "any non-empty array is invalid",
|
||||
"data": [
|
||||
"foo"
|
||||
],
|
||||
"valid": false,
|
||||
"schema_id": "contains_3_0"
|
||||
},
|
||||
{
|
||||
"description": "empty array is invalid",
|
||||
"data": [],
|
||||
"valid": false,
|
||||
"schema_id": "contains_3_0"
|
||||
},
|
||||
{
|
||||
"description": "non-arrays are valid",
|
||||
"data": "contains does not apply to strings",
|
||||
"valid": true,
|
||||
"schema_id": "contains_3_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "items + contains",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"items": {
|
||||
"multipleOf": 2
|
||||
},
|
||||
"contains": {
|
||||
"multipleOf": 3
|
||||
},
|
||||
"$id": "contains_4_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "matches items, does not match contains",
|
||||
"data": [
|
||||
2,
|
||||
4,
|
||||
8
|
||||
],
|
||||
"valid": false,
|
||||
"schema_id": "contains_4_0"
|
||||
},
|
||||
{
|
||||
"description": "does not match items, matches contains",
|
||||
"data": [
|
||||
3,
|
||||
6,
|
||||
9
|
||||
],
|
||||
"valid": false,
|
||||
"schema_id": "contains_4_0"
|
||||
},
|
||||
{
|
||||
"description": "matches both items and contains",
|
||||
"data": [
|
||||
6,
|
||||
12
|
||||
],
|
||||
"valid": true,
|
||||
"schema_id": "contains_4_0"
|
||||
},
|
||||
{
|
||||
"description": "matches neither items nor contains",
|
||||
"data": [
|
||||
1,
|
||||
5
|
||||
],
|
||||
"valid": false,
|
||||
"schema_id": "contains_4_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "contains with false if subschema",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"contains": {
|
||||
"if": false,
|
||||
"else": true
|
||||
},
|
||||
"$id": "contains_5_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "any non-empty array is valid",
|
||||
"data": [
|
||||
"foo"
|
||||
],
|
||||
"valid": true,
|
||||
"schema_id": "contains_5_0"
|
||||
},
|
||||
{
|
||||
"description": "empty array is invalid",
|
||||
"data": [],
|
||||
"valid": false,
|
||||
"schema_id": "contains_5_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "contains with null instance elements",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"contains": {
|
||||
"type": "null"
|
||||
},
|
||||
"$id": "contains_6_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "allows null items",
|
||||
"data": [
|
||||
null
|
||||
],
|
||||
"valid": true,
|
||||
"schema_id": "contains_6_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "extensible: true allows non-matching items in contains",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"contains": {
|
||||
"const": 1
|
||||
},
|
||||
"extensible": true,
|
||||
"$id": "contains_7_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "extra items acceptable",
|
||||
"data": [
|
||||
1,
|
||||
2
|
||||
],
|
||||
"valid": true,
|
||||
"schema_id": "contains_7_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "strict by default: non-matching items in contains are invalid",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"contains": {
|
||||
"const": 1
|
||||
},
|
||||
"$id": "contains_8_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "extra items cause failure",
|
||||
"data": [
|
||||
1,
|
||||
2
|
||||
],
|
||||
"valid": false,
|
||||
"schema_id": "contains_8_0"
|
||||
},
|
||||
{
|
||||
"description": "only matching items is valid",
|
||||
"data": [
|
||||
1,
|
||||
1
|
||||
],
|
||||
"valid": true,
|
||||
"schema_id": "contains_8_0"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
178
tests/fixtures/content.json
vendored
Normal file
178
tests/fixtures/content.json
vendored
Normal file
@ -0,0 +1,178 @@
|
||||
[
|
||||
{
|
||||
"description": "validation of string-encoded content based on media type",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"contentMediaType": "application/json",
|
||||
"$id": "content_0_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "a valid JSON document",
|
||||
"data": "{\"foo\": \"bar\"}",
|
||||
"valid": true,
|
||||
"schema_id": "content_0_0"
|
||||
},
|
||||
{
|
||||
"description": "an invalid JSON document; validates true",
|
||||
"data": "{:}",
|
||||
"valid": true,
|
||||
"schema_id": "content_0_0"
|
||||
},
|
||||
{
|
||||
"description": "ignores non-strings",
|
||||
"data": 100,
|
||||
"valid": true,
|
||||
"schema_id": "content_0_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "validation of binary string-encoding",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"contentEncoding": "base64",
|
||||
"$id": "content_1_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "a valid base64 string",
|
||||
"data": "eyJmb28iOiAiYmFyIn0K",
|
||||
"valid": true,
|
||||
"schema_id": "content_1_0"
|
||||
},
|
||||
{
|
||||
"description": "an invalid base64 string (% is not a valid character); validates true",
|
||||
"data": "eyJmb28iOi%iYmFyIn0K",
|
||||
"valid": true,
|
||||
"schema_id": "content_1_0"
|
||||
},
|
||||
{
|
||||
"description": "ignores non-strings",
|
||||
"data": 100,
|
||||
"valid": true,
|
||||
"schema_id": "content_1_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "validation of binary-encoded media type documents",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"contentMediaType": "application/json",
|
||||
"contentEncoding": "base64",
|
||||
"$id": "content_2_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "a valid base64-encoded JSON document",
|
||||
"data": "eyJmb28iOiAiYmFyIn0K",
|
||||
"valid": true,
|
||||
"schema_id": "content_2_0"
|
||||
},
|
||||
{
|
||||
"description": "a validly-encoded invalid JSON document; validates true",
|
||||
"data": "ezp9Cg==",
|
||||
"valid": true,
|
||||
"schema_id": "content_2_0"
|
||||
},
|
||||
{
|
||||
"description": "an invalid base64 string that is valid JSON; validates true",
|
||||
"data": "{}",
|
||||
"valid": true,
|
||||
"schema_id": "content_2_0"
|
||||
},
|
||||
{
|
||||
"description": "ignores non-strings",
|
||||
"data": 100,
|
||||
"valid": true,
|
||||
"schema_id": "content_2_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "validation of binary-encoded media type documents with schema",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"contentMediaType": "application/json",
|
||||
"contentEncoding": "base64",
|
||||
"contentSchema": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
"foo"
|
||||
],
|
||||
"properties": {
|
||||
"foo": {
|
||||
"type": "string"
|
||||
},
|
||||
"boo": {
|
||||
"type": "integer"
|
||||
}
|
||||
}
|
||||
},
|
||||
"$id": "content_3_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "a valid base64-encoded JSON document",
|
||||
"data": "eyJmb28iOiAiYmFyIn0K",
|
||||
"valid": true,
|
||||
"schema_id": "content_3_0"
|
||||
},
|
||||
{
|
||||
"description": "another valid base64-encoded JSON document",
|
||||
"data": "eyJib28iOiAyMCwgImZvbyI6ICJiYXoifQ==",
|
||||
"valid": true,
|
||||
"schema_id": "content_3_0"
|
||||
},
|
||||
{
|
||||
"description": "an invalid base64-encoded JSON document; validates true",
|
||||
"data": "eyJib28iOiAyMH0=",
|
||||
"valid": true,
|
||||
"schema_id": "content_3_0"
|
||||
},
|
||||
{
|
||||
"description": "an empty object as a base64-encoded JSON document; validates true",
|
||||
"data": "e30=",
|
||||
"valid": true,
|
||||
"schema_id": "content_3_0"
|
||||
},
|
||||
{
|
||||
"description": "an empty array as a base64-encoded JSON document",
|
||||
"data": "W10=",
|
||||
"valid": true,
|
||||
"schema_id": "content_3_0"
|
||||
},
|
||||
{
|
||||
"description": "a validly-encoded invalid JSON document; validates true",
|
||||
"data": "ezp9Cg==",
|
||||
"valid": true,
|
||||
"schema_id": "content_3_0"
|
||||
},
|
||||
{
|
||||
"description": "an invalid base64 string that is valid JSON; validates true",
|
||||
"data": "{}",
|
||||
"valid": true,
|
||||
"schema_id": "content_3_0"
|
||||
},
|
||||
{
|
||||
"description": "ignores non-strings",
|
||||
"data": 100,
|
||||
"valid": true,
|
||||
"schema_id": "content_3_0"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
619
tests/fixtures/dependencies.json
vendored
Normal file
619
tests/fixtures/dependencies.json
vendored
Normal file
@ -0,0 +1,619 @@
|
||||
[
|
||||
{
|
||||
"description": "single dependency (required)",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
||||
"$id": "schema1",
|
||||
"dependencies": {
|
||||
"bar": [
|
||||
"foo"
|
||||
]
|
||||
},
|
||||
"extensible": true
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "neither",
|
||||
"data": {},
|
||||
"valid": true,
|
||||
"schema_id": "schema1"
|
||||
},
|
||||
{
|
||||
"description": "nondependant",
|
||||
"data": {
|
||||
"foo": 1
|
||||
},
|
||||
"valid": true,
|
||||
"schema_id": "schema1"
|
||||
},
|
||||
{
|
||||
"description": "with dependency",
|
||||
"data": {
|
||||
"foo": 1,
|
||||
"bar": 2
|
||||
},
|
||||
"valid": true,
|
||||
"schema_id": "schema1"
|
||||
},
|
||||
{
|
||||
"description": "missing dependency",
|
||||
"data": {
|
||||
"bar": 2
|
||||
},
|
||||
"valid": false,
|
||||
"schema_id": "schema1"
|
||||
},
|
||||
{
|
||||
"description": "ignores arrays",
|
||||
"data": [
|
||||
"bar"
|
||||
],
|
||||
"valid": true,
|
||||
"schema_id": "schema1"
|
||||
},
|
||||
{
|
||||
"description": "ignores strings",
|
||||
"data": "foobar",
|
||||
"valid": true,
|
||||
"schema_id": "schema1"
|
||||
},
|
||||
{
|
||||
"description": "ignores other non-objects",
|
||||
"data": 12,
|
||||
"valid": true,
|
||||
"schema_id": "schema1"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "empty dependents",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
||||
"$id": "schema2",
|
||||
"dependencies": {
|
||||
"bar": []
|
||||
},
|
||||
"extensible": true
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "empty object",
|
||||
"data": {},
|
||||
"valid": true,
|
||||
"schema_id": "schema2"
|
||||
},
|
||||
{
|
||||
"description": "object with one property",
|
||||
"data": {
|
||||
"bar": 2
|
||||
},
|
||||
"valid": true,
|
||||
"schema_id": "schema2"
|
||||
},
|
||||
{
|
||||
"description": "non-object is valid",
|
||||
"data": 1,
|
||||
"valid": true,
|
||||
"schema_id": "schema2"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "multiple dependents required",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
||||
"$id": "schema3",
|
||||
"dependencies": {
|
||||
"quux": [
|
||||
"foo",
|
||||
"bar"
|
||||
]
|
||||
},
|
||||
"extensible": true
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "neither",
|
||||
"data": {},
|
||||
"valid": true,
|
||||
"schema_id": "schema3"
|
||||
},
|
||||
{
|
||||
"description": "nondependants",
|
||||
"data": {
|
||||
"foo": 1,
|
||||
"bar": 2
|
||||
},
|
||||
"valid": true,
|
||||
"schema_id": "schema3"
|
||||
},
|
||||
{
|
||||
"description": "with dependencies",
|
||||
"data": {
|
||||
"foo": 1,
|
||||
"bar": 2,
|
||||
"quux": 3
|
||||
},
|
||||
"valid": true,
|
||||
"schema_id": "schema3"
|
||||
},
|
||||
{
|
||||
"description": "missing dependency",
|
||||
"data": {
|
||||
"foo": 1,
|
||||
"quux": 2
|
||||
},
|
||||
"valid": false,
|
||||
"schema_id": "schema3"
|
||||
},
|
||||
{
|
||||
"description": "missing other dependency",
|
||||
"data": {
|
||||
"bar": 1,
|
||||
"quux": 2
|
||||
},
|
||||
"valid": false,
|
||||
"schema_id": "schema3"
|
||||
},
|
||||
{
|
||||
"description": "missing both dependencies",
|
||||
"data": {
|
||||
"quux": 1
|
||||
},
|
||||
"valid": false,
|
||||
"schema_id": "schema3"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "dependencies with escaped characters",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
||||
"$id": "schema4",
|
||||
"dependencies": {
|
||||
"foo\nbar": [
|
||||
"foo\rbar"
|
||||
],
|
||||
"foo\"bar": [
|
||||
"foo'bar"
|
||||
]
|
||||
},
|
||||
"extensible": true
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "CRLF",
|
||||
"data": {
|
||||
"foo\nbar": 1,
|
||||
"foo\rbar": 2
|
||||
},
|
||||
"valid": true,
|
||||
"schema_id": "schema4"
|
||||
},
|
||||
{
|
||||
"description": "quoted quotes",
|
||||
"data": {
|
||||
"foo'bar": 1,
|
||||
"foo\"bar": 2
|
||||
},
|
||||
"valid": true,
|
||||
"schema_id": "schema4"
|
||||
},
|
||||
{
|
||||
"description": "CRLF missing dependent",
|
||||
"data": {
|
||||
"foo\nbar": 1,
|
||||
"foo": 2
|
||||
},
|
||||
"valid": false,
|
||||
"schema_id": "schema4"
|
||||
},
|
||||
{
|
||||
"description": "quoted quotes missing dependent",
|
||||
"data": {
|
||||
"foo\"bar": 2
|
||||
},
|
||||
"valid": false,
|
||||
"schema_id": "schema4"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "extensible: true allows extra properties in dependentRequired",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
||||
"$id": "schema5",
|
||||
"dependencies": {
|
||||
"bar": [
|
||||
"foo"
|
||||
]
|
||||
},
|
||||
"extensible": true
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "extra property is valid",
|
||||
"data": {
|
||||
"foo": 1,
|
||||
"bar": 2,
|
||||
"baz": 3
|
||||
},
|
||||
"valid": true,
|
||||
"schema_id": "schema5"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "single dependency (schemas, STRICT)",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
||||
"$id": "schema_schema1",
|
||||
"properties": {
|
||||
"foo": true,
|
||||
"bar": true
|
||||
},
|
||||
"dependencies": {
|
||||
"bar": {
|
||||
"properties": {
|
||||
"foo": {
|
||||
"type": "integer"
|
||||
},
|
||||
"bar": {
|
||||
"type": "integer"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "valid",
|
||||
"data": {
|
||||
"foo": 1,
|
||||
"bar": 2
|
||||
},
|
||||
"valid": true,
|
||||
"schema_id": "schema_schema1"
|
||||
},
|
||||
{
|
||||
"description": "no dependency",
|
||||
"data": {
|
||||
"foo": "quux"
|
||||
},
|
||||
"valid": true,
|
||||
"schema_id": "schema_schema1"
|
||||
},
|
||||
{
|
||||
"description": "wrong type",
|
||||
"data": {
|
||||
"foo": "quux",
|
||||
"bar": 2
|
||||
},
|
||||
"valid": false,
|
||||
"schema_id": "schema_schema1"
|
||||
},
|
||||
{
|
||||
"description": "wrong type other",
|
||||
"data": {
|
||||
"foo": 2,
|
||||
"bar": "quux"
|
||||
},
|
||||
"valid": false,
|
||||
"schema_id": "schema_schema1"
|
||||
},
|
||||
{
|
||||
"description": "wrong type both",
|
||||
"data": {
|
||||
"foo": "quux",
|
||||
"bar": "quux"
|
||||
},
|
||||
"valid": false,
|
||||
"schema_id": "schema_schema1"
|
||||
},
|
||||
{
|
||||
"description": "ignores arrays (invalid in strict mode)",
|
||||
"data": [
|
||||
"bar"
|
||||
],
|
||||
"valid": false,
|
||||
"expect_errors": [
|
||||
{
|
||||
"code": "STRICT_ITEM_VIOLATION"
|
||||
}
|
||||
],
|
||||
"schema_id": "schema_schema1"
|
||||
},
|
||||
{
|
||||
"description": "ignores strings",
|
||||
"data": "foobar",
|
||||
"valid": true,
|
||||
"schema_id": "schema_schema1"
|
||||
},
|
||||
{
|
||||
"description": "ignores other non-objects",
|
||||
"data": 12,
|
||||
"valid": true,
|
||||
"schema_id": "schema_schema1"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "single dependency (schemas, EXTENSIBLE)",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
||||
"$id": "schema_schema2",
|
||||
"properties": {
|
||||
"foo": true,
|
||||
"bar": true
|
||||
},
|
||||
"dependencies": {
|
||||
"bar": {
|
||||
"properties": {
|
||||
"foo": {
|
||||
"type": "integer"
|
||||
},
|
||||
"bar": {
|
||||
"type": "integer"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"extensible": true
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "ignores arrays (valid in extensible mode)",
|
||||
"data": [
|
||||
"bar"
|
||||
],
|
||||
"valid": true,
|
||||
"schema_id": "schema_schema2"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "boolean subschemas",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
||||
"$id": "schema_schema3",
|
||||
"properties": {
|
||||
"foo": true,
|
||||
"bar": true
|
||||
},
|
||||
"dependencies": {
|
||||
"foo": true,
|
||||
"bar": false
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "object with property having schema true is valid",
|
||||
"data": {
|
||||
"foo": 1
|
||||
},
|
||||
"valid": true,
|
||||
"schema_id": "schema_schema3"
|
||||
},
|
||||
{
|
||||
"description": "object with property having schema false is invalid",
|
||||
"data": {
|
||||
"bar": 2
|
||||
},
|
||||
"valid": false,
|
||||
"schema_id": "schema_schema3"
|
||||
},
|
||||
{
|
||||
"description": "object with both properties is invalid",
|
||||
"data": {
|
||||
"foo": 1,
|
||||
"bar": 2
|
||||
},
|
||||
"valid": false,
|
||||
"schema_id": "schema_schema3"
|
||||
},
|
||||
{
|
||||
"description": "empty object is valid",
|
||||
"data": {},
|
||||
"valid": true,
|
||||
"schema_id": "schema_schema3"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "dependencies with escaped characters",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
||||
"$id": "schema_schema4",
|
||||
"properties": {
|
||||
"foo\tbar": true,
|
||||
"foo'bar": true,
|
||||
"a": true,
|
||||
"b": true,
|
||||
"c": true
|
||||
},
|
||||
"dependencies": {
|
||||
"foo\tbar": {
|
||||
"minProperties": 4,
|
||||
"extensible": true
|
||||
},
|
||||
"foo'bar": {
|
||||
"required": [
|
||||
"foo\"bar"
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "quoted tab",
|
||||
"data": {
|
||||
"foo\tbar": 1,
|
||||
"a": 2,
|
||||
"b": 3,
|
||||
"c": 4
|
||||
},
|
||||
"valid": true,
|
||||
"schema_id": "schema_schema4"
|
||||
},
|
||||
{
|
||||
"description": "quoted quote",
|
||||
"data": {
|
||||
"foo'bar": {
|
||||
"foo\"bar": 1
|
||||
}
|
||||
},
|
||||
"valid": false,
|
||||
"schema_id": "schema_schema4"
|
||||
},
|
||||
{
|
||||
"description": "quoted tab invalid under dependent schema",
|
||||
"data": {
|
||||
"foo\tbar": 1,
|
||||
"a": 2
|
||||
},
|
||||
"valid": false,
|
||||
"schema_id": "schema_schema4"
|
||||
},
|
||||
{
|
||||
"description": "quoted quote invalid under dependent schema",
|
||||
"data": {
|
||||
"foo'bar": 1
|
||||
},
|
||||
"valid": false,
|
||||
"schema_id": "schema_schema4"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "dependent subschema incompatible with root (STRICT)",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
||||
"$id": "schema_schema5",
|
||||
"properties": {
|
||||
"foo": {},
|
||||
"baz": true
|
||||
},
|
||||
"dependencies": {
|
||||
"foo": {
|
||||
"properties": {
|
||||
"bar": {}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "matches root",
|
||||
"data": {
|
||||
"foo": 1
|
||||
},
|
||||
"valid": false,
|
||||
"schema_id": "schema_schema5"
|
||||
},
|
||||
{
|
||||
"description": "matches dependency (invalid in strict mode - bar not allowed if foo missing)",
|
||||
"data": {
|
||||
"bar": 1
|
||||
},
|
||||
"valid": false,
|
||||
"expect_errors": [
|
||||
{
|
||||
"code": "STRICT_PROPERTY_VIOLATION"
|
||||
}
|
||||
],
|
||||
"schema_id": "schema_schema5"
|
||||
},
|
||||
{
|
||||
"description": "matches both",
|
||||
"data": {
|
||||
"foo": 1,
|
||||
"bar": 2
|
||||
},
|
||||
"valid": false,
|
||||
"schema_id": "schema_schema5"
|
||||
},
|
||||
{
|
||||
"description": "no dependency",
|
||||
"data": {
|
||||
"baz": 1
|
||||
},
|
||||
"valid": true,
|
||||
"schema_id": "schema_schema5"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "dependent subschema incompatible with root (EXTENSIBLE)",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
||||
"$id": "schema_schema6",
|
||||
"properties": {
|
||||
"foo": {},
|
||||
"baz": true
|
||||
},
|
||||
"dependencies": {
|
||||
"foo": {
|
||||
"properties": {
|
||||
"bar": {}
|
||||
},
|
||||
"additionalProperties": false
|
||||
}
|
||||
},
|
||||
"extensible": true
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "matches dependency (valid in extensible mode)",
|
||||
"data": {
|
||||
"bar": 1
|
||||
},
|
||||
"valid": true,
|
||||
"schema_id": "schema_schema6"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
133
tests/fixtures/emptyString.json
vendored
Normal file
133
tests/fixtures/emptyString.json
vendored
Normal file
@ -0,0 +1,133 @@
|
||||
[
|
||||
{
|
||||
"description": "empty string is valid for all types (except const)",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"properties": {
|
||||
"obj": {
|
||||
"type": "object"
|
||||
},
|
||||
"arr": {
|
||||
"type": "array"
|
||||
},
|
||||
"str": {
|
||||
"type": "string"
|
||||
},
|
||||
"int": {
|
||||
"type": "integer"
|
||||
},
|
||||
"num": {
|
||||
"type": "number"
|
||||
},
|
||||
"bool": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"nul": {
|
||||
"type": "null"
|
||||
},
|
||||
"fmt": {
|
||||
"type": "string",
|
||||
"format": "uuid"
|
||||
},
|
||||
"con": {
|
||||
"const": "value"
|
||||
},
|
||||
"con_empty": {
|
||||
"const": ""
|
||||
}
|
||||
},
|
||||
"$id": "emptyString_0_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "empty string valid for object",
|
||||
"data": {
|
||||
"obj": ""
|
||||
},
|
||||
"valid": true,
|
||||
"schema_id": "emptyString_0_0"
|
||||
},
|
||||
{
|
||||
"description": "empty string valid for array",
|
||||
"data": {
|
||||
"arr": ""
|
||||
},
|
||||
"valid": true,
|
||||
"schema_id": "emptyString_0_0"
|
||||
},
|
||||
{
|
||||
"description": "empty string valid for string",
|
||||
"data": {
|
||||
"str": ""
|
||||
},
|
||||
"valid": true,
|
||||
"schema_id": "emptyString_0_0"
|
||||
},
|
||||
{
|
||||
"description": "empty string valid for integer",
|
||||
"data": {
|
||||
"int": ""
|
||||
},
|
||||
"valid": true,
|
||||
"schema_id": "emptyString_0_0"
|
||||
},
|
||||
{
|
||||
"description": "empty string valid for number",
|
||||
"data": {
|
||||
"num": ""
|
||||
},
|
||||
"valid": true,
|
||||
"schema_id": "emptyString_0_0"
|
||||
},
|
||||
{
|
||||
"description": "empty string valid for boolean",
|
||||
"data": {
|
||||
"bool": ""
|
||||
},
|
||||
"valid": true,
|
||||
"schema_id": "emptyString_0_0"
|
||||
},
|
||||
{
|
||||
"description": "empty string valid for null",
|
||||
"data": {
|
||||
"nul": ""
|
||||
},
|
||||
"valid": true,
|
||||
"schema_id": "emptyString_0_0"
|
||||
},
|
||||
{
|
||||
"description": "empty string valid for format",
|
||||
"data": {
|
||||
"fmt": ""
|
||||
},
|
||||
"valid": true,
|
||||
"schema_id": "emptyString_0_0"
|
||||
},
|
||||
{
|
||||
"description": "empty string INVALID for const (unless const is empty string)",
|
||||
"data": {
|
||||
"con": ""
|
||||
},
|
||||
"valid": false,
|
||||
"expect_errors": [
|
||||
{
|
||||
"code": "CONST_VIOLATED",
|
||||
"path": "/con"
|
||||
}
|
||||
],
|
||||
"schema_id": "emptyString_0_0"
|
||||
},
|
||||
{
|
||||
"description": "empty string VALID for const if const IS empty string",
|
||||
"data": {
|
||||
"con_empty": ""
|
||||
},
|
||||
"valid": true,
|
||||
"schema_id": "emptyString_0_0"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
595
tests/fixtures/enum.json
vendored
Normal file
595
tests/fixtures/enum.json
vendored
Normal file
@ -0,0 +1,595 @@
|
||||
[
|
||||
{
|
||||
"description": "simple enum validation",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"enum": [
|
||||
1,
|
||||
2,
|
||||
3
|
||||
],
|
||||
"$id": "enum_0_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "one of the enum is valid",
|
||||
"data": 1,
|
||||
"valid": true,
|
||||
"schema_id": "enum_0_0"
|
||||
},
|
||||
{
|
||||
"description": "something else is invalid",
|
||||
"data": 4,
|
||||
"valid": false,
|
||||
"schema_id": "enum_0_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "heterogeneous enum validation",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"enum": [
|
||||
6,
|
||||
"foo",
|
||||
[],
|
||||
true,
|
||||
{
|
||||
"foo": 12
|
||||
}
|
||||
],
|
||||
"properties": {
|
||||
"foo": {}
|
||||
},
|
||||
"$id": "enum_1_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "one of the enum is valid",
|
||||
"data": [],
|
||||
"valid": true,
|
||||
"schema_id": "enum_1_0"
|
||||
},
|
||||
{
|
||||
"description": "something else is invalid",
|
||||
"data": null,
|
||||
"valid": false,
|
||||
"schema_id": "enum_1_0"
|
||||
},
|
||||
{
|
||||
"description": "objects are deep compared",
|
||||
"data": {
|
||||
"foo": false
|
||||
},
|
||||
"valid": false,
|
||||
"schema_id": "enum_1_0"
|
||||
},
|
||||
{
|
||||
"description": "valid object matches",
|
||||
"data": {
|
||||
"foo": 12
|
||||
},
|
||||
"valid": true,
|
||||
"schema_id": "enum_1_0"
|
||||
},
|
||||
{
|
||||
"description": "extra properties in object is invalid",
|
||||
"data": {
|
||||
"foo": 12,
|
||||
"boo": 42
|
||||
},
|
||||
"valid": false,
|
||||
"schema_id": "enum_1_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "heterogeneous enum-with-null validation",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"enum": [
|
||||
6,
|
||||
null
|
||||
],
|
||||
"$id": "enum_2_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "null is valid",
|
||||
"data": null,
|
||||
"valid": true,
|
||||
"schema_id": "enum_2_0"
|
||||
},
|
||||
{
|
||||
"description": "number is valid",
|
||||
"data": 6,
|
||||
"valid": true,
|
||||
"schema_id": "enum_2_0"
|
||||
},
|
||||
{
|
||||
"description": "something else is invalid",
|
||||
"data": "test",
|
||||
"valid": false,
|
||||
"schema_id": "enum_2_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "enums in properties",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"foo": {
|
||||
"enum": [
|
||||
"foo"
|
||||
]
|
||||
},
|
||||
"bar": {
|
||||
"enum": [
|
||||
"bar"
|
||||
]
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"bar"
|
||||
],
|
||||
"$id": "enum_3_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "both properties are valid",
|
||||
"data": {
|
||||
"foo": "foo",
|
||||
"bar": "bar"
|
||||
},
|
||||
"valid": true,
|
||||
"schema_id": "enum_3_0"
|
||||
},
|
||||
{
|
||||
"description": "wrong foo value",
|
||||
"data": {
|
||||
"foo": "foot",
|
||||
"bar": "bar"
|
||||
},
|
||||
"valid": false,
|
||||
"schema_id": "enum_3_0"
|
||||
},
|
||||
{
|
||||
"description": "wrong bar value",
|
||||
"data": {
|
||||
"foo": "foo",
|
||||
"bar": "bart"
|
||||
},
|
||||
"valid": false,
|
||||
"schema_id": "enum_3_0"
|
||||
},
|
||||
{
|
||||
"description": "missing optional property is valid",
|
||||
"data": {
|
||||
"bar": "bar"
|
||||
},
|
||||
"valid": true,
|
||||
"schema_id": "enum_3_0"
|
||||
},
|
||||
{
|
||||
"description": "missing required property is invalid",
|
||||
"data": {
|
||||
"foo": "foo"
|
||||
},
|
||||
"valid": false,
|
||||
"schema_id": "enum_3_0"
|
||||
},
|
||||
{
|
||||
"description": "missing all properties is invalid",
|
||||
"data": {},
|
||||
"valid": false,
|
||||
"schema_id": "enum_3_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "enum with escaped characters",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"enum": [
|
||||
"foo\nbar",
|
||||
"foo\rbar"
|
||||
],
|
||||
"$id": "enum_4_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "member 1 is valid",
|
||||
"data": "foo\nbar",
|
||||
"valid": true,
|
||||
"schema_id": "enum_4_0"
|
||||
},
|
||||
{
|
||||
"description": "member 2 is valid",
|
||||
"data": "foo\rbar",
|
||||
"valid": true,
|
||||
"schema_id": "enum_4_0"
|
||||
},
|
||||
{
|
||||
"description": "another string is invalid",
|
||||
"data": "abc",
|
||||
"valid": false,
|
||||
"schema_id": "enum_4_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "enum with false does not match 0",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"enum": [
|
||||
false
|
||||
],
|
||||
"$id": "enum_5_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "false is valid",
|
||||
"data": false,
|
||||
"valid": true,
|
||||
"schema_id": "enum_5_0"
|
||||
},
|
||||
{
|
||||
"description": "integer zero is invalid",
|
||||
"data": 0,
|
||||
"valid": false,
|
||||
"schema_id": "enum_5_0"
|
||||
},
|
||||
{
|
||||
"description": "float zero is invalid",
|
||||
"data": 0,
|
||||
"valid": false,
|
||||
"schema_id": "enum_5_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "enum with [false] does not match [0]",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"enum": [
|
||||
[
|
||||
false
|
||||
]
|
||||
],
|
||||
"$id": "enum_6_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "[false] is valid",
|
||||
"data": [
|
||||
false
|
||||
],
|
||||
"valid": true,
|
||||
"schema_id": "enum_6_0"
|
||||
},
|
||||
{
|
||||
"description": "[0] is invalid",
|
||||
"data": [
|
||||
0
|
||||
],
|
||||
"valid": false,
|
||||
"schema_id": "enum_6_0"
|
||||
},
|
||||
{
|
||||
"description": "[0.0] is invalid",
|
||||
"data": [
|
||||
0
|
||||
],
|
||||
"valid": false,
|
||||
"schema_id": "enum_6_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "enum with true does not match 1",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"enum": [
|
||||
true
|
||||
],
|
||||
"$id": "enum_7_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "true is valid",
|
||||
"data": true,
|
||||
"valid": true,
|
||||
"schema_id": "enum_7_0"
|
||||
},
|
||||
{
|
||||
"description": "integer one is invalid",
|
||||
"data": 1,
|
||||
"valid": false,
|
||||
"schema_id": "enum_7_0"
|
||||
},
|
||||
{
|
||||
"description": "float one is invalid",
|
||||
"data": 1,
|
||||
"valid": false,
|
||||
"schema_id": "enum_7_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "enum with [true] does not match [1]",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"enum": [
|
||||
[
|
||||
true
|
||||
]
|
||||
],
|
||||
"$id": "enum_8_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "[true] is valid",
|
||||
"data": [
|
||||
true
|
||||
],
|
||||
"valid": true,
|
||||
"schema_id": "enum_8_0"
|
||||
},
|
||||
{
|
||||
"description": "[1] is invalid",
|
||||
"data": [
|
||||
1
|
||||
],
|
||||
"valid": false,
|
||||
"schema_id": "enum_8_0"
|
||||
},
|
||||
{
|
||||
"description": "[1.0] is invalid",
|
||||
"data": [
|
||||
1
|
||||
],
|
||||
"valid": false,
|
||||
"schema_id": "enum_8_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "enum with 0 does not match false",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"enum": [
|
||||
0
|
||||
],
|
||||
"$id": "enum_9_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "false is invalid",
|
||||
"data": false,
|
||||
"valid": false,
|
||||
"schema_id": "enum_9_0"
|
||||
},
|
||||
{
|
||||
"description": "integer zero is valid",
|
||||
"data": 0,
|
||||
"valid": true,
|
||||
"schema_id": "enum_9_0"
|
||||
},
|
||||
{
|
||||
"description": "float zero is valid",
|
||||
"data": 0,
|
||||
"valid": true,
|
||||
"schema_id": "enum_9_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "enum with [0] does not match [false]",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"enum": [
|
||||
[
|
||||
0
|
||||
]
|
||||
],
|
||||
"$id": "enum_10_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "[false] is invalid",
|
||||
"data": [
|
||||
false
|
||||
],
|
||||
"valid": false,
|
||||
"schema_id": "enum_10_0"
|
||||
},
|
||||
{
|
||||
"description": "[0] is valid",
|
||||
"data": [
|
||||
0
|
||||
],
|
||||
"valid": true,
|
||||
"schema_id": "enum_10_0"
|
||||
},
|
||||
{
|
||||
"description": "[0.0] is valid",
|
||||
"data": [
|
||||
0
|
||||
],
|
||||
"valid": true,
|
||||
"schema_id": "enum_10_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "enum with 1 does not match true",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"enum": [
|
||||
1
|
||||
],
|
||||
"$id": "enum_11_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "true is invalid",
|
||||
"data": true,
|
||||
"valid": false,
|
||||
"schema_id": "enum_11_0"
|
||||
},
|
||||
{
|
||||
"description": "integer one is valid",
|
||||
"data": 1,
|
||||
"valid": true,
|
||||
"schema_id": "enum_11_0"
|
||||
},
|
||||
{
|
||||
"description": "float one is valid",
|
||||
"data": 1,
|
||||
"valid": true,
|
||||
"schema_id": "enum_11_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "enum with [1] does not match [true]",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"enum": [
|
||||
[
|
||||
1
|
||||
]
|
||||
],
|
||||
"$id": "enum_12_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "[true] is invalid",
|
||||
"data": [
|
||||
true
|
||||
],
|
||||
"valid": false,
|
||||
"schema_id": "enum_12_0"
|
||||
},
|
||||
{
|
||||
"description": "[1] is valid",
|
||||
"data": [
|
||||
1
|
||||
],
|
||||
"valid": true,
|
||||
"schema_id": "enum_12_0"
|
||||
},
|
||||
{
|
||||
"description": "[1.0] is valid",
|
||||
"data": [
|
||||
1
|
||||
],
|
||||
"valid": true,
|
||||
"schema_id": "enum_12_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "nul characters in strings",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"enum": [
|
||||
"hello\u0000there"
|
||||
],
|
||||
"$id": "enum_13_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "match string with nul",
|
||||
"data": "hello\u0000there",
|
||||
"valid": true,
|
||||
"schema_id": "enum_13_0"
|
||||
},
|
||||
{
|
||||
"description": "do not match string lacking nul",
|
||||
"data": "hellothere",
|
||||
"valid": false,
|
||||
"schema_id": "enum_13_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "extensible: true allows extra properties in enum object match",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"enum": [
|
||||
{
|
||||
"foo": 1
|
||||
}
|
||||
],
|
||||
"extensible": true,
|
||||
"$id": "enum_14_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "extra property ignored during strict check, but enum check still applies (mismatch here)",
|
||||
"data": {
|
||||
"foo": 1,
|
||||
"bar": 2
|
||||
},
|
||||
"valid": false,
|
||||
"schema_id": "enum_14_0"
|
||||
},
|
||||
{
|
||||
"description": "extra property ignored during strict check, enum match succeeds",
|
||||
"data": {
|
||||
"foo": 1
|
||||
},
|
||||
"valid": true,
|
||||
"schema_id": "enum_14_0"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
39
tests/fixtures/exclusiveMaximum.json
vendored
Normal file
39
tests/fixtures/exclusiveMaximum.json
vendored
Normal file
@ -0,0 +1,39 @@
|
||||
[
|
||||
{
|
||||
"description": "exclusiveMaximum validation",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"exclusiveMaximum": 3,
|
||||
"$id": "exclusiveMaximum_0_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "below the exclusiveMaximum is valid",
|
||||
"data": 2.2,
|
||||
"valid": true,
|
||||
"schema_id": "exclusiveMaximum_0_0"
|
||||
},
|
||||
{
|
||||
"description": "boundary point is invalid",
|
||||
"data": 3,
|
||||
"valid": false,
|
||||
"schema_id": "exclusiveMaximum_0_0"
|
||||
},
|
||||
{
|
||||
"description": "above the exclusiveMaximum is invalid",
|
||||
"data": 3.5,
|
||||
"valid": false,
|
||||
"schema_id": "exclusiveMaximum_0_0"
|
||||
},
|
||||
{
|
||||
"description": "ignores non-numbers",
|
||||
"data": "x",
|
||||
"valid": true,
|
||||
"schema_id": "exclusiveMaximum_0_0"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
39
tests/fixtures/exclusiveMinimum.json
vendored
Normal file
39
tests/fixtures/exclusiveMinimum.json
vendored
Normal file
@ -0,0 +1,39 @@
|
||||
[
|
||||
{
|
||||
"description": "exclusiveMinimum validation",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"exclusiveMinimum": 1.1,
|
||||
"$id": "exclusiveMinimum_0_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "above the exclusiveMinimum is valid",
|
||||
"data": 1.2,
|
||||
"valid": true,
|
||||
"schema_id": "exclusiveMinimum_0_0"
|
||||
},
|
||||
{
|
||||
"description": "boundary point is invalid",
|
||||
"data": 1.1,
|
||||
"valid": false,
|
||||
"schema_id": "exclusiveMinimum_0_0"
|
||||
},
|
||||
{
|
||||
"description": "below the exclusiveMinimum is invalid",
|
||||
"data": 0.6,
|
||||
"valid": false,
|
||||
"schema_id": "exclusiveMinimum_0_0"
|
||||
},
|
||||
{
|
||||
"description": "ignores non-numbers",
|
||||
"data": "x",
|
||||
"valid": true,
|
||||
"schema_id": "exclusiveMinimum_0_0"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
199
tests/fixtures/families.json
vendored
Normal file
199
tests/fixtures/families.json
vendored
Normal file
@ -0,0 +1,199 @@
|
||||
[
|
||||
{
|
||||
"description": "Entity families via pure $ref graph",
|
||||
"database": {
|
||||
"types": [
|
||||
{
|
||||
"name": "entity",
|
||||
"variations": [
|
||||
"entity",
|
||||
"organization",
|
||||
"person"
|
||||
],
|
||||
"schemas": [
|
||||
{
|
||||
"$id": "entity",
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"id": {
|
||||
"type": "string"
|
||||
},
|
||||
"type": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"$id": "light.entity",
|
||||
"$ref": "entity"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "organization",
|
||||
"variations": [
|
||||
"organization",
|
||||
"person"
|
||||
],
|
||||
"schemas": [
|
||||
{
|
||||
"$id": "organization",
|
||||
"$ref": "entity",
|
||||
"properties": {
|
||||
"name": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "person",
|
||||
"variations": [
|
||||
"person"
|
||||
],
|
||||
"schemas": [
|
||||
{
|
||||
"$id": "person",
|
||||
"$ref": "organization",
|
||||
"properties": {
|
||||
"first_name": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"$id": "light.person",
|
||||
"$ref": "light.entity"
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"puncs": [
|
||||
{
|
||||
"name": "get_entities",
|
||||
"schemas": [
|
||||
{
|
||||
"$id": "get_entities.response",
|
||||
"$family": "entity"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "get_light_entities",
|
||||
"schemas": [
|
||||
{
|
||||
"$id": "get_light_entities.response",
|
||||
"$family": "light.entity"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "Family matches base entity",
|
||||
"schema_id": "get_entities.response",
|
||||
"data": {
|
||||
"id": "1",
|
||||
"type": "entity"
|
||||
},
|
||||
"valid": true
|
||||
},
|
||||
{
|
||||
"description": "Family matches descendant person",
|
||||
"schema_id": "get_entities.response",
|
||||
"data": {
|
||||
"id": "2",
|
||||
"type": "person",
|
||||
"name": "ACME",
|
||||
"first_name": "John"
|
||||
},
|
||||
"valid": true
|
||||
},
|
||||
{
|
||||
"description": "Graph family matches light.entity",
|
||||
"schema_id": "get_light_entities.response",
|
||||
"data": {
|
||||
"id": "3",
|
||||
"type": "entity"
|
||||
},
|
||||
"valid": true
|
||||
},
|
||||
{
|
||||
"description": "Graph family matches light.person (because it $refs light.entity)",
|
||||
"schema_id": "get_light_entities.response",
|
||||
"data": {
|
||||
"id": "4",
|
||||
"type": "person"
|
||||
},
|
||||
"valid": true
|
||||
},
|
||||
{
|
||||
"description": "Graph family excludes organization (missing light. schema that $refs light.entity)",
|
||||
"schema_id": "get_light_entities.response",
|
||||
"data": {
|
||||
"id": "5",
|
||||
"type": "organization",
|
||||
"name": "ACME"
|
||||
},
|
||||
"valid": false,
|
||||
"expect_errors": [
|
||||
{
|
||||
"code": "FAMILY_MISMATCH",
|
||||
"path": ""
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "Ad-hoc non-entity families (using normal json-schema object structures)",
|
||||
"database": {
|
||||
"puncs": [
|
||||
{
|
||||
"name": "get_widgets",
|
||||
"schemas": [
|
||||
{
|
||||
"$id": "widget",
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"id": {
|
||||
"type": "string"
|
||||
},
|
||||
"widget_type": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"$id": "special_widget",
|
||||
"$ref": "widget",
|
||||
"properties": {
|
||||
"special_feature": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"$id": "get_widgets.response",
|
||||
"$family": "widget"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "Ad-hoc family matches strictly by shape (no magic variations for base schemas)",
|
||||
"schema_id": "get_widgets.response",
|
||||
"data": {
|
||||
"id": "1",
|
||||
"widget_type": "special",
|
||||
"special_feature": "yes"
|
||||
},
|
||||
"valid": true
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
3770
tests/fixtures/format.json
vendored
Normal file
3770
tests/fixtures/format.json
vendored
Normal file
File diff suppressed because it is too large
Load Diff
495
tests/fixtures/if-then-else.json
vendored
Normal file
495
tests/fixtures/if-then-else.json
vendored
Normal file
@ -0,0 +1,495 @@
|
||||
[
|
||||
{
|
||||
"description": "ignore if without then or else",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"if": {
|
||||
"const": 0
|
||||
},
|
||||
"$id": "if-then-else_0_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "valid when valid against lone if",
|
||||
"data": 0,
|
||||
"valid": true,
|
||||
"schema_id": "if-then-else_0_0"
|
||||
},
|
||||
{
|
||||
"description": "valid when invalid against lone if",
|
||||
"data": "hello",
|
||||
"valid": true,
|
||||
"schema_id": "if-then-else_0_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "ignore then without if",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"then": {
|
||||
"const": 0
|
||||
},
|
||||
"$id": "if-then-else_1_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "valid when valid against lone then",
|
||||
"data": 0,
|
||||
"valid": true,
|
||||
"schema_id": "if-then-else_1_0"
|
||||
},
|
||||
{
|
||||
"description": "valid when invalid against lone then",
|
||||
"data": "hello",
|
||||
"valid": true,
|
||||
"schema_id": "if-then-else_1_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "ignore else without if",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"else": {
|
||||
"const": 0
|
||||
},
|
||||
"$id": "if-then-else_2_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "valid when valid against lone else",
|
||||
"data": 0,
|
||||
"valid": true,
|
||||
"schema_id": "if-then-else_2_0"
|
||||
},
|
||||
{
|
||||
"description": "valid when invalid against lone else",
|
||||
"data": "hello",
|
||||
"valid": true,
|
||||
"schema_id": "if-then-else_2_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "if and then without else",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"if": {
|
||||
"exclusiveMaximum": 0
|
||||
},
|
||||
"then": {
|
||||
"minimum": -10
|
||||
},
|
||||
"$id": "if-then-else_3_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "valid through then",
|
||||
"data": -1,
|
||||
"valid": true,
|
||||
"schema_id": "if-then-else_3_0"
|
||||
},
|
||||
{
|
||||
"description": "invalid through then",
|
||||
"data": -100,
|
||||
"valid": false,
|
||||
"schema_id": "if-then-else_3_0"
|
||||
},
|
||||
{
|
||||
"description": "valid when if test fails",
|
||||
"data": 3,
|
||||
"valid": true,
|
||||
"schema_id": "if-then-else_3_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "if and else without then",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"if": {
|
||||
"exclusiveMaximum": 0
|
||||
},
|
||||
"else": {
|
||||
"multipleOf": 2
|
||||
},
|
||||
"$id": "if-then-else_4_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "valid when if test passes",
|
||||
"data": -1,
|
||||
"valid": true,
|
||||
"schema_id": "if-then-else_4_0"
|
||||
},
|
||||
{
|
||||
"description": "valid through else",
|
||||
"data": 4,
|
||||
"valid": true,
|
||||
"schema_id": "if-then-else_4_0"
|
||||
},
|
||||
{
|
||||
"description": "invalid through else",
|
||||
"data": 3,
|
||||
"valid": false,
|
||||
"schema_id": "if-then-else_4_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "validate against correct branch, then vs else",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"if": {
|
||||
"exclusiveMaximum": 0
|
||||
},
|
||||
"then": {
|
||||
"minimum": -10
|
||||
},
|
||||
"else": {
|
||||
"multipleOf": 2
|
||||
},
|
||||
"$id": "if-then-else_5_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "valid through then",
|
||||
"data": -1,
|
||||
"valid": true,
|
||||
"schema_id": "if-then-else_5_0"
|
||||
},
|
||||
{
|
||||
"description": "invalid through then",
|
||||
"data": -100,
|
||||
"valid": false,
|
||||
"schema_id": "if-then-else_5_0"
|
||||
},
|
||||
{
|
||||
"description": "valid through else",
|
||||
"data": 4,
|
||||
"valid": true,
|
||||
"schema_id": "if-then-else_5_0"
|
||||
},
|
||||
{
|
||||
"description": "invalid through else",
|
||||
"data": 3,
|
||||
"valid": false,
|
||||
"schema_id": "if-then-else_5_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "non-interference across combined schemas",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"allOf": [
|
||||
{
|
||||
"if": {
|
||||
"exclusiveMaximum": 0
|
||||
}
|
||||
},
|
||||
{
|
||||
"then": {
|
||||
"minimum": -10
|
||||
}
|
||||
},
|
||||
{
|
||||
"else": {
|
||||
"multipleOf": 2
|
||||
}
|
||||
}
|
||||
],
|
||||
"$id": "if-then-else_6_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "valid, but would have been invalid through then",
|
||||
"data": -100,
|
||||
"valid": true,
|
||||
"schema_id": "if-then-else_6_0"
|
||||
},
|
||||
{
|
||||
"description": "valid, but would have been invalid through else",
|
||||
"data": 3,
|
||||
"valid": true,
|
||||
"schema_id": "if-then-else_6_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "if with boolean schema true",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"if": true,
|
||||
"then": {
|
||||
"const": "then"
|
||||
},
|
||||
"else": {
|
||||
"const": "else"
|
||||
},
|
||||
"$id": "if-then-else_7_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "boolean schema true in if always chooses the then path (valid)",
|
||||
"data": "then",
|
||||
"valid": true,
|
||||
"schema_id": "if-then-else_7_0"
|
||||
},
|
||||
{
|
||||
"description": "boolean schema true in if always chooses the then path (invalid)",
|
||||
"data": "else",
|
||||
"valid": false,
|
||||
"schema_id": "if-then-else_7_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "if with boolean schema false",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"if": false,
|
||||
"then": {
|
||||
"const": "then"
|
||||
},
|
||||
"else": {
|
||||
"const": "else"
|
||||
},
|
||||
"$id": "if-then-else_8_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "boolean schema false in if always chooses the else path (invalid)",
|
||||
"data": "then",
|
||||
"valid": false,
|
||||
"schema_id": "if-then-else_8_0"
|
||||
},
|
||||
{
|
||||
"description": "boolean schema false in if always chooses the else path (valid)",
|
||||
"data": "else",
|
||||
"valid": true,
|
||||
"schema_id": "if-then-else_8_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "if appears at the end when serialized (keyword processing sequence)",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"then": {
|
||||
"const": "yes"
|
||||
},
|
||||
"else": {
|
||||
"const": "other"
|
||||
},
|
||||
"if": {
|
||||
"maxLength": 4
|
||||
},
|
||||
"$id": "if-then-else_9_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "yes redirects to then and passes",
|
||||
"data": "yes",
|
||||
"valid": true,
|
||||
"schema_id": "if-then-else_9_0"
|
||||
},
|
||||
{
|
||||
"description": "other redirects to else and passes",
|
||||
"data": "other",
|
||||
"valid": true,
|
||||
"schema_id": "if-then-else_9_0"
|
||||
},
|
||||
{
|
||||
"description": "no redirects to then and fails",
|
||||
"data": "no",
|
||||
"valid": false,
|
||||
"schema_id": "if-then-else_9_0"
|
||||
},
|
||||
{
|
||||
"description": "invalid redirects to else and fails",
|
||||
"data": "invalid",
|
||||
"valid": false,
|
||||
"schema_id": "if-then-else_9_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "then: false fails when condition matches",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"if": {
|
||||
"const": 1
|
||||
},
|
||||
"then": false,
|
||||
"$id": "if-then-else_10_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "matches if → then=false → invalid",
|
||||
"data": 1,
|
||||
"valid": false,
|
||||
"schema_id": "if-then-else_10_0"
|
||||
},
|
||||
{
|
||||
"description": "does not match if → then ignored → valid",
|
||||
"data": 2,
|
||||
"valid": true,
|
||||
"schema_id": "if-then-else_10_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "else: false fails when condition does not match",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"if": {
|
||||
"const": 1
|
||||
},
|
||||
"else": false,
|
||||
"$id": "if-then-else_11_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "matches if → else ignored → valid",
|
||||
"data": 1,
|
||||
"valid": true,
|
||||
"schema_id": "if-then-else_11_0"
|
||||
},
|
||||
{
|
||||
"description": "does not match if → else executes → invalid",
|
||||
"data": 2,
|
||||
"valid": false,
|
||||
"schema_id": "if-then-else_11_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "extensible: true allows extra properties in if-then-else",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"if": {
|
||||
"properties": {
|
||||
"foo": {
|
||||
"const": 1
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"foo"
|
||||
]
|
||||
},
|
||||
"then": {
|
||||
"properties": {
|
||||
"bar": {
|
||||
"const": 2
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"bar"
|
||||
]
|
||||
},
|
||||
"extensible": true,
|
||||
"$id": "if-then-else_12_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "extra property is valid (matches if and then)",
|
||||
"data": {
|
||||
"foo": 1,
|
||||
"bar": 2,
|
||||
"extra": "prop"
|
||||
},
|
||||
"valid": true,
|
||||
"schema_id": "if-then-else_12_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "strict by default with if-then properties",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"if": {
|
||||
"properties": {
|
||||
"foo": {
|
||||
"const": 1
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"foo"
|
||||
]
|
||||
},
|
||||
"then": {
|
||||
"properties": {
|
||||
"bar": {
|
||||
"const": 2
|
||||
}
|
||||
}
|
||||
},
|
||||
"$id": "if-then-else_13_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "valid match (foo + bar)",
|
||||
"data": {
|
||||
"foo": 1,
|
||||
"bar": 2
|
||||
},
|
||||
"valid": true,
|
||||
"schema_id": "if-then-else_13_0"
|
||||
},
|
||||
{
|
||||
"description": "fails on extra property z explicitly",
|
||||
"data": {
|
||||
"foo": 1,
|
||||
"bar": 2,
|
||||
"z": 3
|
||||
},
|
||||
"valid": false,
|
||||
"schema_id": "if-then-else_13_0"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
843
tests/fixtures/items.json
vendored
Normal file
843
tests/fixtures/items.json
vendored
Normal file
@ -0,0 +1,843 @@
|
||||
[
|
||||
{
|
||||
"description": "a schema given for items",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"items": {
|
||||
"type": "integer"
|
||||
},
|
||||
"$id": "items_0_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "valid items",
|
||||
"data": [
|
||||
1,
|
||||
2,
|
||||
3
|
||||
],
|
||||
"valid": true,
|
||||
"schema_id": "items_0_0"
|
||||
},
|
||||
{
|
||||
"description": "wrong type of items",
|
||||
"data": [
|
||||
1,
|
||||
"x"
|
||||
],
|
||||
"valid": false,
|
||||
"schema_id": "items_0_0"
|
||||
},
|
||||
{
|
||||
"description": "non-arrays are invalid",
|
||||
"data": {
|
||||
"foo": "bar"
|
||||
},
|
||||
"valid": false,
|
||||
"schema_id": "items_0_0"
|
||||
},
|
||||
{
|
||||
"description": "JavaScript pseudo-arrays are invalid",
|
||||
"data": {
|
||||
"0": "invalid",
|
||||
"length": 1
|
||||
},
|
||||
"valid": false,
|
||||
"schema_id": "items_0_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "items with boolean schema (true)",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"items": true,
|
||||
"$id": "items_1_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "any array is valid",
|
||||
"data": [
|
||||
1,
|
||||
"foo",
|
||||
true
|
||||
],
|
||||
"valid": true,
|
||||
"schema_id": "items_1_0"
|
||||
},
|
||||
{
|
||||
"description": "empty array is valid",
|
||||
"data": [],
|
||||
"valid": true,
|
||||
"schema_id": "items_1_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "items with boolean schema (false)",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"items": false,
|
||||
"$id": "items_2_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "any non-empty array is invalid",
|
||||
"data": [
|
||||
1,
|
||||
"foo",
|
||||
true
|
||||
],
|
||||
"valid": false,
|
||||
"schema_id": "items_2_0"
|
||||
},
|
||||
{
|
||||
"description": "empty array is valid",
|
||||
"data": [],
|
||||
"valid": true,
|
||||
"schema_id": "items_2_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "items and subitems",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"type": "array",
|
||||
"items": false,
|
||||
"prefixItems": [
|
||||
{
|
||||
"$ref": "item"
|
||||
},
|
||||
{
|
||||
"$ref": "item"
|
||||
},
|
||||
{
|
||||
"$ref": "item"
|
||||
}
|
||||
],
|
||||
"$id": "items_3_0"
|
||||
},
|
||||
{
|
||||
"$id": "item",
|
||||
"type": "array",
|
||||
"items": false,
|
||||
"prefixItems": [
|
||||
{
|
||||
"$ref": "sub-item"
|
||||
},
|
||||
{
|
||||
"$ref": "sub-item"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"$id": "sub-item",
|
||||
"type": "object",
|
||||
"required": [
|
||||
"foo"
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "valid items",
|
||||
"data": [
|
||||
[
|
||||
{
|
||||
"foo": null
|
||||
},
|
||||
{
|
||||
"foo": null
|
||||
}
|
||||
],
|
||||
[
|
||||
{
|
||||
"foo": null
|
||||
},
|
||||
{
|
||||
"foo": null
|
||||
}
|
||||
],
|
||||
[
|
||||
{
|
||||
"foo": null
|
||||
},
|
||||
{
|
||||
"foo": null
|
||||
}
|
||||
]
|
||||
],
|
||||
"valid": false,
|
||||
"schema_id": "items_3_0"
|
||||
},
|
||||
{
|
||||
"description": "too many items",
|
||||
"data": [
|
||||
[
|
||||
{
|
||||
"foo": null
|
||||
},
|
||||
{
|
||||
"foo": null
|
||||
}
|
||||
],
|
||||
[
|
||||
{
|
||||
"foo": null
|
||||
},
|
||||
{
|
||||
"foo": null
|
||||
}
|
||||
],
|
||||
[
|
||||
{
|
||||
"foo": null
|
||||
},
|
||||
{
|
||||
"foo": null
|
||||
}
|
||||
],
|
||||
[
|
||||
{
|
||||
"foo": null
|
||||
},
|
||||
{
|
||||
"foo": null
|
||||
}
|
||||
]
|
||||
],
|
||||
"valid": false,
|
||||
"schema_id": "items_3_0"
|
||||
},
|
||||
{
|
||||
"description": "too many sub-items",
|
||||
"data": [
|
||||
[
|
||||
{
|
||||
"foo": null
|
||||
},
|
||||
{
|
||||
"foo": null
|
||||
},
|
||||
{
|
||||
"foo": null
|
||||
}
|
||||
],
|
||||
[
|
||||
{
|
||||
"foo": null
|
||||
},
|
||||
{
|
||||
"foo": null
|
||||
}
|
||||
],
|
||||
[
|
||||
{
|
||||
"foo": null
|
||||
},
|
||||
{
|
||||
"foo": null
|
||||
}
|
||||
]
|
||||
],
|
||||
"valid": false,
|
||||
"schema_id": "items_3_0"
|
||||
},
|
||||
{
|
||||
"description": "wrong item",
|
||||
"data": [
|
||||
{
|
||||
"foo": null
|
||||
},
|
||||
[
|
||||
{
|
||||
"foo": null
|
||||
},
|
||||
{
|
||||
"foo": null
|
||||
}
|
||||
],
|
||||
[
|
||||
{
|
||||
"foo": null
|
||||
},
|
||||
{
|
||||
"foo": null
|
||||
}
|
||||
]
|
||||
],
|
||||
"valid": false,
|
||||
"schema_id": "items_3_0"
|
||||
},
|
||||
{
|
||||
"description": "wrong sub-item",
|
||||
"data": [
|
||||
[
|
||||
{},
|
||||
{
|
||||
"foo": null
|
||||
}
|
||||
],
|
||||
[
|
||||
{
|
||||
"foo": null
|
||||
},
|
||||
{
|
||||
"foo": null
|
||||
}
|
||||
],
|
||||
[
|
||||
{
|
||||
"foo": null
|
||||
},
|
||||
{
|
||||
"foo": null
|
||||
}
|
||||
]
|
||||
],
|
||||
"valid": false,
|
||||
"schema_id": "items_3_0"
|
||||
},
|
||||
{
|
||||
"description": "fewer items is invalid",
|
||||
"data": [
|
||||
[
|
||||
{
|
||||
"foo": null
|
||||
}
|
||||
],
|
||||
[
|
||||
{
|
||||
"foo": null
|
||||
}
|
||||
]
|
||||
],
|
||||
"valid": false,
|
||||
"schema_id": "items_3_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "nested items",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "number"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"$id": "items_4_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "valid nested array",
|
||||
"data": [
|
||||
[
|
||||
[
|
||||
[
|
||||
1
|
||||
]
|
||||
],
|
||||
[
|
||||
[
|
||||
2
|
||||
],
|
||||
[
|
||||
3
|
||||
]
|
||||
]
|
||||
],
|
||||
[
|
||||
[
|
||||
[
|
||||
4
|
||||
],
|
||||
[
|
||||
5
|
||||
],
|
||||
[
|
||||
6
|
||||
]
|
||||
]
|
||||
]
|
||||
],
|
||||
"valid": true,
|
||||
"schema_id": "items_4_0"
|
||||
},
|
||||
{
|
||||
"description": "nested array with invalid type",
|
||||
"data": [
|
||||
[
|
||||
[
|
||||
[
|
||||
"1"
|
||||
]
|
||||
],
|
||||
[
|
||||
[
|
||||
2
|
||||
],
|
||||
[
|
||||
3
|
||||
]
|
||||
]
|
||||
],
|
||||
[
|
||||
[
|
||||
[
|
||||
4
|
||||
],
|
||||
[
|
||||
5
|
||||
],
|
||||
[
|
||||
6
|
||||
]
|
||||
]
|
||||
]
|
||||
],
|
||||
"valid": false,
|
||||
"schema_id": "items_4_0"
|
||||
},
|
||||
{
|
||||
"description": "not deep enough",
|
||||
"data": [
|
||||
[
|
||||
[
|
||||
1
|
||||
],
|
||||
[
|
||||
2
|
||||
],
|
||||
[
|
||||
3
|
||||
]
|
||||
],
|
||||
[
|
||||
[
|
||||
4
|
||||
],
|
||||
[
|
||||
5
|
||||
],
|
||||
[
|
||||
6
|
||||
]
|
||||
]
|
||||
],
|
||||
"valid": false,
|
||||
"schema_id": "items_4_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "prefixItems with no additional items allowed",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"prefixItems": [
|
||||
{},
|
||||
{},
|
||||
{}
|
||||
],
|
||||
"items": false,
|
||||
"$id": "items_5_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "empty array",
|
||||
"data": [],
|
||||
"valid": true,
|
||||
"schema_id": "items_5_0"
|
||||
},
|
||||
{
|
||||
"description": "fewer number of items present (1)",
|
||||
"data": [
|
||||
1
|
||||
],
|
||||
"valid": true,
|
||||
"schema_id": "items_5_0"
|
||||
},
|
||||
{
|
||||
"description": "fewer number of items present (2)",
|
||||
"data": [
|
||||
1,
|
||||
2
|
||||
],
|
||||
"valid": true,
|
||||
"schema_id": "items_5_0"
|
||||
},
|
||||
{
|
||||
"description": "equal number of items present",
|
||||
"data": [
|
||||
1,
|
||||
2,
|
||||
3
|
||||
],
|
||||
"valid": true,
|
||||
"schema_id": "items_5_0"
|
||||
},
|
||||
{
|
||||
"description": "additional items are not permitted",
|
||||
"data": [
|
||||
1,
|
||||
2,
|
||||
3,
|
||||
4
|
||||
],
|
||||
"valid": false,
|
||||
"schema_id": "items_5_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "items does not look in applicators, valid case",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"allOf": [
|
||||
{
|
||||
"prefixItems": [
|
||||
{
|
||||
"minimum": 3
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"items": {
|
||||
"minimum": 5
|
||||
},
|
||||
"$id": "items_6_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "prefixItems in allOf does not constrain items, invalid case",
|
||||
"data": [
|
||||
3,
|
||||
5
|
||||
],
|
||||
"valid": false,
|
||||
"schema_id": "items_6_0"
|
||||
},
|
||||
{
|
||||
"description": "prefixItems in allOf does not constrain items, valid case",
|
||||
"data": [
|
||||
5,
|
||||
5
|
||||
],
|
||||
"valid": true,
|
||||
"schema_id": "items_6_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "prefixItems validation adjusts the starting index for items",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"prefixItems": [
|
||||
{
|
||||
"type": "string"
|
||||
}
|
||||
],
|
||||
"items": {
|
||||
"type": "integer"
|
||||
},
|
||||
"$id": "items_7_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "valid items",
|
||||
"data": [
|
||||
"x",
|
||||
2,
|
||||
3
|
||||
],
|
||||
"valid": true,
|
||||
"schema_id": "items_7_0"
|
||||
},
|
||||
{
|
||||
"description": "wrong type of second item",
|
||||
"data": [
|
||||
"x",
|
||||
"y"
|
||||
],
|
||||
"valid": false,
|
||||
"schema_id": "items_7_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "items with heterogeneous array",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"prefixItems": [
|
||||
{}
|
||||
],
|
||||
"items": false,
|
||||
"$id": "items_8_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "heterogeneous invalid instance",
|
||||
"data": [
|
||||
"foo",
|
||||
"bar",
|
||||
37
|
||||
],
|
||||
"valid": false,
|
||||
"schema_id": "items_8_0"
|
||||
},
|
||||
{
|
||||
"description": "valid instance",
|
||||
"data": [
|
||||
null
|
||||
],
|
||||
"valid": true,
|
||||
"schema_id": "items_8_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "items with null instance elements",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"items": {
|
||||
"type": "null"
|
||||
},
|
||||
"$id": "items_9_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "allows null elements",
|
||||
"data": [
|
||||
null
|
||||
],
|
||||
"valid": true,
|
||||
"schema_id": "items_9_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "extensible: true allows extra items (when items is false)",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"items": false,
|
||||
"extensible": true,
|
||||
"$id": "items_10_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "extra item is valid",
|
||||
"data": [
|
||||
1
|
||||
],
|
||||
"valid": false,
|
||||
"schema_id": "items_10_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "extensible: true allows extra properties for items",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"items": {
|
||||
"minimum": 5
|
||||
},
|
||||
"extensible": true,
|
||||
"$id": "items_11_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "valid item is valid",
|
||||
"data": [
|
||||
5,
|
||||
6
|
||||
],
|
||||
"valid": true,
|
||||
"schema_id": "items_11_0"
|
||||
},
|
||||
{
|
||||
"description": "invalid item (less than min) is invalid even with extensible: true",
|
||||
"data": [
|
||||
4
|
||||
],
|
||||
"valid": false,
|
||||
"schema_id": "items_11_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "array: simple extensible array",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"type": "array",
|
||||
"extensible": true,
|
||||
"$id": "items_12_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "empty array is valid",
|
||||
"data": [],
|
||||
"valid": true,
|
||||
"schema_id": "items_12_0"
|
||||
},
|
||||
{
|
||||
"description": "array with items is valid (extensible)",
|
||||
"data": [
|
||||
1,
|
||||
"foo"
|
||||
],
|
||||
"valid": true,
|
||||
"schema_id": "items_12_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "array: strict array",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"type": "array",
|
||||
"extensible": false,
|
||||
"$id": "items_13_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "empty array is valid",
|
||||
"data": [],
|
||||
"valid": true,
|
||||
"schema_id": "items_13_0"
|
||||
},
|
||||
{
|
||||
"description": "array with items is invalid (strict)",
|
||||
"data": [
|
||||
1
|
||||
],
|
||||
"valid": false,
|
||||
"schema_id": "items_13_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "array: items extensible",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"type": "array",
|
||||
"items": {
|
||||
"extensible": true
|
||||
},
|
||||
"$id": "items_14_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "empty array is valid",
|
||||
"data": [],
|
||||
"valid": true,
|
||||
"schema_id": "items_14_0"
|
||||
},
|
||||
{
|
||||
"description": "array with items is valid (items explicitly allowed to be anything extensible)",
|
||||
"data": [
|
||||
1,
|
||||
"foo",
|
||||
{}
|
||||
],
|
||||
"valid": true,
|
||||
"schema_id": "items_14_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "array: items strict",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "object",
|
||||
"extensible": false
|
||||
},
|
||||
"$id": "items_15_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "empty array is valid (empty objects)",
|
||||
"data": [
|
||||
{}
|
||||
],
|
||||
"valid": true,
|
||||
"schema_id": "items_15_0"
|
||||
},
|
||||
{
|
||||
"description": "array with strict object items is valid",
|
||||
"data": [
|
||||
{}
|
||||
],
|
||||
"valid": true,
|
||||
"schema_id": "items_15_0"
|
||||
},
|
||||
{
|
||||
"description": "array with invalid strict object items (extra property)",
|
||||
"data": [
|
||||
{
|
||||
"extra": 1
|
||||
}
|
||||
],
|
||||
"valid": false,
|
||||
"schema_id": "items_15_0"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
196
tests/fixtures/maxContains.json
vendored
Normal file
196
tests/fixtures/maxContains.json
vendored
Normal file
@ -0,0 +1,196 @@
|
||||
[
|
||||
{
|
||||
"description": "maxContains without contains is ignored",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"maxContains": 1,
|
||||
"extensible": true,
|
||||
"$id": "maxContains_0_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "one item valid against lone maxContains",
|
||||
"data": [
|
||||
1
|
||||
],
|
||||
"valid": true,
|
||||
"schema_id": "maxContains_0_0"
|
||||
},
|
||||
{
|
||||
"description": "two items still valid against lone maxContains",
|
||||
"data": [
|
||||
1,
|
||||
2
|
||||
],
|
||||
"valid": true,
|
||||
"schema_id": "maxContains_0_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "maxContains with contains",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"contains": {
|
||||
"const": 1
|
||||
},
|
||||
"maxContains": 1,
|
||||
"extensible": true,
|
||||
"$id": "maxContains_1_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "empty data",
|
||||
"data": [],
|
||||
"valid": false,
|
||||
"schema_id": "maxContains_1_0"
|
||||
},
|
||||
{
|
||||
"description": "all elements match, valid maxContains",
|
||||
"data": [
|
||||
1
|
||||
],
|
||||
"valid": true,
|
||||
"schema_id": "maxContains_1_0"
|
||||
},
|
||||
{
|
||||
"description": "all elements match, invalid maxContains",
|
||||
"data": [
|
||||
1,
|
||||
1
|
||||
],
|
||||
"valid": false,
|
||||
"schema_id": "maxContains_1_0"
|
||||
},
|
||||
{
|
||||
"description": "some elements match, valid maxContains",
|
||||
"data": [
|
||||
1,
|
||||
2
|
||||
],
|
||||
"valid": true,
|
||||
"schema_id": "maxContains_1_0"
|
||||
},
|
||||
{
|
||||
"description": "some elements match, invalid maxContains",
|
||||
"data": [
|
||||
1,
|
||||
2,
|
||||
1
|
||||
],
|
||||
"valid": false,
|
||||
"schema_id": "maxContains_1_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "maxContains with contains, value with a decimal",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"contains": {
|
||||
"const": 1
|
||||
},
|
||||
"maxContains": 1,
|
||||
"extensible": true,
|
||||
"$id": "maxContains_2_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "one element matches, valid maxContains",
|
||||
"data": [
|
||||
1
|
||||
],
|
||||
"valid": true,
|
||||
"schema_id": "maxContains_2_0"
|
||||
},
|
||||
{
|
||||
"description": "too many elements match, invalid maxContains",
|
||||
"data": [
|
||||
1,
|
||||
1
|
||||
],
|
||||
"valid": false,
|
||||
"schema_id": "maxContains_2_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "minContains < maxContains",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"contains": {
|
||||
"const": 1
|
||||
},
|
||||
"minContains": 1,
|
||||
"maxContains": 3,
|
||||
"extensible": true,
|
||||
"$id": "maxContains_3_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "actual < minContains < maxContains",
|
||||
"data": [],
|
||||
"valid": false,
|
||||
"schema_id": "maxContains_3_0"
|
||||
},
|
||||
{
|
||||
"description": "minContains < actual < maxContains",
|
||||
"data": [
|
||||
1,
|
||||
1
|
||||
],
|
||||
"valid": true,
|
||||
"schema_id": "maxContains_3_0"
|
||||
},
|
||||
{
|
||||
"description": "minContains < maxContains < actual",
|
||||
"data": [
|
||||
1,
|
||||
1,
|
||||
1,
|
||||
1
|
||||
],
|
||||
"valid": false,
|
||||
"schema_id": "maxContains_3_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "extensible: true allows non-matching items in maxContains",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"contains": {
|
||||
"const": 1
|
||||
},
|
||||
"maxContains": 1,
|
||||
"extensible": true,
|
||||
"$id": "maxContains_4_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "extra items disregarded for maxContains",
|
||||
"data": [
|
||||
1,
|
||||
2
|
||||
],
|
||||
"valid": true,
|
||||
"schema_id": "maxContains_4_0"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
105
tests/fixtures/maxItems.json
vendored
Normal file
105
tests/fixtures/maxItems.json
vendored
Normal file
@ -0,0 +1,105 @@
|
||||
[
|
||||
{
|
||||
"description": "maxItems validation",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"maxItems": 2,
|
||||
"extensible": true,
|
||||
"$id": "maxItems_0_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "shorter is valid",
|
||||
"data": [
|
||||
1
|
||||
],
|
||||
"valid": true,
|
||||
"schema_id": "maxItems_0_0"
|
||||
},
|
||||
{
|
||||
"description": "exact length is valid",
|
||||
"data": [
|
||||
1,
|
||||
2
|
||||
],
|
||||
"valid": true,
|
||||
"schema_id": "maxItems_0_0"
|
||||
},
|
||||
{
|
||||
"description": "too long is invalid",
|
||||
"data": [
|
||||
1,
|
||||
2,
|
||||
3
|
||||
],
|
||||
"valid": false,
|
||||
"schema_id": "maxItems_0_0"
|
||||
},
|
||||
{
|
||||
"description": "ignores non-arrays",
|
||||
"data": "foobar",
|
||||
"valid": true,
|
||||
"schema_id": "maxItems_0_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "maxItems validation with a decimal",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"maxItems": 2,
|
||||
"extensible": true,
|
||||
"$id": "maxItems_1_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "shorter is valid",
|
||||
"data": [
|
||||
1
|
||||
],
|
||||
"valid": true,
|
||||
"schema_id": "maxItems_1_0"
|
||||
},
|
||||
{
|
||||
"description": "too long is invalid",
|
||||
"data": [
|
||||
1,
|
||||
2,
|
||||
3
|
||||
],
|
||||
"valid": false,
|
||||
"schema_id": "maxItems_1_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "extensible: true allows extra items in maxItems (but counted)",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"maxItems": 2,
|
||||
"extensible": true,
|
||||
"$id": "maxItems_2_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "extra item counted towards maxItems",
|
||||
"data": [
|
||||
1,
|
||||
2,
|
||||
3
|
||||
],
|
||||
"valid": false,
|
||||
"schema_id": "maxItems_2_0"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
70
tests/fixtures/maxLength.json
vendored
Normal file
70
tests/fixtures/maxLength.json
vendored
Normal file
@ -0,0 +1,70 @@
|
||||
[
|
||||
{
|
||||
"description": "maxLength validation",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"maxLength": 2,
|
||||
"$id": "maxLength_0_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "shorter is valid",
|
||||
"data": "f",
|
||||
"valid": true,
|
||||
"schema_id": "maxLength_0_0"
|
||||
},
|
||||
{
|
||||
"description": "exact length is valid",
|
||||
"data": "fo",
|
||||
"valid": true,
|
||||
"schema_id": "maxLength_0_0"
|
||||
},
|
||||
{
|
||||
"description": "too long is invalid",
|
||||
"data": "foo",
|
||||
"valid": false,
|
||||
"schema_id": "maxLength_0_0"
|
||||
},
|
||||
{
|
||||
"description": "ignores non-strings",
|
||||
"data": 100,
|
||||
"valid": true,
|
||||
"schema_id": "maxLength_0_0"
|
||||
},
|
||||
{
|
||||
"description": "two graphemes is long enough",
|
||||
"data": "💩💩",
|
||||
"valid": true,
|
||||
"schema_id": "maxLength_0_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "maxLength validation with a decimal",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"maxLength": 2,
|
||||
"$id": "maxLength_1_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "shorter is valid",
|
||||
"data": "f",
|
||||
"valid": true,
|
||||
"schema_id": "maxLength_1_0"
|
||||
},
|
||||
{
|
||||
"description": "too long is invalid",
|
||||
"data": "foo",
|
||||
"valid": false,
|
||||
"schema_id": "maxLength_1_0"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
157
tests/fixtures/maxProperties.json
vendored
Normal file
157
tests/fixtures/maxProperties.json
vendored
Normal file
@ -0,0 +1,157 @@
|
||||
[
|
||||
{
|
||||
"description": "maxProperties validation",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"maxProperties": 2,
|
||||
"extensible": true,
|
||||
"$id": "maxProperties_0_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "shorter is valid",
|
||||
"data": {
|
||||
"foo": 1
|
||||
},
|
||||
"valid": true,
|
||||
"schema_id": "maxProperties_0_0"
|
||||
},
|
||||
{
|
||||
"description": "exact length is valid",
|
||||
"data": {
|
||||
"foo": 1,
|
||||
"bar": 2
|
||||
},
|
||||
"valid": true,
|
||||
"schema_id": "maxProperties_0_0"
|
||||
},
|
||||
{
|
||||
"description": "too long is invalid",
|
||||
"data": {
|
||||
"foo": 1,
|
||||
"bar": 2,
|
||||
"baz": 3
|
||||
},
|
||||
"valid": false,
|
||||
"schema_id": "maxProperties_0_0"
|
||||
},
|
||||
{
|
||||
"description": "ignores arrays",
|
||||
"data": [
|
||||
1,
|
||||
2,
|
||||
3
|
||||
],
|
||||
"valid": true,
|
||||
"schema_id": "maxProperties_0_0"
|
||||
},
|
||||
{
|
||||
"description": "ignores strings",
|
||||
"data": "foobar",
|
||||
"valid": true,
|
||||
"schema_id": "maxProperties_0_0"
|
||||
},
|
||||
{
|
||||
"description": "ignores other non-objects",
|
||||
"data": 12,
|
||||
"valid": true,
|
||||
"schema_id": "maxProperties_0_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "maxProperties validation with a decimal",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"maxProperties": 2,
|
||||
"extensible": true,
|
||||
"$id": "maxProperties_1_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "shorter is valid",
|
||||
"data": {
|
||||
"foo": 1
|
||||
},
|
||||
"valid": true,
|
||||
"schema_id": "maxProperties_1_0"
|
||||
},
|
||||
{
|
||||
"description": "too long is invalid",
|
||||
"data": {
|
||||
"foo": 1,
|
||||
"bar": 2,
|
||||
"baz": 3
|
||||
},
|
||||
"valid": false,
|
||||
"schema_id": "maxProperties_1_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "maxProperties = 0 means the object is empty",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"maxProperties": 0,
|
||||
"extensible": true,
|
||||
"$id": "maxProperties_2_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "no properties is valid",
|
||||
"data": {},
|
||||
"valid": true,
|
||||
"schema_id": "maxProperties_2_0"
|
||||
},
|
||||
{
|
||||
"description": "one property is invalid",
|
||||
"data": {
|
||||
"foo": 1
|
||||
},
|
||||
"valid": false,
|
||||
"schema_id": "maxProperties_2_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "extensible: true allows extra properties in maxProperties (though maxProperties still counts them!)",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"maxProperties": 2,
|
||||
"extensible": true,
|
||||
"$id": "maxProperties_3_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "extra property is counted towards maxProperties",
|
||||
"data": {
|
||||
"foo": 1,
|
||||
"bar": 2,
|
||||
"baz": 3
|
||||
},
|
||||
"valid": false,
|
||||
"schema_id": "maxProperties_3_0"
|
||||
},
|
||||
{
|
||||
"description": "extra property is valid if below maxProperties",
|
||||
"data": {
|
||||
"foo": 1
|
||||
},
|
||||
"valid": true,
|
||||
"schema_id": "maxProperties_3_0"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
76
tests/fixtures/maximum.json
vendored
Normal file
76
tests/fixtures/maximum.json
vendored
Normal file
@ -0,0 +1,76 @@
|
||||
[
|
||||
{
|
||||
"description": "maximum validation",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"maximum": 3,
|
||||
"$id": "maximum_0_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "below the maximum is valid",
|
||||
"data": 2.6,
|
||||
"valid": true,
|
||||
"schema_id": "maximum_0_0"
|
||||
},
|
||||
{
|
||||
"description": "boundary point is valid",
|
||||
"data": 3,
|
||||
"valid": true,
|
||||
"schema_id": "maximum_0_0"
|
||||
},
|
||||
{
|
||||
"description": "above the maximum is invalid",
|
||||
"data": 3.5,
|
||||
"valid": false,
|
||||
"schema_id": "maximum_0_0"
|
||||
},
|
||||
{
|
||||
"description": "ignores non-numbers",
|
||||
"data": "x",
|
||||
"valid": true,
|
||||
"schema_id": "maximum_0_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "maximum validation with unsigned integer",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"maximum": 300,
|
||||
"$id": "maximum_1_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "below the maximum is invalid",
|
||||
"data": 299.97,
|
||||
"valid": true,
|
||||
"schema_id": "maximum_1_0"
|
||||
},
|
||||
{
|
||||
"description": "boundary point integer is valid",
|
||||
"data": 300,
|
||||
"valid": true,
|
||||
"schema_id": "maximum_1_0"
|
||||
},
|
||||
{
|
||||
"description": "boundary point float is valid",
|
||||
"data": 300,
|
||||
"valid": true,
|
||||
"schema_id": "maximum_1_0"
|
||||
},
|
||||
{
|
||||
"description": "above the maximum is invalid",
|
||||
"data": 300.5,
|
||||
"valid": false,
|
||||
"schema_id": "maximum_1_0"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
247
tests/fixtures/merge.json
vendored
Normal file
247
tests/fixtures/merge.json
vendored
Normal file
@ -0,0 +1,247 @@
|
||||
[
|
||||
{
|
||||
"description": "merging: properties accumulate",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"$id": "base_0",
|
||||
"properties": {
|
||||
"base_prop": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"$ref": "base_0",
|
||||
"properties": {
|
||||
"child_prop": {
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"$id": "merge_0_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "valid with both properties",
|
||||
"data": {
|
||||
"base_prop": "a",
|
||||
"child_prop": "b"
|
||||
},
|
||||
"valid": true,
|
||||
"schema_id": "merge_0_0"
|
||||
},
|
||||
{
|
||||
"description": "invalid when base property has wrong type",
|
||||
"data": {
|
||||
"base_prop": 1,
|
||||
"child_prop": "b"
|
||||
},
|
||||
"valid": false,
|
||||
"expect_errors": [
|
||||
{
|
||||
"code": "TYPE_MISMATCH",
|
||||
"path": "/base_prop"
|
||||
}
|
||||
],
|
||||
"schema_id": "merge_0_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "merging: required fields accumulate",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"$id": "base_1",
|
||||
"properties": {
|
||||
"a": {
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"a"
|
||||
]
|
||||
},
|
||||
{
|
||||
"$ref": "base_1",
|
||||
"properties": {
|
||||
"b": {
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"b"
|
||||
],
|
||||
"$id": "merge_1_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "valid when both present",
|
||||
"data": {
|
||||
"a": "ok",
|
||||
"b": "ok"
|
||||
},
|
||||
"valid": true,
|
||||
"schema_id": "merge_1_0"
|
||||
},
|
||||
{
|
||||
"description": "invalid when base required missing",
|
||||
"data": {
|
||||
"b": "ok"
|
||||
},
|
||||
"valid": false,
|
||||
"expect_errors": [
|
||||
{
|
||||
"code": "REQUIRED_FIELD_MISSING",
|
||||
"path": "/a"
|
||||
}
|
||||
],
|
||||
"schema_id": "merge_1_0"
|
||||
},
|
||||
{
|
||||
"description": "invalid when child required missing",
|
||||
"data": {
|
||||
"a": "ok"
|
||||
},
|
||||
"valid": false,
|
||||
"expect_errors": [
|
||||
{
|
||||
"code": "REQUIRED_FIELD_MISSING",
|
||||
"path": "/b"
|
||||
}
|
||||
],
|
||||
"schema_id": "merge_1_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "merging: dependencies accumulate",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"$id": "base_2",
|
||||
"properties": {
|
||||
"trigger": {
|
||||
"type": "string"
|
||||
},
|
||||
"base_dep": {
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"dependencies": {
|
||||
"trigger": [
|
||||
"base_dep"
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"$ref": "base_2",
|
||||
"properties": {
|
||||
"child_dep": {
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"dependencies": {
|
||||
"trigger": [
|
||||
"child_dep"
|
||||
]
|
||||
},
|
||||
"$id": "merge_2_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "valid with all deps",
|
||||
"data": {
|
||||
"trigger": "go",
|
||||
"base_dep": "ok",
|
||||
"child_dep": "ok"
|
||||
},
|
||||
"valid": true,
|
||||
"schema_id": "merge_2_0"
|
||||
},
|
||||
{
|
||||
"description": "invalid missing base dep",
|
||||
"data": {
|
||||
"trigger": "go",
|
||||
"child_dep": "ok"
|
||||
},
|
||||
"valid": false,
|
||||
"expect_errors": [
|
||||
{
|
||||
"code": "DEPENDENCY_FAILED",
|
||||
"path": "/base_dep"
|
||||
}
|
||||
],
|
||||
"schema_id": "merge_2_0"
|
||||
},
|
||||
{
|
||||
"description": "invalid missing child dep",
|
||||
"data": {
|
||||
"trigger": "go",
|
||||
"base_dep": "ok"
|
||||
},
|
||||
"valid": false,
|
||||
"expect_errors": [
|
||||
{
|
||||
"code": "DEPENDENCY_FAILED",
|
||||
"path": "/child_dep"
|
||||
}
|
||||
],
|
||||
"schema_id": "merge_2_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "merging: form and display do NOT merge",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"$id": "base_3",
|
||||
"properties": {
|
||||
"a": {
|
||||
"type": "string"
|
||||
},
|
||||
"b": {
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"form": [
|
||||
"a",
|
||||
"b"
|
||||
]
|
||||
},
|
||||
{
|
||||
"$ref": "base_3",
|
||||
"properties": {
|
||||
"c": {
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"form": [
|
||||
"c"
|
||||
],
|
||||
"$id": "merge_3_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "child schema validation",
|
||||
"data": {
|
||||
"a": "ok",
|
||||
"b": "ok",
|
||||
"c": "ok"
|
||||
},
|
||||
"valid": true,
|
||||
"comment": "Verifies validator handles the unmerged metadata correctly (ignores it or handles replacement)",
|
||||
"schema_id": "merge_3_0"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
390
tests/fixtures/minContains.json
vendored
Normal file
390
tests/fixtures/minContains.json
vendored
Normal file
@ -0,0 +1,390 @@
|
||||
[
|
||||
{
|
||||
"description": "minContains without contains is ignored",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"minContains": 1,
|
||||
"extensible": true,
|
||||
"$id": "minContains_0_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "one item valid against lone minContains",
|
||||
"data": [
|
||||
1
|
||||
],
|
||||
"valid": true,
|
||||
"schema_id": "minContains_0_0"
|
||||
},
|
||||
{
|
||||
"description": "zero items still valid against lone minContains",
|
||||
"data": [],
|
||||
"valid": true,
|
||||
"schema_id": "minContains_0_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "minContains=1 with contains",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"contains": {
|
||||
"const": 1
|
||||
},
|
||||
"minContains": 1,
|
||||
"extensible": true,
|
||||
"$id": "minContains_1_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "empty data",
|
||||
"data": [],
|
||||
"valid": false,
|
||||
"schema_id": "minContains_1_0"
|
||||
},
|
||||
{
|
||||
"description": "no elements match",
|
||||
"data": [
|
||||
2
|
||||
],
|
||||
"valid": false,
|
||||
"schema_id": "minContains_1_0"
|
||||
},
|
||||
{
|
||||
"description": "single element matches, valid minContains",
|
||||
"data": [
|
||||
1
|
||||
],
|
||||
"valid": true,
|
||||
"schema_id": "minContains_1_0"
|
||||
},
|
||||
{
|
||||
"description": "some elements match, valid minContains",
|
||||
"data": [
|
||||
1,
|
||||
2
|
||||
],
|
||||
"valid": true,
|
||||
"schema_id": "minContains_1_0"
|
||||
},
|
||||
{
|
||||
"description": "all elements match, valid minContains",
|
||||
"data": [
|
||||
1,
|
||||
1
|
||||
],
|
||||
"valid": true,
|
||||
"schema_id": "minContains_1_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "minContains=2 with contains",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"contains": {
|
||||
"const": 1
|
||||
},
|
||||
"minContains": 2,
|
||||
"extensible": true,
|
||||
"$id": "minContains_2_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "empty data",
|
||||
"data": [],
|
||||
"valid": false,
|
||||
"schema_id": "minContains_2_0"
|
||||
},
|
||||
{
|
||||
"description": "all elements match, invalid minContains",
|
||||
"data": [
|
||||
1
|
||||
],
|
||||
"valid": false,
|
||||
"schema_id": "minContains_2_0"
|
||||
},
|
||||
{
|
||||
"description": "some elements match, invalid minContains",
|
||||
"data": [
|
||||
1,
|
||||
2
|
||||
],
|
||||
"valid": false,
|
||||
"schema_id": "minContains_2_0"
|
||||
},
|
||||
{
|
||||
"description": "all elements match, valid minContains (exactly as needed)",
|
||||
"data": [
|
||||
1,
|
||||
1
|
||||
],
|
||||
"valid": true,
|
||||
"schema_id": "minContains_2_0"
|
||||
},
|
||||
{
|
||||
"description": "all elements match, valid minContains (more than needed)",
|
||||
"data": [
|
||||
1,
|
||||
1,
|
||||
1
|
||||
],
|
||||
"valid": true,
|
||||
"schema_id": "minContains_2_0"
|
||||
},
|
||||
{
|
||||
"description": "some elements match, valid minContains",
|
||||
"data": [
|
||||
1,
|
||||
2,
|
||||
1
|
||||
],
|
||||
"valid": true,
|
||||
"schema_id": "minContains_2_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "minContains=2 with contains with a decimal value",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"contains": {
|
||||
"const": 1
|
||||
},
|
||||
"minContains": 2,
|
||||
"extensible": true,
|
||||
"$id": "minContains_3_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "one element matches, invalid minContains",
|
||||
"data": [
|
||||
1
|
||||
],
|
||||
"valid": false,
|
||||
"schema_id": "minContains_3_0"
|
||||
},
|
||||
{
|
||||
"description": "both elements match, valid minContains",
|
||||
"data": [
|
||||
1,
|
||||
1
|
||||
],
|
||||
"valid": true,
|
||||
"schema_id": "minContains_3_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "maxContains = minContains",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"contains": {
|
||||
"const": 1
|
||||
},
|
||||
"maxContains": 2,
|
||||
"minContains": 2,
|
||||
"extensible": true,
|
||||
"$id": "minContains_4_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "empty data",
|
||||
"data": [],
|
||||
"valid": false,
|
||||
"schema_id": "minContains_4_0"
|
||||
},
|
||||
{
|
||||
"description": "all elements match, invalid minContains",
|
||||
"data": [
|
||||
1
|
||||
],
|
||||
"valid": false,
|
||||
"schema_id": "minContains_4_0"
|
||||
},
|
||||
{
|
||||
"description": "all elements match, invalid maxContains",
|
||||
"data": [
|
||||
1,
|
||||
1,
|
||||
1
|
||||
],
|
||||
"valid": false,
|
||||
"schema_id": "minContains_4_0"
|
||||
},
|
||||
{
|
||||
"description": "all elements match, valid maxContains and minContains",
|
||||
"data": [
|
||||
1,
|
||||
1
|
||||
],
|
||||
"valid": true,
|
||||
"schema_id": "minContains_4_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "maxContains < minContains",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"contains": {
|
||||
"const": 1
|
||||
},
|
||||
"maxContains": 1,
|
||||
"minContains": 3,
|
||||
"extensible": true,
|
||||
"$id": "minContains_5_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "empty data",
|
||||
"data": [],
|
||||
"valid": false,
|
||||
"schema_id": "minContains_5_0"
|
||||
},
|
||||
{
|
||||
"description": "invalid minContains",
|
||||
"data": [
|
||||
1
|
||||
],
|
||||
"valid": false,
|
||||
"schema_id": "minContains_5_0"
|
||||
},
|
||||
{
|
||||
"description": "invalid maxContains",
|
||||
"data": [
|
||||
1,
|
||||
1,
|
||||
1
|
||||
],
|
||||
"valid": false,
|
||||
"schema_id": "minContains_5_0"
|
||||
},
|
||||
{
|
||||
"description": "invalid maxContains and minContains",
|
||||
"data": [
|
||||
1,
|
||||
1
|
||||
],
|
||||
"valid": false,
|
||||
"schema_id": "minContains_5_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "minContains = 0",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"contains": {
|
||||
"const": 1
|
||||
},
|
||||
"minContains": 0,
|
||||
"extensible": true,
|
||||
"$id": "minContains_6_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "empty data",
|
||||
"data": [],
|
||||
"valid": true,
|
||||
"schema_id": "minContains_6_0"
|
||||
},
|
||||
{
|
||||
"description": "minContains = 0 makes contains always pass",
|
||||
"data": [
|
||||
2
|
||||
],
|
||||
"valid": true,
|
||||
"schema_id": "minContains_6_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "minContains = 0 with maxContains",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"contains": {
|
||||
"const": 1
|
||||
},
|
||||
"minContains": 0,
|
||||
"maxContains": 1,
|
||||
"extensible": true,
|
||||
"$id": "minContains_7_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "empty data",
|
||||
"data": [],
|
||||
"valid": true,
|
||||
"schema_id": "minContains_7_0"
|
||||
},
|
||||
{
|
||||
"description": "not more than maxContains",
|
||||
"data": [
|
||||
1
|
||||
],
|
||||
"valid": true,
|
||||
"schema_id": "minContains_7_0"
|
||||
},
|
||||
{
|
||||
"description": "too many",
|
||||
"data": [
|
||||
1,
|
||||
1
|
||||
],
|
||||
"valid": false,
|
||||
"schema_id": "minContains_7_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "extensible: true allows non-matching items in minContains",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"contains": {
|
||||
"const": 1
|
||||
},
|
||||
"minContains": 1,
|
||||
"extensible": true,
|
||||
"$id": "minContains_8_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "extra items disregarded for minContains",
|
||||
"data": [
|
||||
1,
|
||||
2
|
||||
],
|
||||
"valid": true,
|
||||
"schema_id": "minContains_8_0"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
96
tests/fixtures/minItems.json
vendored
Normal file
96
tests/fixtures/minItems.json
vendored
Normal file
@ -0,0 +1,96 @@
|
||||
[
|
||||
{
|
||||
"description": "minItems validation",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"minItems": 1,
|
||||
"extensible": true,
|
||||
"$id": "minItems_0_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "longer is valid",
|
||||
"data": [
|
||||
1,
|
||||
2
|
||||
],
|
||||
"valid": true,
|
||||
"schema_id": "minItems_0_0"
|
||||
},
|
||||
{
|
||||
"description": "exact length is valid",
|
||||
"data": [
|
||||
1
|
||||
],
|
||||
"valid": true,
|
||||
"schema_id": "minItems_0_0"
|
||||
},
|
||||
{
|
||||
"description": "too short is invalid",
|
||||
"data": [],
|
||||
"valid": false,
|
||||
"schema_id": "minItems_0_0"
|
||||
},
|
||||
{
|
||||
"description": "ignores non-arrays",
|
||||
"data": "",
|
||||
"valid": true,
|
||||
"schema_id": "minItems_0_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "minItems validation with a decimal",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"minItems": 1,
|
||||
"extensible": true,
|
||||
"$id": "minItems_1_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "longer is valid",
|
||||
"data": [
|
||||
1,
|
||||
2
|
||||
],
|
||||
"valid": true,
|
||||
"schema_id": "minItems_1_0"
|
||||
},
|
||||
{
|
||||
"description": "too short is invalid",
|
||||
"data": [],
|
||||
"valid": false,
|
||||
"schema_id": "minItems_1_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "extensible: true allows extra items in minItems",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"minItems": 1,
|
||||
"extensible": true,
|
||||
"$id": "minItems_2_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "extra item counted towards minItems",
|
||||
"data": [
|
||||
1
|
||||
],
|
||||
"valid": true,
|
||||
"schema_id": "minItems_2_0"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
70
tests/fixtures/minLength.json
vendored
Normal file
70
tests/fixtures/minLength.json
vendored
Normal file
@ -0,0 +1,70 @@
|
||||
[
|
||||
{
|
||||
"description": "minLength validation",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"minLength": 2,
|
||||
"$id": "minLength_0_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "longer is valid",
|
||||
"data": "foo",
|
||||
"valid": true,
|
||||
"schema_id": "minLength_0_0"
|
||||
},
|
||||
{
|
||||
"description": "exact length is valid",
|
||||
"data": "fo",
|
||||
"valid": true,
|
||||
"schema_id": "minLength_0_0"
|
||||
},
|
||||
{
|
||||
"description": "too short is invalid",
|
||||
"data": "f",
|
||||
"valid": false,
|
||||
"schema_id": "minLength_0_0"
|
||||
},
|
||||
{
|
||||
"description": "ignores non-strings",
|
||||
"data": 1,
|
||||
"valid": true,
|
||||
"schema_id": "minLength_0_0"
|
||||
},
|
||||
{
|
||||
"description": "one grapheme is not long enough",
|
||||
"data": "💩",
|
||||
"valid": false,
|
||||
"schema_id": "minLength_0_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "minLength validation with a decimal",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"minLength": 2,
|
||||
"$id": "minLength_1_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "longer is valid",
|
||||
"data": "foo",
|
||||
"valid": true,
|
||||
"schema_id": "minLength_1_0"
|
||||
},
|
||||
{
|
||||
"description": "too short is invalid",
|
||||
"data": "f",
|
||||
"valid": false,
|
||||
"schema_id": "minLength_1_0"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
108
tests/fixtures/minProperties.json
vendored
Normal file
108
tests/fixtures/minProperties.json
vendored
Normal file
@ -0,0 +1,108 @@
|
||||
[
|
||||
{
|
||||
"description": "minProperties validation",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"minProperties": 1,
|
||||
"extensible": true,
|
||||
"$id": "minProperties_0_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "longer is valid",
|
||||
"data": {
|
||||
"foo": 1,
|
||||
"bar": 2
|
||||
},
|
||||
"valid": true,
|
||||
"schema_id": "minProperties_0_0"
|
||||
},
|
||||
{
|
||||
"description": "exact length is valid",
|
||||
"data": {
|
||||
"foo": 1
|
||||
},
|
||||
"valid": true,
|
||||
"schema_id": "minProperties_0_0"
|
||||
},
|
||||
{
|
||||
"description": "too short is invalid",
|
||||
"data": {},
|
||||
"valid": false,
|
||||
"schema_id": "minProperties_0_0"
|
||||
},
|
||||
{
|
||||
"description": "ignores arrays",
|
||||
"data": [],
|
||||
"valid": true,
|
||||
"schema_id": "minProperties_0_0"
|
||||
},
|
||||
{
|
||||
"description": "ignores strings",
|
||||
"data": "",
|
||||
"valid": true,
|
||||
"schema_id": "minProperties_0_0"
|
||||
},
|
||||
{
|
||||
"description": "ignores other non-objects",
|
||||
"data": 12,
|
||||
"valid": true,
|
||||
"schema_id": "minProperties_0_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "minProperties validation with a decimal",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"minProperties": 1,
|
||||
"extensible": true,
|
||||
"$id": "minProperties_1_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "longer is valid",
|
||||
"data": {
|
||||
"foo": 1,
|
||||
"bar": 2
|
||||
},
|
||||
"valid": true,
|
||||
"schema_id": "minProperties_1_0"
|
||||
},
|
||||
{
|
||||
"description": "too short is invalid",
|
||||
"data": {},
|
||||
"valid": false,
|
||||
"schema_id": "minProperties_1_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "extensible: true allows extra properties in minProperties",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"minProperties": 1,
|
||||
"extensible": true,
|
||||
"$id": "minProperties_2_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "extra property counts towards minProperties",
|
||||
"data": {
|
||||
"foo": 1
|
||||
},
|
||||
"valid": true,
|
||||
"schema_id": "minProperties_2_0"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
94
tests/fixtures/minimum.json
vendored
Normal file
94
tests/fixtures/minimum.json
vendored
Normal file
@ -0,0 +1,94 @@
|
||||
[
|
||||
{
|
||||
"description": "minimum validation",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"minimum": 1.1,
|
||||
"$id": "minimum_0_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "above the minimum is valid",
|
||||
"data": 2.6,
|
||||
"valid": true,
|
||||
"schema_id": "minimum_0_0"
|
||||
},
|
||||
{
|
||||
"description": "boundary point is valid",
|
||||
"data": 1.1,
|
||||
"valid": true,
|
||||
"schema_id": "minimum_0_0"
|
||||
},
|
||||
{
|
||||
"description": "below the minimum is invalid",
|
||||
"data": 0.6,
|
||||
"valid": false,
|
||||
"schema_id": "minimum_0_0"
|
||||
},
|
||||
{
|
||||
"description": "ignores non-numbers",
|
||||
"data": "x",
|
||||
"valid": true,
|
||||
"schema_id": "minimum_0_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "minimum validation with signed integer",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"minimum": -2,
|
||||
"$id": "minimum_1_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "negative above the minimum is valid",
|
||||
"data": -1,
|
||||
"valid": true,
|
||||
"schema_id": "minimum_1_0"
|
||||
},
|
||||
{
|
||||
"description": "positive above the minimum is valid",
|
||||
"data": 0,
|
||||
"valid": true,
|
||||
"schema_id": "minimum_1_0"
|
||||
},
|
||||
{
|
||||
"description": "boundary point is valid",
|
||||
"data": -2,
|
||||
"valid": true,
|
||||
"schema_id": "minimum_1_0"
|
||||
},
|
||||
{
|
||||
"description": "boundary point with float is valid",
|
||||
"data": -2,
|
||||
"valid": true,
|
||||
"schema_id": "minimum_1_0"
|
||||
},
|
||||
{
|
||||
"description": "float below the minimum is invalid",
|
||||
"data": -2.0001,
|
||||
"valid": false,
|
||||
"schema_id": "minimum_1_0"
|
||||
},
|
||||
{
|
||||
"description": "int below the minimum is invalid",
|
||||
"data": -3,
|
||||
"valid": false,
|
||||
"schema_id": "minimum_1_0"
|
||||
},
|
||||
{
|
||||
"description": "ignores non-numbers",
|
||||
"data": "x",
|
||||
"valid": true,
|
||||
"schema_id": "minimum_1_0"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
109
tests/fixtures/multipleOf.json
vendored
Normal file
109
tests/fixtures/multipleOf.json
vendored
Normal file
@ -0,0 +1,109 @@
|
||||
[
|
||||
{
|
||||
"description": "by int",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"multipleOf": 2,
|
||||
"$id": "multipleOf_0_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "int by int",
|
||||
"data": 10,
|
||||
"valid": true,
|
||||
"schema_id": "multipleOf_0_0"
|
||||
},
|
||||
{
|
||||
"description": "int by int fail",
|
||||
"data": 7,
|
||||
"valid": false,
|
||||
"schema_id": "multipleOf_0_0"
|
||||
},
|
||||
{
|
||||
"description": "ignores non-numbers",
|
||||
"data": "foo",
|
||||
"valid": true,
|
||||
"schema_id": "multipleOf_0_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "by number",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"multipleOf": 1.5,
|
||||
"$id": "multipleOf_1_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "zero is multiple of anything",
|
||||
"data": 0,
|
||||
"valid": true,
|
||||
"schema_id": "multipleOf_1_0"
|
||||
},
|
||||
{
|
||||
"description": "4.5 is multiple of 1.5",
|
||||
"data": 4.5,
|
||||
"valid": true,
|
||||
"schema_id": "multipleOf_1_0"
|
||||
},
|
||||
{
|
||||
"description": "35 is not multiple of 1.5",
|
||||
"data": 35,
|
||||
"valid": false,
|
||||
"schema_id": "multipleOf_1_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "by small number",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"multipleOf": 0.0001,
|
||||
"$id": "multipleOf_2_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "0.0075 is multiple of 0.0001",
|
||||
"data": 0.0075,
|
||||
"valid": true,
|
||||
"schema_id": "multipleOf_2_0"
|
||||
},
|
||||
{
|
||||
"description": "0.00751 is not multiple of 0.0001",
|
||||
"data": 0.00751,
|
||||
"valid": false,
|
||||
"schema_id": "multipleOf_2_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "small multiple of large integer",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"type": "integer",
|
||||
"multipleOf": 1e-8,
|
||||
"$id": "multipleOf_3_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "any integer is a multiple of 1e-8",
|
||||
"data": 12391239123,
|
||||
"valid": true,
|
||||
"schema_id": "multipleOf_3_0"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
489
tests/fixtures/not.json
vendored
Normal file
489
tests/fixtures/not.json
vendored
Normal file
@ -0,0 +1,489 @@
|
||||
[
|
||||
{
|
||||
"description": "not",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"not": {
|
||||
"type": "integer"
|
||||
},
|
||||
"$id": "not_0_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "allowed",
|
||||
"data": "foo",
|
||||
"valid": true,
|
||||
"schema_id": "not_0_0"
|
||||
},
|
||||
{
|
||||
"description": "disallowed",
|
||||
"data": 1,
|
||||
"valid": false,
|
||||
"schema_id": "not_0_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "not multiple types",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"not": {
|
||||
"type": [
|
||||
"integer",
|
||||
"boolean"
|
||||
]
|
||||
},
|
||||
"$id": "not_1_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "valid",
|
||||
"data": "foo",
|
||||
"valid": true,
|
||||
"schema_id": "not_1_0"
|
||||
},
|
||||
{
|
||||
"description": "mismatch",
|
||||
"data": 1,
|
||||
"valid": false,
|
||||
"schema_id": "not_1_0"
|
||||
},
|
||||
{
|
||||
"description": "other mismatch",
|
||||
"data": true,
|
||||
"valid": false,
|
||||
"schema_id": "not_1_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "not more complex schema",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"not": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"foo": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
},
|
||||
"extensible": true,
|
||||
"$id": "not_2_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "match",
|
||||
"data": 1,
|
||||
"valid": true,
|
||||
"schema_id": "not_2_0"
|
||||
},
|
||||
{
|
||||
"description": "other match",
|
||||
"data": {
|
||||
"foo": 1
|
||||
},
|
||||
"valid": true,
|
||||
"schema_id": "not_2_0"
|
||||
},
|
||||
{
|
||||
"description": "mismatch",
|
||||
"data": {
|
||||
"foo": "bar"
|
||||
},
|
||||
"valid": false,
|
||||
"schema_id": "not_2_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "forbidden property",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"properties": {
|
||||
"foo": {
|
||||
"not": {}
|
||||
}
|
||||
},
|
||||
"$id": "not_3_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "property present",
|
||||
"data": {
|
||||
"foo": 1,
|
||||
"bar": 2
|
||||
},
|
||||
"valid": false,
|
||||
"schema_id": "not_3_0"
|
||||
},
|
||||
{
|
||||
"description": "empty object is valid",
|
||||
"data": {},
|
||||
"valid": true,
|
||||
"schema_id": "not_3_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "forbid everything with empty schema",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"not": {},
|
||||
"$id": "not_4_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "number is invalid",
|
||||
"data": 1,
|
||||
"valid": false,
|
||||
"schema_id": "not_4_0"
|
||||
},
|
||||
{
|
||||
"description": "string is invalid",
|
||||
"data": "foo",
|
||||
"valid": false,
|
||||
"schema_id": "not_4_0"
|
||||
},
|
||||
{
|
||||
"description": "boolean true is invalid",
|
||||
"data": true,
|
||||
"valid": false,
|
||||
"schema_id": "not_4_0"
|
||||
},
|
||||
{
|
||||
"description": "boolean false is invalid",
|
||||
"data": false,
|
||||
"valid": false,
|
||||
"schema_id": "not_4_0"
|
||||
},
|
||||
{
|
||||
"description": "null is invalid",
|
||||
"data": null,
|
||||
"valid": false,
|
||||
"schema_id": "not_4_0"
|
||||
},
|
||||
{
|
||||
"description": "object is invalid",
|
||||
"data": {
|
||||
"foo": "bar"
|
||||
},
|
||||
"valid": false,
|
||||
"schema_id": "not_4_0"
|
||||
},
|
||||
{
|
||||
"description": "empty object is invalid",
|
||||
"data": {},
|
||||
"valid": false,
|
||||
"schema_id": "not_4_0"
|
||||
},
|
||||
{
|
||||
"description": "array is invalid",
|
||||
"data": [
|
||||
"foo"
|
||||
],
|
||||
"valid": false,
|
||||
"schema_id": "not_4_0"
|
||||
},
|
||||
{
|
||||
"description": "empty array is invalid",
|
||||
"data": [],
|
||||
"valid": false,
|
||||
"schema_id": "not_4_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "forbid everything with boolean schema true",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"not": true,
|
||||
"$id": "not_5_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "number is invalid",
|
||||
"data": 1,
|
||||
"valid": false,
|
||||
"schema_id": "not_5_0"
|
||||
},
|
||||
{
|
||||
"description": "string is invalid",
|
||||
"data": "foo",
|
||||
"valid": false,
|
||||
"schema_id": "not_5_0"
|
||||
},
|
||||
{
|
||||
"description": "boolean true is invalid",
|
||||
"data": true,
|
||||
"valid": false,
|
||||
"schema_id": "not_5_0"
|
||||
},
|
||||
{
|
||||
"description": "boolean false is invalid",
|
||||
"data": false,
|
||||
"valid": false,
|
||||
"schema_id": "not_5_0"
|
||||
},
|
||||
{
|
||||
"description": "null is invalid",
|
||||
"data": null,
|
||||
"valid": false,
|
||||
"schema_id": "not_5_0"
|
||||
},
|
||||
{
|
||||
"description": "object is invalid",
|
||||
"data": {
|
||||
"foo": "bar"
|
||||
},
|
||||
"valid": false,
|
||||
"schema_id": "not_5_0"
|
||||
},
|
||||
{
|
||||
"description": "empty object is invalid",
|
||||
"data": {},
|
||||
"valid": false,
|
||||
"schema_id": "not_5_0"
|
||||
},
|
||||
{
|
||||
"description": "array is invalid",
|
||||
"data": [
|
||||
"foo"
|
||||
],
|
||||
"valid": false,
|
||||
"schema_id": "not_5_0"
|
||||
},
|
||||
{
|
||||
"description": "empty array is invalid",
|
||||
"data": [],
|
||||
"valid": false,
|
||||
"schema_id": "not_5_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "allow everything with boolean schema false",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"not": false,
|
||||
"extensible": true,
|
||||
"$id": "not_6_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "number is valid",
|
||||
"data": 1,
|
||||
"valid": true,
|
||||
"schema_id": "not_6_0"
|
||||
},
|
||||
{
|
||||
"description": "string is valid",
|
||||
"data": "foo",
|
||||
"valid": true,
|
||||
"schema_id": "not_6_0"
|
||||
},
|
||||
{
|
||||
"description": "boolean true is valid",
|
||||
"data": true,
|
||||
"valid": true,
|
||||
"schema_id": "not_6_0"
|
||||
},
|
||||
{
|
||||
"description": "boolean false is valid",
|
||||
"data": false,
|
||||
"valid": true,
|
||||
"schema_id": "not_6_0"
|
||||
},
|
||||
{
|
||||
"description": "null is valid",
|
||||
"data": null,
|
||||
"valid": true,
|
||||
"schema_id": "not_6_0"
|
||||
},
|
||||
{
|
||||
"description": "object is valid",
|
||||
"data": {
|
||||
"foo": "bar"
|
||||
},
|
||||
"valid": true,
|
||||
"schema_id": "not_6_0"
|
||||
},
|
||||
{
|
||||
"description": "empty object is valid",
|
||||
"data": {},
|
||||
"valid": true,
|
||||
"schema_id": "not_6_0"
|
||||
},
|
||||
{
|
||||
"description": "array is valid",
|
||||
"data": [
|
||||
"foo"
|
||||
],
|
||||
"valid": true,
|
||||
"schema_id": "not_6_0"
|
||||
},
|
||||
{
|
||||
"description": "empty array is valid",
|
||||
"data": [],
|
||||
"valid": true,
|
||||
"schema_id": "not_6_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "double negation",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"not": {
|
||||
"not": {}
|
||||
},
|
||||
"$id": "not_7_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "any value is valid",
|
||||
"data": "foo",
|
||||
"valid": true,
|
||||
"schema_id": "not_7_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "extensible: true allows extra properties in not",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"not": {
|
||||
"type": "integer"
|
||||
},
|
||||
"extensible": true,
|
||||
"$id": "not_8_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "extra property is valid (not integer matches)",
|
||||
"data": {
|
||||
"foo": 1
|
||||
},
|
||||
"valid": true,
|
||||
"schema_id": "not_8_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "extensible: false (default) forbids extra properties in not",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"not": {
|
||||
"type": "integer"
|
||||
},
|
||||
"$id": "not_9_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "extra property is invalid due to strictness",
|
||||
"data": {
|
||||
"foo": 1
|
||||
},
|
||||
"valid": false,
|
||||
"schema_id": "not_9_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "property next to not (extensible: true)",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"properties": {
|
||||
"bar": {
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"not": {
|
||||
"type": "integer"
|
||||
},
|
||||
"extensible": true,
|
||||
"$id": "not_10_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "extra property allowed",
|
||||
"data": {
|
||||
"bar": "baz",
|
||||
"foo": 1
|
||||
},
|
||||
"valid": true,
|
||||
"schema_id": "not_10_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "property next to not (extensible: false)",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"properties": {
|
||||
"bar": {
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"not": {
|
||||
"type": "integer"
|
||||
},
|
||||
"$id": "not_11_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "extra property forbidden",
|
||||
"data": {
|
||||
"bar": "baz",
|
||||
"foo": 1
|
||||
},
|
||||
"valid": false,
|
||||
"schema_id": "not_11_0"
|
||||
},
|
||||
{
|
||||
"description": "defined property allowed",
|
||||
"data": {
|
||||
"bar": "baz"
|
||||
},
|
||||
"valid": true,
|
||||
"schema_id": "not_11_0"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
568
tests/fixtures/oneOf.json
vendored
Normal file
568
tests/fixtures/oneOf.json
vendored
Normal file
@ -0,0 +1,568 @@
|
||||
[
|
||||
{
|
||||
"description": "oneOf",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"oneOf": [
|
||||
{
|
||||
"type": "integer"
|
||||
},
|
||||
{
|
||||
"minimum": 2
|
||||
}
|
||||
],
|
||||
"$id": "oneOf_0_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "first oneOf valid",
|
||||
"data": 1,
|
||||
"valid": true,
|
||||
"schema_id": "oneOf_0_0"
|
||||
},
|
||||
{
|
||||
"description": "second oneOf valid",
|
||||
"data": 2.5,
|
||||
"valid": true,
|
||||
"schema_id": "oneOf_0_0"
|
||||
},
|
||||
{
|
||||
"description": "both oneOf valid",
|
||||
"data": 3,
|
||||
"valid": false,
|
||||
"schema_id": "oneOf_0_0"
|
||||
},
|
||||
{
|
||||
"description": "neither oneOf valid",
|
||||
"data": 1.5,
|
||||
"valid": false,
|
||||
"schema_id": "oneOf_0_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "oneOf with base schema",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"type": "string",
|
||||
"oneOf": [
|
||||
{
|
||||
"minLength": 2
|
||||
},
|
||||
{
|
||||
"maxLength": 4
|
||||
}
|
||||
],
|
||||
"$id": "oneOf_1_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "mismatch base schema",
|
||||
"data": 3,
|
||||
"valid": false,
|
||||
"schema_id": "oneOf_1_0"
|
||||
},
|
||||
{
|
||||
"description": "one oneOf valid",
|
||||
"data": "foobar",
|
||||
"valid": true,
|
||||
"schema_id": "oneOf_1_0"
|
||||
},
|
||||
{
|
||||
"description": "both oneOf valid",
|
||||
"data": "foo",
|
||||
"valid": false,
|
||||
"schema_id": "oneOf_1_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "oneOf with boolean schemas, all true",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"oneOf": [
|
||||
true,
|
||||
true,
|
||||
true
|
||||
],
|
||||
"$id": "oneOf_2_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "any value is invalid",
|
||||
"data": "foo",
|
||||
"valid": false,
|
||||
"schema_id": "oneOf_2_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "oneOf with boolean schemas, one true",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"oneOf": [
|
||||
true,
|
||||
false,
|
||||
false
|
||||
],
|
||||
"$id": "oneOf_3_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "any value is valid",
|
||||
"data": "foo",
|
||||
"valid": true,
|
||||
"schema_id": "oneOf_3_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "oneOf with boolean schemas, more than one true",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"oneOf": [
|
||||
true,
|
||||
true,
|
||||
false
|
||||
],
|
||||
"$id": "oneOf_4_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "any value is invalid",
|
||||
"data": "foo",
|
||||
"valid": false,
|
||||
"schema_id": "oneOf_4_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "oneOf with boolean schemas, all false",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"oneOf": [
|
||||
false,
|
||||
false,
|
||||
false
|
||||
],
|
||||
"$id": "oneOf_5_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "any value is invalid",
|
||||
"data": "foo",
|
||||
"valid": false,
|
||||
"schema_id": "oneOf_5_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "oneOf complex types",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"oneOf": [
|
||||
{
|
||||
"properties": {
|
||||
"bar": {
|
||||
"type": "integer"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"bar"
|
||||
]
|
||||
},
|
||||
{
|
||||
"properties": {
|
||||
"foo": {
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"foo"
|
||||
]
|
||||
}
|
||||
],
|
||||
"$id": "oneOf_6_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "first oneOf valid (complex)",
|
||||
"data": {
|
||||
"bar": 2
|
||||
},
|
||||
"valid": true,
|
||||
"schema_id": "oneOf_6_0"
|
||||
},
|
||||
{
|
||||
"description": "second oneOf valid (complex)",
|
||||
"data": {
|
||||
"foo": "baz"
|
||||
},
|
||||
"valid": true,
|
||||
"schema_id": "oneOf_6_0"
|
||||
},
|
||||
{
|
||||
"description": "both oneOf valid (complex)",
|
||||
"data": {
|
||||
"foo": "baz",
|
||||
"bar": 2
|
||||
},
|
||||
"valid": false,
|
||||
"schema_id": "oneOf_6_0"
|
||||
},
|
||||
{
|
||||
"description": "neither oneOf valid (complex)",
|
||||
"data": {
|
||||
"foo": 2,
|
||||
"bar": "quux"
|
||||
},
|
||||
"valid": false,
|
||||
"schema_id": "oneOf_6_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "oneOf with empty schema",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"oneOf": [
|
||||
{
|
||||
"type": "number"
|
||||
},
|
||||
{}
|
||||
],
|
||||
"$id": "oneOf_7_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "one valid - valid",
|
||||
"data": "foo",
|
||||
"valid": true,
|
||||
"schema_id": "oneOf_7_0"
|
||||
},
|
||||
{
|
||||
"description": "both valid - invalid",
|
||||
"data": 123,
|
||||
"valid": false,
|
||||
"schema_id": "oneOf_7_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "oneOf with required",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"foo": true,
|
||||
"bar": true,
|
||||
"baz": true
|
||||
},
|
||||
"oneOf": [
|
||||
{
|
||||
"required": [
|
||||
"foo",
|
||||
"bar"
|
||||
]
|
||||
},
|
||||
{
|
||||
"required": [
|
||||
"foo",
|
||||
"baz"
|
||||
]
|
||||
}
|
||||
],
|
||||
"$id": "oneOf_8_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "both invalid - invalid",
|
||||
"data": {
|
||||
"bar": 2
|
||||
},
|
||||
"valid": false,
|
||||
"schema_id": "oneOf_8_0"
|
||||
},
|
||||
{
|
||||
"description": "first valid - valid",
|
||||
"data": {
|
||||
"foo": 1,
|
||||
"bar": 2
|
||||
},
|
||||
"valid": true,
|
||||
"schema_id": "oneOf_8_0"
|
||||
},
|
||||
{
|
||||
"description": "second valid - valid",
|
||||
"data": {
|
||||
"foo": 1,
|
||||
"baz": 3
|
||||
},
|
||||
"valid": true,
|
||||
"schema_id": "oneOf_8_0"
|
||||
},
|
||||
{
|
||||
"description": "both valid - invalid",
|
||||
"data": {
|
||||
"foo": 1,
|
||||
"bar": 2,
|
||||
"baz": 3
|
||||
},
|
||||
"valid": false,
|
||||
"schema_id": "oneOf_8_0"
|
||||
},
|
||||
{
|
||||
"description": "extra property invalid (strict)",
|
||||
"data": {
|
||||
"foo": 1,
|
||||
"bar": 2,
|
||||
"extra": 3
|
||||
},
|
||||
"valid": false,
|
||||
"schema_id": "oneOf_8_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "oneOf with required (extensible)",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"type": "object",
|
||||
"extensible": true,
|
||||
"oneOf": [
|
||||
{
|
||||
"required": [
|
||||
"foo",
|
||||
"bar"
|
||||
]
|
||||
},
|
||||
{
|
||||
"required": [
|
||||
"foo",
|
||||
"baz"
|
||||
]
|
||||
}
|
||||
],
|
||||
"$id": "oneOf_9_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "both invalid - invalid",
|
||||
"data": {
|
||||
"bar": 2
|
||||
},
|
||||
"valid": false,
|
||||
"schema_id": "oneOf_9_0"
|
||||
},
|
||||
{
|
||||
"description": "first valid - valid",
|
||||
"data": {
|
||||
"foo": 1,
|
||||
"bar": 2
|
||||
},
|
||||
"valid": true,
|
||||
"schema_id": "oneOf_9_0"
|
||||
},
|
||||
{
|
||||
"description": "second valid - valid",
|
||||
"data": {
|
||||
"foo": 1,
|
||||
"baz": 3
|
||||
},
|
||||
"valid": true,
|
||||
"schema_id": "oneOf_9_0"
|
||||
},
|
||||
{
|
||||
"description": "both valid - invalid",
|
||||
"data": {
|
||||
"foo": 1,
|
||||
"bar": 2,
|
||||
"baz": 3
|
||||
},
|
||||
"valid": false,
|
||||
"schema_id": "oneOf_9_0"
|
||||
},
|
||||
{
|
||||
"description": "extra properties are valid (extensible)",
|
||||
"data": {
|
||||
"foo": 1,
|
||||
"bar": 2,
|
||||
"extra": "value"
|
||||
},
|
||||
"valid": true,
|
||||
"schema_id": "oneOf_9_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "oneOf with missing optional property",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"oneOf": [
|
||||
{
|
||||
"properties": {
|
||||
"bar": true,
|
||||
"baz": true
|
||||
},
|
||||
"required": [
|
||||
"bar"
|
||||
]
|
||||
},
|
||||
{
|
||||
"properties": {
|
||||
"foo": true
|
||||
},
|
||||
"required": [
|
||||
"foo"
|
||||
]
|
||||
}
|
||||
],
|
||||
"$id": "oneOf_10_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "first oneOf valid",
|
||||
"data": {
|
||||
"bar": 8
|
||||
},
|
||||
"valid": true,
|
||||
"schema_id": "oneOf_10_0"
|
||||
},
|
||||
{
|
||||
"description": "second oneOf valid",
|
||||
"data": {
|
||||
"foo": "foo"
|
||||
},
|
||||
"valid": true,
|
||||
"schema_id": "oneOf_10_0"
|
||||
},
|
||||
{
|
||||
"description": "both oneOf valid",
|
||||
"data": {
|
||||
"foo": "foo",
|
||||
"bar": 8
|
||||
},
|
||||
"valid": false,
|
||||
"schema_id": "oneOf_10_0"
|
||||
},
|
||||
{
|
||||
"description": "neither oneOf valid",
|
||||
"data": {
|
||||
"baz": "quux"
|
||||
},
|
||||
"valid": false,
|
||||
"schema_id": "oneOf_10_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "nested oneOf, to check validation semantics",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"oneOf": [
|
||||
{
|
||||
"oneOf": [
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"$id": "oneOf_11_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "null is valid",
|
||||
"data": null,
|
||||
"valid": true,
|
||||
"schema_id": "oneOf_11_0"
|
||||
},
|
||||
{
|
||||
"description": "anything non-null is invalid",
|
||||
"data": 123,
|
||||
"valid": false,
|
||||
"schema_id": "oneOf_11_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "extensible: true allows extra properties in oneOf",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"oneOf": [
|
||||
{
|
||||
"properties": {
|
||||
"bar": {
|
||||
"type": "integer"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"bar"
|
||||
]
|
||||
},
|
||||
{
|
||||
"properties": {
|
||||
"foo": {
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"foo"
|
||||
]
|
||||
}
|
||||
],
|
||||
"extensible": true,
|
||||
"$id": "oneOf_12_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "extra property is valid (matches first option)",
|
||||
"data": {
|
||||
"bar": 2,
|
||||
"extra": "prop"
|
||||
},
|
||||
"valid": true,
|
||||
"schema_id": "oneOf_12_0"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
82
tests/fixtures/pattern.json
vendored
Normal file
82
tests/fixtures/pattern.json
vendored
Normal file
@ -0,0 +1,82 @@
|
||||
[
|
||||
{
|
||||
"description": "pattern validation",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"pattern": "^a*$",
|
||||
"$id": "pattern_0_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "a matching pattern is valid",
|
||||
"data": "aaa",
|
||||
"valid": true,
|
||||
"schema_id": "pattern_0_0"
|
||||
},
|
||||
{
|
||||
"description": "a non-matching pattern is invalid",
|
||||
"data": "abc",
|
||||
"valid": false,
|
||||
"schema_id": "pattern_0_0"
|
||||
},
|
||||
{
|
||||
"description": "ignores booleans",
|
||||
"data": true,
|
||||
"valid": true,
|
||||
"schema_id": "pattern_0_0"
|
||||
},
|
||||
{
|
||||
"description": "ignores integers",
|
||||
"data": 123,
|
||||
"valid": true,
|
||||
"schema_id": "pattern_0_0"
|
||||
},
|
||||
{
|
||||
"description": "ignores floats",
|
||||
"data": 1,
|
||||
"valid": true,
|
||||
"schema_id": "pattern_0_0"
|
||||
},
|
||||
{
|
||||
"description": "ignores objects",
|
||||
"data": {},
|
||||
"valid": true,
|
||||
"schema_id": "pattern_0_0"
|
||||
},
|
||||
{
|
||||
"description": "ignores arrays",
|
||||
"data": [],
|
||||
"valid": true,
|
||||
"schema_id": "pattern_0_0"
|
||||
},
|
||||
{
|
||||
"description": "ignores null",
|
||||
"data": null,
|
||||
"valid": true,
|
||||
"schema_id": "pattern_0_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "pattern is not anchored",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"pattern": "a+",
|
||||
"$id": "pattern_1_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "matches a substring",
|
||||
"data": "xxaayy",
|
||||
"valid": true,
|
||||
"schema_id": "pattern_1_0"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
321
tests/fixtures/patternProperties.json
vendored
Normal file
321
tests/fixtures/patternProperties.json
vendored
Normal file
@ -0,0 +1,321 @@
|
||||
[
|
||||
{
|
||||
"description": "patternProperties validates properties matching a regex",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"patternProperties": {
|
||||
"f.*o": {
|
||||
"type": "integer"
|
||||
}
|
||||
},
|
||||
"items": {},
|
||||
"$id": "patternProperties_0_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "a single valid match is valid",
|
||||
"data": {
|
||||
"foo": 1
|
||||
},
|
||||
"valid": true,
|
||||
"schema_id": "patternProperties_0_0"
|
||||
},
|
||||
{
|
||||
"description": "multiple valid matches is valid",
|
||||
"data": {
|
||||
"foo": 1,
|
||||
"foooooo": 2
|
||||
},
|
||||
"valid": true,
|
||||
"schema_id": "patternProperties_0_0"
|
||||
},
|
||||
{
|
||||
"description": "a single invalid match is invalid",
|
||||
"data": {
|
||||
"foo": "bar",
|
||||
"fooooo": 2
|
||||
},
|
||||
"valid": false,
|
||||
"schema_id": "patternProperties_0_0"
|
||||
},
|
||||
{
|
||||
"description": "multiple invalid matches is invalid",
|
||||
"data": {
|
||||
"foo": "bar",
|
||||
"foooooo": "baz"
|
||||
},
|
||||
"valid": false,
|
||||
"schema_id": "patternProperties_0_0"
|
||||
},
|
||||
{
|
||||
"description": "ignores arrays",
|
||||
"data": [
|
||||
"foo"
|
||||
],
|
||||
"valid": true,
|
||||
"schema_id": "patternProperties_0_0"
|
||||
},
|
||||
{
|
||||
"description": "ignores strings",
|
||||
"data": "foo",
|
||||
"valid": true,
|
||||
"schema_id": "patternProperties_0_0"
|
||||
},
|
||||
{
|
||||
"description": "ignores other non-objects",
|
||||
"data": 12,
|
||||
"valid": true,
|
||||
"schema_id": "patternProperties_0_0"
|
||||
},
|
||||
{
|
||||
"description": "extra property not matching pattern is INVALID (strict by default)",
|
||||
"data": {
|
||||
"foo": 1,
|
||||
"extra": 2
|
||||
},
|
||||
"valid": false,
|
||||
"schema_id": "patternProperties_0_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "multiple simultaneous patternProperties are validated",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"patternProperties": {
|
||||
"a*": {
|
||||
"type": "integer"
|
||||
},
|
||||
"aaa*": {
|
||||
"maximum": 20
|
||||
}
|
||||
},
|
||||
"$id": "patternProperties_1_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "a single valid match is valid",
|
||||
"data": {
|
||||
"a": 21
|
||||
},
|
||||
"valid": true,
|
||||
"schema_id": "patternProperties_1_0"
|
||||
},
|
||||
{
|
||||
"description": "a simultaneous match is valid",
|
||||
"data": {
|
||||
"aaaa": 18
|
||||
},
|
||||
"valid": true,
|
||||
"schema_id": "patternProperties_1_0"
|
||||
},
|
||||
{
|
||||
"description": "multiple matches is valid",
|
||||
"data": {
|
||||
"a": 21,
|
||||
"aaaa": 18
|
||||
},
|
||||
"valid": true,
|
||||
"schema_id": "patternProperties_1_0"
|
||||
},
|
||||
{
|
||||
"description": "an invalid due to one is invalid",
|
||||
"data": {
|
||||
"a": "bar"
|
||||
},
|
||||
"valid": false,
|
||||
"schema_id": "patternProperties_1_0"
|
||||
},
|
||||
{
|
||||
"description": "an invalid due to the other is invalid",
|
||||
"data": {
|
||||
"aaaa": 31
|
||||
},
|
||||
"valid": false,
|
||||
"schema_id": "patternProperties_1_0"
|
||||
},
|
||||
{
|
||||
"description": "an invalid due to both is invalid",
|
||||
"data": {
|
||||
"aaa": "foo",
|
||||
"aaaa": 31
|
||||
},
|
||||
"valid": false,
|
||||
"schema_id": "patternProperties_1_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "regexes are not anchored by default and are case sensitive",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"patternProperties": {
|
||||
"[0-9]{2,}": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"X_": {
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"extensible": true,
|
||||
"$id": "patternProperties_2_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "non recognized members are ignored",
|
||||
"data": {
|
||||
"answer 1": "42"
|
||||
},
|
||||
"valid": true,
|
||||
"schema_id": "patternProperties_2_0"
|
||||
},
|
||||
{
|
||||
"description": "recognized members are accounted for",
|
||||
"data": {
|
||||
"a31b": null
|
||||
},
|
||||
"valid": false,
|
||||
"schema_id": "patternProperties_2_0"
|
||||
},
|
||||
{
|
||||
"description": "regexes are case sensitive",
|
||||
"data": {
|
||||
"a_x_3": 3
|
||||
},
|
||||
"valid": true,
|
||||
"schema_id": "patternProperties_2_0"
|
||||
},
|
||||
{
|
||||
"description": "regexes are case sensitive, 2",
|
||||
"data": {
|
||||
"a_X_3": 3
|
||||
},
|
||||
"valid": false,
|
||||
"schema_id": "patternProperties_2_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "patternProperties with boolean schemas",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"patternProperties": {
|
||||
"f.*": true,
|
||||
"b.*": false
|
||||
},
|
||||
"$id": "patternProperties_3_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "object with property matching schema true is valid",
|
||||
"data": {
|
||||
"foo": 1
|
||||
},
|
||||
"valid": true,
|
||||
"schema_id": "patternProperties_3_0"
|
||||
},
|
||||
{
|
||||
"description": "object with property matching schema false is invalid",
|
||||
"data": {
|
||||
"bar": 2
|
||||
},
|
||||
"valid": false,
|
||||
"schema_id": "patternProperties_3_0"
|
||||
},
|
||||
{
|
||||
"description": "object with both properties is invalid",
|
||||
"data": {
|
||||
"foo": 1,
|
||||
"bar": 2
|
||||
},
|
||||
"valid": false,
|
||||
"schema_id": "patternProperties_3_0"
|
||||
},
|
||||
{
|
||||
"description": "object with a property matching both true and false is invalid",
|
||||
"data": {
|
||||
"foobar": 1
|
||||
},
|
||||
"valid": false,
|
||||
"schema_id": "patternProperties_3_0"
|
||||
},
|
||||
{
|
||||
"description": "empty object is valid",
|
||||
"data": {},
|
||||
"valid": true,
|
||||
"schema_id": "patternProperties_3_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "patternProperties with null valued instance properties",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"patternProperties": {
|
||||
"^.*bar$": {
|
||||
"type": "null"
|
||||
}
|
||||
},
|
||||
"$id": "patternProperties_4_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "allows null values",
|
||||
"data": {
|
||||
"foobar": null
|
||||
},
|
||||
"valid": true,
|
||||
"schema_id": "patternProperties_4_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "extensible: true allows extra properties NOT matching pattern",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"patternProperties": {
|
||||
"f.*o": {
|
||||
"type": "integer"
|
||||
}
|
||||
},
|
||||
"extensible": true,
|
||||
"$id": "patternProperties_5_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "extra property not matching pattern is valid",
|
||||
"data": {
|
||||
"bar": 1
|
||||
},
|
||||
"valid": true,
|
||||
"schema_id": "patternProperties_5_0"
|
||||
},
|
||||
{
|
||||
"description": "property matching pattern MUST still be valid",
|
||||
"data": {
|
||||
"foo": "invalid string"
|
||||
},
|
||||
"valid": false,
|
||||
"schema_id": "patternProperties_5_0"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
193
tests/fixtures/prefixItems.json
vendored
Normal file
193
tests/fixtures/prefixItems.json
vendored
Normal file
@ -0,0 +1,193 @@
|
||||
[
|
||||
{
|
||||
"description": "a schema given for prefixItems",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"prefixItems": [
|
||||
{
|
||||
"type": "integer"
|
||||
},
|
||||
{
|
||||
"type": "string"
|
||||
}
|
||||
],
|
||||
"$id": "prefixItems_0_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "correct types",
|
||||
"data": [
|
||||
1,
|
||||
"foo"
|
||||
],
|
||||
"valid": true,
|
||||
"schema_id": "prefixItems_0_0"
|
||||
},
|
||||
{
|
||||
"description": "wrong types",
|
||||
"data": [
|
||||
"foo",
|
||||
1
|
||||
],
|
||||
"valid": false,
|
||||
"schema_id": "prefixItems_0_0"
|
||||
},
|
||||
{
|
||||
"description": "incomplete array of items",
|
||||
"data": [
|
||||
1
|
||||
],
|
||||
"valid": true,
|
||||
"schema_id": "prefixItems_0_0"
|
||||
},
|
||||
{
|
||||
"description": "array with additional items (invalid due to strictness)",
|
||||
"data": [
|
||||
1,
|
||||
"foo",
|
||||
true
|
||||
],
|
||||
"valid": false,
|
||||
"schema_id": "prefixItems_0_0"
|
||||
},
|
||||
{
|
||||
"description": "empty array",
|
||||
"data": [],
|
||||
"valid": true,
|
||||
"schema_id": "prefixItems_0_0"
|
||||
},
|
||||
{
|
||||
"description": "JavaScript pseudo-array is valid (invalid due to strict object validation)",
|
||||
"data": {
|
||||
"0": "invalid",
|
||||
"1": "valid",
|
||||
"length": 2
|
||||
},
|
||||
"valid": false,
|
||||
"schema_id": "prefixItems_0_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "prefixItems with boolean schemas",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"prefixItems": [
|
||||
true,
|
||||
false
|
||||
],
|
||||
"$id": "prefixItems_1_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "array with one item is valid",
|
||||
"data": [
|
||||
1
|
||||
],
|
||||
"valid": true,
|
||||
"schema_id": "prefixItems_1_0"
|
||||
},
|
||||
{
|
||||
"description": "array with two items is invalid",
|
||||
"data": [
|
||||
1,
|
||||
"foo"
|
||||
],
|
||||
"valid": false,
|
||||
"schema_id": "prefixItems_1_0"
|
||||
},
|
||||
{
|
||||
"description": "empty array is valid",
|
||||
"data": [],
|
||||
"valid": true,
|
||||
"schema_id": "prefixItems_1_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "additional items are allowed by default",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"prefixItems": [
|
||||
{
|
||||
"type": "integer"
|
||||
}
|
||||
],
|
||||
"extensible": true,
|
||||
"$id": "prefixItems_2_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "only the first item is validated",
|
||||
"data": [
|
||||
1,
|
||||
"foo",
|
||||
false
|
||||
],
|
||||
"valid": true,
|
||||
"schema_id": "prefixItems_2_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "prefixItems with null instance elements",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"prefixItems": [
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
],
|
||||
"$id": "prefixItems_3_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "allows null elements",
|
||||
"data": [
|
||||
null
|
||||
],
|
||||
"valid": true,
|
||||
"schema_id": "prefixItems_3_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "extensible: true allows extra items with prefixItems",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"prefixItems": [
|
||||
{
|
||||
"type": "integer"
|
||||
}
|
||||
],
|
||||
"extensible": true,
|
||||
"$id": "prefixItems_4_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "extra item is valid",
|
||||
"data": [
|
||||
1,
|
||||
"foo"
|
||||
],
|
||||
"valid": true,
|
||||
"schema_id": "prefixItems_4_0"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
543
tests/fixtures/properties.json
vendored
Normal file
543
tests/fixtures/properties.json
vendored
Normal file
@ -0,0 +1,543 @@
|
||||
[
|
||||
{
|
||||
"description": "object properties validation",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"properties": {
|
||||
"foo": {
|
||||
"type": "integer"
|
||||
},
|
||||
"bar": {
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"$id": "properties_0_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "both properties present and valid is valid",
|
||||
"data": {
|
||||
"foo": 1,
|
||||
"bar": "baz"
|
||||
},
|
||||
"valid": true,
|
||||
"schema_id": "properties_0_0"
|
||||
},
|
||||
{
|
||||
"description": "one property invalid is invalid",
|
||||
"data": {
|
||||
"foo": 1,
|
||||
"bar": {}
|
||||
},
|
||||
"valid": false,
|
||||
"schema_id": "properties_0_0"
|
||||
},
|
||||
{
|
||||
"description": "both properties invalid is invalid",
|
||||
"data": {
|
||||
"foo": [],
|
||||
"bar": {}
|
||||
},
|
||||
"valid": false,
|
||||
"schema_id": "properties_0_0"
|
||||
},
|
||||
{
|
||||
"description": "doesn't invalidate other properties",
|
||||
"data": {},
|
||||
"valid": true,
|
||||
"schema_id": "properties_0_0"
|
||||
},
|
||||
{
|
||||
"description": "ignores arrays",
|
||||
"data": [],
|
||||
"valid": true,
|
||||
"schema_id": "properties_0_0"
|
||||
},
|
||||
{
|
||||
"description": "ignores other non-objects",
|
||||
"data": 12,
|
||||
"valid": true,
|
||||
"schema_id": "properties_0_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "properties with boolean schema",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"properties": {
|
||||
"foo": true,
|
||||
"bar": false
|
||||
},
|
||||
"$id": "properties_1_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "no property present is valid",
|
||||
"data": {},
|
||||
"valid": true,
|
||||
"schema_id": "properties_1_0"
|
||||
},
|
||||
{
|
||||
"description": "only 'true' property present is valid",
|
||||
"data": {
|
||||
"foo": 1
|
||||
},
|
||||
"valid": true,
|
||||
"schema_id": "properties_1_0"
|
||||
},
|
||||
{
|
||||
"description": "only 'false' property present is invalid",
|
||||
"data": {
|
||||
"bar": 2
|
||||
},
|
||||
"valid": false,
|
||||
"schema_id": "properties_1_0"
|
||||
},
|
||||
{
|
||||
"description": "both properties present is invalid",
|
||||
"data": {
|
||||
"foo": 1,
|
||||
"bar": 2
|
||||
},
|
||||
"valid": false,
|
||||
"schema_id": "properties_1_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "properties with escaped characters",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"properties": {
|
||||
"foo\nbar": {
|
||||
"type": "number"
|
||||
},
|
||||
"foo\"bar": {
|
||||
"type": "number"
|
||||
},
|
||||
"foo\\bar": {
|
||||
"type": "number"
|
||||
},
|
||||
"foo\rbar": {
|
||||
"type": "number"
|
||||
},
|
||||
"foo\tbar": {
|
||||
"type": "number"
|
||||
},
|
||||
"foo\fbar": {
|
||||
"type": "number"
|
||||
}
|
||||
},
|
||||
"$id": "properties_2_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "object with all numbers is valid",
|
||||
"data": {
|
||||
"foo\nbar": 1,
|
||||
"foo\"bar": 1,
|
||||
"foo\\bar": 1,
|
||||
"foo\rbar": 1,
|
||||
"foo\tbar": 1,
|
||||
"foo\fbar": 1
|
||||
},
|
||||
"valid": true,
|
||||
"schema_id": "properties_2_0"
|
||||
},
|
||||
{
|
||||
"description": "object with strings is invalid",
|
||||
"data": {
|
||||
"foo\nbar": "1",
|
||||
"foo\"bar": "1",
|
||||
"foo\\bar": "1",
|
||||
"foo\rbar": "1",
|
||||
"foo\tbar": "1",
|
||||
"foo\fbar": "1"
|
||||
},
|
||||
"valid": false,
|
||||
"schema_id": "properties_2_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "properties with null valued instance properties",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"properties": {
|
||||
"foo": {
|
||||
"type": "null"
|
||||
}
|
||||
},
|
||||
"$id": "properties_3_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "allows null values",
|
||||
"data": {
|
||||
"foo": null
|
||||
},
|
||||
"valid": true,
|
||||
"schema_id": "properties_3_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "properties whose names are Javascript object property names",
|
||||
"comment": "Ensure JS implementations don't universally consider e.g. __proto__ to always be present in an object.",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"properties": {
|
||||
"__proto__": {
|
||||
"type": "number"
|
||||
},
|
||||
"toString": {
|
||||
"properties": {
|
||||
"length": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
},
|
||||
"constructor": {
|
||||
"type": "number"
|
||||
}
|
||||
},
|
||||
"$id": "properties_4_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "ignores arrays",
|
||||
"data": [],
|
||||
"valid": true,
|
||||
"schema_id": "properties_4_0"
|
||||
},
|
||||
{
|
||||
"description": "ignores other non-objects",
|
||||
"data": 12,
|
||||
"valid": true,
|
||||
"schema_id": "properties_4_0"
|
||||
},
|
||||
{
|
||||
"description": "none of the properties mentioned",
|
||||
"data": {},
|
||||
"valid": true,
|
||||
"schema_id": "properties_4_0"
|
||||
},
|
||||
{
|
||||
"description": "__proto__ not valid",
|
||||
"data": {
|
||||
"__proto__": "foo"
|
||||
},
|
||||
"valid": false,
|
||||
"schema_id": "properties_4_0"
|
||||
},
|
||||
{
|
||||
"description": "toString not valid",
|
||||
"data": {
|
||||
"toString": {
|
||||
"length": 37
|
||||
}
|
||||
},
|
||||
"valid": false,
|
||||
"schema_id": "properties_4_0"
|
||||
},
|
||||
{
|
||||
"description": "constructor not valid",
|
||||
"data": {
|
||||
"constructor": {
|
||||
"length": 37
|
||||
}
|
||||
},
|
||||
"valid": false,
|
||||
"schema_id": "properties_4_0"
|
||||
},
|
||||
{
|
||||
"description": "all present and valid",
|
||||
"data": {
|
||||
"__proto__": 12,
|
||||
"toString": {
|
||||
"length": "foo"
|
||||
},
|
||||
"constructor": 37
|
||||
},
|
||||
"valid": true,
|
||||
"schema_id": "properties_4_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "extensible: true allows extra properties",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"properties": {
|
||||
"foo": {
|
||||
"type": "integer"
|
||||
}
|
||||
},
|
||||
"extensible": true,
|
||||
"$id": "properties_5_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "extra property is valid",
|
||||
"data": {
|
||||
"foo": 1,
|
||||
"bar": "baz"
|
||||
},
|
||||
"valid": true,
|
||||
"schema_id": "properties_5_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "strict by default: extra properties invalid",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"properties": {
|
||||
"foo": {
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"$id": "properties_6_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "extra property is invalid",
|
||||
"data": {
|
||||
"foo": "bar",
|
||||
"extra": 1
|
||||
},
|
||||
"valid": false,
|
||||
"schema_id": "properties_6_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "inheritance: nested object inherits strictness from strict parent",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"properties": {
|
||||
"nested": {
|
||||
"properties": {
|
||||
"foo": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"$id": "properties_7_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "nested extra property is invalid",
|
||||
"data": {
|
||||
"nested": {
|
||||
"foo": "bar",
|
||||
"extra": 1
|
||||
}
|
||||
},
|
||||
"valid": false,
|
||||
"schema_id": "properties_7_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "override: nested object allows extra properties if extensible: true",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"properties": {
|
||||
"nested": {
|
||||
"extensible": true,
|
||||
"properties": {
|
||||
"foo": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"$id": "properties_8_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "nested extra property is valid",
|
||||
"data": {
|
||||
"nested": {
|
||||
"foo": "bar",
|
||||
"extra": 1
|
||||
}
|
||||
},
|
||||
"valid": true,
|
||||
"schema_id": "properties_8_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "inheritance: nested object inherits looseness from loose parent",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"extensible": true,
|
||||
"properties": {
|
||||
"nested": {
|
||||
"properties": {
|
||||
"foo": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"$id": "properties_9_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "nested extra property is valid",
|
||||
"data": {
|
||||
"nested": {
|
||||
"foo": "bar",
|
||||
"extra": 1
|
||||
}
|
||||
},
|
||||
"valid": true,
|
||||
"schema_id": "properties_9_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "override: nested object enforces strictness if extensible: false",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"extensible": true,
|
||||
"properties": {
|
||||
"nested": {
|
||||
"extensible": false,
|
||||
"properties": {
|
||||
"foo": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"$id": "properties_10_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "nested extra property is invalid",
|
||||
"data": {
|
||||
"nested": {
|
||||
"foo": "bar",
|
||||
"extra": 1
|
||||
}
|
||||
},
|
||||
"valid": false,
|
||||
"schema_id": "properties_10_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "arrays: inline items inherit strictness from strict parent",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"properties": {
|
||||
"list": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"properties": {
|
||||
"foo": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"$id": "properties_11_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "array item with extra property is invalid (strict parent)",
|
||||
"data": {
|
||||
"list": [
|
||||
{
|
||||
"foo": "bar",
|
||||
"extra": 1
|
||||
}
|
||||
]
|
||||
},
|
||||
"valid": false,
|
||||
"schema_id": "properties_11_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "arrays: inline items inherit looseness from loose parent",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"extensible": true,
|
||||
"properties": {
|
||||
"list": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"properties": {
|
||||
"foo": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"$id": "properties_12_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "array item with extra property is valid (loose parent)",
|
||||
"data": {
|
||||
"list": [
|
||||
{
|
||||
"foo": "bar",
|
||||
"extra": 1
|
||||
}
|
||||
]
|
||||
},
|
||||
"valid": true,
|
||||
"schema_id": "properties_12_0"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
281
tests/fixtures/propertyNames.json
vendored
Normal file
281
tests/fixtures/propertyNames.json
vendored
Normal file
@ -0,0 +1,281 @@
|
||||
[
|
||||
{
|
||||
"description": "propertyNames validation",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"propertyNames": {
|
||||
"maxLength": 3
|
||||
},
|
||||
"extensible": true,
|
||||
"$id": "propertyNames_0_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "all property names valid",
|
||||
"data": {
|
||||
"f": {},
|
||||
"foo": {}
|
||||
},
|
||||
"valid": true,
|
||||
"schema_id": "propertyNames_0_0"
|
||||
},
|
||||
{
|
||||
"description": "some property names invalid",
|
||||
"data": {
|
||||
"foo": {},
|
||||
"foobar": {}
|
||||
},
|
||||
"valid": false,
|
||||
"schema_id": "propertyNames_0_0"
|
||||
},
|
||||
{
|
||||
"description": "object without properties is valid",
|
||||
"data": {},
|
||||
"valid": true,
|
||||
"schema_id": "propertyNames_0_0"
|
||||
},
|
||||
{
|
||||
"description": "ignores arrays",
|
||||
"data": [
|
||||
1,
|
||||
2,
|
||||
3,
|
||||
4
|
||||
],
|
||||
"valid": true,
|
||||
"schema_id": "propertyNames_0_0"
|
||||
},
|
||||
{
|
||||
"description": "ignores strings",
|
||||
"data": "foobar",
|
||||
"valid": true,
|
||||
"schema_id": "propertyNames_0_0"
|
||||
},
|
||||
{
|
||||
"description": "ignores other non-objects",
|
||||
"data": 12,
|
||||
"valid": true,
|
||||
"schema_id": "propertyNames_0_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "propertyNames validation with pattern",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"propertyNames": {
|
||||
"pattern": "^a+$"
|
||||
},
|
||||
"extensible": true,
|
||||
"$id": "propertyNames_1_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "matching property names valid",
|
||||
"data": {
|
||||
"a": {},
|
||||
"aa": {},
|
||||
"aaa": {}
|
||||
},
|
||||
"valid": true,
|
||||
"schema_id": "propertyNames_1_0"
|
||||
},
|
||||
{
|
||||
"description": "non-matching property name is invalid",
|
||||
"data": {
|
||||
"aaA": {}
|
||||
},
|
||||
"valid": false,
|
||||
"schema_id": "propertyNames_1_0"
|
||||
},
|
||||
{
|
||||
"description": "object without properties is valid",
|
||||
"data": {},
|
||||
"valid": true,
|
||||
"schema_id": "propertyNames_1_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "propertyNames with boolean schema true",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"propertyNames": true,
|
||||
"extensible": true,
|
||||
"$id": "propertyNames_2_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "object with any properties is valid",
|
||||
"data": {
|
||||
"foo": 1
|
||||
},
|
||||
"valid": true,
|
||||
"schema_id": "propertyNames_2_0"
|
||||
},
|
||||
{
|
||||
"description": "empty object is valid",
|
||||
"data": {},
|
||||
"valid": true,
|
||||
"schema_id": "propertyNames_2_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "propertyNames with boolean schema false",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"propertyNames": false,
|
||||
"extensible": true,
|
||||
"$id": "propertyNames_3_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "object with any properties is invalid",
|
||||
"data": {
|
||||
"foo": 1
|
||||
},
|
||||
"valid": false,
|
||||
"schema_id": "propertyNames_3_0"
|
||||
},
|
||||
{
|
||||
"description": "empty object is valid",
|
||||
"data": {},
|
||||
"valid": true,
|
||||
"schema_id": "propertyNames_3_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "propertyNames with const",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"propertyNames": {
|
||||
"const": "foo"
|
||||
},
|
||||
"extensible": true,
|
||||
"$id": "propertyNames_4_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "object with property foo is valid",
|
||||
"data": {
|
||||
"foo": 1
|
||||
},
|
||||
"valid": true,
|
||||
"schema_id": "propertyNames_4_0"
|
||||
},
|
||||
{
|
||||
"description": "object with any other property is invalid",
|
||||
"data": {
|
||||
"bar": 1
|
||||
},
|
||||
"valid": false,
|
||||
"schema_id": "propertyNames_4_0"
|
||||
},
|
||||
{
|
||||
"description": "empty object is valid",
|
||||
"data": {},
|
||||
"valid": true,
|
||||
"schema_id": "propertyNames_4_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "propertyNames with enum",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"propertyNames": {
|
||||
"enum": [
|
||||
"foo",
|
||||
"bar"
|
||||
]
|
||||
},
|
||||
"extensible": true,
|
||||
"$id": "propertyNames_5_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "object with property foo is valid",
|
||||
"data": {
|
||||
"foo": 1
|
||||
},
|
||||
"valid": true,
|
||||
"schema_id": "propertyNames_5_0"
|
||||
},
|
||||
{
|
||||
"description": "object with property foo and bar is valid",
|
||||
"data": {
|
||||
"foo": 1,
|
||||
"bar": 1
|
||||
},
|
||||
"valid": true,
|
||||
"schema_id": "propertyNames_5_0"
|
||||
},
|
||||
{
|
||||
"description": "object with any other property is invalid",
|
||||
"data": {
|
||||
"baz": 1
|
||||
},
|
||||
"valid": false,
|
||||
"schema_id": "propertyNames_5_0"
|
||||
},
|
||||
{
|
||||
"description": "empty object is valid",
|
||||
"data": {},
|
||||
"valid": true,
|
||||
"schema_id": "propertyNames_5_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "extensible: true allows extra properties (checked by propertyNames)",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"propertyNames": {
|
||||
"maxLength": 3
|
||||
},
|
||||
"extensible": true,
|
||||
"$id": "propertyNames_6_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "extra property with valid name is valid",
|
||||
"data": {
|
||||
"foo": 1
|
||||
},
|
||||
"valid": true,
|
||||
"schema_id": "propertyNames_6_0"
|
||||
},
|
||||
{
|
||||
"description": "extra property with invalid name is invalid",
|
||||
"data": {
|
||||
"foobar": 1
|
||||
},
|
||||
"valid": false,
|
||||
"schema_id": "propertyNames_6_0"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
833
tests/fixtures/ref.json
vendored
Normal file
833
tests/fixtures/ref.json
vendored
Normal file
@ -0,0 +1,833 @@
|
||||
[
|
||||
{
|
||||
"description": "nested refs",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"$ref": "c_212",
|
||||
"$id": "ref_4_0"
|
||||
},
|
||||
{
|
||||
"$id": "a_212",
|
||||
"type": "integer"
|
||||
},
|
||||
{
|
||||
"$id": "b_212",
|
||||
"$ref": "a_212"
|
||||
},
|
||||
{
|
||||
"$id": "c_212",
|
||||
"$ref": "b_212"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "nested ref valid",
|
||||
"data": 5,
|
||||
"valid": true,
|
||||
"schema_id": "ref_4_0"
|
||||
},
|
||||
{
|
||||
"description": "nested ref invalid",
|
||||
"data": "a",
|
||||
"valid": false,
|
||||
"schema_id": "ref_4_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "ref applies alongside sibling keywords",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"properties": {
|
||||
"foo": {
|
||||
"$ref": "reffed_248",
|
||||
"maxItems": 2
|
||||
}
|
||||
},
|
||||
"$id": "ref_5_0"
|
||||
},
|
||||
{
|
||||
"$id": "reffed_248",
|
||||
"type": "array"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "ref valid, maxItems valid",
|
||||
"data": {
|
||||
"foo": []
|
||||
},
|
||||
"valid": true,
|
||||
"schema_id": "ref_5_0"
|
||||
},
|
||||
{
|
||||
"description": "ref valid, maxItems invalid",
|
||||
"data": {
|
||||
"foo": [
|
||||
1,
|
||||
2,
|
||||
3
|
||||
]
|
||||
},
|
||||
"valid": false,
|
||||
"schema_id": "ref_5_0"
|
||||
},
|
||||
{
|
||||
"description": "ref invalid",
|
||||
"data": {
|
||||
"foo": "string"
|
||||
},
|
||||
"valid": false,
|
||||
"schema_id": "ref_5_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "property named $ref that is not a reference",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"properties": {
|
||||
"$ref": {
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"$id": "ref_6_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "property named $ref valid",
|
||||
"data": {
|
||||
"$ref": "a"
|
||||
},
|
||||
"valid": true,
|
||||
"schema_id": "ref_6_0"
|
||||
},
|
||||
{
|
||||
"description": "property named $ref invalid",
|
||||
"data": {
|
||||
"$ref": 2
|
||||
},
|
||||
"valid": false,
|
||||
"schema_id": "ref_6_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "property named $ref, containing an actual $ref",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"properties": {
|
||||
"$ref": {
|
||||
"$ref": "is-string_344"
|
||||
}
|
||||
},
|
||||
"$id": "ref_7_0"
|
||||
},
|
||||
{
|
||||
"$id": "is-string_344",
|
||||
"type": "string"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "property named $ref valid",
|
||||
"data": {
|
||||
"$ref": "a"
|
||||
},
|
||||
"valid": true,
|
||||
"schema_id": "ref_7_0"
|
||||
},
|
||||
{
|
||||
"description": "property named $ref invalid",
|
||||
"data": {
|
||||
"$ref": 2
|
||||
},
|
||||
"valid": false,
|
||||
"schema_id": "ref_7_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "$ref to boolean schema true",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"$ref": "bool_378",
|
||||
"$id": "ref_8_0"
|
||||
},
|
||||
{
|
||||
"$id": "bool_378",
|
||||
"extensible": true
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "any value is valid",
|
||||
"data": "foo",
|
||||
"valid": true,
|
||||
"schema_id": "ref_8_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "$ref to boolean schema false",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"$ref": "bool_400",
|
||||
"$id": "ref_9_0"
|
||||
},
|
||||
{
|
||||
"$id": "bool_400",
|
||||
"extensible": false,
|
||||
"not": {}
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "any value is invalid",
|
||||
"data": "foo",
|
||||
"valid": false,
|
||||
"schema_id": "ref_9_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "refs with quote",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"properties": {
|
||||
"foo\"bar": {
|
||||
"$ref": "foo%22bar_550"
|
||||
}
|
||||
},
|
||||
"$id": "ref_11_0"
|
||||
},
|
||||
{
|
||||
"$id": "foo%22bar_550",
|
||||
"type": "number"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "object with numbers is valid",
|
||||
"data": {
|
||||
"foo\"bar": 1
|
||||
},
|
||||
"valid": true,
|
||||
"schema_id": "ref_11_0"
|
||||
},
|
||||
{
|
||||
"description": "object with strings is invalid",
|
||||
"data": {
|
||||
"foo\"bar": "1"
|
||||
},
|
||||
"valid": false,
|
||||
"schema_id": "ref_11_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "$ref boundary resets to loose",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"$ref": "target_1465",
|
||||
"$id": "ref_35_0"
|
||||
},
|
||||
{
|
||||
"$id": "target_1465",
|
||||
"properties": {
|
||||
"foo": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "extra property in ref target is invalid (strict by default)",
|
||||
"data": {
|
||||
"foo": "bar",
|
||||
"extra": 1
|
||||
},
|
||||
"valid": false,
|
||||
"schema_id": "ref_35_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "$ref target can enforce strictness",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"$ref": "target_1496",
|
||||
"$id": "ref_36_0"
|
||||
},
|
||||
{
|
||||
"$id": "target_1496",
|
||||
"extensible": false,
|
||||
"properties": {
|
||||
"foo": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "extra property in ref target is invalid",
|
||||
"data": {
|
||||
"foo": "bar",
|
||||
"extra": 1
|
||||
},
|
||||
"valid": false,
|
||||
"schema_id": "ref_36_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "strictness: boundary reset at $ref",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"extensible": true,
|
||||
"properties": {
|
||||
"inline_child": {
|
||||
"properties": {
|
||||
"a": {
|
||||
"type": "integer"
|
||||
}
|
||||
}
|
||||
},
|
||||
"ref_child": {
|
||||
"$ref": "strict_node_1544"
|
||||
},
|
||||
"extensible_ref_child": {
|
||||
"$ref": "extensible_node_1551"
|
||||
}
|
||||
},
|
||||
"$id": "ref_37_0"
|
||||
},
|
||||
{
|
||||
"$id": "strict_node_1544",
|
||||
"properties": {
|
||||
"b": {
|
||||
"type": "integer"
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"$id": "extensible_node_1551",
|
||||
"extensible": true,
|
||||
"properties": {
|
||||
"c": {
|
||||
"type": "integer"
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "inline child inherits looseness",
|
||||
"data": {
|
||||
"inline_child": {
|
||||
"a": 1,
|
||||
"extra": 2
|
||||
}
|
||||
},
|
||||
"valid": true,
|
||||
"schema_id": "ref_37_0"
|
||||
},
|
||||
{
|
||||
"description": "ref child resets to strict (default)",
|
||||
"data": {
|
||||
"ref_child": {
|
||||
"b": 1,
|
||||
"extra": 2
|
||||
}
|
||||
},
|
||||
"valid": false,
|
||||
"schema_id": "ref_37_0"
|
||||
},
|
||||
{
|
||||
"description": "ref child with explicit extensible=true is loose",
|
||||
"data": {
|
||||
"extensible_ref_child": {
|
||||
"c": 1,
|
||||
"extra": 2
|
||||
}
|
||||
},
|
||||
"valid": true,
|
||||
"schema_id": "ref_37_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "arrays: ref items inherit strictness (reset at boundary)",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"properties": {
|
||||
"list": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"$ref": "strict_node_1614"
|
||||
}
|
||||
}
|
||||
},
|
||||
"$id": "ref_38_0"
|
||||
},
|
||||
{
|
||||
"$id": "strict_node_1614",
|
||||
"properties": {
|
||||
"a": {
|
||||
"type": "integer"
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "ref item with extra property is invalid (strict by default)",
|
||||
"data": {
|
||||
"list": [
|
||||
{
|
||||
"a": 1,
|
||||
"extra": 2
|
||||
}
|
||||
]
|
||||
},
|
||||
"valid": false,
|
||||
"schema_id": "ref_38_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "implicit keyword shadowing",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"$ref": "parent_1648",
|
||||
"properties": {
|
||||
"type": {
|
||||
"const": "child"
|
||||
},
|
||||
"age": {
|
||||
"minimum": 15
|
||||
}
|
||||
},
|
||||
"$id": "ref_39_0"
|
||||
},
|
||||
{
|
||||
"$id": "parent_1648",
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"type": {
|
||||
"const": "parent"
|
||||
},
|
||||
"age": {
|
||||
"minimum": 10,
|
||||
"maximum": 20
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"type",
|
||||
"age"
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "child type overrides parent type",
|
||||
"data": {
|
||||
"type": "child",
|
||||
"age": 15
|
||||
},
|
||||
"valid": true,
|
||||
"schema_id": "ref_39_0"
|
||||
},
|
||||
{
|
||||
"description": "parent type is now invalid (shadowed)",
|
||||
"data": {
|
||||
"type": "parent",
|
||||
"age": 15
|
||||
},
|
||||
"valid": false,
|
||||
"schema_id": "ref_39_0"
|
||||
},
|
||||
{
|
||||
"description": "child min age (15) is enforced",
|
||||
"data": {
|
||||
"type": "child",
|
||||
"age": 12
|
||||
},
|
||||
"valid": false,
|
||||
"schema_id": "ref_39_0"
|
||||
},
|
||||
{
|
||||
"description": "parent max age (20) is shadowed (replaced) by child definition",
|
||||
"data": {
|
||||
"type": "child",
|
||||
"age": 21
|
||||
},
|
||||
"valid": true,
|
||||
"schema_id": "ref_39_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "Entities extending entities (Physical Birth)",
|
||||
"database": {
|
||||
"types": [
|
||||
{
|
||||
"name": "entity",
|
||||
"variations": [
|
||||
"entity",
|
||||
"organization",
|
||||
"person"
|
||||
],
|
||||
"schemas": [
|
||||
{
|
||||
"$id": "entity",
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"id": {
|
||||
"type": "string"
|
||||
},
|
||||
"type": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "organization",
|
||||
"variations": [
|
||||
"organization",
|
||||
"person"
|
||||
],
|
||||
"schemas": [
|
||||
{
|
||||
"$id": "organization",
|
||||
"$ref": "entity",
|
||||
"properties": {
|
||||
"name": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "person",
|
||||
"variations": [
|
||||
"person"
|
||||
],
|
||||
"schemas": [
|
||||
{
|
||||
"$id": "person",
|
||||
"$ref": "organization",
|
||||
"properties": {
|
||||
"first_name": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"puncs": [
|
||||
{
|
||||
"name": "save_org",
|
||||
"schemas": [
|
||||
{
|
||||
"$id": "save_org.request",
|
||||
"$ref": "organization"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "Valid person against organization schema (implicit type allowance from physical hierarchy)",
|
||||
"schema_id": "save_org.request",
|
||||
"data": {
|
||||
"id": "1",
|
||||
"type": "person",
|
||||
"name": "ACME"
|
||||
},
|
||||
"valid": true
|
||||
},
|
||||
{
|
||||
"description": "Valid organization against organization schema",
|
||||
"schema_id": "save_org.request",
|
||||
"data": {
|
||||
"id": "2",
|
||||
"type": "organization",
|
||||
"name": "ACME"
|
||||
},
|
||||
"valid": true
|
||||
},
|
||||
{
|
||||
"description": "Invalid entity against organization schema (ancestor not allowed)",
|
||||
"schema_id": "save_org.request",
|
||||
"data": {
|
||||
"id": "3",
|
||||
"type": "entity"
|
||||
},
|
||||
"valid": false,
|
||||
"expect_errors": [
|
||||
{
|
||||
"code": "TYPE_MISMATCH",
|
||||
"path": "/type"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "Viral Infection: Ad-hocs inheriting entity boundaries via $ref",
|
||||
"database": {
|
||||
"types": [
|
||||
{
|
||||
"name": "entity",
|
||||
"variations": [
|
||||
"entity",
|
||||
"person"
|
||||
],
|
||||
"schemas": [
|
||||
{
|
||||
"$id": "entity",
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"id": {
|
||||
"type": "string"
|
||||
},
|
||||
"type": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "person",
|
||||
"variations": [
|
||||
"person"
|
||||
],
|
||||
"schemas": [
|
||||
{
|
||||
"$id": "person",
|
||||
"$ref": "entity",
|
||||
"properties": {
|
||||
"first_name": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"$id": "light.person",
|
||||
"$ref": "entity",
|
||||
"properties": {
|
||||
"first_name": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"puncs": [
|
||||
{
|
||||
"name": "save_person_light",
|
||||
"schemas": [
|
||||
{
|
||||
"$id": "save_person_light.request",
|
||||
"$ref": "light.person",
|
||||
"properties": {
|
||||
"extra_request_field": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "Valid person against ad-hoc request schema (request virally inherited person variations)",
|
||||
"schema_id": "save_person_light.request",
|
||||
"data": {
|
||||
"id": "1",
|
||||
"type": "person",
|
||||
"first_name": "John",
|
||||
"extra_request_field": "test"
|
||||
},
|
||||
"valid": true
|
||||
},
|
||||
{
|
||||
"description": "Invalid entity against ad-hoc request schema (viral inheritance enforces person boundary)",
|
||||
"schema_id": "save_person_light.request",
|
||||
"data": {
|
||||
"id": "1",
|
||||
"type": "entity",
|
||||
"first_name": "John"
|
||||
},
|
||||
"valid": false,
|
||||
"expect_errors": [
|
||||
{
|
||||
"code": "TYPE_MISMATCH",
|
||||
"path": "/type"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "Ad-hocs extending ad-hocs (No type property)",
|
||||
"database": {
|
||||
"puncs": [
|
||||
{
|
||||
"name": "save_address",
|
||||
"schemas": [
|
||||
{
|
||||
"$id": "address",
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"street": {
|
||||
"type": "string"
|
||||
},
|
||||
"city": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"$id": "us_address",
|
||||
"$ref": "address",
|
||||
"properties": {
|
||||
"state": {
|
||||
"type": "string"
|
||||
},
|
||||
"zip": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"$id": "save_address.request",
|
||||
"$ref": "us_address"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "Valid us_address",
|
||||
"schema_id": "save_address.request",
|
||||
"data": {
|
||||
"street": "123 Main",
|
||||
"city": "Anytown",
|
||||
"state": "CA",
|
||||
"zip": "12345"
|
||||
},
|
||||
"valid": true
|
||||
},
|
||||
{
|
||||
"description": "Invalid base address against us_address",
|
||||
"schema_id": "save_address.request",
|
||||
"data": {
|
||||
"street": "123 Main",
|
||||
"city": "Anytown"
|
||||
},
|
||||
"valid": true
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "Ad-hocs extending ad-hocs (with string type property, no magic)",
|
||||
"database": {
|
||||
"puncs": [
|
||||
{
|
||||
"name": "save_config",
|
||||
"schemas": [
|
||||
{
|
||||
"$id": "config_base",
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"type": {
|
||||
"type": "string",
|
||||
"const": "config_base"
|
||||
},
|
||||
"setting": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"$id": "config_advanced",
|
||||
"$ref": "config_base",
|
||||
"properties": {
|
||||
"type": {
|
||||
"type": "string",
|
||||
"const": "config_advanced"
|
||||
},
|
||||
"advanced_setting": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"$id": "save_config.request",
|
||||
"$ref": "config_base"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "Valid config_base against config_base",
|
||||
"schema_id": "save_config.request",
|
||||
"data": {
|
||||
"type": "config_base",
|
||||
"setting": "on"
|
||||
},
|
||||
"valid": true
|
||||
},
|
||||
{
|
||||
"description": "Invalid config_advanced against config_base (no type magic, const is strictly 'config_base')",
|
||||
"schema_id": "save_config.request",
|
||||
"data": {
|
||||
"type": "config_advanced",
|
||||
"setting": "on",
|
||||
"advanced_setting": "off"
|
||||
},
|
||||
"valid": false
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
255
tests/fixtures/required.json
vendored
Normal file
255
tests/fixtures/required.json
vendored
Normal file
@ -0,0 +1,255 @@
|
||||
[
|
||||
{
|
||||
"description": "required validation",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"properties": {
|
||||
"foo": {},
|
||||
"bar": {}
|
||||
},
|
||||
"required": [
|
||||
"foo"
|
||||
],
|
||||
"$id": "required_0_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "present required property is valid",
|
||||
"data": {
|
||||
"foo": 1
|
||||
},
|
||||
"valid": true,
|
||||
"schema_id": "required_0_0"
|
||||
},
|
||||
{
|
||||
"description": "non-present required property is invalid",
|
||||
"data": {
|
||||
"bar": 1
|
||||
},
|
||||
"valid": false,
|
||||
"schema_id": "required_0_0"
|
||||
},
|
||||
{
|
||||
"description": "ignores arrays",
|
||||
"data": [],
|
||||
"valid": true,
|
||||
"schema_id": "required_0_0"
|
||||
},
|
||||
{
|
||||
"description": "ignores strings",
|
||||
"data": "",
|
||||
"valid": true,
|
||||
"schema_id": "required_0_0"
|
||||
},
|
||||
{
|
||||
"description": "ignores other non-objects",
|
||||
"data": 12,
|
||||
"valid": true,
|
||||
"schema_id": "required_0_0"
|
||||
},
|
||||
{
|
||||
"description": "ignores null",
|
||||
"data": null,
|
||||
"valid": true,
|
||||
"schema_id": "required_0_0"
|
||||
},
|
||||
{
|
||||
"description": "ignores boolean",
|
||||
"data": true,
|
||||
"valid": true,
|
||||
"schema_id": "required_0_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "required default validation",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"properties": {
|
||||
"foo": {}
|
||||
},
|
||||
"$id": "required_1_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "not required by default",
|
||||
"data": {},
|
||||
"valid": true,
|
||||
"schema_id": "required_1_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "required with empty array",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"properties": {
|
||||
"foo": {}
|
||||
},
|
||||
"required": [],
|
||||
"$id": "required_2_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "property not required",
|
||||
"data": {},
|
||||
"valid": true,
|
||||
"schema_id": "required_2_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "required with escaped characters",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"required": [
|
||||
"foo\nbar",
|
||||
"foo\"bar",
|
||||
"foo\\bar",
|
||||
"foo\rbar",
|
||||
"foo\tbar",
|
||||
"foo\fbar"
|
||||
],
|
||||
"extensible": true,
|
||||
"$id": "required_3_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "object with all properties present is valid",
|
||||
"data": {
|
||||
"foo\nbar": 1,
|
||||
"foo\"bar": 1,
|
||||
"foo\\bar": 1,
|
||||
"foo\rbar": 1,
|
||||
"foo\tbar": 1,
|
||||
"foo\fbar": 1
|
||||
},
|
||||
"valid": true,
|
||||
"schema_id": "required_3_0"
|
||||
},
|
||||
{
|
||||
"description": "object with some properties missing is invalid",
|
||||
"data": {
|
||||
"foo\nbar": "1",
|
||||
"foo\"bar": "1"
|
||||
},
|
||||
"valid": false,
|
||||
"schema_id": "required_3_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "required properties whose names are Javascript object property names",
|
||||
"comment": "Ensure JS implementations don't universally consider e.g. __proto__ to always be present in an object.",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"required": [
|
||||
"__proto__",
|
||||
"toString",
|
||||
"constructor"
|
||||
],
|
||||
"extensible": true,
|
||||
"$id": "required_4_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "ignores arrays",
|
||||
"data": [],
|
||||
"valid": true,
|
||||
"schema_id": "required_4_0"
|
||||
},
|
||||
{
|
||||
"description": "ignores other non-objects",
|
||||
"data": 12,
|
||||
"valid": true,
|
||||
"schema_id": "required_4_0"
|
||||
},
|
||||
{
|
||||
"description": "none of the properties mentioned",
|
||||
"data": {},
|
||||
"valid": false,
|
||||
"schema_id": "required_4_0"
|
||||
},
|
||||
{
|
||||
"description": "__proto__ present",
|
||||
"data": {
|
||||
"__proto__": "foo"
|
||||
},
|
||||
"valid": false,
|
||||
"schema_id": "required_4_0"
|
||||
},
|
||||
{
|
||||
"description": "toString present",
|
||||
"data": {
|
||||
"toString": {
|
||||
"length": 37
|
||||
}
|
||||
},
|
||||
"valid": false,
|
||||
"schema_id": "required_4_0"
|
||||
},
|
||||
{
|
||||
"description": "constructor present",
|
||||
"data": {
|
||||
"constructor": {
|
||||
"length": 37
|
||||
}
|
||||
},
|
||||
"valid": false,
|
||||
"schema_id": "required_4_0"
|
||||
},
|
||||
{
|
||||
"description": "all present",
|
||||
"data": {
|
||||
"__proto__": 12,
|
||||
"toString": {
|
||||
"length": "foo"
|
||||
},
|
||||
"constructor": 37
|
||||
},
|
||||
"valid": true,
|
||||
"schema_id": "required_4_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "extensible: true allows extra properties in required",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"required": [
|
||||
"foo"
|
||||
],
|
||||
"extensible": true,
|
||||
"$id": "required_5_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "extra property is valid",
|
||||
"data": {
|
||||
"foo": 1,
|
||||
"bar": 2
|
||||
},
|
||||
"valid": true,
|
||||
"schema_id": "required_5_0"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
669
tests/fixtures/type.json
vendored
Normal file
669
tests/fixtures/type.json
vendored
Normal file
@ -0,0 +1,669 @@
|
||||
[
|
||||
{
|
||||
"description": "integer type matches integers",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"type": "integer",
|
||||
"$id": "type_0_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "an integer is an integer",
|
||||
"data": 1,
|
||||
"valid": true,
|
||||
"schema_id": "type_0_0"
|
||||
},
|
||||
{
|
||||
"description": "a float with zero fractional part is an integer",
|
||||
"data": 1,
|
||||
"valid": true,
|
||||
"schema_id": "type_0_0"
|
||||
},
|
||||
{
|
||||
"description": "a float is not an integer",
|
||||
"data": 1.1,
|
||||
"valid": false,
|
||||
"schema_id": "type_0_0"
|
||||
},
|
||||
{
|
||||
"description": "a string is not an integer",
|
||||
"data": "foo",
|
||||
"valid": false,
|
||||
"schema_id": "type_0_0"
|
||||
},
|
||||
{
|
||||
"description": "a string is still not an integer, even if it looks like one",
|
||||
"data": "1",
|
||||
"valid": false,
|
||||
"schema_id": "type_0_0"
|
||||
},
|
||||
{
|
||||
"description": "an object is not an integer",
|
||||
"data": {},
|
||||
"valid": false,
|
||||
"schema_id": "type_0_0"
|
||||
},
|
||||
{
|
||||
"description": "an array is not an integer",
|
||||
"data": [],
|
||||
"valid": false,
|
||||
"schema_id": "type_0_0"
|
||||
},
|
||||
{
|
||||
"description": "a boolean is not an integer",
|
||||
"data": true,
|
||||
"valid": false,
|
||||
"schema_id": "type_0_0"
|
||||
},
|
||||
{
|
||||
"description": "null is not an integer",
|
||||
"data": null,
|
||||
"valid": false,
|
||||
"schema_id": "type_0_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "number type matches numbers",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"type": "number",
|
||||
"$id": "type_1_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "an integer is a number",
|
||||
"data": 1,
|
||||
"valid": true,
|
||||
"schema_id": "type_1_0"
|
||||
},
|
||||
{
|
||||
"description": "a float with zero fractional part is a number (and an integer)",
|
||||
"data": 1,
|
||||
"valid": true,
|
||||
"schema_id": "type_1_0"
|
||||
},
|
||||
{
|
||||
"description": "a float is a number",
|
||||
"data": 1.1,
|
||||
"valid": true,
|
||||
"schema_id": "type_1_0"
|
||||
},
|
||||
{
|
||||
"description": "a string is not a number",
|
||||
"data": "foo",
|
||||
"valid": false,
|
||||
"schema_id": "type_1_0"
|
||||
},
|
||||
{
|
||||
"description": "a string is still not a number, even if it looks like one",
|
||||
"data": "1",
|
||||
"valid": false,
|
||||
"schema_id": "type_1_0"
|
||||
},
|
||||
{
|
||||
"description": "an object is not a number",
|
||||
"data": {},
|
||||
"valid": false,
|
||||
"schema_id": "type_1_0"
|
||||
},
|
||||
{
|
||||
"description": "an array is not a number",
|
||||
"data": [],
|
||||
"valid": false,
|
||||
"schema_id": "type_1_0"
|
||||
},
|
||||
{
|
||||
"description": "a boolean is not a number",
|
||||
"data": true,
|
||||
"valid": false,
|
||||
"schema_id": "type_1_0"
|
||||
},
|
||||
{
|
||||
"description": "null is not a number",
|
||||
"data": null,
|
||||
"valid": false,
|
||||
"schema_id": "type_1_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "string type matches strings",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"type": "string",
|
||||
"$id": "type_2_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "1 is not a string",
|
||||
"data": 1,
|
||||
"valid": false,
|
||||
"schema_id": "type_2_0"
|
||||
},
|
||||
{
|
||||
"description": "a float is not a string",
|
||||
"data": 1.1,
|
||||
"valid": false,
|
||||
"schema_id": "type_2_0"
|
||||
},
|
||||
{
|
||||
"description": "a string is a string",
|
||||
"data": "foo",
|
||||
"valid": true,
|
||||
"schema_id": "type_2_0"
|
||||
},
|
||||
{
|
||||
"description": "a string is still a string, even if it looks like a number",
|
||||
"data": "1",
|
||||
"valid": true,
|
||||
"schema_id": "type_2_0"
|
||||
},
|
||||
{
|
||||
"description": "an empty string is still a string",
|
||||
"data": "",
|
||||
"valid": true,
|
||||
"schema_id": "type_2_0"
|
||||
},
|
||||
{
|
||||
"description": "an object is not a string",
|
||||
"data": {},
|
||||
"valid": false,
|
||||
"schema_id": "type_2_0"
|
||||
},
|
||||
{
|
||||
"description": "an array is not a string",
|
||||
"data": [],
|
||||
"valid": false,
|
||||
"schema_id": "type_2_0"
|
||||
},
|
||||
{
|
||||
"description": "a boolean is not a string",
|
||||
"data": true,
|
||||
"valid": false,
|
||||
"schema_id": "type_2_0"
|
||||
},
|
||||
{
|
||||
"description": "null is not a string",
|
||||
"data": null,
|
||||
"valid": false,
|
||||
"schema_id": "type_2_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "object type matches objects",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"type": "object",
|
||||
"$id": "type_3_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "an integer is not an object",
|
||||
"data": 1,
|
||||
"valid": false,
|
||||
"schema_id": "type_3_0"
|
||||
},
|
||||
{
|
||||
"description": "a float is not an object",
|
||||
"data": 1.1,
|
||||
"valid": false,
|
||||
"schema_id": "type_3_0"
|
||||
},
|
||||
{
|
||||
"description": "a string is not an object",
|
||||
"data": "foo",
|
||||
"valid": false,
|
||||
"schema_id": "type_3_0"
|
||||
},
|
||||
{
|
||||
"description": "an object is an object",
|
||||
"data": {},
|
||||
"valid": true,
|
||||
"schema_id": "type_3_0"
|
||||
},
|
||||
{
|
||||
"description": "an array is not an object",
|
||||
"data": [],
|
||||
"valid": false,
|
||||
"schema_id": "type_3_0"
|
||||
},
|
||||
{
|
||||
"description": "a boolean is not an object",
|
||||
"data": true,
|
||||
"valid": false,
|
||||
"schema_id": "type_3_0"
|
||||
},
|
||||
{
|
||||
"description": "null is not an object",
|
||||
"data": null,
|
||||
"valid": false,
|
||||
"schema_id": "type_3_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "array type matches arrays",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"type": "array",
|
||||
"$id": "type_4_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "an integer is not an array",
|
||||
"data": 1,
|
||||
"valid": false,
|
||||
"schema_id": "type_4_0"
|
||||
},
|
||||
{
|
||||
"description": "a float is not an array",
|
||||
"data": 1.1,
|
||||
"valid": false,
|
||||
"schema_id": "type_4_0"
|
||||
},
|
||||
{
|
||||
"description": "a string is not an array",
|
||||
"data": "foo",
|
||||
"valid": false,
|
||||
"schema_id": "type_4_0"
|
||||
},
|
||||
{
|
||||
"description": "an object is not an array",
|
||||
"data": {},
|
||||
"valid": false,
|
||||
"schema_id": "type_4_0"
|
||||
},
|
||||
{
|
||||
"description": "an array is an array",
|
||||
"data": [],
|
||||
"valid": true,
|
||||
"schema_id": "type_4_0"
|
||||
},
|
||||
{
|
||||
"description": "a boolean is not an array",
|
||||
"data": true,
|
||||
"valid": false,
|
||||
"schema_id": "type_4_0"
|
||||
},
|
||||
{
|
||||
"description": "null is not an array",
|
||||
"data": null,
|
||||
"valid": false,
|
||||
"schema_id": "type_4_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "boolean type matches booleans",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"type": "boolean",
|
||||
"$id": "type_5_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "an integer is not a boolean",
|
||||
"data": 1,
|
||||
"valid": false,
|
||||
"schema_id": "type_5_0"
|
||||
},
|
||||
{
|
||||
"description": "zero is not a boolean",
|
||||
"data": 0,
|
||||
"valid": false,
|
||||
"schema_id": "type_5_0"
|
||||
},
|
||||
{
|
||||
"description": "a float is not a boolean",
|
||||
"data": 1.1,
|
||||
"valid": false,
|
||||
"schema_id": "type_5_0"
|
||||
},
|
||||
{
|
||||
"description": "a string is not a boolean",
|
||||
"data": "foo",
|
||||
"valid": false,
|
||||
"schema_id": "type_5_0"
|
||||
},
|
||||
{
|
||||
"description": "an empty string is a null",
|
||||
"data": "",
|
||||
"valid": true,
|
||||
"schema_id": "type_5_0"
|
||||
},
|
||||
{
|
||||
"description": "an object is not a boolean",
|
||||
"data": {},
|
||||
"valid": false,
|
||||
"schema_id": "type_5_0"
|
||||
},
|
||||
{
|
||||
"description": "an array is not a boolean",
|
||||
"data": [],
|
||||
"valid": false,
|
||||
"schema_id": "type_5_0"
|
||||
},
|
||||
{
|
||||
"description": "true is a boolean",
|
||||
"data": true,
|
||||
"valid": true,
|
||||
"schema_id": "type_5_0"
|
||||
},
|
||||
{
|
||||
"description": "false is a boolean",
|
||||
"data": false,
|
||||
"valid": true,
|
||||
"schema_id": "type_5_0"
|
||||
},
|
||||
{
|
||||
"description": "null is not a boolean",
|
||||
"data": null,
|
||||
"valid": false,
|
||||
"schema_id": "type_5_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "null type matches only the null object",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"type": "null",
|
||||
"$id": "type_6_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "an integer is not null",
|
||||
"data": 1,
|
||||
"valid": false,
|
||||
"schema_id": "type_6_0"
|
||||
},
|
||||
{
|
||||
"description": "a float is not null",
|
||||
"data": 1.1,
|
||||
"valid": false,
|
||||
"schema_id": "type_6_0"
|
||||
},
|
||||
{
|
||||
"description": "zero is not null",
|
||||
"data": 0,
|
||||
"valid": false,
|
||||
"schema_id": "type_6_0"
|
||||
},
|
||||
{
|
||||
"description": "a string is not null",
|
||||
"data": "foo",
|
||||
"valid": false,
|
||||
"schema_id": "type_6_0"
|
||||
},
|
||||
{
|
||||
"description": "an empty string is null",
|
||||
"data": "",
|
||||
"valid": true,
|
||||
"schema_id": "type_6_0"
|
||||
},
|
||||
{
|
||||
"description": "an object is not null",
|
||||
"data": {},
|
||||
"valid": false,
|
||||
"schema_id": "type_6_0"
|
||||
},
|
||||
{
|
||||
"description": "an array is not null",
|
||||
"data": [],
|
||||
"valid": false,
|
||||
"schema_id": "type_6_0"
|
||||
},
|
||||
{
|
||||
"description": "true is not null",
|
||||
"data": true,
|
||||
"valid": false,
|
||||
"schema_id": "type_6_0"
|
||||
},
|
||||
{
|
||||
"description": "false is not null",
|
||||
"data": false,
|
||||
"valid": false,
|
||||
"schema_id": "type_6_0"
|
||||
},
|
||||
{
|
||||
"description": "null is null",
|
||||
"data": null,
|
||||
"valid": true,
|
||||
"schema_id": "type_6_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "multiple types can be specified in an array",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"type": [
|
||||
"integer",
|
||||
"string"
|
||||
],
|
||||
"$id": "type_7_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "an integer is valid",
|
||||
"data": 1,
|
||||
"valid": true,
|
||||
"schema_id": "type_7_0"
|
||||
},
|
||||
{
|
||||
"description": "a string is valid",
|
||||
"data": "foo",
|
||||
"valid": true,
|
||||
"schema_id": "type_7_0"
|
||||
},
|
||||
{
|
||||
"description": "a float is invalid",
|
||||
"data": 1.1,
|
||||
"valid": false,
|
||||
"schema_id": "type_7_0"
|
||||
},
|
||||
{
|
||||
"description": "an object is invalid",
|
||||
"data": {},
|
||||
"valid": false,
|
||||
"schema_id": "type_7_0"
|
||||
},
|
||||
{
|
||||
"description": "an array is invalid",
|
||||
"data": [],
|
||||
"valid": false,
|
||||
"schema_id": "type_7_0"
|
||||
},
|
||||
{
|
||||
"description": "a boolean is invalid",
|
||||
"data": true,
|
||||
"valid": false,
|
||||
"schema_id": "type_7_0"
|
||||
},
|
||||
{
|
||||
"description": "null is invalid",
|
||||
"data": null,
|
||||
"valid": false,
|
||||
"schema_id": "type_7_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "type as array with one item",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"type": [
|
||||
"string"
|
||||
],
|
||||
"$id": "type_8_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "string is valid",
|
||||
"data": "foo",
|
||||
"valid": true,
|
||||
"schema_id": "type_8_0"
|
||||
},
|
||||
{
|
||||
"description": "number is invalid",
|
||||
"data": 123,
|
||||
"valid": false,
|
||||
"schema_id": "type_8_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "type: array or object",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"type": [
|
||||
"array",
|
||||
"object"
|
||||
],
|
||||
"items": {},
|
||||
"$id": "type_9_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "array is valid",
|
||||
"data": [
|
||||
1,
|
||||
2,
|
||||
3
|
||||
],
|
||||
"valid": true,
|
||||
"schema_id": "type_9_0"
|
||||
},
|
||||
{
|
||||
"description": "object is valid",
|
||||
"data": {},
|
||||
"valid": true,
|
||||
"schema_id": "type_9_0"
|
||||
},
|
||||
{
|
||||
"description": "number is invalid",
|
||||
"data": 123,
|
||||
"valid": false,
|
||||
"schema_id": "type_9_0"
|
||||
},
|
||||
{
|
||||
"description": "string is invalid",
|
||||
"data": "foo",
|
||||
"valid": false,
|
||||
"schema_id": "type_9_0"
|
||||
},
|
||||
{
|
||||
"description": "null is invalid",
|
||||
"data": null,
|
||||
"valid": false,
|
||||
"schema_id": "type_9_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "type: array, object or null",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"type": [
|
||||
"array",
|
||||
"object",
|
||||
"null"
|
||||
],
|
||||
"items": {},
|
||||
"$id": "type_10_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "array is valid",
|
||||
"data": [
|
||||
1,
|
||||
2,
|
||||
3
|
||||
],
|
||||
"valid": true,
|
||||
"schema_id": "type_10_0"
|
||||
},
|
||||
{
|
||||
"description": "object is valid",
|
||||
"data": {},
|
||||
"valid": true,
|
||||
"schema_id": "type_10_0"
|
||||
},
|
||||
{
|
||||
"description": "null is valid",
|
||||
"data": null,
|
||||
"valid": true,
|
||||
"schema_id": "type_10_0"
|
||||
},
|
||||
{
|
||||
"description": "number is invalid",
|
||||
"data": 123,
|
||||
"valid": false,
|
||||
"schema_id": "type_10_0"
|
||||
},
|
||||
{
|
||||
"description": "string is invalid",
|
||||
"data": "foo",
|
||||
"valid": false,
|
||||
"schema_id": "type_10_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "extensible: true allows extra properties",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"type": "object",
|
||||
"extensible": true,
|
||||
"$id": "type_11_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "extra property is valid",
|
||||
"data": {
|
||||
"foo": 1
|
||||
},
|
||||
"valid": true,
|
||||
"schema_id": "type_11_0"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
958
tests/fixtures/uniqueItems.json
vendored
Normal file
958
tests/fixtures/uniqueItems.json
vendored
Normal file
@ -0,0 +1,958 @@
|
||||
[
|
||||
{
|
||||
"description": "uniqueItems validation",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"uniqueItems": true,
|
||||
"extensible": true,
|
||||
"$id": "uniqueItems_0_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "unique array of integers is valid",
|
||||
"data": [
|
||||
1,
|
||||
2
|
||||
],
|
||||
"valid": true,
|
||||
"schema_id": "uniqueItems_0_0"
|
||||
},
|
||||
{
|
||||
"description": "non-unique array of integers is invalid",
|
||||
"data": [
|
||||
1,
|
||||
1
|
||||
],
|
||||
"valid": false,
|
||||
"schema_id": "uniqueItems_0_0"
|
||||
},
|
||||
{
|
||||
"description": "non-unique array of more than two integers is invalid",
|
||||
"data": [
|
||||
1,
|
||||
2,
|
||||
1
|
||||
],
|
||||
"valid": false,
|
||||
"schema_id": "uniqueItems_0_0"
|
||||
},
|
||||
{
|
||||
"description": "numbers are unique if mathematically unequal",
|
||||
"data": [
|
||||
1,
|
||||
1,
|
||||
1
|
||||
],
|
||||
"valid": false,
|
||||
"schema_id": "uniqueItems_0_0"
|
||||
},
|
||||
{
|
||||
"description": "false is not equal to zero",
|
||||
"data": [
|
||||
0,
|
||||
false
|
||||
],
|
||||
"valid": true,
|
||||
"schema_id": "uniqueItems_0_0"
|
||||
},
|
||||
{
|
||||
"description": "true is not equal to one",
|
||||
"data": [
|
||||
1,
|
||||
true
|
||||
],
|
||||
"valid": true,
|
||||
"schema_id": "uniqueItems_0_0"
|
||||
},
|
||||
{
|
||||
"description": "unique array of strings is valid",
|
||||
"data": [
|
||||
"foo",
|
||||
"bar",
|
||||
"baz"
|
||||
],
|
||||
"valid": true,
|
||||
"schema_id": "uniqueItems_0_0"
|
||||
},
|
||||
{
|
||||
"description": "non-unique array of strings is invalid",
|
||||
"data": [
|
||||
"foo",
|
||||
"bar",
|
||||
"foo"
|
||||
],
|
||||
"valid": false,
|
||||
"schema_id": "uniqueItems_0_0"
|
||||
},
|
||||
{
|
||||
"description": "unique array of objects is valid",
|
||||
"data": [
|
||||
{
|
||||
"foo": "bar"
|
||||
},
|
||||
{
|
||||
"foo": "baz"
|
||||
}
|
||||
],
|
||||
"valid": true,
|
||||
"schema_id": "uniqueItems_0_0"
|
||||
},
|
||||
{
|
||||
"description": "non-unique array of objects is invalid",
|
||||
"data": [
|
||||
{
|
||||
"foo": "bar"
|
||||
},
|
||||
{
|
||||
"foo": "bar"
|
||||
}
|
||||
],
|
||||
"valid": false,
|
||||
"schema_id": "uniqueItems_0_0"
|
||||
},
|
||||
{
|
||||
"description": "property order of array of objects is ignored",
|
||||
"data": [
|
||||
{
|
||||
"foo": "bar",
|
||||
"bar": "foo"
|
||||
},
|
||||
{
|
||||
"bar": "foo",
|
||||
"foo": "bar"
|
||||
}
|
||||
],
|
||||
"valid": false,
|
||||
"schema_id": "uniqueItems_0_0"
|
||||
},
|
||||
{
|
||||
"description": "unique array of nested objects is valid",
|
||||
"data": [
|
||||
{
|
||||
"foo": {
|
||||
"bar": {
|
||||
"baz": true
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"foo": {
|
||||
"bar": {
|
||||
"baz": false
|
||||
}
|
||||
}
|
||||
}
|
||||
],
|
||||
"valid": true,
|
||||
"schema_id": "uniqueItems_0_0"
|
||||
},
|
||||
{
|
||||
"description": "non-unique array of nested objects is invalid",
|
||||
"data": [
|
||||
{
|
||||
"foo": {
|
||||
"bar": {
|
||||
"baz": true
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"foo": {
|
||||
"bar": {
|
||||
"baz": true
|
||||
}
|
||||
}
|
||||
}
|
||||
],
|
||||
"valid": false,
|
||||
"schema_id": "uniqueItems_0_0"
|
||||
},
|
||||
{
|
||||
"description": "unique array of arrays is valid",
|
||||
"data": [
|
||||
[
|
||||
"foo"
|
||||
],
|
||||
[
|
||||
"bar"
|
||||
]
|
||||
],
|
||||
"valid": true,
|
||||
"schema_id": "uniqueItems_0_0"
|
||||
},
|
||||
{
|
||||
"description": "non-unique array of arrays is invalid",
|
||||
"data": [
|
||||
[
|
||||
"foo"
|
||||
],
|
||||
[
|
||||
"foo"
|
||||
]
|
||||
],
|
||||
"valid": false,
|
||||
"schema_id": "uniqueItems_0_0"
|
||||
},
|
||||
{
|
||||
"description": "non-unique array of more than two arrays is invalid",
|
||||
"data": [
|
||||
[
|
||||
"foo"
|
||||
],
|
||||
[
|
||||
"bar"
|
||||
],
|
||||
[
|
||||
"foo"
|
||||
]
|
||||
],
|
||||
"valid": false,
|
||||
"schema_id": "uniqueItems_0_0"
|
||||
},
|
||||
{
|
||||
"description": "1 and true are unique",
|
||||
"data": [
|
||||
1,
|
||||
true
|
||||
],
|
||||
"valid": true,
|
||||
"schema_id": "uniqueItems_0_0"
|
||||
},
|
||||
{
|
||||
"description": "0 and false are unique",
|
||||
"data": [
|
||||
0,
|
||||
false
|
||||
],
|
||||
"valid": true,
|
||||
"schema_id": "uniqueItems_0_0"
|
||||
},
|
||||
{
|
||||
"description": "[1] and [true] are unique",
|
||||
"data": [
|
||||
[
|
||||
1
|
||||
],
|
||||
[
|
||||
true
|
||||
]
|
||||
],
|
||||
"valid": true,
|
||||
"schema_id": "uniqueItems_0_0"
|
||||
},
|
||||
{
|
||||
"description": "[0] and [false] are unique",
|
||||
"data": [
|
||||
[
|
||||
0
|
||||
],
|
||||
[
|
||||
false
|
||||
]
|
||||
],
|
||||
"valid": true,
|
||||
"schema_id": "uniqueItems_0_0"
|
||||
},
|
||||
{
|
||||
"description": "nested [1] and [true] are unique",
|
||||
"data": [
|
||||
[
|
||||
[
|
||||
1
|
||||
],
|
||||
"foo"
|
||||
],
|
||||
[
|
||||
[
|
||||
true
|
||||
],
|
||||
"foo"
|
||||
]
|
||||
],
|
||||
"valid": true,
|
||||
"schema_id": "uniqueItems_0_0"
|
||||
},
|
||||
{
|
||||
"description": "nested [0] and [false] are unique",
|
||||
"data": [
|
||||
[
|
||||
[
|
||||
0
|
||||
],
|
||||
"foo"
|
||||
],
|
||||
[
|
||||
[
|
||||
false
|
||||
],
|
||||
"foo"
|
||||
]
|
||||
],
|
||||
"valid": true,
|
||||
"schema_id": "uniqueItems_0_0"
|
||||
},
|
||||
{
|
||||
"description": "unique heterogeneous types are valid",
|
||||
"data": [
|
||||
{},
|
||||
[
|
||||
1
|
||||
],
|
||||
true,
|
||||
null,
|
||||
1,
|
||||
"{}"
|
||||
],
|
||||
"valid": true,
|
||||
"schema_id": "uniqueItems_0_0"
|
||||
},
|
||||
{
|
||||
"description": "non-unique heterogeneous types are invalid",
|
||||
"data": [
|
||||
{},
|
||||
[
|
||||
1
|
||||
],
|
||||
true,
|
||||
null,
|
||||
{},
|
||||
1
|
||||
],
|
||||
"valid": false,
|
||||
"schema_id": "uniqueItems_0_0"
|
||||
},
|
||||
{
|
||||
"description": "different objects are unique",
|
||||
"data": [
|
||||
{
|
||||
"a": 1,
|
||||
"b": 2
|
||||
},
|
||||
{
|
||||
"a": 2,
|
||||
"b": 1
|
||||
}
|
||||
],
|
||||
"valid": true,
|
||||
"schema_id": "uniqueItems_0_0"
|
||||
},
|
||||
{
|
||||
"description": "objects are non-unique despite key order",
|
||||
"data": [
|
||||
{
|
||||
"a": 1,
|
||||
"b": 2
|
||||
},
|
||||
{
|
||||
"b": 2,
|
||||
"a": 1
|
||||
}
|
||||
],
|
||||
"valid": false,
|
||||
"schema_id": "uniqueItems_0_0"
|
||||
},
|
||||
{
|
||||
"description": "{\"a\": false} and {\"a\": 0} are unique",
|
||||
"data": [
|
||||
{
|
||||
"a": false
|
||||
},
|
||||
{
|
||||
"a": 0
|
||||
}
|
||||
],
|
||||
"valid": true,
|
||||
"schema_id": "uniqueItems_0_0"
|
||||
},
|
||||
{
|
||||
"description": "{\"a\": true} and {\"a\": 1} are unique",
|
||||
"data": [
|
||||
{
|
||||
"a": true
|
||||
},
|
||||
{
|
||||
"a": 1
|
||||
}
|
||||
],
|
||||
"valid": true,
|
||||
"schema_id": "uniqueItems_0_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "uniqueItems with an array of items",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"prefixItems": [
|
||||
{
|
||||
"type": "boolean"
|
||||
},
|
||||
{
|
||||
"type": "boolean"
|
||||
}
|
||||
],
|
||||
"uniqueItems": true,
|
||||
"extensible": true,
|
||||
"$id": "uniqueItems_1_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "[false, true] from items array is valid",
|
||||
"data": [
|
||||
false,
|
||||
true
|
||||
],
|
||||
"valid": true,
|
||||
"schema_id": "uniqueItems_1_0"
|
||||
},
|
||||
{
|
||||
"description": "[true, false] from items array is valid",
|
||||
"data": [
|
||||
true,
|
||||
false
|
||||
],
|
||||
"valid": true,
|
||||
"schema_id": "uniqueItems_1_0"
|
||||
},
|
||||
{
|
||||
"description": "[false, false] from items array is not valid",
|
||||
"data": [
|
||||
false,
|
||||
false
|
||||
],
|
||||
"valid": false,
|
||||
"schema_id": "uniqueItems_1_0"
|
||||
},
|
||||
{
|
||||
"description": "[true, true] from items array is not valid",
|
||||
"data": [
|
||||
true,
|
||||
true
|
||||
],
|
||||
"valid": false,
|
||||
"schema_id": "uniqueItems_1_0"
|
||||
},
|
||||
{
|
||||
"description": "unique array extended from [false, true] is valid",
|
||||
"data": [
|
||||
false,
|
||||
true,
|
||||
"foo",
|
||||
"bar"
|
||||
],
|
||||
"valid": true,
|
||||
"schema_id": "uniqueItems_1_0"
|
||||
},
|
||||
{
|
||||
"description": "unique array extended from [true, false] is valid",
|
||||
"data": [
|
||||
true,
|
||||
false,
|
||||
"foo",
|
||||
"bar"
|
||||
],
|
||||
"valid": true,
|
||||
"schema_id": "uniqueItems_1_0"
|
||||
},
|
||||
{
|
||||
"description": "non-unique array extended from [false, true] is not valid",
|
||||
"data": [
|
||||
false,
|
||||
true,
|
||||
"foo",
|
||||
"foo"
|
||||
],
|
||||
"valid": false,
|
||||
"schema_id": "uniqueItems_1_0"
|
||||
},
|
||||
{
|
||||
"description": "non-unique array extended from [true, false] is not valid",
|
||||
"data": [
|
||||
true,
|
||||
false,
|
||||
"foo",
|
||||
"foo"
|
||||
],
|
||||
"valid": false,
|
||||
"schema_id": "uniqueItems_1_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "uniqueItems with an array of items and additionalItems=false",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"prefixItems": [
|
||||
{
|
||||
"type": "boolean"
|
||||
},
|
||||
{
|
||||
"type": "boolean"
|
||||
}
|
||||
],
|
||||
"uniqueItems": true,
|
||||
"items": false,
|
||||
"$id": "uniqueItems_2_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "[false, true] from items array is valid",
|
||||
"data": [
|
||||
false,
|
||||
true
|
||||
],
|
||||
"valid": true,
|
||||
"schema_id": "uniqueItems_2_0"
|
||||
},
|
||||
{
|
||||
"description": "[true, false] from items array is valid",
|
||||
"data": [
|
||||
true,
|
||||
false
|
||||
],
|
||||
"valid": true,
|
||||
"schema_id": "uniqueItems_2_0"
|
||||
},
|
||||
{
|
||||
"description": "[false, false] from items array is not valid",
|
||||
"data": [
|
||||
false,
|
||||
false
|
||||
],
|
||||
"valid": false,
|
||||
"schema_id": "uniqueItems_2_0"
|
||||
},
|
||||
{
|
||||
"description": "[true, true] from items array is not valid",
|
||||
"data": [
|
||||
true,
|
||||
true
|
||||
],
|
||||
"valid": false,
|
||||
"schema_id": "uniqueItems_2_0"
|
||||
},
|
||||
{
|
||||
"description": "extra items are invalid even if unique",
|
||||
"data": [
|
||||
false,
|
||||
true,
|
||||
null
|
||||
],
|
||||
"valid": false,
|
||||
"schema_id": "uniqueItems_2_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "uniqueItems=false validation",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"uniqueItems": false,
|
||||
"extensible": true,
|
||||
"$id": "uniqueItems_3_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "unique array of integers is valid",
|
||||
"data": [
|
||||
1,
|
||||
2
|
||||
],
|
||||
"valid": true,
|
||||
"schema_id": "uniqueItems_3_0"
|
||||
},
|
||||
{
|
||||
"description": "non-unique array of integers is valid",
|
||||
"data": [
|
||||
1,
|
||||
1
|
||||
],
|
||||
"valid": true,
|
||||
"schema_id": "uniqueItems_3_0"
|
||||
},
|
||||
{
|
||||
"description": "numbers are unique if mathematically unequal",
|
||||
"data": [
|
||||
1,
|
||||
1,
|
||||
1
|
||||
],
|
||||
"valid": true,
|
||||
"schema_id": "uniqueItems_3_0"
|
||||
},
|
||||
{
|
||||
"description": "false is not equal to zero",
|
||||
"data": [
|
||||
0,
|
||||
false
|
||||
],
|
||||
"valid": true,
|
||||
"schema_id": "uniqueItems_3_0"
|
||||
},
|
||||
{
|
||||
"description": "true is not equal to one",
|
||||
"data": [
|
||||
1,
|
||||
true
|
||||
],
|
||||
"valid": true,
|
||||
"schema_id": "uniqueItems_3_0"
|
||||
},
|
||||
{
|
||||
"description": "unique array of objects is valid",
|
||||
"data": [
|
||||
{
|
||||
"foo": "bar"
|
||||
},
|
||||
{
|
||||
"foo": "baz"
|
||||
}
|
||||
],
|
||||
"valid": true,
|
||||
"schema_id": "uniqueItems_3_0"
|
||||
},
|
||||
{
|
||||
"description": "non-unique array of objects is valid",
|
||||
"data": [
|
||||
{
|
||||
"foo": "bar"
|
||||
},
|
||||
{
|
||||
"foo": "bar"
|
||||
}
|
||||
],
|
||||
"valid": true,
|
||||
"schema_id": "uniqueItems_3_0"
|
||||
},
|
||||
{
|
||||
"description": "unique array of nested objects is valid",
|
||||
"data": [
|
||||
{
|
||||
"foo": {
|
||||
"bar": {
|
||||
"baz": true
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"foo": {
|
||||
"bar": {
|
||||
"baz": false
|
||||
}
|
||||
}
|
||||
}
|
||||
],
|
||||
"valid": true,
|
||||
"schema_id": "uniqueItems_3_0"
|
||||
},
|
||||
{
|
||||
"description": "non-unique array of nested objects is valid",
|
||||
"data": [
|
||||
{
|
||||
"foo": {
|
||||
"bar": {
|
||||
"baz": true
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"foo": {
|
||||
"bar": {
|
||||
"baz": true
|
||||
}
|
||||
}
|
||||
}
|
||||
],
|
||||
"valid": true,
|
||||
"schema_id": "uniqueItems_3_0"
|
||||
},
|
||||
{
|
||||
"description": "unique array of arrays is valid",
|
||||
"data": [
|
||||
[
|
||||
"foo"
|
||||
],
|
||||
[
|
||||
"bar"
|
||||
]
|
||||
],
|
||||
"valid": true,
|
||||
"schema_id": "uniqueItems_3_0"
|
||||
},
|
||||
{
|
||||
"description": "non-unique array of arrays is valid",
|
||||
"data": [
|
||||
[
|
||||
"foo"
|
||||
],
|
||||
[
|
||||
"foo"
|
||||
]
|
||||
],
|
||||
"valid": true,
|
||||
"schema_id": "uniqueItems_3_0"
|
||||
},
|
||||
{
|
||||
"description": "1 and true are unique",
|
||||
"data": [
|
||||
1,
|
||||
true
|
||||
],
|
||||
"valid": true,
|
||||
"schema_id": "uniqueItems_3_0"
|
||||
},
|
||||
{
|
||||
"description": "0 and false are unique",
|
||||
"data": [
|
||||
0,
|
||||
false
|
||||
],
|
||||
"valid": true,
|
||||
"schema_id": "uniqueItems_3_0"
|
||||
},
|
||||
{
|
||||
"description": "unique heterogeneous types are valid",
|
||||
"data": [
|
||||
{},
|
||||
[
|
||||
1
|
||||
],
|
||||
true,
|
||||
null,
|
||||
1
|
||||
],
|
||||
"valid": true,
|
||||
"schema_id": "uniqueItems_3_0"
|
||||
},
|
||||
{
|
||||
"description": "non-unique heterogeneous types are valid",
|
||||
"data": [
|
||||
{},
|
||||
[
|
||||
1
|
||||
],
|
||||
true,
|
||||
null,
|
||||
{},
|
||||
1
|
||||
],
|
||||
"valid": true,
|
||||
"schema_id": "uniqueItems_3_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "uniqueItems=false with an array of items",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"prefixItems": [
|
||||
{
|
||||
"type": "boolean"
|
||||
},
|
||||
{
|
||||
"type": "boolean"
|
||||
}
|
||||
],
|
||||
"uniqueItems": false,
|
||||
"extensible": true,
|
||||
"$id": "uniqueItems_4_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "[false, true] from items array is valid",
|
||||
"data": [
|
||||
false,
|
||||
true
|
||||
],
|
||||
"valid": true,
|
||||
"schema_id": "uniqueItems_4_0"
|
||||
},
|
||||
{
|
||||
"description": "[true, false] from items array is valid",
|
||||
"data": [
|
||||
true,
|
||||
false
|
||||
],
|
||||
"valid": true,
|
||||
"schema_id": "uniqueItems_4_0"
|
||||
},
|
||||
{
|
||||
"description": "[false, false] from items array is valid",
|
||||
"data": [
|
||||
false,
|
||||
false
|
||||
],
|
||||
"valid": true,
|
||||
"schema_id": "uniqueItems_4_0"
|
||||
},
|
||||
{
|
||||
"description": "[true, true] from items array is valid",
|
||||
"data": [
|
||||
true,
|
||||
true
|
||||
],
|
||||
"valid": true,
|
||||
"schema_id": "uniqueItems_4_0"
|
||||
},
|
||||
{
|
||||
"description": "unique array extended from [false, true] is valid",
|
||||
"data": [
|
||||
false,
|
||||
true,
|
||||
"foo",
|
||||
"bar"
|
||||
],
|
||||
"valid": true,
|
||||
"schema_id": "uniqueItems_4_0"
|
||||
},
|
||||
{
|
||||
"description": "unique array extended from [true, false] is valid",
|
||||
"data": [
|
||||
true,
|
||||
false,
|
||||
"foo",
|
||||
"bar"
|
||||
],
|
||||
"valid": true,
|
||||
"schema_id": "uniqueItems_4_0"
|
||||
},
|
||||
{
|
||||
"description": "non-unique array extended from [false, true] is valid",
|
||||
"data": [
|
||||
false,
|
||||
true,
|
||||
"foo",
|
||||
"foo"
|
||||
],
|
||||
"valid": true,
|
||||
"schema_id": "uniqueItems_4_0"
|
||||
},
|
||||
{
|
||||
"description": "non-unique array extended from [true, false] is valid",
|
||||
"data": [
|
||||
true,
|
||||
false,
|
||||
"foo",
|
||||
"foo"
|
||||
],
|
||||
"valid": true,
|
||||
"schema_id": "uniqueItems_4_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "uniqueItems=false with an array of items and additionalItems=false",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"prefixItems": [
|
||||
{
|
||||
"type": "boolean"
|
||||
},
|
||||
{
|
||||
"type": "boolean"
|
||||
}
|
||||
],
|
||||
"uniqueItems": false,
|
||||
"items": false,
|
||||
"$id": "uniqueItems_5_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "[false, true] from items array is valid",
|
||||
"data": [
|
||||
false,
|
||||
true
|
||||
],
|
||||
"valid": true,
|
||||
"schema_id": "uniqueItems_5_0"
|
||||
},
|
||||
{
|
||||
"description": "[true, false] from items array is valid",
|
||||
"data": [
|
||||
true,
|
||||
false
|
||||
],
|
||||
"valid": true,
|
||||
"schema_id": "uniqueItems_5_0"
|
||||
},
|
||||
{
|
||||
"description": "[false, false] from items array is valid",
|
||||
"data": [
|
||||
false,
|
||||
false
|
||||
],
|
||||
"valid": true,
|
||||
"schema_id": "uniqueItems_5_0"
|
||||
},
|
||||
{
|
||||
"description": "[true, true] from items array is valid",
|
||||
"data": [
|
||||
true,
|
||||
true
|
||||
],
|
||||
"valid": true,
|
||||
"schema_id": "uniqueItems_5_0"
|
||||
},
|
||||
{
|
||||
"description": "extra items are invalid even if unique",
|
||||
"data": [
|
||||
false,
|
||||
true,
|
||||
null
|
||||
],
|
||||
"valid": false,
|
||||
"schema_id": "uniqueItems_5_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "extensible: true allows extra items in uniqueItems",
|
||||
"database": {
|
||||
"schemas": [
|
||||
{
|
||||
"uniqueItems": true,
|
||||
"extensible": true,
|
||||
"$id": "uniqueItems_6_0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"tests": [
|
||||
{
|
||||
"description": "extra items must be unique",
|
||||
"data": [
|
||||
1,
|
||||
1
|
||||
],
|
||||
"valid": false,
|
||||
"schema_id": "uniqueItems_6_0"
|
||||
},
|
||||
{
|
||||
"description": "extra unique items valid",
|
||||
"data": [
|
||||
1,
|
||||
2
|
||||
],
|
||||
"valid": true,
|
||||
"schema_id": "uniqueItems_6_0"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
91
tests/lib.rs
Normal file
91
tests/lib.rs
Normal file
@ -0,0 +1,91 @@
|
||||
use ::jspg::*;
|
||||
use pgrx::JsonB;
|
||||
use serde_json::json;
|
||||
|
||||
pub mod database;
|
||||
|
||||
#[test]
|
||||
fn test_library_api() {
|
||||
// 1. Initially, schemas are not cached.
|
||||
|
||||
// Expected uninitialized drop format: errors + null response
|
||||
let uninitialized_drop = jspg_validate("test_schema", JsonB(json!({})));
|
||||
assert_eq!(
|
||||
uninitialized_drop.0,
|
||||
json!({
|
||||
"type": "drop",
|
||||
"errors": [{
|
||||
"code": "VALIDATOR_NOT_INITIALIZED",
|
||||
"message": "The JSPG database has not been cached yet. Run jspg_setup()",
|
||||
"details": { "path": "" }
|
||||
}]
|
||||
})
|
||||
);
|
||||
|
||||
// 2. Cache schemas
|
||||
let db_json = json!({
|
||||
"puncs": [],
|
||||
"enums": [],
|
||||
"relations": [],
|
||||
"types": [{
|
||||
"schemas": [{
|
||||
"$id": "test_schema",
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"name": { "type": "string" }
|
||||
},
|
||||
"required": ["name"]
|
||||
}]
|
||||
}]
|
||||
});
|
||||
|
||||
let cache_drop = jspg_setup(JsonB(db_json));
|
||||
assert_eq!(
|
||||
cache_drop.0,
|
||||
json!({
|
||||
"type": "drop",
|
||||
"response": "success"
|
||||
})
|
||||
);
|
||||
|
||||
// 4. Validate Happy Path
|
||||
let happy_drop = jspg_validate("test_schema", JsonB(json!({"name": "Neo"})));
|
||||
assert_eq!(
|
||||
happy_drop.0,
|
||||
json!({
|
||||
"type": "drop",
|
||||
"response": "success"
|
||||
})
|
||||
);
|
||||
|
||||
// 5. Validate Unhappy Path
|
||||
let unhappy_drop = jspg_validate("test_schema", JsonB(json!({"wrong": "data"})));
|
||||
assert_eq!(
|
||||
unhappy_drop.0,
|
||||
json!({
|
||||
"type": "drop",
|
||||
"errors": [
|
||||
{
|
||||
"code": "REQUIRED_FIELD_MISSING",
|
||||
"message": "Missing name",
|
||||
"details": { "path": "/name" }
|
||||
},
|
||||
{
|
||||
"code": "STRICT_PROPERTY_VIOLATION",
|
||||
"message": "Unexpected property 'wrong'",
|
||||
"details": { "path": "/wrong" }
|
||||
}
|
||||
]
|
||||
})
|
||||
);
|
||||
|
||||
// 6. Clear Schemas
|
||||
let clear_drop = jspg_teardown();
|
||||
assert_eq!(
|
||||
clear_drop.0,
|
||||
json!({
|
||||
"type": "drop",
|
||||
"response": "success"
|
||||
})
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user