Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add more tests and fix coverage reporting #170

Merged
merged 5 commits into from
Aug 1, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
1 change: 1 addition & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,7 @@ jobs:
- name: Convert coverage to XML
run: |
pip install coverage covdefaults
coverage combine
coverage xml
- name: Upload coverage
uses: codecov/codecov-action@v3
Expand Down
2 changes: 2 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,8 @@ style = [
source = ["src"]
omit = ["src/mkdocs_include_markdown_plugin/plugin.py"]
plugins = ["covdefaults"]
parallel = true
data_file = ".coverage/.coverage"

[tool.coverage.report]
exclude_lines = [
Expand Down
23 changes: 14 additions & 9 deletions src/mkdocs_include_markdown_plugin/cache.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,14 @@
import time


try:
from platformdirs import user_data_dir
except ImportError:
CACHE_AVAILABLE = False
else:
CACHE_AVAILABLE = True


class Cache:
"""Cache for arbitrary content, one file per entry."""

Expand All @@ -18,7 +26,7 @@ def __init__(self, cache_dir: str, expiration_seconds: int = 0):
def get_creation_time_from_fpath(self, fpath: str) -> int:
"""Get creation time of an entry in the cache given its path."""
with open(fpath, encoding='utf-8') as f:
return int(f.readline().strip())
return int(f.readline())

@classmethod
def generate_unique_key_from_url(cls, url: str) -> str:
Expand All @@ -29,7 +37,7 @@ def generate_unique_key_from_url(cls, url: str) -> str:

def read_file(self, fpath: str) -> str: # noqa: D102
with open(fpath, encoding='utf-8') as f:
return '\n'.join(f.read().split('\n')[1:])
return f.read().split('\n', 1)[1]

def get_(self, url: str) -> str | None: # noqa: D102
key = self.generate_unique_key_from_url(url)
Expand Down Expand Up @@ -62,9 +70,7 @@ def clean(self) -> None:

def get_cache_directory() -> str | None:
"""Get the cache directory."""
try:
from platformdirs import user_data_dir
except ImportError:
if not CACHE_AVAILABLE:
return None

cache_dir = user_data_dir('mkdocs-include-markdown-plugin')
Expand All @@ -77,7 +83,6 @@ def get_cache_directory() -> str | None:
def initialize_cache(expiration_seconds: int) -> Cache | None:
"""Initialize a cache instance."""
cache_dir = get_cache_directory()
if cache_dir is None:
return None

return Cache(cache_dir, expiration_seconds)
return None if cache_dir is None else Cache(
cache_dir, expiration_seconds,
)
2 changes: 1 addition & 1 deletion src/mkdocs_include_markdown_plugin/files_watcher.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,6 @@


class FilesWatcher: # noqa: D101
def __init__(self) -> None:
def __init__(self) -> None: # pragma: no cover
self.prev_included_files: list[str] = []
self.included_files: list[str] = []
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import importlib
import os

import pytest
from testing_helpers import parametrize_directives

from mkdocs_include_markdown_plugin.cache import (
CACHE_AVAILABLE,
Cache,
get_cache_directory,
initialize_cache,
Expand Down Expand Up @@ -42,9 +42,7 @@ def test_page_included_by_url_is_cached(
tmp_path,
):
cache_dir = get_cache_directory()
try:
importlib.import_module('platformdirs')
except ImportError:
if not CACHE_AVAILABLE:
assert cache_dir is None
assert initialize_cache(600) is None
return
Expand Down
43 changes: 33 additions & 10 deletions tests/test_integration/test_examples.py
Original file line number Diff line number Diff line change
@@ -1,27 +1,31 @@
import importlib
import os
import subprocess
import sys

import pytest
from mkdocs import config
from mkdocs.commands.build import build
from mkdocs.exceptions import Abort
from testing_helpers import rootdir

from mkdocs_include_markdown_plugin.cache import CACHE_AVAILABLE


EXAMPLES_DIR = os.path.join(rootdir, 'examples')


@pytest.mark.parametrize('dirname', os.listdir(EXAMPLES_DIR))
def test_examples(dirname):
expected_returncode = 0
def config_is_using_cache_setting(config_file_path):
with open(config_file_path, encoding='utf-8') as f:
return 'cache:' in f.read()


@pytest.mark.parametrize('dirname', os.listdir(EXAMPLES_DIR))
def test_examples_subprocess(dirname):
example_dir = os.path.join(EXAMPLES_DIR, dirname)
config_file = os.path.join(example_dir, 'mkdocs.yml')
with open(config_file, encoding='utf-8') as f:
if 'cache:' in f.read():
try:
importlib.import_module('platformdirs')
except ImportError:
expected_returncode = 1
expected_returncode = 1 if config_is_using_cache_setting(
config_file,
) and not CACHE_AVAILABLE else 0

proc = subprocess.Popen(
[sys.executable, '-mmkdocs', 'build'],
Expand All @@ -34,3 +38,22 @@ def test_examples(dirname):
assert proc.returncode == expected_returncode, (
f'{stdout.decode("utf-8")}\n{stderr.decode("utf-8")}'
)


@pytest.mark.parametrize('dirname', os.listdir(EXAMPLES_DIR))
def test_examples_api(dirname):
example_dir = os.path.join(EXAMPLES_DIR, dirname)
config_file = os.path.join(example_dir, 'mkdocs.yml')
expected_to_raise_exc = (
config_is_using_cache_setting(config_file) and not CACHE_AVAILABLE
)

def run():
cfg = config.load_config(config_file=config_file)
build(cfg, dirty=False)

if expected_to_raise_exc:
with pytest.raises(Abort):
run()
else:
run()
46 changes: 46 additions & 0 deletions tests/test_unit/test_cache.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
import os
import time

from mkdocs_include_markdown_plugin.cache import (
CACHE_AVAILABLE,
Cache,
get_cache_directory,
initialize_cache,
)


def test_cache_read_file(tmp_path):
cache = Cache(tmp_path)
assert cache.read_file('pyproject.toml').split('\n', 1)[0] == (
'name = "mkdocs-include-markdown-plugin"'
)


def test_cache_clean(tmp_path):
now_ts = int(time.time())

file1 = tmp_path / 'file1'
file1.write_text(f'{now_ts}\n')
file2 = tmp_path / 'file2'
file2.write_text(f'{now_ts}\n')

assert len(os.listdir(tmp_path)) == 2

cache = Cache(tmp_path, 0)
cache.clean()

assert len(os.listdir(tmp_path)) == 0


def test_get_cache_directory():
if not CACHE_AVAILABLE:
assert get_cache_directory() is None
else:
assert isinstance(get_cache_directory(), str)


def test_initialize_cache_instance():
if not CACHE_AVAILABLE:
assert initialize_cache(300) is None
else:
assert isinstance(initialize_cache(300), Cache)