| 1 |
"""GJSON test module.""" |
| 2 |
import json |
| 3 |
import re |
| 4 |
from collections.abc import Mapping |
| 5 |
from math import isnan |
| 6 |
|
| 7 |
import gjson |
| 8 |
import pytest |
| 9 |
from gjson._gjson import MODIFIER_NAME_RESERVED_CHARS |
| 10 |
|
| 11 |
INPUT_JSON = """ |
| 12 |
{ |
| 13 |
"name": {"first": "Tom", "last": "Anderson"}, |
| 14 |
"age":37, |
| 15 |
"children": ["Sara","Alex","Jack"], |
| 16 |
"fav.movie": "Deer Hunter", |
| 17 |
"friends": [ |
| 18 |
{"first": "Dale", "last": "Murphy", "age": 44, "nets": ["ig", "fb", "tw"]}, |
| 19 |
{"first": "Roger", "last": "Craig", "age": 68, "nets": ["fb", "tw"]}, |
| 20 |
{"first": "Jane", "last": "Murphy", "age": 47, "nets": ["ig", "tw"]} |
| 21 |
] |
| 22 |
} |
| 23 |
""" |
| 24 |
INPUT_OBJECT = json.loads(INPUT_JSON) |
| 25 |
INPUT_LIST = json.loads(""" |
| 26 |
[ |
| 27 |
{"first": "Dale"}, |
| 28 |
{"first": "Jane"}, |
| 29 |
{"last": "Murphy"} |
| 30 |
] |
| 31 |
""") |
| 32 |
INPUT_ESCAPE = json.loads(""" |
| 33 |
{ |
| 34 |
"test": { |
| 35 |
"*":"valZ", |
| 36 |
"*v":"val0", |
| 37 |
"keyv*":"val1", |
| 38 |
"key*v":"val2", |
| 39 |
"keyv?":"val3", |
| 40 |
"key?v":"val4", |
| 41 |
"keyv.":"val5", |
| 42 |
"key.v":"val6", |
| 43 |
"keyk*":{"key?":"val7"}, |
| 44 |
"1key":"val8" |
| 45 |
} |
| 46 |
} |
| 47 |
""") |
| 48 |
|
| 49 |
INPUT_BASIC = json.loads(""" |
| 50 |
{"age":100, "name2":{"here":"B\\\\\\"R"}, |
| 51 |
"noop":{"what is a wren?":"a bird"}, |
| 52 |
"happy":true,"immortal":false, |
| 53 |
"items":[1,2,3,{"tags":[1,2,3],"points":[[1,2],[3,4]]},4,5,6,7], |
| 54 |
"arr":["1",2,"3",{"hello":"world"},"4",5], |
| 55 |
"vals":[1,2,3],"name":{"first":"tom","last":null}, |
| 56 |
"created":"2014-05-16T08:28:06.989Z", |
| 57 |
"loggy":{ |
| 58 |
"programmers": [ |
| 59 |
{ |
| 60 |
"firstName": "Brett", |
| 61 |
"lastName": "McLaughlin", |
| 62 |
"email": "aaaa", |
| 63 |
"tag": "good" |
| 64 |
}, |
| 65 |
{ |
| 66 |
"firstName": "Jason", |
| 67 |
"lastName": "Hunter", |
| 68 |
"email": "bbbb", |
| 69 |
"tag": "bad" |
| 70 |
}, |
| 71 |
{ |
| 72 |
"firstName": "Elliotte", |
| 73 |
"lastName": "Harold", |
| 74 |
"email": "cccc", |
| 75 |
"tag": "good" |
| 76 |
}, |
| 77 |
{ |
| 78 |
"firstName": 1002.3, |
| 79 |
"age": 101 |
| 80 |
} |
| 81 |
] |
| 82 |
}, |
| 83 |
"lastly":{"end...ing":"soon","yay":"final"} |
| 84 |
} |
| 85 |
""") |
| 86 |
INPUT_LINES = """ |
| 87 |
{"name": "Gilbert", "age": 61} |
| 88 |
{"name": "Alexa", "age": 34} |
| 89 |
{"name": "May", "age": 57} |
| 90 |
{"name": "Deloise", "age": 44} |
| 91 |
""" |
| 92 |
INPUT_LINES_WITH_ERRORS = """ |
| 93 |
{"name": "Gilbert", "age": 61} |
| 94 |
{invalid |
| 95 |
{invalid |
| 96 |
{"name": "Deloise", "age": 44} |
| 97 |
""" |
| 98 |
INPUT_TRUTHINESS = json.loads(""" |
| 99 |
{ |
| 100 |
"vals": [ |
| 101 |
{ "a": 1, "b": true }, |
| 102 |
{ "a": 2, "b": true }, |
| 103 |
{ "a": 3, "b": false }, |
| 104 |
{ "a": 4, "b": "0" }, |
| 105 |
{ "a": 5, "b": 0 }, |
| 106 |
{ "a": 6, "b": "1" }, |
| 107 |
{ "a": 7, "b": 1 }, |
| 108 |
{ "a": 8, "b": "true" }, |
| 109 |
{ "a": 9, "b": false }, |
| 110 |
{ "a": 10, "b": null }, |
| 111 |
{ "a": 11 } |
| 112 |
] |
| 113 |
} |
| 114 |
""") |
| 115 |
INPUT_SUM_N = json.loads(""" |
| 116 |
[ |
| 117 |
{"key": "a", "value": 1, "other": "value"}, |
| 118 |
{"key": "b", "value": 2}, |
| 119 |
{"key": "c", "value": 3, "other": "value"}, |
| 120 |
{"key": "a", "value": 7}, |
| 121 |
{"key": "b", "value": 1.5}, |
| 122 |
{"key": "d", "value": 4}, |
| 123 |
{"key": "c", "value": 9} |
| 124 |
] |
| 125 |
""") |
| 126 |
INPUT_NESTED_QUERIES = json.loads(""" |
| 127 |
{ |
| 128 |
"key": [ |
| 129 |
{"level1": [{"level2": [{"level3": [1, 2]}]}]}, |
| 130 |
{"level1": [{"level2": [{"level3": [2, 3]}]}]}, |
| 131 |
[[{"level3": [1, 2]}], [{"level3": [2, 3]}]], |
| 132 |
[[{"level3": [2, 3]}], [{"level3": [3, 4]}]], |
| 133 |
{"another": [{"level2": [{"level3": [2, 3]}]}]}, |
| 134 |
{"level1": [{"another": [{"level3": [2, 3]}]}]}, |
| 135 |
{"level1": [{"level2": [{"another": [2, 3]}]}]}, |
| 136 |
[[{"another": [2, 3]}], [{"another": [3, 4]}]], |
| 137 |
"spurious", |
| 138 |
12.34, |
| 139 |
{"mixed": [[{"level4": [1, 2]}]]} |
| 140 |
] |
| 141 |
} |
| 142 |
""") |
| 143 |
|
| 144 |
|
| 145 |
def compare_values(result, expected): |
| 146 |
"""Compare results with the expected values ensuring same-order of keys for dictionaries.""" |
| 147 |
if isinstance(expected, float) and isnan(expected): |
| 148 |
assert isnan(result) |
| 149 |
return |
| 150 |
|
| 151 |
assert result == expected |
| 152 |
if isinstance(expected, Mapping): |
| 153 |
assert list(result.keys()) == list(expected.keys()) |
| 154 |
|
| 155 |
|
| 156 |
class TestObject: |
| 157 |
"""Testing gjson with a basic input object.""" |
| 158 |
|
| 159 |
def setup_method(self): |
| 160 |
"""Initialize the test instance.""" |
| 161 |
def upper(options, obj, *, last): |
| 162 |
"""Change the case of the object returning its upper version. Custom modifier to be used in tests.""" |
| 163 |
del options |
| 164 |
del last |
| 165 |
if isinstance(obj, list): |
| 166 |
return [i.upper() for i in obj] |
| 167 |
|
| 168 |
return obj.upper() |
| 169 |
|
| 170 |
self.object = gjson.GJSON(INPUT_OBJECT) |
| 171 |
self.object.register_modifier('upper', upper) |
| 172 |
|
| 173 |
@pytest.mark.parametrize(('query', 'expected'), ( |
| 174 |
|
| 175 |
('name.last', 'Anderson'), |
| 176 |
('name.first', 'Tom'), |
| 177 |
('age', 37), |
| 178 |
('children', ['Sara', 'Alex', 'Jack']), |
| 179 |
('children.0', 'Sara'), |
| 180 |
('children.1', 'Alex'), |
| 181 |
('friends.1', {'first': 'Roger', 'last': 'Craig', 'age': 68, 'nets': ['fb', 'tw']}), |
| 182 |
('friends.1.first', 'Roger'), |
| 183 |
|
| 184 |
('*.first', 'Tom'), |
| 185 |
('?a??.first', 'Tom'), |
| 186 |
('child*.2', 'Jack'), |
| 187 |
('c?ildren.0', 'Sara'), |
| 188 |
|
| 189 |
(r'fav\.movie', 'Deer Hunter'), |
| 190 |
|
| 191 |
('friends.#', 3), |
| 192 |
('friends.#.age', [44, 68, 47]), |
| 193 |
('friends.#.first', ['Dale', 'Roger', 'Jane']), |
| 194 |
('friends.#.nets.0', ['ig', 'fb', 'ig']), |
| 195 |
|
| 196 |
('friends.#(last=="Murphy").first', 'Dale'), |
| 197 |
('friends.#(last=="Murphy")#.first', ['Dale', 'Jane']), |
| 198 |
('friends.#(=="Murphy")#', []), |
| 199 |
('friends.#(=="Mu)(phy")#', []), |
| 200 |
('friends.#(=="Mur\tphy")#', []), |
| 201 |
('friends.#(age\\===44)#', []), |
| 202 |
('friends.#(age>47)#.last', ['Craig']), |
| 203 |
('friends.#(age>=47)#.last', ['Craig', 'Murphy']), |
| 204 |
('friends.#(age<47)#.last', ['Murphy']), |
| 205 |
('friends.#(age<=47)#.last', ['Murphy', 'Murphy']), |
| 206 |
('friends.#(age==44)#.last', ['Murphy']), |
| 207 |
('friends.#(age!=44)#.last', ['Craig', 'Murphy']), |
| 208 |
('friends.#(first%"D*").last', 'Murphy'), |
| 209 |
('friends.#(first!%"D*").last', 'Craig'), |
| 210 |
('friends.#(first!%"D???").last', 'Craig'), |
| 211 |
('friends.#(%0)#', []), |
| 212 |
('friends.#(>40)#', []), |
| 213 |
('children.#(!%"*a*")', 'Alex'), |
| 214 |
('children.#(%"*a*")#', ['Sara', 'Jack']), |
| 215 |
|
| 216 |
('friends.#(nets.#(=="fb"))#.first', ['Dale', 'Roger']), |
| 217 |
|
| 218 |
('children.@reverse', ['Jack', 'Alex', 'Sara']), |
| 219 |
('[email protected]', 'Jack'), |
| 220 |
('name.@reverse', {'last': 'Anderson', 'first': 'Tom'}), |
| 221 |
('age.@reverse', 37), |
| 222 |
('@keys', ['name', 'age', 'children', 'fav.movie', 'friends']), |
| 223 |
('name.@values', ['Tom', 'Anderson']), |
| 224 |
('age.@flatten', 37), |
| 225 |
('@pretty:{"indent": 4}', INPUT_OBJECT), |
| 226 |
(r'fav\.movie.@pretty:{"indent": 4}', 'Deer Hunter'), |
| 227 |
('name.@tostr', '{"first": "Tom", "last": "Anderson"}'), |
| 228 |
('name.@join', {'first': 'Tom', 'last': 'Anderson'}), |
| 229 |
('age.@join', 37), |
| 230 |
('children.@join', {}), |
| 231 |
('children.0.@join', 'Sara'), |
| 232 |
('friends.@join', {'first': 'Jane', 'last': 'Murphy', 'age': 47, 'nets': ['ig', 'tw']}), |
| 233 |
|
| 234 |
('friends.0.first', 'Dale'), |
| 235 |
('friends|0.first', 'Dale'), |
| 236 |
('friends.0|first', 'Dale'), |
| 237 |
('friends|0|first', 'Dale'), |
| 238 |
('friends|#', 3), |
| 239 |
('friends.#(last="Murphy")#', |
| 240 |
[{'first': 'Dale', 'last': 'Murphy', 'age': 44, 'nets': ['ig', 'fb', 'tw']}, |
| 241 |
{'first': 'Jane', 'last': 'Murphy', 'age': 47, 'nets': ['ig', 'tw']}]), |
| 242 |
('friends.#(last="Murphy")#.first', ['Dale', 'Jane']), |
| 243 |
('friends.#(last="Murphy")#.0', []), |
| 244 |
('friends.#(last="Murphy")#|0', {'first': 'Dale', 'last': 'Murphy', 'age': 44, 'nets': ['ig', 'fb', 'tw']}), |
| 245 |
('friends.#(last="Murphy")#.#', []), |
| 246 |
('friends.#(last="Murphy")#|#', 2), |
| 247 |
|
| 248 |
('{}', {}), |
| 249 |
('{.}', {}), |
| 250 |
('{.invalid}', {}), |
| 251 |
('{.invalid,}', {}), |
| 252 |
('{age}', {'age': 37}), |
| 253 |
(r'{a\ge}', {r'a\ge': 37}), |
| 254 |
(r'{"a\\ge":age}', {r'a\ge': 37}), |
| 255 |
('{"a\tb":age}', {'a\tb': 37}), |
| 256 |
('{"key":age}', {'key': 37}), |
| 257 |
('{age,age}', {'age': 37}), |
| 258 |
('{age,"years":age}', {'age': 37, 'years': 37}), |
| 259 |
('{"years":age,age}', {'years': 37, 'age': 37}), |
| 260 |
('{age,name.first}', {'age': 37, 'first': 'Tom'}), |
| 261 |
('{invalid,invalid.invalid,age}', {'age': 37}), |
| 262 |
('{name.first,age,name.last}', {'first': 'Tom', 'age': 37, 'last': 'Anderson'}), |
| 263 |
('{{age}}', {'_': {'age': 37}}), |
| 264 |
('{{age},age}', {'_': {'age': 37}, 'age': 37}), |
| 265 |
('friends.0.{age,nets.#(="ig")}', {'age': 44, '_': 'ig'}), |
| 266 |
('friends.0.{age,nets.#(="ig"),invalid}', {'age': 44, '_': 'ig'}), |
| 267 |
('friends.0.{age,nets.#(="ig")#}', {'age': 44, '_': ['ig']}), |
| 268 |
('friends.#.{age,"key":first}', |
| 269 |
[{'age': 44, 'key': 'Dale'}, {'age': 68, 'key': 'Roger'}, {'age': 47, 'key': 'Jane'}]), |
| 270 |
('friends.#(age>44)#.{age,"key":first}', [{'age': 68, 'key': 'Roger'}, {'age': 47, 'key': 'Jane'}]), |
| 271 |
('friends.#(age>44)#.{age,"key":first,invalid}', [{'age': 68, 'key': 'Roger'}, {'age': 47, 'key': 'Jane'}]), |
| 272 |
(r'{age,name.first,fav\.movie}', {'age': 37, 'first': 'Tom', r'fav\.movie': 'Deer Hunter'}), |
| 273 |
('{age,name.{"name":first,"surname":last},children.@sort}', |
| 274 |
{'age': 37, '_': {'name': 'Tom', 'surname': 'Anderson'}, '@sort': ['Alex', 'Jack', 'Sara']}), |
| 275 |
('friends.{0.first,1.last,2.age}.@values', ['Dale', 'Craig', 47]), |
| 276 |
('{friends.{"a":0.{nets.{0}}}}', {'_': {'a': {'_': {'0': 'ig'}}}}), |
| 277 |
('{friends.{"a":0.{nets.{0,1}}}}', {'_': {'a': {'_': {'0': 'ig', '1': 'fb'}}}}), |
| 278 |
('friends.#.{age,first|@upper}', |
| 279 |
[{'age': 44, '@upper': 'DALE'}, {'age': 68, '@upper': 'ROGER'}, {'age': 47, '@upper': 'JANE'}]), |
| 280 |
('{friends.#.{age,"first":first|@upper}|0.first}', {'first': 'DALE'}), |
| 281 |
('{"children":children|@upper,"name":name.first,"age":age}', |
| 282 |
{'children': ['SARA', 'ALEX', 'JACK'], 'name': 'Tom', 'age': 37}), |
| 283 |
('friends.#.{age,"first":first.invalid}', [{'age': 44}, {'age': 68}, {'age': 47}]), |
| 284 |
|
| 285 |
('[]', []), |
| 286 |
('[.]', []), |
| 287 |
('[.invalid]', []), |
| 288 |
('[.invalid,]', []), |
| 289 |
('[age]', [37]), |
| 290 |
(r'[a\ge]', [37]), |
| 291 |
('[age,age]', [37, 37]), |
| 292 |
('[age,name.first]', [37, 'Tom']), |
| 293 |
('[name.first,age,invalid,invalid.invalid,name.last]', ['Tom', 37, 'Anderson']), |
| 294 |
('[[age]]', [[37]]), |
| 295 |
('[[age],age]', [[37], 37]), |
| 296 |
('friends.0.[age,nets.#(="ig")]', [44, 'ig']), |
| 297 |
('friends.0.[age,nets.#(="ig"),invalid]', [44, 'ig']), |
| 298 |
('friends.0.[age,nets.#(="ig")#]', [44, ['ig']]), |
| 299 |
('friends.#.[age,first]', [[44, 'Dale'], [68, 'Roger'], [47, 'Jane']]), |
| 300 |
('friends.#(age>44)#.[age,first]', [[68, 'Roger'], [47, 'Jane']]), |
| 301 |
('friends.#(age>44)#.[age,invalid,invalid.invalid,first]', [[68, 'Roger'], [47, 'Jane']]), |
| 302 |
(r'[age,name.first,fav\.movie]', [37, 'Tom', 'Deer Hunter']), |
| 303 |
('[age,name.[first,last],children.@sort]', [37, ['Tom', 'Anderson'], ['Alex', 'Jack', 'Sara']]), |
| 304 |
('friends.[0.first,1.last,2.age]', ['Dale', 'Craig', 47]), |
| 305 |
('[friends.[0.[nets.[0]]]]', [[[['ig']]]]), |
| 306 |
('[friends.[0.[nets.[0,1]]]]', [[[['ig', 'fb']]]]), |
| 307 |
|
| 308 |
('[{}]', [{}]), |
| 309 |
('{[]}', {'_': []}), |
| 310 |
('[{},[],{}]', [{}, [], {}]), |
| 311 |
('{"a":[]}', {'a': []}), |
| 312 |
('[{age},{name.first}]', [{'age': 37}, {'first': 'Tom'}]), |
| 313 |
('{friends.0.[age,nets.#(="ig")]}', {'_': [44, 'ig']}), |
| 314 |
('{friends.0.[age,nets.#(="ig")],age}', {'_': [44, 'ig'], 'age': 37}), |
| 315 |
('{friends.0.[invalid,nets.#(="ig")],age,invalid}', {'_': ['ig'], 'age': 37}), |
| 316 |
|
| 317 |
('!true', True), |
| 318 |
('!false', False), |
| 319 |
('!null', None), |
| 320 |
('!NaN', float('nan')), |
| 321 |
('!Infinity', float('inf')), |
| 322 |
('!-Infinity', float('-inf')), |
| 323 |
('!"key"', 'key'), |
| 324 |
('!"line \\"quotes\\""', 'line "quotes"'), |
| 325 |
('!"a\tb"', 'a\tb'), |
| 326 |
('!0', 0), |
| 327 |
('!12', 12), |
| 328 |
('!-12', -12), |
| 329 |
('!12.34', 12.34), |
| 330 |
('!12.34E2', 1234), |
| 331 |
('!12.34E+2', 1234), |
| 332 |
('!12.34e-2', 0.1234), |
| 333 |
('!-12.34e-2', -0.1234), |
| 334 |
('friends.#.!"value"', ['value', 'value', 'value']), |
| 335 |
('friends.#.!invalid', []), |
| 336 |
('friends.#|!"value"', 'value'), |
| 337 |
('friends.#(age>45)#.!"value"', ['value', 'value']), |
| 338 |
('name|!"value"', 'value'), |
| 339 |
('!{}', {}), |
| 340 |
('![]', []), |
| 341 |
('!{"name":{"first":"Tom"}}.{name.first}.first', 'Tom'), |
| 342 |
('{name.last,"key":!"value"}', {'last': 'Anderson', 'key': 'value'}), |
| 343 |
('{name.last,"key":!{"a":"b"},"invalid"}', {'last': 'Anderson', 'key': {'a': 'b'}}), |
| 344 |
('{name.last,"key":!{"c":"d"},!"valid"}', {'last': 'Anderson', 'key': {'c': 'd'}, '_': 'valid'}), |
| 345 |
('[!true,!false,!null,!Infinity,!invalid,{"name":!"andy",name.last},+Infinity,!["value1","value2"]]', |
| 346 |
[True, False, None, float('inf'), {'name': 'andy', 'last': 'Anderson'}, ['value1', 'value2']]), |
| 347 |
('[!12.34,!-12.34e-2,!true]', [12.34, -0.1234, True]), |
| 348 |
)) |
| 349 |
def test_get_ok(self, query, expected): |
| 350 |
"""It should query the JSON object and return the expected result.""" |
| 351 |
compare_values(self.object.get(query), expected) |
| 352 |
|
| 353 |
@pytest.mark.parametrize(('query', 'error'), ( |
| 354 |
|
| 355 |
('.', 'Invalid query starting with a path delimiter.'), |
| 356 |
('|', 'Invalid query starting with a path delimiter.'), |
| 357 |
('.name', 'Invalid query starting with a path delimiter.'), |
| 358 |
('|age', 'Invalid query starting with a path delimiter.'), |
| 359 |
('name..first', 'Invalid query with two consecutive path delimiters.'), |
| 360 |
('name||first', 'Invalid query with two consecutive path delimiters.'), |
| 361 |
('name.|first', 'Invalid query with two consecutive path delimiters.'), |
| 362 |
('name|.first', 'Invalid query with two consecutive path delimiters.'), |
| 363 |
('age.0', "Integer query part on unsupported object type <class 'int'>"), |
| 364 |
('friends.99', 'Index `99` out of range for sequence object with 3 items in query.'), |
| 365 |
('name.nonexistent', 'Mapping object does not have key `nonexistent`.'), |
| 366 |
('name.1', 'Mapping object does not have key `1`.'), |
| 367 |
('children.invalid', 'Invalid or unsupported query part `invalid`.'), |
| 368 |
('children.', 'Delimiter at the end of the query.'), |
| 369 |
('children\\', 'Escape character at the end of the query.'), |
| 370 |
|
| 371 |
('x*', 'No key matching pattern with wildcard `x*`'), |
| 372 |
('??????????', 'No key matching pattern with wildcard `??????????`'), |
| 373 |
('children.x*', "Wildcard matching key `x*` requires a mapping object, got <class 'list'> instead."), |
| 374 |
('(-?', 'No key matching pattern with wildcard `(-?`'), |
| 375 |
|
| 376 |
('#', "Expected a sequence like object for query part # at the end of the query, got <class 'dict'>."), |
| 377 |
('#.invalid', 'Invalid or unsupported query part `invalid`.'), |
| 378 |
('friends.#(=="Murphy")', 'Query on mapping like objects require a key before the operator.'), |
| 379 |
('friends.#(last=={1: 2})', 'Invalid value `{1: 2}` for the query key `last`'), |
| 380 |
('friends.#(invalid', 'Unbalanced parentheses `(`, 1 still opened.'), |
| 381 |
('#(first)', 'Queries are supported only for sequence like objects'), |
| 382 |
('friends.#(invalid)', 'Query for first element does not match anything.'), |
| 383 |
('friends.#(last=="invalid")', 'Query for first element does not match anything.'), |
| 384 |
('friends.#(first%"D?")', 'Query for first element does not match anything.'), |
| 385 |
('friends.#(last=="Murphy")invalid', 'Expected delimiter or end of query after closing parenthesis.'), |
| 386 |
('children.#()', 'Empty or invalid query.'), |
| 387 |
('children.#()#', 'Empty or invalid query.'), |
| 388 |
('friends.#.invalid.#()', 'Empty or invalid query.'), |
| 389 |
('friends.#.invalid.#()#', 'Empty or invalid query.'), |
| 390 |
|
| 391 |
('friends.#(last="Murphy")#|first', 'Invalid or unsupported query'), |
| 392 |
|
| 393 |
('@', 'Got empty modifier name.'), |
| 394 |
('friends.@', 'Got empty modifier name.'), |
| 395 |
('friends.@pretty:', 'Modifier with options separator `:` without any option.'), |
| 396 |
('friends.@pretty:{invalid', 'Unable to load modifier options.'), |
| 397 |
('friends.@pretty:["invalid"]', 'Expected JSON object `{...}` as modifier options.'), |
| 398 |
('friends.@invalid', 'Unknown modifier @invalid.'), |
| 399 |
('friends.@in"valid', 'Invalid modifier name @in"valid, the following characters are not allowed'), |
| 400 |
|
| 401 |
('..name', 'Invalid query starting with a path delimiter.'), |
| 402 |
|
| 403 |
(r'{"a\ge":age}', r'Failed to parse multipaths key "a\ge"'), |
| 404 |
('{"age",age}', 'Expected colon after multipaths item with key "age".'), |
| 405 |
('{]', 'Unbalanced parentheses `{`, 1 still opened.'), |
| 406 |
('{', 'Unbalanced parentheses `{`, 1 still opened.'), |
| 407 |
('{}@pretty', 'Expected delimiter or end of query after closing parenthesis.'), |
| 408 |
('[{age}}]', 'Missing separator after multipath.'), |
| 409 |
('{[age]]}', 'Missing separator after multipath.'), |
| 410 |
('[{age,name.first]},age]', 'Expected delimiter or end of query after closing parenthesis.'), |
| 411 |
|
| 412 |
('!', 'Unable to load literal JSON'), |
| 413 |
('name.!', 'Unable to load literal JSON'), |
| 414 |
('!invalid', 'Unable to load literal JSON'), |
| 415 |
(r'!in\valid', 'Unable to load literal JSON'), |
| 416 |
('!0.a', 'Invalid or unsupported query part `a`.'), |
| 417 |
('!0.1ea', 'Invalid or unsupported query part `ea`.'), |
| 418 |
('!-12.', 'Delimiter at the end of the query.'), |
| 419 |
('!-12.e', 'Invalid or unsupported query part `e`.'), |
| 420 |
('name.!invalid', 'Unable to load literal JSON'), |
| 421 |
('!"invalid', 'Unable to find end of literal string.'), |
| 422 |
('friends.#|!invalid', 'Unable to load literal JSON'), |
| 423 |
('!{true,', 'Unbalanced parentheses `{`, 1 still opened.'), |
| 424 |
('![true,', 'Unbalanced parentheses `[`, 1 still opened.'), |
| 425 |
('!"value".invalid', 'Invalid or unsupported query part `invalid`.'), |
| 426 |
('name.!"value"', 'Unable to load literal JSON: literal afer a dot delimiter.'), |
| 427 |
)) |
| 428 |
def test_get_parser_raise(self, query, error): |
| 429 |
"""It should raise a GJSONParseError error with the expected message.""" |
| 430 |
with pytest.raises(gjson.GJSONParseError, match=fr'^{re.escape(error)}'): |
| 431 |
self.object.get(query) |
| 432 |
|
| 433 |
@pytest.mark.parametrize(('query', 'error'), ( |
| 434 |
|
| 435 |
('', 'Empty query.'), |
| 436 |
|
| 437 |
('children.@keys', 'The current object does not have a keys() method.'), |
| 438 |
('children.@values', 'The current object does not have a values() method.'), |
| 439 |
('age.@group', "Modifier @group got object of type <class 'int'> as input, expected dictionary."), |
| 440 |
('children.@group', "Modifier @group got object of type <class 'list'> as input, expected dictionary."), |
| 441 |
)) |
| 442 |
def test_get_raise(self, query, error): |
| 443 |
"""It should raise a GJSONError error with the expected message.""" |
| 444 |
with pytest.raises(gjson.GJSONError, match=fr'^{re.escape(error)}'): |
| 445 |
self.object.get(query) |
| 446 |
|
| 447 |
|
| 448 |
class TestEscape: |
| 449 |
"""Test gjson for all the escape sequences.""" |
| 450 |
|
| 451 |
def setup_method(self): |
| 452 |
"""Initialize the test instance.""" |
| 453 |
self.escape = gjson.GJSON(INPUT_ESCAPE) |
| 454 |
|
| 455 |
@pytest.mark.parametrize(('query', 'expected'), ( |
| 456 |
(r'test.\*', 'valZ'), |
| 457 |
(r'test.\*v', 'val0'), |
| 458 |
(r'test.keyv\*', 'val1'), |
| 459 |
(r'test.key\*v', 'val2'), |
| 460 |
(r'test.keyv\?', 'val3'), |
| 461 |
(r'test.key\?v', 'val4'), |
| 462 |
(r'test.keyv\.', 'val5'), |
| 463 |
(r'test.key\.v', 'val6'), |
| 464 |
(r'test.keyk\*.key\?', 'val7'), |
| 465 |
('test.1key', 'val8'), |
| 466 |
)) |
| 467 |
def test_get_ok(self, query, expected): |
| 468 |
"""It should query the escape test JSON and return the expected result.""" |
| 469 |
assert self.escape.get(query, quiet=True) == expected |
| 470 |
|
| 471 |
|
| 472 |
class TestBasic: |
| 473 |
"""Test gjson for basic queries.""" |
| 474 |
|
| 475 |
def setup_method(self): |
| 476 |
"""Initialize the test instance.""" |
| 477 |
self.basic = gjson.GJSON(INPUT_BASIC) |
| 478 |
|
| 479 |
@pytest.mark.parametrize(('query', 'expected'), ( |
| 480 |
('loggy.programmers.#(age=101).firstName', 1002.3), |
| 481 |
('loggy.programmers.#(firstName != "Brett").firstName', 'Jason'), |
| 482 |
('loggy.programmers.#(firstName % "Bre*").email', 'aaaa'), |
| 483 |
('loggy.programmers.#(firstName !% "Bre*").email', 'bbbb'), |
| 484 |
('loggy.programmers.#(firstName == "Brett").email', 'aaaa'), |
| 485 |
('loggy.programmers.#.firstName', ['Brett', 'Jason', 'Elliotte', 1002.3]), |
| 486 |
('loggy.programmers.#.asd', []), |
| 487 |
('items.3.tags.#', 3), |
| 488 |
('items.3.points.1.#', 2), |
| 489 |
('items.#', 8), |
| 490 |
('vals.#', 3), |
| 491 |
('name2.here', r'B\"R'), |
| 492 |
('arr.#', 6), |
| 493 |
('arr.3.hello', 'world'), |
| 494 |
('name.first', 'tom'), |
| 495 |
('name.last', None), |
| 496 |
('age', 100), |
| 497 |
('happy', True), |
| 498 |
('immortal', False), |
| 499 |
('noop', {'what is a wren?': 'a bird'}), |
| 500 |
|
| 501 |
('arr.@join', {'hello': 'world'}), |
| 502 |
)) |
| 503 |
def test_get_ok(self, query, expected): |
| 504 |
"""It should query the basic test JSON and return the expected result.""" |
| 505 |
assert self.basic.get(query) == expected |
| 506 |
|
| 507 |
|
| 508 |
class TestList: |
| 509 |
"""Test gjson queries on a list object.""" |
| 510 |
|
| 511 |
def setup_method(self): |
| 512 |
"""Initialize the test instance.""" |
| 513 |
self.list = gjson.GJSON(INPUT_LIST) |
| 514 |
|
| 515 |
@pytest.mark.parametrize(('query', 'expected'), ( |
| 516 |
|
| 517 |
('#.first', ['Dale', 'Jane']), |
| 518 |
('#.first.#', []), |
| 519 |
('#.first|#', 2), |
| 520 |
('#.0', []), |
| 521 |
('#.#', []), |
| 522 |
|
| 523 |
('#(first)#', [{'first': 'Dale'}, {'first': 'Jane'}]), |
| 524 |
('#(first)', {'first': 'Dale'}), |
| 525 |
('#(last)#', [{'last': 'Murphy'}]), |
| 526 |
('#(last)', {'last': 'Murphy'}), |
| 527 |
|
| 528 |
('@join', {'first': 'Jane', 'last': 'Murphy'}), |
| 529 |
|
| 530 |
('#.{first.@reverse}', [{'@reverse': 'Dale'}, {'@reverse': 'Jane'}, {}]), |
| 531 |
)) |
| 532 |
def test_get_ok(self, query, expected): |
| 533 |
"""It should query the list test JSON and return the expected result.""" |
| 534 |
assert self.list.get(query, quiet=False) == expected |
| 535 |
|
| 536 |
@pytest.mark.parametrize(('query', 'error'), ( |
| 537 |
|
| 538 |
('#|first', 'Invalid or unsupported query part `first`.'), |
| 539 |
('#|0', 'Integer query part after a pipe delimiter on an sequence like object.'), |
| 540 |
('#|#', 'The pipe delimiter cannot immediately follow the # element.'), |
| 541 |
)) |
| 542 |
def test_get_raise(self, query, error): |
| 543 |
"""It should raise a GJSONError error with the expected message.""" |
| 544 |
with pytest.raises(gjson.GJSONParseError, match=fr'^{re.escape(error)}'): |
| 545 |
self.list.get(query) |
| 546 |
|
| 547 |
|
| 548 |
class TestFlattenModifier: |
| 549 |
"""Test gjson @flatten modifier.""" |
| 550 |
|
| 551 |
def setup_method(self): |
| 552 |
"""Initialize the test instance.""" |
| 553 |
self.list = gjson.GJSON(json.loads('[1, [2], [3, 4], [5, [6, 7]], [8, [9, [10, 11]]]]')) |
| 554 |
|
| 555 |
@pytest.mark.parametrize(('query', 'expected'), ( |
| 556 |
('@flatten', [1, 2, 3, 4, 5, [6, 7], 8, [9, [10, 11]]]), |
| 557 |
('@flatten:{"deep":true}', [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]), |
| 558 |
)) |
| 559 |
def test_get(self, query, expected): |
| 560 |
"""It should correctly flatten the given object.""" |
| 561 |
assert self.list.get(query, quiet=True) == expected |
| 562 |
|
| 563 |
|
| 564 |
class TestTruthiness: |
| 565 |
"""Testing gjson with an input object with truthy/falsy objects.""" |
| 566 |
|
| 567 |
def setup_method(self): |
| 568 |
"""Initialize the test instance.""" |
| 569 |
self.object = gjson.GJSON(INPUT_TRUTHINESS) |
| 570 |
|
| 571 |
@pytest.mark.parametrize(('query', 'expected'), ( |
| 572 |
('vals.#(b==~true).a', 1), |
| 573 |
('vals.#(b==~true)#.a', [1, 2, 4, 6, 7, 8]), |
| 574 |
('vals.#(b==~false).a', 3), |
| 575 |
('vals.#(b==~false)#.a', [3, 5, 9, 10, 11]), |
| 576 |
('vals.#(b==~"invalid")#', []), |
| 577 |
)) |
| 578 |
def test_get_ok(self, query, expected): |
| 579 |
"""It should query the JSON object and return the expected result.""" |
| 580 |
compare_values(self.object.get(query), expected) |
| 581 |
|
| 582 |
@pytest.mark.parametrize(('query', 'error'), ( |
| 583 |
('vals.#(b==~"invalid")', |
| 584 |
"Queries ==~ operator requires a boolean value, got <class 'str'> instead: `invalid`"), |
| 585 |
)) |
| 586 |
def test_get_raise(self, query, error): |
| 587 |
"""It should raise a GJSONError error with the expected message.""" |
| 588 |
with pytest.raises(gjson.GJSONError, match=fr'^{re.escape(error)}'): |
| 589 |
self.object.get(query) |
| 590 |
|
| 591 |
|
| 592 |
class TestNestedQueries: |
| 593 |
"""Testing gjson nested queries.""" |
| 594 |
|
| 595 |
def setup_method(self): |
| 596 |
"""Initialize the test instance.""" |
| 597 |
self.object = gjson.GJSON(INPUT_NESTED_QUERIES) |
| 598 |
|
| 599 |
@pytest.mark.parametrize(('query', 'expected'), ( |
| 600 |
|
| 601 |
('key.#(level1.#(level2.#(level3)))', INPUT_NESTED_QUERIES['key'][0]), |
| 602 |
('key.#(level1.#(level2.#(level3)))#', INPUT_NESTED_QUERIES['key'][0:2]), |
| 603 |
('key.#(level1.#(level2.#(level3.#(==0))))#', []), |
| 604 |
('key.#(level1.#(level2.#(level3.#(=1))))', INPUT_NESTED_QUERIES['key'][0]), |
| 605 |
('key.#(level1.#(level2.#(level3.#(=1)#)#)#)', INPUT_NESTED_QUERIES['key'][0]), |
| 606 |
('key.#(level1.#(level2.#(level3.#(==1))))#', [INPUT_NESTED_QUERIES['key'][0]]), |
| 607 |
('key.#(level1.#(level2.#(level3.#(==2))))', INPUT_NESTED_QUERIES['key'][0]), |
| 608 |
('key.#(level1.#(level2.#(level3.#(=2))))#', INPUT_NESTED_QUERIES['key'][0:2]), |
| 609 |
|
| 610 |
('key.#(#(#(level3)))', INPUT_NESTED_QUERIES['key'][2]), |
| 611 |
('key.#(#(#(level3)))#', INPUT_NESTED_QUERIES['key'][2:4]), |
| 612 |
('key.#(#(#(level3.#(==0))))#', []), |
| 613 |
('key.#(#(#(level3.#(==1))))', INPUT_NESTED_QUERIES['key'][2]), |
| 614 |
('key.#(#(#(level3.#(==1)#)#)#)', INPUT_NESTED_QUERIES['key'][2]), |
| 615 |
('key.#(#(#(level3.#(==1))))#', [INPUT_NESTED_QUERIES['key'][2]]), |
| 616 |
('key.#(#(#(level3.#(==2))))', INPUT_NESTED_QUERIES['key'][2]), |
| 617 |
('key.#(#(#(level3.#(==2))))#', INPUT_NESTED_QUERIES['key'][2:4]), |
| 618 |
('key.#(#(#(level3.#(>=4))))', INPUT_NESTED_QUERIES['key'][3]), |
| 619 |
('key.#(#(#(level3.#(>=4))))#', [INPUT_NESTED_QUERIES['key'][3]]), |
| 620 |
|
| 621 |
('key.#(mixed.#(#(level4)))', INPUT_NESTED_QUERIES['key'][-1]), |
| 622 |
('key.#(mixed.#(#(level4)))#', [INPUT_NESTED_QUERIES['key'][-1]]), |
| 623 |
)) |
| 624 |
def test_get_ok(self, query, expected): |
| 625 |
"""It should query the JSON object and return the expected result.""" |
| 626 |
compare_values(self.object.get(query), expected) |
| 627 |
|
| 628 |
@pytest.mark.parametrize(('query', 'error'), ( |
| 629 |
('key.#(level1.#(level2.#(level3.#(==0))))', 'Query for first element does not match anything.'), |
| 630 |
('key.#(#(#(level3.#(==0))))', 'Query for first element does not match anything.'), |
| 631 |
)) |
| 632 |
def test_get_raise(self, query, error): |
| 633 |
"""It should raise a GJSONError error with the expected message.""" |
| 634 |
with pytest.raises(gjson.GJSONError, match=fr'^{re.escape(error)}'): |
| 635 |
self.object.get(query) |
| 636 |
|
| 637 |
|
| 638 |
@pytest.mark.parametrize(('query', 'expected'), ( |
| 639 |
('0.0', 'zero'), |
| 640 |
('0|0', 'zero'), |
| 641 |
('#.0', ['zero']), |
| 642 |
('#.1', ['one', 'one']), |
| 643 |
('#.9', []), |
| 644 |
('#(0="zero")#|0', {'0': 'zero', '1': 'one'}), |
| 645 |
('#(0="zero")#.1', ['one']), |
| 646 |
('#(0="zero")#.9', []), |
| 647 |
('#(0="invalid")#.1', []), |
| 648 |
)) |
| 649 |
def test_get_integer_mapping_keys_ok(query, expected): |
| 650 |
"""It should return the expected result.""" |
| 651 |
obj = gjson.GJSON([{'0': 'zero', '1': 'one'}, {'1': 'one'}]) |
| 652 |
assert obj.get(query, quiet=True) == expected |
| 653 |
|
| 654 |
|
| 655 |
@pytest.mark.parametrize(('query', 'error'), ( |
| 656 |
('0.1', 'Mapping object does not have key `1`.'), |
| 657 |
('#|0', 'Integer query part after a pipe delimiter on an sequence like object.'), |
| 658 |
('#|9', 'Integer query part after a pipe delimiter on an sequence like object.'), |
| 659 |
('#(0="zero")#|1', 'Index `1` out of range for sequence object with 1 items in query.'), |
| 660 |
)) |
| 661 |
def test_get_integer_mapping_keys_raise(query, error): |
| 662 |
"""It should return the expected result.""" |
| 663 |
with pytest.raises(gjson.GJSONError, match=fr'^{re.escape(error)}'): |
| 664 |
|
| 665 |
gjson.GJSON([{'0': 'zero'}]).get(query) |
| 666 |
|
| 667 |
|
| 668 |
@pytest.mark.parametrize('modifier', ('@valid', '@this')) |
| 669 |
def test_get_modifier_unmodified_ok(modifier): |
| 670 |
"""It should return the same object.""" |
| 671 |
obj = gjson.GJSON(INPUT_OBJECT) |
| 672 |
assert obj.get(modifier, quiet=True) == INPUT_OBJECT |
| 673 |
|
| 674 |
|
| 675 |
def test_get_modifier_valid_raise(): |
| 676 |
"""It should return None if the object is invalid JSON and quiet is True.""" |
| 677 |
obj = gjson.GJSON({'invalid': {1, 2}}) |
| 678 |
assert obj.get('@valid', quiet=True) is None |
| 679 |
|
| 680 |
|
| 681 |
@pytest.mark.parametrize(('data', 'expected'), ( |
| 682 |
('[3, 1, 5, 8, 2]', [1, 2, 3, 5, 8]), |
| 683 |
('{"b": 2, "d": 4, "c": 3, "a": 1}', {'a': 1, 'b': 2, 'c': 3, 'd': 4}), |
| 684 |
('"a string"', None), |
| 685 |
)) |
| 686 |
def test_get_modifier_sort(data, expected): |
| 687 |
"""It should return the object sorted.""" |
| 688 |
obj = gjson.GJSON(json.loads(data)) |
| 689 |
compare_values(obj.get('@sort', quiet=True), expected) |
| 690 |
|
| 691 |
|
| 692 |
@pytest.mark.parametrize(('data', 'query', 'expected'), ( |
| 693 |
({'a': '{"b": 25}'}, 'a.@fromstr', {'b': 25}), |
| 694 |
({'a': '{"b": 25}'}, '[email protected]', 25), |
| 695 |
)) |
| 696 |
def test_get_modifier_fromstr_ok(data, query, expected): |
| 697 |
"""It should load the JSON-encoded string.""" |
| 698 |
obj = gjson.GJSON(data) |
| 699 |
assert obj.get(query, quiet=True) == expected |
| 700 |
|
| 701 |
|
| 702 |
@pytest.mark.parametrize(('query', 'error'), ( |
| 703 |
('a.@fromstr', 'The current @fromstr input object cannot be converted to JSON.'), |
| 704 |
('b.@fromstr', "Modifier @fromstr got object of type <class 'dict'> as input, expected string or bytes."), |
| 705 |
)) |
| 706 |
def test_get_modifier_fromstr_raise(query, error): |
| 707 |
"""It should raise a GJSONError if the JSON-encoded string has invalid JSON.""" |
| 708 |
obj = gjson.GJSON({'a': '{"invalid: json"', 'b': {'not': 'a string'}}) |
| 709 |
with pytest.raises(gjson.GJSONError, match=fr'^{re.escape(error)}'): |
| 710 |
obj.get(query) |
| 711 |
|
| 712 |
|
| 713 |
def test_get_modifier_tostr_raise(): |
| 714 |
"""It should raise a GJSONError if the object cannot be JSON-encoded.""" |
| 715 |
obj = gjson.GJSON({'a': {1, 2, 3}}) |
| 716 |
match = re.escape('The current object cannot be converted to a JSON-encoded string for @tostr.') |
| 717 |
with pytest.raises(gjson.GJSONError, match=fr'^{match}'): |
| 718 |
obj.get('a.@tostr') |
| 719 |
|
| 720 |
|
| 721 |
def test_get_modifier_group_ok(): |
| 722 |
"""It should group the dict of lists into a list of dicts.""" |
| 723 |
obj = gjson.GJSON({ |
| 724 |
'invalid1': 5, |
| 725 |
'id': ['123', '456', '789'], |
| 726 |
'val': [2, 1], |
| 727 |
'invalid2': 'invalid', |
| 728 |
'unit': ['ms', 's', 's', 'ms'], |
| 729 |
}) |
| 730 |
assert obj.get('@group') == [ |
| 731 |
{'id': '123', 'val': 2, 'unit': 'ms'}, |
| 732 |
{'id': '456', 'val': 1, 'unit': 's'}, |
| 733 |
{'id': '789', 'unit': 's'}, |
| 734 |
{'unit': 'ms'}, |
| 735 |
] |
| 736 |
|
| 737 |
|
| 738 |
def test_get_modifier_group_empty(): |
| 739 |
"""It should return an empty list if no values are lists or are empty.""" |
| 740 |
obj = gjson.GJSON({'invalid1': 5, 'invalid2': 'invalid', 'invalid3': {'a': 5}, 'id': []}) |
| 741 |
assert obj.get('@group') == [] |
| 742 |
|
| 743 |
|
| 744 |
def test_get_integer_index_on_mapping(): |
| 745 |
"""It should access the integer as string key correctly.""" |
| 746 |
obj = gjson.GJSON(json.loads('{"1": 5, "11": 7}')) |
| 747 |
assert obj.get('1') == 5 |
| 748 |
assert obj.get('11') == 7 |
| 749 |
|
| 750 |
|
| 751 |
def test_module_get(): |
| 752 |
"""It should return the queried object.""" |
| 753 |
assert gjson.get({'key': 'value'}, 'key') == 'value' |
| 754 |
|
| 755 |
|
| 756 |
def test_gjson_get_gjson_ok(): |
| 757 |
"""It should return the queried object as a GJSON object.""" |
| 758 |
ret = gjson.GJSON(INPUT_OBJECT).get_gjson('children') |
| 759 |
assert isinstance(ret, gjson.GJSON) |
| 760 |
assert str(ret) == '["Sara", "Alex", "Jack"]' |
| 761 |
|
| 762 |
|
| 763 |
@pytest.mark.parametrize('kwargs', ({}, {'quiet': False})) |
| 764 |
def test_gjson_get_gjson_raise(kwargs): |
| 765 |
"""It should raise a GJSONError if the quiet parameter is not passed or is False.""" |
| 766 |
with pytest.raises(gjson.GJSONError, match=r'^Mapping object does not have key `nonexistent`.'): |
| 767 |
gjson.GJSON(INPUT_OBJECT).get_gjson('nonexistent', **kwargs) |
| 768 |
|
| 769 |
|
| 770 |
@pytest.mark.parametrize(('data', 'num', 'expected'), ( |
| 771 |
|
| 772 |
('[1, 2, 3, 4, 5]', None, {1: 1, 2: 1, 3: 1, 4: 1, 5: 1}), |
| 773 |
('[1, 2, 3, 4, 5]', 0, {}), |
| 774 |
('[1, 2, 3, 4, 5]', 2, {1: 1, 2: 1}), |
| 775 |
('[1, 1, 1, 1, 1]', None, {1: 5}), |
| 776 |
('[1, 1, 1, 1, 1]', 1, {1: 5}), |
| 777 |
('[1, 1, 1, 2, 2, 3]', None, {1: 3, 2: 2, 3: 1}), |
| 778 |
('[1, 1, 1, 2, 2, 3, 3, 3, 3]', None, {3: 4, 1: 3, 2: 2}), |
| 779 |
('[1, 1, 1, 2, 2, 3, 3, 3, 3]', 2, {3: 4, 1: 3}), |
| 780 |
|
| 781 |
('{"key": "value"}', None, None), |
| 782 |
('1', None, None), |
| 783 |
('"value"', None, None), |
| 784 |
)) |
| 785 |
def test_get_modifier_top_n(data, num, expected): |
| 786 |
"""It should return the top N common items.""" |
| 787 |
obj = gjson.GJSON(json.loads(data)) |
| 788 |
if num is not None: |
| 789 |
compare_values(obj.get(f'@top_n:{{"n": {num}}}', quiet=True), expected) |
| 790 |
else: |
| 791 |
compare_values(obj.get('@top_n', quiet=True), expected) |
| 792 |
|
| 793 |
|
| 794 |
@pytest.mark.parametrize(('num', 'expected'), ( |
| 795 |
(0, {}), |
| 796 |
(1, {'c': 12}), |
| 797 |
(2, {'c': 12, 'a': 8}), |
| 798 |
(3, {'c': 12, 'a': 8, 'd': 4}), |
| 799 |
(4, {'c': 12, 'a': 8, 'd': 4, 'b': 3.5}), |
| 800 |
(None, {'c': 12, 'a': 8, 'd': 4, 'b': 3.5}), |
| 801 |
)) |
| 802 |
def test_get_modifier_sum_n_valid(num, expected): |
| 803 |
"""It should group and sum and return the top N items.""" |
| 804 |
obj = gjson.GJSON(INPUT_SUM_N) |
| 805 |
if num is not None: |
| 806 |
compare_values(obj.get(f'@sum_n:{{"group": "key", "sum": "value", "n": {num}}}', quiet=True), expected) |
| 807 |
else: |
| 808 |
compare_values(obj.get('@sum_n:{"group": "key", "sum": "value"}', quiet=True), expected) |
| 809 |
|
| 810 |
|
| 811 |
@pytest.mark.parametrize('data', ( |
| 812 |
'{"an": "object"}', |
| 813 |
'"a string"', |
| 814 |
'1', |
| 815 |
)) |
| 816 |
def test_get_modifier_sum_n_invalid_data(data): |
| 817 |
"""It should raise a GJSONError if the input is invalid.""" |
| 818 |
obj = gjson.GJSON(json.loads(data)) |
| 819 |
with pytest.raises(gjson.GJSONError, match=r'^@sum_n modifier not supported for object of type'): |
| 820 |
obj.get('@sum_n:{"group": "key", "sum": "value"}') |
| 821 |
|
| 822 |
|
| 823 |
@pytest.mark.parametrize('options', ( |
| 824 |
'', |
| 825 |
':{}', |
| 826 |
':{"group": "invalid", "sum": "value"}', |
| 827 |
':{"group": "key", "sum": "invalid"}', |
| 828 |
':{"group": "key", "sum": "other"}', |
| 829 |
':{"group": "other", "sum": "value"}', |
| 830 |
)) |
| 831 |
def test_get_modifier_sum_n_invalid_options(options): |
| 832 |
"""It should raise a GJSONError if the options are invalid.""" |
| 833 |
obj = gjson.GJSON(INPUT_SUM_N) |
| 834 |
with pytest.raises(gjson.GJSONError, match=r'^Modifier @sum_n raised an exception'): |
| 835 |
obj.get(f'@sum_n{options}') |
| 836 |
|
| 837 |
|
| 838 |
class TestJSONOutput: |
| 839 |
"""Test class for all JSON output functionalities.""" |
| 840 |
|
| 841 |
def setup_method(self): |
| 842 |
"""Initialize the test instance.""" |
| 843 |
self.obj = {'key': 'value', 'hello world': '\u3053\u3093\u306b\u3061\u306f\u4e16\u754c'} |
| 844 |
self.query = 'key' |
| 845 |
self.value = '"value"' |
| 846 |
self.gjson = gjson.GJSON(self.obj) |
| 847 |
|
| 848 |
def test_module_get_as_str(self): |
| 849 |
"""It should return the queried object as a JSON string.""" |
| 850 |
assert gjson.get(self.obj, self.query, as_str=True) == self.value |
| 851 |
assert gjson.get(self.obj, '', as_str=True, quiet=True) == '' |
| 852 |
|
| 853 |
def test_module_get_str(self): |
| 854 |
"""It should return the string representation of the object.""" |
| 855 |
assert str(self.gjson) == '{"key": "value", "hello world": "\u3053\u3093\u306b\u3061\u306f\u4e16\u754c"}' |
| 856 |
|
| 857 |
def test_gjson_getj(self): |
| 858 |
"""It should return the queried object as a JSON string.""" |
| 859 |
assert self.gjson.getj(self.query) == self.value |
| 860 |
assert self.gjson.getj('', quiet=True) == '' |
| 861 |
|
| 862 |
def test_module_get_as_str_raise(self): |
| 863 |
"""It should raise a GJSONError with the proper message on failure.""" |
| 864 |
with pytest.raises(gjson.GJSONError, match=r'^Empty query.'): |
| 865 |
gjson.get(self.obj, '', as_str=True) |
| 866 |
|
| 867 |
def test_gjson_get_as_str_raise(self): |
| 868 |
"""It should raise a GJSONError with the proper message on failure.""" |
| 869 |
with pytest.raises(gjson.GJSONError, match=r'^Empty query.'): |
| 870 |
self.gjson.getj('') |
| 871 |
|
| 872 |
@pytest.mark.parametrize(('query', 'expected'), ( |
| 873 |
('@pretty', '{\n "key": "value",\n "hello world": "\u3053\u3093\u306b\u3061\u306f\u4e16\u754c"\n}'), |
| 874 |
('@pretty:{"indent": 4}', |
| 875 |
'{\n "key": "value",\n "hello world": "\u3053\u3093\u306b\u3061\u306f\u4e16\u754c"\n}'), |
| 876 |
('@pretty:{"indent": "\t"}', |
| 877 |
'{\n\t"key": "value",\n\t"hello world": "\u3053\u3093\u306b\u3061\u306f\u4e16\u754c"\n}'), |
| 878 |
|
| 879 |
('{key,"another":key}.@pretty', '{\n "key": "value",\n "another": "value"\n}'), |
| 880 |
)) |
| 881 |
def test_modifier_pretty(self, query, expected): |
| 882 |
"""It should prettyfy the JSON string based on the parameters.""" |
| 883 |
assert self.gjson.getj(query) == expected |
| 884 |
|
| 885 |
def test_modifier_pretty_sort_keys_prefix(self): |
| 886 |
"""It should prettyfy the JSON string and sort the keys.""" |
| 887 |
output = gjson.GJSON({'key2': 'value2', 'key1': 'value1'}).getj('@pretty:{"sortKeys": true, "prefix": "## "}') |
| 888 |
assert output == '## {\n## "key1": "value1",\n## "key2": "value2"\n## }' |
| 889 |
|
| 890 |
def test_modifier_ugly(self): |
| 891 |
"""It should uglyfy the JSON string.""" |
| 892 |
assert gjson.get(self.obj, '@ugly', as_str=True) == ( |
| 893 |
'{"key":"value","hello world":"\u3053\u3093\u306b\u3061\u306f\u4e16\u754c"}') |
| 894 |
|
| 895 |
def test_output_unicode(self): |
| 896 |
"""It should return unicode characters as-is.""" |
| 897 |
assert gjson.get(self.obj, 'hello world', as_str=True) == '"\u3053\u3093\u306b\u3061\u306f\u4e16\u754c"' |
| 898 |
|
| 899 |
def test_modifier_ascii(self): |
| 900 |
"""It should escape all non-ASCII characters.""" |
| 901 |
assert gjson.get(self.obj, 'hello world.@ascii', as_str=True) == ( |
| 902 |
'"\\u3053\\u3093\\u306b\\u3061\\u306f\\u4e16\\u754c"') |
| 903 |
|
| 904 |
|
| 905 |
def custom_sum(options, obj, *, last): |
| 906 |
"""Sum items in list. Custom modifier function to be used in tests.""" |
| 907 |
assert last is True |
| 908 |
assert options == {} |
| 909 |
if not isinstance(obj, list): |
| 910 |
raise TypeError('@sum can be used only on lists') |
| 911 |
|
| 912 |
return sum(obj) |
| 913 |
|
| 914 |
|
| 915 |
class TestCustomModifiers: |
| 916 |
"""Test class for custom modifiers.""" |
| 917 |
|
| 918 |
def setup_method(self): |
| 919 |
"""Initialize the test instance.""" |
| 920 |
self.valid_obj = [1, 2, 3, 4, 5] |
| 921 |
self.invalid_obj = 'invalid' |
| 922 |
self.query = '@sum' |
| 923 |
|
| 924 |
def test_gjson_register_modifier_ok(self): |
| 925 |
"""It should register a valid modifier.""" |
| 926 |
obj = gjson.GJSON(self.valid_obj) |
| 927 |
obj.register_modifier('sum', custom_sum) |
| 928 |
assert obj.get(self.query) == 15 |
| 929 |
|
| 930 |
def test_gjson_register_modifier_with_escape_ok(self): |
| 931 |
"""It should register a valid modifier with escaped characters in the name.""" |
| 932 |
obj = gjson.GJSON(self.valid_obj) |
| 933 |
obj.register_modifier('sum\\=', custom_sum) |
| 934 |
assert obj.get('@sum\\=') == 15 |
| 935 |
|
| 936 |
@pytest.mark.parametrize('char', MODIFIER_NAME_RESERVED_CHARS) |
| 937 |
def test_gjson_register_modifier_invalid_name(self, char): |
| 938 |
"""It should raise a GJSONError if trying to register a modifier with a name with not allowed characters.""" |
| 939 |
obj = gjson.GJSON(self.valid_obj) |
| 940 |
name = fr'a{char}b' |
| 941 |
with pytest.raises( |
| 942 |
gjson.GJSONError, |
| 943 |
match=fr'^Unable to register modifier `{re.escape(name)}`, contains at least one not allowed'): |
| 944 |
obj.register_modifier(name, custom_sum) |
| 945 |
|
| 946 |
def test_gjson_register_modifier_override_builtin(self): |
| 947 |
"""It should raise a GJSONError if trying to register a modifier with the same name of a built-in one.""" |
| 948 |
obj = gjson.GJSON(self.valid_obj) |
| 949 |
match = re.escape('Unable to register a modifier with the same name of the built-in modifier: @valid') |
| 950 |
with pytest.raises(gjson.GJSONError, match=fr'^{match}'): |
| 951 |
obj.register_modifier('valid', custom_sum) |
| 952 |
|
| 953 |
def test_gjson_register_modifier_not_callable(self): |
| 954 |
"""It should raise a GJSONError if trying to register a modifier that is not callable.""" |
| 955 |
obj = gjson.GJSON(self.valid_obj) |
| 956 |
match = re.escape('The given func "not-callable" for the custom modifier @sum does not adhere to the ' |
| 957 |
'gjson.ModifierProtocol.') |
| 958 |
with pytest.raises(gjson.GJSONError, match=fr'^{match}'): |
| 959 |
obj.register_modifier('sum', 'not-callable') |
| 960 |
|
| 961 |
def test_gjsonobj_custom_modifiers_ok(self): |
| 962 |
"""It should register a valid modifier.""" |
| 963 |
obj = gjson.GJSONObj(self.valid_obj, self.query, custom_modifiers={'sum': custom_sum}) |
| 964 |
assert obj.get() == 15 |
| 965 |
|
| 966 |
def test_gjsonobj_custom_modifiers_raise(self): |
| 967 |
"""It should encapsulate the modifier raised exception in a GJSONError.""" |
| 968 |
with pytest.raises(gjson.GJSONError, match=fr'^{re.escape("Modifier @sum raised an exception")}'): |
| 969 |
gjson.GJSONObj(self.invalid_obj, self.query, custom_modifiers={'sum': custom_sum}).get() |
| 970 |
|
| 971 |
def test_gjsonobj_custom_modifiers_override_builtin(self): |
| 972 |
"""It should raise a GJSONError if passing custom modifiers that have the same name of a built-in one.""" |
| 973 |
with pytest.raises(gjson.GJSONError, |
| 974 |
match=r"^Some provided custom_modifiers have the same name of built-in ones: {'valid'}"): |
| 975 |
gjson.GJSONObj(self.valid_obj, self.query, custom_modifiers={'valid': custom_sum}) |
| 976 |
|
| 977 |
def test_gjsoniobj_custom_modifiers_not_callable(self): |
| 978 |
"""It should raise a GJSONError if passing custom modifiers that are not callable.""" |
| 979 |
match = re.escape('The given func "not-callable" for the custom modifier @sum does not adhere to the') |
| 980 |
with pytest.raises(gjson.GJSONError, match=fr'^{match}'): |
| 981 |
gjson.GJSONObj(self.valid_obj, self.query, custom_modifiers={'sum': 'not-callable'}) |
| 982 |
|
| 983 |
def test_gjsonobj_builtin_modifiers(self): |
| 984 |
"""It should return a set with the names of the built-in modifiers.""" |
| 985 |
expected = {'ascii', 'flatten', 'fromstr', 'group', 'join', 'keys', 'pretty', 'reverse', 'sort', 'sum_n', |
| 986 |
'this', 'top_n', 'tostr', 'valid', 'values', 'ugly'} |
| 987 |
assert gjson.GJSONObj.builtin_modifiers() == expected |