cp-stack
cp-stack

Reputation: 876

Using pytest fixtures in class

I have begun writing unit tests for my Flask API. I have gotten them to work when declared outside of a class. However, for simplicity and OOP constraints, I am trying to have everything run from a class. The issue is I cannot seem to pass any fixture methods to my test class. The code I have here is as follow:

#conftest.py

import os, json, pytest
from ..app import create_app
from flask import Flask

@pytest.fixture
def env_setup():
    env_name = os.getenv('FLASK_ENV')
    app = create_app(env_name)
    return app

I am trying to import env_setup into the following file.

# test_BaseURL.py
import pytest

@pytest.mark.usefixtures("env_setup")
class TestStaticPages:

    def setUp(self, env_setup):
        """
        Setup Test
        """
        self.client = env_setup.test_client()

    def test_base_route(self, env_setup):
        #client = env_setup.test_client()
        url   = '/'
        html1 = b'Welcome to the API. Please visit '
        html2 = b'https://example.com to learn more about this app.'

        response = self.client.get(url)
        assert response.get_data() == html1 + html2
        assert response.status_code == 200

I keep geeting the following error when I run this test:

>       response = self.client.get(url)
E       AttributeError: 'TestStaticPages' object has no attribute 'client'

src/tests/test_BaseURL.py:18: AttributeError

However if I should uncomment the line with client = env_setup.test_client() it works. For whatever reason it cannot seem to grab the setup from the setUP method and keeps erroring out.

Upvotes: 8

Views: 14563

Answers (1)

cp-stack
cp-stack

Reputation: 876

Here is how I fixed my issue:

#conftest.py
import os, json, pytest
from ..app import create_app
from flask import Flask

@pytest.fixture
def client():
    env_name = os.getenv('FLASK_ENV')
    app = create_app(env_name)
    client = app.test_client()
    return client

I was then able to import the client into my other test class like so.

#test_StaticView.py
import pytest

@pytest.mark.usefixtures("client")
class TestStaticPages:

    def test_base_route(self, client):
        url   = '/'
        html1 = b'Welcome to the API. Please visit '
        html2 = b'https://example.com to learn more about this app.'

        response = client.get(url)
        assert response.get_data() == html1 + html2
        assert response.status_code == 200

Upvotes: 21

Related Questions