Testing scheduled jobs using faketime
Recently, I was tasked with testing some scheduled exports to investigate a defect. Unit tests should have caught it, but something else was going on. I had to simulate a real execution in a container by faking its internal clock. This is where I utilized faketime . faketime is a tool that manipulates system time for a specific program without changing the system's actual time. It works by…
In the process of investigating a defect concerning scheduled exports, it was necessary to test these jobs in a simulated environment. To achieve this, the author utilized a tool called faketime, which manipulates system time for a particular program without altering the actual time of the system. Faketime functions by intercepting the system calls a program makes to retrieve the current date and time, enabling the execution of programs as if they were a different date and time.
Before initiating the testing process, the first step was to verify the presence of the faketime package in the container image. This could be accomplished by running the command: podman exec -it {container_name} find / -name libfaketime.so.1. If the command located the library file (e.g., at /usr/lib/faketime/libfaketime.so.1), the testing could proceed. If the library was not found, it would need to be installed.
Once the faketime package was confirmed, the next step was to understand its usage. This was quite straightforward. The command: podman exec -it {container_name} sh -c "LD_PRELOAD=/usr/lib/faketime/libfaketime.so.1 FAKETIME_NO_CACHE=1 FAKETIME=$(date -u -d '30 days ago' +%Y-%m-%d 00:01:00) php artisan schedule:work" was executed. This command comprised several components:
- LD_PRELOAD: This directive instructs the shell to load the faketime library before running the specified command.
- FAKETIME_NO_CACHE: This setting ensures that the time is not cached, which is crucial for testing purposes.
- FAKETIME: This parameter sets the exact date and time to be simulated. In the author's scenario, they used the date command to generate a string representing 30 days prior to the current date and time set to 1:00 AM UTC.
With this command, the author was able to simulate various scenarios, such as daily, monthly, and yearly exports, by simply modifying the date string. This approach offered an effective and innovative method for testing the scheduled exports.
Written by urgent.news from Dev.to's reporting — not their text. Machine-written — may contain errors; check the original before relying on it.