gpt4 book ai didi

python - 运行单个 Flask 单元测试通过但运行所有测试给出 AssertionError

转载 作者:行者123 更新时间:2023-11-28 17:35:19 25 4
gpt4 key购买 nike

我有使用 Flask-Restful 库的 Flask 应用程序。我的应用程序结构设置如下:

server
application.py
- app
users.py
- tests
test_users.py
- common
tests.py

我的应用程序设置在 application.py 中定义。我正在使用工厂模式。

api = Api(prefix='/api/v0')

def create_app(config_filemane):
flask_app = Flask(__name__)
flask_app.config.from_object(config_filemane)
db.init_app(flask_app)

from app.users import add_user_resources
add_user_resources()
api.init_app(flask_app)

return flask_app

在 users.py 中,我有我的资源子类:

class UserListAPI(Resource):

def __init__(self):
super(UserListAPI, self).__init__()

def get(self):

def post(self):


class UserAPI(Resource):

def __init__(self):
super(UserAPI, self).__init__()

def get(self, id):

def put(self, id):

def delete(self, id):

def add_user_resources():
api.add_resource(UserListAPI, '/users', endpoint='users')
api.add_resource(UserAPI, '/users/<id>', endpoint='user')

请看我的github完整代码页面。

我在 common/tests.py 中设置我的单元测试类,然后是 snippet .

我使用 Nose 运行我的测试。当我运行任何一个测试时,它都会通过。当我使用

运行所有测试时
$ nosetests

我收到以下错误:

AssertionError: View function mapping is overwriting an existing endpoint function: users

我认为错误是由于测试运行程序在注册另一个 Flask-Restful 资源后尝试注册它们造成的。在 users.py 中,我有两个 Resource 子类:UsersListAPIUsersAPI。 (如果你看到 github 页面,我在 trips.py 中也有相同的设置。)

我认为运行单个 TestCase 不会引发错误,因为我在基本案例中为 TestCase 调用了一次 _pre_setup(),其中创建了测试应用程序,但我仍然得到错误,例如,我运行测试:

$ nosetests app.tests.test_users:UsersTest

我仍然得到 AssertionError

有什么想法吗?

编辑:这是我的测试文件。

common/tests.py 中的基本测试文件:

from flask.ext.testing import TestCase
from unittest import TestCase

from application import create_app

class BaseTestCase(TestCase):

def __call__(self, result=None):
self._pre_setup()
super(BaseTestCase, self).__call__(result)
self._post_teardown()

def _pre_setup(self):
self.app = create_app('settings_test')
self.client = self.app.test_client()
self._ctx = self.app.test_request_context()
self._ctx.push()

def _post_teardown(self):
self._ctx.pop()

请注意,我正在从 flask.ext.testing 和 unittest 导入 TestCase,显然在实际运行测试时不会同时导入。当我从 flask.ext.testcase 导入时,单个测试失败。从 unittest 导入单个测试通过:

$ nosetests app.tests.test_users:UsersTest.test_get_all_users

在这两种情况下,运行所有测试或仅运行 UsersTest 测试用例,测试都会失败。实际的测试文件,test_users.py 很长。我会将其作为 gist 提供.我删除了所有多余的代码,只留下两个测试。如果您想查看完整的测试文件,可以在我的 github repo 中找到。 .

最佳答案

想通了:

我必须将行 api = Api(prefix='/api/v0') 移动到函数 create_app 中并移动 add_resource 也可用于 create_app:

def create_app(config_filemane):
flask_app = Flask(__name__)
...
api = Api(prefix='/api/v0')
api.add_resource(UserListAPI, '/users', endpoint='users')
api.add_resource(UserAPI, '/users/<id>', endpoint='user')
...
return flask_app

api 对象不再是全局的,但我认为我不需要在其他地方这样做。

关于python - 运行单个 Flask 单元测试通过但运行所有测试给出 AssertionError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31142994/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com