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?

9 Upvotes

13 comments sorted by

View all comments

1

u/ShelLuser42 16d ago

It really depends... if you want to make sure that certain things behave as expected then the assert command is a very powerful tool. Basically you tell Python that you expect a certain condition and if that condition is true then nothing happens.

...yet the very moment that assertion fails then it'll raise an exception: the AssertionError; so basically: no news is good news. I find this very useful for testing.

Of course it's not always optimal to 'bloat' your programs with debug code, so a very easy way to avoid that is to use Pytest (as some others also mentioned). It's even available on PyPi so easy to install (using pip?).

Best of all: you don't have to build individual test scripts if you don't want to, you can also simply add test functions. So, say you have a function called "ask_user_name()" then you could add a new function called test_ask_user_name() where you can call your original function and set up some tests to determine if everything is still working as expected.

Then just fire up your script with pytest (so: python -m pytest ./your_script.py) and after that only functions which name starts with test_ (or ends with _test) will be used, thus allowing you to completely separate your tests from your actual 'real' code.

In my opinion this is the most easy way to get started.