File manager - Edit - /home/newsbmcs.com/public_html/static/img/logo/_distutils.zip
Back
PK ,�ZfzO�� � tests/test_build_py.pynu �[��� """Tests for distutils.command.build_py.""" import os import sys from distutils.command.build_py import build_py from distutils.core import Distribution from distutils.errors import DistutilsFileError from distutils.tests import support import jaraco.path import pytest @support.combine_markers class TestBuildPy(support.TempdirManager): def test_package_data(self): sources = self.mkdtemp() jaraco.path.build( { '__init__.py': "# Pretend this is a package.", 'README.txt': 'Info about this package', }, sources, ) destination = self.mkdtemp() dist = Distribution({"packages": ["pkg"], "package_dir": {"pkg": sources}}) # script_name need not exist, it just need to be initialized dist.script_name = os.path.join(sources, "setup.py") dist.command_obj["build"] = support.DummyCommand( force=False, build_lib=destination ) dist.packages = ["pkg"] dist.package_data = {"pkg": ["README.txt"]} dist.package_dir = {"pkg": sources} cmd = build_py(dist) cmd.compile = True cmd.ensure_finalized() assert cmd.package_data == dist.package_data cmd.run() # This makes sure the list of outputs includes byte-compiled # files for Python modules but not for package data files # (there shouldn't *be* byte-code files for those!). assert len(cmd.get_outputs()) == 3 pkgdest = os.path.join(destination, "pkg") files = os.listdir(pkgdest) pycache_dir = os.path.join(pkgdest, "__pycache__") assert "__init__.py" in files assert "README.txt" in files if sys.dont_write_bytecode: assert not os.path.exists(pycache_dir) else: pyc_files = os.listdir(pycache_dir) assert f"__init__.{sys.implementation.cache_tag}.pyc" in pyc_files def test_empty_package_dir(self): # See bugs #1668596/#1720897 sources = self.mkdtemp() jaraco.path.build({'__init__.py': '', 'doc': {'testfile': ''}}, sources) os.chdir(sources) dist = Distribution({ "packages": ["pkg"], "package_dir": {"pkg": ""}, "package_data": {"pkg": ["doc/*"]}, }) # script_name need not exist, it just need to be initialized dist.script_name = os.path.join(sources, "setup.py") dist.script_args = ["build"] dist.parse_command_line() try: dist.run_commands() except DistutilsFileError: self.fail("failed package_data test when package_dir is ''") @pytest.mark.skipif('sys.dont_write_bytecode') def test_byte_compile(self): project_dir, dist = self.create_dist(py_modules=['boiledeggs']) os.chdir(project_dir) self.write_file('boiledeggs.py', 'import antigravity') cmd = build_py(dist) cmd.compile = True cmd.build_lib = 'here' cmd.finalize_options() cmd.run() found = os.listdir(cmd.build_lib) assert sorted(found) == ['__pycache__', 'boiledeggs.py'] found = os.listdir(os.path.join(cmd.build_lib, '__pycache__')) assert found == [f'boiledeggs.{sys.implementation.cache_tag}.pyc'] @pytest.mark.skipif('sys.dont_write_bytecode') def test_byte_compile_optimized(self): project_dir, dist = self.create_dist(py_modules=['boiledeggs']) os.chdir(project_dir) self.write_file('boiledeggs.py', 'import antigravity') cmd = build_py(dist) cmd.compile = False cmd.optimize = 1 cmd.build_lib = 'here' cmd.finalize_options() cmd.run() found = os.listdir(cmd.build_lib) assert sorted(found) == ['__pycache__', 'boiledeggs.py'] found = os.listdir(os.path.join(cmd.build_lib, '__pycache__')) expect = f'boiledeggs.{sys.implementation.cache_tag}.opt-1.pyc' assert sorted(found) == [expect] def test_dir_in_package_data(self): """ A directory in package_data should not be added to the filelist. """ # See bug 19286 sources = self.mkdtemp() jaraco.path.build( { 'pkg': { '__init__.py': '', 'doc': { 'testfile': '', # create a directory that could be incorrectly detected as a file 'otherdir': {}, }, } }, sources, ) os.chdir(sources) dist = Distribution({"packages": ["pkg"], "package_data": {"pkg": ["doc/*"]}}) # script_name need not exist, it just need to be initialized dist.script_name = os.path.join(sources, "setup.py") dist.script_args = ["build"] dist.parse_command_line() try: dist.run_commands() except DistutilsFileError: self.fail("failed package_data when data dir includes a dir") def test_dont_write_bytecode(self, caplog): # makes sure byte_compile is not used dist = self.create_dist()[1] cmd = build_py(dist) cmd.compile = True cmd.optimize = 1 old_dont_write_bytecode = sys.dont_write_bytecode sys.dont_write_bytecode = True try: cmd.byte_compile([]) finally: sys.dont_write_bytecode = old_dont_write_bytecode assert 'byte-compiling is disabled' in caplog.records[0].message def test_namespace_package_does_not_warn(self, caplog): """ Originally distutils implementation did not account for PEP 420 and included warns for package directories that did not contain ``__init__.py`` files. After the acceptance of PEP 420, these warnings don't make more sense so we want to ensure there are not displayed to not confuse the users. """ # Create a fake project structure with a package namespace: tmp = self.mkdtemp() jaraco.path.build({'ns': {'pkg': {'module.py': ''}}}, tmp) os.chdir(tmp) # Configure the package: attrs = { "name": "ns.pkg", "packages": ["ns", "ns.pkg"], "script_name": "setup.py", } dist = Distribution(attrs) # Run code paths that would trigger the trap: cmd = dist.get_command_obj("build_py") cmd.finalize_options() modules = cmd.find_all_modules() assert len(modules) == 1 module_path = modules[0][-1] assert module_path.replace(os.sep, "/") == "ns/pkg/module.py" cmd.run() assert not any( "package init file" in msg and "not found" in msg for msg in caplog.messages ) PK ,�Z�ED tests/support.pynu �[��� """Support code for distutils test cases.""" import itertools import os import pathlib import shutil import sys import sysconfig import tempfile from distutils.core import Distribution import pytest from more_itertools import always_iterable @pytest.mark.usefixtures('distutils_managed_tempdir') class TempdirManager: """ Mix-in class that handles temporary directories for test cases. """ def mkdtemp(self): """Create a temporary directory that will be cleaned up. Returns the path of the directory. """ d = tempfile.mkdtemp() self.tempdirs.append(d) return d def write_file(self, path, content='xxx'): """Writes a file in the given path. path can be a string or a sequence. """ pathlib.Path(*always_iterable(path)).write_text(content, encoding='utf-8') def create_dist(self, pkg_name='foo', **kw): """Will generate a test environment. This function creates: - a Distribution instance using keywords - a temporary directory with a package structure It returns the package directory and the distribution instance. """ tmp_dir = self.mkdtemp() pkg_dir = os.path.join(tmp_dir, pkg_name) os.mkdir(pkg_dir) dist = Distribution(attrs=kw) return pkg_dir, dist class DummyCommand: """Class to store options for retrieval via set_undefined_options().""" def __init__(self, **kwargs): vars(self).update(kwargs) def ensure_finalized(self): pass def copy_xxmodule_c(directory): """Helper for tests that need the xxmodule.c source file. Example use: def test_compile(self): copy_xxmodule_c(self.tmpdir) self.assertIn('xxmodule.c', os.listdir(self.tmpdir)) If the source file can be found, it will be copied to *directory*. If not, the test will be skipped. Errors during copy are not caught. """ shutil.copy(_get_xxmodule_path(), os.path.join(directory, 'xxmodule.c')) def _get_xxmodule_path(): source_name = 'xxmodule.c' if sys.version_info > (3, 9) else 'xxmodule-3.8.c' return os.path.join(os.path.dirname(__file__), source_name) def fixup_build_ext(cmd): """Function needed to make build_ext tests pass. When Python was built with --enable-shared on Unix, -L. is not enough to find libpython<blah>.so, because regrtest runs in a tempdir, not in the source directory where the .so lives. When Python was built with in debug mode on Windows, build_ext commands need their debug attribute set, and it is not done automatically for some reason. This function handles both of these things. Example use: cmd = build_ext(dist) support.fixup_build_ext(cmd) cmd.ensure_finalized() Unlike most other Unix platforms, Mac OS X embeds absolute paths to shared libraries into executables, so the fixup is not needed there. """ if os.name == 'nt': cmd.debug = sys.executable.endswith('_d.exe') elif sysconfig.get_config_var('Py_ENABLE_SHARED'): # To further add to the shared builds fun on Unix, we can't just add # library_dirs to the Extension() instance because that doesn't get # plumbed through to the final compiler command. runshared = sysconfig.get_config_var('RUNSHARED') if runshared is None: cmd.library_dirs = ['.'] else: if sys.platform == 'darwin': cmd.library_dirs = [] else: name, equals, value = runshared.partition('=') cmd.library_dirs = [d for d in value.split(os.pathsep) if d] def combine_markers(cls): """ pytest will honor markers as found on the class, but when markers are on multiple subclasses, only one appears. Use this decorator to combine those markers. """ cls.pytestmark = [ mark for base in itertools.chain([cls], cls.__bases__) for mark in getattr(base, 'pytestmark', []) ] return cls PK ,�Z_�.� � tests/test_core.pynu �[��� """Tests for distutils.core.""" import distutils.core import io import os import sys from distutils.dist import Distribution import pytest # setup script that uses __file__ setup_using___file__ = """\ __file__ from distutils.core import setup setup() """ setup_prints_cwd = """\ import os print(os.getcwd()) from distutils.core import setup setup() """ setup_does_nothing = """\ from distutils.core import setup setup() """ setup_defines_subclass = """\ from distutils.core import setup from distutils.command.install import install as _install class install(_install): sub_commands = _install.sub_commands + ['cmd'] setup(cmdclass={'install': install}) """ setup_within_if_main = """\ from distutils.core import setup def main(): return setup(name="setup_within_if_main") if __name__ == "__main__": main() """ @pytest.fixture(autouse=True) def save_stdout(monkeypatch): monkeypatch.setattr(sys, 'stdout', sys.stdout) @pytest.fixture def temp_file(tmp_path): return tmp_path / 'file' @pytest.mark.usefixtures('save_env') @pytest.mark.usefixtures('save_argv') class TestCore: def test_run_setup_provides_file(self, temp_file): # Make sure the script can use __file__; if that's missing, the test # setup.py script will raise NameError. temp_file.write_text(setup_using___file__, encoding='utf-8') distutils.core.run_setup(temp_file) def test_run_setup_preserves_sys_argv(self, temp_file): # Make sure run_setup does not clobber sys.argv argv_copy = sys.argv.copy() temp_file.write_text(setup_does_nothing, encoding='utf-8') distutils.core.run_setup(temp_file) assert sys.argv == argv_copy def test_run_setup_defines_subclass(self, temp_file): # Make sure the script can use __file__; if that's missing, the test # setup.py script will raise NameError. temp_file.write_text(setup_defines_subclass, encoding='utf-8') dist = distutils.core.run_setup(temp_file) install = dist.get_command_obj('install') assert 'cmd' in install.sub_commands def test_run_setup_uses_current_dir(self, tmp_path): """ Test that the setup script is run with the current directory as its own current directory. """ sys.stdout = io.StringIO() cwd = os.getcwd() # Create a directory and write the setup.py file there: setup_py = tmp_path / 'setup.py' setup_py.write_text(setup_prints_cwd, encoding='utf-8') distutils.core.run_setup(setup_py) output = sys.stdout.getvalue() if output.endswith("\n"): output = output[:-1] assert cwd == output def test_run_setup_within_if_main(self, temp_file): temp_file.write_text(setup_within_if_main, encoding='utf-8') dist = distutils.core.run_setup(temp_file, stop_after="config") assert isinstance(dist, Distribution) assert dist.get_name() == "setup_within_if_main" def test_run_commands(self, temp_file): sys.argv = ['setup.py', 'build'] temp_file.write_text(setup_within_if_main, encoding='utf-8') dist = distutils.core.run_setup(temp_file, stop_after="commandline") assert 'build' not in dist.have_run distutils.core.run_commands(dist) assert 'build' in dist.have_run def test_debug_mode(self, capsys, monkeypatch): # this covers the code called when DEBUG is set sys.argv = ['setup.py', '--name'] distutils.core.setup(name='bar') assert capsys.readouterr().out == 'bar\n' monkeypatch.setattr(distutils.core, 'DEBUG', True) distutils.core.setup(name='bar') wanted = "options (after parsing config files):\n" assert capsys.readouterr().out.startswith(wanted) PK ,�Z�2� � tests/test_text_file.pynu �[��� """Tests for distutils.text_file.""" from distutils.tests import support from distutils.text_file import TextFile import jaraco.path import path TEST_DATA = """# test file line 3 \\ # intervening comment continues on next line """ class TestTextFile(support.TempdirManager): def test_class(self): # old tests moved from text_file.__main__ # so they are really called by the buildbots # result 1: no fancy options result1 = [ '# test file\n', '\n', 'line 3 \\\n', '# intervening comment\n', ' continues on next line\n', ] # result 2: just strip comments result2 = ["\n", "line 3 \\\n", " continues on next line\n"] # result 3: just strip blank lines result3 = [ "# test file\n", "line 3 \\\n", "# intervening comment\n", " continues on next line\n", ] # result 4: default, strip comments, blank lines, # and trailing whitespace result4 = ["line 3 \\", " continues on next line"] # result 5: strip comments and blanks, plus join lines (but don't # "collapse" joined lines result5 = ["line 3 continues on next line"] # result 6: strip comments and blanks, plus join lines (and # "collapse" joined lines result6 = ["line 3 continues on next line"] def test_input(count, description, file, expected_result): result = file.readlines() assert result == expected_result tmp_path = path.Path(self.mkdtemp()) filename = tmp_path / 'test.txt' jaraco.path.build({filename.name: TEST_DATA}, tmp_path) in_file = TextFile( filename, strip_comments=False, skip_blanks=False, lstrip_ws=False, rstrip_ws=False, ) try: test_input(1, "no processing", in_file, result1) finally: in_file.close() in_file = TextFile( filename, strip_comments=True, skip_blanks=False, lstrip_ws=False, rstrip_ws=False, ) try: test_input(2, "strip comments", in_file, result2) finally: in_file.close() in_file = TextFile( filename, strip_comments=False, skip_blanks=True, lstrip_ws=False, rstrip_ws=False, ) try: test_input(3, "strip blanks", in_file, result3) finally: in_file.close() in_file = TextFile(filename) try: test_input(4, "default processing", in_file, result4) finally: in_file.close() in_file = TextFile( filename, strip_comments=True, skip_blanks=True, join_lines=True, rstrip_ws=True, ) try: test_input(5, "join lines without collapsing", in_file, result5) finally: in_file.close() in_file = TextFile( filename, strip_comments=True, skip_blanks=True, join_lines=True, rstrip_ws=True, collapse_join=True, ) try: test_input(6, "join lines with collapsing", in_file, result6) finally: in_file.close() PK ,�Z#��K@ @ tests/test_build_scripts.pynu �[��� """Tests for distutils.command.build_scripts.""" import os import textwrap from distutils import sysconfig from distutils.command.build_scripts import build_scripts from distutils.core import Distribution from distutils.tests import support import jaraco.path class TestBuildScripts(support.TempdirManager): def test_default_settings(self): cmd = self.get_build_scripts_cmd("/foo/bar", []) assert not cmd.force assert cmd.build_dir is None cmd.finalize_options() assert cmd.force assert cmd.build_dir == "/foo/bar" def test_build(self): source = self.mkdtemp() target = self.mkdtemp() expected = self.write_sample_scripts(source) cmd = self.get_build_scripts_cmd( target, [os.path.join(source, fn) for fn in expected] ) cmd.finalize_options() cmd.run() built = os.listdir(target) for name in expected: assert name in built def get_build_scripts_cmd(self, target, scripts): import sys dist = Distribution() dist.scripts = scripts dist.command_obj["build"] = support.DummyCommand( build_scripts=target, force=True, executable=sys.executable ) return build_scripts(dist) @staticmethod def write_sample_scripts(dir): spec = { 'script1.py': textwrap.dedent(""" #! /usr/bin/env python2.3 # bogus script w/ Python sh-bang pass """).lstrip(), 'script2.py': textwrap.dedent(""" #!/usr/bin/python # bogus script w/ Python sh-bang pass """).lstrip(), 'shell.sh': textwrap.dedent(""" #!/bin/sh # bogus shell script w/ sh-bang exit 0 """).lstrip(), } jaraco.path.build(spec, dir) return list(spec) def test_version_int(self): source = self.mkdtemp() target = self.mkdtemp() expected = self.write_sample_scripts(source) cmd = self.get_build_scripts_cmd( target, [os.path.join(source, fn) for fn in expected] ) cmd.finalize_options() # https://bugs.python.org/issue4524 # # On linux-g++-32 with command line `./configure --enable-ipv6 # --with-suffix=3`, python is compiled okay but the build scripts # failed when writing the name of the executable old = sysconfig.get_config_vars().get('VERSION') sysconfig._config_vars['VERSION'] = 4 try: cmd.run() finally: if old is not None: sysconfig._config_vars['VERSION'] = old built = os.listdir(target) for name in expected: assert name in built PK ,�Zl�+(X X tests/test_build_ext.pynu �[��� import contextlib import glob import importlib import os.path import platform import re import shutil import site import subprocess import sys import tempfile import textwrap import time from distutils import sysconfig from distutils.command.build_ext import build_ext from distutils.core import Distribution from distutils.errors import ( CompileError, DistutilsPlatformError, DistutilsSetupError, UnknownFileError, ) from distutils.extension import Extension from distutils.tests import missing_compiler_executable from distutils.tests.support import TempdirManager, copy_xxmodule_c, fixup_build_ext from io import StringIO import jaraco.path import path import pytest from test import support from .compat import py39 as import_helper @pytest.fixture() def user_site_dir(request): self = request.instance self.tmp_dir = self.mkdtemp() self.tmp_path = path.Path(self.tmp_dir) from distutils.command import build_ext orig_user_base = site.USER_BASE site.USER_BASE = self.mkdtemp() build_ext.USER_BASE = site.USER_BASE # bpo-30132: On Windows, a .pdb file may be created in the current # working directory. Create a temporary working directory to cleanup # everything at the end of the test. with self.tmp_path: yield site.USER_BASE = orig_user_base build_ext.USER_BASE = orig_user_base if sys.platform == 'cygwin': time.sleep(1) @contextlib.contextmanager def safe_extension_import(name, path): with import_helper.CleanImport(name): with extension_redirect(name, path) as new_path: with import_helper.DirsOnSysPath(new_path): yield @contextlib.contextmanager def extension_redirect(mod, path): """ Tests will fail to tear down an extension module if it's been imported. Before importing, copy the file to a temporary directory that won't be cleaned up. Yield the new path. """ if platform.system() != "Windows" and sys.platform != "cygwin": yield path return with import_helper.DirsOnSysPath(path): spec = importlib.util.find_spec(mod) filename = os.path.basename(spec.origin) trash_dir = tempfile.mkdtemp(prefix='deleteme') dest = os.path.join(trash_dir, os.path.basename(filename)) shutil.copy(spec.origin, dest) yield trash_dir # TODO: can the file be scheduled for deletion? @pytest.mark.usefixtures('user_site_dir') class TestBuildExt(TempdirManager): def build_ext(self, *args, **kwargs): return build_ext(*args, **kwargs) @pytest.mark.parametrize("copy_so", [False]) def test_build_ext(self, copy_so): missing_compiler_executable() copy_xxmodule_c(self.tmp_dir) xx_c = os.path.join(self.tmp_dir, 'xxmodule.c') xx_ext = Extension('xx', [xx_c]) if sys.platform != "win32": if not copy_so: xx_ext = Extension( 'xx', [xx_c], library_dirs=['/usr/lib'], libraries=['z'], runtime_library_dirs=['/usr/lib'], ) elif sys.platform == 'linux': libz_so = { os.path.realpath(name) for name in glob.iglob('/usr/lib*/libz.so*') } libz_so = sorted(libz_so, key=lambda lib_path: len(lib_path)) shutil.copyfile(libz_so[-1], '/tmp/libxx_z.so') xx_ext = Extension( 'xx', [xx_c], library_dirs=['/tmp'], libraries=['xx_z'], runtime_library_dirs=['/tmp'], ) dist = Distribution({'name': 'xx', 'ext_modules': [xx_ext]}) dist.package_dir = self.tmp_dir cmd = self.build_ext(dist) fixup_build_ext(cmd) cmd.build_lib = self.tmp_dir cmd.build_temp = self.tmp_dir old_stdout = sys.stdout if not support.verbose: # silence compiler output sys.stdout = StringIO() try: cmd.ensure_finalized() cmd.run() finally: sys.stdout = old_stdout with safe_extension_import('xx', self.tmp_dir): self._test_xx(copy_so) if sys.platform == 'linux' and copy_so: os.unlink('/tmp/libxx_z.so') @staticmethod def _test_xx(copy_so): import xx # type: ignore[import-not-found] # Module generated for tests for attr in ('error', 'foo', 'new', 'roj'): assert hasattr(xx, attr) assert xx.foo(2, 5) == 7 assert xx.foo(13, 15) == 28 assert xx.new().demo() is None if support.HAVE_DOCSTRINGS: doc = 'This is a template module just for instruction.' assert xx.__doc__ == doc assert isinstance(xx.Null(), xx.Null) assert isinstance(xx.Str(), xx.Str) if sys.platform == 'linux': so_headers = subprocess.check_output( ["readelf", "-d", xx.__file__], universal_newlines=True ) import pprint pprint.pprint(so_headers) rpaths = [ rpath for line in so_headers.split("\n") if "RPATH" in line or "RUNPATH" in line for rpath in line.split()[2][1:-1].split(":") ] if not copy_so: pprint.pprint(rpaths) # Linked against a library in /usr/lib{,64} assert "/usr/lib" not in rpaths and "/usr/lib64" not in rpaths else: # Linked against a library in /tmp assert "/tmp" in rpaths # The import is the real test here def test_solaris_enable_shared(self): dist = Distribution({'name': 'xx'}) cmd = self.build_ext(dist) old = sys.platform sys.platform = 'sunos' # fooling finalize_options from distutils.sysconfig import _config_vars old_var = _config_vars.get('Py_ENABLE_SHARED') _config_vars['Py_ENABLE_SHARED'] = True try: cmd.ensure_finalized() finally: sys.platform = old if old_var is None: del _config_vars['Py_ENABLE_SHARED'] else: _config_vars['Py_ENABLE_SHARED'] = old_var # make sure we get some library dirs under solaris assert len(cmd.library_dirs) > 0 def test_user_site(self): import site dist = Distribution({'name': 'xx'}) cmd = self.build_ext(dist) # making sure the user option is there options = [name for name, short, label in cmd.user_options] assert 'user' in options # setting a value cmd.user = True # setting user based lib and include lib = os.path.join(site.USER_BASE, 'lib') incl = os.path.join(site.USER_BASE, 'include') os.mkdir(lib) os.mkdir(incl) # let's run finalize cmd.ensure_finalized() # see if include_dirs and library_dirs # were set assert lib in cmd.library_dirs assert lib in cmd.rpath assert incl in cmd.include_dirs def test_optional_extension(self): # this extension will fail, but let's ignore this failure # with the optional argument. modules = [Extension('foo', ['xxx'], optional=False)] dist = Distribution({'name': 'xx', 'ext_modules': modules}) cmd = self.build_ext(dist) cmd.ensure_finalized() with pytest.raises((UnknownFileError, CompileError)): cmd.run() # should raise an error modules = [Extension('foo', ['xxx'], optional=True)] dist = Distribution({'name': 'xx', 'ext_modules': modules}) cmd = self.build_ext(dist) cmd.ensure_finalized() cmd.run() # should pass def test_finalize_options(self): # Make sure Python's include directories (for Python.h, pyconfig.h, # etc.) are in the include search path. modules = [Extension('foo', ['xxx'], optional=False)] dist = Distribution({'name': 'xx', 'ext_modules': modules}) cmd = self.build_ext(dist) cmd.finalize_options() py_include = sysconfig.get_python_inc() for p in py_include.split(os.path.pathsep): assert p in cmd.include_dirs plat_py_include = sysconfig.get_python_inc(plat_specific=True) for p in plat_py_include.split(os.path.pathsep): assert p in cmd.include_dirs # make sure cmd.libraries is turned into a list # if it's a string cmd = self.build_ext(dist) cmd.libraries = 'my_lib, other_lib lastlib' cmd.finalize_options() assert cmd.libraries == ['my_lib', 'other_lib', 'lastlib'] # make sure cmd.library_dirs is turned into a list # if it's a string cmd = self.build_ext(dist) cmd.library_dirs = f'my_lib_dir{os.pathsep}other_lib_dir' cmd.finalize_options() assert 'my_lib_dir' in cmd.library_dirs assert 'other_lib_dir' in cmd.library_dirs # make sure rpath is turned into a list # if it's a string cmd = self.build_ext(dist) cmd.rpath = f'one{os.pathsep}two' cmd.finalize_options() assert cmd.rpath == ['one', 'two'] # make sure cmd.link_objects is turned into a list # if it's a string cmd = build_ext(dist) cmd.link_objects = 'one two,three' cmd.finalize_options() assert cmd.link_objects == ['one', 'two', 'three'] # XXX more tests to perform for win32 # make sure define is turned into 2-tuples # strings if they are ','-separated strings cmd = self.build_ext(dist) cmd.define = 'one,two' cmd.finalize_options() assert cmd.define == [('one', '1'), ('two', '1')] # make sure undef is turned into a list of # strings if they are ','-separated strings cmd = self.build_ext(dist) cmd.undef = 'one,two' cmd.finalize_options() assert cmd.undef == ['one', 'two'] # make sure swig_opts is turned into a list cmd = self.build_ext(dist) cmd.swig_opts = None cmd.finalize_options() assert cmd.swig_opts == [] cmd = self.build_ext(dist) cmd.swig_opts = '1 2' cmd.finalize_options() assert cmd.swig_opts == ['1', '2'] def test_check_extensions_list(self): dist = Distribution() cmd = self.build_ext(dist) cmd.finalize_options() # 'extensions' option must be a list of Extension instances with pytest.raises(DistutilsSetupError): cmd.check_extensions_list('foo') # each element of 'ext_modules' option must be an # Extension instance or 2-tuple exts = [('bar', 'foo', 'bar'), 'foo'] with pytest.raises(DistutilsSetupError): cmd.check_extensions_list(exts) # first element of each tuple in 'ext_modules' # must be the extension name (a string) and match # a python dotted-separated name exts = [('foo-bar', '')] with pytest.raises(DistutilsSetupError): cmd.check_extensions_list(exts) # second element of each tuple in 'ext_modules' # must be a dictionary (build info) exts = [('foo.bar', '')] with pytest.raises(DistutilsSetupError): cmd.check_extensions_list(exts) # ok this one should pass exts = [('foo.bar', {'sources': [''], 'libraries': 'foo', 'some': 'bar'})] cmd.check_extensions_list(exts) ext = exts[0] assert isinstance(ext, Extension) # check_extensions_list adds in ext the values passed # when they are in ('include_dirs', 'library_dirs', 'libraries' # 'extra_objects', 'extra_compile_args', 'extra_link_args') assert ext.libraries == 'foo' assert not hasattr(ext, 'some') # 'macros' element of build info dict must be 1- or 2-tuple exts = [ ( 'foo.bar', { 'sources': [''], 'libraries': 'foo', 'some': 'bar', 'macros': [('1', '2', '3'), 'foo'], }, ) ] with pytest.raises(DistutilsSetupError): cmd.check_extensions_list(exts) exts[0][1]['macros'] = [('1', '2'), ('3',)] cmd.check_extensions_list(exts) assert exts[0].undef_macros == ['3'] assert exts[0].define_macros == [('1', '2')] def test_get_source_files(self): modules = [Extension('foo', ['xxx'], optional=False)] dist = Distribution({'name': 'xx', 'ext_modules': modules}) cmd = self.build_ext(dist) cmd.ensure_finalized() assert cmd.get_source_files() == ['xxx'] def test_unicode_module_names(self): modules = [ Extension('foo', ['aaa'], optional=False), Extension('föö', ['uuu'], optional=False), ] dist = Distribution({'name': 'xx', 'ext_modules': modules}) cmd = self.build_ext(dist) cmd.ensure_finalized() assert re.search(r'foo(_d)?\..*', cmd.get_ext_filename(modules[0].name)) assert re.search(r'föö(_d)?\..*', cmd.get_ext_filename(modules[1].name)) assert cmd.get_export_symbols(modules[0]) == ['PyInit_foo'] assert cmd.get_export_symbols(modules[1]) == ['PyInitU_f_1gaa'] def test_export_symbols__init__(self): # https://github.com/python/cpython/issues/80074 # https://github.com/pypa/setuptools/issues/4826 modules = [ Extension('foo.__init__', ['aaa']), Extension('föö.__init__', ['uuu']), ] dist = Distribution({'name': 'xx', 'ext_modules': modules}) cmd = self.build_ext(dist) cmd.ensure_finalized() assert cmd.get_export_symbols(modules[0]) == ['PyInit_foo'] assert cmd.get_export_symbols(modules[1]) == ['PyInitU_f_1gaa'] def test_compiler_option(self): # cmd.compiler is an option and # should not be overridden by a compiler instance # when the command is run dist = Distribution() cmd = self.build_ext(dist) cmd.compiler = 'unix' cmd.ensure_finalized() cmd.run() assert cmd.compiler == 'unix' def test_get_outputs(self): missing_compiler_executable() tmp_dir = self.mkdtemp() c_file = os.path.join(tmp_dir, 'foo.c') self.write_file(c_file, 'void PyInit_foo(void) {}\n') ext = Extension('foo', [c_file], optional=False) dist = Distribution({'name': 'xx', 'ext_modules': [ext]}) cmd = self.build_ext(dist) fixup_build_ext(cmd) cmd.ensure_finalized() assert len(cmd.get_outputs()) == 1 cmd.build_lib = os.path.join(self.tmp_dir, 'build') cmd.build_temp = os.path.join(self.tmp_dir, 'tempt') # issue #5977 : distutils build_ext.get_outputs # returns wrong result with --inplace other_tmp_dir = os.path.realpath(self.mkdtemp()) old_wd = os.getcwd() os.chdir(other_tmp_dir) try: cmd.inplace = True cmd.run() so_file = cmd.get_outputs()[0] finally: os.chdir(old_wd) assert os.path.exists(so_file) ext_suffix = sysconfig.get_config_var('EXT_SUFFIX') assert so_file.endswith(ext_suffix) so_dir = os.path.dirname(so_file) assert so_dir == other_tmp_dir cmd.inplace = False cmd.compiler = None cmd.run() so_file = cmd.get_outputs()[0] assert os.path.exists(so_file) assert so_file.endswith(ext_suffix) so_dir = os.path.dirname(so_file) assert so_dir == cmd.build_lib # inplace = False, cmd.package = 'bar' build_py = cmd.get_finalized_command('build_py') build_py.package_dir = {'': 'bar'} path = cmd.get_ext_fullpath('foo') # checking that the last directory is the build_dir path = os.path.split(path)[0] assert path == cmd.build_lib # inplace = True, cmd.package = 'bar' cmd.inplace = True other_tmp_dir = os.path.realpath(self.mkdtemp()) old_wd = os.getcwd() os.chdir(other_tmp_dir) try: path = cmd.get_ext_fullpath('foo') finally: os.chdir(old_wd) # checking that the last directory is bar path = os.path.split(path)[0] lastdir = os.path.split(path)[-1] assert lastdir == 'bar' def test_ext_fullpath(self): ext = sysconfig.get_config_var('EXT_SUFFIX') # building lxml.etree inplace # etree_c = os.path.join(self.tmp_dir, 'lxml.etree.c') # etree_ext = Extension('lxml.etree', [etree_c]) # dist = Distribution({'name': 'lxml', 'ext_modules': [etree_ext]}) dist = Distribution() cmd = self.build_ext(dist) cmd.inplace = True cmd.distribution.package_dir = {'': 'src'} cmd.distribution.packages = ['lxml', 'lxml.html'] curdir = os.getcwd() wanted = os.path.join(curdir, 'src', 'lxml', 'etree' + ext) path = cmd.get_ext_fullpath('lxml.etree') assert wanted == path # building lxml.etree not inplace cmd.inplace = False cmd.build_lib = os.path.join(curdir, 'tmpdir') wanted = os.path.join(curdir, 'tmpdir', 'lxml', 'etree' + ext) path = cmd.get_ext_fullpath('lxml.etree') assert wanted == path # building twisted.runner.portmap not inplace build_py = cmd.get_finalized_command('build_py') build_py.package_dir = {} cmd.distribution.packages = ['twisted', 'twisted.runner.portmap'] path = cmd.get_ext_fullpath('twisted.runner.portmap') wanted = os.path.join(curdir, 'tmpdir', 'twisted', 'runner', 'portmap' + ext) assert wanted == path # building twisted.runner.portmap inplace cmd.inplace = True path = cmd.get_ext_fullpath('twisted.runner.portmap') wanted = os.path.join(curdir, 'twisted', 'runner', 'portmap' + ext) assert wanted == path @pytest.mark.skipif('platform.system() != "Darwin"') @pytest.mark.usefixtures('save_env') def test_deployment_target_default(self): # Issue 9516: Test that, in the absence of the environment variable, # an extension module is compiled with the same deployment target as # the interpreter. self._try_compile_deployment_target('==', None) @pytest.mark.skipif('platform.system() != "Darwin"') @pytest.mark.usefixtures('save_env') def test_deployment_target_too_low(self): # Issue 9516: Test that an extension module is not allowed to be # compiled with a deployment target less than that of the interpreter. with pytest.raises(DistutilsPlatformError): self._try_compile_deployment_target('>', '10.1') @pytest.mark.skipif('platform.system() != "Darwin"') @pytest.mark.usefixtures('save_env') def test_deployment_target_higher_ok(self): # pragma: no cover # Issue 9516: Test that an extension module can be compiled with a # deployment target higher than that of the interpreter: the ext # module may depend on some newer OS feature. deptarget = sysconfig.get_config_var('MACOSX_DEPLOYMENT_TARGET') if deptarget: # increment the minor version number (i.e. 10.6 -> 10.7) deptarget = [int(x) for x in deptarget.split('.')] deptarget[-1] += 1 deptarget = '.'.join(str(i) for i in deptarget) self._try_compile_deployment_target('<', deptarget) def _try_compile_deployment_target(self, operator, target): # pragma: no cover if target is None: if os.environ.get('MACOSX_DEPLOYMENT_TARGET'): del os.environ['MACOSX_DEPLOYMENT_TARGET'] else: os.environ['MACOSX_DEPLOYMENT_TARGET'] = target jaraco.path.build( { 'deptargetmodule.c': textwrap.dedent(f"""\ #include <AvailabilityMacros.h> int dummy; #if TARGET {operator} MAC_OS_X_VERSION_MIN_REQUIRED #else #error "Unexpected target" #endif """), }, self.tmp_path, ) # get the deployment target that the interpreter was built with target = sysconfig.get_config_var('MACOSX_DEPLOYMENT_TARGET') target = tuple(map(int, target.split('.')[0:2])) # format the target value as defined in the Apple # Availability Macros. We can't use the macro names since # at least one value we test with will not exist yet. if target[:2] < (10, 10): # for 10.1 through 10.9.x -> "10n0" tmpl = '{:02}{:01}0' else: # for 10.10 and beyond -> "10nn00" if len(target) >= 2: tmpl = '{:02}{:02}00' else: # 11 and later can have no minor version (11 instead of 11.0) tmpl = '{:02}0000' target = tmpl.format(*target) deptarget_ext = Extension( 'deptarget', [self.tmp_path / 'deptargetmodule.c'], extra_compile_args=[f'-DTARGET={target}'], ) dist = Distribution({'name': 'deptarget', 'ext_modules': [deptarget_ext]}) dist.package_dir = self.tmp_dir cmd = self.build_ext(dist) cmd.build_lib = self.tmp_dir cmd.build_temp = self.tmp_dir try: old_stdout = sys.stdout if not support.verbose: # silence compiler output sys.stdout = StringIO() try: cmd.ensure_finalized() cmd.run() finally: sys.stdout = old_stdout except CompileError: self.fail("Wrong deployment target during compilation") class TestParallelBuildExt(TestBuildExt): def build_ext(self, *args, **kwargs): build_ext = super().build_ext(*args, **kwargs) build_ext.parallel = True return build_ext PK ,�Z^��]; ; 2 tests/__pycache__/test_install_lib.cpython-310.pycnu �[��� o �h � @ s| d Z ddlZddlZddlZddlmZ ddlmZ ddl m Z ddlmZ ddl Z eje j�d�G dd � d ej���ZdS ) z)Tests for distutils.command.install_data.� N)�install_lib)�DistutilsOptionError)� Extension)�support�save_envc @ s@ e Zd Zdd� Zej�d�dd� �Zdd� Zdd � Z d d� Z dS ) �TestInstallLibc C s� | � � d }t|�}|�� |jdksJ �|jdksJ �d|_t�t�� |�� W d � n1 s3w Y d|_t�t�� |�� W d � n1 sOw Y d|_|�� |jdksbJ �d S )N� r �foo�4�2� )�create_distr �finalize_options�compile�optimize�pytest�raisesr )�self�dist�cmd� r �_/usr/local/CyberCP/lib/python3.10/site-packages/setuptools/_distutils/tests/test_install_lib.py�test_finalize_options s � �z$TestInstallLib.test_finalize_optionszsys.dont_write_bytecodec C s� | � � \}}t�|� t|�}d |_|_tj�|d�}| �|d� |� |g� t jjddd�}t jjd|jd�}tj� |�sAJ �tj� |�sIJ �d S )Nr zfoo.pyz # python file� )�optimization)r �os�chdirr r r �path�join� write_file�byte_compile� importlib�util�cache_from_source�exists)r �project_dirr r �f�pyc_file�pyc_opt_filer r r �test_byte_compile'