|
| 1 | +# gh-91321: Build a basic C++ test extension to check that the Python C API is |
| 2 | +# compatible with C++ and does not emit C++ compiler warnings. |
| 3 | +import os |
| 4 | +import sys |
| 5 | +import unittest |
| 6 | +import warnings |
| 7 | +from test import support |
| 8 | +from test.support import os_helper |
| 9 | + |
| 10 | +with warnings.catch_warnings(): |
| 11 | + warnings.simplefilter('ignore', DeprecationWarning) |
| 12 | + from distutils.core import setup, Extension |
| 13 | + import distutils.sysconfig |
| 14 | + |
| 15 | + |
| 16 | +MS_WINDOWS = (sys.platform == 'win32') |
| 17 | + |
| 18 | + |
| 19 | +SOURCE = support.findfile('_testcppext.cpp') |
| 20 | +if not MS_WINDOWS: |
| 21 | + # C++ compiler flags for GCC and clang |
| 22 | + CPPFLAGS = [ |
| 23 | + # Python currently targets C++11 |
| 24 | + '-std=c++11', |
| 25 | + # gh-91321: The purpose of _testcppext extension is to check that building |
| 26 | + # a C++ extension using the Python C API does not emit C++ compiler |
| 27 | + # warnings |
| 28 | + '-Werror', |
| 29 | + ] |
| 30 | +else: |
| 31 | + # Don't pass any compiler flag to MSVC |
| 32 | + CPPFLAGS = [] |
| 33 | + |
| 34 | + |
| 35 | +class TestCPPExt(unittest.TestCase): |
| 36 | + def build(self): |
| 37 | + cpp_ext = Extension( |
| 38 | + '_testcppext', |
| 39 | + sources=[SOURCE], |
| 40 | + language='c++', |
| 41 | + extra_compile_args=CPPFLAGS) |
| 42 | + |
| 43 | + try: |
| 44 | + try: |
| 45 | + with (support.captured_stdout() as stdout, |
| 46 | + support.swap_attr(sys, 'argv', ['setup.py', 'build_ext'])): |
| 47 | + setup(name="_testcppext", ext_modules=[cpp_ext]) |
| 48 | + return |
| 49 | + except: |
| 50 | + # Show output on error |
| 51 | + print() |
| 52 | + print(stdout.getvalue()) |
| 53 | + raise |
| 54 | + except SystemExit: |
| 55 | + self.fail("Build failed") |
| 56 | + |
| 57 | + # With MSVC, the linker fails with: cannot open file 'python311.lib' |
| 58 | + # https://github.com/python/cpython/pull/32175#issuecomment-1111175897 |
| 59 | + @unittest.skipIf(MS_WINDOWS, 'test fails on Windows') |
| 60 | + def test_build(self): |
| 61 | + # save/restore os.environ |
| 62 | + def restore_env(old_env): |
| 63 | + os.environ.clear() |
| 64 | + os.environ.update(old_env) |
| 65 | + self.addCleanup(restore_env, dict(os.environ)) |
| 66 | + |
| 67 | + def restore_sysconfig_vars(old_config_vars): |
| 68 | + distutils.sysconfig._config_vars.clear() |
| 69 | + distutils.sysconfig._config_vars.update(old_config_vars) |
| 70 | + self.addCleanup(restore_sysconfig_vars, |
| 71 | + dict(distutils.sysconfig._config_vars)) |
| 72 | + |
| 73 | + # Build in a temporary directory |
| 74 | + with os_helper.temp_cwd(): |
| 75 | + self.build() |
| 76 | + |
| 77 | + |
| 78 | +if __name__ == "__main__": |
| 79 | + unittest.main() |
0 commit comments