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

Added the ability to run tests in scope #73

Merged
merged 8 commits into from
May 7, 2024
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
2 changes: 0 additions & 2 deletions .github/workflows/phpunit.yml
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,5 @@ jobs:
with:
os: >-
['ubuntu-latest']
php: >-
['8.1', '8.2']
stability: >-
['prefer-lowest', 'prefer-stable']
33 changes: 17 additions & 16 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -44,29 +44,30 @@
"nyholm/psr7": "^1.5",
"mockery/mockery": "^1.5",
"phpunit/phpunit": "^9.6 || ^10.0",
"spiral/auth": "^3.8.4",
"spiral/auth-http": "^3.8.4",
"spiral/boot": "^3.8.4",
"spiral/events": "^3.8.4",
"spiral/console": "^3.8.4",
"spiral/http": "^3.8.4",
"spiral/mailer": "^3.8.4",
"spiral/queue": "^3.8.4",
"spiral/session": "^3.8.4",
"spiral/security": "^3.8.4",
"spiral/tokenizer": "^3.8.4",
"spiral/storage": "^3.8.4",
"spiral/views": "^3.8.4",
"spiral/translator": "^3.8.4",
"spiral/scaffolder": "^3.8.4",
"spiral/auth": "^3.12",
"spiral/auth-http": "^3.12",
"spiral/boot": "^3.12",
"spiral/events": "^3.12",
"spiral/console": "^3.12",
"spiral/core": "^3.12",
"spiral/http": "^3.12",
"spiral/mailer": "^3.12",
"spiral/queue": "^3.12",
"spiral/session": "^3.12",
"spiral/security": "^3.12",
"spiral/tokenizer": "^3.12",
"spiral/storage": "^3.12",
"spiral/views": "^3.12",
"spiral/translator": "^3.12",
"spiral/scaffolder": "^3.12",
"symfony/mime": "^6.0 || ^7.0"
},
"suggest": {
"brianium/paratest": "Required to run tests in parallel (^6.0).",
"ext-gd": "Required to use generate fake image files"
},
"require-dev": {
"spiral/framework": "^3.11",
"spiral/framework": "^3.12",
"spiral/roadrunner-bridge": "^2.2 || ^3.0",
"spiral-packages/league-event": "^1.0.1",
"spiral/nyholm-bridge": "^1.2",
Expand Down
17 changes: 17 additions & 0 deletions src/Attribute/TestScope.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
<?php

declare(strict_types=1);

namespace Spiral\Testing\Attribute;

use Attribute;

#[Attribute(flags: Attribute::TARGET_METHOD|Attribute::TARGET_CLASS)]
final class TestScope
{
public function __construct(
public readonly string|\BackedEnum|array $scope,
public readonly array $bindings = [],
) {
}
}
17 changes: 12 additions & 5 deletions src/Http/FakeHttp.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@

use Nyholm\Psr7\ServerRequest;
use Nyholm\Psr7\Stream;
use Psr\Container\ContainerInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Message\StreamInterface;
Expand All @@ -16,7 +17,9 @@
use Spiral\Auth\TokenStorageInterface;
use Spiral\Auth\Transport\HeaderTransport;
use Spiral\Auth\TransportRegistry;
use Spiral\Core\Container;
use Spiral\Core\Attribute\Proxy;
use Spiral\Core\BinderInterface;
use Spiral\Core\InvokerInterface;
use Spiral\Http\Http;
use Spiral\Session\SessionInterface;
use Spiral\Testing\Auth\FakeActorProvider;
Expand All @@ -32,12 +35,16 @@

private ?object $actor = null;
private ?SessionInterface $session = null;
private BinderInterface $binder;

public function __construct(
private readonly Container $container,
#[Proxy] private readonly ContainerInterface $container,
private readonly FileFactory $fileFactory,
private readonly \Closure $scope,
) {
$this->binder = $container
->get(InvokerInterface::class)
->invoke(static fn (#[Proxy] BinderInterface $binder): BinderInterface => $binder);
}

public function withActor(object $actor): self
Expand Down Expand Up @@ -129,7 +136,7 @@
public function withMiddleware(string ...$middleware): self
{
foreach ($middleware as $name) {
$this->container->removeBinding($name);
$this->binder->removeBinding($name);

Check warning on line 139 in src/Http/FakeHttp.php

View check run for this annotation

Codecov / codecov/patch

src/Http/FakeHttp.php#L139

Added line #L139 was not covered by tests
}

return $this;
Expand All @@ -138,8 +145,8 @@
public function withoutMiddleware(string ...$middleware): self
{
foreach ($middleware as $name) {
$this->container->removeBinding($name);
$this->container->bindSingleton(
$this->binder->removeBinding($name);
$this->binder->bindSingleton(

Check warning on line 149 in src/Http/FakeHttp.php

View check run for this annotation

Codecov / codecov/patch

src/Http/FakeHttp.php#L148-L149

Added lines #L148 - L149 were not covered by tests
$name,
new class implements MiddlewareInterface {
public function process(
Expand Down
59 changes: 55 additions & 4 deletions src/TestCase.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@
use Spiral\Core\ConfigsInterface;
use Spiral\Core\Container;
use Spiral\Core\ContainerScope;
use Spiral\Core\Scope;
use Spiral\Testing\Attribute\TestScope;

abstract class TestCase extends BaseTestCase
{
Expand Down Expand Up @@ -127,11 +129,11 @@
* @param array<non-empty-string,mixed> $env
* @return AbstractKernel|TestableKernelInterface
*/
public function makeApp(array $env = []): AbstractKernel
public function makeApp(array $env = [], Container $container = new Container()): AbstractKernel
{
$environment = new Environment($env);

$app = $this->createAppInstance();
$app = $this->createAppInstance($container);
$app->getContainer()->removeBinding(EnvironmentInterface::class);
$app->getContainer()->bindSingleton(EnvironmentInterface::class, $environment);

Expand All @@ -158,9 +160,9 @@
return $app;
}

public function initApp(array $env = []): void
public function initApp(array $env = [], Container $container = new Container()): void
{
$this->app = $this->makeApp($env);
$this->app = $this->makeApp($env, $container);
$this->suppressExceptionHandlingIfAttributeDefined();

(new \ReflectionClass(ContainerScope::class))
Expand Down Expand Up @@ -224,6 +226,21 @@
$this->runTraitSetUpOrTearDown('tearDown');
}

protected function runTest(): mixed
{
$scope = $this->getTestScope();
if ($scope === null) {
return parent::runTest();
}

$scopes = \is_array($scope->scope) ? $scope->scope : [$scope->scope];
$result = $this->runScopes($scopes, function (): mixed {
return parent::runTest();
}, $this->getContainer(), $scope->bindings);

return $result;
}

private function runTraitSetUpOrTearDown(string $method): void
{
$ref = new \ReflectionClass(static::class);
Expand All @@ -244,4 +261,38 @@
$ref = $parent;
}
}

private function getTestScope(): ?TestScope
{
$attribute = $this->getTestAttributes(TestScope::class)[0] ?? null;
if ($attribute !== null) {
return $attribute;
}

try {
foreach ((new \ReflectionClass($this))->getAttributes(TestScope::class) as $attr) {
return $attr->newInstance();

Check warning on line 274 in src/TestCase.php

View check run for this annotation

Codecov / codecov/patch

src/TestCase.php#L274

Added line #L274 was not covered by tests
}
} catch (\Throwable) {
return null;

Check warning on line 277 in src/TestCase.php

View check run for this annotation

Codecov / codecov/patch

src/TestCase.php#L276-L277

Added lines #L276 - L277 were not covered by tests
}

return null;
}

private function runScopes(array $scopes, Closure $callback, Container $container, array $bindings): mixed
{
if ($scopes === []) {
return $container->runScope($bindings, $callback);
}

$scope = \array_shift($scopes);

return $container->runScope(
new Scope($scope, []),
function (Container $container) use ($scopes, $callback, $bindings): mixed {
return $this->runScopes($scopes, $callback, $container, $bindings);
},
);
}
}
10 changes: 5 additions & 5 deletions src/Traits/InteractsWithHttp.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

namespace Spiral\Testing\Traits;

use Spiral\Core\FactoryInterface;
use Spiral\Testing\Http\FakeHttp;
use Spiral\Testing\Http\FileFactory;

Expand All @@ -16,12 +17,11 @@ final public function getFileFactory(): FileFactory

final public function fakeHttp(): FakeHttp
{
return new FakeHttp(
$this->getContainer(),
$this->getFileFactory(),
function (\Closure $closure, array $bindings = []) {
return $this->getContainer()->get(FactoryInterface::class)->make(FakeHttp::class, [
'fileFactory' => $this->getFileFactory(),
'scope' => function (\Closure $closure, array $bindings = []) {
return $this->runScoped($closure, $bindings);
}
);
]);
}
}
10 changes: 10 additions & 0 deletions src/Traits/TestableKernel.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,22 @@

use Spiral\Boot\DispatcherInterface;
use Spiral\Core\Container;
use Spiral\Core\ContainerScope;
use Spiral\Core\Internal\Introspector;

trait TestableKernel
{
/** @inheritDoc */
public function getContainer(): Container
{
$scopedContainer = ContainerScope::getContainer();
if (
$scopedContainer instanceof Container &&
Introspector::scopeName($scopedContainer) !== Container::DEFAULT_ROOT_SCOPE_NAME
) {
return $scopedContainer;
}

return $this->container;
}

Expand Down
20 changes: 20 additions & 0 deletions tests/src/Attribute/ConfigTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,10 @@

namespace Spiral\Testing\Tests\Attribute;

use Spiral\Core\Internal\Introspector;
use Spiral\Storage\Config\StorageConfig;
use Spiral\Testing\Attribute\Config;
use Spiral\Testing\Attribute\TestScope;
use Spiral\Testing\Tests\TestCase;

final class ConfigTest extends TestCase
Expand All @@ -31,4 +33,22 @@ public function testMultipleAttributes(): void
$this->assertSame('replaced', $config['default']);
$this->assertSame('test', $config['servers']['static']['directory']);
}

#[TestScope('foo')]
#[Config('storage.default', 'replaced')]
public function testReplaceUsingAttributeInScope(): void
{
$config = $this->getConfig(StorageConfig::CONFIG);
$this->assertSame('replaced', $config['default']);
$this->assertSame(['foo', 'root'], Introspector::scopeNames($this->getContainer()));
}

#[TestScope(['foo', 'bar'])]
#[Config('storage.default', 'replaced')]
public function testReplaceUsingAttributeInNestedScope(): void
{
$config = $this->getConfig(StorageConfig::CONFIG);
$this->assertSame('replaced', $config['default']);
$this->assertSame(['bar', 'foo', 'root'], Introspector::scopeNames($this->getContainer()));
}
}
20 changes: 20 additions & 0 deletions tests/src/Attribute/EnvTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,9 @@

namespace Spiral\Testing\Tests\Attribute;

use Spiral\Core\Internal\Introspector;
use Spiral\Testing\Attribute\Env;
use Spiral\Testing\Attribute\TestScope;
use Spiral\Testing\Tests\TestCase;

final class EnvTest extends TestCase
Expand Down Expand Up @@ -34,4 +36,22 @@ public function testMultipleAttributes(): void
$this->assertEnvironmentValueSame('FOO', 'BAZ');
$this->assertEnvironmentValueSame('BAZ', 'BAZ');
}

#[TestScope('foo')]
#[Env('FOO', 'BAZ')]
public function testEnvFromAttributeInScope(): void
{
$this->assertEnvironmentValueSame('FOO', 'BAZ');
$this->assertEnvironmentValueSame('BAZ', 'QUX');
$this->assertSame(['foo', 'root'], Introspector::scopeNames($this->getContainer()));
}

#[TestScope(['foo', 'bar'])]
#[Env('FOO', 'BAZ')]
public function testEnvFromAttributeInNestedScope(): void
{
$this->assertEnvironmentValueSame('FOO', 'BAZ');
$this->assertEnvironmentValueSame('BAZ', 'QUX');
$this->assertSame(['bar', 'foo', 'root'], Introspector::scopeNames($this->getContainer()));
}
}
36 changes: 36 additions & 0 deletions tests/src/Attribute/TestScopeTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
<?php

declare(strict_types=1);

namespace Spiral\Testing\Tests\Attribute;

use Spiral\Core\Internal\Introspector;
use Spiral\Testing\Attribute\TestScope;
use Spiral\Testing\Tests\TestCase;

final class TestScopeTest extends TestCase
{
public function testDefaultScope(): void
{
$this->assertSame(['root'], Introspector::scopeNames($this->getContainer()));
}

#[TestScope('foo')]
public function testScopeFromAttribute(): void
{
$this->assertSame(['foo', 'root'], Introspector::scopeNames($this->getContainer()));
}

#[TestScope(['foo', 'bar'])]
public function testNestedScopes(): void
{
$this->assertSame(['bar', 'foo', 'root'], Introspector::scopeNames($this->getContainer()));
}

#[TestScope('foo', ['test' => \stdClass::class])]
public function testScopeWithBindings(): void
{
$this->assertSame(['foo', 'root'], Introspector::scopeNames($this->getContainer()));
$this->assertInstanceOf(\stdClass::class, $this->getContainer()->get('test'));
}
}
Loading
Loading