在Flask中测试装饰的API路径

时间:2017-09-06 08:19:28

标签: python flask python-decorators

我有以下简单的控制器

@companies.route('/companies/<int:id>', methods=['GET'])
@inject_repository(CompanyRepository)
def get_company(repository, id):
    """
    GET /companies/id
    """
    company = repository.get(pk=id)
    return jsonify(company.to_json())

DAO正由@inject_repository(CompanyRepository)

注入

然而,我不知道在测试时发生的事情:

def test_get_company(self):

    response = self.client.get(url_for('companies.get_company', id=1))
    data = json.loads(response.get_data(as_text=True))

    assert_equal(response.status_code, 200)

我收到以下错误

TypeError: get_company() missing 1 required positional argument: 'id'

控制器是不是被装饰了?

装饰员代码

def inject_repository(repository_class):

    def decorator(func):

        @wraps(func)
        def wrapper(*args, **kwargs):

            if 'psql' in class_init_fields(repository_class):
                repository = psql_repository_for(
                    repository_model=repository_class,
                    connection_meta=current_app.config['POSTGRESQL'])

            else:
                raise ValueError("'{}' repository cannot be injected".format(repository_class.__name__))

            return func(repository=repository)

        return wrapper

    return decorator

1 个答案:

答案 0 :(得分:1)

您没有将装饰器中的参数传递给装饰函数。

def wrapper(*args, **kwargs):
    ...
    kwargs['repository'] = repository
    return func(*args, **kwargs)