Skip to content

Commit

Permalink
refactor: use pytest-datadir
Browse files Browse the repository at this point in the history
  • Loading branch information
andreoliwa committed Dec 29, 2021
1 parent 0062792 commit a0f26a2
Show file tree
Hide file tree
Showing 8 changed files with 80 additions and 42 deletions.
31 changes: 23 additions & 8 deletions poetry.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

23 changes: 15 additions & 8 deletions pyproject.toml
Expand Up @@ -64,28 +64,35 @@ marshmallow-polyfield = "^5.10"
identify = "*"
"more-itertools" = "*"
pluggy = "*"
pydantic = "*"
autorepr = "*"
loguru = "*"
ConfigUpdater = "*"
cachy = "*"
importlib-resources = { version = "*", python = ">=3.6, <3.9" }

# TODO: Move to dependency groups once the feature is on a stable version of Poetry
# https://python-poetry.org/docs/master/managing-dependencies/#dependency-groups
# Group: lint
pylint = { version = "*", optional = true }
# Group: test
pytest = { version = "*", optional = true }
pytest-cov = { version = "*", optional = true }
testfixtures = { version = "*", optional = true }
freezegun = { version = "*", optional = true }
responses = { version = "*", optional = true }
freezegun = { version = "*", optional = true }
pytest-testmon = { version = "*", optional = true }
pytest-watch = { version = "*", optional = true }
pytest-socket = { version = "*", optional = true }
pytest-datadir = { version = "*", optional = true }
# Group: doc
sphinx = { version = "*", optional = true }
sphinx_rtd_theme = { version = "*", optional = true }
sphobjinv = { version = "*", optional = true }
pydantic = "*"
autorepr = "*"
loguru = "*"
ConfigUpdater = "*"
cachy = "*"
importlib-resources = { version = "*", python = ">=3.6, <3.9" }

[tool.poetry.extras]
lint = ["pylint"]
test = ["pytest", "pytest-cov", "testfixtures", "responses", "freezegun", "pytest-testmon", "pytest-watch", "pytest-socket"]
test = ["pytest", "pytest-cov", "testfixtures", "responses", "freezegun", "pytest-testmon", "pytest-watch", "pytest-socket", "pytest-datadir"]
doc = ["sphinx", "sphinx_rtd_theme", "sphobjinv"]

[tool.poetry.dev-dependencies]
Expand Down
21 changes: 17 additions & 4 deletions tasks.py
Expand Up @@ -80,19 +80,32 @@ def macos(ctx, enable: bool):
else:
ctx.run("sed -i '' 's/platform = darwin/platform = linux/g' tox.ini")

def _python_versions(self) -> List[str]:
def _python_versions_old_to_new(self) -> List[str]:
"""Python versions executed in tox."""
return list(reversed([v for v in self._parser["tox"]["envlist"].split(",") if v.startswith("py")]))
versions = []
for py_plus_version_without_dot in self._parser["tox"]["envlist"].split(","):
if not py_plus_version_without_dot.startswith("py"):
continue

major = py_plus_version_without_dot[2]
minor = py_plus_version_without_dot[3:]
versions.append(f"{major}.{minor}")
return list(reversed(versions))

@property
def minimum_python_version(self) -> str:
"""Minimum Python version."""
return self._python_versions()[-1]
return self._python_versions_old_to_new()[0]

@property
def stable_python_version(self) -> str:
"""Stable Python version."""
return self._python_versions()[-2]
return self._as_tox_env(self._python_versions_old_to_new()[-2])

@staticmethod
def _as_tox_env(python_version_with_dot: str) -> str:
no_dot = python_version_with_dot.replace(".", "")
return f"py{no_dot}"


@task(help={"deps": "Poetry dependencies", "hooks": "pre-commit hooks"})
Expand Down
File renamed without changes.
7 changes: 7 additions & 0 deletions tests/data/sample-package-json-style.toml
@@ -0,0 +1,7 @@
["package.json"]
contains_keys = ["name", "version", "repository.type", "repository.url", "release.plugins"]

["package.json".contains_json]
commitlint = """
{ "extends": [ "@commitlint/config-conventional" ] }
"""
5 changes: 2 additions & 3 deletions tests/helpers.py
Expand Up @@ -29,7 +29,6 @@
from nitpick.typedefs import Flake8Error, PathOrStr, StrOrList
from nitpick.violations import Fuss, Reporter

FIXTURES_DIR: Path = Path(__file__).parent / "fixtures"
STYLES_DIR: Path = Path(__file__).parent.parent / "styles"

# Non-breaking space
Expand Down Expand Up @@ -68,15 +67,15 @@ def __init__(self, tmp_path: Path, **kwargs) -> None:
if kwargs.get("setup_py", True):
self.save_file("setup.py", "x = 1")

def create_symlink(self, link_name: str, target_dir: Path = None, target_file: str = None) -> "ProjectMock":
def create_symlink(self, link_name: str, target_dir: Path, target_file: str = None) -> "ProjectMock":
"""Create a symlink to a target file.
:param link_name: Link file name.
:param target_dir: Target directory (default: fixture directory).
:param target_file: Target file name (default: source file name).
"""
path: Path = self.root_dir / link_name
full_source_path = Path(target_dir or FIXTURES_DIR) / (target_file or link_name)
full_source_path = Path(target_dir) / (target_file or link_name)
if not full_source_path.exists():
raise RuntimeError(f"Source file does not exist: {full_source_path}")
path.symlink_to(full_source_path)
Expand Down
27 changes: 10 additions & 17 deletions tests/test_json.py
@@ -1,28 +1,21 @@
"""JSON tests."""
import warnings

import pytest

from nitpick.constants import PACKAGE_JSON, READ_THE_DOCS_URL
from nitpick.plugins.json import JSONPlugin
from nitpick.violations import Fuss, SharedViolations
from tests.helpers import ProjectMock

# FIXME: use pytest-datafiles
PACKAGE_JSON_STYLE = '''
["package.json"]
contains_keys = ["name", "version", "repository.type", "repository.url", "release.plugins"]

["package.json".contains_json]
commitlint = """
{
"extends": [
"@commitlint/config-conventional"
]
}
"""
'''
@pytest.fixture()
def package_json_style(shared_datadir) -> str:
"""A sample style for package.json."""
return (shared_datadir / "sample-package-json-style.toml").read_text()


def test_suggest_initial_contents(tmp_path):
def test_suggest_initial_contents(tmp_path, package_json_style):
"""Suggest initial contents for missing JSON file."""
expected_package_json = """
{
Expand All @@ -42,7 +35,7 @@ def test_suggest_initial_contents(tmp_path):
"version": "<some value here>"
}
"""
ProjectMock(tmp_path).named_style("package-json", PACKAGE_JSON_STYLE).pyproject_toml(
ProjectMock(tmp_path).named_style("package-json", package_json_style).pyproject_toml(
"""
[tool.nitpick]
style = ["package-json"]
Expand All @@ -60,7 +53,7 @@ def test_suggest_initial_contents(tmp_path):
)


def test_missing_different_values_with_contains_json_with_contains_keys(tmp_path):
def test_missing_different_values_with_contains_json_with_contains_keys(tmp_path, package_json_style):
"""Test missing and different values with "contains_json" and "contains_keys"."""
expected_package_json = """
{
Expand All @@ -81,7 +74,7 @@ def test_missing_different_values_with_contains_json_with_contains_keys(tmp_path
"version": "0.0.1"
}
"""
ProjectMock(tmp_path).named_style("package-json", PACKAGE_JSON_STYLE).pyproject_toml(
ProjectMock(tmp_path).named_style("package-json", package_json_style).pyproject_toml(
"""
[tool.nitpick]
style = ["package-json"]
Expand Down
8 changes: 6 additions & 2 deletions tests/test_project.py
@@ -1,5 +1,6 @@
"""Config tests."""
import os
import shutil

import pytest
import responses
Expand Down Expand Up @@ -35,9 +36,12 @@ def test_singleton():
assert "This class cannot be instantiated directly" in str(err)


def test_no_root_dir_with_python_file(tmp_path):
def test_no_root_dir_with_python_file(tmp_path, shared_datadir):
"""No root dir with Python file."""
project = ProjectMock(tmp_path, pyproject_toml=False, setup_py=False).create_symlink("hello.py")
hello_py = tmp_path / "hello.py"
shutil.copy(shared_datadir / "hello.py", hello_py)
project = ProjectMock(tmp_path, pyproject_toml=False, setup_py=False)
project.files_to_lint.append(hello_py)
error = f"NIP101 {ProjectViolations.NO_ROOT_DIR.message}"
project.flake8().assert_single_error(error).cli_run(error, exit_code=2).cli_ls(error, exit_code=2)

Expand Down

0 comments on commit a0f26a2

Please sign in to comment.