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

[2.x] Add macros and interceptors to snapshot testing #954

Closed
Closed
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
1 change: 1 addition & 0 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@
"Tests\\Fixtures\\Covers\\": "tests/Fixtures/Covers",
"Tests\\Fixtures\\Inheritance\\": "tests/Fixtures/Inheritance",
"Tests\\Fixtures\\Arch\\": "tests/Fixtures/Arch",
"Tests\\Fixtures\\Snapshot\\": "tests/Fixtures/Snapshot",
"Tests\\": "tests/PHPUnit/"
},
"files": [
Expand Down
7 changes: 6 additions & 1 deletion src/Mixins/Expectation.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
use JsonSerializable;
use Pest\Exceptions\InvalidExpectationValue;
use Pest\Matchers\Any;
use Pest\Plugins\Snapshot;
use Pest\Support\Arr;
use Pest\Support\Exporter;
use Pest\Support\NullClosure;
Expand Down Expand Up @@ -844,16 +845,20 @@ public function toMatchSnapshot(string $message = ''): self

$string = match (true) {
is_string($this->value) => $this->value,
is_object($this->value) && array_key_exists($this->value::class, Snapshot::getInterceptors()) => Snapshot::getInterceptors()[$this->value::class]($this->value),
is_object($this->value) && method_exists($this->value, '__toString') => $this->value->__toString(),
is_object($this->value) && method_exists($this->value, 'toString') => $this->value->toString(),
$this->value instanceof \Illuminate\Testing\TestResponse => $this->value->getContent(), // @phpstan-ignore-line
is_array($this->value) => json_encode($this->value, JSON_THROW_ON_ERROR | JSON_PRETTY_PRINT),
$this->value instanceof Traversable => json_encode(iterator_to_array($this->value), JSON_THROW_ON_ERROR | JSON_PRETTY_PRINT),
$this->value instanceof JsonSerializable => json_encode($this->value->jsonSerialize(), JSON_THROW_ON_ERROR | JSON_PRETTY_PRINT),
is_object($this->value) && method_exists($this->value, 'toArray') => json_encode($this->value->toArray(), JSON_THROW_ON_ERROR | JSON_PRETTY_PRINT),
default => InvalidExpectationValue::expected('array|object|string'),
};

foreach (Snapshot::getMacros() as $macro) {
$string = $macro($string);
}

if ($snapshots->has()) {
[$filename, $content] = $snapshots->get();

Expand Down
44 changes: 41 additions & 3 deletions src/Plugins/Snapshot.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,20 @@
use Pest\Exceptions\InvalidOption;
use Pest\TestSuite;

/**
* @internal
*/
final class Snapshot implements HandlesArguments
{
use Concerns\HandleArguments;

/**
* @var array<string, callable>
*/
private static array $macros = [];

/**
* @var array<string, callable>
*/
private static array $interceptors = [];

/**
* {@inheritDoc}
*/
Expand All @@ -32,4 +39,35 @@ public function handleArguments(array $arguments): array

return $this->popArgument('--update-snapshots', $arguments);
}

public static function intercept(string $class, callable $callable): void
{
self::$interceptors[$class] = $callable;
}

/**
* @return array<string, callable>
*/
public static function getInterceptors(): array
{
return self::$interceptors;
}

public static function macro(string $key, callable $callable): void
{
self::$macros[$key] = $callable;
}

public static function disableMacro(string $key): void
{
unset(self::$macros[$key]);
}

/**
* @return array<string, callable>
*/
public static function getMacros(): array
{
return self::$macros;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
<div key="...">foo</div>
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
<div key="111">foo</div>
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
rgba(255, 0, 0, 1)
5 changes: 4 additions & 1 deletion tests/.snapshots/success.txt
Original file line number Diff line number Diff line change
Expand Up @@ -820,6 +820,9 @@
✓ multiple snapshot expectations with repeat @ repetition 8 of 10
✓ multiple snapshot expectations with repeat @ repetition 9 of 10
✓ multiple snapshot expectations with repeat @ repetition 10 of 10
✓ custom macro
✓ disable macro
✓ intercept

PASS Tests\Features\Expect\toStartWith
✓ pass
Expand Down Expand Up @@ -1325,4 +1328,4 @@
WARN Tests\Visual\Version
- visual snapshot of help command output

Tests: 2 deprecated, 4 warnings, 5 incomplete, 2 notices, 13 todos, 19 skipped, 939 passed (2220 assertions)
Tests: 2 deprecated, 4 warnings, 5 incomplete, 2 notices, 13 todos, 19 skipped, 942 passed (2223 assertions)
31 changes: 31 additions & 0 deletions tests/Features/Expect/toMatchSnapshot.php
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
<?php

use Pest\Plugins\Snapshot;
use Pest\TestSuite;
use PHPUnit\Framework\ExpectationFailedException;
use Tests\Fixtures\Snapshot\Color;

beforeEach(function () {
$this->snapshotable = <<<'HTML'
Expand Down Expand Up @@ -146,3 +148,32 @@ public function toArray()

expect('foo bar 2')->toMatchSnapshot();
})->repeat(10);

test('custom macro', function () {
Snapshot::macro('test', function (string $value) {
return preg_replace('/key="[0-9]*"/', 'key="..."', $value);
});

expect('<div key="'.random_int(1, 999).'">foo</div>')
->toMatchSnapshot();
});

test('disable macro', function () {
Snapshot::macro('test', function (string $value) {
return preg_replace('/key="[0-9]*"/', 'key="..."', $value);
});

Snapshot::disableMacro('test');

expect('<div key="111">foo</div>')
->toMatchSnapshot();
});

test('intercept', function () {
Snapshot::intercept(Color::class, function (Color $color): string {
return $color->getStyle();
});

expect(new Color(255, 0, 0))
->toMatchSnapshot();
});
18 changes: 18 additions & 0 deletions tests/Fixtures/Snapshot/Color.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
<?php

namespace Tests\Fixtures\Snapshot;

class Color
{
public function __construct(
public int $red,
public int $green,
public int $blue,
) {
}

public function getStyle(): string
{
return 'rgba('.$this->red.', '.$this->green.', '.$this->blue.', 1)';
}
}
2 changes: 1 addition & 1 deletion tests/Visual/Parallel.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@

test('parallel', function () use ($run) {
expect($run('--exclude-group=integration'))
->toContain('Tests: 1 deprecated, 4 warnings, 5 incomplete, 2 notices, 13 todos, 15 skipped, 928 passed (2205 assertions)')
->toContain('Tests: 1 deprecated, 4 warnings, 5 incomplete, 2 notices, 13 todos, 15 skipped, 931 passed (2208 assertions)')
->toContain('Parallel: 3 processes');
})->skipOnWindows();

Expand Down