use serde_json::{json, Map, Value};
const ENVELOPE_VERSION: u64 = 2;
use crate::diagnostics::{
RenderedBlockMatcher, RenderedContentMatcher, RenderedContentOwner, RenderedContentRulePath,
RenderedDiagnostic, RenderedListAddress, RenderedMatcher, RenderedPosition, RenderedReference,
RenderedScalar, RenderedSchemaNode, RenderedTarget, ResultKind, ValidationResult,
};
pub(super) fn render_json(results: &[ValidationResult]) -> String {
let diagnostic_count = results
.iter()
.map(|result| result.diagnostics.len())
.sum::<usize>();
let results = results
.iter()
.map(|result| {
json!({
"kind": match result.kind {
ResultKind::Document => "document",
ResultKind::Schema => "schema",
},
"path": result.path,
"schema": result.schema,
"diagnostics": result.diagnostics.iter().map(diagnostic_json).collect::<Vec<_>>()
})
})
.collect::<Vec<_>>();
let document_count = results
.iter()
.filter(|result| result["kind"] == "document")
.count();
let schema_count = results.len() - document_count;
let envelope = json!({
"version": ENVELOPE_VERSION,
"results": results,
"summary": {
"files": results.len(),
"documents": document_count,
"schemas": schema_count,
"diagnostics": diagnostic_count
}
});
let mut output = Vec::new();
write_json_value(&envelope, JsonContext::Default, &mut output);
output.push(b'\n');
String::from_utf8(output).expect("JSON serialization emits UTF-8")
}
#[derive(Clone, Copy)]
enum JsonContext {
Default,
BlockTarget,
MissingBlockTarget,
ItemTarget,
MissingItemTarget,
ContentRuleNode,
ItemRuleNode,
ListAddress,
ContentMatcher,
BlockMatcher,
ContentOwner,
ContentRulePath,
}
fn write_json_value(value: &Value, context: JsonContext, output: &mut Vec<u8>) {
match value {
Value::Null => output.extend_from_slice(b"null"),
Value::Bool(value) => output.extend_from_slice(if *value { b"true" } else { b"false" }),
Value::Number(value) => serde_json::to_writer(output, value)
.expect("writing a JSON number to a byte buffer is infallible"),
Value::String(value) => serde_json::to_writer(output, value)
.expect("writing a JSON string to a byte buffer is infallible"),
Value::Array(values) => {
output.push(b'[');
for (index, value) in values.iter().enumerate() {
if index != 0 {
output.push(b',');
}
let child_context = if matches!(context, JsonContext::ContentMatcher) {
JsonContext::BlockMatcher
} else {
JsonContext::Default
};
write_json_value(value, child_context, output);
}
output.push(b']');
}
Value::Object(object) => write_json_object(object, context, output),
}
}
fn write_json_object(object: &Map<String, Value>, context: JsonContext, output: &mut Vec<u8>) {
let context = match context {
JsonContext::Default => match object.get("kind").and_then(Value::as_str) {
Some("block") => JsonContext::BlockTarget,
Some("missing_block") => JsonContext::MissingBlockTarget,
Some("item") => JsonContext::ItemTarget,
Some("missing_item") => JsonContext::MissingItemTarget,
Some("content_rule") => JsonContext::ContentRuleNode,
Some("item_rule") => JsonContext::ItemRuleNode,
_ => JsonContext::Default,
},
JsonContext::ContentMatcher if object.contains_key("one_of") => JsonContext::ContentMatcher,
JsonContext::ContentMatcher => JsonContext::BlockMatcher,
context => context,
};
let keys: &[&str] = match context {
JsonContext::BlockTarget => &["kind", "parent", "block", "index"],
JsonContext::MissingBlockTarget => &["kind", "parent", "matcher"],
JsonContext::ItemTarget => &["kind", "list", "index"],
JsonContext::MissingItemTarget => &["kind", "list", "matcher"],
JsonContext::ContentRuleNode => &["kind", "owner", "index"],
JsonContext::ItemRuleNode => &["kind", "content", "index"],
JsonContext::ListAddress => &["parent", "index"],
JsonContext::BlockMatcher => &["block", "list_kind"],
JsonContext::ContentOwner => &["kind", "scope", "index"],
JsonContext::ContentRulePath => &["owner", "index"],
JsonContext::ContentMatcher => &["one_of"],
JsonContext::Default => &[],
};
output.push(b'{');
let mut written = 0_usize;
if keys.is_empty() {
for (key, value) in object {
write_json_member(key, value, JsonContext::Default, &mut written, output);
}
} else {
for key in keys {
let Some(value) = object.get(*key) else {
continue;
};
let child_context = match (context, *key) {
(JsonContext::MissingBlockTarget, "matcher") => JsonContext::ContentMatcher,
(JsonContext::ItemTarget | JsonContext::MissingItemTarget, "list") => {
JsonContext::ListAddress
}
(JsonContext::ContentRuleNode, "owner") => JsonContext::ContentOwner,
(JsonContext::ItemRuleNode, "content") => JsonContext::ContentRulePath,
(JsonContext::ContentRulePath, "owner") => JsonContext::ContentOwner,
_ => JsonContext::Default,
};
write_json_member(key, value, child_context, &mut written, output);
}
}
output.push(b'}');
}
fn write_json_member(
key: &str,
value: &Value,
context: JsonContext,
written: &mut usize,
output: &mut Vec<u8>,
) {
if *written != 0 {
output.push(b',');
}
*written = (*written).saturating_add(1);
serde_json::to_writer(&mut *output, key)
.expect("writing a JSON key to a byte buffer is infallible");
output.push(b':');
write_json_value(value, context, output);
}
#[cfg(any(feature = "search", feature = "read"))]
pub(super) fn write_ordered_json_object(
output: &mut Vec<u8>,
members: impl FnOnce(&mut OrderedJsonObject<'_>),
) {
output.push(b'{');
let mut object = OrderedJsonObject { output, written: 0 };
members(&mut object);
object.output.push(b'}');
}
#[cfg(any(feature = "search", feature = "read"))]
pub(super) struct OrderedJsonObject<'a> {
output: &'a mut Vec<u8>,
written: usize,
}
#[cfg(any(feature = "search", feature = "read"))]
impl OrderedJsonObject<'_> {
pub(super) fn value(&mut self, key: &str, value: &Value) {
self.member(key, |output| {
write_json_value(value, JsonContext::Default, output)
});
}
pub(super) fn member(&mut self, key: &str, write: impl FnOnce(&mut Vec<u8>)) {
if self.written != 0 {
self.output.push(b',');
}
self.written = self.written.saturating_add(1);
serde_json::to_writer(&mut *self.output, key)
.expect("writing a JSON key to a byte buffer is infallible");
self.output.push(b':');
write(self.output);
}
}
#[cfg(any(feature = "search", feature = "read"))]
pub(super) fn write_ordered_json_array<T>(
output: &mut Vec<u8>,
values: &[T],
write: impl Fn(&mut Vec<u8>, &T),
) {
output.push(b'[');
for (index, value) in values.iter().enumerate() {
if index != 0 {
output.push(b',');
}
write(output, value);
}
output.push(b']');
}
#[cfg(any(feature = "search", feature = "read"))]
pub(super) fn finish_json_line(mut output: Vec<u8>) -> String {
output.push(b'\n');
String::from_utf8(output).expect("JSON serialization emits UTF-8")
}
fn diagnostic_json(diagnostic: &RenderedDiagnostic) -> Value {
let mut object = Map::new();
object.insert("id".into(), json!(diagnostic.id));
object.insert("message".into(), json!(diagnostic.message));
object.insert(
"location".into(),
json!({ "line": diagnostic.line, "column": diagnostic.column }),
);
if let Some(target) = &diagnostic.target {
object.insert("target".into(), target_json(target));
}
if let Some(node) = &diagnostic.schema_node {
object.insert("schema_node".into(), schema_node_json(node));
}
if let Some(location) = &diagnostic.schema_location {
object.insert(
"schema_location".into(),
json!({
"path": location.path,
"line": location.line,
"column": location.column
}),
);
}
if !diagnostic.involved_headers.is_empty() {
object.insert(
"involved_headers".into(),
Value::Array(
diagnostic
.involved_headers
.iter()
.map(|header| {
json!({
"header_path": header.header_path,
"location": { "line": header.line, "column": header.column }
})
})
.collect(),
),
);
}
if !diagnostic.references.is_empty() {
object.insert(
"references".into(),
Value::Array(diagnostic.references.iter().map(reference_json).collect()),
);
}
Value::Object(object)
}
fn target_json(target: &RenderedTarget) -> Value {
match target {
RenderedTarget::Header { path } => json!({ "kind": "header", "path": path }),
RenderedTarget::MissingHeader { parent, matcher } => {
json!({ "kind": "missing_header", "parent": parent, "matcher": matcher })
}
RenderedTarget::Document => json!({ "kind": "document" }),
RenderedTarget::Frontmatter {
line_range,
pointer,
} => {
let mut object = Map::new();
object.insert("kind".into(), json!("frontmatter"));
if let Some(range) = line_range {
object.insert(
"line_range".into(),
json!({
"start_line": range.start_line,
"end_line": range.end_line
}),
);
}
if let Some(pointer) = pointer {
object.insert("pointer".into(), json!(pointer));
}
Value::Object(object)
}
RenderedTarget::Block {
parent,
block,
index,
} => json!({ "kind": "block", "parent": parent, "block": block, "index": index }),
RenderedTarget::MissingBlock { parent, matcher } => json!({
"kind": "missing_block",
"parent": parent,
"matcher": content_matcher_json(matcher)
}),
RenderedTarget::Item { list, index } => {
json!({ "kind": "item", "list": list_address_json(list), "index": index })
}
RenderedTarget::MissingItem { list, matcher } => json!({
"kind": "missing_item",
"list": list_address_json(list),
"matcher": matcher
}),
}
}
fn list_address_json(address: &RenderedListAddress) -> Value {
json!({ "parent": address.parent, "index": address.index })
}
fn content_matcher_json(matcher: &RenderedContentMatcher) -> Value {
match matcher {
RenderedContentMatcher::Block(matcher) => block_matcher_json(matcher),
RenderedContentMatcher::OneOf(alternatives) => json!({
"one_of": alternatives.iter().map(block_matcher_json).collect::<Vec<_>>()
}),
}
}
fn block_matcher_json(matcher: &RenderedBlockMatcher) -> Value {
let mut object = Map::new();
object.insert("block".into(), json!(matcher.block));
if let Some(list_kind) = &matcher.list_kind {
object.insert("list_kind".into(), json!(list_kind));
}
Value::Object(object)
}
fn schema_node_json(node: &RenderedSchemaNode) -> Value {
match node {
RenderedSchemaNode::Title => json!({ "kind": "title" }),
RenderedSchemaNode::Frontmatter => json!({ "kind": "frontmatter" }),
RenderedSchemaNode::FrontmatterSchemaDeclaration => {
json!({ "kind": "frontmatter_schema_declaration" })
}
RenderedSchemaNode::FrontmatterSchemaDocument => {
json!({ "kind": "frontmatter_schema_document" })
}
RenderedSchemaNode::Rule { scope, index } => {
json!({ "kind": "rule", "scope": scope, "index": index })
}
RenderedSchemaNode::Guard { scope, index } => {
json!({ "kind": "guard", "scope": scope, "index": index })
}
RenderedSchemaNode::Capture { scope, index, name } => {
json!({ "kind": "capture", "scope": scope, "index": index, "name": name })
}
RenderedSchemaNode::FrontmatterCapture { name } => {
json!({ "kind": "frontmatter_capture", "name": name })
}
RenderedSchemaNode::OrderEntry {
scope,
index,
order_index,
} => json!({
"kind": "order_entry",
"scope": scope,
"index": index,
"order_index": order_index
}),
RenderedSchemaNode::Constraint { scope, index } => {
json!({ "kind": "constraint", "scope": scope, "index": index })
}
RenderedSchemaNode::ContentRule { owner, index } => json!({
"kind": "content_rule",
"owner": content_owner_json(owner),
"index": index
}),
RenderedSchemaNode::ItemRule { content, index } => json!({
"kind": "item_rule",
"content": content_rule_path_json(content),
"index": index
}),
}
}
fn content_owner_json(owner: &RenderedContentOwner) -> Value {
match owner {
RenderedContentOwner::Document => json!({ "kind": "document" }),
RenderedContentOwner::Title => json!({ "kind": "title" }),
RenderedContentOwner::Rule { scope, index } => {
json!({ "kind": "rule", "scope": scope, "index": index })
}
}
}
fn content_rule_path_json(path: &RenderedContentRulePath) -> Value {
json!({
"owner": content_owner_json(&path.owner),
"index": path.index
})
}
fn reference_json(reference: &RenderedReference) -> Value {
match reference {
RenderedReference::Rule {
locator,
anchor,
path,
positions,
matcher,
} => {
let mut object = Map::new();
object.insert("kind".into(), json!("rule"));
object.insert("locator".into(), json!(locator));
object.insert("anchor".into(), json!(anchor));
object.insert("path".into(), json!(path));
if let Some(positions) = positions {
object.insert(
"positions".into(),
Value::Array(positions.iter().map(position_json).collect()),
);
}
object.insert("matcher".into(), matcher_json(matcher));
Value::Object(object)
}
RenderedReference::FrontmatterQuery {
locator,
query,
equals,
} => {
let mut object = Map::new();
object.insert("kind".into(), json!("frontmatter_query"));
object.insert("locator".into(), json!(locator));
object.insert("query".into(), json!(query));
if let Some(equals) = equals {
object.insert("equals".into(), scalar_json(equals));
}
Value::Object(object)
}
RenderedReference::FrontmatterCapture {
locator,
name,
value_type,
} => json!({
"kind": "frontmatter_capture",
"locator": locator,
"name": name,
"type": value_type
}),
}
}
fn position_json(position: &Option<RenderedPosition>) -> Value {
match position {
Some(position) => Value::Number(position.as_number().clone()),
None => Value::Null,
}
}
fn matcher_json(matcher: &RenderedMatcher) -> Value {
match matcher {
RenderedMatcher::Exact(value) => json!({ "kind": "exact", "value": value }),
RenderedMatcher::Glob(value) => json!({ "kind": "glob", "value": value }),
RenderedMatcher::Regex(value) => json!({ "kind": "regex", "value": value }),
RenderedMatcher::Any => json!({ "kind": "any" }),
RenderedMatcher::Unknown => json!({ "kind": "unknown" }),
}
}
fn scalar_json(scalar: &RenderedScalar) -> Value {
match scalar {
RenderedScalar::Null => json!({ "type": "null", "value": null }),
RenderedScalar::Boolean(value) => json!({ "type": "boolean", "value": value }),
RenderedScalar::Integer(value) => json!({ "type": "integer", "value": value }),
RenderedScalar::Float(value) => json!({ "type": "float", "value": value }),
RenderedScalar::String(value) => json!({ "type": "string", "value": value }),
}
}
#[cfg(test)]
mod tests {
use serde_json::{json, Value};
use super::{
diagnostic_json, matcher_json, reference_json, render_json, scalar_json, schema_node_json,
target_json, write_json_value, JsonContext,
};
use crate::diagnostics::{
RenderedBlockMatcher, RenderedContentMatcher, RenderedContentOwner,
RenderedContentRulePath, RenderedDiagnostic, RenderedInvolvedHeader, RenderedLineRange,
RenderedListAddress, RenderedLocation, RenderedMatcher, RenderedPosition,
RenderedReference, RenderedScalar, RenderedSchemaNode, RenderedTarget, ResultKind,
ValidationResult,
};
const ABOVE_U64: &str = "340282366920938463463374607431768211456";
fn position(digits: &str) -> RenderedPosition {
RenderedPosition::from_canonical_digits(digits.to_owned())
}
fn rule_coordinates() -> (Vec<usize>, usize) {
(vec![1, 0], 2)
}
fn assert_exact<T>(render: impl Fn(&T) -> Value, fixtures: Vec<(T, Value)>) {
for (value, expected) in fixtures {
assert_eq!(render(&value), expected);
}
}
#[test]
fn target_shapes_match_their_json_fixtures_exactly() {
let range = || {
Some(RenderedLineRange {
start_line: 1,
end_line: 3,
})
};
assert_exact(
target_json,
vec![
(
RenderedTarget::Header {
path: vec!["A".into(), "B".into()],
},
json!({"kind": "header", "path": ["A", "B"]}),
),
(
RenderedTarget::MissingHeader {
parent: vec!["A".into()],
matcher: "Step *".into(),
},
json!({"kind": "missing_header", "parent": ["A"], "matcher": "Step *"}),
),
(RenderedTarget::Document, json!({"kind": "document"})),
(
RenderedTarget::Frontmatter {
line_range: None,
pointer: None,
},
json!({"kind": "frontmatter"}),
),
(
RenderedTarget::Frontmatter {
line_range: range(),
pointer: None,
},
json!({
"kind": "frontmatter",
"line_range": {"start_line": 1, "end_line": 3}
}),
),
(
RenderedTarget::Frontmatter {
line_range: range(),
pointer: Some(String::new()),
},
json!({
"kind": "frontmatter",
"line_range": {"start_line": 1, "end_line": 3},
"pointer": ""
}),
),
(
RenderedTarget::Frontmatter {
line_range: range(),
pointer: Some("/release".into()),
},
json!({
"kind": "frontmatter",
"line_range": {"start_line": 1, "end_line": 3},
"pointer": "/release"
}),
),
(
RenderedTarget::Block {
parent: vec!["A".into()],
block: "list".into(),
index: 2,
},
json!({"kind":"block","parent":["A"],"block":"list","index":2}),
),
(
RenderedTarget::MissingBlock {
parent: vec!["A".into()],
matcher: RenderedContentMatcher::Block(RenderedBlockMatcher {
block: "list".into(),
list_kind: None,
}),
},
json!({"kind":"missing_block","parent":["A"],"matcher":{"block":"list"}}),
),
(
RenderedTarget::MissingBlock {
parent: Vec::new(),
matcher: RenderedContentMatcher::OneOf(vec![
RenderedBlockMatcher {
block: "p".into(),
list_kind: None,
},
RenderedBlockMatcher {
block: "list".into(),
list_kind: Some("bullet".into()),
},
]),
},
json!({"kind":"missing_block","parent":[],"matcher":{"one_of":[{"block":"p"},{"block":"list","list_kind":"bullet"}]}}),
),
(
RenderedTarget::Item {
list: RenderedListAddress {
parent: vec!["A".into()],
index: 2,
},
index: 3,
},
json!({"kind":"item","list":{"parent":["A"],"index":2},"index":3}),
),
(
RenderedTarget::MissingItem {
list: RenderedListAddress {
parent: vec!["A".into()],
index: 2,
},
matcher: "/entry/".into(),
},
json!({"kind":"missing_item","list":{"parent":["A"],"index":2},"matcher":"/entry/"}),
),
],
);
}
#[test]
fn schema_node_shapes_match_their_json_fixtures_exactly() {
let (scope, index) = rule_coordinates();
assert_exact(
schema_node_json,
vec![
(RenderedSchemaNode::Title, json!({"kind": "title"})),
(
RenderedSchemaNode::Frontmatter,
json!({"kind": "frontmatter"}),
),
(
RenderedSchemaNode::FrontmatterSchemaDeclaration,
json!({"kind": "frontmatter_schema_declaration"}),
),
(
RenderedSchemaNode::FrontmatterSchemaDocument,
json!({"kind": "frontmatter_schema_document"}),
),
(
RenderedSchemaNode::Rule {
scope: scope.clone(),
index,
},
json!({"kind": "rule", "scope": [1, 0], "index": 2}),
),
(
RenderedSchemaNode::Guard {
scope: scope.clone(),
index,
},
json!({"kind": "guard", "scope": [1, 0], "index": 2}),
),
(
RenderedSchemaNode::Capture {
scope: scope.clone(),
index,
name: "version".into(),
},
json!({"kind": "capture", "scope": [1, 0], "index": 2, "name": "version"}),
),
(
RenderedSchemaNode::FrontmatterCapture {
name: "release".into(),
},
json!({"kind": "frontmatter_capture", "name": "release"}),
),
(
RenderedSchemaNode::OrderEntry {
scope: scope.clone(),
index,
order_index: 1,
},
json!({
"kind": "order_entry",
"scope": [1, 0],
"index": 2,
"order_index": 1
}),
),
(
RenderedSchemaNode::Constraint { scope, index },
json!({"kind": "constraint", "scope": [1, 0], "index": 2}),
),
(
RenderedSchemaNode::ContentRule {
owner: RenderedContentOwner::Rule {
scope: vec![1, 0],
index: 2,
},
index: 3,
},
json!({"kind":"content_rule","owner":{"kind":"rule","scope":[1,0],"index":2},"index":3}),
),
(
RenderedSchemaNode::ItemRule {
content: RenderedContentRulePath {
owner: RenderedContentOwner::Title,
index: 3,
},
index: 4,
},
json!({"kind":"item_rule","content":{"owner":{"kind":"title"},"index":3},"index":4}),
),
],
);
}
#[test]
fn reference_shapes_match_their_json_fixtures_exactly() {
assert_exact(
reference_json,
vec![
(
RenderedReference::Rule {
locator: "release".into(),
anchor: "current_scope",
path: vec!["release".into()],
positions: None,
matcher: RenderedMatcher::Exact("Release".into()),
},
json!({
"kind": "rule",
"locator": "release",
"anchor": "current_scope",
"path": ["release"],
"matcher": {"kind": "exact", "value": "Release"}
}),
),
(
RenderedReference::Rule {
locator: format!("$.release[{ABOVE_U64}].notes"),
anchor: "schema_root",
path: vec!["release".into(), "notes".into()],
positions: Some(vec![Some(position(ABOVE_U64)), None]),
matcher: RenderedMatcher::Exact("Notes".into()),
},
json!({
"kind": "rule",
"locator": format!("$.release[{ABOVE_U64}].notes"),
"anchor": "schema_root",
"path": ["release", "notes"],
"positions": [Value::Number(ABOVE_U64.parse().expect("a JSON number")), null],
"matcher": {"kind": "exact", "value": "Notes"}
}),
),
(
RenderedReference::FrontmatterQuery {
locator: "fm[$.draft]".into(),
query: "$.draft".into(),
equals: None,
},
json!({
"kind": "frontmatter_query",
"locator": "fm[$.draft]",
"query": "$.draft"
}),
),
(
RenderedReference::FrontmatterQuery {
locator: "fm[$.count]=0x10".into(),
query: "$.count".into(),
equals: Some(RenderedScalar::Integer("16".into())),
},
json!({
"kind": "frontmatter_query",
"locator": "fm[$.count]=0x10",
"query": "$.count",
"equals": {"type": "integer", "value": "16"}
}),
),
(
RenderedReference::FrontmatterCapture {
locator: "fm.version".into(),
name: "version".into(),
value_type: "semver".into(),
},
json!({
"kind": "frontmatter_capture",
"locator": "fm.version",
"name": "version",
"type": "semver"
}),
),
],
);
}
#[test]
fn positions_above_u64_are_emitted_as_unquoted_json_integers() {
let reference = RenderedReference::Rule {
locator: format!("$.release[{ABOVE_U64}].notes"),
anchor: "schema_root",
path: vec!["release".into(), "notes".into()],
positions: Some(vec![Some(position(ABOVE_U64)), None]),
matcher: RenderedMatcher::Any,
};
let rendered = reference_json(&reference);
let text = serde_json::to_string(&rendered["positions"]).expect("renderable");
assert_eq!(text, format!("[{ABOVE_U64},null]"));
assert!(rendered["positions"][0].is_number());
assert!(!rendered["positions"][0].is_f64());
}
#[test]
fn positions_are_omitted_entirely_or_aligned_with_every_path_step() {
let render = |positions: Option<Vec<Option<RenderedPosition>>>| {
reference_json(&RenderedReference::Rule {
locator: "a.b.c".into(),
anchor: "current_scope",
path: vec!["a".into(), "b".into(), "c".into()],
positions,
matcher: RenderedMatcher::Any,
})
};
assert!(
render(None).get("positions").is_none(),
"an unsubscripted path carries no `positions` member"
);
assert_eq!(
render(Some(vec![None, Some(position("7")), None]))["positions"],
json!([null, 7, null])
);
}
#[test]
fn matcher_shapes_match_their_json_fixtures_exactly() {
assert_exact(
matcher_json,
vec![
(
RenderedMatcher::Exact("Release".into()),
json!({"kind": "exact", "value": "Release"}),
),
(
RenderedMatcher::Glob("Release *".into()),
json!({"kind": "glob", "value": "Release *"}),
),
(
RenderedMatcher::Regex("Release (?<version>.+)".into()),
json!({"kind": "regex", "value": "Release (?<version>.+)"}),
),
(RenderedMatcher::Any, json!({"kind": "any"})),
],
);
}
#[test]
fn equality_scalar_shapes_match_their_json_fixtures_exactly() {
assert_exact(
scalar_json,
vec![
(RenderedScalar::Null, json!({"type": "null", "value": null})),
(
RenderedScalar::Boolean(true),
json!({"type": "boolean", "value": true}),
),
(
RenderedScalar::Integer("16".into()),
json!({"type": "integer", "value": "16"}),
),
(
RenderedScalar::Float("15e-1".into()),
json!({"type": "float", "value": "15e-1"}),
),
(
RenderedScalar::String("release".into()),
json!({"type": "string", "value": "release"}),
),
],
);
}
#[test]
fn shared_buffer_preserves_escaping_and_member_order() {
let text = "quote\" slash\\ controls\0\u{1f}\n\r\t 日本語 💚";
let value = json!({"kind": "item", "list": {"parent": [text], "index": 2}, "index": 3});
let mut output = Vec::new();
write_json_value(&value, JsonContext::Default, &mut output);
let escaped = serde_json::to_string(text).expect("string");
assert_eq!(
String::from_utf8(output.clone()).expect("UTF-8"),
format!(
"{{\"kind\":\"item\",\"list\":{{\"parent\":[{escaped}],\"index\":2}},\"index\":3}}"
)
);
assert_eq!(
serde_json::from_slice::<Value>(&output).expect("JSON"),
value
);
let value =
json!({text: text, "position": Value::Number(ABOVE_U64.parse().expect("number"))});
output.clear();
write_json_value(&value, JsonContext::Default, &mut output);
assert_eq!(
serde_json::from_slice::<Value>(&output).expect("JSON"),
value
);
assert!(String::from_utf8(output)
.expect("UTF-8")
.contains(ABOVE_U64));
}
fn skeleton(id: &str) -> RenderedDiagnostic {
RenderedDiagnostic {
id: id.into(),
message: "explanatory prose".into(),
source_path: "doc.md".into(),
line: 1,
column: 1,
target: None,
schema_node: None,
schema_location: None,
involved_headers: Vec::new(),
references: Vec::new(),
}
}
#[test]
fn a_diagnostic_without_optional_data_renders_as_the_bare_skeleton() {
assert_eq!(
diagnostic_json(&skeleton("diagnostic-id")),
json!({
"id": "diagnostic-id",
"message": "explanatory prose",
"location": {"line": 1, "column": 1}
})
);
}
#[test]
fn a_diagnostic_with_every_optional_member_renders_all_of_them() {
let (scope, index) = rule_coordinates();
let diagnostic = RenderedDiagnostic {
target: Some(RenderedTarget::Header {
path: vec!["Parent".into(), "Child".into()],
}),
schema_node: Some(RenderedSchemaNode::Capture {
scope,
index,
name: "version".into(),
}),
schema_location: Some(RenderedLocation {
path: "schema.yml".into(),
line: 7,
column: 9,
}),
involved_headers: vec![RenderedInvolvedHeader {
header_path: vec!["Parent".into(), "Child".into()],
line: 4,
column: 1,
}],
references: vec![RenderedReference::FrontmatterCapture {
locator: "fm.version".into(),
name: "version".into(),
value_type: "semver".into(),
}],
..skeleton("invalid-value")
};
assert_eq!(
diagnostic_json(&diagnostic),
json!({
"id": "invalid-value",
"message": "explanatory prose",
"location": {"line": 1, "column": 1},
"target": {"kind": "header", "path": ["Parent", "Child"]},
"schema_node": {
"kind": "capture",
"scope": [1, 0],
"index": 2,
"name": "version"
},
"schema_location": {"path": "schema.yml", "line": 7, "column": 9},
"involved_headers": [{
"header_path": ["Parent", "Child"],
"location": {"line": 4, "column": 1}
}],
"references": [{
"kind": "frontmatter_capture",
"locator": "fm.version",
"name": "version",
"type": "semver"
}]
})
);
}
#[test]
fn the_envelope_matches_its_json_fixture_exactly() {
let rendered = render_json(&[ValidationResult {
kind: ResultKind::Document,
path: "doc.md".into(),
schema: "schema.yml".into(),
diagnostics: Vec::new(),
}]);
assert!(rendered.ends_with('\n'), "one line, terminated");
assert_eq!(
serde_json::from_str::<Value>(&rendered).expect("one JSON document"),
json!({
"version": 2,
"results": [{
"kind": "document",
"path": "doc.md",
"schema": "schema.yml",
"diagnostics": []
}],
"summary": {
"files": 1,
"documents": 1,
"schemas": 0,
"diagnostics": 0
}
})
);
}
#[test]
fn the_non_exhaustive_matcher_fallback_is_not_one_of_the_specified_kinds() {
let kind = matcher_json(&RenderedMatcher::Unknown)["kind"].clone();
assert!(!["exact", "glob", "regex", "any"].contains(&kind.as_str().expect("a kind")));
}
#[test]
fn json_locations_preserve_unsigned_64_bit_values() {
let line = u64::from(u32::MAX) + 1;
let diagnostic = RenderedDiagnostic {
line,
column: line,
..skeleton("test")
};
let json = diagnostic_json(&diagnostic);
assert_eq!(json["location"]["line"].as_u64(), Some(line));
assert_eq!(json["location"]["column"].as_u64(), Some(line));
}
}