Debian Codegraph @

tests/support.py

raw symbols SCIP
1 # -*- coding: utf-8 -*-
2 #
3 # Copyright (C) 2012-2013 The Python Software Foundation.
4 # See LICENSE.txt and CONTRIBUTORS.txt.
5 #
6 import codecs
7 import os
8 import logging
9 import logging.handlers
10 import shutil
11 import socket
12 try:
13 import ssl
14 except ImportError:
15 ssl = None
16 import sys
17 import tempfile
18 try:
19 import threading
20 except ImportError:
21 import dummy_threading as threading
22 import weakref
23
24 from compat import (unittest, HTTPServer as BaseHTTPServer, SimpleHTTPRequestHandler, urlparse)
25
26 from distlib import logger
27
28 HERE = os.path.dirname(__file__)
29
30
31 class _TestHandler(logging.handlers.BufferingHandler, object):
32 # stolen and adapted from test.support
33
34 def __init__(self):
35 super(_TestHandler, self).__init__(0)
36 self.setLevel(logging.DEBUG)
37
38 def shouldFlush(self):
39 return False
40
41 def emit(self, record):
42 self.buffer.append(record)
43
44
45 class LoggingCatcher(object):
46 """TestCase-compatible mixin to receive logging calls.
47
48 Upon setUp, instances of this classes get a BufferingHandler that's
49 configured to record all messages logged to the 'distutils2' logger.
50
51 Use get_logs to retrieve messages and self.loghandler.flush to discard
52 them. get_logs automatically flushes the logs, unless you pass
53 *flush=False*, for example to make multiple calls to the method with
54 different level arguments. If your test calls some code that generates
55 logging message and then you don't call get_logs, you will need to flush
56 manually before testing other code in the same test_* method, otherwise
57 get_logs in the next lines will see messages from the previous lines.
58 See example in test_command_check.
59 """
60
61 def setUp(self):
62 super(LoggingCatcher, self).setUp()
63 self.loghandler = handler = _TestHandler()
64 self._old_level = logger.level
65 logger.addHandler(handler)
66 logger.setLevel(logging.DEBUG) # we want all messages
67
68 def tearDown(self):
69 handler = self.loghandler
70 # All this is necessary to properly shut down the logging system and
71 # avoid a regrtest complaint. Thanks to Vinay Sajip for the help.
72 handler.close()
73 logger.removeHandler(handler)
74 for ref in weakref.getweakrefs(handler):
75 logging._removeHandlerRef(ref)
76 del self.loghandler
77 logger.setLevel(self._old_level)
78 super(LoggingCatcher, self).tearDown()
79
80 def get_logs(self, level=logging.WARNING, flush=True):
81 """Return all log messages with given level.
82
83 *level* defaults to logging.WARNING.
84
85 For log calls with arguments (i.e. logger.info('bla bla %r', arg)),
86 the messages will be formatted before being returned (e.g. "bla bla
87 'thing'").
88
89 Returns a list. Automatically flushes the loghandler after being
90 called, unless *flush* is False (this is useful to get e.g. all
91 warnings then all info messages).
92 """
93 messages = [log.getMessage() for log in self.loghandler.buffer if log.levelno == level]
94 if flush:
95 self.loghandler.flush()
96 return messages
97
98
99 class TempdirManager(object):
100 """TestCase-compatible mixin to create temporary directories and files.
101
102 Directories and files created in a test_* method will be removed after it
103 has run.
104 """
105
106 def setUp(self):
107 super(TempdirManager, self).setUp()
108 self._olddir = os.getcwd()
109 self._basetempdir = tempfile.mkdtemp()
110 self._files = []
111
112 def tearDown(self):
113 for handle, name in self._files:
114 if handle is not None:
115 handle.close()
116 os.remove(name)
117
118 os.chdir(self._olddir)
119 shutil.rmtree(self._basetempdir)
120 super(TempdirManager, self).tearDown()
121
122 def temp_filename(self):
123 """Create a read-write temporary file name and return it."""
124 fd, fn = tempfile.mkstemp(dir=self._basetempdir)
125 os.close(fd)
126 self._files.append((None, fn))
127 return fn
128
129 def mktempfile(self):
130 """Create a read-write temporary file and return it."""
131 fd, fn = tempfile.mkstemp(dir=self._basetempdir)
132 os.close(fd)
133 fp = open(fn, 'w+')
134 self._files.append((fp, fn))
135 return fp
136
137 def mkdtemp(self):
138 """Create a temporary directory and return its path."""
139 d = tempfile.mkdtemp(dir=self._basetempdir)
140 return d
141
142 def write_file(self, path, content='xxx', encoding=None):
143 """Write a file at the given path.
144
145 path can be a string, a tuple or a list; if it's a tuple or list,
146 os.path.join will be used to produce a path.
147 """
148 if isinstance(path, (list, tuple)):
149 path = os.path.join(*path)
150 f = codecs.open(path, 'w', encoding=encoding)
151 try:
152 f.write(content)
153 finally:
154 f.close()
155
156 def assertIsFile(self, *args):
157 path = os.path.join(*args)
158 dirname = os.path.dirname(path)
159 file = os.path.basename(path)
160 if os.path.isdir(dirname):
161 files = os.listdir(dirname)
162 msg = "%s not found in %s: %s" % (file, dirname, files)
163 assert os.path.isfile(path), msg
164 else:
165 raise AssertionError('%s not found. %s does not exist' % (file, dirname))
166
167 def assertIsNotFile(self, *args):
168 path = os.path.join(*args)
169 self.assertFalse(os.path.isfile(path), "%r exists" % path)
170
171
172 class EnvironRestorer(object):
173 """TestCase-compatible mixin to restore or delete environment variables.
174
175 The variables to restore (or delete if they were not originally present)
176 must be explicitly listed in self.restore_environ. It's better to be
177 aware of what we're modifying instead of saving and restoring the whole
178 environment.
179 """
180
181 def setUp(self):
182 super(EnvironRestorer, self).setUp()
183 self._saved = []
184 self._added = []
185 for key in self.restore_environ:
186 if key in os.environ:
187 self._saved.append((key, os.environ[key]))
188 else:
189 self._added.append(key)
190
191 def tearDown(self):
192 for key, value in self._saved:
193 os.environ[key] = value
194 for key in self._added:
195 os.environ.pop(key, None)
196 super(EnvironRestorer, self).tearDown()
197
198
199 class HTTPRequestHandler(SimpleHTTPRequestHandler):
200
201 server_version = "TestHTTPS/1.0"
202 # Avoid hanging when a request gets interrupted by the client
203 timeout = 5
204
205 def translate_path(self, path):
206 return os.path.join(HERE, 'testsrc', 'README.txt')
207
208 def log_message(self, format, *args):
209 pass
210
211
212 class HTTPSServer(BaseHTTPServer):
213 # Adapted from the one in Python's test suite.
214 def __init__(self, server_address, handler_class, certfile):
215 BaseHTTPServer.__init__(self, server_address, handler_class)
216 self.certfile = certfile
217
218 def get_request(self):
219 try:
220 sock, addr = self.socket.accept()
221 if hasattr(ssl, 'SSLContext'):
222 context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
223 context.load_cert_chain(self.certfile)
224 sock = context.wrap_socket(sock, server_side=True)
225 else:
226 sock = ssl.wrap_socket(sock,
227 server_side=True,
228 certfile=self.certfile,
229 keyfile=self.certfile,
230 ssl_version=ssl.PROTOCOL_SSLv23)
231 except socket.error as e:
232 # socket errors are silenced by the caller, print them here
233 sys.stderr.write("Got an error:\n%s\n" % e)
234 raise
235 return sock, addr
236
237
238 class HTTPSServerThread(threading.Thread):
239
240 def __init__(self, certfile):
241 self.flag = None
242 self.server = HTTPSServer(('localhost', 0), HTTPRequestHandler, certfile)
243 self.port = self.server.server_port
244 threading.Thread.__init__(self)
245 self.daemon = True
246
247 def start(self, flag=None):
248 self.flag = flag
249 threading.Thread.start(self)
250
251 def run(self):
252 if self.flag:
253 self.flag.set()
254 try:
255 self.server.serve_forever(0.05)
256 finally:
257 self.server.server_close()
258
259 def stop(self):
260 self.server.shutdown()
261
262
263 try:
264 import zlib
265 except ImportError:
266 zlib = None
267
268 requires_zlib = unittest.skipUnless(zlib, 'requires zlib')
269
270 _can_symlink = None
271
272
273 def can_symlink():
274 global _can_symlink
275 if _can_symlink is not None:
276 return _can_symlink
277 fd, TESTFN = tempfile.mkstemp()
278 os.close(fd)
279 os.remove(TESTFN)
280 symlink_path = TESTFN + "can_symlink"
281 try:
282 os.symlink(TESTFN, symlink_path)
283 can = True
284 except (OSError, NotImplementedError, AttributeError):
285 can = False
286 else:
287 os.remove(symlink_path)
288 _can_symlink = can
289 return can
290
291
292 def skip_unless_symlink(test):
293 """Skip decorator for tests that require functional symlink"""
294 ok = can_symlink()
295 msg = "Requires functional symlink implementation"
296 return test if ok else unittest.skip(msg)(test)
297
298
299 def fake_dec(*args, **kw):
300 """Fake decorator"""
301
302 def _wrap(func):
303
304 def __wrap(*args, **kw):
305 return func(*args, **kw)
306
307 return __wrap
308
309 return _wrap
310
311
312 def in_github_workflow():
313 return 'GITHUB_WORKFLOW' in os.environ
314
315
316 SEP = '-' * 80
317
318
319 class DistlibTestCase(unittest.TestCase):
320
321 def setUp(self):
322 logger.debug(SEP)
323 logger.debug(self.id().rsplit('.', 1)[-1])
324 logger.debug(SEP)