aboutsummaryrefslogtreecommitdiff
path: root/spec/practical
diff options
context:
space:
mode:
Diffstat (limited to 'spec/practical')
-rw-r--r--spec/practical/json_spec.cr60
1 files changed, 48 insertions, 12 deletions
diff --git a/spec/practical/json_spec.cr b/spec/practical/json_spec.cr
index 0b85658..7373d91 100644
--- a/spec/practical/json_spec.cr
+++ b/spec/practical/json_spec.cr
@@ -2,23 +2,35 @@ require "../spec_helper"
include Parcom
-# defining my own JSON alias in case of strange interactions
-# with the built-in type
-alias JSONValue = Nil \
- | Bool \
- | Int64 \
- | Float64 \
- | String \
- | Array(JSONValue) \
- | Hash(String, JSONValue)
+alias JSONType = Nil \
+ | Bool \
+ | Int64 \
+ | Float64 \
+ | String \
+ | Array(JSONValue) \
+ | Hash(String, JSONValue)
+
+class JSONValue
+ property data : JSONType
+
+ def initialize(@data)
+ end
+end
def json_null
- Parser.token_sequence("null".chars).map { |_| nil.as(JSONValue) }
+ Parser.token_sequence("null".chars).map { |_| JSONValue.new(nil) }
+end
+
+def json_bool
+ t = Parser.token_sequence("true".chars).map { |_| JSONValue.new(true) }
+ f = Parser.token_sequence("false".chars).map { |_| JSONValue.new(false) }
+ t | f
end
def json_value : Parser(Char, JSONValue)
Parser.first_of([
json_null,
+ json_bool,
])
end
@@ -26,17 +38,41 @@ describe "example: JSON parsing" do
describe "json_null" do
it "parses the string 'null' and returns nil when successful" do
result = json_null.parse(Tokens.from_string("null"))
- result.value.should be_nil
+ result.value.data.should be_nil
result.tokens.empty?.should be_true
expect_raises(ParserFail) { json_null.parse(Tokens.from_string("")) }
end
end
+ describe "json_bool" do
+ it "parses the strings 'true' or 'false' and returns bool" do
+ result = json_bool.parse(Tokens.from_string("true"))
+ result.value.data.should be_true
+ result.tokens.empty?.should be_true
+
+ result = json_bool.parse(Tokens.from_string("false"))
+ result.value.data.should be_false
+ result.tokens.empty?.should be_true
+
+ expect_raises(ParserFail) { json_bool.parse(Tokens.from_string("")) }
+ end
+ end
+
describe "json_value" do
it "parses null" do
result = json_value.parse(Tokens.from_string("null"))
- result.value.should be_nil
+ result.value.data.should be_nil
+ result.tokens.empty?.should be_true
+ end
+
+ it "parses bools" do
+ result = json_value.parse(Tokens.from_string("true"))
+ result.value.data.should be_true
+ result.tokens.empty?.should be_true
+
+ result = json_value.parse(Tokens.from_string("false"))
+ result.value.data.should be_false
result.tokens.empty?.should be_true
end
end