pytest-dev / pytest-testinfra

Testinfra test your infrastructures
https://testinfra.readthedocs.io
Apache License 2.0
2.37k stars 355 forks source link

How to setup test ? #633

Open spham opened 2 years ago

spham commented 2 years ago

Hi How To setup or arrange test before , when Arrange test ? Example here. I need To start zookeeper before test kafka

def test_zookeeper_service(host):
     host.run('sudo systemctl start zookeeper')
     z = host.service("kafka")
     assert z.is_running
     assert z.is_enable
philpep commented 2 years ago

Hi, dynamically starting/stopping services during tests could require to wait/retry for instance to wait up to 10 second the service is running:

host.run("sudo systemctl start zookeeper")
zookeeper = host.service("zookeeper")
for _ in range(10):
    if zookeeper.is_running:
        break
    time.sleep(1)
else:
    raise RuntimeError("Zookeeper not started!")

If you need something more configurable to wait there's might be advanced libraries for this like https://github.com/jd/tenacity

Then if you need to temporary start service for a test but expect the service is not running for other tests, you can define a fixture for this:

@pytest.fixture
def zookeper_running(host):
    host.run("sudo systemctl start zookeeper")
    # [...] wait zookeeper is running
    yield
    host.run("sudo systemctl stop zookeeper")
    # [...] wait zookeeper is stopped

@pytest.mark.usefixtures("zookeeper_running")
def test_kafka(host):
    # [...]