Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeError: missing 1 required positional argument while using pytest fixture [duplicate]

I have written my test classes in a file and I am trying to use pytest fixtures so that I don't have to create the same input data in each test functions. Below is the minimal working example.

import unittest
import pytest

@pytest.fixture
def base_value():
    return 5

class Test(unittest.TestCase):

    def test_add_two(self, base_value):
        result = base_value + 2
        self.assertEqual(result, 7, "Result doesn't match")

However, when I test this using pytest-3, I get the following error:

TypeError: test_add_two() missing 1 required positional argument: 'base_value'

This is confusing for me since the base_value is clearly given as one of the arguments to test_add_two. Any help is highly appreciated.

like image 398
Peaceful Avatar asked Sep 07 '25 10:09

Peaceful


1 Answers

This is because you are mixing pytest and unittest. Try

@pytest.fixture
def base_value():
    return 5


class Test:
    def test_add_two(self, base_value):
        result = base_value + 2
        assert result == 7, "Result doesn't match"

And in case of failure the error will be

def test_add_two(self, base_value):
        result = base_value + 2
>       assert result == 8, "Result doesn't match"
E       AssertionError: Result doesn't match
E       assert 7 == 8

But isn't pytest compatible with unittest?

Only on a limited basis. From Pytest unittest.TestCase Support

pytest features in unittest.TestCase subclasses The following pytest features work in unittest.TestCase subclasses:

  • Marks: skip, skipif, xfail;
  • Auto-use fixtures;

The following pytest features do not work, and probably never will due to different design philosophies:

  • Fixtures (except for autouse fixtures, see below);
  • Parametrization;
  • Custom hooks;

Third party plugins may or may not work well, depending on the plugin and the test suite.

like image 145
Guy Avatar answered Sep 10 '25 04:09

Guy