20

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.

Peaceful
  • 4,920
  • 15
  • 54
  • 79

1 Answers1

30

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.

Guy
  • 46,488
  • 10
  • 44
  • 88
  • But isn't pytest compatible with unittest? I just want to keep both testing options open. – Peaceful Jul 19 '21 at 12:39
  • 1
    @Peaceful only on a limited basis, and not with fixtures (see updated answer). – Guy Jul 19 '21 at 12:47
  • Thanks! But the suggested modification throws an error: "TypeError: unsupported operand type(s) for +: 'Test' and 'int'" – Peaceful Jul 19 '21 at 13:57
  • @Peaceful Did you change anything? what's your pytest version? this works fine for me... – Guy Jul 19 '21 at 14:18
  • My pytest version is 4.6.9. Also, I think self should be removed from your code, isn't it? – Peaceful Jul 19 '21 at 15:08
  • OK am not sure what I changed, but if I just copy paste your code and run in another file, it throws a large number of errors called ` ` and the last one is ` IndexError: list index out of range` – Peaceful Jul 19 '21 at 15:18
  • @Peaceful Your Pytest version is quite old (01/20), try to update it. – Guy Jul 19 '21 at 15:33
  • In my case, I am not mixing anything. Found no trace of unittest... – Gulzar May 09 '22 at 17:21