Skip to content
Snippets Groups Projects
Commit 03a13db2 authored by Kunal Sachdev's avatar Kunal Sachdev Committed by Ted Bowman
Browse files

Issue #3327753 by kunal.sachdev, tedbow, Wim Leers: Create a helper function to add listeners

parent 2b96d558
No related branches found
No related tags found
1 merge request!628Issue #3327753: Create a helper function to add listeners
Showing
with 121 additions and 184 deletions
...@@ -84,7 +84,7 @@ class ComposerExecutableValidatorTest extends PackageManagerKernelTestBase { ...@@ -84,7 +84,7 @@ class ComposerExecutableValidatorTest extends PackageManagerKernelTestBase {
$listener = function () use ($exception): void { $listener = function () use ($exception): void {
TestComposerExecutableValidator::setCommandOutput($exception); TestComposerExecutableValidator::setCommandOutput($exception);
}; };
$this->container->get('event_dispatcher')->addListener(PreApplyEvent::class, $listener, PHP_INT_MAX); $this->addEventTestListener($listener);
// The validator should translate that exception into an error. // The validator should translate that exception into an error.
$error = ValidationResult::createError([ $error = ValidationResult::createError([
...@@ -96,7 +96,7 @@ class ComposerExecutableValidatorTest extends PackageManagerKernelTestBase { ...@@ -96,7 +96,7 @@ class ComposerExecutableValidatorTest extends PackageManagerKernelTestBase {
// Setting command output which doesn't raise error for pre-create event. // Setting command output which doesn't raise error for pre-create event.
TestComposerExecutableValidator::setCommandOutput("Composer version 2.2.12"); TestComposerExecutableValidator::setCommandOutput("Composer version 2.2.12");
$this->enableModules(['help']); $this->enableModules(['help']);
$this->container->get('event_dispatcher')->addListener(PreApplyEvent::class, $listener, PHP_INT_MAX); $this->addEventTestListener($listener);
$this->assertResultsWithHelp([$error], PreApplyEvent::class, FALSE); $this->assertResultsWithHelp([$error], PreApplyEvent::class, FALSE);
} }
...@@ -224,7 +224,7 @@ class ComposerExecutableValidatorTest extends PackageManagerKernelTestBase { ...@@ -224,7 +224,7 @@ class ComposerExecutableValidatorTest extends PackageManagerKernelTestBase {
$listener = function () use ($reported_version): void { $listener = function () use ($reported_version): void {
TestComposerExecutableValidator::setCommandOutput("Composer version $reported_version"); TestComposerExecutableValidator::setCommandOutput("Composer version $reported_version");
}; };
$this->container->get('event_dispatcher')->addListener(PreApplyEvent::class, $listener, PHP_INT_MAX); $this->addEventTestListener($listener);
// If the validator can't find a recognized, supported version of Composer, // If the validator can't find a recognized, supported version of Composer,
// it should produce errors. // it should produce errors.
...@@ -234,7 +234,7 @@ class ComposerExecutableValidatorTest extends PackageManagerKernelTestBase { ...@@ -234,7 +234,7 @@ class ComposerExecutableValidatorTest extends PackageManagerKernelTestBase {
// Setting command output which doesn't raise error for pre-create event. // Setting command output which doesn't raise error for pre-create event.
TestComposerExecutableValidator::setCommandOutput("Composer version 2.2.12"); TestComposerExecutableValidator::setCommandOutput("Composer version 2.2.12");
$this->enableModules(['help']); $this->enableModules(['help']);
$this->container->get('event_dispatcher')->addListener(PreApplyEvent::class, $listener, PHP_INT_MAX); $this->addEventTestListener($listener);
$this->assertResultsWithHelp($expected_results, PreApplyEvent::class, FALSE); $this->assertResultsWithHelp($expected_results, PreApplyEvent::class, FALSE);
} }
......
...@@ -25,16 +25,7 @@ class ComposerJsonExistsValidatorTest extends PackageManagerKernelTestBase { ...@@ -25,16 +25,7 @@ class ComposerJsonExistsValidatorTest extends PackageManagerKernelTestBase {
'No composer.json file can be found at vfs://root/active', 'No composer.json file can be found at vfs://root/active',
]); ]);
foreach ([PreCreateEvent::class, StatusCheckEvent::class] as $event_class) { foreach ([PreCreateEvent::class, StatusCheckEvent::class] as $event_class) {
$this->container->get('event_dispatcher')->addListener( $this->assertEventPropagationStopped($event_class, [$this->container->get('package_manager.validator.composer_json_exists'), 'validateComposerJson']);
$event_class,
function () use ($event_class): void {
$this->fail('Event propagation should have been stopped during ' . $event_class . '.');
},
// Execute this listener immediately after the tested validator, which
// uses priority 190. This ensures informative test failures.
// @see \Drupal\package_manager\Validator\ComposerJsonExistsValidator::getSubscribedEvents()
189
);
} }
$this->assertStatusCheckResults([$result]); $this->assertStatusCheckResults([$result]);
$this->assertResults([$result], PreCreateEvent::class); $this->assertResults([$result], PreCreateEvent::class);
...@@ -47,24 +38,11 @@ class ComposerJsonExistsValidatorTest extends PackageManagerKernelTestBase { ...@@ -47,24 +38,11 @@ class ComposerJsonExistsValidatorTest extends PackageManagerKernelTestBase {
$result = ValidationResult::createError([ $result = ValidationResult::createError([
'No composer.json file can be found at vfs://root/active', 'No composer.json file can be found at vfs://root/active',
]); ]);
$this->container->get('event_dispatcher')->addListener( $this->addEventTestListener(function (): void {
PreApplyEvent::class, unlink($this->container->get('package_manager.path_locator')
function (): void { ->getProjectRoot() . '/composer.json');
unlink($this->container->get('package_manager.path_locator') });
->getProjectRoot() . '/composer.json'); $this->assertEventPropagationStopped(PreApplyEvent::class, [$this->container->get('package_manager.validator.composer_json_exists'), 'validateComposerJson']);
},
PHP_INT_MAX
);
$this->container->get('event_dispatcher')->addListener(
PreApplyEvent::class,
function (): void {
$this->fail('Event propagation should have been stopped during ' . PreApplyEvent::class . '.');
},
// Execute this listener immediately after the tested validator, which
// uses priority 190. This ensures informative test failures.
// @see \Drupal\package_manager\Validator\ComposerJsonExistsValidator::getSubscribedEvents()
189
);
$this->assertResults([$result], PreApplyEvent::class); $this->assertResults([$result], PreApplyEvent::class);
} }
......
...@@ -46,13 +46,9 @@ class ComposerPatchesValidatorTest extends PackageManagerKernelTestBase { ...@@ -46,13 +46,9 @@ class ComposerPatchesValidatorTest extends PackageManagerKernelTestBase {
$dir = $this->container->get('package_manager.path_locator') $dir = $this->container->get('package_manager.path_locator')
->getProjectRoot(); ->getProjectRoot();
$this->container->get('event_dispatcher')->addListener( $this->addEventTestListener(function () use ($dir): void {
PreApplyEvent::class, $this->installPatcherInActive($dir);
function () use ($dir): void { });
$this->installPatcherInActive($dir);
},
PHP_INT_MAX
);
// Because ComposerUtility reads composer.json and passes it to the Composer // Because ComposerUtility reads composer.json and passes it to the Composer
// factory as an array, Composer will assume that the configuration is // factory as an array, Composer will assume that the configuration is
// coming from a config.json file, even if one doesn't exist. // coming from a config.json file, even if one doesn't exist.
......
...@@ -80,15 +80,11 @@ class ComposerSettingsValidatorTest extends PackageManagerKernelTestBase { ...@@ -80,15 +80,11 @@ class ComposerSettingsValidatorTest extends PackageManagerKernelTestBase {
* @dataProvider providerSecureHttpValidation * @dataProvider providerSecureHttpValidation
*/ */
public function testSecureHttpValidationDuringPreApply(string $contents, array $expected_results): void { public function testSecureHttpValidationDuringPreApply(string $contents, array $expected_results): void {
$this->container->get('event_dispatcher')->addListener( $this->addEventTestListener(function () use ($contents): void {
PreApplyEvent::class, $active_dir = $this->container->get('package_manager.path_locator')
function () use ($contents): void { ->getProjectRoot();
$active_dir = $this->container->get('package_manager.path_locator') file_put_contents("$active_dir/composer.json", $contents);
->getProjectRoot(); });
file_put_contents("$active_dir/composer.json", $contents);
},
PHP_INT_MAX
);
$this->assertResults($expected_results, PreApplyEvent::class); $this->assertResults($expected_results, PreApplyEvent::class);
} }
......
...@@ -171,16 +171,12 @@ class DiskSpaceValidatorTest extends PackageManagerKernelTestBase { ...@@ -171,16 +171,12 @@ class DiskSpaceValidatorTest extends PackageManagerKernelTestBase {
* @dataProvider providerDiskSpaceValidation * @dataProvider providerDiskSpaceValidation
*/ */
public function testDiskSpaceValidationDuringPreApply(bool $shared_disk, array $free_space, array $expected_results): void { public function testDiskSpaceValidationDuringPreApply(bool $shared_disk, array $free_space, array $expected_results): void {
$this->container->get('event_dispatcher')->addListener( $this->addEventTestListener(function () use ($shared_disk, $free_space): void {
PreApplyEvent::class, /** @var \Drupal\Tests\package_manager\Kernel\TestDiskSpaceValidator $validator */
function () use ($shared_disk, $free_space): void { $validator = $this->container->get('package_manager.validator.disk_space');
/** @var \Drupal\Tests\package_manager\Kernel\TestDiskSpaceValidator $validator */ $validator->sharedDisk = $shared_disk;
$validator = $this->container->get('package_manager.validator.disk_space'); $validator->freeSpace = array_map([Bytes::class, 'toNumber'], $free_space);
$validator->sharedDisk = $shared_disk; });
$validator->freeSpace = array_map([Bytes::class, 'toNumber'], $free_space);
},
PHP_INT_MAX
);
$this->assertResults($expected_results, PreApplyEvent::class); $this->assertResults($expected_results, PreApplyEvent::class);
} }
......
...@@ -27,16 +27,7 @@ class EnvironmentSupportValidatorTest extends PackageManagerKernelTestBase { ...@@ -27,16 +27,7 @@ class EnvironmentSupportValidatorTest extends PackageManagerKernelTestBase {
'Package Manager is not supported by your environment.', 'Package Manager is not supported by your environment.',
]); ]);
foreach ([PreCreateEvent::class, StatusCheckEvent::class] as $event_class) { foreach ([PreCreateEvent::class, StatusCheckEvent::class] as $event_class) {
$this->container->get('event_dispatcher')->addListener( $this->assertEventPropagationStopped($event_class, [$this->container->get('package_manager.validator.environment_support'), 'validateStagePreOperation']);
$event_class,
function () use ($event_class): void {
$this->fail('Event propagation should have been stopped during ' . $event_class . '.');
},
// Execute this listener immediately after the tested validator, which
// uses priority 200. This ensures informative test failures.
// @see \Drupal\package_manager\Validator\EnvironmentSupportValidator::getSubscribedEvents()
199
);
} }
$this->assertStatusCheckResults([$result]); $this->assertStatusCheckResults([$result]);
$this->assertResults([$result], PreCreateEvent::class); $this->assertResults([$result], PreCreateEvent::class);
...@@ -46,28 +37,15 @@ class EnvironmentSupportValidatorTest extends PackageManagerKernelTestBase { ...@@ -46,28 +37,15 @@ class EnvironmentSupportValidatorTest extends PackageManagerKernelTestBase {
* Tests an invalid URL in the environment support variable during pre-apply. * Tests an invalid URL in the environment support variable during pre-apply.
*/ */
public function testInvalidUrlDuringPreApply(): void { public function testInvalidUrlDuringPreApply(): void {
$this->container->get('event_dispatcher')->addListener( $this->addEventTestListener(function (): void {
PreApplyEvent::class, putenv(EnvironmentSupportValidator::VARIABLE_NAME . '=broken/url.org');
function (): void { });
putenv(EnvironmentSupportValidator::VARIABLE_NAME . '=broken/url.org');
},
PHP_INT_MAX
);
$result = ValidationResult::createError([ $result = ValidationResult::createError([
'Package Manager is not supported by your environment.', 'Package Manager is not supported by your environment.',
]); ]);
$this->container->get('event_dispatcher')->addListener( $this->assertEventPropagationStopped(PreApplyEvent::class, [$this->container->get('package_manager.validator.environment_support'), 'validateStagePreOperation']);
PreApplyEvent::class,
function (): void {
$this->fail('Event propagation should have been stopped during ' . PreApplyEvent::class . '.');
},
// Execute this listener immediately after the tested validator, which
// uses priority 200. This ensures informative test failures.
// @see \Drupal\package_manager\Validator\EnvironmentSupportValidator::getSubscribedEvents()
199
);
$this->assertResults([$result], PreApplyEvent::class); $this->assertResults([$result], PreApplyEvent::class);
} }
...@@ -90,13 +68,9 @@ class EnvironmentSupportValidatorTest extends PackageManagerKernelTestBase { ...@@ -90,13 +68,9 @@ class EnvironmentSupportValidatorTest extends PackageManagerKernelTestBase {
*/ */
public function testValidUrlDuringPreApply(): void { public function testValidUrlDuringPreApply(): void {
$url = 'http://www.example.com'; $url = 'http://www.example.com';
$this->container->get('event_dispatcher')->addListener( $this->addEventTestListener(function () use ($url): void {
PreApplyEvent::class, putenv(EnvironmentSupportValidator::VARIABLE_NAME . '=' . $url);
function () use ($url): void { });
putenv(EnvironmentSupportValidator::VARIABLE_NAME . '=' . $url);
},
PHP_INT_MAX
);
$result = ValidationResult::createError([ $result = ValidationResult::createError([
'<a href="' . $url . '">Package Manager is not supported by your environment.</a>', '<a href="' . $url . '">Package Manager is not supported by your environment.</a>',
......
...@@ -74,9 +74,9 @@ class LockFileValidatorTest extends PackageManagerKernelTestBase { ...@@ -74,9 +74,9 @@ class LockFileValidatorTest extends PackageManagerKernelTestBase {
// should raise the validation error. Because the validator uses the default // should raise the validation error. Because the validator uses the default
// priority of 0, this listener changes lock file before the validator // priority of 0, this listener changes lock file before the validator
// runs. // runs.
$this->addListener($event_class, function () { $this->addEventTestListener(function () {
file_put_contents($this->activeDir . '/composer.lock', 'changed'); file_put_contents($this->activeDir . '/composer.lock', 'changed');
}); }, $event_class);
$result = ValidationResult::createError([ $result = ValidationResult::createError([
'Unexpected changes were detected in composer.lock, which indicates that other Composer operations were performed since this Package Manager operation started. This can put the code base into an unreliable state and therefore is not allowed.', 'Unexpected changes were detected in composer.lock, which indicates that other Composer operations were performed since this Package Manager operation started. This can put the code base into an unreliable state and therefore is not allowed.',
]); ]);
...@@ -95,9 +95,9 @@ class LockFileValidatorTest extends PackageManagerKernelTestBase { ...@@ -95,9 +95,9 @@ class LockFileValidatorTest extends PackageManagerKernelTestBase {
// should raise the validation error. Because the validator uses the default // should raise the validation error. Because the validator uses the default
// priority of 0, this listener deletes lock file before the validator // priority of 0, this listener deletes lock file before the validator
// runs. // runs.
$this->addListener($event_class, function () { $this->addEventTestListener(function () {
unlink($this->activeDir . '/composer.lock'); unlink($this->activeDir . '/composer.lock');
}); }, $event_class);
$result = ValidationResult::createError([ $result = ValidationResult::createError([
'Could not hash the active lock file.', 'Could not hash the active lock file.',
]); ]);
...@@ -119,9 +119,9 @@ class LockFileValidatorTest extends PackageManagerKernelTestBase { ...@@ -119,9 +119,9 @@ class LockFileValidatorTest extends PackageManagerKernelTestBase {
// should raise the validation error. Because the validator uses the default // should raise the validation error. Because the validator uses the default
// priority of 0, this listener deletes stored hash before the validator // priority of 0, this listener deletes stored hash before the validator
// runs. // runs.
$this->addListener($event_class, function () use ($state_key) { $this->addEventTestListener(function () use ($state_key) {
$this->container->get('state')->delete($state_key); $this->container->get('state')->delete($state_key);
}); }, $event_class);
$result = ValidationResult::createError([ $result = ValidationResult::createError([
'Could not retrieve stored hash of the active lock file.', 'Could not retrieve stored hash of the active lock file.',
]); ]);
...@@ -171,17 +171,4 @@ class LockFileValidatorTest extends PackageManagerKernelTestBase { ...@@ -171,17 +171,4 @@ class LockFileValidatorTest extends PackageManagerKernelTestBase {
]; ];
} }
/**
* Adds an event listener with the highest possible priority.
*
* @param string $event_class
* The event class to listen for.
* @param callable $listener
* The listener to add.
*/
private function addListener(string $event_class, callable $listener): void {
$this->container->get('event_dispatcher')
->addListener($event_class, $listener, PHP_INT_MAX);
}
} }
...@@ -72,20 +72,16 @@ class MultisiteValidatorTest extends PackageManagerKernelTestBase { ...@@ -72,20 +72,16 @@ class MultisiteValidatorTest extends PackageManagerKernelTestBase {
* @dataProvider providerMultisite * @dataProvider providerMultisite
*/ */
public function testMultisiteDuringPreApply(bool $is_multisite, array $expected_results = []): void { public function testMultisiteDuringPreApply(bool $is_multisite, array $expected_results = []): void {
$this->container->get('event_dispatcher')->addListener( $this->addEventTestListener(function () use ($is_multisite): void {
PreApplyEvent::class, // If we should simulate a multisite, ensure there is a sites.php in the
function () use ($is_multisite): void { // test project.
// If we should simulate a multisite, ensure there is a sites.php in the // @see \Drupal\package_manager\Validator\MultisiteValidator::isMultisite()
// test project. if ($is_multisite) {
// @see \Drupal\package_manager\Validator\MultisiteValidator::isMultisite() $project_root = $this->container->get('package_manager.path_locator')
if ($is_multisite) { ->getProjectRoot();
$project_root = $this->container->get('package_manager.path_locator') touch($project_root . '/sites/sites.php');
->getProjectRoot(); }
touch($project_root . '/sites/sites.php'); });
}
},
PHP_INT_MAX
);
$this->assertResults($expected_results, PreApplyEvent::class); $this->assertResults($expected_results, PreApplyEvent::class);
} }
......
...@@ -6,6 +6,7 @@ namespace Drupal\Tests\package_manager\Kernel; ...@@ -6,6 +6,7 @@ namespace Drupal\Tests\package_manager\Kernel;
use Drupal\Core\DependencyInjection\ContainerBuilder; use Drupal\Core\DependencyInjection\ContainerBuilder;
use Drupal\KernelTests\KernelTestBase; use Drupal\KernelTests\KernelTestBase;
use Drupal\package_manager\Event\PreApplyEvent;
use Drupal\package_manager\Event\StageEvent; use Drupal\package_manager\Event\StageEvent;
use Drupal\package_manager\StatusCheckTrait; use Drupal\package_manager\StatusCheckTrait;
use Drupal\package_manager\UnusedConfigFactory; use Drupal\package_manager\UnusedConfigFactory;
...@@ -323,6 +324,44 @@ abstract class PackageManagerKernelTestBase extends KernelTestBase { ...@@ -323,6 +324,44 @@ abstract class PackageManagerKernelTestBase extends KernelTestBase {
$this->container->set('http_client', $this->client); $this->container->set('http_client', $this->client);
} }
/**
* Adds an event listener on an event for testing purposes.
*
* @param callable $listener
* The listener to add.
* @param string $event_class
* (optional) The event to listen to. Defaults to PreApplyEvent.
* @param int $priority
* (optional) The priority. Defaults to PHP_INT_MAX.
*/
protected function addEventTestListener(callable $listener, string $event_class = PreApplyEvent::class, int $priority = PHP_INT_MAX): void {
$this->container->get('event_dispatcher')
->addListener($event_class, $listener, $priority);
}
/**
* Asserts event propagation is stopped by a certain event subscriber.
*
* @param string $event_class
* The event during which propagation is expected to stop.
* @param callable $expected_propagation_stopper
* The event subscriber (which subscribes to the given event class) which is
* expected to stop propagation. This event subscriber must have been
* registered by one of the installed Drupal module.
*/
protected function assertEventPropagationStopped(string $event_class, callable $expected_propagation_stopper): void {
$priority = $this->container->get('event_dispatcher')->getListenerPriority($event_class, $expected_propagation_stopper);
// Ensure the event subscriber was actually a listener for the event.
$this->assertIsInt($priority);
// Add a listener with a priority that is 1 less than priority of the
// event subscriber. This listener would be called after
// $expected_propagation_stopper if the event propagation was not stopped
// and cause the test to fail.
$this->addEventTestListener(function () use ($event_class): void {
$this->fail('Event propagation should have been stopped during ' . $event_class . '.');
}, $event_class, $priority - 1);
}
} }
/** /**
......
...@@ -57,13 +57,9 @@ class SettingsValidatorTest extends PackageManagerKernelTestBase { ...@@ -57,13 +57,9 @@ class SettingsValidatorTest extends PackageManagerKernelTestBase {
* @dataProvider providerSettingsValidation * @dataProvider providerSettingsValidation
*/ */
public function testSettingsValidationDuringPreApply(bool $setting, array $expected_results): void { public function testSettingsValidationDuringPreApply(bool $setting, array $expected_results): void {
$this->container->get('event_dispatcher')->addListener( $this->addEventTestListener(function () use ($setting): void {
PreApplyEvent::class, $this->setSetting('update_fetch_with_http_fallback', $setting);
function () use ($setting): void { });
$this->setSetting('update_fetch_with_http_fallback', $setting);
},
PHP_INT_MAX
);
$this->assertResults($expected_results, PreApplyEvent::class); $this->assertResults($expected_results, PreApplyEvent::class);
} }
......
...@@ -151,8 +151,7 @@ class StageEventsTest extends PackageManagerKernelTestBase implements EventSubsc ...@@ -151,8 +151,7 @@ class StageEventsTest extends PackageManagerKernelTestBase implements EventSubsc
} }
} }
}; };
$this->container->get('event_dispatcher') $this->addEventTestListener($handler, $event_class);
->addListener($event_class, $handler);
$result = ValidationResult::createError($error_messages); $result = ValidationResult::createError($error_messages);
$this->assertResults([$result], $event_class); $this->assertResults([$result], $event_class);
...@@ -170,10 +169,8 @@ class StageEventsTest extends PackageManagerKernelTestBase implements EventSubsc ...@@ -170,10 +169,8 @@ class StageEventsTest extends PackageManagerKernelTestBase implements EventSubsc
$this->assertSame($expected_runtime, $event->getRuntimePackages()); $this->assertSame($expected_runtime, $event->getRuntimePackages());
$this->assertSame($expected_dev, $event->getDevPackages()); $this->assertSame($expected_dev, $event->getDevPackages());
}; };
/** @var \Symfony\Component\EventDispatcher\EventDispatcherInterface $event_dispatcher */ $this->addEventTestListener($listener, PreRequireEvent::class);
$event_dispatcher = $this->container->get('event_dispatcher'); $this->addEventTestListener($listener, PostRequireEvent::class);
$event_dispatcher->addListener(PreRequireEvent::class, $listener);
$event_dispatcher->addListener(PostRequireEvent::class, $listener);
$this->stage->create(); $this->stage->create();
$this->stage->require(['drupal/core:9.8.2'], ['drupal/core-dev:9.8.2']); $this->stage->require(['drupal/core:9.8.2'], ['drupal/core-dev:9.8.2']);
......
...@@ -294,10 +294,9 @@ class StageOwnershipTest extends PackageManagerKernelTestBase { ...@@ -294,10 +294,9 @@ class StageOwnershipTest extends PackageManagerKernelTestBase {
// Listen to the post-destroy event so we can confirm that it was fired, and // Listen to the post-destroy event so we can confirm that it was fired, and
// the stage was made available, despite the file system error. // the stage was made available, despite the file system error.
$stage_available = NULL; $stage_available = NULL;
$this->container->get('event_dispatcher') $this->addEventTestListener(function (PostDestroyEvent $event) use (&$stage_available): void {
->addListener(PostDestroyEvent::class, function (PostDestroyEvent $event) use (&$stage_available): void { $stage_available = $event->getStage()->isAvailable();
$stage_available = $event->getStage()->isAvailable(); }, PostDestroyEvent::class);
});
$stage->destroy(); $stage->destroy();
$this->assertTrue($stage_available); $this->assertTrue($stage_available);
......
...@@ -180,8 +180,7 @@ class StageTest extends PackageManagerKernelTestBase { ...@@ -180,8 +180,7 @@ class StageTest extends PackageManagerKernelTestBase {
// testing purposes. // testing purposes.
$event->getStage()->destroy($force); $event->getStage()->destroy($force);
}; };
$this->container->get('event_dispatcher') $this->addEventTestListener($listener, $event_class, 0);
->addListener($event_class, $listener);
$stage = $this->createStage(); $stage = $this->createStage();
$stage->create(); $stage->create();
...@@ -220,8 +219,7 @@ class StageTest extends PackageManagerKernelTestBase { ...@@ -220,8 +219,7 @@ class StageTest extends PackageManagerKernelTestBase {
$this->assertStringContainsString('Modules cannot be uninstalled while Package Manager is applying staged changes to the active code base.', $e->getMessage()); $this->assertStringContainsString('Modules cannot be uninstalled while Package Manager is applying staged changes to the active code base.', $e->getMessage());
} }
}; };
$this->container->get('event_dispatcher') $this->addEventTestListener($listener);
->addListener(PreApplyEvent::class, $listener);
$stage = $this->createStage(); $stage = $this->createStage();
$stage->create(); $stage->create();
...@@ -492,12 +490,9 @@ class StageTest extends PackageManagerKernelTestBase { ...@@ -492,12 +490,9 @@ class StageTest extends PackageManagerKernelTestBase {
* Tests that ignored paths are collected before create and apply. * Tests that ignored paths are collected before create and apply.
*/ */
public function testCollectIgnoredPaths(): void { public function testCollectIgnoredPaths(): void {
/** @var \Symfony\Component\EventDispatcher\EventDispatcherInterface $event_dispatcher */ $this->addEventTestListener(function (CollectIgnoredPathsEvent $event): void {
$event_dispatcher = $this->container->get('event_dispatcher');
$event_dispatcher->addListener(CollectIgnoredPathsEvent::class, function (CollectIgnoredPathsEvent $event): void {
$event->add(['ignore/me']); $event->add(['ignore/me']);
}); }, CollectIgnoredPathsEvent::class);
// On pre-create and pre-apply, ensure that the ignored path is known to // On pre-create and pre-apply, ensure that the ignored path is known to
// the event. // the event.
...@@ -507,8 +502,8 @@ class StageTest extends PackageManagerKernelTestBase { ...@@ -507,8 +502,8 @@ class StageTest extends PackageManagerKernelTestBase {
// Use this to confirm that this listener was actually called. // Use this to confirm that this listener was actually called.
$asserted = TRUE; $asserted = TRUE;
}; };
$event_dispatcher->addListener(PreCreateEvent::class, $assert_ignored); $this->addEventTestListener($assert_ignored, PreCreateEvent::class);
$event_dispatcher->addListener(PreApplyEvent::class, $assert_ignored); $this->addEventTestListener($assert_ignored);
$stage = $this->createStage(); $stage = $this->createStage();
$stage->create(); $stage->create();
......
...@@ -21,19 +21,16 @@ class StatusCheckTraitTest extends PackageManagerKernelTestBase { ...@@ -21,19 +21,16 @@ class StatusCheckTraitTest extends PackageManagerKernelTestBase {
* Tests that StatusCheckTrait will collect ignored paths. * Tests that StatusCheckTrait will collect ignored paths.
*/ */
public function testIgnoredPathsCollected(): void { public function testIgnoredPathsCollected(): void {
/** @var \Symfony\Component\EventDispatcher\EventDispatcherInterface $event_dispatcher */ $this->addEventTestListener(function (CollectIgnoredPathsEvent $event): void {
$event_dispatcher = $this->container->get('event_dispatcher');
$event_dispatcher->addListener(CollectIgnoredPathsEvent::class, function (CollectIgnoredPathsEvent $event): void {
$event->add(['/junk/drawer']); $event->add(['/junk/drawer']);
}); }, CollectIgnoredPathsEvent::class);
$status_check_called = FALSE; $status_check_called = FALSE;
$event_dispatcher->addListener(StatusCheckEvent::class, function (StatusCheckEvent $event) use (&$status_check_called): void { $this->addEventTestListener(function (StatusCheckEvent $event) use (&$status_check_called): void {
$this->assertContains('/junk/drawer', $event->getExcludedPaths()); $this->assertContains('/junk/drawer', $event->getExcludedPaths());
$status_check_called = TRUE; $status_check_called = TRUE;
}); }, StatusCheckEvent::class);
$this->runStatusCheck($this->createStage(), $event_dispatcher); $this->runStatusCheck($this->createStage(), $this->container->get('event_dispatcher'));
$this->assertTrue($status_check_called); $this->assertTrue($status_check_called);
} }
......
...@@ -83,8 +83,7 @@ class SymlinkValidatorTest extends PackageManagerKernelTestBase { ...@@ -83,8 +83,7 @@ class SymlinkValidatorTest extends PackageManagerKernelTestBase {
$add_ignored_path = function (CollectIgnoredPathsEvent $event): void { $add_ignored_path = function (CollectIgnoredPathsEvent $event): void {
$event->add(['ignore/me']); $event->add(['ignore/me']);
}; };
$this->container->get('event_dispatcher') $this->addEventTestListener($add_ignored_path, CollectIgnoredPathsEvent::class);
->addListener(CollectIgnoredPathsEvent::class, $add_ignored_path);
$arguments = [ $arguments = [
Argument::type(PathInterface::class), Argument::type(PathInterface::class),
...@@ -107,8 +106,7 @@ class SymlinkValidatorTest extends PackageManagerKernelTestBase { ...@@ -107,8 +106,7 @@ class SymlinkValidatorTest extends PackageManagerKernelTestBase {
$this->enableModules(['help']); $this->enableModules(['help']);
// Enabling Help rebuilt the container, so we need to re-add our event // Enabling Help rebuilt the container, so we need to re-add our event
// listener. // listener.
$this->container->get('event_dispatcher') $this->addEventTestListener($add_ignored_path, CollectIgnoredPathsEvent::class);
->addListener(CollectIgnoredPathsEvent::class, $add_ignored_path);
$url = Url::fromRoute('help.page', ['name' => 'package_manager']) $url = Url::fromRoute('help.page', ['name' => 'package_manager'])
->setOption('fragment', 'package-manager-faq-symlinks-found') ->setOption('fragment', 'package-manager-faq-symlinks-found')
......
...@@ -104,8 +104,7 @@ class WritableFileSystemValidatorTest extends PackageManagerKernelTestBase { ...@@ -104,8 +104,7 @@ class WritableFileSystemValidatorTest extends PackageManagerKernelTestBase {
* @dataProvider providerWritable * @dataProvider providerWritable
*/ */
public function testWritableDuringPreApply(int $root_permissions, int $vendor_permissions, array $expected_results): void { public function testWritableDuringPreApply(int $root_permissions, int $vendor_permissions, array $expected_results): void {
$this->container->get('event_dispatcher')->addListener( $this->addEventTestListener(
PreApplyEvent::class,
function () use ($root_permissions, $vendor_permissions): void { function () use ($root_permissions, $vendor_permissions): void {
$path_locator = $this->container->get('package_manager.path_locator'); $path_locator = $this->container->get('package_manager.path_locator');
...@@ -117,7 +116,6 @@ class WritableFileSystemValidatorTest extends PackageManagerKernelTestBase { ...@@ -117,7 +116,6 @@ class WritableFileSystemValidatorTest extends PackageManagerKernelTestBase {
// During pre-apply we don't care whether the staging root is writable. // During pre-apply we don't care whether the staging root is writable.
$this->assertTrue(chmod($path_locator->getStagingRoot(), 0444)); $this->assertTrue(chmod($path_locator->getStagingRoot(), 0444));
}, },
PHP_INT_MAX
); );
$this->assertResults($expected_results, PreApplyEvent::class); $this->assertResults($expected_results, PreApplyEvent::class);
......
...@@ -360,7 +360,7 @@ class CronUpdaterTest extends AutomaticUpdatesKernelTestBase { ...@@ -360,7 +360,7 @@ class CronUpdaterTest extends AutomaticUpdatesKernelTestBase {
$this->assertSame($event->getStage()->getStageDirectory(), $cron_stage_dir); $this->assertSame($event->getStage()->getStageDirectory(), $cron_stage_dir);
$this->assertDirectoryExists($cron_stage_dir); $this->assertDirectoryExists($cron_stage_dir);
}; };
$this->container->get('event_dispatcher')->addListener(PostRequireEvent::class, $listener, PHP_INT_MAX); $this->addEventTestListener($listener, PostRequireEvent::class);
$this->container->get('cron')->run(); $this->container->get('cron')->run();
$this->assertIsString($cron_stage_dir); $this->assertIsString($cron_stage_dir);
...@@ -385,7 +385,7 @@ class CronUpdaterTest extends AutomaticUpdatesKernelTestBase { ...@@ -385,7 +385,7 @@ class CronUpdaterTest extends AutomaticUpdatesKernelTestBase {
// Add a PreApplyEvent event listener so we can attempt to run cron when // Add a PreApplyEvent event listener so we can attempt to run cron when
// another stage is applying. // another stage is applying.
$this->container->get('event_dispatcher')->addListener(PreApplyEvent::class, function (PreApplyEvent $event) use ($stop_error) { $this->addEventTestListener(function (PreApplyEvent $event) use ($stop_error) {
// Ensure the stage that is applying the operation is not the cron // Ensure the stage that is applying the operation is not the cron
// updater. // updater.
$this->assertInstanceOf(TestStage::class, $event->getStage()); $this->assertInstanceOf(TestStage::class, $event->getStage());
...@@ -393,7 +393,7 @@ class CronUpdaterTest extends AutomaticUpdatesKernelTestBase { ...@@ -393,7 +393,7 @@ class CronUpdaterTest extends AutomaticUpdatesKernelTestBase {
// We do not actually want to apply this operation it was just invoked to // We do not actually want to apply this operation it was just invoked to
// allow cron to be attempted. // allow cron to be attempted.
$event->addError([$stop_error]); $event->addError([$stop_error]);
}, PHP_INT_MAX); });
try { try {
$stage->apply(); $stage->apply();
......
...@@ -28,8 +28,7 @@ class ReadinessCheckTest extends AutomaticUpdatesKernelTestBase { ...@@ -28,8 +28,7 @@ class ReadinessCheckTest extends AutomaticUpdatesKernelTestBase {
protected function setUp(): void { protected function setUp(): void {
parent::setUp(); parent::setUp();
$this->container->get('event_dispatcher') $this->addEventTestListener(function () {}, ReadinessCheckEvent::class);
->addListener(ReadinessCheckEvent::class, function () {});
} }
/** /**
......
...@@ -9,7 +9,6 @@ use Drupal\automatic_updates\Validator\CronServerValidator; ...@@ -9,7 +9,6 @@ use Drupal\automatic_updates\Validator\CronServerValidator;
use Drupal\Core\Logger\RfcLogLevel; use Drupal\Core\Logger\RfcLogLevel;
use Drupal\Core\Url; use Drupal\Core\Url;
use Drupal\fixture_manipulator\StageFixtureManipulator; use Drupal\fixture_manipulator\StageFixtureManipulator;
use Drupal\package_manager\Event\PreApplyEvent;
use Drupal\package_manager\Exception\StageValidationException; use Drupal\package_manager\Exception\StageValidationException;
use Drupal\package_manager\ValidationResult; use Drupal\package_manager\ValidationResult;
use Drupal\Tests\automatic_updates\Kernel\AutomaticUpdatesKernelTestBase; use Drupal\Tests\automatic_updates\Kernel\AutomaticUpdatesKernelTestBase;
...@@ -173,8 +172,7 @@ class CronServerValidatorTest extends AutomaticUpdatesKernelTestBase { ...@@ -173,8 +172,7 @@ class CronServerValidatorTest extends AutomaticUpdatesKernelTestBase {
// Add a listener to change the $server_api and $alternate_port settings // Add a listener to change the $server_api and $alternate_port settings
// during PreApplyEvent. We set $cron_mode above because this determines // during PreApplyEvent. We set $cron_mode above because this determines
// whether updates will actually be run in cron. // whether updates will actually be run in cron.
$this->container->get('event_dispatcher')->addListener( $this->addEventTestListener(
PreApplyEvent::class,
function () use ($alternate_port, $server_api): void { function () use ($alternate_port, $server_api): void {
$property = new \ReflectionProperty(CronServerValidator::class, 'serverApi'); $property = new \ReflectionProperty(CronServerValidator::class, 'serverApi');
$property->setAccessible(TRUE); $property->setAccessible(TRUE);
...@@ -182,8 +180,7 @@ class CronServerValidatorTest extends AutomaticUpdatesKernelTestBase { ...@@ -182,8 +180,7 @@ class CronServerValidatorTest extends AutomaticUpdatesKernelTestBase {
$this->config('automatic_updates.settings') $this->config('automatic_updates.settings')
->set('cron_port', $alternate_port ? 2501 : 0) ->set('cron_port', $alternate_port ? 2501 : 0)
->save(); ->save();
}, }
PHP_INT_MAX
); );
// If errors were expected, cron should not have run. // If errors were expected, cron should not have run.
$this->container->get('cron')->run(); $this->container->get('cron')->run();
......
...@@ -119,8 +119,8 @@ class StagedDatabaseUpdateValidatorTest extends AutomaticUpdatesKernelTestBase { ...@@ -119,8 +119,8 @@ class StagedDatabaseUpdateValidatorTest extends AutomaticUpdatesKernelTestBase {
unlink("$stage_dir/$path/$name.$suffix"); unlink("$stage_dir/$path/$name.$suffix");
} }
}; };
$this->container->get('event_dispatcher') $this->addEventTestListener($listener);
->addListener(PreApplyEvent::class, $listener, PHP_INT_MAX);
$this->container->get('cron')->run(); $this->container->get('cron')->run();
$expected_message = "The update cannot proceed because possible database updates have been detected in the following extensions.\nSystem\nStark\n"; $expected_message = "The update cannot proceed because possible database updates have been detected in the following extensions.\nSystem\nStark\n";
$this->assertTrue($this->logger->hasRecord($expected_message, (string) RfcLogLevel::ERROR)); $this->assertTrue($this->logger->hasRecord($expected_message, (string) RfcLogLevel::ERROR));
...@@ -144,8 +144,8 @@ class StagedDatabaseUpdateValidatorTest extends AutomaticUpdatesKernelTestBase { ...@@ -144,8 +144,8 @@ class StagedDatabaseUpdateValidatorTest extends AutomaticUpdatesKernelTestBase {
file_put_contents("$stage_dir/$path/$name.$suffix", $this->randomString()); file_put_contents("$stage_dir/$path/$name.$suffix", $this->randomString());
} }
}; };
$this->container->get('event_dispatcher') $this->addEventTestListener($listener);
->addListener(PreApplyEvent::class, $listener, PHP_INT_MAX);
$this->container->get('cron')->run(); $this->container->get('cron')->run();
$expected_message = "The update cannot proceed because possible database updates have been detected in the following extensions.\nSystem\nStark\n"; $expected_message = "The update cannot proceed because possible database updates have been detected in the following extensions.\nSystem\nStark\n";
$this->assertTrue($this->logger->hasRecord($expected_message, (string) RfcLogLevel::ERROR)); $this->assertTrue($this->logger->hasRecord($expected_message, (string) RfcLogLevel::ERROR));
...@@ -171,8 +171,7 @@ class StagedDatabaseUpdateValidatorTest extends AutomaticUpdatesKernelTestBase { ...@@ -171,8 +171,7 @@ class StagedDatabaseUpdateValidatorTest extends AutomaticUpdatesKernelTestBase {
unlink("$active_dir/$path/$name.$suffix"); unlink("$active_dir/$path/$name.$suffix");
} }
}; };
$this->container->get('event_dispatcher') $this->addEventTestListener($listener);
->addListener(PreApplyEvent::class, $listener, PHP_INT_MAX);
$this->container->get('cron')->run(); $this->container->get('cron')->run();
$expected_message = "The update cannot proceed because possible database updates have been detected in the following extensions.\nSystem\nStark\n"; $expected_message = "The update cannot proceed because possible database updates have been detected in the following extensions.\nSystem\nStark\n";
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment