# Tests of `std::json`: its text, the reader, the document, and the writer. import std::io; import std::json; import std::testing; import system; # Whether parsing the text fails with the kind of error, at the line and column. def fails_at(text: strview, kind: json::error_kind, line: u32, column: u32): bool { match json::parse(text) { value(&_) => return false; error(e) => return e.kind == kind && e.line == line && e.column == column; } return false; } # The text a document's root is written again as, on one line. def rewritten(text: strview): string { val doc := json::parse(text) else (e) { return e.describe(); }; var out := json::writer::new(); json::encode(&doc.root, &mut out); val written := out.finish() else (e) { return e.describe(); }; return string::from(written, nothing {}); } # The bits of a float, which tell `-0` from `0` and compare exactly. def bits(x: f64): u64 { var copy: f64 = x; return *(((©) as *f64) as *u64); } @test def json_escapes_text_and_checks_utf8(t: &mut tester): void { var out := string::new(nothing {}); t.expects(json::escape("plain é \"quoted\" back\\slash\n\t\x01\x1F", &mut out)); t.expects(out.view() == "plain é \\\"quoted\\\" back\\\\slash\\n\\t\\u0001\\u001f"); var back := string::new(nothing {}); json::unescape("a\\u00e9\\ud83d\\ude00\\n\\/\\\\\\\"\\b\\f\\r\\t", &mut back); t.expects(back.view() == "aé😀\n/\\\"\x08\x0C\r\t"); # Overlong forms, surrogates, and characters past U+10FFFF are not UTF-8. t.expects(json::is_utf8("é😀\xEF\xBF\xBF\xF4\x8F\xBF\xBF")); t.expects(!json::is_utf8("\xC0\x80") && !json::is_utf8("\xE0\x80\x80") && !json::is_utf8("\xED\xA0\x80")); t.expects(!json::is_utf8("\xF4\x90\x80\x80") && !json::is_utf8("\xE2\x82") && !json::is_utf8("\x80")); var cut := string::new(nothing {}); t.expects(!json::escape("ok\xFFno", &mut cut)); t.expects(cut.view() == "ok"); } @test def json_reader_gives_tokens(t: &mut tester): void { var tokens := json::reader::new(" {\"a\\n\": [1, -2.5e3, true, false, null, \"x\"]} "); var kinds := string::new(nothing {}); while tokens.next() is some(read) { kinds.append($"{read.kind}:{read.view} "); } t.expects(tokens.error is none); t.expects(kinds.view() == "begin_object:{ key:a\\n begin_array:[ number:1 number:-2.5e3 boolean:true boolean:false empty:null text:x end_array:] end_object:} "); # A key's escapes are left for `unescape`, and the token says it holds some. var keyed := json::reader::new("{\"a\\n\": 1}"); _ = keyed.next(); val key := keyed.next().some; t.expects(key.kind == json::token_kind::key && key.escaped && key.offset == 1); # Skipping a value reads past everything it holds. var skim := json::reader::new("{\"params\": {\"deep\": [1, [2, {}]]}, \"method\": \"m\"}"); _ = skim.next(); _ = skim.next(); t.expects(skim.skip()); t.expects(skim.next().some.view == "method" && skim.next().some.view == "m"); } @test def json_reader_stops_at_the_first_error(t: &mut tester): void { var tokens := json::reader::new("[1, 2,]"); var count := 0; while tokens.next() is some(_) { count++; } t.expects(count == 3); t.expects(tokens.error.some.kind == json::error_kind::unexpected_byte && tokens.error.some.column == 7); t.expects(tokens.next() is none); } @test def json_nesting_is_limited(t: &mut tester): void { t.expects(json::parse("[[[1]]]", 3) is value); match json::parse("[[[[1]]]]", 3) { value(&_) => t.expects(false); error(e) => t.expects(e.kind == json::error_kind::too_deep && e.column == 4); } # Past 512 levels, a reader given a higher limit keeps what is open elsewhere. var deep := string::new(nothing {}); for _ in 0..600 { deep.append("[{\"k\":"); } deep.append("1"); for _ in 0..600 { deep.append("}]"); } t.expects(json::parse(deep.view()) is error); t.expects(json::parse(deep.view(), 1200) is value); } @test def json_parse_errors_say_where(t: &mut tester): void { t.expects(fails_at("", json::error_kind::unexpected_end, 1, 1)); t.expects(fails_at("{\"a\": 1,\n \"b\" 2}", json::error_kind::unexpected_byte, 2, 6)); t.expects(fails_at("[1, 2", json::error_kind::unexpected_end, 1, 6)); t.expects(fails_at("[01]", json::error_kind::invalid_number, 1, 2)); t.expects(fails_at("[1.]", json::error_kind::invalid_number, 1, 2)); t.expects(fails_at("[.5]", json::error_kind::unexpected_byte, 1, 2)); t.expects(fails_at("[-]", json::error_kind::invalid_number, 1, 2)); t.expects(fails_at("[1e]", json::error_kind::invalid_number, 1, 2)); t.expects(fails_at("[\"a\\x\"]", json::error_kind::invalid_escape, 1, 4)); t.expects(fails_at("[\"\\ud800\"]", json::error_kind::invalid_escape, 1, 3)); t.expects(fails_at("[\"\\udc00\"]", json::error_kind::invalid_escape, 1, 3)); t.expects(fails_at("[\"tab\there\"]", json::error_kind::unexpected_byte, 1, 6)); t.expects(fails_at("[\"\xC0\x80\"]", json::error_kind::invalid_utf8, 1, 3)); t.expects(fails_at("{\"a\": tru}", json::error_kind::unexpected_byte, 1, 7)); t.expects(fails_at("[nul", json::error_kind::unexpected_end, 1, 2)); t.expects(fails_at("{} {}", json::error_kind::trailing_text, 1, 4)); t.expects(fails_at("[1,]", json::error_kind::unexpected_byte, 1, 4)); t.expects(fails_at("{\"a\":1,}", json::error_kind::unexpected_byte, 1, 8)); t.expects(fails_at("NaN", json::error_kind::unexpected_byte, 1, 1)); val failed := json::parse("[1,\n x]") else (e) { t.expects(e.describe().view() == "2:3: A byte stands where JSON allows none of its kind."); return; }; t.expects(false); } @test def json_documents_keep_every_member(t: &mut tester): void { val doc := json::parse("{\"id\": 1, \"name\": \"a\", \"id\": 2, \"n\\u0061me\": \"b\", \"id\": 3}") else (e) { t.expects(false); return; }; val root := doc.root; t.expects(root.kind == json::kind::object && root.length == 5); t.expects(root.get("id").some.as_i64().value == 1); t.expects(root.get("missing") is none); var ids: i64 = 0; for each in root.get_all("id") { ids = ids * 10 + each.as_i64().value; } t.expects(ids == 123); # Escaped names are found by their decoded text, and every member is given in order. var names := string::new(nothing {}); for each in root.get_all("name") { names.append(each.as_text().value); } t.expects(names.view() == "ab"); var keys := string::new(nothing {}); for each in root.members() { keys.append(each.key); keys.push(' '); } t.expects(keys.view() == "id name id name id "); } @test def json_values_are_read_by_kind(t: &mut tester): void { val doc := json::parse("[null, true, false, 0, \"s\", [1, 2], {\"k\": [3]}]") else (e) { t.expects(false); return; }; val root := doc.root; t.expects(root.length == 7 && root.at(7) is none && root.get("k") is none); t.expects(root.at(0).some.is_null && root.at(1).some.as_bool().value && !root.at(2).some.as_bool().value); t.expects(root.at(4).some.as_text().value == "s" && root.at(4).some.length == 0); t.expects(root.at(6).some.get("k").some.at(0).some.as_u64().value == 3); var total: i64 = 0; for item in root.at(5).some.elements() { total += item.as_i64().value; } t.expects(total == 3); # A value of the wrong kind says where it is. match root.at(4).some.as_i64() { value(_) => t.expects(false); error(e) => t.expects(e.kind == json::error_kind::wrong_kind && e.line == 1 && e.column == 24); } t.expects(root.at(0).some.as_bool() is error && root.as_text() is error); t.expects(root.at(4).some.elements().next() is none && root.members().next() is none); } @test def json_integers_read_exactly(t: &mut tester): void { val doc := json::parse(""" [1e3, 1.50e1, 1.5, 1e-1, -0, 0e99999, 9223372036854775807, -9223372036854775808, 9223372036854775808, 18446744073709551615, 18446744073709551616, -1, 12.000, 1e19, 1e20] """) else (e) { t.expects(false); return; }; val at := doc.root; t.expects(at.at(0).some.as_i64().value == 1000 && at.at(1).some.as_i64().value == 15); t.expects(at.at(2).some.as_i64().error.kind == json::error_kind::wrong_kind); t.expects(at.at(3).some.as_i64().error.kind == json::error_kind::wrong_kind); t.expects(at.at(4).some.as_u64().value == 0 && at.at(5).some.as_i64().value == 0); t.expects(at.at(6).some.as_i64().value == 9223372036854775807); t.expects(at.at(7).some.as_i64().value == -9223372036854775807 - 1); t.expects(at.at(8).some.as_i64().error.kind == json::error_kind::out_of_range); t.expects(at.at(8).some.as_u64().value == 9223372036854775808); t.expects(at.at(9).some.as_u64().value == 18446744073709551615); t.expects(at.at(10).some.as_u64().error.kind == json::error_kind::out_of_range); t.expects(at.at(11).some.as_u64().error.kind == json::error_kind::out_of_range && at.at(11).some.as_i64().value == -1); t.expects(at.at(12).some.as_i64().value == 12); t.expects(at.at(13).some.as_u64().value == 10000000000000000000 && at.at(14).some.as_u64() is error); } @test def json_floats_read_back_exactly(t: &mut tester): void { const written: span = [0.1, 5e-324, 2.2250738585072014e-308, 1.7976931348623157e308, 9007199254740993.0, -0.0, 1e21, 1e-7, 123456789012345680000.0, 0.30000000000000004, 3.0, -2.5e-300]; var out := json::writer::new(); out.begin_array(); for x in written { out.real(x); } out.end_array(); val text := out.finish() else (e) { t.expects(false); return; }; val doc := json::parse(text) else (e) { t.expects(false); return; }; for index, x in written { t.expects(bits(doc.root.at(index).some.as_f64().value) == bits(x)); } t.expects(doc.root.at(4).some.as_f64().value == 9007199254740992.0); val huge := json::parse("[1e400, 1e-400]") else (e) { t.expects(false); return; }; t.expects(huge.root.at(0).some.as_f64().error.kind == json::error_kind::out_of_range); t.expects(huge.root.at(1).some.as_f64().value == 0.0); } @test def json_writer_writes_compactly_and_indented(t: &mut tester): void { var out := json::writer::new(); out.begin_object(); out.member("jsonrpc"); out.text("2.0"); out.member("id"); out.unsigned(7); out.member("result"); out.begin_array(); out.signed(-12); out.boolean(false); out.empty(); out.begin_object(); out.end_object(); out.begin_array(); out.end_array(); out.end_array(); out.end_object(); t.expects(out.finish().value == "{\"jsonrpc\":\"2.0\",\"id\":7,\"result\":[-12,false,null,{},[]]}"); var pretty := json::writer::indented(2); pretty.begin_object(); pretty.member("a"); pretty.begin_array(); pretty.signed(1); pretty.signed(2); pretty.end_array(); pretty.member("b"); pretty.begin_object(); pretty.end_object(); pretty.end_object(); t.expects(pretty.finish().value == "{\n \"a\": [\n 1,\n 2\n ],\n \"b\": {}\n}"); # A writer is emptied to write another value. out.clear(); out.text("again"); t.expects(out.finish().value == "\"again\""); # The extremes of the integers write as they are. out.clear(); out.begin_array(); out.signed(-9223372036854775807 - 1); out.unsigned(18446744073709551615); out.signed(0); out.end_array(); t.expects(out.finish().value == "[-9223372036854775808,18446744073709551615,0]"); } # A stream that takes only so many bytes, then fails, as a full disk does. struct refusing : writable { var left: u64; } def refusing::write(&mut this, data: span): result { if data.length > this.left { return io_error::no_space; } this.left -= data.length; return; } # Writes a document larger than a writer holds before it passes its text on. def write_records(out: &mut json::writer): void { out.begin_array(); for i in 0..3000 { out.begin_object(); out.member("n"); out.unsigned(i as u64); out.member("name"); out.text("élément"); out.end_object(); } out.end_array(); } @test def json_writer_passes_its_text_to_a_stream(t: &mut tester): void { var whole := json::writer::indented(2); write_records(&mut whole); val text := whole.finish() else (_) { t.expects(false); return; }; var said := string::new(nothing {}); var streamed := json::writer::to(&mut said, 2); write_records(&mut streamed); t.expects(said.length >= 16384 && said.length < text.length); val rest := streamed.finish() else (_) { t.expects(false); return; }; t.expects(rest.length == 0 && said.view() == text); # A typed value, through a writer that holds what it is given in turn. var numbers := vector::::new(); for i in 0..5000 { numbers.append((i * 7) as u64); } val expected := json::to_text(&numbers) else (_) { t.expects(false); return; }; var buffered := string::new(nothing {}); { var out := io::writer_of(&mut buffered); json::write_to(&numbers, &mut out) else (_) { t.expects(false); return; }; _ = out.flush(); } t.expects(buffered.view() == expected.view() && buffered.length > 16384); # A stream that fails is kept as its failure, and what is written after is let go. var refused := refusing { left = 10 }; var failing := json::writer::to(&mut refused); write_records(&mut failing); t.expects(failing.finish().error.kind == json::error_kind::not_written && refused.left == 10); t.expects(json::write_to(&numbers, &mut refused).error.kind == json::error_kind::not_written); } @test def json_writer_keeps_failures_in_the_data(t: &mut tester): void { var out := json::writer::new(); out.begin_array(); out.real(1.0 / 0.0); out.real(0.0 / 0.0); out.text("ok\xFF"); out.end_array(); match out.finish() { value(_) => t.expects(false); error(e) => t.expects(e.kind == json::error_kind::not_finite && e.line == 0); } t.expects(out._text.view() == "[null,null,null]"); out.clear(); out.begin_object(); out.member("\xC0\x80"); out.signed(1); out.end_object(); t.expects(out.finish().error.kind == json::error_kind::invalid_utf8); t.expects(out._text.view() == "{\"\":1}"); } @test def json_writer_writes_text_lossily_where_asked(t: &mut tester): void { # Each byte that breaks UTF-8 is the escape of U+FFFD, a sequence cut short a # byte at a time, and the escapes and characters around it are as ever. var whole := string::new(nothing {}); t.expects(!json::escape("a\xC0\x80b\xE2\x82 é\x08", &mut whole, true)); t.expects(whole.view() == "a\\ufffd\\ufffdb\\ufffd\\ufffd é\\b"); var plain := string::new(nothing {}); t.expects(json::escape("é\n", &mut plain, true) && plain.view() == "é\\n"); # A lossy writer keeps no failure, in members' names or strings. var out := json::writer::new(); out.set_lossy(true); out.begin_object(); out.member("k\xFF"); out.text("ok\xFF"); out.end_object(); t.expects(out.finish().value == "{\"k\\ufffd\":\"ok\\ufffd\"}"); # Emptied, it stays lossy, and made strict again, it keeps the failure. out.clear(); out.text("\xFF"); t.expects(out.finish().value == "\"\\ufffd\""); out.clear(); out.set_lossy(false); out.text("\xFF"); t.expects(out.finish().error.kind == json::error_kind::invalid_utf8); } @test def json_writer_writes_text_already_written(t: &mut tester): void { # Text already written is a value, with the commas and names around it, and # keeps its own spacing. var out := json::writer::new(); out.begin_object(); out.member("jsonrpc"); out.text("2.0"); out.member("id"); out.raw("\"a\""); out.member("result"); out.begin_array(); out.raw("{\"x\": [1, 2]}"); out.raw("null"); out.end_array(); out.end_object(); t.expects(out.finish().value == "{\"jsonrpc\":\"2.0\",\"id\":\"a\",\"result\":[{\"x\": [1, 2]},null]}"); var pretty := json::writer::indented(2); pretty.begin_array(); pretty.raw("{\"a\":1}"); pretty.signed(2); pretty.end_array(); t.expects(pretty.finish().value == "[\n {\"a\":1},\n 2\n]"); out.clear(); out.raw("[]"); t.expects(out.finish().value == "[]"); } @test def json_documents_are_written_again_whole(t: &mut tester): void { val text: strview = "{\"a\":[1,-2,1.5,18446744073709551615,\"t\\u00e9\\n\",null,true,{}],\"b\":{\"c\":[]},\"a\":0}"; val once := rewritten(text); t.expects(once.view() == "{\"a\":[1,-2,1.5,18446744073709551615,\"té\\n\",null,true,{}],\"b\":{\"c\":[]},\"a\":0}"); val twice := rewritten(once.view()); t.expects(twice.view() == once.view()); }