-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathtest_integrations.py
207 lines (161 loc) · 5.49 KB
/
test_integrations.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
import asyncio
import os
import re
import socket
import warnings
from datetime import timedelta
import pytest
from process_tests import dump_on_error
from process_tests import wait_for_strings
from tornado import gen
from tornado import ioloop
import aspectlib
from aspectlib import debug
from aspectlib.test import mock
from aspectlib.test import record
from aspectlib.utils import PYPY
try:
from StringIO import StringIO
except ImportError:
from io import StringIO
LOG_TEST_SOCKET = r"""^\{_?socket(object)?\}.connect\(\('127.0.0.1', 1\)\) +<<< .*tests[\/]test_integrations.py:\d+:test_socket.*
\{_?socket(object)?\}.connect \~ raised .*(ConnectionRefusedError|error)\((10061|111), .*refused.*\)"""
def test_mock_builtin():
with aspectlib.weave(open, mock('foobar')):
assert open('???') == 'foobar' # noqa: PTH123
assert open(__file__) != 'foobar' # noqa: PTH123
def test_mock_builtin_os():
print(os.open.__name__)
with aspectlib.weave('os.open', mock('foobar')):
assert os.open('???') == 'foobar'
assert os.open(__file__, 0) != 'foobar'
def test_record_warning():
with aspectlib.weave('warnings.warn', record):
warnings.warn('crap', stacklevel=1)
assert warnings.warn.calls == [(None, ('crap',), {'stacklevel': 1})]
@pytest.mark.skipif(not hasattr(os, 'fork'), reason='os.fork not available')
def test_fork():
with aspectlib.weave('os.fork', mock('foobar')):
pid = os.fork()
if not pid:
os._exit(0)
assert pid == 'foobar'
pid = os.fork()
if not pid:
os._exit(0)
assert pid != 'foobar'
def test_socket(target=socket.socket):
buf = StringIO()
with aspectlib.weave(target, aspectlib.debug.log(print_to=buf, stacktrace=4, module=False), lazy=True):
s = socket.socket()
try:
s.connect(('127.0.0.1', 1))
except Exception: # noqa: S110
pass
print(buf.getvalue())
assert re.match(LOG_TEST_SOCKET, buf.getvalue())
s = socket.socket()
try:
s.connect(('127.0.0.1', 1))
except Exception: # noqa: S110
pass
assert re.match(LOG_TEST_SOCKET, buf.getvalue())
def test_socket_as_string_target():
test_socket(target='socket.socket')
def test_socket_meth(meth=socket.socket.close):
calls = []
with aspectlib.weave(meth, record(calls=calls)):
s = socket.socket()
assert s.close() is None
assert calls == [(s, (), {})]
del calls[:]
s = socket.socket()
assert s.close() is None
assert calls == []
def test_socket_meth_as_string_target():
test_socket_meth('socket.socket.close')
def test_socket_all_methods():
buf = StringIO()
with aspectlib.weave(socket.socket, aspectlib.debug.log(print_to=buf, stacktrace=False), lazy=True, methods=aspectlib.ALL_METHODS):
socket.socket()
assert '}.__init__ => None' in buf.getvalue()
@pytest.mark.skipif(not hasattr(os, 'fork') or PYPY, reason='os.fork not available or PYPY')
def test_realsocket_makefile():
buf = StringIO()
p = socket.socket()
p.bind(('127.0.0.1', 0))
p.listen(1)
p.settimeout(1)
pid = os.fork()
if pid:
with aspectlib.weave(
['socket.SocketIO', 'socket.socket'],
aspectlib.debug.log(print_to=buf, stacktrace=False),
lazy=True,
methods=aspectlib.ALL_METHODS,
):
s = socket.socket()
s.settimeout(1)
s.connect(p.getsockname())
fh = s.makefile('rwb', buffering=0)
fh.write(b'STUFF\n')
fh.readline()
with dump_on_error(buf.getvalue):
wait_for_strings(
buf.getvalue,
0,
'}.connect',
'}.makefile',
'}.write(',
'}.send',
'}.write =>',
'}.readline()',
'}.recv',
'}.readline => ',
)
else:
try:
c, _ = p.accept()
c.settimeout(1)
f = c.makefile('rw', buffering=1)
while f.readline():
f.write('-\n')
finally:
os._exit(0)
def test_weave_os_module():
calls = []
with aspectlib.weave('os', record(calls=calls, extended=True), methods='getenv|walk'):
os.getenv('BUBU', 'bubu')
os.walk('.')
assert calls == [(None, 'os.getenv', ('BUBU', 'bubu'), {}), (None, 'os.walk', ('.',), {})]
def test_decorate_asyncio_coroutine():
buf = StringIO()
@debug.log(print_to=buf, module=False, stacktrace=2, result_repr=repr)
async def coro():
await asyncio.sleep(0.01)
return 'result'
loop = asyncio.new_event_loop()
loop.run_until_complete(coro())
output = buf.getvalue()
print(output)
assert 'coro => {!r}'.format('result') in output
def test_decorate_tornado_coroutine():
buf = StringIO()
@gen.coroutine
@debug.log(print_to=buf, module=False, stacktrace=2, result_repr=repr)
def coro():
if hasattr(gen, 'Task'):
yield gen.Task(loop.add_timeout, timedelta(microseconds=10))
else:
yield gen.sleep(0.01)
return 'result'
asyncio_loop = asyncio.new_event_loop()
try:
get_event_loop = asyncio.get_event_loop
asyncio.get_event_loop = lambda: asyncio_loop
loop = ioloop.IOLoop.current()
loop.run_sync(coro)
finally:
asyncio.get_event_loop = get_event_loop
output = buf.getvalue()
assert 'coro => {!r}'.format('result') in output