/
utils.py
1797 lines (1427 loc) · 54.6 KB
/
utils.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
'''
This contains the core test helper code used in Synapse.
This gives the opportunity for third-party users of Synapse to test their
code using some of the same helpers used to test Synapse.
The core class, synapse.tests.utils.SynTest is a subclass of unittest.TestCase,
with several wrapper functions to allow for easier calls to assert* functions,
with less typing. There are also Synapse specific helpers, to load Cortexes and
whole both multi-component environments into memory.
Since SynTest is built from unittest.TestCase, the use of SynTest is
compatible with the unittest, nose and pytest frameworks. This does not lock
users into a particular test framework; while at the same time allowing base
use to be invoked via the built-in Unittest library, with one important exception:
due to an unfortunate design approach, you cannot use the unittest module command
line to run a *single* async unit test. pytest works fine though.
'''
import io
import os
import sys
import copy
import math
import types
import shutil
import asyncio
import hashlib
import inspect
import logging
import tempfile
import unittest
import threading
import contextlib
import collections
import unittest.mock as mock
import aiohttp
from prompt_toolkit.formatted_text import FormattedText
import synapse.exc as s_exc
import synapse.axon as s_axon
import synapse.glob as s_glob
import synapse.common as s_common
import synapse.cortex as s_cortex
import synapse.daemon as s_daemon
import synapse.cryotank as s_cryotank
import synapse.telepath as s_telepath
import synapse.lib.coro as s_coro
import synapse.lib.cmdr as s_cmdr
import synapse.lib.hive as s_hive
import synapse.lib.task as s_task
import synapse.lib.const as s_const
import synapse.lib.layer as s_layer
import synapse.lib.nexus as s_nexus
import synapse.lib.storm as s_storm
import synapse.lib.types as s_types
import synapse.lib.module as s_module
import synapse.lib.output as s_output
import synapse.lib.certdir as s_certdir
import synapse.lib.httpapi as s_httpapi
import synapse.lib.msgpack as s_msgpack
import synapse.lib.lmdbslab as s_lmdbslab
import synapse.lib.thishost as s_thishost
import synapse.lib.stormtypes as s_stormtypes
logger = logging.getLogger(__name__)
# Default LMDB map size for tests
TEST_MAP_SIZE = s_const.gibibyte
async def alist(coro):
return [x async for x in coro]
def norm(z):
if isinstance(z, (list, tuple)):
return tuple([norm(n) for n in z])
if isinstance(z, dict):
return {norm(k): norm(v) for (k, v) in z.items()}
return z
class LibTst(s_stormtypes.Lib):
def addLibFuncs(self):
self.locls.update({
'beep': self.beep,
})
async def beep(self, valu):
'''
Example storm func
'''
ret = f'A {valu} beep!'
return ret
class TestType(s_types.Type):
stortype = s_layer.STOR_TYPE_UTF8
def postTypeInit(self):
self.setNormFunc(str, self._normPyStr)
def _normPyStr(self, valu):
return valu.lower(), {}
class ThreeType(s_types.Type):
stortype = s_layer.STOR_TYPE_U8
def norm(self, valu):
return 3, {'subs': {'three': 3}}
def repr(self, valu):
return '3'
class TestSubType(s_types.Type):
stortype = s_layer.STOR_TYPE_U32
def norm(self, valu):
valu = int(valu)
return valu, {'subs': {'isbig': valu >= 1000}}
def repr(self, norm):
return str(norm)
class TestRunt:
def __init__(self, name, **kwargs):
self.name = name
self.props = kwargs
self.props.setdefault('.created', s_common.now())
def getStorNode(self, form):
ndef = (form.name, form.type.norm(self.name)[0])
buid = s_common.buid(ndef)
pnorms = {}
for prop, valu in self.props.items():
formprop = form.props.get(prop)
if formprop is not None and valu is not None:
pnorms[prop] = formprop.type.norm(valu)[0]
return (buid, {
'ndef': ndef,
'props': pnorms,
})
testmodel = {
'ctors': (
('test:sub', 'synapse.tests.utils.TestSubType', {}, {}),
('test:type', 'synapse.tests.utils.TestType', {}, {}),
('test:threetype', 'synapse.tests.utils.ThreeType', {}, {}),
),
'types': (
('test:type10', ('test:type', {'foo': 10}), {
'doc': 'A fake type.'}),
('test:lower', ('str', {'lower': True}), {}),
('test:time', ('time', {}), {}),
('test:ival', ('ival', {}), {}),
('test:int', ('int', {}), {}),
('test:float', ('float', {}), {}),
('test:str', ('str', {}), {}),
('test:migr', ('str', {}), {}),
('test:auto', ('str', {}), {}),
('test:edge', ('edge', {}), {}),
('test:guid', ('guid', {}), {}),
('test:arrayprop', ('guid', {}), {}),
('test:comp', ('comp', {'fields': (
('hehe', 'test:int'),
('haha', 'test:lower'))
}), {'doc': 'A fake comp type.'}),
('test:compcomp', ('comp', {'fields': (
('comp1', 'test:comp'),
('comp2', 'test:comp'))
}), {}),
('test:complexcomp', ('comp', {'fields': (
('foo', 'test:int'),
('bar', ('str', {'lower': True}),),
)}), {'doc': 'A complex comp type.'}),
('test:hexa', ('hex', {}), {'doc': 'anysize test hex type'}),
('test:hex4', ('hex', {'size': 4}), {'doc': 'size 4 test hex type'}),
('test:pivtarg', ('str', {}), {}),
('test:pivcomp', ('comp', {'fields': (('targ', 'test:pivtarg'), ('lulz', 'test:str'))}), {}),
('test:haspivcomp', ('int', {}), {}),
('test:cycle0', ('str', {}), {}),
('test:cycle1', ('str', {}), {}),
('test:ndef', ('ndef', {}), {}),
('test:runt', ('str', {'lower': True, 'strip': True}), {'doc': 'A Test runt node'}),
),
'univs': (
('test:univ', ('int', {'min': -1, 'max': 10}), {'doc': 'A test universal property.'}),
('univarray', ('array', {'type': 'int'}), {'doc': 'A test array universal property.'}),
),
'forms': (
('test:arrayprop', {}, (
('ints', ('array', {'type': 'test:int'}), {}),
)),
('test:type10', {}, (
('intprop', ('int', {'min': 20, 'max': 30}), {}),
('int2', ('int', {}), {}),
('strprop', ('str', {'lower': 1}), {}),
('guidprop', ('guid', {'lower': 1}), {}),
('locprop', ('loc', {}), {}),
)),
('test:cycle0', {}, (
('cycle1', ('test:cycle1', {}), {}),
)),
('test:cycle1', {}, (
('cycle0', ('test:cycle0', {}), {}),
)),
('test:type', {}, ()),
('test:comp', {}, (
('hehe', ('test:int', {}), {'ro': True}),
('haha', ('test:lower', {}), {'ro': True}),
)),
('test:compcomp', {}, (
('comp1', ('test:comp', {}), {}),
('comp2', ('test:comp', {}), {}),
)),
('test:complexcomp', {}, (
('foo', ('test:int', {}), {'ro': True}),
('bar', ('str', {'lower': 1}), {'ro': True})
)),
('test:int', {}, (
('loc', ('loc', {}), {}),
('int2', ('int', {}), {}),
)),
('test:float', {}, (
('closed', ('float', {'min': 0.0, 'max': 360.0}), {}),
('open', ('float', {'min': 0.0, 'max': 360.0, 'minisvalid': False, 'maxisvalid': False}), {}),
)),
('test:edge', {}, (
('n1', ('ndef', {}), {'ro': True}),
('n1:form', ('str', {}), {'ro': True}),
('n2', ('ndef', {}), {'ro': True}),
('n2:form', ('str', {}), {'ro': True}),
)),
('test:guid', {}, (
('size', ('test:int', {}), {}),
('tick', ('test:time', {}), {}),
('posneg', ('test:sub', {}), {}),
('posneg:isbig', ('bool', {}), {}),
)),
('test:str', {}, (
('bar', ('ndef', {}), {}),
('baz', ('nodeprop', {}), {}),
('tick', ('test:time', {}), {}),
('hehe', ('str', {}), {}),
)),
('test:migr', {}, (
('bar', ('ndef', {}), {}),
('baz', ('nodeprop', {}), {}),
('tick', ('test:time', {}), {}),
)),
('test:threetype', {}, (
('three', ('int', {}), {}),
)),
('test:auto', {}, ()),
('test:hexa', {}, ()),
('test:hex4', {}, ()),
('test:ival', {}, (
('interval', ('ival', {}), {}),
)),
('test:pivtarg', {}, (
('name', ('str', {}), {}),
)),
('test:pivcomp', {}, (
('targ', ('test:pivtarg', {}), {}),
('lulz', ('test:str', {}), {}),
('tick', ('time', {}), {}),
('size', ('test:int', {}), {}),
('width', ('test:int', {}), {}),
)),
('test:haspivcomp', {}, (
('have', ('test:pivcomp', {}), {}),
)),
('test:ndef', {}, (
('form', ('str', {}), {'ro': True}),
)),
('test:runt', {'runt': True}, (
('tick', ('time', {}), {'ro': True}),
('lulz', ('str', {}), {}),
('newp', ('str', {}), {'doc': 'A stray property we never use in nodes.'}),
)),
),
}
class TestCmd(s_storm.Cmd):
'''
A test command
'''
name = 'testcmd'
forms = {
'input': [
'test:str',
'inet:ipv6',
],
'output': [
'inet:fqdn',
],
'nodedata': [
('foo', 'inet:ipv4'),
('bar', 'inet:fqdn'),
],
}
def getArgParser(self):
pars = s_storm.Cmd.getArgParser(self)
return pars
async def execStormCmd(self, runt, genr):
async for node, path in genr:
await runt.printf(f'{self.name}: {node.ndef}')
yield node, path
class TestModule(s_module.CoreModule):
testguid = '8f1401de15918358d5247e21ca29a814'
async def initCoreModule(self):
self.core.setFeedFunc('com.test.record', self.addTestRecords)
async with await self.core.snap() as snap:
node = await snap.getNodeByNdef(('meta:source', self.testguid))
if node is None:
await snap.addNode('meta:source', self.testguid, {'name': 'test'})
self.core.addStormLib(('test',), LibTst)
self.healthy = True
self.core.addHealthFunc(self._testModHealth)
form = self.model.form('test:runt')
self.core.addRuntLift(form.full, self._testRuntLift)
for prop in form.props.values():
self.core.addRuntLift(prop.full, self._testRuntLift)
self.core.addRuntPropSet('test:runt:lulz', self._testRuntPropSetLulz)
self.core.addRuntPropDel('test:runt:lulz', self._testRuntPropDelLulz)
async def _testModHealth(self, health):
if self.healthy:
health.update(self.getModName(), 'nominal',
'Test module is healthy', data={'beep': 0})
else:
health.update(self.getModName(), 'failed',
'Test module is unhealthy', data={'beep': 1})
async def addTestRecords(self, snap, items):
for name in items:
await snap.addNode('test:str', name)
async def _testRuntLift(self, full, valu=None, cmpr=None):
now = s_common.now()
modl = self.core.model
runtdefs = [
(' BEEP ', {'tick': modl.type('time').norm('2001')[0], 'lulz': 'beep.sys', '.created': now}),
('boop', {'tick': modl.type('time').norm('2010')[0], '.created': now}),
('blah', {'tick': modl.type('time').norm('2010')[0], 'lulz': 'blah.sys'}),
('woah', {}),
]
runts = {}
for name, props in runtdefs:
runts[name] = TestRunt(name, **props)
genr = runts.values
async for node in self._doRuntLift(genr, full, valu, cmpr):
yield node
async def _doRuntLift(self, genr, full, valu=None, cmpr=None):
if cmpr is not None:
filt = self.model.prop(full).type.getCmprCtor(cmpr)(valu)
if filt is None:
raise s_exc.BadCmprValu(cmpr=cmpr)
fullprop = self.model.prop(full)
if fullprop.isform:
if cmpr is None:
for obj in genr():
yield obj.getStorNode(fullprop)
return
for obj in genr():
sode = obj.getStorNode(fullprop)
if filt(sode[1]['ndef'][1]):
yield sode
else:
for obj in genr():
sode = obj.getStorNode(fullprop.form)
propval = sode[1]['props'].get(fullprop.name)
if propval is not None and (cmpr is None or filt(propval)):
yield sode
async def _testRuntPropSetLulz(self, node, prop, valu):
curv = node.get(prop.name)
valu, _ = prop.type.norm(valu)
if curv == valu:
return False
if not valu.endswith('.sys'):
raise s_exc.BadTypeValu(mesg='test:runt:lulz must end with ".sys"',
valu=valu, name=prop.full)
node.props[prop.name] = valu
# In this test helper, we do NOT persist the change to our in-memory
# storage of row data, so a re-lift of the node would not reflect the
# change that a user made here.
return True
async def _testRuntPropDelLulz(self, node, prop,):
curv = node.props.pop(prop.name, s_common.novalu)
if curv is s_common.novalu:
return False
# In this test helper, we do NOT persist the change to our in-memory
# storage of row data, so a re-lift of the node would not reflect the
# change that a user made here.
return True
def getModelDefs(self):
return (
('test', testmodel),
)
def getStormCmds(self):
return (TestCmd,
)
class TstEnv:
def __init__(self):
self.items = {}
self.tofini = []
def __getattr__(self, prop):
item = self.items.get(prop)
if item is None:
raise AttributeError(prop)
return item
async def __aenter__(self):
return self
async def __aexit__(self, cls, exc, tb):
await self.fini()
def add(self, name, item, fini=False):
self.items[name] = item
if fini:
self.tofini.append(item)
async def fini(self):
for base in self.tofini:
await base.fini()
class TstOutPut(s_output.OutPutStr):
def expect(self, substr, throw=True):
'''
Check if a string is present in the messages captured by the OutPutStr object.
Args:
substr (str): String to check for the existence of.
throw (bool): If True, a missing substr results in a Exception being thrown.
Returns:
bool: True if the string is present; False if the string is not present and throw is False.
'''
outs = str(self)
if outs.find(substr) == -1:
if throw:
mesg = 'TestOutPut.expect(%s) not in %s' % (substr, outs)
raise s_exc.SynErr(mesg=mesg)
return False
return True
def clear(self):
self.mesgs.clear()
class CmdGenerator:
def __init__(self, cmds):
self.cmds = collections.deque(cmds)
def addCmd(self, cmd):
'''
Add a command to the end of the list of commands returned by the CmdGenerator.
Args:
cmd (str): Command to add to the list of commands to return.
'''
self.cmds.append(cmd)
def __call__(self, *args, **kwargs):
return self._corocall(*args, **kwargs)
async def _corocall(self, *args, **kwargs):
if not self.cmds:
raise Exception('No further actions.')
retn = self.cmds.popleft()
if isinstance(retn, (Exception, KeyboardInterrupt)):
raise retn
return retn
class StreamEvent(io.StringIO, threading.Event):
'''
A combination of a io.StringIO object and a threading.Event object.
'''
def __init__(self, *args, **kwargs):
io.StringIO.__init__(self, *args, **kwargs)
threading.Event.__init__(self)
self.mesg = ''
def setMesg(self, mesg):
'''
Clear the internal event and set a new message that is used to set the event.
Args:
mesg (str): The string to monitor for.
Returns:
None
'''
self.mesg = mesg
self.clear()
def write(self, s):
io.StringIO.write(self, s)
if self.mesg and self.mesg in s:
self.set()
class AsyncStreamEvent(io.StringIO, asyncio.Event):
'''
A combination of a io.StringIO object and an asyncio.Event object.
'''
def __init__(self, *args, **kwargs):
io.StringIO.__init__(self, *args, **kwargs)
asyncio.Event.__init__(self)
self.mesg = ''
def setMesg(self, mesg):
'''
Clear the internal event and set a new message that is used to set the event.
Args:
mesg (str): The string to monitor for.
Returns:
None
'''
self.mesg = mesg
self.clear()
def write(self, s):
io.StringIO.write(self, s)
if self.mesg and self.mesg in s:
self.set()
async def wait(self, timeout=None):
if timeout is None:
return await asyncio.Event.wait(self)
return await s_coro.event_wait(self, timeout=timeout)
class HttpReflector(s_httpapi.Handler):
'''Test handler which reflects get/post data back to the caller'''
async def get(self):
resp = {}
if self.request.arguments:
d = collections.defaultdict(list)
resp['params'] = d
for k, items in self.request.arguments.items():
for v in items:
d[k].append(v.decode())
resp['headers'] = dict(self.request.headers)
resp['path'] = self.request.path
self.sendRestRetn(resp)
async def post(self):
resp = {}
if self.request.arguments:
d = collections.defaultdict(list)
resp['params'] = d
for k, items in self.request.arguments.items():
for v in items:
d[k].append(v.decode())
resp['headers'] = dict(self.request.headers)
resp['path'] = self.request.path
if self.request.body:
resp['body'] = s_common.enbase64(self.request.body)
self.sendRestRetn(resp)
s_task.vardefault('applynest', lambda: None)
async def _doubleapply(self, indx, item):
'''
Just like NexusRoot._apply, but calls the function twice. Patched in when global variable SYNDEV_NEXUS_REPLAY
is set.
'''
try:
nestitem = s_task.varget('applynest')
assert nestitem is None, f'Failure: have nested nexus actions, inner item is {item}, outer item was {nestitem}'
s_task.varset('applynest', item)
nexsiden, event, args, kwargs, _ = item
nexus = self._nexskids[nexsiden]
func, passitem = nexus._nexshands[event]
if passitem:
retn = await func(nexus, *args, nexsitem=(indx, item), **kwargs)
await func(nexus, *args, nexsitem=(indx, item), **kwargs)
return retn
retn = await func(nexus, *args, **kwargs)
await func(nexus, *args, **kwargs)
return retn
finally:
s_task.varset('applynest', None)
class SynTest(unittest.TestCase):
'''
Mark all async test methods as s_glob.synchelp decorated.
Note:
This precludes running a single unit test via path using the unittest module.
'''
def __init__(self, *args, **kwargs):
unittest.TestCase.__init__(self, *args, **kwargs)
self._NextBuid = 0
self._NextGuid = 0
for s in dir(self):
attr = getattr(self, s, None)
# If s is an instance method and starts with 'test_', synchelp wrap it
if inspect.iscoroutinefunction(attr) and s.startswith('test_') and inspect.ismethod(attr):
setattr(self, s, s_glob.synchelp(attr))
def checkNode(self, node, expected):
ex_ndef, ex_props = expected
self.eq(node.ndef, ex_ndef)
[self.eq(node.get(k), v, msg=f'Prop {k} does not match') for (k, v) in ex_props.items()]
diff = {prop for prop in (set(node.props) - set(ex_props)) if not prop.startswith('.')}
if diff:
logger.warning('form(%s): untested properties: %s', node.form.name, diff)
def worker(func, *args, **kwargs):
'''
Fire a worker thread to run the given func(*args,**kwargs)
'''
def work():
return func(*args, **kwargs)
thr = threading.Thread(target=work)
thr.start()
return thr
def printed(self, msgs, text):
# a helper for testing storm print message output
for mesg in msgs:
if mesg[0] == 'print':
if mesg[1].get('mesg') == text:
return
raise Exception('print output not found: %r' % (text,))
def skip(self, mesg):
raise unittest.SkipTest(mesg)
@contextlib.contextmanager
def getRegrDir(self, *path):
regr = os.getenv('SYN_REGRESSION_REPO')
if regr is None: # pragma: no cover
raise unittest.SkipTest('SYN_REGRESSION_REPO is not set')
regr = s_common.genpath(regr)
if not os.path.isdir(regr): # pragma: no cover
raise Exception('SYN_REGRESSION_REPO is not a dir')
dirn = os.path.join(regr, *path)
with self.getTestDir(copyfrom=dirn) as regrdir:
yield regrdir
@contextlib.asynccontextmanager
async def getRegrCore(self, vers, conf=None):
with self.getRegrDir('cortexes', vers) as dirn:
async with await s_cortex.Cortex.anit(dirn, conf=conf) as core:
yield core
def skipIfNoInternet(self): # pragma: no cover
'''
Allow skipping a test if SYN_TEST_SKIP_INTERNET envar is set.
Raises:
unittest.SkipTest if SYN_TEST_SKIP_INTERNET envar is set to a integer greater than 1.
'''
if bool(int(os.getenv('SYN_TEST_SKIP_INTERNET', 0))):
raise unittest.SkipTest('SYN_TEST_SKIP_INTERNET envar set')
def skipLongTest(self): # pragma: no cover
'''
Allow skipping a test if SYN_TEST_SKIP_LONG envar is set.
Raises:
unittest.SkipTest if SYN_TEST_SKIP_LONG envar is set to a integer greater than 1.
'''
if bool(int(os.getenv('SYN_TEST_SKIP_LONG', 0))):
raise unittest.SkipTest('SYN_TEST_SKIP_LONG envar set')
def getTestOutp(self):
'''
Get a Output instance with a expects() function.
Returns:
TstOutPut: A TstOutPut instance.
'''
return TstOutPut()
def thisHostMust(self, **props): # pragma: no cover
'''
Requires a host having a specific property.
Args:
**props:
Raises:
unittest.SkipTest if the required property is missing.
'''
for k, v in props.items():
if s_thishost.get(k) != v:
raise unittest.SkipTest('skip thishost: %s!=%r' % (k, v))
def thisHostMustNot(self, **props): # pragma: no cover
'''
Requires a host to not have a specific property.
Args:
**props:
Raises:
unittest.SkipTest if the required property is missing.
'''
for k, v in props.items():
if s_thishost.get(k) == v:
raise unittest.SkipTest('skip thishost: %s==%r' % (k, v))
@contextlib.asynccontextmanager
async def getTestAxon(self, dirn=None, conf=None):
'''
Get a test Axon as an async context manager.
Returns:
s_axon.Axon: A Axon object.
'''
if dirn is not None:
async with await s_axon.Axon.anit(dirn, conf) as axon:
yield axon
return
with self.getTestDir() as dirn:
async with await s_axon.Axon.anit(dirn, conf) as axon:
yield axon
@contextlib.contextmanager
def withTestCmdr(self, cmdg):
getItemCmdr = s_cmdr.getItemCmdr
async def getTestCmdr(*a, **k):
cli = await getItemCmdr(*a, **k)
cli.prompt = cmdg
return cli
with mock.patch('synapse.lib.cmdr.getItemCmdr', getTestCmdr):
yield
@contextlib.contextmanager
def withCliPromptMockExtendOutp(self, outp):
'''
Context manager to mock our use of Prompt Toolkit's print_formatted_text function and
extend the lines to an an output object.
Args:
outp (TstOutPut): The outp to extend.
Notes:
This extends the outp with the lines AFTER the context manager has exited.
Returns:
mock.MagicMock: Yields a mock.MagicMock object.
'''
with self.withCliPromptMock() as patch:
yield patch
self.extendOutpFromPatch(outp, patch)
@contextlib.contextmanager
def withCliPromptMock(self):
'''
Context manager to mock our use of Prompt Toolkit's print_formatted_text function.
Returns:
mock.MagicMock: Yields a mock.MagikMock object.
'''
with mock.patch('synapse.lib.cli.print_formatted_text',
mock.MagicMock(return_value=None)) as patch: # type: mock.MagicMock
yield patch
@contextlib.contextmanager
def withSetLoggingMock(self):
'''
Context manager to mock calls to the setlogging function to avoid unittests calling logging.basicconfig.
Returns:
mock.MagicMock: Yields a mock.MagikMock object.
'''
with mock.patch('synapse.common.setlogging',
mock.MagicMock(return_value=None)) as patch: # type: mock.MagicMock
yield patch
def getMagicPromptLines(self, patch):
'''
Get the text lines from a MagicMock object from withCliPromptMock.
Args:
patch (mock.MagicMock): The MagicMock object from withCliPromptMock.
Returns:
list: A list of lines.
'''
self.true(patch.called, 'Assert prompt was called')
lines = []
for args in patch.call_args_list:
arg = args[0][0]
if isinstance(arg, str):
lines.append(arg)
continue
if isinstance(arg, FormattedText):
color, text = arg[0]
lines.append(text)
continue
raise ValueError(f'Unknown arg: {type(arg)}/{arg}')
return lines
def getMagicPromptColors(self, patch):
'''
Get the colored lines from a MagicMock object from withCliPromptMock.
Args:
patch (mock.MagicMock): The MagicMock object from withCliPromptMock.
Returns:
list: A list of tuples, containing color and line data.
'''
self.true(patch.called, 'Assert prompt was called')
lines = []
for args in patch.call_args_list:
arg = args[0][0]
if isinstance(arg, str):
continue
if isinstance(arg, FormattedText):
color, text = arg[0]
lines.append((color, text))
continue
raise ValueError(f'Unknown arg: {type(arg)}/{arg}')
return lines
def extendOutpFromPatch(self, outp, patch):
'''
Extend an Outp with lines from a magicMock object from withCliPromptMock.
Args:
outp (TstOutPut): The outp to extend.
patch (mock.MagicMock): The patch object.
Returns:
None: Returns none.
'''
lines = self.getMagicPromptLines(patch)
[outp.printf(line) for line in lines]
@contextlib.asynccontextmanager
async def getTestReadWriteCores(self, conf=None, dirn=None):
'''
Get a read/write core pair.
Notes:
By default, this returns the same cortex. It is expected that
a test which needs two distinct Cortexes implements the bridge
themselves.
Returns:
(s_cortex.Cortex, s_cortex.Cortex): A tuple of Cortex objects.
'''
async with self.getTestCore(conf=conf, dirn=dirn) as core:
yield core, core
@contextlib.contextmanager
def withNexusReplay(self, replay=False):
'''
Patch so that the Nexus apply log is applied twice. Useful to verify idempotency.
Notes:
This is applied if the environment variable SYNDEV_NEXUS_REPLAY is set
or the replay argument is set to True.
Returns:
contextlib.ExitStack: An exitstack object.
'''
replay = os.environ.get('SYNDEV_NEXUS_REPLAY', default=replay)
with contextlib.ExitStack() as stack:
if replay:
stack.enter_context(mock.patch.object(s_nexus.NexsRoot, '_apply', _doubleapply))
yield stack
@contextlib.asynccontextmanager
async def getTestCore(self, conf=None, dirn=None):
'''
Get a simple test Cortex as an async context manager.
Returns:
s_cortex.Cortex: A Cortex object.
'''
if conf is None:
conf = {'layer:lmdb:map_async': True,
'provenance:en': True,
'nexslog:en': True,
'layers:logedits': True,
}
conf = copy.deepcopy(conf)
mods = conf.get('modules')
if mods is None:
mods = []
conf['modules'] = mods
mods.append(('synapse.tests.utils.TestModule', {'key': 'valu'}))
with self.withNexusReplay():
if dirn is not None: