Passing arguments to pytest fixtures
Nov 6 · 1 min read
I needed a way to pass variable arguments to pytest fixtures dynamically without using @pytest.mark.parameteriz
So i came up with this:
import pytest@pytest.fixture
def make_pod(request):
def generate_pod(pod_name, image="busybox"):
make_pod.pod_manifest = {
"apiVersion": "v1",
"kind": "Pod",
"metadata": {
"name": pod_name,
},
"spec": {
"containers": [
{
"name": pod_name,
"image": image,
"command": [
"/bin/sh",
"-c",
"while true; do :; done"
]
}
]
}
}
return make_pod.pod_manifest yield generate_pod # tearing down
print("teardown code")def test_pod(make_pod):
pod_manifest = make_pod("test_pod", image="nginx") print(pod_manifest)
$ pytest -sq -k test_pod
{'metadata': {'name': 'test_pod'}, 'apiVersion': 'v1', 'spec': {'containers': [{'name': 'test_pod', 'image': 'nginx', 'command': ['/bin/sh', '-c', 'while true; do :; done']}]}, 'kind': 'Pod'}
.
teardown code1 passed in 0.01s
