File: test_setup_helpers.py

package info (click to toggle)
extension-helpers 1.4.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 280 kB
  • sloc: python: 1,082; ansic: 69; makefile: 16
file content (617 lines) | stat: -rw-r--r-- 17,283 bytes parent folder | download
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
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
import importlib
import os
import subprocess
import sys
import uuid
from textwrap import dedent

import pytest

from .._setup_helpers import get_compiler, get_extensions
from . import cleanup_import, run_setup

if sys.version_info >= (3, 11):
    from contextlib import chdir
else:
    from .py311_backports import chdir

extension_helpers_PATH = os.path.abspath(
    os.path.join(os.path.dirname(__file__), "..", "..")
)  # noqa


def teardown_module(module):
    # Remove file generated by test_generate_openmp_enabled_py but
    # somehow needed in test_cython_autoextensions
    tmpfile = "openmp_enabled.py"
    if os.path.exists(tmpfile):
        os.remove(tmpfile)


POSSIBLE_COMPILERS = ["unix", "msvc", "bcpp", "cygwin", "mingw32"]


def test_get_compiler():
    assert get_compiler() in POSSIBLE_COMPILERS


def _extension_test_package(
    tmp_path,
    request=None,
    extension_type="c",
    include_numpy=False,
    include_setup_py=True,
):
    """Creates a simple test package with an extension module."""

    test_pkg = tmp_path / "test_pkg"
    os.makedirs(test_pkg / "helpers_test_package")
    (test_pkg / "helpers_test_package" / "__init__.py").touch()

    # TODO: It might be later worth making this particular test package into a
    # reusable fixture for other build_ext tests

    if extension_type in ("c", "both"):
        # A minimal C extension for testing
        (test_pkg / "helpers_test_package" / "unit01.c").write_text(
            dedent(
                """\
            #include <Python.h>

            static struct PyModuleDef moduledef = {
                PyModuleDef_HEAD_INIT,
                "unit01",
                NULL,
                -1,
                NULL
            };
            PyMODINIT_FUNC
            PyInit_unit01(void) {
                return PyModule_Create(&moduledef);
            }
        """
            )
        )

    if extension_type in ("pyx", "both"):
        # A minimal Cython extension for testing
        (test_pkg / "helpers_test_package" / "unit02.pyx").write_text(
            dedent(
                """\
            print("Hello cruel angel.")
        """
            )
        )

    if extension_type == "c":
        extensions = ["unit01.c"]
    elif extension_type == "pyx":
        extensions = ["unit02.pyx"]
    elif extension_type == "both":
        extensions = ["unit01.c", "unit02.pyx"]

    include_dirs = ["numpy"] if include_numpy else []

    extensions_list = [
        f"Extension('helpers_test_package.{os.path.splitext(extension)[0]}', "
        f"[join('helpers_test_package', '{extension}')], "
        f"{include_dirs=})"
        for extension in extensions
    ]

    (test_pkg / "helpers_test_package" / "setup_package.py").write_text(
        dedent(
            """\
        from setuptools import Extension
        from os.path import join
        def get_extensions():
            return [{}]
    """.format(
                ", ".join(extensions_list)
            )
        )
    )

    if include_setup_py:
        (test_pkg / "setup.py").write_text(
            dedent(
                f"""\
            import sys
            from os.path import join
            from setuptools import setup, find_packages
            sys.path.insert(0, r'{extension_helpers_PATH}')
            from extension_helpers import get_extensions

            setup(
                name='helpers_test_package',
                version='0.1',
                packages=find_packages(),
                ext_modules=get_extensions()
            )
        """
            )
        )

    if "" in sys.path:
        sys.path.remove("")

    sys.path.insert(0, "")

    def finalize():
        cleanup_import("helpers_test_package")

    if request:
        request.addfinalizer(finalize)

    return test_pkg


@pytest.fixture
def extension_test_package(tmp_path, request):
    return _extension_test_package(tmp_path, request, extension_type="both")


@pytest.fixture
def c_extension_test_package(tmp_path, request):
    # Check whether numpy is installed in the test environment
    has_numpy = bool(importlib.util.find_spec("numpy"))
    return _extension_test_package(tmp_path, request, extension_type="c", include_numpy=has_numpy)


@pytest.fixture
def pyx_extension_test_package(tmp_path, request):
    return _extension_test_package(tmp_path, request, extension_type="pyx")


def test_cython_autoextensions(tmp_path):
    """
    Regression test for https://github.com/astropy/astropy-helpers/pull/19

    Ensures that Cython extensions in sub-packages are discovered and built
    only once.
    """

    # Make a simple test package

    test_pkg = tmp_path / "test_pkg"
    os.makedirs(test_pkg / "yoda" / "luke")
    (test_pkg / "yoda" / "__init__.py").touch()
    (test_pkg / "yoda" / "luke" / "__init__.py").touch()
    (test_pkg / "yoda" / "luke" / "dagobah.pyx").write_text("""def testfunc(): pass""")

    # Required, currently, for get_extensions to work
    ext_modules = get_extensions(str(test_pkg))

    assert len(ext_modules) == 2
    assert ext_modules[0].name == "yoda.luke.dagobah"


def test_compiler_module(capsys, c_extension_test_package):
    """
    Test ensuring that the compiler module is built and installed for packages
    that have extension modules.
    """

    test_pkg = c_extension_test_package
    install_temp = test_pkg / "install_temp"
    os.mkdir(install_temp)

    with chdir(test_pkg):
        # This is one of the simplest ways to install just a package into a
        # test directory
        run_setup(
            "setup.py",
            [
                "install",
                "--single-version-externally-managed",
                f"--install-lib={install_temp}",
                "--record={}".format(install_temp / "record.txt"),
            ],
        )

    with chdir(install_temp):
        import helpers_test_package

        # Make sure we imported the helpers_test_package package from the correct place
        dirname = os.path.abspath(os.path.dirname(helpers_test_package.__file__))
        assert dirname == str(install_temp / "helpers_test_package")

        import helpers_test_package.compiler_version

        assert helpers_test_package.compiler_version != "unknown"


@pytest.mark.parametrize("use_extension_helpers", [None, False, True])
@pytest.mark.parametrize("pyproject_use_helpers", [None, False, True])
def test_no_setup_py(tmp_path, use_extension_helpers, pyproject_use_helpers):
    """
    Test that makes sure that extension-helpers can be enabled without a
    setup.py file.
    """

    package_name = "helpers_test_package_" + str(uuid.uuid4()).replace("-", "_")

    test_pkg = tmp_path / "test_pkg"
    os.makedirs(test_pkg / package_name)
    (test_pkg / package_name / "__init__.py").touch()

    simple_c = test_pkg / package_name / "simple.c"

    simple_c.write_text(
        dedent(
            """\
        #include <Python.h>

        static struct PyModuleDef moduledef = {
            PyModuleDef_HEAD_INIT,
            "simple",
            NULL,
            -1,
            NULL
        };
        PyMODINIT_FUNC
        PyInit_simple(void) {
            return PyModule_Create(&moduledef);
        }
    """
        )
    )

    (test_pkg / package_name / "setup_package.py").write_text(
        dedent(
            f"""\
        from setuptools import Extension
        from os.path import join
        def get_extensions():
            return [Extension('{package_name}.simple', [join('{package_name}', 'simple.c')])]
        """
        )
    )

    if use_extension_helpers is None:
        (test_pkg / "setup.cfg").write_text(
            dedent(
                f"""\
            [metadata]
            name = {package_name}
            version = 0.1

            [options]
            packages = find:
        """
            )
        )
    else:
        (test_pkg / "setup.cfg").write_text(
            dedent(
                f"""\
            [metadata]
            name = {package_name}
            version = 0.1

            [options]
            packages = find:

            [extension-helpers]
            use_extension_helpers = {str(use_extension_helpers).lower()}
        """
            )
        )

    if pyproject_use_helpers is None:
        (test_pkg / "pyproject.toml").write_text(
            dedent(
                """\
            [build-system]
            requires = ["setuptools>=43.0.0",
                        "wheel"]
            build-backend = 'setuptools.build_meta'
        """
            )
        )
    else:
        (test_pkg / "pyproject.toml").write_text(
            dedent(
                f"""\
            [build-system]
            requires = ["setuptools>=43.0.0",
                        "wheel"]
            build-backend = 'setuptools.build_meta'

            [tool.extension-helpers]
            use_extension_helpers = {str(pyproject_use_helpers).lower()}
        """
            )
        )

    install_temp = test_pkg / "install_temp"
    os.mkdir(install_temp)

    with chdir(test_pkg):
        # NOTE: we disable build isolation as we need to pick up the current
        # developer version of extension-helpers
        subprocess.call(
            [
                sys.executable,
                "-m",
                "pip",
                "install",
                ".",
                "--no-build-isolation",
                f"--target={install_temp}",
            ]
        )

    if "" in sys.path:
        sys.path.remove("")

    sys.path.insert(0, "")

    with chdir(install_temp):
        importlib.import_module(package_name)

        if use_extension_helpers or (use_extension_helpers is None and pyproject_use_helpers):
            compiler_version_mod = importlib.import_module(package_name + ".compiler_version")
            assert compiler_version_mod.compiler != "unknown"
        else:
            try:
                importlib.import_module(package_name + ".compiler_version")
            except ImportError:
                pass
            else:
                raise AssertionError(package_name + ".compiler_version should not exist")


@pytest.mark.parametrize("pyproject_use_helpers", [None, False, True])
def test_only_pyproject(tmp_path, pyproject_use_helpers):
    """
    Test that makes sure that extension-helpers can be enabled without a
    setup.py and without a setup.cfg file.
    """

    pytest.importorskip("setuptools", minversion="62.0")

    package_name = "helpers_test_package_" + str(uuid.uuid4()).replace("-", "_")

    test_pkg = tmp_path / "test_pkg"
    os.makedirs(test_pkg / package_name)
    (test_pkg / package_name / "__init__.py").touch()
    simple_pyx = test_pkg / package_name / "simple.pyx"
    simple_pyx.write_text(
        dedent(
            """\
        def test():
            pass
    """
        )
    )

    if pyproject_use_helpers is None:
        extension_helpers_option = ""
    else:
        extension_helpers_option = dedent(
            f"""
        [tool.extension-helpers]
        use_extension_helpers = {str(pyproject_use_helpers).lower()}
        """
        )

    buildtime_requirements = ["setuptools>=43.0.0", "wheel", "Cython"]
    (test_pkg / "pyproject.toml").write_text(
        dedent(
            f"""\
            [project]
            name = "{package_name}"
            version = "0.1"

            [tool.setuptools.packages]
            find = {{namespaces = false}}

            [build-system]
            requires = [{', '.join(f'"{_}"' for _ in buildtime_requirements)}]
            build-backend = 'setuptools.build_meta'

            """
        )
        + extension_helpers_option
    )

    install_temp = test_pkg / "install_temp"
    os.mkdir(install_temp)

    with chdir(test_pkg):
        # NOTE: we disable build isolation as we need to pick up the current
        # developer version of extension-helpers
        # In order to do so, we need to ensure that build-time dependencies are
        # installed first
        cmd1 = [
            sys.executable,
            "-m",
            "pip",
            "install",
            *buildtime_requirements,
            f"--target={install_temp}",
        ]
        subprocess.call(cmd1)

        cmd2 = [
            sys.executable,
            "-m",
            "pip",
            "install",
            ".",
            "--no-build-isolation",
            f"--target={install_temp}",
        ]
        subprocess.call(cmd2)

    if "" in sys.path:
        sys.path.remove("")

    sys.path.insert(0, "")

    with chdir(install_temp):
        importlib.import_module(package_name)

        if pyproject_use_helpers:
            compiler_version_mod = importlib.import_module(package_name + ".compiler_version")
            assert compiler_version_mod.compiler != "unknown"
        else:
            try:
                importlib.import_module(package_name + ".compiler_version")
            except ImportError:
                pass
            else:
                raise AssertionError(package_name + ".compiler_version should not exist")


# Tests to make sure that limited API support works correctly


@pytest.mark.skip(reason="Requires Cython >= 3.1")
@pytest.mark.parametrize("config", ("setup.cfg", "pyproject.toml"))
@pytest.mark.parametrize("envvar", (False, True))
@pytest.mark.parametrize("limited_api", (None, "cp310"))
@pytest.mark.parametrize("extension_type", ("c", "pyx", "both"))
def test_limited_api(tmp_path, config, envvar, limited_api, extension_type):

    if sys.version_info < (3, 11):
        pytest.skip(
            "This test requires setuptools>=65.4 which is only available for Python 3.11 and later"
        )

    package = _extension_test_package(
        tmp_path, extension_type=extension_type, include_numpy=True, include_setup_py=False
    )

    if config == "setup.cfg":

        setup_cfg = dedent(
            """\
            [metadata]
            name = helpers_test_package
            version = 0.1

            [options]
            packages = find:

            [extension-helpers]
            use_extension_helpers = true
        """
        )

        if limited_api and not envvar:
            setup_cfg += f"\n[bdist_wheel]\npy_limited_api={limited_api}"
        elif envvar:
            # Make sure if we are using the environment variable that it takes
            # precedence over this setting (this only works for setup.cfg)
            setup_cfg += "\n[bdist_wheel]\npy_limited_api=cp35"

        (package / "setup.cfg").write_text(setup_cfg)

        # Still require a minimal pyproject.toml file if no setup.py file

        (package / "pyproject.toml").write_text(
            dedent(
                """
            [build-system]
            requires = ["setuptools>=43.0.0",
                        "wheel"]
            build-backend = 'setuptools.build_meta'

            [tool.extension-helpers]
            use_extension_helpers = true
        """
            )
        )

    elif config == "pyproject.toml":

        pyproject_toml = dedent(
            """\
            [build-system]
            requires = ["setuptools>=43.0.0",
                        "wheel"]
            build-backend = 'setuptools.build_meta'

            [project]
            name = "helpers_test_package"
            version = "0.1"

            [tool.setuptools.packages]
            find = {namespaces = false}

            [tool.extension-helpers]
            use_extension_helpers = true
            """
        )

        if limited_api and not envvar:
            pyproject_toml += f'\n[tool.distutils.bdist_wheel]\npy-limited-api = "{limited_api}"'

        (package / "pyproject.toml").write_text(pyproject_toml)

    env = os.environ.copy()

    if envvar:
        if limited_api:
            env["EXTENSION_HELPERS_PY_LIMITED_API"] = limited_api
        else:
            env["EXTENSION_HELPERS_PY_LIMITED_API"] = ""

    with chdir(package):
        subprocess.run(
            [sys.executable, "-m", "build", "--wheel", "--no-isolation"], env=env, check=True
        )

    wheels = os.listdir(package / "dist")

    assert len(wheels) == 1
    assert ("abi3" in wheels[0]) == (limited_api is not None)


@pytest.mark.skip(reason="Requires Cython >= 3.1")
def test_limited_api_invalid_abi(tmp_path, capsys):

    package = _extension_test_package(
        tmp_path, extension_type="c", include_numpy=True, include_setup_py=False
    )

    (package / "setup.cfg").write_text(
        dedent(
            """\
        [metadata]
        name = helpers_test_package
        version = 0.1

        [options]
        packages = find:

        [extension-helpers]
        use_extension_helpers = true

        [bdist_wheel]
        py_limited_api=invalid
    """
        )
    )

    (package / "pyproject.toml").write_text(
        dedent(
            """
    [build-system]
    requires = ["setuptools>=43.0.0",
                "wheel"]
    build-backend = 'setuptools.build_meta'
    """
        )
    )

    with chdir(package):
        result = subprocess.run(
            [sys.executable, "-m", "build", "--wheel", "--no-isolation"], stderr=subprocess.PIPE
        )

    assert result.stderr.strip().endswith(
        b"ValueError: Unrecognized abi version for limited API: invalid"
    )