如何在测试 Flask 应用时处理导入:断言错误:视图函数映射正在覆盖现有终结点函数



我正在努力理解如何在 Flask 中编写测试。

我继承了一个应用程序,该应用程序已经有一堆测试,可以到达像/login这样的路线,并测试响应是否符合预期。

我的情况要复杂得多。 我需要测试一个路由/方法,根据情况,点击外部 api,确定应用程序本身运行的容器中是否存在路径,启动一个需要 10+ 分钟才能在不同的机器上运行的进程 - 各种各样的事情。所以我不能只是走上路线,看看我是否得到了我想要的;我需要嘲笑和修补来模仿各种外部世界状态的影响。

现在我有一条brain_db/views.py这样的路线:

@app.route('/label_view/<int:scan_number>')
@login_required
def label_view(scan_number):
<so much complicated logic>

在同一文件中定义的第一个路由brain_db/views.py

@app.route('/surface_test')
def surface_test():
<some code>

以下是引发错误的文件的简化版本:

import unittest
from mock import MagicMock, patch
from flask_brain_db.test_helpers import set_up, tear_down
from flask_brain_db.brain_db.models import Scan
from brain_db.views import label_view
class BrainDBTest(unittest.TestCase):
def setUp(self):
app, db = set_up()
scan = Scan(1, '000001', '000001_MR1', 'scan.nii.gz', scan_number=1)
db.session.add(scan)
scan = Scan.query.filter(Scan.scan_number == 1).first()
db.session.commit()
def tearDown(self):
tear_down()
def mock_volume_views_setup(self)
scan = Scan.query.filter(Scan.scan_number == 1).first()
container_file_path = '/path/to/file/in/container'
return scan, container_file_path
def mock_os_path_exists(self, arg):
return True
@patch('brain_db_helpers.volume_views_setup', mock_volume_views_setup)
@patch('os.path.exists', mock_os_path_exists)
def test_label_view(self):
rv = label_view(1)
assert(True) # I'll actually write tests when I figure out that I can!
print rv

这是错误:

======================================================================
ERROR: brain_db.tests.test (unittest.loader.ModuleImportFailure)
----------------------------------------------------------------------
ImportError: Failed to import test module: brain_db.tests.test
Traceback (most recent call last):
File "/usr/local/lib/python2.7/unittest/loader.py", line 254, in _find_tests
module = self._get_module_from_name(name)
File "/usr/local/lib/python2.7/unittest/loader.py", line 232, in _get_module_from_name
__import__(name)
File "/usr/src/app/flask_brain_db/brain_db/tests/test.py", line 7, in <module>
from brain_db.views import label_view
File "/usr/src/app/flask_brain_db/brain_db/views.py", line 36, in <module>
@app.route('/surface_test')
File "/usr/local/lib/python2.7/site-packages/flask/app.py", line 1250, in decorator
self.add_url_rule(rule, endpoint, f, **options)
File "/usr/local/lib/python2.7/site-packages/flask/app.py", line 66, in wrapper_func
return f(self, *args, **kwargs)
File "/usr/local/lib/python2.7/site-packages/flask/app.py", line 1221, in add_url_rule
'existing endpoint function: %s' % endpoint)
AssertionError: View function mapping is overwriting an existing endpoint function: surface_test

我做了什么来尝试解决我的问题:我已经阅读了一堆关于SO的帖子,这些帖子引用了相同的AssertionError。 例如 1、2。 我可以看到问题的总体形式是我的路由已经被定义,并且

from brain_db.views import label_view

再次执行views模块,从而重新定义路由,因此我抛出错误。

我不明白的是我应该如何避免这种情况。 我需要能够将方法导入另一个文件才能对其进行测试。 所有的路线都应该用if __name__ == main包裹吗?我是 Flask 开发的新手,还没有看到这种情况的示例代码;我怀疑这是正确的解决方案;这只是当您尝试搜索以防止代码在导入时执行时提供的唯一内容。

我现在运行测试的方式是通过应用程序顶层的文件manage.py。 它包含以下方法:

@manager.command
def test():
"""Runs the tests without coverage"""
tests = unittest.TestLoader().discover(start_dir='.', pattern='test*.py')
res = unittest.TextTestRunner(verbosity=2).run(tests)
sys.exit(not res.wasSuccessful())

我在命令行运行python manage.py test

同样可能相关的是,虽然我已经将失败的测试放在brain_db子模块中,但在它之前运行了几个测试,这些测试命中了应用程序中定义的路由并测试了预期结果。 但是,注释掉这些测试对我的测试失败的方式没有影响。

最后,我最初在第from flask_brain_db.brain_db.models import Scan行收到错误:

ERROR: brain_db.tests.test (unittest.loader.ModuleImportFailure)
----------------------------------------------------------------------
ImportError: Failed to import test module: brain_db.tests.test
Traceback (most recent call last):
File "/usr/local/lib/python2.7/unittest/loader.py", line 254, in _find_tests
module = self._get_module_from_name(name)
File "/usr/local/lib/python2.7/unittest/loader.py", line 232, in _get_module_from_name
__import__(name)
File "/usr/src/app/flask_brain_db/brain_db/tests/test.py", line 5, in <module>
from flask_brain_db.brain_db.models import Scan
File "/usr/src/app/flask_brain_db/brain_db/models.py", line 6, in <module>
class Scan(db.Model):
File "/usr/local/lib/python2.7/site-packages/flask_sqlalchemy/model.py", line 67, in __init__
super(NameMetaMixin, cls).__init__(name, bases, d)
File "/usr/local/lib/python2.7/site-packages/flask_sqlalchemy/model.py", line 121, in __init__
super(BindMetaMixin, cls).__init__(name, bases, d)
File "/usr/local/lib/python2.7/site-packages/sqlalchemy/ext/declarative/api.py", line 65, in __init__
_as_declarative(cls, classname, cls.__dict__)
File "/usr/local/lib/python2.7/site-packages/sqlalchemy/ext/declarative/base.py", line 116, in _as_declarative
_MapperConfig.setup_mapping(cls, classname, dict_)
File "/usr/local/lib/python2.7/site-packages/sqlalchemy/ext/declarative/base.py", line 144, in setup_mapping
cfg_cls(cls_, classname, dict_)
File "/usr/local/lib/python2.7/site-packages/sqlalchemy/ext/declarative/base.py", line 172, in __init__
self._setup_table()
File "/usr/local/lib/python2.7/site-packages/sqlalchemy/ext/declarative/base.py", line 465, in _setup_table
**table_kw)
File "/usr/local/lib/python2.7/site-packages/flask_sqlalchemy/model.py", line 90, in __table_cls__
return sa.Table(*args, **kwargs)
File "/usr/local/lib/python2.7/site-packages/sqlalchemy/sql/schema.py", line 439, in __new__
"existing Table object." % key)
InvalidRequestError: Table 'scan' is already defined for this MetaData instance.  Specify 'extend_existing=True' to redefine options and columns on an existing Table object.

我通过包括

__table_args__ = {'extend_existing': True}

在模型定义中,但我不知道我是否应该这样做,我怀疑我只是推迟了我现在遇到的相同问题。 似乎根本问题是我不知道如何在不重新定义一堆已经定义的东西的情况下编写测试。

解决这个问题的正确方法是什么? 如果我需要提供任何其他信息,请告诉我。

您应该能够从应用程序对象访问所有视图函数。尝试删除"from brain_db.views import label_view"行,改为在运行 set_up(( 后使用以下方法定义label_view方法:

label_view = app.view_functions["label_view"]

最新更新