Skip to content
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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
54 changes: 36 additions & 18 deletions pytest_mypy_plugins/item.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
from mypy import build
from mypy.fscache import FileSystemCache
from mypy.main import process_options
from mypy.metastore import FilesystemMetadataStore, MetadataStore, SqliteMetadataStore

from pytest_mypy_plugins import configs, utils
from pytest_mypy_plugins.collect import File, YamlTestFile
Expand Down Expand Up @@ -364,26 +365,43 @@ def __init__(
self.incremental_cache_dir = os.path.join(self.root_directory, ".mypy_cache")

def remove_cache_files(self, fpath_no_suffix: Path) -> None:
cache_file = Path(self.incremental_cache_dir)
cache_file /= ".".join([str(part) for part in sys.version_info[:2]])
cache_dir = os.path.join(
self.incremental_cache_dir,
".".join([str(part) for part in sys.version_info[:2]]),
)
if not os.path.isdir(cache_dir):
return

# Build entry names to remove for each path component so namespace-package
# cache entries are also cleaned (e.g. "pkg.*", "pkg/sub.*", "pkg/sub/mod.*").
suffixes = (".meta.json", ".data.json", ".err.json", ".meta.ff", ".data.ff", ".err.ff")
entries: list[str] = []
accumulated = ""
for i, part in enumerate(fpath_no_suffix.parts):
if (i == 0) and part.endswith("-stubs") and ((cache_file / part.removesuffix("-stubs")).is_dir()):
part = part.removesuffix("-stubs")
cache_file /= part
data_json_file = cache_file.with_suffix(".data.json")
if data_json_file.exists():
data_json_file.unlink()
meta_json_file = cache_file.with_suffix(".meta.json")
if meta_json_file.exists():
meta_json_file.unlink()

for parent_dir in cache_file.parents:
if (
parent_dir.exists()
and len(list(parent_dir.iterdir())) == 0
and str(self.incremental_cache_dir) in str(parent_dir)
i == 0
and part.endswith("-stubs")
and os.path.isdir(os.path.join(cache_dir, part.removesuffix("-stubs")))
):
parent_dir.rmdir()
part = part.removesuffix("-stubs")
accumulated = f"{accumulated}/{part}" if accumulated else part
entries.extend(accumulated + s for s in suffixes)

stores: list[MetadataStore] = []
if os.path.isfile(os.path.join(cache_dir, "cache.db")):
stores.append(SqliteMetadataStore(cache_dir))
stores.append(FilesystemMetadataStore(cache_dir))

for store in stores:
try:
for entry in entries:
try:
store.remove(entry)
except FileNotFoundError:
pass
store.commit()
finally:
store.close()

def execute_extension_hook(self) -> None:
extension_hook_fqname = self.config.option.mypy_extension_hook
Expand Down Expand Up @@ -441,7 +459,7 @@ def runtest(self) -> None:
).run()
finally:
temp_dir.cleanup()
# remove created modules
# remove created modules from the shared cache
if not self.disable_cache:
for file in self.files:
path = Path(file.path)
Expand Down
10 changes: 5 additions & 5 deletions pytest_mypy_plugins/tests/test-parametrized.yml
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
- case: only_main
parametrized:
- a: 1
revealed_type: builtins.int
revealed_type: int
- a: 1.0
revealed_type: builtins.float
revealed_type: float
- a: {a: "test"}
revealed_type: builtins.dict[builtins.str, builtins.str]
revealed_type: dict[str, str]
main: |
a = {{ a }}
reveal_type(a) # N: Revealed type is "{{ revealed_type }}"
Expand Down Expand Up @@ -34,9 +34,9 @@
- case: with_out
parametrized:
- what: cat
rt: builtins.str
rt: str
- what: dog
rt: builtins.str
rt: str
main: |
animal = '{{ what }}'
reveal_type(animal)
Expand Down
6 changes: 3 additions & 3 deletions pytest_mypy_plugins/tests/test-regex-assertions.yml
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
a = 1
b = 'hello'

reveal_type(a) # N: Revealed type is "builtins.int"
reveal_type(a) # N: Revealed type is "int"
reveal_type(b) # N: .*str.*

- case: expected_message_regex_with_out
Expand Down Expand Up @@ -61,7 +61,7 @@

def foo(bar: str, ham: int = 42) -> Set[Union[str, int]]:
return {bar, ham}
reveal_type(foo) # NR: Revealed type is "def \(bar: builtins\.str, ham: builtins\.int =\) -> .*"
reveal_type(foo) # NR: Revealed type is "def \(bar: str, ham: int =\) -> .*"

- case: regex_against_callable_out
regex: yes
Expand All @@ -72,4 +72,4 @@
return {bar, ham}
reveal_type(foo)
out: |
main:5: note: Revealed type is "def \(bar: builtins\.str, ham: builtins\.int =\) -> .*"
main:5: note: Revealed type is "def \(bar: str, ham: int =\) -> .*"
14 changes: 7 additions & 7 deletions pytest_mypy_plugins/tests/test-simple-cases.yml
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,8 @@
class MyClass:
pass

reveal_type(a) # N: Revealed type is "builtins.int"
reveal_type(b) # N: Revealed type is "builtins.str"
reveal_type(a) # N: Revealed type is "int"
reveal_type(b) # N: Revealed type is "str"


- case: revealed_type_with_environment
Expand All @@ -19,16 +19,16 @@

b = 'hello'

reveal_type(a) # N: Revealed type is "builtins.int"
reveal_type(b) # N: Revealed type is "builtins.str"
reveal_type(a) # N: Revealed type is "int"
reveal_type(b) # N: Revealed type is "str"
env:
- DJANGO_SETTINGS_MODULE=mysettings


- case: revealed_type_with_disabled_cache
main: |
a = 1
reveal_type(a) # N: Revealed type is "builtins.int"
reveal_type(a) # N: Revealed type is "int"
disable_cache: true


Expand All @@ -37,13 +37,13 @@
a = 1
reveal_type(a)
out: |
main:2: note: Revealed type is "builtins.int"
main:2: note: Revealed type is "int"


- case: create_files
main: |
a = 1
reveal_type(a) # N: Revealed type is "builtins.int"
reveal_type(a) # N: Revealed type is "int"
files:
- path: myapp/__init__.py
- path: myapp/models.py
Expand Down
42 changes: 33 additions & 9 deletions pytest_mypy_plugins/tests/test_mypy_cache.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
from tempfile import TemporaryDirectory

import pytest
from mypy.metastore import FilesystemMetadataStore, MetadataStore, SqliteMetadataStore


def test_non_test_case_files_remain(temp_dir: Path) -> None:
Expand Down Expand Up @@ -143,18 +144,34 @@ def test_non_test_case_files_remain(temp_dir: Path) -> None:
}


@pytest.mark.parametrize(
"mypy_cache_config",
[
pytest.param("", id="default"),
pytest.param("sqlite_cache = False\n", id="no-sqlite"),
pytest.param("fixed_format_cache = False\n", id="no-fixed-format"),
pytest.param("sqlite_cache = False\nfixed_format_cache = False\n", id="legacy"),
],
)
@pytest.mark.parametrize(
("contents", "module_fpaths_no_suffix"),
CACHE_FILES_REMOVED_TEST_DATA.values(),
ids=CACHE_FILES_REMOVED_TEST_DATA.keys(),
)
def test_cache_files_removed(temp_dir: Path, contents: str, module_fpaths_no_suffix: tuple[str, ...]) -> None:
def test_cache_files_removed(
temp_dir: Path, contents: str, module_fpaths_no_suffix: tuple[str, ...], mypy_cache_config: str
) -> None:
"""Tests that cache files associated with ``files`` in a test case get removed"""

cache_dir = temp_dir / ".mypy_cache" / f"{version_info[0]}.{version_info[1]}"
# pytest and mypy hasn't been run yet, so no cache should exist
assert not cache_dir.is_dir()

if mypy_cache_config:
config_lines = mypy_cache_config.strip().splitlines()
indented = "\n".join(f" {line}" for line in config_lines)
contents = contents.replace(" main: |", f" mypy_config: |\n{indented}\n main: |")

make_yaml_test_file(temp_dir, contents)
res = subprocess.run(
["pytest", f"--mypy-testing-base={temp_dir}"], cwd=temp_dir, stdout=subprocess.DEVNULL, stderr=subprocess.STDOUT
Expand Down Expand Up @@ -193,13 +210,20 @@ def make_yaml_test_file(


def get_created_cache_files(cache_dir: Path, module_rel_paths_no_suffix: tuple[str, ...]) -> list[str]:
stores: list[MetadataStore] = []
cache_dir_str = str(cache_dir)
if (cache_dir / "cache.db").is_file():
stores.append(SqliteMetadataStore(cache_dir_str))
if cache_dir.is_dir():
stores.append(FilesystemMetadataStore(cache_dir_str))

created = []
for rel_path in module_rel_paths_no_suffix:
prefix = cache_dir / rel_path
data_file = prefix.with_suffix(".data.json")
if data_file.exists():
created.append(str(data_file.relative_to(cache_dir)))
meta_file = prefix.with_suffix(".meta.json")
if meta_file.exists():
created.append(str(meta_file.relative_to(cache_dir)))
for store in stores:
try:
for entry in store.list_all():
if any(entry.startswith(rel_path + ".") for rel_path in module_rel_paths_no_suffix):
created.append(entry)
finally:
store.close()

return created
4 changes: 2 additions & 2 deletions pytest_mypy_plugins/tests/test_site_packages.py
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ def test_no_silence_site_packages_only(tmp_path: Path) -> None:
a: str
a / 2
out: |
{site_packages_path}/mypy/typeshed/stdlib/types.pyi:721: error: Class cannot subclass "Any" (has type "Any") [misc]
{site_packages_path}/mypy/typeshed/stdlib/types.pyi:716: error: Class cannot subclass "Any" (has type "Any") [misc]
main:4: error: Unsupported operand types for / ("str" and "int") [operator]
subpkg:2: error: Unsupported operand types for / ("str" and "int") [operator]
""",
Expand Down Expand Up @@ -128,7 +128,7 @@ def test_no_silence_site_packages_and_modify_pythonpath(tmp_path: Path) -> None:
a: str
a / 2
out: |
{site_packages_path}/mypy/typeshed/stdlib/types.pyi:721: error: Class cannot subclass "Any" (has type "Any") [misc]
{site_packages_path}/mypy/typeshed/stdlib/types.pyi:716: error: Class cannot subclass "Any" (has type "Any") [misc]
main:4: error: Unsupported operand types for / ("str" and "int") [operator]
subpkg:2: error: Unsupported operand types for / ("str" and "int") [operator]
""",
Expand Down
2 changes: 1 addition & 1 deletion requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -4,5 +4,5 @@ types-decorator
types-PyYAML
types-setuptools
types-regex
mypy==1.19.1
mypy==1.20.1
-e .