Debian Codegraph @

tests/testutils.py

raw
1 import sys
2 import os
3 import io
4 import difflib
5 import tempfile
6 import os.path as op
7 from subprocess import Popen, check_output, PIPE, STDOUT, CalledProcessError
8 import pickle
9 import pickletools
10 from contextlib import contextmanager
11 from concurrent.futures import ProcessPoolExecutor
12
13 import psutil
14 from cloudpickle import dumps
15 from subprocess import TimeoutExpired
16
17 loads = pickle.loads
18 TIMEOUT = 60
19 TEST_GLOBALS = "a test value"
20
21
22 def make_local_function():
23 def g(x):
24 # this function checks that the globals are correctly handled and that
25 # the builtins are available
26 assert TEST_GLOBALS == "a test value"
27 return sum(range(10))
28
29 return g
30
31
32 def _make_cwd_env():
33 """Helper to prepare environment for the child processes"""
34 cloudpickle_repo_folder = op.normpath(op.join(op.dirname(__file__), ".."))
35 env = os.environ.copy()
36 pythonpath = "{src}{sep}tests{pathsep}{src}".format(
37 src=cloudpickle_repo_folder, sep=os.sep, pathsep=os.pathsep
38 )
39 env["PYTHONPATH"] = pythonpath
40 return cloudpickle_repo_folder, env
41
42
43 def subprocess_pickle_string(input_data, protocol=None, timeout=TIMEOUT, add_env=None):
44 """Retrieve pickle string of an object generated by a child Python process
45
46 Pickle the input data into a buffer, send it to a subprocess via
47 stdin, expect the subprocess to unpickle, re-pickle that data back
48 and send it back to the parent process via stdout for final unpickling.
49
50 >>> testutils.subprocess_pickle_string([1, 'a', None], protocol=2)
51 b'\x80\x02]q\x00(K\x01X\x01\x00\x00\x00aq\x01Ne.'
52
53 """
54 # run then pickle_echo(protocol=protocol) in __main__:
55
56 # Protect stderr from any warning, as we will assume an error will happen
57 # if it is not empty. A concrete example is pytest using the imp module,
58 # which is deprecated in python 3.8
59 cmd = [sys.executable, "-W ignore", __file__, "--protocol", str(protocol)]
60 cwd, env = _make_cwd_env()
61 if add_env:
62 env.update(add_env)
63 proc = Popen(
64 cmd, stdin=PIPE, stdout=PIPE, stderr=PIPE, cwd=cwd, env=env, bufsize=4096
65 )
66 pickle_string = dumps(input_data, protocol=protocol)
67 try:
68 comm_kwargs = {}
69 comm_kwargs["timeout"] = timeout
70 out, err = proc.communicate(pickle_string, **comm_kwargs)
71 if proc.returncode != 0 or len(err):
72 message = "Subprocess returned %d: " % proc.returncode
73 message += err.decode("utf-8")
74 raise RuntimeError(message)
75 return out
76 except TimeoutExpired as e:
77 proc.kill()
78 out, err = proc.communicate()
79 message = "\n".join([out.decode("utf-8"), err.decode("utf-8")])
80 raise RuntimeError(message) from e
81
82
83 def subprocess_pickle_echo(input_data, protocol=None, timeout=TIMEOUT, add_env=None):
84 """Echo function with a child Python process
85 Pickle the input data into a buffer, send it to a subprocess via
86 stdin, expect the subprocess to unpickle, re-pickle that data back
87 and send it back to the parent process via stdout for final unpickling.
88 >>> subprocess_pickle_echo([1, 'a', None])
89 [1, 'a', None]
90 """
91 out = subprocess_pickle_string(
92 input_data, protocol=protocol, timeout=timeout, add_env=add_env
93 )
94 return loads(out)
95
96
97 def _read_all_bytes(stream_in, chunk_size=4096):
98 all_data = b""
99 while True:
100 data = stream_in.read(chunk_size)
101 all_data += data
102 if len(data) < chunk_size:
103 break
104 return all_data
105
106
107 def pickle_echo(stream_in=None, stream_out=None, protocol=None):
108 """Read a pickle from stdin and pickle it back to stdout"""
109 if stream_in is None:
110 stream_in = sys.stdin
111 if stream_out is None:
112 stream_out = sys.stdout
113
114 # Force the use of bytes streams under Python 3
115 if hasattr(stream_in, "buffer"):
116 stream_in = stream_in.buffer
117 if hasattr(stream_out, "buffer"):
118 stream_out = stream_out.buffer
119
120 input_bytes = _read_all_bytes(stream_in)
121 stream_in.close()
122 obj = loads(input_bytes)
123 repickled_bytes = dumps(obj, protocol=protocol)
124 stream_out.write(repickled_bytes)
125 stream_out.close()
126
127
128 def call_func(payload, protocol):
129 """Remote function call that uses cloudpickle to transport everthing"""
130 func, args, kwargs = loads(payload)
131 try:
132 result = func(*args, **kwargs)
133 except BaseException as e:
134 result = e
135 return dumps(result, protocol=protocol)
136
137
138 class _Worker:
139 def __init__(self, protocol=None):
140 self.protocol = protocol
141 self.pool = ProcessPoolExecutor(max_workers=1)
142 self.pool.submit(id, 42).result() # start the worker process
143
144 def run(self, func, *args, **kwargs):
145 """Synchronous remote function call"""
146
147 input_payload = dumps((func, args, kwargs), protocol=self.protocol)
148 result_payload = self.pool.submit(
149 call_func, input_payload, self.protocol
150 ).result()
151 result = loads(result_payload)
152
153 if isinstance(result, BaseException):
154 raise result
155 return result
156
157 def memsize(self):
158 workers_pids = [
159 p.pid if hasattr(p, "pid") else p for p in list(self.pool._processes)
160 ]
161 num_workers = len(workers_pids)
162 if num_workers == 0:
163 return 0
164 elif num_workers > 1:
165 raise RuntimeError("Unexpected number of workers: %d" % num_workers)
166 return psutil.Process(workers_pids[0]).memory_info().rss
167
168 def close(self):
169 self.pool.shutdown(wait=True)
170
171
172 @contextmanager
173 def subprocess_worker(protocol=None):
174 worker = _Worker(protocol=protocol)
175 yield worker
176 worker.close()
177
178
179 def assert_run_python_script(source_code, timeout=TIMEOUT):
180 """Utility to help check pickleability of objects defined in __main__
181
182 The script provided in the source code should return 0 and not print
183 anything on stderr or stdout.
184 """
185 fd, source_file = tempfile.mkstemp(suffix="_src_test_cloudpickle.py")
186 os.close(fd)
187 try:
188 with open(source_file, "wb") as f:
189 f.write(source_code.encode("utf-8"))
190 cmd = [sys.executable, "-W ignore", source_file]
191 cwd, env = _make_cwd_env()
192 kwargs = {
193 "cwd": cwd,
194 "stderr": STDOUT,
195 "env": env,
196 }
197 # If coverage is running, pass the config file to the subprocess
198 coverage_rc = os.environ.get("COVERAGE_PROCESS_START")
199 if coverage_rc:
200 kwargs["env"]["COVERAGE_PROCESS_START"] = coverage_rc
201 kwargs["timeout"] = timeout
202 try:
203 try:
204 out = check_output(cmd, **kwargs)
205 except CalledProcessError as e:
206 raise RuntimeError(
207 "script errored with output:\n%s" % e.output.decode("utf-8")
208 ) from e
209 if out != b"":
210 raise AssertionError(out.decode("utf-8"))
211 except TimeoutExpired as e:
212 raise RuntimeError(
213 "script timeout, output so far:\n%s" % e.output.decode("utf-8")
214 ) from e
215 finally:
216 os.unlink(source_file)
217
218
219 def check_deterministic_pickle(a, b):
220 """Check that two pickle output are bitwise equal.
221
222 If it is not the case, print the diff between the disassembled pickle
223 payloads.
224
225 This helper is useful to investigate non-deterministic pickling.
226 """
227 if a != b:
228 with io.StringIO() as out:
229 pickletools.dis(pickletools.optimize(a), out)
230 a_out = out.getvalue()
231 # Remove the 11 first characters of each line to remove the bytecode offset
232 # of each object, which is different on each line for very small differences,
233 # making the diff very hard to read.
234 a_out = "\n".join(ll[11:] for ll in a_out.splitlines())
235 with io.StringIO() as out:
236 pickletools.dis(pickletools.optimize(b), out)
237 b_out = out.getvalue()
238 b_out = "\n".join(ll[11:] for ll in b_out.splitlines())
239 assert a_out == b_out
240 full_diff = difflib.context_diff(
241 a_out.splitlines(keepends=True), b_out.splitlines(keepends=True)
242 )
243 full_diff = "".join(full_diff)
244 if len(full_diff) > 1500:
245 full_diff = full_diff[:1494] + " [...]"
246 raise AssertionError(
247 "Pickle payloads are not bitwise equal:\n"
248 + full_diff
249 )
250
251
252 if __name__ == "__main__":
253 protocol = int(sys.argv[sys.argv.index("--protocol") + 1])
254 pickle_echo(protocol=protocol)