I’m trying to use pytest’s record_property fixture in a test run via Bazel. My py_test build rule includes pytest as a dependency, and my test class inherits from unittest.TestCase:
import pytest
import unittest
from unittest import TestCase
class TestFoo(TestCase):
def test_escape(self, record_property):
pass
if __name__ == "__main__":
unittest.main()
When I run bazel test //path/to:test_foo, I get the error:
TypeError: test_escape() missing 1 required positional argument: 'record_property'
I suspect this is related to the interaction between Bazel, unittest, and pytest fixtures. How can I correctly use record_property in this setup so that Bazel recognizes the fixture?
The main reason you’re seeing this error is that pytest fixtures don’t work with unittest.TestCase methods directly. Fixtures like record_property are injected by pytest, but unittest’s runner doesn’t know about them.
You can rewrite your test as a plain pytest test (no TestCase inheritance):
import pytest
def test_escape(record_property):
record_property("key", "value")
assert True
This way, pytest will automatically provide record_property, and Bazel will run it via the py_test rule without errors.
If you really need to keep TestCase, you can use pytest.mark.usefixtures at the class level, but note that you cannot inject fixtures as method arguments. Instead, access them via self with request:
import pytest
import unittest
@pytest.mark.usefixtures("record_property")
class TestFoo(unittest.TestCase):
def test_escape(self, record_property=None): # optional param
# record_property is None, so you need request to access it
pass
```
Honestly, this is cumbersome. Pytest recommends plain functions or using pytest’s own unittest-style helpers instead of mixing fixtures with unittest.TestCase.
Another approach is to let pytest run your unittest tests explicitly, so fixtures can be used:
import pytest
import unittest
class TestFoo(unittest.TestCase):
def test_escape(self):
# can't inject record_property here
pass
if __name__ == "__main__":
pytest.main([__file__])
But again, record_property won’t be injected automatically into methods that expect self unless you convert them to pytest-style functions.