Esempio n. 1
0
def mock_pj_api(type_api: str, filename: str):
    api_result = json.load(
        open(os.path.join(os.path.dirname(__file__), filename)))
    updated_settings = {}
    source_type = ApiPjSource

    with override_settings(updated_settings), init_pj_source(source_type):
        if type_api == "api":
            api_mock = mock.patch.object(
                places_utils.pj_source,
                "get_from_params",
                new=lambda *x, **y: api_result,
            )
            with api_mock:
                yield
        else:
            api_mock = mock.patch.object(
                places_utils.pj_source,
                "get_from_params",
                new=lambda *x, **y:
                {"search_results": {
                    "listings": [api_result]
                }},
            )
            with api_mock:
                yield
Esempio n. 2
0
def mock_bragi_carrefour_in_bbox(request, httpx_mock):
    bragi_response = read_fixture(
        "fixtures/autocomplete/carrefour_in_bbox.json")
    limit = getattr(request, "param", {}).get("limit")
    if limit is not None:
        bragi_response["features"] = bragi_response["features"][:limit]
    with override_settings({"BRAGI_BASE_URL": BASE_URL}):
        httpx_mock.post(re.compile(f"^{BASE_URL}/autocomplete")).respond(
            json=bragi_response)
        yield
def test_dotted_path_annotation_local_type_def(
    python_version, import_collision_policy, expected_import, comment, remove_type
):
    content = '''
class serializers:
    # why would you do this
    pass

def no_op(arg1):
    """
    Args:
        arg1 (serializers.Serializer): blah
    """
    pass
'''

    if comment:
        comment = f"{comment}\n    "

    docstring_type = "" if remove_type else " (serializers.Serializer)"

    expected = f'''{expected_import}
class serializers:
    # why would you do this
    pass

def no_op(arg1):
    {comment}"""
    Args:
        arg1{docstring_type}: blah
    """
    pass
'''

    with tempfile.NamedTemporaryFile(suffix=".py") as f:
        with open(f.name, "w") as fw:
            fw.write(content)

        test_settings = override_settings(
            PYTHON_VERSION=python_version,
            ALLOW_UNTYPED_ARGS=False,
            REQUIRE_RETURN_TYPE=False,
            IMPORT_COLLISION_POLICY=import_collision_policy,
            UNPATHED_TYPE_POLICY=UnpathedTypePolicy.FAIL,
        )
        inject.clear_and_configure(configuration_factory(test_settings))

        annotate(
            f.name, in_process=True, interactive=False, write=True, silent=True,
        )

        with open(f.name, "r") as fr:
            annotated = fr.read()

    assert annotated == expected
def test_decorated_function():
    content = '''
@whatever(param=val)
def decorated(arg1):
    """
    Args:
        arg1 (Tuple[str, ...]): blah

    Returns:
        Tuple[int, ...]: blah
    """
    return tuple(
        int(arg) for arg in arg1
    )
'''

    expected = '''from typing import Tuple


@whatever(param=val)
def decorated(arg1):
    # type: (Tuple[str, ...]) -> Tuple[int, ...]
    """
    Args:
        arg1: blah

    Returns:
        blah
    """
    return tuple(
        int(arg) for arg in arg1
    )
'''

    with tempfile.NamedTemporaryFile(suffix=".py") as f:
        with open(f.name, "w") as fw:
            fw.write(content)

        test_settings = override_settings(
            ALLOW_UNTYPED_ARGS=False,
            REQUIRE_RETURN_TYPE=False,
            IMPORT_COLLISION_POLICY=ImportCollisionPolicy.IMPORT,
            UNPATHED_TYPE_POLICY=UnpathedTypePolicy.FAIL,
        )
        inject.clear_and_configure(configuration_factory(test_settings))

        annotate(
            f.name, in_process=True, interactive=False, write=True, silent=True,
        )

        with open(f.name, "r") as fr:
            annotated = fr.read()

    assert annotated == expected
Esempio n. 5
0
def enable_bancheck(httpx_mock):
    with override_settings(
        {
            "BANCHECK_ENABLED": True,
            "QWANT_API_BASE_URL": "http://qwant-api.test",
        }
    ), patch("idunn.utils.ban_check.ban_check_http", new_callable=get_ban_check_http):
        httpx_mock.get(url__regex=r"http://qwant-api.test/v3/captcha/isban.*").respond(
            json={"status": "success", "data": True}
        )
        yield
def test_require_return_type(require_return_type):
    """
    NOTE: here is an example of a function where omitting the "Returns"
    block from the docstring and setting `REQUIRE_RETURN_TYPE=False` will
    give the wrong result (...an argument for `REQUIRE_RETURN_TYPE=True`)
    TODO: I don't know if there is any check for return statements we can
    do via Bowler?
    """
    content = '''
def identity(arg1):
    """
    Args:
        arg1 (Tuple[str, ...]): blah
    """
    return arg1
'''

    if not require_return_type:
        expected = '''from typing import Tuple


def identity(arg1):
    # type: (Tuple[str, ...]) -> None
    """
    Args:
        arg1: blah
    """
    return arg1
'''
    else:
        expected = content

    with tempfile.NamedTemporaryFile(suffix=".py") as f:
        with open(f.name, "w") as fw:
            fw.write(content)

        test_settings = override_settings(
            ALLOW_UNTYPED_ARGS=False,
            REQUIRE_RETURN_TYPE=require_return_type,
            IMPORT_COLLISION_POLICY=ImportCollisionPolicy.IMPORT,
            UNPATHED_TYPE_POLICY=UnpathedTypePolicy.FAIL,
        )
        inject.clear_and_configure(configuration_factory(test_settings))

        annotate(
            f.name, in_process=True, interactive=False, write=True, silent=True,
        )

        with open(f.name, "r") as fr:
            annotated = fr.read()

    assert annotated == expected
def test_staticmethod():
    """
    First arg *is* annotatable
    """
    content = '''
class SomeClass:
    @staticmethod
    def method(obj, whatever):
        """
        Args:
            obj (object)
            whatever (Any)
        """
        pass
'''

    expected = '''from typing import Any


class SomeClass:
    @staticmethod
    def method(obj, whatever):
        # type: (object, Any) -> None
        """
        Args:
            obj
            whatever
        """
        pass
'''

    with tempfile.NamedTemporaryFile(suffix=".py") as f:
        with open(f.name, "w") as fw:
            fw.write(content)

        test_settings = override_settings(
            ALLOW_UNTYPED_ARGS=False,
            REQUIRE_RETURN_TYPE=False,
            IMPORT_COLLISION_POLICY=ImportCollisionPolicy.IMPORT,
            UNPATHED_TYPE_POLICY=UnpathedTypePolicy.FAIL,
        )
        inject.clear_and_configure(configuration_factory(test_settings))

        annotate(
            f.name, in_process=True, interactive=False, write=True, silent=True,
        )

        with open(f.name, "r") as fr:
            annotated = fr.read()

    assert annotated == expected
def test_allow_untyped_args(allow_untyped_args):
    content = '''
def identity(arg1):
    """
    Args:
        arg1: blah

    Returns:
        Tuple[str, ...]: blah
    """
    return arg1
'''

    if allow_untyped_args:
        expected = '''from typing import Tuple


def identity(arg1):
    # type: (...) -> Tuple[str, ...]
    """
    Args:
        arg1: blah

    Returns:
        blah
    """
    return arg1
'''
    else:
        expected = content

    with tempfile.NamedTemporaryFile(suffix=".py") as f:
        with open(f.name, "w") as fw:
            fw.write(content)

        test_settings = override_settings(
            ALLOW_UNTYPED_ARGS=allow_untyped_args,
            REQUIRE_RETURN_TYPE=False,
            IMPORT_COLLISION_POLICY=ImportCollisionPolicy.IMPORT,
            UNPATHED_TYPE_POLICY=UnpathedTypePolicy.FAIL,
        )
        inject.clear_and_configure(configuration_factory(test_settings))

        annotate(
            f.name, in_process=True, interactive=False, write=True, silent=True,
        )

        with open(f.name, "r") as fr:
            annotated = fr.read()

    assert annotated == expected
def test_yields_generator():
    content = '''
def generator(arg1):
    """
    Args:
        arg1 (Iterable[int]): blah

    Yields:
        int: blah
    """
    for val in arg1:
        yield val
'''

    expected = '''from typing import Generator, Iterable


def generator(arg1):
    # type: (Iterable[int]) -> Generator[int, None, None]
    """
    Args:
        arg1: blah

    Yields:
        blah
    """
    for val in arg1:
        yield val
'''

    with tempfile.NamedTemporaryFile(suffix=".py") as f:
        with open(f.name, "w") as fw:
            fw.write(content)

        test_settings = override_settings(
            ALLOW_UNTYPED_ARGS=False,
            REQUIRE_RETURN_TYPE=False,
            IMPORT_COLLISION_POLICY=ImportCollisionPolicy.IMPORT,
            UNPATHED_TYPE_POLICY=UnpathedTypePolicy.FAIL,
        )
        inject.clear_and_configure(configuration_factory(test_settings))

        annotate(
            f.name, in_process=True, interactive=False, write=True, silent=True,
        )

        with open(f.name, "r") as fr:
            annotated = fr.read()

    assert annotated == expected
def test_dotted_path_decorator():
    # NOTE: this example is an instance method, so first arg is not annotatable
    content = '''
class SomeClass:
    @some_package.decorator
    def method(cls, obj):
        """
        Args:
            obj (object)

        Returns:
            int
        """
        return 1
'''

    expected = '''
class SomeClass:
    @some_package.decorator
    def method(cls, obj):
        # type: (object) -> int
        """
        Args:
            obj
        """
        return 1
'''

    with tempfile.NamedTemporaryFile(suffix=".py") as f:
        with open(f.name, "w") as fw:
            fw.write(content)

        test_settings = override_settings(
            ALLOW_UNTYPED_ARGS=False,
            REQUIRE_RETURN_TYPE=False,
            IMPORT_COLLISION_POLICY=ImportCollisionPolicy.IMPORT,
            UNPATHED_TYPE_POLICY=UnpathedTypePolicy.FAIL,
        )
        inject.clear_and_configure(configuration_factory(test_settings))

        annotate(
            f.name, in_process=True, interactive=False, write=True, silent=True,
        )

        with open(f.name, "r") as fr:
            annotated = fr.read()

    assert annotated == expected
Esempio n. 11
0
def test_find_local_types(python_version):
    expected = LocalTypes.factory(
        type_defs={
            "T",
            "TopLevel",
            "InnerClass",
            "SomeTuple",
            "SomeTypedTuple",
            "SomeTypedDict",
            "NewClass",
        },
        star_imports={"serious"},
        names_to_packages={
            "Irrelevant": "..sub",
            "Nonsense": "..sub",
            "ReallyUnused": "..sub",
            "Product": "other.module",
            "Imported": "some.module",
            "ConditionallyImported": "some.module",
            "InnerImported": "some.module",
            "namedtuple": "collections",
            "NamedTuple": "typing",
            "TypedDict": "typing",
            "TypeVar": "typing",
            "Union": "typing",
        },
        package_imports={"logging", "nott.so.serious"},
        signatures={
            34: ("static", ("cls", "self")),
            39: ("clsmethod", ("self", )),
            49: ("method", ("cls", )),
            53: ("conditionally_defined_method", ("cls", )),
            57: ("first", ("products", "getter")),
            77: ("second", ("products", "getter")),
            97: ("second_inner", ("product", "key", "default")),
            118: ("third", ("product_ids", "user_id")),
            133: ("fourth", ("product_id", "user_id")),
            141: ("fifth", ("product_ids", "user_id")),
            158: ("sixth", ("product_ids", )),
        },
    )

    test_settings = override_settings(PYTHON_VERSION=python_version)
    inject.clear_and_configure(configuration_factory(test_settings))

    result = find_local_types("tests/fixtures/napoleon.py")

    assert result == expected
def test_returns_none(python_version):
    content = '''
def no_op(arg1):
    """
    Args:
        arg1 (Tuple[str, ...]): blah

    Returns:
        None
    """
    pass
'''

    # "Returns" block omitted since there was no description
    expected = '''from typing import Tuple


def no_op(arg1):
    # type: (Tuple[str, ...]) -> None
    """
    Args:
        arg1: blah
    """
    pass
'''

    with tempfile.NamedTemporaryFile(suffix=".py") as f:
        with open(f.name, "w") as fw:
            fw.write(content)

        test_settings = override_settings(
            PYTHON_VERSION=python_version,
            ALLOW_UNTYPED_ARGS=False,
            REQUIRE_RETURN_TYPE=True,
            IMPORT_COLLISION_POLICY=ImportCollisionPolicy.IMPORT,
            UNPATHED_TYPE_POLICY=UnpathedTypePolicy.FAIL,
        )
        inject.clear_and_configure(configuration_factory(test_settings))

        annotate(
            f.name, in_process=True, interactive=False, write=True, silent=True,
        )

        with open(f.name, "r") as fr:
            annotated = fr.read()

    assert annotated == expected
def test_handle_splat_args():
    content = '''
def no_op(arg1, *args, **kwargs):
    """
    Args:
        arg1 (str): blah
        *args (int)
        **kwargs (Tuple[bool, ...])
    """
    return
'''

    expected = '''from typing import Tuple


def no_op(arg1, *args, **kwargs):
    # type: (str, *int, **Tuple[bool, ...]) -> None
    """
    Args:
        arg1: blah
        *args
        **kwargs
    """
    return
'''

    with tempfile.NamedTemporaryFile(suffix=".py") as f:
        with open(f.name, "w") as fw:
            fw.write(content)

        test_settings = override_settings(
            ALLOW_UNTYPED_ARGS=False,
            REQUIRE_RETURN_TYPE=False,
            IMPORT_COLLISION_POLICY=ImportCollisionPolicy.IMPORT,
            UNPATHED_TYPE_POLICY=UnpathedTypePolicy.FAIL,
        )
        inject.clear_and_configure(configuration_factory(test_settings))

        annotate(
            f.name, in_process=True, interactive=False, write=True, silent=True,
        )

        with open(f.name, "r") as fr:
            annotated = fr.read()

    assert annotated == expected
def test_allow_missing_args_section_no_args_func(allow_untyped_args):
    """
    If func has no args but 'Returns' is given then we should be
    able to annotate it.
    """
    content = '''
def identity():
    """
    Returns:
        Tuple[str, ...]: blah
    """
    return arg1
'''

    expected = '''from typing import Tuple


def identity():
    # type: () -> Tuple[str, ...]
    """
    Returns:
        blah
    """
    return arg1
'''

    with tempfile.NamedTemporaryFile(suffix=".py") as f:
        with open(f.name, "w") as fw:
            fw.write(content)

        test_settings = override_settings(
            ALLOW_UNTYPED_ARGS=allow_untyped_args,
            REQUIRE_RETURN_TYPE=False,
            IMPORT_COLLISION_POLICY=ImportCollisionPolicy.IMPORT,
            UNPATHED_TYPE_POLICY=UnpathedTypePolicy.FAIL,
        )
        inject.clear_and_configure(configuration_factory(test_settings))

        annotate(
            f.name, in_process=True, interactive=False, write=True, silent=True,
        )

        with open(f.name, "r") as fr:
            annotated = fr.read()

    assert annotated == expected
def test_property():
    """
    First arg is not annotatable
    """
    content = '''
class SomeClass:
    @property
    def method(obj):
        """
        Returns:
            int
        """
        return 1
'''

    expected = '''
class SomeClass:
    @property
    def method(obj):
        # type: () -> int
        """
        """
        return 1
'''

    with tempfile.NamedTemporaryFile(suffix=".py") as f:
        with open(f.name, "w") as fw:
            fw.write(content)

        test_settings = override_settings(
            ALLOW_UNTYPED_ARGS=False,
            REQUIRE_RETURN_TYPE=False,
            IMPORT_COLLISION_POLICY=ImportCollisionPolicy.IMPORT,
            UNPATHED_TYPE_POLICY=UnpathedTypePolicy.FAIL,
        )
        inject.clear_and_configure(configuration_factory(test_settings))

        annotate(
            f.name, in_process=True, interactive=False, write=True, silent=True,
        )

        with open(f.name, "r") as fr:
            annotated = fr.read()

    assert annotated == expected
Esempio n. 16
0
def mock_NLU_for(httpx_mock, dataset):
    with override_settings({
            "NLU_TAGGER_URL": NLU_URL,
            "NLU_CLASSIFIER_URL": CLASSIF_URL,
            "PJ_ES": ES_URL
    }):
        nlu_json = read_fixture(f"fixtures/autocomplete/nlu/{dataset}.json")
        httpx_mock.post(NLU_URL).respond(json=nlu_json)

        for q, data in FIXTURE_CLASSIF.items():
            httpx_mock.post(CLASSIF_URL,
                            json={
                                "text": q,
                                "domain": "poi",
                                "language": "fr",
                                "count": 10
                            }).respond(json=data)

        yield nlu_json
def test_package_imports(python_version, import_line, arg_type):
    content = f'''{import_line}

def no_op(arg1):
    """
    Args:
        arg1 ({arg_type}): blah
    """
    pass
'''

    expected = f'''{import_line}

def no_op(arg1):
    # type: ({arg_type}) -> None
    """
    Args:
        arg1: blah
    """
    pass
'''

    with tempfile.NamedTemporaryFile(suffix=".py") as f:
        with open(f.name, "w") as fw:
            fw.write(content)

        test_settings = override_settings(
            PYTHON_VERSION=python_version,
            ALLOW_UNTYPED_ARGS=False,
            REQUIRE_RETURN_TYPE=False,
            IMPORT_COLLISION_POLICY=ImportCollisionPolicy.IMPORT,
            UNPATHED_TYPE_POLICY=UnpathedTypePolicy.FAIL,
        )
        inject.clear_and_configure(configuration_factory(test_settings))

        annotate(
            f.name, in_process=True, interactive=False, write=True, silent=True,
        )

        with open(f.name, "r") as fr:
            annotated = fr.read()

    assert annotated == expected
def test_arg_annotation_signature_mismatch(signature, arg_annotations):
    annotations = "\n".join(
        f"        {name} ({type_}): {description}"
        for name, (type_, description) in arg_annotations.items()
    )
    content = f'''
def no_op({signature}):
    """
    Args:
{annotations}
    """
    pass
'''

    # in all cases we should not have annotated
    expected = content

    with tempfile.NamedTemporaryFile(suffix=".py") as f:
        with open(f.name, "w") as fw:
            fw.write(content)

        test_settings = override_settings(
            ALLOW_UNTYPED_ARGS=True,
            REQUIRE_RETURN_TYPE=False,
            IMPORT_COLLISION_POLICY=ImportCollisionPolicy.IMPORT,
            UNPATHED_TYPE_POLICY=UnpathedTypePolicy.FAIL,
        )
        inject.clear_and_configure(configuration_factory(test_settings))

        annotate(
            f.name, in_process=True, interactive=False, write=True, silent=True,
        )

        with open(f.name, "r") as fr:
            annotated = fr.read()

    assert annotated == expected
Esempio n. 19
0
def mock_autocomplete_get(httpx_mock):
    with override_settings({"BRAGI_BASE_URL": BASE_URL}):
        httpx_mock.get(
            re.compile(f"^{BASE_URL}/autocomplete.*q=bloublou")).respond(
                json=read_fixture("fixtures/autocomplete/empty.json"))

        httpx_mock.get(
            re.compile(f"^{BASE_URL}/autocomplete.*q=(paris|parigi).*")
        ).respond(json=read_fixture("fixtures/autocomplete/paris.json"))

        httpx_mock.get(
            re.compile(f"^{BASE_URL}/autocomplete.*q=auchan.*")).respond(
                json=read_fixture("fixtures/autocomplete/auchan.json"))

        httpx_mock.get(
            re.compile(
                rf"^{BASE_URL}/autocomplete.*q=43\+rue\+de\+paris\+rennes.*")
        ).respond(json=read_fixture(
            "fixtures/autocomplete/43_rue_de_paris_rennes.json"))

        httpx_mock.get(re.compile(f"^{BASE_URL}/autocomplete")).respond(
            json=FIXTURE_AUTOCOMPLETE)

        yield
Esempio n. 20
0
async def test_server():
    with override_settings(
            ASYNC_TASKS=False,
            INTERNAL_DATABASE_FILE=settings.INTERNAL_DATABASE_FILE + '.test'):
        from cloudcopy.server.app import api as app, tasks
        try:
            async with AsyncExitStack() as stack:
                client = await stack.enter_async_context(
                    AsyncClient(app=app, base_url='http://test'))
                test0 = await stack.enter_async_context(
                    setup_test_database('test0', url='file:test0'))
                test1 = await stack.enter_async_context(
                    setup_test_database('test1', url='file:test1'))
                test2 = await stack.enter_async_context(
                    setup_test_database('test2', url='file:test2'))

                await setup_db(test0, tables=('test1', 'test2', 'test3'))
                await setup_db(test1, tables=('test2', 'test3'), rows=5)
                await setup_db(test2, tables=('test3', ))

                databases = [{
                    'name': 'test0',
                    'url': 'file:test0',
                    'scope': {
                        'schemas': {
                            'main': True
                        }
                    }
                }, {
                    'name': 'test2',
                    'url': 'file:test2'
                }, {
                    'name': 'test3',
                    'url': 'file:test3',
                    'scope': {
                        'schemas': {
                            'main': True
                        }
                    }
                }]
                # POST
                for value in databases:
                    response = await client.post('/v0/databases/',
                                                 data=json.dumps(
                                                     {'data': value}))
                    assert response.status_code == 201
                    response = response.json()['data']
                    for k, v in value.items():
                        assert response[k] == v
                    value['id'] = response['id']

                # GET (collection)
                response = await client.get('/v0/databases/')

                assert response.status_code == 200
                response = response.json()['data']
                for i, value in enumerate(databases):
                    for k, v in value.items():
                        assert response[i][k] == v

                # GET (record)
                modify_index = 2
                id = databases[modify_index]['id']
                response = await client.get(f'/v0/databases/{id}/')

                assert response.status_code == 200
                response = response.json()['data']
                for k, v in databases[modify_index].items():
                    assert response[k] == v

                assert response['created']
                created = response['created']

                assert response['updated']
                updated = response['updated']

                # PUT
                # all writable fields not in response
                # should be reset to defaults
                response = await client.put(f'/v0/databases/{id}/',
                                            data=json.dumps({
                                                'data': {
                                                    'name': 'foo',
                                                    'url': 'file:test1'
                                                }
                                            }))
                assert response.status_code == 200
                response = response.json()['data']
                assert response['name'] == 'foo'
                assert response['url'] == 'file:test1'
                # unset "scope" was set to null
                assert response['scope'] == None
                # unchanged
                assert response['created'] == created
                assert response['updated'] >= updated
                updated = response['updated']

                # PATCH (by name)
                response = await client.patch(f'/v0/databases/foo/',
                                              data=json.dumps(
                                                  {'data': {
                                                      'name': 'test1'
                                                  }}))
                assert response.status_code == 200
                response = response.json()['data']
                assert response['name'] == 'test1'
                # unchanged
                assert response['url'] == 'file:test1'
                assert response['updated'] >= updated

                # Workflows
                response = await client.get(f'/v0/workflows')
                assert response.status_code == 200
                response = response.json()['data']
                assert response == []

                workflows = [
                    {
                        "name":
                        "diff-0-1",
                        "schedule": {
                            "immediate": True
                        },
                        "steps": [{
                            "type": "compare",
                            "hashes": True,
                            "source": databases[0]['id'],  # by id (test0)
                            "target": "test1"  # by name reference (test1)
                        }]
                    },
                    {
                        "name": "info-2",
                        "steps": [{
                            "type": "info",
                            "source": "file:test2"
                        }],
                        "schedule": {
                            "delay": "1 minute"
                        }
                    }
                ]
                # add workflow
                for workflow in workflows:
                    response = await client.post('/v0/workflows/',
                                                 data=json.dumps(
                                                     {'data': workflow}))
                    assert response.status_code == 201
                    response = response.json()['data']
                    for k, v in workflow.items():
                        assert response[k] == v
                    workflow['id'] = response['id']

                # DELETE (by newly changed name)
                response = await client.delete(f'/v0/databases/test1/')
                assert response.status_code == 204

                response = await client.get('/v0/databases/')
                assert len(response.json()['data']) == len(databases) - 1

                immediate_workflow = workflows[0]
                delayed_workflow = workflows[1]

                scheduled = tasks.scheduled()

                assert len(scheduled) == 1
                assert scheduled[0].name == 'workflow-execute'
                args, kwargs = scheduled[0].data
                assert args[0] == delayed_workflow['id']

                immediate_id = immediate_workflow['id']
                response = await client.get(
                    f'/v0/jobs/?f__workflow_id={immediate_id}')
                assert response.status_code == 200
                data = response.json()['data']

                assert len(data) == 1
                data = data[0]
                assert data['status'] == 'Succeeded'
                result = data['result']
                assert result == diff_0_1_result
        finally:
            # clean up test sqlite DB
            if os.path.exists(settings.INTERNAL_DATABASE_FILE):
                os.remove(settings.INTERNAL_DATABASE_FILE)
Esempio n. 21
0
def mock_autocomplete_unavailable(httpx_mock):
    with override_settings({"BRAGI_BASE_URL": BASE_URL}):
        httpx_mock.get(re.compile(f"^{BASE_URL}/autocomplete")).respond(502)
        yield
Esempio n. 22
0
def mock_autocomplete_post(httpx_mock):
    with override_settings({"BRAGI_BASE_URL": BASE_URL}):
        httpx_mock.post(re.compile(f"^{BASE_URL}/autocomplete")).respond(
            json=FIXTURE_AUTOCOMPLETE)
        yield
def test_py3_syntax():
    content = '''
class OtherClass(object):
    raise ValueError("WTF python 2")


def one(arg2):
    """
    Args:
        arg2 (str): blah

    Returns:
        my.module.SomeClass[str]: blah
    """
    try:
        SomeClass([])
    except TypeError as e:
        pass
    return SomeClass(arg2)


def two(arg1):
    """
    Args:
        arg1 (Tuple[str, ...]): blah

    Returns:
        Tuple[my.module.SomeClass[str], ...]: blah
    """
    print("print function with kwarg", end='end')
    return tuple(
        one(arg) for arg in arg1
    )
'''

    expected = '''from my.module import SomeClass
from typing import Tuple


class OtherClass(object):
    raise ValueError("WTF python 2")


def one(arg2):
    # type: (str) -> SomeClass[str]
    """
    Args:
        arg2: blah

    Returns:
        blah
    """
    try:
        SomeClass([])
    except TypeError as e:
        pass
    return SomeClass(arg2)


def two(arg1):
    # type: (Tuple[str, ...]) -> Tuple[SomeClass[str], ...]
    """
    Args:
        arg1: blah

    Returns:
        blah
    """
    print("print function with kwarg", end='end')
    return tuple(
        one(arg) for arg in arg1
    )
'''

    with tempfile.NamedTemporaryFile(suffix=".py") as f:
        with open(f.name, "w") as fw:
            fw.write(content)

        test_settings = override_settings(
            PYTHON_VERSION="3.6",
            ALLOW_UNTYPED_ARGS=False,
            REQUIRE_RETURN_TYPE=False,
            IMPORT_COLLISION_POLICY=ImportCollisionPolicy.IMPORT,
            UNPATHED_TYPE_POLICY=UnpathedTypePolicy.FAIL,
        )
        inject.clear_and_configure(configuration_factory(test_settings))

        annotate(
            f.name, in_process=True, interactive=False, write=True, silent=True,
        )

        with open(f.name, "r") as fr:
            annotated = fr.read()

    assert annotated == expected
def test_arg_annotation_signature_validate(signature, arg_annotations):
    annotations = "\n".join(
        f"        {name} ({type_}): {description}"
        for name, (type_, description) in arg_annotations.items()
    )
    content = f'''
def no_op({signature}):
    """
    Args:
{annotations}
    """
    pass
'''

    def splatify(name, type_):
        if name.startswith("**"):
            return f"**{type_}"
        elif name.startswith("*"):
            return f"*{type_}"
        else:
            return type_

    # I guess this is an 'oracle' i.e. an alternate implementation (meh)
    stripped_annotations = "\n".join(
        f"        {name}: {description}"
        for name, (_, description) in arg_annotations.items()
    )
    str_types = ", ".join(
        splatify(name, type_) for name, (type_, _) in arg_annotations.items()
    )
    type_comment = f"# type: ({str_types}) -> None"

    # only builtin types in examples, no imports needed
    expected = f'''
def no_op({signature}):
    {type_comment}
    """
    Args:
{stripped_annotations}
    """
    pass
'''

    with tempfile.NamedTemporaryFile(suffix=".py") as f:
        with open(f.name, "w") as fw:
            fw.write(content)

        test_settings = override_settings(
            PYTHON_VERSION="3.8",  # keyword-only args
            ALLOW_UNTYPED_ARGS=True,
            REQUIRE_RETURN_TYPE=False,
            IMPORT_COLLISION_POLICY=ImportCollisionPolicy.IMPORT,
            UNPATHED_TYPE_POLICY=UnpathedTypePolicy.FAIL,
        )
        inject.clear_and_configure(configuration_factory(test_settings))

        annotate(
            f.name, in_process=True, interactive=False, write=True, silent=True,
        )

        with open(f.name, "r") as fr:
            annotated = fr.read()

    assert annotated == expected