Debian Codegraph @

tests/test_search.py

raw
1 #!/usr/bin/env python
2 import pytest
3 import ipaddress
4 import logging
5 from typing import Union
6 from deepdiff import DeepSearch, grep
7 from datetime import datetime
8 logging.disable(logging.CRITICAL)
9
10 item = "somewhere"
11
12
13 class CustomClass:
14 def __init__(self, a, b=None):
15 self.a = a
16 self.b = b
17
18 def __str__(self):
19 return "({}, {})".format(self.a, self.b)
20
21 def __repr__(self):
22 return self.__str__()
23
24
25 class ClassWithIp:
26 """Class containing single data member to demonstrate deepdiff infinite iterate over IPv6Interface"""
27
28 def __init__(self, addr: str):
29 self.field: Union[
30 ipaddress.IPv4Network,
31 ipaddress.IPv6Network,
32 ipaddress.IPv4Interface,
33 ipaddress.IPv6Interface,
34 ] = ipaddress.IPv6Network(addr)
35
36
37
38 class TestDeepSearch:
39 """DeepSearch Tests."""
40
41 def test_number_in_list(self):
42 obj = ["a", 10, 20]
43 item = 10
44 result = {"matched_values": {'root[1]'}}
45 assert DeepSearch(obj, item, verbose_level=1) == result
46
47 def test_number_in_list2(self):
48 obj = ["a", "10", 10, 20]
49 item = 10
50 result = {"matched_values": {'root[2]'}}
51 assert DeepSearch(obj, item, verbose_level=1) == result
52
53 def test_number_in_list3(self):
54 obj = ["a", "10", 10, 20]
55 item = "10"
56 result = {"matched_values": {'root[1]'}}
57 assert DeepSearch(obj, item, verbose_level=1) == result
58
59 def test_number_in_list_strict_false(self):
60 obj = ["a", "10", 10, 20]
61 item = "20"
62 result = {"matched_values": {'root[3]'}}
63 assert DeepSearch(obj, item, verbose_level=1, strict_checking=False) == result
64
65 def test_string_in_root(self):
66 obj = "long string somewhere"
67 result = {"matched_values": {'root'}}
68 assert DeepSearch(obj, item, verbose_level=1) == result
69
70 def test_string_in_root_verbose(self):
71 obj = "long string somewhere"
72 result = {"matched_values": {'root': "long string somewhere"}}
73 assert DeepSearch(obj, item, verbose_level=2) == result
74
75 def test_string_in_tuple(self):
76 obj = ("long", "string", 0, "somewhere")
77 result = {"matched_values": {'root[3]'}}
78 assert DeepSearch(obj, item, verbose_level=1) == result
79
80 def test_string_in_list(self):
81 obj = ["long", "string", 0, "somewhere"]
82 result = {"matched_values": {'root[3]'}}
83 assert DeepSearch(obj, item, verbose_level=1) == result
84
85 def test_string_in_list_verbose(self):
86 obj = ["long", "string", 0, "somewhere"]
87 result = {"matched_values": {'root[3]': "somewhere"}}
88 assert DeepSearch(obj, item, verbose_level=2) == result
89
90 def test_string_in_list_verbose2(self):
91 obj = ["long", "string", 0, "somewhere great!"]
92 result = {"matched_values": {'root[3]': "somewhere great!"}}
93 assert DeepSearch(obj, item, verbose_level=2) == result
94
95 def test_string_in_list_verbose3(self):
96 obj = ["long somewhere", "string", 0, "somewhere great!"]
97 result = {
98 "matched_values": {
99 'root[0]': 'long somewhere',
100 'root[3]': "somewhere great!"
101 }
102 }
103 assert DeepSearch(obj, item, verbose_level=2) == result
104
105 def test_int_in_dictionary(self):
106 obj = {"long": "somewhere", "num": 2, 0: 0, "somewhere": "around"}
107 item = 2
108 result = {'matched_values': {"root['num']"}}
109 ds = DeepSearch(obj, item, verbose_level=1)
110 assert ds == result
111
112 def test_string_in_dictionary(self):
113 obj = {"long": "somewhere", "string": 2, 0: 0, "somewhere": "around"}
114 result = {
115 'matched_paths': {"root['somewhere']"},
116 'matched_values': {"root['long']"}
117 }
118 ds = DeepSearch(obj, item, verbose_level=1)
119 assert ds == result
120
121 def test_string_in_dictionary_case_insensitive(self):
122 obj = {"long": "Somewhere over there!", "string": 2, 0: 0, "SOMEWHERE": "around"}
123 result = {
124 'matched_paths': {"root['SOMEWHERE']"},
125 'matched_values': {"root['long']"}
126 }
127 ds = DeepSearch(obj, item, verbose_level=1, case_sensitive=False)
128 assert ds == result
129
130 def test_string_in_dictionary_key_case_insensitive_partial(self):
131 obj = {"SOMEWHERE here": "around"}
132 result = {
133 'matched_paths': {"root['SOMEWHERE here']"}
134 }
135 ds = DeepSearch(obj, item, verbose_level=1, case_sensitive=False)
136 assert ds == result
137
138 def test_string_in_dictionary_verbose(self):
139 obj = {"long": "somewhere", "string": 2, 0: 0, "somewhere": "around"}
140 result = {
141 'matched_paths': {
142 "root['somewhere']": "around"
143 },
144 'matched_values': {
145 "root['long']": "somewhere"
146 }
147 }
148 ds = DeepSearch(obj, item, verbose_level=2)
149 assert ds == result
150
151 def test_string_in_dictionary_in_list_verbose(self):
152 obj = [
153 "something somewhere", {
154 "long": "somewhere",
155 "string": 2,
156 0: 0,
157 "somewhere": "around"
158 }
159 ]
160 result = {
161 'matched_paths': {
162 "root[1]['somewhere']": "around"
163 },
164 'matched_values': {
165 "root[1]['long']": "somewhere",
166 "root[0]": "something somewhere"
167 }
168 }
169 ds = DeepSearch(obj, item, verbose_level=2)
170 assert ds == result
171
172 def test_custom_object(self):
173 obj = CustomClass('here, something', 'somewhere')
174 result = {'matched_values': {'root.b'}}
175 ds = DeepSearch(obj, item, verbose_level=1)
176 assert ds == result
177
178 def test_custom_object_verbose(self):
179 obj = CustomClass('here, something', 'somewhere out there')
180 result = {'matched_values': {'root.b': 'somewhere out there'}}
181 ds = DeepSearch(obj, item, verbose_level=2)
182 assert ds == result
183
184 def test_custom_object_in_dictionary_verbose(self):
185 obj = {1: CustomClass('here, something', 'somewhere out there')}
186 result = {'matched_values': {'root[1].b': 'somewhere out there'}}
187 ds = DeepSearch(obj, item, verbose_level=2)
188 assert ds == result
189
190 def test_named_tuples_verbose(self):
191 from collections import namedtuple
192 Point = namedtuple('Point', ['x', 'somewhere_good'])
193 obj = Point(x="my keys are somewhere", somewhere_good=22)
194 ds = DeepSearch(obj, item, verbose_level=2)
195 result = {
196 'matched_values': {
197 'root.x': 'my keys are somewhere'
198 },
199 'matched_paths': {
200 'root.somewhere_good': 22
201 }
202 }
203 assert ds == result
204
205 def test_string_in_set_verbose(self):
206 obj = {"long", "string", 0, "somewhere"}
207 # result = {"matched_values": {'root[3]': "somewhere"}}
208 ds = DeepSearch(obj, item, verbose_level=2)
209 assert list(ds["matched_values"].values())[0] == item
210
211 def test_loop(self):
212 class LoopTest:
213 def __init__(self, a):
214 self.loop = self
215 self.a = a
216
217 obj = LoopTest("somewhere around here.")
218
219 ds = DeepSearch(obj, item, verbose_level=1)
220 result = {'matched_values': {'root.a'}}
221 assert ds == result
222
223 def test_loop_in_lists(self):
224 obj = [1, 2, 'somewhere']
225 obj.append(obj)
226
227 ds = DeepSearch(obj, item, verbose_level=1)
228 result = {'matched_values': {'root[2]'}}
229 assert ds == result
230
231 def test_skip_path1(self):
232 obj = {
233 "for life": "vegan",
234 "ingredients": ["no meat", "no eggs", "no dairy", "somewhere"]
235 }
236 ds = DeepSearch(obj, item, exclude_paths={"root['ingredients']"})
237 assert ds == {}
238
239 def test_custom_object_skip_path(self):
240 obj = CustomClass('here, something', 'somewhere')
241 result = {}
242 ds = DeepSearch(obj, item, verbose_level=1, exclude_paths=['root.b'])
243 assert ds == result
244
245 def test_skip_list_path(self):
246 obj = ['a', 'somewhere']
247 ds = DeepSearch(obj, item, exclude_paths=['root[1]'])
248 result = {}
249 assert ds == result
250
251 def test_skip_dictionary_path(self):
252 obj = {1: {2: "somewhere"}}
253 ds = DeepSearch(obj, item, exclude_paths=['root[1][2]'])
254 result = {}
255 assert ds == result
256
257 def test_skip_type_str(self):
258 obj = "long string somewhere"
259 result = {}
260 ds = DeepSearch(obj, item, verbose_level=1, exclude_types=[str])
261 assert ds == result
262
263 def test_skip_regexp(self):
264 obj = [{'a': 1, 'b': "somewhere"}, {'c': 4, 'b': "somewhere"}]
265 ds = DeepSearch(obj, item, exclude_regex_paths=[r"root\[\d+\]"])
266 result = {}
267 assert ds == result
268
269 def test_skip_regexp2(self):
270 obj = {'a': [1, 2, [3, [item]]]}
271 ds = DeepSearch(obj, item, exclude_regex_paths=[r"\[\d+\]"])
272 result = {}
273 assert ds == result
274
275 def test_unknown_parameters(self):
276 with pytest.raises(ValueError):
277 DeepSearch(1, 1, wrong_param=2)
278
279 def test_bad_attribute(self):
280 class Bad:
281 __slots__ = ['x', 'y']
282
283 def __getattr__(self, key):
284 raise AttributeError("Bad item")
285
286 def __str__(self):
287 return "Bad Object"
288
289 obj = Bad()
290
291 ds = DeepSearch(obj, item, verbose_level=1)
292 result = {'unprocessed': ['root']}
293 assert ds == result
294 ds = DeepSearch(obj, item, verbose_level=2)
295 assert ds == result
296
297 def test_case_insensitive_of_str_in_list(self):
298 obj = ["a", "bb", "BBC", "aBbB"]
299 item = "BB"
300 result = {"matched_values": {'root[1]', 'root[2]', 'root[3]'}}
301 assert DeepSearch(obj, item, verbose_level=1, case_sensitive=False) == result
302
303 def test_case_sensitive_of_str_in_list(self):
304 obj = ["a", "bb", "BBC", "aBbB"]
305 item = "BB"
306 result = {"matched_values": {'root[2]'}}
307 assert DeepSearch(obj, item, verbose_level=1, case_sensitive=True) == result
308
309 def test_case_sensitive_of_str_in_one_liner(self):
310 obj = "Hello, what's up?"
311 item = "WHAT"
312 result = {}
313 assert DeepSearch(obj, item, verbose_level=1, case_sensitive=True) == result
314
315 def test_case_insensitive_of_str_in_one_liner(self):
316 obj = "Hello, what's up?"
317 item = "WHAT"
318 result = {'matched_values': {'root'}}
319 assert DeepSearch(obj, item, verbose_level=1, case_sensitive=False) == result
320
321 def test_none(self):
322 obj = item = None
323 result = {'matched_values': {'root'}}
324 assert DeepSearch(obj, item, verbose_level=1) == result
325
326 def test_complex_obj(self):
327 obj = datetime(2017, 5, 4, 1, 1, 1)
328 item = datetime(2017, 5, 4, 1, 1, 1)
329 result = {'matched_values': {'root'}}
330 assert DeepSearch(obj, item, verbose_level=1) == result
331
332 def test_keep_searching_after_obj_match(self):
333
334 class AlwaysEqual:
335
336 def __init__(self, recurse=True):
337 if recurse:
338 self.some_attr = AlwaysEqual(recurse=False)
339
340 def __eq__(self, other):
341 return True
342
343 obj = AlwaysEqual()
344 item = AlwaysEqual()
345 result = {'matched_values': {'root', 'root.some_attr'}}
346 assert DeepSearch(obj, item, verbose_level=1) == result
347
348 def test_search_inherited_attributes(self):
349 class Parent:
350 a = 1
351
352 class Child(Parent):
353 b = 2
354
355 obj = Child()
356 item = 1
357 result = {'matched_values': {'root.a'}}
358 assert DeepSearch(obj, item, verbose_level=1) == result
359
360 def test_dont_use_regex_by_default(self):
361 obj = "long string somewhere"
362 item = "some.*"
363 result = {}
364 assert DeepSearch(obj, item, verbose_level=1) == result
365
366 def test_regex_in_string(self):
367 obj = "long string somewhere"
368 item = "some.*"
369 result = {"matched_values": {"root"}}
370 assert DeepSearch(obj, item, verbose_level=1, use_regexp=True) == result
371
372 def test_regex_does_not_match_the_regex_string_itself(self):
373 obj = ["We like python", "but not (?:p|t)ython"]
374 item = "(?:p|t)ython"
375 result = {'matched_values': ['root[0]']}
376 assert DeepSearch(obj, item, verbose_level=1, use_regexp=True) == result
377
378 def test_regex_in_string_in_tuple(self):
379 obj = ("long", "string", 0, "somewhere")
380 item = "some.*"
381 result = {"matched_values": {"root[3]"}}
382 assert DeepSearch(obj, item, verbose_level=1, use_regexp=True) == result
383
384 def test_regex_in_string_in_list(self):
385 obj = ["long", "string", 0, "somewhere"]
386 item = "some.*"
387 result = {"matched_values": {"root[3]"}}
388 assert DeepSearch(obj, item, verbose_level=1, use_regexp=True) == result
389
390 def test_regex_in_string_in_dictionary(self):
391 obj = {"long": "somewhere", "string": 2, 0: 0, "somewhere": "around"}
392 result = {
393 "matched_paths": {"root['somewhere']"},
394 "matched_values": {"root['long']"},
395 }
396 item = "some.*"
397 ds = DeepSearch(obj, item, verbose_level=1, use_regexp=True)
398 assert ds == result
399
400 def test_regex_in_string_in_dictionary_in_list_verbose(self):
401 obj = [
402 "something somewhere",
403 {"long": "somewhere", "string": 2, 0: 0, "somewhere": "around"},
404 ]
405 result = {
406 "matched_paths": {"root[1]['somewhere']": "around"},
407 "matched_values": {
408 "root[1]['long']": "somewhere",
409 "root[0]": "something somewhere",
410 },
411 }
412 item = "some.*"
413 ds = DeepSearch(obj, item, verbose_level=2, use_regexp=True)
414 assert ds == result
415
416 def test_regex_in_custom_object(self):
417 obj = CustomClass("here, something", "somewhere")
418 result = {"matched_values": {"root.b"}}
419 item = "somew.*"
420 ds = DeepSearch(obj, item, verbose_level=1, use_regexp=True)
421 assert ds == result
422
423 def test_regex_in_custom_object_in_dictionary_verbose(self):
424 obj = {1: CustomClass("here, something", "somewhere out there")}
425 result = {"matched_values": {"root[1].b": "somewhere out there"}}
426 item = "somew.*"
427 ds = DeepSearch(obj, item, verbose_level=2, use_regexp=True)
428 assert ds == result
429
430 def test_regex_in_named_tuples_verbose(self):
431 from collections import namedtuple
432
433 Point = namedtuple("Point", ["x", "somewhere_good"])
434 obj = Point(x="my keys are somewhere", somewhere_good=22)
435 item = "some.*"
436 ds = DeepSearch(obj, item, verbose_level=2, use_regexp=True)
437 result = {
438 "matched_values": {"root.x": "my keys are somewhere"},
439 "matched_paths": {"root.somewhere_good": 22},
440 }
441 assert ds == result
442
443 def test_regex_in_string_in_set_verbose(self):
444 obj = {"long", "string", 0, "somewhere"}
445 item = "some.*"
446 ds = DeepSearch(obj, item, verbose_level=2, use_regexp=True)
447 assert list(ds["matched_values"].values())[0] == "somewhere"
448
449 def test_regex_in_int_in_dictionary_with_strict_checking(self):
450 obj = {"long": "somewhere", "num": 232, 0: 0, "somewhere": "around"}
451 item = "2.*"
452 result = {}
453 ds = DeepSearch(obj, item, verbose_level=1, use_regexp=True)
454 assert ds == result
455
456 def test_regex_in_int_in_dictionary(self):
457 obj = {"long": "somewhere", "num": 232, 0: 0, "somewhere": "around"}
458 item = "2.*"
459 result = {"matched_values": {"root['num']"}}
460 ds = DeepSearch(obj, item, verbose_level=1, use_regexp=True, strict_checking=False)
461 assert ds == result
462
463 def test_regex_in_int_in_dictionary_returns_partial_match(self):
464 obj = {"long": "somewhere", "num": 1123456, 0: 0, "somewhere": "around"}
465 item = "1234"
466 result = {"matched_values": {"root['num']"}}
467 ds = DeepSearch(obj, item, verbose_level=1, use_regexp=True, strict_checking=False)
468 assert ds == result
469
470 def test_int_cant_become_regex(self):
471 obj = {"long": "somewhere", "num": "1123456", 0: 0, "somewhere": "around"}
472 item = CustomClass(a=10)
473 with pytest.raises(TypeError) as exp:
474 DeepSearch(obj, item, verbose_level=1, use_regexp=True, strict_checking=False)
475 assert str(exp.value).startswith("The passed item of (10, None) is not usable for regex")
476
477 def test_searching_for_int_in_dictionary_when_strict_false(self):
478 obj = {"long": "somewhere", "num": "1234", 0: 0, "somewhere": "around"}
479 item = 1234
480 result = {"matched_values": {"root['num']"}}
481 ds = DeepSearch(obj, item, verbose_level=1, strict_checking=False)
482 assert ds == result
483
484
485 class TestGrep:
486
487 def test_grep_dict(self):
488 obj = {
489 "for life": "vegan",
490 "ingredients": ["no meat", "no eggs", "no dairy", "somewhere"]
491 }
492 ds = obj | grep(item)
493 assert ds == {'matched_values': {"root['ingredients'][3]"}}
494
495 def test_grep_dict_in_dict(self):
496 obj = {
497 "x": {
498 "y": [
499 "aaaaaa\u0142 bbbbb"
500 ]
501 },
502 "z": "z",
503 }
504 item = {"z": "z"}
505 result = obj | grep(item)
506 assert {} == result
507
508 def test_grep_with_non_utf8_chars(self):
509 obj = "aaaaaa\u0142 bbbbb"
510 item = {"z": "z"}
511 result = obj | grep(item)
512 assert {} == result
513
514 def test_grep_regex_in_string_in_tuple(self):
515 obj = ("long", "string", 0, "somewhere")
516 item = "some.*"
517 result = {"matched_values": {"root[3]"}}
518 assert obj | grep(item, verbose_level=1, use_regexp=True) == result
519
520 def test_search_ip_addresses(self):
521 obj1 = [ClassWithIp("2002:db8::/30"), ClassWithIp("2002:db8::/32")]
522 assert obj1 | grep("2002:db8::/32") == {'matched_values': ['root[1].field']}