forked from python/cpython
-
Notifications
You must be signed in to change notification settings - Fork 14
/
mingw_smoketests.py
371 lines (318 loc) · 13.7 KB
/
mingw_smoketests.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
#!/usr/bin/env python3
# Copyright 2017 Christoph Reiter
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
"""The goal of this test suite is collect tests for update regressions
and to test msys2 related modifications like for path handling.
Feel free to extend.
"""
import os
import unittest
import sysconfig
if os.environ.get("MSYSTEM", ""):
SEP = "/"
else:
SEP = "\\"
if sysconfig.is_python_build():
os.environ["PYTHONLEGACYWINDOWSDLLLOADING"] = "1"
_UCRT = 'ucrt' in sysconfig.get_platform()
class Tests(unittest.TestCase):
def test_zoneinfo(self):
# https://github.com/msys2-contrib/cpython-mingw/issues/32
import zoneinfo
self.assertTrue(any(os.path.exists(p) for p in zoneinfo.TZPATH))
zoneinfo.ZoneInfo("America/Sao_Paulo")
def test_userdir_path_sep(self):
# Make sure os.path and pathlib use the same path separators
from unittest import mock
from os.path import expanduser
from pathlib import Path
profiles = ["C:\\foo", "C:/foo"]
for profile in profiles:
with mock.patch.dict(os.environ, {"USERPROFILE": profile}):
self.assertEqual(expanduser("~"), os.path.normpath(expanduser("~")))
self.assertEqual(str(Path("~").expanduser()), expanduser("~"))
self.assertEqual(str(Path.home()), expanduser("~"))
# def test_sysconfig_schemes(self):
# # https://github.com/msys2/MINGW-packages/issues/9319
# import sysconfig
# from distutils.dist import Distribution
# from distutils.command.install import install
# names = ['scripts', 'purelib', 'platlib', 'data', 'include']
# for scheme in ["nt", "nt_user"]:
# for name in names:
# c = install(Distribution({"name": "foobar"}))
# c.user = (scheme == "nt_user")
# c.finalize_options()
# if name == "include":
# dist_path = os.path.dirname(getattr(c, "install_" + "headers"))
# else:
# dist_path = getattr(c, "install_" + name)
# sys_path = sysconfig.get_path(name, scheme)
# self.assertEqual(dist_path, sys_path, (scheme, name))
def test_ctypes_find_library(self):
from ctypes.util import find_library
from ctypes import cdll
self.assertTrue(cdll.msvcrt)
if _UCRT:
self.assertIsNone(find_library('c'))
else:
self.assertEqual(find_library('c'), 'msvcrt.dll')
def test_ctypes_dlopen(self):
import ctypes
import sys
self.assertEqual(ctypes.RTLD_GLOBAL, 0)
self.assertEqual(ctypes.RTLD_GLOBAL, ctypes.RTLD_LOCAL)
self.assertFalse(hasattr(sys, 'setdlopenflags'))
self.assertFalse(hasattr(sys, 'getdlopenflags'))
self.assertFalse([n for n in dir(os) if n.startswith("RTLD_")])
def test_time_no_unix_stuff(self):
import time
self.assertFalse([n for n in dir(time) if n.startswith("clock_")])
self.assertFalse([n for n in dir(time) if n.startswith("CLOCK_")])
self.assertFalse([n for n in dir(time) if n.startswith("pthread_")])
self.assertFalse(hasattr(time, 'tzset'))
def test_strftime(self):
import time
with self.assertRaises(ValueError):
time.strftime('%Y', (12345,) + (0,) * 8)
def test_sep(self):
self.assertEqual(os.sep, SEP)
def test_module_file_path(self):
import asyncio
import zlib
self.assertEqual(zlib.__file__, os.path.normpath(zlib.__file__))
self.assertEqual(asyncio.__file__, os.path.normpath(asyncio.__file__))
def test_importlib_frozen_path_sep(self):
import importlib._bootstrap_external
self.assertEqual(importlib._bootstrap_external.path_sep, SEP)
def test_os_commonpath(self):
self.assertEqual(
os.path.commonpath(
[os.path.join("C:", os.sep, "foo", "bar"),
os.path.join("C:", os.sep, "foo")]),
os.path.join("C:", os.sep, "foo"))
def test_pathlib(self):
import pathlib
p = pathlib.Path("foo") / pathlib.Path("foo")
self.assertEqual(str(p), os.path.normpath(p))
def test_modules_import(self):
import sqlite3
import ssl
import ctypes
import curses
def test_c_modules_import(self):
import _decimal
def test_socket_inet_ntop(self):
import socket
self.assertTrue(hasattr(socket, "inet_ntop"))
def test_socket_inet_pton(self):
import socket
self.assertTrue(hasattr(socket, "inet_pton"))
def test_multiprocessing_queue(self):
from multiprocessing import Queue
Queue(0)
#def test_socket_timout_normal_error(self):
# import urllib.request
# from urllib.error import URLError
# try:
# urllib.request.urlopen(
# 'http://localhost', timeout=0.0001).close()
# except URLError:
# pass
def test_threads(self):
from concurrent.futures import ThreadPoolExecutor
with ThreadPoolExecutor(1) as pool:
for res in pool.map(lambda *x: None, range(10000)):
pass
def test_sysconfig(self):
import sysconfig
# This should be able to execute without exceptions
sysconfig.get_config_vars()
def test_sqlite_enable_load_extension(self):
# Make sure --enable-loadable-sqlite-extensions is used
import sqlite3
self.assertTrue(sqlite3.Connection.enable_load_extension)
def test_venv_creation(self):
import tempfile
import venv
import subprocess
import shutil
with tempfile.TemporaryDirectory() as tmp:
builder = venv.EnvBuilder()
builder.create(tmp)
assert os.path.exists(os.path.join(tmp, "bin", "activate"))
assert os.path.exists(os.path.join(tmp, "bin", "python.exe"))
assert os.path.exists(os.path.join(tmp, "bin", "python3.exe"))
subprocess.check_call([shutil.which("bash.exe"), os.path.join(tmp, "bin", "activate")])
# This will not work in in-tree build
if not sysconfig.is_python_build():
op = subprocess.check_output(
[
os.path.join(tmp, "bin", "python.exe"),
"-c",
"print('Hello World')"
],
cwd=tmp,
)
assert op.decode().strip() == "Hello World"
def test_has_mktime(self):
from time import mktime, gmtime
mktime(gmtime())
def test_platform_things(self):
import sys
import sysconfig
import platform
import importlib.machinery
import tempfile
import venv
import subprocess
self.assertEqual(sys.implementation.name, "cpython")
self.assertEqual(sys.platform, "win32")
self.assertTrue(sysconfig.get_platform().startswith("mingw"))
self.assertTrue(sysconfig.get_config_var('SOABI').startswith("cpython-"))
ext_suffix = sysconfig.get_config_var('EXT_SUFFIX')
self.assertTrue(ext_suffix.endswith(".pyd"))
self.assertTrue("mingw" in ext_suffix)
self.assertEqual(sysconfig.get_config_var('SHLIB_SUFFIX'), ".pyd")
ext_suffixes = importlib.machinery.EXTENSION_SUFFIXES
self.assertTrue(ext_suffix in ext_suffixes)
self.assertTrue(".pyd" in ext_suffixes)
if sysconfig.get_platform().startswith('mingw_i686'):
self.assertEqual(sys.winver, ".".join(map(str, sys.version_info[:2])) + '-32')
elif sysconfig.get_platform().startswith('mingw_aarch64'):
self.assertEqual(sys.winver, ".".join(map(str, sys.version_info[:2])) + '-arm64')
elif sysconfig.get_platform().startswith('mingw_armv7'):
self.assertEqual(sys.winver, ".".join(map(str, sys.version_info[:2])) + '-arm32')
else:
self.assertEqual(sys.winver, ".".join(map(str, sys.version_info[:2])))
self.assertEqual(platform.python_implementation(), "CPython")
self.assertEqual(platform.system(), "Windows")
self.assertTrue(isinstance(sys.api_version, int) and sys.api_version > 0)
with tempfile.TemporaryDirectory() as tmp:
builder = venv.EnvBuilder()
builder.create(tmp)
# This will not work in in-tree build
if not sysconfig.is_python_build():
op = subprocess.check_output(
[
os.path.join(tmp, "bin", "python.exe"),
"-c",
"import sysconfig; print(sysconfig.get_config_var('LIBDIR'))"
],
cwd=tmp,
)
self.assertTrue(op.decode().strip().startswith(sys.base_prefix))
def test_sys_getpath(self):
# everything sourced from getpath.py
import sys
def assertNormpath(path):
self.assertEqual(path, os.path.normpath(path))
assertNormpath(sys.executable)
assertNormpath(sys._base_executable)
assertNormpath(sys.prefix)
assertNormpath(sys.base_prefix)
assertNormpath(sys.exec_prefix)
assertNormpath(sys.base_exec_prefix)
assertNormpath(sys.platlibdir)
assertNormpath(sys._stdlib_dir)
for p in sys.path:
assertNormpath(p)
def test_site(self):
import site
self.assertEqual(len(site.getsitepackages()), 1)
def test_c_ext_build(self):
import tempfile
import sys
import subprocess
import textwrap
import venv
from pathlib import Path
with tempfile.TemporaryDirectory() as tmppro:
builder = venv.EnvBuilder(with_pip=True)
builder.create(tmppro)
venv_exe = os.path.join(tmppro, "bin", os.path.basename(sys.executable))
with Path(tmppro, "setup.py").open("w") as f:
f.write(
textwrap.dedent(
"""\
from setuptools import setup, Extension
setup(
name='cwrapper',
version='1.0',
ext_modules=[
Extension(
'cwrapper',
sources=['cwrapper.c']),
],
)
"""
)
)
with Path(tmppro, "cwrapper.c").open("w") as f:
f.write(
textwrap.dedent(
"""\
#include <Python.h>
static PyObject *
helloworld(PyObject *self, PyObject *args)
{
printf("Hello World\\n");
Py_RETURN_NONE;
}
static PyMethodDef
myMethods[] = {
{ "helloworld", helloworld, METH_NOARGS, "Prints Hello World" },
{ NULL, NULL, 0, NULL }
};
static struct PyModuleDef cwrapper = {
PyModuleDef_HEAD_INIT,
"cwrapper",
"Test Module",
-1,
myMethods
};
PyMODINIT_FUNC
PyInit_cwrapper(void)
{
return PyModule_Create(&cwrapper);
}
"""
)
)
subprocess.check_call(
[venv_exe, "-c", "import struct"],
)
subprocess.check_call(
[
venv_exe,
"-m",
"pip",
"install",
tmppro,
],
)
subprocess.check_call(
[venv_exe, "-c", "import cwrapper"],
)
def suite():
return unittest.TestLoader().loadTestsFromName(__name__)
if __name__ == '__main__':
unittest.main(defaultTest='suite')