Passing arguments to pytest fixtures

Mohamed Ali
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 code
1 passed in 0.01s

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade