Addi O
Addi O

Reputation: 21

Can you use pytest.fixture and unittest.mock decorators together?

I am trying to call four decorators on my unit tests to easily allow code to be refactored: pytest.fixture, unittest.mock.patch, pytest.mark.parameterize, pytest.mark.asyncio. I currently am calling the below and returning the error that test_get_generator_output function has no attribute save_df_to_db

In test_constants.py

import pytest
from unittest import mock
from .test_mock import MockGenRequest
    @pytest.fixture()
    async def gen_request():
        request: MockGenRequest = MockGenRequest()
        return request

    test_cases = [
        (
        gen_request,
        input_df,
        output_df
        ),
    ]

In test_generator.py

from . import test_constants
import pytest
from unittest import mock
from . import evaluator
@pytest.mark.parametrize("gen_request, input_df, output_df",
                            test_constants.test_cases)
@mock.patch('utils.request.GenRequest.save_df_to_db', return_value = None)
@pytest.mark.asyncio
async def test_get_generator_ouput(mock_save_df_to_db, request, input_df, output_df):
    generator_output = evaluator.get_generator_output(
        input = input_df,
        request = request
    )
    assert "output_id" in generator_output.columns
    testing.assert_frame_equal(output_df, generator_output, check_column_order = False)

Is there a way to get these to work together cohesively?

Edit: I have tried the following orders with the fixture taken out of the test cases:

Upvotes: 1

Views: 18

Answers (1)

Addi O
Addi O

Reputation: 21

The async fixture is never awaited and the order needs to be (mock,input,output,fixture)

async def test_get_generator_output(mock_save_df_to_db, input_df, output_df, request):
    generator_output = evaluator.get_generator_output(
        input = input_df,
        request = await request
    )

Upvotes: 0

Related Questions