Skip to content

Instantly share code, notes, and snippets.

@MattApril
Last active July 4, 2024 09:25
Show Gist options
  • Save MattApril/e6f4b8af32eb6438f482d307280d6a79 to your computer and use it in GitHub Desktop.
Save MattApril/e6f4b8af32eb6438f482d307280d6a79 to your computer and use it in GitHub Desktop.
A simple way of testing that your Lumen commands are scheduled exactly when and how you expect. This approach does not trigger commands to actually execute, which is what a lot of other suggestions do.
<?php
use App\Console\Kernel;
use Carbon\Carbon;
use Illuminate\Console\Scheduling\Event;
use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Support\Collection;
class ConsoleSchedulingTest extends TestCase
{
/**
* Verify that my-command-name is scheduled to run at 7AM ET in production.
*/
public function testCommandIsScheduledToRunAt7am() {
$date = Carbon::today()->timezone('America/Toronto')->setTime(7,0);
$dueEvents = $this->getScheduledEventsForCommand('my-command-name', $date);
$this->assertCount(1, $dueEvents, 'Command is not scheduled for expected time');
/**
* @var \Illuminate\Console\Scheduling\Event $event
*/
$event = $dueEvents->first();
$this->assertTrue($event->runsInEnvironment('production'));
}
/**
* For scheduled jobs, the fully qualified class name should be referenced.
*/
public function testJobIsScheduled() {
$scheduledJobEvents = $this->getScheduledEventsForCommand(MyJob::class);
$this->assertCount(1, $scheduledJobEvents);
}
/**
* @param string $commandName
* @param Carbon|null $atTime
* @return Collection
*/
private function getScheduledEventsForCommand(string $commandName, Carbon $atTime=null): Collection {
# configure scheduled through Kernel
new Kernel($this->app);
/**
* @var Schedule $schedule
*/
$schedule = $this->app->get(Schedule::class);
return collect($schedule->events())->filter(function(Event $event) use($commandName, $atTime){
if(!str_contains((string)$event->command, $commandName) && strcmp((string)$event->description, $commandName) !== 0) {
return false;
}
# optionally filter out events that are not due at the given time.
if($atTime !== null) {
Carbon::setTestNow($atTime);
return $event->isDue($this->app) && $event->filtersPass($this->app);
} else {
return true;
}
});
}
}
@natsu90
Copy link

natsu90 commented Oct 19, 2023

i'm using Laravel 6.0, any idea why $schedule->events() return empty?

@MattApril
Copy link
Author

UPDATE: I originally stated that this was for Laravel, but it was actually only tested in Lumen. Sorry, I run both Laravel and Lumen and often forget which one I am using. I will update this if I ever adapt it to Laravel.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment