Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using self in pytest parametrize

Tags:

python

pytest

How can I use attributes in parametrize in pytest with tests organized in classes?

import pytest

class TestA:
    @pytest.fixture(autouse=True)
    def set_up(self):
        self.field1 = "field1"
        self.field2 = "field2"

    @pytest.mark.parametrize("field", (self.field1, self.field2))
    def test_print_field(self, field):
        print(field, flush=False)

I'm getting NameError: name 'self' is not defined.

like image 326
user3565923 Avatar asked Aug 15 '26 00:08

user3565923


1 Answers

Probably not the best practice but here's something that can do the work:

@pytest.mark.parametrize("field", ("field1", "field2"))
def test_print_field(self, field):
    print(eval(f"self.{field}"), flush=False)

You might want to use fixtures instead to set up and tear down.

like image 57
Vikrant Reddy Avatar answered Aug 17 '26 13:08

Vikrant Reddy