wikofad877
wikofad877

Reputation: 53

How to write a unit test using Pytest for the main function in Python

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.

Upvotes: 1

Views: 5911

Answers (1)

Prashant
Prashant

Reputation: 155

Let's assume that you want to test Calculator class and it's method add

# src/calculator.py

def add(x, y):
    return x + y

Then create a test_calculator.py file in the same folder as calculator.py -

# src/test_calculator.py

from calculator import add


def test_calculator_addition():
    output = add(2, 2)
    assert output == 4

That's it. Now you just type pytest . in your terminal and you should see something as follows -

test_calculator.py .                [100%]
===== 1 passed in 0.01s =======

I hope this helps.

Upvotes: 2

Related Questions