Skip to content

Commit

Permalink
chore(types): type functions in tests
Browse files Browse the repository at this point in the history
Signed-off-by: Henry Schreiner <henryschreineriii@gmail.com>
  • Loading branch information
henryiii committed Oct 22, 2024
1 parent 57ac6db commit af892b8
Show file tree
Hide file tree
Showing 15 changed files with 74 additions and 65 deletions.
10 changes: 6 additions & 4 deletions bin/make_dependency_update_pr.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,14 +16,16 @@ def shell(cmd, *, check: bool, **kwargs):
return run([cmd], shell=True, check=check, **kwargs)


def git_repo_has_changes():
unstaged_changes = shell("git diff-index --quiet HEAD --", check=False).returncode != 0
staged_changes = shell("git diff-index --quiet --cached HEAD --", check=False).returncode != 0
def git_repo_has_changes() -> bool:
unstaged_changes: bool = shell("git diff-index --quiet HEAD --", check=False).returncode != 0
staged_changes: bool = (
shell("git diff-index --quiet --cached HEAD --", check=False).returncode != 0
)
return unstaged_changes or staged_changes


@click.command()
def main():
def main() -> None:
project_root = Path(__file__).parent / ".."
os.chdir(project_root)

Expand Down
16 changes: 8 additions & 8 deletions bin/run_example_ci_configs.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,29 +4,29 @@

import os
import shutil
import subprocess
import sys
import textwrap
import time
import typing
from glob import glob
from pathlib import Path
from subprocess import run
from urllib.parse import quote

import click


def shell(cmd, *, check: bool, **kwargs):
return run([cmd], shell=True, check=check, **kwargs)
def shell(cmd: str, *, check: bool, **kwargs: object) -> subprocess.CompletedProcess[str]:
return subprocess.run([cmd], shell=True, check=check, **kwargs) # type: ignore[call-overload, no-any-return]


def git_repo_has_changes():
def git_repo_has_changes() -> bool:
unstaged_changes = shell("git diff-index --quiet HEAD --", check=False).returncode != 0
staged_changes = shell("git diff-index --quiet --cached HEAD --", check=False).returncode != 0
return unstaged_changes or staged_changes


def generate_basic_project(path):
def generate_basic_project(path: Path) -> None:
sys.path.insert(0, "")
from test.test_projects.c import new_c_project

Expand Down Expand Up @@ -79,7 +79,7 @@ class CIService(typing.NamedTuple):
]


def ci_service_for_config_file(config_file):
def ci_service_for_config_file(config_file: str) -> CIService:
filename = Path(config_file).name

try:
Expand Down Expand Up @@ -134,7 +134,7 @@ def run_example_ci_configs(config_files=None):
dst_config_file.parent.mkdir(parents=True, exist_ok=True)
shutil.copyfile(src_config_file, dst_config_file)

run(["git", "add", example_project], check=True)
subprocess.run(["git", "add", example_project], check=True)
message = textwrap.dedent(
f"""\
Test example minimal configs
Expand All @@ -144,7 +144,7 @@ def run_example_ci_configs(config_files=None):
Time: {timestamp}
"""
)
run(["git", "commit", "--no-verify", "--message", message], check=True)
subprocess.run(["git", "commit", "--no-verify", "--message", message], check=True)
shell(f"git subtree --prefix={example_project} push origin {branch_name}", check=True)

print("---")
Expand Down
2 changes: 1 addition & 1 deletion bin/update_how_it_works_image.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
)


def main():
def main() -> None:
subprocess.run(["mkdocs", "build"], check=True)

hti = Html2Image(custom_flags=["--force-device-scale-factor=2"])
Expand Down
2 changes: 1 addition & 1 deletion bin/update_readme_changelog.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@
)


def main():
def main() -> None:
changelog_text = CHANGELOG_FILE.read_text()
readme_text = README_FILE.read_text()

Expand Down
3 changes: 0 additions & 3 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,6 @@ warn_unused_configs = true

strict = true
disallow_untyped_defs = false
disallow_untyped_calls = false
disallow_incomplete_defs = false

enable_error_code = ["ignore-without-code", "redundant-expr", "truthy-bool"]
Expand All @@ -124,9 +123,7 @@ warn_unreachable = false
[[tool.mypy.overrides]]
module = "cibuildwheel.*"
disallow_untyped_defs = true
disallow_untyped_calls = true
disallow_incomplete_defs = true
disallow_untyped_decorators = true

[[tool.mypy.overrides]]
module = [
Expand Down
5 changes: 3 additions & 2 deletions test/test_dependency_versions.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import platform
import re
import textwrap
from pathlib import Path

import pytest

Expand Down Expand Up @@ -46,8 +47,8 @@
VERSION_REGEX = r"([\w-]+)==([^\s]+)"


def get_versions_from_constraint_file(constraint_file):
constraint_file_text = constraint_file.read_text(encoding="utf8")
def get_versions_from_constraint_file(constraint_file: Path) -> dict[str, str]:
constraint_file_text = constraint_file.read_text(encoding="utf-8")

return dict(re.findall(VERSION_REGEX, constraint_file_text))

Expand Down
7 changes: 6 additions & 1 deletion test/test_from_sdist.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import subprocess
import sys
import textwrap
from collections.abc import Mapping
from pathlib import Path
from tempfile import TemporaryDirectory

Expand All @@ -28,7 +29,11 @@ def make_sdist(project: TestProject, working_dir: Path) -> Path:
return next(sdist_dir.glob("*.tar.gz"))


def cibuildwheel_from_sdist_run(sdist_path, add_env=None, config_file=None):
def cibuildwheel_from_sdist_run(
sdist_path: Path | str,
add_env: Mapping[str, str] | None = None,
config_file: str | None = None,
) -> list[str]:
env = os.environ.copy()

if add_env:
Expand Down
2 changes: 1 addition & 1 deletion test/test_projects/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
from pathlib import Path


def main():
def main() -> None:
parser = ArgumentParser(
prog="python -m test.test_projects", description="Generate a test project to check it out"
)
Expand Down
6 changes: 3 additions & 3 deletions test/test_projects/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,11 +22,11 @@ class TestProject:
files: FilesDict
template_context: TemplateContext

def __init__(self):
def __init__(self) -> None:
self.files = {}
self.template_context = {}

def generate(self, path: Path):
def generate(self, path: Path) -> None:
for filename, content in self.files.items():
file_path = path / filename
file_path.parent.mkdir(parents=True, exist_ok=True)
Expand All @@ -37,7 +37,7 @@ def generate(self, path: Path):

f.write(content)

def copy(self):
def copy(self) -> TestProject:
other = TestProject()
other.files = self.files.copy()
other.template_context = self.template_context.copy()
Expand Down
14 changes: 7 additions & 7 deletions test/test_projects/c.py
Original file line number Diff line number Diff line change
Expand Up @@ -78,13 +78,13 @@

def new_c_project(
*,
spam_c_top_level_add="",
spam_c_function_add="",
setup_py_add="",
setup_py_extension_args_add="",
setup_py_setup_args_add="",
setup_cfg_add="",
):
spam_c_top_level_add: str = "",
spam_c_function_add: str = "",
setup_py_add: str = "",
setup_py_extension_args_add: str = "",
setup_py_setup_args_add: str = "",
setup_cfg_add: str = "",
) -> TestProject:
project = TestProject()

project.files.update(
Expand Down
2 changes: 1 addition & 1 deletion test/test_windows.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
basic_project = test_projects.new_c_project()


def skip_if_no_msvc(arm64=False):
def skip_if_no_msvc(arm64: bool = False) -> None:
programfiles = os.getenv("PROGRAMFILES(X86)", "") or os.getenv("PROGRAMFILES", "")
if not programfiles:
pytest.skip("Requires %PROGRAMFILES(X86)% variable to be set")
Expand Down
54 changes: 29 additions & 25 deletions test/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,10 @@
import platform as pm
import subprocess
import sys
from collections.abc import Mapping, Sequence
from pathlib import Path
from tempfile import TemporaryDirectory
from typing import Final
from typing import Any, Final

import pytest

Expand All @@ -37,7 +39,9 @@
raise Exception(msg)


def cibuildwheel_get_build_identifiers(project_path, env=None, *, prerelease_pythons=False):
def cibuildwheel_get_build_identifiers(
project_path: Path, env: dict[str, str] | None = None, *, prerelease_pythons: bool = False
) -> list[str]:
"""
Returns the list of build identifiers that cibuildwheel will try to build
for the current platform.
Expand Down Expand Up @@ -75,14 +79,14 @@ def _update_pip_cache_dir(env: dict[str, str]) -> None:


def cibuildwheel_run(
project_path,
package_dir=".",
env=None,
add_env=None,
output_dir=None,
add_args=None,
single_python=False,
):
project_path: str | Path,
package_dir: str | Path = ".",
env: dict[str, str] | None = None,
add_env: Mapping[str, str] | None = None,
output_dir: Path | None = None,
add_args: Sequence[str] | None = None,
single_python: bool = False,
) -> list[str]:
"""
Runs cibuildwheel as a subprocess, building the project at project_path.
Expand Down Expand Up @@ -144,17 +148,17 @@ def _floor_macosx(*args: str) -> str:


def expected_wheels(
package_name,
package_version,
manylinux_versions=None,
musllinux_versions=None,
macosx_deployment_target="10.9",
machine_arch=None,
python_abi_tags=None,
include_universal2=False,
single_python=False,
single_arch=False,
):
package_name: str,
package_version: str,
manylinux_versions: list[str] | None = None,
musllinux_versions: list[str] | None = None,
macosx_deployment_target: str = "10.9",
machine_arch: str | None = None,
python_abi_tags: list[str] | None = None,
include_universal2: bool = False,
single_python: bool = False,
single_arch: bool = False,
) -> list[str]:
"""
Returns a list of expected wheels from a run of cibuildwheel.
"""
Expand Down Expand Up @@ -307,7 +311,7 @@ def expected_wheels(
return wheels


def get_macos_version():
def get_macos_version() -> tuple[int, int]:
"""
Returns the macOS major/minor version, as a tuple, e.g. (10, 15) or (11, 0)
Expand All @@ -316,10 +320,10 @@ def get_macos_version():
(11, 2) <= (11, 0) != True
"""
version_str, _, _ = pm.mac_ver()
return tuple(map(int, version_str.split(".")[:2]))
return tuple(map(int, version_str.split(".")[:2])) # type: ignore[return-value]


def skip_if_pyodide(reason: str):
def skip_if_pyodide(reason: str) -> Any:
return pytest.mark.skipif(platform == "pyodide", reason=reason)


Expand All @@ -330,7 +334,7 @@ def invoke_pytest() -> str:
return "pytest"


def arch_name_for_linux(arch: str):
def arch_name_for_linux(arch: str) -> str:
"""
Archs have different names on different platforms, but it's useful to be
able to run linux tests on dev machines. This function translates between
Expand Down
6 changes: 3 additions & 3 deletions unit_test/linux_build_steps_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,13 +53,13 @@ def test_linux_container_split(tmp_path: Path, monkeypatch):
build_steps = list(cibuildwheel.linux.get_build_steps(options, python_configurations))

# helper functions to extract test info
def identifiers(step):
def identifiers(step: cibuildwheel.linux.BuildStep) -> list[str]:
return [c.identifier for c in step.platform_configs]

def before_alls(step):
def before_alls(step: cibuildwheel.linux.BuildStep) -> list[str]:
return [options.build_options(c.identifier).before_all for c in step.platform_configs]

def container_engines(step):
def container_engines(step: cibuildwheel.linux.BuildStep) -> list[OCIContainerEngineConfig]:
return [options.build_options(c.identifier).container_engine for c in step.platform_configs]

pprint(build_steps)
Expand Down
8 changes: 4 additions & 4 deletions unit_test/main_tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,12 +12,12 @@


class ArgsInterceptor:
def __init__(self):
def __init__(self) -> None:
self.call_count = 0
self.args = None
self.kwargs = None
self.args: tuple[object, ...] | None = None
self.kwargs: dict[str, object] | None = None

def __call__(self, *args, **kwargs):
def __call__(self, *args: object, **kwargs: object) -> None:
self.call_count += 1
self.args = args
self.kwargs = kwargs
Expand Down
2 changes: 1 addition & 1 deletion unit_test/main_tests/main_options_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,7 @@ def test_manylinux_images(
assert build_options.manylinux_images is None


def get_default_repair_command(platform):
def get_default_repair_command(platform: str) -> str:
if platform == "linux":
return "auditwheel repair -w {dest_dir} {wheel}"
elif platform == "macos":
Expand Down

0 comments on commit af892b8

Please sign in to comment.