Skip to content

Instantly share code, notes, and snippets.

@ZaxR
Last active August 5, 2020 14:54
Show Gist options
  • Save ZaxR/c1d0cdcbdff178579ad7c3e9174c76b9 to your computer and use it in GitHub Desktop.
Save ZaxR/c1d0cdcbdff178579ad7c3e9174c76b9 to your computer and use it in GitHub Desktop.
# https://docs.pytest.org/en/latest/example/parametrize.html#apply-indirect-on-particular-arguments
import pytest
class SomeClass:
def __init__(self, a, b, c):
self.a = a
self.b = b
self.c = c
def add_all(self):
return self.a + self.b + self.c
@pytest.fixture(scope='module')
def some_class(request):
return SomeClass(**request.param)
class TestSomeClass:
@pytest.mark.parametrize('some_class,expected', [
({"a": 2, "c": 3, "b": 5}, 10)
], indirect=["some_class"]) # indirect tells this method which args are fixtures to parameterize
def test_add_all(self, some_class, expected):
assert some_class.add_all() == expected
# if we want to also monkeypatch attributes/methods of some_class, we can change the some_class fixture to:
# Learn more about how to use the monkeypatch fixture:
# https://stackoverflow.com/a/37201584. # no import required
# https://docs.pytest.org/en/stable/monkeypatch.html # examples
@pytest.fixture(scope='module')
def some_class(request, monkeypatch):
instance = SomeClass(**request.param)
monkeypatch.setattr(instance, "c", 100) # attrs must already exist to be monkeypatched
yield instance # note this has to be yield, not return
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment