在测试Flask时在测试之间有共同的数据库

时间:2015-09-08 08:51:46

标签: flask

我正在针对数据库运行DDL并在每个测试的设置中创建应用程序上下文。有没有办法只运行一次?我正在使用test.py来发现并运行这些测试。

ALTER TABLE [dbo].[PricePlan](
    [Id] [uniqueidentifier] NOT NULL,
    [Name] [varchar](50) NULL,
    [ActivationPrice] [decimal](5, 2) NULL,
    ... //Other columns
 CONSTRAINT [PK_Price_Plans] PRIMARY KEY CLUSTERED 
(
    [Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

“测试之间”是指同一类中的测试之间以及测试类本身之间的测试。

1 个答案:

答案 0 :(得分:1)

您可以使用setupUpClass和tearDownClass,这样每个类只执行一次昂贵的操作

class TestStuff(unittest.TestCase):
    @classmethod
    def setUpClass(cls):
        db.create_all()

    @classmethod
    def tearDownClass(cls):
        db.drop_all()

    def setUp(self):
        self.app_context = app.app_context()
        self.app_context.push()

    def tearDown(self):
        db.session.remove()
        self.app_context.pop()

    def test_lookup1(self):
        dostuff()

    def test_lookup2(self):
        dostuff()

`

对于测试之间的设置和拆卸,您可以使用module fixtures 模块中的任何测试都只会调用一次安装和拆卸模块

import unittest


def setUpModule():
    print('Expensive Setup')


def tearDownModule():
    print('Expensive Tear Down')


class TestStuff(unittest.TestCase):

    @classmethod
    def setUpClass(cls):
        pass

    @classmethod
    def tearDownClass(cls):
        pass


class Test1(TestStuff):
    def test_1(self):
        print('Test1')


class Test2(TestStuff):
    def test_1(self):
        print('Test1')


if __name__ == '__main__':
    unittest.main()