DEV Community

ashleygraf_
ashleygraf_

Posted on • Edited on

Testing time: Testing of time-dependent code

Time is not the simplest of things to test. It's not static. It interacts with our computer's time. It can be in the future or in the past. The current time isn't simple either. Consider timezones (and shudder if you want to).

What to use

  • Basic to mid-level SQL
  • Crontab
  • The ISO date format your database uses
  • Enough of your organisation's tech stack of choice to be able to read the code and know what to change

So how do you test time(dependent code)?

I'd like to talk about a few methods I use, but first, I want to discuss how time can be manipulated.

There are a few ways. For example:

  • The code interacts with the relationship between the stored time and the current time.
  • The code is activated by a certain time.
  • The code interacts with the current time.

So you change the time where the code 'looks at it'.

If you trust your programming language of choice's time libraries, which is not unreasonable, what you could do first to check the library is called properly. You would do this by testing the code around the time code, and seeing if the time code is triggered. To trigger the time code, make the period of time it's looking for shorter. Make a timer go off in a sooner amount of time.

This action could be set off by crontabs, which would be in config files (perhaps application.yml?) So you would also modify the crontab to set that off earlier.

After that, say if the time is stored in the database, and the code compares the stored time with the current time, you revert the code changes you made, and then back-date or forward-date the date in the database. Then reload the page. Re-run the scenario.

You can jump-box into the staging database to change this stored date, or load your test-environment locally, and change some numbers in your local database.

If an event should happen a week after someone makes an action, set the stored time for 6 days ago, 7 days ago, 8 days ago. Before, at, after.

If it's time appearance, and you are displaying time, create a number of records with the time appearance options in different permutations. Start with the most likely, and move your way out.

Top comments (0)