Heading image

This is Day 17 of the #100DaysOfPython challenge.

This post will use the FreezeGun library to demonstrate how to mock the datetime.datetime.now return value to set up consistent test environments.

The repo code can be found on GitHub at okeeffed/hello-python-datetime

Prerequisites

  1. Familiarity with JupyterLab. See here for my post on JupyterLab.
  2. My previous blog post Datetime In Python
  3. Familiarity with PyTest. See my blog post Python Unit Testing With PyTest for a start post.

Getting started

For the sake of simplicity, we will operate as if we are building a brand new repo:

Let’s create the hello-python-datetime directory and install the required dependencies.

At this stage, we are now ready to update our main.py file and src/datetimes.py to be up to par with what we need for testing.

Add the following to src/datetimes.py:

Add the following to main.py:

Running python main.py should bring us up to par with the following:

The output matches up to us printing values out from main.py. We are at a stage now where we are up to par and able to start writing tests.

Note: If you are using a virtual environment, you will need to run pipenv shell to enter the virtual environment.

Exploring FreezeGun with PyTest

We can use the library with a decorator for the test or creating a with block.

To demonstrate, add the following code to tests/datetimes_test.py:

The first test demonstrates the with block will the second test demonstrates usage with a decorator.

Running pipenv run pytest will now run the tests and display the results.

Now we are ready to test our is_date_before_today function in a manner similar to how our main.py invokes the functions.

Testing the is_date_before_today function

In our test, we are freezing time (using the decorator) to the date of this blog post 2021-08-05 checking the following scenarios:

  1. is_date_before_today when compared to today should be False.
  2. is_date_before_today when compared to one day ago should be True.
  3. is_date_before_today when compared to one day ahead should be False.

We can confirm this to be true by once again running pipenv run pytest:

Summary

Resources and further reading

  1. Hello, JupyterLab
  2. FreezeGun
  3. Pipenv
  4. Python Unit Testing With PyTest

Photo credit: pawel_czerwinski

Originally posted on my blog. To see new posts without delay, read the posts there and subscribe to my newsletter.

I write content for AWS, Kubernetes, Python, JavaScript and more. To view all the latest content, be sure to visit my blog and subscribe to my newsletter. Follow me on Twitter.

--

--

Senior Engineer @ Visibuild

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store