]> git.ipfire.org Git - thirdparty/mkosi.git/commitdiff
Running mypy in the tests/ folder and correcting errors raised by it.
authorgsegatti <gabrielsegatti2@gmail.com>
Tue, 1 Mar 2022 10:46:51 +0000 (02:46 -0800)
committerDaan De Meyer <daan.j.demeyer@gmail.com>
Tue, 1 Mar 2022 15:56:40 +0000 (15:56 +0000)
.github/workflows/ci.yml
tests/conftest.py
tests/pexpect/boot.py
tests/test_backend.py
tests/test_config_parser.py
tests/test_init.py
tests/test_machine.py
tests/test_parse_load_args.py

index 193b27bf1ff5a99d2d966c2d44847cf2f6c060e1..47675bcb2c1af70ff795fcbdf87c2b9e05c239ec 100644 (file)
@@ -32,7 +32,7 @@ jobs:
       run: sh -c '! git grep -P "\\t" "*.py"'
 
     - name: Type Checking (mypy)
-      run: python3 -m mypy mkosi
+      run: python3 -m mypy mkosi/ tests/
 
     - name: Type Checking (pyright)
       run: pyright .
index 266d0d26a0899d7210630223200aa1d6007f7a5b..933da7c2de3f75f2483c9e4000f098c511ed82d4 100644 (file)
@@ -1,44 +1,44 @@
 # SPDX-License-Identifier: LGPL-2.1+
 
+from typing import Any, Dict, List, Set
+
 from tests.test_config_parser import MkosiConfig
 
 
 class DictDiffer:
-    def __init__(self, expected_dict, current_dict):
+    def __init__(self, expected_dict: Dict[str, Any], current_dict: Dict[str, Any]) -> None:
         self.current_dict = current_dict
         self.expected_dict = expected_dict
         self.set_current, self.set_past = set(current_dict.keys()), set(expected_dict.keys())
         self.intersect = self.set_current.intersection(self.set_past)
 
     @property
-    def unexpected(self):
+    def unexpected(self) -> List[str]:
         return [f"{k}={self.current_dict[k]}" for k in self.set_current - self.intersect]
 
     @property
-    def missing(self):
+    def missing(self) -> List[str]:
         return [str(k) for k in self.set_past - self.intersect]
 
     @property
-    def invalid(self):
+    def invalid(self) -> List[str]:
         inva = {o for o in self.intersect if self.expected_dict[o] != self.current_dict[o]}
         return [f"{k}={self.current_dict[k]} (exp: {self.expected_dict[k]})" for k in inva]
 
     @property
-    def valid(self):
+    def valid(self) -> Set[str]:
         return {o for o in self.intersect if self.expected_dict[o] == self.current_dict[o]}
 
 
-def pytest_assertrepr_compare(op, left, right):
-    if not isinstance(left, MkosiConfig):
-        return
+def pytest_assertrepr_compare(op: str, left: MkosiConfig, right: Dict[str, Any]) -> List[str]:
     if not isinstance(right, dict):
-        return
+        return []
     for r in right.values():
         if not isinstance(vars(r), dict):
             return ["Invalid datatype"]
     if op == "==":
 
-        def compare_job_args(job, l_a, r_a):
+        def compare_job_args(job: str, l_a: Dict[str, Any], r_a: Dict[str, Any]) -> None:
             ddiff = DictDiffer(l_a, r_a)
             ret.append(f'Comparing parsed configuration {job} against expected configuration:')
             ret.append("unexpected:")
@@ -63,3 +63,4 @@ def pytest_assertrepr_compare(op, left, right):
             if not left_job in verified_keys:
                 ret.append(f'Missing job: {left_job}')
         return ret
+    return []
index f27da2d6fda7181364b0d9741c110c327323eb5e..6f10d388aabb0e445eeb3c15a54ffd2cf30e39af 100755 (executable)
@@ -1,9 +1,10 @@
 #!/usr/bin/env python3
 
-import pexpect
 import sys
 import time
 
+import pexpect  # type: ignore
+
 
 def run() -> None:
     p = pexpect.spawnu(" ".join(sys.argv[1:]), logfile=sys.stdout, timeout=240)
index 44ddd795bee8754171b875cfac04c619bb91182e..4b356bd8dfff5342b9ca070269e43a2fb29de63c 100644 (file)
@@ -7,14 +7,14 @@ import mkosi.backend as backend
 from mkosi.backend import Distribution, PackageType, set_umask
 
 
-def test_distribution():
+def test_distribution() -> None:
     assert Distribution.fedora.package_type == PackageType.rpm
     assert Distribution.fedora is Distribution.fedora
-    assert Distribution.fedora is not Distribution.debian
+    assert Distribution.fedora.package_type is not Distribution.debian.package_type
     assert str(Distribution.photon) == "photon"
 
 
-def test_set_umask():
+def test_set_umask() -> None:
     with set_umask(0o767):
         tmp1 = os.umask(0o777)
         with set_umask(0o757):
@@ -26,21 +26,21 @@ def test_set_umask():
     assert tmp3 == 0o777
 
 
-def test_workspace():
+def test_workspace() -> None:
     assert backend.workspace(Path("/home/folder/mkosi/mkosi")) == Path("/home/folder/mkosi")
     assert backend.workspace(Path("/home/../home/folder/mkosi/mkosi")) == Path("/home/../home/folder/mkosi")
     assert backend.workspace(Path("/")) == Path("/")
     assert backend.workspace(Path()) == Path()
 
 
-def test_footer_size():
+def test_footer_size() -> None:
     table = backend.PartitionTable()
     assert table.footer_size() == 16896
     assert table.footer_size(max_partitions=64) == 8704
     assert table.footer_size(max_partitions=1) == 1024
     assert table.footer_size(max_partitions=0) == 512
 
-def test_first_partition_offset():
+def test_first_partition_offset() -> None:
     table = backend.PartitionTable()
     table.grain = 4096
 
@@ -74,7 +74,7 @@ def test_first_partition_offset():
     assert table.first_partition_offset() == 131072
 
 
-def test_last_partition_offset():
+def test_last_partition_offset() -> None:
     table = backend.PartitionTable()
     table.grain = 4096
 
@@ -95,7 +95,7 @@ def test_last_partition_offset():
     assert table.last_partition_offset() == 0
 
 
-def test_disk_size():
+def test_disk_size() -> None:
     table = backend.PartitionTable()
     table.grain = 4096
     table.last_partition_sector = 0
index 1ef6582a8450c78986f17429302695017b58563c..a8c8a057e3d5bd15d2c1930008d76e8f161bf2a5 100644 (file)
@@ -5,12 +5,12 @@ import contextlib
 import copy
 import os
 from pathlib import Path
-from typing import Any, Generator, Mapping
+from typing import Any, Dict, Generator, List, Mapping, Optional
 
 import pytest
 
 import mkosi
-from mkosi.backend import Verb
+from mkosi.backend import MkosiException, OutputFormat, SourceFileTransfer, Verb
 
 
 @contextlib.contextmanager
@@ -29,12 +29,14 @@ DEFAULT_JOB_NAME = "default"
 
 class MkosiConfig:
     """Base class for mkosi test and reference configuration generators"""
+    cli_arguments: List[str]
+    reference_config: Dict[str, Any]
 
-    def __init__(self):
+    def __init__(self) -> None:
         self.cli_arguments = []
         self.reference_config = {}
 
-    def add_reference_config(self, job_name=DEFAULT_JOB_NAME):
+    def add_reference_config(self, job_name: str = DEFAULT_JOB_NAME) -> None:
         """create one initial reference configuration
 
         This default reference configuration is equal to the configuration returned by parse_args
@@ -150,7 +152,7 @@ class MkosiConfig:
             "workspace_dir": None,
         }
 
-    def __eq__(self, other: Mapping[str, Any]) -> bool:
+    def __eq__(self, other: Mapping[str, Any]) -> bool: # type: ignore
         """Compare the configuration returned by parse_args against self.reference_config"""
         if len(self.reference_config) != len(other):
             return False
@@ -166,7 +168,7 @@ class MkosiConfig:
                 is_eq = False
         return is_eq
 
-    def _append_list(self, ref_entry, new_args, job_name=DEFAULT_JOB_NAME, separator=","):
+    def _append_list(self, ref_entry: str, new_args: Any, job_name: str = DEFAULT_JOB_NAME, separator: str = ",") -> None:
         """Helper function handling comma separated list as supported by mkosi"""
         args_list = []
         if isinstance(new_args, str):
@@ -185,14 +187,15 @@ class MkosiConfig:
                 self.reference_config[job_name][ref_entry].append(arg)
 
     @staticmethod
-    def write_ini(dname: str, fname: str, config: dict, prio=1000) -> None:
+    def write_ini(dname: str, fname: str, config: Dict[str, Any], prio: int = 1000) -> None:
         """Write mkosi.default(.d/*) files"""
         if not os.path.exists(dname):
             os.makedirs(dname)
         if prio < 1000:
             fname = f"{prio:03d}_{fname}"
         config_parser = configparser.RawConfigParser()
-        config_parser.optionxform = lambda optionstr: str(optionstr)
+        # This is still an open issue on: https://github.com/python/mypy/issues/2427
+        config_parser.optionxform = lambda optionstr: str(optionstr) # type: ignore
 
         # Replace lists in dict before calling config_parser write file
         config_all_normalized = copy.deepcopy(config)
@@ -205,7 +208,7 @@ class MkosiConfig:
         with open(os.path.join(dname, fname), "w") as f_ini:
             config_parser.write(f_ini)
 
-    def _update_ref_from_file(self, mk_config: dict, job_name=DEFAULT_JOB_NAME) -> None:
+    def _update_ref_from_file(self, mk_config: Dict[str, Any], job_name: str = DEFAULT_JOB_NAME) -> None:
         """Update reference_config from a dict as needed to write an ini file using configparser
 
         This is basically a conversion from snake case to - separated format.
@@ -227,7 +230,7 @@ class MkosiConfig:
         if "Output" in mk_config:
             mk_config_output = mk_config["Output"]
             if "Format" in mk_config_output:
-                self.reference_config[job_name]["output_format"] = mkosi.OutputFormat.from_string(
+                self.reference_config[job_name]["output_format"] = OutputFormat.from_string(
                     mk_config_output["Format"]
                 )
             if "ManifestFormat" in mk_config_output:
@@ -405,16 +408,16 @@ class MkosiConfigOne(MkosiConfig):
     test cases.
     """
 
-    def __init__(self):
+    def __init__(self) -> None:
         """Add the default mkosi.default config"""
         super().__init__()
         self.add_reference_config()
 
-    def _prepare_mkosi_default(self, directory: str, config: dict) -> None:
-        __class__.write_ini(directory, "mkosi.default", config)
+    def _prepare_mkosi_default(self, directory: str, config: Dict[str, Any]) -> None:
+        MkosiConfig.write_ini(directory, "mkosi.default", config)
 
-    def _prepare_mkosi_default_d(self, directory: str, config: dict, prio=1000, fname="mkosi.conf") -> None:
-        __class__.write_ini(os.path.join(directory, "mkosi.default.d"), fname, config, prio)
+    def _prepare_mkosi_default_d(self, directory: str, config: Dict[str, Any], prio: int = 1000, fname: str = "mkosi.conf") -> None:
+        MkosiConfig.write_ini(os.path.join(directory, "mkosi.default.d"), fname, config, prio)
 
     def prepare_mkosi_default(self, directory: str) -> None:
         """Generate a mkosi.default defaults file in the working directory"""
@@ -451,7 +454,7 @@ class MkosiConfigSummary(MkosiConfigOne):
     line arguments are in place.
     """
 
-    def __init__(self):
+    def __init__(self) -> None:
         super().__init__()
         for ref_c in self.reference_config.values():
             ref_c["verb"] = Verb.summary
@@ -468,7 +471,7 @@ class MkosiConfigDistro(MkosiConfigOne):
     - --distribution
     """
 
-    def __init__(self, subdir_name=None, alldir_name=None):
+    def __init__(self, subdir_name: str = "", alldir_name: str = "") -> None:
         super().__init__()
         self.subdir_name = subdir_name
         if subdir_name:
@@ -516,7 +519,7 @@ class MkosiConfigDistro(MkosiConfigOne):
 class MkosiConfigDistroDir(MkosiConfigDistro):
     """Same as Distro, but gets --directory passed and sets verb to summary"""
 
-    def __init__(self):
+    def __init__(self) -> None:
         super().__init__("a_sub_dir")
         for ref_c in self.reference_config.values():
             ref_c["verb"] = Verb.summary
@@ -567,7 +570,7 @@ class MkosiConfigManyParams(MkosiConfigOne):
                 "SkeletonTrees": "a/skeleton",
                 "BuildScript": "fancy_build.sh",
                 "BuildSources": "src",
-                "SourceFileTransfer": mkosi.SourceFileTransfer.copy_all,
+                "SourceFileTransfer": SourceFileTransfer.copy_all,
                 "BuildDirectory": "here/we/build",
                 "BuildPackages": ["build-me", "build-me2"],
                 "PostInstallationScript": "post-script.sh",
@@ -633,7 +636,7 @@ class MkosiConfigManyParams(MkosiConfigOne):
                 "SkeletonTrees": "a/skeleton/ubu",
                 "BuildScript": "ubu_build.sh",
                 "BuildSources": "src/ubu",
-                "SourceFileTransfer": mkosi.SourceFileTransfer.copy_git_cached,
+                "SourceFileTransfer": SourceFileTransfer.copy_git_cached,
                 "BuildDirectory": "here/we/build/ubu",
                 "BuildPackages": ["build-me", "build-me2-ubu"],
                 "PostInstallationScript": "post-ubu-script.sh",
@@ -699,7 +702,7 @@ class MkosiConfigManyParams(MkosiConfigOne):
                 "SkeletonTrees": "a/skeleton/debi",
                 "BuildScript": "debi_build.sh",
                 "BuildSources": "src/debi",
-                "SourceFileTransfer": mkosi.SourceFileTransfer.copy_git_cached,
+                "SourceFileTransfer": SourceFileTransfer.copy_git_cached,
                 "BuildDirectory": "here/we/build/debi",
                 "BuildPackages": ["build-me", "build-me2-debi"],
                 "PostInstallationScript": "post-debi-script.sh",
@@ -826,32 +829,32 @@ class MkosiConfigIniLists2(MkosiConfigIniLists1):
 
 # pytest magic: run each test function with each class derived from MkosiConfigOne
 @pytest.fixture(params=MkosiConfigOne.__subclasses__())
-def tested_config(request):
+def tested_config(request: Any) -> Any:
     return request.param()
 
 
-def test_verb_none(tmpdir):
-    with change_cwd(tmpdir.strpath):
+def test_verb_none(tmpdir: Path) -> None:
+    with change_cwd(tmpdir):
         args = mkosi.parse_args([])
         assert args["default"].verb == Verb.build
 
 
-def test_verb_build(tmpdir):
-    with change_cwd(tmpdir.strpath):
+def test_verb_build(tmpdir: Path) -> None:
+    with change_cwd(tmpdir):
         args = mkosi.parse_args(["build"])
         assert args["default"].verb == Verb.build
 
 
-def test_verb_boot_no_cli_args1(tmpdir):
-    with change_cwd(tmpdir.strpath):
+def test_verb_boot_no_cli_args1(tmpdir: Path) -> None:
+    with change_cwd(tmpdir):
         cmdline_ref = ["boot", "--par-for-sub", "--pom", "--for_sub", "1234"]
         args = mkosi.parse_args(cmdline_ref)
         assert args["default"].verb == Verb.boot
         assert args["default"].cmdline == cmdline_ref[1:]
 
 
-def test_verb_boot_no_cli_args2(tmpdir):
-    with change_cwd(tmpdir.strpath):
+def test_verb_boot_no_cli_args2(tmpdir: Path) -> None:
+    with change_cwd(tmpdir):
         cmdline_ref = ["-pa-package", "boot", "--par-for-sub", "--popenssl", "--for_sub", "1234"]
         args = mkosi.parse_args(cmdline_ref)
         assert args["default"].verb == Verb.boot
@@ -859,24 +862,24 @@ def test_verb_boot_no_cli_args2(tmpdir):
         assert args["default"].cmdline == cmdline_ref[2:]
 
 
-def test_verb_boot_no_cli_args3(tmpdir):
-    with change_cwd(tmpdir.strpath):
+def test_verb_boot_no_cli_args3(tmpdir: Path) -> None:
+    with change_cwd(tmpdir):
         cmdline_ref = ["-pa-package", "-p", "another-package", "build"]
         args = mkosi.parse_args(cmdline_ref)
         assert args["default"].verb == Verb.build
         assert args["default"].packages == ["a-package", "another-package"]
 
 
-def test_verb_summary_no_cli_args4(tmpdir):
-    with change_cwd(tmpdir.strpath):
+def test_verb_summary_no_cli_args4(tmpdir: Path) -> None:
+    with change_cwd(tmpdir):
         cmdline_ref = ["-pa-package", "-p", "another-package", "summary"]
         args = mkosi.parse_args(cmdline_ref)
         assert args["default"].verb == Verb.summary
         assert args["default"].packages == ["a-package", "another-package"]
 
 
-def test_verb_shell_cli_args5(tmpdir):
-    with change_cwd(tmpdir.strpath):
+def test_verb_shell_cli_args5(tmpdir: Path) -> None:
+    with change_cwd(tmpdir):
         cmdline_ref = ["-pa-package", "-p", "another-package", "shell", "python3 -foo -bar;", "ls --inode"]
         args = mkosi.parse_args(cmdline_ref)
         assert args["default"].verb == Verb.shell
@@ -884,104 +887,104 @@ def test_verb_shell_cli_args5(tmpdir):
         assert args["default"].cmdline == cmdline_ref[4:]
 
 
-def test_verb_shell_cli_args6(tmpdir):
-    with change_cwd(tmpdir.strpath):
+def test_verb_shell_cli_args6(tmpdir: Path) -> None:
+    with change_cwd(tmpdir):
         cmdline_ref = ["-i", "yes", "summary"]
         args = mkosi.parse_args(cmdline_ref)
         assert args["default"].verb == Verb.summary
         assert args["default"].incremental == True
 
 
-def test_verb_shell_cli_args7(tmpdir):
-    with change_cwd(tmpdir.strpath):
+def test_verb_shell_cli_args7(tmpdir: Path) -> None:
+    with change_cwd(tmpdir):
         cmdline_ref = ["-i", "summary"]
         args = mkosi.parse_args(cmdline_ref)
         assert args["default"].verb == Verb.summary
         assert args["default"].incremental == True
 
 
-def test_builtin(tested_config, tmpdir):
+def test_builtin(tested_config: Any, tmpdir: Path) -> None:
     """Test if builtin config and reference config match"""
-    with change_cwd(tmpdir.strpath):
+    with change_cwd(tmpdir):
         if "--all" in tested_config.cli_arguments:
-            with pytest.raises(mkosi.MkosiException):
+            with pytest.raises(MkosiException):
                 args = mkosi.parse_args(tested_config.cli_arguments)
         else:
             args = mkosi.parse_args(tested_config.cli_arguments)
             assert tested_config == args
 
 
-def test_def(tested_config, tmpdir):
+def test_def(tested_config: Any, tmpdir: Path) -> None:
     """Generate the mkosi.default file only"""
-    with change_cwd(tmpdir.strpath):
-        tested_config.prepare_mkosi_default(tmpdir.strpath)
+    with change_cwd(tmpdir):
+        tested_config.prepare_mkosi_default(tmpdir)
         args = mkosi.parse_args(tested_config.cli_arguments)
         assert tested_config == args
 
 
-def test_def_1(tested_config, tmpdir):
+def test_def_1(tested_config: Any, tmpdir: Path) -> None:
     """Generate the mkosi.default file plus one config file"""
-    with change_cwd(tmpdir.strpath):
-        tested_config.prepare_mkosi_default(tmpdir.strpath)
-        tested_config.prepare_mkosi_default_d_1(tmpdir.strpath)
+    with change_cwd(tmpdir):
+        tested_config.prepare_mkosi_default(tmpdir)
+        tested_config.prepare_mkosi_default_d_1(tmpdir)
         args = mkosi.parse_args(tested_config.cli_arguments)
         assert tested_config == args
 
 
-def test_def_2(tested_config, tmpdir):
+def test_def_2(tested_config: Any, tmpdir: Path) -> None:
     """Generate the mkosi.default file plus another config file"""
-    with change_cwd(tmpdir.strpath):
-        tested_config.prepare_mkosi_default(tmpdir.strpath)
-        tested_config.prepare_mkosi_default_d_2(tmpdir.strpath)
+    with change_cwd(tmpdir):
+        tested_config.prepare_mkosi_default(tmpdir)
+        tested_config.prepare_mkosi_default_d_2(tmpdir)
         args = mkosi.parse_args(tested_config.cli_arguments)
         assert tested_config == args
 
 
-def test_def_1_2(tested_config, tmpdir):
+def test_def_1_2(tested_config: Any, tmpdir: Path) -> None:
     """Generate the mkosi.default file plus two config files"""
-    with change_cwd(tmpdir.strpath):
-        tested_config.prepare_mkosi_default(tmpdir.strpath)
-        tested_config.prepare_mkosi_default_d_1(tmpdir.strpath)
-        tested_config.prepare_mkosi_default_d_2(tmpdir.strpath)
+    with change_cwd(tmpdir):
+        tested_config.prepare_mkosi_default(tmpdir)
+        tested_config.prepare_mkosi_default_d_1(tmpdir)
+        tested_config.prepare_mkosi_default_d_2(tmpdir)
         args = mkosi.parse_args(tested_config.cli_arguments)
         assert tested_config == args
 
 
-def test_def_args(tested_config, tmpdir):
+def test_def_args(tested_config: Any, tmpdir: Path) -> None:
     """Generate the mkosi.default plus command line arguments"""
-    with change_cwd(tmpdir.strpath):
+    with change_cwd(tmpdir):
         tested_config.prepare_args()
         args = mkosi.parse_args(tested_config.cli_arguments)
         assert tested_config == args
 
 
-def test_def_1_args(tested_config, tmpdir):
+def test_def_1_args(tested_config: Any, tmpdir: Path) -> None:
     """Generate the mkosi.default plus a config file plus command line arguments"""
-    with change_cwd(tmpdir.strpath):
-        tested_config.prepare_mkosi_default(tmpdir.strpath)
-        tested_config.prepare_mkosi_default_d_1(tmpdir.strpath)
+    with change_cwd(tmpdir):
+        tested_config.prepare_mkosi_default(tmpdir)
+        tested_config.prepare_mkosi_default_d_1(tmpdir)
         tested_config.prepare_args()
         args = mkosi.parse_args(tested_config.cli_arguments)
         assert tested_config == args
 
 
-def test_def_1_2_args(tested_config, tmpdir):
+def test_def_1_2_args(tested_config: Any, tmpdir: Path) -> None:
     """Generate the mkosi.default plus two config files plus command line arguments"""
-    with change_cwd(tmpdir.strpath):
-        tested_config.prepare_mkosi_default(tmpdir.strpath)
-        tested_config.prepare_mkosi_default_d_1(tmpdir.strpath)
-        tested_config.prepare_mkosi_default_d_2(tmpdir.strpath)
+    with change_cwd(tmpdir):
+        tested_config.prepare_mkosi_default(tmpdir)
+        tested_config.prepare_mkosi_default_d_1(tmpdir)
+        tested_config.prepare_mkosi_default_d_2(tmpdir)
         tested_config.prepare_args()
         args = mkosi.parse_args(tested_config.cli_arguments)
         assert tested_config == args
 
 
-def test_def_1_2_argssh(tested_config, tmpdir):
+def test_def_1_2_argssh(tested_config: Any, tmpdir: Path) -> None:
     """Generate the mkosi.default plus two config files plus short command line arguments"""
-    with change_cwd(tmpdir.strpath):
-        tested_config.prepare_mkosi_default(tmpdir.strpath)
-        tested_config.prepare_mkosi_default_d_1(tmpdir.strpath)
-        tested_config.prepare_mkosi_default_d_2(tmpdir.strpath)
+    with change_cwd(tmpdir):
+        tested_config.prepare_mkosi_default(tmpdir)
+        tested_config.prepare_mkosi_default_d_1(tmpdir)
+        tested_config.prepare_mkosi_default_d_2(tmpdir)
         tested_config.prepare_args_short()
         args = mkosi.parse_args(tested_config.cli_arguments)
         assert tested_config == args
@@ -998,7 +1001,7 @@ class MkosiConfigAll(MkosiConfig):
 class MkosiConfigAllHost(MkosiConfigAll):
     """Test --all option with two simple configs"""
 
-    def __init__(self):
+    def __init__(self) -> None:
         """Add two default mkosi.default configs"""
         super().__init__()
         for hostname in ["test1.example.org", "test2.example.org"]:
@@ -1008,7 +1011,7 @@ class MkosiConfigAllHost(MkosiConfigAll):
             self.reference_config[job_name]["hostname"] = hostname
         self.cli_arguments = ["--all", "build"]
 
-    def prepare_mkosi_files(self, directory: str, all_directory=None) -> None:
+    def prepare_mkosi_files(self, directory: str, all_directory: Optional[Path] = None) -> None:
         if all_directory is None:
             all_dir = os.path.abspath("mkosi.files")
         else:
@@ -1016,7 +1019,7 @@ class MkosiConfigAllHost(MkosiConfigAll):
 
         for job_name, config in self.reference_config.items():
             mk_config = {"Output": {"Hostname": config["hostname"]}}
-            __class__.write_ini(all_dir, job_name, mk_config)
+            MkosiConfig.write_ini(all_dir, job_name, mk_config)
 
         if all_directory:
             self.cli_arguments[0:0] = ["--all-directory", "all_dir"]
@@ -1024,13 +1027,13 @@ class MkosiConfigAllHost(MkosiConfigAll):
 
 # pytest magic: run each test function with each class derived from MkosiConfigAll
 @pytest.fixture(params=MkosiConfigAll.__subclasses__())
-def tested_config_all(request):
+def tested_config_all(request: Any) -> Any:
     return request.param()
 
 
-def test_all_1(tested_config_all, tmpdir):
+def test_all_1(tested_config_all: Any, tmpdir: Path) -> None:
     """Generate the mkosi.default plus two config files plus short command line arguments"""
-    with change_cwd(tmpdir.strpath):
-        tested_config_all.prepare_mkosi_files(tmpdir.strpath)
+    with change_cwd(tmpdir):
+        tested_config_all.prepare_mkosi_files(tmpdir)
         args = mkosi.parse_args(tested_config_all.cli_arguments)
         assert tested_config_all == args
index 2bfe6d301df3d522a5ba2ba990549352da2a8b01..019a12ce29fdcd3b4acc07c4f43f2a367ab8a981 100644 (file)
@@ -2,12 +2,13 @@
 
 import filecmp
 from pathlib import Path
+
 import pytest
 
 import mkosi
 
 
-def test_fedora_release_cmp():
+def test_fedora_release_cmp() -> None:
     assert mkosi.fedora_release_cmp("rawhide", "rawhide") == 0
     assert mkosi.fedora_release_cmp("32", "32") == 0
     assert mkosi.fedora_release_cmp("33", "32") > 0
@@ -18,7 +19,7 @@ def test_fedora_release_cmp():
         mkosi.fedora_release_cmp("literal", "rawhide")
 
 
-def test_strip_suffixes():
+def test_strip_suffixes() -> None:
     assert mkosi.strip_suffixes(Path("home/test.zstd")) == Path("home/test")
     assert mkosi.strip_suffixes(Path("home/test.xz")) == Path("home/test")
     assert mkosi.strip_suffixes(Path("home/test.raw")) == Path("home/test")
@@ -29,7 +30,7 @@ def test_strip_suffixes():
     assert mkosi.strip_suffixes(Path("home.xz/test")) == Path("home.xz/test")
     assert mkosi.strip_suffixes(Path("home.xz/test.txt")) == Path("home.xz/test.txt")
 
-def test_copy_file(tmpdir):
+def test_copy_file(tmpdir: Path) -> None:
         dir_path = Path(tmpdir)
         file_1 = Path(dir_path) / "file_1.txt"
         file_2 = Path(dir_path) / "file_2.txt"
index 185153e9c62713bce4213012938481cb1c8cd6cb..2ac6d517eea88534b975b8d077685c25238c1fc6 100644 (file)
@@ -8,7 +8,6 @@ import pytest
 import mkosi.machine as machine
 from mkosi.backend import MkosiException
 
-
 pytestmark = [
     pytest.mark.integration,
     pytest.mark.parametrize("verb", ["boot", "qemu"]),
index 0052243a35840d81c3172afb1e697614c045004e..4e102aa00e1625c98e6af612066263542253ecd4 100644 (file)
@@ -7,7 +7,7 @@ import uuid
 from contextlib import contextmanager
 from os import chdir, getcwd
 from pathlib import Path
-from typing import List, Optional
+from typing import Iterator, List, Optional
 
 import pytest
 
@@ -19,7 +19,7 @@ def parse(argv: Optional[List[str]] = None) -> MkosiArgs:
     return mkosi.load_args(mkosi.parse_args(argv)["default"])
 
 @contextmanager
-def cd_temp_dir():
+def cd_temp_dir() -> Iterator[None]:
     old_dir = getcwd()
 
     with tempfile.TemporaryDirectory() as tmp_dir:
@@ -29,7 +29,7 @@ def cd_temp_dir():
         finally:
             chdir(old_dir)
 
-def test_parse_load_verb():
+def test_parse_load_verb() -> None:
     assert parse(["build"]).verb == Verb.build
     assert parse(["clean"]).verb == Verb.clean
     with pytest.raises(SystemExit):
@@ -44,13 +44,13 @@ def test_parse_load_verb():
     with pytest.raises(SystemExit):
         parse(["invalid"])
 
-def test_os_distribution():
+def test_os_distribution() -> None:
     for dist in Distribution:
         assert parse(["-d", dist.name]).distribution == dist
 
-    with pytest.raises((argparse.ArgumentError, SystemExit)):
+    with pytest.raises(tuple((argparse.ArgumentError, SystemExit))):
         parse(["-d", "invalidDistro"])
-    with pytest.raises((argparse.ArgumentError, SystemExit)):
+    with pytest.raises(tuple((argparse.ArgumentError, SystemExit))):
         parse(["-d"])
 
     for dist in Distribution:
@@ -59,7 +59,7 @@ def test_os_distribution():
             config.write_text(f"[Distribution]\nDistribution={dist}")
             assert parse([]).distribution == dist
 
-def test_machine_id():
+def test_machine_id() -> None:
     id = uuid.uuid4().hex
     load_args = parse(["--machine-id", id])
 
@@ -68,7 +68,7 @@ def test_machine_id():
 
     with pytest.raises(MkosiException):
         parse(["--machine-id", "notValidKey"])
-    with pytest.raises((argparse.ArgumentError, SystemExit)):
+    with pytest.raises(tuple((argparse.ArgumentError, SystemExit))):
         parse(["--machine-id"])
 
     with cd_temp_dir():
@@ -84,7 +84,7 @@ def test_machine_id():
         with pytest.raises(MkosiException):
             parse([])
 
-def test_hostname():
+def test_hostname() -> None:
     assert parse(["--hostname", "name"]).hostname == "name"
     with pytest.raises(SystemExit):
         parse(["--hostname", "name", "additional_name"])
@@ -102,7 +102,7 @@ def test_hostname():
         config = Path("hostname.txt")
         assert parse([]).hostname == ""
 
-def test_centos_brtfs():
+def test_centos_brtfs() -> None:
     with cd_temp_dir():
         config = Path("mkosi.default")
         for dist in (Distribution.centos, Distribution.centos_epel):
@@ -138,7 +138,7 @@ def test_centos_brtfs():
                 with pytest.raises(MkosiException, match=".CentOS.*unified.*kernel"):
                     parse([])
 
-def test_shell_boot():
+def test_shell_boot() -> None:
     with pytest.raises(MkosiException, match=".boot.*tar"):
         parse(["--format", "tar", "boot"])
 
@@ -151,7 +151,7 @@ def test_shell_boot():
     with pytest.raises(MkosiException, match=".boot.*qcow2"):
         parse(["--format", "gpt_xfs", "--qcow2", "boot"])
 
-def test_compression():
+def test_compression() -> None:
     assert parse(["--format", "gpt_squashfs"]).compress
 
     with pytest.raises(MkosiException, match=".*compression.*squashfs"):