Skip to main content
 首页 » 编程设计

python之如何将服务器作为 py.test 的 fixture 运行

2025年05月04日11artech

我想用服务器作为 fixture 编写 Selenium 测试:

import pytest 
 
@pytest.fixture() 
def driver(request): 
    from selenium import webdriver 
    d = webdriver.Firefox() 
    request.addfinalizer(d.close) 
    return d 
 
@pytest.fixture() 
def server(): 
    from server import run 
    run(host="localhost", port=8080) 
 
def test_can_see_echo(driver,server): 
    page = TestPage(driver) 
    page.fill_text_in_input("test") 
    page.click_send() 
    print page.get_returnet_value() 

server fixture 中运行的函数是bottle run 函数。问题是,当我调用 run() 程序时进入无限循环并且不执行测试主体。我应该在同一个线程中调用运行吗?我的设计好吗?将来我想使用服务器 fixture 来集成到服务器状态。例如,使用 Selenium 进行测试“添加评论”,最后使用服务器 fixture 询问服务器是否确实发生了此操作。

请您参考如下方法:

测试挂起是因为您的 run(host="localhost", port=8080) 启动了一个永远等待的服务器。您应该在不同的线程/进程中启动该服务器。

查看类似 pytest-xprocess 的内容为您的测试运行外部服务器进程。