python - Flask app created twice during python unittest
问题描述
I have an app.py file which creates an flask app
def create_app():
app = Flask(__name__)
return app
I am trying to write an unittest for my module and below is the file
from app import create_app
class TestCase(unittest.TestCase):
def setUp(self):
self.app = create_app()
self.client = self.app.test_client()
ctx = self.app.app_context()
ctx.push()
def test_healthcheck(self):
res = self.client.get("/")
self.assertEqual(res.status_code, 200)
def test_tenant_creation(self):
res = self.client.post("/tenants")
self.assertEqual(res.status_code, 200)
When i run individual test methods it is working fine. But when i run the entire test case , the create app is called again which causes issues since my create app has dependencies which needs to be called only once.
Is it possible to create app only once ?
解决方案
setUp在每个测试方法之前被调用。因此,如果您运行整个测试用例,它将被调用两次(每种测试方法一次)。
要为 仅运行一次TestCase
,您可以尝试覆盖该__init__
方法(请参阅此 SO 问题)或setUpClass 或 setUpModule。YMMV 取决于您使用的 python 版本和测试运行器。
推荐阅读
- javascript - 在img64背景jsPDF上添加第二个图像
- django - 如何在 Django 循环中排除项目?
- kubernetes - 阿里云节点内存 Requested/Limited/Used
- wordpress - 登录 WP - 将单个字段连接到外部 api
- java - 当我尝试在 C# 上启动这个 .jar 文件时,为什么它不会运行?
- git - 通过cherry-pick将行添加到不同的位置导致冲突
- python - NOT NULL 约束失败:auth_user.password
- react-native - 将导航从子组件传递到父组件获取 TypeError
- flutter - Flutter:如何从 Firebase 获取实时数据库(导入的 Json)中的数据
- python-3.x - 通过 stackoverflow 错误使用 Selenium 登录 Google