[TIP] pytest: Setup/TearDown with fixtures

Bruno Oliveira nicoddemus at gmail.com
Tue Sep 2 08:58:39 PDT 2014


On Tue, Sep 2, 2014 at 10:14 AM, Laszlo Papp <lpapp at kde.org> wrote:

> n


Hi Laszlo,

People at work have asked me the same question, and for people just getting
their feet wet is usually better to introduce pytest features as close to
what they're accustomed to as possible, so their learning curve can be
smoother.

Everyone, in your opinion, what would be a good example that uses pytest
fixtures but doesn't diverge too much what someone might be used to
`XUnit`? I like Laszlo example, but I would change it to not use a
class-scoped fixture and perhaps use `yield_fixture` to show off how easy
it is to write tear-down code.

So this `XUnit` setup code:

```python
class Test(TestCase):

    def setUp(self):
        self.user = User('test-user', 'password')
        self.user.register()
        self.session = Session()
        self.session.login(self.user)

    def tearDown(self):
        self.session.logout()
        self.user.unregister()

    def test_current_user(self):
        self.assertEqual(self.session.get_current_user().name,
self.user.name)
```

Can be almost directly translated to use py.test fixtures like this:

```python
@pytest.yield_fixture
def fixture():
    class Fixture: pass
    f = Fixture()
    f.user = User('test-user', 'password')
    f.user.register()
    f.session = Session()
    f.session.login(self.user)
    yield f
    f.session.logout()
    f.user.unregister()


class Test(object):

    def test_current_user(fixture):
        assert fixture.session.get_current_user().name == fixture.user.name
```

Which can then be further improved to show off how fixtures can reuse other
fixtures:

```python
@pytest.yield_fixture
def logged_session(user):
    session = Session()
    session.login(self.user)
    yield session
    session.session.logout()


@pytest.yield_fixture
def user():
    user = User('test-user', 'password')
    user.register()
    yield user
    user.unregister()

class Test(object):

    def test_current_user(session, user):
        assert session.get_current_user().name == user.name
```

The idea here is to allow the user to map what he already knows, and
gradually introduce fixtures as a concept to make it easier to reuse
setup/tear down code in a more modular fashion.
And furthermore the example can be improved by for example parameterizing
the `user` fixture with the original `"test-user"` and another
`"anonymous"` user without password, producing new tests automatically.

Any thoughts?
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.idyll.org/pipermail/testing-in-python/attachments/20140902/356a851c/attachment.htm>


More information about the testing-in-python mailing list