Exemple #1
0
 def test_render(self):
     cm_stub = _func_stub_from_callable(Dummy.a_class_method.__func__)
     im_stub = _func_stub_from_callable(Dummy.an_instance_method)
     class_stub = ClassStub('Test', function_stubs=(cm_stub, im_stub))
     expected = "\n".join([
         'class Test:',
         cm_stub.render(prefix='    '),
         im_stub.render(prefix='    '),
     ])
     assert class_stub.render() == expected
Exemple #2
0
 def test_build_module_stubs(self):
     entries = [
         FunctionDefinition.from_callable(Dummy.a_static_method),
         FunctionDefinition.from_callable(Dummy.a_class_method.__func__),
         FunctionDefinition.from_callable(Dummy.an_instance_method),
         FunctionDefinition.from_callable(simple_add),
     ]
     simple_add_stub = _func_stub_from_callable(simple_add)
     to_strip = ['typing']
     dummy_stub = ClassStub(
         'Dummy',
         function_stubs=[
             _func_stub_from_callable(Dummy.a_class_method.__func__,
                                      to_strip),
             _func_stub_from_callable(Dummy.an_instance_method, to_strip),
             _func_stub_from_callable(Dummy.a_static_method, to_strip),
         ])
     imports = {'typing': {'Any', 'Optional'}}
     expected = {
         'tests.test_stubs':
         ModuleStub(function_stubs=[simple_add_stub]),
         'tests.util':
         ModuleStub(class_stubs=[dummy_stub],
                    imports_stub=ImportBlockStub(imports)),
     }
     self.maxDiff = None
     assert build_module_stubs(entries) == expected
Exemple #3
0
 def test_render(self):
     cm_stub = _func_stub_from_callable(Dummy.a_class_method)
     im_stub = _func_stub_from_callable(Dummy.an_instance_method)
     func_stubs = (cm_stub, im_stub)
     test_stub = ClassStub('Test', function_stubs=func_stubs)
     test2_stub = ClassStub('Test2', function_stubs=func_stubs)
     other_class_stubs = module_stub_for_method_with_typed_dict['tests.util'].class_stubs.values()
     class_stubs = (*other_class_stubs, test_stub, test2_stub)
     typed_dict_class_stubs = module_stub_for_method_with_typed_dict['tests.util'].typed_dict_class_stubs
     mod_stub = ModuleStub(function_stubs=func_stubs,
                           class_stubs=class_stubs,
                           typed_dict_class_stubs=typed_dict_class_stubs)
     expected = '\n'.join([
         'class DummyAnInstanceMethodTypedDict(TypedDict):',
         '    c: int',
         '',
         '',
         'class FooTypedDict(TypedDict):',
         '    a: int',
         '    b: str',
         '',
         '',
         '@classmethod',
         'def a_class_method(foo: Any) -> Optional[frame]: ...',
         '',
         '',
         'def an_instance_method(self, foo: Any, bar: Any) -> Optional[frame]: ...',
         '',
         '',
         'class Dummy:',
         '    def an_instance_method(self, foo: \'FooTypedDict\', bar: int) '
         + '-> \'DummyAnInstanceMethodTypedDict\': ...',
         '',
         '',
         'class Test:',
         '    @classmethod',
         '    def a_class_method(foo: Any) -> Optional[frame]: ...',
         '    def an_instance_method(self, foo: Any, bar: Any) -> Optional[frame]: ...',
         '',
         '',
         'class Test2:',
         '    @classmethod',
         '    def a_class_method(foo: Any) -> Optional[frame]: ...',
         '    def an_instance_method(self, foo: Any, bar: Any) -> Optional[frame]: ...',
     ])
     assert mod_stub.render() == expected
Exemple #4
0
 def test_render(self):
     cm_stub = _func_stub_from_callable(Dummy.a_class_method.__func__)
     im_stub = _func_stub_from_callable(Dummy.an_instance_method)
     class_stub = ClassStub('Test', function_stubs=(cm_stub, im_stub),
                            attribute_stubs=[
                                AttributeStub('foo', int),
                                AttributeStub('bar', str),
                             ])
     expected = '\n'.join([
         'class Test:',
         '    bar: str',
         '    foo: int',
         '    @classmethod',
         '    def a_class_method(cls, foo: Any) -> Optional[frame]: ...',
         '    def an_instance_method(self, foo: Any, bar: Any) -> Optional[frame]: ...',
     ])
     assert class_stub.render() == expected
Exemple #5
0
 def test_render(self):
     cm_stub = _func_stub_from_callable(Dummy.a_class_method)
     im_stub = _func_stub_from_callable(Dummy.an_instance_method)
     func_stubs = (cm_stub, im_stub)
     test_stub = ClassStub('Test', function_stubs=func_stubs)
     test2_stub = ClassStub('Test2', function_stubs=func_stubs)
     class_stubs = (test_stub, test2_stub)
     mod_stub = ModuleStub(function_stubs=func_stubs, class_stubs=class_stubs)
     expected = "\n\n\n".join([
         cm_stub.render(),
         im_stub.render(),
         test_stub.render(),
         test2_stub.render(),
     ])
     assert mod_stub.render() == expected
Exemple #6
0
class TestFunctionDefinition:
    @pytest.mark.parametrize(
        'func, expected',
        [
            (Dummy.a_static_method, False),
            (Dummy.a_class_method.__func__, True),
            (Dummy.an_instance_method, True),
            (Dummy.a_property.fget, True),
            (Dummy.a_cached_property.func, True),
            (a_module_func, False),
        ],
    )
    def test_has_self(self, func, expected):
        defn = FunctionDefinition.from_callable(func)
        assert defn.has_self == expected

    @pytest.mark.parametrize(
        'func, expected',
        [
            (Dummy.a_static_method, FunctionDefinition(
                'tests.util', 'Dummy.a_static_method', FunctionKind.STATIC,
                Signature.from_callable(Dummy.a_static_method))),
            (Dummy.a_class_method.__func__, FunctionDefinition(
                'tests.util', 'Dummy.a_class_method', FunctionKind.CLASS,
                Signature.from_callable(Dummy.a_class_method.__func__))),
            (Dummy.an_instance_method, FunctionDefinition(
                'tests.util', 'Dummy.an_instance_method', FunctionKind.INSTANCE,
                Signature.from_callable(Dummy.an_instance_method))),
            (Dummy.a_property.fget, FunctionDefinition(
                'tests.util', 'Dummy.a_property', FunctionKind.PROPERTY,
                Signature.from_callable(Dummy.a_property.fget))),
            (Dummy.a_cached_property.func, FunctionDefinition(
                'tests.util', 'Dummy.a_cached_property', FunctionKind.DJANGO_CACHED_PROPERTY,
                Signature.from_callable(Dummy.a_cached_property.func))),
            (a_module_func, FunctionDefinition(
                'tests.test_stubs', 'a_module_func', FunctionKind.MODULE,
                Signature.from_callable(a_module_func))),
            (an_async_func, FunctionDefinition(
                'tests.test_stubs', 'an_async_func', FunctionKind.MODULE,
                Signature.from_callable(a_module_func), is_async=True)),
        ],
    )
    def test_from_callable(self, func, expected):
        defn = FunctionDefinition.from_callable(func)
        assert defn == expected

    @pytest.mark.parametrize(
        'func, arg_types, return_type, yield_type, expected',
        [
            # Non-TypedDict case.
            (
                Dummy.an_instance_method,
                {'foo': int, 'bar': List[str]},
                int,
                None,
                FunctionDefinition(
                    'tests.util',
                    'Dummy.an_instance_method',
                    FunctionKind.INSTANCE,
                    Signature(
                        parameters=[
                            Parameter(name='self', kind=Parameter.POSITIONAL_OR_KEYWORD, annotation=Parameter.empty),
                            Parameter(name='foo', kind=Parameter.POSITIONAL_OR_KEYWORD, annotation=int),
                            Parameter(name='bar', kind=Parameter.POSITIONAL_OR_KEYWORD, annotation=List[str]),
                        ],
                        return_annotation=int,
                    ),
                    False,
                    [],
                )
            ),
            # TypedDict: Add class definitions and use the class names as types.
            (
                Dummy.an_instance_method,
                {
                    'foo': TypedDict(DUMMY_TYPED_DICT_NAME, {'a': int, 'b': str}),
                    'bar': TypedDict(DUMMY_TYPED_DICT_NAME, {'c': int}),
                },
                int,
                None,
                FunctionDefinition(
                    'tests.util',
                    'Dummy.an_instance_method',
                    FunctionKind.INSTANCE,
                    Signature(
                        parameters=[
                            Parameter(name='self', kind=Parameter.POSITIONAL_OR_KEYWORD, annotation=Parameter.empty),
                            Parameter(name='foo', kind=Parameter.POSITIONAL_OR_KEYWORD,
                                      annotation=make_forward_ref('FooTypedDict')),
                            Parameter(name='bar', kind=Parameter.POSITIONAL_OR_KEYWORD,
                                      annotation=make_forward_ref('BarTypedDict')),
                        ],
                        return_annotation=int,
                    ),
                    False,
                    [
                        ClassStub(
                            name='FooTypedDict(TypedDict)',
                            function_stubs=[],
                            attribute_stubs=[
                                AttributeStub('a', int),
                                AttributeStub('b', str),
                            ]
                        ),
                        ClassStub(
                            name='BarTypedDict(TypedDict)',
                            function_stubs=[],
                            attribute_stubs=[
                                AttributeStub('c', int),
                            ]
                        ),
                    ],
                )
            ),
        ],
    )
    def test_from_callable_and_traced_types(self, func, arg_types,
                                            return_type, yield_type, expected):
        function = FunctionDefinition.from_callable_and_traced_types(
            func, arg_types,
            return_type, yield_type,
            existing_annotation_strategy=ExistingAnnotationStrategy.IGNORE
        )
        assert function == expected
Exemple #7
0
class TestReplaceTypedDictsWithStubs:
    SIMPLE_TYPED_DICT_STUB: ClassStub = ClassStub(
        name='FooBarTypedDict(TypedDict)',
        function_stubs=[],
        attribute_stubs=[
            AttributeStub(name='a', typ=int),
            AttributeStub(name='b', typ=str),
        ])
    SIMPLE_TYPED_DICT_STUB2: ClassStub = ClassStub(
        name='FooBar2TypedDict(TypedDict)',
        function_stubs=[],
        attribute_stubs=[
            AttributeStub(name='a', typ=int),
            AttributeStub(name='b', typ=str),
        ])

    @pytest.mark.parametrize(
        'typ, expected',
        [
            (int, (int, [])),
            (List[int], (List[int], [])),
            (Set[int], (Set[int], [])),
            (Dict[str, int], (Dict[str, int], [])),
            (Tuple[str, int], (Tuple[str, int], [])),
            (List[List[Dict[str, int]]], (List[List[Dict[str, int]]], []),),
            (List[List[Dict[str, int]]], (List[List[Dict[str, int]]], []),),
            (
                List[List[TypedDict(DUMMY_TYPED_DICT_NAME, {'a': int, 'b': str})]],
                (List[List[make_forward_ref('FooBarTypedDict')]], [SIMPLE_TYPED_DICT_STUB]),
            ),
            (
                Dict[str, TypedDict(DUMMY_TYPED_DICT_NAME, {'a': int, 'b': str})],
                (Dict[str, make_forward_ref('FooBar2TypedDict')], [SIMPLE_TYPED_DICT_STUB2]),
            ),
            (
                Set[TypedDict(DUMMY_TYPED_DICT_NAME, {'a': int, 'b': str})],
                (Set[make_forward_ref('FooBarTypedDict')], [SIMPLE_TYPED_DICT_STUB]),
            ),
            (
                Tuple[int, TypedDict(DUMMY_TYPED_DICT_NAME, {'a': int, 'b': str})],
                (Tuple[int, make_forward_ref('FooBar2TypedDict')], [SIMPLE_TYPED_DICT_STUB2]),
            ),
            (
                TypedDict(DUMMY_TYPED_DICT_NAME, {'a': int, 'b': str}),
                (make_forward_ref('FooBarTypedDict'), [SIMPLE_TYPED_DICT_STUB]),
            ),
            (
                TypedDict('GenuineTypedDict', {'a': int, 'b': str}),
                (TypedDict('GenuineTypedDict', {'a': int, 'b': str}), []),
            ),
            (
                TypedDict(
                    DUMMY_TYPED_DICT_NAME, {
                        'a': int,
                        'b': TypedDict(DUMMY_TYPED_DICT_NAME, {
                            'a': int,
                            'b': str
                        })
                    }),
                (make_forward_ref('FooBarTypedDict'), [
                    ClassStub(
                        name='BTypedDict(TypedDict)',
                        function_stubs=[],
                        attribute_stubs=[
                            AttributeStub(name='a', typ=int),
                            AttributeStub(name='b', typ=str),
                        ]),
                    ClassStub(
                        name='FooBarTypedDict(TypedDict)',
                        function_stubs=[],
                        attribute_stubs=[
                            AttributeStub(name='a', typ=int),
                            AttributeStub(name='b', typ=make_forward_ref('BTypedDict')),
                        ])
                ]),
            ),
            (
                Tuple[TypedDict(DUMMY_TYPED_DICT_NAME, {'a': int}),
                      TypedDict(DUMMY_TYPED_DICT_NAME, {'b': str})],
                (Tuple[make_forward_ref('FooBarTypedDict'), make_forward_ref('FooBar2TypedDict')],
                 [ClassStub(
                     name='FooBarTypedDict(TypedDict)',
                     function_stubs=[],
                     attribute_stubs=[
                         AttributeStub(name='a', typ=int),
                     ]),
                  ClassStub(
                      name='FooBar2TypedDict(TypedDict)',
                      function_stubs=[],
                      attribute_stubs=[
                          AttributeStub(name='b', typ=str),
                      ])]),
            ),
        ],
    )
    def test_replace_typed_dict_with_stubs(self, typ, expected):
        rewritten_type, stubs = ReplaceTypedDictsWithStubs.rewrite_and_get_stubs(typ, class_name_hint='foo_bar')
        actual = rewritten_type, stubs
        assert actual == expected
Exemple #8
0
 'tests.util': ModuleStub(
     function_stubs=(),
     class_stubs=[
         ClassStub(
             name='Dummy',
             function_stubs=[
                 FunctionStub(
                     name='an_instance_method',
                     signature=Signature(
                         parameters=[
                             Parameter(name='self',
                                       kind=Parameter.POSITIONAL_OR_KEYWORD,
                                       annotation=Parameter.empty),
                             Parameter(name='foo',
                                       kind=Parameter.POSITIONAL_OR_KEYWORD,
                                       annotation=make_forward_ref('FooTypedDict')),
                             Parameter(name='bar',
                                       kind=Parameter.POSITIONAL_OR_KEYWORD,
                                       annotation=int),
                         ],
                         return_annotation=make_forward_ref('DummyAnInstanceMethodTypedDict'),
                     ),
                     kind=FunctionKind.INSTANCE,
                     strip_modules=['mypy_extensions'],
                     is_async=False,
                 ),
             ],
         ),
     ],
     imports_stub=ImportBlockStub(typed_dict_import_map),
     typed_dict_class_stubs=[