Pytest: Inherit fixture from parent class
Asked Answered
E

1

9

I have a couple of test cases to test the endpoints of a flask/connexion based api.

Now I want to reorder them into classes, so there is a base class:

import pytest
from unittest import TestCase

# Get the connexion app with the database configuration
from app import app


class ConnexionTest(TestCase):
    """The base test providing auth and flask clients to other tests
    """
    @pytest.fixture(scope='session')
    def client(self):
        with app.app.test_client() as c:
            yield c

Now I have another class with my actual testcases:

import pytest
from ConnexionTest import ConnexionTest

class CreationTest(ConnexionTest):
    """Tests basic user creation
    """

    @pytest.mark.dependency()
    def test_createUser(self, client):
        self.generateKeys('admin')
        response = client.post('/api/v1/user/register', json={'userKey': self.cache['admin']['pubkey']})
        assert response.status_code == 200

Now unfortunately I always get a

TypeError: test_createUser() missing 1 required positional argument: 'client'

What is the correct way to inherit the fixture to subclasses?

Entertainment answered 20/2, 2019 at 22:4 Comment(0)
E
7

So after googling for more infos about fixtures I came across this post

So there were two required steps

  1. Remove the unittest TestCase inheritance
  2. Add the @pytest.mark.usefixtures() decorator to the child class to actually use the fixture

In Code it becomes

import pytest
from app import app

class TestConnexion:
    """The base test providing auth and flask clients to other tests
    """

    @pytest.fixture(scope='session')
    def client(self):
        with app.app.test_client() as c:
            yield c

And now the child class

import pytest
from .TestConnexion import TestConnexion

@pytest.mark.usefixtures('client')
class TestCreation(TestConnexion):
    """Tests basic user creation
    """
    @pytest.mark.dependency(name='createUser')
    def test_createUser(self, client):
        self.generateKeys('admin')
        response = client.post('/api/v1/user/register', json={'userKey': self.cache['admin']['pubkey']})
        assert response.status_code == 200
Entertainment answered 21/2, 2019 at 11:48 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.