Home > Software design >  How to include a function inside a pytest test
How to include a function inside a pytest test

Time:12-16

I am writing a test for a numerical optimizer. To test it I need to provide it an objective function to minimize, as given below

import pytest
from optimizer import OptimizerClass

def test_optimizer():

    def foo(params):
        return[(params[0] 2)**2]

    optimizer = OptimizerClass(objective_function = foo)
    solution = optimizer.minimize()

    assert abs(solution - (-2)) <= 10 ** -6
  1. How can I do this so that it works and follows the style guide?
  2. If I am writing multiple test functions that all require instantiation of the optimizer object, should I instantiate the optimizer object inside each function or just once outside? I am aware that both are possible, but I don't know which one is correct as per Python style guide.

CodePudding user response:

ad 1. - your solution looks fine already, is something not working?

ad 2. - Since the optimizer supposedly has internal state, I think it would be better to use a fresh one for each test. Have a look into pytest Fixtures. Example:

 @pytest.fixture
 def optimizer():
     def foo(params):
         #...
     return OptimizerClass(objective_function = foo)

 def test_1(optimizer):
     # pytest will automatically resolve the argument by name and pass the function result into the test.
     result = optimizer.minimize()
     assert ...
 
  • Related