Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Adds the ability to fake registered checks. #135

Merged
merged 4 commits into from
Nov 17, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
60 changes: 60 additions & 0 deletions docs/basic-usage/testing.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
---
title: Testing
weight: 5
---

You may wish to test that your checks are handled correctly, without needing to satisfy the
requirements of the check itself. The package provides the ability to fake the results of
checks.

## Basic usage

The `Health` Facade has a `fake` method that allows you to fake the results of a check. Let's use it
to make the `DatabaseCheck` fail in a test:

```php
it('has an error if the database is not available', function () {
Health::fake([
DatabaseCheck::class => new Result(Status::failed())
]);

$this->get('/health')->assertStatus(503);
});
```

Even if the database is available, the health endpoint will fail thanks to our fake. You may fake as many checks
as you'd like in the array passed to the `fake` method.

## Advanced usage

There may be occasions where you need to override the `shouldRun` method in a fake. To accomplish this,
you may call `FakeCheck::result` and pass a boolean indicating whether the check should run:

```php
it('has an error if the database is not available', function () {
Health::fake([
DatabaseCheck::class => FakeCheck::result(
new Result(Status::failed()),
true // Run this check, even if `shouldRun` returns false in the check itself
)
]);

$this->get('/health')->assertStatus(503);
});
```

On rare occasions, you may have multiple instances of the same check, and wish to return different
results for each. The package allows you to provide a closure, which will receive the instance of
the check as an argument:

```php
it('has an error if the database is not available', function () {
Health::fake([
DatabaseCheck::class => fn($check) => $check->getName() === 'Users DB'
? new Result(Status::ok())
: new Result(Status::failed())
]);

$this->get('/health')->assertStatus(503);
});
```
24 changes: 24 additions & 0 deletions src/Facades/Health.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,37 @@

namespace Spatie\Health\Facades;

use Closure;
use Illuminate\Support\Facades\Facade;
use Spatie\Health\Checks\Check;
use Spatie\Health\Checks\Result;
use Spatie\Health\Testing\FakeHealth;
use Spatie\Health\Testing\FakeValues;

/**
* @see \Spatie\Health\Health
*/
class Health extends Facade
{
/**
* @param array<class-string<Check>, Result|FakeValues|(Closure(Check): Result|FakeValues)> $checks
*/
public static function fake(array $checks): FakeHealth
{
$fake = (new FakeHealth(static::getFacadeRoot(), $checks));

static::swap($fake);
static::swapAlias($fake);

return $fake;
}

protected static function swapAlias(FakeHealth $fakeHealth): void
{
static::$resolvedInstance[\Spatie\Health\Health::class] = $fakeHealth;
static::$app->instance(\Spatie\Health\Health::class, $fakeHealth);
}

protected static function getFacadeAccessor()
{
return 'health';
Expand Down
45 changes: 45 additions & 0 deletions src/Testing/FakeCheck.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
<?php

namespace Spatie\Health\Testing;

use Spatie\Health\Checks\Check;
use Spatie\Health\Checks\Result;

class FakeCheck extends Check
{
private Check $fakedCheck;
private FakeValues $fakeValues;

public static function result(Result $result, bool $shouldRun = null): FakeValues
{
return new FakeValues($result, $shouldRun);
}

public function fake(Check $fakedCheck, FakeValues $values): self
{
$this->fakedCheck = $fakedCheck;
$this->fakeValues = $values;

$this->name($fakedCheck->getName());
$this->label($fakedCheck->getLabel());

return $this;
}

public function shouldRun(): bool
{
return $this->fakeValues->shouldRun() === null
? $this->fakedCheck->shouldRun()
: $this->fakeValues->shouldRun();
}

public function onTerminate(mixed $request, mixed $response): void
{
$this->fakedCheck->onTerminate($request, $response);
}

public function run(): Result
{
return $this->fakeValues->getResult();
}
}
42 changes: 42 additions & 0 deletions src/Testing/FakeHealth.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
<?php

namespace Spatie\Health\Testing;

use Closure;
use Illuminate\Support\Collection;
use Spatie\Health\Checks\Check;
use Spatie\Health\Checks\Result;
use Spatie\Health\Health;

class FakeHealth extends Health
{
/**
* @param array<class-string<Check>, Result|FakeValues|(Closure(Check): Result|FakeValues)> $fakeChecks
*/
public function __construct(
private Health $decoratedHealth,
private array $fakeChecks
)
{
}

public function registeredChecks(): Collection
{
return $this->decoratedHealth->registeredChecks()->map(
fn(Check $check) => array_key_exists($check::class, $this->fakeChecks)
? $this->buildFakeCheck($check, $this->fakeChecks[$check::class])
: $check
);
}

/**
* @param Result|FakeValues|(Closure(Check): Result|FakeValues) $result
*/
protected function buildFakeCheck(Check $decoratedCheck, Result|FakeValues|Closure $result): FakeCheck
{
// @phpstan-ignore-next-line
$result = FakeValues::from(value($result, $decoratedCheck));

return FakeCheck::new()->fake($decoratedCheck, $result);
}
}
34 changes: 34 additions & 0 deletions src/Testing/FakeValues.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
<?php

namespace Spatie\Health\Testing;

use Spatie\Health\Checks\Result;

class FakeValues
{
public function __construct(
private Result $result,
private ?bool $shouldRun = null,
)
{
}

public static function from(Result|self $values): self
{
if ($values instanceof Result) {
return new self($values);
}

return $values;
}

public function getResult(): Result
{
return $this->result;
}

public function shouldRun(): ?bool
{
return $this->shouldRun;
}
}
65 changes: 65 additions & 0 deletions tests/HealthTest.php
Original file line number Diff line number Diff line change
@@ -1,10 +1,15 @@
<?php

use Illuminate\Support\Facades\App;
use Spatie\Health\Checks\Checks\DatabaseCheck;
use Spatie\Health\Checks\Checks\PingCheck;
use Spatie\Health\Checks\Checks\UsedDiskSpaceCheck;
use Spatie\Health\Checks\Result;
use Spatie\Health\Enums\Status;
use Spatie\Health\Exceptions\DuplicateCheckNamesFound;
use Spatie\Health\Exceptions\InvalidCheck;
use Spatie\Health\Facades\Health;
use Spatie\Health\Testing\FakeCheck;

it('can register checks', function () {
Health::checks([
Expand Down Expand Up @@ -44,3 +49,63 @@
PingCheck::class,
]);
})->throws(InvalidCheck::class);

it('can fake checks', function () {
Health::checks([
DatabaseCheck::new(),
PingCheck::new(),
]);

Health::fake([
DatabaseCheck::class => new Result(
Status::crashed(),
"We're just making sure faking works",
"Hey, faking works!",
),
PingCheck::class => FakeCheck::result(
new Result(Status::warning()),
true
),
]);

/**
* expectsOutputToContain() is not available before Laravel 9.2.0,
* so we'll just check that the command fails in that case.
*/
if (version_compare(App::version(), '9.2.0', '>=')) {
$this->artisan('health:check', ['--fail-command-on-failing-check' => true])
->expectsOutputToContain(ucfirst((string) Status::crashed()->value))
->expectsOutputToContain(ucfirst((string) Status::warning()->value))
->assertFailed();
} else {
$this->artisan('health:check', ['--fail-command-on-failing-check' => true])->assertFailed();
}
});

it('can pass a closure to fake checks', function () {
Health::checks([
DatabaseCheck::new()->name('MySQL')->connectionName('mysql'),
DatabaseCheck::new()->name('DB SQLite')->connectionName('sqlite'),
]);

Health::fake([
DatabaseCheck::class => function (DatabaseCheck $check) {
return $check->getName() === 'MySQL'
? new Result(Status::crashed())
: new Result(Status::warning());
}
]);

/**
* expectsOutputToContain() is not available before Laravel 9.2.0,
* so we'll just check that the command fails in that case.
*/
if (version_compare(App::version(), '9.2.0', '>=')) {
$this->artisan('health:check', ['--fail-command-on-failing-check' => true])
->expectsOutputToContain(ucfirst((string) Status::crashed()->value))
->expectsOutputToContain(ucfirst((string) Status::warning()->value))
->assertFailed();
} else {
$this->artisan('health:check', ['--fail-command-on-failing-check' => true])->assertFailed();
}
});