-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathjuicy_test.exs
97 lines (78 loc) · 2.82 KB
/
juicy_test.exs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
defmodule JuicyTest.TestStruct do
defstruct some: nil, thing: nil
end
defmodule JuicyTest do
use ExUnit.Case
doctest Juicy
def p(binary), do: Juicy.parse(binary)
test "empty objects" do
assert p("{}") == {:ok, %{}}
assert p("[]") == {:ok, []}
end
test "basic strings" do
assert p(~s(["woo", "hoo"])) == {:ok, ["woo", "hoo"]}
end
test "character escapes" do
input = ~s(["\\"", "\\\\", "\/", "\\b", "\\f", "\\n", "\\r", "\\t"])
output = {:ok, ["\"", "\\", "/", "\b", "\f", "\n", "\r", "\t"]}
assert p(input) == output
end
test "unicode escapes" do
input = ~s(["\\u00E5"])
output = {:ok, ["\u00E5"]}
assert p(input) == output
end
test "integers" do
assert p("[1, -1, 9999]") == {:ok, [1, -1, 9999]}
end
test "floats" do
assert p("[1.0, 1.0e0, -1e-1]") == {:ok, [1.0, 1.0, -0.1]}
end
test "large integers" do
input = ~s([9999999999999999999999999999999999999999])
output = {:ok, [9999999999999999999999999999999999999999]}
assert p(input) == output
end
test "match spec validation" do
assert :ok == Juicy.validate_spec({:map, [], {:any, []}})
assert :ok == Juicy.validate_spec({:map, [], {:any, [stream: true]}})
assert :ok == Juicy.validate_spec({:map_keys, [], %{"a" => {:any, []}}})
assert :ok == Juicy.validate_spec({:map, [atom_keys: [:some]], {:any, []}})
assert :error == Juicy.validate_spec(nil)
assert :error == Juicy.validate_spec({:abc, [], {:any, []}})
assert :error == Juicy.validate_spec({:map_keys, [], %{0 => {:any, []}}})
end
test "basic stream" do
input = ["{\"w", "oo\":", " [12, 2", "3, 34]}"]
spec = {:map, [stream: true], {:array, [], {:any, [stream: true]}}}
out = Juicy.parse_stream(input, spec) |> Enum.into([])
assert out == [
{:yield, {["woo", 0], 12}},
{:yield, {["woo", 1], 23}},
{:yield, {["woo", 2], 34}},
{:yield, {[], %{"woo" => [:streamed, :streamed, :streamed]}}},
:finished,
]
end
test "early end of input stream" do
input = ["{"]
spec = {:any, []}
out = Juicy.parse_stream(input, spec) |> Enum.into([])
assert out == [error: :early_eoi]
end
test "json parsing with simple spec" do
input = ~s({"a": 0, "b": 1})
spec = {:map, [atom_keys: [:a, :b]], {:any, []}}
out = Juicy.parse_spec(input, spec)
assert out == {:ok, %{a: 0, b: 1}}
end
test "json parsing into struct with spec" do
input = ~s([{"some": 0, "thing": 1}, {"some": 2, "thing": 3, "else": 4}])
spec = {:array, [], {:map, [atom_keys: [:some, :thing], struct_atom: JuicyTest.TestStruct, ignore_non_atoms: true], {:any, []}}}
out = Juicy.parse_spec(input, spec)
assert out == {:ok, [
%JuicyTest.TestStruct{some: 0, thing: 1},
%JuicyTest.TestStruct{some: 2, thing: 3},
]}
end
end