sourcetip

py.test의 각 테스트 전후에 코드를 실행하시겠습니까?

fileupload 2023. 6. 12. 21:50
반응형

py.test의 각 테스트 전후에 코드를 실행하시겠습니까?

테스트 제품군에서 각 테스트 전후에 추가 설정 및 해체 검사를 실행하려고 합니다.저는 고정 장치를 살펴보았지만 그것이 올바른 접근법인지 확실하지 않습니다.각 테스트 전에 설정 코드를 실행하고 각 테스트 후에 해체 검사를 실행해야 합니다.

내 사용 사례는 제대로 정리되지 않는 코드를 확인하는 것입니다. 코드가 임시 파일을 남깁니다.제 설정에서, 저는 파일을 확인할 것이고, 분해할 때도 파일을 확인할 것입니다.추가 파일이 있으면 테스트가 실패했으면 합니다.

py.테스트 고정장치는 당신의 목적을 달성하기에 기술적으로 적절한 방법입니다.

다음과 같은 고정 장치를 정의하면 됩니다.

@pytest.fixture(autouse=True)
def run_around_tests():
    # Code that will run before your test, for example:
    files_before = # ... do something to check the existing files
    # A test function will be run at this point
    yield
    # Code that will run after your test, for example:
    files_after = # ... do something to check the existing files
    assert files_before == files_after

당신의 고정 장치를 선언함으로써autouse=True동일한 모듈에 정의된 각 테스트 기능에 대해 자동으로 호출됩니다.

그렇긴 하지만, 한 가지 주의할 점이 있습니다.설정/분해 시 주장하는 것은 논란의 여지가 있는 관행입니다.저는 py.test 주요 저자들이 그것을 좋아하지 않는다는 인상을 받고 있습니다(저도 그것을 좋아하지 않습니다, 그래서 제 인식에 영향을 줄 수 있습니다). 그래서 당신은 앞으로 나아갈 때 약간의 문제나 거친 가장자리에 부딪힐 수 있습니다.

를 사용할 수 있습니다.fixture당신이 원하는 것을 이루기 위해.

import pytest

@pytest.fixture(autouse=True)
def run_before_and_after_tests(tmpdir):
    """Fixture to execute asserts before and after a test is run"""
    # Setup: fill with any logic you want

    yield # this is where the testing happens

    # Teardown : fill with any logic you want

자세한 설명

  1. @pytest.fixture(autouse=True)문서에서: "경우에 따라 함수 인수를 명시적으로 선언하거나 고정 장치 데코레이터를 사용하지 않고 고정 장치를 자동으로 호출할 수 있습니다."따라서 이 고정 장치는 테스트가 실행될 때마다 실행됩니다.

  2. # Setup: fill with any logic you want이 로직은 모든 테스트가 실제로 실행되기 전에 실행됩니다.이 경우 실제 테스트 전에 실행될 Assert 문을 추가할 수 있습니다.

  3. yield있는 처럼, 가 진행됩니다.

  4. # Teardown : fill with any logic you want이 논리는 모든 테스트 후에 실행됩니다.이 논리는 테스트 중에 발생하는 작업에 관계없이 실행됩니다.

참고:pytest실패한 테스트와 테스트를 실행하는 동안 오류 사이에 차이가 있습니다.실패는 테스트가 어떤 방식으로든 실패했음을 나타냅니다.오류는 올바른 테스트를 수행할 수 없음을 나타냅니다.

다음 예를 생각해 보십시오.

테스트를 실행하기 전에 Assert가 실패함 -> ERROR

import pytest


@pytest.fixture(autouse=True)
def run_around_tests():
    assert False # This will generate an error when running tests
    yield
    assert True

def test():
    assert True

테스트 실행 후 Assert 실패 -> ERROR

import pytest


@pytest.fixture(autouse=True)
def run_around_tests():
    assert True
    yield
    assert False

def test():
    assert True

테스트 실패 -> 실패

import pytest


@pytest.fixture(autouse=True)
def run_around_tests():
    assert True
    yield
    assert True

def test():
    assert False

테스트 통과 -> PASSED

import pytest


@pytest.fixture(autouse=True)
def run_around_tests():
    assert True
    yield
    assert True

def test():
    assert True

당신이 원하는 것이 바로 고정장치입니다.그것이 바로 그것들이 목적으로 설계된 것입니다.

파이테스트 스타일 고정장치를 사용할지, 설정해체(모듈, 클래스 또는 방법 수준) xUnit 스타일 고정장치를 사용할지는 환경과 개인 취향에 따라 달라집니다.

당신이 설명한 바로는, 당신은 파이테스트 오토유즈 고정장치를 사용할 수 있을 것 같습니다.
또는 xUnit 스타일 함수 레벨 setup_function()/teardown_function().

파이테스트는 당신을 완전히 덮었습니다.정보의 소방 호스일 수도 있습니다.

Pytest의 모듈 레벨 설정/분해 고정 장치를 사용할 수 있습니다.

링크가 있습니다.

http://pytest.org/latest/xunit_setup.html

다음과 같이 작동합니다.

 def setup_module(module):
     """ setup any state specific to the execution of the given module."""

 def teardown_module(module):
     """ teardown any state that was previously setup with a setup_module
     method."""

 Test_Class():
        def test_01():
          #test 1 Code

그것은 부를 것입니다.setup_module이 시험 전에 그리고teardown_module테스트가 완료된 후.

각 테스트 스크립트에 이 고정 장치를 포함하여 각 테스트에 대해 실행할 수 있습니다.

디렉토리의 모든 테스트에 공통적인 것을 사용하려는 경우 패키지/디렉토리 수준 고정 장치를 사용할 수 있습니다.

http://pythontesting.net/framework/nose/nose-fixture-reference/ # 패키지

__init__.py다음을 포함할 수 있는 패키지 파일

     def setup_package():
       '''Set up your environment for test package'''

     def teardown_package():
        '''revert the state '''

데코레이터를 사용할 수도 있지만 프로그래밍적으로 사용할 수 있으므로 각 방법에 데코레이터를 넣을 필요가 없습니다.

다음 코드에서 몇 가지를 가정합니다.

테스트 방법의 이름은 모두 "testXXX()"와 같습니다. 데코레이터는 테스트 방법이 구현된 동일한 모듈에 추가됩니다.

def test1():
    print ("Testing hello world")

def test2():
    print ("Testing hello world 2")

#This is the decorator
class TestChecker(object):
    def __init__(self, testfn, *args, **kwargs):
        self.testfn = testfn

    def pretest(self):
        print ('precheck %s' % str(self.testfn))
    def posttest(self):
        print ('postcheck %s' % str(self.testfn))
    def __call__(self):
        self.pretest()
        self.testfn()
        self.posttest()


for fn in dir() :
    if fn.startswith('test'):
        locals()[fn] = TestChecker(locals()[fn])

이제 테스트 방법을 호출하면...

test1()
test2()

출력은 다음과 같아야 합니다.

precheck <function test1 at 0x10078cc20>
Testing hello world
postcheck <function test1 at 0x10078cc20>
precheck <function test2 at 0x10078ccb0>
Testing hello world 2
postcheck <function test2 at 0x10078ccb0>

클래스 방법으로 검정 방법을 사용하는 경우 이 방법도 유효합니다.예를 들어:

class TestClass(object):
    @classmethod
    def my_test(cls):
        print ("Testing from class method")

for fn in dir(TestClass) :
    if not fn.startswith('__'):
        setattr(TestClass, fn, TestChecker(getattr(TestClass, fn)))

호출:TestClass.my_test()인쇄 예정:

precheck <bound method type.my_test of <class '__main__.TestClass'>>
Testing from class method 
postcheck <bound method type.my_test of <class '__main__.TestClass'>>

오래된 질문이지만 개인적으로 문서에서 다른 방법을 찾았습니다: 사용:pytest.ini파일:

[pytest]
usefixtures = my_setup_and_tear_down
import pytest

@pytest.fixture
def my_setup_and_tear_down():

    # SETUP
    # Write here the logic that you need for the setUp

    yield # this statement will let the tests execute

    # TEARDOWN 
    # Write here the logic that you need after each tests

수율 문 및 테스트 실행 방법 정보: HERE

기본적으로 고정장치는 다음과 같습니다.scope=function따라서 다음과 같은 정의를 사용하면

@pytest.fixture
def fixture_func(self)

기본값은(scope='function').

따라서 각 테스트 후에 고정 장치 기능의 모든 피니셔가 호출됩니다.

언급URL : https://stackoverflow.com/questions/22627659/run-code-before-and-after-each-test-in-py-test

반응형