You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将命令行参数传递给two_factor_verification.py中的类?

解决命令行参数传入two_factor_verification.py的步骤

1. 在conftest.py中注册命令行参数

首先需要让pytest识别你要传入的命令行参数,在tests/conftest.py中添加以下代码:

def pytest_addoption(parser):
    parser.addoption("--email", action="store", help="登录用的邮箱")
    parser.addoption("--2fa", action="store", help="2FA密钥")

2. 修改TwoFactorVerificationPage类,支持接收外部参数

把原本硬编码的TOTP初始化逻辑移到构造方法中,让类可以接收外部传入的2FA密钥:

from playwright.sync_api import Page
import pyotp

class TwoFactorVerificationPage():
    def __init__(self, page: Page, twofa_secret: str) -> None:
        self.page = page
        self.totp = pyotp.TOTP(twofa_secret)  # 使用传入的密钥初始化TOTP
        self.pin_input = page.locator("[aria-label=\"Two Factor Pin\"]")
        self.verify_button = page.locator('button:has-text("Verify")')

    def verify(self) -> None:
        self.pin_input.fill(self.totp.now())
        self.verify_button.click()

3. 在测试用例中传递参数给页面类实例

修改test_case.py,将fixture中获取到的2FA参数传递给TwoFactorVerificationPage的实例:

from playwright.sync_api import Page
from pages.two_factor_verification import TwoFactorVerificationPage

@pytest.fixture
def command_line_fixtures(request):
    args = {}
    args['email'] = request.config.getoption('--email')
    args['2fa'] = request.config.getoption('--2fa')
    return args

def test_case(page: Page, command_line_fixtures) -> None:
    # 将2FA参数传入页面类
    two_factor_page = TwoFactorVerificationPage(page, command_line_fixtures['2fa'])
    two_factor_page.verify()

4. 运行测试的命令示例

执行测试时,通过命令行直接传入参数:

pytest tests/test_case.py --email "your_email@example.com" --2fa "your_2fa_secret_key"

内容的提问来源于stack exchange,提问作者horse

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 09:26:16