Exemplo n.º 1
0
 def test_generate_c_type_stub_no_crash_for_object(self) -> None:
     output = []  # type: List[str]
     mod = ModuleType('module', '')  # any module is fine
     imports = []  # type: List[str]
     generate_c_type_stub(mod, 'alias', object, output, imports)
     assert_equal(imports, [])
     assert_equal(output[0], 'class alias:')
Exemplo n.º 2
0
    def test_generate_c_type_with_overload_pybind11(self) -> None:
        class TestClass:
            def __init__(self, arg0: str) -> None:
                """
                __init__(*args, **kwargs)
                Overloaded function.

                1. __init__(self: TestClass, arg0: str) -> None

                2. __init__(self: TestClass, arg0: str, arg1: str) -> None
                """
                pass
        output = []  # type: List[str]
        imports = []  # type: List[str]
        mod = ModuleType(TestClass.__module__, '')
        generate_c_function_stub(mod, '__init__', TestClass.__init__, output, imports,
                                 self_var='self', class_name='TestClass')
        assert_equal(output, [
            '@overload',
            'def __init__(self, arg0: str) -> None: ...',
            '@overload',
            'def __init__(self, arg0: str, arg1: str) -> None: ...',
            '@overload',
            'def __init__(*args, **kwargs) -> Any: ...'])
        assert_equal(set(imports), {'from typing import overload'})
Exemplo n.º 3
0
 def test_parse_all_signatures(self) -> None:
     assert_equal(parse_all_signatures(['random text',
                                        '.. function:: fn(arg',
                                        '.. function:: fn()',
                                        '  .. method:: fn2(arg)']),
                  ([('fn', '()'),
                    ('fn2', '(arg)')], []))
Exemplo n.º 4
0
 def test_topsort(self) -> None:
     a = frozenset({'A'})
     b = frozenset({'B'})
     c = frozenset({'C'})
     d = frozenset({'D'})
     data = {a: {b, c}, b: {d}, c: {d}}  # type: Dict[AbstractSet[str], Set[AbstractSet[str]]]
     res = list(topsort(data))
     assert_equal(res, [{d}, {b, c}, {a}])
Exemplo n.º 5
0
    def test_callable_type_with_default_args(self) -> None:
        c = CallableType([self.x, self.y], [ARG_POS, ARG_OPT], [None, None],
                     AnyType(TypeOfAny.special_form), self.function)
        assert_equal(str(c), 'def (X?, Y? =) -> Any')

        c2 = CallableType([self.x, self.y], [ARG_OPT, ARG_OPT], [None, None],
                      AnyType(TypeOfAny.special_form), self.function)
        assert_equal(str(c2), 'def (X? =, Y? =) -> Any')
Exemplo n.º 6
0
 def test_false_only_of_instance(self) -> None:
     fo = false_only(self.fx.a)
     assert_equal(str(fo), "A")
     assert_false(fo.can_be_true)
     assert_true(fo.can_be_false)
     assert_type(Instance, fo)
     # The original class still can be true
     assert_true(self.fx.a.can_be_true)
Exemplo n.º 7
0
 def test_true_only_of_instance(self) -> None:
     to = true_only(self.fx.a)
     assert_equal(str(to), "A")
     assert_true(to.can_be_true)
     assert_false(to.can_be_false)
     assert_type(Instance, to)
     # The original class still can be false
     assert_true(self.fx.a.can_be_false)
Exemplo n.º 8
0
    def test_generate_c_type_stub_variable_type_annotation(self) -> None:
        # This class mimics the stubgen unit test 'testClassVariable'
        class TestClassVariableCls:
            x = 1

        output = []  # type: List[str]
        mod = ModuleType('module', '')  # any module is fine
        generate_c_type_stub(mod, 'C', TestClassVariableCls, output)
        assert_equal(output, ['class C:', '    x: Any = ...'])
Exemplo n.º 9
0
 def test_sorted_components(self) -> None:
     manager = self._make_manager()
     graph = {'a': State('a', None, 'import b, c', manager),
              'd': State('d', None, 'pass', manager),
              'b': State('b', None, 'import c', manager),
              'c': State('c', None, 'import b, d', manager),
              }
     res = sorted_components(graph)
     assert_equal(res, [frozenset({'d'}), frozenset({'c', 'b'}), frozenset({'a'})])
Exemplo n.º 10
0
    def test_infer_arg_sig_from_docstring(self) -> None:
        assert_equal(infer_arg_sig_from_docstring("(*args, **kwargs)"),
                     [ArgSig(name='*args'), ArgSig(name='**kwargs')])

        assert_equal(
            infer_arg_sig_from_docstring(
                "(x: Tuple[int, Tuple[str, int], str]=(1, ('a', 2), 'y'), y: int=4)"),
            [ArgSig(name='x', type='Tuple[int,Tuple[str,int],str]', default=True),
             ArgSig(name='y', type='int', default=True)])
Exemplo n.º 11
0
 def test_find_unique_signatures(self) -> None:
     assert_equal(find_unique_signatures(
         [('func', '()'),
          ('func', '()'),
          ('func2', '()'),
          ('func2', '(arg)'),
          ('func3', '(arg, arg2)')]),
         [('func', '()'),
          ('func3', '(arg, arg2)')])
Exemplo n.º 12
0
    def test_callable_type(self) -> None:
        c = CallableType([self.x, self.y],
                         [ARG_POS, ARG_POS],
                         [None, None],
                         AnyType(TypeOfAny.special_form), self.function)
        assert_equal(str(c), 'def (X?, Y?) -> Any')

        c2 = CallableType([], [], [], NoneType(), self.fx.function)
        assert_equal(str(c2), 'def ()')
Exemplo n.º 13
0
    def test_generate_c_type_inheritance(self) -> None:
        class TestClass(KeyError):
            pass

        output = []  # type: List[str]
        imports = []  # type: List[str]
        mod = ModuleType('module, ')
        generate_c_type_stub(mod, 'C', TestClass, output, imports)
        assert_equal(output, ['class C(KeyError): ...', ])
        assert_equal(imports, [])
Exemplo n.º 14
0
 def assert_simple_join(self, s: Type, t: Type, join: Type) -> None:
     result = join_types(s, t)
     actual = str(result)
     expected = str(join)
     assert_equal(actual, expected,
                  'join({}, {}) == {{}} ({{}} expected)'.format(s, t))
     assert_true(is_subtype(s, result),
                 '{} not subtype of {}'.format(s, result))
     assert_true(is_subtype(t, result),
                 '{} not subtype of {}'.format(t, result))
Exemplo n.º 15
0
    def test_generic_function_type(self) -> None:
        c = CallableType([self.x, self.y], [ARG_POS, ARG_POS], [None, None],
                     self.y, self.function, name=None,
                     variables=[TypeVarDef('X', 'X', -1, [], self.fx.o)])
        assert_equal(str(c), 'def [X] (X?, Y?) -> Y?')

        v = [TypeVarDef('Y', 'Y', -1, [], self.fx.o),
             TypeVarDef('X', 'X', -2, [], self.fx.o)]
        c2 = CallableType([], [], [], NoneType(), self.function, name=None, variables=v)
        assert_equal(str(c2), 'def [Y, X] ()')
Exemplo n.º 16
0
 def assert_simple_meet(self, s: Type, t: Type, meet: Type) -> None:
     result = meet_types(s, t)
     actual = str(result)
     expected = str(meet)
     assert_equal(actual, expected,
                  'meet({}, {}) == {{}} ({{}} expected)'.format(s, t))
     assert_true(is_subtype(result, s),
                 '{} not subtype of {}'.format(result, s))
     assert_true(is_subtype(result, t),
                 '{} not subtype of {}'.format(result, t))
Exemplo n.º 17
0
 def test_scc(self) -> None:
     vertices = {'A', 'B', 'C', 'D'}
     edges = {'A': ['B', 'C'],
              'B': ['C'],
              'C': ['B', 'D'],
              'D': []}  # type: Dict[str, List[str]]
     sccs = set(frozenset(x) for x in strongly_connected_components(vertices, edges))
     assert_equal(sccs,
                  {frozenset({'A'}),
                   frozenset({'B', 'C'}),
                   frozenset({'D'})})
Exemplo n.º 18
0
 def test_true_only_of_union(self) -> None:
     tup_type = self.tuple(AnyType(TypeOfAny.special_form))
     # Union of something that is unknown, something that is always true, something
     # that is always false
     union_type = UnionType([self.fx.a, tup_type, self.tuple()])
     to = true_only(union_type)
     assert isinstance(to, UnionType)
     assert_equal(len(to.items), 2)
     assert_true(to.items[0].can_be_true)
     assert_false(to.items[0].can_be_false)
     assert_true(to.items[1] is tup_type)
Exemplo n.º 19
0
    def test_generate_c_type_inheritance_other_module(self) -> None:
        import argparse

        class TestClass(argparse.Action):
            pass

        output = []  # type: List[str]
        imports = []  # type: List[str]
        mod = ModuleType('module', '')
        generate_c_type_stub(mod, 'C', TestClass, output, imports)
        assert_equal(output, ['class C(argparse.Action): ...', ])
        assert_equal(imports, ['import argparse'])
Exemplo n.º 20
0
 def test_order_ascc(self) -> None:
     manager = self._make_manager()
     graph = {'a': State('a', None, 'import b, c', manager),
              'd': State('d', None, 'def f(): import a', manager),
              'b': State('b', None, 'import c', manager),
              'c': State('c', None, 'import b, d', manager),
              }
     res = sorted_components(graph)
     assert_equal(res, [frozenset({'a', 'd', 'c', 'b'})])
     ascc = res[0]
     scc = order_ascc(graph, ascc)
     assert_equal(scc, ['d', 'c', 'b', 'a'])
Exemplo n.º 21
0
    def test_generate_c_type_inheritance_same_module(self) -> None:
        class TestBaseClass:
            pass

        class TestClass(TestBaseClass):
            pass

        output = []  # type: List[str]
        imports = []  # type: List[str]
        mod = ModuleType(TestBaseClass.__module__, '')
        generate_c_type_stub(mod, 'C', TestClass, output, imports)
        assert_equal(output, ['class C(TestBaseClass): ...', ])
        assert_equal(imports, [])
Exemplo n.º 22
0
 def assert_vararg_map(self,
                       caller_kinds: List[int],
                       callee_kinds: List[int],
                       expected: List[List[int]],
                       vararg_type: Type,
                       ) -> None:
     result = map_actuals_to_formals(
         caller_kinds,
         [],
         callee_kinds,
         [],
         lambda i: vararg_type)
     assert_equal(result, expected)
Exemplo n.º 23
0
 def test_generate_c_function_other_module_ret(self) -> None:
     """Test that if return type references type from other module, module will be imported."""
     def test(arg0: str) -> None:
         """
         test(arg0: str) -> argparse.Action
         """
         pass
     output = []  # type: List[str]
     imports = []  # type: List[str]
     mod = ModuleType(self.__module__, '')
     generate_c_function_stub(mod, 'test', test, output, imports)
     assert_equal(output, ['def test(arg0: str) -> argparse.Action: ...'])
     assert_equal(imports, ['import argparse'])
Exemplo n.º 24
0
 def assert_solve(self,
                  vars: List[TypeVarId],
                  constraints: List[Constraint],
                  results: List[Union[None, Type, Tuple[Type, Type]]],
                  ) -> None:
     res = []  # type: List[Optional[Type]]
     for r in results:
         if isinstance(r, tuple):
             res.append(r[0])
         else:
             res.append(r)
     actual = solve_constraints(vars, constraints)
     assert_equal(str(actual), str(res))
Exemplo n.º 25
0
    def assert_expand(self,
                      orig: Type,
                      map_items: List[Tuple[TypeVarId, Type]],
                      result: Type,
                      ) -> None:
        lower_bounds = {}

        for id, t in map_items:
            lower_bounds[id] = t

        exp = expand_type(orig, lower_bounds)
        # Remove erased tags (asterisks).
        assert_equal(str(exp).replace('*', ''), str(result))
Exemplo n.º 26
0
 def test_generate_c_type_with_docstring_empty_default(self) -> None:
     class TestClass:
         def test(self, arg0: str = "") -> None:
             """
             test(self: TestClass, arg0: str = "")
             """
             pass
     output = []  # type: List[str]
     imports = []  # type: List[str]
     mod = ModuleType(TestClass.__module__, '')
     generate_c_function_stub(mod, 'test', TestClass.test, output, imports,
                              self_var='self', class_name='TestClass')
     assert_equal(output, ['def test(self, arg0: str = ...) -> Any: ...'])
     assert_equal(imports, [])
Exemplo n.º 27
0
 def assert_map(self,
                caller_kinds_: List[Union[int, str]],
                callee_kinds_: List[Union[int, Tuple[int, str]]],
                expected: List[List[int]],
                ) -> None:
     caller_kinds, caller_names = expand_caller_kinds(caller_kinds_)
     callee_kinds, callee_names = expand_callee_kinds(callee_kinds_)
     result = map_actuals_to_formals(
         caller_kinds,
         caller_names,
         callee_kinds,
         callee_names,
         lambda i: AnyType(TypeOfAny.special_form))
     assert_equal(result, expected)
Exemplo n.º 28
0
 def test_generate_c_function_same_module_ret(self) -> None:
     """Test that if return type references type from same module but using full path,
     no module will be imported, and type specification will be striped to local reference.
     """
     def test(arg0: str) -> None:
         """
         test(arg0: str) -> argparse.Action
         """
         pass
     output = []  # type: List[str]
     imports = []  # type: List[str]
     mod = ModuleType('argparse', '')
     generate_c_function_stub(mod, 'test', test, output, imports)
     assert_equal(output, ['def test(arg0: str) -> Action: ...'])
     assert_equal(imports, [])
Exemplo n.º 29
0
 def test_generate_c_function_other_module_arg(self) -> None:
     """Test that if argument references type from other module, module will be imported."""
     # Provide different type in python spec than in docstring to make sure, that docstring
     # information is used.
     def test(arg0: str) -> None:
         """
         test(arg0: argparse.Action)
         """
         pass
     output = []  # type: List[str]
     imports = []  # type: List[str]
     mod = ModuleType(self.__module__, '')
     generate_c_function_stub(mod, 'test', test, output, imports)
     assert_equal(output, ['def test(arg0: argparse.Action) -> Any: ...'])
     assert_equal(imports, ['import argparse'])
Exemplo n.º 30
0
 def test_repr(self) -> None:
     assert_equal(repr(ArgSig(name='asd"dsa')),
                  "ArgSig(name='asd\"dsa', type=None, default=False)")
     assert_equal(repr(ArgSig(name="asd'dsa")),
                  'ArgSig(name="asd\'dsa", type=None, default=False)')
     assert_equal(repr(ArgSig("func", 'str')),
                  "ArgSig(name='func', type='str', default=False)")
     assert_equal(repr(ArgSig("func", 'str', default=True)),
                  "ArgSig(name='func', type='str', default=True)")
Exemplo n.º 31
0
    def test_remove_misplaced_type_comments_5(self) -> None:
        bad = """
        def f(x):
            # type: (int, List[Any],
            #        float, bool) -> int
            pass

        def g(x):
            # type: (int, List[Any])
            pass
        """
        bad_fixed = """
        def f(x):

            #        float, bool) -> int
            pass

        def g(x):

            pass
        """
        assert_equal(remove_misplaced_type_comments(bad), bad_fixed)
Exemplo n.º 32
0
    def test_remove_misplaced_type_comments_2(self) -> None:
        bad = """
        def f(x):
            # type: Callable[[int], int]
            pass

        #  type:  "foo"
        #  type:  'bar'
        x = 1
        # type: int
        """
        bad_fixed = """
        def f(x):

            pass



        x = 1

        """
        assert_equal(remove_misplaced_type_comments(bad), bad_fixed)
 def test_files_found(self) -> None:
     current = os.getcwd()
     with tempfile.TemporaryDirectory() as tmp:
         try:
             os.chdir(tmp)
             os.mkdir('subdir')
             self.make_file('subdir', 'a.py')
             self.make_file('subdir', 'b.py')
             os.mkdir(os.path.join('subdir', 'pack'))
             self.make_file('subdir', 'pack', '__init__.py')
             opts = parse_options(['subdir'])
             py_mods, c_mods = collect_build_targets(
                 opts, mypy_options(opts))
             assert_equal(c_mods, [])
             files = {mod.path for mod in py_mods}
             assert_equal(
                 files, {
                     os.path.join('subdir', 'pack', '__init__.py'),
                     os.path.join('subdir', 'a.py'),
                     os.path.join('subdir', 'b.py')
                 })
         finally:
             os.chdir(current)
    def test_generate_c_type_with_generic_using_other_module_last(
            self) -> None:
        class TestClass:
            def test(self, arg0: str) -> None:
                """
                test(self: TestClass, arg0: Dict[str, argparse.Action])
                """
                pass

        output = []  # type: List[str]
        imports = []  # type: List[str]
        mod = ModuleType(TestClass.__module__, '')
        generate_c_function_stub(mod,
                                 'test',
                                 TestClass.test,
                                 output,
                                 imports,
                                 self_var='self',
                                 class_name='TestClass')
        assert_equal(
            output,
            ['def test(self, arg0: Dict[str,argparse.Action]) -> Any: ...'])
        assert_equal(imports, ['import argparse'])
Exemplo n.º 35
0
    def assert_simple_is_same(self, s: Type, t: Type, expected: bool, strict: bool) -> None:
        actual = is_same_type(s, t)
        assert_equal(actual, expected,
                     'is_same_type({}, {}) is {{}} ({{}} expected)'.format(s, t))

        if strict:
            actual2 = (s == t)
            assert_equal(actual2, expected,
                         '({} == {}) is {{}} ({{}} expected)'.format(s, t))
            assert_equal(hash(s) == hash(t), expected,
                         '(hash({}) == hash({}) is {{}} ({{}} expected)'.format(s, t))
Exemplo n.º 36
0
    def test_callable_type_with_var_args(self) -> None:
        c = CallableType([self.x], [ARG_STAR], [None],
                         AnyType(TypeOfAny.special_form), self.function)
        assert_equal(str(c), 'def (*X?) -> Any')

        c2 = CallableType([self.x, self.y], [ARG_POS, ARG_STAR], [None, None],
                          AnyType(TypeOfAny.special_form), self.function)
        assert_equal(str(c2), 'def (X?, *Y?) -> Any')

        c3 = CallableType([self.x, self.y], [ARG_OPT, ARG_STAR], [None, None],
                          AnyType(TypeOfAny.special_form), self.function)
        assert_equal(str(c3), 'def (X? =, *Y?) -> Any')
Exemplo n.º 37
0
 def test_infer_getitem_sig(self) -> None:
     assert_equal(infer_method_sig('__getitem__'), '(index)')
Exemplo n.º 38
0
 def test_infer_hash_sig(self) -> None:
     assert_equal(infer_method_sig('__hash__'), '()')
Exemplo n.º 39
0
 def test_tuple_type(self) -> None:
     assert_equal(str(TupleType([], self.fx.std_tuple)), 'Tuple[]')
     assert_equal(str(TupleType([self.x], self.fx.std_tuple)), 'Tuple[X?]')
     assert_equal(str(TupleType([self.x, AnyType(TypeOfAny.special_form)],
                                self.fx.std_tuple)), 'Tuple[X?, Any]')
Exemplo n.º 40
0
 def assert_erase(self, orig: Type, result: Type) -> None:
     assert_equal(str(erase_type(orig)), str(result))
    def test_infer_sig_from_docstring(self) -> None:
        assert_equal(infer_sig_from_docstring('\nfunc(x) - y', 'func'), [
            FunctionSig(name='func', args=[ArgSig(name='x')], ret_type='Any')
        ])

        assert_equal(infer_sig_from_docstring('\nfunc(x, Y_a=None)', 'func'), [
            FunctionSig(
                name='func',
                args=[ArgSig(name='x'),
                      ArgSig(name='Y_a', default=True)],
                ret_type='Any')
        ])

        assert_equal(infer_sig_from_docstring('\nfunc(x, Y_a=3)', 'func'), [
            FunctionSig(
                name='func',
                args=[ArgSig(name='x'),
                      ArgSig(name='Y_a', default=True)],
                ret_type='Any')
        ])

        assert_equal(
            infer_sig_from_docstring('\nfunc(x, Y_a=[1, 2, 3])', 'func'), [
                FunctionSig(
                    name='func',
                    args=[ArgSig(name='x'),
                          ArgSig(name='Y_a', default=True)],
                    ret_type='Any')
            ])

        assert_equal(infer_sig_from_docstring('\nafunc(x) - y', 'func'), [])
        assert_equal(infer_sig_from_docstring('\nfunc(x, y', 'func'), [])
        assert_equal(infer_sig_from_docstring('\nfunc(x=z(y))', 'func'), [
            FunctionSig(name='func',
                        args=[ArgSig(name='x', default=True)],
                        ret_type='Any')
        ])

        assert_equal(infer_sig_from_docstring('\nfunc x', 'func'), [])
        # Try to infer signature from type annotation.
        assert_equal(infer_sig_from_docstring('\nfunc(x: int)', 'func'), [
            FunctionSig(name='func',
                        args=[ArgSig(name='x', type='int')],
                        ret_type='Any')
        ])
        assert_equal(infer_sig_from_docstring('\nfunc(x: int=3)', 'func'), [
            FunctionSig(name='func',
                        args=[ArgSig(name='x', type='int', default=True)],
                        ret_type='Any')
        ])

        assert_equal(
            infer_sig_from_docstring('\nfunc(x: int=3) -> int', 'func'), [
                FunctionSig(name='func',
                            args=[ArgSig(name='x', type='int', default=True)],
                            ret_type='int')
            ])

        assert_equal(
            infer_sig_from_docstring('\nfunc(x: int=3) -> int   \n', 'func'), [
                FunctionSig(name='func',
                            args=[ArgSig(name='x', type='int', default=True)],
                            ret_type='int')
            ])

        assert_equal(
            infer_sig_from_docstring('\nfunc(x: Tuple[int, str]) -> str',
                                     'func'),
            [
                FunctionSig(name='func',
                            args=[ArgSig(name='x', type='Tuple[int,str]')],
                            ret_type='str')
            ])

        assert_equal(
            infer_sig_from_docstring(
                '\nfunc(x: Tuple[int, Tuple[str, int], str], y: int) -> str',
                'func'),
            [
                FunctionSig(name='func',
                            args=[
                                ArgSig(name='x',
                                       type='Tuple[int,Tuple[str,int],str]'),
                                ArgSig(name='y', type='int')
                            ],
                            ret_type='str')
            ])

        assert_equal(infer_sig_from_docstring('\nfunc(x: foo.bar)', 'func'), [
            FunctionSig(name='func',
                        args=[ArgSig(name='x', type='foo.bar')],
                        ret_type='Any')
        ])

        assert_equal(
            infer_sig_from_docstring('\nfunc(x: list=[1,2,[3,4]])', 'func'), [
                FunctionSig(name='func',
                            args=[ArgSig(name='x', type='list', default=True)],
                            ret_type='Any')
            ])

        assert_equal(
            infer_sig_from_docstring('\nfunc(x: str="nasty[")', 'func'), [
                FunctionSig(name='func',
                            args=[ArgSig(name='x', type='str', default=True)],
                            ret_type='Any')
            ])

        assert_equal(
            infer_sig_from_docstring('\nfunc[(x: foo.bar, invalid]', 'func'),
            [])

        assert_equal(
            infer_sig_from_docstring('\nfunc(x: invalid::type<with_template>)',
                                     'func'),
            [
                FunctionSig(name='func',
                            args=[ArgSig(name='x', type=None)],
                            ret_type='Any')
            ])

        assert_equal(infer_sig_from_docstring('\nfunc(x: str="")', 'func'), [
            FunctionSig(name='func',
                        args=[ArgSig(name='x', type='str', default=True)],
                        ret_type='Any')
        ])
Exemplo n.º 42
0
 def test_coherence(self) -> None:
     options = Options()
     _, parsed_options = process_options([], require_targets=False)
     # FIX: test this too. Requires changing working dir to avoid finding 'setup.cfg'
     options.config_file = parsed_options.config_file
     assert_equal(options.snapshot(), parsed_options.snapshot())
Exemplo n.º 43
0
 def test_generic_unbound_type(self) -> None:
     u = UnboundType('Foo',
                     [UnboundType('T'),
                      AnyType(TypeOfAny.special_form)])
     assert_equal(str(u), 'Foo?[T?, Any]')
 def test_infer_binary_op_sig(self) -> None:
     for op in ('eq', 'ne', 'lt', 'le', 'gt', 'ge', 'add', 'radd', 'sub',
                'rsub', 'mul', 'rmul'):
         assert_equal(infer_method_sig('__%s__' % op),
                      [self_arg, ArgSig(name='other')])
Exemplo n.º 45
0
 def test_build_signature(self) -> None:
     assert_equal(build_signature([], []), '()')
     assert_equal(build_signature(['arg'], []), '(arg)')
     assert_equal(build_signature(['arg', 'arg2'], []), '(arg, arg2)')
     assert_equal(build_signature(['arg'], ['arg2']), '(arg, arg2=...)')
     assert_equal(build_signature(['arg'], ['arg2', '**x']), '(arg, arg2=..., **x)')
Exemplo n.º 46
0
 def test_infer_unary_op_sig(self) -> None:
     for op in ('neg', 'pos'):
         assert_equal(infer_method_sig('__%s__' % op), '()')
Exemplo n.º 47
0
 def test_infer_setitem_sig(self) -> None:
     assert_equal(infer_method_sig('__setitem__'), '(index, object)')
 def test_parse_all_signatures(self) -> None:
     assert_equal(
         parse_all_signatures([
             'random text', '.. function:: fn(arg', '.. function:: fn()',
             '  .. method:: fn2(arg)'
         ]), ([('fn', '()'), ('fn2', '(arg)')], []))
 def test_find_unique_signatures(self) -> None:
     assert_equal(
         find_unique_signatures([('func', '()'), ('func', '()'),
                                 ('func2', '()'), ('func2', '(arg)'),
                                 ('func3', '(arg, arg2)')]),
         [('func', '()'), ('func3', '(arg, arg2)')])
Exemplo n.º 50
0
 def test_type_variable_binding(self) -> None:
     assert_equal(str(TypeVarDef('X', 'X', 1, [], self.fx.o)), 'X')
     assert_equal(str(TypeVarDef('X', 'X', 1, [self.x, self.y], self.fx.o)),
                  'X in (X?, Y?)')
Exemplo n.º 51
0
 def test_infer_binary_op_sig(self) -> None:
     for op in ('eq', 'ne', 'lt', 'le', 'gt', 'ge',
                'add', 'radd', 'sub', 'rsub', 'mul', 'rmul'):
         assert_equal(infer_method_sig('__%s__' % op), '(other)')
Exemplo n.º 52
0
 def test_get_line_rate(self) -> None:
     assert_equal('1.0', get_line_rate(0, 0))
     assert_equal('0.3333', get_line_rate(1, 3))
Exemplo n.º 53
0
 def test_generate_c_type_stub_no_crash_for_object(self) -> None:
     output = []  # type: List[str]
     mod = ModuleType('module', '')  # any module is fine
     generate_c_type_stub(mod, 'alias', object, output)
     assert_equal(output[0], 'class alias:')
Exemplo n.º 54
0
 def test_infer_sig_from_docstring(self) -> None:
     assert_equal(infer_sig_from_docstring('\nfunc(x) - y', 'func'),
                  ('(x)', 'Any'))
     assert_equal(infer_sig_from_docstring('\nfunc(x, Y_a=None)', 'func'),
                  ('(x, Y_a=None)', 'Any'))
     assert_equal(infer_sig_from_docstring('\nafunc(x) - y', 'func'), None)
     assert_equal(infer_sig_from_docstring('\nfunc(x, y', 'func'), None)
     assert_equal(infer_sig_from_docstring('\nfunc(x=z(y))', 'func'), None)
     assert_equal(infer_sig_from_docstring('\nfunc x', 'func'), None)
     # try to infer signature from type annotation
     assert_equal(infer_sig_from_docstring('\nfunc(x: int)', 'func'),
                  ('(x: int)', 'Any'))
     assert_equal(infer_sig_from_docstring('\nfunc(x: int=3)', 'func'),
                  ('(x: int=3)', 'Any'))
     assert_equal(
         infer_sig_from_docstring('\nfunc(x: int=3) -> int', 'func'),
         ('(x: int=3)', 'int'))
     assert_equal(
         infer_sig_from_docstring('\nfunc(x: int=3) -> int   \n', 'func'),
         ('(x: int=3)', 'int'))
     assert_equal(
         infer_sig_from_docstring('\nfunc(x: Tuple[int, str]) -> str',
                                  'func'), ('(x: Tuple[int, str])', 'str'))
     assert_equal(infer_sig_from_docstring('\nfunc(x: foo.bar)', 'func'),
                  ('(x: foo.bar)', 'Any'))
Exemplo n.º 55
0
 def assert_parse_signature(self, sig: str, result: Tuple[str, List[str], List[str]]) -> None:
     assert_equal(parse_signature(sig), result)
Exemplo n.º 56
0
 def test_infer_getitem_sig(self) -> None:
     assert_equal(infer_method_sig('__getitem__'), [ArgSig(name='index')])
Exemplo n.º 57
0
 def test_any(self) -> None:
     assert_equal(str(AnyType(TypeOfAny.special_form)), 'Any')
 def test_infer_setitem_sig(self) -> None:
     assert_equal(
         infer_method_sig('__setitem__'),
         [self_arg, ArgSig(name='index'),
          ArgSig(name='object')])
Exemplo n.º 59
0
 def test_infer_sig_from_docstring(self) -> None:
     assert_equal(infer_sig_from_docstring('\nfunc(x) - y', 'func'), '(x)')
     assert_equal(infer_sig_from_docstring('\nfunc(x, Y_a=None)', 'func'), '(x, Y_a=None)')
     assert_equal(infer_sig_from_docstring('\nafunc(x) - y', 'func'), None)
     assert_equal(infer_sig_from_docstring('\nfunc(x, y', 'func'), None)
     assert_equal(infer_sig_from_docstring('\nfunc(x=z(y))', 'func'), None)
     assert_equal(infer_sig_from_docstring('\nfunc x', 'func'), None)
Exemplo n.º 60
0
 def test_simple_unbound_type(self) -> None:
     u = UnboundType('Foo')
     assert_equal(str(u), 'Foo?')