forked from nadirizr/json-logic-py
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtests.py
More file actions
660 lines (594 loc) · 19.5 KB
/
tests.py
File metadata and controls
660 lines (594 loc) · 19.5 KB
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
"""
Tests for jsonLogic.
"""
from __future__ import unicode_literals
import json
import unittest
try:
from urllib.request import urlopen
except ImportError:
from urllib2 import urlopen
from json_logic import jsonLogic
class JSONLogicTest(unittest.TestCase):
"""
The tests here come from 'Supported operations' page on jsonlogic.com:
http://jsonlogic.com/operations.html
"""
def test_var(self):
"""Retrieve data from the provided data object."""
self.assertEqual(
jsonLogic(
{"var": ["a"]},
{"a": 1, "b": 2}
),
1
)
# If you like, we support syntactic sugar to skip the array around
# single values.
self.assertEqual(
jsonLogic(
{"var": "a"},
{"a": 1, "b": 2}
),
1
)
# You can supply a default, as the second argument, for values that
# might be missing in the data object.
self.assertEqual(
jsonLogic(
{"var": ["z", 26]},
{"a": 1, "b": 2}
),
26
)
# The key passed to var can use dot-notation to get
# the property of a property (to any depth you need):
self.assertEqual(
jsonLogic(
{"var": "champ.name"},
{
"champ": {
"name": "Fezzig",
"height": 223
},
"challenger": {
"name": "Dread Pirate Roberts",
"height": 183
}
}
),
"Fezzig"
)
# You can also use the var operator to access an array
# by numeric index:
self.assertEqual(
jsonLogic(
{"var": 1},
["apple", "banana", "carrot"]
),
"banana"
)
# Here's a complex rule that mixes literals and data. The pie isn't
# ready to eat unless it's cooler than 110 degrees, and filled
# with apples.
self.assertTrue(
jsonLogic(
{"and": [
{"<": [{"var": "temp"}, 110]},
{"==": [{"var": "pie.filling"}, "apple"]}
]},
{"temp": 100, "pie": {"filling": "apple"}}
)
)
def test_missing(self):
"""
Takes an array of data keys to search for (same format as var).
Returns an array of any keys that are missing from the data object,
or an empty array.
"""
self.assertEqual(
jsonLogic(
{"missing": ["a", "b"]},
{"a": "apple", "c": "carrot"}
),
["b"]
)
self.assertEqual(
jsonLogic(
{"missing": ["a", "b"]},
{"a": "apple", "b": "banana"}
),
[]
)
# Note, in JsonLogic, empty arrays are falsy. So you can use missing
# with if like:
self.assertEqual(
jsonLogic(
{"if": [
{"missing": ["a", "b"]},
"Not enough fruit",
"OK to proceed"
]},
{"a": "apple", "b": "banana"}
),
"OK to proceed"
)
def test_missing_some(self):
"""
Takes a minimum number of data keys that are required, and an array
of keys to search for (same format as var or missing). Returns
an empty array if the minimum is met, or an array of the missing
keys otherwise.
"""
self.assertEqual(
jsonLogic(
{"missing_some": [1, ["a", "b", "c"]]},
{"a": "apple"}
),
[]
)
self.assertEqual(
jsonLogic(
{"missing_some": [2, ["a", "b", "c"]]},
{"a": "apple"}
),
["b", "c"]
)
# This is useful if you're using missing to track required fields,
# but occasionally need to require N of M fields.
self.assertEqual(
jsonLogic(
{"if": [
{"merge": [
{"missing": ["first_name", "last_name"]},
{"missing_some": [1, ["cell_phone", "home_phone"]]},
]},
"We require first name, last name, and one phone number.",
"OK to proceed"
]},
{"first_name": "Bruce", "last_name": "Wayne"}
),
"We require first name, last name, and one phone number."
)
def test_if(self):
"""
The if statement typically takes 3 arguments: a condition (if),
what to do if it's true (then), and what to do if it's false (else).
"""
self.assertEqual(
jsonLogic(
{"if": [True, "yes", "no"]}
),
"yes"
)
self.assertEqual(
jsonLogic(
{"if": [False, "yes", "no"]}
),
"no"
)
# If can also take more than 3 arguments, and will pair up arguments
# like if/then elseif/then elseif/then else. Like:
self.assertEqual(
jsonLogic(
{"if": [
{"<": [{"var": "temp"}, 0]}, "freezing",
{"<": [{"var": "temp"}, 100]}, "liquid",
"gas"
]},
{"temp": 200}
),
"gas"
)
def test_equality(self):
"""Tests equality, with type coercion. Requires two arguments."""
self.assertTrue(jsonLogic({"==": [1, 1]}))
self.assertTrue(jsonLogic({"==": [1, "1"]}))
self.assertTrue(jsonLogic({"==": [0, False]}))
def test_stricy_equality(self):
"""Tests strict equality. Requires two arguments."""
self.assertTrue(jsonLogic({"===": [1, 1]}))
self.assertFalse(jsonLogic({"===": [1, "1"]}))
def test_nonequality(self):
"""Tests not-equal, with type coercion."""
self.assertTrue(jsonLogic({"!=": [1, 2]}))
self.assertFalse(jsonLogic({"!=": [1, "1"]}))
def test_strict_nonequality(self):
"""Tests not-equal, with type coercion."""
self.assertTrue(jsonLogic({"!==": [1, 2]}))
self.assertTrue(jsonLogic({"!==": [1, "1"]}))
def test_not(self):
"""Logical negation ("not"). Takes just one argument."""
self.assertFalse(jsonLogic({"!": [True]}))
# Note: unary operators can also take a single, non array argument:
self.assertFalse(jsonLogic({"!": True}))
def test_or(self):
"""
'or' can be used for simple boolean tests, with 1 or more arguments.
"""
self.assertTrue(jsonLogic({"or": [True, False]}))
# At a more sophisticated level, or returns the first truthy argument,
# or the last argument.
self.assertTrue(jsonLogic({"or": [False, True]}))
self.assertEqual(jsonLogic({"or": [False, "apple"]}), "apple")
self.assertEqual(jsonLogic({"or": [False, None, "apple"]}), "apple")
def test_and(self):
"""
'and' can be used for simple boolean tests, with 1 or more arguments.
"""
self.assertTrue(jsonLogic({"and": [True, True]}))
self.assertFalse(jsonLogic({"and": [True, True, True, False]}))
# At a more sophisticated level, and returns the first falsy argument,
# or the last argument.
self.assertFalse(jsonLogic({"and": [True, "apple", False]}))
self.assertEqual(jsonLogic({"and": [True, "apple", 3.14]}), 3.14)
def test_cmp(self):
"""Arithmetic comparison functions."""
# Greater than:
self.assertTrue(jsonLogic({">": [2, 1]}))
# Greater than or equal to:
self.assertTrue(jsonLogic({">=": [1, 1]}))
# Less than:
self.assertTrue(jsonLogic({"<": [1, 2]}))
# Less than or equal to:
self.assertTrue(jsonLogic({"<=": [1, 1]}))
def test_between(self):
"""
You can use a special case of < and <= to test that one value
is between two others.
"""
# Between exclusive:
self.assertTrue(jsonLogic({"<": [1, 2, 3]}))
self.assertFalse(jsonLogic({"<": [1, 1, 3]}))
self.assertFalse(jsonLogic({"<": [1, 4, 3]}))
# Between inclusive:
self.assertTrue(jsonLogic({"<=": [1, 2, 3]}))
self.assertTrue(jsonLogic({"<=": [1, 1, 3]}))
self.assertFalse(jsonLogic({"<=": [1, 4, 3]}))
# This is most useful with data:
self.assertTrue(jsonLogic(
{"<": [0, {"var": "temp"}, 100]},
{"temp": 37}
))
def test_max_min(self):
"""Return the maximum or minimum from a list of values."""
self.assertEqual(jsonLogic({"max": [1, 2, 3]}), 3)
self.assertEqual(jsonLogic({"min": [1, 2, 3]}), 1)
def test_arithmetic(self):
"""Arithmetic operators."""
self.assertEqual(jsonLogic({"+": [1, 1]}), 2)
self.assertEqual(jsonLogic({"*": [2, 3]}), 6)
self.assertEqual(jsonLogic({"-": [3, 2]}), 1)
self.assertEqual(jsonLogic({"/": [2, 4]}), .5)
self.assertEqual(jsonLogic({"+": [1, 1]}), 2)
# Because addition and multiplication are associative,
# they happily take as many args as you want:
self.assertEqual(jsonLogic({"+": [1, 1, 1, 1, 1]}), 5)
self.assertEqual(jsonLogic({"*": [2, 2, 2, 2, 2]}), 32)
# Passing just one argument to - returns its arithmetic
# negative (additive inverse).
self.assertEqual(jsonLogic({"-": [2]}), -2)
self.assertEqual(jsonLogic({"-": [-2]}), 2)
# Passing just one argument to + casts it to a number.
self.assertEqual(jsonLogic({"+": "0"}), 0)
def test_modulo(self):
"""
Modulo. Finds the remainder after the first argument
is divided by the second argument.
"""
self.assertEqual(jsonLogic({"%": [101, 2]}), 1)
def test_merge(self):
"""
Takes one or more arrays, and merges them into one array.
If arguments aren't arrays, they get cast to arrays.
"""
self.assertEqual(jsonLogic({"merge": [[1, 2], [3, 4]]}), [1, 2, 3, 4])
self.assertEqual(jsonLogic({"merge": [1, 2, [3, 4]]}), [1, 2, 3, 4])
# Merge can be especially useful when defining complex missing rules,
# like which fields are required in a document. For example, the this
# vehicle paperwork always requires the car's VIN, but only needs
# the APR and term if you're financing.
missing = {
"missing": {
"merge": [
"vin",
{"if": [{"var": "financing"}, ["apr", "term"], []]}
]
}
}
self.assertEqual(
jsonLogic(missing, {"financing": True}),
["vin", "apr", "term"]
)
self.assertEqual(
jsonLogic(missing, {"financing": False}),
["vin"]
)
def test_in(self):
"""
If the second argument is a string, tests that the first argument
is a substring:
"""
self.assertTrue(jsonLogic({"in": ["Spring", "Springfield"]}))
def test_cat(self):
"""
Concatenate all the supplied arguments. Note that this is not
a join or implode operation, there is no "glue" string.
"""
self.assertEqual(jsonLogic({"cat": ["I love", " pie"]}), "I love pie")
self.assertEqual(
jsonLogic(
{"cat": ["I love ", {"var": "filling"}, " pie"]},
{"filling": "apple", "temp": 110}
),
"I love apple pie"
)
def test_log(self):
"""
Logs the first value to console, then passes it through unmodified.
This can be especially helpful when debugging a large rule.
"""
self.assertEqual(jsonLogic({"log": "apple"}), "apple")
def test_filter(self):
"""
Filter an array by running a test against each element.
"""
self.assertEqual(
jsonLogic(
{"filter": [
{"var": "integers"},
{"%": [{"var": ""}, 2]}
]},
{"integers": [1, 2, 3, 4, 5]}
),
[1, 3, 5]
)
# Filter with greater than condition
self.assertEqual(
jsonLogic(
{"filter": [
[1, 2, 3, 4, 5],
{">": [{"var": ""}, 2]}
]}
),
[3, 4, 5]
)
# Empty array
self.assertEqual(
jsonLogic({"filter": [[], {">": [{"var": ""}, 2]}]}),
[]
)
# Non-array returns empty array
self.assertEqual(
jsonLogic({"filter": ["not_an_array", {">": [{"var": ""}, 2]}]}),
[]
)
def test_map(self):
"""
Map an array by running a transformation on each element.
"""
self.assertEqual(
jsonLogic(
{"map": [
{"var": "integers"},
{"*": [{"var": ""}, 2]}
]},
{"integers": [1, 2, 3, 4, 5]}
),
[2, 4, 6, 8, 10]
)
# Map with object array
self.assertEqual(
jsonLogic(
{"map": [
{"var": "people"},
{"var": "name"}
]},
{"people": [
{"name": "Alice", "age": 30},
{"name": "Bob", "age": 25}
]}
),
["Alice", "Bob"]
)
# Empty array
self.assertEqual(
jsonLogic({"map": [[], {"*": [{"var": ""}, 2]}]}),
[]
)
# Non-array returns empty array
self.assertEqual(
jsonLogic({"map": ["not_an_array", {"*": [{"var": ""}, 2]}]}),
[]
)
def test_reduce(self):
"""
Reduce an array to a single value using an accumulator.
"""
self.assertEqual(
jsonLogic(
{"reduce": [
{"var": "integers"},
{"+": [{"var": "current"}, {"var": "accumulator"}]},
0
]},
{"integers": [1, 2, 3, 4, 5]}
),
15
)
# Reduce with multiplication
self.assertEqual(
jsonLogic(
{"reduce": [
[1, 2, 3, 4, 5],
{"*": [{"var": "current"}, {"var": "accumulator"}]},
1
]}
),
120
)
# Reduce with string concatenation
self.assertEqual(
jsonLogic(
{"reduce": [
["a", "b", "c"],
{"cat": [{"var": "accumulator"}, {"var": "current"}]},
""
]}
),
"abc"
)
# Empty array returns initial value
self.assertEqual(
jsonLogic(
{"reduce": [
[],
{"+": [{"var": "current"}, {"var": "accumulator"}]},
10
]}
),
10
)
# Non-array returns initial value
self.assertEqual(
jsonLogic(
{"reduce": [
"not_an_array",
{"+": [{"var": "current"}, {"var": "accumulator"}]},
42
]}
),
42
)
def test_all(self):
"""
Test if all elements in an array pass a test.
"""
self.assertTrue(
jsonLogic(
{"all": [
[1, 2, 3],
{">": [{"var": ""}, 0]}
]}
)
)
self.assertFalse(
jsonLogic(
{"all": [
[-1, 2, 3],
{">": [{"var": ""}, 0]}
]}
)
)
# All with var reference
self.assertTrue(
jsonLogic(
{"all": [
{"var": "integers"},
{">=": [{"var": ""}, 1]}
]},
{"integers": [1, 2, 3]}
)
)
# Empty array returns False
self.assertFalse(
jsonLogic({"all": [[], {">": [{"var": ""}, 0]}]})
)
# Non-array returns False
self.assertFalse(
jsonLogic({"all": ["not_an_array", {">": [{"var": ""}, 0]}]})
)
def test_none(self):
"""
Test if no elements in an array pass a test.
"""
self.assertTrue(
jsonLogic(
{"none": [
[1, 2, 3],
{"<": [{"var": ""}, 0]}
]}
)
)
self.assertFalse(
jsonLogic(
{"none": [
[-1, 2, 3],
{"<": [{"var": ""}, 0]}
]}
)
)
# None with var reference
self.assertTrue(
jsonLogic(
{"none": [
{"var": "integers"},
{"<": [{"var": ""}, 1]}
]},
{"integers": [1, 2, 3]}
)
)
# Empty array returns True
self.assertTrue(
jsonLogic({"none": [[], {"<": [{"var": ""}, 0]}]})
)
# Non-array returns True
self.assertTrue(
jsonLogic({"none": ["not_an_array", {"<": [{"var": ""}, 0]}]})
)
def test_some(self):
"""
Test if some elements in an array pass a test.
"""
self.assertTrue(
jsonLogic(
{"some": [
[-1, 0, 1],
{">": [{"var": ""}, 0]}
]}
)
)
self.assertFalse(
jsonLogic(
{"some": [
[-1, -2, -3],
{">": [{"var": ""}, 0]}
]}
)
)
# Some with var reference
self.assertTrue(
jsonLogic(
{"some": [
{"var": "integers"},
{">": [{"var": ""}, 2]}
]},
{"integers": [1, 2, 3]}
)
)
# Empty array returns False
self.assertFalse(
jsonLogic({"some": [[], {">": [{"var": ""}, 0]}]})
)
# Non-array returns False
self.assertFalse(
jsonLogic({"some": ["not_an_array", {">": [{"var": ""}, 0]}]})
)
class SharedTests(unittest.TestCase):
"""This runs the tests from http://jsonlogic.com/tests.json."""
cnt = 0
@classmethod
def create_test(cls, logic, data, expected):
"""Adds new test to the class."""
def test(self):
"""Actual test function."""
self.assertEqual(jsonLogic(logic, data), expected)
test.__doc__ = "{}, {} => {}".format(logic, data, expected)
setattr(cls, "test_{}".format(cls.cnt), test)
cls.cnt += 1
SHARED_TESTS = json.loads(
urlopen("http://jsonlogic.com/tests.json").read().decode('utf-8')
)
for item in SHARED_TESTS:
if isinstance(item, list):
SharedTests.create_test(*item)