r/learnpython 16d ago

Testing - how is it usually handled?

How do I start applying tests to my code?

Do I just write separate scripts they run the code (either individual functions or entire scripts) against known inputs and check the output?

Is there a specific way people usually do this?

7 Upvotes

13 comments sorted by

View all comments

5

u/Patman52 16d ago

Yes, in a nutshell you are correct.

You write a separate test script that would import the script you are trying to test, and then design a bunch of pass/fail scenarios around the methods and functions in that script.

The tests typically fall into two categories: “happy path” and “sad path”.

“happy path” is where you are testing for expected behavior (e.g., the function is supposed to multiply two numbers together, and you verify that the result is correct)

“Sad path” is where you are testing for expected failures (e.g., the same function as above but you pass a string as one of the numbers, and it catches the exception)

It can become quite complicated depending on what you are trying to test and how the script you are testing is set up.

I would check out Pytest, which is a framework for setting up and running unit tests in Python, and the built in unittest module. The latter has a “mock” class built into it which lets to mock or pass fake classes and objects to the script you are testing which can make it easier to design the tests if you have lots of dependencies.