How to call a python function "with arguments" present within a class which has a constructor from a pytest function?

I could not find a similar question based on pytest. Stuck with this for quite sometime. Please do not close this until it is answered. thank you.

The python class looks like:

class Calculator:
    def __init__(self, num1=None, num2=None):
        self.logger = get_logger(__name__)
        self.num1 = num1
        self.num2 = num2

    def calculate(self):
        if self.num1 and self.num2:
            num = self.__divider(num1, num2)
            raise Exception('num2 cannot be 0')
        return self.__faulty_displayer(num)
    def __divider(self, num1, num2):
        value = num1/num2
        return value
    def __faulty_displayer(self,num)
        value = num + 1
        return value

What I want to be able to do is, write a pytest for calculate() method. But, I am unable to do so, as I am unable to call the method with any values. So, inherently, every time, the exception is getting called.

What I have tried so far is:

import pytest

def obj():
    return Calculator()

# Need help in writing a test case which can take the values of num1, and num2
def test_calculate(obj):
    expected_value = 1
    actual_value = obj.calculate()  #How to pass num1, and num2 values
    assert expected_value == actual_value

>Solution :

The way that your class is defined, num1 and num2 have to be defined at the time the object is constructed. This is an awkward design (as you’re discovering now in trying to write your test), but assuming that we need to work with that class as-is instead of fixing it, then the test needs to construct the object with the test values, like this:

def test_calculate(num1, num2, expected):
    """Test that Calculator.calculate() produces the expected result."""
    assert Calculator(num1, num2).calculate() == expected

test_calculate(1, 1, 2)  # 1 / 1 + 1 = 2
test_calculate(4, 2, 3)  # 4 / 2 + 1 = 3

Leave a Reply