-
Notifications
You must be signed in to change notification settings - Fork 8
/
json.bats
3248 lines (2767 loc) · 124 KB
/
json.bats
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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env bats
# shellcheck shell=bash
set -u -o pipefail
bats_require_minimum_version 1.5.0
load json.bash
TIMEOUT_SECONDS=1
if [[ ${CI:-false} == true ]]; then
TIMEOUT_SECONDS=60
fi
# Always use grep, otherwise errors will be different on systems with ggrep.
export JSON_BASH_GREP=grep
setup() {
cd "${BATS_TEST_DIRNAME:?}"
}
function mktemp_bats() {
mktemp "${BATS_RUN_TMPDIR:?}/json.bats.XXX" "$@"
}
@test "json.buffer_output :: out stream :: in args" {
[[ $(json.buffer_output foo) == "foo" ]]
[[ $(json.buffer_output foo "bar baz" $'boz\n123') == $'foobar bazboz\n123' ]]
}
@test "json.buffer_output :: out stream :: in array" {
local input=(foo)
[[ $(in=input json.buffer_output) == "foo" ]]
input=(foo "bar baz" $'boz\n123')
[[ $(in=input json.buffer_output) == $'foobar bazboz\n123' ]]
}
@test "json.buffer_output :: out array :: in array" {
local buff input=()
out=buff in=input json.buffer_output
[[ ${#buff[@]} == 0 ]]
input=(foo)
out=buff in=input json.buffer_output
[[ ${#buff[@]} == 1 && ${buff[0]} == "foo" ]]
input=("bar baz" $'boz\n123')
out=buff in=input json.buffer_output
[[ ${#buff[@]} == 3 && ${buff[0]} == "foo" && ${buff[1]} == "bar baz" \
&& ${buff[2]} == $'boz\n123' ]]
}
@test "json.buffer_output :: out array :: in args" {
local buff input=()
out=buff json.buffer_output "foo"
[[ ${#buff[@]} == 1 && ${buff[0]} == "foo" ]]
out=buff json.buffer_output "bar baz" $'boz\n123'
[[ ${#buff[@]} == 3 && ${buff[0]} == "foo" && ${buff[1]} == "bar baz" \
&& ${buff[2]} == $'boz\n123' ]]
}
@test "json.buffer_output :: errors" {
local buff
# in=arrayname must be set when 0 args are passed. Explicitly calling with 0
# args is a no-op, and when calling with dynamic args an array ref should be
# used for efficiency.
run json.buffer_output
[[ $status == 1 \
&& $output == *"in: in= must be set when no positional args are given" ]]
out=buff run json.buffer_output
[[ $status == 1 \
&& $output == *"in: in= must be set when no positional args are given" ]]
}
@test "json.encode_string" {
run json.encode_string
[[ $status == 1 \
&& $output == *"in: in= must be set when no positional args are given" ]]
join=,
[[ $(json.encode_string "") == '""' ]]
[[ $(json.encode_string foo) == '"foo"' ]]
[[ $(json.encode_string foo $'bar\nbaz\tboz\n') == '"foo","bar\nbaz\tboz\n"' ]]
[[ $(join=$'\n' json.encode_string foo $'bar\nbaz\tboz\n') \
== $'"foo"\n"bar\\nbaz\\tboz\\n"' ]]
local buff=()
empty=()
out=buff in=empty json.encode_string
[[ ${buff[*]} == "" ]]
buff=()
out=buff json.encode_string ""
[[ ${#buff[@]} == 1 && ${buff[0]} == '""' ]]
out=buff json.encode_string "foo"
[[ ${#buff[@]} == 2 && ${buff[0]} == '""' && ${buff[1]} == '"foo"' ]]
out=buff join= json.encode_string $'bar\nbaz' boz
[[ ${#buff[@]} == 4 && ${buff[0]} == '""' && ${buff[1]} == '"foo"' \
&& ${buff[2]} == $'"bar\\nbaz"' && ${buff[3]} == '"boz"' ]]
out=buff join=, json.encode_string abc def
[[ ${#buff[@]} == 5 && ${buff[4]} == '"abc","def"' ]]
local input=()
in=input run json.encode_string
[[ $status == 0 && $output == '' ]]
input=(foo $'bar\nbaz\tboz\n')
[[ $(in=input json.encode_string) == '"foo","bar\nbaz\tboz\n"' ]]
}
# A string containing all bytes (other than 0, which bash can't hold in vars)
function all_bytes() {
python3 -c 'print("".join(chr(c) for c in range(1, 256)))'
}
# Verify that the first arg is a JSON string containing bytes 1..255 inclusive
function assert_is_all_bytes_json() {
all_bytes_json="${1:?}" python3 <<< '
import json, os
actual = json.loads(os.environ["all_bytes_json"])
expected = "".join(chr(c) for c in range(1, 256))
if actual != expected:
raise AssertionError(
f"Decoded JSON chars did not match:\n {actual=!r}\n{expected=!r}"
)
'
}
@test "json.encode_string :: all bytes (other than zero)" {
# Check we can encode all bytes (other than 0, which bash can't hold in vars)
bytes=$(all_bytes)
# json.encode_string has 3 code paths which we need to test:
# 1. single strings
all_bytes_json=$(json.encode_string "${bytes:?}")
assert_is_all_bytes_json "${all_bytes_json:?}"
# 2. multiple strings with un-joined output
buff=()
out=buff json.encode_string "${bytes:?}" "${bytes:?}"
assert_is_all_bytes_json "${buff[0]:?}"
assert_is_all_bytes_json "${buff[1]:?}"
[[ ${#buff[@]} == 2 ]]
# 3. multiple strings with joined output
output=$(join=, json.encode_string "${bytes:?}" "${bytes:?}")
[[ $output == "${buff[0]},${buff[1]}" ]]
}
@test "json.encode_number" {
local buff input join
run json.encode_number
[[ $status == 1 \
&& $output == *"in: in= must be set when no positional args are given" ]]
run json.encode_number ''
[[ $status == 1 && $output == *"not all inputs are numbers: ''" ]]
input=('')
in=input run json.encode_number
[[ $status == 1 && $output == *"not all inputs are numbers: ''" ]]
input=()
in=input run json.encode_number
[[ $status == 0 && $output == '' ]]
join=,
[[ $(json.encode_number 42) == "42" ]]
[[ $(json.encode_number -1.34e+4 2.1e-4 2e6) == "-1.34e+4,2.1e-4,2e6" ]]
input=(-1.34e+4 2.1e-4 2e6)
[[ $(in=input json.encode_number) == "-1.34e+4,2.1e-4,2e6" ]]
run json.encode_number foo bar
[[ $status == 1 ]]
[[ $output == "json.encode_number(): not all inputs are numbers: 'foo' 'bar'" ]]
run json.encode_bool 42,42
[[ $status == 1 ]]
buff=()
out=buff join= json.encode_number 1
out=buff join= json.encode_number 2 3
out=buff join=$'\n' json.encode_number 4 5
[[ ${#buff[@]} == 4 && ${buff[0]} == '1' && ${buff[1]} == '2' \
&& ${buff[2]} == '3' && ${buff[3]} == $'4\n5' ]]
}
@test "json.encode_bool" {
local buff input join
run json.encode_bool
[[ $status == 1 \
&& $output == *"in: in= must be set when no positional args are given" ]]
input=()
in=input run json.encode_bool
[[ $status == 0 && $output == '' ]]
join=,
[[ $(json.encode_bool true) == "true" ]]
[[ $(json.encode_bool false) == "false" ]]
[[ $(json.encode_bool false true) == "false,true" ]]
input=(false true)
[[ $(in=input json.encode_bool) == "false,true" ]]
run json.encode_bool foo bar
[[ $status == 1 ]]
[[ $output == "json.encode_bool(): not all inputs are bools: 'foo' 'bar'" ]]
run json.encode_bool true,true
[[ $status == 1 ]]
buff=()
out=buff join= json.encode_bool true
out=buff join= json.encode_bool false true
out=buff join=$'\n' json.encode_bool true false
[[ ${#buff[@]} == 4 && ${buff[0]} == 'true' && ${buff[1]} == 'false' \
&& ${buff[2]} == 'true' && ${buff[3]} == $'true\nfalse' ]]
}
@test "json.encode_null" {
local buff input join
run json.encode_null
[[ $status == 1 \
&& $output == *"in: in= must be set when no positional args are given" ]]
input=()
in=input run json.encode_null
[[ $status == 0 && $output == '' ]]
join=,
[[ $(json.encode_null null) == "null" ]]
[[ $(json.encode_null null null) == "null,null" ]]
input=(null null)
[[ $(in=input json.encode_null) == "null,null" ]]
run json.encode_null foo bar
[[ $status == 1 ]]
[[ $output == "json.encode_null(): not all inputs are null: 'foo' 'bar'" ]]
run json.encode_null null,null
[[ $status == 1 ]]
buff=()
out=buff join= json.encode_null null
out=buff join= json.encode_null null null
out=buff join=$'\n' json.encode_auto null null
[[ ${#buff[@]} == 4 && ${buff[0]} == 'null' && ${buff[1]} == 'null' \
&& ${buff[2]} == 'null' && ${buff[3]} == $'null\nnull' ]]
}
@test "json.encode_auto" {
local buff input join
run json.encode_auto
[[ $status == 1 \
&& $output == *"in: in= must be set when no positional args are given" ]]
input=()
in=input run json.encode_auto
[[ $status == 0 && $output == '' ]]
join=,
[[ $(json.encode_auto 42) == '42' ]]
[[ $(json.encode_auto hi) == '"hi"' ]]
[[ $(json.encode_auto true) == 'true' ]]
[[ $(json.encode_auto true hi 42) == 'true,"hi",42' ]]
[[ $(json.encode_auto true,false foo bar 42) == '"true,false","foo","bar",42' ]]
[[ $(json.encode_auto '"42') == '"\"42"' ]]
[[ $(json.encode_auto ',"42') == '",\"42"' ]]
[[ $(json.encode_auto foo '"42' foo '"42') == '"foo","\"42","foo","\"42"' ]]
[[ $(json.encode_auto foo ',"42' foo ',"42') == '"foo",",\"42","foo",",\"42"' ]]
input=(foo ',"42' foo ',"42')
[[ $(in=input json.encode_auto) == '"foo",",\"42","foo",",\"42"' ]]
buff=()
out=buff join= json.encode_auto null
out=buff join= json.encode_auto hi 42
out=buff join=$'\n' json.encode_auto abc true
[[ ${#buff[@]} == 4 && ${buff[0]} == 'null' && ${buff[1]} == '"hi"' \
&& ${buff[2]} == '42' && ${buff[3]} == $'"abc"\ntrue' ]]
}
@test "json.encode_raw" {
local buff join input
run json.encode_raw
[[ $status == 1 \
&& $output == *"in: in= must be set when no positional args are given" ]]
input=()
in=input run json.encode_raw
[[ $status == 0 && $output == '' ]]
join=,
[[ $(json.encode_raw '{}') == '{}' ]]
# invalid JSON is not checked/detected
[[ $(json.encode_raw '}') == '}' ]]
[[ $(json.encode_raw '[]' '{}') == '[],{}' ]]
input=('[]' '{}')
[[ $(in=input json.encode_raw) == '[],{}' ]]
run json.encode_raw ''
echo $output >&2
[[ $status == 1 ]]
[[ $output =~ "raw JSON value is empty" ]]
buff=()
out=buff join= json.encode_raw 1
out=buff join= json.encode_raw 2 3
out=buff join=$'\n' json.encode_raw 4 5
declare -p buff
[[ ${#buff[@]} == 4 && ${buff[0]} == '1' && ${buff[1]} == '2' \
&& ${buff[2]} == '3' && ${buff[3]} == $'4\n5' ]]
}
@test "json.encode_json :: in must be set with no args" {
run json.encode_json
[[ $status == 1 \
&& $output == *"in: in= must be set when no positional args are given" ]]
}
@test "json.encode_json" {
local join=','
[[ $(json.encode_json '{}') == '{}' ]]
[[ $(json.encode_json '{"foo":["bar","baz"]}') == '{"foo":["bar","baz"]}' ]]
[[ $(json.encode_json '[123]') == '[123]' ]]
[[ $(json.encode_json '"hi"') == '"hi"' ]]
[[ $(json.encode_json '-1.34e+4') == '-1.34e+4' ]]
[[ $(json.encode_json 'true') == 'true' ]]
[[ $(json.encode_json 'null') == 'null' ]]
[[ $(json.encode_json '{"a":1}' '{"b":2}') == '{"a":1},{"b":2}' ]]
join=''
[[ $(json.encode_json 'true' '42') == 'true42' ]]
local buff=() input=()
out=buff in=input json.encode_json
[[ ${#buff[@]} == 0 ]]
input=(42 '"hi"')
out=buff in=input json.encode_json
[[ ${#buff[@]} == 2 && ${buff[0]} == '42' && ${buff[1]} == '"hi"' ]]
join=','
out=buff in=input json.encode_json
declare -p buff
[[ ${#buff[@]} == 3 && ${buff[0]} == '42' && ${buff[1]} == '"hi"' \
&& ${buff[2]} == '42,"hi"' ]]
}
@test "json.encode_json :: recognises valid JSON with insignificant whitespace" {
local buff
out=buff json.encode_json ' { "foo" : [ "bar" , 42 ] , "baz" : true } '
[[ ${#buff[@]} == 1 \
&& ${buff[0]} == ' { "foo" : [ "bar" , 42 ] , "baz" : true } ' ]]
}
@test "json.encode_json :: rejects invalid JSON" {
invalid_json=('{:}' ' ' '[' '{' '"foo' '[true false]')
for invalid in "${invalid_json[@]:?}"; do
run json.encode_json ''
[[ $status == 1 \
&& $output == *"json.encode_json(): not all inputs are valid JSON:"* ]]
run json.encode_json "${invalid:?}"
[[ $status == 1 \
&& $output == *"json.encode_json(): not all inputs are valid JSON:"* ]]
run json.encode_json '"ok"' "${invalid:?}"
[[ $status == 1 \
&& $output == *"json.encode_json(): not all inputs are valid JSON:"* ]]
run json.encode_json "${invalid:?}" '"ok"'
[[ $status == 1 \
&& $output == *"json.encode_json(): not all inputs are valid JSON:"* ]]
local -i tests+=4
done
(( ${tests:?} == 4 * 6 ))
}
@test "json.encode_object_entries_from_attrs" {
local attrs=() expected
for prefix in '' '"foo",'; do
attrs=()
in=attrs type=string run json.encode_object_entries_from_attrs
[[ $status == 10 && $output == '' ]]
attrs=('' '')
in=attrs type=string run json.encode_object_entries_from_attrs
[[ $status == 11 && $output == '' ]]
attrs=('a=1,b=2' 'c=3')
in=attrs type=string run json.encode_object_entries_from_attrs
[[ $status == 0 && $output == "${prefix?}"'"a":"1","b":"2","c":"3"' ]]
# type defines entry value type
attrs=('a=1,b=2' 'c=3')
in=attrs type=number run json.encode_object_entries_from_attrs
[[ $status == 0 && $output == "${prefix?}"'"a":1,"b":2,"c":3' ]]
# entries can be passed via args
type=string run json.encode_object_entries_from_attrs 'a=1,b=2' 'c=3'
[[ $status == 0 && $output == "${prefix?}"'"a":"1","b":"2","c":"3"' ]]
done
# optimisation: the fn can avoid escaping inputs if split is set. The
# assumption is that input chunks were split on $split, so the split char
# can't occur in in the input. If split isn't used \x10 is escaped and then
# used as a separator when parsing attrs.
attrs=($'a=1\x102,b=2' 'c=3')
split=$'\n' in=attrs type=string run json.encode_object_entries_from_attrs
[[ $status == 0 && $output == "${prefix?}"'"a":"1\u00102","b":"2","c":"3"' ]]
}
@test "json.encode_object_entries_from_attrs :: errors" {
run json.encode_object_entries_from_attrs
[[ $status == 1 && $output == *"\$type must be provided"* ]]
type=string run json.encode_object_entries_from_attrs
[[ $status == 1 && $output == *'$in must be set if arguments are not provided' ]]
# attribute values encode as the stated type
local entries=('a=foo')
type=number in=entries run json.encode_object_entries_from_attrs
[[ $status == 1 && $output == "json.encode_number(): not all inputs are numbers: 'foo'" ]]
}
function assert_encode_object_entries_from_json() {
local status expected_status=${status:-0} prefix=${prefix:-}
printf -v expected_str '%s' "${expected[@]}"
type=${type:?} in=${in:?} prefix=${prefix?} run json.encode_object_entries_from_json
[[ $expected_status == "$status" && $expected_str == "$output" ]] || {
echo "type=${type@Q} in=${in@Q} entries=${entries[@]@Q}" >&2
echo "[[ ${expected_status@Q} == ${status@Q} && ${expected_str@Q} == ${output@Q} ]]" >&2
return 1
}
local buff=() status=0
type=${type:?} in=${in:?} out=buff prefix=${prefix?} json.encode_object_entries_from_json || status=$?
[[ $expected_status == $status ]]
assert_array_equals expected buff
}
@test "json.encode_object_entries_from_json" {
local entries=() expected
for prefix in '' '"foo",'; do
# No entries produce no outputs (specifically, no empty string output)
entries=() expected=()
status=10 type=string in=entries assert_encode_object_entries_from_json
# Only empty objects also produce no outputs
entries=('{}' '{ }' $' \t\n\r { \t\n\r } \t\n\r ') expected=()
status=11 type=string in=entries assert_encode_object_entries_from_json
entries=('{"a":"x"}' '{}' '{"b":"y","c":"z"}') expected=($prefix '"a":"x","b":"y","c":"z"')
type=string in=entries assert_encode_object_entries_from_json
entries=('{}' '{"a":[{"x":true}]}' '{}' '{"b":42,"c":false}' '{}')
expected=($prefix '"a":[{"x":true}],"b":42,"c":false')
type=json in=entries assert_encode_object_entries_from_json
done
}
@test "json.encode_object_entries_from_json :: non-errors" {
# pre-encoded entries of type raw are not validated. But the braces surrounding
# entries are still removed, and empty values ignored without introducing commas
local entries=('"a":null}' '' '"b":1' '{"foo":"bar"')
type=raw in=entries json.encode_object_entries_from_json
[[ $(type=raw in=entries json.encode_object_entries_from_json) \
== '"a":null,"b":1,"foo":"bar"' ]]
}
@test "json.encode_object_entries_from_json :: errors" {
run json.encode_object_entries_from_json
[[ $status == 1 && $output == *"\$type must be provided"* ]]
type=string run json.encode_object_entries_from_json
[[ $status == 1 && $output == *'$in must be set if arguments are not provided' ]]
# pre-encoded entries must be of the stated type
local entries=('{"a":null}')
type=string in=entries run json.encode_object_entries_from_json
[[ $status == 1 && $output == "json.encode_object_entries_from_json(): provided entries \
are not all valid JSON objects with 'string' values." ]]
}
@test "json.encode_object_entries" {
for prefix in '' '"foo",'; do
[[ $(type=string json.encode_object_entries 'a b' '1 2' c d) == "$prefix"'"a b":"1 2","c":"d"' ]]
[[ $(type=number json.encode_object_entries a 1 c 2) == "$prefix"'"a":1,"c":2' ]]
[[ $(type=bool json.encode_object_entries a true c false) == "$prefix"'"a":true,"c":false' ]]
[[ $(type=true json.encode_object_entries a true c true) == "$prefix"'"a":true,"c":true' ]]
[[ $(type=false json.encode_object_entries a false c false) == "$prefix"'"a":false,"c":false' ]]
[[ $(type=null json.encode_object_entries a null c null) == "$prefix"'"a":null,"c":null' ]]
[[ $(type=json json.encode_object_entries a '{"b":42}' c [1,2]) == "$prefix"'"a":{"b":42},"c":[1,2]' ]]
[[ $(type=raw json.encode_object_entries a '{"b":42}' c [1,2]) == "$prefix"'"a":{"b":42},"c":[1,2]' ]]
# empty inputs exit with status 10. (Status 11 is not possible because
# inputs always produce output)
local empty_k=() empty_v=()
type=string in=empty_k,empty_v run json.encode_object_entries
[[ $status == 10 && $output == '' ]]
local -A empty_entries=()
type=string in=empty_entries run json.encode_object_entries
[[ $status == 10 && $output == '' ]]
local k=(a b) v_str=('foo bar' 42) v_json=('{}' true)
[[ $(type=string in=k,v_str json.encode_object_entries) == "$prefix"'"a":"foo bar","b":"42"' ]]
[[ $(type=json in=k,v_json json.encode_object_entries) == "$prefix"'"a":{},"b":true' ]]
local -A kv=([a]='foo bar' [b]='bar baz')
# order of associative array keys is not defined
{ printf '{'; type=string in=kv prefix='' json.encode_object_entries; printf '}'; } \
| compare=parsed equals_json '{a: "foo bar", b: "bar baz"}'
local buff=()
out=buff type=string in=k,v_str json.encode_object_entries
[[ $(printf '%s' "${buff[@]}") == "$prefix"'"a":"foo bar","b":"42"' ]]
done
}
@test "json.encode_object_entries :: escapes" {
# When encoding from separate key value arrays, the implementation uses printf
# to consume bash arrays without running bash ops for each array element. This
# has the potential to mangle data if we don't escape format strings correctly
local buff
buff=(); out=buff type=string json.encode_object_entries $'a\nb\x10c' $'d\te\x01f'
[[ $(printf '%s' "${buff[@]}") == '"a\nb\u0010c":"d\te\u0001f"' ]]
}
@test "json.encode_object_entries :: errors" {
run json.encode_object_entries
[[ $status == 1 && $output == *"\$type must be provided"* ]]
type=string run json.encode_object_entries
[[ $status == 1 && $output == *'$in must be set if arguments are not provided' ]]
local k=() v=()
# no values specified
in=k, type=string run json.encode_object_entries
[[ $status == 1 && $output == *"k,': invalid variable name for name reference"* ]]
# unequal number of keys / values
k=(foo)
in=k,v type=string run json.encode_object_entries
[[ $status == 1 && $output == *'unequal number of keys and values: 1 keys, 0 values' ]]
# unequal number of keys / values via arguments
type=string run json.encode_object_entries a
[[ $status == 1 && $output == *'number of arguments is odd — not all keys have values' ]]
}
@test "json.encode_array_entries_from_json" {
local arrays type prefix
# encode_*_entries functions return 10 without emitting the prefix when
# emitting no entries
prefix=('"ex":')
type=string arrays=()
# status 10 = no input and no output
in=arrays run json.encode_array_entries_from_json
[[ $status == 10 && $output == '' ]]
# status 11 = input but no output
type=string arrays=('[]' '[]')
in=arrays run json.encode_array_entries_from_json
[[ $status == 11 && $output == '' ]]
type=string arrays=('["a","b"]' '["c"]' '["d","e"]')
[[ $(in=arrays json.encode_array_entries_from_json) == '"ex":"a","b","c","d","e"' ]]
type=number arrays=('[12,34]' '[5.6]' '[7,8]')
[[ $(in=arrays json.encode_array_entries_from_json) == '"ex":12,34,5.6,7,8' ]]
# whitespace is trimmed/ignored
type=number arrays=($' \n\r\t[ \n\r\t12,34 \n\r\t] \n\r\t' '[5.6]' '[7,8]')
[[ $(in=arrays json.encode_array_entries_from_json) == '"ex":12,34,5.6,7,8' ]]
# empty arrays are collapsed
type=number arrays=(' [1,2] ' ' [] ' ' [] ' ' [3] ')
[[ $(in=arrays json.encode_array_entries_from_json) == '"ex":1,2,3' ]]
# as with encode_object_entries, raw type values are not validated
type=raw arrays=('12,"34"]' '[5.6' '[7,8]')
[[ $(in=arrays json.encode_array_entries_from_json) == '"ex":12,"34",5.6,7,8' ]]
# positional arguments can be used instead of an $in array
type=string run json.encode_array_entries_from_json '[]' '[]'
[[ $status == 11 && $output == '' ]]
type=number
[[ $(json.encode_array_entries_from_json '[12,34]' '[5.6]' '[7,8]') == '"ex":12,34,5.6,7,8' ]]
}
@test "json.encode_array_entries_from_json :: errors" {
# entry value types are validated
type=number arrays=('[1, 2]' '["3"]')
in=arrays run json.encode_array_entries_from_json
echo "${output@Q}"
[[ $status == 1 && $output == "json.encode_array_entries_from_json(): \
provided entries are not all valid JSON arrays with 'number' values — \
'[1, 2]' '[\"3\"]'" ]]
}
@test "encode_array_entries_from_values" {
local values type prefix
# encode_*_entries functions return 10 without emitting the prefix when
# emitting no entries
prefix=('"ex":')
type=string values=()
in=values run json.encode_array_entries_from_values
[[ $status == 10 && $output == '' ]]
type=string values=('foo bar' 'baz')
[[ $(in=values json.encode_array_entries_from_values) == '"ex":"foo bar","baz"' ]]
type=number values=('1234' '5.6')
[[ $(in=values json.encode_array_entries_from_values) == '"ex":1234,5.6' ]]
# positional arguments can be used instead of an $in array
type=number
json.encode_array_entries_from_values '1234' '5.6'
[[ $(json.encode_array_entries_from_values '1234' '5.6') == '"ex":1234,5.6' ]]
}
@test "encode_array_entries_from_values :: errors" {
# values are validated
type=number values=('frob')
in=values run json.encode_array_entries_from_values
[[ $status == 1 && $output == "json.encode_number(): not all inputs are numbers: 'frob'" ]]
}
# Verify that a json.encode_${type} function handles in & out parameters correctly
function assert_input_encodes_to_output_under_all_calling_conventions() {
: "${input?}" "${output:?}" "${join?}"
local buff1=() buff2=() IFS
local stdout1=$(mktemp_bats); local stdout2=$(mktemp_bats)
# Note: join is passed implicitly/automatically
# There are 4 ways to call - {in array, in args} x {out stdout, out array}
out='' in='' "json.encode_${type:?}" "${input[@]}" > "${stdout1:?}"
out='' in=input "json.encode_${type:?}" > "${stdout2:?}"
out=buff1 in='' "json.encode_${type:?}" "${input[@]}"
out=buff2 in=input "json.encode_${type:?}"
IFS=${join?}; joined_output=${output[*]}
echo -n "$joined_output" | diff -u - "${stdout1:?}"
echo -n "$joined_output" | diff -u - "${stdout2:?}"
# When a join character is set, the encode fn joins inputs and outputs 1 result
if [[ $join ]]; then
[[ ${#buff1[@]} == 1 ]]
[[ ${#buff2[@]} == 1 ]]
[[ ${buff1[0]} == "${joined_output:?}" ]]
[[ ${buff2[0]} == "${joined_output:?}" ]]
else
[[ ${#buff1[@]} == "${#output[@]}" ]]
[[ ${#buff2[@]} == "${#output[@]}" ]]
for i in "${!buff1[@]}"; do
[[ ${buff1[$i]} == "${output[$i]}" ]]
[[ ${buff2[$i]} == "${output[$i]}" ]]
done
fi
}
@test "json.encode_* in/out calling convention" {
# Verify that the encode functions correctly handle in and out parameters
local input=() buff=()
local -A examples=(
[string_in]=$'a b\nc d\n \n' [string_out]='"a b\nc d\n \n"'
[number_in]='-42.4e2' [number_out]='-42.4e2'
[bool_in]='false' [bool_out]='false'
[true_in]='true' [true_out]='true'
[false_in]='false' [false_out]='false'
[null_in]='null' [null_out]='null'
[auto_in]='hi' [auto_out]='"hi"'
[raw_in]='{"msg":"hi"}' [raw_out]='{"msg":"hi"}'
[json_in]='{"msg":"hi"}' [json_out]='{"msg":"hi"}'
)
# for type in auto; do
for type in string number bool true false null auto raw json; do
raw="${examples[${type:?}_in]:?}" enc="${examples[${type:?}_out]:?}"
if [[ $type != @(string|auto) ]]; then
run "json.encode_${type:?}" ''
[[ $status == 1 && $output =~ "json.encode_${type:?}(): ".+ ]]
out=buff run "json.encode_${type:?}" ''
[[ $status == 1 && $output =~ "json.encode_${type:?}(): ".+ ]]
input=('')
in=input run "json.encode_${type:?}"
[[ $status == 1 && $output =~ "json.encode_${type:?}(): ".+ ]]
in=input out=buff run "json.encode_${type:?}"
[[ $status == 1 && $output =~ "json.encode_${type:?}(): ".+ ]]
else
# Single empty
input=('') output=('""')
join='' assert_input_encodes_to_output_under_all_calling_conventions
join=',' assert_input_encodes_to_output_under_all_calling_conventions
fi
# Multiple inputs
input=("${raw:?}" "${raw:?}") output=("${enc:?}" "${enc:?}")
join='' assert_input_encodes_to_output_under_all_calling_conventions
join=',' assert_input_encodes_to_output_under_all_calling_conventions
# Multiple inputs
input=("${raw:?}" "${raw:?}") output=("${enc:?}" "${enc:?}")
join='' assert_input_encodes_to_output_under_all_calling_conventions
join=',' assert_input_encodes_to_output_under_all_calling_conventions
done
}
@test "json.stream_encode_string" {
local json_chunk_size=2 buff=()
for json_chunk_size in '' 2; do
for prefix in '' '"foo bar":'; do
run json.stream_encode_string < <(printf 'foo')
[[ $status == 0 && $output == "${prefix?}"'"foo"' ]]
run json.stream_encode_string < <(printf 'foo bar\nbaz boz\nabc')
[[ $status == 0 && $output == "${prefix?}"'"foo bar\nbaz boz\nabc"' ]]
done done
# encoding an empty files emits nothing and returns 10
prefix=',' buff=() status=0
out=buff json.stream_encode_string < <(printf '') || status=$?
[[ ${#buff[@]} == 0 && $status == 10 ]]
# out_cb names a function that's called for each encoded chunk
stdout_file=$(mktemp_bats) json_chunk_size=2 buff=() prefix=''
out=buff out_cb=__json.stream_encode_cb json.stream_encode_string \
< <(printf 'abcdefg') > "${stdout_file:?}"
# out_cb is called incrementally. It's not called after the initial or ending
# " though.
[[ $(<"${stdout_file:?}") == $'CB: ab\nCB: cd\nCB: ef\nCB: g' ]]
[[ ${#buff[@]} == 6 && ${buff[0]} == '"' && ${buff[1]} == 'ab' \
&& ${buff[2]} == 'cd' && ${buff[3]} == 'ef' && ${buff[4]} == 'g' \
&& ${buff[5]} == '"' ]]
}
function __json.stream_encode_cb() {
printf 'CB: %s\n' "${buff[-1]}"
}
@test "json.stream_encode_raw" {
local json_chunk_size=2 buff=()
for json_chunk_size in '' 2; do
for prefix in '' '"foo bar":'; do
# encoding an empty files emits nothing and returns 10
status=0 buff=()
out=buff json.stream_encode_raw < <(printf '') || status=$?
[[ ${#buff[@]} == 0 && $status == 10 ]]
run json.stream_encode_raw < <(printf '{"foo":true}')
echo "$status $output"
[[ $status == 0 && $output == "${prefix?}"'{"foo":true}' ]]
# Trailing newlines are not striped from file contents
diff <(json.stream_encode_raw < <(printf '{\n "foo": true\n}\n')) \
<(printf '%s{\n "foo": true\n}\n' "${prefix?}")
done done
# out_cb names a function that's called for each encoded chunk
stdout_file=$(mktemp_bats) buff=() prefix=''
json_chunk_size=2
out=buff out_cb=__json.stream_encode_cb json.stream_encode_raw \
< <(printf '["abc"]') > "${stdout_file:?}"
[[ $(<"${stdout_file:?}") == $'CB: ["\nCB: ab\nCB: c"\nCB: ]' ]]
[[ ${#buff[@]} == 4 && ${buff[0]} == '["' && ${buff[1]} == 'ab' \
&& ${buff[2]} == 'c"' && ${buff[3]} == ']' ]]
}
function get_value_encode_examples() {
example_names=(string_notrim string_trim number bool{1,2} true false null auto{1,2} raw json)
examples+=(
# json.stream_encode_string preserves trailing whitespace/newlines
[string_notrim_in]=$'a b\nc d\n \n' [string_notrim_out]='"a b\nc d\n \n"' [string_notrim_type]=string [string_notrim_cb]=2
# json.encode_value_from_file trims trailing whitespace. However it's not
# currently called via json(), because json.encode_from_file always uses
# json.stream_encode_string.
[string_trim_in]=$'a b\nc d\n \n' [string_trim_out]='"a b\nc d"' [string_trim_type]=string
[number_in]='-42.4e2' [number_out]='-42.4e2'
[bool1_in]='true' [bool1_out]='true' [bool1_type]=bool
[bool2_in]='false' [bool2_out]='false' [bool2_type]=bool
[true_in]='true' [true_out]='true'
[false_in]='false' [false_out]='false'
[null_in]='null' [null_out]='null'
[auto1_in]='hi' [auto1_out]='"hi"' [auto1_type]=auto
[auto2_in]='42' [auto2_out]='42' [auto2_type]=auto
[raw_in]='{"msg":"hi"}' [raw_out]='{"msg":"hi"}' [raw_cb]=2
[json_in]='{"msg":"hi"}' [json_out]='{"msg":"hi"}'
)
}
@test "json.encode_value_from_file" {
local expected buff json_chunk_size=8 cb_count=0 prefix IFS
local example_names; local -A examples; get_value_encode_examples
for name in "${example_names[@]:?}"; do
for prefix in '' '"foo bar":'; do
type=${examples[${name}_type]:-${name:?}}
# json.encode_value_from_file trims whitespace from the file contents before
# encoding.
if [[ $name == string_notrim ]]; then continue; fi
# encoding an empty files emits nothing and returns 10
status=0 buff=()
out=buff json.encode_value_from_file < <(printf '') || status=$?
[[ ${#buff[@]} == 0 && $status == 10 ]]
# output to stdout
out='' type=${type:?} run json.encode_value_from_file \
< <(echo -n "${examples["${name:?}_in"]}" )
[[ $status == 0 && $output == "${prefix?}${examples[${name:?}_out]:?}" ]]
# output to array
buff=()
out=buff type=${type:?} json.encode_value_from_file \
< <(echo -n "${examples["${name:?}_in"]}" )
IFS=''; expected=(${prefix?} "${examples[${name:?}_out]:?}")
echo "expected: ${expected[@]@Q}"
echo "actual: ${buff[@]@Q}"
assert_array_equals expected buff
done done
}
@test "json.encode_value_from_file :: stops reading after null byte" {
type=string run json.encode_value_from_file \
< <(printf "foo\x00"; timeout "${TIMEOUT_SECONDS:?}" yes )
[[ $status == 0 && $output == '"foo"' ]]
}
@test "json.encode_from_file :: single value" {
local IFS actual buff json_chunk_size=8 cb_count
local tmp=$(mktemp_bats)
local example_names; local -A examples; get_value_encode_examples
for name in "${example_names[@]:?}"; do
for prefix in '' '"foo bar",'; do
type=${examples[${name}_type]:-${name:?}}
# When encoding strings, json.encode_from_file always uses
# json.stream_encode_string, never json.encode_value_from_file, so it
# preserves trailing whitespace.
if [[ $name == string_trim ]]; then continue; fi
# output to stdout
cb_count=0
type=${type:?} out_cb=_increment_cb_count json.encode_from_file \
< <(echo -n "${examples["${name:?}_in"]}" ) > "${tmp:?}"
diff <(echo -n "${prefix?}${examples[${name:?}_out]:?}") "${tmp:?}"
[[ $cb_count == ${examples[${name:?}_cb]:-0} ]]
# output to array
buff=() cb_count=0
out=buff type=${type:?} out_cb=_increment_cb_count json.encode_from_file \
< <(echo -n "${examples["${name:?}_in"]}" )
printf -v actual '%s' "${buff[@]}"
[[ $actual == "${prefix?}${examples[${name:?}_out]:?}" ]]
[[ $cb_count == ${examples[${name:?}_cb]:-0} ]]
done done
}
function _increment_cb_count() { let ++cb_count; }
function get_array_encode_examples() {
example_names=(string number bool true false null auto raw json)
format_names=(json raw)
examples+=(
[raw_string_in]=$'a b\nc d\n \n' [json_string_in]=$'["a b","c d"]\n[]\n [" "] \n'
[string_out]=$'"a b","c d"," "'
[raw_number_in]=$'1\n2\n3\n' [json_number_in]=$'[1,2]\n[]\n[3]\n'
[number_out]=$'1,2,3'
[raw_bool_in]=$'true\nfalse\nfalse\n' [json_bool_in]=$'[true,false]\n[]\n[false]\n'
[bool_out]=$'true,false,false'
[raw_true_in]=$'true\ntrue\ntrue\n' [json_true_in]=$'[true,true]\n[]\n[true]\n'
[true_out]=$'true,true,true'
[raw_false_in]=$'false\nfalse\nfalse\n' [json_false_in]=$'[false,false]\n[]\n[false]\n'
[false_out]=$'false,false,false'
[raw_null_in]=$'null\nnull\nnull\n' [json_null_in]=$'[null,null]\n[]\n[null]\n'
[null_out]=$'null,null,null'
[raw_auto_in]=$'hi\n42\ntrue\nnull\n' [json_auto_in]=$'["hi",42]\n[]\n[true,null]\n'
[auto_out]=$'"hi",42,true,null'
[raw_raw_in]=$'{"msg":"hi"}\n42\n[]\n' [json_raw_in]=$'[{"msg":"hi"},42]\n[]\n[[]]\n'
[raw_out]=$'{"msg":"hi"},42,[]'
[raw_json_in]=$'{"msg":"hi"}\n42\n[]\n' [json_json_in]=$'[{"msg":"hi"},42]\n[]\n[[]]\n'
[json_out]=$'{"msg":"hi"},42,[]'
)
}
@test "json.encode_from_file :: array" {
local json_buffered_chunk_count=2 cb_count type array_format
local tmp=$(mktemp_bats)
local example_names format_names; local -A examples; get_array_encode_examples
for type in "${example_names[@]:?}"; do
for format in "${format_names[@]:?}"; do
for prefix in '' '"foo bar",'; do
# output to stdout
cb_count=0
collection=array split=$'\n' out_cb=_increment_cb_count \
array_format=${format:?} json.encode_from_file \
< <(echo -n "${examples["${format:?}_${type:?}_in"]}" ) > "${tmp:?}"
diff <(echo -n "${prefix?}[${examples[${type:?}_out]:?}]") "${tmp:?}"
[[ $cb_count == 2 ]]
# entries only to stdout
cb_count=0
collection=array split=$'\n' out_cb=_increment_cb_count \
array_format=${format:?} entries=true json.encode_from_file \
< <(echo -n "${examples["${format:?}_${type:?}_in"]}" ) > "${tmp:?}"
diff <(echo -n "${prefix?}${examples[${type:?}_out]:?}") "${tmp:?}"
[[ $cb_count == 2 ]]
# output to array
buff=() cb_count=0
out=buff collection=array split=$'\n' out_cb=_increment_cb_count \
array_format=${format:?} json.encode_from_file \
< <(echo -n "${examples["${format:?}_${type:?}_in"]}" )
printf -v actual '%s' "${buff[@]}"
[[ "${actual:?}" == "${prefix?}[${examples[${type:?}_out]:?}]" ]]
[[ $cb_count == 2 ]]
# entries only to array
buff=() cb_count=0
out=buff collection=array split=$'\n' out_cb=_increment_cb_count \
array_format=${format:?} entries=true json.encode_from_file \
< <(echo -n "${examples["${format:?}_${type:?}_in"]}" )
printf -v actual '%s' "${buff[@]}"
[[ "${actual:?}" == "${prefix?}${examples[${type:?}_out]:?}" ]]
[[ $cb_count == 2 ]]
done done done
}
function get_object_encode_examples() {
example_names=(string number)
format_names=(json attrs)
examples+=(
[json_string_in]=$'{"a b":"c d","e":"f"}\n{"":""}\n{"g":"h"}\n{}\n'
[attrs_string_in]=$'a b=c d,e=f\n=\ng=h\n\n'
[string_out]='"a b":"c d","e":"f","":"","g":"h"'
[json_number_in]=$'{"a":1}\n{"b":2}\n{"c":3}\n'
[attrs_number_in]=$'a=1\nb=2\nc=3\n'
[number_out]=$'"a":1,"b":2,"c":3'
)
}
@test "json.encode_from_file :: object :: empty in/out convention" {
local type=string object_format=json array_format=json split=$'\n'
for prefix in '' '"ex",'; do
for collection in object array; do
entries=true run json.encode_from_file < <(printf '')
[[ $status == 10 && $output == '' ]]
entries=false run json.encode_from_file < <(printf '')
[[ $status == 10 && $output == '' ]]
case $collection in
(array) local col_json='[]' ;;
(object) local col_json='{}' ;;
esac
local input="${col_json:?}\n${col_json:?}\n${col_json:?}\n"
# When emitting entries only, we exit with status 11 to report no output
# when non-empty input produces no entries.
entries=true run json.encode_from_file < <(printf "${input:?}")
[[ $status == 11 && $output == '' ]]
# When emitting complete collections, we still emit the collection when
# non-empty input produces no entries.
entries=false run json.encode_from_file < <(printf "${input:?}")
[[ $status == 0 && $output == "${prefix?}${col_json:?}" ]]
done done
}
@test "json.encode_from_file :: object" {
local json_buffered_chunk_count=2 cb_count type format