Skip to content

Commit

Permalink
More types (#1701)
Browse files Browse the repository at this point in the history
ssbarnea authored Feb 28, 2024

Verified

This commit was created on GitHub.com and signed with GitHub’s verified signature.
1 parent 7dd9023 commit e96635d
Showing 12 changed files with 91 additions and 60 deletions.
19 changes: 11 additions & 8 deletions src/ansible_navigator/actions/open_file.py
Original file line number Diff line number Diff line change
@@ -9,6 +9,7 @@
from collections.abc import Callable
from pathlib import Path
from re import Pattern
from types import TracebackType
from typing import Any

from ansible_navigator.app_public import AppPublic
@@ -29,11 +30,13 @@
class SuspendCurses:
"""Context Manager to temporarily leave curses mode."""

def __enter__(self):
def __enter__(self) -> None:
"""Close the curses window."""
curses.endwin()

def __exit__(self, exc_type, exc_val, traceback):
def __exit__(
self, exc_type: BaseException | None, exc_val: BaseException, traceback: TracebackType
) -> None:
"""Open the curses window.
:param exc_type: The exception class
@@ -63,8 +66,8 @@ def _transform_menu(
self,
menu: Menu,
menu_filter: Callable[..., Pattern[str] | None],
serialization_format=SerializationFormat | None,
) -> list[dict[Any, Any]]:
serialization_format: SerializationFormat | None,
) -> list[dict[Any, Any] | ContentBase[Any]]:
"""Convert a menu into structured data.
:param menu: The current menu showing
@@ -73,9 +76,9 @@ def _transform_menu(
:returns: The menu converted to a structured data
"""
self._logger.debug("menu is showing, open that")
menu_entries = []
menu_entries: list[dict[Any, Any] | ContentBase[Any]] = []
for entry in menu.current:
if isinstance(entry, ContentBase):
if isinstance(entry, ContentBase) and serialization_format is not None:
entry = entry.asdict(
content_view=ContentView.FULL,
serialization_format=serialization_format,
@@ -90,7 +93,7 @@ def _transform_menu(
menu_entries = [
e
for e in menu_entries
if menu_filter_result.search(" ".join(str(v) for v in e.values()))
if menu_filter_result.search(" ".join(str(v) for v in e.values())) # type: ignore[union-attr]
]
return menu_entries

@@ -118,7 +121,7 @@ def _open_a_file(
line_number: int,
editor_console: bool,
editor_command: str,
):
) -> None:
"""Open a file using the editor.
:param file_name: The name of the file to open
7 changes: 5 additions & 2 deletions src/ansible_navigator/configuration_subsystem/parser.py
Original file line number Diff line number Diff line change
@@ -2,6 +2,8 @@

from __future__ import annotations

import argparse

from argparse import SUPPRESS
from argparse import ArgumentParser
from argparse import HelpFormatter
@@ -10,6 +12,7 @@

from .definitions import ApplicationConfiguration
from .definitions import Constants as C
from .definitions import SettingsEntry


class Parser:
@@ -71,7 +74,7 @@ def generate_argument(entry) -> tuple[Any, Any, dict[str, Any]]:

return entry.cli_parameters.short, long, kwargs

def _add_parser(self, group, entry) -> None:
def _add_parser(self, group: argparse._ArgumentGroup, entry: SettingsEntry) -> None:
"""Add a parser to the subparsers.
:param group: The group to add the parser to
@@ -189,7 +192,7 @@ def _format_action_invocation(self, action):
msg = "Too many option strings"
raise ValueError(msg)

def _format_usage(self, usage, actions, groups, prefix):
def _format_usage(self, usage: Any, actions: Any, groups: Any, prefix) -> str:
"""Format the usage.
:param usage: The usage
9 changes: 5 additions & 4 deletions src/ansible_navigator/utils/definitions.py
Original file line number Diff line number Diff line change
@@ -54,27 +54,28 @@ class ExitPrefix(Enum):
WARNING = "Warning"

@classmethod
def _longest_name(cls):
def _longest_name(cls) -> int:
"""Return the longest exit message prefix.
:returns: The longest exit message prefix
"""
return max(len(member.value) for member in cls)

@classmethod
def longest_formatted(cls):
def longest_formatted(cls) -> int:
"""Return the longest exit message prefix.
:returns: The longest exit message prefix
"""
return max(len(str(member)) for member in cls)

def __str__(self):
def __str__(self) -> str:
"""Return the exit message prefix as a string.
:returns: The exit message prefix as a string
"""
return f"{' ' * (self._longest_name() - len(self.name))}{self.name.capitalize()}: "
name_len = self._longest_name()
return f"{' ' * (name_len - len(self.name))}{self.name.capitalize()}: "


@dataclass
28 changes: 15 additions & 13 deletions tests/integration/actions/replay/base.py
Original file line number Diff line number Diff line change
@@ -3,6 +3,9 @@
import difflib
import os

from collections.abc import Generator
from pathlib import Path

import pytest

from tests.defaults import FIXTURES_DIR
@@ -23,33 +26,32 @@ class BaseClass:

@staticmethod
@pytest.fixture(scope="module", name="tmux_session")
def fixture_tmux_session(request):
def fixture_tmux_session(request: pytest.FixtureRequest) -> Generator[TmuxSession, None, None]:
"""Tmux fixture for this module.
:param request: A fixture providing details about the test caller
:yields: Tmux session
"""
params = {
"config_path": TEST_CONFIG_FILE,
"pane_height": "100",
"setup_commands": [
with TmuxSession(
config_path=Path(TEST_CONFIG_FILE),
pane_height=100,
setup_commands=[
"export ANSIBLE_DEVEL_WARNING=False",
"export ANSIBLE_DEPRECATION_WARNINGS=False",
],
"request": request,
}
with TmuxSession(**params) as tmux_session:
request=request,
) as tmux_session:
yield tmux_session

def test(
self,
request: pytest.FixtureRequest,
tmux_session: TmuxSession,
index,
user_input,
comment,
search_within_response,
):
index: int,
user_input: str,
comment: str,
search_within_response: str,
) -> None:
# pylint: disable=too-many-arguments
"""Run the tests for replay, mode and ``ee`` set in child class.
16 changes: 11 additions & 5 deletions tests/integration/actions/run/base.py
Original file line number Diff line number Diff line change
@@ -5,6 +5,8 @@
import difflib
import os

from collections.abc import Generator

import pytest

from tests.defaults import FIXTURES_DIR
@@ -13,6 +15,7 @@
from tests.integration._interactions import SearchFor
from tests.integration._interactions import UiTestStep
from tests.integration._tmux_session import TmuxSession
from tests.integration._tmux_session import TmuxSessionKwargs


# run playbook
@@ -48,15 +51,15 @@ class BaseClass:

@staticmethod
@pytest.fixture(scope="module", name="tmux_session")
def fixture_tmux_session(request):
def fixture_tmux_session(request: pytest.FixtureRequest) -> Generator[TmuxSession, None, None]:
"""Generate a tmux fixture for this module.
:param request: A fixture providing details about the test caller
:yields: A tmux session
"""
params = {
"pane_height": "1000",
"pane_width": "500",
params: TmuxSessionKwargs = {
"pane_height": 1000,
"pane_width": 500,
"setup_commands": [
"export ANSIBLE_DEVEL_WARNING=False",
"export ANSIBLE_DEPRECATION_WARNINGS=False",
@@ -66,13 +69,16 @@ def fixture_tmux_session(request):
with TmuxSession(**params) as tmux_session:
yield tmux_session

def test(self, request: pytest.FixtureRequest, tmux_session: TmuxSession, step):
def test(
self, request: pytest.FixtureRequest, tmux_session: TmuxSession, step: UiTestStep
) -> None:
"""Run the tests for run, mode and ``ee`` set in child class.
:param request: A fixture providing details about the test caller
:param tmux_session: The tmux session to use
:param step: The commands to issue and content to look for
"""
search_within_response: str | list[str]
if step.search_within_response is SearchFor.HELP:
search_within_response = ":help help"
elif step.search_within_response is SearchFor.PROMPT:
2 changes: 1 addition & 1 deletion tests/integration/actions/run/test_stdout_tmux.py
Original file line number Diff line number Diff line change
@@ -124,7 +124,7 @@ class ShellCommand(UiTestStep):
steps = add_indices(stdout_tests)


def step_id(value) -> str:
def step_id(value: ShellCommand) -> str:
"""Return the test id from the test step object.
:param value: The parameterized value from which the id will be generated
6 changes: 4 additions & 2 deletions tests/integration/actions/run_unicode/base.py
Original file line number Diff line number Diff line change
@@ -5,6 +5,8 @@
import difflib
import os

from collections.abc import Generator

import pytest

from tests.defaults import FIXTURES_DIR
@@ -42,7 +44,7 @@ class BaseClass:

@staticmethod
@pytest.fixture(scope="module", name="tmux_session")
def fixture_tmux_session(request: pytest.FixtureRequest):
def fixture_tmux_session(request: pytest.FixtureRequest) -> Generator[TmuxSession, None, None]:
"""Tmux fixture for this module.
:param request: The request for this fixture from a test
@@ -65,7 +67,7 @@ def test(
request: pytest.FixtureRequest,
tmux_session: TmuxSession,
step: UiTestStep,
):
) -> None:
"""Run the tests for run, mode and ``ee`` set in child class.
:param request: The request for a test
2 changes: 1 addition & 1 deletion tests/integration/actions/run_unicode/test_stdout_tmux.py
Original file line number Diff line number Diff line change
@@ -49,7 +49,7 @@ class ShellCommand(UiTestStep):
steps = add_indices(stdout_tests)


def step_id(value) -> str:
def step_id(value: ShellCommand) -> str:
"""Return a test id for the test step object.
:param value: The data to generate the id from
23 changes: 14 additions & 9 deletions tests/integration/actions/settings/base.py
Original file line number Diff line number Diff line change
@@ -3,6 +3,8 @@
import difflib
import os

from collections.abc import Generator

import pytest

from tests.defaults import FIXTURES_DIR
@@ -45,25 +47,28 @@ class BaseClass:
PANE_WIDTH = 300

@pytest.fixture(scope="module", name="tmux_session")
def fixture_tmux_session(self, request):
def fixture_tmux_session(
self, request: pytest.FixtureRequest
) -> Generator[TmuxSession, None, None]:
"""Tmux fixture for this module.
:param request: Used for generating test id
:yields: tmux_session object
"""
params = {
"setup_commands": [
with TmuxSession(
setup_commands=[
"export ANSIBLE_NAVIGATOR_ANSIBLE_RUNNER_TIMEOUT=42",
"export PAGER=cat",
],
"request": request,
"pane_height": self.PANE_HEIGHT,
"pane_width": self.PANE_WIDTH,
}
with TmuxSession(**params) as tmux_session:
request=request,
pane_height=self.PANE_HEIGHT,
pane_width=self.PANE_WIDTH,
) as tmux_session:
yield tmux_session

def test(self, request: pytest.FixtureRequest, tmux_session: TmuxSession, step):
def test(
self, request: pytest.FixtureRequest, tmux_session: TmuxSession, step: UiTestStep
) -> None:
# pylint: disable=too-many-locals
"""Run the tests for ``settings``, mode and ``ee`` set in child class.
22 changes: 13 additions & 9 deletions tests/integration/actions/stdout/base.py
Original file line number Diff line number Diff line change
@@ -3,12 +3,16 @@
import difflib
import os

from collections.abc import Generator
from pathlib import Path

import pytest

from tests.defaults import FIXTURES_DIR
from tests.integration._common import retrieve_fixture_for_step
from tests.integration._common import update_fixtures
from tests.integration._tmux_session import TmuxSession
from tests.integration._tmux_session import TmuxSessionKwargs


TEST_FIXTURE_DIR = os.path.join(FIXTURES_DIR, "integration/actions/stdout")
@@ -23,15 +27,15 @@ class BaseClass:

@staticmethod
@pytest.fixture(scope="module", name="tmux_session")
def fixture_tmux_session(request):
def fixture_tmux_session(request: pytest.FixtureRequest) -> Generator[TmuxSession, None, None]:
"""Tmux fixture for this module.
:param request: A fixture providing details about the test caller
:yields: Tmux session
"""
params = {
"config_path": TEST_CONFIG_FILE,
"pane_height": "100",
params: TmuxSessionKwargs = {
"config_path": Path(TEST_CONFIG_FILE),
"pane_height": 100,
"setup_commands": [
"export ANSIBLE_DEVEL_WARNING=False",
"export ANSIBLE_DEPRECATION_WARNINGS=False",
@@ -45,11 +49,11 @@ def test(
self,
request: pytest.FixtureRequest,
tmux_session: TmuxSession,
index,
user_input,
comment,
search_within_response,
):
index: int,
user_input: str,
comment: str,
search_within_response: str,
) -> None:
# pylint:disable=too-many-arguments
"""Run the tests for stdout, mode and EE set in child class.
Loading

0 comments on commit e96635d

Please sign in to comment.