Search code examples
pythonbottlepytestfixtures

How to run server as fixture for py.test


I want to write Selenium tests with server as fixture:

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()

Function run in server fixture is bottle run function. The problem is that, when I call run() programs go into infinite loop and body of test is not executed. Should I call run in same thread? Is my design fine? In future I want use server fixture to integrate to server state. For example make test "add comment" using Selenium and in the end use server fixture to ask server if this action really happened.


Solution

  • The tests hang because your run(host="localhost", port=8080) starts a server which waits forever. You should start that server in a different thread/process.

    Look into something like pytest-xprocess for running external server processes for your tests.