下面是用于运行2个测试的pytest类。要在两个测试都执行完后退出驱动程序。使用了Teardown,但在每次测试执行完成后都会退出驱动程序
class FlightTest(unittest.TestCase):
driver = webdriver.Chrome(direct_path+'/resources/chromedriver.exe')
startup = StartUpPage(driver)
register = RegisterPage(driver)
def test_flight_registration(self):
dat = self.json_reader.read_from_file("testdata.json")
self.startup.navigate_to_url(dat['url'])\
.click_on_register_button()
self.register.create_user(dat['uid'], dat['pwd'], dat['con_pwd'])
def test_flight_sign_in(self,):
dat = self.json_reader.read_from_file("testdata.json")
self.startup.click_sign_in_link()
def tearDown(self):
self.driver.quit()
答案 0 :(得分:3)
用unittest
术语,您将需要使用setUpClass
和tearDownClass
类方法:
class FlightTest(unittest.TestCase):
@classmethod
def setUpClass(cls)
cls.driver = webdriver.Chrome()
cls.startup = StartUpPage(driver)
cls.register = RegisterPage(driver)
@classmethod
def tearDownClass(cls):
cls.driver.quit()
...
在pytest
中,您将创建一个class-scoped fixture:
import pytest
@pytest.fixture(scope="class")
def driver(request):
# code before 'yield' is executed before the tests
request.cls.driver = webdriver.Chrome()
request.cls.startup = StartUpPage(request.cls.driver)
request.cls.register = RegisterPage(request.cls.driver)
yield
# code after 'yield' is executed after the tests
request.cls.driver.quit()
@pytest.mark.usefixtures('driver')
class FlightTest(unittest.TestCase):
def test_spam(self):
self.driver.get('https://www.google.de')
def test_eggs(self):
self.driver.get('https://www.facebook.com')
一个更好的解决方案是使用webdriver的上下文管理器属性,因此无论如何它都会自动关闭:
import pytest
@pytest.fixture(scope="class")
def driver(request):
with webdriver.Chrome() as driver:
request.cls.driver = driver
request.cls.startup = StartUpPage(driver)
request.cls.register = RegisterPage(driver)
yield
@pytest.mark.usefixtures('driver')
class FlightTest(unittest.TestCase):
def test_spam(self):
self.driver.get('https://www.google.de')
def test_eggs(self):
self.driver.get('https://www.facebook.com')