[問題]在不同測試case中共用同一個變數-pytest

看板Python作者 (jacobcan118)時間8年前 (2016/10/19 12:35), 編輯推噓1(109)
留言10則, 2人參與, 最新討論串1/1
請問我想用pytest寫單元測試.不過如果我在每個測試中都需要用selenium開啟頁面.我有任何方法可以使每個測試共用base這個變數嗎 謝謝 class TestLogin(object): def setup_method(self, method): self.driver = WebDriver(desired_capabilities=desired_capabilities, command_executor=command_executor) self.current_method_name = method.__name__ def teardown_method(self, method): self.driver.close() self.driver.quit() @pytest.fixture(scope="function") def loadpage(): self.base = Home(self.driver).open() def loadLogin(): base.loadLogin() def test_a(self): base = Home(self.driver).open() assert True == base.dotesta() base.loadLogin() def test_b(self): base = Home(self.driver).open() assert True == base.dotestb() base.loadLogin() def test_c(self): base = Home(self.driver).open() assert True == base.dotestc() base.loadLogin() -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 108.6.244.145 ※ 文章網址: https://www.ptt.cc/bbs/Python/M.1476851724.A.9A1.html

10/19 16:50, , 1F
用 global 前綴看看
10/19 16:50, 1F

10/20 10:28, , 2F
我之前是在 class 外寫 fixture
10/20 10:28, 2F

10/20 10:29, , 3F
@pytest.fixture(scope="module")
10/20 10:29, 3F

10/20 10:29, , 4F
def base():
10/20 10:29, 4F

10/20 10:29, , 5F
return Home(self.driver).open()
10/20 10:29, 5F

10/20 10:29, , 6F
然後在 class 那邊加上你要用的 fixture
10/20 10:29, 6F

10/20 10:30, , 7F
@pytest.mark.usefixtures('base')
10/20 10:30, 7F

10/20 10:30, , 8F
class TestLogin(object):
10/20 10:30, 8F

10/20 10:30, , 9F
def loadpage(self, base):
10/20 10:30, 9F

10/20 10:31, , 10F
你參考看看 XD
10/20 10:31, 10F
文章代碼(AID): #1O1lWCcX (Python)