(*--------------------------------------------------------------------------- Copyright (c) 2026 Thomas Gazagnaire . All rights reserved. SPDX-License-Identifier: ISC ---------------------------------------------------------------------------*) (* -- Tree-level helpers (parser tests) -------------------------------- *) let parse_ok s = match Xml.Value.of_string s with | Ok el -> el | Error e -> Alcotest.failf "parse error: %a" Xml.Error.pp e let parse_err s = match Xml.Value.of_string s with | Ok _ -> Alcotest.fail "expected parse error but got success" | Error _ -> () (* 1. Simple element *) let test_simple_element () = let el = parse_ok "text" in Alcotest.(check string) "tag" "a" (fst el.tag); Alcotest.(check string) "text" "text" (Xml.Value.text el); Alcotest.(check int) "no attrs" 0 (List.length el.attrs); Alcotest.(check int) "one child" 1 (List.length el.children) (* 2. Attributes *) let test_attributes () = let el = parse_ok {||} in Alcotest.(check string) "tag" "a" (fst el.tag); Alcotest.(check (option string)) "attr x" (Some "1") (Xml.Value.attr "x" el); Alcotest.(check (option string)) "attr y" (Some "2") (Xml.Value.attr "y" el); Alcotest.(check (option string)) "attr z" None (Xml.Value.attr "z" el); Alcotest.(check int) "no children" 0 (List.length el.children) let test_single_quoted_attrs () = let el = parse_ok "" in Alcotest.(check (option string)) "attr x" (Some "hello") (Xml.Value.attr "x" el) (* 3. Nested elements *) let test_nested_elements () = let el = parse_ok "deep" in Alcotest.(check string) "root tag" "a" (fst el.tag); let b = match Xml.Value.find "b" el with | Some e -> e | None -> Alcotest.fail "no b" in let c = match Xml.Value.find "c" b with Some e -> e | None -> Alcotest.fail "no c" in Alcotest.(check string) "deep text" "deep" (Xml.Value.text c) (* 4. Mixed content *) let test_mixed_content () = let el = parse_ok "

Hello world

" in Alcotest.(check string) "tag" "p" (fst el.tag); Alcotest.(check int) "children" 2 (List.length el.children); (* First child is text "Hello " *) (match List.nth el.children 0 with | Xml.Value.Text (s, _) -> Alcotest.(check string) "text before" "Hello " s | _ -> Alcotest.fail "expected text"); (* Second child is element *) match List.nth el.children 1 with | Xml.Value.Element e -> Alcotest.(check string) "b tag" "b" (fst e.tag); Alcotest.(check string) "b text" "world" (Xml.Value.text e) | _ -> Alcotest.fail "expected element" (* 5. Self-closing *) let test_self_closing () = let el = parse_ok "
" in Alcotest.(check string) "tag" "br" (fst el.tag); Alcotest.(check int) "no children" 0 (List.length el.children); Alcotest.(check int) "no attrs" 0 (List.length el.attrs) let test_self_closing_with_space () = let el = parse_ok "
" in Alcotest.(check string) "tag" "br" (fst el.tag); Alcotest.(check int) "no children" 0 (List.length el.children) (* 6. CDATA *) let test_cdata () = let el = parse_ok "]]>" in Alcotest.(check string) "tag" "data" (fst el.tag); Alcotest.(check string) "cdata content" "" (Xml.Value.text el) let test_cdata_with_ampersand () = let el = parse_ok "" in Alcotest.(check string) "cdata with &" "a & b" (Xml.Value.text el) (* 7. Entity references *) let test_entity_refs () = let el = parse_ok "&<>" in Alcotest.(check string) "entities" "&<>" (Xml.Value.text el) let test_entity_quot_apos () = let el = parse_ok ""'" in Alcotest.(check string) "quot and apos" "\"'" (Xml.Value.text el) let test_entity_in_attr () = let el = parse_ok {||} in Alcotest.(check (option string)) "entity in attr" (Some "x&y") (Xml.Value.attr "a" el) let test_numeric_entity () = let el = parse_ok "AB" in Alcotest.(check string) "numeric entities" "AB" (Xml.Value.text el) (* 8. Comments skipped *) let test_comments_skipped () = let el = parse_ok "" in Alcotest.(check string) "tag" "a" (fst el.tag); Alcotest.(check int) "one child (comment skipped)" 1 (List.length el.children); match List.nth el.children 0 with | Xml.Value.Element e -> Alcotest.(check string) "child tag" "b" (fst e.tag) | _ -> Alcotest.fail "expected element" let test_comment_in_preamble () = let el = parse_ok "" in Alcotest.(check string) "tag" "root" (fst el.tag) (* 9. XML declaration skipped *) let test_xml_declaration () = let el = parse_ok {||} in Alcotest.(check string) "tag" "root" (fst el.tag) let test_xml_declaration_with_encoding () = let el = parse_ok {||} in Alcotest.(check string) "tag" "root" (fst el.tag) let test_processing_instruction () = let el = parse_ok {||} in Alcotest.(check string) "tag" "root" (fst el.tag) let test_pi_in_content () = let el = parse_ok "" in Alcotest.(check int) "PI skipped" 1 (List.length el.children) (* 10. Roundtrip *) let test_roundtrip () = let inputs = [ "text"; {||}; "deep"; "

Hello world

"; "
"; ] in List.iter (fun input -> let el = parse_ok input in let serialized = Xml.Value.to_string el in let el2 = parse_ok serialized in let reserialized = Xml.Value.to_string el2 in Alcotest.(check string) (Fmt.str "roundtrip: %s" input) serialized reserialized) inputs (* Pretty-printing must not alter mixed content. A naive implementation inserts indentation whitespace between text and element siblings, which changes the document's semantics. *) let test_indent_preserves_mixed_content () = let input = "

Hello world!

" in let el = parse_ok input in let pretty = Xml.Value.to_string ~indent:2 el in let reparsed = parse_ok pretty in let compact = Xml.Value.to_string reparsed in Alcotest.(check string) "mixed content unchanged after pretty/reparse" input compact let test_roundtrip_with_indent () = let el = parse_ok "text" in let s = Xml.Value.to_string ~indent:2 el in let el2 = parse_ok s in Alcotest.(check string) "root tag preserved" "root" (fst el2.tag); Alcotest.(check int) "children preserved" 2 (List.length (Xml.Value.find_all "child" el2) + List.length (Xml.Value.find_all "other" el2)) (* 11. Error on unclosed tag *) let test_unclosed_tag () = parse_err ""; parse_err "" (* 12. Error on mismatched tags *) let test_mismatched_tags () = parse_err ""; parse_err "text" let test_error_empty () = parse_err ""; parse_err " " let test_error_no_root () = parse_err "just text" (* 13. Query helpers *) let test_find () = let el = parse_ok "
" in Alcotest.(check bool) "find a" true (match Xml.Value.find "a" el with | Some e -> fst e.tag = "a" | None -> false); Alcotest.(check bool) "find d" true (Xml.Value.find "d" el = None) let test_find_all () = let el = parse_ok "" in let items = Xml.Value.find_all "item" el in Alcotest.(check int) "find_all item" 3 (List.length items); let others = Xml.Value.find_all "other" el in Alcotest.(check int) "find_all other" 1 (List.length others); let missing = Xml.Value.find_all "nope" el in Alcotest.(check int) "find_all missing" 0 (List.length missing) let test_attr () = let el = parse_ok {||} in Alcotest.(check (option string)) "attr key" (Some "val") (Xml.Value.attr "key" el); Alcotest.(check (option string)) "attr flag" (Some "true") (Xml.Value.attr "flag" el); Alcotest.(check (option string)) "attr missing" None (Xml.Value.attr "nope" el) let test_text () = let el = parse_ok "hello world" in Alcotest.(check string) "text" "hello world" (Xml.Value.text el) let test_text_mixed () = let el = parse_ok "

Hello world!

" in (* text only returns direct text children, not nested *) Alcotest.(check string) "text mixed" "Hello !" (Xml.Value.text el) let test_text_of () = let el = parse_ok "Alice30" in Alcotest.(check (option string)) "text_of name" (Some "Alice") (Xml.Value.text_of "name" el); Alcotest.(check (option string)) "text_of age" (Some "30") (Xml.Value.text_of "age" el); Alcotest.(check (option string)) "text_of missing" None (Xml.Value.text_of "email" el) let test_path () = let el = parse_ok "
found" in (match Xml.Value.path [ "b"; "c"; "d" ] el with | Some e -> Alcotest.(check string) "path" "found" (Xml.Value.text e) | None -> Alcotest.fail "path returned None"); Alcotest.(check bool) "path missing" true (Xml.Value.path [ "b"; "x" ] el = None); (* Empty path returns the element itself *) match Xml.Value.path [] el with | Some e -> Alcotest.(check string) "path empty" "a" (fst e.tag) | None -> Alcotest.fail "path [] returned None" (* 14. Real-world example: small XTCE-like document *) let test_xtce_like () = let xml = {| Temperature sensor reading |} in let el = parse_ok xml in Alcotest.(check string) "root tag" "SpaceSystem" (fst el.tag); Alcotest.(check (option string)) "root name" (Some "TestSat") (Xml.Value.attr "name" el); (* Navigate to ParameterTypeSet *) let pts = match Xml.Value.path [ "TelemetryMetaData"; "ParameterTypeSet" ] el with | Some e -> e | None -> Alcotest.fail "ParameterTypeSet not found" in let int_types = Xml.Value.find_all "IntegerParameterType" pts in Alcotest.(check int) "int types" 1 (List.length int_types); let float_types = Xml.Value.find_all "FloatParameterType" pts in Alcotest.(check int) "float types" 1 (List.length float_types); (* Check IntegerParameterType attrs *) let it = List.hd int_types in Alcotest.(check (option string)) "uint16 name" (Some "uint16") (Xml.Value.attr "name" it); Alcotest.(check (option string)) "uint16 bits" (Some "16") (Xml.Value.attr "sizeInBits" it); Alcotest.(check (option string)) "uint16 signed" (Some "false") (Xml.Value.attr "signed" it); (* Navigate to ParameterSet *) let ps = match Xml.Value.path [ "TelemetryMetaData"; "ParameterSet" ] el with | Some e -> e | None -> Alcotest.fail "ParameterSet not found" in let params = Xml.Value.find_all "Parameter" ps in Alcotest.(check int) "parameters" 2 (List.length params); let temp = List.hd params in Alcotest.(check (option string)) "TEMP typeRef" (Some "float32") (Xml.Value.attr "parameterTypeRef" temp); Alcotest.(check (option string)) "TEMP description" (Some "Temperature sensor reading") (Xml.Value.text_of "LongDescription" temp); (* Roundtrip the whole thing *) let serialized = Xml.Value.to_string el in let el2 = parse_ok serialized in let reserialized = Xml.Value.to_string el2 in Alcotest.(check string) "XTCE roundtrip" serialized reserialized (* Serialization-specific tests *) let test_serialize_escaping () = let el : Xml.Value.t = Xml.Value.element "t" ~attrs:(Xml.Value.attrs [ ("a", "x&y") ]) ~children:[ Xml.Value.Text ("a&bd", Xml.Meta.none) ] in let s = Xml.Value.to_string el in let el2 = parse_ok s in Alcotest.(check string) "text preserved" "a&bd" (Xml.Value.text el2); Alcotest.(check (option string)) "attr preserved" (Some "x&y") (Xml.Value.attr "a" el2) let test_whitespace_handling () = let el = parse_ok " " in (* Whitespace text nodes should be preserved *) let children = el.children in Alcotest.(check bool) "has whitespace children" true (List.length children > 1) let test_namespaced_names () = let el = parse_ok {||} in let xs = "http://www.w3.org/2001/XMLSchema" in Alcotest.(check string) "namespaced tag" "xs:element" (fst el.tag); Alcotest.(check (option string)) "declaration" (Some xs) (Xml.Namespace.find "xs" (Xml.Value.scope el)); Alcotest.(check (option string)) "prefixed attr" (Some "string") (Xml.Value.attr ~ns:xs "type" el); Alcotest.(check (option string)) "an unprefixed name is not the prefixed one" None (Xml.Value.attr "type" el) let test_doctype_skipped () = let el = parse_ok "" in Alcotest.(check string) "tag after DOCTYPE" "root" (fst el.tag) (* -- Codec tests ------------------------------------------------------ *) let decode_ok codec s = match Xml.of_string codec s with | Ok v -> v | Error e -> Alcotest.failf "decode error: %a" Xml.Error.pp e let decode_err codec s = match Xml.of_string codec s with | Ok _ -> Alcotest.fail "expected decode error but got success" | Error _ -> () (* Codec: primitive text codecs *) let test_codec_string () = let v = decode_ok Xml.Codec.string "hello" in Alcotest.(check string) "string decode" "hello" v let test_codec_int () = let v = decode_ok Xml.Codec.int "42" in Alcotest.(check int) "int decode" 42 v let test_codec_float () = let v = decode_ok Xml.Codec.float "3.14" in Alcotest.(check (float 0.001)) "float decode" 3.14 v let test_codec_bool () = let v = decode_ok Xml.Codec.bool "true" in Alcotest.(check bool) "bool decode" true v; let v2 = decode_ok Xml.Codec.bool "false" in Alcotest.(check bool) "bool decode false" false v2 let test_codec_int_error () = decode_err Xml.Codec.int "abc" (* Codec: element wrapper *) let test_codec_element () = let codec = Xml.Codec.element "greeting" Xml.Codec.string in let v = decode_ok codec "hello" in Alcotest.(check string) "element decode" "hello" v; decode_err codec "hello" (* Codec: element roundtrip *) let test_codec_element_roundtrip () = let codec = Xml.Codec.element "greeting" Xml.Codec.string in let encoded = Xml.to_string codec "hello" in let decoded = decode_ok codec encoded in Alcotest.(check string) "element roundtrip" "hello" decoded (* Codec: record with attributes *) type point = { x : float; y : float; label : string } let point_codec = Xml.Codec.( element "point" El.( obj (fun x y label -> { x; y; label }) |> attr "x" Attr.float ~enc:(fun p -> p.x) |> attr "y" Attr.float ~enc:(fun p -> p.y) |> attr "label" Attr.string ~enc:(fun p -> p.label) |> finish)) let test_codec_record_attrs () = let v = decode_ok point_codec {||} in Alcotest.(check (float 0.001)) "x" 1.5 v.x; Alcotest.(check (float 0.001)) "y" 2.5 v.y; Alcotest.(check string) "label" "origin" v.label let test_codec_record_attrs_roundtrip () = let p = { x = 1.5; y = 2.5; label = "test" } in let encoded = Xml.to_string point_codec p in let decoded = decode_ok point_codec encoded in Alcotest.(check (float 0.001)) "x roundtrip" 1.5 decoded.x; Alcotest.(check (float 0.001)) "y roundtrip" 2.5 decoded.y; Alcotest.(check string) "label roundtrip" "test" decoded.label (* Codec: record with children *) type person = { name : string; age : int; email : string option } let person_codec = Xml.Codec.( element "person" El.( obj (fun name age email -> { name; age; email }) |> child "name" string ~enc:(fun p -> p.name) |> child "age" int ~enc:(fun p -> p.age) |> child_opt "email" string ~enc:(fun p -> p.email) |> finish)) let test_codec_record_children () = let v = decode_ok person_codec "Alice30a@b.c" in Alcotest.(check string) "name" "Alice" v.name; Alcotest.(check int) "age" 30 v.age; Alcotest.(check (option string)) "email" (Some "a@b.c") v.email let test_codec_record_children_optional () = let v = decode_ok person_codec "Bob25" in Alcotest.(check string) "name" "Bob" v.name; Alcotest.(check int) "age" 25 v.age; Alcotest.(check (option string)) "email absent" None v.email let test_codec_record_children_roundtrip () = let p = { name = "Alice"; age = 30; email = Some "a@b.c" } in let encoded = Xml.to_string person_codec p in let decoded = decode_ok person_codec encoded in Alcotest.(check string) "name roundtrip" "Alice" decoded.name; Alcotest.(check int) "age roundtrip" 30 decoded.age; Alcotest.(check (option string)) "email roundtrip" (Some "a@b.c") decoded.email let test_record_children_rt_none () = let p = { name = "Bob"; age = 25; email = None } in let encoded = Xml.to_string person_codec p in let decoded = decode_ok person_codec encoded in Alcotest.(check (option string)) "email none roundtrip" None decoded.email (* A present-but-malformed element must surface as Error, not silently become None. The option combinator encodes absence-only semantics; swallowing decode errors would hide corrupt data. *) let opt_codec = Xml.Codec.(option (element "age" int)) let test_option_present_valid () = match Xml.of_string opt_codec "42" with | Ok (Some 42) -> () | Ok _ -> Alcotest.fail "expected Some 42" | Error e -> Alcotest.failf "expected Ok, got Error: %a" Xml.Error.pp e let test_option_present_malformed_errors () = match Xml.of_string opt_codec "not-a-number" with | Error _ -> () | Ok _ -> Alcotest.fail "present-but-malformed must error, not None" (* Codec: children list *) type team = { team_name : string; members : string list } let team_codec = Xml.Codec.( element "team" El.( obj (fun team_name members -> { team_name; members }) |> attr "name" Attr.string ~enc:(fun t -> t.team_name) |> children "member" string ~enc:(fun t -> t.members) |> finish)) let test_codec_children_list () = let v = decode_ok team_codec {|AliceBob|} in Alcotest.(check string) "team name" "A" v.team_name; Alcotest.(check (list string)) "members" [ "Alice"; "Bob" ] v.members let test_codec_children_list_empty () = let v = decode_ok team_codec {||} in Alcotest.(check (list string)) "empty members" [] v.members let test_codec_children_list_roundtrip () = let t = { team_name = "A"; members = [ "Alice"; "Bob"; "Carol" ] } in let encoded = Xml.to_string team_codec t in let decoded = decode_ok team_codec encoded in Alcotest.(check (list string)) "members roundtrip" [ "Alice"; "Bob"; "Carol" ] decoded.members (* Codec: mixed attributes and children *) type config = { host : string; port : int; debug : bool } let config_codec = Xml.Codec.( element "config" El.( obj (fun host port debug -> { host; port; debug }) |> child "host" string ~enc:(fun c -> c.host) |> child "port" int ~enc:(fun c -> c.port) |> attr "debug" Attr.bool ~enc:(fun c -> c.debug) |> finish)) let test_codec_mixed () = let v = decode_ok config_codec {|localhost8080|} in Alcotest.(check string) "host" "localhost" v.host; Alcotest.(check int) "port" 8080 v.port; Alcotest.(check bool) "debug" true v.debug let test_codec_mixed_roundtrip () = let c = { host = "example.com"; port = 443; debug = false } in let encoded = Xml.to_string config_codec c in let decoded = decode_ok config_codec encoded in Alcotest.(check string) "host roundtrip" "example.com" decoded.host; Alcotest.(check int) "port roundtrip" 443 decoded.port; Alcotest.(check bool) "debug roundtrip" false decoded.debug (* Codec: optional attributes *) type link = { href : string; title : string option } let link_codec = Xml.Codec.( element "link" El.( obj (fun href title -> { href; title }) |> attr "href" Attr.string ~enc:(fun l -> l.href) |> attr_opt "title" Attr.string ~enc:(fun l -> l.title) |> finish)) let test_codec_attr_opt () = let v = decode_ok link_codec {||} in Alcotest.(check string) "href" "http://example.com" v.href; Alcotest.(check (option string)) "title" (Some "Example") v.title let test_codec_attr_opt_absent () = let v = decode_ok link_codec {||} in Alcotest.(check (option string)) "title absent" None v.title let test_codec_attr_opt_roundtrip () = let l = { href = "http://example.com"; title = None } in let encoded = Xml.to_string link_codec l in let decoded = decode_ok link_codec encoded in Alcotest.(check (option string)) "title none roundtrip" None decoded.title (* Codec: text field *) type note = { author : string; body : string } let note_codec = Xml.Codec.( element "note" El.( obj (fun author body -> { author; body }) |> attr "author" Attr.string ~enc:(fun n -> n.author) |> text ~enc:(fun n -> n.body) |> finish)) let test_codec_text_field () = let v = decode_ok note_codec {|Hello world|} in Alcotest.(check string) "author" "Alice" v.author; Alcotest.(check string) "body" "Hello world" v.body let test_codec_text_field_roundtrip () = let n = { author = "Bob"; body = "Test message" } in let encoded = Xml.to_string note_codec n in let decoded = decode_ok note_codec encoded in Alcotest.(check string) "author roundtrip" "Bob" decoded.author; Alcotest.(check string) "body roundtrip" "Test message" decoded.body (* Codec: list *) let test_codec_list () = let codec = Xml.Codec.(element "items" (list (element "item" int))) in let v = decode_ok codec "123" in Alcotest.(check (list int)) "list" [ 1; 2; 3 ] v let test_codec_list_roundtrip () = let codec = Xml.Codec.(element "items" (list (element "item" int))) in let encoded = Xml.to_string codec [ 10; 20; 30 ] in let decoded = decode_ok codec encoded in Alcotest.(check (list int)) "list roundtrip" [ 10; 20; 30 ] decoded (* Codec: map combinator -- dec raises Loc.Error on failure *) let test_codec_map () = let hex_codec = Xml.Codec.map ~dec:(fun s -> match int_of_string_opt ("0x" ^ s) with | Some n -> n | None -> Loc.Error.failf Loc.Meta.none "bad hex: %S" s) ~enc:(fun n -> Fmt.str "%x" n) Xml.Codec.string in let codec = Xml.Codec.element "hex" hex_codec in let v = decode_ok codec "ff" in Alcotest.(check int) "hex decode" 255 v (* Codec: bytesrw integration *) let test_codec_bytesrw_decode () = let codec = Xml.Codec.element "msg" Xml.Codec.string in let reader = Bytesrw.Bytes.Reader.of_string "hello" in match Xml.of_reader codec reader with | Ok v -> Alcotest.(check string) "bytesrw decode" "hello" v | Error e -> Alcotest.failf "bytesrw decode error: %a" Xml.Error.pp e let test_codec_bytesrw_encode () = let codec = Xml.Codec.element "msg" Xml.Codec.string in let buf = Buffer.create 64 in let writer = Bytesrw.Bytes.Writer.of_buffer buf in Xml.to_writer codec "hello" writer; Bytesrw.Bytes.Writer.write_eod writer; let s = Buffer.contents buf in Alcotest.(check string) "bytesrw encode" "hello" s (* Codec: encode with indent *) let test_codec_encode_indent () = let p = { name = "Alice"; age = 30; email = Some "a@b.c" } in let s = Xml.to_string ~indent:2 person_codec p in (* Should have newlines when indented *) Alcotest.(check bool) "has newlines" true (String.contains s '\n'); (* Should roundtrip *) let decoded = decode_ok person_codec s in Alcotest.(check string) "name after indent" "Alice" decoded.name (* Codec: missing required attribute error *) let test_codec_missing_attr () = decode_err point_codec {||} (* missing "label" *) (* Codec: missing required child error *) let test_codec_missing_child () = decode_err person_codec "Alice" (* missing "age" *) (* -- XML 1.0 Spec Edge Cases ----------------------------------------- *) (* 1. Character references: A -> A, A -> A, -> newline *) let test_char_ref_hex () = let el = parse_ok "A" in Alcotest.(check string) "hex A" "A" (Xml.Value.text el) let test_char_ref_dec () = let el = parse_ok "A" in Alcotest.(check string) "dec A" "A" (Xml.Value.text el) let test_char_ref_newline () = let el = parse_ok " " in Alcotest.(check string) "hex newline" "\n" (Xml.Value.text el) (* 2. Non-ASCII character references *) let test_char_ref_euro () = let el = parse_ok "€" in Alcotest.(check string) "euro sign" "\xe2\x82\xac" (Xml.Value.text el) let test_char_ref_snowman () = let el = parse_ok "☃" in Alcotest.(check string) "snowman" "\xe2\x98\x83" (Xml.Value.text el) (* 3. Predefined entity references in all positions *) let test_all_entities_in_text () = let el = parse_ok "&<>'"" in Alcotest.(check string) "all entities" "&<>'\x22" (Xml.Value.text el) let test_all_entities_in_attr () = let el = parse_ok {||} in Alcotest.(check (option string)) "entities in attr" (Some "<>&\"'") (Xml.Value.attr "b" el) (* 4. Whitespace in attributes: a literal TAB or LF in an attribute value normalizes to a space, XML 1.0 section 3.3.3. *) let test_attr_whitespace_tab () = let el = parse_ok "" in Alcotest.(check (option string)) "tab in attr" (Some "hel lo") (Xml.Value.attr "x" el) let test_attr_whitespace_newline () = let el = parse_ok "" in Alcotest.(check (option string)) "newline in attr" (Some "line1 line2") (Xml.Value.attr "x" el) (* 5. CDATA sections with special characters preserved literally *) let test_cdata_special_chars () = let el = parse_ok {|&"']]>|} in Alcotest.(check string) "CDATA special chars" "<>&\"'" (Xml.Value.text el) (* 6. CDATA section with ]]> escape via split *) let test_cdata_split_escape () = let el = parse_ok "more]]>" in Alcotest.(check string) "CDATA ]]> escape" "text]]>more" (Xml.Value.text el) (* 7. Empty elements: , , all equivalent *) let test_empty_element_forms () = let check_empty input label = let el = parse_ok input in Alcotest.(check string) (label ^ " tag") "a" (fst el.tag); Alcotest.(check int) (label ^ " children") 0 (List.length el.children); Alcotest.(check string) (label ^ " text") "" (Xml.Value.text el) in check_empty "" "self-close"; check_empty "" "self-close-space"; check_empty "" "open-close" (* 8. Deeply nested elements -- should not stack overflow. Past the default max_depth of 100, so the limit is raised explicitly: the point here is the recursion, not the cap (which "of_string default max_depth" in test_value.ml pins). *) let test_deep_nesting () = let depth = 200 in let buf = Buffer.create (depth * 10) in for _ = 1 to depth do Buffer.add_string buf "" done; Buffer.add_string buf "leaf"; for _ = 1 to depth do Buffer.add_string buf "" done; let xml = Buffer.contents buf in let el = match Xml.Value.of_string ~max_depth:depth xml with | Ok el -> el | Error e -> Alcotest.failf "parse error: %a" Xml.Error.pp e in (* Navigate to the deepest level *) let rec descend el n = if n = 0 then el else match Xml.Value.find "a" el with | Some child -> descend child (n - 1) | None -> Alcotest.fail "nesting too shallow" in let leaf = descend el (depth - 1) in Alcotest.(check string) "deep leaf text" "leaf" (Xml.Value.text leaf) (* 9. Very long text content *) let test_long_text () = let len = 1_000_000 in let content = String.make len 'x' in let xml = "" ^ content ^ "" in let el = parse_ok xml in Alcotest.(check int) "long text length" len (String.length (Xml.Value.text el)) (* 10. Very long attribute values *) let test_long_attr_value () = let len = 100_000 in let value = String.make len 'v' in let xml = Fmt.str {||} value in let el = parse_ok xml in Alcotest.(check (option string)) "long attr" (Some value) (Xml.Value.attr "x" el) (* 11. Many attributes on a single element *) let test_many_attributes () = let n = 200 in let buf = Buffer.create (n * 20) in let ppf = Fmt.with_buffer buf in Buffer.add_string buf ""; let el = parse_ok (Buffer.contents buf) in Alcotest.(check int) "many attrs count" n (List.length el.attrs); Alcotest.(check (option string)) "first attr" (Some "0") (Xml.Value.attr "a0" el); Alcotest.(check (option string)) "last attr" (Some (string_of_int (n - 1))) (Xml.Value.attr (Fmt.str "a%d" (n - 1)) el) (* 12. Many children on a single element *) let test_many_children () = let n = 10_000 in let buf = Buffer.create (n * 10) in let ppf = Fmt.with_buffer buf in Buffer.add_string buf ""; for i = 0 to n - 1 do Fmt.pf ppf "%d" i done; Buffer.add_string buf ""; let el = parse_ok (Buffer.contents buf) in let children = Xml.Value.find_all "c" el in Alcotest.(check int) "many children count" n (List.length children) (* 13. Mixed content: text interleaved with elements *) let test_mixed_content_complex () = let el = parse_ok "

textboldmoreitalicend

" in Alcotest.(check int) "mixed children" 5 (List.length el.children); (* Check order: Text, Element, Text, Element, Text *) match el.children with | [ Xml.Value.Text (t1, _); Element b; Text (t2, _); Element i; Text (t3, _) ] -> Alcotest.(check string) "text1" "text" t1; Alcotest.(check string) "b tag" "b" (fst b.tag); Alcotest.(check string) "b text" "bold" (Xml.Value.text b); Alcotest.(check string) "text2" "more" t2; Alcotest.(check string) "i tag" "i" (fst i.tag); Alcotest.(check string) "i text" "italic" (Xml.Value.text i); Alcotest.(check string) "text3" "end" t3 | _ -> Alcotest.fail "unexpected mixed content structure" (* 14. Adjacent text nodes after entity expansion *) let test_adjacent_text_entity () = let el = parse_ok "A&B" in Alcotest.(check string) "entity in text" "A&B" (Xml.Value.text el) (* 15. Processing instructions *) let test_pi_target_data () = let el = parse_ok "" in Alcotest.(check string) "PI skipped, root found" "root" (fst el.tag) let test_pi_xml_stylesheet () = let el = parse_ok {||} in Alcotest.(check string) "xml-stylesheet PI" "root" (fst el.tag) (* 16. Comments containing "--" are forbidden by XML 1.0 section 2.5. *) let test_comment_double_dash () = parse_err "" (* 17. Same story for comments that terminate as "--->" (the inner "--" is a forbidden double-dash, not part of the "-->" terminator). *) let test_comment_triple_dash_end () = parse_err "" (* 18. Attribute value with both quote types *) let test_attr_squote_with_dquote () = let el = parse_ok "
" in Alcotest.(check (option string)) "single-quoted with dquote" (Some "value with \"quotes\"") (Xml.Value.attr "x" el) (* 19. Attribute value with single quotes *) let test_attr_single_quotes () = let el = parse_ok "" in Alcotest.(check (option string)) "single-quoted attr" (Some "hello world") (Xml.Value.attr "x" el) (* 20. Empty attribute value *) let test_empty_attr_value () = let el = parse_ok {||} in Alcotest.(check (option string)) "empty attr" (Some "") (Xml.Value.attr "x" el) (* 21. Multiple CDATA sections in one element *) let test_multi_cdata () = let el = parse_ok "" in Alcotest.(check string) "multi CDATA text" "firstsecond" (Xml.Value.text el); Alcotest.(check int) "multi CDATA children" 2 (List.length el.children) (* 22. Whitespace-only text content *) let test_whitespace_only_text () = let el = parse_ok " " in Alcotest.(check string) "ws-only text" " " (Xml.Value.text el); Alcotest.(check int) "ws-only children" 1 (List.length el.children) (* 23. Element names with hyphens, dots, underscores *) let test_element_name_special_chars () = let el = parse_ok "" in Alcotest.(check string) "hyphen-dot-underscore tag" "my-elem.foo_bar" (fst el.tag) (* 24. Element names starting with underscore *) let test_element_name_underscore () = let el = parse_ok "<_private/>" in Alcotest.(check string) "underscore tag" "_private" (fst el.tag) (* 25. Namespace-prefixed names are kept as written, and resolve *) let test_namespace_prefix () = let el = parse_ok {||} in Alcotest.(check string) "ns tag" "ns:element" (fst el.tag); Alcotest.(check (option string)) "ns attr" (Some "val") (Xml.Value.attr ~ns:"urn:ns" "attr" el) (* 26. XML declaration with encoding *) let test_xml_decl_encoding () = let el = parse_ok {||} in Alcotest.(check string) "xml decl encoding" "root" (fst el.tag) (* 27. XML declaration with standalone *) let test_xml_decl_standalone () = let el = parse_ok {||} in Alcotest.(check string) "xml decl standalone" "root" (fst el.tag) (* 28. DOCTYPE skipped *) let test_doctype_system () = let el = parse_ok {||} in Alcotest.(check string) "DOCTYPE SYSTEM" "root" (fst el.tag) (* 29. DOCTYPE with internal subset skipped *) let test_doctype_internal_subset () = let el = parse_ok "]>" in Alcotest.(check string) "DOCTYPE internal subset" "root" (fst el.tag) (* -- Error cases (parser should return Error, not crash) ------------ *) (* 30. Unclosed element *) let test_err_unclosed_element () = parse_err "" (* 31. Mismatched tags *) let test_err_mismatched_tags () = parse_err "
" (* 32. Unclosed attribute *) let test_err_unclosed_attr () = parse_err {||} (* 34. Invalid character reference *) let test_err_invalid_char_ref () = parse_err "�" (* 35. Unknown entity reference *) let test_err_unknown_entity () = parse_err "&foo;" (* 36. Bare < in text *) let test_err_bare_lt () = parse_err "1 < 2" (* 37. Bare & in text *) let test_err_bare_amp () = parse_err "A & B" (* 38. Null byte in content: forbidden by XML 1.0 section 2.2. *) let test_null_byte_in_content () = parse_err "hel\x00lo" (* 39. Truncated CDATA *) let test_err_truncated_cdata () = parse_err "" in let _ = parse_ok "" in () (* 44. Content before root *) let test_err_content_before_root () = parse_err "hello" (* -- Codec edge cases ----------------------------------------------- *) (* 45. Decode with missing required attribute *) let test_codec_missing_required_attr () = decode_err point_codec {||} (* 46. Decode with missing required child *) let test_codec_missing_required_child () = decode_err person_codec "Alice" (* 47. Decode with extra unknown attributes -> Ok (ignore) *) let test_codec_extra_attrs () = let v = decode_ok point_codec {||} in Alcotest.(check string) "label" "test" v.label; Alcotest.(check (float 0.001)) "x" 1.5 v.x (* 48. Decode with extra unknown children -> Ok (ignore) *) let test_codec_extra_children () = let v = decode_ok person_codec "Alice30blah" in Alcotest.(check string) "name" "Alice" v.name; Alcotest.(check int) "age" 30 v.age (* 49. Int codec with non-numeric text *) let test_codec_int_non_numeric () = decode_err Xml.Codec.int "abc"; decode_err Xml.Codec.int "3.14"; decode_err Xml.Codec.int "" (* 50. Float codec with NaN and inf *) let test_codec_float_nan_inf () = let v_nan = decode_ok Xml.Codec.float "nan" in Alcotest.(check bool) "nan is nan" true (Float.is_nan v_nan); let v_inf = decode_ok Xml.Codec.float "inf" in Alcotest.(check bool) "inf is infinite" true (Float.is_infinite v_inf); Alcotest.(check bool) "inf is positive" true (v_inf > 0.0); let v_nan2 = decode_ok Xml.Codec.float "NaN" in Alcotest.(check bool) "NaN is nan" true (Float.is_nan v_nan2) (* 51. Bool codec with "1"/"0" vs "true"/"false" *) let test_codec_bool_values () = let t = decode_ok Xml.Codec.bool "true" in Alcotest.(check bool) "true" true t; let f = decode_ok Xml.Codec.bool "false" in Alcotest.(check bool) "false" false f; (* "1" and "0" are not accepted *) decode_err Xml.Codec.bool "1"; decode_err Xml.Codec.bool "0"; decode_err Xml.Codec.bool "yes"; decode_err Xml.Codec.bool "no" (* 52. Empty list codec -> no children *) let test_codec_empty_list () = let codec = Xml.Codec.(element "items" (list (element "item" int))) in let v = decode_ok codec "" in Alcotest.(check (list int)) "empty list" [] v; let encoded = Xml.to_string codec [] in let v2 = decode_ok codec encoded in Alcotest.(check (list int)) "empty list roundtrip" [] v2 (* 53. Nested record codecs (record inside record) *) type address = { street : string; city : string } type contact = { cname : string; addr : address } let address_codec = Xml.Codec.( element "address" El.( obj (fun street city -> { street; city }) |> child "street" string ~enc:(fun a -> a.street) |> child "city" string ~enc:(fun a -> a.city) |> finish)) let contact_codec = Xml.Codec.( element "contact" El.( obj (fun cname addr -> { cname; addr }) |> attr "name" Attr.string ~enc:(fun c -> c.cname) |> child "address" address_codec ~enc:(fun c -> c.addr) |> finish)) let test_codec_nested_record () = let xml = {|
123 MainNYC
|} in let v = decode_ok contact_codec xml in Alcotest.(check string) "cname" "Alice" v.cname; Alcotest.(check string) "street" "123 Main" v.addr.street; Alcotest.(check string) "city" "NYC" v.addr.city let test_codec_nested_record_roundtrip () = let c = { cname = "Bob"; addr = { street = "456 Oak"; city = "LA" } } in let encoded = Xml.to_string contact_codec c in let decoded = decode_ok contact_codec encoded in Alcotest.(check string) "cname rt" "Bob" decoded.cname; Alcotest.(check string) "street rt" "456 Oak" decoded.addr.street; Alcotest.(check string) "city rt" "LA" decoded.addr.city (* 54. Codec roundtrip with special characters in values *) let test_codec_special_chars_roundtrip () = let codec = Xml.Codec.element "msg" Xml.Codec.string in let test_val s = let encoded = Xml.to_string codec s in let decoded = decode_ok codec encoded in Alcotest.(check string) (Fmt.str "roundtrip %S" s) s decoded in test_val "hello & world"; test_val "a < b > c"; test_val "quotes: \"double\" and 'single'"; test_val "mixed: &"; test_val "newlines\nand\ttabs" (* Additional roundtrip: codec with special chars in attributes *) let test_attr_special_chars_rt () = let p = { x = 1.0; y = 2.0; label = "a&bd\"e" } in let encoded = Xml.to_string point_codec p in let decoded = decode_ok point_codec encoded in Alcotest.(check string) "special label roundtrip" "a&bd\"e" decoded.label (* Additional: roundtrip with complex mixed content at tree level *) let test_tree_roundtrip_mixed () = let el : Xml.Value.t = Xml.Value.element "doc" ~attrs:(Xml.Value.attrs [ ("a", "x&y"); ("b", "<>\"'") ]) ~children: [ Xml.Value.Text ("before ", Xml.Meta.none); Xml.Value.Element (Xml.Value.element "em" ~children:[ Xml.Value.Text ("middle", Xml.Meta.none) ]); Xml.Value.Text (" after", Xml.Meta.none); ] in let s = Xml.Value.to_string el in let el2 = parse_ok s in Alcotest.(check string) "tag preserved" "doc" (fst el2.tag); Alcotest.(check (option string)) "attr a preserved" (Some "x&y") (Xml.Value.attr "a" el2); Alcotest.(check (option string)) "attr b preserved" (Some "<>\"'") (Xml.Value.attr "b" el2); Alcotest.(check int) "children count" 3 (List.length el2.children) (* Additional: tree-level roundtrip of large XML *) let test_tree_roundtrip_large () = let n = 500 in let children = List.init n (fun i -> let tag = "item" ^ string_of_int i in Xml.Value.Element (Xml.Value.element tag ~attrs:(Xml.Value.attrs [ ("id", string_of_int i) ]) ~children:[ Xml.Value.Text (string_of_int (i * i), Xml.Meta.none) ])) in let el : Xml.Value.t = Xml.Value.element "root" ~children in let s = Xml.Value.to_string el in let el2 = parse_ok s in let s2 = Xml.Value.to_string el2 in Alcotest.(check string) "large roundtrip" s s2 (* -- Query / Update / Introspection tests --------------------------- *) (* get_child: extract a child element by tag *) let test_get_child () = let codec = Xml.Codec.child "name" Xml.Codec.string in let v = decode_ok codec "Alice30" in Alcotest.(check string) "get_child name" "Alice" v let test_get_child_int () = let codec = Xml.Codec.child "age" Xml.Codec.int in let v = decode_ok codec "Alice30" in Alcotest.(check int) "get_child age" 30 v let test_get_child_nested () = let codec = Xml.Codec.child "config" (Xml.Codec.child "host" Xml.Codec.string) in let v = decode_ok codec "localhost8080" in Alcotest.(check string) "get_child nested" "localhost" v let test_get_child_missing () = let codec = Xml.Codec.child "email" Xml.Codec.string in decode_err codec "Alice" (* get_attr: extract an attribute value *) let test_get_attr () = let codec = Xml.Codec.attr "name" in let v = decode_ok codec {||} in Alcotest.(check string) "get_attr name" "Alice" v let test_get_attr_second () = let codec = Xml.Codec.attr "age" in let v = decode_ok codec {||} in Alcotest.(check string) "get_attr age" "30" v let test_get_attr_missing () = let codec = Xml.Codec.attr "email" in decode_err codec {||} (* nth: extract the nth child element *) let test_get_nth () = let codec = Xml.Codec.nth 1 Xml.Codec.string in let v = decode_ok codec "
firstsecondthird
" in Alcotest.(check string) "nth 1" "second" v let test_get_nth_first () = let codec = Xml.Codec.nth 0 Xml.Codec.int in let v = decode_ok codec "102030" in Alcotest.(check int) "nth 0" 10 v let test_get_nth_last () = let codec = Xml.Codec.nth 2 Xml.Codec.string in let v = decode_ok codec "xyz" in Alcotest.(check string) "nth 2" "z" v let test_get_nth_oob () = let codec = Xml.Codec.nth 5 Xml.Codec.string in decode_err codec "x" (* kind: introspection *) let test_kind_string () = Alcotest.(check string) "kind string" "string" (Xml.Codec.kind Xml.Codec.string) let test_kind_int () = Alcotest.(check string) "kind int" "int" (Xml.Codec.kind Xml.Codec.int) let test_kind_float () = Alcotest.(check string) "kind float" "float" (Xml.Codec.kind Xml.Codec.float) let test_kind_bool () = Alcotest.(check string) "kind bool" "bool" (Xml.Codec.kind Xml.Codec.bool) let test_kind_element () = let codec = Xml.Codec.element "foo" Xml.Codec.string in let k = Xml.Codec.kind codec in Alcotest.(check bool) "kind element contains foo" true (let idx = try String.index k 'f' with Not_found -> -1 in idx >= 0) let test_kind_list () = let codec = Xml.Codec.list Xml.Codec.int in let k = Xml.Codec.kind codec in Alcotest.(check bool) "kind list contains list" true (String.length k > 0 && k <> "") let test_kind_option () = let codec = Xml.Codec.option Xml.Codec.string in let k = Xml.Codec.kind codec in Alcotest.(check string) "kind option" "optional string" k (* -- Test suite ------------------------------------------------------- *) (* {1 UTF-8 handling} *) let string_elem = Xml.Codec.(element "v" string) let test_utf8_multibyte_text () = (* Multi-byte UTF-8 passes through XML text content unchanged. *) let xml = "café 世界 héllo" in match Xml.of_string string_elem xml with | Ok s -> Alcotest.(check string) "text" "café 世界 héllo" s | Error e -> Alcotest.failf "decode failed: %a" Xml.Error.pp e let test_utf8_bom_stripped () = (* UTF-8 BOM (EF BB BF) at the start must be silently stripped per XML 1.0 section F. Otherwise the parser would see it as part of the first token and fail. *) let xml = "\xEF\xBB\xBFhello" in match Xml.of_string string_elem xml with | Ok s -> Alcotest.(check string) "text" "hello" s | Error e -> Alcotest.failf "decode failed: %a" Xml.Error.pp e (* Slice lengths to read a BOM-prefixed document at: the three BOM bytes arriving one, two, three and four at a time, plus whatever the reader picks for itself. *) let bom_slices = [ ("default", None); ("1", Some 1); ("2", Some 2); ("3", Some 3); ("4", Some 4); ] (* XML 1.0 (5th ed.) section F.1: a BOM at the head of an entity is an encoding signature, not document content, so it is removed before parsing -- and that is a statement about the bytes, not about how they were delivered. Bytesrw promises nothing about slice length, so the three BOM bytes can arrive one refill at a time from a file read through a small buffer, a socket, or a decompressor. A stripper that decides on whatever the first refill happened to hand it leaves the tail of the BOM in front of the first token, and the parser reports [expected "<"]. Every slice length must yield the same document. *) let test_utf8_bom_stripped_any_slice () = let xml = "\xEF\xBB\xBFhello" in List.iter (fun (name, slice_length) -> let r = Bytesrw.Bytes.Reader.of_string ?slice_length xml in match Xml.of_reader string_elem r with | Ok s -> Alcotest.(check string) name "hello" s | Error e -> Alcotest.failf "%s: decode failed: %a" name Xml.Error.pp e) bom_slices (* The same, through the tree parser: [Value.of_reader] and the codec's [of_reader] share one stream, and a BOM split across refills must reach neither. *) let test_utf8_bom_stripped_any_slice_value () = let xml = "\xEF\xBB\xBF" in List.iter (fun (name, slice_length) -> let r = Bytesrw.Bytes.Reader.of_string ?slice_length xml in match Xml.Value.of_reader r with | Ok el -> Alcotest.(check string) name "r" (fst el.tag) | Error e -> Alcotest.failf "%s: parse failed: %a" name Xml.Error.pp e) bom_slices let test_utf8_invalid_bytes () = (* Lone continuation byte \xC3 without the required continuation must be rejected as malformed UTF-8 per XML 1.0 section 4.3.3. *) let xml = "\xC3" in match Xml.of_string string_elem xml with | Error err -> let msg = Xml.Error.to_string err in if not (String.length msg > 0) then Alcotest.fail "empty error message" | Ok _ -> Alcotest.fail "expected error for malformed UTF-8" (* The reader-based [decode] must validate UTF-8 incrementally, not by buffering the whole input. This fixture just exercises the reader path; correctness follows from decode going through the same [check_stream_utf8] as [decode_string]. *) let test_utf8_invalid_bytes_reader () = let xml = "\xC3" in let reader = Bytesrw.Bytes.Reader.of_string xml in match Xml.of_reader string_elem reader with | Error err -> let msg = Xml.Error.to_string err in if not (String.length msg > 0) then Alcotest.fail "empty error message" | Ok _ -> Alcotest.fail "expected error for malformed UTF-8 via reader" let test_utf8_bad_bytes_reader () = let xml = "\xC3" in let reader = Bytesrw.Bytes.Reader.of_string xml in match Xml.Value.of_reader reader with | Error _ -> () | Ok _ -> Alcotest.fail "expected error for malformed UTF-8 via Value.of_reader" (* A serializer must not manufacture malformed XML from an ordinary OCaml string. NUL and other C0 controls are forbidden by XML 1.0 section 2.2; invalid UTF-8 is forbidden by section 4.3.3. *) let test_encode_rejects_forbidden_char () = let codec = Xml.Codec.element "v" Xml.Codec.string in match Xml.to_string codec "has\x00nul" with | s -> Alcotest.failf "encoded forbidden char, got: %S" s | exception Xml.Invalid_xml_char _ -> () (* The exception's byte offset must be the FIRST byte of the offending sequence/codepoint. *) let test_encode_bad_utf8_offset () = let codec = Xml.Codec.element "v" Xml.Codec.string in match Xml.to_string codec "ok \xC3rest" with | _ -> Alcotest.fail "expected Invalid_xml_char" | exception Xml.Invalid_xml_char i -> Alcotest.(check int) "offset at malformed byte" 3 i let test_encode_bad_char_offset () = let codec = Xml.Codec.element "v" Xml.Codec.string in match Xml.to_string codec "ab\x00cd" with | _ -> Alcotest.fail "expected Invalid_xml_char" | exception Xml.Invalid_xml_char i -> Alcotest.(check int) "NUL at offset 2" 2 i let test_encode_rejects_invalid_utf8 () = let codec = Xml.Codec.element "v" Xml.Codec.string in match Xml.to_string codec "\xC3" with | s -> Alcotest.failf "encoded invalid UTF-8, got: %S" s | exception Xml.Invalid_xml_char _ -> () let string_contains msg sub = Re.execp Re.(compile (str sub)) msg (* Errors now carry Loc-formatted line/column info; verify that a syntax error on line 3 mentions line 3, not just a byte offset. *) let test_error_message_includes_line () = (* A digit as an element name-start is illegal XML; the parser's parse_name fails with err_expected_at, which now formats the location via Loc.pp_ocaml (mentions the line number). *) let xml = "\n \n <1bad/>\n \n" in match Xml.Value.of_string xml with | Ok _ -> Alcotest.fail "expected parse error" | Error err -> let msg = Xml.Error.to_string err in Alcotest.(check bool) "error includes a line number" true (string_contains msg "line") let test_encode_attr_bad_char () = let codec = Xml.Codec.( element "v" El.(obj (fun v -> v) |> attr "x" Attr.string ~enc:Fun.id |> finish)) in match Xml.to_string codec "a\x01b" with | s -> Alcotest.failf "encoded forbidden attr char, got: %S" s | exception Xml.Invalid_xml_char _ -> () let test_utf8_numeric_char_ref () = (* Character references like 世界 should produce the UTF-8 encoding of the referenced Unicode scalars (U+4E16 U+754C). *) let xml = "世界" in match Xml.of_string string_elem xml with | Ok s -> Alcotest.(check string) "char ref" "世界" s | Error e -> Alcotest.failf "decode failed: %a" Xml.Error.pp e