Skip to content

Commit

Permalink
Update typehints within ./tests (#973)
Browse files Browse the repository at this point in the history
  • Loading branch information
ogenstad authored Sep 23, 2024
1 parent 8d8001e commit 175e6f0
Show file tree
Hide file tree
Showing 14 changed files with 215 additions and 156 deletions.
48 changes: 42 additions & 6 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -74,8 +74,48 @@ warn_return_any = true
warn_redundant_casts = true

[[tool.mypy.overrides]]
module = "tests.*"
ignore_errors = true
module = "tests.conftest"
disable_error_code = [
"return-value",
]

[[tool.mypy.overrides]]
module = "tests.core.test_InitNornir"
disable_error_code = [
"arg-type",
]

[[tool.mypy.overrides]]
module = "tests.core.test_filter"
disable_error_code = [
"arg-type",
"assignment",
"operator"
]

[[tool.mypy.overrides]]
module = "tests.core.test_inventory"
disable_error_code = [
"arg-type",
"index"
]

[[tool.mypy.overrides]]
module = "tests.core.test_processors"
disable_error_code = [
"assignment",
"index",
"var-annotated"
]

[[tool.mypy.overrides]]
module = "tests.wrapper"
disable_error_code = [
"import-untyped",
"misc",
"no-any-return"
]


[tool.ruff]
line-length = 100
Expand Down Expand Up @@ -232,10 +272,6 @@ max-returns = 11
# like this so that we can reactivate them one by one. Alternatively ignored after further #
# investigation if they are deemed to not make sense. #
##################################################################################################
"ANN001", # Missing type annotation for function argument
"ANN002", # Missing type annotation for `*args`
"ANN003", # Missing type annotation for `**kwargs`
"ANN201", # Missing return type annotation for public function
"ARG001", # Unused function argument
"B007", # Loop control variable `host` not used within loop body
"C414", # Unnecessary `list` call within `sorted()`
Expand Down
10 changes: 5 additions & 5 deletions tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,11 +23,11 @@
global_data = GlobalState(dry_run=True)


def inventory_from_yaml():
def inventory_from_yaml() -> Inventory:
dir_path = os.path.dirname(os.path.realpath(__file__))
yml = ruamel.yaml.YAML(typ="safe")

def get_connection_options(data) -> Dict[str, ConnectionOptions]:
def get_connection_options(data: Dict[str, Any]) -> Dict[str, ConnectionOptions]:
cp = {}
for cn, c in data.items():
cp[cn] = ConnectionOptions(
Expand Down Expand Up @@ -119,17 +119,17 @@ def run(self, task: Task, hosts: List[Host]) -> AggregatedResult:


@pytest.fixture(scope="session", autouse=True)
def inv(request):
def inv() -> Inventory:
return inventory_from_yaml()


@pytest.fixture(scope="session", autouse=True)
def nornir(request):
def nornir() -> Nornir:
"""Initializes nornir"""
return Nornir(inventory=inventory_from_yaml(), runner=SerialRunner(), data=global_data)


@pytest.fixture(scope="function", autouse=True)
def reset_data():
def reset_data() -> None:
global_data.dry_run = True
global_data.reset_failed_hosts()
37 changes: 19 additions & 18 deletions tests/core/test_InitNornir.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import logging
import logging.config
import os
from typing import Any, Dict

import pytest

Expand Down Expand Up @@ -36,19 +37,19 @@
}


def transform_func(host):
def transform_func(host: Host) -> None:
host["processed_by_transform_function"] = True


def transform_func_with_options(host, a):
def transform_func_with_options(host: Host, a: Any) -> None:
host["a"] = a


class InventoryTest:
def __init__(self, *args, **kwargs) -> None:
def __init__(self, *args: Any, **kwargs: Dict[str, Any]) -> None:
pass

def load(self):
def load(self) -> Inventory:
return Inventory(
hosts=Hosts({"h1": Host("h1"), "h2": Host("h2"), "h3": Host("h3")}),
groups=Groups({"g1": Group("g1")}),
Expand All @@ -62,14 +63,14 @@ def load(self):


class Test:
def test_InitNornir_bare(self):
def test_InitNornir_bare(self) -> None:
os.chdir("tests/inventory_data/")
nr = InitNornir()
os.chdir("../../")
assert len(nr.inventory.hosts)
assert len(nr.inventory.groups)

def test_InitNornir_defaults(self):
def test_InitNornir_defaults(self) -> None:
os.chdir("tests/inventory_data/")
nr = InitNornir(inventory={"plugin": "inventory-test"})
os.chdir("../../")
Expand All @@ -78,13 +79,13 @@ def test_InitNornir_defaults(self):
assert len(nr.inventory.hosts)
assert len(nr.inventory.groups)

def test_InitNornir_file(self):
def test_InitNornir_file(self) -> None:
nr = InitNornir(config_file=os.path.join(dir_path, "a_config.yaml"))
assert not nr.data.dry_run
assert len(nr.inventory.hosts)
assert len(nr.inventory.groups)

def test_InitNornir_programmatically(self):
def test_InitNornir_programmatically(self) -> None:
nr = InitNornir(
core={"raise_on_error": True},
inventory={
Expand All @@ -100,14 +101,14 @@ def test_InitNornir_programmatically(self):
assert len(nr.inventory.hosts)
assert len(nr.inventory.groups)

def test_InitNornir_override_partial_section(self):
def test_InitNornir_override_partial_section(self) -> None:
nr = InitNornir(
config_file=os.path.join(dir_path, "a_config.yaml"),
core={"raise_on_error": True},
)
assert nr.config.core.raise_on_error

def test_InitNornir_combined(self):
def test_InitNornir_combined(self) -> None:
nr = InitNornir(
config_file=os.path.join(dir_path, "a_config.yaml"),
core={"raise_on_error": True},
Expand All @@ -117,7 +118,7 @@ def test_InitNornir_combined(self):
assert len(nr.inventory.hosts)
assert len(nr.inventory.groups)

def test_InitNornir_different_transform_function_by_string(self):
def test_InitNornir_different_transform_function_by_string(self) -> None:
nr = InitNornir(
config_file=os.path.join(dir_path, "a_config.yaml"),
inventory={
Expand All @@ -132,7 +133,7 @@ def test_InitNornir_different_transform_function_by_string(self):
for host in nr.inventory.hosts.values():
assert host["processed_by_transform_function"]

def test_InitNornir_different_transform_function_by_string_with_options(self):
def test_InitNornir_different_transform_function_by_string_with_options(self) -> None:
nr = InitNornir(
config_file=os.path.join(dir_path, "a_config.yaml"),
inventory={
Expand All @@ -148,7 +149,7 @@ def test_InitNornir_different_transform_function_by_string_with_options(self):
for host in nr.inventory.hosts.values():
assert host["a"] == 1

def test_InitNornir_different_transform_function_by_string_with_bad_options(self):
def test_InitNornir_different_transform_function_by_string_with_bad_options(self) -> None:
with pytest.raises(TypeError):
nr = InitNornir(
config_file=os.path.join(dir_path, "a_config.yaml"),
Expand Down Expand Up @@ -186,7 +187,7 @@ def cleanup(cls) -> None:
def teardown_class(cls) -> None:
cls.cleanup()

def test_InitNornir_logging_defaults(self):
def test_InitNornir_logging_defaults(self) -> None:
self.cleanup()
InitNornir(
config_file=os.path.join(dir_path, "a_config.yaml"),
Expand All @@ -197,7 +198,7 @@ def test_InitNornir_logging_defaults(self):
assert len(nornir_logger.handlers) == 1
assert isinstance(nornir_logger.handlers[0], logging.FileHandler)

def test_InitNornir_logging_to_console(self):
def test_InitNornir_logging_to_console(self) -> None:
self.cleanup()
InitNornir(
config_file=os.path.join(dir_path, "a_config.yaml"),
Expand All @@ -210,7 +211,7 @@ def test_InitNornir_logging_to_console(self):
assert any(isinstance(handler, logging.FileHandler) for handler in nornir_logger.handlers)
assert any(isinstance(handler, logging.StreamHandler) for handler in nornir_logger.handlers)

def test_InitNornir_logging_disabled(self):
def test_InitNornir_logging_disabled(self) -> None:
self.cleanup()
InitNornir(
config_file=os.path.join(dir_path, "a_config.yaml"),
Expand All @@ -220,7 +221,7 @@ def test_InitNornir_logging_disabled(self):

assert nornir_logger.level == logging.NOTSET

def test_InitNornir_logging_basicConfig(self):
def test_InitNornir_logging_basicConfig(self) -> None:
self.cleanup()
logging.basicConfig()
with pytest.warns(ConflictingConfigurationWarning):
Expand All @@ -231,7 +232,7 @@ def test_InitNornir_logging_basicConfig(self):
assert nornir_logger.level == logging.INFO
assert nornir_logger.hasHandlers()

def test_InitNornir_logging_dictConfig(self):
def test_InitNornir_logging_dictConfig(self) -> None:
self.cleanup()
logging.config.dictConfig(LOGGING_DICT)
with pytest.warns(ConflictingConfigurationWarning):
Expand Down
18 changes: 9 additions & 9 deletions tests/core/test_configuration.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@


class Test:
def test_config_defaults(self):
def test_config_defaults(self) -> None:
c = Config()
assert c.dict() == {
"core": {"raise_on_error": False},
Expand All @@ -33,7 +33,7 @@ def test_config_defaults(self):
"user_defined": {},
}

def test_config_from_dict_defaults(self):
def test_config_from_dict_defaults(self) -> None:
c = Config.from_dict()
assert c.dict() == {
"core": {"raise_on_error": False},
Expand All @@ -56,7 +56,7 @@ def test_config_from_dict_defaults(self):
"user_defined": {},
}

def test_config_basic(self):
def test_config_basic(self) -> None:
c = Config.from_dict(
inventory={"plugin": "an-inventory"},
runner={"plugin": "serial", "options": {"a": 1, "b": 2}},
Expand Down Expand Up @@ -84,14 +84,14 @@ def test_config_basic(self):
"user_defined": {"my_opt": True},
}

def test_configuration_file_override_argument(self):
def test_configuration_file_override_argument(self) -> None:
config = Config.from_file(
os.path.join(dir_path, "config.yaml"),
core={"raise_on_error": True},
)
assert config.core.raise_on_error

def test_configuration_file_override_env(self):
def test_configuration_file_override_env(self) -> None:
os.environ["NORNIR_CORE_RAISE_ON_ERROR"] = "1"
os.environ["NORNIR_SSH_CONFIG_FILE"] = "/user/ssh_config"
config = Config.from_dict(inventory={"plugin": "an-inventory"})
Expand All @@ -100,22 +100,22 @@ def test_configuration_file_override_env(self):
os.environ.pop("NORNIR_CORE_RAISE_ON_ERROR")
os.environ.pop("NORNIR_SSH_CONFIG_FILE")

def test_configuration_bool_env(self):
def test_configuration_bool_env(self) -> None:
os.environ["NORNIR_CORE_RAISE_ON_ERROR"] = "0"
config = Config.from_dict(inventory={"plugin": "an-inventory"})
assert not config.core.raise_on_error

def test_get_user_defined_from_file(self):
def test_get_user_defined_from_file(self) -> None:
config = Config.from_file(os.path.join(dir_path, "config.yaml"))
assert config.user_defined["asd"] == "qwe"

def test_order_of_resolution_config_higher_than_env(self):
def test_order_of_resolution_config_higher_than_env(self) -> None:
os.environ["NORNIR_CORE_RAISE_ON_ERROR"] = "1"
config = Config.from_file(os.path.join(dir_path, "config.yaml"))
os.environ.pop("NORNIR_CORE_RAISE_ON_ERROR")
assert config.core.raise_on_error is False

def test_order_of_resolution_code_is_higher_than_env(self):
def test_order_of_resolution_code_is_higher_than_env(self) -> None:
os.environ["NORNIR_CORE_RAISE_ON_ERROR"] = "0"
config = Config.from_file(
os.path.join(dir_path, "config.yaml"), core={"raise_on_error": True}
Expand Down
Loading

0 comments on commit 175e6f0

Please sign in to comment.