I am new with unit testing and am confused about a lot of things. In the project I have been inherited, there is a __main__.py
file, in which there is only one function:
import some_class
def func1 (some_instance) -> bool:
#some code
#returns true or False
some_instance = some_class()
func1 (some_instance)
Now, in another file ( tests.py
), which is in the same folder as __main__.py
, I want to write a unit test to test the func1
function. I don't know how I can do that. This is all I got:
import some_class
from __main__ import func1
def test_func1():
test_instance = some_class()
assert func1(test_instance) is True
It doesn't work and I think the test_func1()
cannot even access func1
. How can import func1
? How can I test it? The ( from __main__ import func1
) part looks strange.
Let's assume that you want to test Calculator
class and it's method add
# src/calculator.py
class Calculator:
def __init__(self, x, y):
self.x = x
self.y = y
def add(self):
return self.x + self.y
Then create a test file in the same folder as calculator.py -
# src/test_calculator.py
from src.calculator import Calculator
def test_calculator_instance():
calculator = Calculator(2, 2)
assert isinstance(calculator, Calculator) == True
def test_calculator_addition():
calculator = Calculator(2, 2)
assert calculator.add() == 4
That's it. Now you just type pytest.
in your terminal and you should see something as follows -
test_calculator.py .. [100%]
===== 2 passed in 0.01s =======
I hope this helps.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.