feat: adds toUseTraits expectation

This commit is contained in:
Nuno Maduro
2024-06-25 21:56:08 +01:00
parent 00643312b7
commit 9d02b649e2
3 changed files with 88 additions and 0 deletions

View File

@ -611,6 +611,41 @@ final class Expectation
);
}
/**
* Asserts that the given expectation target to use the given trait.
*
* @param string $trait
*/
public function toUseTrait(string $trait): ArchExpectation
{
return $this->toUseTraits($trait);
}
/**
* Asserts that the given expectation target to use the given traits.
*
* @param array<int, string>|string $traits
*/
public function toUseTraits(array|string $traits): ArchExpectation
{
$traits = is_array($traits) ? $traits : [$traits];
return Targeted::make(
$this,
function (ObjectDescription $object) use ($traits): bool {
foreach ($traits as $trait) {
if (! in_array($trait, $object->reflectionClass->getTraitNames(), true)) {
return false;
}
}
return true;
},
"to use traits '".implode("', '", $traits)."'",
FileLineFinder::where(fn (string $line): bool => str_contains($line, 'class')),
);
}
/**
* Asserts that the given expectation target to not implement any interfaces.
*/
@ -668,6 +703,8 @@ final class Expectation
);
}
/**
* Asserts that the given expectation target to implement the given interfaces.
*

View File

@ -252,6 +252,41 @@ final class OppositeExpectation
);
}
/**
* Asserts that the given expectation target not to use the given trait.
*
* @param string $trait
*/
public function toUseTrait(string $trait): ArchExpectation
{
return $this->toUseTraits($trait);
}
/**
* Asserts that the given expectation target not to use the given traits.
*
* @param array<int, string>|string $traits
*/
public function toUseTraits(array|string $traits): ArchExpectation
{
$traits = is_array($traits) ? $traits : [$traits];
return Targeted::make(
$this->original,
function (ObjectDescription $object) use ($traits): bool {
foreach ($traits as $trait) {
if (in_array($trait, $object->reflectionClass->getTraitNames(), true)) {
return false;
}
}
return true;
},
"to use traits '" . implode("', '", $traits) . "'",
FileLineFinder::where(fn(string $line): bool => str_contains($line, 'class')),
);
}
/**
* Asserts that the given expectation target not to implement the given interfaces.
*

View File

@ -0,0 +1,16 @@
<?php
use Pest\Arch\Exceptions\ArchExpectationFailedException;
test('pass', function () {
expect('Pest\Expectations\HigherOrderExpectation')->toUseTrait('Pest\Concerns\Retrievable')
->and('Pest\Expectations\EachExpectation')->not->toUseTrait('Pest\Concerns\Retrievable');
});
test('failures', function () {
expect('Pest\Expectations\EachExpectation')->toUseTrait('Pest\Concerns\Foo');
})->throws(ArchExpectationFailedException::class);
test('not failures', function () {
expect('Pest\Expectations\HigherOrderExpectation')->not->toUseTrait('Pest\Concerns\Retrievable');
})->throws(ArchExpectationFailedException::class);