2

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.)

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

3 Comments

interesting, I get E ImportError: attempted relative import with no known parent package
This worked though: changing from .pythonscript to from pythonscript. Thank you
Oops, I'll fix my answer 🙂

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.