[Core] Python tests in pytest (#25345) ## Why IREE's Python tests run as scripts that end in `unittest.main()`, so every test has to be a `unittest.TestCase`. Future tests may be plain test functions, fixtures, with parametrization. pytest also runs `unittest` classes, so making it the runner keeps all existing tests working without changes. ## Change - CMake: `iree_py_test` and `iree_local_py_test` run `python -m pytest <file>`, and `ARGS` go to pytest. The new `SCRIPT` option keeps running a file as a script, for samples and for files that pytest cannot run. 27 of the 50 registered tests now run under pytest; 23 stay scripts - CMake passes `--log-level=DEBUG`, so a failed test still shows what it logged - Bazel: an `iree_py_test` macro that runs pytest, used by the tests of `iree.core`, the profile renderer and two build scripts. pytest is added to the Bazel pip lock - pkgci runs the `iree.core` tests and the ONNX import test with pytest - pytest is added to `runtime/bindings/python/iree/runtime/build_requirements.txt` - `pytest.ini` at the repository root, so that pytest doesn't use the configuration of a project that contains IREE - Four tests that relied on running as `__main__` now work under any runner: `basic_test` and `net_test` of `iree.build`, `import_onnx_test` and `mnist_builder_test` - The testing guide gets a section on Python tests --------- Signed-off-by: Tobias Fuchs <fuchs@roofline.ai>
diff --git a/.github/workflows/pkgci_unit_test.yml b/.github/workflows/pkgci_unit_test.yml index eb0e281..00d2197 100644 --- a/.github/workflows/pkgci_unit_test.yml +++ b/.github/workflows/pkgci_unit_test.yml
@@ -66,9 +66,7 @@ echo "This run has no iree-base-core wheel, skipping its tests" exit 0 fi - for test in core/python/test/*_test.py; do - python "${test}" - done + python -m pytest core/python/test - name: Validate runtime wheel run: | source ${VENV_DIR}/bin/activate @@ -91,7 +89,7 @@ run: | source ${VENV_DIR}/bin/activate python -m pip install onnx>=1.16.0 - python compiler/bindings/python/test/tools/import_onnx_test.py + python -m pytest compiler/bindings/python/test/tools/import_onnx_test.py python compiler/bindings/python/test/extras/onnx_importer_test.py - name: Test FX (PyTorch) importer run: |
diff --git a/.gitignore b/.gitignore index f0d01e6..0b76128 100644 --- a/.gitignore +++ b/.gitignore
@@ -4,6 +4,7 @@ **/.ipynb_checkpoints/ .pytype/ **/__pycache__/** +.pytest_cache/ # Visual Studio files .vs/
diff --git a/build_tools/bazel/BUILD.bazel b/build_tools/bazel/BUILD.bazel index 7ad5e2f..8c0fff6 100644 --- a/build_tools/bazel/BUILD.bazel +++ b/build_tools/bazel/BUILD.bazel
@@ -6,6 +6,7 @@ load("@bazel_skylib//lib:selects.bzl", "selects") load("@bazel_skylib//rules:common_settings.bzl", "string_flag") +load("//build_tools/bazel:iree_py_test.bzl", "iree_py_test") package( default_visibility = ["//visibility:public"], @@ -13,7 +14,10 @@ licenses = ["notice"], # Apache 2.0 ) -exports_files(["assert_empty_query.sh"]) +exports_files([ + "assert_empty_query.sh", + "pytest_main.py", +]) # Helper tool for the IREE compiler ABI symbol rename (see renamed_link.bzl). py_binary( @@ -21,7 +25,7 @@ srcs = ["gen_rename_map.py"], ) -py_test( +iree_py_test( name = "gen_rename_map_test", srcs = [ "gen_rename_map.py",
diff --git a/build_tools/bazel/iree_py_test.bzl b/build_tools/bazel/iree_py_test.bzl new file mode 100644 index 0000000..1628400 --- /dev/null +++ b/build_tools/bazel/iree_py_test.bzl
@@ -0,0 +1,41 @@ +# Copyright 2026 The IREE Authors +# +# Licensed under the Apache License v2.0 with LLVM Exceptions. +# See https://llvm.org/LICENSE.txt for license information. +# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + +"""Rule for Python tests that are run by pytest.""" + +load("@rules_python//python:defs.bzl", "py_test") + +def iree_py_test(name, srcs, main = None, args = [], deps = [], **kwargs): + """A py_test whose tests are collected and run by pytest. + + Args: + name: Name of the test. + srcs: Python sources: the file with the tests and what it needs from its + own package. + main: The file with the tests. Defaults to `name + ".py"`. + args: Additional command line arguments for pytest. + deps: Python libraries that the tests need. pytest is added. + **kwargs: Passed on to py_test. + """ + if main == None: + main = name + ".py" + runner = Label("//build_tools/bazel:pytest_main.py") + + # `__init__.py` files created in the runfiles would turn the directories of + # the test into packages: pytest would import the test under a package + # name, and a created `iree/__init__.py` would hide the other packages of + # the `iree` namespace. + legacy_create_init = kwargs.pop("legacy_create_init", False) + + py_test( + name = name, + srcs = srcs + [runner], + args = ["$(rootpath {})".format(main)] + args, + legacy_create_init = legacy_create_init, + main = runner, + deps = deps + [Label("@pip//pytest")], + **kwargs + )
diff --git a/build_tools/bazel/pytest_main.py b/build_tools/bazel/pytest_main.py new file mode 100644 index 0000000..cb2d40d --- /dev/null +++ b/build_tools/bazel/pytest_main.py
@@ -0,0 +1,30 @@ +# Copyright 2026 The IREE Authors +# +# Licensed under the Apache License v2.0 with LLVM Exceptions. +# See https://llvm.org/LICENSE.txt for license information. +# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + +"""Entry point of iree_py_test targets: runs pytest with the given arguments.""" + +import os +import sys + +import pytest + +if __name__ == "__main__": + args = [ + # The runfiles tree is not a place for pytest's cache. + "-p", + "no:cacheprovider", + # No configuration file: pytest would otherwise search the directories + # above the runfiles tree for one, which are outside the build. + "-c", + os.devnull, + "--rootdir", + os.getcwd(), + ] + # Bazel reads the results of the individual tests from this report. + xml_output_file = os.environ.get("XML_OUTPUT_FILE") + if xml_output_file: + args.append(f"--junitxml={xml_output_file}") + sys.exit(pytest.main(args + sys.argv[1:]))
diff --git a/build_tools/bazel/requirements.in b/build_tools/bazel/requirements.in index 8b4661f..90a0702 100644 --- a/build_tools/bazel/requirements.in +++ b/build_tools/bazel/requirements.in
@@ -11,3 +11,6 @@ # Used by runtime/bindings/python for the numpy headers, which numpy 2 moved to # numpy/_core/include, and by tools/test. numpy>=2.0.0 + +# Used by iree_py_test (build_tools/bazel/iree_py_test.bzl) to run the tests. +pytest>=8.0.0
diff --git a/build_tools/bazel/requirements.txt b/build_tools/bazel/requirements.txt index c64566d..ab2e5bd 100644 --- a/build_tools/bazel/requirements.txt +++ b/build_tools/bazel/requirements.txt
@@ -1,9 +1,17 @@ # This file was autogenerated by uv via the following command: # uv pip compile --universal --generate-hashes --python-version 3.11 --only-binary :all: requirements.in ../../core/python/pyproject.toml -o requirements.txt +colorama==0.4.6 ; sys_platform == 'win32' \ + --hash=sha256:08695f5cb7ed6e0531a20572697297273c47b8cae5a63ffc6d6ed5c201be6e44 \ + --hash=sha256:4f1d9991f5acc0ca119f9d443620b77f9d6b33703e51011c16baf57afb285fc6 + # via pytest dacite==1.9.2 \ --hash=sha256:053f7c3f5128ca2e9aceb66892b1a3c8936d02c686e707bee96e19deef4bc4a0 \ --hash=sha256:6ccc3b299727c7aa17582f0021f6ae14d5de47c7227932c47fec4cdfefd26f09 # via iree-base-core (../../core/python/pyproject.toml) +iniconfig==2.3.1 \ + --hash=sha256:67f4b9c50da0dedf52af349e7749a80a9057a5031199791b906c3bb3ae878960 \ + --hash=sha256:9121e2c1fdb355232495be3194c8dfe87ccc2d5dee45947b78e68f499790d7a7 + # via pytest numpy==2.4.6 ; python_full_version < '3.12' \ --hash=sha256:001fbb8e08d942dd57599e781f2472269ee7f2755fae407b4f67b2f0b17da3f1 \ --hash=sha256:0280e0356c0829a18d9de1cb7eee50ec22ca639878d7240307ca0943d73cd2c4 \ @@ -146,7 +154,21 @@ --hash=sha256:fd47c92e0d1e53f9498b1a30305072434fbae6b5a305cbcab514f959e9ce0fab \ --hash=sha256:ff5c1ab54a637c0adcdbb69ad10e5c4f1c4dedba69c0d1de383249b70c36908f # via -r requirements.in +packaging==26.3 \ + --hash=sha256:94edc256424af38762eb31306eed28beb9f0efc50a8837492c9d6fd6004aed79 \ + --hash=sha256:d7193f7c8e4e93f444fde0262bf90af30e16fa0ad0ad44cb553c87339b23cd1c + # via pytest pluggy==1.7.0 \ --hash=sha256:7dd7b0d8832ba3cb632c306926ded123429211b83641b35dc5c41ad2d34f9bec \ --hash=sha256:d1eaa46ebb595891b860ab086b4d09c8588af65ebd4361b8e8f4bb8920b90ba8 - # via iree-base-core (../../core/python/pyproject.toml) + # via + # iree-base-core (../../core/python/pyproject.toml) + # pytest +pygments==2.21.0 \ + --hash=sha256:2363c69b61c4a97c838da3b130dcd6468f4848992b21a82f2a63ec34377137d9 \ + --hash=sha256:610ca751c9bc2492b38eb9a38a7fbc93edbbb2d7182edaf34e66ae493dee5c8c + # via pytest +pytest==9.2.0 \ + --hash=sha256:07acdcf88ec174f907dc01af70bf52d49b014bbab03faeeade31c96b18c2e588 \ + --hash=sha256:97c4f3b1f3c7414aa36465e09b8220f1d03627993bd51b1282e193753c80557b + # via -r requirements.in
diff --git a/build_tools/bazel_to_cmake/bazel_to_cmake_converter.py b/build_tools/bazel_to_cmake/bazel_to_cmake_converter.py index 6b91438..9c53e88 100644 --- a/build_tools/bazel_to_cmake/bazel_to_cmake_converter.py +++ b/build_tools/bazel_to_cmake/bazel_to_cmake_converter.py
@@ -632,6 +632,9 @@ def py_test(self, *args, **kwargs): pass + def iree_py_test(self, *args, **kwargs): + pass + def filegroup(self, name, srcs, **kwargs): if not srcs: return
diff --git a/build_tools/cmake/iree_python.cmake b/build_tools/cmake/iree_python.cmake index abec009..3d351de 100644 --- a/build_tools/cmake/iree_python.cmake +++ b/build_tools/cmake/iree_python.cmake
@@ -62,20 +62,45 @@ endif() endfunction() +# Warns, once per configuration, when pytest is not installed for the Python +# interpreter that runs the tests. The tests are still added and then fail, +# so that a missing package cannot make them go unnoticed. +function(_iree_warn_without_pytest) + get_property(_CHECKED GLOBAL PROPERTY _IREE_PYTEST_CHECKED) + if(_CHECKED) + return() + endif() + set_property(GLOBAL PROPERTY _IREE_PYTEST_CHECKED TRUE) + execute_process( + COMMAND "${Python3_EXECUTABLE}" -c "import pytest" + RESULT_VARIABLE _RESULT + OUTPUT_QUIET + ERROR_QUIET + ) + if(NOT _RESULT EQUAL 0) + message(WARNING + "pytest is not installed for ${Python3_EXECUTABLE}, so the Python tests " + "will fail. Install it with: python -m pip install -r " + "runtime/bindings/python/iree/runtime/build_requirements.txt") + endif() +endfunction() + # iree_local_py_test() # # CMake function to run python test with provided python package paths. # # Parameters: # NAME: name of test -# SRC: Test source file -# ARGS: Command line arguments to the Python source file. +# SRC: Test source file. pytest runs the tests in it, unless SCRIPT is given. +# ARGS: Command line arguments to pytest or, with SCRIPT, to the source file. # LABELS: Additional labels to apply to the test. The package path is added # automatically. # WILL_FAIL: The test will run, but its pass/fail status will be inverted. # GENERATED_IN_BINARY_DIR: If present, indicates that the srcs have been # in the CMAKE_CURRENT_BINARY_DIR. # PACKAGE_DIRS: Python package paths to be added to PYTHONPATH. +# SCRIPT: If present, the source file is run as a script. This is for files +# that are not made of tests that pytest can collect, such as samples. function(iree_local_py_test) if(NOT IREE_BUILD_TESTS OR ANDROID OR EMSCRIPTEN) return() @@ -83,7 +108,7 @@ cmake_parse_arguments( _RULE - "GENERATED_IN_BINARY_DIR" + "GENERATED_IN_BINARY_DIR;SCRIPT" "NAME;SRC;WILL_FAIL" "ARGS;LABELS;PACKAGE_DIRS;TIMEOUT" ${ARGN} @@ -106,10 +131,20 @@ set(_RULE_TIMEOUT 60) endif() + if(_RULE_SCRIPT) + set(_RUNNER) + else() + _iree_warn_without_pytest() + # Without the cache provider, pytest writes nothing into the source tree. + # With the log level, a failed test reports all that it logged. + set(_RUNNER -m pytest -p no:cacheprovider --log-level=DEBUG) + endif() + add_test( NAME ${_NAME_PATH} COMMAND "${Python3_EXECUTABLE}" + ${_RUNNER} "${CMAKE_CURRENT_SOURCE_DIR}/${_RULE_SRC}" ${_RULE_ARGS} ) @@ -145,17 +180,20 @@ # # Parameters: # NAME: name of test -# SRCS: Test source file (single file only, despite name) -# ARGS: Command line arguments to the Python source file. +# SRCS: Test source file (single file only, despite name). pytest runs the +# tests in it, unless SCRIPT is given. +# ARGS: Command line arguments to pytest or, with SCRIPT, to the source file. # LABELS: Additional labels to apply to the test. The package path is added # automatically. # WILL_FAIL: The test will run, but its pass/fail status will be inverted. # GENERATED_IN_BINARY_DIR: If present, indicates that the srcs have been # in the CMAKE_CURRENT_BINARY_DIR. +# SCRIPT: If present, the source file is run as a script. This is for files +# that are not made of tests that pytest can collect, such as samples. function(iree_py_test) cmake_parse_arguments( _RULE - "GENERATED_IN_BINARY_DIR" + "GENERATED_IN_BINARY_DIR;SCRIPT" "NAME;SRCS;WILL_FAIL" "ARGS;LABELS;TIMEOUT" ${ARGN} @@ -164,6 +202,11 @@ return() endif() + set(_SCRIPT) + if(_RULE_SCRIPT) + set(_SCRIPT SCRIPT) + endif() + iree_local_py_test( NAME "${_RULE_NAME}" @@ -182,5 +225,6 @@ "${_RULE_GENERATED_IN_BINARY_DIR}" TIMEOUT ${_RULE_TIMEOUT} + ${_SCRIPT} ) endfunction()
diff --git a/build_tools/scripts/BUILD.bazel b/build_tools/scripts/BUILD.bazel index a25500b..a605ea5 100644 --- a/build_tools/scripts/BUILD.bazel +++ b/build_tools/scripts/BUILD.bazel
@@ -4,7 +4,8 @@ # See https://llvm.org/LICENSE.txt for license information. # SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception -load("@rules_python//python:defs.bzl", "py_binary", "py_test") +load("@rules_python//python:defs.bzl", "py_binary") +load("//build_tools/bazel:iree_py_test.bzl", "iree_py_test") package( default_visibility = ["//visibility:public"], @@ -23,7 +24,7 @@ srcs = ["generate_vm_isa.py"], ) -py_test( +iree_py_test( name = "gen_plugin_abi_hash_test", srcs = [ "gen_plugin_abi_hash.py",
diff --git a/compiler/bindings/python/test/api/CMakeLists.txt b/compiler/bindings/python/test/api/CMakeLists.txt index b07215f..be8310c 100644 --- a/compiler/bindings/python/test/api/CMakeLists.txt +++ b/compiler/bindings/python/test/api/CMakeLists.txt
@@ -4,18 +4,24 @@ # See https://llvm.org/LICENSE.txt for license information. # SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +# On Windows this file disables itself when it is imported and then defines +# no tests, which only works for a script. iree_py_test( NAME api_test SRCS "api_test.py" + SCRIPT ) +# The next two run their checks when they are imported, which only works for +# a script. iree_py_test( NAME output_buffer_reference_test SRCS "output_buffer_reference_test.py" + SCRIPT ) iree_py_test( @@ -23,4 +29,5 @@ tuner_api_test SRCS "tuner_api_test.py" + SCRIPT )
diff --git a/compiler/bindings/python/test/build_api/basic_test.py b/compiler/bindings/python/test/build_api/basic_test.py index e70f841..68f9a86 100644 --- a/compiler/bindings/python/test/build_api/basic_test.py +++ b/compiler/bindings/python/test/build_api/basic_test.py
@@ -6,6 +6,7 @@ import io import os +import sys from pathlib import Path import tempfile import unittest @@ -14,6 +15,10 @@ from iree.build.executor import BuildContext from iree.build.test_actions import ExecuteOutOfProcessThunkAction +# iree.build looks up the entry points in this module, whether it runs as a +# script or is imported by a test runner. +THIS_MODULE = sys.modules[__name__] + @entrypoint def write_out_of_process_pid(): @@ -66,7 +71,8 @@ parent_pid = os.getpid() print(f"Testing out of process concurrency: pid={parent_pid}") iree_build_main( - args=["write_out_of_process_pid", "--output-dir", str(self.output_path)] + THIS_MODULE, + args=["write_out_of_process_pid", "--output-dir", str(self.output_path)], ) pid_file = ( self.output_path / "genfiles" / "write_out_of_process_pid" / "pid.txt" @@ -81,6 +87,7 @@ out_io = io.StringIO() err_io = io.StringIO() iree_build_main( + THIS_MODULE, args=[ "write_out_of_process_pid", "--output-dir", @@ -101,6 +108,7 @@ err_io = io.StringIO() with self.assertRaises(SystemExit): iree_build_main( + THIS_MODULE, args=[ "exception_in_action", "--output-dir", @@ -122,6 +130,7 @@ out_io = io.StringIO() err_io = io.StringIO() iree_build_main( + THIS_MODULE, args=["write_out_of_process_pid", "--output-dir", str(self.output_path)], stderr=err_io, stdout=out_io, @@ -135,6 +144,7 @@ out_io = io.StringIO() err_io = io.StringIO() iree_build_main( + THIS_MODULE, args=[ "write_out_of_process_pid", "--output-dir",
diff --git a/compiler/bindings/python/test/build_api/mnist_builder_test.py b/compiler/bindings/python/test/build_api/mnist_builder_test.py index 60f750c..302c944 100644 --- a/compiler/bindings/python/test/build_api/mnist_builder_test.py +++ b/compiler/bindings/python/test/build_api/mnist_builder_test.py
@@ -4,6 +4,7 @@ # See https://llvm.org/LICENSE.txt for license information. # SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +import importlib.util import io from pathlib import Path import re @@ -22,6 +23,12 @@ ] +requires_onnx = unittest.skipUnless( + importlib.util.find_spec("onnx"), "the onnx package is not installed" +) + + +@requires_onnx class MnistBuilderTest(unittest.TestCase): def setUp(self): self._temp_dir = tempfile.TemporaryDirectory(ignore_cleanup_errors=True) @@ -117,10 +124,4 @@ if __name__ == "__main__": - try: - import onnx - except ModuleNotFoundError: - print(f"Skipping test {__file__} because Python dependency `onnx` is not found") - sys.exit(0) - unittest.main()
diff --git a/compiler/bindings/python/test/build_api/net_test.py b/compiler/bindings/python/test/build_api/net_test.py index 8899065..c7c1d79 100644 --- a/compiler/bindings/python/test/build_api/net_test.py +++ b/compiler/bindings/python/test/build_api/net_test.py
@@ -6,11 +6,16 @@ import io from pathlib import Path +import sys import tempfile import unittest from iree.build import * +# iree.build looks up the entry points in this module, whether it runs as a +# script or is imported by a test runner. +THIS_MODULE = sys.modules[__name__] + TEST_URL = None # Arbitrary URLs to download from via HTTP requests. These should require no @@ -53,6 +58,7 @@ out_io = io.StringIO() err_io = io.StringIO() iree_build_main( + THIS_MODULE, args=[ "file_via_http", "--output-dir",
diff --git a/compiler/bindings/python/test/extras/CMakeLists.txt b/compiler/bindings/python/test/extras/CMakeLists.txt index 18469dd..2387e5c 100644 --- a/compiler/bindings/python/test/extras/CMakeLists.txt +++ b/compiler/bindings/python/test/extras/CMakeLists.txt
@@ -5,11 +5,13 @@ # SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception if(IREE_INPUT_TORCH) + # These only import a module and define no tests for pytest to collect. iree_py_test( NAME fx_importer_test SRCS "fx_importer_test.py" + SCRIPT ) iree_py_test( @@ -17,5 +19,6 @@ onnx_importer_test SRCS "onnx_importer_test.py" + SCRIPT ) endif()
diff --git a/compiler/bindings/python/test/ir/CMakeLists.txt b/compiler/bindings/python/test/ir/CMakeLists.txt index fcf7b13..efdca6f 100644 --- a/compiler/bindings/python/test/ir/CMakeLists.txt +++ b/compiler/bindings/python/test/ir/CMakeLists.txt
@@ -4,11 +4,14 @@ # See https://llvm.org/LICENSE.txt for license information. # SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +# These run their checks when they are imported, which only works for a +# script. iree_py_test( NAME registration_test SRCS "registration_test.py" + SCRIPT ) iree_py_test( @@ -16,4 +19,5 @@ dialects_test SRCS "dialects_test.py" + SCRIPT )
diff --git a/compiler/bindings/python/test/tools/CMakeLists.txt b/compiler/bindings/python/test/tools/CMakeLists.txt index ec96eea..59ac742 100644 --- a/compiler/bindings/python/test/tools/CMakeLists.txt +++ b/compiler/bindings/python/test/tools/CMakeLists.txt
@@ -31,11 +31,14 @@ "ir_tool_test.py" ) +# The next two exit when they are imported without the TensorFlow tools +# installed, which only works for a script. iree_py_test( NAME compiler_tf_test SRCS "compiler_tf_test.py" + SCRIPT ) iree_py_test( @@ -43,4 +46,5 @@ compiler_tflite_test SRCS "compiler_tflite_test.py" + SCRIPT )
diff --git a/compiler/bindings/python/test/tools/import_onnx_test.py b/compiler/bindings/python/test/tools/import_onnx_test.py index 0692e4c..72a0045 100644 --- a/compiler/bindings/python/test/tools/import_onnx_test.py +++ b/compiler/bindings/python/test/tools/import_onnx_test.py
@@ -4,8 +4,8 @@ # See https://llvm.org/LICENSE.txt for license information. # SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +import importlib.util import os -import sys import tempfile import unittest from pathlib import Path @@ -28,6 +28,12 @@ ) +requires_onnx = unittest.skipUnless( + importlib.util.find_spec("onnx"), "the onnx package is not installed" +) + + +@requires_onnx class ImportOnnxTest(unittest.TestCase): def setUp(self): with tempfile.NamedTemporaryFile(delete=False) as f: @@ -52,6 +58,7 @@ self.assertIn("torch.operator", contents) +@requires_onnx class ImportOnnxwithExternalizationTest(unittest.TestCase): def setUp(self): with tempfile.NamedTemporaryFile(delete=False) as f: @@ -192,10 +199,4 @@ if __name__ == "__main__": - try: - import onnx - except ModuleNotFoundError: - print(f"Skipping test {__file__} because Python dependency `onnx` is not found") - sys.exit(0) - unittest.main()
diff --git a/core/python/BUILD.bazel b/core/python/BUILD.bazel index 1011de3..5cce0dc 100644 --- a/core/python/BUILD.bazel +++ b/core/python/BUILD.bazel
@@ -4,9 +4,10 @@ # See https://llvm.org/LICENSE.txt for license information. # SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception -load("@rules_python//python:defs.bzl", "py_library", "py_test") +load("@rules_python//python:defs.bzl", "py_library") load("//build_tools/bazel:build_defs.oss.bzl", "iree_cmake_extra_content") load("//build_tools/bazel:enforce_glob.bzl", "enforce_glob") +load("//build_tools/bazel:iree_py_test.bzl", "iree_py_test") package( default_visibility = ["//visibility:public"], @@ -48,47 +49,42 @@ ], ) -py_test( +iree_py_test( name = "config_test", size = "small", srcs = ["test/config_test.py"], - legacy_create_init = False, main = "test/config_test.py", deps = [":core"], ) -py_test( +iree_py_test( name = "plugins_test", size = "small", srcs = ["test/plugins_test.py"], - legacy_create_init = False, main = "test/plugins_test.py", deps = [":core"], ) -py_test( +iree_py_test( name = "result_test", size = "small", srcs = ["test/result_test.py"], - legacy_create_init = False, main = "test/result_test.py", deps = [":core"], ) -py_test( +iree_py_test( name = "package_test", size = "small", srcs = ["test/package_test.py"], - # A generated `iree/__init__.py` would hide iree.compiler and iree.runtime, - # which share the `iree` namespace. - legacy_create_init = False, main = "test/package_test.py", deps = [":core"], ) -# bazel_to_cmake does not convert py_test, so each test is mirrored here for -# CTest. The tests are registered only if the dependencies in pyproject.toml -# are installed, so that builds that use no Python need not install them. +# bazel_to_cmake does not convert iree_py_test, so each test is mirrored here +# for CTest. The tests are registered only if the dependencies in +# pyproject.toml are installed, so that builds that use no Python need not +# install them. iree_cmake_extra_content( content = """ if(IREE_BUILD_TESTS)
diff --git a/core/python/README.md b/core/python/README.md index 9fbaf9f..045186d 100644 --- a/core/python/README.md +++ b/core/python/README.md
@@ -22,9 +22,11 @@ ``` With CMake, the tests are registered if the Python interpreter of the build has -the dependencies installed. The Python bindings are not needed: +the dependencies installed. They are run by pytest. The Python bindings are not +needed: ```shell +python -m pip install pytest python -m pip install --require-hashes -r core/python/requirements.txt ctest --test-dir ${BUILD_DIR} -R iree/core/python ``` @@ -32,6 +34,6 @@ Against the installed package: ```shell -python -m pip install core/python/ -python -m unittest discover -s core/python/test -p "*_test.py" +python -m pip install pytest core/python/ +python -m pytest core/python/test ```
diff --git a/docs/website/docs/developers/general/testing-guide.md b/docs/website/docs/developers/general/testing-guide.md index 2beff16..13a2086 100644 --- a/docs/website/docs/developers/general/testing-guide.md +++ b/docs/website/docs/developers/general/testing-guide.md
@@ -15,6 +15,7 @@ | | iree_hal_cts_test_suite | Bazel/CMake | Host/Device | | Core E2E tests | iree_check_test | Bazel/CMake | Host/Device | | | iree_static_linker_test | CMake | Host/Device | +| Python tests | iree_py_test | Bazel/CMake | Host | There are also more `*_test_suite` targets that groups test targets with the same configuration together. @@ -205,6 +206,76 @@ `iree-runtime-coverage-export` target can be built to export LCOV information for tooling/IDEs. +## Python tests + +Tests for the Python packages (`iree.compiler`, `iree.runtime` and `iree.core`) +are written in Python and run by [pytest](https://docs.pytest.org/en/stable/). +Test files that pytest cannot run are run as scripts, as described at the end +of this section. The tests are in files named `*_test.py`, next to the package +they test: + +* [`compiler/bindings/python/test/`](https://github.com/iree-org/iree/tree/main/compiler/bindings/python/test) +* [`runtime/bindings/python/tests/`](https://github.com/iree-org/iree/tree/main/runtime/bindings/python/tests) +* [`core/python/test/`](https://github.com/iree-org/iree/tree/main/core/python/test) + +### Running a test + +With CMake, the tests are registered with CTest. They need pytest for the +Python interpreter of the build. It is installed with +`runtime/bindings/python/iree/runtime/build_requirements.txt`. + +```shell +# From the build directory +ctest -R runtime/bindings/python +``` + +To run pytest yourself, make the packages importable first, as described in +[Using the Python bindings](../../building-from-source/getting-started.md#using-the-python-bindings): + +```shell +python -m pytest runtime/bindings/python/tests/vm_test.py +``` + +With Bazel, run the test targets of a package, for example: + +```shell +bazel test //core/python/... +``` + +### Writing a test + +pytest runs test functions and `unittest.TestCase` classes alike, so both +styles can be used. Most existing tests are `unittest.TestCase` classes. + +A test that needs an optional package should skip itself when the package is +missing, for example with `unittest.skipUnless` on the test class. Do not skip +a whole file while it is imported: pytest then finds no test in the file and +reports a failure. + +### Configuring the build system + +In CMake, use `iree_py_test` for tests of the Python bindings, and +`iree_local_py_test` for tests that do not need them: + +```cmake +iree_py_test( + NAME + vm_test + SRCS + "vm_test.py" +) +``` + +Files that pytest cannot run take the `SCRIPT` option and are run as scripts. +These are the samples that are run as a check, and test files that run their +checks or exit when they are imported, or that are configured through +their own command line. With `SCRIPT`, `ARGS` are passed to the file. +Otherwise they are passed to pytest. + +In Bazel, use `iree_py_test` from `//build_tools/bazel:iree_py_test.bzl`. The +Bazel to CMake converter does not convert it, so the CMake side is written by +hand or added with `iree_cmake_extra_content`. + ## IREE core end-to-end (e2e) tests Here "end-to-end" means from the input accepted by the IREE core compiler
diff --git a/pytest.ini b/pytest.ini new file mode 100644 index 0000000..cb65491 --- /dev/null +++ b/pytest.ini
@@ -0,0 +1,4 @@ +# Marks the root of IREE's Python tests. With it, pytest does not go on to +# search the directories above the repository for a configuration, such as that +# of a project which contains IREE. +[pytest]
diff --git a/runtime/bindings/python/iree/runtime/build_requirements.txt b/runtime/bindings/python/iree/runtime/build_requirements.txt index 81384ac..f056495 100644 --- a/runtime/bindings/python/iree/runtime/build_requirements.txt +++ b/runtime/bindings/python/iree/runtime/build_requirements.txt
@@ -10,4 +10,5 @@ wheel>=0.36.2 sympy>=1.14.0 ml_dtypes>=0.5.4 +pytest>=8.0.0 pyright==1.1.410
diff --git a/runtime/src/iree/tooling/profile/BUILD.bazel b/runtime/src/iree/tooling/profile/BUILD.bazel index aeb571f..51469ac 100644 --- a/runtime/src/iree/tooling/profile/BUILD.bazel +++ b/runtime/src/iree/tooling/profile/BUILD.bazel
@@ -6,6 +6,7 @@ load("@rules_python//python:defs.bzl", "py_test") load("//build_tools/bazel:build_defs.oss.bzl", "iree_cmake_extra_content", "iree_runtime_cc_binary", "iree_runtime_cc_library", "iree_runtime_cc_test") +load("//build_tools/bazel:iree_py_test.bzl", "iree_py_test") package( default_visibility = ["//visibility:public"], @@ -304,7 +305,7 @@ ], ) -py_test( +iree_py_test( name = "render_test", srcs = [ "render/__init__.py", @@ -329,6 +330,8 @@ tags = ["noriscv"], ) +# In CMake these run as scripts: a build of the runtime alone needs no Python +# packages, so its tests cannot rely on pytest. iree_cmake_extra_content( content = """ iree_local_py_test( @@ -336,6 +339,7 @@ render_test SRC "render_test.py" + SCRIPT PACKAGE_DIRS "${CMAKE_CURRENT_SOURCE_DIR}" ) @@ -345,6 +349,7 @@ cli_test SRC "cli_test.py" + SCRIPT ARGS "--fixture-generator=$<TARGET_FILE:iree_tooling_profile_test_fixture_generator>" "--iree-profile=$<TARGET_FILE:iree-profile>"
diff --git a/runtime/src/iree/tooling/profile/CMakeLists.txt b/runtime/src/iree/tooling/profile/CMakeLists.txt index fc72cb8..0703e11 100644 --- a/runtime/src/iree/tooling/profile/CMakeLists.txt +++ b/runtime/src/iree/tooling/profile/CMakeLists.txt
@@ -363,6 +363,7 @@ render_test SRC "render_test.py" + SCRIPT PACKAGE_DIRS "${CMAKE_CURRENT_SOURCE_DIR}" ) @@ -372,6 +373,7 @@ cli_test SRC "cli_test.py" + SCRIPT ARGS "--fixture-generator=$<TARGET_FILE:iree_tooling_profile_test_fixture_generator>" "--iree-profile=$<TARGET_FILE:iree-profile>"
diff --git a/samples/py_custom_module/CMakeLists.txt b/samples/py_custom_module/CMakeLists.txt index 85c82bc..282129a 100644 --- a/samples/py_custom_module/CMakeLists.txt +++ b/samples/py_custom_module/CMakeLists.txt
@@ -18,4 +18,5 @@ decode_secret_message_sample SRCS "decode_secret_message.py" + SCRIPT )
diff --git a/samples/sink_callback/CMakeLists.txt b/samples/sink_callback/CMakeLists.txt index 1a5957b..bcd5367 100644 --- a/samples/sink_callback/CMakeLists.txt +++ b/samples/sink_callback/CMakeLists.txt
@@ -18,6 +18,7 @@ sink_callback_log_simple SRCS "sink_callback_log.py" + SCRIPT ) iree_py_test( @@ -25,4 +26,5 @@ sink_callback_log_async SRCS "sink_callback_log_async.py" + SCRIPT )
diff --git a/tests/e2e/collectives/CMakeLists.txt b/tests/e2e/collectives/CMakeLists.txt index 863da9f..387f668 100644 --- a/tests/e2e/collectives/CMakeLists.txt +++ b/tests/e2e/collectives/CMakeLists.txt
@@ -26,6 +26,7 @@ collectives_test_cuda_1_gpu SRCS "collectives_test.py" + SCRIPT ARGS "-k" "SingleRank" ${COMMON_ARGS} @@ -38,6 +39,7 @@ collectives_test_cuda_2_gpus SRCS "collectives_test.py" + SCRIPT ARGS "-k" "TwoRanks" ${COMMON_ARGS} @@ -53,6 +55,7 @@ collectives_test_cuda_4_gpus SRCS "collectives_test.py" + SCRIPT ARGS "-k" "FourRanks" ${COMMON_ARGS} @@ -79,6 +82,7 @@ collectives_test_hip_1_gpu SRCS "collectives_test.py" + SCRIPT ARGS "-k" "SingleRank" ${COMMON_ARGS} @@ -91,6 +95,7 @@ collectives_test_hip_2_gpus SRCS "collectives_test.py" + SCRIPT ARGS "-k" "TwoRanks" ${COMMON_ARGS} @@ -106,6 +111,7 @@ collectives_test_hip_4_gpus SRCS "collectives_test.py" + SCRIPT ARGS "-k" "FourRanks" ${COMMON_ARGS}
diff --git a/tests/e2e/stablehlo_models/mnist_train_test/CMakeLists.txt b/tests/e2e/stablehlo_models/mnist_train_test/CMakeLists.txt index f362a3e..17be48e 100644 --- a/tests/e2e/stablehlo_models/mnist_train_test/CMakeLists.txt +++ b/tests/e2e/stablehlo_models/mnist_train_test/CMakeLists.txt
@@ -21,6 +21,7 @@ mnist_train_test_cpu SRCS "mnist_train_test.py" + SCRIPT ARGS "--target_backend=llvm-cpu" "--driver=local-task" @@ -35,6 +36,7 @@ mnist_train_test_cuda SRCS "mnist_train_test.py" + SCRIPT ARGS "--target_backend=cuda" "--driver=cuda" @@ -50,6 +52,7 @@ mnist_train_test_vulkan SRCS "mnist_train_test.py" + SCRIPT ARGS "--target_backend=vulkan-spirv" "--driver=vulkan"