Skip to content

Instantly share code, notes, and snippets.

@allenyang79
Last active March 21, 2018 06:37
Show Gist options
  • Select an option

  • Save allenyang79/b502612562f07ba82eaeffe757d0db3b to your computer and use it in GitHub Desktop.

Select an option

Save allenyang79/b502612562f07ba82eaeffe757d0db3b to your computer and use it in GitHub Desktop.
@pytest.fixture(scope="session", autouse=True)

有時候在跑unittest的時候,需要一些前置作業,多半可以寫在setUp或tearDown上

pytest提供fixture, 可以定義每一次的跑unitest的session, module, class, method,都預先跑某個準備函式

例如,我希望跑unittest時先起一個mock database,並在結束時,關掉這個mock database 就可以寫在conftest.py

#conftest.py 

@pytest.fixture(scope="session", autouse=True)
def on_begin(request):
    print "on_begin"
    def on_finish():
      print "in_finish"
      request.addfinalizer(on_finish)
# -*- coding: utf-8 -*-
import pytest
@pytest.fixture(scope="session", autouse=True)
def callattr_ahead_of_alltests(request):
print "before all test start"
def on_session_finish():
print "after all test start"
request.addfinalizer(on_session_finish)
# -*- coding: utf-8 -*-
import unittest
def test_one():
"""test_one"""
assert True
class PublicTest(unittest.TestCase):
def setUp(self):
pass
def tearDown(self):
pass
def test_two(self):
"""test_two"""
self.assertTrue(True)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment