-
Notifications
You must be signed in to change notification settings - Fork 3
/
test_parsers.py
1422 lines (1279 loc) · 55.2 KB
/
test_parsers.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
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
# -*- coding: utf-8 -*-
import asyncio
import time
import warnings
from urllib.parse import urlparse
import requests
from bs4 import Tag
from selectolax.parser import Node
from uniparser import (Crawler, CrawlerRule, HostRule, JSONRuleStorage,
ParseRule, Uniparser)
from uniparser.crawler import RuleNotFoundError
from uniparser.exceptions import InvalidSchemaError
from uniparser.utils import (AiohttpAsyncAdapter, HTTPXAsyncAdapter,
HTTPXSyncAdapter, RequestsAdapter,
TorequestsAsyncAdapter, TorequestsSyncAdapter,
fix_relative_path)
warnings.filterwarnings('ignore', 'TimeParser')
HTML = '''
<html><head><title >This is HTML title</title></head>
<body>
<p class="title" name="dromouse"><b>This is article title</b></p>
<p class="body">
first part
<a class="a" id="link1"><!--invisible comment--></a>
<a class="a" href="http://example.com/2" id="link2">a2</a>
<a class="a" href="http://example.com/3" id="link3">a3</a>
and they lived at the bottom of a well.</p>
<p class="body">...</p>
<div>
<span>d1</span>
</div>
<div>
<span>d2</span>
</div>
'''
JSON = '''
{
"firstName": "John",
"lastName" : "doe",
"age" : 26,
"address" : {
"streetAddress": "naist street",
"city" : "Nara",
"postalCode" : "630-0192"
},
"prices": [
{
"price": 1
},
{
"price": 2
},
{
"price": 3
}
],
"phoneNums": [
{
"type" : "iPhone",
"number": "0123-4567-8888"
},
{
"type" : "home",
"number": "0123-4567-8910"
}
]
}
'''
XML = r'''
<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0">
<channel>
<title>Channel title</title>
<atom:link href="https://www.example.com/feed/" rel="self" type="application/rss+xml" />
<link>https://www.example.com</link>
<description>XML example</description>
<lastBuildDate>Fri, 31 Jan 2020 08:02:33 +0000</lastBuildDate>
<language>zh-CN</language>
<sy:updatePeriod>
hourly </sy:updatePeriod>
<sy:updateFrequency>1</sy:updateFrequency>
<item>
<title>This is a title</title>
<link>https://example.com/1/</link>
<comments>https://example.com/1/#comments</comments>
<pubDate>Fri, 31 Jan 2020 08:02:12 +0000</pubDate>
<dc:creator>
<![CDATA[creator]]>
</dc:creator>
<category>
<![CDATA[category]]>
</category>
<guid isPermaLink="false">https://www.example.com/?p=35293</guid>
<description>
<![CDATA[ description ]]>
</description>
<content:encoded>
<![CDATA[ <p><a href="https://example.com" class="home">homepage</a> some words </p>]]>
</content:encoded>
</item>
<item>
<title>This is a title2</title>
<link>https://example.com/2/</link>
<comments>https://example.com/1/#comments</comments>
<pubDate>Fri, 31 Jan 2020 08:02:12 +0000</pubDate>
<dc:creator>
<![CDATA[creator]]>
</dc:creator>
<category>
<![CDATA[category]]>
</category>
<guid isPermaLink="false">https://www.example.com/?p=35293</guid>
<description>
<![CDATA[ description ]]>
</description>
<content:encoded>
<![CDATA[ <p><a href="https://example.com" class="home">homepage</a> some words </p>]]>
</content:encoded>
</item>
</channel>
</rss>
'''
YAML = r'''
user1:
name: a
pwd: 123
user2:
name: b
pwd: 456
'''
TOML = """
# This is a TOML document.
title = "TOML Example"
[owner]
name = "ClericPy" # some comments
[example]
ports = [ 8001, 8001, 8002 ]
connection_max = 5000
enabled = true
"""
def test_context_parser():
uni = Uniparser()
# test get attribute
result = uni.context.parse({'a': 1}, 'a', 2)
# print(result)
assert result == 1
result = uni.context.parse({'a': 1}, 'b', 2)
# print(result)
assert result == 2
def test_css_parser():
uni = Uniparser()
# test get attribute
result = uni.css.parse(HTML, 'a', '@href')
# print(result)
assert result == [None, 'http://example.com/2', 'http://example.com/3']
# test get text
result = uni.css.parse(HTML, 'a.a', '$text')
# print(result)
assert result == ['', 'a2', 'a3']
# test get innerHTML, html
result = uni.css.parse(HTML, 'a', '$innerHTML')
# print(result)
assert result == ['<!--invisible comment-->', 'a2', 'a3']
result = uni.css.parse(HTML, 'a', '$html')
# print(result)
assert result == ['<!--invisible comment-->', 'a2', 'a3']
# test get outerHTML, string
result = uni.css.parse(HTML, 'a', '$outerHTML')
# print(result)
assert result == [
'<a class="a" id="link1"><!--invisible comment--></a>',
'<a class="a" href="http://example.com/2" id="link2">a2</a>',
'<a class="a" href="http://example.com/3" id="link3">a3</a>'
]
result = uni.css.parse(HTML, 'a', '$string')
# print(result)
assert result == [
'<a class="a" id="link1"><!--invisible comment--></a>',
'<a class="a" href="http://example.com/2" id="link2">a2</a>',
'<a class="a" href="http://example.com/3" id="link3">a3</a>'
]
# test get Tag object self
result = uni.css.parse(HTML, 'a', '$self')
# print(result)
assert all([isinstance(i, Tag) for i in result])
# test parsing Tag object
tag = uni.css.parse(HTML, 'p.body', '$self')[0]
result = uni.css.parse(tag, 'a', '$text')
# print(result)
assert result == ['', 'a2', 'a3']
# test parsing list of input_object
tags = uni.css.parse(HTML, 'div', '$self')
result = uni.css.parse(tags, 'span', '$text')
# print(result)
assert result == [['d1'], ['d2']]
# =================== test css1 ===================
result = uni.css1.parse('<a class="url" href="/">title</a>', 'a.url1',
'@href')
assert result is None
result = uni.css1.parse('<a class="url" href="/">title</a>', 'a.url',
'@href')
assert result == '/'
result = uni.css1.parse('<a class="url" href="/">title</a>', 'a.url',
'$text')
assert result == 'title'
result = uni.css1.parse('<a class="url" href="/">title</a>', 'a.url',
'$innerHTML')
assert result == 'title'
result = uni.css1.parse('<a class="url" href="/">title</a>', 'a.url',
'$html')
assert result == 'title'
result = uni.css1.parse('<a class="url" href="/">title</a>', 'a.url',
'$outerHTML')
assert result == '<a class="url" href="/">title</a>'
result = uni.css1.parse('<a class="url" href="/">title</a>', 'a.url',
'$string')
assert result == '<a class="url" href="/">title</a>'
result = uni.css1.parse('<a class="url" href="/">title</a>', 'a.url',
'$self')
assert isinstance(result, Tag)
def test_selectolax_parser():
uni = Uniparser()
# test get attribute
result = uni.se.parse(HTML, 'a', '@href')
# print(result)
assert result == [None, 'http://example.com/2', 'http://example.com/3']
# test get text
result = uni.se.parse(HTML, 'a.a', '$text')
# print(result)
assert result == ['', 'a2', 'a3']
# test get outerHTML, html
result = uni.se.parse(HTML, 'a', '$outerHTML')
# print(result)
assert result == [
'<a class="a" id="link1"><!--invisible comment--></a>',
'<a class="a" href="http://example.com/2" id="link2">a2</a>',
'<a class="a" href="http://example.com/3" id="link3">a3</a>'
]
result = uni.se.parse(HTML, 'a', '$string')
# print(result)
assert result == [
'<a class="a" id="link1"><!--invisible comment--></a>',
'<a class="a" href="http://example.com/2" id="link2">a2</a>',
'<a class="a" href="http://example.com/3" id="link3">a3</a>'
]
# test get Tag object self
result = uni.se.parse(HTML, 'a', '$self')
# print(result)
assert all([isinstance(i, Node) for i in result])
# test parsing Tag object
tag = uni.se.parse(HTML, 'p.body', '$self')[0]
result = uni.se.parse(tag, 'a', '$text')
# print(result)
assert result == ['', 'a2', 'a3']
# test parsing list of input_object
tags = uni.se.parse(HTML, 'div', '$self')
result = uni.se.parse(tags, 'span', '$text')
# print(result)
assert result == [['d1'], ['d2']]
# =================== test se1 ===================
result = uni.se1.parse('<a class="url" href="/">title</a>', 'a.url1',
'@href')
assert result == '', result
result = uni.se1.parse('<a class="url" href="/">title</a>', 'a.url',
'@href')
assert result == '/', result
result = uni.se1.parse('<a class="url" href="/">title</a>', 'a.url',
'$text')
assert result == 'title', result
result = uni.se1.parse('<a class="url" href="/">title</a>', 'a.url',
'$string')
assert result == '<a class="url" href="/">title</a>', result
result = uni.se1.parse('<a class="url" href="/">title</a>', 'a.url',
'$outerHTML')
assert result == '<a class="url" href="/">title</a>', result
result = uni.se1.parse('<a class="url" href="/">title</a>', 'a.url',
'$string')
assert result == '<a class="url" href="/">title</a>', result
result = uni.se1.parse('<a class="url" href="/">title</a>', 'a.url',
'$self')
assert isinstance(result, Node), result
result = uni.se1.parse('<a class="url" href="/">title</a>', 'a.url',
'$html')
assert result == 'title', result
result = uni.se1.parse('<a class="url" href="/">title</a>', 'a.url',
'$innerHTML')
assert result == 'title', result
def test_xml_parser():
uni = Uniparser()
# test get attribute
result = uni.xml.parse(XML, 'link', '@href')
# print(result)
assert result == ['https://www.example.com/feed/', None, None, None]
# test get text
result = uni.xml.parse(XML, 'creator', '$text')
# print(result)
assert result == [
'\n creator\n ',
'\n creator\n '
]
# test get innerXML
result = uni.xml.parse(XML, 'description', '$innerXML')
# print(result)
assert result == [
'XML example', '\n description \n ',
'\n description \n '
]
# test get outerXML
result = uni.xml.parse(XML, 'encoded', '$outerXML')
# print(result)
assert result == [
'<encoded>\n <p><a href="https://example.com" class="home">homepage</a> some words </p>\n </encoded>',
'<encoded>\n <p><a href="https://example.com" class="home">homepage</a> some words </p>\n </encoded>'
]
# test get Tag object self
result = uni.xml.parse(XML, 'link', '$self')
# print(result)
assert all([isinstance(i, Tag) for i in result])
# test parsing Tag object
tag = uni.xml.parse(XML, 'item', '$self')[0]
result = uni.xml.parse(tag, 'title', '$text')
# print(result)
assert result == ['This is a title']
# test parsing list of input_object
tags = uni.xml.parse(XML, 'item', '$self')
result = uni.xml.parse(tags, 'title', '$text')
# print(result)
assert result == [['This is a title'], ['This is a title2']]
def test_re_parser():
uni = Uniparser()
# ======================
# test re findall without () group
result = uni.re.parse(HTML, 'class="a"', '')
# print(result)
assert result == ['class="a"', 'class="a"', 'class="a"']
# test re findall with () group
result = uni.re.parse(HTML, 'class="(.*?)"', '')
# print(result)
assert result == ['title', 'body', 'a', 'a', 'a', 'body']
# ======================
# test re match $0
result = uni.re.parse(HTML, 'class="(a)"', '$0')
# print(result)
assert result == ['class="a"', 'class="a"', 'class="a"']
# test re match $1
result = uni.re.parse(HTML, 'class="(a)"', '$1')
# print(result)
assert result == ['a', 'a', 'a']
# ======================
# test re sub @xxx, with group id \1
result = uni.re.parse(HTML, '<a.*</a>', '')
result = uni.re.parse(result, 'class="(a)"', r'@class="\1 b"')
# print(result)
assert result == [
'<a class="a b" id="link1"><!--invisible comment--></a>',
'<a class="a b" href="http://example.com/2" id="link2">a2</a>',
'<a class="a b" href="http://example.com/3" id="link3">a3</a>'
]
# ======================
# test re.split
result = uni.re.parse('a\t \nb c', r'\s+', '-')
# print(result)
assert result == ['a', 'b', 'c']
# ======================
# test #
result = uni.re.parse('a\t \nb c', r'(\s+)', '#1')
# print(result)
assert result == '\t \n'
result = uni.re.parse('a\t \nb c', r'b(\s+)', '#0')
# print(result)
assert result == 'b '
def test_jsonpath_parser():
uni = Uniparser()
# test default value ''
result = uni.jsonpath.parse(JSON, 'firstName', '')
# print(result)
assert result == ['John']
# test value=$value
result = uni.jsonpath.parse(JSON, 'firstName', '$value')
# print(result)
assert result == ['John']
# test absolute path
result = uni.jsonpath.parse(JSON, '$.address.city', '')
# print(result)
assert result == ['Nara']
# test slice
result = uni.jsonpath.parse(JSON, '$.phoneNums[1:]', '')
# print(result)
assert result == [{'type': 'home', 'number': '0123-4567-8910'}]
# test filter large than
result = uni.jsonpath.parse(JSON, '$.prices[?(@.price > 1)]', '')
# print(result)
assert result == [{'price': 2}, {'price': 3}]
# test filter2
result = uni.jsonpath.parse(JSON, '$.phoneNums[?(@.type = "iPhone")]', '')
# print(result)
assert result == [{'type': 'iPhone', 'number': '0123-4567-8888'}]
# test other attributes, full_path
result = uni.jsonpath.parse(JSON, 'firstName', '$full_path')
# print(result)
assert str(result) == "[Fields('firstName')]"
def test_objectpath_parser():
uni = Uniparser()
# test default value ''
result = uni.objectpath.parse(JSON, '$.firstName', '')
# print(result)
assert result == 'John'
# test absolute path
result = uni.objectpath.parse(JSON, '$.address.city', '')
# print(result)
assert result == 'Nara'
# test slice, not support...........
# result = uni.objectpath.parse(JSON, '$.phoneNums[0:1]', '')
# print(result)
# assert result == [{'type': 'home', 'number': '0123-4567-8910'}]
# test filter large than
result = uni.objectpath.parse(JSON, '$.prices[@.price > 1]', '')
# print(result)
assert result == [{'price': 2}, {'price': 3}]
# test filter2
result = uni.objectpath.parse(JSON, '$.phoneNums[@.type is "iPhone"]', '')
# print(result)
assert result == [{'type': 'iPhone', 'number': '0123-4567-8888'}]
def test_jmespath_parser():
uni = Uniparser()
# test alias
result = uni.json.parse(JSON, 'firstName', '')
# print(result)
assert result == 'John'
# test default value ''
result = uni.jmespath.parse(JSON, 'firstName', '')
# print(result)
assert result == 'John'
# test absolute path
result = uni.jmespath.parse(JSON, 'address.city', '')
# print(result)
assert result == 'Nara'
# test filter index
result = uni.jmespath.parse(JSON, "prices[1].price", '')
# print(result)
assert result == 2
# test filter slice
result = uni.jmespath.parse(JSON, "prices[1:3].price", '')
# print(result)
assert result == [2, 3]
# test attribute equals filter, use single-quote is ok, double-quote is invalid!
result = uni.jmespath.parse(JSON, "phoneNums[?type == 'iPhone'].number", '')
# print(result)
assert result == ['0123-4567-8888']
# filt by number, use ``
result = uni.jmespath.parse(JSON, "prices[?price > `1`].price", '')
# print(result)
assert result == [2, 3]
def test_python_parser():
uni = Uniparser()
# ===================== test getitem =====================
# getitem with index
result = uni.python.parse([1, 2, 3], 'getitem', '[-1]')
# print(result)
assert result == 3
# getitem with index
result = uni.python.parse([1, 2, 3], 'get', '[-1]')
# print(result)
assert result == 3
# getitem with slice
result = uni.python.parse([1, 2, 3], 'getitem', '[:2]')
# print(result)
assert result == [1, 2]
result = uni.python.parse([1, 2, 3, 4, 5], 'getitem', '[1::2]')
# print(result)
assert result == [2, 4]
result = uni.python.parse({'a': '1'}, 'getitem', 'a')
# print(result)
assert result == '1'
result = uni.python.parse({'a': '1'}, 'getitem', 'b')
# print(result)
# key error returns the bad key
assert str(result) == "'b'" and isinstance(result, KeyError)
# ===================== test split =====================
# split by None
result = uni.python.parse('a b\tc \n \td', 'split', '')
# print(result)
assert result == ['a', 'b', 'c', 'd']
# split by 's'
result = uni.python.parse('asbscsd', 'split', 's')
# print(result)
assert result == ['a', 'b', 'c', 'd']
# ===================== test join =====================
# join by ''
result = uni.python.parse(['a', 'b', 'c', 'd'], 'join', '')
# print(result)
assert result == 'abcd'
# ===================== test const =====================
# const as input_object
result = uni.python.parse(['a', 'b', 'c', 'd'], 'const', '')
# print(result)
assert result == ['a', 'b', 'c', 'd']
# const as value
result = uni.python.parse(['a', 'b', 'c', 'd'], 'const', 'abcd')
# print(result)
assert result == 'abcd'
# ===================== test template =====================
# const as input_object
result = uni.python.parse(['a', 'b', 'c', 'd'], 'template',
'1 $input_object 2')
# print(result)
assert result == "1 ['a', 'b', 'c', 'd'] 2"
# const as value
result = uni.python.parse({
'a': 'aaaa',
'b': 'bbbb'
}, 'template', '$a + $b = ?')
# print(result)
assert result == 'aaaa + bbbb = ?'
# ===================== test index =====================
result = uni.python.parse(['a', 'b', 'c', 'd'], 'index', '-1')
# print(result)
assert result == 'd'
result = uni.python.parse({'a': 1}, 'index', 'a')
# print(result)
assert result == 1
# ===================== test chain =====================
result = uni.python.parse(['a', 'b', ['c', 'd']], 'chain', '')
# print(result)
assert result == ['a', 'b', 'c', 'd']
result = uni.python.parse(['aaa', ['b'], ['c', 'd']], 'chain', '')
# print(result)
assert result == ['a', 'a', 'a', 'b', 'c', 'd']
# ===================== test sort =====================
result = uni.python.parse(*['adcb', 'sort', ''])
# print(result)
assert result == ['a', 'b', 'c', 'd']
result = uni.python.parse(*[[1, 3, 2, 4], 'sort', 'desc'])
# print(result)
assert result == [4, 3, 2, 1]
# ===================== test strip =====================
result = uni.python.parse(*['aabbcc', 'strip', 'ac'])
# print(result)
assert result == 'bb'
result = uni.python.parse(*[' bb\t\n', 'strip', ''])
# print(result)
assert result == 'bb'
result = uni.python.parse(*[' \t\n', 'default', 'default'])
# print(result)
assert result == 'default'
result = uni.python.parse(*['', 'default', 'default'])
# print(result)
assert result == 'default'
result = uni.python.parse(*['a', 'default', 'default'])
# print(result)
assert result == 'a'
# ===================== test base64 =====================
result = uni.python.parse('abc', 'base64_encode', '')
# print(result)
assert result == 'YWJj'
result = uni.python.parse('YWJj', 'base64_decode', '')
# print(result)
assert result == 'abc'
# ===================== test parser.__call__() =====================
result = uni.python('abc', 'base64_encode', '')
# print(result)
assert result == 'YWJj'
result = uni.python('YWJj', 'base64_decode', '')
# print(result)
assert result == 'abc'
# test index int
assert uni.python(*['a', '0', 'b']) == 'a'
assert uni.python(*['', '0', 'b']) == 'b'
assert uni.python(*[None, '0', 'b']) == 'b'
assert uni.python(*[{0: 'a'}, '0', 'a']) == 'a'
assert uni.python(*[['a'], '0', 'b']) == 'a'
# test null param
assert uni.python(*['a', '', 'abc']) == 'abc'
def test_udf_parser():
uni = Uniparser()
context = {'a': 1}
# ===================== test dangerous words =====================
assert uni.udf.parse('abcd', 'open', context) is NotImplemented
assert uni.udf.parse('abcd', 'input', context) is NotImplemented
assert uni.udf.parse('abcd', 'input_object', context) is not NotImplemented
assert uni.udf.parse('abcd', 'exec', context) is NotImplemented
assert uni.udf.parse('abcd', 'eval', context) is NotImplemented
# ===================== test udf with context=====================
# return a variable like context, one line code.
result = uni.udf.parse('abcd', 'context', context)
# print(result)
assert result == context
# return a variable like context(json), one line code.
result = uni.udf.parse('abcd', 'context["a"]', '{"a": 1}')
# print(result)
assert result == 1
# return a variable like context, lambda function.
# context will be set to exec's globals
result = uni.udf.parse(
'abcd', 'parse = lambda input_object: (input_object, context)', context)
# print(result)
assert result == ('abcd', context)
# return a variable like context, `def` function.
# context will be set to exec's globals
scode = '''
def parse(item):
return (item, context)
'''
result = uni.udf.parse('abcd', scode, context)
# print(result)
assert result == ('abcd', context)
# ===================== test udf without context=====================
# test python code without import; use `lambda` and `def`
result = uni.udf.parse(JSON, 'parse = lambda item: item.strip()[5:5+9]', '')
# print(result)
assert result == 'firstName'
# test python code without import; use `lambda` and `def`
result = uni.udf.parse(JSON, 'def parse(item): return item.strip()[5:5+9]',
'')
# print(result)
assert result == 'firstName'
# test python code with import, raise RuntimeError
scode = '''
def parse(item):
import json
return json.loads(item)['firstName']
'''
result = uni.udf.parse(JSON, scode, '')
# print(result)
assert result == 'John'
# test python code with import, no raise RuntimeError
uni.udf._ALLOW_IMPORT = True
result = uni.udf.parse(JSON, scode, '')
# print(result)
assert result == 'John'
# test python code without parse function, using eval
result = uni.udf.parse('hello', 'input_object + " world."', '')
# print(result)
assert result == 'hello world.'
# test alias obj
result = uni.udf.parse('hello', 'obj + " world."', '')
# print(result)
assert result == 'hello world.'
# test custom locals from context
result = uni.udf.parse('', 'abc', {'locals': {'abc': True}})
# print(result)
assert result is True
def test_loader_parser():
uni = Uniparser()
# ===================== test getitem =====================
# yaml
result = uni.loader.parse(YAML, 'yaml', '')
# print(result)
assert result == {
'user1': {
'name': 'a',
'pwd': 123
},
'user2': {
'name': 'b',
'pwd': 456
}
}
# toml
result = uni.loader.parse(TOML, 'toml', '{"decoder": null}')
# print(result)
assert result == {
'title': 'TOML Example',
'owner': {
'name': 'ClericPy'
},
'example': {
'ports': [8001, 8001, 8002],
'connection_max': 5000,
'enabled': True
}
}
# json
result = uni.loader.parse(JSON, 'json', '{"parse_int": null}')
# print(result)
assert result['age'] == 26
# base64 lib
result = uni.loader.parse('a', 'b64encode', '')
# print(result)
assert result == 'YQ=='
result = uni.loader.parse('YQ==', 'b64decode', '')
# print(result)
assert result == 'a'
result = uni.loader.parse('a', 'b16encode', '')
# print(result)
assert uni.loader.parse(result, 'b16decode', '') == 'a'
result = uni.loader.parse('a', 'b32encode', '')
# print(result)
assert uni.loader.parse(result, 'b32decode', '') == 'a'
result = uni.loader.parse('a', 'b85encode', '')
# print(result)
assert uni.loader.parse(result, 'b85decode', '') == 'a'
def test_time_parser():
timestamp = '1580732985.1873155'
time_string = '2020-02-03 20:29:45'
time_string_timezone = '2020-02-03T20:29:45 +0000'
uni = Uniparser()
uni.time.LOCAL_TIME_ZONE = +8
# translate time_string into timestamp float
result = uni.time.parse(time_string, 'encode', '')
# print(result)
assert int(result) == int(float(timestamp))
result = uni.time.parse(timestamp, 'decode', '')
# print(result)
assert result == time_string
result = uni.time.parse(result, 'encode', '')
# print(result)
assert int(result) == int(float(timestamp))
result_time_zone = uni.time.parse(time_string_timezone, 'encode',
'%Y-%m-%dT%H:%M:%S %z')
# print(result_time_zone)
assert int(result_time_zone) == int(float(timestamp))
# =============================================
# set a new timezone as local timezone +1, time will be 1 hour earlier than local.
uni.time.LOCAL_TIME_ZONE += 1
# same timestamp, different tz, earlier time_string will be larger than the old one.
new_result = uni.time.parse(timestamp, 'decode', '')
# print(new_result)
# print(time_string)
assert new_result > time_string
# same time_string, different tz, earlier timestamp is less than the old one.
new_result = uni.time.parse(time_string, 'encode', '')
# print(new_result - int(float(timestamp)))
assert new_result - int(float(timestamp)) == -1 * 3600
def test_crawler_rule():
# Simple usage of Uniparser and CrawlerRule
uni = Uniparser()
crawler_rule = CrawlerRule('test', {
'url': 'http://httpbin.org/get',
'method': 'get'
}, [{
"name": "rule1",
"chain_rules": [
['objectpath', 'JSON.url', ''],
['python', 'getitem', '[:4]'],
[
'udf',
'(context["resp"].url, context["request_args"]["url"], input_object)',
''
],
],
"child_rules": []
}], '')
resp = requests.request(timeout=3, **crawler_rule['request_args'])
result = uni.parse(resp.text, crawler_rule, context={'resp': resp})
# print(result)
assert result == {
'test': {
'rule1':
('http://httpbin.org/get', 'http://httpbin.org/get', 'http')
}
}
crawler_rule_json = crawler_rule.to_json()
# print(crawler_rule_json)
assert crawler_rule_json == r'{"name": "test", "parse_rules": [{"name": "rule1", "chain_rules": [["objectpath", "JSON.url", ""], ["python", "getitem", "[:4]"], ["udf", "(context[\"resp\"].url, context[\"request_args\"][\"url\"], input_object)", ""]], "child_rules": []}], "request_args": {"url": "http://httpbin.org/get", "method": "get"}, "regex": ""}'
crawler_rule_dict = crawler_rule.to_dict()
# print(crawler_rule_dict)
# yapf: disable
assert crawler_rule_dict == {'name': 'test', 'parse_rules': [{'name': 'rule1', 'chain_rules': [['objectpath', 'JSON.url', ''], ['python', 'getitem', '[:4]'], ['udf', '(context["resp"].url, context["request_args"]["url"], input_object)', '']], 'child_rules': []}], 'request_args': {'url': 'http://httpbin.org/get', 'method': 'get'}, 'regex': ''}
# yapf: enable
# saving some custom kwargs to crawler_rule
crawler_rule['context'] = {'a': 1, 'b': {'c': 2}}
# print(crawler_rule)
# yapf: disable
assert crawler_rule == {'name': 'test', 'parse_rules': [{'name': 'rule1', 'chain_rules': [['objectpath', 'JSON.url', ''], ['python', 'getitem', '[:4]'], ['udf', '(context["resp"].url, context["request_args"]["url"], input_object)', '']], 'child_rules': []}], 'request_args': {'url': 'http://httpbin.org/get', 'method': 'get'}, 'regex': '', 'context': {'a': 1, 'b': {'c': 2}}}
# yapf: enable
host_rule = HostRule('importpython.com')
crawler_rule_json = '{"name":"C-1583501370","request_args":{"method":"get","url":"https://importpython.com/blog/feed/"},"parse_rules":[{"name":"text","chain_rules":[["xml","channel>item>title","$text"],["python","getitem","[0]"]],"childs":""},{"name":"url","chain_rules":[["xml","channel>item>link","$text"],["python","getitem","[0]"]],"childs":""}],"regex":"https://bad_url_host.com/blog/feed/$"}'
try:
host_rule.add_crawler_rule(crawler_rule_json)
assert NotImplementedError
except AssertionError as err:
assert err
assert host_rule['crawler_rules'] == {}
crawler_rule = CrawlerRule.loads(crawler_rule_json)
crawler_rule['regex'] = r'https?://importpython\.com/.*'
host_rule.add_crawler_rule(crawler_rule)
assert host_rule['crawler_rules']
assert not host_rule.findall('https://bad_url_host.com/')
assert host_rule.findall('https://importpython.com/')
def test_default_usage():
# 1. prepare for storage to save {'host': HostRule}
uni = Uniparser()
storage = {}
test_url = 'http://httpbin.org/get'
crawler_rule = CrawlerRule(
'test_crawler_rule',
{
'url': 'http://httpbin.org/get',
'method': 'get'
},
[{
"name": "rule1",
"chain_rules": [
['objectpath', 'JSON.url', ''],
['python', 'getitem', '[:4]'],
['udf', '(context["resp"].url, input_object)', ''],
],
"child_rules": []
}],
'https?://httpbin.org/get',
)
host = urlparse(test_url).netloc
host_rule = HostRule(host=host)
host_rule.add_crawler_rule(crawler_rule)
# same as: json_string = host_rule.to_json()
json_string = host_rule.dumps()
# print(json_string)
assert json_string == r'{"host": "httpbin.org", "crawler_rules": {"test_crawler_rule": {"name": "test_crawler_rule", "parse_rules": [{"name": "rule1", "chain_rules": [["objectpath", "JSON.url", ""], ["python", "getitem", "[:4]"], ["udf", "(context[\"resp\"].url, input_object)", ""]], "child_rules": []}], "request_args": {"url": "http://httpbin.org/get", "method": "get"}, "regex": "https?://httpbin.org/get"}}}'
# 2. add HostRule to storage, sometimes save on redis
storage[host_rule['host']] = json_string
# ============================================
# start to crawl
# 1. set a example url
test_url1 = test_url
# 2. find the HostRule
json_string = storage.get(host)
# 3. HostRule init: load from json
# same as: host_rule = HostRule.from_json(json_string)
host_rule = HostRule.loads(json_string)
# print(crawler_rule)
# 4. now search / match the url with existing rules
crawler_rule = host_rule.search(test_url1)
# print(crawler_rule)
# yapf: disable
assert crawler_rule == {'name': 'test_crawler_rule', 'parse_rules': [{'name': 'rule1', 'chain_rules': [['objectpath', 'JSON.url', ''], ['python', 'getitem', '[:4]'], ['udf', '(context["resp"].url, input_object)', '']], 'child_rules': []}], 'request_args': {'url': 'http://httpbin.org/get', 'method': 'get'}, 'regex': 'https?://httpbin.org/get'}
# yapf: enable
# print(host_rule.match(test_url1))
assert crawler_rule == host_rule.match(test_url1)
# 5. send request as crawler_rule's request_args, download the page source code
resp = requests.request(**crawler_rule['request_args'])
source_code = resp.text
# 6. parse the whole crawler_rule as crawler_rule's with uniparser. set context with resp
assert isinstance(crawler_rule, CrawlerRule)
result = uni.parse(source_code, crawler_rule, context={'resp': resp})
# print(result)
assert result == {
'test_crawler_rule': {
'rule1': ('http://httpbin.org/get', 'http')
}
}
# ===================== while search failed =====================
# given a url not matched the pattern
test_url2 = 'http://notmatch.com'
crawler_rule2 = host_rule.search(test_url2)
assert crawler_rule2 is None
# ===================== shared context =====================
# !!! use context by updating rule.context variable
new_parse = '''
def parse(input_object):
context['new_key'] = 'cleared'
return 'ok'
'''
crawler_rule.context.update({'new_key': 'new_value'})
crawler_rule.clear_parse_rules()
crawler_rule.add_parse_rule({
'name': 'rule1',
'chain_rules': [['objectpath', 'JSON.url', ''],
['python', 'getitem', '[:4]'], ['udf', new_parse, '']],
'child_rules': []
})
result = uni.parse(source_code, crawler_rule)
# print(result)
assert result == {'test_crawler_rule': {'rule1': 'ok'}}
# print(crawler_rule.context)
# now the crawler_rule.context has been updated as 'cleared'.
assert crawler_rule.context['new_key'] == 'cleared'
def test_uni_parser():
uni = Uniparser()
# ===================================================
# 1. test Uniparser's parse_parse_rule
rule1 = ParseRule(
'rule1',
[['python', 'getitem', '[:7]'],
['udf', 'str(input_object)+" "+context["key"]', '']],
[],
)
result = uni.parse(HTML, rule1, {'key': 'hello world'})
# print(result)
assert result == {'rule1': '\n<html> hello world'}
json_string = r'{"name": "rule1", "chain_rules": [["python", "getitem", "[:7]"], ["udf", "str(input_object)+\" \"+context[\"key\"]", ""]], "child_rules": []}'
# print(rule1.dumps(), rule1.to_json(), json_string)
assert rule1.dumps() == rule1.to_json() == json_string
loaded_rule = ParseRule.from_json(json_string)
assert isinstance(loaded_rule, ParseRule)
assert loaded_rule == ParseRule.loads(json_string)
# print(loaded_rule)
# ===================================================
# # 2. test Uniparser's nested parse_parse_rule
rule2 = ParseRule('rule2', [['udf', 'input_object[::-1]', '']], [])
rule1['child_rules'].append(rule2)
rule3 = ParseRule(
'rule3', [['udf', 'input_object[::-1]', '']],
[ParseRule('rule4', [['udf', 'input_object[::-1]', '']], [])])
rule1['child_rules'].append(rule3)
# init parse rule
parse_rule = ParseRule(
'parse_rule',
[['css', 'p', '$outerHTML'], ['css', 'b', '$text'],