Pytest:从父类继承夹具

时间:2019-02-20 22:04:31

标签: python flask pytest connexion

我有几个测试用例,用于测试基于flask / connexion的api的端点。

现在我想将它们重新排序为类,所以有一个基类:

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

现在我的实际测试用例还有另一个类:

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

不幸的是,现在我总是得到一个

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

将灯具继承到子类的正确方法是什么?

1 个答案:

答案 0 :(得分:1)

因此,在搜寻了有关灯具的更多信息之后,我遇到了this post

所以有两个必要步骤

  1. 删除单元测试TestCase继承
  2. @pytest.mark.usefixtures()装饰器添加到子类中以实际使用灯具

在代码中变成

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

现在是子类

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