Skip to content

Commit

Permalink
Tested decoartors for preserving mypy types (#226)
Browse files Browse the repository at this point in the history
This patch adds a test case to make sure that class invariants do not
break the type inference with mypy.

Related to #224.
  • Loading branch information
mristin authored Aug 12, 2021
1 parent 19bd4f8 commit d0981f7
Showing 1 changed file with 36 additions and 1 deletion.
37 changes: 36 additions & 1 deletion tests/test_mypy_decorators.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@


class TestMypyDecorators(unittest.TestCase):
def test_mypy_me(self) -> None:
def test_functions(self) -> None:
with tempfile.TemporaryDirectory(prefix="mypy_fail_case_") as tmpdir:
content = textwrap.dedent('''\
"""Implement a fail case for mypy to test that the types are preserved with the decorators."""
Expand Down Expand Up @@ -47,6 +47,41 @@ def f3(x: int) -> int:
'''.format(path=pth)),
out)

def test_class_type_when_decorated_with_invariant(self) -> None:
with tempfile.TemporaryDirectory(prefix="mypy_fail_case_") as tmpdir:
content = textwrap.dedent('''\
"""Implement a fail case for mypy to test that the type of class is preserved."""
import icontract
class SomeClass:
pass
reveal_type(SomeClass)
@icontract.invariant(lambda self: self.x > 0)
class Decorated:
def __init__(self) -> None:
self.x = 1
reveal_type(Decorated)
''')

pth = pathlib.Path(tmpdir) / "source.py"
pth.write_text(content)

with subprocess.Popen(
['mypy', '--strict', str(pth)], universal_newlines=True, stdout=subprocess.PIPE) as proc:
out, err = proc.communicate()

self.assertIsNone(err)
self.assertEqual(
textwrap.dedent('''\
{path}:8: note: Revealed type is "def () -> source.SomeClass"
{path}:15: note: Revealed type is "def () -> source.Decorated"
'''.format(path=pth)),
out)


if __name__ == '__main__':
unittest.main()

0 comments on commit d0981f7

Please sign in to comment.