Skip to content

Commit

Permalink
Removed dead code and add few no cover (#2743)
Browse files Browse the repository at this point in the history
  • Loading branch information
ssbarnea authored Dec 1, 2022
1 parent 6c124b6 commit 5b3acbe
Show file tree
Hide file tree
Showing 13 changed files with 47 additions and 49 deletions.
13 changes: 3 additions & 10 deletions .github/workflows/tox.yml
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ jobs:
WSLENV: FORCE_COLOR:PYTEST_REQPASS:TOXENV:TOX_PARALLEL_NO_SPINNER
# Number of expected test passes, safety measure for accidental skip of
# tests. Update value if you add/remove tests.
PYTEST_REQPASS: 723
PYTEST_REQPASS: 724

steps:
- name: Activate WSL1
Expand Down Expand Up @@ -136,12 +136,12 @@ jobs:
run: python3 -m tox -e ${{ matrix.tox_env }}

- name: Combine coverage data
if: "(matrix.cover || false) && runner.os == 'Linux'"
if: ${{ startsWith(matrix.tox_env, 'py') }}
# produce a single .coverage file at repo root
run: tox -e coverage

- name: Upload coverage data
if: "(matrix.cover || false) && runner.os == 'Linux'"
if: ${{ startsWith(matrix.tox_env, 'py') }}
uses: codecov/codecov-action@v3
with:
name: ${{ matrix.tox_env }}
Expand All @@ -157,13 +157,6 @@ jobs:
# https://github.com/actions/upload-artifact/issues/123
continue-on-error: true

- name: Report junit failures
# cspell:disable-next-line
uses: shyim/junit-report-annotations-action@3d2e5374f2b13e70f6f3209a21adfdbc42c466ae
with:
path: .tox/junit.*.xml
if: always() && (matrix.cover || false)

- name: Report failure if git reports dirty status
run: |
if [[ -n $(git status -s) ]]; then
Expand Down
2 changes: 1 addition & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ pip-log.txt

# Coverage artifacts
.coverage
coverage.xml
coverage*.xml
pip-wheel-metadata
.test-results/

Expand Down
4 changes: 4 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -15,13 +15,17 @@ source_pkgs = ["ansiblelint"]
branch = true
parallel = true
concurrency = ["multiprocessing", "thread"]
data_file = ".tox/.coverage"

[tool.coverage.paths]
source = ["src", ".tox/*/site-packages"]

[tool.coverage.report]
exclude_lines = ["pragma: no cover", "if TYPE_CHECKING:"]
omit = ["*/src/ansible_compat/*", "test/*"]
fail_under = 88
skip_covered = true
skip_empty = true

[tool.isort]
profile = "black"
Expand Down
12 changes: 6 additions & 6 deletions src/ansiblelint/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -117,14 +117,14 @@ def initialize_options(arguments: list[str] | None = None) -> None:
options.cache_dir_lock = FileLock(f"{options.cache_dir}/.lock")
try:
options.cache_dir_lock.acquire(timeout=180)
except Timeout:
except Timeout: # pragma: no cover
_logger.error(
"Timeout waiting for another instance of ansible-lint to release the lock."
)
sys.exit(LOCK_TIMEOUT_RC)

# Avoid extra output noise from Ansible about using devel versions
if "ANSIBLE_DEVEL_WARNING" not in os.environ:
if "ANSIBLE_DEVEL_WARNING" not in os.environ: # pragma: no branch
os.environ["ANSIBLE_DEVEL_WARNING"] = "false"


Expand Down Expand Up @@ -347,11 +347,11 @@ def _run_cli_entrypoint() -> None:
sys.exit(main(sys.argv))
except OSError as exc:
# NOTE: Only "broken pipe" is acceptable to ignore
if exc.errno != errno.EPIPE:
if exc.errno != errno.EPIPE: # pragma: no cover
raise
except KeyboardInterrupt:
except KeyboardInterrupt: # pragma: no cover
sys.exit(EXIT_CONTROL_C_RC)
except RuntimeError as exc:
except RuntimeError as exc: # pragma: no cover
raise SystemExit(exc) from exc


Expand Down Expand Up @@ -416,7 +416,7 @@ def to_bool(value: Any) -> bool:
return False


def should_do_markup(stream: TextIO = sys.stdout) -> bool:
def should_do_markup(stream: TextIO = sys.stdout) -> bool: # pragma: no cover
"""Decide about use of ANSI colors."""
py_colors = None

Expand Down
7 changes: 6 additions & 1 deletion src/ansiblelint/_internal/rules.py
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,12 @@ def help(self) -> str:
@property
def url(self) -> str:
"""Return rule documentation url."""
return self.link or RULE_DOC_URL + self.id + "/"
url = self.link
if not url:
url = RULE_DOC_URL
if self.id:
url += self.id + "/"
return url

@property
def shortdesc(self) -> str:
Expand Down
29 changes: 8 additions & 21 deletions src/ansiblelint/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@
import json
import logging
import os
import re
import sys
import time
import urllib.request
Expand Down Expand Up @@ -145,7 +144,7 @@
def get_rule_config(rule_id: str) -> dict[str, Any]:
"""Get configurations for the rule ``rule_id``."""
rule_config = options.rules.get(rule_id, {})
if not isinstance(rule_config, dict):
if not isinstance(rule_config, dict): # pragma: no branch
raise RuntimeError(f"Invalid rule config for {rule_id}: {rule_config}")
return rule_config

Expand All @@ -154,27 +153,15 @@ def get_rule_config(rule_id: str) -> dict[str, Any]:
def ansible_collections_path() -> str:
"""Return collection path variable for current version of Ansible."""
# respect Ansible behavior, which is to load old name if present
for env_var in ["ANSIBLE_COLLECTIONS_PATHS", "ANSIBLE_COLLECTIONS_PATH"]:
for env_var in [
"ANSIBLE_COLLECTIONS_PATHS",
"ANSIBLE_COLLECTIONS_PATH",
]: # pragma: no cover
if env_var in os.environ:
return env_var
return "ANSIBLE_COLLECTIONS_PATH"


def parse_ansible_version(stdout: str) -> tuple[str, str | None]:
"""Parse output of 'ansible --version'."""
# Ansible can produce extra output before displaying version in debug mode.

# ansible-core 2.11+: 'ansible [core 2.11.3]'
match = re.search(r"^ansible \[(?:core|base) ([^\]]+)\]", stdout, re.MULTILINE)
if match:
return match.group(1), None
# ansible-base 2.10 and Ansible 2.9: 'ansible 2.x.y'
match = re.search(r"^ansible ([^\s]+)", stdout, re.MULTILINE)
if match:
return match.group(1), None
return "", f"FATAL: Unable parse ansible cli version: {stdout}"


def in_venv() -> bool:
"""Determine whether Python is running from a venv."""
if hasattr(sys, "real_prefix") or os.environ.get("CONDA_EXE", None) is not None:
Expand Down Expand Up @@ -233,14 +220,14 @@ def guess_install_method() -> str:
def get_version_warning() -> str:
"""Display warning if current version is outdated."""
# 0.1dev1 is special fallback version
if __version__ == "0.1.dev1":
if __version__ == "0.1.dev1": # pragma: no cover
return ""

msg = ""
data = {}
current_version = Version(__version__)

if not os.path.exists(CACHE_DIR):
if not os.path.exists(CACHE_DIR): # pragma: no cover
os.makedirs(CACHE_DIR)
cache_file = f"{CACHE_DIR}/latest.json"
refresh = True
Expand All @@ -260,7 +247,7 @@ def get_version_warning() -> str:
data = json.load(url)
with open(cache_file, "w", encoding="utf-8") as f:
json.dump(data, f)
except (URLError, HTTPError) as exc:
except (URLError, HTTPError) as exc: # pragma: no cover
_logger.debug(
"Unable to fetch latest version from %s due to: %s", release_url, exc
)
Expand Down
2 changes: 1 addition & 1 deletion src/ansiblelint/runner.py
Original file line number Diff line number Diff line change
Expand Up @@ -207,7 +207,7 @@ def _emit_matches(self, files: list[Lintable]) -> Generator[MatchError, None, No
self.lintables.add(child)
files.append(child)
except MatchError as exc:
if not exc.filename:
if not exc.filename: # pragma: no branch
exc.filename = str(lintable.path)
exc.rule = LoadingFailureRule()
yield exc
Expand Down
1 change: 1 addition & 0 deletions src/ansiblelint/schemas/__main__.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
"""Module containing cached JSON schemas."""
# pragma: no cover
import sys

from .main import refresh_schemas
Expand Down
2 changes: 1 addition & 1 deletion src/ansiblelint/text.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ def strip_ansi_escape(data: str | bytes) -> str:
If bytes is passed instead of string, it will be converted to string
using UTF-8.
"""
if isinstance(data, bytes):
if isinstance(data, bytes): # pragma: no branch
data = data.decode("utf-8")

return re.sub(r"\x1b[^m]*m", "", data)
Expand Down
10 changes: 5 additions & 5 deletions src/ansiblelint/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -307,7 +307,7 @@ def _include_children(
v = v["file"]

# we cannot really parse any jinja2 in includes, so we ignore them
if "{{" in v:
if "{{" in v: # pragma: no branch
return []

if "import_playbook" in k and COLLECTION_PLAY_RE.match(v):
Expand Down Expand Up @@ -402,7 +402,7 @@ def _get_task_handler_children_for_tasks_or_playbooks(
with contextlib.suppress(KeyError):

# ignore empty tasks
if not task_handler:
if not task_handler: # pragma: no branch
continue

file_name = task_handler[task_handler_key]
Expand Down Expand Up @@ -478,12 +478,12 @@ def _rolepath(basedir: str, role: str) -> str | None:

possible_paths.append(path_dwim(basedir, ""))

for path_option in possible_paths:
for path_option in possible_paths: # pragma: no branch
if os.path.isdir(path_option):
role_path = path_option
break

if role_path:
if role_path: # pragma: no branch
add_all_plugin_dirs(role_path)

return role_path
Expand All @@ -494,7 +494,7 @@ def _look_for_role_files(
) -> list[Lintable]:
# pylint: disable=unused-argument # main
role_path = _rolepath(basedir, role)
if not role_path:
if not role_path: # pragma: no branch
return []

results = []
Expand Down
2 changes: 1 addition & 1 deletion src/ansiblelint/version.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
"""Ansible-lint version information."""
try:
from ._version import version as __version__
except ImportError:
except ImportError: # pragma: no branch

try:
import pkg_resources
Expand Down
8 changes: 8 additions & 0 deletions test/test_internal_rules.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
"""Tests for internal rules."""
from ansiblelint._internal.rules import BaseRule


def test_base_rule_url() -> None:
"""Test that rule URL is set to expected value."""
rule = BaseRule()
assert rule.url == "https://ansible-lint.readthedocs.io/rules/"
4 changes: 2 additions & 2 deletions tox.ini
Original file line number Diff line number Diff line change
Expand Up @@ -210,10 +210,10 @@ commands =
[testenv:coverage]
description = Combines and displays coverage results
commands =
sh -c "coverage combine .tox/.coverage.*"
sh -c "coverage combine -q .tox/.coverage.*"
# needed by codecov github actions:
coverage xml
# just for humans running it:
coverage report --skip-covered --fail-under=88
coverage report
deps =
coverage[toml]

0 comments on commit 5b3acbe

Please sign in to comment.