support.py 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210
  1. """Support code for distutils test cases."""
  2. import os
  3. import sys
  4. import shutil
  5. import tempfile
  6. import unittest
  7. import sysconfig
  8. from copy import deepcopy
  9. from . import py38compat as os_helper
  10. from distutils import log
  11. from distutils.log import DEBUG, INFO, WARN, ERROR, FATAL
  12. from distutils.core import Distribution
  13. class LoggingSilencer(object):
  14. def setUp(self):
  15. super().setUp()
  16. self.threshold = log.set_threshold(log.FATAL)
  17. # catching warnings
  18. # when log will be replaced by logging
  19. # we won't need such monkey-patch anymore
  20. self._old_log = log.Log._log
  21. log.Log._log = self._log
  22. self.logs = []
  23. def tearDown(self):
  24. log.set_threshold(self.threshold)
  25. log.Log._log = self._old_log
  26. super().tearDown()
  27. def _log(self, level, msg, args):
  28. if level not in (DEBUG, INFO, WARN, ERROR, FATAL):
  29. raise ValueError('%s wrong log level' % str(level))
  30. if not isinstance(msg, str):
  31. raise TypeError("msg should be str, not '%.200s'"
  32. % (type(msg).__name__))
  33. self.logs.append((level, msg, args))
  34. def get_logs(self, *levels):
  35. return [msg % args for level, msg, args
  36. in self.logs if level in levels]
  37. def clear_logs(self):
  38. self.logs = []
  39. class TempdirManager(object):
  40. """Mix-in class that handles temporary directories for test cases.
  41. This is intended to be used with unittest.TestCase.
  42. """
  43. def setUp(self):
  44. super().setUp()
  45. self.old_cwd = os.getcwd()
  46. self.tempdirs = []
  47. def tearDown(self):
  48. # Restore working dir, for Solaris and derivatives, where rmdir()
  49. # on the current directory fails.
  50. os.chdir(self.old_cwd)
  51. super().tearDown()
  52. while self.tempdirs:
  53. tmpdir = self.tempdirs.pop()
  54. os_helper.rmtree(tmpdir)
  55. def mkdtemp(self):
  56. """Create a temporary directory that will be cleaned up.
  57. Returns the path of the directory.
  58. """
  59. d = tempfile.mkdtemp()
  60. self.tempdirs.append(d)
  61. return d
  62. def write_file(self, path, content='xxx'):
  63. """Writes a file in the given path.
  64. path can be a string or a sequence.
  65. """
  66. if isinstance(path, (list, tuple)):
  67. path = os.path.join(*path)
  68. f = open(path, 'w')
  69. try:
  70. f.write(content)
  71. finally:
  72. f.close()
  73. def create_dist(self, pkg_name='foo', **kw):
  74. """Will generate a test environment.
  75. This function creates:
  76. - a Distribution instance using keywords
  77. - a temporary directory with a package structure
  78. It returns the package directory and the distribution
  79. instance.
  80. """
  81. tmp_dir = self.mkdtemp()
  82. pkg_dir = os.path.join(tmp_dir, pkg_name)
  83. os.mkdir(pkg_dir)
  84. dist = Distribution(attrs=kw)
  85. return pkg_dir, dist
  86. class DummyCommand:
  87. """Class to store options for retrieval via set_undefined_options()."""
  88. def __init__(self, **kwargs):
  89. for kw, val in kwargs.items():
  90. setattr(self, kw, val)
  91. def ensure_finalized(self):
  92. pass
  93. class EnvironGuard(object):
  94. def setUp(self):
  95. super(EnvironGuard, self).setUp()
  96. self.old_environ = deepcopy(os.environ)
  97. def tearDown(self):
  98. for key, value in self.old_environ.items():
  99. if os.environ.get(key) != value:
  100. os.environ[key] = value
  101. for key in tuple(os.environ.keys()):
  102. if key not in self.old_environ:
  103. del os.environ[key]
  104. super(EnvironGuard, self).tearDown()
  105. def copy_xxmodule_c(directory):
  106. """Helper for tests that need the xxmodule.c source file.
  107. Example use:
  108. def test_compile(self):
  109. copy_xxmodule_c(self.tmpdir)
  110. self.assertIn('xxmodule.c', os.listdir(self.tmpdir))
  111. If the source file can be found, it will be copied to *directory*. If not,
  112. the test will be skipped. Errors during copy are not caught.
  113. """
  114. filename = _get_xxmodule_path()
  115. if filename is None:
  116. raise unittest.SkipTest('cannot find xxmodule.c (test must run in '
  117. 'the python build dir)')
  118. shutil.copy(filename, directory)
  119. def _get_xxmodule_path():
  120. srcdir = sysconfig.get_config_var('srcdir')
  121. candidates = [
  122. # use installed copy if available
  123. os.path.join(os.path.dirname(__file__), 'xxmodule.c'),
  124. # otherwise try using copy from build directory
  125. os.path.join(srcdir, 'Modules', 'xxmodule.c'),
  126. # srcdir mysteriously can be $srcdir/Lib/distutils/tests when
  127. # this file is run from its parent directory, so walk up the
  128. # tree to find the real srcdir
  129. os.path.join(srcdir, '..', '..', '..', 'Modules', 'xxmodule.c'),
  130. ]
  131. for path in candidates:
  132. if os.path.exists(path):
  133. return path
  134. def fixup_build_ext(cmd):
  135. """Function needed to make build_ext tests pass.
  136. When Python was built with --enable-shared on Unix, -L. is not enough to
  137. find libpython<blah>.so, because regrtest runs in a tempdir, not in the
  138. source directory where the .so lives.
  139. When Python was built with in debug mode on Windows, build_ext commands
  140. need their debug attribute set, and it is not done automatically for
  141. some reason.
  142. This function handles both of these things. Example use:
  143. cmd = build_ext(dist)
  144. support.fixup_build_ext(cmd)
  145. cmd.ensure_finalized()
  146. Unlike most other Unix platforms, Mac OS X embeds absolute paths
  147. to shared libraries into executables, so the fixup is not needed there.
  148. """
  149. if os.name == 'nt':
  150. cmd.debug = sys.executable.endswith('_d.exe')
  151. elif sysconfig.get_config_var('Py_ENABLE_SHARED'):
  152. # To further add to the shared builds fun on Unix, we can't just add
  153. # library_dirs to the Extension() instance because that doesn't get
  154. # plumbed through to the final compiler command.
  155. runshared = sysconfig.get_config_var('RUNSHARED')
  156. if runshared is None:
  157. cmd.library_dirs = ['.']
  158. else:
  159. if sys.platform == 'darwin':
  160. cmd.library_dirs = []
  161. else:
  162. name, equals, value = runshared.partition('=')
  163. cmd.library_dirs = [d for d in value.split(os.pathsep) if d]