Skip to content

Commit 6544f99

Browse files
authored
[3.12] pythongh-127906: Backport test_cppext changes from the main branch (python#127915)
1 parent c77bfd7 commit 6544f99

File tree

3 files changed

+99
-42
lines changed

3 files changed

+99
-42
lines changed

Lib/test/test_cppext/__init__.py

Lines changed: 35 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -1,56 +1,64 @@
11
# gh-91321: Build a basic C++ test extension to check that the Python C API is
22
# compatible with C++ and does not emit C++ compiler warnings.
33
import os.path
4+
import shlex
45
import shutil
5-
import sys
6-
import unittest
76
import subprocess
8-
import sysconfig
7+
import unittest
98
from test import support
10-
from test.support import os_helper
119

1210

1311
SOURCE = os.path.join(os.path.dirname(__file__), 'extension.cpp')
1412
SETUP = os.path.join(os.path.dirname(__file__), 'setup.py')
1513

1614

15+
# With MSVC on a debug build, the linker fails with: cannot open file
16+
# 'python311.lib', it should look 'python311_d.lib'.
17+
@unittest.skipIf(support.MS_WINDOWS and support.Py_DEBUG,
18+
'test fails on Windows debug build')
19+
# Building and running an extension in clang sanitizing mode is not
20+
# straightforward
21+
@support.skip_if_sanitizer('test does not work with analyzing builds',
22+
address=True, memory=True, ub=True, thread=True)
23+
# the test uses venv+pip: skip if it's not available
24+
@support.requires_venv_with_pip()
1725
@support.requires_subprocess()
26+
@support.requires_resource('cpu')
1827
class TestCPPExt(unittest.TestCase):
19-
@support.requires_resource('cpu')
20-
def test_build_cpp11(self):
21-
self.check_build(False, '_testcpp11ext')
28+
def test_build(self):
29+
self.check_build('_testcppext')
2230

23-
@support.requires_resource('cpu')
2431
def test_build_cpp03(self):
25-
self.check_build(True, '_testcpp03ext')
32+
self.check_build('_testcpp03ext', std='c++03')
33+
34+
@unittest.skipIf(support.MS_WINDOWS, "MSVC doesn't support /std:c++11")
35+
def test_build_cpp11(self):
36+
self.check_build('_testcpp11ext', std='c++11')
37+
38+
# Only test C++14 on MSVC.
39+
# On s390x RHEL7, GCC 4.8.5 doesn't support C++14.
40+
@unittest.skipIf(not support.MS_WINDOWS, "need Windows")
41+
def test_build_cpp14(self):
42+
self.check_build('_testcpp14ext', std='c++14')
2643

27-
# With MSVC, the linker fails with: cannot open file 'python311.lib'
28-
# https://github.com/python/cpython/pull/32175#issuecomment-1111175897
29-
@unittest.skipIf(support.MS_WINDOWS, 'test fails on Windows')
30-
# Building and running an extension in clang sanitizing mode is not
31-
# straightforward
32-
@unittest.skipIf(
33-
'-fsanitize' in (sysconfig.get_config_var('PY_CFLAGS') or ''),
34-
'test does not work with analyzing builds')
35-
# the test uses venv+pip: skip if it's not available
36-
@support.requires_venv_with_pip()
37-
def check_build(self, std_cpp03, extension_name):
44+
def check_build(self, extension_name, std=None):
3845
venv_dir = 'env'
3946
with support.setup_venv_with_pip_setuptools_wheel(venv_dir) as python_exe:
40-
self._check_build(std_cpp03, extension_name, python_exe)
47+
self._check_build(extension_name, python_exe, std=std)
4148

42-
def _check_build(self, std_cpp03, extension_name, python_exe):
49+
def _check_build(self, extension_name, python_exe, std):
4350
pkg_dir = 'pkg'
4451
os.mkdir(pkg_dir)
4552
shutil.copy(SETUP, os.path.join(pkg_dir, os.path.basename(SETUP)))
4653
shutil.copy(SOURCE, os.path.join(pkg_dir, os.path.basename(SOURCE)))
4754

4855
def run_cmd(operation, cmd):
4956
env = os.environ.copy()
50-
env['CPYTHON_TEST_CPP_STD'] = 'c++03' if std_cpp03 else 'c++11'
57+
if std:
58+
env['CPYTHON_TEST_CPP_STD'] = std
5159
env['CPYTHON_TEST_EXT_NAME'] = extension_name
5260
if support.verbose:
53-
print('Run:', ' '.join(cmd))
61+
print('Run:', ' '.join(map(shlex.quote, cmd)))
5462
subprocess.run(cmd, check=True, env=env)
5563
else:
5664
proc = subprocess.run(cmd,
@@ -59,6 +67,7 @@ def run_cmd(operation, cmd):
5967
stderr=subprocess.STDOUT,
6068
text=True)
6169
if proc.returncode:
70+
print('Run:', ' '.join(map(shlex.quote, cmd)))
6271
print(proc.stdout, end='')
6372
self.fail(
6473
f"{operation} failed with exit code {proc.returncode}")
@@ -67,6 +76,8 @@ def run_cmd(operation, cmd):
6776
cmd = [python_exe, '-X', 'dev',
6877
'-m', 'pip', 'install', '--no-build-isolation',
6978
os.path.abspath(pkg_dir)]
79+
if support.verbose:
80+
cmd.append('-v')
7081
run_cmd('Install', cmd)
7182

7283
# Do a reference run. Until we test that running python

Lib/test/test_cppext/extension.cpp

Lines changed: 9 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -8,10 +8,8 @@
88

99
#include "Python.h"
1010

11-
#if __cplusplus >= 201103
12-
# define NAME _testcpp11ext
13-
#else
14-
# define NAME _testcpp03ext
11+
#ifndef MODULE_NAME
12+
# error "MODULE_NAME macro must be defined"
1513
#endif
1614

1715
#define _STR(NAME) #NAME
@@ -160,7 +158,7 @@ PyType_Slot VirtualPyObject_Slots[] = {
160158
};
161159

162160
PyType_Spec VirtualPyObject_Spec = {
163-
/* .name */ STR(NAME) ".VirtualPyObject",
161+
/* .name */ STR(MODULE_NAME) ".VirtualPyObject",
164162
/* .basicsize */ sizeof(VirtualPyObject),
165163
/* .itemsize */ 0,
166164
/* .flags */ Py_TPFLAGS_DEFAULT,
@@ -227,6 +225,10 @@ _testcppext_exec(PyObject *module)
227225
if (!result) return -1;
228226
Py_DECREF(result);
229227

228+
// test Py_BUILD_ASSERT() and Py_BUILD_ASSERT_EXPR()
229+
Py_BUILD_ASSERT(sizeof(int) == sizeof(unsigned int));
230+
assert(Py_BUILD_ASSERT_EXPR(sizeof(int) == sizeof(unsigned int)) == 0);
231+
230232
return 0;
231233
}
232234

@@ -240,7 +242,7 @@ PyDoc_STRVAR(_testcppext_doc, "C++ test extension.");
240242

241243
static struct PyModuleDef _testcppext_module = {
242244
PyModuleDef_HEAD_INIT, // m_base
243-
STR(NAME), // m_name
245+
STR(MODULE_NAME), // m_name
244246
_testcppext_doc, // m_doc
245247
0, // m_size
246248
_testcppext_methods, // m_methods
@@ -254,7 +256,7 @@ static struct PyModuleDef _testcppext_module = {
254256
#define FUNC_NAME(NAME) _FUNC_NAME(NAME)
255257

256258
PyMODINIT_FUNC
257-
FUNC_NAME(NAME)(void)
259+
FUNC_NAME(MODULE_NAME)(void)
258260
{
259261
return PyModuleDef_Init(&_testcppext_module);
260262
}

Lib/test/test_cppext/setup.py

Lines changed: 55 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,16 @@
11
# gh-91321: Build a basic C++ test extension to check that the Python C API is
22
# compatible with C++ and does not emit C++ compiler warnings.
33
import os
4+
import platform
45
import shlex
5-
import sys
66
import sysconfig
77
from test import support
88

99
from setuptools import setup, Extension
1010

1111

1212
SOURCE = 'extension.cpp'
13+
1314
if not support.MS_WINDOWS:
1415
# C++ compiler flags for GCC and clang
1516
CPPFLAGS = [
@@ -19,34 +20,77 @@
1920
'-Werror',
2021
]
2122
else:
22-
# Don't pass any compiler flag to MSVC
23-
CPPFLAGS = []
23+
# MSVC compiler flags
24+
CPPFLAGS = [
25+
# Display warnings level 1 to 4
26+
'/W4',
27+
# Treat all compiler warnings as compiler errors
28+
'/WX',
29+
]
2430

2531

2632
def main():
2733
cppflags = list(CPPFLAGS)
28-
std = os.environ["CPYTHON_TEST_CPP_STD"]
29-
name = os.environ["CPYTHON_TEST_EXT_NAME"]
34+
std = os.environ.get("CPYTHON_TEST_CPP_STD", "")
35+
module_name = os.environ["CPYTHON_TEST_EXT_NAME"]
3036

31-
cppflags = [*CPPFLAGS, f'-std={std}']
37+
cppflags = list(CPPFLAGS)
38+
cppflags.append(f'-DMODULE_NAME={module_name}')
39+
40+
# Add -std=STD or /std:STD (MSVC) compiler flag
41+
if std:
42+
if support.MS_WINDOWS:
43+
cppflags.append(f'/std:{std}')
44+
else:
45+
cppflags.append(f'-std={std}')
3246

3347
# gh-105776: When "gcc -std=11" is used as the C++ compiler, -std=c11
3448
# option emits a C++ compiler warning. Remove "-std11" option from the
3549
# CC command.
3650
cmd = (sysconfig.get_config_var('CC') or '')
3751
if cmd is not None:
52+
if support.MS_WINDOWS:
53+
std_prefix = '/std'
54+
else:
55+
std_prefix = '-std'
3856
cmd = shlex.split(cmd)
39-
cmd = [arg for arg in cmd if not arg.startswith('-std=')]
57+
cmd = [arg for arg in cmd if not arg.startswith(std_prefix)]
4058
cmd = shlex.join(cmd)
4159
# CC env var overrides sysconfig CC variable in setuptools
4260
os.environ['CC'] = cmd
4361

44-
cpp_ext = Extension(
45-
name,
62+
# On Windows, add PCbuild\amd64\ to include and library directories
63+
include_dirs = []
64+
library_dirs = []
65+
if support.MS_WINDOWS:
66+
srcdir = sysconfig.get_config_var('srcdir')
67+
machine = platform.uname().machine
68+
pcbuild = os.path.join(srcdir, 'PCbuild', machine)
69+
if os.path.exists(pcbuild):
70+
# pyconfig.h is generated in PCbuild\amd64\
71+
include_dirs.append(pcbuild)
72+
# python313.lib is generated in PCbuild\amd64\
73+
library_dirs.append(pcbuild)
74+
print(f"Add PCbuild directory: {pcbuild}")
75+
76+
# Display information to help debugging
77+
for env_name in ('CC', 'CFLAGS', 'CPPFLAGS'):
78+
if env_name in os.environ:
79+
print(f"{env_name} env var: {os.environ[env_name]!r}")
80+
else:
81+
print(f"{env_name} env var: <missing>")
82+
print(f"extra_compile_args: {cppflags!r}")
83+
84+
ext = Extension(
85+
module_name,
4686
sources=[SOURCE],
4787
language='c++',
48-
extra_compile_args=cppflags)
49-
setup(name='internal' + name, version='0.0', ext_modules=[cpp_ext])
88+
extra_compile_args=cppflags,
89+
include_dirs=include_dirs,
90+
library_dirs=library_dirs)
91+
setup(name=f'internal_{module_name}',
92+
version='0.0',
93+
ext_modules=[ext])
5094

5195

5296
if __name__ == "__main__":

0 commit comments

Comments
 (0)