테스트를 통해 pytest 클래스를 올바르게 설정하고 분해하는 방법은 무엇입니까?
엔드 투 엔드 테스트에 셀레늄을 사용 setup_class
하고 있으며 사용 teardown_class
방법 과 방법을 알 수 없습니다 .
setup_class
메서드에서 브라우저를 설정 한 다음 클래스 메서드로 정의 된 여러 테스트를 수행하고 마지막으로 teardown_clas
s 메서드 에서 브라우저를 종료해야합니다 .
그러나 논리적으로 나쁜 해결책으로 보입니다. 사실 내 테스트는 클래스가 아닌 객체로 작동하기 때문입니다. self
모든 테스트 메서드 내에서 매개 변수를 전달 하므로 개체의 var에 액세스 할 수 있습니다.
class TestClass:
def setup_class(cls):
pass
def test_buttons(self, data):
# self.$attribute can be used, but not cls.$attribute?
pass
def test_buttons2(self, data):
# self.$attribute can be used, but not cls.$attribute?
pass
def teardown_class(cls):
pass
그리고 클래스에 대한 브라우저 인스턴스를 생성하는 것도 옳지 않은 것 같습니다. 모든 객체에 대해 개별적으로 생성해야합니다.
그래서, 사용할 필요가 __init__
와 __del__
대신의 방법 setup_class
과 teardown_class
?
따르면 지그 완결 / 해체 실행 코드 를 사용하여 addfinalizer
"과거"이다.
역사적으로 알 수 있듯이 분해 코드를 작성하는 또 다른 방법은 요청 객체를 조명기 함수로 받아들이고 request.addfinalizer를 한 번 또는 여러 번 호출하는 것입니다.
설정 및 해체에 대한 현재 모범 사례는 yield
import pytest
@pytest.fixture()
def resource():
print("setup")
yield "resource"
print("teardown")
class TestResource(object):
def test_that_depends_on_resource(self, resource):
print("testing {}".format(resource))
그것을 실행하면
$ py.test --capture=no pytest_yield.py
=== test session starts ===
platform darwin -- Python 2.7.10, pytest-3.0.2, py-1.4.31, pluggy-0.3.1
collected 1 items
pytest_yield.py setup
testing resource
.teardown
=== 1 passed in 0.01 seconds ===
"클래스 메서드로 정의 된 테스트" 를 작성할 때 실제로 클래스 메서드 ( 클래스 를 첫 번째 매개 변수로 받는 메서드 ) 또는 일반 메서드 ( 인스턴스 를 첫 번째 매개 변수로 받는 메서드 )를 의미합니까?
귀하의 예제는 self
테스트 방법을 사용 하기 때문에 후자를 가정하고 있으므로 setup_method
대신 사용해야 합니다.
class Test:
def setup_method(self, test_method):
# configure self.attribute
def teardown_method(self, test_method):
# tear down self.attribute
def test_buttons(self):
# use self.attribute for test
테스트 메서드 인스턴스는 setup_method
및에 전달 teardown_method
되지만 설정 / 해체 코드가 테스트 컨텍스트를 알 필요가없는 경우 무시할 수 있습니다. 자세한 내용은 여기 에서 확인할 수 있습니다 .
또한 py.test의 fixtures 는 더 강력한 개념이므로 익숙해지는 것이 좋습니다 .
@Bruno가 제안했듯이 pytest 픽스처를 사용하는 것은 두 테스트 클래스 또는 단순한 테스트 기능에 대해 액세스 할 수있는 또 다른 솔루션입니다. 다음은 python2.7 함수를 테스트하는 예입니다 .
import pytest
@pytest.fixture(scope='function')
def some_resource(request):
stuff_i_setup = ["I setup"]
def some_teardown():
stuff_i_setup[0] += " ... but now I'm torn down..."
print stuff_i_setup[0]
request.addfinalizer(some_teardown)
return stuff_i_setup[0]
def test_1_that_needs_resource(some_resource):
print some_resource + "... and now I'm testing things..."
따라서 실행 test_1...
하면 다음이 생성됩니다.
I setup... and now I'm testing things...
I setup ... but now I'm torn down...
Notice that stuff_i_setup
is referenced in the fixture, allowing that object to be setup
and torn down
for the test it's interacting with. You can imagine this could be useful for a persistent object, such as a hypothetical database or some connection, that must be cleared before each test runs to keep them isolated.
This might help http://docs.pytest.org/en/latest/xunit_setup.html
In my test suite, I group my test cases into classes. For the setup and teardown I need for all the test cases in that class, I use the setup_class(cls)
and teardown_class(cls)
classmethods.
And for the setup and teardown I need for each of the test case, I use the setup_method(method)
and teardown_method(methods)
Example:
lh = <got log handler from logger module>
class TestClass:
@classmethod
def setup_class(cls):
lh.info("starting class: {} execution".format(cls.__name__))
@classmethod
def teardown_class(cls):
lh.info("starting class: {} execution".format(cls.__name__))
def setup_method(self, method):
lh.info("starting execution of tc: {}".format(method.__name__))
def teardown_method(self, method):
lh.info("starting execution of tc: {}".format(method.__name__))
def test_tc1(self):
<tc_content>
assert
def test_tc2(self):
<tc_content>
assert
Now when I run my tests, when the TestClass execution is starting, it logs the details for when it is beginning execution, when it is ending execution and same for the methods..
You can add up other setup and teardown steps you might have in the respective locations.
Hope it helps!
Your code should work just as you expect it to if you add @classmethod
decorators.
@classmethod
def setup_class(cls):
"Runs once per class"
@classmethod
def teardown_class(cls):
"Runs at end of class"
See http://pythontesting.net/framework/pytest/pytest-xunit-style-fixtures/
'UFO ET IT' 카테고리의 다른 글
Asp.NET MVC에서 DateTime 값을 dd / mm / yyyy 형식으로 표시 (0) | 2020.11.16 |
---|---|
Microsoft.Office.Interop Visual Studio를 찾을 수 없습니다. (0) | 2020.11.16 |
PHP에서 파일의 마지막 줄을 읽는 가장 좋은 방법은 무엇입니까? (0) | 2020.11.15 |
PHP 재귀 함수를 사용하여 디렉토리의 모든 파일 및 폴더 나열 (0) | 2020.11.15 |
캔버스를 마우스 커서로 확대 (0) | 2020.11.15 |