forked from nadirizr/json-logic-py
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtests.py
387 lines (349 loc) · 12.7 KB
/
tests.py
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
"""
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")
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)