Why do I need unit tests?
So I want to compare if two dates are equal. I therefore input two dates and in return expect the comparison’s outcome as a bool.
Usually I would:
-
Write the function
-
Print it’s result until I’m happy with it
#somecode.py from datetime import datetime def compare_two_dates(date,otherdate): return date==otherdate date = datetime.now().date() otherdate = datetime(1900,12,12) true_expected=compare_two_dates(date,date) false_expected=compare_two_dates(date,otherdate) print("true_expected:",true_expected) print("false_expected:",false_expected)
Result:
true_expected: True false_expected: False
Why am I not happy with that approach?
I’m required to see the output. My focus constantly switches between looking what is printed and the code itself. I’m required to repeat it over and over since I can’t remember later if I already printed the functions outcome.
What do I want?
Write down the result I want. Write the necessary code. Done.
This translates into two steps for most of the coding:
- Write what I want
- Write the code to get what I want
Result
No more print statements cluttering my commits. No more insecurities about memorizing if I ever tested this before.
# my_unit_test.py
import pytest
from datetime import datetime
def compare_two_dates(date, otherdate):
return date == otherdate
def test_compare_two_dates():
date = datetime.now().date()
otherdate = datetime(1900, 12, 12)
assert compare_two_dates(date, date) == True
assert compare_two_dates(date, otherdate) == False
pytest my_unit_test.py
echo
============================= test session starts ==============================
platform linux -- Python 3.9.6, pytest-6.2.4, py-1.10.0, pluggy-0.13.1
rootdir: /home/ra/tmp/83820272
plugins: cov-2.12.1, hypothesis-6.14.5, pycharm-0.6.0, vcr-1.0.2
collected 1 item
my_unit_test.py . [100%]
============================== 1 passed in 0.01s ===============================
Conclusion:
Unit tests free me from printing over and over the same stuff. They free me from being needed to overview in person what I’ve already written down as an expected result. I can agree with third parties on tests similar to a contract.