Skip to content

Test_Class: how to write a setup/fixture that runs once for a class instance(not per class/method)? #3718

@Sathisha-Movvar-Bose

Description

@Sathisha-Movvar-Bose

I am looking to parametrize a class which has more than 1 tests in it. I want a setup/teardown method called for each instance of the class.

BTW, I am not sure if class level fixture works the way I think it (I am assuming for each class level parameter I get new class instance). I would appreciate if someone can educate me if my understanding is wrong.

@pytest.fixture(scope="class", params=[2,4,8])
def n_iter(request):
    return request.param

@pytest.mark.usefixtures("n_iter")
class Test_Class1:
	@classmethod
	def setup_class(cls):
		''' This gets called only once not per parameter of class
			: no issues
		'''
		cls.buffer = []
		pdb.set_trace()
		log.info("setup class")
		
	def setup(self):
		''' I want this to be called only once and all the test below
		gets executed one after other 
			:instead this gets called for every test method
		'''
		self.buffer.append(len(self.buffer))
		log.info("setup instance of class")
		
	def teardown(self):
		''' I want this to be called only once after all the
		tests are completed for a class level param
			:instead this gets called after every test method
		'''
		self.buffer = [] # clear
		
	@pytest.mark.parametrize('newVal', [2,4])
	def test_clsMethod1(self, newVal, n_iter):
		assert n_iter == newVal

	def test_clsMethod2(self, n_iter):
		assert n_iter > 0

	@pytest.mark.parametrize('newVal', [2,4])
	def test_clsMethod3(self, newVal):
		assert newVal > 0

Metadata

Metadata

Assignees

No one assigned

    Labels

    type: questiongeneral question, might be closed after 2 weeks of inactivity

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions