Debian Codegraph @

tests/conftest.py

raw symbols ◀ ▶
Source reconstructed at patch state 1 of 2 — not the installed (fully patched) source.
2 Debian patches touch this file
1 import asyncio
2 import collections
3 import contextlib
4 import functools
5 import math
6 import socket
7 import ssl
8 import tempfile
9 import time
10 from pathlib import Path
11
12 import pytest
13 import pytest_asyncio
14 import trustme
15 from async_timeout import timeout
16 try:
17 from siosocks.io.asyncio import socks_server_handler
18 except ImportError:
19 pass
20
21 import aioftp
22
23 # No ssl tests since https://bugs.python.org/issue36098
24 ca = trustme.CA()
25 server_cert = ca.issue_server_cert("127.0.0.1", "::1")
26
27 ssl_server = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
28 server_cert.configure_cert(ssl_server)
29
30 ssl_client = ssl.create_default_context(ssl.Purpose.SERVER_AUTH)
31 ca.configure_trust(ssl_client)
32
33
34 class Container:
35 def __init__(self, *args, **kwargs):
36 self.args = args
37 self.kwargs = kwargs
38
39
40 @pytest.fixture
41 def Client():
42 return Container
43
44
45 @pytest.fixture
46 def Server():
47 return Container
48
49
50 def _wrap_with_defaults(kwargs):
51 test_defaults = dict(
52 path_io_factory=aioftp.MemoryPathIO,
53 )
54 return collections.ChainMap(kwargs, test_defaults)
55
56
57 @pytest.fixture(params=["127.0.0.1", "::1"])
58 def pair_factory(request):
59 class Factory:
60 def __init__(
61 self,
62 client=None,
63 server=None,
64 *,
65 connected=True,
66 logged=True,
67 do_quit=True,
68 host=request.param,
69 server_factory=aioftp.Server,
70 client_factory=aioftp.Client,
71 ):
72 if client is None:
73 client = Container()
74 self.client = client_factory(*client.args, **_wrap_with_defaults(client.kwargs))
75 if server is None:
76 server = Container()
77 self.server = server_factory(*server.args, **_wrap_with_defaults(server.kwargs))
78 self.connected = connected
79 self.logged = logged
80 self.do_quit = do_quit
81 self.host = host
82 self.timeout = timeout(1)
83
84 async def make_server_files(self, *paths, size=None, atom=b"-"):
85 if size is None:
86 size = aioftp.DEFAULT_BLOCK_SIZE * 3
87 data = atom * size
88 for p in paths:
89 await self.client.make_directory(Path(p).parent)
90 async with self.client.upload_stream(p) as stream:
91 await stream.write(data)
92
93 async def make_client_files(self, *paths, size=None, atom=b"-"):
94 if size is None:
95 size = aioftp.DEFAULT_BLOCK_SIZE * 3
96 data = atom * size
97 for p in map(Path, paths):
98 await self.client.path_io.mkdir(
99 p.parent,
100 parents=True,
101 exist_ok=True,
102 )
103 async with self.client.path_io.open(p, mode="wb") as f:
104 await f.write(data)
105
106 async def server_paths_exists(self, *paths):
107 values = []
108 for p in paths:
109 values.append(await self.client.exists(p))
110 if all(values):
111 return True
112 if any(values):
113 raise ValueError("Mixed exists/not exists list")
114 return False
115
116 async def client_paths_exists(self, *paths):
117 values = []
118 for p in paths:
119 values.append(await self.client.path_io.exists(Path(p)))
120 if all(values):
121 return True
122 if any(values):
123 raise ValueError("Mixed exists/not exists list")
124 return False
125
126 async def __aenter__(self):
127 await self.timeout.__aenter__()
128 await self.server.start(host=self.host)
129 if self.connected:
130 await self.client.connect(
131 self.server.server_host,
132 self.server.server_port,
133 )
134 if self.logged:
135 await self.client.login()
136 return self
137
138 async def __aexit__(self, *exc_info):
139 if self.connected and self.do_quit:
140 await self.client.quit()
141 self.client.close()
142 await self.server.close()
143 await self.timeout.__aexit__(*exc_info)
144
145 return Factory
146
147
148 @pytest.fixture
149 def expect_codes_in_exception():
150 @contextlib.contextmanager
151 def context(*codes):
152 try:
153 yield
154 except aioftp.StatusCodeError as e:
155 assert set(e.received_codes) == set(codes)
156 else:
157 raise RuntimeError("There was no exception")
158
159 return context
160
161
162 @pytest.fixture(
163 params=[
164 aioftp.MemoryPathIO,
165 aioftp.PathIO,
166 aioftp.AsyncPathIO,
167 ],
168 )
169 def path_io(request):
170 return request.param()
171
172
173 @pytest.fixture
174 def temp_dir(path_io):
175 if isinstance(path_io, aioftp.MemoryPathIO):
176 yield Path("/")
177 else:
178 with tempfile.TemporaryDirectory() as name:
179 yield Path(name)
180
181
182 class Sleep:
183 def __init__(self):
184 self.delay = 0
185 self.first_sleep = None
186
187 async def sleep(self, delay, result=None, **kwargs):
188 if self.first_sleep is None:
189 self.first_sleep = time.monotonic()
190 delay = (time.monotonic() - self.first_sleep) + delay
191 self.delay = max(self.delay, delay)
192 return result
193
194 def is_close(self, delay, *, rel_tol=0.05, abs_tol=0.5):
195 ok = math.isclose(self.delay, delay, rel_tol=rel_tol, abs_tol=abs_tol)
196 if not ok:
197 print(
198 f"latest sleep: {self.delay}; expected delay: {delay}; rel: {rel_tol}",
199 )
200 return ok
201
202
203 @pytest.fixture
204 def skip_sleep(monkeypatch):
205 with monkeypatch.context() as m:
206 sleeper = Sleep()
207 m.setattr(asyncio, "sleep", sleeper.sleep)
208 yield sleeper
209
210
211 @pytest_asyncio.fixture(
212 params=[
213 ("127.0.0.1", socket.AF_INET),
214 ("::1", socket.AF_INET6),
215 ],
216 )
217 async def socks(request, unused_tcp_port):
218 handler = functools.partial(
219 socks_server_handler,
220 allowed_versions={5},
221 username="foo",
222 password="bar",
223 )
224 Socks = collections.namedtuple("Socks", "host port server")
225 host, family = request.param
226 port = unused_tcp_port
227 server = await asyncio.start_server(
228 handler,
229 host=host,
230 port=port,
231 family=family,
232 )
233 yield Socks(host, port, server)
234 server.close()
235 await server.wait_closed()