Skip to content
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
8 changes: 5 additions & 3 deletions phpunit.xml.dist
Original file line number Diff line number Diff line change
@@ -1,20 +1,22 @@
<?xml version="1.0" encoding="UTF-8"?>
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="https://schema.phpunit.de/12.0/phpunit.xsd"
bootstrap="vendor/autoload.php"
bootstrap="tests/bootstrap.php"
cacheDirectory=".phpunit.cache"
executionOrder="defects"
requireCoverageMetadata="true"
beStrictAboutCoverageMetadata="true"
beStrictAboutOutputDuringTests="true"
failOnRisky="true"
failOnWarning="true">
failOnWarning="true"
failOnDeprecation="true"
displayDetailsOnTestsThatTriggerDeprecations="true">
<testsuites>
<testsuite name="default">
<directory>tests</directory>
</testsuite>
</testsuites>
<source>
<source ignoreSuppressionOfDeprecations="true">
<include>
<directory suffix=".php">src</directory>
</include>
Expand Down
5 changes: 5 additions & 0 deletions rector.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
declare(strict_types=1);

use Rector\Config\RectorConfig;
use Rector\DeadCode\Rector\If_\RemoveAlwaysTrueIfConditionRector;
use Rector\Symfony\Set\SymfonySetList;
use Rector\ValueObject\PhpVersion;

Expand All @@ -20,4 +21,8 @@
->withSets([
SymfonySetList::SYMFONY_CONSTRUCTOR_INJECTION,
])
->withSkip([
// Conditions on the Symfony version: always true with the installed version only
RemoveAlwaysTrueIfConditionRector::class => [__DIR__.'/tests/App/TestKernel.php'],
])
;
131 changes: 131 additions & 0 deletions tests/App/TestKernel.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,131 @@
<?php

declare(strict_types=1);

/*
* This file is part of the CleverAge/ProcessBundle package.
*
* Copyright (c) Clever-Age
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace CleverAge\ProcessBundle\Tests\App;

use CleverAge\ProcessBundle\CleverAgeProcessBundle;
use CleverAge\ProcessBundle\Manager\ProcessManager;
use CleverAge\ProcessBundle\Registry\ProcessConfigurationRegistry;
use CleverAge\ProcessBundle\Registry\TaskRegistry;
use CleverAge\ProcessBundle\Registry\TransformerRegistry;
use Psr\Log\NullLogger;
use Symfony\Bundle\FrameworkBundle\FrameworkBundle;
use Symfony\Bundle\FrameworkBundle\Kernel\MicroKernelTrait;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
use Symfony\Component\HttpKernel\Kernel;
use Symfony\Component\Yaml\Yaml;

/**
* Application used by the integration tests: the bundle with FrameworkBundle, a process referencing every task of the
* bundle by its code and a process to run, in a temporary directory of its own (per PHP process).
*/
final class TestKernel extends Kernel
{
use MicroKernelTrait;

public function registerBundles(): iterable
{
yield new FrameworkBundle();
yield new CleverAgeProcessBundle();
}

public function getProjectDir(): string
{
return __DIR__;
}

public function getCacheDir(): string
{
return $this->getRunDir().'/cache/'.$this->environment;
}

public function getLogDir(): string
{
return $this->getRunDir().'/logs';
}

/**
* Codes of the tasks of the bundle (cleverage.task tags of config/services/task.yaml).
*
* @return list<string>
*/
public static function getTaskCodes(): array
{
/** @var array{services: array<string, array{tags?: list<array{name?: string, code?: string}|string>}|string|null>} $config */
$config = Yaml::parseFile(\dirname(__DIR__, 2).'/config/services/task.yaml', Yaml::PARSE_CUSTOM_TAGS);
$codes = [];
foreach ($config['services'] as $service) {
foreach (\is_array($service) ? $service['tags'] ?? [] : [] as $tag) {
if (\is_array($tag) && 'cleverage.task' === ($tag['name'] ?? null) && isset($tag['code'])) {
$codes[] = $tag['code'];
}
}
}

return $codes;
}

protected function configureContainer(ContainerConfigurator $container): void
{
$container->extension('framework', [
'secret' => 'test',
'test' => true,
'http_method_override' => false,
'handle_all_throwables' => true,
'php_errors' => ['log' => true],
'validation' => ['email_validation_mode' => 'html5'],
]);
if (Kernel::VERSION_ID >= 70300) {
// Not setting it is deprecated since Symfony 7.3: its default value changes in 8.0
$container->extension('framework', ['property_info' => ['with_constructor_extractor' => true]]);
}

$tasks = [];
foreach (self::getTaskCodes() as $code) {
$tasks[$code] = ['task' => $code];
}
$container->extension('clever_age_process', [
'configurations' => [
'test.every_task' => ['tasks' => $tasks],
'test.run' => [
'end_point' => 'format',
'tasks' => [
'constant' => [
'task' => 'constant_output',
'options' => ['output' => 'world'],
'outputs' => ['format'],
],
'format' => [
'task' => 'transformer',
'options' => ['transformers' => ['sprintf' => ['format' => 'Hello %s']]],
],
],
],
],
]);

$services = $container->services();
// The default logger of FrameworkBundle may write the process logs to the output
$services->set('logger', NullLogger::class);
// Exposed to the tests
$services->alias('test.task_registry', TaskRegistry::class)->public();
$services->alias('test.transformer_registry', TransformerRegistry::class)->public();
$services->alias('test.process_configuration_registry', ProcessConfigurationRegistry::class)->public();
$services->alias('test.process_manager', ProcessManager::class)->public();
}

private function getRunDir(): string
{
return sys_get_temp_dir().'/process_bundle_tests_'.getmypid();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -14,13 +14,16 @@
namespace CleverAge\ProcessBundle\Tests\DependencyInjection\Compiler;

use CleverAge\ProcessBundle\DependencyInjection\Compiler\RegistryCompilerPass;
use CleverAge\ProcessBundle\Tests\IgnoreDeprecationsTrait;
use PHPUnit\Framework\TestCase;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Reference;

#[\PHPUnit\Framework\Attributes\CoversClass(RegistryCompilerPass::class)]
class RegistryCompilerPassTest extends TestCase
{
use IgnoreDeprecationsTrait;

public function testIsDeprecated(): void
{
$deprecations = [];
Expand All @@ -44,7 +47,7 @@ public function testTaggedServicesAreAddedToTheRegistry(): void
$container->register('registry', \ArrayObject::class);
$container->register('service', \stdClass::class)->addTag('tag');

(new RegistryCompilerPass('registry', 'tag', 'append'))->process($container);
self::ignoreDeprecations(static fn () => new RegistryCompilerPass('registry', 'tag', 'append'))->process($container);

self::assertEquals([['append', [new Reference('service')]]], $container->getDefinition('registry')->getMethodCalls());
}
Expand All @@ -54,7 +57,7 @@ public function testMissingRegistryIsIgnored(): void
$container = new ContainerBuilder();
$container->register('service', \stdClass::class)->addTag('tag');

(new RegistryCompilerPass('registry', 'tag', 'append'))->process($container);
self::ignoreDeprecations(static fn () => new RegistryCompilerPass('registry', 'tag', 'append'))->process($container);

self::assertFalse($container->has('registry'));
}
Expand All @@ -64,6 +67,6 @@ public function testUndefinedConfigurationThrows(): void
$this->expectException(\LogicException::class);
$this->expectExceptionMessage('The registry, tag and method of the RegistryCompilerPass must be defined');

(new RegistryCompilerPass())->process(new ContainerBuilder());
self::ignoreDeprecations(static fn () => new RegistryCompilerPass())->process(new ContainerBuilder());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
use CleverAge\ProcessBundle\DependencyInjection\Compiler\TaskLocatorCompilerPass;
use CleverAge\ProcessBundle\DependencyInjection\Configuration;
use CleverAge\ProcessBundle\Task\DummyTask;
use CleverAge\ProcessBundle\Tests\IgnoreDeprecationsTrait;
use PHPUnit\Framework\Attributes\CoversClass;
use PHPUnit\Framework\Attributes\UsesClass;
use PHPUnit\Framework\TestCase;
Expand All @@ -32,10 +33,13 @@
#[UsesClass(Configuration::class)]
class TaskLocatorCompilerPassTest extends TestCase
{
use IgnoreDeprecationsTrait;

public function testLocatorContainsTheServicesReferencedByTheProcesses(): void
{
$container = new ContainerBuilder();
(new CleverAgeProcessExtension())->load([[
// Deprecated "service" option
self::ignoreDeprecations(static fn () => (new CleverAgeProcessExtension())->load([[
'configurations' => [
'test.first' => ['tasks' => [
'dummy' => ['service' => '@'.DummyTask::class],
Expand All @@ -46,7 +50,7 @@ public function testLocatorContainsTheServicesReferencedByTheProcesses(): void
'unknown' => ['service' => '@app.unknown'],
]],
],
]], $container);
]], $container));
// Private services can be fetched from the locator
$container->setDefinition('app.private_task', (new Definition(DummyTask::class))->setPublic(false));

Expand Down
11 changes: 8 additions & 3 deletions tests/DependencyInjection/ConfigurationTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@

use CleverAge\ProcessBundle\DependencyInjection\CleverAgeProcessExtension;
use CleverAge\ProcessBundle\DependencyInjection\Configuration;
use CleverAge\ProcessBundle\Tests\IgnoreDeprecationsTrait;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Config\Definition\Exception\InvalidConfigurationException;
use Symfony\Component\Config\Definition\Processor;
Expand All @@ -24,6 +25,8 @@
#[\PHPUnit\Framework\Attributes\CoversClass(CleverAgeProcessExtension::class)]
class ConfigurationTest extends TestCase
{
use IgnoreDeprecationsTrait;

public function testLogLevelsDefaults(): void
{
$config = $this->process(['configurations' => ['test.process' => ['tasks' => []]]]);
Expand Down Expand Up @@ -56,10 +59,11 @@ public function testLogLevelsCanBeConfigured(): void

public function testTaskIsDefinedByAServiceOrACode(): void
{
$config = $this->process(['configurations' => ['test.process' => ['tasks' => [
// Deprecated "service" option, see testServiceIsDeprecated()
$config = self::ignoreDeprecations(fn (): array => $this->process(['configurations' => ['test.process' => ['tasks' => [
'by_service' => ['service' => '@app.task'],
'by_code' => ['task' => 'transformer'],
]]]]);
]]]]));

$tasks = $config['configurations']['test.process']['tasks'];
self::assertSame(['@app.task', null], [$tasks['by_service']['service'], $tasks['by_service']['task']]);
Expand Down Expand Up @@ -107,7 +111,8 @@ public function testTaskMustDefineEitherAServiceOrACode(array $task): void
$this->expectException(InvalidConfigurationException::class);
$this->expectExceptionMessage('A task must define either its code ("task: <code>") or, deprecated, its "service", not both');

$this->process(['configurations' => ['test.process' => ['tasks' => ['invalid' => $task]]]]);
// Deprecated "service" option, see testServiceIsDeprecated()
self::ignoreDeprecations(fn (): array => $this->process(['configurations' => ['test.process' => ['tasks' => ['invalid' => $task]]]]));
}

public function testInvalidDefaultLogLevelIsRejected(): void
Expand Down
95 changes: 95 additions & 0 deletions tests/Functional/KernelTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
<?php

declare(strict_types=1);

/*
* This file is part of the CleverAge/ProcessBundle package.
*
* Copyright (c) Clever-Age
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace CleverAge\ProcessBundle\Tests\Functional;

use CleverAge\ProcessBundle\Manager\ProcessManager;
use CleverAge\ProcessBundle\Model\TaskInterface;
use CleverAge\ProcessBundle\Registry\ProcessConfigurationRegistry;
use CleverAge\ProcessBundle\Registry\TaskRegistry;
use CleverAge\ProcessBundle\Registry\TransformerRegistry;
use CleverAge\ProcessBundle\Tests\App\TestKernel;
use CleverAge\ProcessBundle\Transformer\TransformerInterface;
use PHPUnit\Framework\Attributes\CoversNothing;
use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;

/**
* The bundle in an application (see TestKernel): the container compiles, the tasks and transformers are resolved with
* their dependencies, a process runs.
*/
#[CoversNothing]
class KernelTest extends KernelTestCase
{
private mixed $exceptionHandler;

protected function setUp(): void
{
$this->exceptionHandler = $this->getExceptionHandler();
}

protected function tearDown(): void
{
parent::tearDown();
// The ErrorHandler registered when the kernel boots is not removed by the first Symfony 6.4 versions
if ($this->getExceptionHandler() !== $this->exceptionHandler) {
restore_exception_handler();
}
}

public function testEveryTaskIsResolvedByItsCode(): void
{
$processConfigurationRegistry = self::getContainer()->get('test.process_configuration_registry');
self::assertInstanceOf(ProcessConfigurationRegistry::class, $processConfigurationRegistry);
$taskRegistry = self::getContainer()->get('test.task_registry');
self::assertInstanceOf(TaskRegistry::class, $taskRegistry);

$processConfiguration = $processConfigurationRegistry->getProcessConfiguration('test.every_task');
$codes = TestKernel::getTaskCodes();
self::assertNotEmpty($codes);
foreach ($codes as $code) {
self::assertInstanceOf(TaskInterface::class, $taskRegistry->getTask($processConfiguration->getTaskConfiguration($code)), $code);
}
}

public function testEveryTransformerIsResolved(): void
{
$transformerRegistry = self::getContainer()->get('test.transformer_registry');
self::assertInstanceOf(TransformerRegistry::class, $transformerRegistry);

$transformers = $transformerRegistry->getTransformers();
self::assertNotEmpty($transformers);
self::assertContainsOnlyInstancesOf(TransformerInterface::class, $transformers);
self::assertInstanceOf(TransformerInterface::class, $transformerRegistry->getTransformer('sprintf'));
}

public function testProcessIsExecuted(): void
{
$processManager = self::getContainer()->get('test.process_manager');
self::assertInstanceOf(ProcessManager::class, $processManager);

self::assertSame('Hello world', $processManager->execute('test.run'));
}

private function getExceptionHandler(): mixed
{
$handler = set_exception_handler(null);
restore_exception_handler();

return $handler;
}

protected static function getKernelClass(): string
{
return TestKernel::class;
}
}
Loading
Loading