Skip to content

Commit

Permalink
fix some bad union tests
Browse files Browse the repository at this point in the history
Summary:
As noted in #49 some of these union
tests became ineffective when we closed the union-annotations soundness hole by
widening all non-optional union annotations to dynamic. The tests are passing but for
the wrong reason; instead of testing union `can_assign_from`, they are effectively now
testing that anything can be assigned to dynamic.

Remove the bad tests and replace them with a single unit-test style test of
`UnionType.can_assign_from` which covers the cases which (for now) aren't testable
via real code.

Reviewed By: DinoV

Differential Revision: D31451895

fbshipit-source-id: f888f1b
  • Loading branch information
Carl Meyer authored and facebook-github-bot committed Oct 7, 2021
1 parent 80c949e commit 439b330
Showing 1 changed file with 14 additions and 47 deletions.
61 changes: 14 additions & 47 deletions Lib/test/test_compiler/test_static/union.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,8 @@
import re
import unittest
from compiler.static import StaticCodeGenerator
from compiler.static.symbol_table import SymbolTable
from compiler.static.types import UNION_TYPE, INT_TYPE, STR_TYPE, NONE_TYPE

from .common import StaticTestBase
from .tests import bad_ret_type, type_mismatch
Expand Down Expand Up @@ -80,54 +84,17 @@ def f(x: Union[int, None]) -> int:
bad_ret_type("Optional[int]", "int"),
)

def test_union_can_assign_to_broader_union(self):
self.assertReturns(
"""
from typing import Union
class B:
pass
def f(x: int, y: str) -> Union[int, str, B]:
return x or y
""",
"Union[int, str]",
)

def test_union_can_assign_to_same_union(self):
self.assertReturns(
"""
from typing import Union
def f(x: int, y: str) -> Union[int, str]:
return x or y
""",
"Union[int, str]",
)

def test_union_can_assign_from_individual_element(self):
self.assertReturns(
"""
from typing import Union
def f(x: int) -> Union[int, str]:
return x
""",
"int",
)

def test_union_cannot_assign_from_broader_union(self):
# TODO this should be a type error, but can't be safely
# until we have runtime checking for unions
self.assertReturns(
"""
from typing import Union
class B: pass
def f(x: int, y: str, z: B) -> Union[int, str]:
return x or y or z
""",
"Union[int, str, foo.B]",
def test_union_can_assign_from(self):
st = SymbolTable(StaticCodeGenerator)
u1 = UNION_TYPE.make_generic_type((INT_TYPE, STR_TYPE), st.generic_types)
u2 = UNION_TYPE.make_generic_type(
(INT_TYPE, STR_TYPE, NONE_TYPE), st.generic_types
)
self.assertTrue(u2.can_assign_from(u1))
self.assertFalse(u1.can_assign_from(u2))
self.assertTrue(u1.can_assign_from(u1))
self.assertTrue(u2.can_assign_from(u2))
self.assertTrue(u1.can_assign_from(INT_TYPE))

def test_union_simplify_to_single_type(self):
self.assertReturns(
Expand Down

0 comments on commit 439b330

Please sign in to comment.