|
import contextlib |
|
import os |
|
import platform |
|
import socket |
|
import sys |
|
import textwrap |
|
import typing |
|
import unittest |
|
import warnings |
|
|
|
from tornado.testing import bind_unused_port |
|
|
|
skipIfNonUnix = unittest.skipIf( |
|
os.name != "posix" or sys.platform == "cygwin", "non-unix platform" |
|
) |
|
|
|
|
|
|
|
skipOnTravis = unittest.skipIf( |
|
"TRAVIS" in os.environ, "timing tests unreliable on travis" |
|
) |
|
|
|
|
|
|
|
skipIfNoNetwork = unittest.skipIf("NO_NETWORK" in os.environ, "network access disabled") |
|
|
|
skipNotCPython = unittest.skipIf( |
|
platform.python_implementation() != "CPython", "Not CPython implementation" |
|
) |
|
|
|
|
|
|
|
|
|
skipPypy3V58 = unittest.skipIf( |
|
platform.python_implementation() == "PyPy" |
|
and sys.version_info > (3,) |
|
and sys.pypy_version_info < (5, 9), |
|
"pypy3 5.8 has buggy ssl module", |
|
) |
|
|
|
|
|
def _detect_ipv6(): |
|
if not socket.has_ipv6: |
|
|
|
|
|
return False |
|
sock = None |
|
try: |
|
sock = socket.socket(socket.AF_INET6) |
|
sock.bind(("::1", 0)) |
|
except socket.error: |
|
return False |
|
finally: |
|
if sock is not None: |
|
sock.close() |
|
return True |
|
|
|
|
|
skipIfNoIPv6 = unittest.skipIf(not _detect_ipv6(), "ipv6 support not present") |
|
|
|
|
|
def refusing_port(): |
|
"""Returns a local port number that will refuse all connections. |
|
|
|
Return value is (cleanup_func, port); the cleanup function |
|
must be called to free the port to be reused. |
|
""" |
|
|
|
|
|
|
|
|
|
server_socket, port = bind_unused_port() |
|
server_socket.setblocking(True) |
|
client_socket = socket.socket() |
|
client_socket.connect(("127.0.0.1", port)) |
|
conn, client_addr = server_socket.accept() |
|
conn.close() |
|
server_socket.close() |
|
return (client_socket.close, client_addr[1]) |
|
|
|
|
|
def exec_test(caller_globals, caller_locals, s): |
|
"""Execute ``s`` in a given context and return the result namespace. |
|
|
|
Used to define functions for tests in particular python |
|
versions that would be syntax errors in older versions. |
|
""" |
|
|
|
|
|
|
|
global_namespace = dict(caller_globals, **caller_locals) |
|
local_namespace = {} |
|
exec(textwrap.dedent(s), global_namespace, local_namespace) |
|
return local_namespace |
|
|
|
|
|
def subTest(test, *args, **kwargs): |
|
"""Compatibility shim for unittest.TestCase.subTest. |
|
|
|
Usage: ``with tornado.test.util.subTest(self, x=x):`` |
|
""" |
|
try: |
|
subTest = test.subTest |
|
except AttributeError: |
|
subTest = contextlib.contextmanager(lambda *a, **kw: (yield)) |
|
return subTest(*args, **kwargs) |
|
|
|
|
|
@contextlib.contextmanager |
|
def ignore_deprecation(): |
|
"""Context manager to ignore deprecation warnings.""" |
|
with warnings.catch_warnings(): |
|
warnings.simplefilter("ignore", DeprecationWarning) |
|
yield |
|
|