user2883071
user2883071

Reputation: 980

Unit tests for a single python file

I have a python script with main, and a whole lot of helper methods. How do I write unit tests for these helper methods which all reside in the same file. A lot of the examples I see online involve creating libraries of helpers and then importing and testing that. In my case it is all one file.

Sample structure:

/user/
  |-- pythonscript.py

and I want to write tests for pythonscript.py.

Sample pythonscript.py:

def getSum(i ,j):
    return i+j

def main():
    summer = getSum(1,1)

if __name__ == '__main__':
    main()

For example, I want to write tests for methods like getSum in another file. (I recall there was a tester which would screen .py files and identify functions needing tests based on appending test_ or _test, but I cannot seem to find it anymore.)

Upvotes: 1

Views: 1485

Answers (1)

jidicula
jidicula

Reputation: 3929

It sounds like you're describing pytest, which can automatically discover tests that follow certain naming and path conventions. One of these is considering every function prefixed with test to be a test.

For your scenario, I'd recommend creating a file called test_pythonscript.py also at the root of your directory. Inside that file, you could import functions from pythonscript.py, then test them:

# test_pythonscript.py
from pythonscript import getSum

test_getSum():
    assert getSum(1, 2) == 3

Once you've installed pytest as a dependency, you'd run pytest at the root of your project and it should be able to discover the above test.

Upvotes: 2

Related Questions