首页 > 解决方案 > 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 ?

标签: pythonflaskpython-unittest

解决方案


setUp在每个测试方法之前被调用。因此,如果您运行整个测试用例,它将被调用两次(每种测试方法一次)。

要为 仅运行一次TestCase,您可以尝试覆盖该__init__方法(请参阅此 SO 问题)或setUpClass 或 setUpModule。YMMV 取决于您使用的 python 版本和测试运行器。


推荐阅读