Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/unit-testing/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 烧瓶单元测试-如何为每个测试重置app.url\u映射?_Python_Unit Testing_Flask_Pytest - Fatal编程技术网

Python 烧瓶单元测试-如何为每个测试重置app.url\u映射?

Python 烧瓶单元测试-如何为每个测试重置app.url\u映射?,python,unit-testing,flask,pytest,Python,Unit Testing,Flask,Pytest,我正在为Flask应用程序编写一系列单元测试。每个测试的设置如下所示: 在测试模式下创建烧瓶应用程序(app.testing=True) 在测试应用程序内的蓝图上装载测试端点(路由) (然后,对端点进行一些测试…) 问题在于,我的测试中使用的应用程序实例将以前测试中添加的路由累加起来,而不是从头开始。就好像我每次创建一个新的应用程序时,app.url\u map都不会重置一样 下面是我的setup函数的代码,它在每次测试之前运行(我使用的是pytest): def设置(烧瓶应用程序): ap

我正在为Flask应用程序编写一系列单元测试。每个测试的设置如下所示:

  • 在测试模式下创建烧瓶应用程序(
    app.testing=True
  • 在测试应用程序内的蓝图上装载测试端点(路由)
  • (然后,对端点进行一些测试…)
问题在于,我的测试中使用的应用程序实例将以前测试中添加的路由累加起来,而不是从头开始。就好像我每次创建一个新的应用程序时,
app.url\u map
都不会重置一样

下面是我的setup函数的代码,它在每次测试之前运行(我使用的是pytest):

def设置(烧瓶应用程序):
app=flask\u app
#在API蓝图上装载测试端点。
bp=应用程序蓝图[“api”]
添加规则('/foo',view\u func=test\u view,methods=['GET',]))
打印(应用程序url\u地图)
flask\u app
是一个pytest夹具,用于创建新的测试应用程序,如下所示:

@pytest.fixture()
def flask_app():
从我的应用导入创建应用
应用程序=创建应用程序(“测试”)
#在应用程序上配置一堆东西。。。
返回应用程序
如果我编写了三个测试,我的
设置
函数将被调用三次,并为
app.url\u map
记录以下内容:

# 1st test — My new '/api/foo' rule doesn't even show yet...
# For that, I'd need to re-register the blueprint after adding the URL to it.

Map([<Rule '/' (HEAD, OPTIONS, GET) -> main.index>,
<Rule '/static/<filename>' (HEAD, OPTIONS, GET) -> static>])


# 2nd test — Rule '/api/foo' added once

Map([<Rule '/' (HEAD, OPTIONS, GET) -> main.index>,
<Rule '/static/<filename>' (HEAD, OPTIONS, GET) -> static>,
<Rule '/api/foo' (HEAD, OPTIONS, GET) -> api.test_view>])


# 3rd test — Rule '/api/foo' added twice

Map([<Rule '/' (HEAD, OPTIONS, GET) -> main.index>,
<Rule '/static/<filename>' (HEAD, OPTIONS, GET) -> static>,
<Rule '/api/foo' (HEAD, OPTIONS, GET) -> api.test_view>],
<Rule '/api/foo' (HEAD, OPTIONS, GET) -> api.test_view>]
这是有道理的,因为我尝试多次添加相同的视图。。。为什么每次运行新测试时,我都不能得到一个新的应用程序实例


我甚至不确定这是烧瓶问题还是pytest问题…:(

我可以通过将您为安装程序实例化的所有内容移动到安装程序中(甚至是导入您在那里使用的库)来解决类似的问题。当然,这可以通过使用create_app()以更优雅的方式完成方法,就像您对整个flask应用程序所做的那样。这里需要注意的重要一点是,获取将状态(此处为端点)保持在全局范围之外的实例,并将其移动到create_app()方法中


如果您需要更多信息,请告诉我。

我删除了我的答案,因为您是对的,我没有动态添加路线(这是我匆忙回答问题时忽略的一个关键点)。干杯!
AssertionError: View function mapping is overwriting an existing endpoint function:
lib/flask/app.py:1068: AssertionError