From b1f3a911ff4406540ad3212566e6d4bb10e0339f Mon Sep 17 00:00:00 2001 From: everzet Date: Sun, 25 Dec 2016 13:45:19 +0000 Subject: [PATCH 001/567] Bump dev version of Application --- src/Behat/Behat/ApplicationFactory.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Behat/Behat/ApplicationFactory.php b/src/Behat/Behat/ApplicationFactory.php index 6309c7a52..5763f3d99 100644 --- a/src/Behat/Behat/ApplicationFactory.php +++ b/src/Behat/Behat/ApplicationFactory.php @@ -46,7 +46,7 @@ */ final class ApplicationFactory extends BaseFactory { - const VERSION = '3.2-dev'; + const VERSION = '3.3-dev'; /** * {@inheritdoc} From a998d45dca71340d5dd79b60fe1b6f7c70ff08fe Mon Sep 17 00:00:00 2001 From: Konstantin Kudryashov Date: Sun, 25 Dec 2016 13:51:49 +0000 Subject: [PATCH 002/567] Update CHANGELOG.md --- CHANGELOG.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 19ae19f88..422264e18 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,9 @@ and this project adheres to [Semantic Versioning](http://semver.org/). * [#973](https://github.com/Behat/Behat/pull/974): Added helper containers * [#973](https://github.com/Behat/Behat/pull/974): Added `SuiteScopedResolverFactory` extension point +### Removed + * Removed php 5.3 from the Travis build matrix. You can consider it official end of support. 5.4 and 5.5 will follow shortly. + ## [3.2.3] - 2016-12-25 ### Fixed * [#971](https://github.com/Behat/Behat/pull/971): Added support for suite names with hyphens From e3b3423852c98fd85460b52220f14c13f17cd1a2 Mon Sep 17 00:00:00 2001 From: Martin Heigermoser Date: Mon, 12 Dec 2016 11:11:33 +0100 Subject: [PATCH 003/567] add junit time attribute for scenarios and features --- .../JUnit/JUnitDurationListener.php | 98 +++++++++++++++++++ .../Printer/JUnit/JUnitFeaturePrinter.php | 10 +- .../Printer/JUnit/JUnitScenarioPrinter.php | 7 +- .../Formatter/JUnitFormatterFactory.php | 8 ++ 4 files changed, 120 insertions(+), 3 deletions(-) create mode 100644 src/Behat/Behat/Output/Node/EventListener/JUnit/JUnitDurationListener.php diff --git a/src/Behat/Behat/Output/Node/EventListener/JUnit/JUnitDurationListener.php b/src/Behat/Behat/Output/Node/EventListener/JUnit/JUnitDurationListener.php new file mode 100644 index 000000000..f5cb3a59b --- /dev/null +++ b/src/Behat/Behat/Output/Node/EventListener/JUnit/JUnitDurationListener.php @@ -0,0 +1,98 @@ +captureBeforeScenarioEvent($event); + } + + if ($event instanceof BeforeFeatureTested) { + $this->captureBeforeFeatureTested($event); + } + + if ($event instanceof AfterScenarioTested) { + $this->captureAfterScenarioEvent($event); + } + + if ($event instanceof AfterFeatureTested) { + $this->captureAfterFeatureEvent($event); + } + } + + public function getDuration(ScenarioLikeInterface $scenario) + { + $key = $this->getHash($scenario); + return array_key_exists($key, $this->resultStore) ? $this->resultStore[$key] : ''; + } + + public function getFeatureDuration(FeatureNode $feature) + { + $key = $this->getHash($feature); + return array_key_exists($key, $this->featureResultStore) ? $this->featureResultStore[$key] : ''; + } + + private function captureBeforeFeatureTested(BeforeFeatureTested $event) + { + $this->featureTimerStore[$this->getHash($event->getFeature())] = $this->startTimer(); + } + + private function captureBeforeScenarioEvent(BeforeScenarioTested $event) + { + $this->scenarioTimerStore[$this->getHash($event->getScenario())] = $this->startTimer(); + } + + private function captureAfterScenarioEvent(AfterScenarioTested $event) + { + $key = $this->getHash($event->getScenario()); + $timer = $this->scenarioTimerStore[$key]; + if ($timer instanceof Timer) { + $timer->stop(); + $this->resultStore[$key] = $timer->getSeconds(); + } + } + + private function captureAfterFeatureEvent(AfterFeatureTested $event) + { + $key = $this->getHash($event->getFeature()); + $timer = $this->featureTimerStore[$key]; + if ($timer instanceof Timer) { + $timer->stop(); + $this->featureResultStore[$key] = $timer->getSeconds(); + } + } + + private function getHash(KeywordNodeInterface $node) + { + return spl_object_hash($node); + } + + /** @return Timer */ + private function startTimer() + { + $timer = new Timer(); + $timer->start(); + + return $timer; + } +} diff --git a/src/Behat/Behat/Output/Node/Printer/JUnit/JUnitFeaturePrinter.php b/src/Behat/Behat/Output/Node/Printer/JUnit/JUnitFeaturePrinter.php index 6b6e87184..7b3277a0d 100644 --- a/src/Behat/Behat/Output/Node/Printer/JUnit/JUnitFeaturePrinter.php +++ b/src/Behat/Behat/Output/Node/Printer/JUnit/JUnitFeaturePrinter.php @@ -10,6 +10,7 @@ namespace Behat\Behat\Output\Node\Printer\JUnit; +use Behat\Behat\Output\Node\EventListener\JUnit\JUnitDurationListener; use Behat\Behat\Output\Node\Printer\FeaturePrinter; use Behat\Behat\Output\Statistics\PhaseStatistics; use Behat\Behat\Tester\Result\StepResult; @@ -30,9 +31,15 @@ final class JUnitFeaturePrinter implements FeaturePrinter */ private $statistics; - public function __construct(PhaseStatistics $statistics) + /** + * @var JUnitDurationListener + */ + private $durationListener; + + public function __construct(PhaseStatistics $statistics, JUnitDurationListener $durationListener) { $this->statistics = $statistics; + $this->durationListener = $durationListener; } /** @@ -57,6 +64,7 @@ public function printHeader(Formatter $formatter, FeatureNode $feature) 'skipped' => $stats[TestResult::SKIPPED], 'failures' => $stats[TestResult::FAILED], 'errors' => $stats[TestResult::PENDING] + $stats[StepResult::UNDEFINED], + 'time' => $this->durationListener->getFeatureDuration($feature) )); $this->statistics->reset(); } diff --git a/src/Behat/Behat/Output/Node/Printer/JUnit/JUnitScenarioPrinter.php b/src/Behat/Behat/Output/Node/Printer/JUnit/JUnitScenarioPrinter.php index cf61eaab9..27eb86de7 100644 --- a/src/Behat/Behat/Output/Node/Printer/JUnit/JUnitScenarioPrinter.php +++ b/src/Behat/Behat/Output/Node/Printer/JUnit/JUnitScenarioPrinter.php @@ -11,6 +11,7 @@ namespace Behat\Behat\Output\Node\Printer\JUnit; use Behat\Behat\Output\Node\EventListener\JUnit\JUnitOutlineStoreListener; +use Behat\Behat\Output\Node\EventListener\JUnit\JUnitDurationListener; use Behat\Behat\Output\Node\Printer\Helper\ResultToStringConverter; use Behat\Gherkin\Node\ExampleNode; use Behat\Gherkin\Node\FeatureNode; @@ -47,10 +48,11 @@ final class JUnitScenarioPrinter */ private $outlineStepCount; - public function __construct(ResultToStringConverter $resultConverter, JUnitOutlineStoreListener $outlineListener) + public function __construct(ResultToStringConverter $resultConverter, JUnitOutlineStoreListener $outlineListener, JUnitDurationListener $durationListener) { $this->resultConverter = $resultConverter; $this->outlineStoreListener = $outlineListener; + $this->durationListener = $durationListener; } /** @@ -71,7 +73,8 @@ public function printOpenTag(Formatter $formatter, FeatureNode $feature, Scenari $outputPrinter->addTestcase(array( 'name' => $name, - 'status' => $this->resultConverter->convertResultToString($result) + 'status' => $this->resultConverter->convertResultToString($result), + 'time' => $this->durationListener->getDuration($scenario) )); } diff --git a/src/Behat/Behat/Output/ServiceContainer/Formatter/JUnitFormatterFactory.php b/src/Behat/Behat/Output/ServiceContainer/Formatter/JUnitFormatterFactory.php index a9d289516..4212fbb01 100644 --- a/src/Behat/Behat/Output/ServiceContainer/Formatter/JUnitFormatterFactory.php +++ b/src/Behat/Behat/Output/ServiceContainer/Formatter/JUnitFormatterFactory.php @@ -73,12 +73,14 @@ private function loadCorePrinters(ContainerBuilder $container) $definition = new Definition('Behat\Behat\Output\Node\Printer\JUnit\JUnitFeaturePrinter', array( new Reference('output.junit.statistics'), + new Reference('output.node.listener.junit.duration') )); $container->setDefinition('output.node.printer.junit.feature', $definition); $definition = new Definition('Behat\Behat\Output\Node\Printer\JUnit\JUnitScenarioPrinter', array( new Reference(self::RESULT_TO_STRING_CONVERTER_ID), new Reference('output.node.listener.junit.outline'), + new Reference('output.node.listener.junit.duration') )); $container->setDefinition('output.node.printer.junit.scenario', $definition); @@ -109,9 +111,15 @@ private function loadRootNodeListener(ContainerBuilder $container) ); $container->setDefinition('output.node.listener.junit.outline', $definition); + $definition = new Definition( + 'Behat\Behat\Output\Node\EventListener\JUnit\JUnitDurationListener' + ); + + $container->setDefinition('output.node.listener.junit.duration', $definition); $definition = new Definition('Behat\Testwork\Output\Node\EventListener\ChainEventListener', array( array( + new Reference('output.node.listener.junit.duration'), new Reference('output.node.listener.junit.outline'), new Definition('Behat\Behat\Output\Node\EventListener\JUnit\JUnitFeatureElementListener', array( new Reference('output.node.printer.junit.feature'), From 72e178f1f1bb5d1cf8314c21cd89eaa6cb9fc4b1 Mon Sep 17 00:00:00 2001 From: Martin Heigermoser Date: Thu, 5 Jan 2017 11:18:17 +0100 Subject: [PATCH 004/567] ignore time attribute in junit xml --- features/bootstrap/FeatureContext.php | 4 ++ features/junit_format.feature | 58 +++++++++++++-------------- 2 files changed, 33 insertions(+), 29 deletions(-) diff --git a/features/bootstrap/FeatureContext.php b/features/bootstrap/FeatureContext.php index bc476cad3..0b9fdec15 100644 --- a/features/bootstrap/FeatureContext.php +++ b/features/bootstrap/FeatureContext.php @@ -9,7 +9,9 @@ */ use Behat\Behat\Context\Context; +use Behat\Behat\Output\Node\EventListener\JUnit\JUnitDurationListener; use Behat\Gherkin\Node\PyStringNode; +use Prophecy\Argument; use Symfony\Component\Process\InputStream; use Symfony\Component\Process\PhpExecutableFinder; use Symfony\Component\Process\Process; @@ -240,6 +242,8 @@ public function fileXmlShouldBeLike($path, PyStringNode $text) $fileContent = trim(file_get_contents($path)); + $fileContent = preg_replace('/time="(.*)"/', 'time="-IGNORE-VALUE-"', $fileContent); + $dom = new DOMDocument(); $dom->loadXML($text); $dom->formatOutput = true; diff --git a/features/junit_format.feature b/features/junit_format.feature index f9e4bfd88..a9cb00f11 100644 --- a/features/junit_format.feature +++ b/features/junit_format.feature @@ -104,25 +104,25 @@ """ - - + + - + - + - + - - + + - - + + """ @@ -191,11 +191,11 @@ """ - - + + - - + + """ @@ -266,9 +266,9 @@ """ - - - + + + """ @@ -386,8 +386,8 @@ """ - - + + """ @@ -396,8 +396,8 @@ """ - - + + @@ -455,9 +455,9 @@ """ - - - + + + """ @@ -517,8 +517,8 @@ """ - - + + @@ -655,8 +655,8 @@ """ - - + + @@ -711,8 +711,8 @@ """ - - + + From f1212fc6df0fbcc4d94458ab4130a7b7641fc1a4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Baptiste=20Clavi=C3=A9?= Date: Fri, 27 Jan 2017 12:12:12 +0100 Subject: [PATCH 005/567] Prepare a pass for typehinted arguments this is done in order that the next prepare call (prepareNumberedArguments) have the right indexes for its arguments. E.g, if for 5 arguments, we had the 2 typehinted `[1 => Foo, 3 => Bar]`, before it would try to replace those with `[0 => 'foo', 1 => 'bar', 2 => 'baz']`, resulting in `[0 => 'foo', 1 => Foo, 2 => 'baz', 3 => Bar]` which is wrong, as we would expect it to be `[0 => 'foo', 1 => Foo, 2 => 'bar', 3 => Bar, 4 => 'baz']` To achieve that, we need to indicate that the typehinted args are defined... Thus they are indeed skipped when trying to match numbered args. --- .../Argument/MixedArgumentOrganiser.php | 25 ++++++++++++++++++- 1 file changed, 24 insertions(+), 1 deletion(-) diff --git a/src/Behat/Testwork/Argument/MixedArgumentOrganiser.php b/src/Behat/Testwork/Argument/MixedArgumentOrganiser.php index 88ace2243..7a73ee86e 100644 --- a/src/Behat/Testwork/Argument/MixedArgumentOrganiser.php +++ b/src/Behat/Testwork/Argument/MixedArgumentOrganiser.php @@ -58,7 +58,7 @@ private function prepareArguments(array $parameters, array $arguments) $arguments = $this->prepareNamedArguments($parameters, $named) + - $typehinted + + $this->prepareTypehintedArguments($typehinted) + $this->prepareNumberedArguments($parameters, $numbered) + $this->prepareDefaultArguments($parameters); @@ -173,6 +173,29 @@ private function prepareNamedArguments(array $parameters, array $namedArguments) return $arguments; } + /** + * Captures argument value based on their respective typehints. + * + * Note ; as it is keeping in mind that $typeHintedArgument already has the + * right keys matching the correct parameter, it just iterates over this + * array in order to mark each arguments as "defined". + * + * @see https://github.com/Behat/Behat/pull/993#issuecomment-275669510 + * + * @param mixed[] $typehintedArguments + * + * @return mixed[] + */ + private function prepareTypehintedArguments(array $typehintedArguments) + { + foreach (array_keys($typehintedArguments) as $num) { + $this->markArgumentDefined($num); + } + + return $typehintedArguments; + } + + /** * Captures argument values for undefined arguments based on their respective numbers. * From c4d727834b0010b4a6d2fa3bc74588338a8a9cad Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Baptiste=20Clavi=C3=A9?= Date: Fri, 27 Jan 2017 12:18:32 +0100 Subject: [PATCH 006/567] Update CHANGELOG --- CHANGELOG.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 422264e18..9ddd3b382 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,8 @@ The format is based on [Keep a Changelog](http://keepachangelog.com/) and this project adheres to [Semantic Versioning](http://semver.org/). ## [Unreleased] +### Fixed + * [#993](https://github.com/Behat/Behat/pull/993) Fix mixed arguments organizer not marking typehinted arguments as "defined" ## [3.3.0] - 2016-12-25 ### Added From 0e832dab286d16b4b01b89ddfdaed87887bff92d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Baptiste=20Clavi=C3=A9?= Date: Sun, 29 Jan 2017 23:26:07 +0100 Subject: [PATCH 007/567] Add feature test for prepare arguments fix --- features/helper_containers.feature | 41 ++++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) diff --git a/features/helper_containers.feature b/features/helper_containers.feature index 9235aa744..f0bbdde62 100644 --- a/features/helper_containers.feature +++ b/features/helper_containers.feature @@ -305,3 +305,44 @@ Feature: Per-suite helper containers """ When I run "behat --no-colors -f progress features/container.feature" Then it should pass + + Scenario: Mix of typehinted arguments and numbered arguments (fix #991) + Given a file named "behat.yml" with: + """ + default: + suites: + default: + contexts: + - FirstContext: + - foo + - "@typehinted_service" + - bar + + services: + typehinted_service: + class: stdClass + """ + And a file named "features/container_args.feature" with: + """ + Feature: + Scenario: + Given foo + """ + And a file named "features/bootstrap/FirstContext.php" with: + """ + Date: Fri, 27 Jan 2017 10:21:22 +0100 Subject: [PATCH 008/567] Do not treat first argument as numbered argument if typehinted --- src/Behat/Testwork/Argument/MixedArgumentOrganiser.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Behat/Testwork/Argument/MixedArgumentOrganiser.php b/src/Behat/Testwork/Argument/MixedArgumentOrganiser.php index 7a73ee86e..2b3251496 100644 --- a/src/Behat/Testwork/Argument/MixedArgumentOrganiser.php +++ b/src/Behat/Testwork/Argument/MixedArgumentOrganiser.php @@ -88,7 +88,7 @@ function (ReflectionParameter $parameter) { foreach ($arguments as $key => $val) { if ($this->isStringKeyAndExistsInParameters($key, $parameterNames)) { $namedArguments[$key] = $val; - } elseif ($num = $this->getParameterNumberWithTypehintingValue($parameters, $val)) { + } elseif (null !== ($num = $this->getParameterNumberWithTypehintingValue($parameters, $val))) { $typehintedArguments[$num] = $val; } else { $numberedArguments[] = $val; From a2a5fa8ddb0d21dff501ba32fccd3853f9ec981c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Baptiste=20Clavi=C3=A9?= Date: Fri, 27 Jan 2017 12:11:17 +0100 Subject: [PATCH 009/567] Update CHANGELOG --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 9ddd3b382..5cc6a1206 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,7 @@ and this project adheres to [Semantic Versioning](http://semver.org/). ## [Unreleased] ### Fixed * [#993](https://github.com/Behat/Behat/pull/993) Fix mixed arguments organizer not marking typehinted arguments as "defined" + * [#992](https://github.com/Behat/Behat/pull/993) Do not misinterpret first argument as a numbered argument if it is in fact typehinted ## [3.3.0] - 2016-12-25 ### Added From 41681cf92884e8ff61a57cfd66151054d94d7542 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Baptiste=20Clavi=C3=A9?= Date: Wed, 1 Feb 2017 13:32:02 +0100 Subject: [PATCH 010/567] Alter scenario for #993 --- features/helper_containers.feature | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/features/helper_containers.feature b/features/helper_containers.feature index f0bbdde62..643b75609 100644 --- a/features/helper_containers.feature +++ b/features/helper_containers.feature @@ -314,7 +314,6 @@ Feature: Per-suite helper containers default: contexts: - FirstContext: - - foo - "@typehinted_service" - bar @@ -333,10 +332,7 @@ Feature: Per-suite helper containers Date: Wed, 15 Feb 2017 16:53:40 +0200 Subject: [PATCH 011/567] Allow to use `*.yaml` configuration files This PR adds the ability to use `*.yaml` extension for the configuration, since this extension is considered official. To keep backward compatibility but avoid extra file operation, checking with `is_file` was replaced with `glob`. --- src/Behat/Behat/ApplicationFactory.php | 13 +++---------- 1 file changed, 3 insertions(+), 10 deletions(-) diff --git a/src/Behat/Behat/ApplicationFactory.php b/src/Behat/Behat/ApplicationFactory.php index 5763f3d99..a1ba8917a 100644 --- a/src/Behat/Behat/ApplicationFactory.php +++ b/src/Behat/Behat/ApplicationFactory.php @@ -110,16 +110,9 @@ protected function getEnvironmentVariableName() */ protected function getConfigPath() { - $cwd = rtrim(getcwd(), DIRECTORY_SEPARATOR); - $paths = array_filter( - array( - $cwd . DIRECTORY_SEPARATOR . 'behat.yml', - $cwd . DIRECTORY_SEPARATOR . 'behat.yml.dist', - $cwd . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'behat.yml', - $cwd . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'behat.yml.dist', - ), - 'is_file' - ); + $cwd = rtrim(getcwd(), DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR; + $configDir = 'config' . DIRECTORY_SEPARATOR; + $paths = glob("{$cwd}{,{$configDir}}behat.y{a,}ml{,.dist}", GLOB_BRACE); if (count($paths)) { return current($paths); From c32bbdfc7bc79effe674ad2d842b38aa907ee827 Mon Sep 17 00:00:00 2001 From: Veaceslav Medvedev Date: Wed, 15 Feb 2017 18:07:46 +0200 Subject: [PATCH 012/567] Revert usage of is_file instead of glob --- src/Behat/Behat/ApplicationFactory.php | 21 ++++++++++++++++----- 1 file changed, 16 insertions(+), 5 deletions(-) diff --git a/src/Behat/Behat/ApplicationFactory.php b/src/Behat/Behat/ApplicationFactory.php index a1ba8917a..ced51d911 100644 --- a/src/Behat/Behat/ApplicationFactory.php +++ b/src/Behat/Behat/ApplicationFactory.php @@ -111,11 +111,22 @@ protected function getEnvironmentVariableName() protected function getConfigPath() { $cwd = rtrim(getcwd(), DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR; - $configDir = 'config' . DIRECTORY_SEPARATOR; - $paths = glob("{$cwd}{,{$configDir}}behat.y{a,}ml{,.dist}", GLOB_BRACE); - - if (count($paths)) { - return current($paths); + $configDir = $cwd . 'config' . DIRECTORY_SEPARATOR; + $paths = array( + $cwd . 'behat.yaml', + $cwd . 'behat.yml', + $cwd . 'behat.yaml.dist', + $cwd . 'behat.yml.dist', + $configDir . 'behat.yaml', + $configDir . 'behat.yml', + $configDir . 'behat.yaml.dist', + $configDir . 'behat.yml.dist', + ); + + foreach ($paths as $path) { + if (is_file($path)) { + return $path; + } } return null; From 9e16d00f4ef5af40defac5ef42e5f3c2af9e2360 Mon Sep 17 00:00:00 2001 From: Veaceslav Medvedev Date: Wed, 15 Feb 2017 19:11:26 +0200 Subject: [PATCH 013/567] Add scenarios to test config files order --- features/bootstrap/FeatureContext.php | 60 ++++++++++++++++++++++++++- features/config.feature | 33 +++++++++++++++ 2 files changed, 92 insertions(+), 1 deletion(-) diff --git a/features/bootstrap/FeatureContext.php b/features/bootstrap/FeatureContext.php index bc476cad3..8ee8bfacf 100644 --- a/features/bootstrap/FeatureContext.php +++ b/features/bootstrap/FeatureContext.php @@ -10,7 +10,6 @@ use Behat\Behat\Context\Context; use Behat\Gherkin\Node\PyStringNode; -use Symfony\Component\Process\InputStream; use Symfony\Component\Process\PhpExecutableFinder; use Symfony\Component\Process\Process; @@ -88,6 +87,54 @@ public function aFileNamedWith($filename, PyStringNode $content) $this->createFile($this->workingDir . '/' . $filename, $content); } + /** + * Creates a empty file with specified name in current workdir. + * + * @Given /^(?:there is )?a file named "([^"]*)"$/ + * + * @param string $filename name of the file (relative path) + */ + public function aFileNamed($filename) + { + $this->createFile($this->workingDir . '/' . $filename, ''); + } + + /** + * Creates a noop feature context in current workdir. + * + * @Given /^(?:there is )?a some feature context$/ + */ + public function aNoopFeatureContext() + { + $filename = 'features/bootstrap/FeatureContext.php'; + $content = <<<'EOL' +createFile($this->workingDir . '/' . $filename, $content); + } + + /** + * Creates a noop feature in current workdir. + * + * @Given /^(?:there is )?a some feature scenarios/ + */ + public function aNoopFeature() + { + $filename = 'features/bootstrap/FeatureContext.php'; + $content = <<<'EOL' +Feature: + Scenario: + When this scenario executes +EOL; + $this->createFile($this->workingDir . '/' . $filename, $content); + } + /** * Moves user to the specified path. * @@ -176,6 +223,17 @@ public function iRunBehatInteractively($answerString, $argumentsString) $this->iRunBehat($argumentsString); } + /** + * Runs behat command in debug mode + * + * @When /^I run behat in debug mode$/ + */ + public function iRunBehatInDebugMode() + { + $this->options = ''; + $this->iRunBehat('--debug'); + } + /** * Checks whether previously ran command passes|fails with provided output. * diff --git a/features/config.feature b/features/config.feature index d6b55b23a..53b84b09f 100644 --- a/features/config.feature +++ b/features/config.feature @@ -91,3 +91,36 @@ Feature: Config """ The requested config file does not exist """ + + Scenario: Prioritize *.yaml config file + Given a file named "behat.yaml" + Given a file named "behat.yml" + Given a some feature context + And a some feature scenarios + When I run behat in debug mode + Then the output should contain: + """ + behat.yaml + """ + + Scenario: Load custom config instead of distribution + Given a file named "behat.yml" + Given a file named "behat.yaml.dist" + Given a some feature context + And a some feature scenarios + When I run behat in debug mode + Then the output should contain: + """ + behat.yml + """ + + Scenario: Prioritize config file from root + Given a file named "behat.yaml.dist" + Given a file named "config/behat.yaml" + Given a some feature context + And a some feature scenarios + When I run behat in debug mode + Then the output should contain: + """ + behat.yaml.dist + """ \ No newline at end of file From 33c393c70088510a6b4285e200f1e9075cf91ce2 Mon Sep 17 00:00:00 2001 From: Kamil Kokot Date: Thu, 16 Feb 2017 21:20:33 +0100 Subject: [PATCH 014/567] Correct command options descriptions --- src/Behat/Testwork/Cli/Application.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Behat/Testwork/Cli/Application.php b/src/Behat/Testwork/Cli/Application.php index 08eca8711..f9f35212e 100644 --- a/src/Behat/Testwork/Cli/Application.php +++ b/src/Behat/Testwork/Cli/Application.php @@ -75,8 +75,8 @@ public function getDefaultInputDefinition() ), new InputOption('--help', '-h', InputOption::VALUE_NONE, 'Display this help message.'), new InputOption('--config-reference', null, InputOption::VALUE_NONE, 'Display the configuration reference.'), - new InputOption('--debug', null, InputOption::VALUE_NONE, 'Provide debuggin information about current environment.'), - new InputOption('--version', '-V', InputOption::VALUE_NONE, 'Display this behat version.'), + new InputOption('--debug', null, InputOption::VALUE_NONE, 'Provide debugging information about current environment.'), + new InputOption('--version', '-V', InputOption::VALUE_NONE, 'Display version.'), new InputOption('--no-interaction', '-n', InputOption::VALUE_NONE, 'Do not ask any interactive question.'), new InputOption( '--colors', null, InputOption::VALUE_NONE, From fd4ec00790497a5711b89e2c6d29eca44722e264 Mon Sep 17 00:00:00 2001 From: Veaceslav Medvedev Date: Fri, 17 Feb 2017 14:19:48 +0200 Subject: [PATCH 015/567] Update CHANGELOG --- CHANGELOG.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 5cc6a1206..926fd7056 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,9 @@ The format is based on [Keep a Changelog](http://keepachangelog.com/) and this project adheres to [Semantic Versioning](http://semver.org/). ## [Unreleased] +### Changed + * [#997](https://github.com/Behat/Behat/pull/997) Prioritize `*.yaml` extension for configuration files, as this extension is considered official. + ### Fixed * [#993](https://github.com/Behat/Behat/pull/993) Fix mixed arguments organizer not marking typehinted arguments as "defined" * [#992](https://github.com/Behat/Behat/pull/993) Do not misinterpret first argument as a numbered argument if it is in fact typehinted From cf47261ea5a2e7376dafa307b3783b8768795fca Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Baptiste=20Clavi=C3=A9?= Date: Tue, 4 Apr 2017 14:12:52 +0200 Subject: [PATCH 016/567] Use php 5.4 for the low dependency test instead of php 5.3 --- .travis.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index b39461129..3d686d6bf 100644 --- a/.travis.yml +++ b/.travis.yml @@ -14,7 +14,7 @@ branches: matrix: include: - - php: 5.3 + - php: 5.4 env: DEPENDENCIES='low' - php: 5.6 env: SYMFONY_VERSION='2.3.*' From 1aac3efe0eeea54928261c9367690387465d4b16 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Baptiste=20Clavi=C3=A9?= Date: Tue, 4 Apr 2017 14:13:30 +0200 Subject: [PATCH 017/567] Remove job on sf 3.0 on 7.0 --- .travis.yml | 2 -- 1 file changed, 2 deletions(-) diff --git a/.travis.yml b/.travis.yml index 3d686d6bf..ca3cf9b9a 100644 --- a/.travis.yml +++ b/.travis.yml @@ -22,8 +22,6 @@ matrix: env: SYMFONY_VERSION='2.7.*' - php: 5.6 env: SYMFONY_VERSION='2.8.*' - - php: 7.0 - env: SYMFONY_VERSION='3.0.*' - php: 7.0 env: DEPENDENCIES='dev' From 1edf9c6bb9b22299c6e4b8132f39fb8f20aeb6a0 Mon Sep 17 00:00:00 2001 From: everzet Date: Thu, 6 Apr 2017 19:38:23 +0100 Subject: [PATCH 018/567] Do not wait for HHVM build to finish --- .travis.yml | 3 +++ 1 file changed, 3 insertions(+) diff --git a/.travis.yml b/.travis.yml index ca3cf9b9a..93165d8a1 100644 --- a/.travis.yml +++ b/.travis.yml @@ -24,6 +24,9 @@ matrix: env: SYMFONY_VERSION='2.8.*' - php: 7.0 env: DEPENDENCIES='dev' + allow_failures: + - php: hhvm + fast_finish: true before_install: - if [[ ${TRAVIS_PHP_VERSION:0:4} != "hhvm" ]]; then phpenv config-rm xdebug.ini; fi From d878837228e10028612f1d61972e4c51bde533bf Mon Sep 17 00:00:00 2001 From: everzet Date: Thu, 6 Apr 2017 19:44:05 +0100 Subject: [PATCH 019/567] Bump PHP version used on AppVeyor to latest 7.1 --- appveyor.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/appveyor.yml b/appveyor.yml index 4a8cd913f..7ef75979e 100644 --- a/appveyor.yml +++ b/appveyor.yml @@ -6,7 +6,7 @@ clone_folder: c:\projects\behat environment: matrix: - - PHP_DOWNLOAD_FILE: php-7.0.9-nts-Win32-VC14-x86.zip + - PHP_DOWNLOAD_FILE: php-7.1.3-nts-Win32-VC14-x86.zip branches: only: From 0cb14ea731f5a40d1c3aa02e3575bfca477772c3 Mon Sep 17 00:00:00 2001 From: everzet Date: Thu, 6 Apr 2017 19:46:23 +0100 Subject: [PATCH 020/567] Test Symfony=dev against 7.1 --- .travis.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index 93165d8a1..943f02e18 100644 --- a/.travis.yml +++ b/.travis.yml @@ -22,7 +22,7 @@ matrix: env: SYMFONY_VERSION='2.7.*' - php: 5.6 env: SYMFONY_VERSION='2.8.*' - - php: 7.0 + - php: 7.1 env: DEPENDENCIES='dev' allow_failures: - php: hhvm From 72f555591fe684485723a7e0898e74382e366653 Mon Sep 17 00:00:00 2001 From: everzet Date: Thu, 6 Apr 2017 19:49:21 +0100 Subject: [PATCH 021/567] Fix Windows PHP download link --- appveyor.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/appveyor.yml b/appveyor.yml index 7ef75979e..c9a5eed06 100644 --- a/appveyor.yml +++ b/appveyor.yml @@ -28,7 +28,7 @@ init: install: - IF EXIST c:\php (SET PHP=0) ELSE (mkdir c:\php) - cd c:\php - - IF %PHP%==1 appveyor DownloadFile http://windows.php.net/downloads/releases/archives/%PHP_DOWNLOAD_FILE% + - IF %PHP%==1 appveyor DownloadFile http://windows.php.net/downloads/releases/%PHP_DOWNLOAD_FILE% - IF %PHP%==1 7z x %PHP_DOWNLOAD_FILE% -y > 7z.log - IF %PHP%==1 echo @php %%~dp0composer.phar %%* > composer.bat - appveyor DownloadFile https://getcomposer.org/composer.phar From 9fbf95a7e51cdd54dd4cc6deee22bcc9e058ba60 Mon Sep 17 00:00:00 2001 From: Will Gibson Date: Fri, 6 Jan 2017 17:40:57 +0000 Subject: [PATCH 022/567] Stop apostrophes causing unexpected capitals in snippets for #976 --- CHANGELOG.md | 3 +++ composer.json | 2 +- features/snippets.feature | 52 +++++++++++++++++++++++++++++++++++++++ 3 files changed, 56 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 926fd7056..95f0dd7d9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,9 @@ and this project adheres to [Semantic Versioning](http://semver.org/). ### Fixed * [#993](https://github.com/Behat/Behat/pull/993) Fix mixed arguments organizer not marking typehinted arguments as "defined" * [#992](https://github.com/Behat/Behat/pull/993) Do not misinterpret first argument as a numbered argument if it is in fact typehinted + +### Added + * [#976](https://github.com/Behat/Behat/pull/1001): Add tests to check that snippets treat words containing apostrophes as a single word ## [3.3.0] - 2016-12-25 ### Added diff --git a/composer.json b/composer.json index 95eb16ba9..8a50e5686 100644 --- a/composer.json +++ b/composer.json @@ -17,7 +17,7 @@ "php": ">=5.3.3", "ext-mbstring": "*", "behat/gherkin": "^4.4.4", - "behat/transliterator": "~1.0", + "behat/transliterator": "^1.2", "symfony/console": "~2.5||~3.0", "symfony/config": "~2.3||~3.0", "symfony/dependency-injection": "~2.1||~3.0", diff --git a/features/snippets.feature b/features/snippets.feature index fcef28566..c3617d355 100644 --- a/features/snippets.feature +++ b/features/snippets.feature @@ -432,3 +432,55 @@ Feature: Snippets generation and addition throw new PendingException(); } """ + + Scenario: Generating snippets for steps with apostrophes + Given a file named "features/bootstrap/FeatureContext.php" with: + """ + Date: Thu, 4 May 2017 10:14:07 +0100 Subject: [PATCH 023/567] Fixes issue #1008 Adds in a new method to assign the typehinted arguments to the best fitting constructor arguments. --- .../Argument/MixedArgumentOrganiser.php | 91 ++++++++++++++----- 1 file changed, 70 insertions(+), 21 deletions(-) diff --git a/src/Behat/Testwork/Argument/MixedArgumentOrganiser.php b/src/Behat/Testwork/Argument/MixedArgumentOrganiser.php index 2b3251496..ac54270bf 100644 --- a/src/Behat/Testwork/Argument/MixedArgumentOrganiser.php +++ b/src/Behat/Testwork/Argument/MixedArgumentOrganiser.php @@ -58,7 +58,7 @@ private function prepareArguments(array $parameters, array $arguments) $arguments = $this->prepareNamedArguments($parameters, $named) + - $this->prepareTypehintedArguments($typehinted) + + $this->prepareTypehintedArguments($parameters, $typehinted) + $this->prepareNumberedArguments($parameters, $numbered) + $this->prepareDefaultArguments($parameters); @@ -88,8 +88,8 @@ function (ReflectionParameter $parameter) { foreach ($arguments as $key => $val) { if ($this->isStringKeyAndExistsInParameters($key, $parameterNames)) { $namedArguments[$key] = $val; - } elseif (null !== ($num = $this->getParameterNumberWithTypehintingValue($parameters, $val))) { - $typehintedArguments[$num] = $val; + } elseif ($this->isParameterTypehintedInArgumentList($parameters, $val)) { + $typehintedArguments[] = $val; } else { $numberedArguments[] = $val; } @@ -112,26 +112,26 @@ private function isStringKeyAndExistsInParameters($argumentKey, $parameterNames) } /** - * Tries to find a parameter number, which typehints provided value. + * Check if a given value is typehinted in the argument list. * - * @param ReflectionParameter[] $parameters - * @param mixed $value + * @param ReflectionParameter[] $parameters + * @param mixed $value * - * @return null|integer + * @return Boolean */ - private function getParameterNumberWithTypehintingValue(array $parameters, $value) + public function isParameterTypehintedInArgumentList(array $parameters, $value) { if (!is_object($value)) { - return null; + return false; } - foreach ($parameters as $num => $parameter) { + foreach ($parameters as $parameter) { if ($this->isValueMatchesTypehintedParameter($value, $parameter)) { - return $num; + return true; } } - return null; + return false; } /** @@ -174,27 +174,76 @@ private function prepareNamedArguments(array $parameters, array $namedArguments) } /** - * Captures argument value based on their respective typehints. + * Captures argument values for typehinted arguments based on the given candidates. + * + * This method attempts to match up the best fitting arguments to each constructor argument. * - * Note ; as it is keeping in mind that $typeHintedArgument already has the - * right keys matching the correct parameter, it just iterates over this - * array in order to mark each arguments as "defined". + * This case specifically fixes the issue where a constructor asks for a parent and child class, + * as separate arguments, but both arguments could satisfy the first argument, + * so they would both be passed in (overwriting each other). * - * @see https://github.com/Behat/Behat/pull/993#issuecomment-275669510 + * This will ensure that the children (exact class matches) are mapped first, and then other dependencies + * are mapped sequentially (to arguments which they are an `instanceof`). * - * @param mixed[] $typehintedArguments + * As such, this requires two passes of the $parameters array to ensure it is mapped as accurately as possible. + * + * @param ReflectionParameter[] $parameters Reflection Parameters (constructor argument requirements) + * @param mixed[] $typehintedArguments Resolved arguments * * @return mixed[] */ - private function prepareTypehintedArguments(array $typehintedArguments) + private function prepareTypehintedArguments(array $parameters, array $typehintedArguments) { - foreach (array_keys($typehintedArguments) as $num) { + $arguments = []; + + $candidates = $typehintedArguments; + + foreach ($parameters as $num => $parameter) { + if ($this->isArgumentDefined($num)) { + continue; + } + + foreach ($candidates as $candidateIndex => $candidate) { + $reflectionClass = $parameter->getClass(); + + if (!$reflectionClass || !$reflectionClass->isInstance($candidate)) { + continue; + } + + if ($reflectionClass->getName() === get_class($candidate)) { + $arguments[$num] = $candidate; + $this->markArgumentDefined($num); + + unset($candidates[$candidateIndex]); + + break 1; + } + } } - return $typehintedArguments; + foreach ($parameters as $num => $parameter) { + if ($this->isArgumentDefined($num)) { + continue; + } + + foreach ($candidates as $candidateIndex => $candidate) { + if (!$reflectionClass || !$reflectionClass->isInstance($candidate)) { + continue; + } + + $arguments[$num] = $candidate; + + $this->markArgumentDefined(true); + + unset($candidates[$candidateIndex]); + + break 1; + } } + return $arguments; + } /** * Captures argument values for undefined arguments based on their respective numbers. From 05c9e7468bf3e2ac13464d91f5e50bf9921e83a9 Mon Sep 17 00:00:00 2001 From: Glenn McEwan Date: Thu, 4 May 2017 10:24:10 +0100 Subject: [PATCH 024/567] Add a detailed descriptionn of the return value --- src/Behat/Testwork/Argument/MixedArgumentOrganiser.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Behat/Testwork/Argument/MixedArgumentOrganiser.php b/src/Behat/Testwork/Argument/MixedArgumentOrganiser.php index ac54270bf..47c8ceb3d 100644 --- a/src/Behat/Testwork/Argument/MixedArgumentOrganiser.php +++ b/src/Behat/Testwork/Argument/MixedArgumentOrganiser.php @@ -190,7 +190,7 @@ private function prepareNamedArguments(array $parameters, array $namedArguments) * @param ReflectionParameter[] $parameters Reflection Parameters (constructor argument requirements) * @param mixed[] $typehintedArguments Resolved arguments * - * @return mixed[] + * @return mixed[] Ordered list of arguments, index is the constructor argument position, value is what will be injected */ private function prepareTypehintedArguments(array $parameters, array $typehintedArguments) { From 6d7c950c21af1165d7c20ca9f6487ccfb60cbf31 Mon Sep 17 00:00:00 2001 From: Glenn McEwan Date: Thu, 4 May 2017 10:26:49 +0100 Subject: [PATCH 025/567] Add missing parameter definition --- src/Behat/Testwork/Argument/MixedArgumentOrganiser.php | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/Behat/Testwork/Argument/MixedArgumentOrganiser.php b/src/Behat/Testwork/Argument/MixedArgumentOrganiser.php index 47c8ceb3d..4fd072fe5 100644 --- a/src/Behat/Testwork/Argument/MixedArgumentOrganiser.php +++ b/src/Behat/Testwork/Argument/MixedArgumentOrganiser.php @@ -228,6 +228,8 @@ private function prepareTypehintedArguments(array $parameters, array $typehinted } foreach ($candidates as $candidateIndex => $candidate) { + $reflectionClass = $parameter->getClass(); + if (!$reflectionClass || !$reflectionClass->isInstance($candidate)) { continue; } From d47871ce03a7f57d85e7d6c4cdb89b46a25ddb2e Mon Sep 17 00:00:00 2001 From: Glenn McEwan Date: Thu, 4 May 2017 11:00:47 +0100 Subject: [PATCH 026/567] Typo --- src/Behat/Testwork/Argument/MixedArgumentOrganiser.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Behat/Testwork/Argument/MixedArgumentOrganiser.php b/src/Behat/Testwork/Argument/MixedArgumentOrganiser.php index 4fd072fe5..1f306eb8a 100644 --- a/src/Behat/Testwork/Argument/MixedArgumentOrganiser.php +++ b/src/Behat/Testwork/Argument/MixedArgumentOrganiser.php @@ -236,7 +236,7 @@ private function prepareTypehintedArguments(array $parameters, array $typehinted $arguments[$num] = $candidate; - $this->markArgumentDefined(true); + $this->markArgumentDefined($num); unset($candidates[$candidateIndex]); From ea92d9542305f101b1719ff482a1444c173cdf59 Mon Sep 17 00:00:00 2001 From: Glenn McEwan Date: Thu, 4 May 2017 15:01:22 +0100 Subject: [PATCH 027/567] Add Behat test to check the status of the changes I've added in --- features/helper_containers.feature | 49 ++++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) diff --git a/features/helper_containers.feature b/features/helper_containers.feature index 643b75609..cfc822816 100644 --- a/features/helper_containers.feature +++ b/features/helper_containers.feature @@ -342,3 +342,52 @@ Feature: Per-suite helper containers """ When I run "behat --no-colors -f progress features/container_args.feature" Then it should pass + + Scenario: Injecting typehinted arguments for a parent and child class (fix #1008) + Given a file named "behat.yml" with: + """ + default: + suites: + default: + contexts: + - FirstContext: + - "@child_class" + - "@parent_class" + services: + parent_class: + class: ParentClass + child_class: + class: ChildClass + """ + And a file named "features/container_args.feature" with: + """ + Feature: + Scenario: + Given foo + """ + And a file named "features/bootstrap/FirstContext.php" with: + """ + Date: Mon, 8 May 2017 09:19:32 +0100 Subject: [PATCH 028/567] Update visibility to match other methods --- src/Behat/Testwork/Argument/MixedArgumentOrganiser.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Behat/Testwork/Argument/MixedArgumentOrganiser.php b/src/Behat/Testwork/Argument/MixedArgumentOrganiser.php index 1f306eb8a..48c7102d4 100644 --- a/src/Behat/Testwork/Argument/MixedArgumentOrganiser.php +++ b/src/Behat/Testwork/Argument/MixedArgumentOrganiser.php @@ -119,7 +119,7 @@ private function isStringKeyAndExistsInParameters($argumentKey, $parameterNames) * * @return Boolean */ - public function isParameterTypehintedInArgumentList(array $parameters, $value) + private function isParameterTypehintedInArgumentList(array $parameters, $value) { if (!is_object($value)) { return false; From d7cc1409e17824d3041fab6cd89bb623f5d9caf8 Mon Sep 17 00:00:00 2001 From: Glenn McEwan Date: Mon, 8 May 2017 10:29:57 +0100 Subject: [PATCH 029/567] Refactor the code so that there is less repetition of code (but in turn, more code... --- .../Argument/MixedArgumentOrganiser.php | 59 ++++++++++++------- 1 file changed, 38 insertions(+), 21 deletions(-) diff --git a/src/Behat/Testwork/Argument/MixedArgumentOrganiser.php b/src/Behat/Testwork/Argument/MixedArgumentOrganiser.php index 48c7102d4..9bb4309ca 100644 --- a/src/Behat/Testwork/Argument/MixedArgumentOrganiser.php +++ b/src/Behat/Testwork/Argument/MixedArgumentOrganiser.php @@ -12,6 +12,7 @@ use Behat\Testwork\Argument\Exception\UnknownParameterValueException; use ReflectionFunctionAbstract; +use ReflectionClass; use ReflectionMethod; use ReflectionParameter; @@ -198,30 +199,30 @@ private function prepareTypehintedArguments(array $parameters, array $typehinted $candidates = $typehintedArguments; - foreach ($parameters as $num => $parameter) { - if ($this->isArgumentDefined($num)) { - continue; - } - - foreach ($candidates as $candidateIndex => $candidate) { - $reflectionClass = $parameter->getClass(); + $this->applyPredicateToTypehintedArguments($parameters, $candidates, $arguments, 'classMatchingPredicateForTypehintedArguments'); - if (!$reflectionClass || !$reflectionClass->isInstance($candidate)) { - continue; - } - - if ($reflectionClass->getName() === get_class($candidate)) { - $arguments[$num] = $candidate; - - $this->markArgumentDefined($num); + // This iteration maps up everything else, providing the argument is an instanceof the parameter. + $this->applyPredicateToTypehintedArguments($parameters, $candidates, $arguments); - unset($candidates[$candidateIndex]); - - break 1; - } - } + return $arguments; } + /** + * Applies a predicate for each candidate when matching up typehinted arguments. + * This helps to avoid repetition when looping them, as multiple passes are needed over the parameters / candidates. + * + * @param ReflectionParameter[] $parameters Reflection Parameters (constructor argument requirements) + * @param mixed[] &$candidates Resolved arguments + * @param mixed[] &$arguments Argument mapping + * @param string $predicate [optional] Predicate to each candidate in this iteration + * @return void + */ + private function applyPredicateToTypehintedArguments( + array $parameters, + array &$candidates, + array &$arguments, + $predicate = null + ) { foreach ($parameters as $num => $parameter) { if ($this->isArgumentDefined($num)) { continue; @@ -234,6 +235,12 @@ private function prepareTypehintedArguments(array $parameters, array $typehinted continue; } + if ($predicate !== null && method_exists($this, $predicate)) { + if (call_user_func_array([$this, $predicate], [$reflectionClass, $candidate]) !== true) { + continue; + } + } + $arguments[$num] = $candidate; $this->markArgumentDefined($num); @@ -243,8 +250,18 @@ private function prepareTypehintedArguments(array $parameters, array $typehinted break 1; } } + } - return $arguments; + /** + * Typehinted argument predicate to check if the argument and parameter classes match equally. + * + * @param ReflectionClass $reflectionClass Typehinted argument + * @param mixed $candidate Resolved argument + * @return boolean + */ + private function classMatchingPredicateForTypehintedArguments(ReflectionClass $reflectionClass, $candidate) + { + return $reflectionClass->getName() === get_class($candidate); } /** From bb899c2a3761bca794ccd4a2db4736cf2a291922 Mon Sep 17 00:00:00 2001 From: Glenn McEwan Date: Mon, 8 May 2017 11:05:30 +0100 Subject: [PATCH 030/567] An attempt at removing complexity (from Scrutinizer) by adding more code! --- .../Argument/MixedArgumentOrganiser.php | 52 +++++++++++++------ 1 file changed, 36 insertions(+), 16 deletions(-) diff --git a/src/Behat/Testwork/Argument/MixedArgumentOrganiser.php b/src/Behat/Testwork/Argument/MixedArgumentOrganiser.php index 9bb4309ca..c8c3bf26e 100644 --- a/src/Behat/Testwork/Argument/MixedArgumentOrganiser.php +++ b/src/Behat/Testwork/Argument/MixedArgumentOrganiser.php @@ -199,13 +199,23 @@ private function prepareTypehintedArguments(array $parameters, array $typehinted $candidates = $typehintedArguments; - $this->applyPredicateToTypehintedArguments($parameters, $candidates, $arguments, 'classMatchingPredicateForTypehintedArguments'); + $this->applyPredicateToTypehintedArguments( + $parameters, + $candidates, + $arguments, + [$this, 'classMatchingPredicateForTypehintedArguments'] + ); // This iteration maps up everything else, providing the argument is an instanceof the parameter. - $this->applyPredicateToTypehintedArguments($parameters, $candidates, $arguments); + $this->applyPredicateToTypehintedArguments( + $parameters, + $candidates, + $arguments, + [$this, 'isInstancePredicateForTypehintedArguments'] + ); return $arguments; - } + } /** * Applies a predicate for each candidate when matching up typehinted arguments. @@ -214,33 +224,31 @@ private function prepareTypehintedArguments(array $parameters, array $typehinted * @param ReflectionParameter[] $parameters Reflection Parameters (constructor argument requirements) * @param mixed[] &$candidates Resolved arguments * @param mixed[] &$arguments Argument mapping - * @param string $predicate [optional] Predicate to each candidate in this iteration + * @param callable $predicate Callable predicate to apply to each candidate * @return void */ private function applyPredicateToTypehintedArguments( array $parameters, array &$candidates, array &$arguments, - $predicate = null + callable $predicate ) { foreach ($parameters as $num => $parameter) { if ($this->isArgumentDefined($num)) { continue; } + + $reflectionClass = $parameter->getClass(); - foreach ($candidates as $candidateIndex => $candidate) { - $reflectionClass = $parameter->getClass(); + if (!$reflectionClass) { + continue; + } - if (!$reflectionClass || !$reflectionClass->isInstance($candidate)) { + foreach ($candidates as $candidateIndex => $candidate) { + if (call_user_func_array($predicate, [$reflectionClass, $candidate]) !== true) { continue; } - if ($predicate !== null && method_exists($this, $predicate)) { - if (call_user_func_array([$this, $predicate], [$reflectionClass, $candidate]) !== true) { - continue; - } - } - $arguments[$num] = $candidate; $this->markArgumentDefined($num); @@ -249,7 +257,7 @@ private function applyPredicateToTypehintedArguments( break 1; } - } + } } /** @@ -264,6 +272,18 @@ private function classMatchingPredicateForTypehintedArguments(ReflectionClass $r return $reflectionClass->getName() === get_class($candidate); } + /** + * Typehinted argument predicate to check if the argument is an instance of the parameter. + * + * @param ReflectionClass $reflectionClass Typehinted argument + * @param mixed $candidate Resolved argument + * @return boolean + */ + private function isInstancePredicateForTypehintedArguments(ReflectionClass $reflectionClass, $candidate) + { + return $reflectionClass->isInstance($candidate); + } + /** * Captures argument values for undefined arguments based on their respective numbers. * @@ -421,4 +441,4 @@ private function isArgumentDefined($position) { return isset($this->definedArguments[$position]); } -} +} \ No newline at end of file From e37c3bd9501a26ed2495725afbe689d1316bd115 Mon Sep 17 00:00:00 2001 From: Glenn McEwan Date: Mon, 8 May 2017 11:28:58 +0100 Subject: [PATCH 031/567] Further reduce the complexity by adding yet another method --- .../Argument/MixedArgumentOrganiser.php | 37 +++++++++++++++---- 1 file changed, 29 insertions(+), 8 deletions(-) diff --git a/src/Behat/Testwork/Argument/MixedArgumentOrganiser.php b/src/Behat/Testwork/Argument/MixedArgumentOrganiser.php index c8c3bf26e..5bee0da7f 100644 --- a/src/Behat/Testwork/Argument/MixedArgumentOrganiser.php +++ b/src/Behat/Testwork/Argument/MixedArgumentOrganiser.php @@ -217,6 +217,33 @@ private function prepareTypehintedArguments(array $parameters, array $typehinted return $arguments; } + /** + * Filtered out superfluous parameters for matching up typehinted arguments. + * + * @param ReflectionParameter[] $parameters Constructor Arguments + * @return ReflectionParameter[] Filtered $parameters + */ + private function filterApplicableTypehintedParameters(array $parameters) + { + $filtered = []; + + foreach ($parameters as $num => $parameter) { + if ($this->isArgumentDefined($num)) { + continue; + } + + $reflectionClass = $parameter->getClass(); + + if (!$reflectionClass) { + continue; + } + + $filtered[$num] = $parameter; + } + + return $filtered; + } + /** * Applies a predicate for each candidate when matching up typehinted arguments. * This helps to avoid repetition when looping them, as multiple passes are needed over the parameters / candidates. @@ -233,17 +260,11 @@ private function applyPredicateToTypehintedArguments( array &$arguments, callable $predicate ) { + $parameters = $this->filterApplicableTypehintedParameters($parameters); + foreach ($parameters as $num => $parameter) { - if ($this->isArgumentDefined($num)) { - continue; - } - $reflectionClass = $parameter->getClass(); - if (!$reflectionClass) { - continue; - } - foreach ($candidates as $candidateIndex => $candidate) { if (call_user_func_array($predicate, [$reflectionClass, $candidate]) !== true) { continue; From 19bedc8f9d23cd6bc700a65f82503bcc4521b4a1 Mon Sep 17 00:00:00 2001 From: Glenn McEwan Date: Mon, 8 May 2017 11:37:58 +0100 Subject: [PATCH 032/567] Rename variable for codestyle reasons --- src/Behat/Testwork/Argument/MixedArgumentOrganiser.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Behat/Testwork/Argument/MixedArgumentOrganiser.php b/src/Behat/Testwork/Argument/MixedArgumentOrganiser.php index 5bee0da7f..c05e9bd17 100644 --- a/src/Behat/Testwork/Argument/MixedArgumentOrganiser.php +++ b/src/Behat/Testwork/Argument/MixedArgumentOrganiser.php @@ -260,9 +260,9 @@ private function applyPredicateToTypehintedArguments( array &$arguments, callable $predicate ) { - $parameters = $this->filterApplicableTypehintedParameters($parameters); + $filtered = $this->filterApplicableTypehintedParameters($parameters); - foreach ($parameters as $num => $parameter) { + foreach ($filtered as $num => $parameter) { $reflectionClass = $parameter->getClass(); foreach ($candidates as $candidateIndex => $candidate) { From 2249f095e6a52cc7408fa112fe6b02e920207058 Mon Sep 17 00:00:00 2001 From: Glenn McEwan Date: Tue, 9 May 2017 10:11:55 +0100 Subject: [PATCH 033/567] Try and simplify a bit more... --- .../Testwork/Argument/MixedArgumentOrganiser.php | 16 ++++++---------- 1 file changed, 6 insertions(+), 10 deletions(-) diff --git a/src/Behat/Testwork/Argument/MixedArgumentOrganiser.php b/src/Behat/Testwork/Argument/MixedArgumentOrganiser.php index c05e9bd17..ed8931908 100644 --- a/src/Behat/Testwork/Argument/MixedArgumentOrganiser.php +++ b/src/Behat/Testwork/Argument/MixedArgumentOrganiser.php @@ -263,20 +263,16 @@ private function applyPredicateToTypehintedArguments( $filtered = $this->filterApplicableTypehintedParameters($parameters); foreach ($filtered as $num => $parameter) { - $reflectionClass = $parameter->getClass(); - foreach ($candidates as $candidateIndex => $candidate) { - if (call_user_func_array($predicate, [$reflectionClass, $candidate]) !== true) { - continue; - } + if (call_user_func_array($predicate, [$parameter->getClass(), $candidate])) { + $arguments[$num] = $candidate; - $arguments[$num] = $candidate; + $this->markArgumentDefined($num); - $this->markArgumentDefined($num); - - unset($candidates[$candidateIndex]); + unset($candidates[$candidateIndex]); - break 1; + break 1; + } } } } From 567a8e4ebc7d4a1d2d2ddc09ea8349ed67767da2 Mon Sep 17 00:00:00 2001 From: Glenn McEwan Date: Tue, 9 May 2017 11:08:10 +0100 Subject: [PATCH 034/567] Add another method! To reduce complexity... --- .../Argument/MixedArgumentOrganiser.php | 40 +++++++++++++++---- 1 file changed, 32 insertions(+), 8 deletions(-) diff --git a/src/Behat/Testwork/Argument/MixedArgumentOrganiser.php b/src/Behat/Testwork/Argument/MixedArgumentOrganiser.php index ed8931908..a2f023cd9 100644 --- a/src/Behat/Testwork/Argument/MixedArgumentOrganiser.php +++ b/src/Behat/Testwork/Argument/MixedArgumentOrganiser.php @@ -246,7 +246,8 @@ private function filterApplicableTypehintedParameters(array $parameters) /** * Applies a predicate for each candidate when matching up typehinted arguments. - * This helps to avoid repetition when looping them, as multiple passes are needed over the parameters / candidates. + * This passes through to another loop of the candidates in @matchParameterToCandidateUsingPredicate, + * because this method is "too complex" with two loops... * * @param ReflectionParameter[] $parameters Reflection Parameters (constructor argument requirements) * @param mixed[] &$candidates Resolved arguments @@ -263,18 +264,41 @@ private function applyPredicateToTypehintedArguments( $filtered = $this->filterApplicableTypehintedParameters($parameters); foreach ($filtered as $num => $parameter) { - foreach ($candidates as $candidateIndex => $candidate) { - if (call_user_func_array($predicate, [$parameter->getClass(), $candidate])) { - $arguments[$num] = $candidate; + $this->matchParameterToCandidateUsingPredicate($parameter, $candidates, $arguments, $predicate); + } + } + + /** + * Applies a predicate for each candidate when matching up typehinted arguments. + * This helps to avoid repetition when looping them, as multiple passes are needed over the parameters / candidates. + * + * @param ReflectionParameter $parameter Reflection Parameter (constructor argument requirements) + * @param mixed[] &$candidates Resolved arguments + * @param mixed[] &$arguments Argument mapping + * @param callable $predicate Callable predicate to apply to each candidate + * @return boolean Returns true if a candidate has been matched to the given parameter, otherwise false + */ + public function matchParameterToCandidateUsingPredicate( + ReflectionParameter $parameter, + array &$candidates, + array &$arguments, + callable $predicate + ) { + foreach ($candidates as $candidateIndex => $candidate) { + if (call_user_func_array($predicate, [$parameter->getClass(), $candidate])) { + $num = $parameter->getPosition(); - $this->markArgumentDefined($num); + $arguments[$num] = $candidate; - unset($candidates[$candidateIndex]); + $this->markArgumentDefined($num); - break 1; - } + unset($candidates[$candidateIndex]); + + return true; } } + + return false; } /** From a02da149a4a4bcf2de279429e762b110b6b21cee Mon Sep 17 00:00:00 2001 From: everzet Date: Mon, 15 May 2017 17:15:04 +0100 Subject: [PATCH 035/567] Refactor to follow 5.3 style (for now) This is not to support 5.3, but rather to have consistency across the codebase. --- src/Behat/Testwork/Argument/MixedArgumentOrganiser.php | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/Behat/Testwork/Argument/MixedArgumentOrganiser.php b/src/Behat/Testwork/Argument/MixedArgumentOrganiser.php index a2f023cd9..0c919070e 100644 --- a/src/Behat/Testwork/Argument/MixedArgumentOrganiser.php +++ b/src/Behat/Testwork/Argument/MixedArgumentOrganiser.php @@ -195,7 +195,7 @@ private function prepareNamedArguments(array $parameters, array $namedArguments) */ private function prepareTypehintedArguments(array $parameters, array $typehintedArguments) { - $arguments = []; + $arguments = array(); $candidates = $typehintedArguments; @@ -203,7 +203,7 @@ private function prepareTypehintedArguments(array $parameters, array $typehinted $parameters, $candidates, $arguments, - [$this, 'classMatchingPredicateForTypehintedArguments'] + array($this, 'classMatchingPredicateForTypehintedArguments') ); // This iteration maps up everything else, providing the argument is an instanceof the parameter. @@ -211,7 +211,7 @@ private function prepareTypehintedArguments(array $parameters, array $typehinted $parameters, $candidates, $arguments, - [$this, 'isInstancePredicateForTypehintedArguments'] + array($this, 'isInstancePredicateForTypehintedArguments') ); return $arguments; @@ -225,7 +225,7 @@ private function prepareTypehintedArguments(array $parameters, array $typehinted */ private function filterApplicableTypehintedParameters(array $parameters) { - $filtered = []; + $filtered = array(); foreach ($parameters as $num => $parameter) { if ($this->isArgumentDefined($num)) { @@ -482,4 +482,4 @@ private function isArgumentDefined($position) { return isset($this->definedArguments[$position]); } -} \ No newline at end of file +} From 8a629b75365c0c0d3097b395266c07b3615e5056 Mon Sep 17 00:00:00 2001 From: everzet Date: Mon, 15 May 2017 17:22:45 +0100 Subject: [PATCH 036/567] Add fix to the changelog --- CHANGELOG.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 95f0dd7d9..10b4a6440 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,7 +11,9 @@ and this project adheres to [Semantic Versioning](http://semver.org/). ### Fixed * [#993](https://github.com/Behat/Behat/pull/993) Fix mixed arguments organizer not marking typehinted arguments as "defined" * [#992](https://github.com/Behat/Behat/pull/993) Do not misinterpret first argument as a numbered argument if it is in fact typehinted - + * [#1028](https://github.com/Behat/Behat/pull/1028) Parent / Child class argument ambiguity issue + with `MixedArgumentResolver` + ### Added * [#976](https://github.com/Behat/Behat/pull/1001): Add tests to check that snippets treat words containing apostrophes as a single word From 0492ecb674301497012d8bf514aa95dc7798c45e Mon Sep 17 00:00:00 2001 From: everzet Date: Mon, 15 May 2017 17:27:57 +0100 Subject: [PATCH 037/567] Update changelog --- CHANGELOG.md | 15 +++++++-------- 1 file changed, 7 insertions(+), 8 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 10b4a6440..85c063c7f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,17 +5,15 @@ The format is based on [Keep a Changelog](http://keepachangelog.com/) and this project adheres to [Semantic Versioning](http://semver.org/). ## [Unreleased] -### Changed - * [#997](https://github.com/Behat/Behat/pull/997) Prioritize `*.yaml` extension for configuration files, as this extension is considered official. + +## [3.3.1] - 2017-05-15 +### Added + * [#976](https://github.com/Behat/Behat/pull/1001): Add tests to check that snippets treat words containing apostrophes as a single word ### Fixed * [#993](https://github.com/Behat/Behat/pull/993) Fix mixed arguments organizer not marking typehinted arguments as "defined" * [#992](https://github.com/Behat/Behat/pull/993) Do not misinterpret first argument as a numbered argument if it is in fact typehinted - * [#1028](https://github.com/Behat/Behat/pull/1028) Parent / Child class argument ambiguity issue - with `MixedArgumentResolver` - -### Added - * [#976](https://github.com/Behat/Behat/pull/1001): Add tests to check that snippets treat words containing apostrophes as a single word + * [#1028](https://github.com/Behat/Behat/pull/1028) Parent / Child class argument ambiguity issue with `MixedArgumentResolver` ## [3.3.0] - 2016-12-25 ### Added @@ -807,7 +805,8 @@ and this project adheres to [Semantic Versioning](http://semver.org/). ### Changed * Initial release -[Unreleased]: https://github.com/Behat/Behat/compare/v3.3.0...HEAD +[Unreleased]: https://github.com/Behat/Behat/compare/v3.3.1...HEAD +[3.3.1]: https://github.com/Behat/Behat/compare/v3.3.0...v3.3.1 [3.3.0]: https://github.com/Behat/Behat/compare/v3.2.3...v3.3.0 [3.2.3]: https://github.com/Behat/Behat/compare/v3.2.2...v3.2.3 [3.2.2]: https://github.com/Behat/Behat/compare/v3.2.1...v3.2.2 From b4466048e01725724757a189648e0da9f1ef6d13 Mon Sep 17 00:00:00 2001 From: everzet Date: Mon, 15 May 2017 17:41:36 +0100 Subject: [PATCH 038/567] Add deployment step --- .travis.yml | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/.travis.yml b/.travis.yml index 943f02e18..dbad05c46 100644 --- a/.travis.yml +++ b/.travis.yml @@ -42,3 +42,22 @@ before_script: script: - phpunit - behat -fprogress --strict --tags '~@php-version,'`php php_version_tags.php` + +before_deploy: + - curl -LSs https://box-project.github.io/box2/installer.php | php + - export PATH=.:$PATH + - rm -Rf ./vendor + - composer install --no-dev -o + - box.phar build + +deploy: + provider: releases + api_key: + secure: KLoJVMKTdabtNxRxVk92Lx9+ifK6nyYx2ATRflvaxJLJ0tkbvdkYwFnd79JuarE2FlJ65/Jd2Buy+dXCRPUkEaQ5Mg5IeZQg9C9qjTCjPE46n1nFa9487b/ZWsmx/iE7Bh8D2+A5CiEC62EXxWxf2i41IKaCr6t2ws49EjGOp+0= + file: behat.phar + skip_cleanup: true + on: + repo: Behat/Behat + tags: true + php: 5.6 + condition: $SYMFONY_VERSION != "2.8.*" From 44a58c1480d6144b2dc2c2bf02b9cef73c83840d Mon Sep 17 00:00:00 2001 From: everzet Date: Mon, 15 May 2017 17:49:16 +0100 Subject: [PATCH 039/567] Fix the conditional for deployment --- .travis.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index dbad05c46..c33d5edad 100644 --- a/.travis.yml +++ b/.travis.yml @@ -60,4 +60,4 @@ deploy: repo: Behat/Behat tags: true php: 5.6 - condition: $SYMFONY_VERSION != "2.8.*" + condition: $SYMFONY_VERSION == "2.8.*" From 3f5c2060d394de31b4842858f2b10b39c8fb335d Mon Sep 17 00:00:00 2001 From: Ciaran McNulty Date: Sat, 20 May 2017 11:07:50 +0100 Subject: [PATCH 040/567] Remove short array syntax --- src/Behat/Testwork/Argument/MixedArgumentOrganiser.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Behat/Testwork/Argument/MixedArgumentOrganiser.php b/src/Behat/Testwork/Argument/MixedArgumentOrganiser.php index 0c919070e..e50f47a7f 100644 --- a/src/Behat/Testwork/Argument/MixedArgumentOrganiser.php +++ b/src/Behat/Testwork/Argument/MixedArgumentOrganiser.php @@ -285,7 +285,7 @@ public function matchParameterToCandidateUsingPredicate( callable $predicate ) { foreach ($candidates as $candidateIndex => $candidate) { - if (call_user_func_array($predicate, [$parameter->getClass(), $candidate])) { + if (call_user_func_array($predicate, array($parameter->getClass(), $candidate))) { $num = $parameter->getPosition(); $arguments[$num] = $candidate; From 36a9d2788ff1d11b1a25a9bf58f7f8f73a00de6a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Droz?= Date: Fri, 9 Jun 2017 11:47:55 -0300 Subject: [PATCH 041/567] support environment variable inside behat.yml With symfony#21460 fixed (>= 3.3.0, symfony/symfony@a3fd5122), this change allow the use of environment variables in any section of behat configuration file. For example: `base_url: "http://%env(HOSTNAME)%"` --- src/Behat/Testwork/Cli/Application.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Behat/Testwork/Cli/Application.php b/src/Behat/Testwork/Cli/Application.php index f9f35212e..4189224e0 100644 --- a/src/Behat/Testwork/Cli/Application.php +++ b/src/Behat/Testwork/Cli/Application.php @@ -184,7 +184,7 @@ private function createContainer(InputInterface $input, OutputInterface $output) $extension = new ContainerLoader($this->extensionManager); $extension->load($container, $this->loadConfiguration($input)); $container->addObjectResource($extension); - $container->compile(); + $container->compile(true); return $container; } From ec9e110e8d0fb738f5e201830ab9b7335a9873ff Mon Sep 17 00:00:00 2001 From: Jakub Zalas Date: Fri, 21 Jul 2017 14:15:19 +0200 Subject: [PATCH 042/567] Fix a typo --- .../Testwork/Argument/ServiceContainer/ArgumentExtension.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Behat/Testwork/Argument/ServiceContainer/ArgumentExtension.php b/src/Behat/Testwork/Argument/ServiceContainer/ArgumentExtension.php index 021966440..9aa5afeff 100644 --- a/src/Behat/Testwork/Argument/ServiceContainer/ArgumentExtension.php +++ b/src/Behat/Testwork/Argument/ServiceContainer/ArgumentExtension.php @@ -18,7 +18,7 @@ use Symfony\Component\DependencyInjection\Reference; /** - * Enables argument organises for the Testwork. + * Enables argument organisers for Testwork. * * @author Konstantin Kudryashov */ From c1b69b0bd6989d800797f52d90f2e7d697d686c9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lu=C3=ADs=20Henrique=20Faria?= Date: Tue, 25 Apr 2017 23:04:27 -0300 Subject: [PATCH 043/567] add file info to definitions command --- features/bootstrap/FeatureContext.php | 6 +++++- features/syntax_help.feature | 4 ++++ .../Printer/ConsoleDefinitionInformationPrinter.php | 9 +++++++++ 3 files changed, 18 insertions(+), 1 deletion(-) diff --git a/features/bootstrap/FeatureContext.php b/features/bootstrap/FeatureContext.php index 8ee8bfacf..ac49312f4 100644 --- a/features/bootstrap/FeatureContext.php +++ b/features/bootstrap/FeatureContext.php @@ -320,7 +320,11 @@ public function theOutputShouldContain(PyStringNode $text) private function getExpectedOutput(PyStringNode $expectedText) { - $text = strtr($expectedText, array('\'\'\'' => '"""', '%%TMP_DIR%%' => sys_get_temp_dir() . DIRECTORY_SEPARATOR)); + $text = strtr($expectedText, array( + '\'\'\'' => '"""', + '%%TMP_DIR%%' => sys_get_temp_dir() . DIRECTORY_SEPARATOR, + '%%WORKING_DIR%%' => $this->workingDir + )); // windows path fix if ('/' !== DIRECTORY_SEPARATOR) { diff --git a/features/syntax_help.feature b/features/syntax_help.feature index aa03422b8..fc166ad1f 100644 --- a/features/syntax_help.feature +++ b/features/syntax_help.feature @@ -247,6 +247,7 @@ Feature: Syntax helpers """ default | [Given|*] /^I have (\d+) apples?$/ | at `FeatureContext::iHaveApples()` + | on `%%WORKING_DIR%%/features/bootstrap/FeatureContext.php[11:13]` default | [When|*] /^I ate (\d+) apples?$/ | Eating apples @@ -255,12 +256,15 @@ Feature: Syntax helpers | - one | - two | at `FeatureContext::iAteApples()` + | on `%%WORKING_DIR%%/features/bootstrap/FeatureContext.php[26:28]` default | [When|*] /^I found (\d+) apples?$/ | at `FeatureContext::iFoundApples()` + | on `%%WORKING_DIR%%/features/bootstrap/FeatureContext.php[33:35]` default | [Then|*] /^I should have (\d+) apples$/ | at `FeatureContext::iShouldHaveApples()` + | on `%%WORKING_DIR%%/features/bootstrap/FeatureContext.php[40:42]` """ Scenario: Search definition diff --git a/src/Behat/Behat/Definition/Printer/ConsoleDefinitionInformationPrinter.php b/src/Behat/Behat/Definition/Printer/ConsoleDefinitionInformationPrinter.php index 4c074ea45..9f504f815 100644 --- a/src/Behat/Behat/Definition/Printer/ConsoleDefinitionInformationPrinter.php +++ b/src/Behat/Behat/Definition/Printer/ConsoleDefinitionInformationPrinter.php @@ -131,6 +131,15 @@ private function extractFooter(Suite $suite, Definition $definition) ) ); + $lines[] = strtr( + '{space}| on `{filepath}[{start}:{end}]`', array( + '{space}' => str_pad('', mb_strlen($suite->getName(), 'utf8') + 1), + '{filepath}' => $definition->getReflection()->getFileName(), + '{start}' => $definition->getReflection()->getStartLine(), + '{end}' => $definition->getReflection()->getEndLine() + ) + ); + return $lines; } } From ee41bccaff76a52e224643675c142746c87783ad Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lu=C3=ADs=20Henrique=20Faria?= Date: Sat, 1 Jul 2017 11:30:24 -0300 Subject: [PATCH 044/567] print file name on definitions command only when running on verbose mode --- features/syntax_help.feature | 69 ++++++++++++++++++- .../ConsoleDefinitionInformationPrinter.php | 18 ++--- .../Printer/ConsoleDefinitionPrinter.php | 10 +++ 3 files changed, 88 insertions(+), 9 deletions(-) diff --git a/features/syntax_help.feature b/features/syntax_help.feature index fc166ad1f..fd548058d 100644 --- a/features/syntax_help.feature +++ b/features/syntax_help.feature @@ -214,7 +214,7 @@ Feature: Syntax helpers /** * Eating apples - * + * * More details on eating apples, and a list: * - one * - two @@ -243,6 +243,73 @@ Feature: Syntax helpers } """ When I run "behat --no-colors -di" + Then the output should contain: + """ + default | [Given|*] /^I have (\d+) apples?$/ + | at `FeatureContext::iHaveApples()` + + default | [When|*] /^I ate (\d+) apples?$/ + | Eating apples + | More details on eating apples, and a list: + | - one + | - two + | at `FeatureContext::iAteApples()` + + default | [When|*] /^I found (\d+) apples?$/ + | at `FeatureContext::iFoundApples()` + + default | [Then|*] /^I should have (\d+) apples$/ + | at `FeatureContext::iShouldHaveApples()` + """ + + Scenario: Print extended definitions info with file name and line numbers + Given a file named "features/bootstrap/FeatureContext.php" with: + """ + | on `{filepath}[{start}:{end}]`', array( - '{space}' => str_pad('', mb_strlen($suite->getName(), 'utf8') + 1), - '{filepath}' => $definition->getReflection()->getFileName(), - '{start}' => $definition->getReflection()->getStartLine(), - '{end}' => $definition->getReflection()->getEndLine() - ) - ); + if ($this->isVerbose()) { + $lines[] = strtr( + '{space}| on `{filepath}[{start}:{end}]`', array( + '{space}' => str_pad('', mb_strlen($suite->getName(), 'utf8') + 1), + '{filepath}' => $definition->getReflection()->getFileName(), + '{start}' => $definition->getReflection()->getStartLine(), + '{end}' => $definition->getReflection()->getEndLine() + ) + ); + } return $lines; } diff --git a/src/Behat/Behat/Definition/Printer/ConsoleDefinitionPrinter.php b/src/Behat/Behat/Definition/Printer/ConsoleDefinitionPrinter.php index 08b8f92ac..bd0546f41 100644 --- a/src/Behat/Behat/Definition/Printer/ConsoleDefinitionPrinter.php +++ b/src/Behat/Behat/Definition/Printer/ConsoleDefinitionPrinter.php @@ -110,4 +110,14 @@ final protected function translateDefinition(Suite $suite, Definition $definitio { return $this->translator->translateDefinition($suite, $definition); } + + /** + * Returns whether verbosity is verbose (-v). + * + * @return bool true if verbosity is set to VERBOSITY_VERBOSE, false otherwise + */ + final protected function isVerbose() + { + return $this->output->isVerbose(); + } } From 3fecfeba90c60fd65ddf2fcac34daa2fe6bbdff2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lu=C3=ADs=20Henrique=20Faria?= Date: Sat, 1 Jul 2017 12:47:25 -0300 Subject: [PATCH 045/567] fix broken test on windows environment --- features/bootstrap/FeatureContext.php | 3 ++- features/syntax_help.feature | 8 ++++---- 2 files changed, 6 insertions(+), 5 deletions(-) diff --git a/features/bootstrap/FeatureContext.php b/features/bootstrap/FeatureContext.php index ac49312f4..8b008deb7 100644 --- a/features/bootstrap/FeatureContext.php +++ b/features/bootstrap/FeatureContext.php @@ -323,7 +323,8 @@ private function getExpectedOutput(PyStringNode $expectedText) $text = strtr($expectedText, array( '\'\'\'' => '"""', '%%TMP_DIR%%' => sys_get_temp_dir() . DIRECTORY_SEPARATOR, - '%%WORKING_DIR%%' => $this->workingDir + '%%WORKING_DIR%%' => $this->workingDir . DIRECTORY_SEPARATOR, + '%%DS%%' => DIRECTORY_SEPARATOR, )); // windows path fix diff --git a/features/syntax_help.feature b/features/syntax_help.feature index fd548058d..1f6432ad6 100644 --- a/features/syntax_help.feature +++ b/features/syntax_help.feature @@ -314,7 +314,7 @@ Feature: Syntax helpers """ default | [Given|*] /^I have (\d+) apples?$/ | at `FeatureContext::iHaveApples()` - | on `%%WORKING_DIR%%/features/bootstrap/FeatureContext.php[11:13]` + | on `%%WORKING_DIR%%features%%DS%%bootstrap%%DS%%FeatureContext.php[11:13]` default | [When|*] /^I ate (\d+) apples?$/ | Eating apples @@ -323,15 +323,15 @@ Feature: Syntax helpers | - one | - two | at `FeatureContext::iAteApples()` - | on `%%WORKING_DIR%%/features/bootstrap/FeatureContext.php[26:28]` + | on `%%WORKING_DIR%%features%%DS%%bootstrap%%DS%%FeatureContext.php[26:28]` default | [When|*] /^I found (\d+) apples?$/ | at `FeatureContext::iFoundApples()` - | on `%%WORKING_DIR%%/features/bootstrap/FeatureContext.php[33:35]` + | on `%%WORKING_DIR%%features%%DS%%bootstrap%%DS%%FeatureContext.php[33:35]` default | [Then|*] /^I should have (\d+) apples$/ | at `FeatureContext::iShouldHaveApples()` - | on `%%WORKING_DIR%%/features/bootstrap/FeatureContext.php[40:42]` + | on `%%WORKING_DIR%%features%%DS%%bootstrap%%DS%%FeatureContext.php[40:42]` """ Scenario: Search definition From 90bf3160ea2c476a57d5b529eb31345e944cd819 Mon Sep 17 00:00:00 2001 From: everzet Date: Wed, 30 Aug 2017 12:46:44 +0100 Subject: [PATCH 046/567] Fix setting of WORKING_DIR in context --- features/bootstrap/FeatureContext.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/features/bootstrap/FeatureContext.php b/features/bootstrap/FeatureContext.php index 8b008deb7..1e7f3fea4 100644 --- a/features/bootstrap/FeatureContext.php +++ b/features/bootstrap/FeatureContext.php @@ -323,7 +323,7 @@ private function getExpectedOutput(PyStringNode $expectedText) $text = strtr($expectedText, array( '\'\'\'' => '"""', '%%TMP_DIR%%' => sys_get_temp_dir() . DIRECTORY_SEPARATOR, - '%%WORKING_DIR%%' => $this->workingDir . DIRECTORY_SEPARATOR, + '%%WORKING_DIR%%' => realpath($this->workingDir . DIRECTORY_SEPARATOR), '%%DS%%' => DIRECTORY_SEPARATOR, )); From 9612e9ebbb1ff3596d19ec62ce7c74a0cb0227ca Mon Sep 17 00:00:00 2001 From: everzet Date: Wed, 30 Aug 2017 12:47:04 +0100 Subject: [PATCH 047/567] Update examples to reflect latest i18n --- features/syntax_help.feature | 26 +++++++++++++------------- 1 file changed, 13 insertions(+), 13 deletions(-) diff --git a/features/syntax_help.feature b/features/syntax_help.feature index 1f6432ad6..6b700da53 100644 --- a/features/syntax_help.feature +++ b/features/syntax_help.feature @@ -54,21 +54,21 @@ Feature: Syntax helpers We need to be able to erase past agents' memory [Предыстория|Контекст]: - [Допустим|Пусть|Дано|*] there is agent A + [Допустим|Пусть|Дано|Если|*] there is agent A [К тому же|Также|*|И] there is agent B Сценарий: Erasing agent memory - [Допустим|Пусть|Дано|*] there is agent J + [Допустим|Пусть|Дано|Если|*] there is agent J [К тому же|Также|*|И] there is agent K - [Когда|Если|*] I erase agent K's memory - [Тогда|То|*] there should be agent J + [Когда|*] I erase agent K's memory + [Затем|Тогда|То|*] there should be agent J [Но|*|А] there should not be agent K Структура сценария: Erasing other agents' memory - [Допустим|Пусть|Дано|*] there is agent + [Допустим|Пусть|Дано|Если|*] there is agent [К тому же|Также|*|И] there is agent - [Когда|Если|*] I erase agent 's memory - [Тогда|То|*] there should be agent + [Когда|*] I erase agent 's memory + [Затем|Тогда|То|*] there should be agent [Но|*|А] there should not be agent Примеры: @@ -192,7 +192,7 @@ Feature: Syntax helpers default | Допустим /^у меня (\d+) яблоко?$/ default | Когда /^I ate (\d+) apples?$/ default | Когда /^Я нашел (\d+) яблоко?$/ - default | Тогда /^I should have (\d+) apples$/ + default | Затем /^I should have (\d+) apples$/ """ Scenario: Print extended definitions info @@ -314,7 +314,7 @@ Feature: Syntax helpers """ default | [Given|*] /^I have (\d+) apples?$/ | at `FeatureContext::iHaveApples()` - | on `%%WORKING_DIR%%features%%DS%%bootstrap%%DS%%FeatureContext.php[11:13]` + | on `%%WORKING_DIR%%/features%%DS%%bootstrap%%DS%%FeatureContext.php[11:13]` default | [When|*] /^I ate (\d+) apples?$/ | Eating apples @@ -323,15 +323,15 @@ Feature: Syntax helpers | - one | - two | at `FeatureContext::iAteApples()` - | on `%%WORKING_DIR%%features%%DS%%bootstrap%%DS%%FeatureContext.php[26:28]` + | on `%%WORKING_DIR%%/features%%DS%%bootstrap%%DS%%FeatureContext.php[26:28]` default | [When|*] /^I found (\d+) apples?$/ | at `FeatureContext::iFoundApples()` - | on `%%WORKING_DIR%%features%%DS%%bootstrap%%DS%%FeatureContext.php[33:35]` + | on `%%WORKING_DIR%%/features%%DS%%bootstrap%%DS%%FeatureContext.php[33:35]` default | [Then|*] /^I should have (\d+) apples$/ | at `FeatureContext::iShouldHaveApples()` - | on `%%WORKING_DIR%%features%%DS%%bootstrap%%DS%%FeatureContext.php[40:42]` + | on `%%WORKING_DIR%%/features%%DS%%bootstrap%%DS%%FeatureContext.php[40:42]` """ Scenario: Search definition @@ -399,6 +399,6 @@ Feature: Syntax helpers When I run "behat --no-colors --lang=ru -d 'нашел'" Then the output should contain: """ - default | [Когда|Если|*] /^Я нашел (\d+) яблоко?$/ + default | [Когда|*] /^Я нашел (\d+) яблоко?$/ | at `FeatureContext::iFoundApples()` """ From 3b95012b81cb824d8379b1c324641f2bf3b74b44 Mon Sep 17 00:00:00 2001 From: everzet Date: Wed, 30 Aug 2017 12:47:40 +0100 Subject: [PATCH 048/567] Bump minimum Gherkin version required --- composer.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/composer.json b/composer.json index 8a50e5686..76897c8f6 100644 --- a/composer.json +++ b/composer.json @@ -16,7 +16,7 @@ "require": { "php": ">=5.3.3", "ext-mbstring": "*", - "behat/gherkin": "^4.4.4", + "behat/gherkin": "^4.5.1", "behat/transliterator": "^1.2", "symfony/console": "~2.5||~3.0", "symfony/config": "~2.3||~3.0", From b834cbf20525ab1d1b074d5801f6813e86f88bb0 Mon Sep 17 00:00:00 2001 From: everzet Date: Wed, 30 Aug 2017 12:49:40 +0100 Subject: [PATCH 049/567] Bump PHP version used in Appveyor --- appveyor.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/appveyor.yml b/appveyor.yml index c9a5eed06..a1e451243 100644 --- a/appveyor.yml +++ b/appveyor.yml @@ -6,7 +6,7 @@ clone_folder: c:\projects\behat environment: matrix: - - PHP_DOWNLOAD_FILE: php-7.1.3-nts-Win32-VC14-x86.zip + - PHP_DOWNLOAD_FILE: php-7.1.8-nts-Win32-VC14-x86.zip branches: only: From 1081d59073c0ed5c68f6aaf1df65af1c5496ab06 Mon Sep 17 00:00:00 2001 From: everzet Date: Wed, 30 Aug 2017 13:12:48 +0100 Subject: [PATCH 050/567] Fix tests on Windows --- features/bootstrap/FeatureContext.php | 2 +- features/syntax_help.feature | 8 ++++---- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/features/bootstrap/FeatureContext.php b/features/bootstrap/FeatureContext.php index 1e7f3fea4..629c6fc21 100644 --- a/features/bootstrap/FeatureContext.php +++ b/features/bootstrap/FeatureContext.php @@ -323,7 +323,7 @@ private function getExpectedOutput(PyStringNode $expectedText) $text = strtr($expectedText, array( '\'\'\'' => '"""', '%%TMP_DIR%%' => sys_get_temp_dir() . DIRECTORY_SEPARATOR, - '%%WORKING_DIR%%' => realpath($this->workingDir . DIRECTORY_SEPARATOR), + '%%WORKING_DIR%%' => realpath($this->workingDir . DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR, '%%DS%%' => DIRECTORY_SEPARATOR, )); diff --git a/features/syntax_help.feature b/features/syntax_help.feature index 6b700da53..caf9d8006 100644 --- a/features/syntax_help.feature +++ b/features/syntax_help.feature @@ -314,7 +314,7 @@ Feature: Syntax helpers """ default | [Given|*] /^I have (\d+) apples?$/ | at `FeatureContext::iHaveApples()` - | on `%%WORKING_DIR%%/features%%DS%%bootstrap%%DS%%FeatureContext.php[11:13]` + | on `%%WORKING_DIR%%features%%DS%%bootstrap%%DS%%FeatureContext.php[11:13]` default | [When|*] /^I ate (\d+) apples?$/ | Eating apples @@ -323,15 +323,15 @@ Feature: Syntax helpers | - one | - two | at `FeatureContext::iAteApples()` - | on `%%WORKING_DIR%%/features%%DS%%bootstrap%%DS%%FeatureContext.php[26:28]` + | on `%%WORKING_DIR%%features%%DS%%bootstrap%%DS%%FeatureContext.php[26:28]` default | [When|*] /^I found (\d+) apples?$/ | at `FeatureContext::iFoundApples()` - | on `%%WORKING_DIR%%/features%%DS%%bootstrap%%DS%%FeatureContext.php[33:35]` + | on `%%WORKING_DIR%%features%%DS%%bootstrap%%DS%%FeatureContext.php[33:35]` default | [Then|*] /^I should have (\d+) apples$/ | at `FeatureContext::iShouldHaveApples()` - | on `%%WORKING_DIR%%/features%%DS%%bootstrap%%DS%%FeatureContext.php[40:42]` + | on `%%WORKING_DIR%%features%%DS%%bootstrap%%DS%%FeatureContext.php[40:42]` """ Scenario: Search definition From e44f9da22d8450907d647b1d2b09468acca14ac9 Mon Sep 17 00:00:00 2001 From: everzet Date: Fri, 30 Jun 2017 08:01:12 +0100 Subject: [PATCH 051/567] Describe support for PSR-11 --- features/helper_containers.feature | 44 ++++++++++++++++++++++++++---- 1 file changed, 39 insertions(+), 5 deletions(-) diff --git a/features/helper_containers.feature b/features/helper_containers.feature index cfc822816..934a6bbf9 100644 --- a/features/helper_containers.feature +++ b/features/helper_containers.feature @@ -7,7 +7,7 @@ Feature: Per-suite helper containers - Having a container enables you to use its services as context arguments via `@name` syntax - Container is rebuilt and is isolated between scenarios - Container is configured via suite's `services` option - - Container is a class implementing `Interop\Container\ContainerInterface` + - Container is a class implementing `Psr\Container\ContainerInterface` - There is a built-in container if you need a very simple service-sharing, configurable through the same `services` setting - There is an extension point that allows Behat extensions provide their own containers for end-users via `@name` syntax @@ -120,7 +120,7 @@ Feature: Per-suite helper containers """ And a file named "features/bootstrap/MyContainer.php" with: """ - service) ? $this->service : $this->service = new SharedService(); + } + } + """ + When I run "behat --no-colors -f progress features/container.feature" + Then it should pass + Scenario: Simplest built-in container configuration Given a file named "behat.yml" with: """ @@ -255,7 +289,7 @@ Feature: Per-suite helper containers """ And a file named "features/bootstrap/MyContainer.php" with: """ - Date: Fri, 30 Jun 2017 08:01:39 +0100 Subject: [PATCH 052/567] Implement support for PSR-11 --- composer.json | 5 +++-- .../Behat/HelperContainer/Argument/ServicesResolver.php | 2 +- .../HelperContainer/Argument/ServicesResolverFactory.php | 4 ++-- src/Behat/Behat/HelperContainer/BuiltInServiceContainer.php | 2 +- .../HelperContainer/Exception/HelperContainerException.php | 4 ++-- .../HelperContainer/Exception/ServiceNotFoundException.php | 4 ++-- 6 files changed, 11 insertions(+), 10 deletions(-) diff --git a/composer.json b/composer.json index 76897c8f6..c21bc234c 100644 --- a/composer.json +++ b/composer.json @@ -25,13 +25,14 @@ "symfony/translation": "~2.3||~3.0", "symfony/yaml": "~2.1||~3.0", "symfony/class-loader": "~2.1||~3.0", - "container-interop/container-interop": "^1.1" + "psr/container": "^1.0" }, "require-dev": { "symfony/process": "~2.5|~3.0", "phpunit/phpunit": "~4.5", - "herrera-io/box": "~1.6.1" + "herrera-io/box": "~1.6.1", + "container-interop/container-interop": "^1.2" }, "suggest": { diff --git a/src/Behat/Behat/HelperContainer/Argument/ServicesResolver.php b/src/Behat/Behat/HelperContainer/Argument/ServicesResolver.php index e8d23474d..1031a0587 100644 --- a/src/Behat/Behat/HelperContainer/Argument/ServicesResolver.php +++ b/src/Behat/Behat/HelperContainer/Argument/ServicesResolver.php @@ -11,7 +11,7 @@ namespace Behat\Behat\HelperContainer\Argument; use Behat\Behat\Context\Argument\ArgumentResolver; -use Interop\Container\ContainerInterface; +use Psr\Container\ContainerInterface; use ReflectionClass; /** diff --git a/src/Behat/Behat/HelperContainer/Argument/ServicesResolverFactory.php b/src/Behat/Behat/HelperContainer/Argument/ServicesResolverFactory.php index e5dbfadc5..25617033f 100644 --- a/src/Behat/Behat/HelperContainer/Argument/ServicesResolverFactory.php +++ b/src/Behat/Behat/HelperContainer/Argument/ServicesResolverFactory.php @@ -16,7 +16,7 @@ use Behat\Behat\HelperContainer\Exception\WrongServicesConfigurationException; use Behat\Behat\HelperContainer\ServiceContainer\HelperContainerExtension; use Behat\Testwork\Suite\Suite; -use Interop\Container\ContainerInterface; +use Psr\Container\ContainerInterface; use Symfony\Component\DependencyInjection\TaggedContainerInterface; /** @@ -157,7 +157,7 @@ private function createArgumentResolver($container) if (!$container instanceof ContainerInterface) { throw new WrongContainerClassException( sprintf( - 'Service container is expected to implement `Interop\Container\ContainerInterface`, but `%s` does not.', + 'Service container is expected to implement `Psr\Container\ContainerInterface`, but `%s` does not.', get_class($container) ), get_class($container) diff --git a/src/Behat/Behat/HelperContainer/BuiltInServiceContainer.php b/src/Behat/Behat/HelperContainer/BuiltInServiceContainer.php index 71795ee84..b3aead5e6 100644 --- a/src/Behat/Behat/HelperContainer/BuiltInServiceContainer.php +++ b/src/Behat/Behat/HelperContainer/BuiltInServiceContainer.php @@ -12,7 +12,7 @@ use Behat\Behat\HelperContainer\Exception\ServiceNotFoundException; use Behat\Behat\HelperContainer\Exception\WrongServicesConfigurationException; -use Interop\Container\ContainerInterface; +use Psr\Container\ContainerInterface; use ReflectionClass; use ReflectionMethod; diff --git a/src/Behat/Behat/HelperContainer/Exception/HelperContainerException.php b/src/Behat/Behat/HelperContainer/Exception/HelperContainerException.php index 04ab35f96..317175af3 100644 --- a/src/Behat/Behat/HelperContainer/Exception/HelperContainerException.php +++ b/src/Behat/Behat/HelperContainer/Exception/HelperContainerException.php @@ -11,13 +11,13 @@ namespace Behat\Behat\HelperContainer\Exception; use Behat\Testwork\Environment\Exception\EnvironmentException; -use Interop\Container\Exception\ContainerException; +use Psr\Container\ContainerExceptionInterface; /** * All HelperContainer exceptions implement this interface. * * @author Konstantin Kudryashov */ -interface HelperContainerException extends ContainerException, EnvironmentException +interface HelperContainerException extends ContainerExceptionInterface, EnvironmentException { } diff --git a/src/Behat/Behat/HelperContainer/Exception/ServiceNotFoundException.php b/src/Behat/Behat/HelperContainer/Exception/ServiceNotFoundException.php index 02bd601b7..ba8d5bf15 100644 --- a/src/Behat/Behat/HelperContainer/Exception/ServiceNotFoundException.php +++ b/src/Behat/Behat/HelperContainer/Exception/ServiceNotFoundException.php @@ -10,7 +10,7 @@ namespace Behat\Behat\HelperContainer\Exception; -use Interop\Container\Exception\NotFoundException; +use Psr\Container\NotFoundExceptionInterface; use InvalidArgumentException; /** @@ -18,7 +18,7 @@ * * @author Konstantin Kudryashov */ -final class ServiceNotFoundException extends InvalidArgumentException implements HelperContainerException, NotFoundException +final class ServiceNotFoundException extends InvalidArgumentException implements HelperContainerException, NotFoundExceptionInterface { /** * @var string From 12a5690104dc1232b80aad76e7bdd011dc837335 Mon Sep 17 00:00:00 2001 From: everzet Date: Fri, 30 Jun 2017 08:06:25 +0100 Subject: [PATCH 053/567] Update CHANGES --- CHANGELOG.md | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 85c063c7f..775bfdbff 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,13 @@ The format is based on [Keep a Changelog](http://keepachangelog.com/) and this project adheres to [Semantic Versioning](http://semver.org/). ## [Unreleased] +### Added + * [#1054](https://github.com/Behat/Behat/pull/1054): PSR-11 support + +### Deprecated + * [#1054](https://github.com/Behat/Behat/pull/1054): `Interop\Container` + usage. Upgrade to `1.2` in the interim, but aim to move to `Psr\Container` + as soon as possible. ## [3.3.1] - 2017-05-15 ### Added From 09f941b3999f818c308e5d91b2a5a302ad5e2e34 Mon Sep 17 00:00:00 2001 From: everzet Date: Fri, 30 Jun 2017 08:18:09 +0100 Subject: [PATCH 054/567] Update CHANGELOG --- CHANGELOG.md | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 775bfdbff..535e9a9c4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,12 +6,14 @@ and this project adheres to [Semantic Versioning](http://semver.org/). ## [Unreleased] ### Added - * [#1054](https://github.com/Behat/Behat/pull/1054): PSR-11 support + * [#1054](https://github.com/Behat/Behat/pull/1054): [PSR-11](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-11-container.md) support for helper containers. ### Deprecated - * [#1054](https://github.com/Behat/Behat/pull/1054): `Interop\Container` - usage. Upgrade to `1.2` in the interim, but aim to move to `Psr\Container` - as soon as possible. + * [#1054](https://github.com/Behat/Behat/pull/1054): Deprecated usage + of `Interop\Container`. Versions prior to `1.2` are not supported, but `1.2` + is a non-breaking change. If you depend heavily on `Interop`, upgrade to + `1.2`, which is still supported by helper containers. Aim to migrate to + `Psr` before Behat 4.0 shows up on horizon ## [3.3.1] - 2017-05-15 ### Added From bbdcfb9b4a5adb38e20f212535d3a399ae2829a3 Mon Sep 17 00:00:00 2001 From: everzet Date: Wed, 30 Aug 2017 13:03:59 +0100 Subject: [PATCH 055/567] Specify conflict with container-interop prior v1.2 --- composer.json | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/composer.json b/composer.json index c21bc234c..04aae8e83 100644 --- a/composer.json +++ b/composer.json @@ -28,6 +28,10 @@ "psr/container": "^1.0" }, + "conflict": { + "container-interop/container-interop": "<1.2" + }, + "require-dev": { "symfony/process": "~2.5|~3.0", "phpunit/phpunit": "~4.5", From ebae58a97c062a192dc415c5fe75b779f6eb93a2 Mon Sep 17 00:00:00 2001 From: everzet Date: Wed, 30 Aug 2017 13:37:03 +0100 Subject: [PATCH 056/567] Switch exceptions back to extend from Interop container --- src/Behat/Behat/HelperContainer/BuiltInServiceContainer.php | 2 +- .../HelperContainer/Exception/HelperContainerException.php | 4 ++-- .../HelperContainer/Exception/ServiceNotFoundException.php | 4 ++-- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/src/Behat/Behat/HelperContainer/BuiltInServiceContainer.php b/src/Behat/Behat/HelperContainer/BuiltInServiceContainer.php index b3aead5e6..71795ee84 100644 --- a/src/Behat/Behat/HelperContainer/BuiltInServiceContainer.php +++ b/src/Behat/Behat/HelperContainer/BuiltInServiceContainer.php @@ -12,7 +12,7 @@ use Behat\Behat\HelperContainer\Exception\ServiceNotFoundException; use Behat\Behat\HelperContainer\Exception\WrongServicesConfigurationException; -use Psr\Container\ContainerInterface; +use Interop\Container\ContainerInterface; use ReflectionClass; use ReflectionMethod; diff --git a/src/Behat/Behat/HelperContainer/Exception/HelperContainerException.php b/src/Behat/Behat/HelperContainer/Exception/HelperContainerException.php index 317175af3..04ab35f96 100644 --- a/src/Behat/Behat/HelperContainer/Exception/HelperContainerException.php +++ b/src/Behat/Behat/HelperContainer/Exception/HelperContainerException.php @@ -11,13 +11,13 @@ namespace Behat\Behat\HelperContainer\Exception; use Behat\Testwork\Environment\Exception\EnvironmentException; -use Psr\Container\ContainerExceptionInterface; +use Interop\Container\Exception\ContainerException; /** * All HelperContainer exceptions implement this interface. * * @author Konstantin Kudryashov */ -interface HelperContainerException extends ContainerExceptionInterface, EnvironmentException +interface HelperContainerException extends ContainerException, EnvironmentException { } diff --git a/src/Behat/Behat/HelperContainer/Exception/ServiceNotFoundException.php b/src/Behat/Behat/HelperContainer/Exception/ServiceNotFoundException.php index ba8d5bf15..02bd601b7 100644 --- a/src/Behat/Behat/HelperContainer/Exception/ServiceNotFoundException.php +++ b/src/Behat/Behat/HelperContainer/Exception/ServiceNotFoundException.php @@ -10,7 +10,7 @@ namespace Behat\Behat\HelperContainer\Exception; -use Psr\Container\NotFoundExceptionInterface; +use Interop\Container\Exception\NotFoundException; use InvalidArgumentException; /** @@ -18,7 +18,7 @@ * * @author Konstantin Kudryashov */ -final class ServiceNotFoundException extends InvalidArgumentException implements HelperContainerException, NotFoundExceptionInterface +final class ServiceNotFoundException extends InvalidArgumentException implements HelperContainerException, NotFoundException { /** * @var string From c48c639f0ed0363bddaa5813bf48649e3903339b Mon Sep 17 00:00:00 2001 From: everzet Date: Wed, 30 Aug 2017 13:41:58 +0100 Subject: [PATCH 057/567] Return back the interop-container dependency --- composer.json | 10 +++------- 1 file changed, 3 insertions(+), 7 deletions(-) diff --git a/composer.json b/composer.json index 04aae8e83..b3dbd81f3 100644 --- a/composer.json +++ b/composer.json @@ -25,18 +25,14 @@ "symfony/translation": "~2.3||~3.0", "symfony/yaml": "~2.1||~3.0", "symfony/class-loader": "~2.1||~3.0", - "psr/container": "^1.0" - }, - - "conflict": { - "container-interop/container-interop": "<1.2" + "psr/container": "^1.0", + "container-interop/container-interop": "^1.2" }, "require-dev": { "symfony/process": "~2.5|~3.0", "phpunit/phpunit": "~4.5", - "herrera-io/box": "~1.6.1", - "container-interop/container-interop": "^1.2" + "herrera-io/box": "~1.6.1" }, "suggest": { From 08802b7f2d736b88df339e5411a1c722e92adbe3 Mon Sep 17 00:00:00 2001 From: Glenn McEwan Date: Mon, 3 Jul 2017 14:11:12 +0100 Subject: [PATCH 058/567] Call setBasePath on the Gherkin manager when registering the extension. --- src/Behat/Behat/Gherkin/ServiceContainer/GherkinExtension.php | 1 + 1 file changed, 1 insertion(+) diff --git a/src/Behat/Behat/Gherkin/ServiceContainer/GherkinExtension.php b/src/Behat/Behat/Gherkin/ServiceContainer/GherkinExtension.php index 2b33cd569..3f770aa72 100644 --- a/src/Behat/Behat/Gherkin/ServiceContainer/GherkinExtension.php +++ b/src/Behat/Behat/Gherkin/ServiceContainer/GherkinExtension.php @@ -225,6 +225,7 @@ private function loadDefaultLoaders(ContainerBuilder $container, $cachePath) } $definition->addMethodCall('setCache', array($cacheDefinition)); + $definition->addMethodCall('setBasePath', ['%paths.base%']); $definition->addTag(self::LOADER_TAG, array('priority' => 50)); $container->setDefinition('gherkin.loader.gherkin_file', $definition); } From f3ed04666c7ef307a2ed9c12f9857e323d34b8a5 Mon Sep 17 00:00:00 2001 From: everzet Date: Wed, 30 Aug 2017 16:30:22 +0100 Subject: [PATCH 059/567] Add #1056 to changelog --- CHANGELOG.md | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 535e9a9c4..311ac5b56 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,7 +6,12 @@ and this project adheres to [Semantic Versioning](http://semver.org/). ## [Unreleased] ### Added - * [#1054](https://github.com/Behat/Behat/pull/1054): [PSR-11](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-11-container.md) support for helper containers. + * [#1054](https://github.com/Behat/Behat/pull/1054): [PSR-11](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-11-container.md) + support for helper containers. + +### Fixed + * [#1056](https://github.com/Behat/Behat/pull/1056): Make Gherkin aware of the + base path so it can filter correctly ### Deprecated * [#1054](https://github.com/Behat/Behat/pull/1054): Deprecated usage From 1f4348a1cedbb91ce9d75b55ed61fdbdb8ae0e3f Mon Sep 17 00:00:00 2001 From: everzet Date: Wed, 30 Aug 2017 16:31:50 +0100 Subject: [PATCH 060/567] Wrap long lines --- CHANGELOG.md | 84 ++++++++++++++++++++++++++++++++++------------------ 1 file changed, 56 insertions(+), 28 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 311ac5b56..edb86da55 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -22,66 +22,92 @@ and this project adheres to [Semantic Versioning](http://semver.org/). ## [3.3.1] - 2017-05-15 ### Added - * [#976](https://github.com/Behat/Behat/pull/1001): Add tests to check that snippets treat words containing apostrophes as a single word + * [#976](https://github.com/Behat/Behat/pull/1001): Add tests to check that + snippets treat words containing apostrophes as a single word ### Fixed - * [#993](https://github.com/Behat/Behat/pull/993) Fix mixed arguments organizer not marking typehinted arguments as "defined" - * [#992](https://github.com/Behat/Behat/pull/993) Do not misinterpret first argument as a numbered argument if it is in fact typehinted - * [#1028](https://github.com/Behat/Behat/pull/1028) Parent / Child class argument ambiguity issue with `MixedArgumentResolver` + * [#993](https://github.com/Behat/Behat/pull/993) Fix mixed arguments + organizer not marking typehinted arguments as "defined" + * [#992](https://github.com/Behat/Behat/pull/993) Do not misinterpret first + argument as a numbered argument if it is in fact typehinted + * [#1028](https://github.com/Behat/Behat/pull/1028) Parent / Child class + argument ambiguity issue with `MixedArgumentResolver` ## [3.3.0] - 2016-12-25 ### Added * [#973](https://github.com/Behat/Behat/pull/974): Added helper containers - * [#973](https://github.com/Behat/Behat/pull/974): Added `SuiteScopedResolverFactory` extension point + * [#973](https://github.com/Behat/Behat/pull/974): Added + `SuiteScopedResolverFactory` extension point ### Removed - * Removed php 5.3 from the Travis build matrix. You can consider it official end of support. 5.4 and 5.5 will follow shortly. + * Removed php 5.3 from the Travis build matrix. You can consider it official + end of support. 5.4 and 5.5 will follow shortly. ## [3.2.3] - 2016-12-25 ### Fixed - * [#971](https://github.com/Behat/Behat/pull/971): Added support for suite names with hyphens + * [#971](https://github.com/Behat/Behat/pull/971): Added support for suite + names with hyphens ## [3.2.2] - 2016-11-05 ### Fixed - * [#959](https://github.com/Behat/Behat/issues/959): Fix transformations not sorted properly on different php version + * [#959](https://github.com/Behat/Behat/issues/959): Fix transformations not + sorted properly on different php version ## [3.2.1] - 2016-09-25 ### Changed - * [#955](https://github.com/Behat/Behat/pull/955): `--snippets-for` is not required now as interactive mode is the new default - * [#954](https://github.com/Behat/Behat/pull/954): Stop execution on missing steps when running with `--stop-on-failure` and `--strict` options + * [#955](https://github.com/Behat/Behat/pull/955): `--snippets-for` is not + required now as interactive mode is the new default + * [#954](https://github.com/Behat/Behat/pull/954): Stop execution on missing + steps when running with `--stop-on-failure` and `--strict` options ## [3.2.0] - 2016-09-20 ### Added - * [#910](https://github.com/Behat/Behat/pull/910): Return type based transformations - * [#903](https://github.com/Behat/Behat/pull/903): Multiline step definitions support + * [#910](https://github.com/Behat/Behat/pull/910): Return type based + transformations + * [#903](https://github.com/Behat/Behat/pull/903): Multiline step definitions + support * [#930](https://github.com/Behat/Behat/pull/930): Whole table transformation * [#935](https://github.com/Behat/Behat/pull/935): Narrative filters in suites * [#936](https://github.com/Behat/Behat/pull/936): Debug command - * [#931](https://github.com/Behat/Behat/pull/931): Exception handlers extension point - * [#870](https://github.com/Behat/Behat/pull/870): Added build-related files and folders to .gitattributes - * [#946](https://github.com/Behat/Behat/pull/946): Official full Windows support with CI ([AppVeyor](http://appveyor.com)) on every build + * [#931](https://github.com/Behat/Behat/pull/931): Exception handlers + extension point + * [#870](https://github.com/Behat/Behat/pull/870): Added build-related files + and folders to .gitattributes + * [#946](https://github.com/Behat/Behat/pull/946): Official full Windows + support with CI ([AppVeyor](http://appveyor.com)) on every build ### Changed * [#922](https://github.com/Behat/Behat/pull/922): Snippets generation revamp - * [#920](https://github.com/Behat/Behat/pull/920): More context for pending/failed steps with progress formatter + * [#920](https://github.com/Behat/Behat/pull/920): More context for + pending/failed steps with progress formatter * [#905](https://github.com/Behat/Behat/pull/905): Transformations refactoring - * [#864](https://github.com/Behat/Behat/pull/864): Use only one autoloader if possible - * [#920](https://github.com/Behat/Behat/pull/920): Improve "No specifications found" error message + * [#864](https://github.com/Behat/Behat/pull/864): Use only one autoloader if + possible + * [#920](https://github.com/Behat/Behat/pull/920): Improve "No specifications + found" error message * Refactor changelog to follow [Keep a Changelog](http://keepachangelog.com/) * Refreshed [CONTRIBUTING.md](CONTRIBUTING.md) * Refreshed Scrutinizer config ### Fixed - * [#911](https://github.com/Behat/Behat/pull/911): Fix context isolation for Scenario Outlines - * [#860](https://github.com/Behat/Behat/pull/860): Include basepath in `generateKey` - * [#857](https://github.com/Behat/Behat/pull/857): Only cache failed scenario's for rerun - * [#933](https://github.com/Behat/Behat/pull/933): Save failed runs with suite information - * [#833](https://github.com/Behat/Behat/pull/833): Properly handle interupts on PHP7 - * [#904](https://github.com/Behat/Behat/pull/904): Provide clearer exception message when long token names used - * [#941](https://github.com/Behat/Behat/pull/941): Transformation should be allowed if printable chars are used + * [#911](https://github.com/Behat/Behat/pull/911): Fix context isolation for + Scenario Outlines + * [#860](https://github.com/Behat/Behat/pull/860): Include basepath in + `generateKey` + * [#857](https://github.com/Behat/Behat/pull/857): Only cache failed + scenario's for rerun + * [#933](https://github.com/Behat/Behat/pull/933): Save failed runs with suite + information + * [#833](https://github.com/Behat/Behat/pull/833): Properly handle interupts + on PHP7 + * [#904](https://github.com/Behat/Behat/pull/904): Provide clearer exception + message when long token names used + * [#941](https://github.com/Behat/Behat/pull/941): Transformation should be + allowed if printable chars are used ### Deprecated - * [#922](https://github.com/Behat/Behat/pull/922): `*SnippetAcceptingContext` interfaces + * [#922](https://github.com/Behat/Behat/pull/922): `*SnippetAcceptingContext` + interfaces * [#905](https://github.com/Behat/Behat/pull/905): `RuntimeTransformation` * [#905](https://github.com/Behat/Behat/pull/905): `Transformation::getPattern` * [#920](https://github.com/Behat/Behat/pull/920): `StepStat` @@ -100,7 +126,8 @@ and this project adheres to [Semantic Versioning](http://semver.org/). * Add Japanese translation (thanks @SNakano) * Add romanian translation for formatters (thanks @Chriton) * Add table row transformations (thanks @ciaranmcnulty) - * Add support for negative numbers without surrounding quotes (thanks @ryancookdev) + * Add support for negative numbers without surrounding quotes (thanks + @ryancookdev) * Handle case when non-existent config file is used (thanks @watermanio) * Handle non-default `error_reporting()` * Handle PHP7 errors implementing `Throwable` @@ -114,7 +141,8 @@ and this project adheres to [Semantic Versioning](http://semver.org/). * Allow suite settings with null values to exist (thanks @docteurklein) * Improve "can not generate snippets" message * Improve performance of Turnip parsing (thanks @Sam-Burns) - * Improve the snippet generation by auto-importing needed classes (thanks @stof) + * Improve the snippet generation by auto-importing needed classes (thanks + @stof) ## [3.0.15] - 2015-02-22 ### Changed From bf5ebd4e044588e8335e150e5133ae2e0b5e5dad Mon Sep 17 00:00:00 2001 From: everzet Date: Wed, 30 Aug 2017 16:49:10 +0100 Subject: [PATCH 061/567] Add support for modern phpunit --- CHANGELOG.md | 1 + .../Exception/Stringer/PHPUnitExceptionStringer.php | 11 +++++++---- 2 files changed, 8 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index edb86da55..18ff849a3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,7 @@ and this project adheres to [Semantic Versioning](http://semver.org/). ### Added * [#1054](https://github.com/Behat/Behat/pull/1054): [PSR-11](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-11-container.md) support for helper containers. + * Support for modern PHPUnit. ### Fixed * [#1056](https://github.com/Behat/Behat/pull/1056): Make Gherkin aware of the diff --git a/src/Behat/Testwork/Exception/Stringer/PHPUnitExceptionStringer.php b/src/Behat/Testwork/Exception/Stringer/PHPUnitExceptionStringer.php index 3534924f8..0b06299ef 100644 --- a/src/Behat/Testwork/Exception/Stringer/PHPUnitExceptionStringer.php +++ b/src/Behat/Testwork/Exception/Stringer/PHPUnitExceptionStringer.php @@ -11,8 +11,6 @@ namespace Behat\Testwork\Exception\Stringer; use Exception; -use PHPUnit_Framework_Exception; -use PHPUnit_Framework_TestFailure; /** * Strings PHPUnit assertion exceptions. @@ -28,7 +26,8 @@ final class PHPUnitExceptionStringer implements ExceptionStringer */ public function supportsException(Exception $exception) { - return $exception instanceof PHPUnit_Framework_Exception; + return $exception instanceof \PHPUnit_Framework_Exception + || $exception instanceof \PHPUnit\Framework\Exception; } /** @@ -36,9 +35,13 @@ public function supportsException(Exception $exception) */ public function stringException(Exception $exception, $verbosity) { + if (!class_exists('PHPUnit\\Framework\\TestFailure')) { + return trim(\PHPUnit_Framework_TestFailure::exceptionToString($exception)); + } + // PHPUnit assertion exceptions do not include expected / observed info in their // messages, but expect the test listeners to format that info like the following // (see e.g. PHPUnit_TextUI_ResultPrinter::printDefectTrace) - return trim(PHPUnit_Framework_TestFailure::exceptionToString($exception)); + return trim(\PHPUnit\Framework\TestFailure::exceptionToString($exception)); } } From 905dddc5e7d1bf489c82c473e0b3953b1d4d35e7 Mon Sep 17 00:00:00 2001 From: everzet Date: Wed, 30 Aug 2017 16:55:33 +0100 Subject: [PATCH 062/567] Upgrade internal test suite to modern phpunit --- composer.json | 2 +- features/append_snippets.feature | 48 +++++++-------- features/arguments.feature | 8 +-- features/bootstrap/FeatureContext.php | 31 +++++----- features/config_inheritance.feature | 4 +- features/context.feature | 8 +-- features/definitions_patterns.feature | 58 +++++++++---------- features/definitions_transformations.feature | 12 ++-- features/definitions_translations.feature | 16 ++--- features/error_reporting.feature | 4 +- features/extensions.feature | 2 +- features/format_options.feature | 8 +-- features/helper_containers.feature | 4 +- features/hooks.feature | 2 +- features/i18n.feature | 2 +- features/junit_format.feature | 16 ++--- features/multiple_formats.feature | 8 +-- features/outlines.feature | 4 +- features/parameters.feature | 2 +- features/pretty_format.feature | 6 +- features/profiles.feature | 2 +- features/rerun.feature | 8 +-- features/rerun_with_multiple_suite.feature | 8 +-- features/result_types.feature | 4 +- features/traits.feature | 2 +- .../Subject/GroupedSubjectIteratorTest.php | 3 +- 26 files changed, 137 insertions(+), 135 deletions(-) diff --git a/composer.json b/composer.json index b3dbd81f3..a056e594b 100644 --- a/composer.json +++ b/composer.json @@ -31,7 +31,7 @@ "require-dev": { "symfony/process": "~2.5|~3.0", - "phpunit/phpunit": "~4.5", + "phpunit/phpunit": "~6.3", "herrera-io/box": "~1.6.1" }, diff --git a/features/append_snippets.feature b/features/append_snippets.feature index 8eb9390ec..e1727bdb4 100644 --- a/features/append_snippets.feature +++ b/features/append_snippets.feature @@ -47,22 +47,22 @@ Feature: Append snippets option * @Then /^I should have (\d+) apples$/ */ public function iShouldHaveApples($count) { - \PHPUnit_Framework_Assert::assertEquals(intval($count), $this->apples); + \PHPUnit\Framework\Assert::assertEquals(intval($count), $this->apples); } /** * @Then /^context parameter "([^"]*)" should be equal to "([^"]*)"$/ */ public function contextParameterShouldBeEqualTo($key, $val) { - \PHPUnit_Framework_Assert::assertEquals($val, $this->parameters[$key]); + \PHPUnit\Framework\Assert::assertEquals($val, $this->parameters[$key]); } /** * @Given /^context parameter "([^"]*)" should be array with (\d+) elements$/ */ public function contextParameterShouldBeArrayWithElements($key, $count) { - \PHPUnit_Framework_Assert::assertInternalType('array', $this->parameters[$key]); - \PHPUnit_Framework_Assert::assertEquals(2, count($this->parameters[$key])); + \PHPUnit\Framework\Assert::assertInternalType('array', $this->parameters[$key]); + \PHPUnit\Framework\Assert::assertEquals(2, count($this->parameters[$key])); } private function doSomethingUndefinedWith() {} @@ -162,22 +162,22 @@ Feature: Append snippets option * @Then /^I should have (\d+) apples$/ */ public function iShouldHaveApples($count) { - \PHPUnit_Framework_Assert::assertEquals(intval($count), $this->apples); + \PHPUnit\Framework\Assert::assertEquals(intval($count), $this->apples); } /** * @Then /^context parameter "([^"]*)" should be equal to "([^"]*)"$/ */ public function contextParameterShouldBeEqualTo($key, $val) { - \PHPUnit_Framework_Assert::assertEquals($val, $this->parameters[$key]); + \PHPUnit\Framework\Assert::assertEquals($val, $this->parameters[$key]); } /** * @Given /^context parameter "([^"]*)" should be array with (\d+) elements$/ */ public function contextParameterShouldBeArrayWithElements($key, $count) { - \PHPUnit_Framework_Assert::assertInternalType('array', $this->parameters[$key]); - \PHPUnit_Framework_Assert::assertEquals(2, count($this->parameters[$key])); + \PHPUnit\Framework\Assert::assertInternalType('array', $this->parameters[$key]); + \PHPUnit\Framework\Assert::assertEquals(2, count($this->parameters[$key])); } private function doSomethingUndefinedWith() {} @@ -267,22 +267,22 @@ Feature: Append snippets option * @Then /^I should have (\d+) apples$/ */ public function iShouldHaveApples($count) { - \PHPUnit_Framework_Assert::assertEquals(intval($count), $this->apples); + \PHPUnit\Framework\Assert::assertEquals(intval($count), $this->apples); } /** * @Then /^context parameter "([^"]*)" should be equal to "([^"]*)"$/ */ public function contextParameterShouldBeEqualTo($key, $val) { - \PHPUnit_Framework_Assert::assertEquals($val, $this->parameters[$key]); + \PHPUnit\Framework\Assert::assertEquals($val, $this->parameters[$key]); } /** * @Given /^context parameter "([^"]*)" should be array with (\d+) elements$/ */ public function contextParameterShouldBeArrayWithElements($key, $count) { - \PHPUnit_Framework_Assert::assertInternalType('array', $this->parameters[$key]); - \PHPUnit_Framework_Assert::assertEquals(2, count($this->parameters[$key])); + \PHPUnit\Framework\Assert::assertInternalType('array', $this->parameters[$key]); + \PHPUnit\Framework\Assert::assertEquals(2, count($this->parameters[$key])); } private function doSomethingUndefinedWith() {} @@ -332,22 +332,22 @@ Feature: Append snippets option * @Then /^I should have (\d+) apples$/ */ public function iShouldHaveApples($count) { - \PHPUnit_Framework_Assert::assertEquals(intval($count), $this->apples); + \PHPUnit\Framework\Assert::assertEquals(intval($count), $this->apples); } /** * @Then /^context parameter "([^"]*)" should be equal to "([^"]*)"$/ */ public function contextParameterShouldBeEqualTo($key, $val) { - \PHPUnit_Framework_Assert::assertEquals($val, $this->parameters[$key]); + \PHPUnit\Framework\Assert::assertEquals($val, $this->parameters[$key]); } /** * @Given /^context parameter "([^"]*)" should be array with (\d+) elements$/ */ public function contextParameterShouldBeArrayWithElements($key, $count) { - \PHPUnit_Framework_Assert::assertInternalType('array', $this->parameters[$key]); - \PHPUnit_Framework_Assert::assertEquals(2, count($this->parameters[$key])); + \PHPUnit\Framework\Assert::assertInternalType('array', $this->parameters[$key]); + \PHPUnit\Framework\Assert::assertEquals(2, count($this->parameters[$key])); } private function doSomethingUndefinedWith() {} @@ -435,22 +435,22 @@ Feature: Append snippets option * @Then /^I should have (\d+) apples$/ */ public function iShouldHaveApples($count) { - \PHPUnit_Framework_Assert::assertEquals(intval($count), $this->apples); + \PHPUnit\Framework\Assert::assertEquals(intval($count), $this->apples); } /** * @Then /^context parameter "([^"]*)" should be equal to "([^"]*)"$/ */ public function contextParameterShouldBeEqualTo($key, $val) { - \PHPUnit_Framework_Assert::assertEquals($val, $this->parameters[$key]); + \PHPUnit\Framework\Assert::assertEquals($val, $this->parameters[$key]); } /** * @Given /^context parameter "([^"]*)" should be array with (\d+) elements$/ */ public function contextParameterShouldBeArrayWithElements($key, $count) { - \PHPUnit_Framework_Assert::assertInternalType('array', $this->parameters[$key]); - \PHPUnit_Framework_Assert::assertEquals(2, count($this->parameters[$key])); + \PHPUnit\Framework\Assert::assertInternalType('array', $this->parameters[$key]); + \PHPUnit\Framework\Assert::assertEquals(2, count($this->parameters[$key])); } private function doSomethingUndefinedWith() {} @@ -500,22 +500,22 @@ Feature: Append snippets option * @Then /^I should have (\d+) apples$/ */ public function iShouldHaveApples($count) { - \PHPUnit_Framework_Assert::assertEquals(intval($count), $this->apples); + \PHPUnit\Framework\Assert::assertEquals(intval($count), $this->apples); } /** * @Then /^context parameter "([^"]*)" should be equal to "([^"]*)"$/ */ public function contextParameterShouldBeEqualTo($key, $val) { - \PHPUnit_Framework_Assert::assertEquals($val, $this->parameters[$key]); + \PHPUnit\Framework\Assert::assertEquals($val, $this->parameters[$key]); } /** * @Given /^context parameter "([^"]*)" should be array with (\d+) elements$/ */ public function contextParameterShouldBeArrayWithElements($key, $count) { - \PHPUnit_Framework_Assert::assertInternalType('array', $this->parameters[$key]); - \PHPUnit_Framework_Assert::assertEquals(2, count($this->parameters[$key])); + \PHPUnit\Framework\Assert::assertInternalType('array', $this->parameters[$key]); + \PHPUnit\Framework\Assert::assertEquals(2, count($this->parameters[$key])); } private function doSomethingUndefinedWith() {} diff --git a/features/arguments.feature b/features/arguments.feature index 6da60915a..161a18111 100644 --- a/features/arguments.feature +++ b/features/arguments.feature @@ -44,22 +44,22 @@ Feature: Step Arguments * @Then /^it must be equals to string (\d+)$/ */ public function itMustBeEqualsToString($number) { - \PHPUnit_Framework_Assert::assertEquals($this->strings[intval($number)], (string) $this->input); + \PHPUnit\Framework\Assert::assertEquals($this->strings[intval($number)], (string) $this->input); } /** * @Then /^it must be equals to table (\d+)$/ */ public function itMustBeEqualsToTable($number) { - \PHPUnit_Framework_Assert::assertEquals($this->tables[intval($number)], $this->input->getHash()); + \PHPUnit\Framework\Assert::assertEquals($this->tables[intval($number)], $this->input->getHash()); } /** * @Given /^I have number2 = (?P\d+) and number1 = (?P\d+)$/ */ public function iHaveNumberAndNumber($number1, $number2) { - \PHPUnit_Framework_Assert::assertEquals(13, intval($number1)); - \PHPUnit_Framework_Assert::assertEquals(243, intval($number2)); + \PHPUnit\Framework\Assert::assertEquals(13, intval($number1)); + \PHPUnit\Framework\Assert::assertEquals(243, intval($number2)); } } """ diff --git a/features/bootstrap/FeatureContext.php b/features/bootstrap/FeatureContext.php index 629c6fc21..11905b956 100644 --- a/features/bootstrap/FeatureContext.php +++ b/features/bootstrap/FeatureContext.php @@ -10,6 +10,7 @@ use Behat\Behat\Context\Context; use Behat\Gherkin\Node\PyStringNode; +use PHPUnit\Framework\Assert; use Symfony\Component\Process\PhpExecutableFinder; use Symfony\Component\Process\Process; @@ -119,12 +120,12 @@ class FeatureContext implements Context $this->createFile($this->workingDir . '/' . $filename, $content); } - /** - * Creates a noop feature in current workdir. - * - * @Given /^(?:there is )?a some feature scenarios/ - */ - public function aNoopFeature() + /** + * Creates a noop feature in current workdir. + * + * @Given /^(?:there is )?a some feature scenarios/ + */ + public function aNoopFeature() { $filename = 'features/bootstrap/FeatureContext.php'; $content = <<<'EOL' @@ -156,7 +157,7 @@ public function iAmInThePath($path) */ public function fileShouldExist($path) { - PHPUnit_Framework_Assert::assertFileExists($this->workingDir . DIRECTORY_SEPARATOR . $path); + Assert::assertFileExists($this->workingDir . DIRECTORY_SEPARATOR . $path); } /** @@ -258,7 +259,7 @@ public function itShouldPassWith($success, PyStringNode $text) public function itShouldPassWithNoOutput($success) { $this->itShouldFail($success); - PHPUnit_Framework_Assert::assertEmpty($this->getOutput()); + Assert::assertEmpty($this->getOutput()); } /** @@ -272,7 +273,7 @@ public function itShouldPassWithNoOutput($success) public function fileShouldContain($path, PyStringNode $text) { $path = $this->workingDir . '/' . $path; - PHPUnit_Framework_Assert::assertFileExists($path); + Assert::assertFileExists($path); $fileContent = trim(file_get_contents($path)); // Normalize the line endings in the output @@ -280,7 +281,7 @@ public function fileShouldContain($path, PyStringNode $text) $fileContent = str_replace(PHP_EOL, "\n", $fileContent); } - PHPUnit_Framework_Assert::assertEquals($this->getExpectedOutput($text), $fileContent); + Assert::assertEquals($this->getExpectedOutput($text), $fileContent); } /** @@ -294,7 +295,7 @@ public function fileShouldContain($path, PyStringNode $text) public function fileXmlShouldBeLike($path, PyStringNode $text) { $path = $this->workingDir . '/' . $path; - PHPUnit_Framework_Assert::assertFileExists($path); + Assert::assertFileExists($path); $fileContent = trim(file_get_contents($path)); @@ -302,7 +303,7 @@ public function fileXmlShouldBeLike($path, PyStringNode $text) $dom->loadXML($text); $dom->formatOutput = true; - PHPUnit_Framework_Assert::assertEquals(trim($dom->saveXML(null, LIBXML_NOEMPTYTAG)), $fileContent); + Assert::assertEquals(trim($dom->saveXML(null, LIBXML_NOEMPTYTAG)), $fileContent); } @@ -315,7 +316,7 @@ public function fileXmlShouldBeLike($path, PyStringNode $text) */ public function theOutputShouldContain(PyStringNode $text) { - PHPUnit_Framework_Assert::assertContains($this->getExpectedOutput($text), $this->getOutput()); + Assert::assertContains($this->getExpectedOutput($text), $this->getOutput()); } private function getExpectedOutput(PyStringNode $expectedText) @@ -363,13 +364,13 @@ public function itShouldFail($success) echo 'Actual output:' . PHP_EOL . PHP_EOL . $this->getOutput(); } - PHPUnit_Framework_Assert::assertNotEquals(0, $this->getExitCode()); + Assert::assertNotEquals(0, $this->getExitCode()); } else { if (0 !== $this->getExitCode()) { echo 'Actual output:' . PHP_EOL . PHP_EOL . $this->getOutput(); } - PHPUnit_Framework_Assert::assertEquals(0, $this->getExitCode()); + Assert::assertEquals(0, $this->getExitCode()); } } diff --git a/features/config_inheritance.feature b/features/config_inheritance.feature index c418ad404..16d6cb5e6 100644 --- a/features/config_inheritance.feature +++ b/features/config_inheritance.feature @@ -73,12 +73,12 @@ Feature: Config inheritance /** @Then the context parameters should be overwritten */ public function theContextParametersOverwrite() { - \PHPUnit_Framework_Assert::assertEquals(array('param2' => 'val2'), $this->parameters); + \PHPUnit\Framework\Assert::assertEquals(array('param2' => 'val2'), $this->parameters); } /** @Then the extension config should be merged */ public function theExtensionConfigMerge() { - \PHPUnit_Framework_Assert::assertEquals(array('param1' => 'val2', 'param2' => 'val1'), $this->extension); + \PHPUnit\Framework\Assert::assertEquals(array('param1' => 'val2', 'param2' => 'val1'), $this->extension); } } """ diff --git a/features/context.feature b/features/context.feature index e96118009..eae21a44a 100644 --- a/features/context.feature +++ b/features/context.feature @@ -47,22 +47,22 @@ Feature: Context consistency * @Then /^I should have (\d+) apples$/ */ public function iShouldHaveApples($count) { - PHPUnit_Framework_Assert::assertEquals(intval($count), $this->apples); + PHPUnit\Framework\Assert::assertEquals(intval($count), $this->apples); } /** * @Then /^context parameter "([^"]*)" should be equal to "([^"]*)"$/ */ public function contextParameterShouldBeEqualTo($key, $val) { - PHPUnit_Framework_Assert::assertEquals($val, $this->parameters[$key]); + PHPUnit\Framework\Assert::assertEquals($val, $this->parameters[$key]); } /** * @Given /^context parameter "([^"]*)" should be array with (\d+) elements$/ */ public function contextParameterShouldBeArrayWithElements($key, $count) { - PHPUnit_Framework_Assert::assertInternalType('array', $this->parameters[$key]); - PHPUnit_Framework_Assert::assertEquals(2, count($this->parameters[$key])); + PHPUnit\Framework\Assert::assertInternalType('array', $this->parameters[$key]); + PHPUnit\Framework\Assert::assertEquals(2, count($this->parameters[$key])); } } diff --git a/features/definitions_patterns.feature b/features/definitions_patterns.feature index 66d4d553f..66eeb73d2 100644 --- a/features/definitions_patterns.feature +++ b/features/definitions_patterns.feature @@ -158,8 +158,8 @@ Feature: Step Definition Pattern * @Given only second :second */ public function invalidRegex($first = 'foo', $second = 'fiz') { - PHPUnit_Framework_Assert::assertEquals('foo', $first); - PHPUnit_Framework_Assert::assertEquals('bar', $second); + PHPUnit\Framework\Assert::assertEquals('foo', $first); + PHPUnit\Framework\Assert::assertEquals('bar', $second); } } """ @@ -192,7 +192,7 @@ Feature: Step Definition Pattern * @Given I can provide parameter :param */ public function parameterCouldBeNull($param = null) { - PHPUnit_Framework_Assert::assertNull($param); + PHPUnit\Framework\Assert::assertNull($param); } } """ @@ -256,7 +256,7 @@ Feature: Step Definition Pattern * parameter :param */ public function parameterCouldBeNull($param = null) { - PHPUnit_Framework_Assert::assertNull($param); + PHPUnit\Framework\Assert::assertNull($param); } } """ @@ -295,8 +295,8 @@ Feature: Step Definition Pattern * @Given I can provide parameters :someParam and :someParam2 */ public function multipleWrongNamedParameters($param1, $param2) { - PHPUnit_Framework_Assert::assertEquals('one', $param1); - PHPUnit_Framework_Assert::assertEquals('two', $param2); + PHPUnit\Framework\Assert::assertEquals('one', $param1); + PHPUnit\Framework\Assert::assertEquals('two', $param2); } } """ @@ -328,8 +328,8 @@ Feature: Step Definition Pattern * @Given I can provide parameters :someParam and :someParam2 */ public function multipleWrongNamedParameters($param1, $someParam) { - PHPUnit_Framework_Assert::assertEquals('two', $param1); - PHPUnit_Framework_Assert::assertEquals('one', $someParam); + PHPUnit\Framework\Assert::assertEquals('two', $param1); + PHPUnit\Framework\Assert::assertEquals('one', $someParam); } } """ @@ -361,9 +361,9 @@ Feature: Step Definition Pattern * @Given I can provide :count parameters :firstParam and :otherParam */ public function multipleWrongNamedParameters($param1, $firstParam, $count) { - PHPUnit_Framework_Assert::assertEquals('two', $param1); - PHPUnit_Framework_Assert::assertEquals('one', $firstParam); - PHPUnit_Framework_Assert::assertEquals(2, $count); + PHPUnit\Framework\Assert::assertEquals('two', $param1); + PHPUnit\Framework\Assert::assertEquals('one', $firstParam); + PHPUnit\Framework\Assert::assertEquals(2, $count); } } """ @@ -395,10 +395,10 @@ Feature: Step Definition Pattern * @Given I can provide :count parameters :firstParam and :otherParam with: */ public function multipleWrongNamedParameters($param1, $firstParam, $count, $string) { - PHPUnit_Framework_Assert::assertEquals('two', $param1); - PHPUnit_Framework_Assert::assertEquals('one', $firstParam); - PHPUnit_Framework_Assert::assertEquals(2, $count); - PHPUnit_Framework_Assert::assertEquals("Test", (string) $string); + PHPUnit\Framework\Assert::assertEquals('two', $param1); + PHPUnit\Framework\Assert::assertEquals('one', $firstParam); + PHPUnit\Framework\Assert::assertEquals(2, $count); + PHPUnit\Framework\Assert::assertEquals("Test", (string) $string); } } """ @@ -433,9 +433,9 @@ Feature: Step Definition Pattern * @Given I can provide :count parameters for :name: */ public function multipleWrongNamedParameters($count, $name, $string) { - PHPUnit_Framework_Assert::assertEquals('2', $count); - PHPUnit_Framework_Assert::assertEquals('thing', $name); - PHPUnit_Framework_Assert::assertEquals("Test", (string) $string); + PHPUnit\Framework\Assert::assertEquals('2', $count); + PHPUnit\Framework\Assert::assertEquals('thing', $name); + PHPUnit\Framework\Assert::assertEquals("Test", (string) $string); } } """ @@ -472,9 +472,9 @@ Feature: Step Definition Pattern */ public function checkEquality($path = null, $isNegative = null, PyStringNode $json = null) { - PHPUnit_Framework_Assert::assertNull($path); - PHPUnit_Framework_Assert::assertNull($isNegative); - PHPUnit_Framework_Assert::assertNotNull($json); + PHPUnit\Framework\Assert::assertNull($path); + PHPUnit\Framework\Assert::assertNull($isNegative); + PHPUnit\Framework\Assert::assertNotNull($json); } /** @@ -482,9 +482,9 @@ Feature: Step Definition Pattern */ public function checkEquality2($json = null, $path = null, $isNegative = null) { - PHPUnit_Framework_Assert::assertNull($path); - PHPUnit_Framework_Assert::assertNull($isNegative); - PHPUnit_Framework_Assert::assertNotNull($json); + PHPUnit\Framework\Assert::assertNull($path); + PHPUnit\Framework\Assert::assertNull($isNegative); + PHPUnit\Framework\Assert::assertNotNull($json); } } """ @@ -523,7 +523,7 @@ Feature: Step Definition Pattern * @Given I have a package v:version */ public function multipleWrongNamedParameters($version) { - PHPUnit_Framework_Assert::assertEquals('2.5', $version); + PHPUnit\Framework\Assert::assertEquals('2.5', $version); } } """ @@ -555,7 +555,7 @@ Feature: Step Definition Pattern * @When I enter the string :input */ public function multipleWrongNamedParameters($input) { - PHPUnit_Framework_Assert::assertEquals('', $input); + PHPUnit\Framework\Assert::assertEquals('', $input); } } """ @@ -587,8 +587,8 @@ Feature: Step Definition Pattern * @Then images should be uploaded to web\/uploads\/media\/default\/:arg1\/:arg2\/ */ public function multipleWrongNamedParameters($arg1, $arg2) { - PHPUnit_Framework_Assert::assertEquals('0001', $arg1); - PHPUnit_Framework_Assert::assertEquals('01', $arg2); + PHPUnit\Framework\Assert::assertEquals('0001', $arg1); + PHPUnit\Framework\Assert::assertEquals('01', $arg2); } } """ @@ -620,7 +620,7 @@ Feature: Step Definition Pattern * @Given I have a negative number :num */ public function multipleWrongNamedParameters($num) { - PHPUnit_Framework_Assert::assertEquals('-3', $num); + PHPUnit\Framework\Assert::assertEquals('-3', $num); } } """ diff --git a/features/definitions_transformations.feature b/features/definitions_transformations.feature index ff986a4ce..92c4e6f25 100644 --- a/features/definitions_transformations.feature +++ b/features/definitions_transformations.feature @@ -117,29 +117,29 @@ Feature: Step Arguments Transformations * @Then /Username must be "([^"]+)"/ */ public function usernameMustBe($username) { - PHPUnit_Framework_Assert::assertEquals($username, $this->user->getUsername()); + PHPUnit\Framework\Assert::assertEquals($username, $this->user->getUsername()); } /** * @Then /Age must be (\d+)/ */ public function ageMustBe($age) { - PHPUnit_Framework_Assert::assertEquals($age, $this->user->getAge()); - PHPUnit_Framework_Assert::assertInternalType('int', $age); + PHPUnit\Framework\Assert::assertEquals($age, $this->user->getAge()); + PHPUnit\Framework\Assert::assertInternalType('int', $age); } /** * @Then the Usernames must be: */ public function usernamesMustBe(array $usernames) { - PHPUnit_Framework_Assert::assertEquals($usernames[0], $this->user->getUsername()); + PHPUnit\Framework\Assert::assertEquals($usernames[0], $this->user->getUsername()); } /** * @Then /^the boolean (no) should be transformed to false$/ */ public function theBooleanShouldBeTransformed($boolean) { - PHPUnit_Framework_Assert::assertSame(false, $boolean); + PHPUnit\Framework\Assert::assertSame(false, $boolean); } } """ @@ -289,7 +289,7 @@ Feature: Step Arguments Transformations /** @Then the :field should be :value */ public function theFieldShouldBe($field, $value) { - PHPUnit_Framework_Assert::assertSame($value, $this->data[0][$field]); + PHPUnit\Framework\Assert::assertSame($value, $this->data[0][$field]); } } """ diff --git a/features/definitions_translations.feature b/features/definitions_translations.feature index df41e942f..c3ace9d05 100644 --- a/features/definitions_translations.feature +++ b/features/definitions_translations.feature @@ -47,7 +47,7 @@ Feature: Definitions translations * @Then /^I should see (\d+) on the screen$/ */ public function iShouldSeeOnTheScreen($result) { - PHPUnit_Framework_Assert::assertEquals(intval($result), $this->result); + PHPUnit\Framework\Assert::assertEquals(intval($result), $this->result); } /** @Transform /"([^"]+)" user/ */ @@ -59,7 +59,7 @@ Feature: Definitions translations * @Then /^the ("[^"]+" user) name should be "([^"]*)"$/ */ public function theUserUsername($user, $username) { - PHPUnit_Framework_Assert::assertEquals($username, $user->name); + PHPUnit\Framework\Assert::assertEquals($username, $user->name); } public static function getTranslationResources() { @@ -150,7 +150,7 @@ Feature: Definitions translations * @Then /^I should see (\d+) on the screen$/ */ public function iShouldSeeOnTheScreen($result) { - PHPUnit_Framework_Assert::assertEquals(intval($result), $this->result); + PHPUnit\Framework\Assert::assertEquals(intval($result), $this->result); } /** @Transform /"([^"]+)" user/ */ @@ -162,7 +162,7 @@ Feature: Definitions translations * @Then /^the ("[^"]+" user) name should be "([^"]*)"$/ */ public function theUserUsername($user, $username) { - PHPUnit_Framework_Assert::assertEquals($username, $user->name); + PHPUnit\Framework\Assert::assertEquals($username, $user->name); } public static function getTranslationResources() { @@ -231,7 +231,7 @@ Feature: Definitions translations * @Then /^I should see (\d+) on the screen$/ */ public function iShouldSeeOnTheScreen($result) { - PHPUnit_Framework_Assert::assertEquals(intval($result), $this->result); + PHPUnit\Framework\Assert::assertEquals(intval($result), $this->result); } /** @Transform /"([^"]+)" user/ */ @@ -243,7 +243,7 @@ Feature: Definitions translations * @Then /^the ("[^"]+" user) name should be "([^"]*)"$/ */ public function theUserUsername($user, $username) { - PHPUnit_Framework_Assert::assertEquals($username, $user->name); + PHPUnit\Framework\Assert::assertEquals($username, $user->name); } public static function getTranslationResources() { @@ -321,7 +321,7 @@ Feature: Definitions translations * @Then /^I should see (\d+) on the screen$/ */ public function iShouldSeeOnTheScreen($result) { - PHPUnit_Framework_Assert::assertEquals(intval($result), $this->result); + PHPUnit\Framework\Assert::assertEquals(intval($result), $this->result); } /** @Transform /"([^"]+)" user/ */ @@ -333,7 +333,7 @@ Feature: Definitions translations * @Then /^the ("[^"]+" user) name should be "([^"]*)"$/ */ public function theUserUsername($user, $username) { - PHPUnit_Framework_Assert::assertEquals($username, $user->name); + PHPUnit\Framework\Assert::assertEquals($username, $user->name); } public static function getTranslationResources() { diff --git a/features/error_reporting.feature b/features/error_reporting.feature index c3b859479..1139b48bc 100644 --- a/features/error_reporting.feature +++ b/features/error_reporting.feature @@ -37,7 +37,7 @@ Feature: Error Reporting */ public function iShouldGetNull() { - PHPUnit_Framework_Assert::assertNull($this->result); + PHPUnit\Framework\Assert::assertNull($this->result); } /** @@ -53,7 +53,7 @@ Feature: Error Reporting */ public function iShouldGet($arg1) { - PHPUnit_Framework_Assert::assertEquals($arg1, $this->result); + PHPUnit\Framework\Assert::assertEquals($arg1, $this->result); } } diff --git a/features/extensions.feature b/features/extensions.feature index 5fb9de911..9d5bd2f3f 100644 --- a/features/extensions.feature +++ b/features/extensions.feature @@ -31,7 +31,7 @@ Feature: Extensions /** @Then the extension should be loaded */ public function theExtensionLoaded() { - PHPUnit_Framework_Assert::assertEquals(array('param1' => 'val1', 'param2' => 'val2'), $this->extension); + PHPUnit\Framework\Assert::assertEquals(array('param1' => 'val1', 'param2' => 'val2'), $this->extension); } } """ diff --git a/features/format_options.feature b/features/format_options.feature index ce773fa0b..f523e42c9 100644 --- a/features/format_options.feature +++ b/features/format_options.feature @@ -47,22 +47,22 @@ Feature: Format options * @Then /^I should have (\d+) apples$/ */ public function iShouldHaveApples($count) { - PHPUnit_Framework_Assert::assertEquals(intval($count), $this->apples); + PHPUnit\Framework\Assert::assertEquals(intval($count), $this->apples); } /** * @Then /^context parameter "([^"]*)" should be equal to "([^"]*)"$/ */ public function contextParameterShouldBeEqualTo($key, $val) { - PHPUnit_Framework_Assert::assertEquals($val, $this->parameters[$key]); + PHPUnit\Framework\Assert::assertEquals($val, $this->parameters[$key]); } /** * @Given /^context parameter "([^"]*)" should be array with (\d+) elements$/ */ public function contextParameterShouldBeArrayWithElements($key, $count) { - PHPUnit_Framework_Assert::assertInternalType('array', $this->parameters[$key]); - PHPUnit_Framework_Assert::assertEquals(2, count($this->parameters[$key])); + PHPUnit\Framework\Assert::assertInternalType('array', $this->parameters[$key]); + PHPUnit\Framework\Assert::assertEquals(2, count($this->parameters[$key])); } } """ diff --git a/features/helper_containers.feature b/features/helper_containers.feature index 934a6bbf9..ce6bd6bb9 100644 --- a/features/helper_containers.feature +++ b/features/helper_containers.feature @@ -47,7 +47,7 @@ Feature: Per-suite helper containers /** @Given service has no state */ public function noState() { - PHPUnit_Framework_Assert::assertNull($this->service->number); + PHPUnit\Framework\Assert::assertNull($this->service->number); } /** @When service gets a state of :number in first context */ @@ -67,7 +67,7 @@ Feature: Per-suite helper containers /** @Then service should have a state of :number in second context */ public function checkState($number) { - PHPUnit_Framework_Assert::assertSame($number, $this->service->number); + PHPUnit\Framework\Assert::assertSame($number, $this->service->number); } } """ diff --git a/features/hooks.feature b/features/hooks.feature index 557969e4e..20066b000 100644 --- a/features/hooks.feature +++ b/features/hooks.feature @@ -101,7 +101,7 @@ Feature: hooks * @Then /^I must have (\d+)$/ */ public function iMustHave($number) { - \PHPUnit_Framework_Assert::assertEquals(intval($number), $this->number); + \PHPUnit\Framework\Assert::assertEquals(intval($number), $this->number); } } """ diff --git a/features/i18n.feature b/features/i18n.feature index b130b82e2..1856d204f 100644 --- a/features/i18n.feature +++ b/features/i18n.feature @@ -28,7 +28,7 @@ Feature: I18n * @Then /Я должен иметь (\d+)/ */ public function iShouldHave($number) { - PHPUnit_Framework_Assert::assertEquals(intval($number), $this->value); + PHPUnit\Framework\Assert::assertEquals(intval($number), $this->value); } /** diff --git a/features/junit_format.feature b/features/junit_format.feature index f9e4bfd88..180cd5a27 100644 --- a/features/junit_format.feature +++ b/features/junit_format.feature @@ -26,7 +26,7 @@ * @Then /I must have (\d+)/ */ public function iMustHave($num) { - PHPUnit_Framework_Assert::assertEquals($num, $this->value); + PHPUnit\Framework\Assert::assertEquals($num, $this->value); } /** @@ -151,7 +151,7 @@ * @Then /I must have (\d+)/ */ public function iMustHave($num) { - PHPUnit_Framework_Assert::assertEquals($num, $this->value); + PHPUnit\Framework\Assert::assertEquals($num, $this->value); } /** @@ -223,7 +223,7 @@ * @Then /I must have (\d+)/ */ public function iMustHave($num) { - PHPUnit_Framework_Assert::assertEquals($num, $this->value); + PHPUnit\Framework\Assert::assertEquals($num, $this->value); } /** @@ -303,7 +303,7 @@ * @Then /I will be stronger/ */ public function iWillBeStronger() { - PHPUnit_Framework_Assert::assertNotEquals(0, $this->strongLevel); + PHPUnit\Framework\Assert::assertNotEquals(0, $this->strongLevel); } } """ @@ -333,7 +333,7 @@ * @Then /I will be stronger/ */ public function iWillBeStronger() { - PHPUnit_Framework_Assert::assertNotEquals(0, $this->strongLevel); + PHPUnit\Framework\Assert::assertNotEquals(0, $this->strongLevel); } } """ @@ -486,7 +486,7 @@ * @Then /I must have (\d+)/ */ public function iMustHave($num) { - PHPUnit_Framework_Assert::assertEquals($num, $this->value); + PHPUnit\Framework\Assert::assertEquals($num, $this->value); } /** @@ -550,7 +550,7 @@ * @Then /I must have (\d+)/ */ public function iMustHave($num) { - PHPUnit_Framework_Assert::assertEqual($num, $this->value); + PHPUnit\Framework\Assert::assertEqual($num, $this->value); } /** @@ -578,7 +578,7 @@ When I run "behat --no-colors -f junit -o junit" Then it should fail with: """ - Call to undefined method PHPUnit_Framework_Assert::assertEqual + Call to undefined method PHPUnit\Framework\Assert::assertEqual """ And "junit/default.xml" file xml should be like: """ diff --git a/features/multiple_formats.feature b/features/multiple_formats.feature index 1ef068178..ecbb2605c 100644 --- a/features/multiple_formats.feature +++ b/features/multiple_formats.feature @@ -47,22 +47,22 @@ Feature: Multiple formats * @Then /^I should have (\d+) apples$/ */ public function iShouldHaveApples($count) { - PHPUnit_Framework_Assert::assertEquals(intval($count), $this->apples); + PHPUnit\Framework\Assert::assertEquals(intval($count), $this->apples); } /** * @Then /^context parameter "([^"]*)" should be equal to "([^"]*)"$/ */ public function contextParameterShouldBeEqualTo($key, $val) { - PHPUnit_Framework_Assert::assertEquals($val, $this->parameters[$key]); + PHPUnit\Framework\Assert::assertEquals($val, $this->parameters[$key]); } /** * @Given /^context parameter "([^"]*)" should be array with (\d+) elements$/ */ public function contextParameterShouldBeArrayWithElements($key, $count) { - PHPUnit_Framework_Assert::assertInternalType('array', $this->parameters[$key]); - PHPUnit_Framework_Assert::assertEquals(2, count($this->parameters[$key])); + PHPUnit\Framework\Assert::assertInternalType('array', $this->parameters[$key]); + PHPUnit\Framework\Assert::assertEquals(2, count($this->parameters[$key])); } } """ diff --git a/features/outlines.feature b/features/outlines.feature index 148f9ab7c..352fca98c 100644 --- a/features/outlines.feature +++ b/features/outlines.feature @@ -80,7 +80,7 @@ Feature: Scenario Outlines * @Then /^The result should be (\d+)$/ */ public function theResultShouldBe($result) { - PHPUnit_Framework_Assert::assertEquals(intval($result), $this->result); + PHPUnit\Framework\Assert::assertEquals(intval($result), $this->result); } } """ @@ -242,7 +242,7 @@ Feature: Scenario Outlines * @Then the result should be :result */ public function theResultShouldBe($result) { - PHPUnit_Framework_Assert::assertEquals(intval($result), $this->number); + PHPUnit\Framework\Assert::assertEquals(intval($result), $this->number); } } """ diff --git a/features/parameters.feature b/features/parameters.feature index b60550dcc..784c542ac 100644 --- a/features/parameters.feature +++ b/features/parameters.feature @@ -53,7 +53,7 @@ Feature: Parameters * @Then /The result should be (\d+)/ */ public function theResultShouldBe($result) { - PHPUnit_Framework_Assert::assertEquals($result, $this->result); + PHPUnit\Framework\Assert::assertEquals($result, $this->result); } } """ diff --git a/features/pretty_format.feature b/features/pretty_format.feature index 1bfa914ca..6f7a575ee 100644 --- a/features/pretty_format.feature +++ b/features/pretty_format.feature @@ -28,7 +28,7 @@ Feature: Pretty Formatter * @Then /I must have (\d+)/ */ public function iMustHave($num) { - PHPUnit_Framework_Assert::assertEquals($num, $this->value); + PHPUnit\Framework\Assert::assertEquals($num, $this->value); } /** @@ -163,7 +163,7 @@ Feature: Pretty Formatter * @Then /I must have (\d+)/ */ public function iMustHave($num) { - PHPUnit_Framework_Assert::assertEquals($num, $this->value); + PHPUnit\Framework\Assert::assertEquals($num, $this->value); } /** @@ -245,7 +245,7 @@ Feature: Pretty Formatter * @Then /I must have "([^"]+)"/ */ public function iMustHave($num) { - PHPUnit_Framework_Assert::assertEquals(intval(preg_replace('/[^\d]+/', '', $num)), $this->value); + PHPUnit\Framework\Assert::assertEquals(intval(preg_replace('/[^\d]+/', '', $num)), $this->value); } /** diff --git a/features/profiles.feature b/features/profiles.feature index 481b3a9d6..6b726437b 100644 --- a/features/profiles.feature +++ b/features/profiles.feature @@ -51,7 +51,7 @@ Feature: Profiles * @Then /The result should be (\d+)/ */ public function theResultShouldBe($result) { - PHPUnit_Framework_Assert::assertEquals($result, $this->result); + PHPUnit\Framework\Assert::assertEquals($result, $this->result); } } """ diff --git a/features/rerun.feature b/features/rerun.feature index e835b8e0d..0aa3000c4 100644 --- a/features/rerun.feature +++ b/features/rerun.feature @@ -44,22 +44,22 @@ Feature: Rerun * @Then /^I should have (\d+) apples$/ */ public function iShouldHaveApples($count) { - PHPUnit_Framework_Assert::assertEquals(intval($count), $this->apples); + PHPUnit\Framework\Assert::assertEquals(intval($count), $this->apples); } /** * @Then /^context parameter "([^"]*)" should be equal to "([^"]*)"$/ */ public function contextParameterShouldBeEqualTo($key, $val) { - PHPUnit_Framework_Assert::assertEquals($val, $this->parameters[$key]); + PHPUnit\Framework\Assert::assertEquals($val, $this->parameters[$key]); } /** * @Given /^context parameter "([^"]*)" should be array with (\d+) elements$/ */ public function contextParameterShouldBeArrayWithElements($key, $count) { - PHPUnit_Framework_Assert::assertInternalType('array', $this->parameters[$key]); - PHPUnit_Framework_Assert::assertEquals(2, count($this->parameters[$key])); + PHPUnit\Framework\Assert::assertInternalType('array', $this->parameters[$key]); + PHPUnit\Framework\Assert::assertEquals(2, count($this->parameters[$key])); } } """ diff --git a/features/rerun_with_multiple_suite.feature b/features/rerun_with_multiple_suite.feature index feb04dfa4..a706b8d1e 100644 --- a/features/rerun_with_multiple_suite.feature +++ b/features/rerun_with_multiple_suite.feature @@ -60,22 +60,22 @@ Feature: Rerun with multiple suite * @Then /^I should have (\d+) (apples|bananas)$/ */ public function iShouldHaveFruit($count, $fruit) { - PHPUnit_Framework_Assert::assertEquals(intval($count), $this->fruits[$fruit]); + PHPUnit\Framework\Assert::assertEquals(intval($count), $this->fruits[$fruit]); } /** * @Then /^context parameter "([^"]*)" should be equal to "([^"]*)"$/ */ public function contextParameterShouldBeEqualTo($key, $val) { - PHPUnit_Framework_Assert::assertEquals($val, $this->parameters[$key]); + PHPUnit\Framework\Assert::assertEquals($val, $this->parameters[$key]); } /** * @Given /^context parameter "([^"]*)" should be array with (\d+) elements$/ */ public function contextParameterShouldBeArrayWithElements($key, $count) { - PHPUnit_Framework_Assert::assertInternalType('array', $this->parameters[$key]); - PHPUnit_Framework_Assert::assertEquals(2, count($this->parameters[$key])); + PHPUnit\Framework\Assert::assertInternalType('array', $this->parameters[$key]); + PHPUnit\Framework\Assert::assertEquals(2, count($this->parameters[$key])); } } """ diff --git a/features/result_types.feature b/features/result_types.feature index 3467b6eaf..04feb95a5 100644 --- a/features/result_types.feature +++ b/features/result_types.feature @@ -236,7 +236,7 @@ Feature: Different result types * @Then /^I should see (\d+)\$ on the screen$/ */ public function iShouldSee($money) { - PHPUnit_Framework_Assert::assertEquals($money, $this->money); + PHPUnit\Framework\Assert::assertEquals($money, $this->money); } } """ @@ -324,7 +324,7 @@ Feature: Different result types * @Then /^I should see (\d+)\$ on the screen$/ */ public function iShouldSee($money) { - PHPUnit_Framework_Assert::assertEquals($money, $this->money); + PHPUnit\Framework\Assert::assertEquals($money, $this->money); } } """ diff --git a/features/traits.feature b/features/traits.feature index 0c2157cef..dc2c6a519 100644 --- a/features/traits.feature +++ b/features/traits.feature @@ -49,7 +49,7 @@ Feature: Support php 5.4 traits * @Then /^I should have (\d+) apples$/ */ public function iShouldHaveApples($count) { - PHPUnit_Framework_Assert::assertEquals(intval($count), $this->apples); + PHPUnit\Framework\Assert::assertEquals(intval($count), $this->apples); } } """ diff --git a/tests/Behat/Tests/Testwork/Subject/GroupedSubjectIteratorTest.php b/tests/Behat/Tests/Testwork/Subject/GroupedSubjectIteratorTest.php index e260b7596..84b8dd18f 100644 --- a/tests/Behat/Tests/Testwork/Subject/GroupedSubjectIteratorTest.php +++ b/tests/Behat/Tests/Testwork/Subject/GroupedSubjectIteratorTest.php @@ -5,8 +5,9 @@ use Behat\Testwork\Specification\GroupedSpecificationIterator; use Behat\Testwork\Specification\NoSpecificationsIterator; use Behat\Testwork\Specification\SpecificationArrayIterator; +use PHPUnit\Framework\TestCase; -class GroupedSubjectIteratorTest extends \PHPUnit_Framework_TestCase +class GroupedSubjectIteratorTest extends TestCase { public function testIterationWithEmptyAtBeginning() { From acf07c6341f4ec4e200f9383d2ca190d65d25179 Mon Sep 17 00:00:00 2001 From: everzet Date: Wed, 30 Aug 2017 16:59:45 +0100 Subject: [PATCH 063/567] Revert "Upgrade internal test suite to modern phpunit" This reverts commit 905dddc5e7d1bf489c82c473e0b3953b1d4d35e7. --- composer.json | 2 +- features/append_snippets.feature | 48 +++++++-------- features/arguments.feature | 8 +-- features/bootstrap/FeatureContext.php | 31 +++++----- features/config_inheritance.feature | 4 +- features/context.feature | 8 +-- features/definitions_patterns.feature | 58 +++++++++---------- features/definitions_transformations.feature | 12 ++-- features/definitions_translations.feature | 16 ++--- features/error_reporting.feature | 4 +- features/extensions.feature | 2 +- features/format_options.feature | 8 +-- features/helper_containers.feature | 4 +- features/hooks.feature | 2 +- features/i18n.feature | 2 +- features/junit_format.feature | 16 ++--- features/multiple_formats.feature | 8 +-- features/outlines.feature | 4 +- features/parameters.feature | 2 +- features/pretty_format.feature | 6 +- features/profiles.feature | 2 +- features/rerun.feature | 8 +-- features/rerun_with_multiple_suite.feature | 8 +-- features/result_types.feature | 4 +- features/traits.feature | 2 +- .../Subject/GroupedSubjectIteratorTest.php | 3 +- 26 files changed, 135 insertions(+), 137 deletions(-) diff --git a/composer.json b/composer.json index a056e594b..b3dbd81f3 100644 --- a/composer.json +++ b/composer.json @@ -31,7 +31,7 @@ "require-dev": { "symfony/process": "~2.5|~3.0", - "phpunit/phpunit": "~6.3", + "phpunit/phpunit": "~4.5", "herrera-io/box": "~1.6.1" }, diff --git a/features/append_snippets.feature b/features/append_snippets.feature index e1727bdb4..8eb9390ec 100644 --- a/features/append_snippets.feature +++ b/features/append_snippets.feature @@ -47,22 +47,22 @@ Feature: Append snippets option * @Then /^I should have (\d+) apples$/ */ public function iShouldHaveApples($count) { - \PHPUnit\Framework\Assert::assertEquals(intval($count), $this->apples); + \PHPUnit_Framework_Assert::assertEquals(intval($count), $this->apples); } /** * @Then /^context parameter "([^"]*)" should be equal to "([^"]*)"$/ */ public function contextParameterShouldBeEqualTo($key, $val) { - \PHPUnit\Framework\Assert::assertEquals($val, $this->parameters[$key]); + \PHPUnit_Framework_Assert::assertEquals($val, $this->parameters[$key]); } /** * @Given /^context parameter "([^"]*)" should be array with (\d+) elements$/ */ public function contextParameterShouldBeArrayWithElements($key, $count) { - \PHPUnit\Framework\Assert::assertInternalType('array', $this->parameters[$key]); - \PHPUnit\Framework\Assert::assertEquals(2, count($this->parameters[$key])); + \PHPUnit_Framework_Assert::assertInternalType('array', $this->parameters[$key]); + \PHPUnit_Framework_Assert::assertEquals(2, count($this->parameters[$key])); } private function doSomethingUndefinedWith() {} @@ -162,22 +162,22 @@ Feature: Append snippets option * @Then /^I should have (\d+) apples$/ */ public function iShouldHaveApples($count) { - \PHPUnit\Framework\Assert::assertEquals(intval($count), $this->apples); + \PHPUnit_Framework_Assert::assertEquals(intval($count), $this->apples); } /** * @Then /^context parameter "([^"]*)" should be equal to "([^"]*)"$/ */ public function contextParameterShouldBeEqualTo($key, $val) { - \PHPUnit\Framework\Assert::assertEquals($val, $this->parameters[$key]); + \PHPUnit_Framework_Assert::assertEquals($val, $this->parameters[$key]); } /** * @Given /^context parameter "([^"]*)" should be array with (\d+) elements$/ */ public function contextParameterShouldBeArrayWithElements($key, $count) { - \PHPUnit\Framework\Assert::assertInternalType('array', $this->parameters[$key]); - \PHPUnit\Framework\Assert::assertEquals(2, count($this->parameters[$key])); + \PHPUnit_Framework_Assert::assertInternalType('array', $this->parameters[$key]); + \PHPUnit_Framework_Assert::assertEquals(2, count($this->parameters[$key])); } private function doSomethingUndefinedWith() {} @@ -267,22 +267,22 @@ Feature: Append snippets option * @Then /^I should have (\d+) apples$/ */ public function iShouldHaveApples($count) { - \PHPUnit\Framework\Assert::assertEquals(intval($count), $this->apples); + \PHPUnit_Framework_Assert::assertEquals(intval($count), $this->apples); } /** * @Then /^context parameter "([^"]*)" should be equal to "([^"]*)"$/ */ public function contextParameterShouldBeEqualTo($key, $val) { - \PHPUnit\Framework\Assert::assertEquals($val, $this->parameters[$key]); + \PHPUnit_Framework_Assert::assertEquals($val, $this->parameters[$key]); } /** * @Given /^context parameter "([^"]*)" should be array with (\d+) elements$/ */ public function contextParameterShouldBeArrayWithElements($key, $count) { - \PHPUnit\Framework\Assert::assertInternalType('array', $this->parameters[$key]); - \PHPUnit\Framework\Assert::assertEquals(2, count($this->parameters[$key])); + \PHPUnit_Framework_Assert::assertInternalType('array', $this->parameters[$key]); + \PHPUnit_Framework_Assert::assertEquals(2, count($this->parameters[$key])); } private function doSomethingUndefinedWith() {} @@ -332,22 +332,22 @@ Feature: Append snippets option * @Then /^I should have (\d+) apples$/ */ public function iShouldHaveApples($count) { - \PHPUnit\Framework\Assert::assertEquals(intval($count), $this->apples); + \PHPUnit_Framework_Assert::assertEquals(intval($count), $this->apples); } /** * @Then /^context parameter "([^"]*)" should be equal to "([^"]*)"$/ */ public function contextParameterShouldBeEqualTo($key, $val) { - \PHPUnit\Framework\Assert::assertEquals($val, $this->parameters[$key]); + \PHPUnit_Framework_Assert::assertEquals($val, $this->parameters[$key]); } /** * @Given /^context parameter "([^"]*)" should be array with (\d+) elements$/ */ public function contextParameterShouldBeArrayWithElements($key, $count) { - \PHPUnit\Framework\Assert::assertInternalType('array', $this->parameters[$key]); - \PHPUnit\Framework\Assert::assertEquals(2, count($this->parameters[$key])); + \PHPUnit_Framework_Assert::assertInternalType('array', $this->parameters[$key]); + \PHPUnit_Framework_Assert::assertEquals(2, count($this->parameters[$key])); } private function doSomethingUndefinedWith() {} @@ -435,22 +435,22 @@ Feature: Append snippets option * @Then /^I should have (\d+) apples$/ */ public function iShouldHaveApples($count) { - \PHPUnit\Framework\Assert::assertEquals(intval($count), $this->apples); + \PHPUnit_Framework_Assert::assertEquals(intval($count), $this->apples); } /** * @Then /^context parameter "([^"]*)" should be equal to "([^"]*)"$/ */ public function contextParameterShouldBeEqualTo($key, $val) { - \PHPUnit\Framework\Assert::assertEquals($val, $this->parameters[$key]); + \PHPUnit_Framework_Assert::assertEquals($val, $this->parameters[$key]); } /** * @Given /^context parameter "([^"]*)" should be array with (\d+) elements$/ */ public function contextParameterShouldBeArrayWithElements($key, $count) { - \PHPUnit\Framework\Assert::assertInternalType('array', $this->parameters[$key]); - \PHPUnit\Framework\Assert::assertEquals(2, count($this->parameters[$key])); + \PHPUnit_Framework_Assert::assertInternalType('array', $this->parameters[$key]); + \PHPUnit_Framework_Assert::assertEquals(2, count($this->parameters[$key])); } private function doSomethingUndefinedWith() {} @@ -500,22 +500,22 @@ Feature: Append snippets option * @Then /^I should have (\d+) apples$/ */ public function iShouldHaveApples($count) { - \PHPUnit\Framework\Assert::assertEquals(intval($count), $this->apples); + \PHPUnit_Framework_Assert::assertEquals(intval($count), $this->apples); } /** * @Then /^context parameter "([^"]*)" should be equal to "([^"]*)"$/ */ public function contextParameterShouldBeEqualTo($key, $val) { - \PHPUnit\Framework\Assert::assertEquals($val, $this->parameters[$key]); + \PHPUnit_Framework_Assert::assertEquals($val, $this->parameters[$key]); } /** * @Given /^context parameter "([^"]*)" should be array with (\d+) elements$/ */ public function contextParameterShouldBeArrayWithElements($key, $count) { - \PHPUnit\Framework\Assert::assertInternalType('array', $this->parameters[$key]); - \PHPUnit\Framework\Assert::assertEquals(2, count($this->parameters[$key])); + \PHPUnit_Framework_Assert::assertInternalType('array', $this->parameters[$key]); + \PHPUnit_Framework_Assert::assertEquals(2, count($this->parameters[$key])); } private function doSomethingUndefinedWith() {} diff --git a/features/arguments.feature b/features/arguments.feature index 161a18111..6da60915a 100644 --- a/features/arguments.feature +++ b/features/arguments.feature @@ -44,22 +44,22 @@ Feature: Step Arguments * @Then /^it must be equals to string (\d+)$/ */ public function itMustBeEqualsToString($number) { - \PHPUnit\Framework\Assert::assertEquals($this->strings[intval($number)], (string) $this->input); + \PHPUnit_Framework_Assert::assertEquals($this->strings[intval($number)], (string) $this->input); } /** * @Then /^it must be equals to table (\d+)$/ */ public function itMustBeEqualsToTable($number) { - \PHPUnit\Framework\Assert::assertEquals($this->tables[intval($number)], $this->input->getHash()); + \PHPUnit_Framework_Assert::assertEquals($this->tables[intval($number)], $this->input->getHash()); } /** * @Given /^I have number2 = (?P\d+) and number1 = (?P\d+)$/ */ public function iHaveNumberAndNumber($number1, $number2) { - \PHPUnit\Framework\Assert::assertEquals(13, intval($number1)); - \PHPUnit\Framework\Assert::assertEquals(243, intval($number2)); + \PHPUnit_Framework_Assert::assertEquals(13, intval($number1)); + \PHPUnit_Framework_Assert::assertEquals(243, intval($number2)); } } """ diff --git a/features/bootstrap/FeatureContext.php b/features/bootstrap/FeatureContext.php index 11905b956..629c6fc21 100644 --- a/features/bootstrap/FeatureContext.php +++ b/features/bootstrap/FeatureContext.php @@ -10,7 +10,6 @@ use Behat\Behat\Context\Context; use Behat\Gherkin\Node\PyStringNode; -use PHPUnit\Framework\Assert; use Symfony\Component\Process\PhpExecutableFinder; use Symfony\Component\Process\Process; @@ -120,12 +119,12 @@ class FeatureContext implements Context $this->createFile($this->workingDir . '/' . $filename, $content); } - /** - * Creates a noop feature in current workdir. - * - * @Given /^(?:there is )?a some feature scenarios/ - */ - public function aNoopFeature() + /** + * Creates a noop feature in current workdir. + * + * @Given /^(?:there is )?a some feature scenarios/ + */ + public function aNoopFeature() { $filename = 'features/bootstrap/FeatureContext.php'; $content = <<<'EOL' @@ -157,7 +156,7 @@ public function iAmInThePath($path) */ public function fileShouldExist($path) { - Assert::assertFileExists($this->workingDir . DIRECTORY_SEPARATOR . $path); + PHPUnit_Framework_Assert::assertFileExists($this->workingDir . DIRECTORY_SEPARATOR . $path); } /** @@ -259,7 +258,7 @@ public function itShouldPassWith($success, PyStringNode $text) public function itShouldPassWithNoOutput($success) { $this->itShouldFail($success); - Assert::assertEmpty($this->getOutput()); + PHPUnit_Framework_Assert::assertEmpty($this->getOutput()); } /** @@ -273,7 +272,7 @@ public function itShouldPassWithNoOutput($success) public function fileShouldContain($path, PyStringNode $text) { $path = $this->workingDir . '/' . $path; - Assert::assertFileExists($path); + PHPUnit_Framework_Assert::assertFileExists($path); $fileContent = trim(file_get_contents($path)); // Normalize the line endings in the output @@ -281,7 +280,7 @@ public function fileShouldContain($path, PyStringNode $text) $fileContent = str_replace(PHP_EOL, "\n", $fileContent); } - Assert::assertEquals($this->getExpectedOutput($text), $fileContent); + PHPUnit_Framework_Assert::assertEquals($this->getExpectedOutput($text), $fileContent); } /** @@ -295,7 +294,7 @@ public function fileShouldContain($path, PyStringNode $text) public function fileXmlShouldBeLike($path, PyStringNode $text) { $path = $this->workingDir . '/' . $path; - Assert::assertFileExists($path); + PHPUnit_Framework_Assert::assertFileExists($path); $fileContent = trim(file_get_contents($path)); @@ -303,7 +302,7 @@ public function fileXmlShouldBeLike($path, PyStringNode $text) $dom->loadXML($text); $dom->formatOutput = true; - Assert::assertEquals(trim($dom->saveXML(null, LIBXML_NOEMPTYTAG)), $fileContent); + PHPUnit_Framework_Assert::assertEquals(trim($dom->saveXML(null, LIBXML_NOEMPTYTAG)), $fileContent); } @@ -316,7 +315,7 @@ public function fileXmlShouldBeLike($path, PyStringNode $text) */ public function theOutputShouldContain(PyStringNode $text) { - Assert::assertContains($this->getExpectedOutput($text), $this->getOutput()); + PHPUnit_Framework_Assert::assertContains($this->getExpectedOutput($text), $this->getOutput()); } private function getExpectedOutput(PyStringNode $expectedText) @@ -364,13 +363,13 @@ public function itShouldFail($success) echo 'Actual output:' . PHP_EOL . PHP_EOL . $this->getOutput(); } - Assert::assertNotEquals(0, $this->getExitCode()); + PHPUnit_Framework_Assert::assertNotEquals(0, $this->getExitCode()); } else { if (0 !== $this->getExitCode()) { echo 'Actual output:' . PHP_EOL . PHP_EOL . $this->getOutput(); } - Assert::assertEquals(0, $this->getExitCode()); + PHPUnit_Framework_Assert::assertEquals(0, $this->getExitCode()); } } diff --git a/features/config_inheritance.feature b/features/config_inheritance.feature index 16d6cb5e6..c418ad404 100644 --- a/features/config_inheritance.feature +++ b/features/config_inheritance.feature @@ -73,12 +73,12 @@ Feature: Config inheritance /** @Then the context parameters should be overwritten */ public function theContextParametersOverwrite() { - \PHPUnit\Framework\Assert::assertEquals(array('param2' => 'val2'), $this->parameters); + \PHPUnit_Framework_Assert::assertEquals(array('param2' => 'val2'), $this->parameters); } /** @Then the extension config should be merged */ public function theExtensionConfigMerge() { - \PHPUnit\Framework\Assert::assertEquals(array('param1' => 'val2', 'param2' => 'val1'), $this->extension); + \PHPUnit_Framework_Assert::assertEquals(array('param1' => 'val2', 'param2' => 'val1'), $this->extension); } } """ diff --git a/features/context.feature b/features/context.feature index eae21a44a..e96118009 100644 --- a/features/context.feature +++ b/features/context.feature @@ -47,22 +47,22 @@ Feature: Context consistency * @Then /^I should have (\d+) apples$/ */ public function iShouldHaveApples($count) { - PHPUnit\Framework\Assert::assertEquals(intval($count), $this->apples); + PHPUnit_Framework_Assert::assertEquals(intval($count), $this->apples); } /** * @Then /^context parameter "([^"]*)" should be equal to "([^"]*)"$/ */ public function contextParameterShouldBeEqualTo($key, $val) { - PHPUnit\Framework\Assert::assertEquals($val, $this->parameters[$key]); + PHPUnit_Framework_Assert::assertEquals($val, $this->parameters[$key]); } /** * @Given /^context parameter "([^"]*)" should be array with (\d+) elements$/ */ public function contextParameterShouldBeArrayWithElements($key, $count) { - PHPUnit\Framework\Assert::assertInternalType('array', $this->parameters[$key]); - PHPUnit\Framework\Assert::assertEquals(2, count($this->parameters[$key])); + PHPUnit_Framework_Assert::assertInternalType('array', $this->parameters[$key]); + PHPUnit_Framework_Assert::assertEquals(2, count($this->parameters[$key])); } } diff --git a/features/definitions_patterns.feature b/features/definitions_patterns.feature index 66eeb73d2..66d4d553f 100644 --- a/features/definitions_patterns.feature +++ b/features/definitions_patterns.feature @@ -158,8 +158,8 @@ Feature: Step Definition Pattern * @Given only second :second */ public function invalidRegex($first = 'foo', $second = 'fiz') { - PHPUnit\Framework\Assert::assertEquals('foo', $first); - PHPUnit\Framework\Assert::assertEquals('bar', $second); + PHPUnit_Framework_Assert::assertEquals('foo', $first); + PHPUnit_Framework_Assert::assertEquals('bar', $second); } } """ @@ -192,7 +192,7 @@ Feature: Step Definition Pattern * @Given I can provide parameter :param */ public function parameterCouldBeNull($param = null) { - PHPUnit\Framework\Assert::assertNull($param); + PHPUnit_Framework_Assert::assertNull($param); } } """ @@ -256,7 +256,7 @@ Feature: Step Definition Pattern * parameter :param */ public function parameterCouldBeNull($param = null) { - PHPUnit\Framework\Assert::assertNull($param); + PHPUnit_Framework_Assert::assertNull($param); } } """ @@ -295,8 +295,8 @@ Feature: Step Definition Pattern * @Given I can provide parameters :someParam and :someParam2 */ public function multipleWrongNamedParameters($param1, $param2) { - PHPUnit\Framework\Assert::assertEquals('one', $param1); - PHPUnit\Framework\Assert::assertEquals('two', $param2); + PHPUnit_Framework_Assert::assertEquals('one', $param1); + PHPUnit_Framework_Assert::assertEquals('two', $param2); } } """ @@ -328,8 +328,8 @@ Feature: Step Definition Pattern * @Given I can provide parameters :someParam and :someParam2 */ public function multipleWrongNamedParameters($param1, $someParam) { - PHPUnit\Framework\Assert::assertEquals('two', $param1); - PHPUnit\Framework\Assert::assertEquals('one', $someParam); + PHPUnit_Framework_Assert::assertEquals('two', $param1); + PHPUnit_Framework_Assert::assertEquals('one', $someParam); } } """ @@ -361,9 +361,9 @@ Feature: Step Definition Pattern * @Given I can provide :count parameters :firstParam and :otherParam */ public function multipleWrongNamedParameters($param1, $firstParam, $count) { - PHPUnit\Framework\Assert::assertEquals('two', $param1); - PHPUnit\Framework\Assert::assertEquals('one', $firstParam); - PHPUnit\Framework\Assert::assertEquals(2, $count); + PHPUnit_Framework_Assert::assertEquals('two', $param1); + PHPUnit_Framework_Assert::assertEquals('one', $firstParam); + PHPUnit_Framework_Assert::assertEquals(2, $count); } } """ @@ -395,10 +395,10 @@ Feature: Step Definition Pattern * @Given I can provide :count parameters :firstParam and :otherParam with: */ public function multipleWrongNamedParameters($param1, $firstParam, $count, $string) { - PHPUnit\Framework\Assert::assertEquals('two', $param1); - PHPUnit\Framework\Assert::assertEquals('one', $firstParam); - PHPUnit\Framework\Assert::assertEquals(2, $count); - PHPUnit\Framework\Assert::assertEquals("Test", (string) $string); + PHPUnit_Framework_Assert::assertEquals('two', $param1); + PHPUnit_Framework_Assert::assertEquals('one', $firstParam); + PHPUnit_Framework_Assert::assertEquals(2, $count); + PHPUnit_Framework_Assert::assertEquals("Test", (string) $string); } } """ @@ -433,9 +433,9 @@ Feature: Step Definition Pattern * @Given I can provide :count parameters for :name: */ public function multipleWrongNamedParameters($count, $name, $string) { - PHPUnit\Framework\Assert::assertEquals('2', $count); - PHPUnit\Framework\Assert::assertEquals('thing', $name); - PHPUnit\Framework\Assert::assertEquals("Test", (string) $string); + PHPUnit_Framework_Assert::assertEquals('2', $count); + PHPUnit_Framework_Assert::assertEquals('thing', $name); + PHPUnit_Framework_Assert::assertEquals("Test", (string) $string); } } """ @@ -472,9 +472,9 @@ Feature: Step Definition Pattern */ public function checkEquality($path = null, $isNegative = null, PyStringNode $json = null) { - PHPUnit\Framework\Assert::assertNull($path); - PHPUnit\Framework\Assert::assertNull($isNegative); - PHPUnit\Framework\Assert::assertNotNull($json); + PHPUnit_Framework_Assert::assertNull($path); + PHPUnit_Framework_Assert::assertNull($isNegative); + PHPUnit_Framework_Assert::assertNotNull($json); } /** @@ -482,9 +482,9 @@ Feature: Step Definition Pattern */ public function checkEquality2($json = null, $path = null, $isNegative = null) { - PHPUnit\Framework\Assert::assertNull($path); - PHPUnit\Framework\Assert::assertNull($isNegative); - PHPUnit\Framework\Assert::assertNotNull($json); + PHPUnit_Framework_Assert::assertNull($path); + PHPUnit_Framework_Assert::assertNull($isNegative); + PHPUnit_Framework_Assert::assertNotNull($json); } } """ @@ -523,7 +523,7 @@ Feature: Step Definition Pattern * @Given I have a package v:version */ public function multipleWrongNamedParameters($version) { - PHPUnit\Framework\Assert::assertEquals('2.5', $version); + PHPUnit_Framework_Assert::assertEquals('2.5', $version); } } """ @@ -555,7 +555,7 @@ Feature: Step Definition Pattern * @When I enter the string :input */ public function multipleWrongNamedParameters($input) { - PHPUnit\Framework\Assert::assertEquals('', $input); + PHPUnit_Framework_Assert::assertEquals('', $input); } } """ @@ -587,8 +587,8 @@ Feature: Step Definition Pattern * @Then images should be uploaded to web\/uploads\/media\/default\/:arg1\/:arg2\/ */ public function multipleWrongNamedParameters($arg1, $arg2) { - PHPUnit\Framework\Assert::assertEquals('0001', $arg1); - PHPUnit\Framework\Assert::assertEquals('01', $arg2); + PHPUnit_Framework_Assert::assertEquals('0001', $arg1); + PHPUnit_Framework_Assert::assertEquals('01', $arg2); } } """ @@ -620,7 +620,7 @@ Feature: Step Definition Pattern * @Given I have a negative number :num */ public function multipleWrongNamedParameters($num) { - PHPUnit\Framework\Assert::assertEquals('-3', $num); + PHPUnit_Framework_Assert::assertEquals('-3', $num); } } """ diff --git a/features/definitions_transformations.feature b/features/definitions_transformations.feature index 92c4e6f25..ff986a4ce 100644 --- a/features/definitions_transformations.feature +++ b/features/definitions_transformations.feature @@ -117,29 +117,29 @@ Feature: Step Arguments Transformations * @Then /Username must be "([^"]+)"/ */ public function usernameMustBe($username) { - PHPUnit\Framework\Assert::assertEquals($username, $this->user->getUsername()); + PHPUnit_Framework_Assert::assertEquals($username, $this->user->getUsername()); } /** * @Then /Age must be (\d+)/ */ public function ageMustBe($age) { - PHPUnit\Framework\Assert::assertEquals($age, $this->user->getAge()); - PHPUnit\Framework\Assert::assertInternalType('int', $age); + PHPUnit_Framework_Assert::assertEquals($age, $this->user->getAge()); + PHPUnit_Framework_Assert::assertInternalType('int', $age); } /** * @Then the Usernames must be: */ public function usernamesMustBe(array $usernames) { - PHPUnit\Framework\Assert::assertEquals($usernames[0], $this->user->getUsername()); + PHPUnit_Framework_Assert::assertEquals($usernames[0], $this->user->getUsername()); } /** * @Then /^the boolean (no) should be transformed to false$/ */ public function theBooleanShouldBeTransformed($boolean) { - PHPUnit\Framework\Assert::assertSame(false, $boolean); + PHPUnit_Framework_Assert::assertSame(false, $boolean); } } """ @@ -289,7 +289,7 @@ Feature: Step Arguments Transformations /** @Then the :field should be :value */ public function theFieldShouldBe($field, $value) { - PHPUnit\Framework\Assert::assertSame($value, $this->data[0][$field]); + PHPUnit_Framework_Assert::assertSame($value, $this->data[0][$field]); } } """ diff --git a/features/definitions_translations.feature b/features/definitions_translations.feature index c3ace9d05..df41e942f 100644 --- a/features/definitions_translations.feature +++ b/features/definitions_translations.feature @@ -47,7 +47,7 @@ Feature: Definitions translations * @Then /^I should see (\d+) on the screen$/ */ public function iShouldSeeOnTheScreen($result) { - PHPUnit\Framework\Assert::assertEquals(intval($result), $this->result); + PHPUnit_Framework_Assert::assertEquals(intval($result), $this->result); } /** @Transform /"([^"]+)" user/ */ @@ -59,7 +59,7 @@ Feature: Definitions translations * @Then /^the ("[^"]+" user) name should be "([^"]*)"$/ */ public function theUserUsername($user, $username) { - PHPUnit\Framework\Assert::assertEquals($username, $user->name); + PHPUnit_Framework_Assert::assertEquals($username, $user->name); } public static function getTranslationResources() { @@ -150,7 +150,7 @@ Feature: Definitions translations * @Then /^I should see (\d+) on the screen$/ */ public function iShouldSeeOnTheScreen($result) { - PHPUnit\Framework\Assert::assertEquals(intval($result), $this->result); + PHPUnit_Framework_Assert::assertEquals(intval($result), $this->result); } /** @Transform /"([^"]+)" user/ */ @@ -162,7 +162,7 @@ Feature: Definitions translations * @Then /^the ("[^"]+" user) name should be "([^"]*)"$/ */ public function theUserUsername($user, $username) { - PHPUnit\Framework\Assert::assertEquals($username, $user->name); + PHPUnit_Framework_Assert::assertEquals($username, $user->name); } public static function getTranslationResources() { @@ -231,7 +231,7 @@ Feature: Definitions translations * @Then /^I should see (\d+) on the screen$/ */ public function iShouldSeeOnTheScreen($result) { - PHPUnit\Framework\Assert::assertEquals(intval($result), $this->result); + PHPUnit_Framework_Assert::assertEquals(intval($result), $this->result); } /** @Transform /"([^"]+)" user/ */ @@ -243,7 +243,7 @@ Feature: Definitions translations * @Then /^the ("[^"]+" user) name should be "([^"]*)"$/ */ public function theUserUsername($user, $username) { - PHPUnit\Framework\Assert::assertEquals($username, $user->name); + PHPUnit_Framework_Assert::assertEquals($username, $user->name); } public static function getTranslationResources() { @@ -321,7 +321,7 @@ Feature: Definitions translations * @Then /^I should see (\d+) on the screen$/ */ public function iShouldSeeOnTheScreen($result) { - PHPUnit\Framework\Assert::assertEquals(intval($result), $this->result); + PHPUnit_Framework_Assert::assertEquals(intval($result), $this->result); } /** @Transform /"([^"]+)" user/ */ @@ -333,7 +333,7 @@ Feature: Definitions translations * @Then /^the ("[^"]+" user) name should be "([^"]*)"$/ */ public function theUserUsername($user, $username) { - PHPUnit\Framework\Assert::assertEquals($username, $user->name); + PHPUnit_Framework_Assert::assertEquals($username, $user->name); } public static function getTranslationResources() { diff --git a/features/error_reporting.feature b/features/error_reporting.feature index 1139b48bc..c3b859479 100644 --- a/features/error_reporting.feature +++ b/features/error_reporting.feature @@ -37,7 +37,7 @@ Feature: Error Reporting */ public function iShouldGetNull() { - PHPUnit\Framework\Assert::assertNull($this->result); + PHPUnit_Framework_Assert::assertNull($this->result); } /** @@ -53,7 +53,7 @@ Feature: Error Reporting */ public function iShouldGet($arg1) { - PHPUnit\Framework\Assert::assertEquals($arg1, $this->result); + PHPUnit_Framework_Assert::assertEquals($arg1, $this->result); } } diff --git a/features/extensions.feature b/features/extensions.feature index 9d5bd2f3f..5fb9de911 100644 --- a/features/extensions.feature +++ b/features/extensions.feature @@ -31,7 +31,7 @@ Feature: Extensions /** @Then the extension should be loaded */ public function theExtensionLoaded() { - PHPUnit\Framework\Assert::assertEquals(array('param1' => 'val1', 'param2' => 'val2'), $this->extension); + PHPUnit_Framework_Assert::assertEquals(array('param1' => 'val1', 'param2' => 'val2'), $this->extension); } } """ diff --git a/features/format_options.feature b/features/format_options.feature index f523e42c9..ce773fa0b 100644 --- a/features/format_options.feature +++ b/features/format_options.feature @@ -47,22 +47,22 @@ Feature: Format options * @Then /^I should have (\d+) apples$/ */ public function iShouldHaveApples($count) { - PHPUnit\Framework\Assert::assertEquals(intval($count), $this->apples); + PHPUnit_Framework_Assert::assertEquals(intval($count), $this->apples); } /** * @Then /^context parameter "([^"]*)" should be equal to "([^"]*)"$/ */ public function contextParameterShouldBeEqualTo($key, $val) { - PHPUnit\Framework\Assert::assertEquals($val, $this->parameters[$key]); + PHPUnit_Framework_Assert::assertEquals($val, $this->parameters[$key]); } /** * @Given /^context parameter "([^"]*)" should be array with (\d+) elements$/ */ public function contextParameterShouldBeArrayWithElements($key, $count) { - PHPUnit\Framework\Assert::assertInternalType('array', $this->parameters[$key]); - PHPUnit\Framework\Assert::assertEquals(2, count($this->parameters[$key])); + PHPUnit_Framework_Assert::assertInternalType('array', $this->parameters[$key]); + PHPUnit_Framework_Assert::assertEquals(2, count($this->parameters[$key])); } } """ diff --git a/features/helper_containers.feature b/features/helper_containers.feature index ce6bd6bb9..934a6bbf9 100644 --- a/features/helper_containers.feature +++ b/features/helper_containers.feature @@ -47,7 +47,7 @@ Feature: Per-suite helper containers /** @Given service has no state */ public function noState() { - PHPUnit\Framework\Assert::assertNull($this->service->number); + PHPUnit_Framework_Assert::assertNull($this->service->number); } /** @When service gets a state of :number in first context */ @@ -67,7 +67,7 @@ Feature: Per-suite helper containers /** @Then service should have a state of :number in second context */ public function checkState($number) { - PHPUnit\Framework\Assert::assertSame($number, $this->service->number); + PHPUnit_Framework_Assert::assertSame($number, $this->service->number); } } """ diff --git a/features/hooks.feature b/features/hooks.feature index 20066b000..557969e4e 100644 --- a/features/hooks.feature +++ b/features/hooks.feature @@ -101,7 +101,7 @@ Feature: hooks * @Then /^I must have (\d+)$/ */ public function iMustHave($number) { - \PHPUnit\Framework\Assert::assertEquals(intval($number), $this->number); + \PHPUnit_Framework_Assert::assertEquals(intval($number), $this->number); } } """ diff --git a/features/i18n.feature b/features/i18n.feature index 1856d204f..b130b82e2 100644 --- a/features/i18n.feature +++ b/features/i18n.feature @@ -28,7 +28,7 @@ Feature: I18n * @Then /Я должен иметь (\d+)/ */ public function iShouldHave($number) { - PHPUnit\Framework\Assert::assertEquals(intval($number), $this->value); + PHPUnit_Framework_Assert::assertEquals(intval($number), $this->value); } /** diff --git a/features/junit_format.feature b/features/junit_format.feature index 180cd5a27..f9e4bfd88 100644 --- a/features/junit_format.feature +++ b/features/junit_format.feature @@ -26,7 +26,7 @@ * @Then /I must have (\d+)/ */ public function iMustHave($num) { - PHPUnit\Framework\Assert::assertEquals($num, $this->value); + PHPUnit_Framework_Assert::assertEquals($num, $this->value); } /** @@ -151,7 +151,7 @@ * @Then /I must have (\d+)/ */ public function iMustHave($num) { - PHPUnit\Framework\Assert::assertEquals($num, $this->value); + PHPUnit_Framework_Assert::assertEquals($num, $this->value); } /** @@ -223,7 +223,7 @@ * @Then /I must have (\d+)/ */ public function iMustHave($num) { - PHPUnit\Framework\Assert::assertEquals($num, $this->value); + PHPUnit_Framework_Assert::assertEquals($num, $this->value); } /** @@ -303,7 +303,7 @@ * @Then /I will be stronger/ */ public function iWillBeStronger() { - PHPUnit\Framework\Assert::assertNotEquals(0, $this->strongLevel); + PHPUnit_Framework_Assert::assertNotEquals(0, $this->strongLevel); } } """ @@ -333,7 +333,7 @@ * @Then /I will be stronger/ */ public function iWillBeStronger() { - PHPUnit\Framework\Assert::assertNotEquals(0, $this->strongLevel); + PHPUnit_Framework_Assert::assertNotEquals(0, $this->strongLevel); } } """ @@ -486,7 +486,7 @@ * @Then /I must have (\d+)/ */ public function iMustHave($num) { - PHPUnit\Framework\Assert::assertEquals($num, $this->value); + PHPUnit_Framework_Assert::assertEquals($num, $this->value); } /** @@ -550,7 +550,7 @@ * @Then /I must have (\d+)/ */ public function iMustHave($num) { - PHPUnit\Framework\Assert::assertEqual($num, $this->value); + PHPUnit_Framework_Assert::assertEqual($num, $this->value); } /** @@ -578,7 +578,7 @@ When I run "behat --no-colors -f junit -o junit" Then it should fail with: """ - Call to undefined method PHPUnit\Framework\Assert::assertEqual + Call to undefined method PHPUnit_Framework_Assert::assertEqual """ And "junit/default.xml" file xml should be like: """ diff --git a/features/multiple_formats.feature b/features/multiple_formats.feature index ecbb2605c..1ef068178 100644 --- a/features/multiple_formats.feature +++ b/features/multiple_formats.feature @@ -47,22 +47,22 @@ Feature: Multiple formats * @Then /^I should have (\d+) apples$/ */ public function iShouldHaveApples($count) { - PHPUnit\Framework\Assert::assertEquals(intval($count), $this->apples); + PHPUnit_Framework_Assert::assertEquals(intval($count), $this->apples); } /** * @Then /^context parameter "([^"]*)" should be equal to "([^"]*)"$/ */ public function contextParameterShouldBeEqualTo($key, $val) { - PHPUnit\Framework\Assert::assertEquals($val, $this->parameters[$key]); + PHPUnit_Framework_Assert::assertEquals($val, $this->parameters[$key]); } /** * @Given /^context parameter "([^"]*)" should be array with (\d+) elements$/ */ public function contextParameterShouldBeArrayWithElements($key, $count) { - PHPUnit\Framework\Assert::assertInternalType('array', $this->parameters[$key]); - PHPUnit\Framework\Assert::assertEquals(2, count($this->parameters[$key])); + PHPUnit_Framework_Assert::assertInternalType('array', $this->parameters[$key]); + PHPUnit_Framework_Assert::assertEquals(2, count($this->parameters[$key])); } } """ diff --git a/features/outlines.feature b/features/outlines.feature index 352fca98c..148f9ab7c 100644 --- a/features/outlines.feature +++ b/features/outlines.feature @@ -80,7 +80,7 @@ Feature: Scenario Outlines * @Then /^The result should be (\d+)$/ */ public function theResultShouldBe($result) { - PHPUnit\Framework\Assert::assertEquals(intval($result), $this->result); + PHPUnit_Framework_Assert::assertEquals(intval($result), $this->result); } } """ @@ -242,7 +242,7 @@ Feature: Scenario Outlines * @Then the result should be :result */ public function theResultShouldBe($result) { - PHPUnit\Framework\Assert::assertEquals(intval($result), $this->number); + PHPUnit_Framework_Assert::assertEquals(intval($result), $this->number); } } """ diff --git a/features/parameters.feature b/features/parameters.feature index 784c542ac..b60550dcc 100644 --- a/features/parameters.feature +++ b/features/parameters.feature @@ -53,7 +53,7 @@ Feature: Parameters * @Then /The result should be (\d+)/ */ public function theResultShouldBe($result) { - PHPUnit\Framework\Assert::assertEquals($result, $this->result); + PHPUnit_Framework_Assert::assertEquals($result, $this->result); } } """ diff --git a/features/pretty_format.feature b/features/pretty_format.feature index 6f7a575ee..1bfa914ca 100644 --- a/features/pretty_format.feature +++ b/features/pretty_format.feature @@ -28,7 +28,7 @@ Feature: Pretty Formatter * @Then /I must have (\d+)/ */ public function iMustHave($num) { - PHPUnit\Framework\Assert::assertEquals($num, $this->value); + PHPUnit_Framework_Assert::assertEquals($num, $this->value); } /** @@ -163,7 +163,7 @@ Feature: Pretty Formatter * @Then /I must have (\d+)/ */ public function iMustHave($num) { - PHPUnit\Framework\Assert::assertEquals($num, $this->value); + PHPUnit_Framework_Assert::assertEquals($num, $this->value); } /** @@ -245,7 +245,7 @@ Feature: Pretty Formatter * @Then /I must have "([^"]+)"/ */ public function iMustHave($num) { - PHPUnit\Framework\Assert::assertEquals(intval(preg_replace('/[^\d]+/', '', $num)), $this->value); + PHPUnit_Framework_Assert::assertEquals(intval(preg_replace('/[^\d]+/', '', $num)), $this->value); } /** diff --git a/features/profiles.feature b/features/profiles.feature index 6b726437b..481b3a9d6 100644 --- a/features/profiles.feature +++ b/features/profiles.feature @@ -51,7 +51,7 @@ Feature: Profiles * @Then /The result should be (\d+)/ */ public function theResultShouldBe($result) { - PHPUnit\Framework\Assert::assertEquals($result, $this->result); + PHPUnit_Framework_Assert::assertEquals($result, $this->result); } } """ diff --git a/features/rerun.feature b/features/rerun.feature index 0aa3000c4..e835b8e0d 100644 --- a/features/rerun.feature +++ b/features/rerun.feature @@ -44,22 +44,22 @@ Feature: Rerun * @Then /^I should have (\d+) apples$/ */ public function iShouldHaveApples($count) { - PHPUnit\Framework\Assert::assertEquals(intval($count), $this->apples); + PHPUnit_Framework_Assert::assertEquals(intval($count), $this->apples); } /** * @Then /^context parameter "([^"]*)" should be equal to "([^"]*)"$/ */ public function contextParameterShouldBeEqualTo($key, $val) { - PHPUnit\Framework\Assert::assertEquals($val, $this->parameters[$key]); + PHPUnit_Framework_Assert::assertEquals($val, $this->parameters[$key]); } /** * @Given /^context parameter "([^"]*)" should be array with (\d+) elements$/ */ public function contextParameterShouldBeArrayWithElements($key, $count) { - PHPUnit\Framework\Assert::assertInternalType('array', $this->parameters[$key]); - PHPUnit\Framework\Assert::assertEquals(2, count($this->parameters[$key])); + PHPUnit_Framework_Assert::assertInternalType('array', $this->parameters[$key]); + PHPUnit_Framework_Assert::assertEquals(2, count($this->parameters[$key])); } } """ diff --git a/features/rerun_with_multiple_suite.feature b/features/rerun_with_multiple_suite.feature index a706b8d1e..feb04dfa4 100644 --- a/features/rerun_with_multiple_suite.feature +++ b/features/rerun_with_multiple_suite.feature @@ -60,22 +60,22 @@ Feature: Rerun with multiple suite * @Then /^I should have (\d+) (apples|bananas)$/ */ public function iShouldHaveFruit($count, $fruit) { - PHPUnit\Framework\Assert::assertEquals(intval($count), $this->fruits[$fruit]); + PHPUnit_Framework_Assert::assertEquals(intval($count), $this->fruits[$fruit]); } /** * @Then /^context parameter "([^"]*)" should be equal to "([^"]*)"$/ */ public function contextParameterShouldBeEqualTo($key, $val) { - PHPUnit\Framework\Assert::assertEquals($val, $this->parameters[$key]); + PHPUnit_Framework_Assert::assertEquals($val, $this->parameters[$key]); } /** * @Given /^context parameter "([^"]*)" should be array with (\d+) elements$/ */ public function contextParameterShouldBeArrayWithElements($key, $count) { - PHPUnit\Framework\Assert::assertInternalType('array', $this->parameters[$key]); - PHPUnit\Framework\Assert::assertEquals(2, count($this->parameters[$key])); + PHPUnit_Framework_Assert::assertInternalType('array', $this->parameters[$key]); + PHPUnit_Framework_Assert::assertEquals(2, count($this->parameters[$key])); } } """ diff --git a/features/result_types.feature b/features/result_types.feature index 04feb95a5..3467b6eaf 100644 --- a/features/result_types.feature +++ b/features/result_types.feature @@ -236,7 +236,7 @@ Feature: Different result types * @Then /^I should see (\d+)\$ on the screen$/ */ public function iShouldSee($money) { - PHPUnit\Framework\Assert::assertEquals($money, $this->money); + PHPUnit_Framework_Assert::assertEquals($money, $this->money); } } """ @@ -324,7 +324,7 @@ Feature: Different result types * @Then /^I should see (\d+)\$ on the screen$/ */ public function iShouldSee($money) { - PHPUnit\Framework\Assert::assertEquals($money, $this->money); + PHPUnit_Framework_Assert::assertEquals($money, $this->money); } } """ diff --git a/features/traits.feature b/features/traits.feature index dc2c6a519..0c2157cef 100644 --- a/features/traits.feature +++ b/features/traits.feature @@ -49,7 +49,7 @@ Feature: Support php 5.4 traits * @Then /^I should have (\d+) apples$/ */ public function iShouldHaveApples($count) { - PHPUnit\Framework\Assert::assertEquals(intval($count), $this->apples); + PHPUnit_Framework_Assert::assertEquals(intval($count), $this->apples); } } """ diff --git a/tests/Behat/Tests/Testwork/Subject/GroupedSubjectIteratorTest.php b/tests/Behat/Tests/Testwork/Subject/GroupedSubjectIteratorTest.php index 84b8dd18f..e260b7596 100644 --- a/tests/Behat/Tests/Testwork/Subject/GroupedSubjectIteratorTest.php +++ b/tests/Behat/Tests/Testwork/Subject/GroupedSubjectIteratorTest.php @@ -5,9 +5,8 @@ use Behat\Testwork\Specification\GroupedSpecificationIterator; use Behat\Testwork\Specification\NoSpecificationsIterator; use Behat\Testwork\Specification\SpecificationArrayIterator; -use PHPUnit\Framework\TestCase; -class GroupedSubjectIteratorTest extends TestCase +class GroupedSubjectIteratorTest extends \PHPUnit_Framework_TestCase { public function testIterationWithEmptyAtBeginning() { From df8838aa221554e473fd61b3f0ee442776cb799a Mon Sep 17 00:00:00 2001 From: everzet Date: Thu, 31 Aug 2017 09:06:58 +0100 Subject: [PATCH 064/567] Use logo repository logo --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index e71a77b4e..550ee8185 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -![Behat](https://dl.dropboxusercontent.com/u/282797/behat/behat.png) +![Behat](https://github.com/Behat/logo/raw/master/logo%402x.png) Behat is a BDD framework for PHP to help you test business expectations. From 1d426006388f6523bd715de98c4f48d8d6609704 Mon Sep 17 00:00:00 2001 From: everzet Date: Thu, 31 Aug 2017 09:07:36 +0100 Subject: [PATCH 065/567] Use smaller version of logo --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 550ee8185..4159ab7df 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -![Behat](https://github.com/Behat/logo/raw/master/logo%402x.png) +![Behat](https://github.com/Behat/logo/raw/master/logo.png) Behat is a BDD framework for PHP to help you test business expectations. From 44b6de275cf5b593049ed62c4881e55378ca9c7a Mon Sep 17 00:00:00 2001 From: everzet Date: Thu, 31 Aug 2017 09:08:26 +0100 Subject: [PATCH 066/567] Remove broken HHVM badge --- README.md | 1 - 1 file changed, 1 deletion(-) diff --git a/README.md b/README.md index 4159ab7df..22543cb51 100644 --- a/README.md +++ b/README.md @@ -6,7 +6,6 @@ Behat is a BDD framework for PHP to help you test business expectations. [![License](https://poser.pugx.org/behat/behat/license.svg)](https://packagist.org/packages/behat/behat) [![Unix Status](https://travis-ci.org/Behat/Behat.svg?branch=master)](https://travis-ci.org/Behat/Behat) [![Windows status](https://ci.appveyor.com/api/projects/status/9uc5sellmvbv02ei/branch/master?svg=true)](https://ci.appveyor.com/project/everzet/behat/branch/master) -[![HHVM Status](http://hhvm.h4cc.de/badge/behat/behat.svg?branch=master)](http://hhvm.h4cc.de/package/behat/behat) [![Scrutinizer Quality Score](https://scrutinizer-ci.com/g/Behat/Behat/badges/quality-score.png?s=ad84e95fc2405712f88a96d89b4f31dfe5c80fae)](https://scrutinizer-ci.com/g/Behat/Behat/) Installing Behat From 237bd0b4d9057679ae8eb316e1ffcfa6d6bfc2ac Mon Sep 17 00:00:00 2001 From: everzet Date: Thu, 31 Aug 2017 11:13:46 +0100 Subject: [PATCH 067/567] Extract argument Validator from Organiser --- src/Behat/Behat/Context/ContextFactory.php | 12 +++- .../Argument/MixedArgumentOrganiser.php | 58 +-------------- src/Behat/Testwork/Argument/Validator.php | 70 +++++++++++++++++++ 3 files changed, 81 insertions(+), 59 deletions(-) create mode 100644 src/Behat/Testwork/Argument/Validator.php diff --git a/src/Behat/Behat/Context/ContextFactory.php b/src/Behat/Behat/Context/ContextFactory.php index ff255d19c..e9f5baaf7 100644 --- a/src/Behat/Behat/Context/ContextFactory.php +++ b/src/Behat/Behat/Context/ContextFactory.php @@ -10,6 +10,7 @@ namespace Behat\Behat\Context; +use Behat\Testwork\Argument\Validator; use Behat\Behat\Context\Argument\ArgumentResolver; use Behat\Behat\Context\Initializer\ContextInitializer; use Behat\Testwork\Argument\ArgumentOrganiser; @@ -34,6 +35,10 @@ final class ContextFactory * @var ContextInitializer[] */ private $contextInitializers = array(); + /** + * @var Validator + */ + private $validator; /** * Initialises factory. @@ -43,6 +48,7 @@ final class ContextFactory public function __construct(ArgumentOrganiser $argumentOrganiser) { $this->argumentOrganiser = $argumentOrganiser; + $this->validator = new Validator(); } /** @@ -100,13 +106,15 @@ private function resolveArguments(ReflectionClass $reflection, array $arguments, $arguments = $resolver->resolveArguments($reflection, $arguments); } - if (!$reflection->hasMethod('__construct') || !count($arguments)) { + if (!$reflection->hasMethod('__construct')) { return $arguments; } $constructor = $reflection->getConstructor(); + $arguments = $this->argumentOrganiser->organiseArguments($constructor, $arguments); + $this->validator->validateArguments($constructor, $arguments); - return $this->argumentOrganiser->organiseArguments($constructor, $arguments); + return $arguments; } /** diff --git a/src/Behat/Testwork/Argument/MixedArgumentOrganiser.php b/src/Behat/Testwork/Argument/MixedArgumentOrganiser.php index e50f47a7f..bc116ddd2 100644 --- a/src/Behat/Testwork/Argument/MixedArgumentOrganiser.php +++ b/src/Behat/Testwork/Argument/MixedArgumentOrganiser.php @@ -10,10 +10,8 @@ namespace Behat\Testwork\Argument; -use Behat\Testwork\Argument\Exception\UnknownParameterValueException; use ReflectionFunctionAbstract; use ReflectionClass; -use ReflectionMethod; use ReflectionParameter; /** @@ -35,12 +33,7 @@ final class MixedArgumentOrganiser implements ArgumentOrganiser */ public function organiseArguments(ReflectionFunctionAbstract $function, array $arguments) { - $parameters = $function->getParameters(); - $arguments = $this->prepareArguments($parameters, $arguments); - - $this->validateArguments($function, $parameters, $arguments); - - return $arguments; + return $this->prepareArguments($function->getParameters(), $arguments); } /** @@ -402,55 +395,6 @@ private function reorderArguments(array $parameters, array $arguments) return $orderedArguments; } - /** - * Validates that all arguments are in place, throws exception otherwise. - * - * @param ReflectionFunctionAbstract $function - * @param ReflectionParameter[] $parameters - * @param mixed[] $arguments - * - * @throws UnknownParameterValueException - */ - private function validateArguments( - ReflectionFunctionAbstract $function, - array $parameters, - array $arguments - ) { - foreach ($parameters as $num => $parameter) { - $name = $parameter->getName(); - - if (array_key_exists($num, $arguments) || array_key_exists($name, $arguments)) { - continue; - } - - throw new UnknownParameterValueException(sprintf( - 'Can not find a matching value for an argument `$%s` of the method `%s`.', - $name, - $this->getFunctionPath($function) - )); - } - } - - /** - * Returns function path for a provided reflection. - * - * @param ReflectionFunctionAbstract $function - * - * @return string - */ - private function getFunctionPath(ReflectionFunctionAbstract $function) - { - if ($function instanceof ReflectionMethod) { - return sprintf( - '%s::%s()', - $function->getDeclaringClass()->getName(), - $function->getName() - ); - } - - return sprintf('%s()', $function->getName()); - } - /** * Marks arguments at all positions as undefined. * diff --git a/src/Behat/Testwork/Argument/Validator.php b/src/Behat/Testwork/Argument/Validator.php new file mode 100644 index 000000000..7e3bd1c60 --- /dev/null +++ b/src/Behat/Testwork/Argument/Validator.php @@ -0,0 +1,70 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Behat\Testwork\Argument; + +use Behat\Testwork\Argument\Exception\UnknownParameterValueException; +use ReflectionFunctionAbstract; +use ReflectionMethod; + +/** + * Validates function arguments. + * + * @author Konstantin Kudryashov + */ +final class Validator +{ + /** + * Validates that all arguments are in place, throws exception otherwise. + * + * @param ReflectionFunctionAbstract $function + * @param mixed[] $arguments + * + * @throws UnknownParameterValueException + */ + public function validateArguments(ReflectionFunctionAbstract $function, array $arguments) + { + foreach ($function->getParameters() as $num => $parameter) { + $name = $parameter->getName(); + + if ($parameter->isDefaultValueAvailable() + || array_key_exists($num, $arguments) + || array_key_exists($name, $arguments)) { + continue; + } + + throw new UnknownParameterValueException(sprintf( + 'Can not find a matching value for an argument `$%s` of the method `%s`.', + $name, + $this->getFunctionPath($function) + )); + } + } + + /** + * Returns function path for a provided reflection. + * + * @param ReflectionFunctionAbstract $function + * + * @return string + */ + private function getFunctionPath(ReflectionFunctionAbstract $function) + { + if ($function instanceof ReflectionMethod) { + return sprintf( + '%s::%s()', + $function->getDeclaringClass()->getName(), + $function->getName() + ); + } + + return sprintf('%s()', $function->getName()); + } +} From 679b9a18b23979846205ac2e61946ac8169f375d Mon Sep 17 00:00:00 2001 From: everzet Date: Thu, 31 Aug 2017 11:14:14 +0100 Subject: [PATCH 068/567] Use Validator to validate call arguments --- src/Behat/Testwork/Call/Handler/RuntimeCallHandler.php | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/src/Behat/Testwork/Call/Handler/RuntimeCallHandler.php b/src/Behat/Testwork/Call/Handler/RuntimeCallHandler.php index 09267bbd4..62b3d1d6d 100644 --- a/src/Behat/Testwork/Call/Handler/RuntimeCallHandler.php +++ b/src/Behat/Testwork/Call/Handler/RuntimeCallHandler.php @@ -10,6 +10,7 @@ namespace Behat\Testwork\Call\Handler; +use Behat\Testwork\Argument\Validator; use Behat\Testwork\Call\Call; use Behat\Testwork\Call\CallResult; use Behat\Testwork\Call\Exception\CallErrorException; @@ -26,11 +27,14 @@ final class RuntimeCallHandler implements CallHandler * @var integer */ private $errorReportingLevel; - /** * @var bool */ private $obStarted = false; + /** + * @var Validator + */ + private $validator; /** * Initializes executor. @@ -40,6 +44,7 @@ final class RuntimeCallHandler implements CallHandler public function __construct($errorReportingLevel = E_ALL) { $this->errorReportingLevel = $errorReportingLevel; + $this->validator = new Validator(); } /** @@ -94,12 +99,13 @@ public function handleError($level, $message, $file, $line) */ private function executeCall(Call $call) { + $reflection = $call->getCallee()->getReflection(); $callable = $call->getBoundCallable(); $arguments = $call->getArguments(); - $return = $exception = null; try { + $this->validator->validateArguments($reflection, $arguments); $return = call_user_func_array($callable, $arguments); } catch (Exception $caught) { $exception = $caught; From 7de680106c07243503daae63e96e279d2a88d8e6 Mon Sep 17 00:00:00 2001 From: everzet Date: Thu, 31 Aug 2017 11:33:05 +0100 Subject: [PATCH 069/567] Post-refactoring cleanup --- src/Behat/Behat/Context/ContextFactory.php | 12 ++++--- src/Behat/Testwork/Argument/Validator.php | 39 ++++++++++++++++------ 2 files changed, 35 insertions(+), 16 deletions(-) diff --git a/src/Behat/Behat/Context/ContextFactory.php b/src/Behat/Behat/Context/ContextFactory.php index e9f5baaf7..b7a24422e 100644 --- a/src/Behat/Behat/Context/ContextFactory.php +++ b/src/Behat/Behat/Context/ContextFactory.php @@ -102,19 +102,21 @@ public function createContext($class, array $arguments = array(), array $singleU */ private function resolveArguments(ReflectionClass $reflection, array $arguments, array $resolvers) { + $newArguments = $arguments; + foreach ($resolvers as $resolver) { - $arguments = $resolver->resolveArguments($reflection, $arguments); + $newArguments = $resolver->resolveArguments($reflection, $newArguments); } if (!$reflection->hasMethod('__construct')) { - return $arguments; + return $newArguments; } $constructor = $reflection->getConstructor(); - $arguments = $this->argumentOrganiser->organiseArguments($constructor, $arguments); - $this->validator->validateArguments($constructor, $arguments); + $newArguments = $this->argumentOrganiser->organiseArguments($constructor, $newArguments); + $this->validator->validateArguments($constructor, $newArguments); - return $arguments; + return $newArguments; } /** diff --git a/src/Behat/Testwork/Argument/Validator.php b/src/Behat/Testwork/Argument/Validator.php index 7e3bd1c60..3d47e7e5a 100644 --- a/src/Behat/Testwork/Argument/Validator.php +++ b/src/Behat/Testwork/Argument/Validator.php @@ -13,6 +13,7 @@ use Behat\Testwork\Argument\Exception\UnknownParameterValueException; use ReflectionFunctionAbstract; use ReflectionMethod; +use ReflectionParameter; /** * Validates function arguments. @@ -32,20 +33,36 @@ final class Validator public function validateArguments(ReflectionFunctionAbstract $function, array $arguments) { foreach ($function->getParameters() as $num => $parameter) { - $name = $parameter->getName(); + $this->validateArgument($parameter, $num, $arguments); + } + } + + /** + * Validates given argument. + * + * @param ReflectionParameter $parameter + * @param integer $parameterIndex + * @param array $givenArguments + */ + private function validateArgument(ReflectionParameter $parameter, $parameterIndex, array $givenArguments) + { + if ($parameter->isDefaultValueAvailable()) { + return; + } - if ($parameter->isDefaultValueAvailable() - || array_key_exists($num, $arguments) - || array_key_exists($name, $arguments)) { - continue; - } + if (array_key_exists($parameterIndex, $givenArguments)) { + return; + } - throw new UnknownParameterValueException(sprintf( - 'Can not find a matching value for an argument `$%s` of the method `%s`.', - $name, - $this->getFunctionPath($function) - )); + if (array_key_exists($parameter->getName(), $givenArguments)) { + return; } + + throw new UnknownParameterValueException(sprintf( + 'Can not find a matching value for an argument `$%s` of the method `%s`.', + $parameter->getName(), + $this->getFunctionPath($parameter->getDeclaringFunction()) + )); } /** From 2e1911bfaf41dde0244995335232478eaf5be5ad Mon Sep 17 00:00:00 2001 From: everzet Date: Thu, 31 Aug 2017 11:34:00 +0100 Subject: [PATCH 070/567] Update CHANGELOG [ci skip] --- CHANGELOG.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 18ff849a3..5392af5b0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -14,6 +14,9 @@ and this project adheres to [Semantic Versioning](http://semver.org/). * [#1056](https://github.com/Behat/Behat/pull/1056): Make Gherkin aware of the base path so it can filter correctly +### Changed + * [#1069](https://github.com/Behat/Behat/pull/1069): Rework argument validators + ### Deprecated * [#1054](https://github.com/Behat/Behat/pull/1054): Deprecated usage of `Interop\Container`. Versions prior to `1.2` are not supported, but `1.2` From 78b54116c2901c500005e220a9f1f7b44f699021 Mon Sep 17 00:00:00 2001 From: everzet Date: Fri, 1 Sep 2017 09:45:27 +0100 Subject: [PATCH 071/567] Hold helper container instance on the Environment --- .../Argument/ArgumentResolverFactory.php | 32 ++++++++++++++++ .../Behat/Context/Argument/NullFactory.php | 11 +++++- .../Argument/SuiteScopedResolverFactory.php | 2 + .../Handler/ContextEnvironmentHandler.php | 30 ++++++++++++--- .../InitializedContextEnvironment.php | 23 ++++++++++- .../ServiceContainerEnvironment.php | 38 +++++++++++++++++++ .../Argument/ServicesResolverFactory.php | 25 +++++++++++- 7 files changed, 153 insertions(+), 8 deletions(-) create mode 100644 src/Behat/Behat/Context/Argument/ArgumentResolverFactory.php create mode 100644 src/Behat/Behat/Context/Environment/ServiceContainerEnvironment.php diff --git a/src/Behat/Behat/Context/Argument/ArgumentResolverFactory.php b/src/Behat/Behat/Context/Argument/ArgumentResolverFactory.php new file mode 100644 index 000000000..708c38bc7 --- /dev/null +++ b/src/Behat/Behat/Context/Argument/ArgumentResolverFactory.php @@ -0,0 +1,32 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Behat\Behat\Context\Argument; + +use Behat\Testwork\Environment\Environment; + +/** + * Creates argument resolvers for provided environment. + * + * @see ContextEnvironmentHandler + * + * @author Konstantin Kudryashov + */ +interface ArgumentResolverFactory +{ + /** + * Builds argument resolvers for provided suite. + * + * @param Environment $environment + * + * @return ArgumentResolver[] + */ + public function createArgumentResolvers(Environment $environment); +} diff --git a/src/Behat/Behat/Context/Argument/NullFactory.php b/src/Behat/Behat/Context/Argument/NullFactory.php index 6265cc4c2..c2e070c40 100644 --- a/src/Behat/Behat/Context/Argument/NullFactory.php +++ b/src/Behat/Behat/Context/Argument/NullFactory.php @@ -10,6 +10,7 @@ namespace Behat\Behat\Context\Argument; +use Behat\Testwork\Environment\Environment; use Behat\Testwork\Suite\Suite; /** @@ -19,7 +20,7 @@ * * @author Konstantin Kudryashov */ -final class NullFactory implements SuiteScopedResolverFactory +final class NullFactory implements ArgumentResolverFactory, SuiteScopedResolverFactory { /** * {@inheritdoc} @@ -28,4 +29,12 @@ public function generateArgumentResolvers(Suite $suite) { return array(); } + + /** + * {@inheritdoc} + */ + public function createArgumentResolvers(Environment $environment) + { + return array(); + } } diff --git a/src/Behat/Behat/Context/Argument/SuiteScopedResolverFactory.php b/src/Behat/Behat/Context/Argument/SuiteScopedResolverFactory.php index 60d858826..9f953fc2d 100644 --- a/src/Behat/Behat/Context/Argument/SuiteScopedResolverFactory.php +++ b/src/Behat/Behat/Context/Argument/SuiteScopedResolverFactory.php @@ -18,6 +18,8 @@ * @see ContextEnvironmentHandler * * @author Konstantin Kudryashov + * + * @deprecated since 3.4. Use `ArgumentResolverFactory` instead */ interface SuiteScopedResolverFactory { diff --git a/src/Behat/Behat/Context/Environment/Handler/ContextEnvironmentHandler.php b/src/Behat/Behat/Context/Environment/Handler/ContextEnvironmentHandler.php index d5c3a0fce..0b9b9b127 100644 --- a/src/Behat/Behat/Context/Environment/Handler/ContextEnvironmentHandler.php +++ b/src/Behat/Behat/Context/Environment/Handler/ContextEnvironmentHandler.php @@ -10,10 +10,12 @@ namespace Behat\Behat\Context\Environment\Handler; +use Behat\Behat\Context\Argument\ArgumentResolver; use Behat\Behat\Context\Argument\SuiteScopedResolverFactory; use Behat\Behat\Context\Argument\NullFactory; use Behat\Behat\Context\ContextClass\ClassResolver; use Behat\Behat\Context\ContextFactory; +use Behat\Behat\Context\Environment\ContextEnvironment; use Behat\Behat\Context\Environment\InitializedContextEnvironment; use Behat\Behat\Context\Environment\UninitializedContextEnvironment; use Behat\Testwork\Environment\Environment; @@ -36,7 +38,7 @@ final class ContextEnvironmentHandler implements EnvironmentHandler */ private $contextFactory; /** - * @var SuiteScopedResolverFactory + * @var ArgumentResolver|SuiteScopedResolverFactory */ private $resolverFactory; /** @@ -47,10 +49,10 @@ final class ContextEnvironmentHandler implements EnvironmentHandler /** * Initializes handler. * - * @param ContextFactory $factory - * @param SuiteScopedResolverFactory $resolverFactory + * @param ContextFactory $factory + * @param ArgumentResolver|SuiteScopedResolverFactory $resolverFactory */ - public function __construct(ContextFactory $factory, SuiteScopedResolverFactory $resolverFactory = null) + public function __construct(ContextFactory $factory, $resolverFactory = null) { $this->contextFactory = $factory; $this->resolverFactory = $resolverFactory ?: new NullFactory(); @@ -108,7 +110,7 @@ public function isolateEnvironment(Environment $uninitializedEnvironment, $testS } $environment = new InitializedContextEnvironment($uninitializedEnvironment->getSuite()); - $resolvers = $this->resolverFactory->generateArgumentResolvers($uninitializedEnvironment->getSuite()); + $resolvers = $this->createArgumentResolvers($environment); foreach ($uninitializedEnvironment->getContextClassesWithArguments() as $class => $arguments) { $context = $this->contextFactory->createContext($class, $arguments, $resolvers); @@ -184,4 +186,22 @@ private function resolveClass($class) return $class; } + + /** + * Creates argument resolvers for a given environment. + * + * @param ContextEnvironment $environment + * + * @return ArgumentResolver[] + */ + private function createArgumentResolvers(ContextEnvironment $environment) + { + if ($this->resolverFactory instanceof ArgumentResolver) { + return $this->resolverFactory->createArgumentResolvers($environment); + } elseif ($this->resolverFactory instanceof SuiteScopedResolverFactory) { + return $this->resolverFactory->generateArgumentResolvers($environment->getSuite()); + } + + return array(); + } } diff --git a/src/Behat/Behat/Context/Environment/InitializedContextEnvironment.php b/src/Behat/Behat/Context/Environment/InitializedContextEnvironment.php index c26826ecf..d03e6df1b 100644 --- a/src/Behat/Behat/Context/Environment/InitializedContextEnvironment.php +++ b/src/Behat/Behat/Context/Environment/InitializedContextEnvironment.php @@ -15,6 +15,7 @@ use Behat\Behat\Context\Exception\ContextNotFoundException; use Behat\Testwork\Call\Callee; use Behat\Testwork\Suite\Suite; +use Psr\Container\ContainerInterface; /** * Context environment based on a list of instantiated context objects. @@ -23,12 +24,16 @@ * * @author Konstantin Kudryashov */ -final class InitializedContextEnvironment implements ContextEnvironment +final class InitializedContextEnvironment implements ContextEnvironment, ServiceContainerEnvironment { /** * @var string */ private $suite; + /** + * @var ContainerInterface + */ + private $serviceContainer; /** * @var Context[] */ @@ -54,6 +59,14 @@ public function registerContext(Context $context) $this->contexts[get_class($context)] = $context; } + /** + * {@inheritdoc} + */ + public function setServiceContainer(ContainerInterface $container = null) + { + $this->serviceContainer = $container; + } + /** * {@inheritdoc} */ @@ -117,6 +130,14 @@ public function getContext($class) return $this->contexts[$class]; } + /** + * {@inheritdoc} + */ + public function getServiceContainer() + { + return $this->serviceContainer; + } + /** * {@inheritdoc} */ diff --git a/src/Behat/Behat/Context/Environment/ServiceContainerEnvironment.php b/src/Behat/Behat/Context/Environment/ServiceContainerEnvironment.php new file mode 100644 index 000000000..cc72bb7c1 --- /dev/null +++ b/src/Behat/Behat/Context/Environment/ServiceContainerEnvironment.php @@ -0,0 +1,38 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Behat\Behat\Context\Environment; + +use Behat\Testwork\Environment\Environment; +use Psr\Container\ContainerInterface; + +/** + * Represents test environment based on a service locator pattern. + * + * @see ContextEnvironmentHandler + * + * @author Konstantin Kudryashov + */ +interface ServiceContainerEnvironment extends Environment +{ + /** + * Sets/unsets service container for the environment. + * + * @param ContainerInterface|null $container + */ + public function setServiceContainer(ContainerInterface $container = null); + + /** + * Returns environment service container if set. + * + * @return null|ContainerInterface + */ + public function getServiceContainer(); +} diff --git a/src/Behat/Behat/HelperContainer/Argument/ServicesResolverFactory.php b/src/Behat/Behat/HelperContainer/Argument/ServicesResolverFactory.php index 25617033f..a95d14d5a 100644 --- a/src/Behat/Behat/HelperContainer/Argument/ServicesResolverFactory.php +++ b/src/Behat/Behat/HelperContainer/Argument/ServicesResolverFactory.php @@ -10,11 +10,14 @@ namespace Behat\Behat\HelperContainer\Argument; +use Behat\Behat\Context\Environment\ServiceContainerEnvironment; +use Behat\Behat\Context\Argument\ArgumentResolverFactory; use Behat\Behat\Context\Argument\SuiteScopedResolverFactory; use Behat\Behat\HelperContainer\BuiltInServiceContainer; use Behat\Behat\HelperContainer\Exception\WrongContainerClassException; use Behat\Behat\HelperContainer\Exception\WrongServicesConfigurationException; use Behat\Behat\HelperContainer\ServiceContainer\HelperContainerExtension; +use Behat\Testwork\Environment\Environment; use Behat\Testwork\Suite\Suite; use Psr\Container\ContainerInterface; use Symfony\Component\DependencyInjection\TaggedContainerInterface; @@ -26,7 +29,7 @@ * * @author Konstantin Kudryashov */ -final class ServicesResolverFactory implements SuiteScopedResolverFactory +final class ServicesResolverFactory implements SuiteScopedResolverFactory, ArgumentResolverFactory { /** * @var TaggedContainerInterface @@ -45,6 +48,8 @@ public function __construct(TaggedContainerInterface $container) /** * {@inheritdoc} + * + * @deprecated */ public function generateArgumentResolvers(Suite $suite) { @@ -57,6 +62,24 @@ public function generateArgumentResolvers(Suite $suite) return array($this->createArgumentResolver($container)); } + /** + * {@inheritdoc} + */ + public function createArgumentResolvers(Environment $environment) + { + if (!$environment->getSuite()->hasSetting('services')) { + return array(); + } + + $container = $this->createContainer($environment->getSuite()->getSetting('services')); + + if ($environment instanceof ServiceContainerEnvironment) { + $environment->setServiceContainer($container); + } + + return array($this->createArgumentResolver($container)); + } + /** * Creates container from the setting passed. * From 1168d1b9e7587c18321756b2e684f5deb36f1f60 Mon Sep 17 00:00:00 2001 From: everzet Date: Fri, 1 Sep 2017 13:35:54 +0100 Subject: [PATCH 072/567] Refactor towards SuiteScopedResolverFactoryAdapter --- .../SuiteScopedResolverFactoryAdapter.php | 48 +++++++++++++++++++ .../Handler/ContextEnvironmentHandler.php | 42 +++++++--------- 2 files changed, 66 insertions(+), 24 deletions(-) create mode 100644 src/Behat/Behat/Context/Argument/SuiteScopedResolverFactoryAdapter.php diff --git a/src/Behat/Behat/Context/Argument/SuiteScopedResolverFactoryAdapter.php b/src/Behat/Behat/Context/Argument/SuiteScopedResolverFactoryAdapter.php new file mode 100644 index 000000000..2317c8eb6 --- /dev/null +++ b/src/Behat/Behat/Context/Argument/SuiteScopedResolverFactoryAdapter.php @@ -0,0 +1,48 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Behat\Behat\Context\Argument; + +use Behat\Testwork\Environment\Environment; + +/** + * Adapts SuiteScopedResolverFactory to new ArgumentResolverFactory interface. + * + * @see ContextEnvironmentHandler + * + * @author Konstantin Kudryashov + * + * @deprecated since 3.4. Use `ArgumentResolverFactory` instead + */ +final class SuiteScopedResolverFactoryAdapter implements ArgumentResolverFactory +{ + /** + * @var SuiteScopedResolverFactory + */ + private $factory; + + /** + * Initialises adapter. + * + * @param SuiteScopedResolverFactory $factory + */ + public function __construct(SuiteScopedResolverFactory $factory) + { + $this->factory = $factory; + } + + /** + * {@inheritdoc} + */ + public function createArgumentResolvers(Environment $environment) + { + return $this->factory->generateArgumentResolvers($environment->getSuite()); + } +} diff --git a/src/Behat/Behat/Context/Environment/Handler/ContextEnvironmentHandler.php b/src/Behat/Behat/Context/Environment/Handler/ContextEnvironmentHandler.php index 0b9b9b127..7b8098233 100644 --- a/src/Behat/Behat/Context/Environment/Handler/ContextEnvironmentHandler.php +++ b/src/Behat/Behat/Context/Environment/Handler/ContextEnvironmentHandler.php @@ -10,12 +10,12 @@ namespace Behat\Behat\Context\Environment\Handler; -use Behat\Behat\Context\Argument\ArgumentResolver; use Behat\Behat\Context\Argument\SuiteScopedResolverFactory; +use Behat\Behat\Context\Argument\SuiteScopedResolverFactoryAdapter; +use Behat\Behat\Context\Argument\ArgumentResolverFactory; use Behat\Behat\Context\Argument\NullFactory; use Behat\Behat\Context\ContextClass\ClassResolver; use Behat\Behat\Context\ContextFactory; -use Behat\Behat\Context\Environment\ContextEnvironment; use Behat\Behat\Context\Environment\InitializedContextEnvironment; use Behat\Behat\Context\Environment\UninitializedContextEnvironment; use Behat\Testwork\Environment\Environment; @@ -23,6 +23,7 @@ use Behat\Testwork\Environment\Handler\EnvironmentHandler; use Behat\Testwork\Suite\Exception\SuiteConfigurationException; use Behat\Testwork\Suite\Suite; +use Webmozart\Assert\Assert; /** * Handles build and initialisation of the context-based environments. @@ -38,7 +39,7 @@ final class ContextEnvironmentHandler implements EnvironmentHandler */ private $contextFactory; /** - * @var ArgumentResolver|SuiteScopedResolverFactory + * @var ArgumentResolverFactory */ private $resolverFactory; /** @@ -49,12 +50,23 @@ final class ContextEnvironmentHandler implements EnvironmentHandler /** * Initializes handler. * - * @param ContextFactory $factory - * @param ArgumentResolver|SuiteScopedResolverFactory $resolverFactory + * @param ContextFactory $factory + * @param ArgumentResolverFactory|SuiteScopedResolverFactory $resolverFactory */ public function __construct(ContextFactory $factory, $resolverFactory = null) { $this->contextFactory = $factory; + + if ($resolverFactory && !$resolverFactory instanceof ArgumentResolverFactory) { + Assert::isInstanceOf( + $resolverFactory, + 'Behat\Behat\Context\Argument\SuiteScopedResolverFactory', + 'Argument resolver must implement ArgumentResolverFactory or SuiteScopedResolverFactory (deprecated)' + ); + + $resolverFactory = new SuiteScopedResolverFactoryAdapter($resolverFactory); + } + $this->resolverFactory = $resolverFactory ?: new NullFactory(); } @@ -110,7 +122,7 @@ public function isolateEnvironment(Environment $uninitializedEnvironment, $testS } $environment = new InitializedContextEnvironment($uninitializedEnvironment->getSuite()); - $resolvers = $this->createArgumentResolvers($environment); + $resolvers = $this->resolverFactory->createArgumentResolvers($environment); foreach ($uninitializedEnvironment->getContextClassesWithArguments() as $class => $arguments) { $context = $this->contextFactory->createContext($class, $arguments, $resolvers); @@ -186,22 +198,4 @@ private function resolveClass($class) return $class; } - - /** - * Creates argument resolvers for a given environment. - * - * @param ContextEnvironment $environment - * - * @return ArgumentResolver[] - */ - private function createArgumentResolvers(ContextEnvironment $environment) - { - if ($this->resolverFactory instanceof ArgumentResolver) { - return $this->resolverFactory->createArgumentResolvers($environment); - } elseif ($this->resolverFactory instanceof SuiteScopedResolverFactory) { - return $this->resolverFactory->generateArgumentResolvers($environment->getSuite()); - } - - return array(); - } } From eea03496d0b1a2d14de8c8b808a8e9831a8bbf4a Mon Sep 17 00:00:00 2001 From: everzet Date: Fri, 1 Sep 2017 13:38:39 +0100 Subject: [PATCH 073/567] Trigger deprecation warning --- .../HelperContainer/Argument/ServicesResolverFactory.php | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/src/Behat/Behat/HelperContainer/Argument/ServicesResolverFactory.php b/src/Behat/Behat/HelperContainer/Argument/ServicesResolverFactory.php index a95d14d5a..c6520e887 100644 --- a/src/Behat/Behat/HelperContainer/Argument/ServicesResolverFactory.php +++ b/src/Behat/Behat/HelperContainer/Argument/ServicesResolverFactory.php @@ -49,10 +49,15 @@ public function __construct(TaggedContainerInterface $container) /** * {@inheritdoc} * - * @deprecated + * @deprecated as part of SuiteScopedResolverFactory deprecation. Would be removed in 4.0 */ public function generateArgumentResolvers(Suite $suite) { + @trigger_error( + 'SuiteScopedResolverFactory::generateArgumentResolvers() was deprecated and will be removed in 4.0', + E_USER_DEPRECATED + ); + if (!$suite->hasSetting('services')) { return array(); } From 8b699c58973f082e6537125c19bd11b12d11b920 Mon Sep 17 00:00:00 2001 From: everzet Date: Fri, 1 Sep 2017 13:53:50 +0100 Subject: [PATCH 074/567] Remove Assert --- .../Environment/Handler/ContextEnvironmentHandler.php | 7 ------- 1 file changed, 7 deletions(-) diff --git a/src/Behat/Behat/Context/Environment/Handler/ContextEnvironmentHandler.php b/src/Behat/Behat/Context/Environment/Handler/ContextEnvironmentHandler.php index 7b8098233..d686400dd 100644 --- a/src/Behat/Behat/Context/Environment/Handler/ContextEnvironmentHandler.php +++ b/src/Behat/Behat/Context/Environment/Handler/ContextEnvironmentHandler.php @@ -23,7 +23,6 @@ use Behat\Testwork\Environment\Handler\EnvironmentHandler; use Behat\Testwork\Suite\Exception\SuiteConfigurationException; use Behat\Testwork\Suite\Suite; -use Webmozart\Assert\Assert; /** * Handles build and initialisation of the context-based environments. @@ -58,12 +57,6 @@ public function __construct(ContextFactory $factory, $resolverFactory = null) $this->contextFactory = $factory; if ($resolverFactory && !$resolverFactory instanceof ArgumentResolverFactory) { - Assert::isInstanceOf( - $resolverFactory, - 'Behat\Behat\Context\Argument\SuiteScopedResolverFactory', - 'Argument resolver must implement ArgumentResolverFactory or SuiteScopedResolverFactory (deprecated)' - ); - $resolverFactory = new SuiteScopedResolverFactoryAdapter($resolverFactory); } From 74c665dcc28e18a34142032ddfcc5fd8333d74c8 Mon Sep 17 00:00:00 2001 From: everzet Date: Sun, 3 Sep 2017 11:07:19 +0100 Subject: [PATCH 075/567] Fix release building --- .travis.yml | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/.travis.yml b/.travis.yml index c33d5edad..7477ba96d 100644 --- a/.travis.yml +++ b/.travis.yml @@ -52,12 +52,9 @@ before_deploy: deploy: provider: releases - api_key: - secure: KLoJVMKTdabtNxRxVk92Lx9+ifK6nyYx2ATRflvaxJLJ0tkbvdkYwFnd79JuarE2FlJ65/Jd2Buy+dXCRPUkEaQ5Mg5IeZQg9C9qjTCjPE46n1nFa9487b/ZWsmx/iE7Bh8D2+A5CiEC62EXxWxf2i41IKaCr6t2ws49EjGOp+0= + api_key: $GITHUB_API_KEY file: behat.phar skip_cleanup: true on: - repo: Behat/Behat tags: true - php: 5.6 - condition: $SYMFONY_VERSION == "2.8.*" + php: 5.4 From 421e60098a81290d17a2092332b298133afbc7e6 Mon Sep 17 00:00:00 2001 From: everzet Date: Fri, 1 Sep 2017 15:29:35 +0100 Subject: [PATCH 076/567] Initial pass at services autowiring --- features/autowire.feature | 162 ++++++++++++++++++ .../CompositeArgumentResolverFactory.php | 52 ++++++ .../Context/Argument/CompositeFactory.php | 2 + .../ServiceContainer/ContextExtension.php | 2 +- .../Argument/ServicesResolver.php | 24 ++- .../Argument/ServicesResolverFactory.php | 16 +- .../Call/Filter/ServicesResolver.php | 90 ++++++++++ .../Exception/UnsupportedCallException.php | 50 ++++++ .../HelperContainerExtension.php | 5 + 9 files changed, 394 insertions(+), 9 deletions(-) create mode 100644 features/autowire.feature create mode 100644 src/Behat/Behat/Context/Argument/CompositeArgumentResolverFactory.php create mode 100644 src/Behat/Behat/HelperContainer/Call/Filter/ServicesResolver.php create mode 100644 src/Behat/Behat/HelperContainer/Exception/UnsupportedCallException.php diff --git a/features/autowire.feature b/features/autowire.feature new file mode 100644 index 000000000..8470eeb36 --- /dev/null +++ b/features/autowire.feature @@ -0,0 +1,162 @@ +Feature: Helper services autowire + In order to speed up the development process at early stages + developers need to have a convenient way of requesting services without going through the explicit configuration layer + + Rules: + - Autowiring only works with helper containers + - Autowiring is off by default + - Autowiring is enabled/disabled by a suite-level `autowire` flag + - It works for context constructor arguments + - It works for step definition arguments + - It works for transformation arguments + - It only wires arguments that weren't otherwise set + + Background: + Given a file named "behat.yaml" with: + """ + default: + suites: + default: + services: ServiceContainer + autowire: true + """ + And a file named "features/bootstrap/ServiceContainer.php" with: + """ + services[$class]) + ? $this->services[$class] + : $this->services[$class] = new $class; + } + } + """ + + Scenario: Constructor arguments + Given a file named "features/autowire.feature" with: + """ + Feature: + Scenario: + Given a step + """ + And a file named "features/bootstrap/FeatureContext.php" with: + """ + state = $value; + } + + /** @Then that state should be persisted as :value */ + public function checkState($val, Service2 $s2) { + PHPUnit_Framework_Assert::assertEquals($val, $s2->state); + } + } + """ + When I run "behat --no-colors -f progress features/autowire.feature" + Then it should pass + + Scenario: Transformation arguments + Given a file named "features/autowire.feature" with: + """ + Feature: + Scenario: + When I set the "myFlag" flag to "isSet" + Then the "myFlag" flag should be persisted as "isSet" + """ + And a file named "features/bootstrap/FeatureContext.php" with: + """ + $flag; + } + + /** @When I set the :flat flag to :value */ + public function setState($flag, $value, Service2 $s2) { + $s2->$flag = $value; + } + + /** @Then the :flag flag should be persisted as :value */ + public function checkState($flag, $value) { + PHPUnit_Framework_Assert::assertEquals($value, $flag); + } + } + """ + When I run "behat --no-colors -f progress features/autowire.feature" + Then it should pass diff --git a/src/Behat/Behat/Context/Argument/CompositeArgumentResolverFactory.php b/src/Behat/Behat/Context/Argument/CompositeArgumentResolverFactory.php new file mode 100644 index 000000000..fbfd69c83 --- /dev/null +++ b/src/Behat/Behat/Context/Argument/CompositeArgumentResolverFactory.php @@ -0,0 +1,52 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Behat\Behat\Context\Argument; + +use Behat\Testwork\Environment\Environment; + +/** + * Composite factory. Delegates to other (registered) factories to do the job. + * + * @see ContextEnvironmentHandler + * + * @author Konstantin Kudryashov + */ +final class CompositeArgumentResolverFactory implements ArgumentResolverFactory +{ + /** + * @var ArgumentResolverFactory[] + */ + private $factories = array(); + + /** + * Registers factory. + * + * @param ArgumentResolverFactory $factory + */ + public function registerFactory(ArgumentResolverFactory $factory) + { + $this->factories[] = $factory; + } + + /** + * {@inheritdoc} + */ + public function createArgumentResolvers(Environment $environment) + { + return array_reduce( + $this->factories, + function (array $resolvers, ArgumentResolverFactory $factory) use ($environment) { + return array_merge($resolvers, $factory->createArgumentResolvers($environment)); + }, + array() + ); + } +} diff --git a/src/Behat/Behat/Context/Argument/CompositeFactory.php b/src/Behat/Behat/Context/Argument/CompositeFactory.php index 822896c8a..5b3d93f84 100644 --- a/src/Behat/Behat/Context/Argument/CompositeFactory.php +++ b/src/Behat/Behat/Context/Argument/CompositeFactory.php @@ -18,6 +18,8 @@ * @see ContextEnvironmentHandler * * @author Konstantin Kudryashov + * + * @deprecated and will be removed in 4.0. Use CompositeArgumentResolverFactory instead */ final class CompositeFactory implements SuiteScopedResolverFactory { diff --git a/src/Behat/Behat/Context/ServiceContainer/ContextExtension.php b/src/Behat/Behat/Context/ServiceContainer/ContextExtension.php index de3f35248..f4c6917b7 100644 --- a/src/Behat/Behat/Context/ServiceContainer/ContextExtension.php +++ b/src/Behat/Behat/Context/ServiceContainer/ContextExtension.php @@ -142,7 +142,7 @@ private function loadFactory(ContainerBuilder $container) */ private function loadArgumentResolverFactory(ContainerBuilder $container) { - $definition = new Definition('Behat\Behat\Context\Argument\CompositeFactory'); + $definition = new Definition('Behat\Behat\Context\Argument\CompositeArgumentResolverFactory'); $container->setDefinition(self::AGGREGATE_RESOLVER_FACTORY_ID, $definition); } diff --git a/src/Behat/Behat/HelperContainer/Argument/ServicesResolver.php b/src/Behat/Behat/HelperContainer/Argument/ServicesResolver.php index 1031a0587..6052e1ca4 100644 --- a/src/Behat/Behat/HelperContainer/Argument/ServicesResolver.php +++ b/src/Behat/Behat/HelperContainer/Argument/ServicesResolver.php @@ -27,15 +27,21 @@ final class ServicesResolver implements ArgumentResolver * @var ContainerInterface */ private $container; + /** + * @var bool + */ + private $autowire; /** * Initialises resolver. * * @param ContainerInterface $container + * @param bool $autowire */ - public function __construct(ContainerInterface $container) + public function __construct(ContainerInterface $container, $autowire = false) { $this->container = $container; + $this->autowire = $autowire; } /** @@ -43,7 +49,21 @@ public function __construct(ContainerInterface $container) */ public function resolveArguments(ReflectionClass $classReflection, array $arguments) { - return array_map(array($this, 'resolveArgument'), $arguments); + $newArguments = array_map(array($this, 'resolveArgument'), $arguments); + + if ($this->autowire && $classReflection->getConstructor()) { + foreach ($classReflection->getConstructor()->getParameters() as $index => $parameter) { + if (isset($newArguments[$index]) || isset($newArguments[$parameter->getName()])) { + continue; + } + + if ($parameter->hasType() && $this->container->has($parameter->getType()->getName())) { + $newArguments[$index] = $this->container->get($parameter->getType()->getName()); + } + } + } + + return $newArguments; } /** diff --git a/src/Behat/Behat/HelperContainer/Argument/ServicesResolverFactory.php b/src/Behat/Behat/HelperContainer/Argument/ServicesResolverFactory.php index c6520e887..07bc7d2d7 100644 --- a/src/Behat/Behat/HelperContainer/Argument/ServicesResolverFactory.php +++ b/src/Behat/Behat/HelperContainer/Argument/ServicesResolverFactory.php @@ -64,7 +64,7 @@ public function generateArgumentResolvers(Suite $suite) $container = $this->createContainer($suite->getSetting('services')); - return array($this->createArgumentResolver($container)); + return array($this->createArgumentResolver($container, false)); } /** @@ -72,17 +72,20 @@ public function generateArgumentResolvers(Suite $suite) */ public function createArgumentResolvers(Environment $environment) { - if (!$environment->getSuite()->hasSetting('services')) { + $suite = $environment->getSuite(); + + if (!$suite->hasSetting('services')) { return array(); } - $container = $this->createContainer($environment->getSuite()->getSetting('services')); + $container = $this->createContainer($suite->getSetting('services')); + $autowire = $suite->hasSetting('autowire') && $suite->getSetting('autowire'); if ($environment instanceof ServiceContainerEnvironment) { $environment->setServiceContainer($container); } - return array($this->createArgumentResolver($container)); + return array($this->createArgumentResolver($container, $autowire)); } /** @@ -177,10 +180,11 @@ private function createContainerFromClassSpec($classSpec) * Checks if container implements the correct interface and creates resolver using it. * * @param mixed $container + * @param bool $autowire * * @return ServicesResolver */ - private function createArgumentResolver($container) + private function createArgumentResolver($container, $autowire) { if (!$container instanceof ContainerInterface) { throw new WrongContainerClassException( @@ -192,6 +196,6 @@ private function createArgumentResolver($container) ); } - return new ServicesResolver($container); + return new ServicesResolver($container, $autowire); } } diff --git a/src/Behat/Behat/HelperContainer/Call/Filter/ServicesResolver.php b/src/Behat/Behat/HelperContainer/Call/Filter/ServicesResolver.php new file mode 100644 index 000000000..368dcb673 --- /dev/null +++ b/src/Behat/Behat/HelperContainer/Call/Filter/ServicesResolver.php @@ -0,0 +1,90 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Behat\Behat\HelperContainer\Call\Filter; + +use Behat\Behat\Context\Environment\ServiceContainerEnvironment; +use Behat\Behat\Definition\Call\DefinitionCall; +use Behat\Behat\HelperContainer\Exception\UnsupportedCallException; +use Behat\Behat\Transformation\Call\TransformationCall; +use Behat\Testwork\Call\Call; +use Behat\Testwork\Call\Filter\CallFilter; +use Behat\Testwork\Environment\Call\EnvironmentCall; + +/** + * Dynamically resolves call arguments using the service container. + * + * @author Konstantin Kudryashov + */ +final class ServicesResolver implements CallFilter +{ + /** + * {@inheritdoc} + */ + public function supportsCall(Call $call) + { + return ($call instanceof DefinitionCall || $call instanceof TransformationCall) + && $call->getEnvironment() instanceof ServiceContainerEnvironment; + } + + /** + * Filters a call and returns a new one. + * + * @param Call $call + * + * @return Call + */ + public function filterCall(Call $call) + { + if (!$call instanceof EnvironmentCall || !$call->getEnvironment() instanceof ServiceContainerEnvironment) { + throw new UnsupportedCallException(sprintf( + 'ServicesResolver can not filter `%s` call.', + get_class($call) + ), $call); + } + + $container = $call->getEnvironment()->getServiceContainer(); + $newArguments = $call->getArguments(); + + if ($container) { + foreach ($call->getCallee()->getReflection()->getParameters() as $index => $parameter) { + if (isset($newArguments[$index]) || isset($newArguments[$parameter->getName()])) { + continue; + } + + if ($parameter->hasType() && $container->has((string) $parameter->getType())) { + $newArguments[$index] = $container->get((string) $parameter->getType()); + } + } + } + + if ($call instanceof DefinitionCall) { + return new DefinitionCall( + $call->getEnvironment(), + $call->getFeature(), + $call->getStep(), + $call->getCallee(), + $newArguments, + $call->getErrorReportingLevel() + ); + } + + if ($call instanceof TransformationCall) { + return new TransformationCall( + $call->getEnvironment(), + $call->getDefinition(), + $call->getCallee(), + $newArguments + ); + } + + return $call; + } +} diff --git a/src/Behat/Behat/HelperContainer/Exception/UnsupportedCallException.php b/src/Behat/Behat/HelperContainer/Exception/UnsupportedCallException.php new file mode 100644 index 000000000..7f16ca82f --- /dev/null +++ b/src/Behat/Behat/HelperContainer/Exception/UnsupportedCallException.php @@ -0,0 +1,50 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Behat\Behat\HelperContainer\Exception; + +use Behat\Testwork\Call\Call; +use InvalidArgumentException; + +/** + * Represents an exception caused by an attempt to filter an unsupported call. + * + * @author Konstantin Kudryashov + */ +final class UnsupportedCallException extends InvalidArgumentException implements HelperContainerException +{ + /** + * @var Call + */ + private $call; + + /** + * Initializes exception. + * + * @param string $message + * @param Call $call + */ + public function __construct($message, Call $call) + { + parent::__construct($message); + + $this->call = $call; + } + + /** + * Returns a call that caused exception. + * + * @return Call + */ + public function getCall() + { + return $this->call; + } +} diff --git a/src/Behat/Behat/HelperContainer/ServiceContainer/HelperContainerExtension.php b/src/Behat/Behat/HelperContainer/ServiceContainer/HelperContainerExtension.php index 09ff59400..1d5100f5c 100644 --- a/src/Behat/Behat/HelperContainer/ServiceContainer/HelperContainerExtension.php +++ b/src/Behat/Behat/HelperContainer/ServiceContainer/HelperContainerExtension.php @@ -12,6 +12,7 @@ use Behat\Behat\Context\ServiceContainer\ContextExtension; use Behat\Behat\HelperContainer\Exception\WrongServicesConfigurationException; +use Behat\Testwork\Call\ServiceContainer\CallExtension; use Behat\Testwork\ServiceContainer\Extension; use Behat\Testwork\ServiceContainer\ExtensionManager; use Behat\Testwork\ServiceContainer\ServiceProcessor; @@ -78,6 +79,10 @@ public function load(ContainerBuilder $container, array $config) $definition = new Definition('Behat\Behat\HelperContainer\Argument\ServicesResolverFactory', array($container)); $definition->addTag(ContextExtension::SUITE_SCOPED_RESOLVER_FACTORY_TAG, array('priority' => 0)); $container->setDefinition(ContextExtension::SUITE_SCOPED_RESOLVER_FACTORY_TAG . '.helper_container', $definition); + + $definition = new Definition('Behat\Behat\HelperContainer\Call\Filter\ServicesResolver'); + $definition->addTag(CallExtension::CALL_FILTER_TAG, array('priority' => 0)); + $container->setDefinition(CallExtension::CALL_FILTER_TAG . '.helper_container', $definition); } /** From 31974c10a908c92aeef9244739f712a795f61772 Mon Sep 17 00:00:00 2001 From: everzet Date: Fri, 1 Sep 2017 16:39:30 +0100 Subject: [PATCH 077/567] Use php5-compatible reflection API --- src/Behat/Behat/HelperContainer/Argument/ServicesResolver.php | 4 ++-- .../Behat/HelperContainer/Call/Filter/ServicesResolver.php | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/Behat/Behat/HelperContainer/Argument/ServicesResolver.php b/src/Behat/Behat/HelperContainer/Argument/ServicesResolver.php index 6052e1ca4..57ea55fe2 100644 --- a/src/Behat/Behat/HelperContainer/Argument/ServicesResolver.php +++ b/src/Behat/Behat/HelperContainer/Argument/ServicesResolver.php @@ -57,8 +57,8 @@ public function resolveArguments(ReflectionClass $classReflection, array $argume continue; } - if ($parameter->hasType() && $this->container->has($parameter->getType()->getName())) { - $newArguments[$index] = $this->container->get($parameter->getType()->getName()); + if ($parameter->getClass() && $this->container->has($parameter->getClass()->getName())) { + $newArguments[$index] = $this->container->get($parameter->getClass()->getName()); } } } diff --git a/src/Behat/Behat/HelperContainer/Call/Filter/ServicesResolver.php b/src/Behat/Behat/HelperContainer/Call/Filter/ServicesResolver.php index 368dcb673..3c150a076 100644 --- a/src/Behat/Behat/HelperContainer/Call/Filter/ServicesResolver.php +++ b/src/Behat/Behat/HelperContainer/Call/Filter/ServicesResolver.php @@ -59,8 +59,8 @@ public function filterCall(Call $call) continue; } - if ($parameter->hasType() && $container->has((string) $parameter->getType())) { - $newArguments[$index] = $container->get((string) $parameter->getType()); + if ($parameter->getClass() && $container->has($parameter->getClass()->getName())) { + $newArguments[$index] = $container->get($parameter->getClass()->getName()); } } } From 894a0835d8ce978965766404765bc616d953713e Mon Sep 17 00:00:00 2001 From: everzet Date: Fri, 1 Sep 2017 16:40:05 +0100 Subject: [PATCH 078/567] Fix scenario title --- features/autowire.feature | 2 -- 1 file changed, 2 deletions(-) diff --git a/features/autowire.feature b/features/autowire.feature index 8470eeb36..589228796 100644 --- a/features/autowire.feature +++ b/features/autowire.feature @@ -101,8 +101,6 @@ Feature: Helper services autowire Then it should pass Scenario: Step definition arguments - - Scenario: Constructor arguments Given a file named "features/autowire.feature" with: """ Feature: From b69dce1c617ef7c8109a4a212051af639899ffe4 Mon Sep 17 00:00:00 2001 From: everzet Date: Fri, 1 Sep 2017 17:00:00 +0100 Subject: [PATCH 079/567] Refactoring and handling of negative cases --- features/autowire.feature | 59 +++++++++++- .../Argument/ServicesResolver.php | 37 +++++-- .../Call/Filter/ServicesResolver.php | 96 ++++++++++++++----- 3 files changed, 160 insertions(+), 32 deletions(-) diff --git a/features/autowire.feature b/features/autowire.feature index 589228796..700579a2b 100644 --- a/features/autowire.feature +++ b/features/autowire.feature @@ -17,8 +17,8 @@ Feature: Helper services autowire default: suites: default: - services: ServiceContainer autowire: true + services: ServiceContainer """ And a file named "features/bootstrap/ServiceContainer.php" with: """ @@ -27,6 +27,7 @@ Feature: Helper services autowire class Service1 {public $state;} class Service2 {public $state;} class Service3 {public $state;} + class Service4 {public $state;} class ServiceContainer implements ContainerInterface { private $services = array(); @@ -36,6 +37,9 @@ Feature: Helper services autowire } public function get($class) { + if (!$this->has($class)) + throw new \Behat\Behat\HelperContainer\Exception\ServiceNotFoundException("Service $class not found", $class); + return isset($this->services[$class]) ? $this->services[$class] : $this->services[$class] = new $class; @@ -100,6 +104,31 @@ Feature: Helper services autowire When I run "behat --no-colors -f progress features/autowire.feature" Then it should pass + Scenario: Unregistered services as constructor arguments + Given a file named "features/autowire.feature" with: + """ + Feature: + Scenario: + Given a step + """ + And a file named "features/bootstrap/FeatureContext.php" with: + """ + autowire && $classReflection->getConstructor()) { - foreach ($classReflection->getConstructor()->getParameters() as $index => $parameter) { - if (isset($newArguments[$index]) || isset($newArguments[$parameter->getName()])) { - continue; - } + $constructor = $classReflection->getConstructor(); - if ($parameter->getClass() && $this->container->has($parameter->getClass()->getName())) { - $newArguments[$index] = $this->container->get($parameter->getClass()->getName()); - } - } + if ($this->autowire && $constructor) { + return $this->autowireArguments($constructor, $newArguments); } return $newArguments; @@ -84,4 +79,28 @@ private function resolveArgument($value) return $value; } + + /** + * Autowires given arguments. + * + * @param ReflectionFunctionAbstract $constructor + * @param array $arguments + * + * @return array + */ + private function autowireArguments(ReflectionFunctionAbstract $constructor, array $arguments) + { + $newArguments = $arguments; + foreach ($constructor->getParameters() as $index => $parameter) { + if (isset($newArguments[$index]) || isset($newArguments[$parameter->getName()]) || !$parameter->getClass()) { + continue; + } + + if ($parameter->getClass()) { + $newArguments[$index] = $this->container->get($parameter->getClass()->getName()); + } + } + + return $newArguments; + } } diff --git a/src/Behat/Behat/HelperContainer/Call/Filter/ServicesResolver.php b/src/Behat/Behat/HelperContainer/Call/Filter/ServicesResolver.php index 3c150a076..d3aedf086 100644 --- a/src/Behat/Behat/HelperContainer/Call/Filter/ServicesResolver.php +++ b/src/Behat/Behat/HelperContainer/Call/Filter/ServicesResolver.php @@ -17,6 +17,8 @@ use Behat\Testwork\Call\Call; use Behat\Testwork\Call\Filter\CallFilter; use Behat\Testwork\Environment\Call\EnvironmentCall; +use Psr\Container\ContainerInterface; +use ReflectionFunctionAbstract; /** * Dynamically resolves call arguments using the service container. @@ -43,48 +45,98 @@ public function supportsCall(Call $call) */ public function filterCall(Call $call) { - if (!$call instanceof EnvironmentCall || !$call->getEnvironment() instanceof ServiceContainerEnvironment) { + if ($container = $this->getContainer($call)) { + $newArguments = $this->autowireArguments( + $container, + $call->getCallee()->getReflection(), + $call->getArguments() + ); + + return $this->repackageCallWithNewArguments($call, $newArguments); + } + + return $call; + } + + /** + * Gets container from the call. + * + * @param Call $call + * + * @return null|ContainerInterface + */ + private function getContainer(Call $call) + { + if (!$call instanceof EnvironmentCall) { throw new UnsupportedCallException(sprintf( 'ServicesResolver can not filter `%s` call.', get_class($call) ), $call); } - $container = $call->getEnvironment()->getServiceContainer(); - $newArguments = $call->getArguments(); + if (!$call->getEnvironment() instanceof ServiceContainerEnvironment) { + throw new UnsupportedCallException(sprintf( + 'ServicesResolver can not filter `%s` call.', + get_class($call) + ), $call); + } - if ($container) { - foreach ($call->getCallee()->getReflection()->getParameters() as $index => $parameter) { - if (isset($newArguments[$index]) || isset($newArguments[$parameter->getName()])) { - continue; - } + return $call->getEnvironment()->getServiceContainer(); + } - if ($parameter->getClass() && $container->has($parameter->getClass()->getName())) { - $newArguments[$index] = $container->get($parameter->getClass()->getName()); - } + /** + * * Autowires given arguments using provided container. + * + * @param ContainerInterface $container + * @param ReflectionFunctionAbstract $reflection + * @param array $arguments + * + * @return array + */ + private function autowireArguments( + ContainerInterface $container, + ReflectionFunctionAbstract $reflection, + array $arguments + ) { + $newArguments = $arguments; + foreach ($reflection->getParameters() as $index => $parameter) { + if (isset($newArguments[$index]) || isset($newArguments[$parameter->getName()])) { + continue; + } + + if ($parameter->getClass()) { + $newArguments[$index] = $container->get($parameter->getClass()->getName()); } } + return $newArguments; + } + /** + * Repackages old calls with new arguments. + * + * @param Call $call + * @param array $arguments + * + * @return DefinitionCall|TransformationCall + */ + private function repackageCallWithNewArguments(Call $call, array $arguments) + { if ($call instanceof DefinitionCall) { return new DefinitionCall( $call->getEnvironment(), $call->getFeature(), $call->getStep(), $call->getCallee(), - $newArguments, + $arguments, $call->getErrorReportingLevel() ); } - if ($call instanceof TransformationCall) { - return new TransformationCall( - $call->getEnvironment(), - $call->getDefinition(), - $call->getCallee(), - $newArguments - ); - } - - return $call; + return new TransformationCall( + $call->getEnvironment(), + $call->getDefinition(), + $call->getCallee(), + $arguments + ); } } From e86e7ed6492ec2d92ecb874bcc8a2dc779a7d2db Mon Sep 17 00:00:00 2001 From: everzet Date: Fri, 1 Sep 2017 17:02:20 +0100 Subject: [PATCH 080/567] Improve readability of ServicesResolver::repackageCallWithNewArguments --- .../Behat/HelperContainer/Call/Filter/ServicesResolver.php | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/Behat/Behat/HelperContainer/Call/Filter/ServicesResolver.php b/src/Behat/Behat/HelperContainer/Call/Filter/ServicesResolver.php index d3aedf086..7cf69dd84 100644 --- a/src/Behat/Behat/HelperContainer/Call/Filter/ServicesResolver.php +++ b/src/Behat/Behat/HelperContainer/Call/Filter/ServicesResolver.php @@ -114,12 +114,12 @@ private function autowireArguments( /** * Repackages old calls with new arguments. * - * @param Call $call - * @param array $arguments + * @param DefinitionCall|TransformationCall $call + * @param array $arguments * * @return DefinitionCall|TransformationCall */ - private function repackageCallWithNewArguments(Call $call, array $arguments) + private function repackageCallWithNewArguments($call, array $arguments) { if ($call instanceof DefinitionCall) { return new DefinitionCall( From 3cf8b0804b0b4c389dea661f75c3e6efc343a585 Mon Sep 17 00:00:00 2001 From: everzet Date: Fri, 1 Sep 2017 17:05:30 +0100 Subject: [PATCH 081/567] Services must be last arguments --- features/autowire.feature | 2 ++ 1 file changed, 2 insertions(+) diff --git a/features/autowire.feature b/features/autowire.feature index 700579a2b..41441af8e 100644 --- a/features/autowire.feature +++ b/features/autowire.feature @@ -10,6 +10,8 @@ Feature: Helper services autowire - It works for step definition arguments - It works for transformation arguments - It only wires arguments that weren't otherwise set + - Services must be last arguments in step definitions + - Services must be last arguments in transformations Background: Given a file named "behat.yaml" with: From 7b4bb60b2708b96efeb0d5720fb60be09f411311 Mon Sep 17 00:00:00 2001 From: everzet Date: Sat, 2 Sep 2017 09:36:30 +0100 Subject: [PATCH 082/567] Refactor ..\Call\..\ServicesResolver --- .../InitializedContextEnvironment.php | 1 + .../Argument/ServicesResolverFactory.php | 2 +- .../HelperContainer/ArgumentAutowirer.php | 74 +++++++++++++++++ .../Call/Filter/ServicesResolver.php | 81 ++++++++----------- .../ServiceContainerEnvironment.php | 2 +- 5 files changed, 112 insertions(+), 48 deletions(-) create mode 100644 src/Behat/Behat/HelperContainer/ArgumentAutowirer.php rename src/Behat/Behat/{Context => HelperContainer}/Environment/ServiceContainerEnvironment.php (94%) diff --git a/src/Behat/Behat/Context/Environment/InitializedContextEnvironment.php b/src/Behat/Behat/Context/Environment/InitializedContextEnvironment.php index d03e6df1b..053354963 100644 --- a/src/Behat/Behat/Context/Environment/InitializedContextEnvironment.php +++ b/src/Behat/Behat/Context/Environment/InitializedContextEnvironment.php @@ -13,6 +13,7 @@ use Behat\Behat\Context\Context; use Behat\Behat\Context\Environment\Handler\ContextEnvironmentHandler; use Behat\Behat\Context\Exception\ContextNotFoundException; +use Behat\Behat\HelperContainer\Environment\ServiceContainerEnvironment; use Behat\Testwork\Call\Callee; use Behat\Testwork\Suite\Suite; use Psr\Container\ContainerInterface; diff --git a/src/Behat/Behat/HelperContainer/Argument/ServicesResolverFactory.php b/src/Behat/Behat/HelperContainer/Argument/ServicesResolverFactory.php index 07bc7d2d7..7c6c2855f 100644 --- a/src/Behat/Behat/HelperContainer/Argument/ServicesResolverFactory.php +++ b/src/Behat/Behat/HelperContainer/Argument/ServicesResolverFactory.php @@ -10,7 +10,7 @@ namespace Behat\Behat\HelperContainer\Argument; -use Behat\Behat\Context\Environment\ServiceContainerEnvironment; +use Behat\Behat\HelperContainer\Environment\ServiceContainerEnvironment; use Behat\Behat\Context\Argument\ArgumentResolverFactory; use Behat\Behat\Context\Argument\SuiteScopedResolverFactory; use Behat\Behat\HelperContainer\BuiltInServiceContainer; diff --git a/src/Behat/Behat/HelperContainer/ArgumentAutowirer.php b/src/Behat/Behat/HelperContainer/ArgumentAutowirer.php new file mode 100644 index 000000000..f16df4ad1 --- /dev/null +++ b/src/Behat/Behat/HelperContainer/ArgumentAutowirer.php @@ -0,0 +1,74 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Behat\Behat\HelperContainer; + +use Psr\Container\ContainerInterface; +use ReflectionFunctionAbstract; +use ReflectionParameter; + +/** + * Automatically wires arguments of a given function from inside the container by using type-hitns. + * + * @author Konstantin Kudryashov + */ +final class ArgumentAutowirer +{ + /** + * @var ContainerInterface + */ + private $container; + + /** + * Initialises wirer. + * + * @param ContainerInterface $container + */ + public function __construct(ContainerInterface $container) + { + $this->container = $container; + } + + /** + * * Autowires given arguments using provided container. + * + * @param ReflectionFunctionAbstract $reflection + * @param array $arguments + * + * @return array + */ + public function autowireArguments(ReflectionFunctionAbstract $reflection, array $arguments) + { + $newArguments = $arguments; + foreach ($reflection->getParameters() as $index => $parameter) { + if ($this->isArgumentWireable($newArguments, $index, $parameter)) { + $newArguments[$index] = $this->container->get($parameter->getClass()->getName()); + } + } + + return $newArguments; + } + + /** + * Checks if given argument is wireable. + * + * Argument is wireable if it was not previously set and it has a class type-hint. + * + * @param array $arguments + * @param integer $index + * @param ReflectionParameter $parameter + * + * @return bool + */ + private function isArgumentWireable(array $arguments, $index, ReflectionParameter $parameter) + { + return !isset($arguments[$index]) && !isset($arguments[$parameter->getName()]) && $parameter->getClass(); + } +} diff --git a/src/Behat/Behat/HelperContainer/Call/Filter/ServicesResolver.php b/src/Behat/Behat/HelperContainer/Call/Filter/ServicesResolver.php index 7cf69dd84..97a7991c7 100644 --- a/src/Behat/Behat/HelperContainer/Call/Filter/ServicesResolver.php +++ b/src/Behat/Behat/HelperContainer/Call/Filter/ServicesResolver.php @@ -10,15 +10,15 @@ namespace Behat\Behat\HelperContainer\Call\Filter; -use Behat\Behat\Context\Environment\ServiceContainerEnvironment; +use Behat\Behat\HelperContainer\Environment\ServiceContainerEnvironment; use Behat\Behat\Definition\Call\DefinitionCall; +use Behat\Behat\HelperContainer\ArgumentAutowirer; use Behat\Behat\HelperContainer\Exception\UnsupportedCallException; use Behat\Behat\Transformation\Call\TransformationCall; use Behat\Testwork\Call\Call; use Behat\Testwork\Call\Filter\CallFilter; use Behat\Testwork\Environment\Call\EnvironmentCall; use Psr\Container\ContainerInterface; -use ReflectionFunctionAbstract; /** * Dynamically resolves call arguments using the service container. @@ -42,15 +42,14 @@ public function supportsCall(Call $call) * @param Call $call * * @return Call + * + * @throws UnsupportedCallException */ public function filterCall(Call $call) { if ($container = $this->getContainer($call)) { - $newArguments = $this->autowireArguments( - $container, - $call->getCallee()->getReflection(), - $call->getArguments() - ); + $autowirer = new ArgumentAutowirer($container); + $newArguments = $autowirer->autowireArguments($call->getCallee()->getReflection(), $call->getArguments()); return $this->repackageCallWithNewArguments($call, $newArguments); } @@ -64,6 +63,8 @@ public function filterCall(Call $call) * @param Call $call * * @return null|ContainerInterface + * + * @throws UnsupportedCallException if given call is not EnvironmentCall or environment is not ServiceContainerEnvironment */ private function getContainer(Call $call) { @@ -74,53 +75,34 @@ private function getContainer(Call $call) ), $call); } - if (!$call->getEnvironment() instanceof ServiceContainerEnvironment) { + $environment = $call->getEnvironment(); + + if (!$environment instanceof ServiceContainerEnvironment) { throw new UnsupportedCallException(sprintf( 'ServicesResolver can not filter `%s` call.', get_class($call) ), $call); } - return $call->getEnvironment()->getServiceContainer(); - } - - /** - * * Autowires given arguments using provided container. - * - * @param ContainerInterface $container - * @param ReflectionFunctionAbstract $reflection - * @param array $arguments - * - * @return array - */ - private function autowireArguments( - ContainerInterface $container, - ReflectionFunctionAbstract $reflection, - array $arguments - ) { - $newArguments = $arguments; - foreach ($reflection->getParameters() as $index => $parameter) { - if (isset($newArguments[$index]) || isset($newArguments[$parameter->getName()])) { - continue; - } - - if ($parameter->getClass()) { - $newArguments[$index] = $container->get($parameter->getClass()->getName()); - } - } - return $newArguments; + return $environment->getServiceContainer(); } /** * Repackages old calls with new arguments. * - * @param DefinitionCall|TransformationCall $call - * @param array $arguments + * @param Call $call + * @param array $arguments + * + * @return Call * - * @return DefinitionCall|TransformationCall + * @throws UnsupportedCallException if given call is not DefinitionCall or TransformationCall */ - private function repackageCallWithNewArguments($call, array $arguments) + private function repackageCallWithNewArguments(Call $call, array $arguments) { + if ($arguments === $call->getArguments()) { + return $call; + } + if ($call instanceof DefinitionCall) { return new DefinitionCall( $call->getEnvironment(), @@ -132,11 +114,18 @@ private function repackageCallWithNewArguments($call, array $arguments) ); } - return new TransformationCall( - $call->getEnvironment(), - $call->getDefinition(), - $call->getCallee(), - $arguments - ); + if ($call instanceof TransformationCall) { + return new TransformationCall( + $call->getEnvironment(), + $call->getDefinition(), + $call->getCallee(), + $arguments + ); + } + + throw new UnsupportedCallException(sprintf( + 'ServicesResolver can not filter `%s` call.', + get_class($call) + ), $call); } } diff --git a/src/Behat/Behat/Context/Environment/ServiceContainerEnvironment.php b/src/Behat/Behat/HelperContainer/Environment/ServiceContainerEnvironment.php similarity index 94% rename from src/Behat/Behat/Context/Environment/ServiceContainerEnvironment.php rename to src/Behat/Behat/HelperContainer/Environment/ServiceContainerEnvironment.php index cc72bb7c1..8f58ba623 100644 --- a/src/Behat/Behat/Context/Environment/ServiceContainerEnvironment.php +++ b/src/Behat/Behat/HelperContainer/Environment/ServiceContainerEnvironment.php @@ -8,7 +8,7 @@ * file that was distributed with this source code. */ -namespace Behat\Behat\Context\Environment; +namespace Behat\Behat\HelperContainer\Environment; use Behat\Testwork\Environment\Environment; use Psr\Container\ContainerInterface; From f5629fa1bba3d30ba215b9abaa008a7b8ff592d2 Mon Sep 17 00:00:00 2001 From: everzet Date: Sat, 2 Sep 2017 09:50:59 +0100 Subject: [PATCH 083/567] Refactor ServicesResolverFactory --- .../Argument/AutowiringResolver.php | 53 +++++++++++++++++++ .../Argument/ServicesResolver.php | 50 +++-------------- .../Argument/ServicesResolverFactory.php | 35 +++++++++--- 3 files changed, 88 insertions(+), 50 deletions(-) create mode 100644 src/Behat/Behat/HelperContainer/Argument/AutowiringResolver.php diff --git a/src/Behat/Behat/HelperContainer/Argument/AutowiringResolver.php b/src/Behat/Behat/HelperContainer/Argument/AutowiringResolver.php new file mode 100644 index 000000000..11dde13b9 --- /dev/null +++ b/src/Behat/Behat/HelperContainer/Argument/AutowiringResolver.php @@ -0,0 +1,53 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Behat\Behat\HelperContainer\Argument; + +use Behat\Behat\Context\Argument\ArgumentResolver; +use Behat\Behat\HelperContainer\ArgumentAutowirer; +use Psr\Container\ContainerInterface; +use ReflectionClass; + +/** + * Resolves arguments that weren't resolved before by autowiring. + * + * @see ContextFactory + * + * @author Konstantin Kudryashov + */ +final class AutowiringResolver implements ArgumentResolver +{ + /** + * @var ArgumentAutowirer + */ + private $autowirer; + + /** + * Initialises resolver. + * + * @param ContainerInterface $container + */ + public function __construct(ContainerInterface $container) + { + $this->autowirer = new ArgumentAutowirer($container); + } + + /** + * {@inheritdoc} + */ + public function resolveArguments(ReflectionClass $classReflection, array $arguments) + { + if ($constructor = $classReflection->getConstructor()) { + return $this->autowirer->autowireArguments($constructor, $arguments); + } + + return $arguments; + } +} diff --git a/src/Behat/Behat/HelperContainer/Argument/ServicesResolver.php b/src/Behat/Behat/HelperContainer/Argument/ServicesResolver.php index 6539302cd..9e16f32de 100644 --- a/src/Behat/Behat/HelperContainer/Argument/ServicesResolver.php +++ b/src/Behat/Behat/HelperContainer/Argument/ServicesResolver.php @@ -11,9 +11,9 @@ namespace Behat\Behat\HelperContainer\Argument; use Behat\Behat\Context\Argument\ArgumentResolver; +use Psr\Container\ContainerExceptionInterface; use Psr\Container\ContainerInterface; use ReflectionClass; -use ReflectionFunctionAbstract; /** * Resolves arguments using provided service container. @@ -28,37 +28,25 @@ final class ServicesResolver implements ArgumentResolver * @var ContainerInterface */ private $container; - /** - * @var bool - */ - private $autowire; /** * Initialises resolver. * * @param ContainerInterface $container - * @param bool $autowire */ - public function __construct(ContainerInterface $container, $autowire = false) + public function __construct(ContainerInterface $container) { $this->container = $container; - $this->autowire = $autowire; } /** * {@inheritdoc} + * + * @throws ContainerExceptionInterface */ public function resolveArguments(ReflectionClass $classReflection, array $arguments) { - $newArguments = array_map(array($this, 'resolveArgument'), $arguments); - - $constructor = $classReflection->getConstructor(); - - if ($this->autowire && $constructor) { - return $this->autowireArguments($constructor, $newArguments); - } - - return $newArguments; + return array_map(array($this, 'resolveArgument'), $arguments); } /** @@ -70,37 +58,15 @@ public function resolveArguments(ReflectionClass $classReflection, array $argume * @param mixed $value * * @return mixed + * + * @throws ContainerExceptionInterface */ private function resolveArgument($value) { - if ('@' === mb_substr($value, 0, 1)) { + if (0 === mb_strpos($value, '@')) { return $this->container->get(mb_substr($value, 1)); } return $value; } - - /** - * Autowires given arguments. - * - * @param ReflectionFunctionAbstract $constructor - * @param array $arguments - * - * @return array - */ - private function autowireArguments(ReflectionFunctionAbstract $constructor, array $arguments) - { - $newArguments = $arguments; - foreach ($constructor->getParameters() as $index => $parameter) { - if (isset($newArguments[$index]) || isset($newArguments[$parameter->getName()]) || !$parameter->getClass()) { - continue; - } - - if ($parameter->getClass()) { - $newArguments[$index] = $this->container->get($parameter->getClass()->getName()); - } - } - - return $newArguments; - } } diff --git a/src/Behat/Behat/HelperContainer/Argument/ServicesResolverFactory.php b/src/Behat/Behat/HelperContainer/Argument/ServicesResolverFactory.php index 7c6c2855f..8820288c5 100644 --- a/src/Behat/Behat/HelperContainer/Argument/ServicesResolverFactory.php +++ b/src/Behat/Behat/HelperContainer/Argument/ServicesResolverFactory.php @@ -10,6 +10,7 @@ namespace Behat\Behat\HelperContainer\Argument; +use Behat\Behat\Context\Argument\ArgumentResolver; use Behat\Behat\HelperContainer\Environment\ServiceContainerEnvironment; use Behat\Behat\Context\Argument\ArgumentResolverFactory; use Behat\Behat\Context\Argument\SuiteScopedResolverFactory; @@ -50,6 +51,9 @@ public function __construct(TaggedContainerInterface $container) * {@inheritdoc} * * @deprecated as part of SuiteScopedResolverFactory deprecation. Would be removed in 4.0 + * + * @throws WrongServicesConfigurationException + * @throws WrongContainerClassException */ public function generateArgumentResolvers(Suite $suite) { @@ -64,11 +68,14 @@ public function generateArgumentResolvers(Suite $suite) $container = $this->createContainer($suite->getSetting('services')); - return array($this->createArgumentResolver($container, false)); + return $this->createResolvers($container, false); } /** * {@inheritdoc} + * + * @throws WrongServicesConfigurationException + * @throws WrongContainerClassException */ public function createArgumentResolvers(Environment $environment) { @@ -85,7 +92,7 @@ public function createArgumentResolvers(Environment $environment) $environment->setServiceContainer($container); } - return array($this->createArgumentResolver($container, $autowire)); + return $this->createResolvers($container, $autowire); } /** @@ -94,6 +101,8 @@ public function createArgumentResolvers(Environment $environment) * @param string $settings * * @return mixed + * + * @throws WrongServicesConfigurationException */ private function createContainer($settings) { @@ -116,10 +125,12 @@ private function createContainer($settings) * @param string $settings * * @return mixed + * + * @throws WrongServicesConfigurationException */ private function createContainerFromString($settings) { - if ('@' === mb_substr($settings, 0, 1)) { + if (0 === mb_strpos($settings, '@')) { return $this->loadContainerFromContainer(mb_substr($settings, 1)); } @@ -144,12 +155,14 @@ private function createContainerFromArray(array $settings) * @param string $name * * @return mixed + * + * @throws WrongServicesConfigurationException */ private function loadContainerFromContainer($name) { $services = $this->container->findTaggedServiceIds(HelperContainerExtension::HELPER_CONTAINER_TAG); - if (!in_array($name, array_keys($services))) { + if (!array_key_exists($name, $services)) { throw new WrongServicesConfigurationException( sprintf('Service container `@%s` was not found.', $name) ); @@ -169,7 +182,7 @@ private function createContainerFromClassSpec($classSpec) { $constructor = explode('::', $classSpec); - if (2 == count($constructor)) { + if (2 === count($constructor)) { return call_user_func($constructor); } @@ -182,9 +195,11 @@ private function createContainerFromClassSpec($classSpec) * @param mixed $container * @param bool $autowire * - * @return ServicesResolver + * @return ArgumentResolver[] + * + * @throws WrongContainerClassException */ - private function createArgumentResolver($container, $autowire) + private function createResolvers($container, $autowire) { if (!$container instanceof ContainerInterface) { throw new WrongContainerClassException( @@ -196,6 +211,10 @@ private function createArgumentResolver($container, $autowire) ); } - return new ServicesResolver($container, $autowire); + if ($autowire) { + return array(new ServicesResolver($container), new AutowiringResolver($container)); + } + + return array(new ServicesResolver($container)); } } From 102d141b0458aaf13169b7e141869f7d0d07e947 Mon Sep 17 00:00:00 2001 From: everzet Date: Sat, 2 Sep 2017 09:52:51 +0100 Subject: [PATCH 084/567] Simplify expectation --- features/autowire.feature | 11 ++--------- 1 file changed, 2 insertions(+), 9 deletions(-) diff --git a/features/autowire.feature b/features/autowire.feature index 41441af8e..6e8c9285f 100644 --- a/features/autowire.feature +++ b/features/autowire.feature @@ -127,8 +127,7 @@ Feature: Helper services autowire When I run "behat --no-colors -f progress features/autowire.feature" Then it should fail with: """ - [Behat\Behat\HelperContainer\Exception\ServiceNotFoundException] - Service Service4 not found + Service Service4 not found """ Scenario: Step definition arguments @@ -177,13 +176,7 @@ Feature: Helper services autowire When I run "behat --no-colors -f progress features/autowire.feature" Then it should fail with: """ - F - - --- Failed steps: - - 001 Scenario: # features/autowire.feature:2 - Given a step # features/autowire.feature:3 - Fatal error: Service Service4 not found (Behat\Testwork\Call\Exception\FatalThrowableError) + Service Service4 not found """ Scenario: Transformation arguments From 6fd2d24c3cc77f7f11b6da90354310f3e5776316 Mon Sep 17 00:00:00 2001 From: everzet Date: Sat, 2 Sep 2017 09:56:50 +0100 Subject: [PATCH 085/567] Fix docblock --- src/Behat/Behat/HelperContainer/ArgumentAutowirer.php | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/src/Behat/Behat/HelperContainer/ArgumentAutowirer.php b/src/Behat/Behat/HelperContainer/ArgumentAutowirer.php index f16df4ad1..d4d514728 100644 --- a/src/Behat/Behat/HelperContainer/ArgumentAutowirer.php +++ b/src/Behat/Behat/HelperContainer/ArgumentAutowirer.php @@ -10,6 +10,7 @@ namespace Behat\Behat\HelperContainer; +use Psr\Container\ContainerExceptionInterface; use Psr\Container\ContainerInterface; use ReflectionFunctionAbstract; use ReflectionParameter; @@ -37,12 +38,14 @@ public function __construct(ContainerInterface $container) } /** - * * Autowires given arguments using provided container. + * Autowires given arguments using provided container. * * @param ReflectionFunctionAbstract $reflection - * @param array $arguments + * @param array $arguments * * @return array + * + * @throws ContainerExceptionInterface if unset argument typehint can not be resolved from container */ public function autowireArguments(ReflectionFunctionAbstract $reflection, array $arguments) { From e33d10bf03e89abea2f0f958cdb0f312a3b0e778 Mon Sep 17 00:00:00 2001 From: everzet Date: Sat, 2 Sep 2017 10:00:41 +0100 Subject: [PATCH 086/567] Simplify Call ServicesResolver a bit --- .../Call/Filter/ServicesResolver.php | 33 +++++++++++++++---- 1 file changed, 26 insertions(+), 7 deletions(-) diff --git a/src/Behat/Behat/HelperContainer/Call/Filter/ServicesResolver.php b/src/Behat/Behat/HelperContainer/Call/Filter/ServicesResolver.php index 97a7991c7..a214b6465 100644 --- a/src/Behat/Behat/HelperContainer/Call/Filter/ServicesResolver.php +++ b/src/Behat/Behat/HelperContainer/Call/Filter/ServicesResolver.php @@ -18,6 +18,7 @@ use Behat\Testwork\Call\Call; use Behat\Testwork\Call\Filter\CallFilter; use Behat\Testwork\Environment\Call\EnvironmentCall; +use Psr\Container\ContainerExceptionInterface; use Psr\Container\ContainerInterface; /** @@ -44,6 +45,7 @@ public function supportsCall(Call $call) * @return Call * * @throws UnsupportedCallException + * @throws ContainerExceptionInterface */ public function filterCall(Call $call) { @@ -51,7 +53,7 @@ public function filterCall(Call $call) $autowirer = new ArgumentAutowirer($container); $newArguments = $autowirer->autowireArguments($call->getCallee()->getReflection(), $call->getArguments()); - return $this->repackageCallWithNewArguments($call, $newArguments); + return $this->repackageCallIfNewArguments($call, $newArguments); } return $call; @@ -88,7 +90,7 @@ private function getContainer(Call $call) } /** - * Repackages old calls with new arguments. + * Repackages old calls with new arguments, but only if two differ. * * @param Call $call * @param array $arguments @@ -97,12 +99,27 @@ private function getContainer(Call $call) * * @throws UnsupportedCallException if given call is not DefinitionCall or TransformationCall */ - private function repackageCallWithNewArguments(Call $call, array $arguments) + private function repackageCallIfNewArguments(Call $call, array $arguments) { if ($arguments === $call->getArguments()) { return $call; } + return $this->repackageCallWithNewArguments($call, $arguments); + } + + /** + * Repackages old calls with new arguments. + * + * @param Call $call + * @param array $arguments + * + * @return DefinitionCall|TransformationCall + * + * @throws UnsupportedCallException + */ + private function repackageCallWithNewArguments(Call $call, array $arguments) + { if ($call instanceof DefinitionCall) { return new DefinitionCall( $call->getEnvironment(), @@ -123,9 +140,11 @@ private function repackageCallWithNewArguments(Call $call, array $arguments) ); } - throw new UnsupportedCallException(sprintf( - 'ServicesResolver can not filter `%s` call.', - get_class($call) - ), $call); + throw new UnsupportedCallException( + sprintf( + 'ServicesResolver can not filter `%s` call.', + get_class($call) + ), $call + ); } } From 7c9970438af4d87547b4484f0fbff5e1ea324207 Mon Sep 17 00:00:00 2001 From: everzet Date: Sat, 2 Sep 2017 10:36:16 +0100 Subject: [PATCH 087/567] Implement simple notation for inline services --- features/helper_containers.feature | 38 +++++++++++++++++++ .../BuiltInServiceContainer.php | 10 ++++- 2 files changed, 47 insertions(+), 1 deletion(-) diff --git a/features/helper_containers.feature b/features/helper_containers.feature index 934a6bbf9..4b77d321f 100644 --- a/features/helper_containers.feature +++ b/features/helper_containers.feature @@ -250,6 +250,44 @@ Feature: Per-suite helper containers When I run "behat --no-colors -f progress features/container.feature" Then it should pass + Scenario: Built-in container with class names as service IDs + Given a file named "behat.yml" with: + """ + default: + suites: + default: + contexts: + - FirstContext: + - "@SharedService" + - SecondContext: + - "@SharedService" + + services: + SharedService: ~ + """ + When I run "behat --no-colors -f progress features/container.feature" + Then it should pass + + Scenario: Built-in container with class names as service IDs and arguments + Given a file named "behat.yml" with: + """ + default: + suites: + default: + contexts: + - FirstContext: + - "@SharedServiceExpecting1" + - SecondContext: + - "@SharedServiceExpecting1" + + services: + SharedServiceExpecting1: + arguments: + - 1 + """ + When I run "behat --no-colors -f progress features/container.feature" + Then it should pass + Scenario: Built-in container with factory-based services Given a file named "behat.yml" with: """ diff --git a/src/Behat/Behat/HelperContainer/BuiltInServiceContainer.php b/src/Behat/Behat/HelperContainer/BuiltInServiceContainer.php index 71795ee84..c58bae65b 100644 --- a/src/Behat/Behat/HelperContainer/BuiltInServiceContainer.php +++ b/src/Behat/Behat/HelperContainer/BuiltInServiceContainer.php @@ -47,7 +47,7 @@ public function __construct(array $schema) */ public function has($id) { - return isset($this->schema[$id]); + return array_key_exists($id, $this->schema); } /** @@ -99,6 +99,14 @@ private function getAndValidateServiceSchema($id) { $schema = $this->schema[$id]; + if (null === $schema) { + $schema = array('class' => $id); + } + + if (!isset($schema['class'])) { + $schema['class'] = $id; + } + if (is_string($schema)) { $schema = array('class' => $schema); } From dc0bb881cedf8ef99ad926415a094342918f2936 Mon Sep 17 00:00:00 2001 From: everzet Date: Sat, 2 Sep 2017 10:47:11 +0100 Subject: [PATCH 088/567] Add couple guards Likely unnecessary --- .../Call/Filter/ServicesResolver.php | 86 +++++++++++++++---- 1 file changed, 70 insertions(+), 16 deletions(-) diff --git a/src/Behat/Behat/HelperContainer/Call/Filter/ServicesResolver.php b/src/Behat/Behat/HelperContainer/Call/Filter/ServicesResolver.php index a214b6465..0c70fef71 100644 --- a/src/Behat/Behat/HelperContainer/Call/Filter/ServicesResolver.php +++ b/src/Behat/Behat/HelperContainer/Call/Filter/ServicesResolver.php @@ -10,11 +10,13 @@ namespace Behat\Behat\HelperContainer\Call\Filter; +use Behat\Behat\Definition\Definition; use Behat\Behat\HelperContainer\Environment\ServiceContainerEnvironment; use Behat\Behat\Definition\Call\DefinitionCall; use Behat\Behat\HelperContainer\ArgumentAutowirer; use Behat\Behat\HelperContainer\Exception\UnsupportedCallException; use Behat\Behat\Transformation\Call\TransformationCall; +use Behat\Behat\Transformation\Transformation; use Behat\Testwork\Call\Call; use Behat\Testwork\Call\Filter\CallFilter; use Behat\Testwork\Environment\Call\EnvironmentCall; @@ -112,32 +114,20 @@ private function repackageCallIfNewArguments(Call $call, array $arguments) * Repackages old calls with new arguments. * * @param Call $call - * @param array $arguments + * @param array $newArguments * * @return DefinitionCall|TransformationCall * * @throws UnsupportedCallException */ - private function repackageCallWithNewArguments(Call $call, array $arguments) + private function repackageCallWithNewArguments(Call $call, array $newArguments) { if ($call instanceof DefinitionCall) { - return new DefinitionCall( - $call->getEnvironment(), - $call->getFeature(), - $call->getStep(), - $call->getCallee(), - $arguments, - $call->getErrorReportingLevel() - ); + return $this->repackageDefinitionCall($call, $newArguments); } if ($call instanceof TransformationCall) { - return new TransformationCall( - $call->getEnvironment(), - $call->getDefinition(), - $call->getCallee(), - $arguments - ); + return $this->repackageTransformationCall($call, $newArguments); } throw new UnsupportedCallException( @@ -147,4 +137,68 @@ private function repackageCallWithNewArguments(Call $call, array $arguments) ), $call ); } + + /** + * Repackages definition call with new arguments. + * + * @param DefinitionCall $call + * @param array $newArguments + * + * @return DefinitionCall + * + * @throws UnsupportedCallException + */ + private function repackageDefinitionCall(DefinitionCall $call, array $newArguments) + { + $definition = $call->getCallee(); + + if (!$definition instanceof Definition) { + throw new UnsupportedCallException( + sprintf( + 'Something is wrong in callee associated with `%s` call.', + get_class($call) + ), $call + ); + } + + return new DefinitionCall( + $call->getEnvironment(), + $call->getFeature(), + $call->getStep(), + $definition, + $newArguments, + $call->getErrorReportingLevel() + ); + } + + /** + * Repackages transformation call with new arguments. + * + * @param TransformationCall $call + * @param array $newArguments + * + * @return TransformationCall + * + * @throws UnsupportedCallException + */ + private function repackageTransformationCall(TransformationCall $call, array $newArguments) + { + $transformation = $call->getCallee(); + + if (!$transformation instanceof Transformation) { + throw new UnsupportedCallException( + sprintf( + 'Something is wrong in callee associated with `%s` call.', + get_class($call) + ), $call + ); + } + + return new TransformationCall( + $call->getEnvironment(), + $call->getDefinition(), + $transformation, + $newArguments + ); + } } From 4752f27e319ed0044ae44634b1a1b293ce865103 Mon Sep 17 00:00:00 2001 From: everzet Date: Sat, 2 Sep 2017 10:50:31 +0100 Subject: [PATCH 089/567] Avoid operating on non-array --- src/Behat/Behat/HelperContainer/BuiltInServiceContainer.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Behat/Behat/HelperContainer/BuiltInServiceContainer.php b/src/Behat/Behat/HelperContainer/BuiltInServiceContainer.php index c58bae65b..809d5f268 100644 --- a/src/Behat/Behat/HelperContainer/BuiltInServiceContainer.php +++ b/src/Behat/Behat/HelperContainer/BuiltInServiceContainer.php @@ -103,7 +103,7 @@ private function getAndValidateServiceSchema($id) $schema = array('class' => $id); } - if (!isset($schema['class'])) { + if (is_array($schema) && !array_key_exists('class', $schema)) { $schema['class'] = $id; } From 606683f8255d8785cda755ea5a88b7e0196bfe1d Mon Sep 17 00:00:00 2001 From: everzet Date: Sat, 2 Sep 2017 10:58:06 +0100 Subject: [PATCH 090/567] Refactor BuiltInServiceContainer --- .../Behat/HelperContainer/BuiltInServiceContainer.php | 9 +-------- 1 file changed, 1 insertion(+), 8 deletions(-) diff --git a/src/Behat/Behat/HelperContainer/BuiltInServiceContainer.php b/src/Behat/Behat/HelperContainer/BuiltInServiceContainer.php index 809d5f268..624bd28e5 100644 --- a/src/Behat/Behat/HelperContainer/BuiltInServiceContainer.php +++ b/src/Behat/Behat/HelperContainer/BuiltInServiceContainer.php @@ -103,10 +103,6 @@ private function getAndValidateServiceSchema($id) $schema = array('class' => $id); } - if (is_array($schema) && !array_key_exists('class', $schema)) { - $schema['class'] = $id; - } - if (is_string($schema)) { $schema = array('class' => $schema); } @@ -128,10 +124,7 @@ private function getAndValidateServiceSchema($id) private function getAndValidateClass($id, array $schema) { if (!isset($schema['class'])) { - throw new WrongServicesConfigurationException(sprintf( - 'All services of the built-in `services` must have `class` option set, but `%s` does not.', - $id - )); + $schema['class'] = $id; } return $schema['class']; From dd8d3d711a93a3eca91b581c2ddf25c1751e83ab Mon Sep 17 00:00:00 2001 From: everzet Date: Sun, 3 Sep 2017 10:46:37 +0100 Subject: [PATCH 091/567] Update CHANGELOG --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 5392af5b0..cdb73622a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,7 @@ and this project adheres to [Semantic Versioning](http://semver.org/). ## [Unreleased] ### Added + * [#1071](https://github.com/Behat/Behat/pull/1071): Services auto-wiring * [#1054](https://github.com/Behat/Behat/pull/1054): [PSR-11](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-11-container.md) support for helper containers. * Support for modern PHPUnit. From 2ea1381d400dcdbe6829a8b867c7bbf0ab1fabe6 Mon Sep 17 00:00:00 2001 From: everzet Date: Sun, 10 Sep 2017 12:08:16 +0100 Subject: [PATCH 092/567] Cleanup Travis build matrix - Remove HHVM - Remove non-supported PHP versions - Do not test against DEV dependencies --- .travis.yml | 16 ++++------------ 1 file changed, 4 insertions(+), 12 deletions(-) diff --git a/.travis.yml b/.travis.yml index 7477ba96d..924bf1e7c 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,6 +1,6 @@ language: php -php: [5.4, 5.5, 5.6, 7.0, 7.1, hhvm] +php: [5.6, 7.0, 7.1] sudo: false @@ -14,25 +14,17 @@ branches: matrix: include: - - php: 5.4 - env: DEPENDENCIES='low' - php: 5.6 - env: SYMFONY_VERSION='2.3.*' + env: DEPENDENCIES='low' - php: 5.6 env: SYMFONY_VERSION='2.7.*' - php: 5.6 env: SYMFONY_VERSION='2.8.*' - - php: 7.1 - env: DEPENDENCIES='dev' - allow_failures: - - php: hhvm - fast_finish: true before_install: - - if [[ ${TRAVIS_PHP_VERSION:0:4} != "hhvm" ]]; then phpenv config-rm xdebug.ini; fi + - phpenv config-rm xdebug.ini before_script: - - if [ "$DEPENDENCIES" = "dev" ]; then perl -pi -e 's/^}$/,"minimum-stability":"dev"}/' composer.json; fi; - if [ "$SYMFONY_VERSION" != "" ]; then composer require --no-update "symfony/symfony:${SYMFONY_VERSION}"; fi; - if [ "$DEPENDENCIES" != "low" ]; then composer update; fi; - if [ "$DEPENDENCIES" = "low" ]; then composer update --prefer-lowest; fi; @@ -57,4 +49,4 @@ deploy: skip_cleanup: true on: tags: true - php: 5.4 + php: 5.6 From b2f2ec75e2b25d48ed96411551aae5b118217567 Mon Sep 17 00:00:00 2001 From: everzet Date: Sun, 10 Sep 2017 12:18:37 +0100 Subject: [PATCH 093/567] Note the build matrix update in CHANGELOG [ci skip] --- CHANGELOG.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index cdb73622a..2d861e454 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -24,6 +24,10 @@ and this project adheres to [Semantic Versioning](http://semver.org/). is a non-breaking change. If you depend heavily on `Interop`, upgrade to `1.2`, which is still supported by helper containers. Aim to migrate to `Psr` before Behat 4.0 shows up on horizon + * PHP versions prior to 5.6 and HHVM were dropped from CI build matrix. It + doesn't mean that we'll start using features of 5.6 yet, it just means we + don't get out of our way to support 5.3 and 5.4 anymore. In 4.0 support will + be completely dropped. ## [3.3.1] - 2017-05-15 ### Added From dcee0bfcdd79a2b67d91f18f726bc0ddd548852e Mon Sep 17 00:00:00 2001 From: everzet Date: Sun, 10 Sep 2017 12:19:04 +0100 Subject: [PATCH 094/567] Bump dev-version --- src/Behat/Behat/ApplicationFactory.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Behat/Behat/ApplicationFactory.php b/src/Behat/Behat/ApplicationFactory.php index ced51d911..261094881 100644 --- a/src/Behat/Behat/ApplicationFactory.php +++ b/src/Behat/Behat/ApplicationFactory.php @@ -46,7 +46,7 @@ */ final class ApplicationFactory extends BaseFactory { - const VERSION = '3.3-dev'; + const VERSION = '3.4-dev'; /** * {@inheritdoc} @@ -122,7 +122,7 @@ protected function getConfigPath() $configDir . 'behat.yaml.dist', $configDir . 'behat.yml.dist', ); - + foreach ($paths as $path) { if (is_file($path)) { return $path; From a6aab8b439fbdb8880238af05639535a530dd3f8 Mon Sep 17 00:00:00 2001 From: everzet Date: Sun, 10 Sep 2017 12:20:37 +0100 Subject: [PATCH 095/567] Bump changelog version --- CHANGELOG.md | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2d861e454..2aa98c7fb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,8 @@ The format is based on [Keep a Changelog](http://keepachangelog.com/) and this project adheres to [Semantic Versioning](http://semver.org/). ## [Unreleased] + +## [3.4.0] - 2017-09-10 ### Added * [#1071](https://github.com/Behat/Behat/pull/1071): Services auto-wiring * [#1054](https://github.com/Behat/Behat/pull/1054): [PSR-11](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-11-container.md) @@ -856,7 +858,8 @@ and this project adheres to [Semantic Versioning](http://semver.org/). ### Changed * Initial release -[Unreleased]: https://github.com/Behat/Behat/compare/v3.3.1...HEAD +[Unreleased]: https://github.com/Behat/Behat/compare/v3.4.0...HEAD +[3.4.0]: https://github.com/Behat/Behat/compare/v3.3.1...v3.4.0 [3.3.1]: https://github.com/Behat/Behat/compare/v3.3.0...v3.3.1 [3.3.0]: https://github.com/Behat/Behat/compare/v3.2.3...v3.3.0 [3.2.3]: https://github.com/Behat/Behat/compare/v3.2.2...v3.2.3 From 8ab237fe7ca886a909b81830ea309fe9de996914 Mon Sep 17 00:00:00 2001 From: Scott Moorhouse Date: Wed, 13 Sep 2017 11:37:41 -0700 Subject: [PATCH 096/567] Removing short array syntax --- src/Behat/Behat/Gherkin/ServiceContainer/GherkinExtension.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Behat/Behat/Gherkin/ServiceContainer/GherkinExtension.php b/src/Behat/Behat/Gherkin/ServiceContainer/GherkinExtension.php index 3f770aa72..c24ddce17 100644 --- a/src/Behat/Behat/Gherkin/ServiceContainer/GherkinExtension.php +++ b/src/Behat/Behat/Gherkin/ServiceContainer/GherkinExtension.php @@ -225,7 +225,7 @@ private function loadDefaultLoaders(ContainerBuilder $container, $cachePath) } $definition->addMethodCall('setCache', array($cacheDefinition)); - $definition->addMethodCall('setBasePath', ['%paths.base%']); + $definition->addMethodCall('setBasePath', array('%paths.base%')); $definition->addTag(self::LOADER_TAG, array('priority' => 50)); $container->setDefinition('gherkin.loader.gherkin_file', $definition); } From 356cdd9a556ad42b3d9188a92e886effd9abecff Mon Sep 17 00:00:00 2001 From: Scott Moorhouse Date: Wed, 13 Sep 2017 11:57:40 -0700 Subject: [PATCH 097/567] Add changelog message --- CHANGELOG.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2aa98c7fb..cc9fe0aba 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,8 @@ The format is based on [Keep a Changelog](http://keepachangelog.com/) and this project adheres to [Semantic Versioning](http://semver.org/). ## [Unreleased] +### Fixed + * PHP 5.3 style cleanup. ## [3.4.0] - 2017-09-10 ### Added From 745a3a61df20301b0a1436b87289096848a166ed Mon Sep 17 00:00:00 2001 From: Konstantin Kudryashov Date: Mon, 18 Sep 2017 08:04:33 +0100 Subject: [PATCH 098/567] Fix Windows build --- appveyor.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/appveyor.yml b/appveyor.yml index a1e451243..945deee67 100644 --- a/appveyor.yml +++ b/appveyor.yml @@ -6,7 +6,7 @@ clone_folder: c:\projects\behat environment: matrix: - - PHP_DOWNLOAD_FILE: php-7.1.8-nts-Win32-VC14-x86.zip + - PHP_DOWNLOAD_FILE: php-7.1.9-nts-Win32-VC14-x86.zip branches: only: From 269777f1477b132031f048aa45620aef787d8425 Mon Sep 17 00:00:00 2001 From: everzet Date: Mon, 18 Sep 2017 12:09:58 +0100 Subject: [PATCH 099/567] Bump changelog --- CHANGELOG.md | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index cc9fe0aba..26c9c258c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,8 @@ The format is based on [Keep a Changelog](http://keepachangelog.com/) and this project adheres to [Semantic Versioning](http://semver.org/). ## [Unreleased] + +## [3.4.1] - 2017-09-18 ### Fixed * PHP 5.3 style cleanup. @@ -860,7 +862,8 @@ and this project adheres to [Semantic Versioning](http://semver.org/). ### Changed * Initial release -[Unreleased]: https://github.com/Behat/Behat/compare/v3.4.0...HEAD +[Unreleased]: https://github.com/Behat/Behat/compare/v3.4.1...HEAD +[3.4.1]: https://github.com/Behat/Behat/compare/v3.4.0...v3.4.1 [3.4.0]: https://github.com/Behat/Behat/compare/v3.3.1...v3.4.0 [3.3.1]: https://github.com/Behat/Behat/compare/v3.3.0...v3.3.1 [3.3.0]: https://github.com/Behat/Behat/compare/v3.2.3...v3.3.0 From e906b9f2e91b26298bc46166bc0b9ca89cd72e78 Mon Sep 17 00:00:00 2001 From: Serhii Polishchuk Date: Thu, 28 Sep 2017 18:18:59 +0300 Subject: [PATCH 100/567] Added changelog --- CHANGELOG.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 26c9c258c..b3eacc21a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,8 @@ The format is based on [Keep a Changelog](http://keepachangelog.com/) and this project adheres to [Semantic Versioning](http://semver.org/). ## [Unreleased] +### Added + * [#1083](https://github.com/Behat/Behat/pull/1083): JUnit time attribute ## [3.4.1] - 2017-09-18 ### Fixed From 6e0e51f3ef1fd6368fb156420ed456f3e1601628 Mon Sep 17 00:00:00 2001 From: Serhii Polishchuk Date: Mon, 2 Oct 2017 13:23:25 +0300 Subject: [PATCH 101/567] Fixed time --- .../Output/Node/EventListener/JUnit/JUnitDurationListener.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Behat/Behat/Output/Node/EventListener/JUnit/JUnitDurationListener.php b/src/Behat/Behat/Output/Node/EventListener/JUnit/JUnitDurationListener.php index f5cb3a59b..b36a96176 100644 --- a/src/Behat/Behat/Output/Node/EventListener/JUnit/JUnitDurationListener.php +++ b/src/Behat/Behat/Output/Node/EventListener/JUnit/JUnitDurationListener.php @@ -68,7 +68,7 @@ private function captureAfterScenarioEvent(AfterScenarioTested $event) $timer = $this->scenarioTimerStore[$key]; if ($timer instanceof Timer) { $timer->stop(); - $this->resultStore[$key] = $timer->getSeconds(); + $this->resultStore[$key] = round($timer->getTime()); } } @@ -78,7 +78,7 @@ private function captureAfterFeatureEvent(AfterFeatureTested $event) $timer = $this->featureTimerStore[$key]; if ($timer instanceof Timer) { $timer->stop(); - $this->featureResultStore[$key] = $timer->getSeconds(); + $this->featureResultStore[$key] = round($timer->getTime()); } } From 0ab45bb4351d3e0738c4e9beb4432c84f73cb080 Mon Sep 17 00:00:00 2001 From: Benjamin Doherty Date: Mon, 2 Oct 2017 20:25:09 -0500 Subject: [PATCH 102/567] Add missing property. --- .../Behat/Output/Node/Printer/JUnit/JUnitScenarioPrinter.php | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/Behat/Behat/Output/Node/Printer/JUnit/JUnitScenarioPrinter.php b/src/Behat/Behat/Output/Node/Printer/JUnit/JUnitScenarioPrinter.php index 27eb86de7..a20b6ded5 100644 --- a/src/Behat/Behat/Output/Node/Printer/JUnit/JUnitScenarioPrinter.php +++ b/src/Behat/Behat/Output/Node/Printer/JUnit/JUnitScenarioPrinter.php @@ -48,6 +48,11 @@ final class JUnitScenarioPrinter */ private $outlineStepCount; + /** + * @var JUnitDurationListener + */ + private $durationListener; + public function __construct(ResultToStringConverter $resultConverter, JUnitOutlineStoreListener $outlineListener, JUnitDurationListener $durationListener) { $this->resultConverter = $resultConverter; From 91821a821a256aae4c0122ec6b175b59ec5a291f Mon Sep 17 00:00:00 2001 From: Benjamin Doherty Date: Tue, 3 Oct 2017 00:43:14 -0500 Subject: [PATCH 103/567] Simplify listenEvent method. Each listener method returns early if the event object isn't the right type. --- .../JUnit/JUnitDurationListener.php | 43 +++++++++++-------- 1 file changed, 24 insertions(+), 19 deletions(-) diff --git a/src/Behat/Behat/Output/Node/EventListener/JUnit/JUnitDurationListener.php b/src/Behat/Behat/Output/Node/EventListener/JUnit/JUnitDurationListener.php index b36a96176..2c7372103 100644 --- a/src/Behat/Behat/Output/Node/EventListener/JUnit/JUnitDurationListener.php +++ b/src/Behat/Behat/Output/Node/EventListener/JUnit/JUnitDurationListener.php @@ -23,21 +23,10 @@ final class JUnitDurationListener implements EventListener /** @inheritdoc */ public function listenEvent(Formatter $formatter, Event $event, $eventName) { - if ($event instanceof BeforeScenarioTested) { - $this->captureBeforeScenarioEvent($event); - } - - if ($event instanceof BeforeFeatureTested) { - $this->captureBeforeFeatureTested($event); - } - - if ($event instanceof AfterScenarioTested) { - $this->captureAfterScenarioEvent($event); - } - - if ($event instanceof AfterFeatureTested) { - $this->captureAfterFeatureEvent($event); - } + $this->captureBeforeScenarioEvent($event); + $this->captureBeforeFeatureTested($event); + $this->captureAfterScenarioEvent($event); + $this->captureAfterFeatureEvent($event); } public function getDuration(ScenarioLikeInterface $scenario) @@ -52,18 +41,30 @@ public function getFeatureDuration(FeatureNode $feature) return array_key_exists($key, $this->featureResultStore) ? $this->featureResultStore[$key] : ''; } - private function captureBeforeFeatureTested(BeforeFeatureTested $event) + private function captureBeforeFeatureTested(Event $event) { + if (!$event instanceof BeforeFeatureTested) { + return; + } + $this->featureTimerStore[$this->getHash($event->getFeature())] = $this->startTimer(); } - private function captureBeforeScenarioEvent(BeforeScenarioTested $event) + private function captureBeforeScenarioEvent(Event $event) { + if (!$event instanceof BeforeScenarioTested) { + return; + } + $this->scenarioTimerStore[$this->getHash($event->getScenario())] = $this->startTimer(); } - private function captureAfterScenarioEvent(AfterScenarioTested $event) + private function captureAfterScenarioEvent(Event $event) { + if (!$event instanceof AfterScenarioTested) { + return; + } + $key = $this->getHash($event->getScenario()); $timer = $this->scenarioTimerStore[$key]; if ($timer instanceof Timer) { @@ -72,8 +73,12 @@ private function captureAfterScenarioEvent(AfterScenarioTested $event) } } - private function captureAfterFeatureEvent(AfterFeatureTested $event) + private function captureAfterFeatureEvent(Event $event) { + if (!$event instanceof AfterFeatureTested) { + return; + } + $key = $this->getHash($event->getFeature()); $timer = $this->featureTimerStore[$key]; if ($timer instanceof Timer) { From d50fb7abeeab9d110f66a9446eb26e1ecbf3abf1 Mon Sep 17 00:00:00 2001 From: Denis Brumann Date: Tue, 24 Oct 2017 14:00:28 +0200 Subject: [PATCH 104/567] Update dependencies to allow Symfony 4.x-components. --- .travis.yml | 2 ++ composer.json | 16 ++++++++-------- .../Cli/ServiceContainer/CliExtension.php | 1 + 3 files changed, 11 insertions(+), 8 deletions(-) diff --git a/.travis.yml b/.travis.yml index 924bf1e7c..0b0cc2102 100644 --- a/.travis.yml +++ b/.travis.yml @@ -20,6 +20,8 @@ matrix: env: SYMFONY_VERSION='2.7.*' - php: 5.6 env: SYMFONY_VERSION='2.8.*' + - php: 7.1 + env: SYMFONY_VERSION='4.0.*@dev' before_install: - phpenv config-rm xdebug.ini diff --git a/composer.json b/composer.json index b3dbd81f3..fb2bf3e8f 100644 --- a/composer.json +++ b/composer.json @@ -18,19 +18,19 @@ "ext-mbstring": "*", "behat/gherkin": "^4.5.1", "behat/transliterator": "^1.2", - "symfony/console": "~2.5||~3.0", - "symfony/config": "~2.3||~3.0", - "symfony/dependency-injection": "~2.1||~3.0", - "symfony/event-dispatcher": "~2.1||~3.0", - "symfony/translation": "~2.3||~3.0", - "symfony/yaml": "~2.1||~3.0", - "symfony/class-loader": "~2.1||~3.0", + "symfony/console": "~2.5||~3.0||~4.0", + "symfony/config": "~2.3||~3.0||~4.0", + "symfony/dependency-injection": "~2.1||~3.0||~4.0", + "symfony/event-dispatcher": "~2.1||~3.0||~4.0", + "symfony/translation": "~2.3||~3.0||~4.0", + "symfony/yaml": "~2.1||~3.0||~4.0", + "symfony/class-loader": "~2.1||~3.0||~4.0", "psr/container": "^1.0", "container-interop/container-interop": "^1.2" }, "require-dev": { - "symfony/process": "~2.5|~3.0", + "symfony/process": "~2.5|~3.0|~4.0", "phpunit/phpunit": "~4.5", "herrera-io/box": "~1.6.1" }, diff --git a/src/Behat/Testwork/Cli/ServiceContainer/CliExtension.php b/src/Behat/Testwork/Cli/ServiceContainer/CliExtension.php index 4b9fba847..497993cef 100644 --- a/src/Behat/Testwork/Cli/ServiceContainer/CliExtension.php +++ b/src/Behat/Testwork/Cli/ServiceContainer/CliExtension.php @@ -99,6 +99,7 @@ public function process(ContainerBuilder $container) protected function loadCommand(ContainerBuilder $container) { $definition = new Definition('Behat\Testwork\Cli\Command', array('%cli.command.name%', array())); + $definition->setPublic(true); $container->setDefinition(self::COMMAND_ID, $definition); } From 396c79c660f238d0e284dab1b335b282bc828865 Mon Sep 17 00:00:00 2001 From: Jakub Zalas Date: Fri, 27 Oct 2017 10:43:55 +0100 Subject: [PATCH 105/567] Allow to use the latest PHPUnit but keep compatibility with legacy versions --- composer.json | 2 +- features/append_snippets.feature | 48 +++++++-------- features/arguments.feature | 8 +-- features/autowire.feature | 6 +- features/bootstrap/FeatureContext.php | 31 +++++----- features/config_inheritance.feature | 4 +- features/context.feature | 8 +-- features/definitions_patterns.feature | 58 +++++++++---------- features/definitions_transformations.feature | 12 ++-- features/definitions_translations.feature | 16 ++--- features/error_reporting.feature | 4 +- features/extensions.feature | 2 +- features/format_options.feature | 8 +-- features/helper_containers.feature | 4 +- features/hooks.feature | 2 +- features/i18n.feature | 2 +- features/junit_format.feature | 16 ++--- features/multiple_formats.feature | 8 +-- features/outlines.feature | 4 +- features/parameters.feature | 2 +- features/pretty_format.feature | 6 +- features/profiles.feature | 2 +- features/rerun.feature | 8 +-- features/rerun_with_multiple_suite.feature | 8 +-- features/result_types.feature | 4 +- features/traits.feature | 2 +- .../Subject/GroupedSubjectIteratorTest.php | 3 +- 27 files changed, 140 insertions(+), 138 deletions(-) diff --git a/composer.json b/composer.json index b3dbd81f3..7126d0db4 100644 --- a/composer.json +++ b/composer.json @@ -31,7 +31,7 @@ "require-dev": { "symfony/process": "~2.5|~3.0", - "phpunit/phpunit": "~4.5", + "phpunit/phpunit": "^4.8.36|^6.3", "herrera-io/box": "~1.6.1" }, diff --git a/features/append_snippets.feature b/features/append_snippets.feature index 8eb9390ec..e1727bdb4 100644 --- a/features/append_snippets.feature +++ b/features/append_snippets.feature @@ -47,22 +47,22 @@ Feature: Append snippets option * @Then /^I should have (\d+) apples$/ */ public function iShouldHaveApples($count) { - \PHPUnit_Framework_Assert::assertEquals(intval($count), $this->apples); + \PHPUnit\Framework\Assert::assertEquals(intval($count), $this->apples); } /** * @Then /^context parameter "([^"]*)" should be equal to "([^"]*)"$/ */ public function contextParameterShouldBeEqualTo($key, $val) { - \PHPUnit_Framework_Assert::assertEquals($val, $this->parameters[$key]); + \PHPUnit\Framework\Assert::assertEquals($val, $this->parameters[$key]); } /** * @Given /^context parameter "([^"]*)" should be array with (\d+) elements$/ */ public function contextParameterShouldBeArrayWithElements($key, $count) { - \PHPUnit_Framework_Assert::assertInternalType('array', $this->parameters[$key]); - \PHPUnit_Framework_Assert::assertEquals(2, count($this->parameters[$key])); + \PHPUnit\Framework\Assert::assertInternalType('array', $this->parameters[$key]); + \PHPUnit\Framework\Assert::assertEquals(2, count($this->parameters[$key])); } private function doSomethingUndefinedWith() {} @@ -162,22 +162,22 @@ Feature: Append snippets option * @Then /^I should have (\d+) apples$/ */ public function iShouldHaveApples($count) { - \PHPUnit_Framework_Assert::assertEquals(intval($count), $this->apples); + \PHPUnit\Framework\Assert::assertEquals(intval($count), $this->apples); } /** * @Then /^context parameter "([^"]*)" should be equal to "([^"]*)"$/ */ public function contextParameterShouldBeEqualTo($key, $val) { - \PHPUnit_Framework_Assert::assertEquals($val, $this->parameters[$key]); + \PHPUnit\Framework\Assert::assertEquals($val, $this->parameters[$key]); } /** * @Given /^context parameter "([^"]*)" should be array with (\d+) elements$/ */ public function contextParameterShouldBeArrayWithElements($key, $count) { - \PHPUnit_Framework_Assert::assertInternalType('array', $this->parameters[$key]); - \PHPUnit_Framework_Assert::assertEquals(2, count($this->parameters[$key])); + \PHPUnit\Framework\Assert::assertInternalType('array', $this->parameters[$key]); + \PHPUnit\Framework\Assert::assertEquals(2, count($this->parameters[$key])); } private function doSomethingUndefinedWith() {} @@ -267,22 +267,22 @@ Feature: Append snippets option * @Then /^I should have (\d+) apples$/ */ public function iShouldHaveApples($count) { - \PHPUnit_Framework_Assert::assertEquals(intval($count), $this->apples); + \PHPUnit\Framework\Assert::assertEquals(intval($count), $this->apples); } /** * @Then /^context parameter "([^"]*)" should be equal to "([^"]*)"$/ */ public function contextParameterShouldBeEqualTo($key, $val) { - \PHPUnit_Framework_Assert::assertEquals($val, $this->parameters[$key]); + \PHPUnit\Framework\Assert::assertEquals($val, $this->parameters[$key]); } /** * @Given /^context parameter "([^"]*)" should be array with (\d+) elements$/ */ public function contextParameterShouldBeArrayWithElements($key, $count) { - \PHPUnit_Framework_Assert::assertInternalType('array', $this->parameters[$key]); - \PHPUnit_Framework_Assert::assertEquals(2, count($this->parameters[$key])); + \PHPUnit\Framework\Assert::assertInternalType('array', $this->parameters[$key]); + \PHPUnit\Framework\Assert::assertEquals(2, count($this->parameters[$key])); } private function doSomethingUndefinedWith() {} @@ -332,22 +332,22 @@ Feature: Append snippets option * @Then /^I should have (\d+) apples$/ */ public function iShouldHaveApples($count) { - \PHPUnit_Framework_Assert::assertEquals(intval($count), $this->apples); + \PHPUnit\Framework\Assert::assertEquals(intval($count), $this->apples); } /** * @Then /^context parameter "([^"]*)" should be equal to "([^"]*)"$/ */ public function contextParameterShouldBeEqualTo($key, $val) { - \PHPUnit_Framework_Assert::assertEquals($val, $this->parameters[$key]); + \PHPUnit\Framework\Assert::assertEquals($val, $this->parameters[$key]); } /** * @Given /^context parameter "([^"]*)" should be array with (\d+) elements$/ */ public function contextParameterShouldBeArrayWithElements($key, $count) { - \PHPUnit_Framework_Assert::assertInternalType('array', $this->parameters[$key]); - \PHPUnit_Framework_Assert::assertEquals(2, count($this->parameters[$key])); + \PHPUnit\Framework\Assert::assertInternalType('array', $this->parameters[$key]); + \PHPUnit\Framework\Assert::assertEquals(2, count($this->parameters[$key])); } private function doSomethingUndefinedWith() {} @@ -435,22 +435,22 @@ Feature: Append snippets option * @Then /^I should have (\d+) apples$/ */ public function iShouldHaveApples($count) { - \PHPUnit_Framework_Assert::assertEquals(intval($count), $this->apples); + \PHPUnit\Framework\Assert::assertEquals(intval($count), $this->apples); } /** * @Then /^context parameter "([^"]*)" should be equal to "([^"]*)"$/ */ public function contextParameterShouldBeEqualTo($key, $val) { - \PHPUnit_Framework_Assert::assertEquals($val, $this->parameters[$key]); + \PHPUnit\Framework\Assert::assertEquals($val, $this->parameters[$key]); } /** * @Given /^context parameter "([^"]*)" should be array with (\d+) elements$/ */ public function contextParameterShouldBeArrayWithElements($key, $count) { - \PHPUnit_Framework_Assert::assertInternalType('array', $this->parameters[$key]); - \PHPUnit_Framework_Assert::assertEquals(2, count($this->parameters[$key])); + \PHPUnit\Framework\Assert::assertInternalType('array', $this->parameters[$key]); + \PHPUnit\Framework\Assert::assertEquals(2, count($this->parameters[$key])); } private function doSomethingUndefinedWith() {} @@ -500,22 +500,22 @@ Feature: Append snippets option * @Then /^I should have (\d+) apples$/ */ public function iShouldHaveApples($count) { - \PHPUnit_Framework_Assert::assertEquals(intval($count), $this->apples); + \PHPUnit\Framework\Assert::assertEquals(intval($count), $this->apples); } /** * @Then /^context parameter "([^"]*)" should be equal to "([^"]*)"$/ */ public function contextParameterShouldBeEqualTo($key, $val) { - \PHPUnit_Framework_Assert::assertEquals($val, $this->parameters[$key]); + \PHPUnit\Framework\Assert::assertEquals($val, $this->parameters[$key]); } /** * @Given /^context parameter "([^"]*)" should be array with (\d+) elements$/ */ public function contextParameterShouldBeArrayWithElements($key, $count) { - \PHPUnit_Framework_Assert::assertInternalType('array', $this->parameters[$key]); - \PHPUnit_Framework_Assert::assertEquals(2, count($this->parameters[$key])); + \PHPUnit\Framework\Assert::assertInternalType('array', $this->parameters[$key]); + \PHPUnit\Framework\Assert::assertEquals(2, count($this->parameters[$key])); } private function doSomethingUndefinedWith() {} diff --git a/features/arguments.feature b/features/arguments.feature index 6da60915a..161a18111 100644 --- a/features/arguments.feature +++ b/features/arguments.feature @@ -44,22 +44,22 @@ Feature: Step Arguments * @Then /^it must be equals to string (\d+)$/ */ public function itMustBeEqualsToString($number) { - \PHPUnit_Framework_Assert::assertEquals($this->strings[intval($number)], (string) $this->input); + \PHPUnit\Framework\Assert::assertEquals($this->strings[intval($number)], (string) $this->input); } /** * @Then /^it must be equals to table (\d+)$/ */ public function itMustBeEqualsToTable($number) { - \PHPUnit_Framework_Assert::assertEquals($this->tables[intval($number)], $this->input->getHash()); + \PHPUnit\Framework\Assert::assertEquals($this->tables[intval($number)], $this->input->getHash()); } /** * @Given /^I have number2 = (?P\d+) and number1 = (?P\d+)$/ */ public function iHaveNumberAndNumber($number1, $number2) { - \PHPUnit_Framework_Assert::assertEquals(13, intval($number1)); - \PHPUnit_Framework_Assert::assertEquals(243, intval($number2)); + \PHPUnit\Framework\Assert::assertEquals(13, intval($number1)); + \PHPUnit\Framework\Assert::assertEquals(243, intval($number2)); } } """ diff --git a/features/autowire.feature b/features/autowire.feature index 6e8c9285f..86cff9a69 100644 --- a/features/autowire.feature +++ b/features/autowire.feature @@ -96,7 +96,7 @@ Feature: Helper services autowire class FeatureContext implements Context { public function __construct(Service2 $s2, $name, Service1 $s1, Service3 $s3) { - PHPUnit_Framework_Assert::assertEquals('Konstantin', $name); + PHPUnit\Framework\Assert::assertEquals('Konstantin', $name); } /** @Given a step */ @@ -150,7 +150,7 @@ Feature: Helper services autowire /** @Then that state should be persisted as :value */ public function checkState($val, Service2 $s2) { - PHPUnit_Framework_Assert::assertEquals($val, $s2->state); + PHPUnit\Framework\Assert::assertEquals($val, $s2->state); } } """ @@ -204,7 +204,7 @@ Feature: Helper services autowire /** @Then the :flag flag should be persisted as :value */ public function checkState($flag, $value) { - PHPUnit_Framework_Assert::assertEquals($value, $flag); + PHPUnit\Framework\Assert::assertEquals($value, $flag); } } """ diff --git a/features/bootstrap/FeatureContext.php b/features/bootstrap/FeatureContext.php index 629c6fc21..11905b956 100644 --- a/features/bootstrap/FeatureContext.php +++ b/features/bootstrap/FeatureContext.php @@ -10,6 +10,7 @@ use Behat\Behat\Context\Context; use Behat\Gherkin\Node\PyStringNode; +use PHPUnit\Framework\Assert; use Symfony\Component\Process\PhpExecutableFinder; use Symfony\Component\Process\Process; @@ -119,12 +120,12 @@ class FeatureContext implements Context $this->createFile($this->workingDir . '/' . $filename, $content); } - /** - * Creates a noop feature in current workdir. - * - * @Given /^(?:there is )?a some feature scenarios/ - */ - public function aNoopFeature() + /** + * Creates a noop feature in current workdir. + * + * @Given /^(?:there is )?a some feature scenarios/ + */ + public function aNoopFeature() { $filename = 'features/bootstrap/FeatureContext.php'; $content = <<<'EOL' @@ -156,7 +157,7 @@ public function iAmInThePath($path) */ public function fileShouldExist($path) { - PHPUnit_Framework_Assert::assertFileExists($this->workingDir . DIRECTORY_SEPARATOR . $path); + Assert::assertFileExists($this->workingDir . DIRECTORY_SEPARATOR . $path); } /** @@ -258,7 +259,7 @@ public function itShouldPassWith($success, PyStringNode $text) public function itShouldPassWithNoOutput($success) { $this->itShouldFail($success); - PHPUnit_Framework_Assert::assertEmpty($this->getOutput()); + Assert::assertEmpty($this->getOutput()); } /** @@ -272,7 +273,7 @@ public function itShouldPassWithNoOutput($success) public function fileShouldContain($path, PyStringNode $text) { $path = $this->workingDir . '/' . $path; - PHPUnit_Framework_Assert::assertFileExists($path); + Assert::assertFileExists($path); $fileContent = trim(file_get_contents($path)); // Normalize the line endings in the output @@ -280,7 +281,7 @@ public function fileShouldContain($path, PyStringNode $text) $fileContent = str_replace(PHP_EOL, "\n", $fileContent); } - PHPUnit_Framework_Assert::assertEquals($this->getExpectedOutput($text), $fileContent); + Assert::assertEquals($this->getExpectedOutput($text), $fileContent); } /** @@ -294,7 +295,7 @@ public function fileShouldContain($path, PyStringNode $text) public function fileXmlShouldBeLike($path, PyStringNode $text) { $path = $this->workingDir . '/' . $path; - PHPUnit_Framework_Assert::assertFileExists($path); + Assert::assertFileExists($path); $fileContent = trim(file_get_contents($path)); @@ -302,7 +303,7 @@ public function fileXmlShouldBeLike($path, PyStringNode $text) $dom->loadXML($text); $dom->formatOutput = true; - PHPUnit_Framework_Assert::assertEquals(trim($dom->saveXML(null, LIBXML_NOEMPTYTAG)), $fileContent); + Assert::assertEquals(trim($dom->saveXML(null, LIBXML_NOEMPTYTAG)), $fileContent); } @@ -315,7 +316,7 @@ public function fileXmlShouldBeLike($path, PyStringNode $text) */ public function theOutputShouldContain(PyStringNode $text) { - PHPUnit_Framework_Assert::assertContains($this->getExpectedOutput($text), $this->getOutput()); + Assert::assertContains($this->getExpectedOutput($text), $this->getOutput()); } private function getExpectedOutput(PyStringNode $expectedText) @@ -363,13 +364,13 @@ public function itShouldFail($success) echo 'Actual output:' . PHP_EOL . PHP_EOL . $this->getOutput(); } - PHPUnit_Framework_Assert::assertNotEquals(0, $this->getExitCode()); + Assert::assertNotEquals(0, $this->getExitCode()); } else { if (0 !== $this->getExitCode()) { echo 'Actual output:' . PHP_EOL . PHP_EOL . $this->getOutput(); } - PHPUnit_Framework_Assert::assertEquals(0, $this->getExitCode()); + Assert::assertEquals(0, $this->getExitCode()); } } diff --git a/features/config_inheritance.feature b/features/config_inheritance.feature index c418ad404..16d6cb5e6 100644 --- a/features/config_inheritance.feature +++ b/features/config_inheritance.feature @@ -73,12 +73,12 @@ Feature: Config inheritance /** @Then the context parameters should be overwritten */ public function theContextParametersOverwrite() { - \PHPUnit_Framework_Assert::assertEquals(array('param2' => 'val2'), $this->parameters); + \PHPUnit\Framework\Assert::assertEquals(array('param2' => 'val2'), $this->parameters); } /** @Then the extension config should be merged */ public function theExtensionConfigMerge() { - \PHPUnit_Framework_Assert::assertEquals(array('param1' => 'val2', 'param2' => 'val1'), $this->extension); + \PHPUnit\Framework\Assert::assertEquals(array('param1' => 'val2', 'param2' => 'val1'), $this->extension); } } """ diff --git a/features/context.feature b/features/context.feature index e96118009..eae21a44a 100644 --- a/features/context.feature +++ b/features/context.feature @@ -47,22 +47,22 @@ Feature: Context consistency * @Then /^I should have (\d+) apples$/ */ public function iShouldHaveApples($count) { - PHPUnit_Framework_Assert::assertEquals(intval($count), $this->apples); + PHPUnit\Framework\Assert::assertEquals(intval($count), $this->apples); } /** * @Then /^context parameter "([^"]*)" should be equal to "([^"]*)"$/ */ public function contextParameterShouldBeEqualTo($key, $val) { - PHPUnit_Framework_Assert::assertEquals($val, $this->parameters[$key]); + PHPUnit\Framework\Assert::assertEquals($val, $this->parameters[$key]); } /** * @Given /^context parameter "([^"]*)" should be array with (\d+) elements$/ */ public function contextParameterShouldBeArrayWithElements($key, $count) { - PHPUnit_Framework_Assert::assertInternalType('array', $this->parameters[$key]); - PHPUnit_Framework_Assert::assertEquals(2, count($this->parameters[$key])); + PHPUnit\Framework\Assert::assertInternalType('array', $this->parameters[$key]); + PHPUnit\Framework\Assert::assertEquals(2, count($this->parameters[$key])); } } diff --git a/features/definitions_patterns.feature b/features/definitions_patterns.feature index 66d4d553f..66eeb73d2 100644 --- a/features/definitions_patterns.feature +++ b/features/definitions_patterns.feature @@ -158,8 +158,8 @@ Feature: Step Definition Pattern * @Given only second :second */ public function invalidRegex($first = 'foo', $second = 'fiz') { - PHPUnit_Framework_Assert::assertEquals('foo', $first); - PHPUnit_Framework_Assert::assertEquals('bar', $second); + PHPUnit\Framework\Assert::assertEquals('foo', $first); + PHPUnit\Framework\Assert::assertEquals('bar', $second); } } """ @@ -192,7 +192,7 @@ Feature: Step Definition Pattern * @Given I can provide parameter :param */ public function parameterCouldBeNull($param = null) { - PHPUnit_Framework_Assert::assertNull($param); + PHPUnit\Framework\Assert::assertNull($param); } } """ @@ -256,7 +256,7 @@ Feature: Step Definition Pattern * parameter :param */ public function parameterCouldBeNull($param = null) { - PHPUnit_Framework_Assert::assertNull($param); + PHPUnit\Framework\Assert::assertNull($param); } } """ @@ -295,8 +295,8 @@ Feature: Step Definition Pattern * @Given I can provide parameters :someParam and :someParam2 */ public function multipleWrongNamedParameters($param1, $param2) { - PHPUnit_Framework_Assert::assertEquals('one', $param1); - PHPUnit_Framework_Assert::assertEquals('two', $param2); + PHPUnit\Framework\Assert::assertEquals('one', $param1); + PHPUnit\Framework\Assert::assertEquals('two', $param2); } } """ @@ -328,8 +328,8 @@ Feature: Step Definition Pattern * @Given I can provide parameters :someParam and :someParam2 */ public function multipleWrongNamedParameters($param1, $someParam) { - PHPUnit_Framework_Assert::assertEquals('two', $param1); - PHPUnit_Framework_Assert::assertEquals('one', $someParam); + PHPUnit\Framework\Assert::assertEquals('two', $param1); + PHPUnit\Framework\Assert::assertEquals('one', $someParam); } } """ @@ -361,9 +361,9 @@ Feature: Step Definition Pattern * @Given I can provide :count parameters :firstParam and :otherParam */ public function multipleWrongNamedParameters($param1, $firstParam, $count) { - PHPUnit_Framework_Assert::assertEquals('two', $param1); - PHPUnit_Framework_Assert::assertEquals('one', $firstParam); - PHPUnit_Framework_Assert::assertEquals(2, $count); + PHPUnit\Framework\Assert::assertEquals('two', $param1); + PHPUnit\Framework\Assert::assertEquals('one', $firstParam); + PHPUnit\Framework\Assert::assertEquals(2, $count); } } """ @@ -395,10 +395,10 @@ Feature: Step Definition Pattern * @Given I can provide :count parameters :firstParam and :otherParam with: */ public function multipleWrongNamedParameters($param1, $firstParam, $count, $string) { - PHPUnit_Framework_Assert::assertEquals('two', $param1); - PHPUnit_Framework_Assert::assertEquals('one', $firstParam); - PHPUnit_Framework_Assert::assertEquals(2, $count); - PHPUnit_Framework_Assert::assertEquals("Test", (string) $string); + PHPUnit\Framework\Assert::assertEquals('two', $param1); + PHPUnit\Framework\Assert::assertEquals('one', $firstParam); + PHPUnit\Framework\Assert::assertEquals(2, $count); + PHPUnit\Framework\Assert::assertEquals("Test", (string) $string); } } """ @@ -433,9 +433,9 @@ Feature: Step Definition Pattern * @Given I can provide :count parameters for :name: */ public function multipleWrongNamedParameters($count, $name, $string) { - PHPUnit_Framework_Assert::assertEquals('2', $count); - PHPUnit_Framework_Assert::assertEquals('thing', $name); - PHPUnit_Framework_Assert::assertEquals("Test", (string) $string); + PHPUnit\Framework\Assert::assertEquals('2', $count); + PHPUnit\Framework\Assert::assertEquals('thing', $name); + PHPUnit\Framework\Assert::assertEquals("Test", (string) $string); } } """ @@ -472,9 +472,9 @@ Feature: Step Definition Pattern */ public function checkEquality($path = null, $isNegative = null, PyStringNode $json = null) { - PHPUnit_Framework_Assert::assertNull($path); - PHPUnit_Framework_Assert::assertNull($isNegative); - PHPUnit_Framework_Assert::assertNotNull($json); + PHPUnit\Framework\Assert::assertNull($path); + PHPUnit\Framework\Assert::assertNull($isNegative); + PHPUnit\Framework\Assert::assertNotNull($json); } /** @@ -482,9 +482,9 @@ Feature: Step Definition Pattern */ public function checkEquality2($json = null, $path = null, $isNegative = null) { - PHPUnit_Framework_Assert::assertNull($path); - PHPUnit_Framework_Assert::assertNull($isNegative); - PHPUnit_Framework_Assert::assertNotNull($json); + PHPUnit\Framework\Assert::assertNull($path); + PHPUnit\Framework\Assert::assertNull($isNegative); + PHPUnit\Framework\Assert::assertNotNull($json); } } """ @@ -523,7 +523,7 @@ Feature: Step Definition Pattern * @Given I have a package v:version */ public function multipleWrongNamedParameters($version) { - PHPUnit_Framework_Assert::assertEquals('2.5', $version); + PHPUnit\Framework\Assert::assertEquals('2.5', $version); } } """ @@ -555,7 +555,7 @@ Feature: Step Definition Pattern * @When I enter the string :input */ public function multipleWrongNamedParameters($input) { - PHPUnit_Framework_Assert::assertEquals('', $input); + PHPUnit\Framework\Assert::assertEquals('', $input); } } """ @@ -587,8 +587,8 @@ Feature: Step Definition Pattern * @Then images should be uploaded to web\/uploads\/media\/default\/:arg1\/:arg2\/ */ public function multipleWrongNamedParameters($arg1, $arg2) { - PHPUnit_Framework_Assert::assertEquals('0001', $arg1); - PHPUnit_Framework_Assert::assertEquals('01', $arg2); + PHPUnit\Framework\Assert::assertEquals('0001', $arg1); + PHPUnit\Framework\Assert::assertEquals('01', $arg2); } } """ @@ -620,7 +620,7 @@ Feature: Step Definition Pattern * @Given I have a negative number :num */ public function multipleWrongNamedParameters($num) { - PHPUnit_Framework_Assert::assertEquals('-3', $num); + PHPUnit\Framework\Assert::assertEquals('-3', $num); } } """ diff --git a/features/definitions_transformations.feature b/features/definitions_transformations.feature index ff986a4ce..92c4e6f25 100644 --- a/features/definitions_transformations.feature +++ b/features/definitions_transformations.feature @@ -117,29 +117,29 @@ Feature: Step Arguments Transformations * @Then /Username must be "([^"]+)"/ */ public function usernameMustBe($username) { - PHPUnit_Framework_Assert::assertEquals($username, $this->user->getUsername()); + PHPUnit\Framework\Assert::assertEquals($username, $this->user->getUsername()); } /** * @Then /Age must be (\d+)/ */ public function ageMustBe($age) { - PHPUnit_Framework_Assert::assertEquals($age, $this->user->getAge()); - PHPUnit_Framework_Assert::assertInternalType('int', $age); + PHPUnit\Framework\Assert::assertEquals($age, $this->user->getAge()); + PHPUnit\Framework\Assert::assertInternalType('int', $age); } /** * @Then the Usernames must be: */ public function usernamesMustBe(array $usernames) { - PHPUnit_Framework_Assert::assertEquals($usernames[0], $this->user->getUsername()); + PHPUnit\Framework\Assert::assertEquals($usernames[0], $this->user->getUsername()); } /** * @Then /^the boolean (no) should be transformed to false$/ */ public function theBooleanShouldBeTransformed($boolean) { - PHPUnit_Framework_Assert::assertSame(false, $boolean); + PHPUnit\Framework\Assert::assertSame(false, $boolean); } } """ @@ -289,7 +289,7 @@ Feature: Step Arguments Transformations /** @Then the :field should be :value */ public function theFieldShouldBe($field, $value) { - PHPUnit_Framework_Assert::assertSame($value, $this->data[0][$field]); + PHPUnit\Framework\Assert::assertSame($value, $this->data[0][$field]); } } """ diff --git a/features/definitions_translations.feature b/features/definitions_translations.feature index df41e942f..c3ace9d05 100644 --- a/features/definitions_translations.feature +++ b/features/definitions_translations.feature @@ -47,7 +47,7 @@ Feature: Definitions translations * @Then /^I should see (\d+) on the screen$/ */ public function iShouldSeeOnTheScreen($result) { - PHPUnit_Framework_Assert::assertEquals(intval($result), $this->result); + PHPUnit\Framework\Assert::assertEquals(intval($result), $this->result); } /** @Transform /"([^"]+)" user/ */ @@ -59,7 +59,7 @@ Feature: Definitions translations * @Then /^the ("[^"]+" user) name should be "([^"]*)"$/ */ public function theUserUsername($user, $username) { - PHPUnit_Framework_Assert::assertEquals($username, $user->name); + PHPUnit\Framework\Assert::assertEquals($username, $user->name); } public static function getTranslationResources() { @@ -150,7 +150,7 @@ Feature: Definitions translations * @Then /^I should see (\d+) on the screen$/ */ public function iShouldSeeOnTheScreen($result) { - PHPUnit_Framework_Assert::assertEquals(intval($result), $this->result); + PHPUnit\Framework\Assert::assertEquals(intval($result), $this->result); } /** @Transform /"([^"]+)" user/ */ @@ -162,7 +162,7 @@ Feature: Definitions translations * @Then /^the ("[^"]+" user) name should be "([^"]*)"$/ */ public function theUserUsername($user, $username) { - PHPUnit_Framework_Assert::assertEquals($username, $user->name); + PHPUnit\Framework\Assert::assertEquals($username, $user->name); } public static function getTranslationResources() { @@ -231,7 +231,7 @@ Feature: Definitions translations * @Then /^I should see (\d+) on the screen$/ */ public function iShouldSeeOnTheScreen($result) { - PHPUnit_Framework_Assert::assertEquals(intval($result), $this->result); + PHPUnit\Framework\Assert::assertEquals(intval($result), $this->result); } /** @Transform /"([^"]+)" user/ */ @@ -243,7 +243,7 @@ Feature: Definitions translations * @Then /^the ("[^"]+" user) name should be "([^"]*)"$/ */ public function theUserUsername($user, $username) { - PHPUnit_Framework_Assert::assertEquals($username, $user->name); + PHPUnit\Framework\Assert::assertEquals($username, $user->name); } public static function getTranslationResources() { @@ -321,7 +321,7 @@ Feature: Definitions translations * @Then /^I should see (\d+) on the screen$/ */ public function iShouldSeeOnTheScreen($result) { - PHPUnit_Framework_Assert::assertEquals(intval($result), $this->result); + PHPUnit\Framework\Assert::assertEquals(intval($result), $this->result); } /** @Transform /"([^"]+)" user/ */ @@ -333,7 +333,7 @@ Feature: Definitions translations * @Then /^the ("[^"]+" user) name should be "([^"]*)"$/ */ public function theUserUsername($user, $username) { - PHPUnit_Framework_Assert::assertEquals($username, $user->name); + PHPUnit\Framework\Assert::assertEquals($username, $user->name); } public static function getTranslationResources() { diff --git a/features/error_reporting.feature b/features/error_reporting.feature index c3b859479..1139b48bc 100644 --- a/features/error_reporting.feature +++ b/features/error_reporting.feature @@ -37,7 +37,7 @@ Feature: Error Reporting */ public function iShouldGetNull() { - PHPUnit_Framework_Assert::assertNull($this->result); + PHPUnit\Framework\Assert::assertNull($this->result); } /** @@ -53,7 +53,7 @@ Feature: Error Reporting */ public function iShouldGet($arg1) { - PHPUnit_Framework_Assert::assertEquals($arg1, $this->result); + PHPUnit\Framework\Assert::assertEquals($arg1, $this->result); } } diff --git a/features/extensions.feature b/features/extensions.feature index 5fb9de911..9d5bd2f3f 100644 --- a/features/extensions.feature +++ b/features/extensions.feature @@ -31,7 +31,7 @@ Feature: Extensions /** @Then the extension should be loaded */ public function theExtensionLoaded() { - PHPUnit_Framework_Assert::assertEquals(array('param1' => 'val1', 'param2' => 'val2'), $this->extension); + PHPUnit\Framework\Assert::assertEquals(array('param1' => 'val1', 'param2' => 'val2'), $this->extension); } } """ diff --git a/features/format_options.feature b/features/format_options.feature index ce773fa0b..f523e42c9 100644 --- a/features/format_options.feature +++ b/features/format_options.feature @@ -47,22 +47,22 @@ Feature: Format options * @Then /^I should have (\d+) apples$/ */ public function iShouldHaveApples($count) { - PHPUnit_Framework_Assert::assertEquals(intval($count), $this->apples); + PHPUnit\Framework\Assert::assertEquals(intval($count), $this->apples); } /** * @Then /^context parameter "([^"]*)" should be equal to "([^"]*)"$/ */ public function contextParameterShouldBeEqualTo($key, $val) { - PHPUnit_Framework_Assert::assertEquals($val, $this->parameters[$key]); + PHPUnit\Framework\Assert::assertEquals($val, $this->parameters[$key]); } /** * @Given /^context parameter "([^"]*)" should be array with (\d+) elements$/ */ public function contextParameterShouldBeArrayWithElements($key, $count) { - PHPUnit_Framework_Assert::assertInternalType('array', $this->parameters[$key]); - PHPUnit_Framework_Assert::assertEquals(2, count($this->parameters[$key])); + PHPUnit\Framework\Assert::assertInternalType('array', $this->parameters[$key]); + PHPUnit\Framework\Assert::assertEquals(2, count($this->parameters[$key])); } } """ diff --git a/features/helper_containers.feature b/features/helper_containers.feature index 4b77d321f..97032f256 100644 --- a/features/helper_containers.feature +++ b/features/helper_containers.feature @@ -47,7 +47,7 @@ Feature: Per-suite helper containers /** @Given service has no state */ public function noState() { - PHPUnit_Framework_Assert::assertNull($this->service->number); + PHPUnit\Framework\Assert::assertNull($this->service->number); } /** @When service gets a state of :number in first context */ @@ -67,7 +67,7 @@ Feature: Per-suite helper containers /** @Then service should have a state of :number in second context */ public function checkState($number) { - PHPUnit_Framework_Assert::assertSame($number, $this->service->number); + PHPUnit\Framework\Assert::assertSame($number, $this->service->number); } } """ diff --git a/features/hooks.feature b/features/hooks.feature index 557969e4e..20066b000 100644 --- a/features/hooks.feature +++ b/features/hooks.feature @@ -101,7 +101,7 @@ Feature: hooks * @Then /^I must have (\d+)$/ */ public function iMustHave($number) { - \PHPUnit_Framework_Assert::assertEquals(intval($number), $this->number); + \PHPUnit\Framework\Assert::assertEquals(intval($number), $this->number); } } """ diff --git a/features/i18n.feature b/features/i18n.feature index b130b82e2..1856d204f 100644 --- a/features/i18n.feature +++ b/features/i18n.feature @@ -28,7 +28,7 @@ Feature: I18n * @Then /Я должен иметь (\d+)/ */ public function iShouldHave($number) { - PHPUnit_Framework_Assert::assertEquals(intval($number), $this->value); + PHPUnit\Framework\Assert::assertEquals(intval($number), $this->value); } /** diff --git a/features/junit_format.feature b/features/junit_format.feature index f9e4bfd88..180cd5a27 100644 --- a/features/junit_format.feature +++ b/features/junit_format.feature @@ -26,7 +26,7 @@ * @Then /I must have (\d+)/ */ public function iMustHave($num) { - PHPUnit_Framework_Assert::assertEquals($num, $this->value); + PHPUnit\Framework\Assert::assertEquals($num, $this->value); } /** @@ -151,7 +151,7 @@ * @Then /I must have (\d+)/ */ public function iMustHave($num) { - PHPUnit_Framework_Assert::assertEquals($num, $this->value); + PHPUnit\Framework\Assert::assertEquals($num, $this->value); } /** @@ -223,7 +223,7 @@ * @Then /I must have (\d+)/ */ public function iMustHave($num) { - PHPUnit_Framework_Assert::assertEquals($num, $this->value); + PHPUnit\Framework\Assert::assertEquals($num, $this->value); } /** @@ -303,7 +303,7 @@ * @Then /I will be stronger/ */ public function iWillBeStronger() { - PHPUnit_Framework_Assert::assertNotEquals(0, $this->strongLevel); + PHPUnit\Framework\Assert::assertNotEquals(0, $this->strongLevel); } } """ @@ -333,7 +333,7 @@ * @Then /I will be stronger/ */ public function iWillBeStronger() { - PHPUnit_Framework_Assert::assertNotEquals(0, $this->strongLevel); + PHPUnit\Framework\Assert::assertNotEquals(0, $this->strongLevel); } } """ @@ -486,7 +486,7 @@ * @Then /I must have (\d+)/ */ public function iMustHave($num) { - PHPUnit_Framework_Assert::assertEquals($num, $this->value); + PHPUnit\Framework\Assert::assertEquals($num, $this->value); } /** @@ -550,7 +550,7 @@ * @Then /I must have (\d+)/ */ public function iMustHave($num) { - PHPUnit_Framework_Assert::assertEqual($num, $this->value); + PHPUnit\Framework\Assert::assertEqual($num, $this->value); } /** @@ -578,7 +578,7 @@ When I run "behat --no-colors -f junit -o junit" Then it should fail with: """ - Call to undefined method PHPUnit_Framework_Assert::assertEqual + Call to undefined method PHPUnit\Framework\Assert::assertEqual """ And "junit/default.xml" file xml should be like: """ diff --git a/features/multiple_formats.feature b/features/multiple_formats.feature index 1ef068178..ecbb2605c 100644 --- a/features/multiple_formats.feature +++ b/features/multiple_formats.feature @@ -47,22 +47,22 @@ Feature: Multiple formats * @Then /^I should have (\d+) apples$/ */ public function iShouldHaveApples($count) { - PHPUnit_Framework_Assert::assertEquals(intval($count), $this->apples); + PHPUnit\Framework\Assert::assertEquals(intval($count), $this->apples); } /** * @Then /^context parameter "([^"]*)" should be equal to "([^"]*)"$/ */ public function contextParameterShouldBeEqualTo($key, $val) { - PHPUnit_Framework_Assert::assertEquals($val, $this->parameters[$key]); + PHPUnit\Framework\Assert::assertEquals($val, $this->parameters[$key]); } /** * @Given /^context parameter "([^"]*)" should be array with (\d+) elements$/ */ public function contextParameterShouldBeArrayWithElements($key, $count) { - PHPUnit_Framework_Assert::assertInternalType('array', $this->parameters[$key]); - PHPUnit_Framework_Assert::assertEquals(2, count($this->parameters[$key])); + PHPUnit\Framework\Assert::assertInternalType('array', $this->parameters[$key]); + PHPUnit\Framework\Assert::assertEquals(2, count($this->parameters[$key])); } } """ diff --git a/features/outlines.feature b/features/outlines.feature index 148f9ab7c..352fca98c 100644 --- a/features/outlines.feature +++ b/features/outlines.feature @@ -80,7 +80,7 @@ Feature: Scenario Outlines * @Then /^The result should be (\d+)$/ */ public function theResultShouldBe($result) { - PHPUnit_Framework_Assert::assertEquals(intval($result), $this->result); + PHPUnit\Framework\Assert::assertEquals(intval($result), $this->result); } } """ @@ -242,7 +242,7 @@ Feature: Scenario Outlines * @Then the result should be :result */ public function theResultShouldBe($result) { - PHPUnit_Framework_Assert::assertEquals(intval($result), $this->number); + PHPUnit\Framework\Assert::assertEquals(intval($result), $this->number); } } """ diff --git a/features/parameters.feature b/features/parameters.feature index b60550dcc..784c542ac 100644 --- a/features/parameters.feature +++ b/features/parameters.feature @@ -53,7 +53,7 @@ Feature: Parameters * @Then /The result should be (\d+)/ */ public function theResultShouldBe($result) { - PHPUnit_Framework_Assert::assertEquals($result, $this->result); + PHPUnit\Framework\Assert::assertEquals($result, $this->result); } } """ diff --git a/features/pretty_format.feature b/features/pretty_format.feature index 1bfa914ca..6f7a575ee 100644 --- a/features/pretty_format.feature +++ b/features/pretty_format.feature @@ -28,7 +28,7 @@ Feature: Pretty Formatter * @Then /I must have (\d+)/ */ public function iMustHave($num) { - PHPUnit_Framework_Assert::assertEquals($num, $this->value); + PHPUnit\Framework\Assert::assertEquals($num, $this->value); } /** @@ -163,7 +163,7 @@ Feature: Pretty Formatter * @Then /I must have (\d+)/ */ public function iMustHave($num) { - PHPUnit_Framework_Assert::assertEquals($num, $this->value); + PHPUnit\Framework\Assert::assertEquals($num, $this->value); } /** @@ -245,7 +245,7 @@ Feature: Pretty Formatter * @Then /I must have "([^"]+)"/ */ public function iMustHave($num) { - PHPUnit_Framework_Assert::assertEquals(intval(preg_replace('/[^\d]+/', '', $num)), $this->value); + PHPUnit\Framework\Assert::assertEquals(intval(preg_replace('/[^\d]+/', '', $num)), $this->value); } /** diff --git a/features/profiles.feature b/features/profiles.feature index 481b3a9d6..6b726437b 100644 --- a/features/profiles.feature +++ b/features/profiles.feature @@ -51,7 +51,7 @@ Feature: Profiles * @Then /The result should be (\d+)/ */ public function theResultShouldBe($result) { - PHPUnit_Framework_Assert::assertEquals($result, $this->result); + PHPUnit\Framework\Assert::assertEquals($result, $this->result); } } """ diff --git a/features/rerun.feature b/features/rerun.feature index e835b8e0d..0aa3000c4 100644 --- a/features/rerun.feature +++ b/features/rerun.feature @@ -44,22 +44,22 @@ Feature: Rerun * @Then /^I should have (\d+) apples$/ */ public function iShouldHaveApples($count) { - PHPUnit_Framework_Assert::assertEquals(intval($count), $this->apples); + PHPUnit\Framework\Assert::assertEquals(intval($count), $this->apples); } /** * @Then /^context parameter "([^"]*)" should be equal to "([^"]*)"$/ */ public function contextParameterShouldBeEqualTo($key, $val) { - PHPUnit_Framework_Assert::assertEquals($val, $this->parameters[$key]); + PHPUnit\Framework\Assert::assertEquals($val, $this->parameters[$key]); } /** * @Given /^context parameter "([^"]*)" should be array with (\d+) elements$/ */ public function contextParameterShouldBeArrayWithElements($key, $count) { - PHPUnit_Framework_Assert::assertInternalType('array', $this->parameters[$key]); - PHPUnit_Framework_Assert::assertEquals(2, count($this->parameters[$key])); + PHPUnit\Framework\Assert::assertInternalType('array', $this->parameters[$key]); + PHPUnit\Framework\Assert::assertEquals(2, count($this->parameters[$key])); } } """ diff --git a/features/rerun_with_multiple_suite.feature b/features/rerun_with_multiple_suite.feature index feb04dfa4..a706b8d1e 100644 --- a/features/rerun_with_multiple_suite.feature +++ b/features/rerun_with_multiple_suite.feature @@ -60,22 +60,22 @@ Feature: Rerun with multiple suite * @Then /^I should have (\d+) (apples|bananas)$/ */ public function iShouldHaveFruit($count, $fruit) { - PHPUnit_Framework_Assert::assertEquals(intval($count), $this->fruits[$fruit]); + PHPUnit\Framework\Assert::assertEquals(intval($count), $this->fruits[$fruit]); } /** * @Then /^context parameter "([^"]*)" should be equal to "([^"]*)"$/ */ public function contextParameterShouldBeEqualTo($key, $val) { - PHPUnit_Framework_Assert::assertEquals($val, $this->parameters[$key]); + PHPUnit\Framework\Assert::assertEquals($val, $this->parameters[$key]); } /** * @Given /^context parameter "([^"]*)" should be array with (\d+) elements$/ */ public function contextParameterShouldBeArrayWithElements($key, $count) { - PHPUnit_Framework_Assert::assertInternalType('array', $this->parameters[$key]); - PHPUnit_Framework_Assert::assertEquals(2, count($this->parameters[$key])); + PHPUnit\Framework\Assert::assertInternalType('array', $this->parameters[$key]); + PHPUnit\Framework\Assert::assertEquals(2, count($this->parameters[$key])); } } """ diff --git a/features/result_types.feature b/features/result_types.feature index 3467b6eaf..04feb95a5 100644 --- a/features/result_types.feature +++ b/features/result_types.feature @@ -236,7 +236,7 @@ Feature: Different result types * @Then /^I should see (\d+)\$ on the screen$/ */ public function iShouldSee($money) { - PHPUnit_Framework_Assert::assertEquals($money, $this->money); + PHPUnit\Framework\Assert::assertEquals($money, $this->money); } } """ @@ -324,7 +324,7 @@ Feature: Different result types * @Then /^I should see (\d+)\$ on the screen$/ */ public function iShouldSee($money) { - PHPUnit_Framework_Assert::assertEquals($money, $this->money); + PHPUnit\Framework\Assert::assertEquals($money, $this->money); } } """ diff --git a/features/traits.feature b/features/traits.feature index 0c2157cef..dc2c6a519 100644 --- a/features/traits.feature +++ b/features/traits.feature @@ -49,7 +49,7 @@ Feature: Support php 5.4 traits * @Then /^I should have (\d+) apples$/ */ public function iShouldHaveApples($count) { - PHPUnit_Framework_Assert::assertEquals(intval($count), $this->apples); + PHPUnit\Framework\Assert::assertEquals(intval($count), $this->apples); } } """ diff --git a/tests/Behat/Tests/Testwork/Subject/GroupedSubjectIteratorTest.php b/tests/Behat/Tests/Testwork/Subject/GroupedSubjectIteratorTest.php index e260b7596..84b8dd18f 100644 --- a/tests/Behat/Tests/Testwork/Subject/GroupedSubjectIteratorTest.php +++ b/tests/Behat/Tests/Testwork/Subject/GroupedSubjectIteratorTest.php @@ -5,8 +5,9 @@ use Behat\Testwork\Specification\GroupedSpecificationIterator; use Behat\Testwork\Specification\NoSpecificationsIterator; use Behat\Testwork\Specification\SpecificationArrayIterator; +use PHPUnit\Framework\TestCase; -class GroupedSubjectIteratorTest extends \PHPUnit_Framework_TestCase +class GroupedSubjectIteratorTest extends TestCase { public function testIterationWithEmptyAtBeginning() { From 83d9e0cfdc16b475ab74b6276ee3ad1e6309a184 Mon Sep 17 00:00:00 2001 From: Ciaran McNulty Date: Thu, 16 Nov 2017 22:51:53 +0000 Subject: [PATCH 106/567] Fix error from merge conflict --- composer.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/composer.json b/composer.json index d76139de9..2f5acf657 100644 --- a/composer.json +++ b/composer.json @@ -31,7 +31,7 @@ "require-dev": { "symfony/process": "~2.5|~3.0|~4.0", - "phpunit/phpunit": "^4.8.36|^6.3" + "phpunit/phpunit": "^4.8.36|^6.3", "herrera-io/box": "~1.6.1" }, From 7a47963e73f9e864a490ee8c4a3f56f6b6b063d2 Mon Sep 17 00:00:00 2001 From: everzet Date: Mon, 20 Nov 2017 08:50:25 +0000 Subject: [PATCH 107/567] Remove callable typehint This breaks 5.3 --- src/Behat/Testwork/Argument/MixedArgumentOrganiser.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Behat/Testwork/Argument/MixedArgumentOrganiser.php b/src/Behat/Testwork/Argument/MixedArgumentOrganiser.php index bc116ddd2..533214836 100644 --- a/src/Behat/Testwork/Argument/MixedArgumentOrganiser.php +++ b/src/Behat/Testwork/Argument/MixedArgumentOrganiser.php @@ -252,7 +252,7 @@ private function applyPredicateToTypehintedArguments( array $parameters, array &$candidates, array &$arguments, - callable $predicate + $predicate ) { $filtered = $this->filterApplicableTypehintedParameters($parameters); @@ -275,7 +275,7 @@ public function matchParameterToCandidateUsingPredicate( ReflectionParameter $parameter, array &$candidates, array &$arguments, - callable $predicate + $predicate ) { foreach ($candidates as $candidateIndex => $candidate) { if (call_user_func_array($predicate, array($parameter->getClass(), $candidate))) { From 18990c31ad0e670df7ed8a35e1ce552fea7e5d78 Mon Sep 17 00:00:00 2001 From: everzet Date: Mon, 20 Nov 2017 08:56:22 +0000 Subject: [PATCH 108/567] Bump changelog --- CHANGELOG.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 26c9c258c..2e6d6fecc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,11 @@ and this project adheres to [Semantic Versioning](http://semver.org/). ## [Unreleased] +## [3.4.2] - 2017-11-20 +### Added + * [#1095](https://github.com/Behat/Behat/pull/1095): Support for Symfony 4.x + * [#1096](https://github.com/Behat/Behat/pull/1096): Allow to use latest PHPUnit + ## [3.4.1] - 2017-09-18 ### Fixed * PHP 5.3 style cleanup. From ccb728f6d4dc156c38c19ce7b7a7613c175e86af Mon Sep 17 00:00:00 2001 From: everzet Date: Mon, 20 Nov 2017 09:01:02 +0000 Subject: [PATCH 109/567] Fix references in the CHANGELOG --- CHANGELOG.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2e6d6fecc..92cecac23 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -867,7 +867,8 @@ and this project adheres to [Semantic Versioning](http://semver.org/). ### Changed * Initial release -[Unreleased]: https://github.com/Behat/Behat/compare/v3.4.1...HEAD +[Unreleased]: https://github.com/Behat/Behat/compare/v3.4.2...HEAD +[3.4.2]: https://github.com/Behat/Behat/compare/v3.4.1...v3.4.2 [3.4.1]: https://github.com/Behat/Behat/compare/v3.4.0...v3.4.1 [3.4.0]: https://github.com/Behat/Behat/compare/v3.3.1...v3.4.0 [3.3.1]: https://github.com/Behat/Behat/compare/v3.3.0...v3.3.1 From 8789ee1efb5e3af669b7a9a9c54c48e1a3971980 Mon Sep 17 00:00:00 2001 From: everzet Date: Mon, 27 Nov 2017 10:35:53 +0000 Subject: [PATCH 110/567] Fix BC break in DIC parameter resolution Some Behat extensions already depend on Behat not resolving parameters and handle escaping themselves. The change in 3.4 broke that behaviour and many test suites with it. This commit reverts the change to how it was. It does disable environment variables again, but this is a lesser of two evils. --- CHANGELOG.md | 7 ++++++- src/Behat/Testwork/Cli/Application.php | 2 +- 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 92cecac23..c6e3fbf67 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,10 @@ and this project adheres to [Semantic Versioning](http://semver.org/). ## [Unreleased] +## [3.4.3] - 2017-11-27 +### Fixed + * BC break due to parameters resolution in Dependency Injection Container + ## [3.4.2] - 2017-11-20 ### Added * [#1095](https://github.com/Behat/Behat/pull/1095): Support for Symfony 4.x @@ -867,7 +871,8 @@ and this project adheres to [Semantic Versioning](http://semver.org/). ### Changed * Initial release -[Unreleased]: https://github.com/Behat/Behat/compare/v3.4.2...HEAD +[Unreleased]: https://github.com/Behat/Behat/compare/v3.4.3...HEAD +[3.4.3]: https://github.com/Behat/Behat/compare/v3.4.2...v3.4.3 [3.4.2]: https://github.com/Behat/Behat/compare/v3.4.1...v3.4.2 [3.4.1]: https://github.com/Behat/Behat/compare/v3.4.0...v3.4.1 [3.4.0]: https://github.com/Behat/Behat/compare/v3.3.1...v3.4.0 diff --git a/src/Behat/Testwork/Cli/Application.php b/src/Behat/Testwork/Cli/Application.php index 4189224e0..f9f35212e 100644 --- a/src/Behat/Testwork/Cli/Application.php +++ b/src/Behat/Testwork/Cli/Application.php @@ -184,7 +184,7 @@ private function createContainer(InputInterface $input, OutputInterface $output) $extension = new ContainerLoader($this->extensionManager); $extension->load($container, $this->loadConfiguration($input)); $container->addObjectResource($extension); - $container->compile(true); + $container->compile(); return $container; } From 203ce015c92b2ebebb3d5908af4bf3d92cea81d7 Mon Sep 17 00:00:00 2001 From: everzet Date: Mon, 27 Nov 2017 11:15:15 +0000 Subject: [PATCH 111/567] Relax assertions and fix yaml examples --- features/context.feature | 9 +++------ features/definitions_patterns.feature | 6 ++---- features/execution_order.feature | 3 +-- features/extensions.feature | 3 +-- features/init.feature | 14 +++++++------- features/junit_format.feature | 3 +-- features/suite.feature | 11 +++++------ 7 files changed, 20 insertions(+), 29 deletions(-) diff --git a/features/context.feature b/features/context.feature index eae21a44a..eab92c3d9 100644 --- a/features/context.feature +++ b/features/context.feature @@ -311,8 +311,7 @@ Feature: Context consistency When I run "behat --no-colors -f progress features/params.feature" Then it should fail with: """ - [Behat\Testwork\Suite\Exception\SuiteConfigurationException] - `contexts` setting of the "default" suite is expected to be an array, string given. + `contexts` setting of the "default" suite is expected to be an array, string given. """ Scenario: Unexisting custom context class @@ -337,8 +336,7 @@ Feature: Context consistency When I run "behat --no-colors -f progress features/params.feature" Then it should fail with: """ - [Behat\Behat\Context\Exception\ContextNotFoundException] - `UnexistentContext` context class not found and can not be used. + `UnexistentContext` context class not found and can not be used. """ Scenario: Unexisting context argument @@ -365,8 +363,7 @@ Feature: Context consistency When I run "behat --no-colors -f progress features/params.feature" Then it should fail with: """ - [Behat\Testwork\Argument\Exception\UnknownParameterValueException] - `CoreContext::__construct()` does not expect argument `$unexistingParam`. + `CoreContext::__construct()` does not expect argument `$unexistingParam`. """ Scenario: Suite without contexts and FeatureContext available diff --git a/features/definitions_patterns.feature b/features/definitions_patterns.feature index 66eeb73d2..bc62dc4a3 100644 --- a/features/definitions_patterns.feature +++ b/features/definitions_patterns.feature @@ -141,8 +141,7 @@ Feature: Step Definition Pattern When I run "behat -f progress --no-colors" Then it should fail with: """ - [Behat\Behat\Definition\Exception\InvalidPatternException] - The regex `/I am (foo/` is invalid: + The regex `/I am (foo/` is invalid: """ Scenario: Pattern with default values @@ -235,8 +234,7 @@ Feature: Step Definition Pattern When I run "behat -f progress --no-colors" Then it should fail with: """ - [Behat\Behat\Definition\Exception\InvalidPatternException] - Token name should not exceed 32 characters, but `too1234567891123456789012345678901` was used. + Token name should not exceed 32 characters, but `too1234567891123456789012345678901` was used. """ Scenario: Multiline definitions diff --git a/features/execution_order.feature b/features/execution_order.feature index d778418c2..f97d2195d 100644 --- a/features/execution_order.feature +++ b/features/execution_order.feature @@ -61,8 +61,7 @@ Feature: Setting order of execution When I run "behat -fpretty --order=foo" Then it should fail with: """ - [Behat\Testwork\Ordering\Exception\InvalidOrderException] - Order option 'foo' was not recognised + Order option 'foo' was not recognised """ Scenario: Reverse order diff --git a/features/extensions.feature b/features/extensions.feature index 9d5bd2f3f..eefaa76a7 100644 --- a/features/extensions.feature +++ b/features/extensions.feature @@ -119,8 +119,7 @@ Feature: Extensions When I run "behat -f progress --no-colors" Then it should fail with: """ - [Behat\Testwork\ServiceContainer\Exception\ExtensionInitializationException] - `inexistent_extension` extension file or class could not be located. + `inexistent_extension` extension file or class could not be located. """ @php-version @php7.0 diff --git a/features/init.feature b/features/init.feature index 20237800a..a4134e1d4 100644 --- a/features/init.feature +++ b/features/init.feature @@ -19,10 +19,10 @@ Feature: Init And a file named "behat.yml" with: """ default: - autoload: %paths.base%/supp + autoload: '%paths.base%/supp' suites: default: - paths: [ %paths.base%/scenarios ] + paths: [ '%paths.base%/scenarios' ] contexts: [ CustomContext ] """ When I run "behat --no-colors --init" @@ -39,13 +39,13 @@ Feature: Init And a file named "behat.yml" with: """ default: - autoload: %paths.base%/contexts + autoload: '%paths.base%/contexts' suites: suite1: - paths: [ %paths.base%/scenarios1 ] + paths: [ '%paths.base%/scenarios1' ] contexts: [ Custom1Context ] suite2: - paths: [ %paths.base%/scenarios2 ] + paths: [ '%paths.base%/scenarios2' ] contexts: [ Custom2Context ] """ When I run "behat --no-colors --init" @@ -65,10 +65,10 @@ Feature: Init And a file named "behat.yml" with: """ default: - autoload: %paths.base%/supp + autoload: '%paths.base%/supp' suites: default: - paths: [ %paths.base%/scenarios ] + paths: [ '%paths.base%/scenarios' ] contexts: - CustomContext: [ 'a', 'b' ] """ diff --git a/features/junit_format.feature b/features/junit_format.feature index 180cd5a27..eb611f844 100644 --- a/features/junit_format.feature +++ b/features/junit_format.feature @@ -604,8 +604,7 @@ When I run "behat --no-colors -f junit -o junit.txt" Then it should fail with: """ - [Behat\Testwork\Output\Exception\BadOutputPathException] - Directory expected for the `output_path` option, but a filename was given. + Directory expected for the `output_path` option, but a filename was given. """ Scenario: Include BeforeStep Failures diff --git a/features/suite.feature b/features/suite.feature index 5a42d6d11..645abea17 100644 --- a/features/suite.feature +++ b/features/suite.feature @@ -146,10 +146,10 @@ Feature: Suites default: suites: first: - paths: [ %paths.base%/features/first ] + paths: [ '%paths.base%/features/first' ] contexts: [ FirstContext ] second: - paths: [ %paths.base%/features/second ] + paths: [ '%paths.base%/features/second' ] contexts: [ SecondContext ] """ When I run "behat --no-colors -fpretty --format-settings='{\"paths\": true}' features" @@ -241,17 +241,16 @@ Feature: Suites default: suites: first: - paths: %paths.base%/features/first + paths: '%paths.base%/features/first' contexts: [ FirstContext ] second: - paths: [ %paths.base%/features/second ] + paths: [ '%paths.base%/features/second' ] contexts: [ SecondContext ] """ When I run "behat --no-colors -fpretty --format-settings='{\"paths\": true}' features" Then it should fail with: """ - Behat\Testwork\Suite\Exception\SuiteConfigurationException] - `paths` setting of the "first" suite is expected to be an array, string given. + `paths` setting of the "first" suite is expected to be an array, string given. """ Scenario: Role-based suites From ec1dd6f4622b1ab6c844424b16c6fe5257676d93 Mon Sep 17 00:00:00 2001 From: everzet Date: Mon, 27 Nov 2017 11:30:07 +0000 Subject: [PATCH 112/567] Custom container must be public to be accesible by Behat --- features/helper_containers.feature | 1 + 1 file changed, 1 insertion(+) diff --git a/features/helper_containers.feature b/features/helper_containers.feature index 97032f256..4ef1bddb6 100644 --- a/features/helper_containers.feature +++ b/features/helper_containers.feature @@ -362,6 +362,7 @@ Feature: Per-suite helper containers public function load(ContainerBuilder $container, array $config) { $definition = new Definition('MyContainer', array()); $definition->addTag(HelperContainerExtension::HELPER_CONTAINER_TAG); + $definition->setPublic(true); if (method_exists($definition, 'setShared')) { $definition->setShared(false); // <- Starting Symfony 2.8 From b2734e5516d0d6bbbfd50a67fabfa0611a70252b Mon Sep 17 00:00:00 2001 From: everzet Date: Mon, 27 Nov 2017 11:47:48 +0000 Subject: [PATCH 113/567] Fix the last broken test on Symfony 4 --- features/junit_format.feature | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/features/junit_format.feature b/features/junit_format.feature index eb611f844..6cfd9a1c1 100644 --- a/features/junit_format.feature +++ b/features/junit_format.feature @@ -373,10 +373,10 @@ contexts: [SmallKidContext] filters: role: small kid - path: %paths.base%/features + path: '%paths.base%/features' old_man: contexts: [OldManContext] - path: %paths.base%/features + path: '%paths.base%/features' filters: role: old man """ From c22d74ff630b659f69fd51351148761205b87e56 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?K=C3=A9vin=20Dunglas?= Date: Tue, 28 Nov 2017 11:07:27 +0100 Subject: [PATCH 114/567] symfony/class-loader 4.0 doesn't exist --- composer.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/composer.json b/composer.json index 2f5acf657..187510289 100644 --- a/composer.json +++ b/composer.json @@ -24,7 +24,7 @@ "symfony/event-dispatcher": "~2.1||~3.0||~4.0", "symfony/translation": "~2.3||~3.0||~4.0", "symfony/yaml": "~2.1||~3.0||~4.0", - "symfony/class-loader": "~2.1||~3.0||~4.0", + "symfony/class-loader": "~2.1||~3.0", "psr/container": "^1.0", "container-interop/container-interop": "^1.2" }, From 3334785524b3d7ff5f5a7267d447af921e0bc249 Mon Sep 17 00:00:00 2001 From: Serhii Polishchuk Date: Fri, 19 Jan 2018 15:48:51 +0700 Subject: [PATCH 115/567] Support BC break for constructor arguments --- .../Behat/Output/Node/Printer/JUnit/JUnitFeaturePrinter.php | 6 +++--- .../Output/Node/Printer/JUnit/JUnitScenarioPrinter.php | 6 +++--- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/src/Behat/Behat/Output/Node/Printer/JUnit/JUnitFeaturePrinter.php b/src/Behat/Behat/Output/Node/Printer/JUnit/JUnitFeaturePrinter.php index 7b3277a0d..651c4a650 100644 --- a/src/Behat/Behat/Output/Node/Printer/JUnit/JUnitFeaturePrinter.php +++ b/src/Behat/Behat/Output/Node/Printer/JUnit/JUnitFeaturePrinter.php @@ -32,11 +32,11 @@ final class JUnitFeaturePrinter implements FeaturePrinter private $statistics; /** - * @var JUnitDurationListener + * @var JUnitDurationListener|null */ private $durationListener; - public function __construct(PhaseStatistics $statistics, JUnitDurationListener $durationListener) + public function __construct(PhaseStatistics $statistics, JUnitDurationListener $durationListener = null) { $this->statistics = $statistics; $this->durationListener = $durationListener; @@ -64,7 +64,7 @@ public function printHeader(Formatter $formatter, FeatureNode $feature) 'skipped' => $stats[TestResult::SKIPPED], 'failures' => $stats[TestResult::FAILED], 'errors' => $stats[TestResult::PENDING] + $stats[StepResult::UNDEFINED], - 'time' => $this->durationListener->getFeatureDuration($feature) + 'time' => $this->durationListener ? $this->durationListener->getFeatureDuration($feature) : '', )); $this->statistics->reset(); } diff --git a/src/Behat/Behat/Output/Node/Printer/JUnit/JUnitScenarioPrinter.php b/src/Behat/Behat/Output/Node/Printer/JUnit/JUnitScenarioPrinter.php index a20b6ded5..57f8906e9 100644 --- a/src/Behat/Behat/Output/Node/Printer/JUnit/JUnitScenarioPrinter.php +++ b/src/Behat/Behat/Output/Node/Printer/JUnit/JUnitScenarioPrinter.php @@ -49,11 +49,11 @@ final class JUnitScenarioPrinter private $outlineStepCount; /** - * @var JUnitDurationListener + * @var JUnitDurationListener|null */ private $durationListener; - public function __construct(ResultToStringConverter $resultConverter, JUnitOutlineStoreListener $outlineListener, JUnitDurationListener $durationListener) + public function __construct(ResultToStringConverter $resultConverter, JUnitOutlineStoreListener $outlineListener, JUnitDurationListener $durationListener = null) { $this->resultConverter = $resultConverter; $this->outlineStoreListener = $outlineListener; @@ -79,7 +79,7 @@ public function printOpenTag(Formatter $formatter, FeatureNode $feature, Scenari $outputPrinter->addTestcase(array( 'name' => $name, 'status' => $this->resultConverter->convertResultToString($result), - 'time' => $this->durationListener->getDuration($scenario) + 'time' => $this->durationListener ? $this->durationListener->getDuration($scenario) : '' )); } From 134ca5884cf1729929748fba169b51cd7b5b48e9 Mon Sep 17 00:00:00 2001 From: Jakub Zalas Date: Fri, 26 Jan 2018 15:02:25 +0000 Subject: [PATCH 116/567] Fix the test suite by working around a Symfony problem There is a BC break that broke the test suite: https://github.com/symfony/symfony/issues/25825 --- features/suite.feature | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/features/suite.feature b/features/suite.feature index 645abea17..e59919fb2 100644 --- a/features/suite.feature +++ b/features/suite.feature @@ -517,7 +517,7 @@ Feature: Suites filters: role: big brother """ - When I run "behat --no-colors -sbig_brother -fpretty --format-settings='{\"paths\": true}' features" + When I run "behat --no-colors -s big_brother -fpretty --format-settings='{\"paths\": true}' features" Then it should pass with: """ Feature: Apples story From ce9934dd96eece73f8a9fe7a2a6db60da231c8d8 Mon Sep 17 00:00:00 2001 From: Jakub Zalas Date: Fri, 26 Jan 2018 21:54:33 +0000 Subject: [PATCH 117/567] Bump PHP version used in AppVeyor --- appveyor.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/appveyor.yml b/appveyor.yml index 945deee67..e81556764 100644 --- a/appveyor.yml +++ b/appveyor.yml @@ -6,7 +6,7 @@ clone_folder: c:\projects\behat environment: matrix: - - PHP_DOWNLOAD_FILE: php-7.1.9-nts-Win32-VC14-x86.zip + - PHP_DOWNLOAD_FILE: php-7.2.1-nts-Win32-VC15-x86.zip branches: only: From 5fcd33b112aadf7c9cdcdb7596dd6dafb0d81048 Mon Sep 17 00:00:00 2001 From: Jakub Zalas Date: Fri, 26 Jan 2018 21:59:07 +0000 Subject: [PATCH 118/567] Disable colours in scenarios with complex output to make them pass on windows again --- features/execution_order.feature | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/features/execution_order.feature b/features/execution_order.feature index f97d2195d..4348fe6b6 100644 --- a/features/execution_order.feature +++ b/features/execution_order.feature @@ -38,7 +38,7 @@ Feature: Setting order of execution """ Scenario: No order specified - When I run "behat -fpretty" + When I run "behat -fpretty --no-colors" Then it should pass with: """ Feature: Feature 1 @@ -65,7 +65,7 @@ Feature: Setting order of execution """ Scenario: Reverse order - When I run "behat -fpretty --order=reverse" + When I run "behat -fpretty --order=reverse --no-colors" Then it should pass with: """ Feature: Feature 2 From e755cc7a029ff3d1b091b5d04fe7f76eba2b900d Mon Sep 17 00:00:00 2001 From: Jakub Zalas Date: Mon, 29 Jan 2018 22:02:02 +0000 Subject: [PATCH 119/567] Simplify installation instructions At the time these instructions were written it might've been necessary to explain how to install composer. With composer becoming a de-facto standard package manager for PHP I think it's now better to assume it's installed, and refer to composer's installation docs. The installation method we have here is outdated (and insecure) anyway. --- README.md | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 22543cb51..9aeb64e57 100644 --- a/README.md +++ b/README.md @@ -14,8 +14,7 @@ Installing Behat The easiest way to install Behat is by using [Composer](https://getcomposer.org): ```bash -$> curl -sS https://getcomposer.org/installer | php -$> php composer.phar require behat/behat +$> composer require --dev behat/behat ``` After that you'll be able to run Behat via: @@ -30,8 +29,7 @@ Installing Development Version Clone the repository and install dependencies via [Composer](https://getcomposer.org): ```bash -$> curl -sS https://getcomposer.org/installer | php -$> php composer.phar install +$> composer install ``` After that you will be able to run development version of Behat via: From fbdaeb76ec4a82a91d6c8856262c3f7c77b8e385 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D0=BB=D0=B5=D0=BA=D1=81=D0=B5=D0=B9=20=D0=A7=D1=83?= =?UTF-8?q?=D0=BF=D1=80=D0=BE=D0=B2?= Date: Thu, 22 Feb 2018 16:32:58 +0300 Subject: [PATCH 120/567] Fix quoteless definition arguments matching with unicode characters --- CHANGELOG.md | 3 + features/definitions_transformations.feature | 74 +++++++++++++++++ features/definitions_translations.feature | 79 +++++++++++++++++++ .../Pattern/Policy/TurnipPatternPolicy.php | 2 +- 4 files changed, 157 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index c6e3fbf67..6e3453d91 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,9 @@ The format is based on [Keep a Changelog](http://keepachangelog.com/) and this project adheres to [Semantic Versioning](http://semver.org/). ## [Unreleased] +### Fixed + * [#1129](https://github.com/Behat/Behat/issues/1129): Fix quoteless + definition arguments matching with unicode characters ## [3.4.3] - 2017-11-27 ### Fixed diff --git a/features/definitions_transformations.feature b/features/definitions_transformations.feature index 92c4e6f25..3063d6a13 100644 --- a/features/definitions_transformations.feature +++ b/features/definitions_transformations.feature @@ -565,3 +565,77 @@ Feature: Step Arguments Transformations 1 scenario (1 passed) 4 steps (4 passed) """ + + Scenario: Unicode Named Arguments Transformations + Given a file named "features/step_arguments_unicode.feature" with: + """ + Feature: Step Arguments + Scenario: + Given I am боб + Then Username must be "боб" + + Scenario: + Given I am "элис" + Then Username must be "элис" + """ + When I run "behat -f progress --no-colors" + Then it should pass with: + """ + .... + + 2 scenarios (2 passed) + 4 steps (4 passed) + """ + + Scenario: Ordinal Arguments without quotes Transformations + Given a file named "features/bootstrap/FeatureContext.php" with: + """ + index = $index; + } + + /** @Then the index should be :value */ + public function theIndexShouldBe($value) { + PHPUnit\Framework\Assert::assertSame($value, $this->index); + } + } + """ + And a file named "features/ordinal_arguments.feature" with: + """ + Feature: Ordinal Step Arguments + Scenario: + Given I pick the 1st thing + Then the index should be "1" + Scenario: + Given I pick the "1st" thing + Then the index should be "1" + Scenario: + Given I pick the 27th thing + Then the index should be "27" + Scenario: + Given I pick the 5 thing + Then the index should be "5" + """ + When I run "behat -f progress --no-colors" + Then it should pass with: + """ + ........ + + 4 scenarios (4 passed) + 8 steps (8 passed) + """ diff --git a/features/definitions_translations.feature b/features/definitions_translations.feature index c3ace9d05..b5d17e862 100644 --- a/features/definitions_translations.feature +++ b/features/definitions_translations.feature @@ -359,3 +359,82 @@ Feature: Definitions translations 2 scenarios (2 passed) 10 steps (10 passed) """ + + Scenario: Translations with arguments without quotes + Given a file named "features/calc_ru_arguments.feature" with: + """ + # language: ru + Функция: Индексы + + Сценарий: + Допустим Я беру 14ую вещь + То индекс должен быть "14" + + Сценарий: + Допустим Я беру "2ю" вещь + То индекс должен быть "2" + + Сценарий: + Допустим Я беру 5 вещь + То индекс должен быть "5" + + Сценарий: + Допустим Я беру "10" вещь + То индекс должен быть "10" + """ + And a file named "features/bootstrap/FeatureContext.php" with: + """ + index = $index; + } + + /** @Then /^the index should be "([^"]*)"$/ */ + public function theIndexShouldBe($value) { + PHPUnit\Framework\Assert::assertSame($value, $this->index); + } + + public static function getTranslationResources() { + return array(__DIR__ . DIRECTORY_SEPARATOR . 'i18n' . DIRECTORY_SEPARATOR . 'ru.xliff'); + } + } + """ + And a file named "features/bootstrap/i18n/ru.xliff" with: + """ + + +
+ + + I pick the :index thing + я беру :index вещь + + + /^the index should be "([^"]*)"$/ + /^индекс должен быть "([^"]*)"$/ + + + + + """ + When I run "behat --no-colors -f progress features/calc_ru_arguments.feature" + Then it should pass with: + """ + ........ + + 4 scenarios (4 passed) + 8 steps (8 passed) + """ diff --git a/src/Behat/Behat/Definition/Pattern/Policy/TurnipPatternPolicy.php b/src/Behat/Behat/Definition/Pattern/Policy/TurnipPatternPolicy.php index c0732680f..0fbb8fc32 100644 --- a/src/Behat/Behat/Definition/Pattern/Policy/TurnipPatternPolicy.php +++ b/src/Behat/Behat/Definition/Pattern/Policy/TurnipPatternPolicy.php @@ -100,7 +100,7 @@ private function createTransformedRegex($pattern) $regex = $this->replaceTurnipOptionalEndingWithRegex($regex); $regex = $this->replaceTurnipAlternativeWordsWithRegex($regex); - return '/^' . $regex . '$/i'; + return '/^' . $regex . '$/iu'; } /** From 9c7447110ce50dcce1efacc61f745112bc8c463c Mon Sep 17 00:00:00 2001 From: Samuele Lilli Date: Mon, 19 Mar 2018 17:17:08 +0100 Subject: [PATCH 121/567] Update composer.json --- composer.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/composer.json b/composer.json index 187510289..7cc4af70d 100644 --- a/composer.json +++ b/composer.json @@ -50,7 +50,7 @@ "extra": { "branch-alias": { - "dev-master": "3.2.x-dev" + "dev-master": "3.4.x-dev" } }, From 0b342b1bb404ac3b082d8eb54cc9f7c57b7cdd27 Mon Sep 17 00:00:00 2001 From: John Eismeier Date: Tue, 3 Apr 2018 09:11:29 -0400 Subject: [PATCH 122/567] Propose fix two typos --- features/definitions_override.feature | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/features/definitions_override.feature b/features/definitions_override.feature index 464a63cd3..6ee2ebdf3 100644 --- a/features/definitions_override.feature +++ b/features/definitions_override.feature @@ -3,7 +3,7 @@ Feature: Step Definitions Override As a step definitions developer I need to be able to override definition methods - Scenario: Overriden method without own annotation will inherit parent pattern + Scenario: Overridden method without own annotation will inherit parent pattern Given a file named "features/bootstrap/FeatureContext.php" with: """ Date: Thu, 10 May 2018 09:26:34 +0100 Subject: [PATCH 123/567] Use the Symfony hosted version of PHP --- appveyor.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/appveyor.yml b/appveyor.yml index e81556764..46b951ef0 100644 --- a/appveyor.yml +++ b/appveyor.yml @@ -6,7 +6,7 @@ clone_folder: c:\projects\behat environment: matrix: - - PHP_DOWNLOAD_FILE: php-7.2.1-nts-Win32-VC15-x86.zip + - PHP_DOWNLOAD_FILE: php-7.1.3-Win32-VC14-x86.zip branches: only: @@ -28,7 +28,7 @@ init: install: - IF EXIST c:\php (SET PHP=0) ELSE (mkdir c:\php) - cd c:\php - - IF %PHP%==1 appveyor DownloadFile http://windows.php.net/downloads/releases/%PHP_DOWNLOAD_FILE% + - IF %PHP%==1 appveyor DownloadFile https://github.com/symfony/binary-utils/releases/download/v0.1/%PHP_DOWNLOAD_FILE% - IF %PHP%==1 7z x %PHP_DOWNLOAD_FILE% -y > 7z.log - IF %PHP%==1 echo @php %%~dp0composer.phar %%* > composer.bat - appveyor DownloadFile https://getcomposer.org/composer.phar From 6eff2378fdbdecfd6443d4d640d4d8530c7f79bf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Baptiste=20Clavi=C3=A9?= Date: Thu, 10 May 2018 18:20:12 +0200 Subject: [PATCH 124/567] Rework appveyor --- appveyor.yml | 53 ++++++++++++++++++++++++++++++++++------------------ 1 file changed, 35 insertions(+), 18 deletions(-) diff --git a/appveyor.yml b/appveyor.yml index 46b951ef0..58e8a4eba 100644 --- a/appveyor.yml +++ b/appveyor.yml @@ -6,7 +6,7 @@ clone_folder: c:\projects\behat environment: matrix: - - PHP_DOWNLOAD_FILE: php-7.1.3-Win32-VC14-x86.zip + - php: 7.2 branches: only: @@ -16,31 +16,48 @@ skip_commits: message: /\[ci skip\]/ cache: - - c:\php -> appveyor.yml + - C:\ProgramData\chocolatey\bin -> appveyor.yml + - C:\ProgramData\chocolatey\lib -> appveyor.yml + - C:\tools\php -> appveyor.yml + - C:\tools\composer -> appveyor.yml + - '%LOCALAPPDATA%\Composer\files' init: - - SET PATH=c:\php;%PATH% + - SET PATH=C:\Program Files\OpenSSL;c:\tools\php;C:\tools\composer;%PATH% - SET COMPOSER_NO_INTERACTION=1 - - SET PHP=1 - SET ANSICON=121x90 (121x90) - git config --global core.autocrlf input install: - - IF EXIST c:\php (SET PHP=0) ELSE (mkdir c:\php) - - cd c:\php - - IF %PHP%==1 appveyor DownloadFile https://github.com/symfony/binary-utils/releases/download/v0.1/%PHP_DOWNLOAD_FILE% - - IF %PHP%==1 7z x %PHP_DOWNLOAD_FILE% -y > 7z.log - - IF %PHP%==1 echo @php %%~dp0composer.phar %%* > composer.bat - - appveyor DownloadFile https://getcomposer.org/composer.phar - - copy php.ini-production php.ini /Y - - echo date.timezone="UTC" >> php.ini - - echo extension_dir=ext >> php.ini - - echo extension=php_openssl.dll >> php.ini - - echo extension=php_curl.dll >> php.ini - - echo extension=php_mbstring.dll >> php.ini - - echo extension=php_fileinfo.dll >> php.ini + - ps: | + if (!(Test-Path c:\tools\php)) { + appveyor-retry cinst --params '""/InstallDir:C:\tools\php""' --ignore-checksums -y php --version ((choco search php --exact --all-versions -r | select-string -pattern $env:php | sort { [version]($_ -split '\|' | select -last 1) } -Descending | Select-Object -first 1) -replace '[php|]','') + Get-ChildItem -Path c:\tools\php + cd c:\tools\php + + # Set PHP environment items that are always needed + copy php.ini-production php.ini + Add-Content php.ini "`n date.timezone=UTC" + Add-Content php.ini "`n extension_dir=ext" + Add-Content php.ini "`n extension=php_openssl.dll" + Add-Content php.ini "`n extension=php_curl.dll" + Add-Content php.ini "`n extension=php_mbstring.dll" + Add-Content php.ini "`n extension=php_fileinfo.dll" + + # download Composer + if (!(Test-Path C:\tools\composer)) { + New-Item -path c:\tools -name composer -itemtype directory + } + + if (!(Test-Path c:\tools\composer\composer.phar)) { + appveyor-retry appveyor DownloadFile https://getcomposer.org/composer.phar -Filename C:\tools\composer\composer.phar + Set-Content -path 'C:\tools\composer\composer.bat' -Value ('@php C:\tools\composer\composer.phar %*') + } + } + - cd c:\projects\behat - - composer install --no-progress --ansi + - appveyor-retry composer self-update + - appveyor-retry composer install --no-progress --ansi test_script: - cd c:\projects\behat From 4008e193cbcd766abab5b8437108197b26f66b95 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Baptiste=20Clavi=C3=A9?= Date: Thu, 10 May 2018 18:20:52 +0200 Subject: [PATCH 125/567] Test travis against php 7.2 --- .travis.yml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/.travis.yml b/.travis.yml index 0b0cc2102..ba30bbf04 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,6 +1,6 @@ language: php -php: [5.6, 7.0, 7.1] +php: [5.6, 7.0, 7.1, 7.2] sudo: false @@ -20,8 +20,8 @@ matrix: env: SYMFONY_VERSION='2.7.*' - php: 5.6 env: SYMFONY_VERSION='2.8.*' - - php: 7.1 - env: SYMFONY_VERSION='4.0.*@dev' + - php: 7.2 + env: SYMFONY_VERSION='^3.4' before_install: - phpenv config-rm xdebug.ini From 8fd30e8e7f4aa1c1bbacb3c29b2597ac6455e254 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gr=C3=A9goire=20Paris?= Date: Mon, 21 May 2018 19:08:46 +0200 Subject: [PATCH 126/567] Remove trailing whitespace --- src/Behat/Behat/Context/Cli/InteractiveContextIdentifier.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Behat/Behat/Context/Cli/InteractiveContextIdentifier.php b/src/Behat/Behat/Context/Cli/InteractiveContextIdentifier.php index c39488ae6..3d4607978 100644 --- a/src/Behat/Behat/Context/Cli/InteractiveContextIdentifier.php +++ b/src/Behat/Behat/Context/Cli/InteractiveContextIdentifier.php @@ -51,7 +51,7 @@ public function __construct(TranslatorInterface $translator, InputInterface $inp $this->input = $input; $this->output = $output; } - + /** * {@inheritdoc} */ From 7581001fb9426e763e4f018395ee33af8e70ce01 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gr=C3=A9goire=20Paris?= Date: Mon, 21 May 2018 19:06:58 +0200 Subject: [PATCH 127/567] Use a valid key as the default This is how the QuestionHelper API was intended to be used, but it only has been so since a recent bugfix. See https://github.com/symfony/symfony/pull/25521 Fixes #1151 --- composer.json | 2 +- src/Behat/Behat/Context/Cli/InteractiveContextIdentifier.php | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/composer.json b/composer.json index 187510289..2b2ecd56e 100644 --- a/composer.json +++ b/composer.json @@ -18,7 +18,7 @@ "ext-mbstring": "*", "behat/gherkin": "^4.5.1", "behat/transliterator": "^1.2", - "symfony/console": "~2.5||~3.0||~4.0", + "symfony/console": "~2.7.40||^2.8.33||~3.3.15||^3.4.3||^4.0.3", "symfony/config": "~2.3||~3.0||~4.0", "symfony/dependency-injection": "~2.1||~3.0||~4.0", "symfony/event-dispatcher": "~2.1||~3.0||~4.0", diff --git a/src/Behat/Behat/Context/Cli/InteractiveContextIdentifier.php b/src/Behat/Behat/Context/Cli/InteractiveContextIdentifier.php index 3d4607978..52a3eb934 100644 --- a/src/Behat/Behat/Context/Cli/InteractiveContextIdentifier.php +++ b/src/Behat/Behat/Context/Cli/InteractiveContextIdentifier.php @@ -70,7 +70,7 @@ public function guessTargetContextClass(ContextEnvironment $environment) $message = $this->translator->trans('snippet_context_choice', array('%1%' => $suiteName), 'output'); $choices = array_values(array_merge(array('None'), $contextClasses)); - $default = current($contextClasses); + $default = 1; $answer = $this->askQuestion('>> ' . $message, $choices, $default); From 016789cc28b2981be7880a07c6025be6c05adf8c Mon Sep 17 00:00:00 2001 From: everzet Date: Sat, 2 Jun 2018 12:25:31 +0100 Subject: [PATCH 128/567] Migrate to new scrutinizer https://scrutinizer-ci.com/docs/tools/php/php-analyzer/guides/migrate_to_new_php_analysis --- .scrutinizer.yml | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/.scrutinizer.yml b/.scrutinizer.yml index 43634ee11..04255e8ea 100644 --- a/.scrutinizer.yml +++ b/.scrutinizer.yml @@ -58,3 +58,10 @@ checks: no_exit: false no_unnecessary_final_modifier: false overriding_private_members: false + +build: + nodes: + analysis: + tests: + override: + - php-scrutinizer-run From 9c675380c13da71527c10c761c335765579332e2 Mon Sep 17 00:00:00 2001 From: everzet Date: Sat, 2 Jun 2018 12:46:25 +0100 Subject: [PATCH 129/567] Remove suggestions from composer.json [ci skip] --- composer.json | 6 ------ 1 file changed, 6 deletions(-) diff --git a/composer.json b/composer.json index ea7304652..523fd6bbd 100644 --- a/composer.json +++ b/composer.json @@ -35,12 +35,6 @@ "herrera-io/box": "~1.6.1" }, - "suggest": { - "behat/symfony2-extension": "for integration with Symfony2 web framework", - "behat/yii-extension": "for integration with Yii web framework", - "behat/mink-extension": "for integration with Mink testing framework" - }, - "autoload": { "psr-0": { "Behat\\Behat": "src/", From 8a993829942bddfb3c40680d7ded9a37eb8f925c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Baptiste=20Clavi=C3=A9?= Date: Thu, 10 May 2018 00:53:49 +0200 Subject: [PATCH 130/567] Do not call mb_strpos on non-string arguments --- src/Behat/Behat/HelperContainer/Argument/ServicesResolver.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Behat/Behat/HelperContainer/Argument/ServicesResolver.php b/src/Behat/Behat/HelperContainer/Argument/ServicesResolver.php index 9e16f32de..7e2191a0f 100644 --- a/src/Behat/Behat/HelperContainer/Argument/ServicesResolver.php +++ b/src/Behat/Behat/HelperContainer/Argument/ServicesResolver.php @@ -63,7 +63,7 @@ public function resolveArguments(ReflectionClass $classReflection, array $argume */ private function resolveArgument($value) { - if (0 === mb_strpos($value, '@')) { + if (is_string($value) && 0 === mb_strpos($value, '@')) { return $this->container->get(mb_substr($value, 1)); } From 27259f972ebeec7dae0f2a10347f6b9daec354d1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Baptiste=20Clavi=C3=A9?= Date: Thu, 10 May 2018 01:00:55 +0200 Subject: [PATCH 131/567] Add scenario for array arguments --- features/context.feature | 39 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) diff --git a/features/context.feature b/features/context.feature index eab92c3d9..684f23330 100644 --- a/features/context.feature +++ b/features/context.feature @@ -466,3 +466,42 @@ Feature: Context consistency 2 scenarios (2 passed) 2 steps (2 passed) """ + + Scenario: Array arguments + Given a file named "behat.yml" with: + """ + default: + suites: + default: + contexts: + - FirstContext: + - [foo, bar] + """ + And a file named "features/context-args-array.feature" with: + """ + Feature: + Scenario: + Given foo + """ + And a file named "features/bootstrap/FirstContext.php" with: + """ + foo = $foo; + } + + /** @Given foo */ + public function foo() { + PHPUnit\Framework\Assert::assertInternalType('array', $this->foo); + + PHPUnit\Framework\Assert::assertSame('foo', $this->foo[0]); + PHPUnit\Framework\Assert::assertSame('bar', $this->foo[1]); + } + } + """ + When I run "behat --no-colors -f progress features/context-args-array.feature" + Then it should pass From 9fb5a224ccc2caaccd5e28571b49765d6c2b61f6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Baptiste=20Clavi=C3=A9?= Date: Thu, 10 May 2018 01:16:45 +0200 Subject: [PATCH 132/567] Update CHANGELOG --- CHANGELOG.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index c6e3fbf67..5fd9442b8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,8 @@ The format is based on [Keep a Changelog](http://keepachangelog.com/) and this project adheres to [Semantic Versioning](http://semver.org/). ## [Unreleased] +### Fixed + * [#1144](https://github.com/Behat/Behat/pull/1144) : Allow to use arrays as context parameters ## [3.4.3] - 2017-11-27 ### Fixed From c332a7b04629eed464ffa4220384285e437fc249 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Baptiste=20Clavi=C3=A9?= Date: Mon, 25 Sep 2017 01:24:06 +0200 Subject: [PATCH 133/567] Check with array_key_exists for autowiring arguments isset() returns false for `null` value, so if we put a `null` value in the list arguments, it will be ignored and "something else" can be used instead. This is particularly bothersome if the type-hinted class does not exist, even though a `null` value has been specifically used. --- src/Behat/Behat/HelperContainer/ArgumentAutowirer.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Behat/Behat/HelperContainer/ArgumentAutowirer.php b/src/Behat/Behat/HelperContainer/ArgumentAutowirer.php index d4d514728..00dbbcded 100644 --- a/src/Behat/Behat/HelperContainer/ArgumentAutowirer.php +++ b/src/Behat/Behat/HelperContainer/ArgumentAutowirer.php @@ -72,6 +72,6 @@ public function autowireArguments(ReflectionFunctionAbstract $reflection, array */ private function isArgumentWireable(array $arguments, $index, ReflectionParameter $parameter) { - return !isset($arguments[$index]) && !isset($arguments[$parameter->getName()]) && $parameter->getClass(); + return !isset($arguments[$index]) && !isset($arguments[$parameter->getName()]) && !array_key_exists($index, $arguments) && !array_key_exists($parameter->getName(), $arguments) && $parameter->getClass(); } } From 6a48d28b06f3059f9a44e2f08f78c6955bb354bb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Baptiste=20Clavi=C3=A9?= Date: Mon, 25 Sep 2017 01:32:04 +0200 Subject: [PATCH 134/567] Make the condition more readable in ArgumentAutowirer --- .../Behat/HelperContainer/ArgumentAutowirer.php | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/src/Behat/Behat/HelperContainer/ArgumentAutowirer.php b/src/Behat/Behat/HelperContainer/ArgumentAutowirer.php index 00dbbcded..8771eabdc 100644 --- a/src/Behat/Behat/HelperContainer/ArgumentAutowirer.php +++ b/src/Behat/Behat/HelperContainer/ArgumentAutowirer.php @@ -14,6 +14,7 @@ use Psr\Container\ContainerInterface; use ReflectionFunctionAbstract; use ReflectionParameter; +use ReflectionException; /** * Automatically wires arguments of a given function from inside the container by using type-hitns. @@ -72,6 +73,18 @@ public function autowireArguments(ReflectionFunctionAbstract $reflection, array */ private function isArgumentWireable(array $arguments, $index, ReflectionParameter $parameter) { - return !isset($arguments[$index]) && !isset($arguments[$parameter->getName()]) && !array_key_exists($index, $arguments) && !array_key_exists($parameter->getName(), $arguments) && $parameter->getClass(); + if (isset($arguments[$index]) || array_key_exists($index, $arguments)) { + return false; + } + + if (isset($arguments[$parameter->getName()]) || array_key_exists($parameter->getName(), $arguments)) { + return false; + } + + try { + return (bool) $parameter->getClass(); + } catch (ReflectionException $e) { + return false; + } } } From e2fc74749352f57866881b0f51a7a05221b96764 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Baptiste=20Clavi=C3=A9?= Date: Mon, 25 Sep 2017 01:40:16 +0200 Subject: [PATCH 135/567] Add scenario for null arguments and autowire --- features/autowire.feature | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) diff --git a/features/autowire.feature b/features/autowire.feature index 86cff9a69..5e2be789a 100644 --- a/features/autowire.feature +++ b/features/autowire.feature @@ -106,6 +106,41 @@ Feature: Helper services autowire When I run "behat --no-colors -f progress features/autowire.feature" Then it should pass + Scenario: Null arguments should be skipped + Given a file named "behat.yaml" with: + """ + default: + suites: + default: + contexts: + - FeatureContext: + name: null + services: ServiceContainer + autowire: true + """ + And a file named "features/autowire.feature" with: + """ + Feature: + Scenario: + Given a step + """ + And a file named "features/bootstrap/FeatureContext.php" with: + """ + Date: Mon, 25 Sep 2017 11:42:49 +0200 Subject: [PATCH 136/567] If ->getClass() is not available, ignore it --- src/Behat/Testwork/Argument/MixedArgumentOrganiser.php | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/src/Behat/Testwork/Argument/MixedArgumentOrganiser.php b/src/Behat/Testwork/Argument/MixedArgumentOrganiser.php index 533214836..c845f03d4 100644 --- a/src/Behat/Testwork/Argument/MixedArgumentOrganiser.php +++ b/src/Behat/Testwork/Argument/MixedArgumentOrganiser.php @@ -13,6 +13,7 @@ use ReflectionFunctionAbstract; use ReflectionClass; use ReflectionParameter; +use ReflectionException; /** * Organises function arguments using its reflection. @@ -225,7 +226,11 @@ private function filterApplicableTypehintedParameters(array $parameters) continue; } - $reflectionClass = $parameter->getClass(); + try { + $reflectionClass = $parameter->getClass(); + } catch (ReflectionException $e) { + continue; + } if (!$reflectionClass) { continue; From 80e734055295b2b4c7503d662c6ec349fbecac58 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Baptiste=20Clavi=C3=A9?= Date: Thu, 10 May 2018 01:19:07 +0200 Subject: [PATCH 137/567] Update CHANGELOG --- CHANGELOG.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index c6e3fbf67..5ea490ffe 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,9 @@ The format is based on [Keep a Changelog](http://keepachangelog.com/) and this project adheres to [Semantic Versioning](http://semver.org/). ## [Unreleased] +### Fixed + * [#1081](https://github.com/Behat/Behat/pull/1081): Do not use isset to be + able to check for intentional `null` values when autowiring contexts ## [3.4.3] - 2017-11-27 ### Fixed From 8ba1ea4c5c3f7d5a39408c4807e590a153846ffc Mon Sep 17 00:00:00 2001 From: Julien Deniau Date: Tue, 29 May 2018 14:17:31 +0200 Subject: [PATCH 138/567] add local cache for transformPatternToRegex --- .../Definition/Pattern/PatternTransformer.php | 14 +++- .../Pattern/PatternTransformerTest.php | 68 +++++++++++++++++++ 2 files changed, 79 insertions(+), 3 deletions(-) create mode 100644 tests/Behat/Tests/Definition/Pattern/PatternTransformerTest.php diff --git a/src/Behat/Behat/Definition/Pattern/PatternTransformer.php b/src/Behat/Behat/Definition/Pattern/PatternTransformer.php index 6af5bacd6..d632e2567 100644 --- a/src/Behat/Behat/Definition/Pattern/PatternTransformer.php +++ b/src/Behat/Behat/Definition/Pattern/PatternTransformer.php @@ -26,6 +26,8 @@ final class PatternTransformer */ private $policies = array(); + private $patternToRegexpCache = array(); + /** * Registers pattern policy. * @@ -34,6 +36,7 @@ final class PatternTransformer public function registerPatternPolicy(PatternPolicy $policy) { $this->policies[] = $policy; + $this->patternToRegexpCache = array(); } /** @@ -68,11 +71,16 @@ public function generatePattern($type, $stepText) */ public function transformPatternToRegex($pattern) { - foreach ($this->policies as $policy) { - if ($policy->supportsPattern($pattern)) { - return $policy->transformPatternToRegex($pattern); + if (!isset($this->patternToRegexpCache[$pattern])) { + foreach ($this->policies as $policy) { + if ($policy->supportsPattern($pattern)) { + $this->patternToRegexpCache[$pattern] = $policy->transformPatternToRegex($pattern); + break; + } } } + return $this->patternToRegexpCache[$pattern]; + throw new UnknownPatternException(sprintf('Can not find policy for a pattern `%s`.', $pattern), $pattern); } diff --git a/tests/Behat/Tests/Definition/Pattern/PatternTransformerTest.php b/tests/Behat/Tests/Definition/Pattern/PatternTransformerTest.php new file mode 100644 index 000000000..015eeeb70 --- /dev/null +++ b/tests/Behat/Tests/Definition/Pattern/PatternTransformerTest.php @@ -0,0 +1,68 @@ + + */ +class PatternTransformerTest extends TestCase +{ + public function testTransformPatternToRegexCache() + { + $observer = $this->prophesize(PatternPolicy::class); + // first pattern + $observer->supportsPattern('hello world')->willReturn(true); + $observer->transformPatternToRegex('hello world') + ->shouldBeCalledTimes(1) + ->willReturn('/hello world/'); + + // second pattern + $observer->supportsPattern('hi world')->willReturn(true); + $observer->transformPatternToRegex('hi world') + ->shouldBeCalledTimes(1) + ->willReturn('/hi world/'); + + $testedInstance = new PatternTransformer(); + $testedInstance->registerPatternPolicy($observer->reveal()); + $regex = $testedInstance->transformPatternToRegex('hello world'); + $regex2 = $testedInstance->transformPatternToRegex('hello world'); + + $regex3 = $testedInstance->transformPatternToRegex('hi world'); + + $this->assertEquals('/hello world/', $regex); + $this->assertEquals('/hello world/', $regex2); + $this->assertEquals('/hi world/', $regex3); + } + + public function testTransformPatternToRegexCacheAndRegisterNewPolicy() + { + // first pattern + $policy1Prophecy = $this->prophesize(PatternPolicy::class); + $policy1Prophecy->supportsPattern('hello world')->willReturn(true); + $policy1Prophecy->transformPatternToRegex('hello world') + ->shouldBeCalledTimes(2) + ->willReturn('/hello world/'); + + // second pattern + $policy2Prophecy = $this->prophesize(PatternPolicy::class); + $policy1Prophecy->supportsPattern()->shouldNotBeCalled(); + $policy1Prophecy->transformPatternToRegex()->shouldNotBeCalled(); + + $testedInstance = new PatternTransformer(); + $testedInstance->registerPatternPolicy($policy1Prophecy->reveal()); + $regex = $testedInstance->transformPatternToRegex('hello world'); + $regex2 = $testedInstance->transformPatternToRegex('hello world'); + + $testedInstance->registerPatternPolicy($policy2Prophecy->reveal()); + $regex3 = $testedInstance->transformPatternToRegex('hello world'); + + $this->assertEquals('/hello world/', $regex); + $this->assertEquals('/hello world/', $regex2); + $this->assertEquals('/hello world/', $regex3); + } +} From b04cc572ebf6058fdbe69d5add8b60892fc013ce Mon Sep 17 00:00:00 2001 From: Julien Deniau Date: Tue, 29 May 2018 15:49:11 +0200 Subject: [PATCH 139/567] add test to check that transformPatternToRegex throw an exception if no match is found --- .../Definition/Pattern/PatternTransformer.php | 6 ++++-- .../Pattern/PatternTransformerTest.php | 18 ++++++++++++++++++ 2 files changed, 22 insertions(+), 2 deletions(-) diff --git a/src/Behat/Behat/Definition/Pattern/PatternTransformer.php b/src/Behat/Behat/Definition/Pattern/PatternTransformer.php index d632e2567..3d4787b26 100644 --- a/src/Behat/Behat/Definition/Pattern/PatternTransformer.php +++ b/src/Behat/Behat/Definition/Pattern/PatternTransformer.php @@ -79,9 +79,11 @@ public function transformPatternToRegex($pattern) } } } - return $this->patternToRegexpCache[$pattern]; + if (!isset($this->patternToRegexpCache[$pattern])) { + throw new UnknownPatternException(sprintf('Can not find policy for a pattern `%s`.', $pattern), $pattern); + } - throw new UnknownPatternException(sprintf('Can not find policy for a pattern `%s`.', $pattern), $pattern); + return $this->patternToRegexpCache[$pattern]; } } diff --git a/tests/Behat/Tests/Definition/Pattern/PatternTransformerTest.php b/tests/Behat/Tests/Definition/Pattern/PatternTransformerTest.php index 015eeeb70..44aca4825 100644 --- a/tests/Behat/Tests/Definition/Pattern/PatternTransformerTest.php +++ b/tests/Behat/Tests/Definition/Pattern/PatternTransformerTest.php @@ -65,4 +65,22 @@ public function testTransformPatternToRegexCacheAndRegisterNewPolicy() $this->assertEquals('/hello world/', $regex2); $this->assertEquals('/hello world/', $regex3); } + + /** + * @expectedException \Behat\Behat\Definition\Exception\UnknownPatternException + * @expectedExceptionMessage Can not find policy for a pattern `hello world`. + */ + public function testTransformPatternToRegexNoMatch() + { + // first pattern + $policy1Prophecy = $this->prophesize(PatternPolicy::class); + $policy1Prophecy->supportsPattern('hello world')->willReturn(false); + $policy1Prophecy->transformPatternToRegex('hello world') + ->shouldNotBeCalled(); + + + $testedInstance = new PatternTransformer(); + $testedInstance->registerPatternPolicy($policy1Prophecy->reveal()); + $regex = $testedInstance->transformPatternToRegex('hello world'); + } } From 615459bfb7f759fc212ea86a16f35e2f9d3029df Mon Sep 17 00:00:00 2001 From: Julien Deniau Date: Wed, 30 May 2018 14:05:19 +0200 Subject: [PATCH 140/567] simplify public method --- .../Definition/Pattern/PatternTransformer.php | 20 ++++++++++--------- 1 file changed, 11 insertions(+), 9 deletions(-) diff --git a/src/Behat/Behat/Definition/Pattern/PatternTransformer.php b/src/Behat/Behat/Definition/Pattern/PatternTransformer.php index 3d4787b26..204cbd80e 100644 --- a/src/Behat/Behat/Definition/Pattern/PatternTransformer.php +++ b/src/Behat/Behat/Definition/Pattern/PatternTransformer.php @@ -72,18 +72,20 @@ public function generatePattern($type, $stepText) public function transformPatternToRegex($pattern) { if (!isset($this->patternToRegexpCache[$pattern])) { - foreach ($this->policies as $policy) { - if ($policy->supportsPattern($pattern)) { - $this->patternToRegexpCache[$pattern] = $policy->transformPatternToRegex($pattern); - break; - } - } + $this->patternToRegexpCache[$pattern] = $this->transformPatternToRegexWithSupportedPolicy($pattern); } - if (!isset($this->patternToRegexpCache[$pattern])) { - throw new UnknownPatternException(sprintf('Can not find policy for a pattern `%s`.', $pattern), $pattern); + return $this->patternToRegexpCache[$pattern]; + } + + private function transformPatternToRegexWithSupportedPolicy($pattern) + { + foreach ($this->policies as $policy) { + if ($policy->supportsPattern($pattern)) { + return $policy->transformPatternToRegex($pattern); + } } - return $this->patternToRegexpCache[$pattern]; + throw new UnknownPatternException(sprintf('Can not find policy for a pattern `%s`.', $pattern), $pattern); } } From a95d38a5ddfc859fbd99388393acc7dea832f271 Mon Sep 17 00:00:00 2001 From: Julien Deniau Date: Mon, 4 Jun 2018 09:41:53 +0200 Subject: [PATCH 141/567] add typehint --- .../Behat/Definition/Pattern/PatternTransformer.php | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/src/Behat/Behat/Definition/Pattern/PatternTransformer.php b/src/Behat/Behat/Definition/Pattern/PatternTransformer.php index 204cbd80e..adda52b66 100644 --- a/src/Behat/Behat/Definition/Pattern/PatternTransformer.php +++ b/src/Behat/Behat/Definition/Pattern/PatternTransformer.php @@ -26,6 +26,9 @@ final class PatternTransformer */ private $policies = array(); + /** + * @var string[] + */ private $patternToRegexpCache = array(); /** @@ -78,6 +81,13 @@ public function transformPatternToRegex($pattern) return $this->patternToRegexpCache[$pattern]; } + /** + * @param string $pattern + * + * @return string + * + * @throws UnknownPatternException + */ private function transformPatternToRegexWithSupportedPolicy($pattern) { foreach ($this->policies as $policy) { From be0d6196b24bd3920269b5d052decb5d9d7d4d3e Mon Sep 17 00:00:00 2001 From: Jakub Zalas Date: Tue, 3 Jul 2018 11:58:42 +0100 Subject: [PATCH 142/567] Register cli input/output services as synthetic --- src/Behat/Testwork/Cli/ServiceContainer/CliExtension.php | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/src/Behat/Testwork/Cli/ServiceContainer/CliExtension.php b/src/Behat/Testwork/Cli/ServiceContainer/CliExtension.php index 497993cef..352b2d6a6 100644 --- a/src/Behat/Testwork/Cli/ServiceContainer/CliExtension.php +++ b/src/Behat/Testwork/Cli/ServiceContainer/CliExtension.php @@ -81,6 +81,7 @@ public function configure(ArrayNodeDefinition $builder) public function load(ContainerBuilder $container, array $config) { $this->loadCommand($container); + $this->loadSyntheticServices($container); } /** @@ -103,6 +104,12 @@ protected function loadCommand(ContainerBuilder $container) $container->setDefinition(self::COMMAND_ID, $definition); } + protected function loadSyntheticServices(ContainerBuilder $container) + { + $container->register(self::INPUT_ID)->setSynthetic(true)->setPublic(true); + $container->register(self::OUTPUT_ID)->setSynthetic(true)->setPublic(true); + } + /** * Processes all controllers in container. * From 8f9c9d9a4dc857bc3d7437bd4ea27d3e2b2297d7 Mon Sep 17 00:00:00 2001 From: Phil Weir Date: Thu, 12 Jul 2018 16:31:28 +0100 Subject: [PATCH 143/567] Allow for new-style Symfony serialization Fixes #1108 by changing the argument to the HelperContainerExtension to be a Symfony DI Reference to the service container rather than the instantiated service container itself. --- .../ServiceContainer/HelperContainerExtension.php | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/Behat/Behat/HelperContainer/ServiceContainer/HelperContainerExtension.php b/src/Behat/Behat/HelperContainer/ServiceContainer/HelperContainerExtension.php index 1d5100f5c..ab9c3cb53 100644 --- a/src/Behat/Behat/HelperContainer/ServiceContainer/HelperContainerExtension.php +++ b/src/Behat/Behat/HelperContainer/ServiceContainer/HelperContainerExtension.php @@ -19,6 +19,7 @@ use Symfony\Component\Config\Definition\Builder\ArrayNodeDefinition; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Definition; +use Symfony\Component\DependencyInjection\Reference; /** * Behat helper container extension. @@ -76,7 +77,9 @@ public function configure(ArrayNodeDefinition $builder) */ public function load(ContainerBuilder $container, array $config) { - $definition = new Definition('Behat\Behat\HelperContainer\Argument\ServicesResolverFactory', array($container)); + $definition = new Definition('Behat\Behat\HelperContainer\Argument\ServicesResolverFactory', array( + new Reference('service_container') + )); $definition->addTag(ContextExtension::SUITE_SCOPED_RESOLVER_FACTORY_TAG, array('priority' => 0)); $container->setDefinition(ContextExtension::SUITE_SCOPED_RESOLVER_FACTORY_TAG . '.helper_container', $definition); From 6169bb41593290ce549f34bd3156c6396c553aa9 Mon Sep 17 00:00:00 2001 From: Phil Weir Date: Thu, 12 Jul 2018 19:02:21 +0100 Subject: [PATCH 144/567] update CHANGELOG to note serialization fix --- CHANGELOG.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index c6e3fbf67..fe14c339f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,8 @@ The format is based on [Keep a Changelog](http://keepachangelog.com/) and this project adheres to [Semantic Versioning](http://semver.org/). ## [Unreleased] +### Fixed + * Serializable definitions for Symfony 4.x ## [3.4.3] - 2017-11-27 ### Fixed From 29df00633392c6bfca5f8319a4f0c8af36dd9350 Mon Sep 17 00:00:00 2001 From: Ciaran McNulty Date: Mon, 6 Aug 2018 17:38:49 +0100 Subject: [PATCH 145/567] Updated changelog --- CHANGELOG.md | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index fb97927d8..1fd71d465 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,9 +6,16 @@ and this project adheres to [Semantic Versioning](http://semver.org/). ## [Unreleased] ### Added - * [#1144](https://github.com/Behat/Behat/pull/1144) : Support for arrays as context parameters + * [#1144](https://github.com/Behat/Behat/pull/1144) : Allow to use arrays as context parameters + +### Changed + * [#1153](https://github.com/Behat/Behat/pull/1153) : Cache pattern to regex transformations + * [#1155](https://github.com/Behat/Behat/pull/1155) : Remove composer suggestions + ### Fixed - * Serializable definitions for Symfony 4.x + * Custom container must be public for symfony 4 + * [#1160](https://github.com/Behat/Behat/pull/1160) : Register CLI services as synthetic + * [#1163](https://github.com/Behat/Behat/pull/1163) : Allow for new-style symfony serialisation ## [3.4.3] - 2017-11-27 ### Fixed From 74aa665d3201a012eb7267b2bf672eafa35b5f75 Mon Sep 17 00:00:00 2001 From: Ciaran McNulty Date: Mon, 6 Aug 2018 19:38:14 +0100 Subject: [PATCH 146/567] 3.5.0 release prep --- composer.json | 2 +- src/Behat/Behat/ApplicationFactory.php | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/composer.json b/composer.json index 523fd6bbd..4a6cbb70f 100644 --- a/composer.json +++ b/composer.json @@ -44,7 +44,7 @@ "extra": { "branch-alias": { - "dev-master": "3.4.x-dev" + "dev-master": "3.5.x-dev" } }, diff --git a/src/Behat/Behat/ApplicationFactory.php b/src/Behat/Behat/ApplicationFactory.php index 261094881..d9838a1fb 100644 --- a/src/Behat/Behat/ApplicationFactory.php +++ b/src/Behat/Behat/ApplicationFactory.php @@ -46,7 +46,7 @@ */ final class ApplicationFactory extends BaseFactory { - const VERSION = '3.4-dev'; + const VERSION = '3.5.0'; /** * {@inheritdoc} From 1c93c1411a6ce4967af88b91cb180c76e82d6761 Mon Sep 17 00:00:00 2001 From: Konstantin Kudryashov Date: Fri, 10 Aug 2018 19:56:03 +0100 Subject: [PATCH 147/567] Link 3.5.0 changeset --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 3679ee294..ac30094ae 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -885,7 +885,7 @@ and this project adheres to [Semantic Versioning](http://semver.org/). ### Changed * Initial release -[Unreleased]: https://github.com/Behat/Behat/compare/v3.4.3...HEAD +[3.5.0]: https://github.com/Behat/Behat/compare/v3.4.3...v3.5.0 [3.4.3]: https://github.com/Behat/Behat/compare/v3.4.2...v3.4.3 [3.4.2]: https://github.com/Behat/Behat/compare/v3.4.1...v3.4.2 [3.4.1]: https://github.com/Behat/Behat/compare/v3.4.0...v3.4.1 From e4bce688be0c2029dc1700e46058d86428c63cab Mon Sep 17 00:00:00 2001 From: Konstantin Kudryashov Date: Fri, 10 Aug 2018 19:56:51 +0100 Subject: [PATCH 148/567] Change the date of release --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ac30094ae..54acf1e1e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,7 +4,7 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](http://keepachangelog.com/) and this project adheres to [Semantic Versioning](http://semver.org/). -## [3.5.0] - 2018-08-06 +## [3.5.0] - 2018-08-10 ### Added * [#1144](https://github.com/Behat/Behat/pull/1144): Allow to use arrays as context parameters * [#1081](https://github.com/Behat/Behat/pull/1081): Allow passing null as a named context parameter From a2fb304fce186292f11b16f5fc186e5cc456dbd6 Mon Sep 17 00:00:00 2001 From: Konstantin Kudryashov Date: Fri, 10 Aug 2018 19:58:42 +0100 Subject: [PATCH 149/567] Add unreleased section back --- CHANGELOG.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 54acf1e1e..b758751ab 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,8 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](http://keepachangelog.com/) and this project adheres to [Semantic Versioning](http://semver.org/). +## [Unreleased] + ## [3.5.0] - 2018-08-10 ### Added * [#1144](https://github.com/Behat/Behat/pull/1144): Allow to use arrays as context parameters @@ -885,6 +887,7 @@ and this project adheres to [Semantic Versioning](http://semver.org/). ### Changed * Initial release +[Unreleased]: https://github.com/Behat/Behat/compare/v3.5.0...master [3.5.0]: https://github.com/Behat/Behat/compare/v3.4.3...v3.5.0 [3.4.3]: https://github.com/Behat/Behat/compare/v3.4.2...v3.4.3 [3.4.2]: https://github.com/Behat/Behat/compare/v3.4.1...v3.4.2 From a5a6745c378fbe1049714a9508be620ec171b7c8 Mon Sep 17 00:00:00 2001 From: Felds Liscia Date: Tue, 28 Aug 2018 16:24:46 -0300 Subject: [PATCH 150/567] replace symfony class loader with composer --- .../Behat/Context/Suite/Setup/SuiteWithContextsSetup.php | 2 +- .../Testwork/Autoloader/Cli/AutoloaderController.php | 2 +- .../Autoloader/ServiceContainer/AutoloaderExtension.php | 8 ++++++-- 3 files changed, 8 insertions(+), 4 deletions(-) diff --git a/src/Behat/Behat/Context/Suite/Setup/SuiteWithContextsSetup.php b/src/Behat/Behat/Context/Suite/Setup/SuiteWithContextsSetup.php index 0bc41db7a..9fc219d3a 100644 --- a/src/Behat/Behat/Context/Suite/Setup/SuiteWithContextsSetup.php +++ b/src/Behat/Behat/Context/Suite/Setup/SuiteWithContextsSetup.php @@ -16,7 +16,7 @@ use Behat\Testwork\Suite\Exception\SuiteConfigurationException; use Behat\Testwork\Suite\Setup\SuiteSetup; use Behat\Testwork\Suite\Suite; -use Symfony\Component\ClassLoader\ClassLoader; +use Composer\Autoload\ClassLoader; /** * Generates classes for all contexts in the suite using autoloader. diff --git a/src/Behat/Testwork/Autoloader/Cli/AutoloaderController.php b/src/Behat/Testwork/Autoloader/Cli/AutoloaderController.php index 991eb412c..70ebe94af 100644 --- a/src/Behat/Testwork/Autoloader/Cli/AutoloaderController.php +++ b/src/Behat/Testwork/Autoloader/Cli/AutoloaderController.php @@ -11,7 +11,7 @@ namespace Behat\Testwork\Autoloader\Cli; use Behat\Testwork\Cli\Controller; -use Symfony\Component\ClassLoader\ClassLoader; +use Composer\Autoload\ClassLoader; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; diff --git a/src/Behat/Testwork/Autoloader/ServiceContainer/AutoloaderExtension.php b/src/Behat/Testwork/Autoloader/ServiceContainer/AutoloaderExtension.php index 2c5f021cd..476601345 100644 --- a/src/Behat/Testwork/Autoloader/ServiceContainer/AutoloaderExtension.php +++ b/src/Behat/Testwork/Autoloader/ServiceContainer/AutoloaderExtension.php @@ -108,7 +108,7 @@ public function process(ContainerBuilder $container) */ private function loadAutoloader(ContainerBuilder $container) { - $definition = new Definition('Symfony\Component\ClassLoader\ClassLoader'); + $definition = new Definition('Composer\Autoload\ClassLoader'); $container->setDefinition(self::CLASS_LOADER_ID, $definition); } @@ -146,6 +146,10 @@ private function setLoaderPrefixes(ContainerBuilder $container, array $prefixes) private function processLoaderPrefixes(ContainerBuilder $container) { $loaderDefinition = $container->getDefinition(self::CLASS_LOADER_ID); - $loaderDefinition->addMethodCall('addPrefixes', array($container->getParameter('class_loader.prefixes'))); + $prefixes = $container->getParameter('class_loader.prefixes'); + + foreach ($prefixes as $prefix => $path) { + $loaderDefinition->addMethodCall('addPsr4', array($prefix, $path)); + } } } From afa775441bde81fed047e8ce766f992c2bf3068f Mon Sep 17 00:00:00 2001 From: Felds Liscia Date: Tue, 28 Aug 2018 19:12:58 -0300 Subject: [PATCH 151/567] add prefixes as PSR0 --- .../Autoloader/ServiceContainer/AutoloaderExtension.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Behat/Testwork/Autoloader/ServiceContainer/AutoloaderExtension.php b/src/Behat/Testwork/Autoloader/ServiceContainer/AutoloaderExtension.php index 476601345..40f0fa226 100644 --- a/src/Behat/Testwork/Autoloader/ServiceContainer/AutoloaderExtension.php +++ b/src/Behat/Testwork/Autoloader/ServiceContainer/AutoloaderExtension.php @@ -149,7 +149,7 @@ private function processLoaderPrefixes(ContainerBuilder $container) $prefixes = $container->getParameter('class_loader.prefixes'); foreach ($prefixes as $prefix => $path) { - $loaderDefinition->addMethodCall('addPsr4', array($prefix, $path)); + $loaderDefinition->addMethodCall('add', array($prefix, $path)); } } } From fc001f9269e20ae4007bb90532a6a727ceb2002a Mon Sep 17 00:00:00 2001 From: Felds Liscia Date: Wed, 29 Aug 2018 11:47:05 -0300 Subject: [PATCH 152/567] remove symfony/class-loader dependency --- composer.json | 1 - 1 file changed, 1 deletion(-) diff --git a/composer.json b/composer.json index 4a6cbb70f..dfb31dc41 100644 --- a/composer.json +++ b/composer.json @@ -24,7 +24,6 @@ "symfony/event-dispatcher": "~2.1||~3.0||~4.0", "symfony/translation": "~2.3||~3.0||~4.0", "symfony/yaml": "~2.1||~3.0||~4.0", - "symfony/class-loader": "~2.1||~3.0", "psr/container": "^1.0", "container-interop/container-interop": "^1.2" }, From 317631d7475bbbd0e4e3bd6da741de5a1d588b7c Mon Sep 17 00:00:00 2001 From: Samuel NELA Date: Tue, 28 Aug 2018 14:44:34 +0200 Subject: [PATCH 153/567] Change specification for autoloading classes --- composer.json | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/composer.json b/composer.json index dfb31dc41..ef899943e 100644 --- a/composer.json +++ b/composer.json @@ -35,12 +35,18 @@ }, "autoload": { - "psr-0": { - "Behat\\Behat": "src/", - "Behat\\Testwork": "src/" + "psr-4": { + "Behat\\Behat\\": "src/Behat/Behat/", + "Behat\\Testwork\\": "src/Behat/Testwork/" } }, - + + "autoload-dev": { + "psr-4": { + "Behat\\Tests\\": "tests/" + } + }, + "extra": { "branch-alias": { "dev-master": "3.5.x-dev" From 28ffdf9ba878a986dbef4461c3b0d8282e6fa5e0 Mon Sep 17 00:00:00 2001 From: getsolaris Date: Sun, 23 Dec 2018 20:56:40 +0900 Subject: [PATCH 154/567] Added kor lang --- i18n.php | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/i18n.php b/i18n.php index 44eda3c91..19aeabd81 100644 --- a/i18n.php +++ b/i18n.php @@ -214,4 +214,20 @@ 'undefined_count' => '{1,21,31} %1% не определен|]1,Inf] %1% не определено', 'skipped_count' => '{1,21,31} %1% пропущен|]1,Inf] %1% пропущено', ), + 'ko' => array( + 'snippet_proposal_title' => '%1% 정의가 되지 않았습니다. 스니펫을 생성할 컨텍스트를 선택하십시오:', + 'snippet_missing_title' => '%1% 단계가 누락되었습니다. 스니펫을 정의해주세요:', + 'skipped_scenarios_title' => '건너뛴 시나리오:', + 'failed_scenarios_title' => '실패한 시나리오:', + 'failed_hooks_title' => '실패한 훅 연결:', + 'failed_steps_title' => '실패한 단계:', + 'pending_steps_title' => '준비중인 단계:', + 'scenarios_count' => '{0} 없는 시나리오들|{1} 1 시나리오|]1,Inf] %1% 시나리오들', + 'steps_count' => '{0} 없는 단계들|{1} 1 단계|]1,Inf] %1% 단계들', + 'passed_count' => '[1,Inf] %1% 통과', + 'failed_count' => '[1,Inf] %1% 실패', + 'pending_count' => '[1,Inf] %1% 준비중', + 'undefined_count' => '[1,Inf] %1% 정의되지 않았습니다.', + 'skipped_count' => '[1,Inf] %1% 건너뜀', + ), ); From ea2b9fdb7513ac6194d9cacfbccd70594f4f1335 Mon Sep 17 00:00:00 2001 From: Tibor Kotosz Date: Thu, 7 Mar 2019 08:47:11 +0100 Subject: [PATCH 155/567] Update composer package description --- composer.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/composer.json b/composer.json index ef899943e..9376aa798 100644 --- a/composer.json +++ b/composer.json @@ -1,6 +1,6 @@ { "name": "behat/behat", - "description": "Scenario-oriented BDD framework for PHP 5.3", + "description": "Scenario-oriented BDD framework for PHP", "keywords": ["BDD", "ScenarioBDD", "StoryBDD", "Examples", "Scrum", "Agile", "User story", "Symfony", "business", "development", "testing", "documentation"], "homepage": "http://behat.org/", "type": "library", From db965afb25125d9aa05fb90d6afbcde1ad9cb43a Mon Sep 17 00:00:00 2001 From: Witold Wasiczko Date: Mon, 24 Jun 2019 13:56:26 +0200 Subject: [PATCH 156/567] PHP 7.3 support --- .travis.yml | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index ba30bbf04..d38706a38 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,6 +1,6 @@ language: php -php: [5.6, 7.0, 7.1, 7.2] +php: [5.6, 7.0, 7.1, 7.2, 7.3] sudo: false @@ -22,6 +22,8 @@ matrix: env: SYMFONY_VERSION='2.8.*' - php: 7.2 env: SYMFONY_VERSION='^3.4' + - php: 7.3 + env: SYMFONY_VERSION='^3.4' before_install: - phpenv config-rm xdebug.ini From 137a7efdc1ce6254fe005c27925a7f1cd79e3372 Mon Sep 17 00:00:00 2001 From: Witold Wasiczko Date: Wed, 26 Jun 2019 23:37:13 +0200 Subject: [PATCH 157/567] Test symfony 4.2 --- .travis.yml | 2 ++ 1 file changed, 2 insertions(+) diff --git a/.travis.yml b/.travis.yml index d38706a38..65d848211 100644 --- a/.travis.yml +++ b/.travis.yml @@ -24,6 +24,8 @@ matrix: env: SYMFONY_VERSION='^3.4' - php: 7.3 env: SYMFONY_VERSION='^3.4' + - php: 7.3 + env: SYMFONY_VERSION='^4.2' before_install: - phpenv config-rm xdebug.ini From dae534f705bcd58f5382949d0fe15f90db2be5ce Mon Sep 17 00:00:00 2001 From: Jakub Zalas Date: Sun, 11 Aug 2019 09:31:17 +0000 Subject: [PATCH 158/567] Fix tests with the latest version of gherkin --- composer.json | 2 +- features/syntax_help.feature | 20 ++++++++++---------- 2 files changed, 11 insertions(+), 11 deletions(-) diff --git a/composer.json b/composer.json index ef899943e..43ea18de5 100644 --- a/composer.json +++ b/composer.json @@ -16,7 +16,7 @@ "require": { "php": ">=5.3.3", "ext-mbstring": "*", - "behat/gherkin": "^4.5.1", + "behat/gherkin": "^4.6.0", "behat/transliterator": "^1.2", "symfony/console": "~2.7.40||^2.8.33||~3.3.15||^3.4.3||^4.0.3", "symfony/config": "~2.3||~3.0||~4.0", diff --git a/features/syntax_help.feature b/features/syntax_help.feature index caf9d8006..d0027901e 100644 --- a/features/syntax_help.feature +++ b/features/syntax_help.feature @@ -20,7 +20,7 @@ Feature: Syntax helpers [Given|*] there is agent A [And|*] there is agent B - Scenario: Erasing agent memory + [Scenario|Example]: Erasing agent memory [Given|*] there is agent J [And|*] there is agent K [When|*] I erase agent K's memory @@ -54,22 +54,22 @@ Feature: Syntax helpers We need to be able to erase past agents' memory [Предыстория|Контекст]: - [Допустим|Пусть|Дано|Если|*] there is agent A + [Допустим|Пусть|Дано|*] there is agent A [К тому же|Также|*|И] there is agent B - Сценарий: Erasing agent memory - [Допустим|Пусть|Дано|Если|*] there is agent J + [Сценарий|Пример]: Erasing agent memory + [Допустим|Пусть|Дано|*] there is agent J [К тому же|Также|*|И] there is agent K - [Когда|*] I erase agent K's memory + [Когда|Если|*] I erase agent K's memory [Затем|Тогда|То|*] there should be agent J - [Но|*|А] there should not be agent K + [Иначе|Но|*|А] there should not be agent K Структура сценария: Erasing other agents' memory - [Допустим|Пусть|Дано|Если|*] there is agent + [Допустим|Пусть|Дано|*] there is agent [К тому же|Также|*|И] there is agent - [Когда|*] I erase agent 's memory + [Когда|Если|*] I erase agent 's memory [Затем|Тогда|То|*] there should be agent - [Но|*|А] there should not be agent + [Иначе|Но|*|А] there should not be agent Примеры: | agent1 | agent2 | @@ -399,6 +399,6 @@ Feature: Syntax helpers When I run "behat --no-colors --lang=ru -d 'нашел'" Then the output should contain: """ - default | [Когда|*] /^Я нашел (\d+) яблоко?$/ + default | [Когда|Если|*] /^Я нашел (\d+) яблоко?$/ | at `FeatureContext::iFoundApples()` """ From 5ec7ceb1aa7e0d98402724afd271cea80220411e Mon Sep 17 00:00:00 2001 From: Jakub Zalas Date: Sun, 11 Aug 2019 09:39:33 +0000 Subject: [PATCH 159/567] Use the locally installed phpunit version on travis --- .travis.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index ba30bbf04..edd90370a 100644 --- a/.travis.yml +++ b/.travis.yml @@ -34,7 +34,7 @@ before_script: - echo " php_version_tags.php script: - - phpunit + - ./vendor/bin/phpunit - behat -fprogress --strict --tags '~@php-version,'`php php_version_tags.php` before_deploy: From 69a9147ea274d17d0ba460b34771ae503b5ab23c Mon Sep 17 00:00:00 2001 From: Pieter Frenssen Date: Tue, 24 Sep 2019 20:43:11 +0300 Subject: [PATCH 160/567] The PHP DOM extension is required I'm getting the following error when running a test scenario on a minimal Ubuntu Bionic image: ``` Fatal error: Class 'DOMDocument' not found (Behat\Testwork\Call\Exception\FatalThrowableError) ``` It is thrown in `Behat\Testwork\Output\Printer\JUnitOutputPrinter`. --- composer.json | 1 + 1 file changed, 1 insertion(+) diff --git a/composer.json b/composer.json index 43ea18de5..0f2331a33 100644 --- a/composer.json +++ b/composer.json @@ -15,6 +15,7 @@ "require": { "php": ">=5.3.3", + "ext-dom": "*", "ext-mbstring": "*", "behat/gherkin": "^4.6.0", "behat/transliterator": "^1.2", From 857fda364155841529a9671a64a7f0dea91ca248 Mon Sep 17 00:00:00 2001 From: Pieter Frenssen Date: Wed, 25 Sep 2019 00:36:53 +0300 Subject: [PATCH 161/567] Suggest to install the DOM extension when using JUnit output printer. --- composer.json | 5 ++++- src/Behat/Testwork/Output/Printer/JUnitOutputPrinter.php | 4 ++++ 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/composer.json b/composer.json index 0f2331a33..2246d04e1 100644 --- a/composer.json +++ b/composer.json @@ -15,7 +15,6 @@ "require": { "php": ">=5.3.3", - "ext-dom": "*", "ext-mbstring": "*", "behat/gherkin": "^4.6.0", "behat/transliterator": "^1.2", @@ -35,6 +34,10 @@ "herrera-io/box": "~1.6.1" }, + "suggest": { + "ext-dom": "Needed to output test results in JUnit format." + }, + "autoload": { "psr-4": { "Behat\\Behat\\": "src/Behat/Behat/", diff --git a/src/Behat/Testwork/Output/Printer/JUnitOutputPrinter.php b/src/Behat/Testwork/Output/Printer/JUnitOutputPrinter.php index 7577e111c..ec491108f 100644 --- a/src/Behat/Testwork/Output/Printer/JUnitOutputPrinter.php +++ b/src/Behat/Testwork/Output/Printer/JUnitOutputPrinter.php @@ -57,6 +57,10 @@ public function __construct(FilesystemOutputFactory $outputFactory) */ public function createNewFile($name, array $testsuitesAttributes = array()) { + // This requires the DOM extension to be enabled. + if (!extension_loaded('dom')) { + throw new \Exception('The PHP DOM extension is required to generate JUnit reports.'); + } $this->setFileName(strtolower(trim(preg_replace('/[^[:alnum:]_]+/', '_', $name), '_'))); $this->domDocument = new \DOMDocument(self::XML_VERSION, self::XML_ENCODING); From 5b3939009aa8fcac39c449abc217a7c2cc45950f Mon Sep 17 00:00:00 2001 From: Jakub Zalas Date: Mon, 30 Sep 2019 08:52:02 +0100 Subject: [PATCH 162/567] Disable XDebug if it is enabled --- .travis.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index a7c0c7115..1dc30050e 100644 --- a/.travis.yml +++ b/.travis.yml @@ -28,7 +28,7 @@ matrix: env: SYMFONY_VERSION='^4.2' before_install: - - phpenv config-rm xdebug.ini + - phpenv config-rm xdebug.ini || echo "XDebug is not enabled" before_script: - if [ "$SYMFONY_VERSION" != "" ]; then composer require --no-update "symfony/symfony:${SYMFONY_VERSION}"; fi; From 2eedfc4b8de66b200d6e921ac9e0c6d22240ada2 Mon Sep 17 00:00:00 2001 From: Witold Wasiczko Date: Mon, 24 Jun 2019 14:00:01 +0200 Subject: [PATCH 163/567] Boolean -> boolean --- .../Context/Cli/InteractiveContextIdentifier.php | 2 +- .../Context/ContextClass/ClassGenerator.php | 2 +- .../Behat/Context/ContextClass/ClassResolver.php | 2 +- .../Context/Environment/ContextEnvironment.php | 4 ++-- .../Context/Reader/AnnotatedContextReader.php | 6 +++--- .../Snippet/Appender/ContextSnippetAppender.php | 2 +- .../Definition/Pattern/Policy/PatternPolicy.php | 4 ++-- src/Behat/Behat/Definition/SearchResult.php | 2 +- .../EventDispatcher/Event/AfterStepSetup.php | 2 +- .../EventDispatcher/Event/AfterStepTested.php | 8 ++++---- .../EventDispatcher/Event/BeforeStepTeardown.php | 6 +++--- .../Gherkin/Suite/Setup/SuiteWithPathsSetup.php | 2 +- src/Behat/Behat/Hook/Call/RuntimeFeatureHook.php | 6 +++--- .../Behat/Hook/Call/RuntimeScenarioHook.php | 6 +++--- src/Behat/Behat/Hook/Call/RuntimeStepHook.php | 2 +- .../EventListener/AST/OutlineTableListener.php | 2 +- .../Flow/FireOnlySiblingsListener.php | 2 +- .../Flow/FirstBackgroundFiresFirstListener.php | 4 ++-- .../Flow/OnlyFirstBackgroundFiresListener.php | 16 ++++++++-------- .../Node/Printer/Pretty/PrettySetupPrinter.php | 4 ++-- .../Printer/Pretty/PrettySkippedStepPrinter.php | 2 +- .../Node/Printer/Pretty/PrettyStepPrinter.php | 2 +- .../Behat/Snippet/Appender/SnippetAppender.php | 2 +- .../Behat/Snippet/Generator/SnippetGenerator.php | 2 +- src/Behat/Behat/Snippet/SnippetRegistry.php | 2 +- src/Behat/Behat/Tester/BackgroundTester.php | 6 +++--- src/Behat/Behat/Tester/OutlineTester.php | 6 +++--- .../Tester/Runtime/RuntimeScenarioTester.php | 2 +- .../Behat/Tester/Runtime/RuntimeStepTester.php | 2 +- src/Behat/Behat/Tester/ScenarioTester.php | 6 +++--- src/Behat/Behat/Tester/StepContainerTester.php | 2 +- src/Behat/Behat/Tester/StepTester.php | 6 +++--- .../SimpleArgumentTransformation.php | 2 +- .../Transformer/ArgumentTransformer.php | 2 +- .../Testwork/Argument/MixedArgumentOrganiser.php | 8 ++++---- .../Argument/PregMatchArgumentOrganiser.php | 2 +- src/Behat/Testwork/Call/CallResult.php | 4 ++-- src/Behat/Testwork/Call/CallResults.php | 4 ++-- src/Behat/Testwork/Call/Callee.php | 4 ++-- src/Behat/Testwork/Call/Filter/CallFilter.php | 2 +- src/Behat/Testwork/Call/Filter/ResultFilter.php | 2 +- src/Behat/Testwork/Call/Handler/CallHandler.php | 2 +- .../Testwork/Call/Handler/RuntimeCallHandler.php | 4 ++-- src/Behat/Testwork/Call/RuntimeCallee.php | 4 ++-- .../Environment/Handler/EnvironmentHandler.php | 4 ++-- .../Environment/Reader/EnvironmentReader.php | 2 +- .../Exception/Stringer/ExceptionStringer.php | 2 +- .../Testwork/Hook/Call/RuntimeSuiteHook.php | 2 +- src/Behat/Testwork/Hook/FilterableHook.php | 2 +- src/Behat/Testwork/Ordering/OrderedExercise.php | 6 +++--- .../Testwork/Output/Cli/OutputController.php | 6 +++--- src/Behat/Testwork/Output/OutputManager.php | 2 +- .../Output/Printer/Factory/OutputFactory.php | 2 +- .../Testwork/Output/Printer/OutputPrinter.php | 2 +- .../Configuration/ConfigurationLoader.php | 2 +- .../Testwork/Suite/Generator/SuiteGenerator.php | 2 +- src/Behat/Testwork/Suite/GenericSuite.php | 2 +- src/Behat/Testwork/Suite/Setup/SuiteSetup.php | 2 +- src/Behat/Testwork/Suite/Suite.php | 2 +- src/Behat/Testwork/Suite/SuiteRegistry.php | 2 +- .../Testwork/Tester/Cli/ExerciseController.php | 4 ++-- .../Testwork/Tester/Cli/StrictController.php | 4 ++-- src/Behat/Testwork/Tester/Exercise.php | 6 +++--- .../Testwork/Tester/Result/ExceptionResult.php | 2 +- .../Interpretation/ResultInterpretation.php | 2 +- src/Behat/Testwork/Tester/Result/TestResult.php | 2 +- .../Tester/ServiceContainer/TesterExtension.php | 4 ++-- src/Behat/Testwork/Tester/Setup/Setup.php | 4 ++-- src/Behat/Testwork/Tester/Setup/Teardown.php | 4 ++-- .../Testwork/Tester/SpecificationTester.php | 6 +++--- src/Behat/Testwork/Tester/SuiteTester.php | 6 +++--- 71 files changed, 125 insertions(+), 125 deletions(-) diff --git a/src/Behat/Behat/Context/Cli/InteractiveContextIdentifier.php b/src/Behat/Behat/Context/Cli/InteractiveContextIdentifier.php index 52a3eb934..286ffde12 100644 --- a/src/Behat/Behat/Context/Cli/InteractiveContextIdentifier.php +++ b/src/Behat/Behat/Context/Cli/InteractiveContextIdentifier.php @@ -98,7 +98,7 @@ private function askQuestion($message, $choices, $default) /** * Checks if interactive mode is supported. * - * @return Boolean + * @return boolean * * @deprecated there is a better way to do it - `InputInterface::isInteractive()` method. * Sadly, this doesn't work properly prior Symfony\Console 2.7 and as we need diff --git a/src/Behat/Behat/Context/ContextClass/ClassGenerator.php b/src/Behat/Behat/Context/ContextClass/ClassGenerator.php index d2a740926..61b3fc1d8 100644 --- a/src/Behat/Behat/Context/ContextClass/ClassGenerator.php +++ b/src/Behat/Behat/Context/ContextClass/ClassGenerator.php @@ -28,7 +28,7 @@ interface ClassGenerator * @param Suite $suite * @param string $contextClass * - * @return Boolean + * @return boolean */ public function supportsSuiteAndClass(Suite $suite, $contextClass); diff --git a/src/Behat/Behat/Context/ContextClass/ClassResolver.php b/src/Behat/Behat/Context/ContextClass/ClassResolver.php index 464f68f41..a97680ee6 100644 --- a/src/Behat/Behat/Context/ContextClass/ClassResolver.php +++ b/src/Behat/Behat/Context/ContextClass/ClassResolver.php @@ -26,7 +26,7 @@ interface ClassResolver * * @param string $contextString * - * @return Boolean + * @return boolean */ public function supportsClass($contextString); diff --git a/src/Behat/Behat/Context/Environment/ContextEnvironment.php b/src/Behat/Behat/Context/Environment/ContextEnvironment.php index 690eebb28..90acc4db3 100644 --- a/src/Behat/Behat/Context/Environment/ContextEnvironment.php +++ b/src/Behat/Behat/Context/Environment/ContextEnvironment.php @@ -25,7 +25,7 @@ interface ContextEnvironment extends Environment /** * Checks if environment has any contexts registered. * - * @return Boolean + * @return boolean */ public function hasContexts(); @@ -41,7 +41,7 @@ public function getContextClasses(); * * @param string $class * - * @return Boolean + * @return boolean */ public function hasContextClass($class); } diff --git a/src/Behat/Behat/Context/Reader/AnnotatedContextReader.php b/src/Behat/Behat/Context/Reader/AnnotatedContextReader.php index a3144740e..722473f1c 100644 --- a/src/Behat/Behat/Context/Reader/AnnotatedContextReader.php +++ b/src/Behat/Behat/Context/Reader/AnnotatedContextReader.php @@ -180,7 +180,7 @@ private function readDescription($docBlock) * * @param string $docLine * - * @return Boolean + * @return boolean */ private function isEmpty($docLine) { @@ -192,7 +192,7 @@ private function isEmpty($docLine) * * @param string $docLine * - * @return Boolean + * @return boolean */ private function isNotAnnotation($docLine) { @@ -229,7 +229,7 @@ private function readDocLineCallee($class, ReflectionMethod $method, $docLine, $ * * @param string $docLine * - * @return Boolean + * @return boolean */ private function isIgnoredAnnotation($docLine) { diff --git a/src/Behat/Behat/Context/Snippet/Appender/ContextSnippetAppender.php b/src/Behat/Behat/Context/Snippet/Appender/ContextSnippetAppender.php index 5a881f94b..7af719c36 100644 --- a/src/Behat/Behat/Context/Snippet/Appender/ContextSnippetAppender.php +++ b/src/Behat/Behat/Context/Snippet/Appender/ContextSnippetAppender.php @@ -81,7 +81,7 @@ public function appendSnippet(AggregateSnippet $snippet) * @param string $class * @param string $contextFileContent * - * @return Boolean + * @return boolean */ private function isClassImported($class, $contextFileContent) { diff --git a/src/Behat/Behat/Definition/Pattern/Policy/PatternPolicy.php b/src/Behat/Behat/Definition/Pattern/Policy/PatternPolicy.php index 247624170..cbad76e50 100644 --- a/src/Behat/Behat/Definition/Pattern/Policy/PatternPolicy.php +++ b/src/Behat/Behat/Definition/Pattern/Policy/PatternPolicy.php @@ -27,7 +27,7 @@ interface PatternPolicy * * @param string $type * - * @return Boolean + * @return boolean */ public function supportsPatternType($type); @@ -45,7 +45,7 @@ public function generatePattern($stepText); * * @param string $pattern * - * @return Boolean + * @return boolean */ public function supportsPattern($pattern); diff --git a/src/Behat/Behat/Definition/SearchResult.php b/src/Behat/Behat/Definition/SearchResult.php index 158f63557..512d6c24c 100644 --- a/src/Behat/Behat/Definition/SearchResult.php +++ b/src/Behat/Behat/Definition/SearchResult.php @@ -47,7 +47,7 @@ public function __construct(Definition $definition = null, $matchedText = null, /** * Checks if result contains a match. * - * @return Boolean + * @return boolean */ public function hasMatch() { diff --git a/src/Behat/Behat/EventDispatcher/Event/AfterStepSetup.php b/src/Behat/Behat/EventDispatcher/Event/AfterStepSetup.php index cf9b6c5f5..9eb520fa1 100644 --- a/src/Behat/Behat/EventDispatcher/Event/AfterStepSetup.php +++ b/src/Behat/Behat/EventDispatcher/Event/AfterStepSetup.php @@ -86,7 +86,7 @@ public function getSetup() /** * Checks if step call, setup or teardown produced any output (stdOut or exception). * - * @return Boolean + * @return boolean */ public function hasOutput() { diff --git a/src/Behat/Behat/EventDispatcher/Event/AfterStepTested.php b/src/Behat/Behat/EventDispatcher/Event/AfterStepTested.php index 37b497bfa..7ddcd9bdc 100644 --- a/src/Behat/Behat/EventDispatcher/Event/AfterStepTested.php +++ b/src/Behat/Behat/EventDispatcher/Event/AfterStepTested.php @@ -111,7 +111,7 @@ public function getTeardown() /** * Checks if step call, setup or teardown produced any output (stdOut or exception). * - * @return Boolean + * @return boolean */ public function hasOutput() { @@ -121,7 +121,7 @@ public function hasOutput() /** * Checks if step teardown has output. * - * @return Boolean + * @return boolean */ private function teardownHasOutput() { @@ -131,7 +131,7 @@ private function teardownHasOutput() /** * Checks if result has produced exception. * - * @return Boolean + * @return boolean */ private function resultHasException() { @@ -141,7 +141,7 @@ private function resultHasException() /** * Checks if result is executed and call result has produced exception or stdOut. * - * @return Boolean + * @return boolean */ private function resultCallHasOutput() { diff --git a/src/Behat/Behat/EventDispatcher/Event/BeforeStepTeardown.php b/src/Behat/Behat/EventDispatcher/Event/BeforeStepTeardown.php index 6d9b9c6e9..4bb296ec2 100644 --- a/src/Behat/Behat/EventDispatcher/Event/BeforeStepTeardown.php +++ b/src/Behat/Behat/EventDispatcher/Event/BeforeStepTeardown.php @@ -93,7 +93,7 @@ public function getTestResult() /** * Checks if step call produced any output (stdOut or exception). * - * @return Boolean + * @return boolean */ public function hasOutput() { @@ -103,7 +103,7 @@ public function hasOutput() /** * Checks if result has produced exception. * - * @return Boolean + * @return boolean */ private function resultHasException() { @@ -113,7 +113,7 @@ private function resultHasException() /** * Checks if result is executed and call result has produced exception or stdOut. * - * @return Boolean + * @return boolean */ private function resultCallHasOutput() { diff --git a/src/Behat/Behat/Gherkin/Suite/Setup/SuiteWithPathsSetup.php b/src/Behat/Behat/Gherkin/Suite/Setup/SuiteWithPathsSetup.php index 65c7c8f73..5147d4f11 100644 --- a/src/Behat/Behat/Gherkin/Suite/Setup/SuiteWithPathsSetup.php +++ b/src/Behat/Behat/Gherkin/Suite/Setup/SuiteWithPathsSetup.php @@ -97,7 +97,7 @@ private function locatePath($path) * * @param string $file A file path * - * @return Boolean + * @return boolean */ private function isAbsolutePath($file) { diff --git a/src/Behat/Behat/Hook/Call/RuntimeFeatureHook.php b/src/Behat/Behat/Hook/Call/RuntimeFeatureHook.php index b3d4fb24b..8b3ca5348 100644 --- a/src/Behat/Behat/Hook/Call/RuntimeFeatureHook.php +++ b/src/Behat/Behat/Hook/Call/RuntimeFeatureHook.php @@ -68,7 +68,7 @@ public function filterMatches(HookScope $scope) * @param FeatureNode $feature * @param string $filterString * - * @return Boolean + * @return boolean */ private function isMatch(FeatureNode $feature, $filterString) { @@ -89,7 +89,7 @@ private function isMatch(FeatureNode $feature, $filterString) * @param FeatureNode $feature * @param string $filterString * - * @return Boolean + * @return boolean */ private function isMatchTagFilter(FeatureNode $feature, $filterString) { @@ -104,7 +104,7 @@ private function isMatchTagFilter(FeatureNode $feature, $filterString) * @param FeatureNode $feature * @param string $filterString * - * @return Boolean + * @return boolean */ private function isMatchNameFilter(FeatureNode $feature, $filterString) { diff --git a/src/Behat/Behat/Hook/Call/RuntimeScenarioHook.php b/src/Behat/Behat/Hook/Call/RuntimeScenarioHook.php index 56e25f999..9bb6bbb8c 100644 --- a/src/Behat/Behat/Hook/Call/RuntimeScenarioHook.php +++ b/src/Behat/Behat/Hook/Call/RuntimeScenarioHook.php @@ -48,7 +48,7 @@ public function filterMatches(HookScope $scope) * @param ScenarioInterface $scenario * @param string $filterString * - * @return Boolean + * @return boolean */ protected function isMatch(FeatureNode $feature, ScenarioInterface $scenario, $filterString) { @@ -70,7 +70,7 @@ protected function isMatch(FeatureNode $feature, ScenarioInterface $scenario, $f * @param ScenarioInterface $scenario * @param string $filterString * - * @return Boolean + * @return boolean */ protected function isMatchTagFilter(FeatureNode $feature, ScenarioInterface $scenario, $filterString) { @@ -89,7 +89,7 @@ protected function isMatchTagFilter(FeatureNode $feature, ScenarioInterface $sce * @param ScenarioInterface $scenario * @param string $filterString * - * @return Boolean + * @return boolean */ protected function isMatchNameFilter(ScenarioInterface $scenario, $filterString) { diff --git a/src/Behat/Behat/Hook/Call/RuntimeStepHook.php b/src/Behat/Behat/Hook/Call/RuntimeStepHook.php index a1326c3cf..57ea7641b 100644 --- a/src/Behat/Behat/Hook/Call/RuntimeStepHook.php +++ b/src/Behat/Behat/Hook/Call/RuntimeStepHook.php @@ -55,7 +55,7 @@ public function filterMatches(HookScope $scope) * @param StepNode $step * @param string $filterString * - * @return Boolean + * @return boolean */ private function isStepMatch(StepNode $step, $filterString) { diff --git a/src/Behat/Behat/Output/Node/EventListener/AST/OutlineTableListener.php b/src/Behat/Behat/Output/Node/EventListener/AST/OutlineTableListener.php index fa77da454..490dfbbb5 100644 --- a/src/Behat/Behat/Output/Node/EventListener/AST/OutlineTableListener.php +++ b/src/Behat/Behat/Output/Node/EventListener/AST/OutlineTableListener.php @@ -61,7 +61,7 @@ final class OutlineTableListener implements EventListener */ private $exampleSetup; /** - * @var Boolean + * @var boolean */ private $headerPrinted = false; /** diff --git a/src/Behat/Behat/Output/Node/EventListener/Flow/FireOnlySiblingsListener.php b/src/Behat/Behat/Output/Node/EventListener/Flow/FireOnlySiblingsListener.php index 7e5788554..44db35bb8 100644 --- a/src/Behat/Behat/Output/Node/EventListener/Flow/FireOnlySiblingsListener.php +++ b/src/Behat/Behat/Output/Node/EventListener/Flow/FireOnlySiblingsListener.php @@ -37,7 +37,7 @@ class FireOnlySiblingsListener implements EventListener */ private $descendant; /** - * @var Boolean + * @var boolean */ private $inContext = false; diff --git a/src/Behat/Behat/Output/Node/EventListener/Flow/FirstBackgroundFiresFirstListener.php b/src/Behat/Behat/Output/Node/EventListener/Flow/FirstBackgroundFiresFirstListener.php index f9bb95f64..b63824d6a 100644 --- a/src/Behat/Behat/Output/Node/EventListener/Flow/FirstBackgroundFiresFirstListener.php +++ b/src/Behat/Behat/Output/Node/EventListener/Flow/FirstBackgroundFiresFirstListener.php @@ -34,7 +34,7 @@ class FirstBackgroundFiresFirstListener implements EventListener */ private $descendant; /** - * @var Boolean + * @var boolean */ private $firstBackgroundEnded = false; /** @@ -103,7 +103,7 @@ private function markFirstBackgroundPrintedAfterBackground($eventName) * * @param Event $event * - * @return Boolean + * @return boolean */ private function isEventDelayedUntilFirstBackgroundPrinted(Event $event) { diff --git a/src/Behat/Behat/Output/Node/EventListener/Flow/OnlyFirstBackgroundFiresListener.php b/src/Behat/Behat/Output/Node/EventListener/Flow/OnlyFirstBackgroundFiresListener.php index ad3679c8f..4a0278c06 100644 --- a/src/Behat/Behat/Output/Node/EventListener/Flow/OnlyFirstBackgroundFiresListener.php +++ b/src/Behat/Behat/Output/Node/EventListener/Flow/OnlyFirstBackgroundFiresListener.php @@ -36,15 +36,15 @@ class OnlyFirstBackgroundFiresListener implements EventListener */ private $descendant; /** - * @var Boolean + * @var boolean */ private $firstBackgroundEnded = false; /** - * @var Boolean + * @var boolean */ private $inBackground = false; /** - * @var Boolean + * @var boolean */ private $stepSetupHadOutput = false; @@ -125,7 +125,7 @@ private function markFirstBackgroundPrintedAfterBackground($eventName) * * @param Event $event * - * @return Boolean + * @return boolean */ private function isSkippableEvent(Event $event) { @@ -141,7 +141,7 @@ private function isSkippableEvent(Event $event) * * @param Event $event * - * @return Boolean + * @return boolean */ private function isNonFailingConsequentBackgroundStep(Event $event) { @@ -157,7 +157,7 @@ private function isNonFailingConsequentBackgroundStep(Event $event) * * @param Event $event * - * @return Boolean + * @return boolean */ private function isStepEventWithOutput(Event $event) { @@ -169,7 +169,7 @@ private function isStepEventWithOutput(Event $event) * * @param Event $event * - * @return Boolean + * @return boolean */ private function isBeforeStepEventWithOutput(Event $event) { @@ -187,7 +187,7 @@ private function isBeforeStepEventWithOutput(Event $event) * * @param Event $event * - * @return Boolean + * @return boolean */ private function isAfterStepWithOutput(Event $event) { diff --git a/src/Behat/Behat/Output/Node/Printer/Pretty/PrettySetupPrinter.php b/src/Behat/Behat/Output/Node/Printer/Pretty/PrettySetupPrinter.php index 46bcba3a3..09e900788 100644 --- a/src/Behat/Behat/Output/Node/Printer/Pretty/PrettySetupPrinter.php +++ b/src/Behat/Behat/Output/Node/Printer/Pretty/PrettySetupPrinter.php @@ -56,8 +56,8 @@ final class PrettySetupPrinter implements SetupPrinter * @param ResultToStringConverter $resultConverter * @param ExceptionPresenter $exceptionPresenter * @param integer $indentation - * @param Boolean $newlineBefore - * @param Boolean $newlineAfter + * @param boolean $newlineBefore + * @param boolean $newlineAfter */ public function __construct( ResultToStringConverter $resultConverter, diff --git a/src/Behat/Behat/Output/Node/Printer/Pretty/PrettySkippedStepPrinter.php b/src/Behat/Behat/Output/Node/Printer/Pretty/PrettySkippedStepPrinter.php index 718afd3b9..2ec682556 100644 --- a/src/Behat/Behat/Output/Node/Printer/Pretty/PrettySkippedStepPrinter.php +++ b/src/Behat/Behat/Output/Node/Printer/Pretty/PrettySkippedStepPrinter.php @@ -129,7 +129,7 @@ private function printArguments(Formatter $formatter, array $arguments) * Returns argument string for provided argument. * * @param ArgumentInterface $argument - * @param Boolean $collapse + * @param boolean $collapse * * @return string */ diff --git a/src/Behat/Behat/Output/Node/Printer/Pretty/PrettyStepPrinter.php b/src/Behat/Behat/Output/Node/Printer/Pretty/PrettyStepPrinter.php index 8d47da1ec..9604c1021 100644 --- a/src/Behat/Behat/Output/Node/Printer/Pretty/PrettyStepPrinter.php +++ b/src/Behat/Behat/Output/Node/Printer/Pretty/PrettyStepPrinter.php @@ -180,7 +180,7 @@ private function printException(OutputPrinter $printer, StepResult $result) * Returns argument string for provided argument. * * @param ArgumentInterface $argument - * @param Boolean $collapse + * @param boolean $collapse * * @return string */ diff --git a/src/Behat/Behat/Snippet/Appender/SnippetAppender.php b/src/Behat/Behat/Snippet/Appender/SnippetAppender.php index 041b8e6e5..e78d6bea4 100644 --- a/src/Behat/Behat/Snippet/Appender/SnippetAppender.php +++ b/src/Behat/Behat/Snippet/Appender/SnippetAppender.php @@ -27,7 +27,7 @@ interface SnippetAppender * * @param AggregateSnippet $snippet * - * @return Boolean + * @return boolean */ public function supportsSnippet(AggregateSnippet $snippet); diff --git a/src/Behat/Behat/Snippet/Generator/SnippetGenerator.php b/src/Behat/Behat/Snippet/Generator/SnippetGenerator.php index ca7d73937..5e68af1fe 100644 --- a/src/Behat/Behat/Snippet/Generator/SnippetGenerator.php +++ b/src/Behat/Behat/Snippet/Generator/SnippetGenerator.php @@ -30,7 +30,7 @@ interface SnippetGenerator * @param Environment $environment * @param StepNode $step * - * @return Boolean + * @return boolean */ public function supportsEnvironmentAndStep(Environment $environment, StepNode $step); diff --git a/src/Behat/Behat/Snippet/SnippetRegistry.php b/src/Behat/Behat/Snippet/SnippetRegistry.php index 0724c3e40..6bdbbebf7 100644 --- a/src/Behat/Behat/Snippet/SnippetRegistry.php +++ b/src/Behat/Behat/Snippet/SnippetRegistry.php @@ -34,7 +34,7 @@ final class SnippetRegistry implements SnippetRepository */ private $snippets = array(); /** - * @var Boolean + * @var boolean */ private $snippetsGenerated = false; diff --git a/src/Behat/Behat/Tester/BackgroundTester.php b/src/Behat/Behat/Tester/BackgroundTester.php index 8d70b57d8..4a8c823ec 100644 --- a/src/Behat/Behat/Tester/BackgroundTester.php +++ b/src/Behat/Behat/Tester/BackgroundTester.php @@ -28,7 +28,7 @@ interface BackgroundTester * * @param Environment $env * @param FeatureNode $feature - * @param Boolean $skip + * @param boolean $skip * * @return Setup */ @@ -39,7 +39,7 @@ public function setUp(Environment $env, FeatureNode $feature, $skip); * * @param Environment $env * @param FeatureNode $feature - * @param Boolean $skip + * @param boolean $skip * * @return TestResult */ @@ -50,7 +50,7 @@ public function test(Environment $env, FeatureNode $feature, $skip); * * @param Environment $env * @param FeatureNode $feature - * @param Boolean $skip + * @param boolean $skip * @param TestResult $result * * @return Teardown diff --git a/src/Behat/Behat/Tester/OutlineTester.php b/src/Behat/Behat/Tester/OutlineTester.php index 863aba38c..144f1caf4 100644 --- a/src/Behat/Behat/Tester/OutlineTester.php +++ b/src/Behat/Behat/Tester/OutlineTester.php @@ -30,7 +30,7 @@ interface OutlineTester * @param Environment $env * @param FeatureNode $feature * @param OutlineNode $outline - * @param Boolean $skip + * @param boolean $skip * * @return Setup */ @@ -42,7 +42,7 @@ public function setUp(Environment $env, FeatureNode $feature, OutlineNode $outli * @param Environment $env * @param FeatureNode $feature * @param OutlineNode $outline - * @param Boolean $skip + * @param boolean $skip * * @return TestResult */ @@ -54,7 +54,7 @@ public function test(Environment $env, FeatureNode $feature, OutlineNode $outlin * @param Environment $env * @param FeatureNode $feature * @param OutlineNode $outline - * @param Boolean $skip + * @param boolean $skip * @param TestResult $result * * @return Teardown diff --git a/src/Behat/Behat/Tester/Runtime/RuntimeScenarioTester.php b/src/Behat/Behat/Tester/Runtime/RuntimeScenarioTester.php index 7ab11a0be..47ec35f1b 100644 --- a/src/Behat/Behat/Tester/Runtime/RuntimeScenarioTester.php +++ b/src/Behat/Behat/Tester/Runtime/RuntimeScenarioTester.php @@ -91,7 +91,7 @@ public function tearDown(Environment $env, FeatureNode $feature, Scenario $scena * * @param Environment $env * @param FeatureNode $feature - * @param Boolean $skip + * @param boolean $skip * * @return TestResult */ diff --git a/src/Behat/Behat/Tester/Runtime/RuntimeStepTester.php b/src/Behat/Behat/Tester/Runtime/RuntimeStepTester.php index 7031eeca7..82e76c144 100644 --- a/src/Behat/Behat/Tester/Runtime/RuntimeStepTester.php +++ b/src/Behat/Behat/Tester/Runtime/RuntimeStepTester.php @@ -107,7 +107,7 @@ private function searchDefinition(Environment $env, FeatureNode $feature, StepNo * @param FeatureNode $feature * @param StepNode $step * @param SearchResult $search - * @param Boolean $skip + * @param boolean $skip * * @return StepResult */ diff --git a/src/Behat/Behat/Tester/ScenarioTester.php b/src/Behat/Behat/Tester/ScenarioTester.php index 2fd249489..ae3baef5e 100644 --- a/src/Behat/Behat/Tester/ScenarioTester.php +++ b/src/Behat/Behat/Tester/ScenarioTester.php @@ -30,7 +30,7 @@ interface ScenarioTester * @param Environment $env * @param FeatureNode $feature * @param Scenario $scenario - * @param Boolean $skip + * @param boolean $skip * * @return Setup */ @@ -42,7 +42,7 @@ public function setUp(Environment $env, FeatureNode $feature, Scenario $scenario * @param Environment $env * @param FeatureNode $feature * @param Scenario $scenario - * @param Boolean $skip + * @param boolean $skip * * @return TestResult */ @@ -54,7 +54,7 @@ public function test(Environment $env, FeatureNode $feature, Scenario $scenario, * @param Environment $env * @param FeatureNode $feature * @param Scenario $scenario - * @param Boolean $skip + * @param boolean $skip * @param TestResult $result * * @return Teardown diff --git a/src/Behat/Behat/Tester/StepContainerTester.php b/src/Behat/Behat/Tester/StepContainerTester.php index 543e133d2..a78ac1003 100644 --- a/src/Behat/Behat/Tester/StepContainerTester.php +++ b/src/Behat/Behat/Tester/StepContainerTester.php @@ -45,7 +45,7 @@ public function __construct(StepTester $stepTester) * @param Environment $env * @param FeatureNode $feature * @param StepContainerInterface $container - * @param Boolean $skip + * @param boolean $skip * * @return TestResult[] */ diff --git a/src/Behat/Behat/Tester/StepTester.php b/src/Behat/Behat/Tester/StepTester.php index d5c995ceb..7ffd7b35b 100644 --- a/src/Behat/Behat/Tester/StepTester.php +++ b/src/Behat/Behat/Tester/StepTester.php @@ -30,7 +30,7 @@ interface StepTester * @param Environment $env * @param FeatureNode $feature * @param StepNode $step - * @param Boolean $skip + * @param boolean $skip * * @return Setup */ @@ -42,7 +42,7 @@ public function setUp(Environment $env, FeatureNode $feature, StepNode $step, $s * @param Environment $env * @param FeatureNode $feature * @param StepNode $step - * @param Boolean $skip + * @param boolean $skip * * @return StepResult */ @@ -54,7 +54,7 @@ public function test(Environment $env, FeatureNode $feature, StepNode $step, $sk * @param Environment $env * @param FeatureNode $feature * @param StepNode $step - * @param Boolean $skip + * @param boolean $skip * @param StepResult $result * * @return Teardown diff --git a/src/Behat/Behat/Transformation/SimpleArgumentTransformation.php b/src/Behat/Behat/Transformation/SimpleArgumentTransformation.php index 77cdeefb2..c8a71a6e4 100644 --- a/src/Behat/Behat/Transformation/SimpleArgumentTransformation.php +++ b/src/Behat/Behat/Transformation/SimpleArgumentTransformation.php @@ -45,7 +45,7 @@ public function getPriority(); * @param integer|string $argumentIndex * @param mixed $argumentValue * - * @return Boolean + * @return boolean */ public function supportsDefinitionAndArgument(DefinitionCall $definitionCall, $argumentIndex, $argumentValue); diff --git a/src/Behat/Behat/Transformation/Transformer/ArgumentTransformer.php b/src/Behat/Behat/Transformation/Transformer/ArgumentTransformer.php index 4773960e0..f49be2dcd 100644 --- a/src/Behat/Behat/Transformation/Transformer/ArgumentTransformer.php +++ b/src/Behat/Behat/Transformation/Transformer/ArgumentTransformer.php @@ -26,7 +26,7 @@ interface ArgumentTransformer * @param integer|string $argumentIndex * @param mixed $argumentValue * - * @return Boolean + * @return boolean */ public function supportsDefinitionAndArgument(DefinitionCall $definitionCall, $argumentIndex, $argumentValue); diff --git a/src/Behat/Testwork/Argument/MixedArgumentOrganiser.php b/src/Behat/Testwork/Argument/MixedArgumentOrganiser.php index c845f03d4..d21e8bd5d 100644 --- a/src/Behat/Testwork/Argument/MixedArgumentOrganiser.php +++ b/src/Behat/Testwork/Argument/MixedArgumentOrganiser.php @@ -99,7 +99,7 @@ function (ReflectionParameter $parameter) { * @param mixed $argumentKey * @param string[] $parameterNames * - * @return Boolean + * @return boolean */ private function isStringKeyAndExistsInParameters($argumentKey, $parameterNames) { @@ -112,7 +112,7 @@ private function isStringKeyAndExistsInParameters($argumentKey, $parameterNames) * @param ReflectionParameter[] $parameters * @param mixed $value * - * @return Boolean + * @return boolean */ private function isParameterTypehintedInArgumentList(array $parameters, $value) { @@ -135,7 +135,7 @@ private function isParameterTypehintedInArgumentList(array $parameters, $value) * @param object $value * @param ReflectionParameter $parameter * - * @return Boolean + * @return boolean */ private function isValueMatchesTypehintedParameter($value, ReflectionParameter $parameter) { @@ -425,7 +425,7 @@ private function markArgumentDefined($position) * * @param integer $position * - * @return Boolean + * @return boolean */ private function isArgumentDefined($position) { diff --git a/src/Behat/Testwork/Argument/PregMatchArgumentOrganiser.php b/src/Behat/Testwork/Argument/PregMatchArgumentOrganiser.php index 2fb053585..a49d3920a 100644 --- a/src/Behat/Testwork/Argument/PregMatchArgumentOrganiser.php +++ b/src/Behat/Testwork/Argument/PregMatchArgumentOrganiser.php @@ -81,7 +81,7 @@ private function cleanupMatchDuplicates(array $match) * @param integer $keyIndex * @param mixed[] $keys * - * @return Boolean + * @return boolean */ private function isKeyAStringAndNexOneIsAnInteger($keyIndex, array $keys) { diff --git a/src/Behat/Testwork/Call/CallResult.php b/src/Behat/Testwork/Call/CallResult.php index ca3c52837..6bb4c69ec 100644 --- a/src/Behat/Testwork/Call/CallResult.php +++ b/src/Behat/Testwork/Call/CallResult.php @@ -75,7 +75,7 @@ public function getReturn() /** * Check if call thrown exception. * - * @return Boolean + * @return boolean */ public function hasException() { @@ -95,7 +95,7 @@ public function getException() /** * Checks if call produced stdOut. * - * @return Boolean + * @return boolean */ public function hasStdOut() { diff --git a/src/Behat/Testwork/Call/CallResults.php b/src/Behat/Testwork/Call/CallResults.php index f79ea0c9e..bd0048872 100644 --- a/src/Behat/Testwork/Call/CallResults.php +++ b/src/Behat/Testwork/Call/CallResults.php @@ -53,7 +53,7 @@ public static function merge(CallResults $first, CallResults $second) /** * Checks if any call in collection throws an exception. * - * @return Boolean + * @return boolean */ public function hasExceptions() { @@ -69,7 +69,7 @@ public function hasExceptions() /** * Checks if any call in collection produces an output. * - * @return Boolean + * @return boolean */ public function hasStdOuts() { diff --git a/src/Behat/Testwork/Call/Callee.php b/src/Behat/Testwork/Call/Callee.php index c03e77649..240d8d5c1 100644 --- a/src/Behat/Testwork/Call/Callee.php +++ b/src/Behat/Testwork/Call/Callee.php @@ -36,14 +36,14 @@ public function getDescription(); /** * Returns true if callee is a method, false otherwise. * - * @return Boolean + * @return boolean */ public function isAMethod(); /** * Returns true if callee is an instance (non-static) method, false otherwise. * - * @return Boolean + * @return boolean */ public function isAnInstanceMethod(); diff --git a/src/Behat/Testwork/Call/Filter/CallFilter.php b/src/Behat/Testwork/Call/Filter/CallFilter.php index 5426c160a..7565d8af2 100644 --- a/src/Behat/Testwork/Call/Filter/CallFilter.php +++ b/src/Behat/Testwork/Call/Filter/CallFilter.php @@ -27,7 +27,7 @@ interface CallFilter * * @param Call $call * - * @return Boolean + * @return boolean */ public function supportsCall(Call $call); diff --git a/src/Behat/Testwork/Call/Filter/ResultFilter.php b/src/Behat/Testwork/Call/Filter/ResultFilter.php index ac3ebe000..66dabef18 100644 --- a/src/Behat/Testwork/Call/Filter/ResultFilter.php +++ b/src/Behat/Testwork/Call/Filter/ResultFilter.php @@ -27,7 +27,7 @@ interface ResultFilter * * @param CallResult $result * - * @return Boolean + * @return boolean */ public function supportsResult(CallResult $result); diff --git a/src/Behat/Testwork/Call/Handler/CallHandler.php b/src/Behat/Testwork/Call/Handler/CallHandler.php index e553d2a76..78c6df57b 100644 --- a/src/Behat/Testwork/Call/Handler/CallHandler.php +++ b/src/Behat/Testwork/Call/Handler/CallHandler.php @@ -28,7 +28,7 @@ interface CallHandler * * @param Call $call * - * @return Boolean + * @return boolean */ public function supportsCall(Call $call); diff --git a/src/Behat/Testwork/Call/Handler/RuntimeCallHandler.php b/src/Behat/Testwork/Call/Handler/RuntimeCallHandler.php index 62b3d1d6d..8f09a406f 100644 --- a/src/Behat/Testwork/Call/Handler/RuntimeCallHandler.php +++ b/src/Behat/Testwork/Call/Handler/RuntimeCallHandler.php @@ -77,7 +77,7 @@ public function handleCall(Call $call) * @param string $file * @param integer $line * - * @return Boolean + * @return boolean * * @throws CallErrorException */ @@ -154,7 +154,7 @@ private function stopErrorAndOutputBuffering() * * @param integer $level * - * @return Boolean + * @return boolean */ private function errorLevelIsNotReportable($level) { diff --git a/src/Behat/Testwork/Call/RuntimeCallee.php b/src/Behat/Testwork/Call/RuntimeCallee.php index c764629d2..710697a82 100644 --- a/src/Behat/Testwork/Call/RuntimeCallee.php +++ b/src/Behat/Testwork/Call/RuntimeCallee.php @@ -112,7 +112,7 @@ public function getReflection() /** * Returns true if callee is a method, false otherwise. * - * @return Boolean + * @return boolean */ public function isAMethod() { @@ -122,7 +122,7 @@ public function isAMethod() /** * Returns true if callee is an instance (non-static) method, false otherwise. * - * @return Boolean + * @return boolean */ public function isAnInstanceMethod() { diff --git a/src/Behat/Testwork/Environment/Handler/EnvironmentHandler.php b/src/Behat/Testwork/Environment/Handler/EnvironmentHandler.php index f2b6b9820..062de8f78 100644 --- a/src/Behat/Testwork/Environment/Handler/EnvironmentHandler.php +++ b/src/Behat/Testwork/Environment/Handler/EnvironmentHandler.php @@ -28,7 +28,7 @@ interface EnvironmentHandler * * @param Suite $suite * - * @return Boolean + * @return boolean */ public function supportsSuite(Suite $suite); @@ -47,7 +47,7 @@ public function buildEnvironment(Suite $suite); * @param Environment $environment * @param mixed $testSubject * - * @return Boolean + * @return boolean */ public function supportsEnvironmentAndSubject(Environment $environment, $testSubject = null); diff --git a/src/Behat/Testwork/Environment/Reader/EnvironmentReader.php b/src/Behat/Testwork/Environment/Reader/EnvironmentReader.php index dcf66fde8..9c7430d10 100644 --- a/src/Behat/Testwork/Environment/Reader/EnvironmentReader.php +++ b/src/Behat/Testwork/Environment/Reader/EnvironmentReader.php @@ -28,7 +28,7 @@ interface EnvironmentReader * * @param Environment $environment * - * @return Boolean + * @return boolean */ public function supportsEnvironment(Environment $environment); diff --git a/src/Behat/Testwork/Exception/Stringer/ExceptionStringer.php b/src/Behat/Testwork/Exception/Stringer/ExceptionStringer.php index eab706186..0a302b006 100644 --- a/src/Behat/Testwork/Exception/Stringer/ExceptionStringer.php +++ b/src/Behat/Testwork/Exception/Stringer/ExceptionStringer.php @@ -27,7 +27,7 @@ interface ExceptionStringer * * @param Exception $exception * - * @return Boolean + * @return boolean */ public function supportsException(Exception $exception); diff --git a/src/Behat/Testwork/Hook/Call/RuntimeSuiteHook.php b/src/Behat/Testwork/Hook/Call/RuntimeSuiteHook.php index 237bc7615..ce9269179 100644 --- a/src/Behat/Testwork/Hook/Call/RuntimeSuiteHook.php +++ b/src/Behat/Testwork/Hook/Call/RuntimeSuiteHook.php @@ -70,7 +70,7 @@ public function filterMatches(HookScope $scope) * @param Suite $suite * @param string $filterString * - * @return Boolean + * @return boolean */ private function isSuiteMatch(Suite $suite, $filterString) { diff --git a/src/Behat/Testwork/Hook/FilterableHook.php b/src/Behat/Testwork/Hook/FilterableHook.php index 48ece6aba..42399f32a 100644 --- a/src/Behat/Testwork/Hook/FilterableHook.php +++ b/src/Behat/Testwork/Hook/FilterableHook.php @@ -24,7 +24,7 @@ interface FilterableHook extends Hook * * @param HookScope $scope * - * @return Boolean + * @return boolean */ public function filterMatches(HookScope $scope); } diff --git a/src/Behat/Testwork/Ordering/OrderedExercise.php b/src/Behat/Testwork/Ordering/OrderedExercise.php index 1cc3055a6..8c4add8cc 100644 --- a/src/Behat/Testwork/Ordering/OrderedExercise.php +++ b/src/Behat/Testwork/Ordering/OrderedExercise.php @@ -58,7 +58,7 @@ public function __construct(Exercise $decoratedExercise) * Sets up exercise for a test. * * @param SpecificationIterator[] $iterators - * @param Boolean $skip + * @param boolean $skip * * @return Setup */ @@ -71,7 +71,7 @@ public function setUp(array $iterators, $skip) * Tests suites specifications. * * @param SpecificationIterator[] $iterators - * @param Boolean $skip + * @param boolean $skip * * @return TestResult */ @@ -84,7 +84,7 @@ public function test(array $iterators, $skip) * Tears down exercise after a test. * * @param SpecificationIterator[] $iterators - * @param Boolean $skip + * @param boolean $skip * @param TestResult $result * * @return Teardown diff --git a/src/Behat/Testwork/Output/Cli/OutputController.php b/src/Behat/Testwork/Output/Cli/OutputController.php index ae886519b..2891f2c7e 100644 --- a/src/Behat/Testwork/Output/Cli/OutputController.php +++ b/src/Behat/Testwork/Output/Cli/OutputController.php @@ -153,7 +153,7 @@ protected function locateOutputPath($path) * * @param array $formats * @param array $outputs - * @param Boolean $decorated + * @param boolean $decorated */ private function configureOutputs(array $formats, array $outputs, $decorated = false) { @@ -184,7 +184,7 @@ private function configureOutputs(array $formats, array $outputs, $decorated = f * * @param string $outputId * - * @return Boolean + * @return boolean */ private function isStandardOutput($outputId) { @@ -196,7 +196,7 @@ private function isStandardOutput($outputId) * * @param string $file A file path * - * @return Boolean + * @return boolean */ private function isAbsolutePath($file) { diff --git a/src/Behat/Testwork/Output/OutputManager.php b/src/Behat/Testwork/Output/OutputManager.php index cdf776018..b26dc28ee 100644 --- a/src/Behat/Testwork/Output/OutputManager.php +++ b/src/Behat/Testwork/Output/OutputManager.php @@ -58,7 +58,7 @@ public function registerFormatter(Formatter $formatter) * * @param string $name * - * @return Boolean + * @return boolean */ public function isFormatterRegistered($name) { diff --git a/src/Behat/Testwork/Output/Printer/Factory/OutputFactory.php b/src/Behat/Testwork/Output/Printer/Factory/OutputFactory.php index 20f47d35a..04b49de7e 100644 --- a/src/Behat/Testwork/Output/Printer/Factory/OutputFactory.php +++ b/src/Behat/Testwork/Output/Printer/Factory/OutputFactory.php @@ -83,7 +83,7 @@ public function getOutputStyles() /** * Forces output to be decorated. * - * @param Boolean $decorated + * @param boolean $decorated */ public function setOutputDecorated($decorated) { diff --git a/src/Behat/Testwork/Output/Printer/OutputPrinter.php b/src/Behat/Testwork/Output/Printer/OutputPrinter.php index 91292d39c..c6f91a6bf 100644 --- a/src/Behat/Testwork/Output/Printer/OutputPrinter.php +++ b/src/Behat/Testwork/Output/Printer/OutputPrinter.php @@ -69,7 +69,7 @@ public function getOutputStyles(); /** * Forces output to be decorated. * - * @param Boolean $decorated + * @param boolean $decorated */ public function setOutputDecorated($decorated); diff --git a/src/Behat/Testwork/ServiceContainer/Configuration/ConfigurationLoader.php b/src/Behat/Testwork/ServiceContainer/Configuration/ConfigurationLoader.php index 33521c10d..5de153e88 100644 --- a/src/Behat/Testwork/ServiceContainer/Configuration/ConfigurationLoader.php +++ b/src/Behat/Testwork/ServiceContainer/Configuration/ConfigurationLoader.php @@ -29,7 +29,7 @@ final class ConfigurationLoader */ private $environmentVariable; /** - * @var Boolean + * @var boolean */ private $profileFound; /** diff --git a/src/Behat/Testwork/Suite/Generator/SuiteGenerator.php b/src/Behat/Testwork/Suite/Generator/SuiteGenerator.php index 876d6b600..a6b1c1b1d 100644 --- a/src/Behat/Testwork/Suite/Generator/SuiteGenerator.php +++ b/src/Behat/Testwork/Suite/Generator/SuiteGenerator.php @@ -28,7 +28,7 @@ interface SuiteGenerator * @param string $type * @param array $settings * - * @return Boolean + * @return boolean */ public function supportsTypeAndSettings($type, array $settings); diff --git a/src/Behat/Testwork/Suite/GenericSuite.php b/src/Behat/Testwork/Suite/GenericSuite.php index 766cffe5b..3111bc0ce 100644 --- a/src/Behat/Testwork/Suite/GenericSuite.php +++ b/src/Behat/Testwork/Suite/GenericSuite.php @@ -65,7 +65,7 @@ public function getSettings() * * @param string $key * - * @return Boolean + * @return boolean */ public function hasSetting($key) { diff --git a/src/Behat/Testwork/Suite/Setup/SuiteSetup.php b/src/Behat/Testwork/Suite/Setup/SuiteSetup.php index 616562434..2dc25da7f 100644 --- a/src/Behat/Testwork/Suite/Setup/SuiteSetup.php +++ b/src/Behat/Testwork/Suite/Setup/SuiteSetup.php @@ -27,7 +27,7 @@ interface SuiteSetup * * @param Suite $suite * - * @return Boolean + * @return boolean */ public function supportsSuite(Suite $suite); diff --git a/src/Behat/Testwork/Suite/Suite.php b/src/Behat/Testwork/Suite/Suite.php index 782f8fd7c..5f2ad3586 100644 --- a/src/Behat/Testwork/Suite/Suite.php +++ b/src/Behat/Testwork/Suite/Suite.php @@ -36,7 +36,7 @@ public function getSettings(); * * @param string $key * - * @return Boolean + * @return boolean */ public function hasSetting($key); diff --git a/src/Behat/Testwork/Suite/SuiteRegistry.php b/src/Behat/Testwork/Suite/SuiteRegistry.php index 5ad98fdcb..ef708fc45 100644 --- a/src/Behat/Testwork/Suite/SuiteRegistry.php +++ b/src/Behat/Testwork/Suite/SuiteRegistry.php @@ -23,7 +23,7 @@ final class SuiteRegistry implements SuiteRepository { /** - * @var Boolean + * @var boolean */ private $suitesGenerated = false; /** diff --git a/src/Behat/Testwork/Tester/Cli/ExerciseController.php b/src/Behat/Testwork/Tester/Cli/ExerciseController.php index b3d2eac5b..e88bbfc6c 100644 --- a/src/Behat/Testwork/Tester/Cli/ExerciseController.php +++ b/src/Behat/Testwork/Tester/Cli/ExerciseController.php @@ -52,7 +52,7 @@ final class ExerciseController implements Controller */ private $resultInterpreter; /** - * @var Boolean + * @var boolean */ private $skip; @@ -63,7 +63,7 @@ final class ExerciseController implements Controller * @param SpecificationFinder $specificationFinder * @param Exercise $exercise * @param ResultInterpreter $resultInterpreter - * @param Boolean $skip + * @param boolean $skip */ public function __construct( SuiteRepository $suiteRepository, diff --git a/src/Behat/Testwork/Tester/Cli/StrictController.php b/src/Behat/Testwork/Tester/Cli/StrictController.php index 1e610be21..6ea5fdac5 100644 --- a/src/Behat/Testwork/Tester/Cli/StrictController.php +++ b/src/Behat/Testwork/Tester/Cli/StrictController.php @@ -30,7 +30,7 @@ final class StrictController implements Controller */ private $resultInterpreter; /** - * @var Boolean + * @var boolean */ private $strict; @@ -38,7 +38,7 @@ final class StrictController implements Controller * Initializes controller. * * @param ResultInterpreter $resultInterpreter - * @param Boolean $strict + * @param boolean $strict */ public function __construct(ResultInterpreter $resultInterpreter, $strict = false) { diff --git a/src/Behat/Testwork/Tester/Exercise.php b/src/Behat/Testwork/Tester/Exercise.php index 6a19c1efb..705cd7d9d 100644 --- a/src/Behat/Testwork/Tester/Exercise.php +++ b/src/Behat/Testwork/Tester/Exercise.php @@ -26,7 +26,7 @@ interface Exercise * Sets up exercise for a test. * * @param SpecificationIterator[] $iterators - * @param Boolean $skip + * @param boolean $skip * * @return Setup */ @@ -36,7 +36,7 @@ public function setUp(array $iterators, $skip); * Tests suites specifications. * * @param SpecificationIterator[] $iterators - * @param Boolean $skip + * @param boolean $skip * * @return TestResult */ @@ -46,7 +46,7 @@ public function test(array $iterators, $skip); * Tears down exercise after a test. * * @param SpecificationIterator[] $iterators - * @param Boolean $skip + * @param boolean $skip * @param TestResult $result * * @return Teardown diff --git a/src/Behat/Testwork/Tester/Result/ExceptionResult.php b/src/Behat/Testwork/Tester/Result/ExceptionResult.php index f30edcf19..a8d4c68d9 100644 --- a/src/Behat/Testwork/Tester/Result/ExceptionResult.php +++ b/src/Behat/Testwork/Tester/Result/ExceptionResult.php @@ -22,7 +22,7 @@ interface ExceptionResult extends TestResult /** * Checks that the test result has exception. * - * @return Boolean + * @return boolean */ public function hasException(); diff --git a/src/Behat/Testwork/Tester/Result/Interpretation/ResultInterpretation.php b/src/Behat/Testwork/Tester/Result/Interpretation/ResultInterpretation.php index 555e75fa8..10b74bf75 100644 --- a/src/Behat/Testwork/Tester/Result/Interpretation/ResultInterpretation.php +++ b/src/Behat/Testwork/Tester/Result/Interpretation/ResultInterpretation.php @@ -27,7 +27,7 @@ interface ResultInterpretation * * @param TestResult $result * - * @return Boolean + * @return boolean */ public function isFailure(TestResult $result); } diff --git a/src/Behat/Testwork/Tester/Result/TestResult.php b/src/Behat/Testwork/Tester/Result/TestResult.php index 9d557965d..b017fff23 100644 --- a/src/Behat/Testwork/Tester/Result/TestResult.php +++ b/src/Behat/Testwork/Tester/Result/TestResult.php @@ -25,7 +25,7 @@ interface TestResult /** * Checks that test has passed. * - * @return Boolean + * @return boolean */ public function isPassed(); diff --git a/src/Behat/Testwork/Tester/ServiceContainer/TesterExtension.php b/src/Behat/Testwork/Tester/ServiceContainer/TesterExtension.php index 55bcfa9da..d81268119 100644 --- a/src/Behat/Testwork/Tester/ServiceContainer/TesterExtension.php +++ b/src/Behat/Testwork/Tester/ServiceContainer/TesterExtension.php @@ -123,7 +123,7 @@ public function process(ContainerBuilder $container) * Loads exercise cli controllers. * * @param ContainerBuilder $container - * @param Boolean $skip + * @param boolean $skip */ protected function loadExerciseController(ContainerBuilder $container, $skip = false) { @@ -142,7 +142,7 @@ protected function loadExerciseController(ContainerBuilder $container, $skip = f * Loads exercise cli controllers. * * @param ContainerBuilder $container - * @param Boolean $strict + * @param boolean $strict */ protected function loadStrictController(ContainerBuilder $container, $strict = false) { diff --git a/src/Behat/Testwork/Tester/Setup/Setup.php b/src/Behat/Testwork/Tester/Setup/Setup.php index e904ebb35..4e83d2558 100644 --- a/src/Behat/Testwork/Tester/Setup/Setup.php +++ b/src/Behat/Testwork/Tester/Setup/Setup.php @@ -20,14 +20,14 @@ interface Setup /** * Returns true if fixtures have been handled successfully. * - * @return Boolean + * @return boolean */ public function isSuccessful(); /** * Checks if setup has produced any output. * - * @return Boolean + * @return boolean */ public function hasOutput(); } diff --git a/src/Behat/Testwork/Tester/Setup/Teardown.php b/src/Behat/Testwork/Tester/Setup/Teardown.php index fbb445b17..0303709c0 100644 --- a/src/Behat/Testwork/Tester/Setup/Teardown.php +++ b/src/Behat/Testwork/Tester/Setup/Teardown.php @@ -20,14 +20,14 @@ interface Teardown /** * Returns true if fixtures have been handled successfully. * - * @return Boolean + * @return boolean */ public function isSuccessful(); /** * Checks if tear down has produced any output. * - * @return Boolean + * @return boolean */ public function hasOutput(); } diff --git a/src/Behat/Testwork/Tester/SpecificationTester.php b/src/Behat/Testwork/Tester/SpecificationTester.php index 9dc106a22..00ac817b0 100644 --- a/src/Behat/Testwork/Tester/SpecificationTester.php +++ b/src/Behat/Testwork/Tester/SpecificationTester.php @@ -27,7 +27,7 @@ interface SpecificationTester * * @param Environment $env * @param mixed $spec - * @param Boolean $skip + * @param boolean $skip * * @return Setup */ @@ -38,7 +38,7 @@ public function setUp(Environment $env, $spec, $skip); * * @param Environment $env * @param mixed $spec - * @param Boolean $skip + * @param boolean $skip * * @return TestResult */ @@ -49,7 +49,7 @@ public function test(Environment $env, $spec, $skip); * * @param Environment $env * @param mixed $spec - * @param Boolean $skip + * @param boolean $skip * @param TestResult $result * * @return Teardown diff --git a/src/Behat/Testwork/Tester/SuiteTester.php b/src/Behat/Testwork/Tester/SuiteTester.php index f139f1a14..532665ae2 100644 --- a/src/Behat/Testwork/Tester/SuiteTester.php +++ b/src/Behat/Testwork/Tester/SuiteTester.php @@ -28,7 +28,7 @@ interface SuiteTester * * @param Environment $env * @param SpecificationIterator $iterator - * @param Boolean $skip + * @param boolean $skip * * @return Setup */ @@ -39,7 +39,7 @@ public function setUp(Environment $env, SpecificationIterator $iterator, $skip); * * @param Environment $env * @param SpecificationIterator $iterator - * @param Boolean $skip + * @param boolean $skip * * @return TestResult */ @@ -50,7 +50,7 @@ public function test(Environment $env, SpecificationIterator $iterator, $skip); * * @param Environment $env * @param SpecificationIterator $iterator - * @param Boolean $skip + * @param boolean $skip * @param TestResult $result * * @return Teardown From 5cec16d9fd3a53ace9220e272e4518bb208296fc Mon Sep 17 00:00:00 2001 From: Witold Wasiczko Date: Wed, 26 Jun 2019 23:35:28 +0200 Subject: [PATCH 164/567] boolean -> bool --- .../Context/Cli/InteractiveContextIdentifier.php | 2 +- .../Context/ContextClass/ClassGenerator.php | 2 +- .../Behat/Context/ContextClass/ClassResolver.php | 2 +- .../Context/Environment/ContextEnvironment.php | 4 ++-- .../Context/Reader/AnnotatedContextReader.php | 6 +++--- .../Snippet/Appender/ContextSnippetAppender.php | 2 +- .../Definition/Pattern/Policy/PatternPolicy.php | 4 ++-- src/Behat/Behat/Definition/SearchResult.php | 2 +- .../EventDispatcher/Event/AfterStepSetup.php | 2 +- .../EventDispatcher/Event/AfterStepTested.php | 8 ++++---- .../EventDispatcher/Event/BeforeStepTeardown.php | 6 +++--- .../Gherkin/Suite/Setup/SuiteWithPathsSetup.php | 2 +- src/Behat/Behat/Hook/Call/RuntimeFeatureHook.php | 6 +++--- .../Behat/Hook/Call/RuntimeScenarioHook.php | 6 +++--- src/Behat/Behat/Hook/Call/RuntimeStepHook.php | 2 +- .../EventListener/AST/OutlineTableListener.php | 2 +- .../Flow/FireOnlySiblingsListener.php | 2 +- .../Flow/FirstBackgroundFiresFirstListener.php | 4 ++-- .../Flow/OnlyFirstBackgroundFiresListener.php | 16 ++++++++-------- .../Node/Printer/Pretty/PrettySetupPrinter.php | 4 ++-- .../Printer/Pretty/PrettySkippedStepPrinter.php | 2 +- .../Node/Printer/Pretty/PrettyStepPrinter.php | 2 +- .../Behat/Snippet/Appender/SnippetAppender.php | 2 +- .../Behat/Snippet/Generator/SnippetGenerator.php | 2 +- src/Behat/Behat/Snippet/SnippetRegistry.php | 2 +- src/Behat/Behat/Tester/BackgroundTester.php | 6 +++--- src/Behat/Behat/Tester/OutlineTester.php | 6 +++--- .../Tester/Runtime/RuntimeScenarioTester.php | 2 +- .../Behat/Tester/Runtime/RuntimeStepTester.php | 2 +- src/Behat/Behat/Tester/ScenarioTester.php | 6 +++--- src/Behat/Behat/Tester/StepContainerTester.php | 2 +- src/Behat/Behat/Tester/StepTester.php | 6 +++--- .../SimpleArgumentTransformation.php | 2 +- .../Transformer/ArgumentTransformer.php | 2 +- .../Testwork/Argument/MixedArgumentOrganiser.php | 14 +++++++------- .../Argument/PregMatchArgumentOrganiser.php | 2 +- src/Behat/Testwork/Call/CallResult.php | 4 ++-- src/Behat/Testwork/Call/CallResults.php | 4 ++-- src/Behat/Testwork/Call/Callee.php | 4 ++-- src/Behat/Testwork/Call/Filter/CallFilter.php | 2 +- src/Behat/Testwork/Call/Filter/ResultFilter.php | 2 +- src/Behat/Testwork/Call/Handler/CallHandler.php | 2 +- .../Testwork/Call/Handler/RuntimeCallHandler.php | 4 ++-- src/Behat/Testwork/Call/RuntimeCallee.php | 4 ++-- .../Environment/Handler/EnvironmentHandler.php | 4 ++-- .../Environment/Reader/EnvironmentReader.php | 2 +- .../Exception/Stringer/ExceptionStringer.php | 2 +- .../Testwork/Hook/Call/RuntimeSuiteHook.php | 2 +- src/Behat/Testwork/Hook/FilterableHook.php | 2 +- src/Behat/Testwork/Ordering/OrderedExercise.php | 6 +++--- .../Testwork/Output/Cli/OutputController.php | 6 +++--- src/Behat/Testwork/Output/OutputManager.php | 2 +- .../Output/Printer/Factory/OutputFactory.php | 2 +- .../Testwork/Output/Printer/OutputPrinter.php | 2 +- .../Configuration/ConfigurationLoader.php | 2 +- .../Testwork/Suite/Generator/SuiteGenerator.php | 2 +- src/Behat/Testwork/Suite/GenericSuite.php | 2 +- src/Behat/Testwork/Suite/Setup/SuiteSetup.php | 2 +- src/Behat/Testwork/Suite/Suite.php | 2 +- src/Behat/Testwork/Suite/SuiteRegistry.php | 2 +- .../Testwork/Tester/Cli/ExerciseController.php | 4 ++-- .../Testwork/Tester/Cli/StrictController.php | 4 ++-- src/Behat/Testwork/Tester/Exercise.php | 6 +++--- .../Testwork/Tester/Result/ExceptionResult.php | 2 +- .../Interpretation/ResultInterpretation.php | 2 +- src/Behat/Testwork/Tester/Result/TestResult.php | 2 +- .../Tester/ServiceContainer/TesterExtension.php | 4 ++-- src/Behat/Testwork/Tester/Setup/Setup.php | 4 ++-- src/Behat/Testwork/Tester/Setup/Teardown.php | 4 ++-- .../Testwork/Tester/SpecificationTester.php | 6 +++--- src/Behat/Testwork/Tester/SuiteTester.php | 6 +++--- 71 files changed, 128 insertions(+), 128 deletions(-) diff --git a/src/Behat/Behat/Context/Cli/InteractiveContextIdentifier.php b/src/Behat/Behat/Context/Cli/InteractiveContextIdentifier.php index 286ffde12..5f3791743 100644 --- a/src/Behat/Behat/Context/Cli/InteractiveContextIdentifier.php +++ b/src/Behat/Behat/Context/Cli/InteractiveContextIdentifier.php @@ -98,7 +98,7 @@ private function askQuestion($message, $choices, $default) /** * Checks if interactive mode is supported. * - * @return boolean + * @return bool * * @deprecated there is a better way to do it - `InputInterface::isInteractive()` method. * Sadly, this doesn't work properly prior Symfony\Console 2.7 and as we need diff --git a/src/Behat/Behat/Context/ContextClass/ClassGenerator.php b/src/Behat/Behat/Context/ContextClass/ClassGenerator.php index 61b3fc1d8..0a7cb5e19 100644 --- a/src/Behat/Behat/Context/ContextClass/ClassGenerator.php +++ b/src/Behat/Behat/Context/ContextClass/ClassGenerator.php @@ -28,7 +28,7 @@ interface ClassGenerator * @param Suite $suite * @param string $contextClass * - * @return boolean + * @return bool */ public function supportsSuiteAndClass(Suite $suite, $contextClass); diff --git a/src/Behat/Behat/Context/ContextClass/ClassResolver.php b/src/Behat/Behat/Context/ContextClass/ClassResolver.php index a97680ee6..dce0f8049 100644 --- a/src/Behat/Behat/Context/ContextClass/ClassResolver.php +++ b/src/Behat/Behat/Context/ContextClass/ClassResolver.php @@ -26,7 +26,7 @@ interface ClassResolver * * @param string $contextString * - * @return boolean + * @return bool */ public function supportsClass($contextString); diff --git a/src/Behat/Behat/Context/Environment/ContextEnvironment.php b/src/Behat/Behat/Context/Environment/ContextEnvironment.php index 90acc4db3..44bcf29b8 100644 --- a/src/Behat/Behat/Context/Environment/ContextEnvironment.php +++ b/src/Behat/Behat/Context/Environment/ContextEnvironment.php @@ -25,7 +25,7 @@ interface ContextEnvironment extends Environment /** * Checks if environment has any contexts registered. * - * @return boolean + * @return bool */ public function hasContexts(); @@ -41,7 +41,7 @@ public function getContextClasses(); * * @param string $class * - * @return boolean + * @return bool */ public function hasContextClass($class); } diff --git a/src/Behat/Behat/Context/Reader/AnnotatedContextReader.php b/src/Behat/Behat/Context/Reader/AnnotatedContextReader.php index 722473f1c..02baea625 100644 --- a/src/Behat/Behat/Context/Reader/AnnotatedContextReader.php +++ b/src/Behat/Behat/Context/Reader/AnnotatedContextReader.php @@ -180,7 +180,7 @@ private function readDescription($docBlock) * * @param string $docLine * - * @return boolean + * @return bool */ private function isEmpty($docLine) { @@ -192,7 +192,7 @@ private function isEmpty($docLine) * * @param string $docLine * - * @return boolean + * @return bool */ private function isNotAnnotation($docLine) { @@ -229,7 +229,7 @@ private function readDocLineCallee($class, ReflectionMethod $method, $docLine, $ * * @param string $docLine * - * @return boolean + * @return bool */ private function isIgnoredAnnotation($docLine) { diff --git a/src/Behat/Behat/Context/Snippet/Appender/ContextSnippetAppender.php b/src/Behat/Behat/Context/Snippet/Appender/ContextSnippetAppender.php index 7af719c36..82e6ec35a 100644 --- a/src/Behat/Behat/Context/Snippet/Appender/ContextSnippetAppender.php +++ b/src/Behat/Behat/Context/Snippet/Appender/ContextSnippetAppender.php @@ -81,7 +81,7 @@ public function appendSnippet(AggregateSnippet $snippet) * @param string $class * @param string $contextFileContent * - * @return boolean + * @return bool */ private function isClassImported($class, $contextFileContent) { diff --git a/src/Behat/Behat/Definition/Pattern/Policy/PatternPolicy.php b/src/Behat/Behat/Definition/Pattern/Policy/PatternPolicy.php index cbad76e50..cd3daac5c 100644 --- a/src/Behat/Behat/Definition/Pattern/Policy/PatternPolicy.php +++ b/src/Behat/Behat/Definition/Pattern/Policy/PatternPolicy.php @@ -27,7 +27,7 @@ interface PatternPolicy * * @param string $type * - * @return boolean + * @return bool */ public function supportsPatternType($type); @@ -45,7 +45,7 @@ public function generatePattern($stepText); * * @param string $pattern * - * @return boolean + * @return bool */ public function supportsPattern($pattern); diff --git a/src/Behat/Behat/Definition/SearchResult.php b/src/Behat/Behat/Definition/SearchResult.php index 512d6c24c..cdb4191ad 100644 --- a/src/Behat/Behat/Definition/SearchResult.php +++ b/src/Behat/Behat/Definition/SearchResult.php @@ -47,7 +47,7 @@ public function __construct(Definition $definition = null, $matchedText = null, /** * Checks if result contains a match. * - * @return boolean + * @return bool */ public function hasMatch() { diff --git a/src/Behat/Behat/EventDispatcher/Event/AfterStepSetup.php b/src/Behat/Behat/EventDispatcher/Event/AfterStepSetup.php index 9eb520fa1..a2256f0c1 100644 --- a/src/Behat/Behat/EventDispatcher/Event/AfterStepSetup.php +++ b/src/Behat/Behat/EventDispatcher/Event/AfterStepSetup.php @@ -86,7 +86,7 @@ public function getSetup() /** * Checks if step call, setup or teardown produced any output (stdOut or exception). * - * @return boolean + * @return bool */ public function hasOutput() { diff --git a/src/Behat/Behat/EventDispatcher/Event/AfterStepTested.php b/src/Behat/Behat/EventDispatcher/Event/AfterStepTested.php index 7ddcd9bdc..d5829b77a 100644 --- a/src/Behat/Behat/EventDispatcher/Event/AfterStepTested.php +++ b/src/Behat/Behat/EventDispatcher/Event/AfterStepTested.php @@ -111,7 +111,7 @@ public function getTeardown() /** * Checks if step call, setup or teardown produced any output (stdOut or exception). * - * @return boolean + * @return bool */ public function hasOutput() { @@ -121,7 +121,7 @@ public function hasOutput() /** * Checks if step teardown has output. * - * @return boolean + * @return bool */ private function teardownHasOutput() { @@ -131,7 +131,7 @@ private function teardownHasOutput() /** * Checks if result has produced exception. * - * @return boolean + * @return bool */ private function resultHasException() { @@ -141,7 +141,7 @@ private function resultHasException() /** * Checks if result is executed and call result has produced exception or stdOut. * - * @return boolean + * @return bool */ private function resultCallHasOutput() { diff --git a/src/Behat/Behat/EventDispatcher/Event/BeforeStepTeardown.php b/src/Behat/Behat/EventDispatcher/Event/BeforeStepTeardown.php index 4bb296ec2..89f626fc5 100644 --- a/src/Behat/Behat/EventDispatcher/Event/BeforeStepTeardown.php +++ b/src/Behat/Behat/EventDispatcher/Event/BeforeStepTeardown.php @@ -93,7 +93,7 @@ public function getTestResult() /** * Checks if step call produced any output (stdOut or exception). * - * @return boolean + * @return bool */ public function hasOutput() { @@ -103,7 +103,7 @@ public function hasOutput() /** * Checks if result has produced exception. * - * @return boolean + * @return bool */ private function resultHasException() { @@ -113,7 +113,7 @@ private function resultHasException() /** * Checks if result is executed and call result has produced exception or stdOut. * - * @return boolean + * @return bool */ private function resultCallHasOutput() { diff --git a/src/Behat/Behat/Gherkin/Suite/Setup/SuiteWithPathsSetup.php b/src/Behat/Behat/Gherkin/Suite/Setup/SuiteWithPathsSetup.php index 5147d4f11..f50249f6e 100644 --- a/src/Behat/Behat/Gherkin/Suite/Setup/SuiteWithPathsSetup.php +++ b/src/Behat/Behat/Gherkin/Suite/Setup/SuiteWithPathsSetup.php @@ -97,7 +97,7 @@ private function locatePath($path) * * @param string $file A file path * - * @return boolean + * @return bool */ private function isAbsolutePath($file) { diff --git a/src/Behat/Behat/Hook/Call/RuntimeFeatureHook.php b/src/Behat/Behat/Hook/Call/RuntimeFeatureHook.php index 8b3ca5348..9bc9a554f 100644 --- a/src/Behat/Behat/Hook/Call/RuntimeFeatureHook.php +++ b/src/Behat/Behat/Hook/Call/RuntimeFeatureHook.php @@ -68,7 +68,7 @@ public function filterMatches(HookScope $scope) * @param FeatureNode $feature * @param string $filterString * - * @return boolean + * @return bool */ private function isMatch(FeatureNode $feature, $filterString) { @@ -89,7 +89,7 @@ private function isMatch(FeatureNode $feature, $filterString) * @param FeatureNode $feature * @param string $filterString * - * @return boolean + * @return bool */ private function isMatchTagFilter(FeatureNode $feature, $filterString) { @@ -104,7 +104,7 @@ private function isMatchTagFilter(FeatureNode $feature, $filterString) * @param FeatureNode $feature * @param string $filterString * - * @return boolean + * @return bool */ private function isMatchNameFilter(FeatureNode $feature, $filterString) { diff --git a/src/Behat/Behat/Hook/Call/RuntimeScenarioHook.php b/src/Behat/Behat/Hook/Call/RuntimeScenarioHook.php index 9bb6bbb8c..d8a401d48 100644 --- a/src/Behat/Behat/Hook/Call/RuntimeScenarioHook.php +++ b/src/Behat/Behat/Hook/Call/RuntimeScenarioHook.php @@ -48,7 +48,7 @@ public function filterMatches(HookScope $scope) * @param ScenarioInterface $scenario * @param string $filterString * - * @return boolean + * @return bool */ protected function isMatch(FeatureNode $feature, ScenarioInterface $scenario, $filterString) { @@ -70,7 +70,7 @@ protected function isMatch(FeatureNode $feature, ScenarioInterface $scenario, $f * @param ScenarioInterface $scenario * @param string $filterString * - * @return boolean + * @return bool */ protected function isMatchTagFilter(FeatureNode $feature, ScenarioInterface $scenario, $filterString) { @@ -89,7 +89,7 @@ protected function isMatchTagFilter(FeatureNode $feature, ScenarioInterface $sce * @param ScenarioInterface $scenario * @param string $filterString * - * @return boolean + * @return bool */ protected function isMatchNameFilter(ScenarioInterface $scenario, $filterString) { diff --git a/src/Behat/Behat/Hook/Call/RuntimeStepHook.php b/src/Behat/Behat/Hook/Call/RuntimeStepHook.php index 57ea7641b..401e3ccdf 100644 --- a/src/Behat/Behat/Hook/Call/RuntimeStepHook.php +++ b/src/Behat/Behat/Hook/Call/RuntimeStepHook.php @@ -55,7 +55,7 @@ public function filterMatches(HookScope $scope) * @param StepNode $step * @param string $filterString * - * @return boolean + * @return bool */ private function isStepMatch(StepNode $step, $filterString) { diff --git a/src/Behat/Behat/Output/Node/EventListener/AST/OutlineTableListener.php b/src/Behat/Behat/Output/Node/EventListener/AST/OutlineTableListener.php index 490dfbbb5..9882b7c64 100644 --- a/src/Behat/Behat/Output/Node/EventListener/AST/OutlineTableListener.php +++ b/src/Behat/Behat/Output/Node/EventListener/AST/OutlineTableListener.php @@ -61,7 +61,7 @@ final class OutlineTableListener implements EventListener */ private $exampleSetup; /** - * @var boolean + * @var bool */ private $headerPrinted = false; /** diff --git a/src/Behat/Behat/Output/Node/EventListener/Flow/FireOnlySiblingsListener.php b/src/Behat/Behat/Output/Node/EventListener/Flow/FireOnlySiblingsListener.php index 44db35bb8..0a4c85674 100644 --- a/src/Behat/Behat/Output/Node/EventListener/Flow/FireOnlySiblingsListener.php +++ b/src/Behat/Behat/Output/Node/EventListener/Flow/FireOnlySiblingsListener.php @@ -37,7 +37,7 @@ class FireOnlySiblingsListener implements EventListener */ private $descendant; /** - * @var boolean + * @var bool */ private $inContext = false; diff --git a/src/Behat/Behat/Output/Node/EventListener/Flow/FirstBackgroundFiresFirstListener.php b/src/Behat/Behat/Output/Node/EventListener/Flow/FirstBackgroundFiresFirstListener.php index b63824d6a..271b8e580 100644 --- a/src/Behat/Behat/Output/Node/EventListener/Flow/FirstBackgroundFiresFirstListener.php +++ b/src/Behat/Behat/Output/Node/EventListener/Flow/FirstBackgroundFiresFirstListener.php @@ -34,7 +34,7 @@ class FirstBackgroundFiresFirstListener implements EventListener */ private $descendant; /** - * @var boolean + * @var bool */ private $firstBackgroundEnded = false; /** @@ -103,7 +103,7 @@ private function markFirstBackgroundPrintedAfterBackground($eventName) * * @param Event $event * - * @return boolean + * @return bool */ private function isEventDelayedUntilFirstBackgroundPrinted(Event $event) { diff --git a/src/Behat/Behat/Output/Node/EventListener/Flow/OnlyFirstBackgroundFiresListener.php b/src/Behat/Behat/Output/Node/EventListener/Flow/OnlyFirstBackgroundFiresListener.php index 4a0278c06..2af5ba2d9 100644 --- a/src/Behat/Behat/Output/Node/EventListener/Flow/OnlyFirstBackgroundFiresListener.php +++ b/src/Behat/Behat/Output/Node/EventListener/Flow/OnlyFirstBackgroundFiresListener.php @@ -36,15 +36,15 @@ class OnlyFirstBackgroundFiresListener implements EventListener */ private $descendant; /** - * @var boolean + * @var bool */ private $firstBackgroundEnded = false; /** - * @var boolean + * @var bool */ private $inBackground = false; /** - * @var boolean + * @var bool */ private $stepSetupHadOutput = false; @@ -125,7 +125,7 @@ private function markFirstBackgroundPrintedAfterBackground($eventName) * * @param Event $event * - * @return boolean + * @return bool */ private function isSkippableEvent(Event $event) { @@ -141,7 +141,7 @@ private function isSkippableEvent(Event $event) * * @param Event $event * - * @return boolean + * @return bool */ private function isNonFailingConsequentBackgroundStep(Event $event) { @@ -157,7 +157,7 @@ private function isNonFailingConsequentBackgroundStep(Event $event) * * @param Event $event * - * @return boolean + * @return bool */ private function isStepEventWithOutput(Event $event) { @@ -169,7 +169,7 @@ private function isStepEventWithOutput(Event $event) * * @param Event $event * - * @return boolean + * @return bool */ private function isBeforeStepEventWithOutput(Event $event) { @@ -187,7 +187,7 @@ private function isBeforeStepEventWithOutput(Event $event) * * @param Event $event * - * @return boolean + * @return bool */ private function isAfterStepWithOutput(Event $event) { diff --git a/src/Behat/Behat/Output/Node/Printer/Pretty/PrettySetupPrinter.php b/src/Behat/Behat/Output/Node/Printer/Pretty/PrettySetupPrinter.php index 09e900788..5475f51fe 100644 --- a/src/Behat/Behat/Output/Node/Printer/Pretty/PrettySetupPrinter.php +++ b/src/Behat/Behat/Output/Node/Printer/Pretty/PrettySetupPrinter.php @@ -56,8 +56,8 @@ final class PrettySetupPrinter implements SetupPrinter * @param ResultToStringConverter $resultConverter * @param ExceptionPresenter $exceptionPresenter * @param integer $indentation - * @param boolean $newlineBefore - * @param boolean $newlineAfter + * @param bool $newlineBefore + * @param bool $newlineAfter */ public function __construct( ResultToStringConverter $resultConverter, diff --git a/src/Behat/Behat/Output/Node/Printer/Pretty/PrettySkippedStepPrinter.php b/src/Behat/Behat/Output/Node/Printer/Pretty/PrettySkippedStepPrinter.php index 2ec682556..b8c8d464a 100644 --- a/src/Behat/Behat/Output/Node/Printer/Pretty/PrettySkippedStepPrinter.php +++ b/src/Behat/Behat/Output/Node/Printer/Pretty/PrettySkippedStepPrinter.php @@ -129,7 +129,7 @@ private function printArguments(Formatter $formatter, array $arguments) * Returns argument string for provided argument. * * @param ArgumentInterface $argument - * @param boolean $collapse + * @param bool $collapse * * @return string */ diff --git a/src/Behat/Behat/Output/Node/Printer/Pretty/PrettyStepPrinter.php b/src/Behat/Behat/Output/Node/Printer/Pretty/PrettyStepPrinter.php index 9604c1021..ee2e5d09e 100644 --- a/src/Behat/Behat/Output/Node/Printer/Pretty/PrettyStepPrinter.php +++ b/src/Behat/Behat/Output/Node/Printer/Pretty/PrettyStepPrinter.php @@ -180,7 +180,7 @@ private function printException(OutputPrinter $printer, StepResult $result) * Returns argument string for provided argument. * * @param ArgumentInterface $argument - * @param boolean $collapse + * @param bool $collapse * * @return string */ diff --git a/src/Behat/Behat/Snippet/Appender/SnippetAppender.php b/src/Behat/Behat/Snippet/Appender/SnippetAppender.php index e78d6bea4..863d88fb3 100644 --- a/src/Behat/Behat/Snippet/Appender/SnippetAppender.php +++ b/src/Behat/Behat/Snippet/Appender/SnippetAppender.php @@ -27,7 +27,7 @@ interface SnippetAppender * * @param AggregateSnippet $snippet * - * @return boolean + * @return bool */ public function supportsSnippet(AggregateSnippet $snippet); diff --git a/src/Behat/Behat/Snippet/Generator/SnippetGenerator.php b/src/Behat/Behat/Snippet/Generator/SnippetGenerator.php index 5e68af1fe..09bbd1164 100644 --- a/src/Behat/Behat/Snippet/Generator/SnippetGenerator.php +++ b/src/Behat/Behat/Snippet/Generator/SnippetGenerator.php @@ -30,7 +30,7 @@ interface SnippetGenerator * @param Environment $environment * @param StepNode $step * - * @return boolean + * @return bool */ public function supportsEnvironmentAndStep(Environment $environment, StepNode $step); diff --git a/src/Behat/Behat/Snippet/SnippetRegistry.php b/src/Behat/Behat/Snippet/SnippetRegistry.php index 6bdbbebf7..7b9257263 100644 --- a/src/Behat/Behat/Snippet/SnippetRegistry.php +++ b/src/Behat/Behat/Snippet/SnippetRegistry.php @@ -34,7 +34,7 @@ final class SnippetRegistry implements SnippetRepository */ private $snippets = array(); /** - * @var boolean + * @var bool */ private $snippetsGenerated = false; diff --git a/src/Behat/Behat/Tester/BackgroundTester.php b/src/Behat/Behat/Tester/BackgroundTester.php index 4a8c823ec..10086c76c 100644 --- a/src/Behat/Behat/Tester/BackgroundTester.php +++ b/src/Behat/Behat/Tester/BackgroundTester.php @@ -28,7 +28,7 @@ interface BackgroundTester * * @param Environment $env * @param FeatureNode $feature - * @param boolean $skip + * @param bool $skip * * @return Setup */ @@ -39,7 +39,7 @@ public function setUp(Environment $env, FeatureNode $feature, $skip); * * @param Environment $env * @param FeatureNode $feature - * @param boolean $skip + * @param bool $skip * * @return TestResult */ @@ -50,7 +50,7 @@ public function test(Environment $env, FeatureNode $feature, $skip); * * @param Environment $env * @param FeatureNode $feature - * @param boolean $skip + * @param bool $skip * @param TestResult $result * * @return Teardown diff --git a/src/Behat/Behat/Tester/OutlineTester.php b/src/Behat/Behat/Tester/OutlineTester.php index 144f1caf4..43b45e62f 100644 --- a/src/Behat/Behat/Tester/OutlineTester.php +++ b/src/Behat/Behat/Tester/OutlineTester.php @@ -30,7 +30,7 @@ interface OutlineTester * @param Environment $env * @param FeatureNode $feature * @param OutlineNode $outline - * @param boolean $skip + * @param bool $skip * * @return Setup */ @@ -42,7 +42,7 @@ public function setUp(Environment $env, FeatureNode $feature, OutlineNode $outli * @param Environment $env * @param FeatureNode $feature * @param OutlineNode $outline - * @param boolean $skip + * @param bool $skip * * @return TestResult */ @@ -54,7 +54,7 @@ public function test(Environment $env, FeatureNode $feature, OutlineNode $outlin * @param Environment $env * @param FeatureNode $feature * @param OutlineNode $outline - * @param boolean $skip + * @param bool $skip * @param TestResult $result * * @return Teardown diff --git a/src/Behat/Behat/Tester/Runtime/RuntimeScenarioTester.php b/src/Behat/Behat/Tester/Runtime/RuntimeScenarioTester.php index 47ec35f1b..08b8ca951 100644 --- a/src/Behat/Behat/Tester/Runtime/RuntimeScenarioTester.php +++ b/src/Behat/Behat/Tester/Runtime/RuntimeScenarioTester.php @@ -91,7 +91,7 @@ public function tearDown(Environment $env, FeatureNode $feature, Scenario $scena * * @param Environment $env * @param FeatureNode $feature - * @param boolean $skip + * @param bool $skip * * @return TestResult */ diff --git a/src/Behat/Behat/Tester/Runtime/RuntimeStepTester.php b/src/Behat/Behat/Tester/Runtime/RuntimeStepTester.php index 82e76c144..46959f6de 100644 --- a/src/Behat/Behat/Tester/Runtime/RuntimeStepTester.php +++ b/src/Behat/Behat/Tester/Runtime/RuntimeStepTester.php @@ -107,7 +107,7 @@ private function searchDefinition(Environment $env, FeatureNode $feature, StepNo * @param FeatureNode $feature * @param StepNode $step * @param SearchResult $search - * @param boolean $skip + * @param bool $skip * * @return StepResult */ diff --git a/src/Behat/Behat/Tester/ScenarioTester.php b/src/Behat/Behat/Tester/ScenarioTester.php index ae3baef5e..601e4f67a 100644 --- a/src/Behat/Behat/Tester/ScenarioTester.php +++ b/src/Behat/Behat/Tester/ScenarioTester.php @@ -30,7 +30,7 @@ interface ScenarioTester * @param Environment $env * @param FeatureNode $feature * @param Scenario $scenario - * @param boolean $skip + * @param bool $skip * * @return Setup */ @@ -42,7 +42,7 @@ public function setUp(Environment $env, FeatureNode $feature, Scenario $scenario * @param Environment $env * @param FeatureNode $feature * @param Scenario $scenario - * @param boolean $skip + * @param bool $skip * * @return TestResult */ @@ -54,7 +54,7 @@ public function test(Environment $env, FeatureNode $feature, Scenario $scenario, * @param Environment $env * @param FeatureNode $feature * @param Scenario $scenario - * @param boolean $skip + * @param bool $skip * @param TestResult $result * * @return Teardown diff --git a/src/Behat/Behat/Tester/StepContainerTester.php b/src/Behat/Behat/Tester/StepContainerTester.php index a78ac1003..d7364a9bc 100644 --- a/src/Behat/Behat/Tester/StepContainerTester.php +++ b/src/Behat/Behat/Tester/StepContainerTester.php @@ -45,7 +45,7 @@ public function __construct(StepTester $stepTester) * @param Environment $env * @param FeatureNode $feature * @param StepContainerInterface $container - * @param boolean $skip + * @param bool $skip * * @return TestResult[] */ diff --git a/src/Behat/Behat/Tester/StepTester.php b/src/Behat/Behat/Tester/StepTester.php index 7ffd7b35b..94d735778 100644 --- a/src/Behat/Behat/Tester/StepTester.php +++ b/src/Behat/Behat/Tester/StepTester.php @@ -30,7 +30,7 @@ interface StepTester * @param Environment $env * @param FeatureNode $feature * @param StepNode $step - * @param boolean $skip + * @param bool $skip * * @return Setup */ @@ -42,7 +42,7 @@ public function setUp(Environment $env, FeatureNode $feature, StepNode $step, $s * @param Environment $env * @param FeatureNode $feature * @param StepNode $step - * @param boolean $skip + * @param bool $skip * * @return StepResult */ @@ -54,7 +54,7 @@ public function test(Environment $env, FeatureNode $feature, StepNode $step, $sk * @param Environment $env * @param FeatureNode $feature * @param StepNode $step - * @param boolean $skip + * @param bool $skip * @param StepResult $result * * @return Teardown diff --git a/src/Behat/Behat/Transformation/SimpleArgumentTransformation.php b/src/Behat/Behat/Transformation/SimpleArgumentTransformation.php index c8a71a6e4..16530c3f7 100644 --- a/src/Behat/Behat/Transformation/SimpleArgumentTransformation.php +++ b/src/Behat/Behat/Transformation/SimpleArgumentTransformation.php @@ -45,7 +45,7 @@ public function getPriority(); * @param integer|string $argumentIndex * @param mixed $argumentValue * - * @return boolean + * @return bool */ public function supportsDefinitionAndArgument(DefinitionCall $definitionCall, $argumentIndex, $argumentValue); diff --git a/src/Behat/Behat/Transformation/Transformer/ArgumentTransformer.php b/src/Behat/Behat/Transformation/Transformer/ArgumentTransformer.php index f49be2dcd..4457d838b 100644 --- a/src/Behat/Behat/Transformation/Transformer/ArgumentTransformer.php +++ b/src/Behat/Behat/Transformation/Transformer/ArgumentTransformer.php @@ -26,7 +26,7 @@ interface ArgumentTransformer * @param integer|string $argumentIndex * @param mixed $argumentValue * - * @return boolean + * @return bool */ public function supportsDefinitionAndArgument(DefinitionCall $definitionCall, $argumentIndex, $argumentValue); diff --git a/src/Behat/Testwork/Argument/MixedArgumentOrganiser.php b/src/Behat/Testwork/Argument/MixedArgumentOrganiser.php index d21e8bd5d..6acea5fdd 100644 --- a/src/Behat/Testwork/Argument/MixedArgumentOrganiser.php +++ b/src/Behat/Testwork/Argument/MixedArgumentOrganiser.php @@ -99,7 +99,7 @@ function (ReflectionParameter $parameter) { * @param mixed $argumentKey * @param string[] $parameterNames * - * @return boolean + * @return bool */ private function isStringKeyAndExistsInParameters($argumentKey, $parameterNames) { @@ -112,7 +112,7 @@ private function isStringKeyAndExistsInParameters($argumentKey, $parameterNames) * @param ReflectionParameter[] $parameters * @param mixed $value * - * @return boolean + * @return bool */ private function isParameterTypehintedInArgumentList(array $parameters, $value) { @@ -135,7 +135,7 @@ private function isParameterTypehintedInArgumentList(array $parameters, $value) * @param object $value * @param ReflectionParameter $parameter * - * @return boolean + * @return bool */ private function isValueMatchesTypehintedParameter($value, ReflectionParameter $parameter) { @@ -274,7 +274,7 @@ private function applyPredicateToTypehintedArguments( * @param mixed[] &$candidates Resolved arguments * @param mixed[] &$arguments Argument mapping * @param callable $predicate Callable predicate to apply to each candidate - * @return boolean Returns true if a candidate has been matched to the given parameter, otherwise false + * @return bool Returns true if a candidate has been matched to the given parameter, otherwise false */ public function matchParameterToCandidateUsingPredicate( ReflectionParameter $parameter, @@ -304,7 +304,7 @@ public function matchParameterToCandidateUsingPredicate( * * @param ReflectionClass $reflectionClass Typehinted argument * @param mixed $candidate Resolved argument - * @return boolean + * @return bool */ private function classMatchingPredicateForTypehintedArguments(ReflectionClass $reflectionClass, $candidate) { @@ -316,7 +316,7 @@ private function classMatchingPredicateForTypehintedArguments(ReflectionClass $r * * @param ReflectionClass $reflectionClass Typehinted argument * @param mixed $candidate Resolved argument - * @return boolean + * @return bool */ private function isInstancePredicateForTypehintedArguments(ReflectionClass $reflectionClass, $candidate) { @@ -425,7 +425,7 @@ private function markArgumentDefined($position) * * @param integer $position * - * @return boolean + * @return bool */ private function isArgumentDefined($position) { diff --git a/src/Behat/Testwork/Argument/PregMatchArgumentOrganiser.php b/src/Behat/Testwork/Argument/PregMatchArgumentOrganiser.php index a49d3920a..8a03b884f 100644 --- a/src/Behat/Testwork/Argument/PregMatchArgumentOrganiser.php +++ b/src/Behat/Testwork/Argument/PregMatchArgumentOrganiser.php @@ -81,7 +81,7 @@ private function cleanupMatchDuplicates(array $match) * @param integer $keyIndex * @param mixed[] $keys * - * @return boolean + * @return bool */ private function isKeyAStringAndNexOneIsAnInteger($keyIndex, array $keys) { diff --git a/src/Behat/Testwork/Call/CallResult.php b/src/Behat/Testwork/Call/CallResult.php index 6bb4c69ec..924ce0d8a 100644 --- a/src/Behat/Testwork/Call/CallResult.php +++ b/src/Behat/Testwork/Call/CallResult.php @@ -75,7 +75,7 @@ public function getReturn() /** * Check if call thrown exception. * - * @return boolean + * @return bool */ public function hasException() { @@ -95,7 +95,7 @@ public function getException() /** * Checks if call produced stdOut. * - * @return boolean + * @return bool */ public function hasStdOut() { diff --git a/src/Behat/Testwork/Call/CallResults.php b/src/Behat/Testwork/Call/CallResults.php index bd0048872..d1aeeda57 100644 --- a/src/Behat/Testwork/Call/CallResults.php +++ b/src/Behat/Testwork/Call/CallResults.php @@ -53,7 +53,7 @@ public static function merge(CallResults $first, CallResults $second) /** * Checks if any call in collection throws an exception. * - * @return boolean + * @return bool */ public function hasExceptions() { @@ -69,7 +69,7 @@ public function hasExceptions() /** * Checks if any call in collection produces an output. * - * @return boolean + * @return bool */ public function hasStdOuts() { diff --git a/src/Behat/Testwork/Call/Callee.php b/src/Behat/Testwork/Call/Callee.php index 240d8d5c1..17ed0f5cc 100644 --- a/src/Behat/Testwork/Call/Callee.php +++ b/src/Behat/Testwork/Call/Callee.php @@ -36,14 +36,14 @@ public function getDescription(); /** * Returns true if callee is a method, false otherwise. * - * @return boolean + * @return bool */ public function isAMethod(); /** * Returns true if callee is an instance (non-static) method, false otherwise. * - * @return boolean + * @return bool */ public function isAnInstanceMethod(); diff --git a/src/Behat/Testwork/Call/Filter/CallFilter.php b/src/Behat/Testwork/Call/Filter/CallFilter.php index 7565d8af2..1519823db 100644 --- a/src/Behat/Testwork/Call/Filter/CallFilter.php +++ b/src/Behat/Testwork/Call/Filter/CallFilter.php @@ -27,7 +27,7 @@ interface CallFilter * * @param Call $call * - * @return boolean + * @return bool */ public function supportsCall(Call $call); diff --git a/src/Behat/Testwork/Call/Filter/ResultFilter.php b/src/Behat/Testwork/Call/Filter/ResultFilter.php index 66dabef18..02267029a 100644 --- a/src/Behat/Testwork/Call/Filter/ResultFilter.php +++ b/src/Behat/Testwork/Call/Filter/ResultFilter.php @@ -27,7 +27,7 @@ interface ResultFilter * * @param CallResult $result * - * @return boolean + * @return bool */ public function supportsResult(CallResult $result); diff --git a/src/Behat/Testwork/Call/Handler/CallHandler.php b/src/Behat/Testwork/Call/Handler/CallHandler.php index 78c6df57b..93966130d 100644 --- a/src/Behat/Testwork/Call/Handler/CallHandler.php +++ b/src/Behat/Testwork/Call/Handler/CallHandler.php @@ -28,7 +28,7 @@ interface CallHandler * * @param Call $call * - * @return boolean + * @return bool */ public function supportsCall(Call $call); diff --git a/src/Behat/Testwork/Call/Handler/RuntimeCallHandler.php b/src/Behat/Testwork/Call/Handler/RuntimeCallHandler.php index 8f09a406f..7db716556 100644 --- a/src/Behat/Testwork/Call/Handler/RuntimeCallHandler.php +++ b/src/Behat/Testwork/Call/Handler/RuntimeCallHandler.php @@ -77,7 +77,7 @@ public function handleCall(Call $call) * @param string $file * @param integer $line * - * @return boolean + * @return bool * * @throws CallErrorException */ @@ -154,7 +154,7 @@ private function stopErrorAndOutputBuffering() * * @param integer $level * - * @return boolean + * @return bool */ private function errorLevelIsNotReportable($level) { diff --git a/src/Behat/Testwork/Call/RuntimeCallee.php b/src/Behat/Testwork/Call/RuntimeCallee.php index 710697a82..fa232f836 100644 --- a/src/Behat/Testwork/Call/RuntimeCallee.php +++ b/src/Behat/Testwork/Call/RuntimeCallee.php @@ -112,7 +112,7 @@ public function getReflection() /** * Returns true if callee is a method, false otherwise. * - * @return boolean + * @return bool */ public function isAMethod() { @@ -122,7 +122,7 @@ public function isAMethod() /** * Returns true if callee is an instance (non-static) method, false otherwise. * - * @return boolean + * @return bool */ public function isAnInstanceMethod() { diff --git a/src/Behat/Testwork/Environment/Handler/EnvironmentHandler.php b/src/Behat/Testwork/Environment/Handler/EnvironmentHandler.php index 062de8f78..1b4358919 100644 --- a/src/Behat/Testwork/Environment/Handler/EnvironmentHandler.php +++ b/src/Behat/Testwork/Environment/Handler/EnvironmentHandler.php @@ -28,7 +28,7 @@ interface EnvironmentHandler * * @param Suite $suite * - * @return boolean + * @return bool */ public function supportsSuite(Suite $suite); @@ -47,7 +47,7 @@ public function buildEnvironment(Suite $suite); * @param Environment $environment * @param mixed $testSubject * - * @return boolean + * @return bool */ public function supportsEnvironmentAndSubject(Environment $environment, $testSubject = null); diff --git a/src/Behat/Testwork/Environment/Reader/EnvironmentReader.php b/src/Behat/Testwork/Environment/Reader/EnvironmentReader.php index 9c7430d10..39cd46724 100644 --- a/src/Behat/Testwork/Environment/Reader/EnvironmentReader.php +++ b/src/Behat/Testwork/Environment/Reader/EnvironmentReader.php @@ -28,7 +28,7 @@ interface EnvironmentReader * * @param Environment $environment * - * @return boolean + * @return bool */ public function supportsEnvironment(Environment $environment); diff --git a/src/Behat/Testwork/Exception/Stringer/ExceptionStringer.php b/src/Behat/Testwork/Exception/Stringer/ExceptionStringer.php index 0a302b006..5f8de153c 100644 --- a/src/Behat/Testwork/Exception/Stringer/ExceptionStringer.php +++ b/src/Behat/Testwork/Exception/Stringer/ExceptionStringer.php @@ -27,7 +27,7 @@ interface ExceptionStringer * * @param Exception $exception * - * @return boolean + * @return bool */ public function supportsException(Exception $exception); diff --git a/src/Behat/Testwork/Hook/Call/RuntimeSuiteHook.php b/src/Behat/Testwork/Hook/Call/RuntimeSuiteHook.php index ce9269179..44b7f6573 100644 --- a/src/Behat/Testwork/Hook/Call/RuntimeSuiteHook.php +++ b/src/Behat/Testwork/Hook/Call/RuntimeSuiteHook.php @@ -70,7 +70,7 @@ public function filterMatches(HookScope $scope) * @param Suite $suite * @param string $filterString * - * @return boolean + * @return bool */ private function isSuiteMatch(Suite $suite, $filterString) { diff --git a/src/Behat/Testwork/Hook/FilterableHook.php b/src/Behat/Testwork/Hook/FilterableHook.php index 42399f32a..a241ff816 100644 --- a/src/Behat/Testwork/Hook/FilterableHook.php +++ b/src/Behat/Testwork/Hook/FilterableHook.php @@ -24,7 +24,7 @@ interface FilterableHook extends Hook * * @param HookScope $scope * - * @return boolean + * @return bool */ public function filterMatches(HookScope $scope); } diff --git a/src/Behat/Testwork/Ordering/OrderedExercise.php b/src/Behat/Testwork/Ordering/OrderedExercise.php index 8c4add8cc..aba9ba894 100644 --- a/src/Behat/Testwork/Ordering/OrderedExercise.php +++ b/src/Behat/Testwork/Ordering/OrderedExercise.php @@ -58,7 +58,7 @@ public function __construct(Exercise $decoratedExercise) * Sets up exercise for a test. * * @param SpecificationIterator[] $iterators - * @param boolean $skip + * @param bool $skip * * @return Setup */ @@ -71,7 +71,7 @@ public function setUp(array $iterators, $skip) * Tests suites specifications. * * @param SpecificationIterator[] $iterators - * @param boolean $skip + * @param bool $skip * * @return TestResult */ @@ -84,7 +84,7 @@ public function test(array $iterators, $skip) * Tears down exercise after a test. * * @param SpecificationIterator[] $iterators - * @param boolean $skip + * @param bool $skip * @param TestResult $result * * @return Teardown diff --git a/src/Behat/Testwork/Output/Cli/OutputController.php b/src/Behat/Testwork/Output/Cli/OutputController.php index 2891f2c7e..bf8f94488 100644 --- a/src/Behat/Testwork/Output/Cli/OutputController.php +++ b/src/Behat/Testwork/Output/Cli/OutputController.php @@ -153,7 +153,7 @@ protected function locateOutputPath($path) * * @param array $formats * @param array $outputs - * @param boolean $decorated + * @param bool $decorated */ private function configureOutputs(array $formats, array $outputs, $decorated = false) { @@ -184,7 +184,7 @@ private function configureOutputs(array $formats, array $outputs, $decorated = f * * @param string $outputId * - * @return boolean + * @return bool */ private function isStandardOutput($outputId) { @@ -196,7 +196,7 @@ private function isStandardOutput($outputId) * * @param string $file A file path * - * @return boolean + * @return bool */ private function isAbsolutePath($file) { diff --git a/src/Behat/Testwork/Output/OutputManager.php b/src/Behat/Testwork/Output/OutputManager.php index b26dc28ee..ede7b574f 100644 --- a/src/Behat/Testwork/Output/OutputManager.php +++ b/src/Behat/Testwork/Output/OutputManager.php @@ -58,7 +58,7 @@ public function registerFormatter(Formatter $formatter) * * @param string $name * - * @return boolean + * @return bool */ public function isFormatterRegistered($name) { diff --git a/src/Behat/Testwork/Output/Printer/Factory/OutputFactory.php b/src/Behat/Testwork/Output/Printer/Factory/OutputFactory.php index 04b49de7e..6571555ee 100644 --- a/src/Behat/Testwork/Output/Printer/Factory/OutputFactory.php +++ b/src/Behat/Testwork/Output/Printer/Factory/OutputFactory.php @@ -83,7 +83,7 @@ public function getOutputStyles() /** * Forces output to be decorated. * - * @param boolean $decorated + * @param bool $decorated */ public function setOutputDecorated($decorated) { diff --git a/src/Behat/Testwork/Output/Printer/OutputPrinter.php b/src/Behat/Testwork/Output/Printer/OutputPrinter.php index c6f91a6bf..56fe45793 100644 --- a/src/Behat/Testwork/Output/Printer/OutputPrinter.php +++ b/src/Behat/Testwork/Output/Printer/OutputPrinter.php @@ -69,7 +69,7 @@ public function getOutputStyles(); /** * Forces output to be decorated. * - * @param boolean $decorated + * @param bool $decorated */ public function setOutputDecorated($decorated); diff --git a/src/Behat/Testwork/ServiceContainer/Configuration/ConfigurationLoader.php b/src/Behat/Testwork/ServiceContainer/Configuration/ConfigurationLoader.php index 5de153e88..dfc02eb4d 100644 --- a/src/Behat/Testwork/ServiceContainer/Configuration/ConfigurationLoader.php +++ b/src/Behat/Testwork/ServiceContainer/Configuration/ConfigurationLoader.php @@ -29,7 +29,7 @@ final class ConfigurationLoader */ private $environmentVariable; /** - * @var boolean + * @var bool */ private $profileFound; /** diff --git a/src/Behat/Testwork/Suite/Generator/SuiteGenerator.php b/src/Behat/Testwork/Suite/Generator/SuiteGenerator.php index a6b1c1b1d..5d8934683 100644 --- a/src/Behat/Testwork/Suite/Generator/SuiteGenerator.php +++ b/src/Behat/Testwork/Suite/Generator/SuiteGenerator.php @@ -28,7 +28,7 @@ interface SuiteGenerator * @param string $type * @param array $settings * - * @return boolean + * @return bool */ public function supportsTypeAndSettings($type, array $settings); diff --git a/src/Behat/Testwork/Suite/GenericSuite.php b/src/Behat/Testwork/Suite/GenericSuite.php index 3111bc0ce..1c6702b61 100644 --- a/src/Behat/Testwork/Suite/GenericSuite.php +++ b/src/Behat/Testwork/Suite/GenericSuite.php @@ -65,7 +65,7 @@ public function getSettings() * * @param string $key * - * @return boolean + * @return bool */ public function hasSetting($key) { diff --git a/src/Behat/Testwork/Suite/Setup/SuiteSetup.php b/src/Behat/Testwork/Suite/Setup/SuiteSetup.php index 2dc25da7f..75eef7c13 100644 --- a/src/Behat/Testwork/Suite/Setup/SuiteSetup.php +++ b/src/Behat/Testwork/Suite/Setup/SuiteSetup.php @@ -27,7 +27,7 @@ interface SuiteSetup * * @param Suite $suite * - * @return boolean + * @return bool */ public function supportsSuite(Suite $suite); diff --git a/src/Behat/Testwork/Suite/Suite.php b/src/Behat/Testwork/Suite/Suite.php index 5f2ad3586..e26c1617e 100644 --- a/src/Behat/Testwork/Suite/Suite.php +++ b/src/Behat/Testwork/Suite/Suite.php @@ -36,7 +36,7 @@ public function getSettings(); * * @param string $key * - * @return boolean + * @return bool */ public function hasSetting($key); diff --git a/src/Behat/Testwork/Suite/SuiteRegistry.php b/src/Behat/Testwork/Suite/SuiteRegistry.php index ef708fc45..b5f90df46 100644 --- a/src/Behat/Testwork/Suite/SuiteRegistry.php +++ b/src/Behat/Testwork/Suite/SuiteRegistry.php @@ -23,7 +23,7 @@ final class SuiteRegistry implements SuiteRepository { /** - * @var boolean + * @var bool */ private $suitesGenerated = false; /** diff --git a/src/Behat/Testwork/Tester/Cli/ExerciseController.php b/src/Behat/Testwork/Tester/Cli/ExerciseController.php index e88bbfc6c..2fc5642e1 100644 --- a/src/Behat/Testwork/Tester/Cli/ExerciseController.php +++ b/src/Behat/Testwork/Tester/Cli/ExerciseController.php @@ -52,7 +52,7 @@ final class ExerciseController implements Controller */ private $resultInterpreter; /** - * @var boolean + * @var bool */ private $skip; @@ -63,7 +63,7 @@ final class ExerciseController implements Controller * @param SpecificationFinder $specificationFinder * @param Exercise $exercise * @param ResultInterpreter $resultInterpreter - * @param boolean $skip + * @param bool $skip */ public function __construct( SuiteRepository $suiteRepository, diff --git a/src/Behat/Testwork/Tester/Cli/StrictController.php b/src/Behat/Testwork/Tester/Cli/StrictController.php index 6ea5fdac5..697b881fc 100644 --- a/src/Behat/Testwork/Tester/Cli/StrictController.php +++ b/src/Behat/Testwork/Tester/Cli/StrictController.php @@ -30,7 +30,7 @@ final class StrictController implements Controller */ private $resultInterpreter; /** - * @var boolean + * @var bool */ private $strict; @@ -38,7 +38,7 @@ final class StrictController implements Controller * Initializes controller. * * @param ResultInterpreter $resultInterpreter - * @param boolean $strict + * @param bool $strict */ public function __construct(ResultInterpreter $resultInterpreter, $strict = false) { diff --git a/src/Behat/Testwork/Tester/Exercise.php b/src/Behat/Testwork/Tester/Exercise.php index 705cd7d9d..e63883d8c 100644 --- a/src/Behat/Testwork/Tester/Exercise.php +++ b/src/Behat/Testwork/Tester/Exercise.php @@ -26,7 +26,7 @@ interface Exercise * Sets up exercise for a test. * * @param SpecificationIterator[] $iterators - * @param boolean $skip + * @param bool $skip * * @return Setup */ @@ -36,7 +36,7 @@ public function setUp(array $iterators, $skip); * Tests suites specifications. * * @param SpecificationIterator[] $iterators - * @param boolean $skip + * @param bool $skip * * @return TestResult */ @@ -46,7 +46,7 @@ public function test(array $iterators, $skip); * Tears down exercise after a test. * * @param SpecificationIterator[] $iterators - * @param boolean $skip + * @param bool $skip * @param TestResult $result * * @return Teardown diff --git a/src/Behat/Testwork/Tester/Result/ExceptionResult.php b/src/Behat/Testwork/Tester/Result/ExceptionResult.php index a8d4c68d9..1b724f5c3 100644 --- a/src/Behat/Testwork/Tester/Result/ExceptionResult.php +++ b/src/Behat/Testwork/Tester/Result/ExceptionResult.php @@ -22,7 +22,7 @@ interface ExceptionResult extends TestResult /** * Checks that the test result has exception. * - * @return boolean + * @return bool */ public function hasException(); diff --git a/src/Behat/Testwork/Tester/Result/Interpretation/ResultInterpretation.php b/src/Behat/Testwork/Tester/Result/Interpretation/ResultInterpretation.php index 10b74bf75..cc9250915 100644 --- a/src/Behat/Testwork/Tester/Result/Interpretation/ResultInterpretation.php +++ b/src/Behat/Testwork/Tester/Result/Interpretation/ResultInterpretation.php @@ -27,7 +27,7 @@ interface ResultInterpretation * * @param TestResult $result * - * @return boolean + * @return bool */ public function isFailure(TestResult $result); } diff --git a/src/Behat/Testwork/Tester/Result/TestResult.php b/src/Behat/Testwork/Tester/Result/TestResult.php index b017fff23..77281b785 100644 --- a/src/Behat/Testwork/Tester/Result/TestResult.php +++ b/src/Behat/Testwork/Tester/Result/TestResult.php @@ -25,7 +25,7 @@ interface TestResult /** * Checks that test has passed. * - * @return boolean + * @return bool */ public function isPassed(); diff --git a/src/Behat/Testwork/Tester/ServiceContainer/TesterExtension.php b/src/Behat/Testwork/Tester/ServiceContainer/TesterExtension.php index d81268119..85509d5d3 100644 --- a/src/Behat/Testwork/Tester/ServiceContainer/TesterExtension.php +++ b/src/Behat/Testwork/Tester/ServiceContainer/TesterExtension.php @@ -123,7 +123,7 @@ public function process(ContainerBuilder $container) * Loads exercise cli controllers. * * @param ContainerBuilder $container - * @param boolean $skip + * @param bool $skip */ protected function loadExerciseController(ContainerBuilder $container, $skip = false) { @@ -142,7 +142,7 @@ protected function loadExerciseController(ContainerBuilder $container, $skip = f * Loads exercise cli controllers. * * @param ContainerBuilder $container - * @param boolean $strict + * @param bool $strict */ protected function loadStrictController(ContainerBuilder $container, $strict = false) { diff --git a/src/Behat/Testwork/Tester/Setup/Setup.php b/src/Behat/Testwork/Tester/Setup/Setup.php index 4e83d2558..5f6fd45b7 100644 --- a/src/Behat/Testwork/Tester/Setup/Setup.php +++ b/src/Behat/Testwork/Tester/Setup/Setup.php @@ -20,14 +20,14 @@ interface Setup /** * Returns true if fixtures have been handled successfully. * - * @return boolean + * @return bool */ public function isSuccessful(); /** * Checks if setup has produced any output. * - * @return boolean + * @return bool */ public function hasOutput(); } diff --git a/src/Behat/Testwork/Tester/Setup/Teardown.php b/src/Behat/Testwork/Tester/Setup/Teardown.php index 0303709c0..7ff253168 100644 --- a/src/Behat/Testwork/Tester/Setup/Teardown.php +++ b/src/Behat/Testwork/Tester/Setup/Teardown.php @@ -20,14 +20,14 @@ interface Teardown /** * Returns true if fixtures have been handled successfully. * - * @return boolean + * @return bool */ public function isSuccessful(); /** * Checks if tear down has produced any output. * - * @return boolean + * @return bool */ public function hasOutput(); } diff --git a/src/Behat/Testwork/Tester/SpecificationTester.php b/src/Behat/Testwork/Tester/SpecificationTester.php index 00ac817b0..b6e06ff41 100644 --- a/src/Behat/Testwork/Tester/SpecificationTester.php +++ b/src/Behat/Testwork/Tester/SpecificationTester.php @@ -27,7 +27,7 @@ interface SpecificationTester * * @param Environment $env * @param mixed $spec - * @param boolean $skip + * @param bool $skip * * @return Setup */ @@ -38,7 +38,7 @@ public function setUp(Environment $env, $spec, $skip); * * @param Environment $env * @param mixed $spec - * @param boolean $skip + * @param bool $skip * * @return TestResult */ @@ -49,7 +49,7 @@ public function test(Environment $env, $spec, $skip); * * @param Environment $env * @param mixed $spec - * @param boolean $skip + * @param bool $skip * @param TestResult $result * * @return Teardown diff --git a/src/Behat/Testwork/Tester/SuiteTester.php b/src/Behat/Testwork/Tester/SuiteTester.php index 532665ae2..61dffad7f 100644 --- a/src/Behat/Testwork/Tester/SuiteTester.php +++ b/src/Behat/Testwork/Tester/SuiteTester.php @@ -28,7 +28,7 @@ interface SuiteTester * * @param Environment $env * @param SpecificationIterator $iterator - * @param boolean $skip + * @param bool $skip * * @return Setup */ @@ -39,7 +39,7 @@ public function setUp(Environment $env, SpecificationIterator $iterator, $skip); * * @param Environment $env * @param SpecificationIterator $iterator - * @param boolean $skip + * @param bool $skip * * @return TestResult */ @@ -50,7 +50,7 @@ public function test(Environment $env, SpecificationIterator $iterator, $skip); * * @param Environment $env * @param SpecificationIterator $iterator - * @param boolean $skip + * @param bool $skip * @param TestResult $result * * @return Teardown From 438dfd766883975aca8d325c7f7d3617d6d0cb21 Mon Sep 17 00:00:00 2001 From: Wouter J Date: Thu, 3 Oct 2019 00:19:32 +0200 Subject: [PATCH 165/567] Show only user-land trace for exceptions and errors in very verbose mode --- features/bootstrap/FeatureContext.php | 12 +++- features/error_reporting.feature | 56 ++++++++++++++++++- .../Testwork/Exception/ExceptionPresenter.php | 35 +++++++++++- 3 files changed, 99 insertions(+), 4 deletions(-) diff --git a/features/bootstrap/FeatureContext.php b/features/bootstrap/FeatureContext.php index 450e9e829..ff05889f1 100644 --- a/features/bootstrap/FeatureContext.php +++ b/features/bootstrap/FeatureContext.php @@ -348,6 +348,13 @@ private function getExpectedOutput(PyStringNode $expectedText) return str_replace('/', DIRECTORY_SEPARATOR, $matches[0]); }, $text ); + + // error stacktrace + $text = preg_replace_callback( + '/#\d+ [^:]+:/', function ($matches) { + return str_replace('/', DIRECTORY_SEPARATOR, $matches[0]); + }, $text + ); } return $text; @@ -402,11 +409,14 @@ private function getOutput() { $output = $this->process->getErrorOutput() . $this->process->getOutput(); - // Normalize the line endings in the output + // Normalize the line endings and directory separators in the output if ("\n" !== PHP_EOL) { $output = str_replace(PHP_EOL, "\n", $output); } + // Remove location of the project + $output = str_replace(realpath(dirname(dirname(__DIR__))).DIRECTORY_SEPARATOR, '', $output); + // Replace wrong warning message of HHVM $output = str_replace('Notice: Undefined index: ', 'Notice: Undefined offset: ', $output); diff --git a/features/error_reporting.feature b/features/error_reporting.feature index 1139b48bc..de192df2a 100644 --- a/features/error_reporting.feature +++ b/features/error_reporting.feature @@ -56,6 +56,13 @@ Feature: Error Reporting PHPUnit\Framework\Assert::assertEquals($arg1, $this->result); } + /** + * @When an exception is thrown + */ + public function anExceptionIsThrown() + { + throw new \Exception('Exception is thrown'); + } } """ And a file named "features/e_notice_in_scenario.feature" with: @@ -76,11 +83,21 @@ Feature: Error Reporting When I push "foo" to that array And I access array index 0 Then I should get "foo" + """ + And a file named "features/exception_in_scenario.feature" with: + """ + Feature: Error in scenario + In order to test the error stacktraces + As a contributor of behat + I need to have a FeatureContext that triggers an error within steps. + + Scenario: Exception thrown + When an exception is thrown """ Scenario: With default error reporting - When I run "behat -f progress --no-colors" + When I run "behat -f progress --no-colors features/e_notice_in_scenario.feature" Then it should fail And the output should contain: """ @@ -101,5 +118,40 @@ Feature: Error Reporting calls: error_reporting: 32759 """ - When I run "behat -f progress --no-colors" + When I run "behat -f progress --no-colors features/e_notice_in_scenario.feature" Then it should pass + + @php-version @php7 + Scenario: With very verbose error reporting + When I run "behat -f progress --no-colors -vv features/exception_in_scenario.feature" + Then it should fail + And the output should contain: + """ + --- Failed steps: + + 001 Scenario: Exception thrown # features/exception_in_scenario.feature:6 + When an exception is thrown # features/exception_in_scenario.feature:7 + Exception: Exception is thrown in features/bootstrap/FeatureContext.php:56 + Stack trace: + #0 [internal function]: FeatureContext->anExceptionIsThrown() + + 1 scenario (1 failed) + 1 step (1 failed) + """ + + @php-version @php7 + Scenario: With debug verbose error reporting + When I run "behat -f progress --no-colors -vvv features/exception_in_scenario.feature" + Then it should fail + And the output should contain: + """ + --- Failed steps: + + 001 Scenario: Exception thrown # features/exception_in_scenario.feature:6 + When an exception is thrown # features/exception_in_scenario.feature:7 + Exception: Exception is thrown in features/bootstrap/FeatureContext.php:56 + Stack trace: + #0 [internal function]: FeatureContext->anExceptionIsThrown() + #1 src/Behat/Testwork/Call/Handler/RuntimeCallHandler.php(109): call_user_func_array(Array, Array) + #2 src/Behat/Testwork/Call/Handler/RuntimeCallHandler.php(64): Behat\Testwork\Call\Handler\RuntimeCallHandler->executeCall(Object(Behat\Behat\Definition\Call\DefinitionCall)) + """ diff --git a/src/Behat/Testwork/Exception/ExceptionPresenter.php b/src/Behat/Testwork/Exception/ExceptionPresenter.php index fce59bbf6..9ad0d14c2 100644 --- a/src/Behat/Testwork/Exception/ExceptionPresenter.php +++ b/src/Behat/Testwork/Exception/ExceptionPresenter.php @@ -13,6 +13,7 @@ use Behat\Testwork\Exception\Stringer\ExceptionStringer; use Behat\Testwork\Output\Printer\OutputPrinter; use Exception; +use Symfony\Component\Console\Output\OutputInterface; /** * Presents exceptions as strings using registered stringers. @@ -93,13 +94,45 @@ public function presentException(Exception $exception, $verbosity = null) } } - if (OutputPrinter::VERBOSITY_VERY_VERBOSE <= $verbosity) { + if (OutputInterface::VERBOSITY_VERY_VERBOSE <= $verbosity) { + if (OutputInterface::VERBOSITY_DEBUG > $verbosity) { + $exception = $this->removeBehatCallsFromTrace($exception); + } + return $this->relativizePaths(trim($exception)); } return trim($this->relativizePaths($exception->getMessage()) . ' (' . get_class($exception) . ')'); } + private function removeBehatCallsFromTrace(Exception $exception) + { + $traceOutput = ''; + foreach ($exception->getTrace() as $i => $trace) { + if (isset($trace['file']) && false !== strpos(str_replace('\\', '/', $trace['file']), 'Behat/Testwork/Call/Handler/RuntimeCallHandler')) { + break; + } + + $traceOutput .= sprintf( + '#%d %s: %s()'.PHP_EOL, + $i, + isset($trace['file']) ? $trace['file'].'('.$trace['line'].')' : '[internal function]', + isset($trace['class']) ? $trace['class'].$trace['type'].$trace['function'] : $trace['function'] + ); + } + + return sprintf( + "%s: %s in %s:%d%sStack trace:%s%s", + get_class($exception), + $exception->getMessage(), + $exception->getFile(), + $exception->getLine(), + PHP_EOL, + PHP_EOL, + $traceOutput + ); + } + /** * Relativizes absolute paths in the text. * From cc26516da9557853243be3ebc40a1e91e5ff8869 Mon Sep 17 00:00:00 2001 From: Pieter Frenssen Date: Mon, 4 Nov 2019 16:49:30 +0200 Subject: [PATCH 166/567] Throw a dedicated MissingExtensionException instead of a generic one. --- .../Exception/MissingExtensionException.php | 22 +++++++++++++++++++ .../Output/Printer/JUnitOutputPrinter.php | 3 ++- 2 files changed, 24 insertions(+), 1 deletion(-) create mode 100644 src/Behat/Testwork/Output/Exception/MissingExtensionException.php diff --git a/src/Behat/Testwork/Output/Exception/MissingExtensionException.php b/src/Behat/Testwork/Output/Exception/MissingExtensionException.php new file mode 100644 index 000000000..a54cdbd9f --- /dev/null +++ b/src/Behat/Testwork/Output/Exception/MissingExtensionException.php @@ -0,0 +1,22 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Behat\Testwork\Output\Exception; + +use RuntimeException; + +/** + * Represents an exception thrown when a required extension is missing. + * + * @author Konstantin Kudryashov + */ +class MissingExtensionException extends RuntimeException implements PrinterException +{ +} diff --git a/src/Behat/Testwork/Output/Printer/JUnitOutputPrinter.php b/src/Behat/Testwork/Output/Printer/JUnitOutputPrinter.php index ec491108f..fa2308553 100644 --- a/src/Behat/Testwork/Output/Printer/JUnitOutputPrinter.php +++ b/src/Behat/Testwork/Output/Printer/JUnitOutputPrinter.php @@ -10,6 +10,7 @@ namespace Behat\Testwork\Output\Printer; +use Behat\Testwork\Output\Exception\MissingExtensionException; use Behat\Testwork\Output\Printer\Factory\FilesystemOutputFactory; use Symfony\Component\Console\Output\OutputInterface; @@ -59,7 +60,7 @@ public function createNewFile($name, array $testsuitesAttributes = array()) { // This requires the DOM extension to be enabled. if (!extension_loaded('dom')) { - throw new \Exception('The PHP DOM extension is required to generate JUnit reports.'); + throw new MissingExtensionException('The PHP DOM extension is required to generate JUnit reports.'); } $this->setFileName(strtolower(trim(preg_replace('/[^[:alnum:]_]+/', '_', $name), '_'))); From 0bcd4af5c48bd156291ba4792be23ea02bc73284 Mon Sep 17 00:00:00 2001 From: Ciaran McNulty Date: Sat, 9 Nov 2019 15:45:45 +0000 Subject: [PATCH 167/567] Update CHANGELOG.md --- CHANGELOG.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index b758751ab..de9db3a23 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,8 @@ The format is based on [Keep a Changelog](http://keepachangelog.com/) and this project adheres to [Semantic Versioning](http://semver.org/). ## [Unreleased] +### Added + * [#1244](https://github.com/Behat/Behat/pull/1244): Hide internal steps from stack traces in very verbose mode ## [3.5.0] - 2018-08-10 ### Added From 5df6e0864fcff09b7429ecb26d75f3cfe889ca2d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Koles=C3=A1r=20Andr=C3=A1s?= Date: Sun, 10 Nov 2019 07:01:46 +0100 Subject: [PATCH 168/567] Add hungarian translation --- i18n.php | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/i18n.php b/i18n.php index 44eda3c91..b7e9e570e 100644 --- a/i18n.php +++ b/i18n.php @@ -214,4 +214,21 @@ 'undefined_count' => '{1,21,31} %1% не определен|]1,Inf] %1% не определено', 'skipped_count' => '{1,21,31} %1% пропущен|]1,Inf] %1% пропущено', ), + 'hu' => array( + 'snippet_context_choice' => '%1% sorozat meghatározatlan lépéseket tartalmaz. Válaszd ki a környezetet kódrészlet készítéséhez:', + 'snippet_proposal_title' => '%1% lépései hiányosak. Hozd létre az alábbi kódrészletekkel:', + 'snippet_missing_title' => 'Használd a --snippets-for parancssori kapcsolót kódrészletek készítéséhez a %1% sorozat lépéseihez:', + 'skipped_scenarios_title' => 'Kihagyott forgatókönyvek:', + 'failed_scenarios_title' => 'Sikertelen forgatókönyvek:', + 'failed_hooks_title' => 'Sikertelen kampók:', + 'failed_steps_title' => 'Sikertelen lépések:', + 'pending_steps_title' => 'Elintézendő lépések:', + 'scenarios_count' => '{0} Nem volt forgatókönyv|{1} 1 forgatókönyv|]1,Inf] %1% forgatókönyv', + 'steps_count' => '{0} Nem volt lépés|{1} 1 lépés|]1,Inf] %1% lépés', + 'passed_count' => '[1,Inf] %1% sikeres', + 'failed_count' => '[1,Inf] %1% sikertelen', + 'pending_count' => '[1,Inf] %1% elintézendő', + 'undefined_count' => '[1,Inf] %1% meghatározatlan', + 'skipped_count' => '[1,Inf] %1% kihagyott', + ), ); From 8c3ef5a5c5fd7e4d1664848d546e0d5382ec5340 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Javier=20D=C3=ADaz?= Date: Sat, 23 Nov 2019 12:13:05 +0100 Subject: [PATCH 169/567] Update dependencies to allow Symfony 5.x components --- composer.json | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/composer.json b/composer.json index 2246d04e1..2abbfd968 100644 --- a/composer.json +++ b/composer.json @@ -18,18 +18,18 @@ "ext-mbstring": "*", "behat/gherkin": "^4.6.0", "behat/transliterator": "^1.2", - "symfony/console": "~2.7.40||^2.8.33||~3.3.15||^3.4.3||^4.0.3", - "symfony/config": "~2.3||~3.0||~4.0", - "symfony/dependency-injection": "~2.1||~3.0||~4.0", - "symfony/event-dispatcher": "~2.1||~3.0||~4.0", - "symfony/translation": "~2.3||~3.0||~4.0", - "symfony/yaml": "~2.1||~3.0||~4.0", + "symfony/console": "~2.7.40||^2.8.33||~3.3.15||^3.4.3||^4.0.3||^5.0.0", + "symfony/config": "~2.3||~3.0||~4.0||~5.0", + "symfony/dependency-injection": "~2.1||~3.0||~4.0||~5.0", + "symfony/event-dispatcher": "~2.1||~3.0||~4.0||~5.0", + "symfony/translation": "~2.3||~3.0||~4.0||~5.0", + "symfony/yaml": "~2.1||~3.0||~4.0||~5.0", "psr/container": "^1.0", "container-interop/container-interop": "^1.2" }, "require-dev": { - "symfony/process": "~2.5|~3.0|~4.0", + "symfony/process": "~2.5|~3.0|~4.0|~5.0", "phpunit/phpunit": "^4.8.36|^6.3", "herrera-io/box": "~1.6.1" }, From 7d4cac6defc641229ecdadce3e4154f24d4973a5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Javier=20D=C3=ADaz?= Date: Sat, 23 Nov 2019 14:28:21 +0100 Subject: [PATCH 170/567] Added CHANGELOG.MD update --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index de9db3a23..8bbc0645c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,7 @@ The format is based on [Keep a Changelog](http://keepachangelog.com/) and this project adheres to [Semantic Versioning](http://semver.org/). ## [Unreleased] + * [#1256](https://github.com/Behat/Behat/pull/1256): Update dependencies to support Symfony 5.x ### Added * [#1244](https://github.com/Behat/Behat/pull/1244): Hide internal steps from stack traces in very verbose mode From 63d26f73c592352e8c8a170d56b8af8138844e3f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Javier=20D=C3=ADaz?= Date: Sat, 23 Nov 2019 14:30:11 +0100 Subject: [PATCH 171/567] Adapted all the code to the new components in Symfony --- features/bootstrap/FeatureContext.php | 31 +++++++++++++------ .../Context/Cli/ContextSnippetsController.php | 2 +- .../Cli/InteractiveContextIdentifier.php | 2 +- .../Translator/DefinitionTranslator.php | 10 +++--- .../Cli/StopOnFailureController.php | 4 +-- .../EventDispatchingBackgroundTester.php | 8 ++--- .../Tester/EventDispatchingFeatureTester.php | 8 ++--- .../Tester/EventDispatchingOutlineTester.php | 8 ++--- .../Tester/EventDispatchingScenarioTester.php | 8 ++--- .../Tester/EventDispatchingStepTester.php | 8 ++--- .../Behat/Gherkin/Cli/SyntaxController.php | 2 +- .../EventListener/AST/FeatureListener.php | 2 +- .../EventListener/AST/OutlineListener.php | 2 +- .../AST/OutlineTableListener.php | 2 +- .../AST/ScenarioNodeListener.php | 2 +- .../Node/EventListener/AST/StepListener.php | 2 +- .../Node/EventListener/AST/SuiteListener.php | 2 +- .../Flow/FireOnlySiblingsListener.php | 2 +- .../FirstBackgroundFiresFirstListener.php | 2 +- .../Flow/OnlyFirstBackgroundFiresListener.php | 2 +- .../JUnit/JUnitDurationListener.php | 2 +- .../JUnit/JUnitFeatureElementListener.php | 2 +- .../JUnit/JUnitOutlineStoreListener.php | 2 +- .../Statistics/HookStatsListener.php | 2 +- .../Statistics/ScenarioStatsListener.php | 2 +- .../Statistics/StatisticsListener.php | 2 +- .../Statistics/StepStatsListener.php | 2 +- .../Output/Node/Printer/CounterPrinter.php | 6 ++-- .../Behat/Output/Node/Printer/ListPrinter.php | 2 +- .../Snippet/Printer/ConsoleSnippetPrinter.php | 2 +- .../RepositoryArgumentTransformer.php | 2 +- .../Event/ExerciseCompleted.php | 2 +- .../EventDispatcher/Event/LifecycleEvent.php | 2 +- .../Tester/EventDispatchingExercise.php | 8 ++--- .../Tester/EventDispatchingSuiteTester.php | 8 ++--- .../TestworkEventDispatcher.php | 8 ++--- .../Node/EventListener/ChainEventListener.php | 2 +- .../Node/EventListener/EventListener.php | 2 +- .../FireOnlyIfFormatterParameterListener.php | 2 +- .../Output/NodeEventListeningFormatter.php | 2 +- .../Configuration/ConfigurationTree.php | 4 +-- 41 files changed, 93 insertions(+), 82 deletions(-) diff --git a/features/bootstrap/FeatureContext.php b/features/bootstrap/FeatureContext.php index ff05889f1..8fd7b725c 100644 --- a/features/bootstrap/FeatureContext.php +++ b/features/bootstrap/FeatureContext.php @@ -38,6 +38,14 @@ class FeatureContext implements Context * @var string */ private $options = '--format-settings=\'{"timer": false}\' --no-interaction'; + /** + * @var array + */ + private $env = []; + /** + * @var string + */ + private $answerString; /** * Cleans test folders in the temporary directory. @@ -71,8 +79,7 @@ public function prepareTestFolders() } $this->workingDir = $dir; $this->phpBin = $php; - $this->process = new Process(null); - $this->process->setTimeout(20); + $this->process = Process::fromShellCommandline(''); } /** @@ -170,7 +177,7 @@ public function fileShouldExist($path) */ public function iSetEnvironmentVariable(PyStringNode $value) { - $this->process->setEnv(array('BEHAT_PARAMS' => (string) $value)); + $this->env = array('BEHAT_PARAMS' => (string) $value); } /** @@ -184,8 +191,7 @@ public function iRunBehat($argumentsString = '') { $argumentsString = strtr($argumentsString, array('\'' => '"')); - $this->process->setWorkingDirectory($this->workingDir); - $this->process->setCommandLine( + $this->process = Process::fromShellCommandline( sprintf( '%s %s %s %s', $this->phpBin, @@ -195,6 +201,15 @@ public function iRunBehat($argumentsString = '') ) ); + // Prepare the process parameters. + $this->process->setTimeout(20); + $this->process->setEnv($this->env); + $this->process->setWorkingDirectory($this->workingDir); + + if (!empty($this->answerString)) { + $this->process->setInput($this->answerString); + } + // Don't reset the LANG variable on HHVM, because it breaks HHVM itself if (!defined('HHVM_VERSION')) { $env = $this->process->getEnv(); @@ -215,11 +230,9 @@ public function iRunBehat($argumentsString = '') */ public function iRunBehatInteractively($answerString, $argumentsString) { - $env = $this->process->getEnv(); - $env['SHELL_INTERACTIVE'] = true; + $this->env['SHELL_INTERACTIVE'] = true; - $this->process->setEnv($env); - $this->process->setInput($answerString); + $this->answerString = $answerString; $this->options = '--format-settings=\'{"timer": false}\''; $this->iRunBehat($argumentsString); diff --git a/src/Behat/Behat/Context/Cli/ContextSnippetsController.php b/src/Behat/Behat/Context/Cli/ContextSnippetsController.php index 3a6edf63c..c13d3436b 100644 --- a/src/Behat/Behat/Context/Cli/ContextSnippetsController.php +++ b/src/Behat/Behat/Context/Cli/ContextSnippetsController.php @@ -22,7 +22,7 @@ use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; -use Symfony\Component\Translation\TranslatorInterface; +use Symfony\Contracts\Translation\TranslatorInterface; /** * Configures which context snippets are generated for. diff --git a/src/Behat/Behat/Context/Cli/InteractiveContextIdentifier.php b/src/Behat/Behat/Context/Cli/InteractiveContextIdentifier.php index 5f3791743..17a29b9f4 100644 --- a/src/Behat/Behat/Context/Cli/InteractiveContextIdentifier.php +++ b/src/Behat/Behat/Context/Cli/InteractiveContextIdentifier.php @@ -16,7 +16,7 @@ use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Console\Question\ChoiceQuestion; -use Symfony\Component\Translation\TranslatorInterface; +use Symfony\Contracts\Translation\TranslatorInterface; /** * Interactive identifier that asks user for input. diff --git a/src/Behat/Behat/Definition/Translator/DefinitionTranslator.php b/src/Behat/Behat/Definition/Translator/DefinitionTranslator.php index 3192a3d8e..ed3c3cb33 100644 --- a/src/Behat/Behat/Definition/Translator/DefinitionTranslator.php +++ b/src/Behat/Behat/Definition/Translator/DefinitionTranslator.php @@ -12,7 +12,8 @@ use Behat\Behat\Definition\Definition; use Behat\Testwork\Suite\Suite; -use Symfony\Component\Translation\TranslatorInterface; +use Symfony\Contracts\Translation\TranslatorInterface; +use Symfony\Contracts\Translation\TranslatorTrait; /** * Translates definitions using translator component. @@ -21,6 +22,8 @@ */ final class DefinitionTranslator { + use TranslatorTrait; + /** * @var TranslatorInterface */ @@ -57,9 +60,4 @@ public function translateDefinition(Suite $suite, Definition $definition, $langu return $definition; } - - public function getLocale() - { - return $this->translator->getLocale(); - } } diff --git a/src/Behat/Behat/EventDispatcher/Cli/StopOnFailureController.php b/src/Behat/Behat/EventDispatcher/Cli/StopOnFailureController.php index d86b34573..940ac09fd 100644 --- a/src/Behat/Behat/EventDispatcher/Cli/StopOnFailureController.php +++ b/src/Behat/Behat/EventDispatcher/Cli/StopOnFailureController.php @@ -100,8 +100,8 @@ public function exitOnFailure(AfterScenarioTested $event) return; } - $this->eventDispatcher->dispatch(SuiteTested::AFTER, new AfterSuiteAborted($event->getEnvironment())); - $this->eventDispatcher->dispatch(ExerciseCompleted::AFTER, new AfterExerciseAborted()); + $this->eventDispatcher->dispatch(new AfterSuiteAborted($event->getEnvironment()), SuiteTested::AFTER); + $this->eventDispatcher->dispatch(new AfterExerciseAborted(), ExerciseCompleted::AFTER); exit(1); } diff --git a/src/Behat/Behat/EventDispatcher/Tester/EventDispatchingBackgroundTester.php b/src/Behat/Behat/EventDispatcher/Tester/EventDispatchingBackgroundTester.php index d947df55d..e0732d818 100644 --- a/src/Behat/Behat/EventDispatcher/Tester/EventDispatchingBackgroundTester.php +++ b/src/Behat/Behat/EventDispatcher/Tester/EventDispatchingBackgroundTester.php @@ -55,12 +55,12 @@ public function __construct(BackgroundTester $baseTester, EventDispatcherInterfa public function setUp(Environment $env, FeatureNode $feature, $skip) { $event = new BeforeBackgroundTested($env, $feature, $feature->getBackground()); - $this->eventDispatcher->dispatch($event::BEFORE, $event); + $this->eventDispatcher->dispatch($event, $event::BEFORE); $setup = $this->baseTester->setUp($env, $feature, $skip); $event = new AfterBackgroundSetup($env, $feature, $feature->getBackground(), $setup); - $this->eventDispatcher->dispatch($event::AFTER_SETUP, $event); + $this->eventDispatcher->dispatch($event, $event::AFTER_SETUP); return $setup; } @@ -79,12 +79,12 @@ public function test(Environment $env, FeatureNode $feature, $skip) public function tearDown(Environment $env, FeatureNode $feature, $skip, TestResult $result) { $event = new BeforeBackgroundTeardown($env, $feature, $feature->getBackground(), $result); - $this->eventDispatcher->dispatch(BackgroundTested::BEFORE_TEARDOWN, $event); + $this->eventDispatcher->dispatch($event, BackgroundTested::BEFORE_TEARDOWN); $teardown = $this->baseTester->tearDown($env, $feature, $skip, $result); $event = new AfterBackgroundTested($env, $feature, $feature->getBackground(), $result, $teardown); - $this->eventDispatcher->dispatch(BackgroundTested::AFTER, $event); + $this->eventDispatcher->dispatch($event, BackgroundTested::AFTER); return $teardown; } diff --git a/src/Behat/Behat/EventDispatcher/Tester/EventDispatchingFeatureTester.php b/src/Behat/Behat/EventDispatcher/Tester/EventDispatchingFeatureTester.php index 2bd0ad5dd..088a4d6d1 100644 --- a/src/Behat/Behat/EventDispatcher/Tester/EventDispatchingFeatureTester.php +++ b/src/Behat/Behat/EventDispatcher/Tester/EventDispatchingFeatureTester.php @@ -53,12 +53,12 @@ public function __construct(SpecificationTester $baseTester, EventDispatcherInte public function setUp(Environment $env, $feature, $skip) { $event = new BeforeFeatureTested($env, $feature); - $this->eventDispatcher->dispatch($event::BEFORE, $event); + $this->eventDispatcher->dispatch($event, $event::BEFORE); $setup = $this->baseTester->setUp($env, $feature, $skip); $event = new AfterFeatureSetup($env, $feature, $setup); - $this->eventDispatcher->dispatch($event::AFTER_SETUP, $event); + $this->eventDispatcher->dispatch($event, $event::AFTER_SETUP); return $setup; } @@ -77,12 +77,12 @@ public function test(Environment $env, $feature, $skip) public function tearDown(Environment $env, $feature, $skip, TestResult $result) { $event = new BeforeFeatureTeardown($env, $feature, $result); - $this->eventDispatcher->dispatch($event::BEFORE_TEARDOWN, $event); + $this->eventDispatcher->dispatch($event, $event::BEFORE_TEARDOWN); $teardown = $this->baseTester->tearDown($env, $feature, $skip, $result); $event = new AfterFeatureTested($env, $feature, $result, $teardown); - $this->eventDispatcher->dispatch($event::AFTER, $event); + $this->eventDispatcher->dispatch($event, $event::AFTER); return $teardown; } diff --git a/src/Behat/Behat/EventDispatcher/Tester/EventDispatchingOutlineTester.php b/src/Behat/Behat/EventDispatcher/Tester/EventDispatchingOutlineTester.php index 13d257cef..24b3f9898 100644 --- a/src/Behat/Behat/EventDispatcher/Tester/EventDispatchingOutlineTester.php +++ b/src/Behat/Behat/EventDispatcher/Tester/EventDispatchingOutlineTester.php @@ -55,12 +55,12 @@ public function __construct(OutlineTester $baseTester, EventDispatcherInterface public function setUp(Environment $env, FeatureNode $feature, OutlineNode $outline, $skip) { $event = new BeforeOutlineTested($env, $feature, $outline); - $this->eventDispatcher->dispatch($event::BEFORE, $event); + $this->eventDispatcher->dispatch($event, $event::BEFORE); $setup = $this->baseTester->setUp($env, $feature, $outline, $skip); $event = new AfterOutlineSetup($env, $feature, $outline, $setup); - $this->eventDispatcher->dispatch($event::AFTER_SETUP, $event); + $this->eventDispatcher->dispatch($event, $event::AFTER_SETUP); return $setup; } @@ -79,12 +79,12 @@ public function test(Environment $env, FeatureNode $feature, OutlineNode $outlin public function tearDown(Environment $env, FeatureNode $feature, OutlineNode $outline, $skip, TestResult $result) { $event = new BeforeOutlineTeardown($env, $feature, $outline, $result); - $this->eventDispatcher->dispatch($event::BEFORE_TEARDOWN, $event); + $this->eventDispatcher->dispatch($event, $event::BEFORE_TEARDOWN); $teardown = $this->baseTester->tearDown($env, $feature, $outline, $skip, $result); $event = new AfterOutlineTested($env, $feature, $outline, $result, $teardown); - $this->eventDispatcher->dispatch($event::AFTER, $event); + $this->eventDispatcher->dispatch($event, $event::AFTER); return $teardown; } diff --git a/src/Behat/Behat/EventDispatcher/Tester/EventDispatchingScenarioTester.php b/src/Behat/Behat/EventDispatcher/Tester/EventDispatchingScenarioTester.php index 44eb13120..85c182e6e 100644 --- a/src/Behat/Behat/EventDispatcher/Tester/EventDispatchingScenarioTester.php +++ b/src/Behat/Behat/EventDispatcher/Tester/EventDispatchingScenarioTester.php @@ -85,12 +85,12 @@ public function __construct( public function setUp(Environment $env, FeatureNode $feature, Scenario $scenario, $skip) { $event = new BeforeScenarioTested($env, $feature, $scenario); - $this->eventDispatcher->dispatch($this->beforeEventName, $event); + $this->eventDispatcher->dispatch($event, $this->beforeEventName); $setup = $this->baseTester->setUp($env, $feature, $scenario, $skip); $event = new AfterScenarioSetup($env, $feature, $scenario, $setup); - $this->eventDispatcher->dispatch($this->afterSetupEventName, $event); + $this->eventDispatcher->dispatch($event, $this->afterSetupEventName); return $setup; } @@ -109,12 +109,12 @@ public function test(Environment $env, FeatureNode $feature, Scenario $scenario, public function tearDown(Environment $env, FeatureNode $feature, Scenario $scenario, $skip, TestResult $result) { $event = new BeforeScenarioTeardown($env, $feature, $scenario, $result); - $this->eventDispatcher->dispatch($this->beforeTeardownEventName, $event); + $this->eventDispatcher->dispatch($event, $this->beforeTeardownEventName); $teardown = $this->baseTester->tearDown($env, $feature, $scenario, $skip, $result); $event = new AfterScenarioTested($env, $feature, $scenario, $result, $teardown); - $this->eventDispatcher->dispatch($this->afterEventName, $event); + $this->eventDispatcher->dispatch($event, $this->afterEventName); return $teardown; } diff --git a/src/Behat/Behat/EventDispatcher/Tester/EventDispatchingStepTester.php b/src/Behat/Behat/EventDispatcher/Tester/EventDispatchingStepTester.php index 6bf3c46b2..03337556d 100644 --- a/src/Behat/Behat/EventDispatcher/Tester/EventDispatchingStepTester.php +++ b/src/Behat/Behat/EventDispatcher/Tester/EventDispatchingStepTester.php @@ -55,12 +55,12 @@ public function __construct(StepTester $baseTester, EventDispatcherInterface $ev public function setUp(Environment $env, FeatureNode $feature, StepNode $step, $skip) { $event = new BeforeStepTested($env, $feature, $step); - $this->eventDispatcher->dispatch($event::BEFORE, $event); + $this->eventDispatcher->dispatch($event, $event::BEFORE); $setup = $this->baseTester->setUp($env, $feature, $step, $skip); $event = new AfterStepSetup($env, $feature, $step, $setup); - $this->eventDispatcher->dispatch($event::AFTER_SETUP, $event); + $this->eventDispatcher->dispatch($event, $event::AFTER_SETUP); return $setup; } @@ -79,12 +79,12 @@ public function test(Environment $env, FeatureNode $feature, StepNode $step, $sk public function tearDown(Environment $env, FeatureNode $feature, StepNode $step, $skip, StepResult $result) { $event = new BeforeStepTeardown($env, $feature, $step, $result); - $this->eventDispatcher->dispatch($event::BEFORE_TEARDOWN, $event); + $this->eventDispatcher->dispatch($event, $event::BEFORE_TEARDOWN); $teardown = $this->baseTester->tearDown($env, $feature, $step, $skip, $result); $event = new AfterStepTested($env, $feature, $step, $result, $teardown); - $this->eventDispatcher->dispatch($event::AFTER, $event); + $this->eventDispatcher->dispatch($event, $event::AFTER); return $teardown; } diff --git a/src/Behat/Behat/Gherkin/Cli/SyntaxController.php b/src/Behat/Behat/Gherkin/Cli/SyntaxController.php index a3e3f6cfc..88397c4b3 100644 --- a/src/Behat/Behat/Gherkin/Cli/SyntaxController.php +++ b/src/Behat/Behat/Gherkin/Cli/SyntaxController.php @@ -17,7 +17,7 @@ use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; -use Symfony\Component\Translation\TranslatorInterface; +use Symfony\Contracts\Translation\TranslatorInterface; /** * Prints example of the feature to present all available syntax keywords. diff --git a/src/Behat/Behat/Output/Node/EventListener/AST/FeatureListener.php b/src/Behat/Behat/Output/Node/EventListener/AST/FeatureListener.php index 13bc0a415..8cc4a1e7a 100644 --- a/src/Behat/Behat/Output/Node/EventListener/AST/FeatureListener.php +++ b/src/Behat/Behat/Output/Node/EventListener/AST/FeatureListener.php @@ -17,7 +17,7 @@ use Behat\Behat\Output\Node\Printer\SetupPrinter; use Behat\Testwork\Output\Formatter; use Behat\Testwork\Output\Node\EventListener\EventListener; -use Symfony\Component\EventDispatcher\Event; +use Symfony\Contracts\EventDispatcher\Event; /** * Listens to feature events and calls appropriate printers. diff --git a/src/Behat/Behat/Output/Node/EventListener/AST/OutlineListener.php b/src/Behat/Behat/Output/Node/EventListener/AST/OutlineListener.php index bacb12f3a..5881b26c0 100644 --- a/src/Behat/Behat/Output/Node/EventListener/AST/OutlineListener.php +++ b/src/Behat/Behat/Output/Node/EventListener/AST/OutlineListener.php @@ -24,7 +24,7 @@ use Behat\Gherkin\Node\ExampleNode; use Behat\Testwork\Output\Formatter; use Behat\Testwork\Output\Node\EventListener\EventListener; -use Symfony\Component\EventDispatcher\Event; +use Symfony\Contracts\EventDispatcher\Event; /** * Listens to expanded outline events and calls appropriate printers. diff --git a/src/Behat/Behat/Output/Node/EventListener/AST/OutlineTableListener.php b/src/Behat/Behat/Output/Node/EventListener/AST/OutlineTableListener.php index 9882b7c64..7c0607f89 100644 --- a/src/Behat/Behat/Output/Node/EventListener/AST/OutlineTableListener.php +++ b/src/Behat/Behat/Output/Node/EventListener/AST/OutlineTableListener.php @@ -27,7 +27,7 @@ use Behat\Testwork\Output\Formatter; use Behat\Testwork\Output\Node\EventListener\EventListener; use Behat\Testwork\Tester\Setup\Setup; -use Symfony\Component\EventDispatcher\Event; +use Symfony\Contracts\EventDispatcher\Event; /** * Listens to outline table events and calls appropriate printers. diff --git a/src/Behat/Behat/Output/Node/EventListener/AST/ScenarioNodeListener.php b/src/Behat/Behat/Output/Node/EventListener/AST/ScenarioNodeListener.php index 77ac28e70..17d455d0d 100644 --- a/src/Behat/Behat/Output/Node/EventListener/AST/ScenarioNodeListener.php +++ b/src/Behat/Behat/Output/Node/EventListener/AST/ScenarioNodeListener.php @@ -17,7 +17,7 @@ use Behat\Testwork\EventDispatcher\Event\AfterTested; use Behat\Testwork\Output\Formatter; use Behat\Testwork\Output\Node\EventListener\EventListener; -use Symfony\Component\EventDispatcher\Event; +use Symfony\Contracts\EventDispatcher\Event; /** * Listens to scenario events and calls appropriate printers (header/footer). diff --git a/src/Behat/Behat/Output/Node/EventListener/AST/StepListener.php b/src/Behat/Behat/Output/Node/EventListener/AST/StepListener.php index 0d62a56ef..7392e3448 100644 --- a/src/Behat/Behat/Output/Node/EventListener/AST/StepListener.php +++ b/src/Behat/Behat/Output/Node/EventListener/AST/StepListener.php @@ -20,7 +20,7 @@ use Behat\Gherkin\Node\ScenarioLikeInterface; use Behat\Testwork\Output\Formatter; use Behat\Testwork\Output\Node\EventListener\EventListener; -use Symfony\Component\EventDispatcher\Event; +use Symfony\Contracts\EventDispatcher\Event; /** * Listens to step events and call appropriate printers. diff --git a/src/Behat/Behat/Output/Node/EventListener/AST/SuiteListener.php b/src/Behat/Behat/Output/Node/EventListener/AST/SuiteListener.php index 8e116e06d..a679fe852 100644 --- a/src/Behat/Behat/Output/Node/EventListener/AST/SuiteListener.php +++ b/src/Behat/Behat/Output/Node/EventListener/AST/SuiteListener.php @@ -15,7 +15,7 @@ use Behat\Testwork\EventDispatcher\Event\AfterSuiteTested; use Behat\Testwork\Output\Formatter; use Behat\Testwork\Output\Node\EventListener\EventListener; -use Symfony\Component\EventDispatcher\Event; +use Symfony\Contracts\EventDispatcher\Event; /** * Behat suite listener. diff --git a/src/Behat/Behat/Output/Node/EventListener/Flow/FireOnlySiblingsListener.php b/src/Behat/Behat/Output/Node/EventListener/Flow/FireOnlySiblingsListener.php index 0a4c85674..fad3c179d 100644 --- a/src/Behat/Behat/Output/Node/EventListener/Flow/FireOnlySiblingsListener.php +++ b/src/Behat/Behat/Output/Node/EventListener/Flow/FireOnlySiblingsListener.php @@ -12,7 +12,7 @@ use Behat\Testwork\Output\Formatter; use Behat\Testwork\Output\Node\EventListener\EventListener; -use Symfony\Component\EventDispatcher\Event; +use Symfony\Contracts\EventDispatcher\Event; /** * Behat fire only siblings listener. diff --git a/src/Behat/Behat/Output/Node/EventListener/Flow/FirstBackgroundFiresFirstListener.php b/src/Behat/Behat/Output/Node/EventListener/Flow/FirstBackgroundFiresFirstListener.php index 271b8e580..60200b432 100644 --- a/src/Behat/Behat/Output/Node/EventListener/Flow/FirstBackgroundFiresFirstListener.php +++ b/src/Behat/Behat/Output/Node/EventListener/Flow/FirstBackgroundFiresFirstListener.php @@ -17,7 +17,7 @@ use Behat\Behat\EventDispatcher\Event\ScenarioTested; use Behat\Testwork\Output\Formatter; use Behat\Testwork\Output\Node\EventListener\EventListener; -use Symfony\Component\EventDispatcher\Event; +use Symfony\Contracts\EventDispatcher\Event; /** * Behat first background fires first listener. diff --git a/src/Behat/Behat/Output/Node/EventListener/Flow/OnlyFirstBackgroundFiresListener.php b/src/Behat/Behat/Output/Node/EventListener/Flow/OnlyFirstBackgroundFiresListener.php index 2af5ba2d9..1c4c74bfb 100644 --- a/src/Behat/Behat/Output/Node/EventListener/Flow/OnlyFirstBackgroundFiresListener.php +++ b/src/Behat/Behat/Output/Node/EventListener/Flow/OnlyFirstBackgroundFiresListener.php @@ -16,7 +16,7 @@ use Behat\Behat\EventDispatcher\Event\FeatureTested; use Behat\Testwork\Output\Formatter; use Behat\Testwork\Output\Node\EventListener\EventListener; -use Symfony\Component\EventDispatcher\Event; +use Symfony\Contracts\EventDispatcher\Event; /** * Behat only first background fires listener. diff --git a/src/Behat/Behat/Output/Node/EventListener/JUnit/JUnitDurationListener.php b/src/Behat/Behat/Output/Node/EventListener/JUnit/JUnitDurationListener.php index 2c7372103..b70789a8c 100644 --- a/src/Behat/Behat/Output/Node/EventListener/JUnit/JUnitDurationListener.php +++ b/src/Behat/Behat/Output/Node/EventListener/JUnit/JUnitDurationListener.php @@ -11,7 +11,7 @@ use Behat\Testwork\Counter\Timer; use Behat\Testwork\Output\Formatter; use Behat\Testwork\Output\Node\EventListener\EventListener; -use Symfony\Component\EventDispatcher\Event; +use Symfony\Contracts\EventDispatcher\Event; final class JUnitDurationListener implements EventListener { diff --git a/src/Behat/Behat/Output/Node/EventListener/JUnit/JUnitFeatureElementListener.php b/src/Behat/Behat/Output/Node/EventListener/JUnit/JUnitFeatureElementListener.php index 465efb6ab..479032245 100644 --- a/src/Behat/Behat/Output/Node/EventListener/JUnit/JUnitFeatureElementListener.php +++ b/src/Behat/Behat/Output/Node/EventListener/JUnit/JUnitFeatureElementListener.php @@ -25,7 +25,7 @@ use Behat\Testwork\EventDispatcher\Event\AfterSetup; use Behat\Testwork\Output\Formatter; use Behat\Testwork\Output\Node\EventListener\EventListener; -use Symfony\Component\EventDispatcher\Event; +use Symfony\Contracts\EventDispatcher\Event; /** * Listens to feature, scenario and step events and calls appropriate printers. diff --git a/src/Behat/Behat/Output/Node/EventListener/JUnit/JUnitOutlineStoreListener.php b/src/Behat/Behat/Output/Node/EventListener/JUnit/JUnitOutlineStoreListener.php index 4458ebb73..e16708684 100644 --- a/src/Behat/Behat/Output/Node/EventListener/JUnit/JUnitOutlineStoreListener.php +++ b/src/Behat/Behat/Output/Node/EventListener/JUnit/JUnitOutlineStoreListener.php @@ -18,7 +18,7 @@ use Behat\Testwork\EventDispatcher\Event\BeforeSuiteTested; use Behat\Testwork\Output\Formatter; use Behat\Testwork\Output\Node\EventListener\EventListener; -use Symfony\Component\EventDispatcher\Event; +use Symfony\Contracts\EventDispatcher\Event; /** * Listens for Outline events store the current one diff --git a/src/Behat/Behat/Output/Node/EventListener/Statistics/HookStatsListener.php b/src/Behat/Behat/Output/Node/EventListener/Statistics/HookStatsListener.php index a8d6007b9..92040a7ff 100644 --- a/src/Behat/Behat/Output/Node/EventListener/Statistics/HookStatsListener.php +++ b/src/Behat/Behat/Output/Node/EventListener/Statistics/HookStatsListener.php @@ -20,7 +20,7 @@ use Behat\Testwork\Hook\Tester\Setup\HookedTeardown; use Behat\Testwork\Output\Formatter; use Behat\Testwork\Output\Node\EventListener\EventListener; -use Symfony\Component\EventDispatcher\Event; +use Symfony\Contracts\EventDispatcher\Event; /** * Listens and records hook stats. diff --git a/src/Behat/Behat/Output/Node/EventListener/Statistics/ScenarioStatsListener.php b/src/Behat/Behat/Output/Node/EventListener/Statistics/ScenarioStatsListener.php index f83a38f78..c51982e4c 100644 --- a/src/Behat/Behat/Output/Node/EventListener/Statistics/ScenarioStatsListener.php +++ b/src/Behat/Behat/Output/Node/EventListener/Statistics/ScenarioStatsListener.php @@ -17,7 +17,7 @@ use Behat\Behat\Output\Statistics\Statistics; use Behat\Testwork\Output\Formatter; use Behat\Testwork\Output\Node\EventListener\EventListener; -use Symfony\Component\EventDispatcher\Event; +use Symfony\Contracts\EventDispatcher\Event; /** * Listens and records scenario events to the statistics. diff --git a/src/Behat/Behat/Output/Node/EventListener/Statistics/StatisticsListener.php b/src/Behat/Behat/Output/Node/EventListener/Statistics/StatisticsListener.php index 1845e1b64..f5a4f0065 100644 --- a/src/Behat/Behat/Output/Node/EventListener/Statistics/StatisticsListener.php +++ b/src/Behat/Behat/Output/Node/EventListener/Statistics/StatisticsListener.php @@ -15,7 +15,7 @@ use Behat\Testwork\EventDispatcher\Event\ExerciseCompleted; use Behat\Testwork\Output\Formatter; use Behat\Testwork\Output\Node\EventListener\EventListener; -use Symfony\Component\EventDispatcher\Event; +use Symfony\Contracts\EventDispatcher\Event; /** * Collects general suite stats such as time and memory during its execution and prints it afterwards. diff --git a/src/Behat/Behat/Output/Node/EventListener/Statistics/StepStatsListener.php b/src/Behat/Behat/Output/Node/EventListener/Statistics/StepStatsListener.php index 2f84d052b..2cfcfcf94 100644 --- a/src/Behat/Behat/Output/Node/EventListener/Statistics/StepStatsListener.php +++ b/src/Behat/Behat/Output/Node/EventListener/Statistics/StepStatsListener.php @@ -26,7 +26,7 @@ use Behat\Testwork\Output\Node\EventListener\EventListener; use Behat\Testwork\Tester\Result\ExceptionResult; use Exception; -use Symfony\Component\EventDispatcher\Event; +use Symfony\Contracts\EventDispatcher\Event; /** * Listens and records step events to statistics. diff --git a/src/Behat/Behat/Output/Node/Printer/CounterPrinter.php b/src/Behat/Behat/Output/Node/Printer/CounterPrinter.php index ff567dba3..b6db04fdc 100644 --- a/src/Behat/Behat/Output/Node/Printer/CounterPrinter.php +++ b/src/Behat/Behat/Output/Node/Printer/CounterPrinter.php @@ -12,7 +12,7 @@ use Behat\Behat\Output\Node\Printer\Helper\ResultToStringConverter; use Behat\Testwork\Output\Printer\OutputPrinter; -use Symfony\Component\Translation\TranslatorInterface; +use Symfony\Contracts\Translation\TranslatorInterface; /** * Behat counter printer. @@ -64,12 +64,12 @@ public function printCounters(OutputPrinter $printer, $intro, array $stats) $style = $this->resultConverter->convertResultCodeToString($resultCode); $transId = $style . '_count'; - $message = $this->translator->transChoice($transId, $count, array('%1%' => $count), 'output'); + $message = $this->translator->trans($transId, array('%1%' => $count), 'output'); $detailedStats[] = sprintf('{+%s}%s{-%s}', $style, $message, $style); } - $message = $this->translator->transChoice($intro, $totalCount, array('%1%' => $totalCount), 'output'); + $message = $this->translator->trans($intro, array('%1%' => $totalCount), 'output'); $printer->write($message); if (count($detailedStats)) { diff --git a/src/Behat/Behat/Output/Node/Printer/ListPrinter.php b/src/Behat/Behat/Output/Node/Printer/ListPrinter.php index 31e8388ee..41f92ce97 100644 --- a/src/Behat/Behat/Output/Node/Printer/ListPrinter.php +++ b/src/Behat/Behat/Output/Node/Printer/ListPrinter.php @@ -18,7 +18,7 @@ use Behat\Testwork\Exception\ExceptionPresenter; use Behat\Testwork\Output\Printer\OutputPrinter; use Behat\Testwork\Tester\Result\TestResult; -use Symfony\Component\Translation\TranslatorInterface; +use Symfony\Contracts\Translation\TranslatorInterface; /** * Behat list printer. diff --git a/src/Behat/Behat/Snippet/Printer/ConsoleSnippetPrinter.php b/src/Behat/Behat/Snippet/Printer/ConsoleSnippetPrinter.php index 7a5b36e74..e32d17610 100644 --- a/src/Behat/Behat/Snippet/Printer/ConsoleSnippetPrinter.php +++ b/src/Behat/Behat/Snippet/Printer/ConsoleSnippetPrinter.php @@ -14,7 +14,7 @@ use Behat\Gherkin\Node\StepNode; use Symfony\Component\Console\Formatter\OutputFormatterStyle; use Symfony\Component\Console\Output\OutputInterface; -use Symfony\Component\Translation\TranslatorInterface; +use Symfony\Contracts\Translation\TranslatorInterface; /** * Behat console-based snippet printer. diff --git a/src/Behat/Behat/Transformation/Transformer/RepositoryArgumentTransformer.php b/src/Behat/Behat/Transformation/Transformer/RepositoryArgumentTransformer.php index 795f42fae..02b889f7b 100644 --- a/src/Behat/Behat/Transformation/Transformer/RepositoryArgumentTransformer.php +++ b/src/Behat/Behat/Transformation/Transformer/RepositoryArgumentTransformer.php @@ -19,7 +19,7 @@ use Behat\Behat\Transformation\TransformationRepository; use Behat\Gherkin\Node\ArgumentInterface; use Behat\Testwork\Call\CallCenter; -use Symfony\Component\Translation\TranslatorInterface; +use Symfony\Contracts\Translation\TranslatorInterface; /** * Argument transformer based on transformations repository. diff --git a/src/Behat/Testwork/EventDispatcher/Event/ExerciseCompleted.php b/src/Behat/Testwork/EventDispatcher/Event/ExerciseCompleted.php index 026592bdc..614c06196 100644 --- a/src/Behat/Testwork/EventDispatcher/Event/ExerciseCompleted.php +++ b/src/Behat/Testwork/EventDispatcher/Event/ExerciseCompleted.php @@ -11,7 +11,7 @@ namespace Behat\Testwork\EventDispatcher\Event; use Behat\Testwork\Specification\SpecificationIterator; -use Symfony\Component\EventDispatcher\Event; +use Symfony\Contracts\EventDispatcher\Event; /** * Represents an exercise event. diff --git a/src/Behat/Testwork/EventDispatcher/Event/LifecycleEvent.php b/src/Behat/Testwork/EventDispatcher/Event/LifecycleEvent.php index 50191b463..96e1820e8 100644 --- a/src/Behat/Testwork/EventDispatcher/Event/LifecycleEvent.php +++ b/src/Behat/Testwork/EventDispatcher/Event/LifecycleEvent.php @@ -12,7 +12,7 @@ use Behat\Testwork\Environment\Environment; use Behat\Testwork\Suite\Suite; -use Symfony\Component\EventDispatcher\Event; +use Symfony\Contracts\EventDispatcher\Event; /** * Represents an event which holds references to current suite and environment. diff --git a/src/Behat/Testwork/EventDispatcher/Tester/EventDispatchingExercise.php b/src/Behat/Testwork/EventDispatcher/Tester/EventDispatchingExercise.php index 10f34196e..38b0b36cf 100644 --- a/src/Behat/Testwork/EventDispatcher/Tester/EventDispatchingExercise.php +++ b/src/Behat/Testwork/EventDispatcher/Tester/EventDispatchingExercise.php @@ -52,12 +52,12 @@ public function __construct(Exercise $baseExercise, EventDispatcherInterface $ev public function setUp(array $iterators, $skip) { $event = new BeforeExerciseCompleted($iterators); - $this->eventDispatcher->dispatch($event::BEFORE, $event); + $this->eventDispatcher->dispatch($event, $event::BEFORE); $setup = $this->baseExercise->setUp($iterators, $skip); $event = new AfterExerciseSetup($iterators, $setup); - $this->eventDispatcher->dispatch($event::AFTER_SETUP, $event); + $this->eventDispatcher->dispatch($event, $event::AFTER_SETUP); return $setup; } @@ -76,12 +76,12 @@ public function test(array $iterators, $skip = false) public function tearDown(array $iterators, $skip, TestResult $result) { $event = new BeforeExerciseTeardown($iterators, $result); - $this->eventDispatcher->dispatch($event::BEFORE_TEARDOWN, $event); + $this->eventDispatcher->dispatch($event, $event::BEFORE_TEARDOWN); $teardown = $this->baseExercise->tearDown($iterators, $skip, $result); $event = new AfterExerciseCompleted($iterators, $result, $teardown); - $this->eventDispatcher->dispatch($event::AFTER, $event); + $this->eventDispatcher->dispatch($event, $event::AFTER); return $teardown; } diff --git a/src/Behat/Testwork/EventDispatcher/Tester/EventDispatchingSuiteTester.php b/src/Behat/Testwork/EventDispatcher/Tester/EventDispatchingSuiteTester.php index 84b2d07c0..3dbeae502 100644 --- a/src/Behat/Testwork/EventDispatcher/Tester/EventDispatchingSuiteTester.php +++ b/src/Behat/Testwork/EventDispatcher/Tester/EventDispatchingSuiteTester.php @@ -54,12 +54,12 @@ public function __construct(SuiteTester $baseTester, EventDispatcherInterface $e public function setUp(Environment $env, SpecificationIterator $iterator, $skip) { $event = new BeforeSuiteTested($env, $iterator); - $this->eventDispatcher->dispatch($event::BEFORE, $event); + $this->eventDispatcher->dispatch($event, $event::BEFORE); $setup = $this->baseTester->setUp($env, $iterator, $skip); $event = new AfterSuiteSetup($env, $iterator, $setup); - $this->eventDispatcher->dispatch($event::AFTER_SETUP, $event); + $this->eventDispatcher->dispatch($event, $event::AFTER_SETUP); return $setup; } @@ -78,12 +78,12 @@ public function test(Environment $env, SpecificationIterator $iterator, $skip = public function tearDown(Environment $env, SpecificationIterator $iterator, $skip, TestResult $result) { $event = new BeforeSuiteTeardown($env, $iterator, $result); - $this->eventDispatcher->dispatch($event::BEFORE_TEARDOWN, $event); + $this->eventDispatcher->dispatch($event, $event::BEFORE_TEARDOWN); $teardown = $this->baseTester->tearDown($env, $iterator, $skip, $result); $event = new AfterSuiteTested($env, $iterator, $result, $teardown); - $this->eventDispatcher->dispatch($event::AFTER, $event); + $this->eventDispatcher->dispatch($event, $event::AFTER); return $teardown; } diff --git a/src/Behat/Testwork/EventDispatcher/TestworkEventDispatcher.php b/src/Behat/Testwork/EventDispatcher/TestworkEventDispatcher.php index c1200f300..890b157ed 100644 --- a/src/Behat/Testwork/EventDispatcher/TestworkEventDispatcher.php +++ b/src/Behat/Testwork/EventDispatcher/TestworkEventDispatcher.php @@ -10,7 +10,7 @@ namespace Behat\Testwork\EventDispatcher; -use Symfony\Component\EventDispatcher\Event; +use Symfony\Contracts\EventDispatcher\Event; use Symfony\Component\EventDispatcher\EventDispatcher; /** @@ -26,7 +26,7 @@ final class TestworkEventDispatcher extends EventDispatcher /** * {@inheritdoc} */ - public function dispatch($eventName, Event $event = null) + public function dispatch(object $event, string $eventName = null): object { if (null === $event) { $event = new Event(); @@ -36,7 +36,7 @@ public function dispatch($eventName, Event $event = null) $event->setName($eventName); } - $this->doDispatch($this->getListeners($eventName), $eventName, $event); + $this->callListeners($this->getListeners($eventName), $eventName, $event); return $event; } @@ -44,7 +44,7 @@ public function dispatch($eventName, Event $event = null) /** * {@inheritdoc} */ - public function getListeners($eventName = null) + public function getListeners(string $eventName = null) { if (null == $eventName || self::BEFORE_ALL_EVENTS === $eventName) { return parent::getListeners($eventName); diff --git a/src/Behat/Testwork/Output/Node/EventListener/ChainEventListener.php b/src/Behat/Testwork/Output/Node/EventListener/ChainEventListener.php index 0c76bac39..76695753a 100644 --- a/src/Behat/Testwork/Output/Node/EventListener/ChainEventListener.php +++ b/src/Behat/Testwork/Output/Node/EventListener/ChainEventListener.php @@ -14,7 +14,7 @@ use Behat\Testwork\Output\Formatter; use Countable; use IteratorAggregate; -use Symfony\Component\EventDispatcher\Event; +use Symfony\Contracts\EventDispatcher\Event; /** * Used to compose formatter event listeners. diff --git a/src/Behat/Testwork/Output/Node/EventListener/EventListener.php b/src/Behat/Testwork/Output/Node/EventListener/EventListener.php index 6fbc078ff..e6145265c 100644 --- a/src/Behat/Testwork/Output/Node/EventListener/EventListener.php +++ b/src/Behat/Testwork/Output/Node/EventListener/EventListener.php @@ -11,7 +11,7 @@ namespace Behat\Testwork\Output\Node\EventListener; use Behat\Testwork\Output\Formatter; -use Symfony\Component\EventDispatcher\Event; +use Symfony\Contracts\EventDispatcher\Event; /** * Used to define formatter event listeners. diff --git a/src/Behat/Testwork/Output/Node/EventListener/Flow/FireOnlyIfFormatterParameterListener.php b/src/Behat/Testwork/Output/Node/EventListener/Flow/FireOnlyIfFormatterParameterListener.php index 0df21eb3a..bbc8d136e 100644 --- a/src/Behat/Testwork/Output/Node/EventListener/Flow/FireOnlyIfFormatterParameterListener.php +++ b/src/Behat/Testwork/Output/Node/EventListener/Flow/FireOnlyIfFormatterParameterListener.php @@ -12,7 +12,7 @@ use Behat\Testwork\Output\Formatter; use Behat\Testwork\Output\Node\EventListener\EventListener; -use Symfony\Component\EventDispatcher\Event; +use Symfony\Contracts\EventDispatcher\Event; /** * Catches all events, but proxies them only if formatter has specific parameter set to a specific value. diff --git a/src/Behat/Testwork/Output/NodeEventListeningFormatter.php b/src/Behat/Testwork/Output/NodeEventListeningFormatter.php index 3894d49fa..8e5c32a04 100644 --- a/src/Behat/Testwork/Output/NodeEventListeningFormatter.php +++ b/src/Behat/Testwork/Output/NodeEventListeningFormatter.php @@ -13,7 +13,7 @@ use Behat\Testwork\EventDispatcher\TestworkEventDispatcher; use Behat\Testwork\Output\Node\EventListener\EventListener; use Behat\Testwork\Output\Printer\OutputPrinter; -use Symfony\Component\EventDispatcher\Event; +use Symfony\Contracts\EventDispatcher\Event; /** * Formatter built around the idea of event delegation and composition. diff --git a/src/Behat/Testwork/ServiceContainer/Configuration/ConfigurationTree.php b/src/Behat/Testwork/ServiceContainer/Configuration/ConfigurationTree.php index d713cbc9b..445266716 100644 --- a/src/Behat/Testwork/ServiceContainer/Configuration/ConfigurationTree.php +++ b/src/Behat/Testwork/ServiceContainer/Configuration/ConfigurationTree.php @@ -30,8 +30,8 @@ final class ConfigurationTree */ public function getConfigTree(array $extensions) { - $tree = new TreeBuilder(); - $root = $tree->root('testwork'); + $tree = new TreeBuilder('testwork'); + $root = $tree->getRootNode(); foreach ($extensions as $extension) { $extension->configure($root->children()->arrayNode($extension->getConfigKey())); From 353770f067a957b2ab8c94fe43a09339eb18b5de Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Javier=20D=C3=ADaz?= Date: Sat, 23 Nov 2019 16:23:52 +0100 Subject: [PATCH 172/567] Fix to use the correct placeholder in the internationalization --- i18n.php | 254 +++++++++--------- .../Cli/InteractiveContextIdentifier.php | 2 +- .../Output/Node/Printer/CounterPrinter.php | 4 +- .../Snippet/Printer/ConsoleSnippetPrinter.php | 4 +- .../Testwork/Cli/DumpReferenceCommand.php | 2 + 5 files changed, 134 insertions(+), 132 deletions(-) diff --git a/i18n.php b/i18n.php index 44eda3c91..393181d39 100644 --- a/i18n.php +++ b/i18n.php @@ -1,217 +1,217 @@ array( - 'snippet_context_choice' => '%1% suite has undefined steps. Please choose the context to generate snippets:', - 'snippet_proposal_title' => '%1% has missing steps. Define them with these snippets:', - 'snippet_missing_title' => 'Use --snippets-for CLI option to generate snippets for following %1% suite steps:', + 'snippet_context_choice' => '%count% suite has undefined steps. Please choose the context to generate snippets:', + 'snippet_proposal_title' => '%count% has missing steps. Define them with these snippets:', + 'snippet_missing_title' => 'Use --snippets-for CLI option to generate snippets for following %count% suite steps:', 'skipped_scenarios_title' => 'Skipped scenarios:', 'failed_scenarios_title' => 'Failed scenarios:', 'failed_hooks_title' => 'Failed hooks:', 'failed_steps_title' => 'Failed steps:', 'pending_steps_title' => 'Pending steps:', - 'scenarios_count' => '{0} No scenarios|{1} 1 scenario|]1,Inf] %1% scenarios', - 'steps_count' => '{0} No steps|{1} 1 step|]1,Inf] %1% steps', - 'passed_count' => '[1,Inf] %1% passed', - 'failed_count' => '[1,Inf] %1% failed', - 'pending_count' => '[1,Inf] %1% pending', - 'undefined_count' => '[1,Inf] %1% undefined', - 'skipped_count' => '[1,Inf] %1% skipped', + 'scenarios_count' => '{0} No scenarios|{1} 1 scenario|]1,Inf] %count% scenarios', + 'steps_count' => '{0} No steps|{1} 1 step|]1,Inf] %count% steps', + 'passed_count' => '[1,Inf] %count% passed', + 'failed_count' => '[1,Inf] %count% failed', + 'pending_count' => '[1,Inf] %count% pending', + 'undefined_count' => '[1,Inf] %count% undefined', + 'skipped_count' => '[1,Inf] %count% skipped', ), 'cs' => array( - 'snippet_proposal_title' => '%1% obsahuje chybné kroky. Definujte je za použití následujícího kódu:', - 'snippet_missing_title' => 'Snippety pro následující kroky v sadě %1% nebyly vygenerovány (zkontrolujte správnost konfigurace):', + 'snippet_proposal_title' => '%count% obsahuje chybné kroky. Definujte je za použití následujícího kódu:', + 'snippet_missing_title' => 'Snippety pro následující kroky v sadě %count% nebyly vygenerovány (zkontrolujte správnost konfigurace):', 'failed_scenarios_title' => 'Chybné scénáře:', 'failed_hooks_title' => 'Chybné hooky:', 'failed_steps_title' => 'Chybné kroky:', 'pending_steps_title' => 'Čekající kroky:', - 'scenarios_count' => '{0} Žádný scénář|{1} 1 scénář|{2,3,4} %1% scénáře|]4,Inf] %1% scénářů', - 'steps_count' => '{0} Žádné kroky|{1} 1 krok|{2,3,4} %1% kroky|]4,Inf] %1% kroků', - 'passed_count' => '{1} %1% prošel|{2,3,4} %1% prošly|]4,Inf] %1% prošlo', - 'failed_count' => '{1} %1% selhal|{2,3,4} %1% selhaly|]4,Inf] %1% selhalo', - 'pending_count' => '{1} %1% čeká|{2,3,4} %1% čekají|]4,Inf] %1% čeká', - 'undefined_count' => '{1} %1% nedefinován|{2,3,4} %1% nedefinovány|]4,Inf] %1% nedefinováno', - 'skipped_count' => '{1} %1% přeskočen|{2,3,4} %1% přeskočeny|]4,Inf] %1% přeskočeno', + 'scenarios_count' => '{0} Žádný scénář|{1} 1 scénář|{2,3,4} %count% scénáře|]4,Inf] %count% scénářů', + 'steps_count' => '{0} Žádné kroky|{1} 1 krok|{2,3,4} %count% kroky|]4,Inf] %count% kroků', + 'passed_count' => '{1} %count% prošel|{2,3,4} %count% prošly|]4,Inf] %count% prošlo', + 'failed_count' => '{1} %count% selhal|{2,3,4} %count% selhaly|]4,Inf] %count% selhalo', + 'pending_count' => '{1} %count% čeká|{2,3,4} %count% čekají|]4,Inf] %count% čeká', + 'undefined_count' => '{1} %count% nedefinován|{2,3,4} %count% nedefinovány|]4,Inf] %count% nedefinováno', + 'skipped_count' => '{1} %count% přeskočen|{2,3,4} %count% přeskočeny|]4,Inf] %count% přeskočeno', ), 'de' => array( - 'snippet_proposal_title' => '%1% hat fehlende Schritte. Definiere diese mit den folgenden Snippets:', - 'snippet_missing_title' => 'Snippets für die folgenden Schritte in der %1% Suite wurden nicht generiert (Konfiguration überprüfen):', + 'snippet_proposal_title' => '%count% hat fehlende Schritte. Definiere diese mit den folgenden Snippets:', + 'snippet_missing_title' => 'Snippets für die folgenden Schritte in der %count% Suite wurden nicht generiert (Konfiguration überprüfen):', 'failed_scenarios_title' => 'Fehlgeschlagene Szenarien:', 'failed_hooks_title' => 'Fehlgeschlagene Hooks:', 'failed_steps_title' => 'Fehlgeschlagene Schritte:', 'pending_steps_title' => 'Ausstehende Schritte:', - 'scenarios_count' => '{0} Kein Szenario|{1} 1 Szenario|]1,Inf] %1% Szenarien', - 'steps_count' => '{0} Kein Schritt|{1} 1 Schritt|]1,Inf] %1% Schritte', - 'passed_count' => '[1,Inf] %1% bestanden', - 'failed_count' => '[1,Inf] %1% fehlgeschlagen', - 'pending_count' => '[1,Inf] %1% ausstehend', - 'undefined_count' => '[1,Inf] %1% nicht definiert', - 'skipped_count' => '[1,Inf] %1% übersprungen', + 'scenarios_count' => '{0} Kein Szenario|{1} 1 Szenario|]1,Inf] %count% Szenarien', + 'steps_count' => '{0} Kein Schritt|{1} 1 Schritt|]1,Inf] %count% Schritte', + 'passed_count' => '[1,Inf] %count% bestanden', + 'failed_count' => '[1,Inf] %count% fehlgeschlagen', + 'pending_count' => '[1,Inf] %count% ausstehend', + 'undefined_count' => '[1,Inf] %count% nicht definiert', + 'skipped_count' => '[1,Inf] %count% übersprungen', ), 'es' => array( - 'snippet_proposal_title' => 'A %1% le faltan pasos. Defínelos con estos pasos:', - 'snippet_missing_title' => 'Las plantillas para los siguientes pasos en %1% no fueron generadas (revisa tu configuración):', + 'snippet_proposal_title' => 'A %count% le faltan pasos. Defínelos con estos pasos:', + 'snippet_missing_title' => 'Las plantillas para los siguientes pasos en %count% no fueron generadas (revisa tu configuración):', 'failed_scenarios_title' => 'Escenarios fallidos:', 'failed_hooks_title' => 'Hooks fallidos:', 'failed_steps_title' => 'Pasos fallidos:', 'pending_steps_title' => 'Pasos pendientes:', - 'scenarios_count' => '{0} Ningún escenario|{1} 1 escenario|]1,Inf] %1% escenarios', - 'steps_count' => '{0} Ningún paso|{1} 1 paso|]1,Inf] %1% pasos', - 'passed_count' => '[1,Inf] %1% pasaron', - 'failed_count' => '[1,Inf] %1% fallaron', - 'pending_count' => '[1,Inf] %1% pendientes', - 'undefined_count' => '[1,Inf] %1% por definir', - 'skipped_count' => '[1,Inf] %1% saltadas', + 'scenarios_count' => '{0} Ningún escenario|{1} 1 escenario|]1,Inf] %count% escenarios', + 'steps_count' => '{0} Ningún paso|{1} 1 paso|]1,Inf] %count% pasos', + 'passed_count' => '[1,Inf] %count% pasaron', + 'failed_count' => '[1,Inf] %count% fallaron', + 'pending_count' => '[1,Inf] %count% pendientes', + 'undefined_count' => '[1,Inf] %count% por definir', + 'skipped_count' => '[1,Inf] %count% saltadas', ), 'fr' => array( - 'snippet_proposal_title' => '%1% a des étapes manquantes. Définissez-les avec les modèles suivants :', - 'snippet_missing_title' => 'Les modèles des étapes de la suite %1% n\'ont pas été générés (vérifiez votre configuration):', + 'snippet_proposal_title' => '%count% a des étapes manquantes. Définissez-les avec les modèles suivants :', + 'snippet_missing_title' => 'Les modèles des étapes de la suite %count% n\'ont pas été générés (vérifiez votre configuration):', 'failed_scenarios_title' => 'Scénarios échoués:', 'failed_hooks_title' => 'Hooks échoués:', 'failed_steps_title' => 'Etapes échouées:', 'pending_steps_title' => 'Etapes en attente:', - 'scenarios_count' => '{0} Pas de scénario|{1} 1 scénario|]1,Inf] %1% scénarios', - 'steps_count' => '{0} Pas d\'étape|{1} 1 étape|]1,Inf] %1% étapes', - 'passed_count' => '[1,Inf] %1% succès', - 'failed_count' => '[1,Inf] %1% échecs', - 'pending_count' => '[1,Inf] %1% en attente', - 'undefined_count' => '[1,Inf] %1% indéfinis', - 'skipped_count' => '[1,Inf] %1% ignorés', + 'scenarios_count' => '{0} Pas de scénario|{1} 1 scénario|]1,Inf] %count% scénarios', + 'steps_count' => '{0} Pas d\'étape|{1} 1 étape|]1,Inf] %count% étapes', + 'passed_count' => '[1,Inf] %count% succès', + 'failed_count' => '[1,Inf] %count% échecs', + 'pending_count' => '[1,Inf] %count% en attente', + 'undefined_count' => '[1,Inf] %count% indéfinis', + 'skipped_count' => '[1,Inf] %count% ignorés', ), 'it' => array( - 'snippet_proposal_title' => '%1% ha dei passaggi mancanti. Definiscili con questi snippet:', - 'snippet_missing_title' => 'Gli snippet per i seguenti passaggi della suite %1% non sono stati generati (verifica la configurazione):', + 'snippet_proposal_title' => '%count% ha dei passaggi mancanti. Definiscili con questi snippet:', + 'snippet_missing_title' => 'Gli snippet per i seguenti passaggi della suite %count% non sono stati generati (verifica la configurazione):', 'failed_scenarios_title' => 'Scenari falliti:', 'failed_hooks_title' => 'Hook falliti:', 'failed_steps_title' => 'Passaggi falliti:', 'pending_steps_title' => 'Passaggi in sospeso:', - 'scenarios_count' => '{0} Nessuno scenario|{1} 1 scenario|]1,Inf] %1% scenari', - 'steps_count' => '{0} Nessun passaggio|{1} 1 passaggio|]1,Inf] %1% passaggi', - 'passed_count' => '{1} 1 superato|]1,Inf] %1% superati', - 'failed_count' => '{1} 1 fallito|]1,Inf] %1% falliti', - 'pending_count' => '[1,Inf] %1% in sospeso', - 'undefined_count' => '{1} 1 non definito|]1,Inf] %1% non definiti', - 'skipped_count' => '{1} 1 ignorato|]1,Inf] %1% ignorati', + 'scenarios_count' => '{0} Nessuno scenario|{1} 1 scenario|]1,Inf] %count% scenari', + 'steps_count' => '{0} Nessun passaggio|{1} 1 passaggio|]1,Inf] %count% passaggi', + 'passed_count' => '{1} 1 superato|]1,Inf] %count% superati', + 'failed_count' => '{1} 1 fallito|]1,Inf] %count% falliti', + 'pending_count' => '[1,Inf] %count% in sospeso', + 'undefined_count' => '{1} 1 non definito|]1,Inf] %count% non definiti', + 'skipped_count' => '{1} 1 ignorato|]1,Inf] %count% ignorati', ), 'ja' => array( - 'snippet_proposal_title' => '%1% のステップが見つかりません。 次のスニペットで定義できます:', - 'snippet_missing_title' => '以下のステップのスニペットは%1%スイートに生成されませんでした(設定を確認してください):', + 'snippet_proposal_title' => '%count% のステップが見つかりません。 次のスニペットで定義できます:', + 'snippet_missing_title' => '以下のステップのスニペットは%count%スイートに生成されませんでした(設定を確認してください):', 'skipped_scenarios_title' => 'スキップした シナリオ:', 'failed_scenarios_title' => '失敗した シナリオ:', 'failed_hooks_title' => '失敗した フック:', 'failed_steps_title' => '失敗した ステップ:', 'pending_steps_title' => '保留中のステップ:', - 'scenarios_count' => '{0} No scenarios|{1} 1 個のシナリオ|]1,Inf] %1% 個のシナリオ', - 'steps_count' => '{0} ステップがありません|{1} 1 個のステップ|]1,Inf] %1% 個のステップ', - 'passed_count' => '[1,Inf] %1% 個成功', - 'failed_count' => '[1,Inf] %1% 個失敗', - 'pending_count' => '[1,Inf] %1% 個保留', - 'undefined_count' => '[1,Inf] %1% 個未定義', - 'skipped_count' => '[1,Inf] %1% 個スキップ', + 'scenarios_count' => '{0} No scenarios|{1} 1 個のシナリオ|]1,Inf] %count% 個のシナリオ', + 'steps_count' => '{0} ステップがありません|{1} 1 個のステップ|]1,Inf] %count% 個のステップ', + 'passed_count' => '[1,Inf] %count% 個成功', + 'failed_count' => '[1,Inf] %count% 個失敗', + 'pending_count' => '[1,Inf] %count% 個保留', + 'undefined_count' => '[1,Inf] %count% 個未定義', + 'skipped_count' => '[1,Inf] %count% 個スキップ', ), 'nl' => array( - 'snippet_proposal_title' => 'Ontbrekende stappen in %1%. Definieer ze met de volgende fragmenten:', - 'snippet_missing_title' => 'Fragmenten voor de volgende stappen in de %1% suite werden niet gegenereerd (controleer de configuratie):', + 'snippet_proposal_title' => 'Ontbrekende stappen in %count%. Definieer ze met de volgende fragmenten:', + 'snippet_missing_title' => 'Fragmenten voor de volgende stappen in de %count% suite werden niet gegenereerd (controleer de configuratie):', 'failed_scenarios_title' => 'Gefaalde scenario\'s:', 'failed_hooks_title' => 'Gefaalde hooks:', 'failed_steps_title' => 'Gefaalde stappen:', 'pending_steps_title' => 'Onafgewerkte stappen:', - 'scenarios_count' => '{0} Geen scenario\'s|{1} 1 scenario|]1,Inf] %1% scenario\'s', - 'steps_count' => '{0} Geen stappen|{1} 1 stap|]1,Inf] %1% stappen', - 'passed_count' => '[1,Inf] %1% geslaagd', - 'failed_count' => '[1,Inf] %1% gefaald', - 'pending_count' => '[1,Inf] %1% wachtende', - 'undefined_count' => '[1,Inf] %1% niet gedefinieerd', - 'skipped_count' => '[1,Inf] %1% overgeslagen', + 'scenarios_count' => '{0} Geen scenario\'s|{1} 1 scenario|]1,Inf] %count% scenario\'s', + 'steps_count' => '{0} Geen stappen|{1} 1 stap|]1,Inf] %count% stappen', + 'passed_count' => '[1,Inf] %count% geslaagd', + 'failed_count' => '[1,Inf] %count% gefaald', + 'pending_count' => '[1,Inf] %count% wachtende', + 'undefined_count' => '[1,Inf] %count% niet gedefinieerd', + 'skipped_count' => '[1,Inf] %count% overgeslagen', ), 'no' => array( - 'snippet_proposal_title' => '%1% mangler steg. Definer dem med disse snuttene:', - 'snippet_missing_title' => 'Snutter for de følgende stegene i %1%-samlingen ble ikke laget. (Sjekk konfigurasjonen din.):', + 'snippet_proposal_title' => '%count% mangler steg. Definer dem med disse snuttene:', + 'snippet_missing_title' => 'Snutter for de følgende stegene i %count%-samlingen ble ikke laget. (Sjekk konfigurasjonen din.):', 'failed_scenarios_title' => 'Feilende scenarier:', 'failed_hooks_title' => 'Feilende hooks:', 'failed_steps_title' => 'Feilende steg:', 'pending_steps_title' => 'Ikke implementerte steg:', - 'scenarios_count' => '{0} Ingen scenarier|{1} 1 scenario|]1,Inf] %1% scenarier', - 'steps_count' => '{0} Ingen steg|{1} 1 steg|]1,Inf] %1% steg', - 'passed_count' => '[1,Inf] %1% ok', - 'failed_count' => '[1,Inf] %1% feilet', - 'pending_count' => '[1,Inf] %1% ikke implementert', - 'undefined_count' => '[1,Inf] %1% ikke definert', - 'skipped_count' => '[1,Inf] %1% hoppet over', + 'scenarios_count' => '{0} Ingen scenarier|{1} 1 scenario|]1,Inf] %count% scenarier', + 'steps_count' => '{0} Ingen steg|{1} 1 steg|]1,Inf] %count% steg', + 'passed_count' => '[1,Inf] %count% ok', + 'failed_count' => '[1,Inf] %count% feilet', + 'pending_count' => '[1,Inf] %count% ikke implementert', + 'undefined_count' => '[1,Inf] %count% ikke definert', + 'skipped_count' => '[1,Inf] %count% hoppet over', ), 'pl' => array( - 'snippet_proposal_title' => '%1% zawiera brakujące kroki. Utwórz je korzystając z tych fragmentów kodu:', - 'snippet_missing_title' => 'Fragmenty kodu dla następujących kroków %1% nie zostały wygenerowane (sprawdź swoją konfigurację):', + 'snippet_proposal_title' => '%count% zawiera brakujące kroki. Utwórz je korzystając z tych fragmentów kodu:', + 'snippet_missing_title' => 'Fragmenty kodu dla następujących kroków %count% nie zostały wygenerowane (sprawdź swoją konfigurację):', 'failed_scenarios_title' => 'Nieudane scenariusze:', 'failed_hooks_title' => 'Nieudane hooki:', 'failed_steps_title' => 'Nieudane kroki', 'pending_steps_title' => 'Oczekujące kroki', - 'scenarios_count' => '{0} Brak scenariuszy|{1} 1 scenariusz|{2,3,4,22,23,24,32,33,34,42,43,44} %1% scenariusze|]4,Inf] %1% scenariuszy', - 'steps_count' => '{0} Brak kroków|{1} 1 krok|{2,3,4,22,23,24,32,33,34,42,43,44} %1% kroki|]4,Inf] %1% kroków', - 'passed_count' => '{1} %1% udany|{2,3,4,22,23,24,32,33,34,42,43,44} %1% udane|]4,Inf] %1% udanych', - 'failed_count' => '{1} %1% nieudany|{2,3,4,22,23,24,32,33,34,42,43,44} %1% nieudane|]4,Inf] %1% nieudanych', - 'pending_count' => '{1} %1% oczekujący|{2,3,4,22,23,24,32,33,34,42,43,44} %1% oczekujące|]4,Inf] %1% oczekujących', - 'undefined_count' => '{1} %1% niezdefiniowany|{2,3,4,22,23,24,32,33,34,42,43,44} %1% niezdefiniowane|]4,Inf] %1% niezdefiniowanych', - 'skipped_count' => '{1} %1% pominięty|{2,3,4,22,23,24,32,33,34,42,43,44} %1% pominięte|]4,Inf] %1% pominiętych', + 'scenarios_count' => '{0} Brak scenariuszy|{1} 1 scenariusz|{2,3,4,22,23,24,32,33,34,42,43,44} %count% scenariusze|]4,Inf] %count% scenariuszy', + 'steps_count' => '{0} Brak kroków|{1} 1 krok|{2,3,4,22,23,24,32,33,34,42,43,44} %count% kroki|]4,Inf] %count% kroków', + 'passed_count' => '{1} %count% udany|{2,3,4,22,23,24,32,33,34,42,43,44} %count% udane|]4,Inf] %count% udanych', + 'failed_count' => '{1} %count% nieudany|{2,3,4,22,23,24,32,33,34,42,43,44} %count% nieudane|]4,Inf] %count% nieudanych', + 'pending_count' => '{1} %count% oczekujący|{2,3,4,22,23,24,32,33,34,42,43,44} %count% oczekujące|]4,Inf] %count% oczekujących', + 'undefined_count' => '{1} %count% niezdefiniowany|{2,3,4,22,23,24,32,33,34,42,43,44} %count% niezdefiniowane|]4,Inf] %count% niezdefiniowanych', + 'skipped_count' => '{1} %count% pominięty|{2,3,4,22,23,24,32,33,34,42,43,44} %count% pominięte|]4,Inf] %count% pominiętych', ), 'pt' => array( - 'snippet_proposal_title' => '%1% contém definições em falta. Defina-as com estes exemplos:', - 'snippet_missing_title' => 'Os exemplos para as seguintes definições da suite %1% não foram gerados (verifique a configuração):', + 'snippet_proposal_title' => '%count% contém definições em falta. Defina-as com estes exemplos:', + 'snippet_missing_title' => 'Os exemplos para as seguintes definições da suite %count% não foram gerados (verifique a configuração):', 'failed_scenarios_title' => 'Cenários que falharam:', 'failed_hooks_title' => 'Hooks que falharam:', 'failed_steps_title' => 'Definições que falharam:', 'pending_steps_title' => 'Definições por definir:', - 'scenarios_count' => '{0} Nenhum cenário|{1} 1 cenário|]1,Inf] %1% cenários', - 'steps_count' => '{0} Nenhuma definição|{1} 1 definição|]1,Inf] %1% definições', - 'passed_count' => '{1} passou|]1,Inf] %1% passaram', - 'failed_count' => '{1} falhou|]1,Inf] %1% falharam', - 'pending_count' => '[1,Inf] %1% por definir', - 'undefined_count' => '{1} indefinido|]1,Inf] %1% indefinidos', - 'skipped_count' => '{1} omitido|]1,Inf] %1% omitidos', + 'scenarios_count' => '{0} Nenhum cenário|{1} 1 cenário|]1,Inf] %count% cenários', + 'steps_count' => '{0} Nenhuma definição|{1} 1 definição|]1,Inf] %count% definições', + 'passed_count' => '{1} passou|]1,Inf] %count% passaram', + 'failed_count' => '{1} falhou|]1,Inf] %count% falharam', + 'pending_count' => '[1,Inf] %count% por definir', + 'undefined_count' => '{1} indefinido|]1,Inf] %count% indefinidos', + 'skipped_count' => '{1} omitido|]1,Inf] %count% omitidos', ), 'pt-BR' => array( - 'snippet_proposal_title' => '%1% possue etapas faltando. Defina elas com esse(s) trecho(s) de código:', - 'snippet_missing_title' => 'Trecho de códigos para as seguintes etapas em %1% suite não foram geradas (verique sua configuração):', + 'snippet_proposal_title' => '%count% possue etapas faltando. Defina elas com esse(s) trecho(s) de código:', + 'snippet_missing_title' => 'Trecho de códigos para as seguintes etapas em %count% suite não foram geradas (verique sua configuração):', 'failed_scenarios_title' => 'Cenários falhados:', 'failed_hooks_title' => 'Hooks falhados:', 'failed_steps_title' => 'Etapas falhadas:', 'pending_steps_title' => 'Etapas pendentes:', - 'scenarios_count' => '{0} Nenhum cenário|{1} 1 cenário|]1,Inf] %1% cenários', - 'steps_count' => '{0} Nenhuma etapa|{1} 1 etapa|]1,Inf] %1% etapas', - 'passed_count' => '[1,Inf] %1% passou', - 'failed_count' => '[1,Inf] %1% falhou', - 'pending_count' => '[1,Inf] %1% pendente', - 'undefined_count' => '[1,Inf] %1% indefinido', - 'skipped_count' => '[1,Inf] %1% pulado', + 'scenarios_count' => '{0} Nenhum cenário|{1} 1 cenário|]1,Inf] %count% cenários', + 'steps_count' => '{0} Nenhuma etapa|{1} 1 etapa|]1,Inf] %count% etapas', + 'passed_count' => '[1,Inf] %count% passou', + 'failed_count' => '[1,Inf] %count% falhou', + 'pending_count' => '[1,Inf] %count% pendente', + 'undefined_count' => '[1,Inf] %count% indefinido', + 'skipped_count' => '[1,Inf] %count% pulado', ), 'ro' => array( - 'snippet_proposal_title' => '%1% are pași lipsa. Puteți implementa pașii cu ajutorul acestor fragmente de cod:', - 'snippet_missing_title' => 'Fragmentele de cod pentru urmatorii pași din suita %1% nu au fost generate (contextul tau implementeaza interfata SnippetAcceptingContext?):', + 'snippet_proposal_title' => '%count% are pași lipsa. Puteți implementa pașii cu ajutorul acestor fragmente de cod:', + 'snippet_missing_title' => 'Fragmentele de cod pentru urmatorii pași din suita %count% nu au fost generate (contextul tau implementeaza interfata SnippetAcceptingContext?):', 'skipped_scenarios_title' => 'Scenarii omise:', 'failed_scenarios_title' => 'Scenarii eșuate:', 'failed_hooks_title' => 'Hook-uri eșuate:', 'failed_steps_title' => 'Pași esuați:', 'pending_steps_title' => 'Pași in așteptare:', - 'scenarios_count' => '{0} Niciun scenariu|{1} 1 scenariu|]1,Inf] %1% scenarii', - 'steps_count' => '{0} Niciun pas|{1} 1 pas|]1,Inf] %1% pasi', - 'passed_count' => '[1,Inf] %1% cu succes', - 'failed_count' => '[1,Inf] %1% fara success', - 'pending_count' => '[1,Inf] %1% in așteptare', - 'undefined_count' => '[1,Inf] %1% fara implementare', - 'skipped_count' => '{1} %1% omis|]1,Inf] %1% omiși', + 'scenarios_count' => '{0} Niciun scenariu|{1} 1 scenariu|]1,Inf] %count% scenarii', + 'steps_count' => '{0} Niciun pas|{1} 1 pas|]1,Inf] %count% pasi', + 'passed_count' => '[1,Inf] %count% cu succes', + 'failed_count' => '[1,Inf] %count% fara success', + 'pending_count' => '[1,Inf] %count% in așteptare', + 'undefined_count' => '[1,Inf] %count% fara implementare', + 'skipped_count' => '{1} %count% omis|]1,Inf] %count% omiși', ), 'ru' => array( - 'snippet_proposal_title' => '%1% не содержит необходимых определений. Вы можете добавить их используя шаблоны:', - 'snippet_missing_title' => 'Шаблоны для следующих шагов в среде %1% не были сгенерированы (проверьте ваши настройки):', + 'snippet_proposal_title' => '%count% не содержит необходимых определений. Вы можете добавить их используя шаблоны:', + 'snippet_missing_title' => 'Шаблоны для следующих шагов в среде %count% не были сгенерированы (проверьте ваши настройки):', 'skipped_scenarios_title' => 'Пропущенные сценарии:', 'failed_scenarios_title' => 'Проваленные сценарии:', 'failed_hooks_title' => 'Проваленные хуки:', 'failed_steps_title' => 'Проваленные шаги:', 'pending_steps_title' => 'Шаги в ожидании:', - 'scenarios_count' => '{0} Нет сценариев|{1,21,31} %1% сценарий|{2,3,4,22,23,24} %1% сценария|]4,Inf] %1% сценариев', - 'steps_count' => '{0} Нет шагов|{1,21,31} %1% шаг|{2,3,4,22,23,24} %1% шага|]4,Inf] %1% шагов', - 'passed_count' => '{1,21,31} %1% пройден|]1,Inf] %1% пройдено', - 'failed_count' => '{1,21,31} %1% провален|]1,Inf] %1% провалено', - 'pending_count' => '[1,Inf] %1% в ожидании', - 'undefined_count' => '{1,21,31} %1% не определен|]1,Inf] %1% не определено', - 'skipped_count' => '{1,21,31} %1% пропущен|]1,Inf] %1% пропущено', + 'scenarios_count' => '{0} Нет сценариев|{1,21,31} %count% сценарий|{2,3,4,22,23,24} %count% сценария|]4,Inf] %count% сценариев', + 'steps_count' => '{0} Нет шагов|{1,21,31} %count% шаг|{2,3,4,22,23,24} %count% шага|]4,Inf] %count% шагов', + 'passed_count' => '{1,21,31} %count% пройден|]1,Inf] %count% пройдено', + 'failed_count' => '{1,21,31} %count% провален|]1,Inf] %count% провалено', + 'pending_count' => '[1,Inf] %count% в ожидании', + 'undefined_count' => '{1,21,31} %count% не определен|]1,Inf] %count% не определено', + 'skipped_count' => '{1,21,31} %count% пропущен|]1,Inf] %count% пропущено', ), ); diff --git a/src/Behat/Behat/Context/Cli/InteractiveContextIdentifier.php b/src/Behat/Behat/Context/Cli/InteractiveContextIdentifier.php index 17a29b9f4..447e47098 100644 --- a/src/Behat/Behat/Context/Cli/InteractiveContextIdentifier.php +++ b/src/Behat/Behat/Context/Cli/InteractiveContextIdentifier.php @@ -68,7 +68,7 @@ public function guessTargetContextClass(ContextEnvironment $environment) return null; } - $message = $this->translator->trans('snippet_context_choice', array('%1%' => $suiteName), 'output'); + $message = $this->translator->trans('snippet_context_choice', array('%count%' => $suiteName), 'output'); $choices = array_values(array_merge(array('None'), $contextClasses)); $default = 1; diff --git a/src/Behat/Behat/Output/Node/Printer/CounterPrinter.php b/src/Behat/Behat/Output/Node/Printer/CounterPrinter.php index b6db04fdc..47655f20e 100644 --- a/src/Behat/Behat/Output/Node/Printer/CounterPrinter.php +++ b/src/Behat/Behat/Output/Node/Printer/CounterPrinter.php @@ -64,12 +64,12 @@ public function printCounters(OutputPrinter $printer, $intro, array $stats) $style = $this->resultConverter->convertResultCodeToString($resultCode); $transId = $style . '_count'; - $message = $this->translator->trans($transId, array('%1%' => $count), 'output'); + $message = $this->translator->trans($transId, array('%count%' => $count), 'output'); $detailedStats[] = sprintf('{+%s}%s{-%s}', $style, $message, $style); } - $message = $this->translator->trans($intro, array('%1%' => $totalCount), 'output'); + $message = $this->translator->trans($intro, array('%count%' => $totalCount), 'output'); $printer->write($message); if (count($detailedStats)) { diff --git a/src/Behat/Behat/Snippet/Printer/ConsoleSnippetPrinter.php b/src/Behat/Behat/Snippet/Printer/ConsoleSnippetPrinter.php index e32d17610..ec06bc17d 100644 --- a/src/Behat/Behat/Snippet/Printer/ConsoleSnippetPrinter.php +++ b/src/Behat/Behat/Snippet/Printer/ConsoleSnippetPrinter.php @@ -57,7 +57,7 @@ public function __construct(OutputInterface $output, TranslatorInterface $transl */ public function printSnippets($targetName, array $snippets) { - $message = $this->translator->trans('snippet_proposal_title', array('%1%' => $targetName), 'output'); + $message = $this->translator->trans('snippet_proposal_title', array('%count%' => $targetName), 'output'); $this->output->writeln('--- ' . $message . PHP_EOL); @@ -74,7 +74,7 @@ public function printSnippets($targetName, array $snippets) */ public function printUndefinedSteps($suiteName, array $steps) { - $message = $this->translator->trans('snippet_missing_title', array('%1%' => $suiteName), 'output'); + $message = $this->translator->trans('snippet_missing_title', array('%count%' => $suiteName), 'output'); $this->output->writeln('--- ' . $message . PHP_EOL); diff --git a/src/Behat/Testwork/Cli/DumpReferenceCommand.php b/src/Behat/Testwork/Cli/DumpReferenceCommand.php index d6b57d442..57416d8b7 100644 --- a/src/Behat/Testwork/Cli/DumpReferenceCommand.php +++ b/src/Behat/Testwork/Cli/DumpReferenceCommand.php @@ -57,5 +57,7 @@ protected function execute(InputInterface $input, OutputInterface $output) $configTree = new ConfigurationTree(); $output->writeln($dumper->dumpNode($configTree->getConfigTree($this->extensionManager->getExtensions()))); + + return 0; } } From 0f3ed3b43cb2763be3719b5db3c5032cc7f47461 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Javier=20D=C3=ADaz?= Date: Sun, 24 Nov 2019 13:02:11 +0100 Subject: [PATCH 173/567] Added the new Symfony version for travis --- .travis.yml | 2 ++ 1 file changed, 2 insertions(+) diff --git a/.travis.yml b/.travis.yml index 1dc30050e..732e4253e 100644 --- a/.travis.yml +++ b/.travis.yml @@ -26,6 +26,8 @@ matrix: env: SYMFONY_VERSION='^3.4' - php: 7.3 env: SYMFONY_VERSION='^4.2' + - php: 7.3 + env: SYMFONY_VERSION='^5.0' before_install: - phpenv config-rm xdebug.ini || echo "XDebug is not enabled" From d4fde010458646fb383df833ed9e528df4f689b5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Javier=20D=C3=ADaz?= Date: Sun, 24 Nov 2019 13:08:24 +0100 Subject: [PATCH 174/567] Use the original getLocale() instead of the TranslatorTrait::getLocale() --- .../Behat/Definition/Translator/DefinitionTranslator.php | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/src/Behat/Behat/Definition/Translator/DefinitionTranslator.php b/src/Behat/Behat/Definition/Translator/DefinitionTranslator.php index ed3c3cb33..3423249cb 100644 --- a/src/Behat/Behat/Definition/Translator/DefinitionTranslator.php +++ b/src/Behat/Behat/Definition/Translator/DefinitionTranslator.php @@ -13,7 +13,6 @@ use Behat\Behat\Definition\Definition; use Behat\Testwork\Suite\Suite; use Symfony\Contracts\Translation\TranslatorInterface; -use Symfony\Contracts\Translation\TranslatorTrait; /** * Translates definitions using translator component. @@ -22,8 +21,6 @@ */ final class DefinitionTranslator { - use TranslatorTrait; - /** * @var TranslatorInterface */ @@ -60,4 +57,9 @@ public function translateDefinition(Suite $suite, Definition $definition, $langu return $definition; } + + public function getLocale() + { + return $this->translator->getLocale(); + } } From 51d9dfe4012f4d0ccca5d1879c9f1f1362551bb8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Javier=20D=C3=ADaz?= Date: Wed, 27 Nov 2019 14:39:40 +0100 Subject: [PATCH 175/567] Added BC layer for the TreeBuilder --- features/bootstrap/FeatureContext.php | 1 - .../Configuration/ConfigurationTree.php | 15 ++++++++++++--- 2 files changed, 12 insertions(+), 4 deletions(-) diff --git a/features/bootstrap/FeatureContext.php b/features/bootstrap/FeatureContext.php index 8fd7b725c..6b63074f6 100644 --- a/features/bootstrap/FeatureContext.php +++ b/features/bootstrap/FeatureContext.php @@ -79,7 +79,6 @@ public function prepareTestFolders() } $this->workingDir = $dir; $this->phpBin = $php; - $this->process = Process::fromShellCommandline(''); } /** diff --git a/src/Behat/Testwork/ServiceContainer/Configuration/ConfigurationTree.php b/src/Behat/Testwork/ServiceContainer/Configuration/ConfigurationTree.php index 445266716..cf2fa1936 100644 --- a/src/Behat/Testwork/ServiceContainer/Configuration/ConfigurationTree.php +++ b/src/Behat/Testwork/ServiceContainer/Configuration/ConfigurationTree.php @@ -11,6 +11,7 @@ namespace Behat\Testwork\ServiceContainer\Configuration; use Behat\Testwork\ServiceContainer\Extension; +use Symfony\Component\Config\Definition\Builder\ArrayNodeDefinition; use Symfony\Component\Config\Definition\Builder\TreeBuilder; use Symfony\Component\Config\Definition\NodeInterface; @@ -30,11 +31,19 @@ final class ConfigurationTree */ public function getConfigTree(array $extensions) { - $tree = new TreeBuilder('testwork'); - $root = $tree->getRootNode(); + if (method_exists(TreeBuilder::class, 'getRootNode')) { + $treeBuilder = new TreeBuilder('testwork'); + /** @var ArrayNodeDefinition $rootNode */ + $rootNode = $treeBuilder->getRootNode(); + } else { + // BC layer for symfony/config 4.1 and older + $treeBuilder = new TreeBuilder(); + /** @var ArrayNodeDefinition $rootNode */ + $rootNode = $treeBuilder->root('sylius_resource'); + } foreach ($extensions as $extension) { - $extension->configure($root->children()->arrayNode($extension->getConfigKey())); + $extension->configure($rootNode->children()->arrayNode($extension->getConfigKey())); } return $tree->buildTree(); From 56439838a845fac7a7fc3f66644487b30cc8bc1e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Javier=20D=C3=ADaz?= Date: Wed, 27 Nov 2019 18:25:03 +0100 Subject: [PATCH 176/567] Added BC layer for older versions of Symfony --- .../Context/Cli/ContextSnippetsController.php | 2 +- .../Cli/InteractiveContextIdentifier.php | 2 +- .../Translator/DefinitionTranslator.php | 1 - .../Definition/Translator/Translator.php | 15 +++ .../Translator/TranslatorInterface.php | 13 +++ .../Cli/StopOnFailureController.php | 9 +- .../EventDispatchingBackgroundTester.php | 29 +++++- .../Tester/EventDispatchingFeatureTester.php | 28 +++++- .../Tester/EventDispatchingOutlineTester.php | 28 +++++- .../Tester/EventDispatchingScenarioTester.php | 28 +++++- .../Tester/EventDispatchingStepTester.php | 28 +++++- .../Behat/Gherkin/Cli/SyntaxController.php | 2 +- .../EventListener/AST/FeatureListener.php | 2 +- .../EventListener/AST/OutlineListener.php | 2 +- .../AST/OutlineTableListener.php | 2 +- .../AST/ScenarioNodeListener.php | 2 +- .../Node/EventListener/AST/StepListener.php | 2 +- .../Node/EventListener/AST/SuiteListener.php | 2 +- .../Flow/FireOnlySiblingsListener.php | 2 +- .../FirstBackgroundFiresFirstListener.php | 2 +- .../Flow/OnlyFirstBackgroundFiresListener.php | 2 +- .../JUnit/JUnitDurationListener.php | 2 +- .../JUnit/JUnitFeatureElementListener.php | 2 +- .../JUnit/JUnitOutlineStoreListener.php | 2 +- .../Statistics/HookStatsListener.php | 2 +- .../Statistics/ScenarioStatsListener.php | 2 +- .../Statistics/StatisticsListener.php | 2 +- .../Statistics/StepStatsListener.php | 3 +- .../Output/Node/Printer/CounterPrinter.php | 2 +- .../Behat/Output/Node/Printer/ListPrinter.php | 2 +- .../Snippet/Printer/ConsoleSnippetPrinter.php | 2 +- .../RepositoryArgumentTransformer.php | 2 +- src/Behat/Testwork/Event/Event.php | 15 +++ .../Event/ExerciseCompleted.php | 3 +- .../EventDispatcher/Event/LifecycleEvent.php | 2 +- .../Tester/EventDispatchingExercise.php | 28 +++++- .../Tester/EventDispatchingSuiteTester.php | 27 +++++- .../TestworkEventDispatcher.php | 97 +++++++++++++------ .../Testwork/Exception/ExceptionPresenter.php | 1 - .../Node/EventListener/ChainEventListener.php | 2 +- .../Node/EventListener/EventListener.php | 2 +- .../FireOnlyIfFormatterParameterListener.php | 2 +- .../Output/NodeEventListeningFormatter.php | 2 +- .../ServiceContainer/TranslatorExtension.php | 2 +- 44 files changed, 318 insertions(+), 91 deletions(-) create mode 100644 src/Behat/Behat/Definition/Translator/Translator.php create mode 100644 src/Behat/Behat/Definition/Translator/TranslatorInterface.php create mode 100644 src/Behat/Testwork/Event/Event.php diff --git a/src/Behat/Behat/Context/Cli/ContextSnippetsController.php b/src/Behat/Behat/Context/Cli/ContextSnippetsController.php index c13d3436b..3bfbc40bd 100644 --- a/src/Behat/Behat/Context/Cli/ContextSnippetsController.php +++ b/src/Behat/Behat/Context/Cli/ContextSnippetsController.php @@ -17,12 +17,12 @@ use Behat\Behat\Context\Snippet\Generator\FixedContextIdentifier; use Behat\Behat\Context\Snippet\Generator\FixedPatternIdentifier; use Behat\Behat\Context\Snippet\Generator\AggregateContextIdentifier; +use Behat\Behat\Definition\Translator\TranslatorInterface; use Behat\Testwork\Cli\Controller; use Symfony\Component\Console\Command\Command as SymfonyCommand; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; -use Symfony\Contracts\Translation\TranslatorInterface; /** * Configures which context snippets are generated for. diff --git a/src/Behat/Behat/Context/Cli/InteractiveContextIdentifier.php b/src/Behat/Behat/Context/Cli/InteractiveContextIdentifier.php index 447e47098..137cac797 100644 --- a/src/Behat/Behat/Context/Cli/InteractiveContextIdentifier.php +++ b/src/Behat/Behat/Context/Cli/InteractiveContextIdentifier.php @@ -12,11 +12,11 @@ use Behat\Behat\Context\Environment\ContextEnvironment; use Behat\Behat\Context\Snippet\Generator\TargetContextIdentifier; +use Behat\Behat\Definition\Translator\TranslatorInterface; use Symfony\Component\Console\Helper\QuestionHelper; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Console\Question\ChoiceQuestion; -use Symfony\Contracts\Translation\TranslatorInterface; /** * Interactive identifier that asks user for input. diff --git a/src/Behat/Behat/Definition/Translator/DefinitionTranslator.php b/src/Behat/Behat/Definition/Translator/DefinitionTranslator.php index 3423249cb..105d61c50 100644 --- a/src/Behat/Behat/Definition/Translator/DefinitionTranslator.php +++ b/src/Behat/Behat/Definition/Translator/DefinitionTranslator.php @@ -12,7 +12,6 @@ use Behat\Behat\Definition\Definition; use Behat\Testwork\Suite\Suite; -use Symfony\Contracts\Translation\TranslatorInterface; /** * Translates definitions using translator component. diff --git a/src/Behat/Behat/Definition/Translator/Translator.php b/src/Behat/Behat/Definition/Translator/Translator.php new file mode 100644 index 000000000..858e6445d --- /dev/null +++ b/src/Behat/Behat/Definition/Translator/Translator.php @@ -0,0 +1,15 @@ +eventDispatcher->dispatch(new AfterSuiteAborted($event->getEnvironment()), SuiteTested::AFTER); - $this->eventDispatcher->dispatch(new AfterExerciseAborted(), ExerciseCompleted::AFTER); + if (class_exists(\Symfony\Contracts\EventDispatcher\Event::class)) { + $this->eventDispatcher->dispatch(new AfterSuiteAborted($event->getEnvironment()), SuiteTested::AFTER); + $this->eventDispatcher->dispatch(new AfterExerciseAborted(), ExerciseCompleted::AFTER); + } else { + $this->eventDispatcher->dispatch(SuiteTested::AFTER, new AfterSuiteAborted($event->getEnvironment())); + $this->eventDispatcher->dispatch(ExerciseCompleted::AFTER, new AfterExerciseAborted()); + } exit(1); } diff --git a/src/Behat/Behat/EventDispatcher/Tester/EventDispatchingBackgroundTester.php b/src/Behat/Behat/EventDispatcher/Tester/EventDispatchingBackgroundTester.php index e0732d818..7b168f448 100644 --- a/src/Behat/Behat/EventDispatcher/Tester/EventDispatchingBackgroundTester.php +++ b/src/Behat/Behat/EventDispatcher/Tester/EventDispatchingBackgroundTester.php @@ -55,12 +55,22 @@ public function __construct(BackgroundTester $baseTester, EventDispatcherInterfa public function setUp(Environment $env, FeatureNode $feature, $skip) { $event = new BeforeBackgroundTested($env, $feature, $feature->getBackground()); - $this->eventDispatcher->dispatch($event, $event::BEFORE); + + if (class_exists(\Symfony\Contracts\EventDispatcher\Event::class)) { + $this->eventDispatcher->dispatch($event, $event::BEFORE); + } else { + $this->eventDispatcher->dispatch($event::BEFORE, $event); + } $setup = $this->baseTester->setUp($env, $feature, $skip); $event = new AfterBackgroundSetup($env, $feature, $feature->getBackground(), $setup); - $this->eventDispatcher->dispatch($event, $event::AFTER_SETUP); + + if (class_exists(\Symfony\Contracts\EventDispatcher\Event::class)) { + $this->eventDispatcher->dispatch($event, $event::AFTER_SETUP); + } else { + $this->eventDispatcher->dispatch($event::AFTER_SETUP, $event); + } return $setup; } @@ -79,12 +89,23 @@ public function test(Environment $env, FeatureNode $feature, $skip) public function tearDown(Environment $env, FeatureNode $feature, $skip, TestResult $result) { $event = new BeforeBackgroundTeardown($env, $feature, $feature->getBackground(), $result); - $this->eventDispatcher->dispatch($event, BackgroundTested::BEFORE_TEARDOWN); + + if (class_exists(\Symfony\Contracts\EventDispatcher\Event::class)) { + $this->eventDispatcher->dispatch($event, BackgroundTested::BEFORE_TEARDOWN); + } else { + $this->eventDispatcher->dispatch(BackgroundTested::BEFORE_TEARDOWN, $event); + + } $teardown = $this->baseTester->tearDown($env, $feature, $skip, $result); $event = new AfterBackgroundTested($env, $feature, $feature->getBackground(), $result, $teardown); - $this->eventDispatcher->dispatch($event, BackgroundTested::AFTER); + + if (class_exists(\Symfony\Contracts\EventDispatcher\Event::class)) { + $this->eventDispatcher->dispatch($event, BackgroundTested::AFTER); + } else { + $this->eventDispatcher->dispatch(BackgroundTested::AFTER, $event); + } return $teardown; } diff --git a/src/Behat/Behat/EventDispatcher/Tester/EventDispatchingFeatureTester.php b/src/Behat/Behat/EventDispatcher/Tester/EventDispatchingFeatureTester.php index 088a4d6d1..7175c7620 100644 --- a/src/Behat/Behat/EventDispatcher/Tester/EventDispatchingFeatureTester.php +++ b/src/Behat/Behat/EventDispatcher/Tester/EventDispatchingFeatureTester.php @@ -53,12 +53,22 @@ public function __construct(SpecificationTester $baseTester, EventDispatcherInte public function setUp(Environment $env, $feature, $skip) { $event = new BeforeFeatureTested($env, $feature); - $this->eventDispatcher->dispatch($event, $event::BEFORE); + + if (class_exists(\Symfony\Contracts\EventDispatcher\Event::class)) { + $this->eventDispatcher->dispatch($event, $event::BEFORE); + } else { + $this->eventDispatcher->dispatch($event::BEFORE, $event); + } $setup = $this->baseTester->setUp($env, $feature, $skip); $event = new AfterFeatureSetup($env, $feature, $setup); - $this->eventDispatcher->dispatch($event, $event::AFTER_SETUP); + + if (class_exists(\Symfony\Contracts\EventDispatcher\Event::class)) { + $this->eventDispatcher->dispatch($event, $event::AFTER_SETUP); + } else { + $this->eventDispatcher->dispatch($event::AFTER_SETUP, $event); + } return $setup; } @@ -77,12 +87,22 @@ public function test(Environment $env, $feature, $skip) public function tearDown(Environment $env, $feature, $skip, TestResult $result) { $event = new BeforeFeatureTeardown($env, $feature, $result); - $this->eventDispatcher->dispatch($event, $event::BEFORE_TEARDOWN); + + if (class_exists(\Symfony\Contracts\EventDispatcher\Event::class)) { + $this->eventDispatcher->dispatch($event, $event::BEFORE_TEARDOWN); + } else { + $this->eventDispatcher->dispatch($event::BEFORE_TEARDOWN, $event); + } $teardown = $this->baseTester->tearDown($env, $feature, $skip, $result); $event = new AfterFeatureTested($env, $feature, $result, $teardown); - $this->eventDispatcher->dispatch($event, $event::AFTER); + + if (class_exists(\Symfony\Contracts\EventDispatcher\Event::class)) { + $this->eventDispatcher->dispatch($event, $event::AFTER); + } else { + $this->eventDispatcher->dispatch($event::AFTER, $event); + } return $teardown; } diff --git a/src/Behat/Behat/EventDispatcher/Tester/EventDispatchingOutlineTester.php b/src/Behat/Behat/EventDispatcher/Tester/EventDispatchingOutlineTester.php index 24b3f9898..21850c86f 100644 --- a/src/Behat/Behat/EventDispatcher/Tester/EventDispatchingOutlineTester.php +++ b/src/Behat/Behat/EventDispatcher/Tester/EventDispatchingOutlineTester.php @@ -55,12 +55,22 @@ public function __construct(OutlineTester $baseTester, EventDispatcherInterface public function setUp(Environment $env, FeatureNode $feature, OutlineNode $outline, $skip) { $event = new BeforeOutlineTested($env, $feature, $outline); - $this->eventDispatcher->dispatch($event, $event::BEFORE); + + if (class_exists(\Symfony\Contracts\EventDispatcher\Event::class)) { + $this->eventDispatcher->dispatch($event, $event::BEFORE); + } else { + $this->eventDispatcher->dispatch($event::BEFORE, $event); + } $setup = $this->baseTester->setUp($env, $feature, $outline, $skip); $event = new AfterOutlineSetup($env, $feature, $outline, $setup); - $this->eventDispatcher->dispatch($event, $event::AFTER_SETUP); + + if (class_exists(\Symfony\Contracts\EventDispatcher\Event::class)) { + $this->eventDispatcher->dispatch($event, $event::AFTER_SETUP); + } else { + $this->eventDispatcher->dispatch($event::AFTER_SETUP, $event); + } return $setup; } @@ -79,12 +89,22 @@ public function test(Environment $env, FeatureNode $feature, OutlineNode $outlin public function tearDown(Environment $env, FeatureNode $feature, OutlineNode $outline, $skip, TestResult $result) { $event = new BeforeOutlineTeardown($env, $feature, $outline, $result); - $this->eventDispatcher->dispatch($event, $event::BEFORE_TEARDOWN); + + if (class_exists(\Symfony\Contracts\EventDispatcher\Event::class)) { + $this->eventDispatcher->dispatch( $event,$event::BEFORE_TEARDOWN); + } else { + $this->eventDispatcher->dispatch($event::BEFORE_TEARDOWN, $event); + } $teardown = $this->baseTester->tearDown($env, $feature, $outline, $skip, $result); $event = new AfterOutlineTested($env, $feature, $outline, $result, $teardown); - $this->eventDispatcher->dispatch($event, $event::AFTER); + + if (class_exists(\Symfony\Contracts\EventDispatcher\Event::class)) { + $this->eventDispatcher->dispatch($event, $event::AFTER); + } else { + $this->eventDispatcher->dispatch($event::AFTER, $event); + } return $teardown; } diff --git a/src/Behat/Behat/EventDispatcher/Tester/EventDispatchingScenarioTester.php b/src/Behat/Behat/EventDispatcher/Tester/EventDispatchingScenarioTester.php index 85c182e6e..c25c55201 100644 --- a/src/Behat/Behat/EventDispatcher/Tester/EventDispatchingScenarioTester.php +++ b/src/Behat/Behat/EventDispatcher/Tester/EventDispatchingScenarioTester.php @@ -85,12 +85,22 @@ public function __construct( public function setUp(Environment $env, FeatureNode $feature, Scenario $scenario, $skip) { $event = new BeforeScenarioTested($env, $feature, $scenario); - $this->eventDispatcher->dispatch($event, $this->beforeEventName); + + if (class_exists(\Symfony\Contracts\EventDispatcher\Event::class)) { + $this->eventDispatcher->dispatch($event, $this->beforeEventName); + } else { + $this->eventDispatcher->dispatch($this->beforeEventName, $event); + } $setup = $this->baseTester->setUp($env, $feature, $scenario, $skip); $event = new AfterScenarioSetup($env, $feature, $scenario, $setup); - $this->eventDispatcher->dispatch($event, $this->afterSetupEventName); + + if (class_exists(\Symfony\Contracts\EventDispatcher\Event::class)) { + $this->eventDispatcher->dispatch($event, $this->afterSetupEventName); + } else { + $this->eventDispatcher->dispatch($this->afterSetupEventName, $event); + } return $setup; } @@ -109,12 +119,22 @@ public function test(Environment $env, FeatureNode $feature, Scenario $scenario, public function tearDown(Environment $env, FeatureNode $feature, Scenario $scenario, $skip, TestResult $result) { $event = new BeforeScenarioTeardown($env, $feature, $scenario, $result); - $this->eventDispatcher->dispatch($event, $this->beforeTeardownEventName); + + if (class_exists(\Symfony\Contracts\EventDispatcher\Event::class)) { + $this->eventDispatcher->dispatch($event, $this->beforeTeardownEventName); + } else { + $this->eventDispatcher->dispatch($this->beforeTeardownEventName, $event); + } $teardown = $this->baseTester->tearDown($env, $feature, $scenario, $skip, $result); $event = new AfterScenarioTested($env, $feature, $scenario, $result, $teardown); - $this->eventDispatcher->dispatch($event, $this->afterEventName); + + if (class_exists(\Symfony\Contracts\EventDispatcher\Event::class)) { + $this->eventDispatcher->dispatch($event, $this->afterEventName); + } else { + $this->eventDispatcher->dispatch($this->afterEventName, $event); + } return $teardown; } diff --git a/src/Behat/Behat/EventDispatcher/Tester/EventDispatchingStepTester.php b/src/Behat/Behat/EventDispatcher/Tester/EventDispatchingStepTester.php index 03337556d..5a0fec6e0 100644 --- a/src/Behat/Behat/EventDispatcher/Tester/EventDispatchingStepTester.php +++ b/src/Behat/Behat/EventDispatcher/Tester/EventDispatchingStepTester.php @@ -55,12 +55,22 @@ public function __construct(StepTester $baseTester, EventDispatcherInterface $ev public function setUp(Environment $env, FeatureNode $feature, StepNode $step, $skip) { $event = new BeforeStepTested($env, $feature, $step); - $this->eventDispatcher->dispatch($event, $event::BEFORE); + + if (class_exists(\Symfony\Contracts\EventDispatcher\Event::class)) { + $this->eventDispatcher->dispatch($event, $event::BEFORE); + } else { + $this->eventDispatcher->dispatch($event::BEFORE, $event); + } $setup = $this->baseTester->setUp($env, $feature, $step, $skip); $event = new AfterStepSetup($env, $feature, $step, $setup); - $this->eventDispatcher->dispatch($event, $event::AFTER_SETUP); + + if (class_exists(\Symfony\Contracts\EventDispatcher\Event::class)) { + $this->eventDispatcher->dispatch($event, $event::AFTER_SETUP); + } else { + $this->eventDispatcher->dispatch($event::AFTER_SETUP, $event); + } return $setup; } @@ -79,12 +89,22 @@ public function test(Environment $env, FeatureNode $feature, StepNode $step, $sk public function tearDown(Environment $env, FeatureNode $feature, StepNode $step, $skip, StepResult $result) { $event = new BeforeStepTeardown($env, $feature, $step, $result); - $this->eventDispatcher->dispatch($event, $event::BEFORE_TEARDOWN); + + if (class_exists(\Symfony\Contracts\EventDispatcher\Event::class)) { + $this->eventDispatcher->dispatch($event, $event::BEFORE_TEARDOWN); + } else { + $this->eventDispatcher->dispatch($event::BEFORE_TEARDOWN, $event); + } $teardown = $this->baseTester->tearDown($env, $feature, $step, $skip, $result); $event = new AfterStepTested($env, $feature, $step, $result, $teardown); - $this->eventDispatcher->dispatch($event, $event::AFTER); + + if (class_exists(\Symfony\Contracts\EventDispatcher\Event::class)) { + $this->eventDispatcher->dispatch($event, $event::AFTER); + } else { + $this->eventDispatcher->dispatch($event::AFTER, $event); + } return $teardown; } diff --git a/src/Behat/Behat/Gherkin/Cli/SyntaxController.php b/src/Behat/Behat/Gherkin/Cli/SyntaxController.php index 88397c4b3..62acc12a6 100644 --- a/src/Behat/Behat/Gherkin/Cli/SyntaxController.php +++ b/src/Behat/Behat/Gherkin/Cli/SyntaxController.php @@ -10,6 +10,7 @@ namespace Behat\Behat\Gherkin\Cli; +use Behat\Behat\Definition\Translator\TranslatorInterface; use Behat\Gherkin\Keywords\KeywordsDumper; use Behat\Testwork\Cli\Controller; use Symfony\Component\Console\Command\Command; @@ -17,7 +18,6 @@ use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; -use Symfony\Contracts\Translation\TranslatorInterface; /** * Prints example of the feature to present all available syntax keywords. diff --git a/src/Behat/Behat/Output/Node/EventListener/AST/FeatureListener.php b/src/Behat/Behat/Output/Node/EventListener/AST/FeatureListener.php index 8cc4a1e7a..9487ecde2 100644 --- a/src/Behat/Behat/Output/Node/EventListener/AST/FeatureListener.php +++ b/src/Behat/Behat/Output/Node/EventListener/AST/FeatureListener.php @@ -15,9 +15,9 @@ use Behat\Behat\EventDispatcher\Event\FeatureTested; use Behat\Behat\Output\Node\Printer\FeaturePrinter; use Behat\Behat\Output\Node\Printer\SetupPrinter; +use Behat\Testwork\Event\Event; use Behat\Testwork\Output\Formatter; use Behat\Testwork\Output\Node\EventListener\EventListener; -use Symfony\Contracts\EventDispatcher\Event; /** * Listens to feature events and calls appropriate printers. diff --git a/src/Behat/Behat/Output/Node/EventListener/AST/OutlineListener.php b/src/Behat/Behat/Output/Node/EventListener/AST/OutlineListener.php index 5881b26c0..85b602b7b 100644 --- a/src/Behat/Behat/Output/Node/EventListener/AST/OutlineListener.php +++ b/src/Behat/Behat/Output/Node/EventListener/AST/OutlineListener.php @@ -22,9 +22,9 @@ use Behat\Behat\Output\Node\Printer\SetupPrinter; use Behat\Behat\Output\Node\Printer\StepPrinter; use Behat\Gherkin\Node\ExampleNode; +use Behat\Testwork\Event\Event; use Behat\Testwork\Output\Formatter; use Behat\Testwork\Output\Node\EventListener\EventListener; -use Symfony\Contracts\EventDispatcher\Event; /** * Listens to expanded outline events and calls appropriate printers. diff --git a/src/Behat/Behat/Output/Node/EventListener/AST/OutlineTableListener.php b/src/Behat/Behat/Output/Node/EventListener/AST/OutlineTableListener.php index 7c0607f89..09a179bc1 100644 --- a/src/Behat/Behat/Output/Node/EventListener/AST/OutlineTableListener.php +++ b/src/Behat/Behat/Output/Node/EventListener/AST/OutlineTableListener.php @@ -24,10 +24,10 @@ use Behat\Behat\Output\Node\Printer\SetupPrinter; use Behat\Behat\Tester\Result\StepResult; use Behat\Gherkin\Node\OutlineNode; +use Behat\Testwork\Event\Event; use Behat\Testwork\Output\Formatter; use Behat\Testwork\Output\Node\EventListener\EventListener; use Behat\Testwork\Tester\Setup\Setup; -use Symfony\Contracts\EventDispatcher\Event; /** * Listens to outline table events and calls appropriate printers. diff --git a/src/Behat/Behat/Output/Node/EventListener/AST/ScenarioNodeListener.php b/src/Behat/Behat/Output/Node/EventListener/AST/ScenarioNodeListener.php index 17d455d0d..bcc9f206a 100644 --- a/src/Behat/Behat/Output/Node/EventListener/AST/ScenarioNodeListener.php +++ b/src/Behat/Behat/Output/Node/EventListener/AST/ScenarioNodeListener.php @@ -13,11 +13,11 @@ use Behat\Behat\EventDispatcher\Event\ScenarioLikeTested; use Behat\Behat\Output\Node\Printer\ScenarioPrinter; use Behat\Behat\Output\Node\Printer\SetupPrinter; +use Behat\Testwork\Event\Event; use Behat\Testwork\EventDispatcher\Event\AfterSetup; use Behat\Testwork\EventDispatcher\Event\AfterTested; use Behat\Testwork\Output\Formatter; use Behat\Testwork\Output\Node\EventListener\EventListener; -use Symfony\Contracts\EventDispatcher\Event; /** * Listens to scenario events and calls appropriate printers (header/footer). diff --git a/src/Behat/Behat/Output/Node/EventListener/AST/StepListener.php b/src/Behat/Behat/Output/Node/EventListener/AST/StepListener.php index 7392e3448..dda597b72 100644 --- a/src/Behat/Behat/Output/Node/EventListener/AST/StepListener.php +++ b/src/Behat/Behat/Output/Node/EventListener/AST/StepListener.php @@ -18,9 +18,9 @@ use Behat\Behat\Output\Node\Printer\SetupPrinter; use Behat\Behat\Output\Node\Printer\StepPrinter; use Behat\Gherkin\Node\ScenarioLikeInterface; +use Behat\Testwork\Event\Event; use Behat\Testwork\Output\Formatter; use Behat\Testwork\Output\Node\EventListener\EventListener; -use Symfony\Contracts\EventDispatcher\Event; /** * Listens to step events and call appropriate printers. diff --git a/src/Behat/Behat/Output/Node/EventListener/AST/SuiteListener.php b/src/Behat/Behat/Output/Node/EventListener/AST/SuiteListener.php index a679fe852..71ee608fe 100644 --- a/src/Behat/Behat/Output/Node/EventListener/AST/SuiteListener.php +++ b/src/Behat/Behat/Output/Node/EventListener/AST/SuiteListener.php @@ -11,11 +11,11 @@ namespace Behat\Behat\Output\Node\EventListener\AST; use Behat\Behat\Output\Node\Printer\SetupPrinter; +use Behat\Testwork\Event\Event; use Behat\Testwork\EventDispatcher\Event\AfterSuiteSetup; use Behat\Testwork\EventDispatcher\Event\AfterSuiteTested; use Behat\Testwork\Output\Formatter; use Behat\Testwork\Output\Node\EventListener\EventListener; -use Symfony\Contracts\EventDispatcher\Event; /** * Behat suite listener. diff --git a/src/Behat/Behat/Output/Node/EventListener/Flow/FireOnlySiblingsListener.php b/src/Behat/Behat/Output/Node/EventListener/Flow/FireOnlySiblingsListener.php index fad3c179d..243b200d8 100644 --- a/src/Behat/Behat/Output/Node/EventListener/Flow/FireOnlySiblingsListener.php +++ b/src/Behat/Behat/Output/Node/EventListener/Flow/FireOnlySiblingsListener.php @@ -10,9 +10,9 @@ namespace Behat\Behat\Output\Node\EventListener\Flow; +use Behat\Testwork\Event\Event; use Behat\Testwork\Output\Formatter; use Behat\Testwork\Output\Node\EventListener\EventListener; -use Symfony\Contracts\EventDispatcher\Event; /** * Behat fire only siblings listener. diff --git a/src/Behat/Behat/Output/Node/EventListener/Flow/FirstBackgroundFiresFirstListener.php b/src/Behat/Behat/Output/Node/EventListener/Flow/FirstBackgroundFiresFirstListener.php index 60200b432..78983627a 100644 --- a/src/Behat/Behat/Output/Node/EventListener/Flow/FirstBackgroundFiresFirstListener.php +++ b/src/Behat/Behat/Output/Node/EventListener/Flow/FirstBackgroundFiresFirstListener.php @@ -15,9 +15,9 @@ use Behat\Behat\EventDispatcher\Event\FeatureTested; use Behat\Behat\EventDispatcher\Event\OutlineTested; use Behat\Behat\EventDispatcher\Event\ScenarioTested; +use Behat\Testwork\Event\Event; use Behat\Testwork\Output\Formatter; use Behat\Testwork\Output\Node\EventListener\EventListener; -use Symfony\Contracts\EventDispatcher\Event; /** * Behat first background fires first listener. diff --git a/src/Behat/Behat/Output/Node/EventListener/Flow/OnlyFirstBackgroundFiresListener.php b/src/Behat/Behat/Output/Node/EventListener/Flow/OnlyFirstBackgroundFiresListener.php index 1c4c74bfb..9bb73822e 100644 --- a/src/Behat/Behat/Output/Node/EventListener/Flow/OnlyFirstBackgroundFiresListener.php +++ b/src/Behat/Behat/Output/Node/EventListener/Flow/OnlyFirstBackgroundFiresListener.php @@ -14,9 +14,9 @@ use Behat\Behat\EventDispatcher\Event\AfterStepTested; use Behat\Behat\EventDispatcher\Event\BackgroundTested; use Behat\Behat\EventDispatcher\Event\FeatureTested; +use Behat\Testwork\Event\Event; use Behat\Testwork\Output\Formatter; use Behat\Testwork\Output\Node\EventListener\EventListener; -use Symfony\Contracts\EventDispatcher\Event; /** * Behat only first background fires listener. diff --git a/src/Behat/Behat/Output/Node/EventListener/JUnit/JUnitDurationListener.php b/src/Behat/Behat/Output/Node/EventListener/JUnit/JUnitDurationListener.php index b70789a8c..12604d5b7 100644 --- a/src/Behat/Behat/Output/Node/EventListener/JUnit/JUnitDurationListener.php +++ b/src/Behat/Behat/Output/Node/EventListener/JUnit/JUnitDurationListener.php @@ -9,9 +9,9 @@ use Behat\Gherkin\Node\KeywordNodeInterface; use Behat\Gherkin\Node\ScenarioLikeInterface; use Behat\Testwork\Counter\Timer; +use Behat\Testwork\Event\Event; use Behat\Testwork\Output\Formatter; use Behat\Testwork\Output\Node\EventListener\EventListener; -use Symfony\Contracts\EventDispatcher\Event; final class JUnitDurationListener implements EventListener { diff --git a/src/Behat/Behat/Output/Node/EventListener/JUnit/JUnitFeatureElementListener.php b/src/Behat/Behat/Output/Node/EventListener/JUnit/JUnitFeatureElementListener.php index 479032245..031accdaa 100644 --- a/src/Behat/Behat/Output/Node/EventListener/JUnit/JUnitFeatureElementListener.php +++ b/src/Behat/Behat/Output/Node/EventListener/JUnit/JUnitFeatureElementListener.php @@ -22,10 +22,10 @@ use Behat\Behat\Output\Node\Printer\SetupPrinter; use Behat\Behat\Output\Node\Printer\StepPrinter; use Behat\Gherkin\Node\FeatureNode; +use Behat\Testwork\Event\Event; use Behat\Testwork\EventDispatcher\Event\AfterSetup; use Behat\Testwork\Output\Formatter; use Behat\Testwork\Output\Node\EventListener\EventListener; -use Symfony\Contracts\EventDispatcher\Event; /** * Listens to feature, scenario and step events and calls appropriate printers. diff --git a/src/Behat/Behat/Output/Node/EventListener/JUnit/JUnitOutlineStoreListener.php b/src/Behat/Behat/Output/Node/EventListener/JUnit/JUnitOutlineStoreListener.php index e16708684..530a6ca18 100644 --- a/src/Behat/Behat/Output/Node/EventListener/JUnit/JUnitOutlineStoreListener.php +++ b/src/Behat/Behat/Output/Node/EventListener/JUnit/JUnitOutlineStoreListener.php @@ -14,11 +14,11 @@ use Behat\Behat\Output\Node\Printer\SuitePrinter; use Behat\Gherkin\Node\ExampleNode; use Behat\Gherkin\Node\OutlineNode; +use Behat\Testwork\Event\Event; use Behat\Testwork\EventDispatcher\Event\AfterSuiteTested; use Behat\Testwork\EventDispatcher\Event\BeforeSuiteTested; use Behat\Testwork\Output\Formatter; use Behat\Testwork\Output\Node\EventListener\EventListener; -use Symfony\Contracts\EventDispatcher\Event; /** * Listens for Outline events store the current one diff --git a/src/Behat/Behat/Output/Node/EventListener/Statistics/HookStatsListener.php b/src/Behat/Behat/Output/Node/EventListener/Statistics/HookStatsListener.php index 92040a7ff..a4c9b779b 100644 --- a/src/Behat/Behat/Output/Node/EventListener/Statistics/HookStatsListener.php +++ b/src/Behat/Behat/Output/Node/EventListener/Statistics/HookStatsListener.php @@ -13,6 +13,7 @@ use Behat\Behat\Output\Statistics\HookStat; use Behat\Behat\Output\Statistics\Statistics; use Behat\Testwork\Call\CallResult; +use Behat\Testwork\Event\Event; use Behat\Testwork\EventDispatcher\Event\AfterSetup; use Behat\Testwork\EventDispatcher\Event\AfterTested; use Behat\Testwork\Exception\ExceptionPresenter; @@ -20,7 +21,6 @@ use Behat\Testwork\Hook\Tester\Setup\HookedTeardown; use Behat\Testwork\Output\Formatter; use Behat\Testwork\Output\Node\EventListener\EventListener; -use Symfony\Contracts\EventDispatcher\Event; /** * Listens and records hook stats. diff --git a/src/Behat/Behat/Output/Node/EventListener/Statistics/ScenarioStatsListener.php b/src/Behat/Behat/Output/Node/EventListener/Statistics/ScenarioStatsListener.php index c51982e4c..ce94b2b2f 100644 --- a/src/Behat/Behat/Output/Node/EventListener/Statistics/ScenarioStatsListener.php +++ b/src/Behat/Behat/Output/Node/EventListener/Statistics/ScenarioStatsListener.php @@ -15,9 +15,9 @@ use Behat\Behat\EventDispatcher\Event\BeforeFeatureTested; use Behat\Behat\Output\Statistics\ScenarioStat; use Behat\Behat\Output\Statistics\Statistics; +use Behat\Testwork\Event\Event; use Behat\Testwork\Output\Formatter; use Behat\Testwork\Output\Node\EventListener\EventListener; -use Symfony\Contracts\EventDispatcher\Event; /** * Listens and records scenario events to the statistics. diff --git a/src/Behat/Behat/Output/Node/EventListener/Statistics/StatisticsListener.php b/src/Behat/Behat/Output/Node/EventListener/Statistics/StatisticsListener.php index f5a4f0065..763eb76ad 100644 --- a/src/Behat/Behat/Output/Node/EventListener/Statistics/StatisticsListener.php +++ b/src/Behat/Behat/Output/Node/EventListener/Statistics/StatisticsListener.php @@ -12,10 +12,10 @@ use Behat\Behat\Output\Node\Printer\StatisticsPrinter; use Behat\Behat\Output\Statistics\Statistics; +use Behat\Testwork\Event\Event; use Behat\Testwork\EventDispatcher\Event\ExerciseCompleted; use Behat\Testwork\Output\Formatter; use Behat\Testwork\Output\Node\EventListener\EventListener; -use Symfony\Contracts\EventDispatcher\Event; /** * Collects general suite stats such as time and memory during its execution and prints it afterwards. diff --git a/src/Behat/Behat/Output/Node/EventListener/Statistics/StepStatsListener.php b/src/Behat/Behat/Output/Node/EventListener/Statistics/StepStatsListener.php index 2cfcfcf94..2e4a2f7ba 100644 --- a/src/Behat/Behat/Output/Node/EventListener/Statistics/StepStatsListener.php +++ b/src/Behat/Behat/Output/Node/EventListener/Statistics/StepStatsListener.php @@ -17,16 +17,15 @@ use Behat\Behat\EventDispatcher\Event\ScenarioTested; use Behat\Behat\Output\Statistics\StepStatV2; use Behat\Behat\Output\Statistics\Statistics; -use Behat\Behat\Output\Statistics\StepStat; use Behat\Behat\Tester\Exception\PendingException; use Behat\Behat\Tester\Result\ExecutedStepResult; use Behat\Behat\Tester\Result\StepResult; +use Behat\Testwork\Event\Event; use Behat\Testwork\Exception\ExceptionPresenter; use Behat\Testwork\Output\Formatter; use Behat\Testwork\Output\Node\EventListener\EventListener; use Behat\Testwork\Tester\Result\ExceptionResult; use Exception; -use Symfony\Contracts\EventDispatcher\Event; /** * Listens and records step events to statistics. diff --git a/src/Behat/Behat/Output/Node/Printer/CounterPrinter.php b/src/Behat/Behat/Output/Node/Printer/CounterPrinter.php index 47655f20e..92954c342 100644 --- a/src/Behat/Behat/Output/Node/Printer/CounterPrinter.php +++ b/src/Behat/Behat/Output/Node/Printer/CounterPrinter.php @@ -10,9 +10,9 @@ namespace Behat\Behat\Output\Node\Printer; +use Behat\Behat\Definition\Translator\TranslatorInterface; use Behat\Behat\Output\Node\Printer\Helper\ResultToStringConverter; use Behat\Testwork\Output\Printer\OutputPrinter; -use Symfony\Contracts\Translation\TranslatorInterface; /** * Behat counter printer. diff --git a/src/Behat/Behat/Output/Node/Printer/ListPrinter.php b/src/Behat/Behat/Output/Node/Printer/ListPrinter.php index 41f92ce97..8f7193649 100644 --- a/src/Behat/Behat/Output/Node/Printer/ListPrinter.php +++ b/src/Behat/Behat/Output/Node/Printer/ListPrinter.php @@ -10,6 +10,7 @@ namespace Behat\Behat\Output\Node\Printer; +use Behat\Behat\Definition\Translator\TranslatorInterface; use Behat\Behat\Output\Node\Printer\Helper\ResultToStringConverter; use Behat\Behat\Output\Statistics\HookStat; use Behat\Behat\Output\Statistics\ScenarioStat; @@ -18,7 +19,6 @@ use Behat\Testwork\Exception\ExceptionPresenter; use Behat\Testwork\Output\Printer\OutputPrinter; use Behat\Testwork\Tester\Result\TestResult; -use Symfony\Contracts\Translation\TranslatorInterface; /** * Behat list printer. diff --git a/src/Behat/Behat/Snippet/Printer/ConsoleSnippetPrinter.php b/src/Behat/Behat/Snippet/Printer/ConsoleSnippetPrinter.php index ec06bc17d..4112b695d 100644 --- a/src/Behat/Behat/Snippet/Printer/ConsoleSnippetPrinter.php +++ b/src/Behat/Behat/Snippet/Printer/ConsoleSnippetPrinter.php @@ -10,11 +10,11 @@ namespace Behat\Behat\Snippet\Printer; +use Behat\Behat\Definition\Translator\TranslatorInterface; use Behat\Behat\Snippet\AggregateSnippet; use Behat\Gherkin\Node\StepNode; use Symfony\Component\Console\Formatter\OutputFormatterStyle; use Symfony\Component\Console\Output\OutputInterface; -use Symfony\Contracts\Translation\TranslatorInterface; /** * Behat console-based snippet printer. diff --git a/src/Behat/Behat/Transformation/Transformer/RepositoryArgumentTransformer.php b/src/Behat/Behat/Transformation/Transformer/RepositoryArgumentTransformer.php index 02b889f7b..62b14bd1f 100644 --- a/src/Behat/Behat/Transformation/Transformer/RepositoryArgumentTransformer.php +++ b/src/Behat/Behat/Transformation/Transformer/RepositoryArgumentTransformer.php @@ -12,6 +12,7 @@ use Behat\Behat\Definition\Call\DefinitionCall; use Behat\Behat\Definition\Pattern\PatternTransformer; +use Behat\Behat\Definition\Translator\TranslatorInterface; use Behat\Behat\Transformation\SimpleArgumentTransformation; use Behat\Behat\Transformation\Transformation\PatternTransformation; use Behat\Behat\Transformation\RegexGenerator; @@ -19,7 +20,6 @@ use Behat\Behat\Transformation\TransformationRepository; use Behat\Gherkin\Node\ArgumentInterface; use Behat\Testwork\Call\CallCenter; -use Symfony\Contracts\Translation\TranslatorInterface; /** * Argument transformer based on transformations repository. diff --git a/src/Behat/Testwork/Event/Event.php b/src/Behat/Testwork/Event/Event.php new file mode 100644 index 000000000..4e570ef4b --- /dev/null +++ b/src/Behat/Testwork/Event/Event.php @@ -0,0 +1,15 @@ +eventDispatcher->dispatch($event, $event::BEFORE); + + if (class_exists(\Symfony\Contracts\EventDispatcher\Event::class)) { + $this->eventDispatcher->dispatch($event, $event::BEFORE); + } else { + $this->eventDispatcher->dispatch($event::BEFORE, $event); + } $setup = $this->baseExercise->setUp($iterators, $skip); $event = new AfterExerciseSetup($iterators, $setup); - $this->eventDispatcher->dispatch($event, $event::AFTER_SETUP); + + if (class_exists(\Symfony\Contracts\EventDispatcher\Event::class)) { + $this->eventDispatcher->dispatch($event, $event::AFTER_SETUP); + } else { + $this->eventDispatcher->dispatch($event::AFTER_SETUP, $event); + } return $setup; } @@ -76,12 +86,22 @@ public function test(array $iterators, $skip = false) public function tearDown(array $iterators, $skip, TestResult $result) { $event = new BeforeExerciseTeardown($iterators, $result); - $this->eventDispatcher->dispatch($event, $event::BEFORE_TEARDOWN); + + if (class_exists(\Symfony\Contracts\EventDispatcher\Event::class)) { + $this->eventDispatcher->dispatch($event, $event::BEFORE_TEARDOWN); + } else { + $this->eventDispatcher->dispatch($event::BEFORE_TEARDOWN, $event); + } $teardown = $this->baseExercise->tearDown($iterators, $skip, $result); $event = new AfterExerciseCompleted($iterators, $result, $teardown); - $this->eventDispatcher->dispatch($event, $event::AFTER); + + if (class_exists(\Symfony\Contracts\EventDispatcher\Event::class)) { + $this->eventDispatcher->dispatch($event, $event::AFTER); + } else { + $this->eventDispatcher->dispatch($event::AFTER, $event); + } return $teardown; } diff --git a/src/Behat/Testwork/EventDispatcher/Tester/EventDispatchingSuiteTester.php b/src/Behat/Testwork/EventDispatcher/Tester/EventDispatchingSuiteTester.php index 3dbeae502..84a16b8d9 100644 --- a/src/Behat/Testwork/EventDispatcher/Tester/EventDispatchingSuiteTester.php +++ b/src/Behat/Testwork/EventDispatcher/Tester/EventDispatchingSuiteTester.php @@ -54,12 +54,22 @@ public function __construct(SuiteTester $baseTester, EventDispatcherInterface $e public function setUp(Environment $env, SpecificationIterator $iterator, $skip) { $event = new BeforeSuiteTested($env, $iterator); - $this->eventDispatcher->dispatch($event, $event::BEFORE); + + if (class_exists(\Symfony\Contracts\EventDispatcher\Event::class)) { + $this->eventDispatcher->dispatch($event, $event::BEFORE); + } else { + $this->eventDispatcher->dispatch($event::BEFORE, $event); + } $setup = $this->baseTester->setUp($env, $iterator, $skip); $event = new AfterSuiteSetup($env, $iterator, $setup); - $this->eventDispatcher->dispatch($event, $event::AFTER_SETUP); + + if (class_exists(\Symfony\Contracts\EventDispatcher\Event::class)) { + $this->eventDispatcher->dispatch($event, $event::AFTER_SETUP); + } else { + $this->eventDispatcher->dispatch($event::AFTER_SETUP, $event); + } return $setup; } @@ -78,12 +88,21 @@ public function test(Environment $env, SpecificationIterator $iterator, $skip = public function tearDown(Environment $env, SpecificationIterator $iterator, $skip, TestResult $result) { $event = new BeforeSuiteTeardown($env, $iterator, $result); - $this->eventDispatcher->dispatch($event, $event::BEFORE_TEARDOWN); + if (class_exists(\Symfony\Contracts\EventDispatcher\Event::class)) { + $this->eventDispatcher->dispatch( $event, $event::BEFORE_TEARDOWN); + } else { + $this->eventDispatcher->dispatch($event::BEFORE_TEARDOWN, $event); + } $teardown = $this->baseTester->tearDown($env, $iterator, $skip, $result); $event = new AfterSuiteTested($env, $iterator, $result, $teardown); - $this->eventDispatcher->dispatch($event, $event::AFTER); + + if (class_exists(\Symfony\Contracts\EventDispatcher\Event::class)) { + $this->eventDispatcher->dispatch( $event, $event::AFTER); + } else { + $this->eventDispatcher->dispatch($event::AFTER, $event); + } return $teardown; } diff --git a/src/Behat/Testwork/EventDispatcher/TestworkEventDispatcher.php b/src/Behat/Testwork/EventDispatcher/TestworkEventDispatcher.php index 890b157ed..9555bd314 100644 --- a/src/Behat/Testwork/EventDispatcher/TestworkEventDispatcher.php +++ b/src/Behat/Testwork/EventDispatcher/TestworkEventDispatcher.php @@ -10,7 +10,6 @@ namespace Behat\Testwork\EventDispatcher; -use Symfony\Contracts\EventDispatcher\Event; use Symfony\Component\EventDispatcher\EventDispatcher; /** @@ -18,42 +17,84 @@ * * @author Konstantin Kudryashov */ -final class TestworkEventDispatcher extends EventDispatcher -{ - const BEFORE_ALL_EVENTS = '*~'; - const AFTER_ALL_EVENTS = '~*'; - - /** - * {@inheritdoc} - */ - public function dispatch(object $event, string $eventName = null): object + +if (class_exists(\Symfony\Contracts\EventDispatcher\Event::class)) { + + final class TestworkEventDispatcher extends EventDispatcher { - if (null === $event) { - $event = new Event(); - } + const BEFORE_ALL_EVENTS = '*~'; + const AFTER_ALL_EVENTS = '~*'; + + /** + * {@inheritdoc} + */ + public function dispatch(object $event, string $eventName = null): object + { + if (null === $event) { + $event = new \Symfony\Contracts\EventDispatcher\Event(); + } + if (method_exists($event, 'setName')) { + $event->setName($eventName); + } + + $this->callListeners($this->getListeners($eventName), $eventName, $event); - if (method_exists($event, 'setName')) { - $event->setName($eventName); + return $event; } - $this->callListeners($this->getListeners($eventName), $eventName, $event); + /** + * {@inheritdoc} + */ + public function getListeners(string $eventName = null) + { + if (null == $eventName || self::BEFORE_ALL_EVENTS === $eventName) { + return parent::getListeners($eventName); + } - return $event; + return array_merge( + parent::getListeners(self::BEFORE_ALL_EVENTS), + parent::getListeners($eventName), + parent::getListeners(self::AFTER_ALL_EVENTS) + ); + } } +} else { - /** - * {@inheritdoc} - */ - public function getListeners(string $eventName = null) + final class TestworkEventDispatcher extends EventDispatcher { - if (null == $eventName || self::BEFORE_ALL_EVENTS === $eventName) { - return parent::getListeners($eventName); + const BEFORE_ALL_EVENTS = '*~'; + const AFTER_ALL_EVENTS = '~*'; + + /** + * {@inheritdoc} + */ + public function dispatch($eventName, \Symfony\Component\EventDispatcher\Event $event = null) + { + if (null === $event) { + $event = new \Symfony\Component\EventDispatcher\Event(); + } + if (method_exists($event, 'setName')) { + $event->setName($eventName); + } + $this->doDispatch($this->getListeners($eventName), $eventName, $event); + + return $event; } + /** + * {@inheritdoc} + */ + public function getListeners($eventName = null) + { + if (null == $eventName || self::BEFORE_ALL_EVENTS === $eventName) { + return parent::getListeners($eventName); + } - return array_merge( - parent::getListeners(self::BEFORE_ALL_EVENTS), - parent::getListeners($eventName), - parent::getListeners(self::AFTER_ALL_EVENTS) - ); + return array_merge( + parent::getListeners(self::BEFORE_ALL_EVENTS), + parent::getListeners($eventName), + parent::getListeners(self::AFTER_ALL_EVENTS) + ); + } } + } diff --git a/src/Behat/Testwork/Exception/ExceptionPresenter.php b/src/Behat/Testwork/Exception/ExceptionPresenter.php index 9ad0d14c2..3eb4a28bd 100644 --- a/src/Behat/Testwork/Exception/ExceptionPresenter.php +++ b/src/Behat/Testwork/Exception/ExceptionPresenter.php @@ -13,7 +13,6 @@ use Behat\Testwork\Exception\Stringer\ExceptionStringer; use Behat\Testwork\Output\Printer\OutputPrinter; use Exception; -use Symfony\Component\Console\Output\OutputInterface; /** * Presents exceptions as strings using registered stringers. diff --git a/src/Behat/Testwork/Output/Node/EventListener/ChainEventListener.php b/src/Behat/Testwork/Output/Node/EventListener/ChainEventListener.php index 76695753a..a360581ee 100644 --- a/src/Behat/Testwork/Output/Node/EventListener/ChainEventListener.php +++ b/src/Behat/Testwork/Output/Node/EventListener/ChainEventListener.php @@ -11,10 +11,10 @@ namespace Behat\Testwork\Output\Node\EventListener; use ArrayIterator; +use Behat\Testwork\Event\Event; use Behat\Testwork\Output\Formatter; use Countable; use IteratorAggregate; -use Symfony\Contracts\EventDispatcher\Event; /** * Used to compose formatter event listeners. diff --git a/src/Behat/Testwork/Output/Node/EventListener/EventListener.php b/src/Behat/Testwork/Output/Node/EventListener/EventListener.php index e6145265c..2faaef957 100644 --- a/src/Behat/Testwork/Output/Node/EventListener/EventListener.php +++ b/src/Behat/Testwork/Output/Node/EventListener/EventListener.php @@ -10,8 +10,8 @@ namespace Behat\Testwork\Output\Node\EventListener; +use Behat\Testwork\Event\Event; use Behat\Testwork\Output\Formatter; -use Symfony\Contracts\EventDispatcher\Event; /** * Used to define formatter event listeners. diff --git a/src/Behat/Testwork/Output/Node/EventListener/Flow/FireOnlyIfFormatterParameterListener.php b/src/Behat/Testwork/Output/Node/EventListener/Flow/FireOnlyIfFormatterParameterListener.php index bbc8d136e..3c917189b 100644 --- a/src/Behat/Testwork/Output/Node/EventListener/Flow/FireOnlyIfFormatterParameterListener.php +++ b/src/Behat/Testwork/Output/Node/EventListener/Flow/FireOnlyIfFormatterParameterListener.php @@ -10,9 +10,9 @@ namespace Behat\Testwork\Output\Node\EventListener\Flow; +use Behat\Testwork\Event\Event; use Behat\Testwork\Output\Formatter; use Behat\Testwork\Output\Node\EventListener\EventListener; -use Symfony\Contracts\EventDispatcher\Event; /** * Catches all events, but proxies them only if formatter has specific parameter set to a specific value. diff --git a/src/Behat/Testwork/Output/NodeEventListeningFormatter.php b/src/Behat/Testwork/Output/NodeEventListeningFormatter.php index 8e5c32a04..272e08041 100644 --- a/src/Behat/Testwork/Output/NodeEventListeningFormatter.php +++ b/src/Behat/Testwork/Output/NodeEventListeningFormatter.php @@ -10,10 +10,10 @@ namespace Behat\Testwork\Output; +use Behat\Testwork\Event\Event; use Behat\Testwork\EventDispatcher\TestworkEventDispatcher; use Behat\Testwork\Output\Node\EventListener\EventListener; use Behat\Testwork\Output\Printer\OutputPrinter; -use Symfony\Contracts\EventDispatcher\Event; /** * Formatter built around the idea of event delegation and composition. diff --git a/src/Behat/Testwork/Translator/ServiceContainer/TranslatorExtension.php b/src/Behat/Testwork/Translator/ServiceContainer/TranslatorExtension.php index 39de237cf..b6e06184e 100644 --- a/src/Behat/Testwork/Translator/ServiceContainer/TranslatorExtension.php +++ b/src/Behat/Testwork/Translator/ServiceContainer/TranslatorExtension.php @@ -91,7 +91,7 @@ public function process(ContainerBuilder $container) */ private function loadTranslator(ContainerBuilder $container, $locale, $fallbackLocale) { - $definition = new Definition('Symfony\Component\Translation\Translator', array($locale)); + $definition = new Definition('Behat\Behat\Definition\Translator\Translator', array($locale)); $container->setDefinition(self::TRANSLATOR_ID, $definition); $definition->addMethodCall('setFallbackLocales', array(array($fallbackLocale))); From be451e9cab39638718ff0d4ab30117ba9b840a66 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Javier=20D=C3=ADaz?= Date: Wed, 27 Nov 2019 19:23:25 +0100 Subject: [PATCH 177/567] Last treebuilder and code fixes --- .../Tester/EventDispatchingBackgroundTester.php | 1 - src/Behat/Testwork/Exception/ExceptionPresenter.php | 1 + .../ServiceContainer/Configuration/ConfigurationTree.php | 4 ++-- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/Behat/Behat/EventDispatcher/Tester/EventDispatchingBackgroundTester.php b/src/Behat/Behat/EventDispatcher/Tester/EventDispatchingBackgroundTester.php index 7b168f448..8593c746f 100644 --- a/src/Behat/Behat/EventDispatcher/Tester/EventDispatchingBackgroundTester.php +++ b/src/Behat/Behat/EventDispatcher/Tester/EventDispatchingBackgroundTester.php @@ -94,7 +94,6 @@ public function tearDown(Environment $env, FeatureNode $feature, $skip, TestResu $this->eventDispatcher->dispatch($event, BackgroundTested::BEFORE_TEARDOWN); } else { $this->eventDispatcher->dispatch(BackgroundTested::BEFORE_TEARDOWN, $event); - } $teardown = $this->baseTester->tearDown($env, $feature, $skip, $result); diff --git a/src/Behat/Testwork/Exception/ExceptionPresenter.php b/src/Behat/Testwork/Exception/ExceptionPresenter.php index 3eb4a28bd..9ad0d14c2 100644 --- a/src/Behat/Testwork/Exception/ExceptionPresenter.php +++ b/src/Behat/Testwork/Exception/ExceptionPresenter.php @@ -13,6 +13,7 @@ use Behat\Testwork\Exception\Stringer\ExceptionStringer; use Behat\Testwork\Output\Printer\OutputPrinter; use Exception; +use Symfony\Component\Console\Output\OutputInterface; /** * Presents exceptions as strings using registered stringers. diff --git a/src/Behat/Testwork/ServiceContainer/Configuration/ConfigurationTree.php b/src/Behat/Testwork/ServiceContainer/Configuration/ConfigurationTree.php index cf2fa1936..6be1deada 100644 --- a/src/Behat/Testwork/ServiceContainer/Configuration/ConfigurationTree.php +++ b/src/Behat/Testwork/ServiceContainer/Configuration/ConfigurationTree.php @@ -39,13 +39,13 @@ public function getConfigTree(array $extensions) // BC layer for symfony/config 4.1 and older $treeBuilder = new TreeBuilder(); /** @var ArrayNodeDefinition $rootNode */ - $rootNode = $treeBuilder->root('sylius_resource'); + $rootNode = $treeBuilder->root('testwork'); } foreach ($extensions as $extension) { $extension->configure($rootNode->children()->arrayNode($extension->getConfigKey())); } - return $tree->buildTree(); + return $treeBuilder->buildTree(); } } From 2c1dbf74d49d1d11285282453fef23172652d872 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Javier=20D=C3=ADaz?= Date: Wed, 27 Nov 2019 20:00:55 +0100 Subject: [PATCH 178/567] Symfony 4.3 is the oldest 4.x maintained version --- .travis.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index 732e4253e..fafcca5b0 100644 --- a/.travis.yml +++ b/.travis.yml @@ -25,7 +25,7 @@ matrix: - php: 7.3 env: SYMFONY_VERSION='^3.4' - php: 7.3 - env: SYMFONY_VERSION='^4.2' + env: SYMFONY_VERSION='^4.3' - php: 7.3 env: SYMFONY_VERSION='^5.0' From 379c9e1f210a379e64f08ad00c3bfccedc61b524 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Javier=20D=C3=ADaz?= Date: Wed, 27 Nov 2019 20:01:27 +0100 Subject: [PATCH 179/567] Scrutinizer considers this call to the old library method something critical --- .../ServiceContainer/Configuration/ConfigurationTree.php | 1 + 1 file changed, 1 insertion(+) diff --git a/src/Behat/Testwork/ServiceContainer/Configuration/ConfigurationTree.php b/src/Behat/Testwork/ServiceContainer/Configuration/ConfigurationTree.php index 6be1deada..7fe010956 100644 --- a/src/Behat/Testwork/ServiceContainer/Configuration/ConfigurationTree.php +++ b/src/Behat/Testwork/ServiceContainer/Configuration/ConfigurationTree.php @@ -39,6 +39,7 @@ public function getConfigTree(array $extensions) // BC layer for symfony/config 4.1 and older $treeBuilder = new TreeBuilder(); /** @var ArrayNodeDefinition $rootNode */ + /** @scrutinizer ignore-call */ $rootNode = $treeBuilder->root('testwork'); } From 70eb4035e5e44899ad2e6fc39d5d3eae543acfdf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Javier=20D=C3=ADaz?= Date: Wed, 27 Nov 2019 21:05:48 +0100 Subject: [PATCH 180/567] Added changes to maximize BC compatibility --- .../Behat/Definition/Translator/TranslatorInterface.php | 2 +- src/Behat/Testwork/EventDispatcher/Cli/SigintController.php | 6 +++++- .../Testwork/EventDispatcher/TestworkEventDispatcher.php | 2 +- 3 files changed, 7 insertions(+), 3 deletions(-) diff --git a/src/Behat/Behat/Definition/Translator/TranslatorInterface.php b/src/Behat/Behat/Definition/Translator/TranslatorInterface.php index 8a89f74fa..c2827fafe 100644 --- a/src/Behat/Behat/Definition/Translator/TranslatorInterface.php +++ b/src/Behat/Behat/Definition/Translator/TranslatorInterface.php @@ -7,7 +7,7 @@ interface TranslatorInterface extends \Symfony\Contracts\Translation\TranslatorI { } } else { - interface TranslatorInterface extends \Symfony\Component\Translation\TranslatorInterface + interface TranslatorInterface extends \Symfony\Component\Translation\TranslatorInterface { } } diff --git a/src/Behat/Testwork/EventDispatcher/Cli/SigintController.php b/src/Behat/Testwork/EventDispatcher/Cli/SigintController.php index 24a639c9c..9f6a9cef8 100644 --- a/src/Behat/Testwork/EventDispatcher/Cli/SigintController.php +++ b/src/Behat/Testwork/EventDispatcher/Cli/SigintController.php @@ -63,7 +63,11 @@ public function execute(InputInterface $input, OutputInterface $output) */ public function abortExercise() { - $this->eventDispatcher->dispatch(ExerciseCompleted::AFTER, new AfterExerciseAborted()); + if (class_exists(\Symfony\Contracts\EventDispatcher\Event::class)) { + $this->eventDispatcher->dispatch(new AfterExerciseAborted(), ExerciseCompleted::AFTER); + } else { + $this->eventDispatcher->dispatch(ExerciseCompleted::AFTER, new AfterExerciseAborted()); + } exit(1); } diff --git a/src/Behat/Testwork/EventDispatcher/TestworkEventDispatcher.php b/src/Behat/Testwork/EventDispatcher/TestworkEventDispatcher.php index 9555bd314..88a5d1ddf 100644 --- a/src/Behat/Testwork/EventDispatcher/TestworkEventDispatcher.php +++ b/src/Behat/Testwork/EventDispatcher/TestworkEventDispatcher.php @@ -28,7 +28,7 @@ final class TestworkEventDispatcher extends EventDispatcher /** * {@inheritdoc} */ - public function dispatch(object $event, string $eventName = null): object + public function dispatch($event, string $eventName = null): object { if (null === $event) { $event = new \Symfony\Contracts\EventDispatcher\Event(); From 389a25d9297c692767a2b466daedd505b0323676 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Javier=20D=C3=ADaz?= Date: Wed, 27 Nov 2019 21:29:35 +0100 Subject: [PATCH 181/567] BC: Remove type reference from the method signature --- src/Behat/Testwork/EventDispatcher/TestworkEventDispatcher.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Behat/Testwork/EventDispatcher/TestworkEventDispatcher.php b/src/Behat/Testwork/EventDispatcher/TestworkEventDispatcher.php index 88a5d1ddf..e9c3c1d82 100644 --- a/src/Behat/Testwork/EventDispatcher/TestworkEventDispatcher.php +++ b/src/Behat/Testwork/EventDispatcher/TestworkEventDispatcher.php @@ -45,7 +45,7 @@ public function dispatch($event, string $eventName = null): object /** * {@inheritdoc} */ - public function getListeners(string $eventName = null) + public function getListeners($eventName = null) { if (null == $eventName || self::BEFORE_ALL_EVENTS === $eventName) { return parent::getListeners($eventName); From e04a6ebb7f6d88c45344467d0a7cd44190e32a63 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Javier=20D=C3=ADaz?= Date: Wed, 27 Nov 2019 21:49:45 +0100 Subject: [PATCH 182/567] Process BC compatibility for symfony 3.4 --- features/bootstrap/FeatureContext.php | 22 ++++++++++++++-------- 1 file changed, 14 insertions(+), 8 deletions(-) diff --git a/features/bootstrap/FeatureContext.php b/features/bootstrap/FeatureContext.php index 6b63074f6..4aaf6f795 100644 --- a/features/bootstrap/FeatureContext.php +++ b/features/bootstrap/FeatureContext.php @@ -190,16 +190,22 @@ public function iRunBehat($argumentsString = '') { $argumentsString = strtr($argumentsString, array('\'' => '"')); - $this->process = Process::fromShellCommandline( - sprintf( - '%s %s %s %s', - $this->phpBin, - escapeshellarg(BEHAT_BIN_PATH), - $argumentsString, - strtr($this->options, array('\'' => '"', '"' => '\"')) - ) + $cmd = sprintf( + '%s %s %s %s', + $this->phpBin, + escapeshellarg(BEHAT_BIN_PATH), + $argumentsString, + strtr($this->options, array('\'' => '"', '"' => '\"')) ); + if (method_exists('\\Symfony\\Component\\Process\\Process', 'fromShellCommandline')) { + $this->process = Process::fromShellCommandline($cmd); + } else { + // BC layer for symfony/process 4.1 and older + $this->process = new Process(null); + $this->process->setCommandLine($cmd); + } + // Prepare the process parameters. $this->process->setTimeout(20); $this->process->setEnv($this->env); From 8fcc67e69950a8c0eaf16ef968faf6c22fb239fb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Javier=20D=C3=ADaz?= Date: Sun, 1 Dec 2019 13:39:23 +0100 Subject: [PATCH 183/567] Some extra work to have scrutinizer green --- src/Behat/Behat/Definition/Translator/TranslatorInterface.php | 2 +- src/Behat/Testwork/EventDispatcher/TestworkEventDispatcher.php | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/src/Behat/Behat/Definition/Translator/TranslatorInterface.php b/src/Behat/Behat/Definition/Translator/TranslatorInterface.php index c2827fafe..5384a48d2 100644 --- a/src/Behat/Behat/Definition/Translator/TranslatorInterface.php +++ b/src/Behat/Behat/Definition/Translator/TranslatorInterface.php @@ -6,7 +6,7 @@ interface TranslatorInterface extends \Symfony\Contracts\Translation\TranslatorInterface { } -} else { +} else if (interface_exists(\Symfony\Component\Translation\TranslatorInterface::class)) { interface TranslatorInterface extends \Symfony\Component\Translation\TranslatorInterface { } diff --git a/src/Behat/Testwork/EventDispatcher/TestworkEventDispatcher.php b/src/Behat/Testwork/EventDispatcher/TestworkEventDispatcher.php index e9c3c1d82..7b7125b7b 100644 --- a/src/Behat/Testwork/EventDispatcher/TestworkEventDispatcher.php +++ b/src/Behat/Testwork/EventDispatcher/TestworkEventDispatcher.php @@ -76,6 +76,7 @@ public function dispatch($eventName, \Symfony\Component\EventDispatcher\Event $e if (method_exists($event, 'setName')) { $event->setName($eventName); } + /** @scrutinizer ignore-call */ $this->doDispatch($this->getListeners($eventName), $eventName, $event); return $event; From 6dab359f76ca0bcb2f0c86b0aa96efe136954562 Mon Sep 17 00:00:00 2001 From: Nyholm Date: Sat, 7 Dec 2019 15:30:37 +0100 Subject: [PATCH 184/567] Fixed build --- composer.json | 16 +++++------ .../Translator/TranslatorInterface.php | 2 +- .../Cli/StopOnFailureController.php | 3 ++- .../EventDispatchingBackgroundTester.php | 9 ++++--- .../Tester/EventDispatchingFeatureTester.php | 9 ++++--- .../Tester/EventDispatchingOutlineTester.php | 9 ++++--- .../Tester/EventDispatchingScenarioTester.php | 9 ++++--- .../Tester/EventDispatchingStepTester.php | 9 ++++--- src/Behat/Testwork/Event/Event.php | 3 ++- .../EventDispatcher/Cli/SigintController.php | 3 ++- .../Tester/EventDispatchingExercise.php | 9 ++++--- .../Tester/EventDispatchingSuiteTester.php | 9 ++++--- .../TestworkEventDispatcher.php | 24 +++++------------ .../TestworkEventDispatcherPhp72Trait.php | 27 +++++++++++++++++++ 14 files changed, 83 insertions(+), 58 deletions(-) create mode 100644 src/Behat/Testwork/EventDispatcher/TestworkEventDispatcherPhp72Trait.php diff --git a/composer.json b/composer.json index 2abbfd968..7390a5018 100644 --- a/composer.json +++ b/composer.json @@ -18,19 +18,19 @@ "ext-mbstring": "*", "behat/gherkin": "^4.6.0", "behat/transliterator": "^1.2", - "symfony/console": "~2.7.40||^2.8.33||~3.3.15||^3.4.3||^4.0.3||^5.0.0", - "symfony/config": "~2.3||~3.0||~4.0||~5.0", - "symfony/dependency-injection": "~2.1||~3.0||~4.0||~5.0", - "symfony/event-dispatcher": "~2.1||~3.0||~4.0||~5.0", - "symfony/translation": "~2.3||~3.0||~4.0||~5.0", - "symfony/yaml": "~2.1||~3.0||~4.0||~5.0", + "symfony/console": "^2.7.51 || ^2.8.33 || ^3.3.15 || ^3.4.3 || ^4.0.3 || ^5.0", + "symfony/config": "^2.7.51 || ^3.0 || ^4.0 || ^5.0", + "symfony/dependency-injection": "^2.7.51 || ^3.0 || ^4.0 || ^5.0", + "symfony/event-dispatcher": "^2.7.51 || ^3.0 || ^4.0 || ^5.0", + "symfony/translation": "^2.7.51 || ^3.0 || ^4.0 || ^5.0", + "symfony/yaml": "^2.7.51 || ^3.0 || ^4.0 || ^5.0", "psr/container": "^1.0", "container-interop/container-interop": "^1.2" }, "require-dev": { - "symfony/process": "~2.5|~3.0|~4.0|~5.0", - "phpunit/phpunit": "^4.8.36|^6.3", + "symfony/process": "~2.5 || ^3.0 || ^4.0 || ^5.0", + "phpunit/phpunit": "^4.8.36 || ^6.3", "herrera-io/box": "~1.6.1" }, diff --git a/src/Behat/Behat/Definition/Translator/TranslatorInterface.php b/src/Behat/Behat/Definition/Translator/TranslatorInterface.php index 5384a48d2..9ad91e381 100644 --- a/src/Behat/Behat/Definition/Translator/TranslatorInterface.php +++ b/src/Behat/Behat/Definition/Translator/TranslatorInterface.php @@ -6,7 +6,7 @@ interface TranslatorInterface extends \Symfony\Contracts\Translation\TranslatorInterface { } -} else if (interface_exists(\Symfony\Component\Translation\TranslatorInterface::class)) { +} elseif (interface_exists(\Symfony\Component\Translation\TranslatorInterface::class)) { interface TranslatorInterface extends \Symfony\Component\Translation\TranslatorInterface { } diff --git a/src/Behat/Behat/EventDispatcher/Cli/StopOnFailureController.php b/src/Behat/Behat/EventDispatcher/Cli/StopOnFailureController.php index f5d7f627a..637f99dd0 100644 --- a/src/Behat/Behat/EventDispatcher/Cli/StopOnFailureController.php +++ b/src/Behat/Behat/EventDispatcher/Cli/StopOnFailureController.php @@ -18,6 +18,7 @@ use Behat\Testwork\EventDispatcher\Event\AfterSuiteAborted; use Behat\Testwork\EventDispatcher\Event\ExerciseCompleted; use Behat\Testwork\EventDispatcher\Event\SuiteTested; +use Behat\Testwork\EventDispatcher\TestworkEventDispatcher; use Behat\Testwork\Tester\Result\Interpretation\ResultInterpretation; use Behat\Testwork\Tester\Result\Interpretation\SoftInterpretation; use Behat\Testwork\Tester\Result\Interpretation\StrictInterpretation; @@ -100,7 +101,7 @@ public function exitOnFailure(AfterScenarioTested $event) return; } - if (class_exists(\Symfony\Contracts\EventDispatcher\Event::class)) { + if (TestworkEventDispatcher::DISPATCHER_VERSION === 2) { $this->eventDispatcher->dispatch(new AfterSuiteAborted($event->getEnvironment()), SuiteTested::AFTER); $this->eventDispatcher->dispatch(new AfterExerciseAborted(), ExerciseCompleted::AFTER); } else { diff --git a/src/Behat/Behat/EventDispatcher/Tester/EventDispatchingBackgroundTester.php b/src/Behat/Behat/EventDispatcher/Tester/EventDispatchingBackgroundTester.php index 8593c746f..2c50db1f5 100644 --- a/src/Behat/Behat/EventDispatcher/Tester/EventDispatchingBackgroundTester.php +++ b/src/Behat/Behat/EventDispatcher/Tester/EventDispatchingBackgroundTester.php @@ -18,6 +18,7 @@ use Behat\Behat\Tester\BackgroundTester; use Behat\Gherkin\Node\FeatureNode; use Behat\Testwork\Environment\Environment; +use Behat\Testwork\EventDispatcher\TestworkEventDispatcher; use Behat\Testwork\Tester\Result\TestResult; use Symfony\Component\EventDispatcher\EventDispatcherInterface; @@ -56,7 +57,7 @@ public function setUp(Environment $env, FeatureNode $feature, $skip) { $event = new BeforeBackgroundTested($env, $feature, $feature->getBackground()); - if (class_exists(\Symfony\Contracts\EventDispatcher\Event::class)) { + if (TestworkEventDispatcher::DISPATCHER_VERSION === 2) { $this->eventDispatcher->dispatch($event, $event::BEFORE); } else { $this->eventDispatcher->dispatch($event::BEFORE, $event); @@ -66,7 +67,7 @@ public function setUp(Environment $env, FeatureNode $feature, $skip) $event = new AfterBackgroundSetup($env, $feature, $feature->getBackground(), $setup); - if (class_exists(\Symfony\Contracts\EventDispatcher\Event::class)) { + if (TestworkEventDispatcher::DISPATCHER_VERSION === 2) { $this->eventDispatcher->dispatch($event, $event::AFTER_SETUP); } else { $this->eventDispatcher->dispatch($event::AFTER_SETUP, $event); @@ -90,7 +91,7 @@ public function tearDown(Environment $env, FeatureNode $feature, $skip, TestResu { $event = new BeforeBackgroundTeardown($env, $feature, $feature->getBackground(), $result); - if (class_exists(\Symfony\Contracts\EventDispatcher\Event::class)) { + if (TestworkEventDispatcher::DISPATCHER_VERSION === 2) { $this->eventDispatcher->dispatch($event, BackgroundTested::BEFORE_TEARDOWN); } else { $this->eventDispatcher->dispatch(BackgroundTested::BEFORE_TEARDOWN, $event); @@ -100,7 +101,7 @@ public function tearDown(Environment $env, FeatureNode $feature, $skip, TestResu $event = new AfterBackgroundTested($env, $feature, $feature->getBackground(), $result, $teardown); - if (class_exists(\Symfony\Contracts\EventDispatcher\Event::class)) { + if (TestworkEventDispatcher::DISPATCHER_VERSION === 2) { $this->eventDispatcher->dispatch($event, BackgroundTested::AFTER); } else { $this->eventDispatcher->dispatch(BackgroundTested::AFTER, $event); diff --git a/src/Behat/Behat/EventDispatcher/Tester/EventDispatchingFeatureTester.php b/src/Behat/Behat/EventDispatcher/Tester/EventDispatchingFeatureTester.php index 7175c7620..c07313b61 100644 --- a/src/Behat/Behat/EventDispatcher/Tester/EventDispatchingFeatureTester.php +++ b/src/Behat/Behat/EventDispatcher/Tester/EventDispatchingFeatureTester.php @@ -15,6 +15,7 @@ use Behat\Behat\EventDispatcher\Event\BeforeFeatureTeardown; use Behat\Behat\EventDispatcher\Event\BeforeFeatureTested; use Behat\Testwork\Environment\Environment; +use Behat\Testwork\EventDispatcher\TestworkEventDispatcher; use Behat\Testwork\Tester\Result\TestResult; use Behat\Testwork\Tester\SpecificationTester; use Symfony\Component\EventDispatcher\EventDispatcherInterface; @@ -54,7 +55,7 @@ public function setUp(Environment $env, $feature, $skip) { $event = new BeforeFeatureTested($env, $feature); - if (class_exists(\Symfony\Contracts\EventDispatcher\Event::class)) { + if (TestworkEventDispatcher::DISPATCHER_VERSION === 2) { $this->eventDispatcher->dispatch($event, $event::BEFORE); } else { $this->eventDispatcher->dispatch($event::BEFORE, $event); @@ -64,7 +65,7 @@ public function setUp(Environment $env, $feature, $skip) $event = new AfterFeatureSetup($env, $feature, $setup); - if (class_exists(\Symfony\Contracts\EventDispatcher\Event::class)) { + if (TestworkEventDispatcher::DISPATCHER_VERSION === 2) { $this->eventDispatcher->dispatch($event, $event::AFTER_SETUP); } else { $this->eventDispatcher->dispatch($event::AFTER_SETUP, $event); @@ -88,7 +89,7 @@ public function tearDown(Environment $env, $feature, $skip, TestResult $result) { $event = new BeforeFeatureTeardown($env, $feature, $result); - if (class_exists(\Symfony\Contracts\EventDispatcher\Event::class)) { + if (TestworkEventDispatcher::DISPATCHER_VERSION === 2) { $this->eventDispatcher->dispatch($event, $event::BEFORE_TEARDOWN); } else { $this->eventDispatcher->dispatch($event::BEFORE_TEARDOWN, $event); @@ -98,7 +99,7 @@ public function tearDown(Environment $env, $feature, $skip, TestResult $result) $event = new AfterFeatureTested($env, $feature, $result, $teardown); - if (class_exists(\Symfony\Contracts\EventDispatcher\Event::class)) { + if (TestworkEventDispatcher::DISPATCHER_VERSION === 2) { $this->eventDispatcher->dispatch($event, $event::AFTER); } else { $this->eventDispatcher->dispatch($event::AFTER, $event); diff --git a/src/Behat/Behat/EventDispatcher/Tester/EventDispatchingOutlineTester.php b/src/Behat/Behat/EventDispatcher/Tester/EventDispatchingOutlineTester.php index 21850c86f..3b1d77fa9 100644 --- a/src/Behat/Behat/EventDispatcher/Tester/EventDispatchingOutlineTester.php +++ b/src/Behat/Behat/EventDispatcher/Tester/EventDispatchingOutlineTester.php @@ -18,6 +18,7 @@ use Behat\Gherkin\Node\FeatureNode; use Behat\Gherkin\Node\OutlineNode; use Behat\Testwork\Environment\Environment; +use Behat\Testwork\EventDispatcher\TestworkEventDispatcher; use Behat\Testwork\Tester\Result\TestResult; use Symfony\Component\EventDispatcher\EventDispatcherInterface; @@ -56,7 +57,7 @@ public function setUp(Environment $env, FeatureNode $feature, OutlineNode $outli { $event = new BeforeOutlineTested($env, $feature, $outline); - if (class_exists(\Symfony\Contracts\EventDispatcher\Event::class)) { + if (TestworkEventDispatcher::DISPATCHER_VERSION === 2) { $this->eventDispatcher->dispatch($event, $event::BEFORE); } else { $this->eventDispatcher->dispatch($event::BEFORE, $event); @@ -66,7 +67,7 @@ public function setUp(Environment $env, FeatureNode $feature, OutlineNode $outli $event = new AfterOutlineSetup($env, $feature, $outline, $setup); - if (class_exists(\Symfony\Contracts\EventDispatcher\Event::class)) { + if (TestworkEventDispatcher::DISPATCHER_VERSION === 2) { $this->eventDispatcher->dispatch($event, $event::AFTER_SETUP); } else { $this->eventDispatcher->dispatch($event::AFTER_SETUP, $event); @@ -90,7 +91,7 @@ public function tearDown(Environment $env, FeatureNode $feature, OutlineNode $ou { $event = new BeforeOutlineTeardown($env, $feature, $outline, $result); - if (class_exists(\Symfony\Contracts\EventDispatcher\Event::class)) { + if (TestworkEventDispatcher::DISPATCHER_VERSION === 2) { $this->eventDispatcher->dispatch( $event,$event::BEFORE_TEARDOWN); } else { $this->eventDispatcher->dispatch($event::BEFORE_TEARDOWN, $event); @@ -100,7 +101,7 @@ public function tearDown(Environment $env, FeatureNode $feature, OutlineNode $ou $event = new AfterOutlineTested($env, $feature, $outline, $result, $teardown); - if (class_exists(\Symfony\Contracts\EventDispatcher\Event::class)) { + if (TestworkEventDispatcher::DISPATCHER_VERSION === 2) { $this->eventDispatcher->dispatch($event, $event::AFTER); } else { $this->eventDispatcher->dispatch($event::AFTER, $event); diff --git a/src/Behat/Behat/EventDispatcher/Tester/EventDispatchingScenarioTester.php b/src/Behat/Behat/EventDispatcher/Tester/EventDispatchingScenarioTester.php index c25c55201..a45ee5ac9 100644 --- a/src/Behat/Behat/EventDispatcher/Tester/EventDispatchingScenarioTester.php +++ b/src/Behat/Behat/EventDispatcher/Tester/EventDispatchingScenarioTester.php @@ -18,6 +18,7 @@ use Behat\Gherkin\Node\FeatureNode; use Behat\Gherkin\Node\ScenarioInterface as Scenario; use Behat\Testwork\Environment\Environment; +use Behat\Testwork\EventDispatcher\TestworkEventDispatcher; use Behat\Testwork\Tester\Result\TestResult; use Symfony\Component\EventDispatcher\EventDispatcherInterface; @@ -86,7 +87,7 @@ public function setUp(Environment $env, FeatureNode $feature, Scenario $scenario { $event = new BeforeScenarioTested($env, $feature, $scenario); - if (class_exists(\Symfony\Contracts\EventDispatcher\Event::class)) { + if (TestworkEventDispatcher::DISPATCHER_VERSION === 2) { $this->eventDispatcher->dispatch($event, $this->beforeEventName); } else { $this->eventDispatcher->dispatch($this->beforeEventName, $event); @@ -96,7 +97,7 @@ public function setUp(Environment $env, FeatureNode $feature, Scenario $scenario $event = new AfterScenarioSetup($env, $feature, $scenario, $setup); - if (class_exists(\Symfony\Contracts\EventDispatcher\Event::class)) { + if (TestworkEventDispatcher::DISPATCHER_VERSION === 2) { $this->eventDispatcher->dispatch($event, $this->afterSetupEventName); } else { $this->eventDispatcher->dispatch($this->afterSetupEventName, $event); @@ -120,7 +121,7 @@ public function tearDown(Environment $env, FeatureNode $feature, Scenario $scena { $event = new BeforeScenarioTeardown($env, $feature, $scenario, $result); - if (class_exists(\Symfony\Contracts\EventDispatcher\Event::class)) { + if (TestworkEventDispatcher::DISPATCHER_VERSION === 2) { $this->eventDispatcher->dispatch($event, $this->beforeTeardownEventName); } else { $this->eventDispatcher->dispatch($this->beforeTeardownEventName, $event); @@ -130,7 +131,7 @@ public function tearDown(Environment $env, FeatureNode $feature, Scenario $scena $event = new AfterScenarioTested($env, $feature, $scenario, $result, $teardown); - if (class_exists(\Symfony\Contracts\EventDispatcher\Event::class)) { + if (TestworkEventDispatcher::DISPATCHER_VERSION === 2) { $this->eventDispatcher->dispatch($event, $this->afterEventName); } else { $this->eventDispatcher->dispatch($this->afterEventName, $event); diff --git a/src/Behat/Behat/EventDispatcher/Tester/EventDispatchingStepTester.php b/src/Behat/Behat/EventDispatcher/Tester/EventDispatchingStepTester.php index 5a0fec6e0..3fa53f8df 100644 --- a/src/Behat/Behat/EventDispatcher/Tester/EventDispatchingStepTester.php +++ b/src/Behat/Behat/EventDispatcher/Tester/EventDispatchingStepTester.php @@ -19,6 +19,7 @@ use Behat\Gherkin\Node\FeatureNode; use Behat\Gherkin\Node\StepNode; use Behat\Testwork\Environment\Environment; +use Behat\Testwork\EventDispatcher\TestworkEventDispatcher; use Symfony\Component\EventDispatcher\EventDispatcherInterface; /** @@ -56,7 +57,7 @@ public function setUp(Environment $env, FeatureNode $feature, StepNode $step, $s { $event = new BeforeStepTested($env, $feature, $step); - if (class_exists(\Symfony\Contracts\EventDispatcher\Event::class)) { + if (TestworkEventDispatcher::DISPATCHER_VERSION === 2) { $this->eventDispatcher->dispatch($event, $event::BEFORE); } else { $this->eventDispatcher->dispatch($event::BEFORE, $event); @@ -66,7 +67,7 @@ public function setUp(Environment $env, FeatureNode $feature, StepNode $step, $s $event = new AfterStepSetup($env, $feature, $step, $setup); - if (class_exists(\Symfony\Contracts\EventDispatcher\Event::class)) { + if (TestworkEventDispatcher::DISPATCHER_VERSION === 2) { $this->eventDispatcher->dispatch($event, $event::AFTER_SETUP); } else { $this->eventDispatcher->dispatch($event::AFTER_SETUP, $event); @@ -90,7 +91,7 @@ public function tearDown(Environment $env, FeatureNode $feature, StepNode $step, { $event = new BeforeStepTeardown($env, $feature, $step, $result); - if (class_exists(\Symfony\Contracts\EventDispatcher\Event::class)) { + if (TestworkEventDispatcher::DISPATCHER_VERSION === 2) { $this->eventDispatcher->dispatch($event, $event::BEFORE_TEARDOWN); } else { $this->eventDispatcher->dispatch($event::BEFORE_TEARDOWN, $event); @@ -100,7 +101,7 @@ public function tearDown(Environment $env, FeatureNode $feature, StepNode $step, $event = new AfterStepTested($env, $feature, $step, $result, $teardown); - if (class_exists(\Symfony\Contracts\EventDispatcher\Event::class)) { + if (TestworkEventDispatcher::DISPATCHER_VERSION === 2) { $this->eventDispatcher->dispatch($event, $event::AFTER); } else { $this->eventDispatcher->dispatch($event::AFTER, $event); diff --git a/src/Behat/Testwork/Event/Event.php b/src/Behat/Testwork/Event/Event.php index 4e570ef4b..859a9d0f1 100644 --- a/src/Behat/Testwork/Event/Event.php +++ b/src/Behat/Testwork/Event/Event.php @@ -2,8 +2,9 @@ namespace Behat\Testwork\Event; +use Behat\Testwork\EventDispatcher\TestworkEventDispatcher; -if (class_exists(\Symfony\Contracts\EventDispatcher\Event::class)) { +if (TestworkEventDispatcher::DISPATCHER_VERSION === 2) { class Event extends \Symfony\Contracts\EventDispatcher\Event { } diff --git a/src/Behat/Testwork/EventDispatcher/Cli/SigintController.php b/src/Behat/Testwork/EventDispatcher/Cli/SigintController.php index 9f6a9cef8..cf9338b25 100644 --- a/src/Behat/Testwork/EventDispatcher/Cli/SigintController.php +++ b/src/Behat/Testwork/EventDispatcher/Cli/SigintController.php @@ -13,6 +13,7 @@ use Behat\Testwork\Cli\Controller; use Behat\Testwork\EventDispatcher\Event\AfterExerciseAborted; use Behat\Testwork\EventDispatcher\Event\ExerciseCompleted; +use Behat\Testwork\EventDispatcher\TestworkEventDispatcher; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; @@ -63,7 +64,7 @@ public function execute(InputInterface $input, OutputInterface $output) */ public function abortExercise() { - if (class_exists(\Symfony\Contracts\EventDispatcher\Event::class)) { + if (TestworkEventDispatcher::DISPATCHER_VERSION === 2) { $this->eventDispatcher->dispatch(new AfterExerciseAborted(), ExerciseCompleted::AFTER); } else { $this->eventDispatcher->dispatch(ExerciseCompleted::AFTER, new AfterExerciseAborted()); diff --git a/src/Behat/Testwork/EventDispatcher/Tester/EventDispatchingExercise.php b/src/Behat/Testwork/EventDispatcher/Tester/EventDispatchingExercise.php index 6f48f6232..0ea275d6c 100644 --- a/src/Behat/Testwork/EventDispatcher/Tester/EventDispatchingExercise.php +++ b/src/Behat/Testwork/EventDispatcher/Tester/EventDispatchingExercise.php @@ -14,6 +14,7 @@ use Behat\Testwork\EventDispatcher\Event\AfterExerciseSetup; use Behat\Testwork\EventDispatcher\Event\BeforeExerciseCompleted; use Behat\Testwork\EventDispatcher\Event\BeforeExerciseTeardown; +use Behat\Testwork\EventDispatcher\TestworkEventDispatcher; use Behat\Testwork\Tester\Exercise; use Behat\Testwork\Tester\Result\TestResult; use Symfony\Component\EventDispatcher\EventDispatcherInterface; @@ -53,7 +54,7 @@ public function setUp(array $iterators, $skip) { $event = new BeforeExerciseCompleted($iterators); - if (class_exists(\Symfony\Contracts\EventDispatcher\Event::class)) { + if (TestworkEventDispatcher::DISPATCHER_VERSION === 2) { $this->eventDispatcher->dispatch($event, $event::BEFORE); } else { $this->eventDispatcher->dispatch($event::BEFORE, $event); @@ -63,7 +64,7 @@ public function setUp(array $iterators, $skip) $event = new AfterExerciseSetup($iterators, $setup); - if (class_exists(\Symfony\Contracts\EventDispatcher\Event::class)) { + if (TestworkEventDispatcher::DISPATCHER_VERSION === 2) { $this->eventDispatcher->dispatch($event, $event::AFTER_SETUP); } else { $this->eventDispatcher->dispatch($event::AFTER_SETUP, $event); @@ -87,7 +88,7 @@ public function tearDown(array $iterators, $skip, TestResult $result) { $event = new BeforeExerciseTeardown($iterators, $result); - if (class_exists(\Symfony\Contracts\EventDispatcher\Event::class)) { + if (TestworkEventDispatcher::DISPATCHER_VERSION === 2) { $this->eventDispatcher->dispatch($event, $event::BEFORE_TEARDOWN); } else { $this->eventDispatcher->dispatch($event::BEFORE_TEARDOWN, $event); @@ -97,7 +98,7 @@ public function tearDown(array $iterators, $skip, TestResult $result) $event = new AfterExerciseCompleted($iterators, $result, $teardown); - if (class_exists(\Symfony\Contracts\EventDispatcher\Event::class)) { + if (TestworkEventDispatcher::DISPATCHER_VERSION === 2) { $this->eventDispatcher->dispatch($event, $event::AFTER); } else { $this->eventDispatcher->dispatch($event::AFTER, $event); diff --git a/src/Behat/Testwork/EventDispatcher/Tester/EventDispatchingSuiteTester.php b/src/Behat/Testwork/EventDispatcher/Tester/EventDispatchingSuiteTester.php index 84a16b8d9..466a759f1 100644 --- a/src/Behat/Testwork/EventDispatcher/Tester/EventDispatchingSuiteTester.php +++ b/src/Behat/Testwork/EventDispatcher/Tester/EventDispatchingSuiteTester.php @@ -15,6 +15,7 @@ use Behat\Testwork\EventDispatcher\Event\AfterSuiteTested; use Behat\Testwork\EventDispatcher\Event\BeforeSuiteTeardown; use Behat\Testwork\EventDispatcher\Event\BeforeSuiteTested; +use Behat\Testwork\EventDispatcher\TestworkEventDispatcher; use Behat\Testwork\Specification\SpecificationIterator; use Behat\Testwork\Tester\Result\TestResult; use Behat\Testwork\Tester\SuiteTester; @@ -55,7 +56,7 @@ public function setUp(Environment $env, SpecificationIterator $iterator, $skip) { $event = new BeforeSuiteTested($env, $iterator); - if (class_exists(\Symfony\Contracts\EventDispatcher\Event::class)) { + if (TestworkEventDispatcher::DISPATCHER_VERSION === 2) { $this->eventDispatcher->dispatch($event, $event::BEFORE); } else { $this->eventDispatcher->dispatch($event::BEFORE, $event); @@ -65,7 +66,7 @@ public function setUp(Environment $env, SpecificationIterator $iterator, $skip) $event = new AfterSuiteSetup($env, $iterator, $setup); - if (class_exists(\Symfony\Contracts\EventDispatcher\Event::class)) { + if (TestworkEventDispatcher::DISPATCHER_VERSION === 2) { $this->eventDispatcher->dispatch($event, $event::AFTER_SETUP); } else { $this->eventDispatcher->dispatch($event::AFTER_SETUP, $event); @@ -88,7 +89,7 @@ public function test(Environment $env, SpecificationIterator $iterator, $skip = public function tearDown(Environment $env, SpecificationIterator $iterator, $skip, TestResult $result) { $event = new BeforeSuiteTeardown($env, $iterator, $result); - if (class_exists(\Symfony\Contracts\EventDispatcher\Event::class)) { + if (TestworkEventDispatcher::DISPATCHER_VERSION === 2) { $this->eventDispatcher->dispatch( $event, $event::BEFORE_TEARDOWN); } else { $this->eventDispatcher->dispatch($event::BEFORE_TEARDOWN, $event); @@ -98,7 +99,7 @@ public function tearDown(Environment $env, SpecificationIterator $iterator, $ski $event = new AfterSuiteTested($env, $iterator, $result, $teardown); - if (class_exists(\Symfony\Contracts\EventDispatcher\Event::class)) { + if (TestworkEventDispatcher::DISPATCHER_VERSION === 2) { $this->eventDispatcher->dispatch( $event, $event::AFTER); } else { $this->eventDispatcher->dispatch($event::AFTER, $event); diff --git a/src/Behat/Testwork/EventDispatcher/TestworkEventDispatcher.php b/src/Behat/Testwork/EventDispatcher/TestworkEventDispatcher.php index 7b7125b7b..66afc961a 100644 --- a/src/Behat/Testwork/EventDispatcher/TestworkEventDispatcher.php +++ b/src/Behat/Testwork/EventDispatcher/TestworkEventDispatcher.php @@ -18,29 +18,16 @@ * @author Konstantin Kudryashov */ -if (class_exists(\Symfony\Contracts\EventDispatcher\Event::class)) { +if (class_exists(\Symfony\Contracts\EventDispatcher\Event::class) && PHP_VERSION_ID > 70200) { + // Assert: This is Symfony 5 and PHP >= 7.2 + include_once __DIR__.'/TestworkEventDispatcherPhp72Trait.php'; final class TestworkEventDispatcher extends EventDispatcher { + use \TestworkEventDispatcherPhp72Trait; const BEFORE_ALL_EVENTS = '*~'; const AFTER_ALL_EVENTS = '~*'; - - /** - * {@inheritdoc} - */ - public function dispatch($event, string $eventName = null): object - { - if (null === $event) { - $event = new \Symfony\Contracts\EventDispatcher\Event(); - } - if (method_exists($event, 'setName')) { - $event->setName($eventName); - } - - $this->callListeners($this->getListeners($eventName), $eventName, $event); - - return $event; - } + const DISPATCHER_VERSION = 2; /** * {@inheritdoc} @@ -64,6 +51,7 @@ final class TestworkEventDispatcher extends EventDispatcher { const BEFORE_ALL_EVENTS = '*~'; const AFTER_ALL_EVENTS = '~*'; + const DISPATCHER_VERSION = 1; /** * {@inheritdoc} diff --git a/src/Behat/Testwork/EventDispatcher/TestworkEventDispatcherPhp72Trait.php b/src/Behat/Testwork/EventDispatcher/TestworkEventDispatcherPhp72Trait.php new file mode 100644 index 000000000..1387bec4f --- /dev/null +++ b/src/Behat/Testwork/EventDispatcher/TestworkEventDispatcherPhp72Trait.php @@ -0,0 +1,27 @@ + + */ +trait TestworkEventDispatcherPhp72Trait +{ + /** + * {@inheritdoc} + */ + public function dispatch($event, string $eventName = null): object + { + if (null === $event) { + $event = new \Symfony\Contracts\EventDispatcher\Event(); + } + if (method_exists($event, 'setName')) { + $event->setName($eventName); + } + + $this->callListeners($this->getListeners($eventName), $eventName, $event); + + return $event; + } +} \ No newline at end of file From b4f7a00d5ca5650cee641d305eb4f24399b5d23d Mon Sep 17 00:00:00 2001 From: Sam Burns Date: Thu, 16 Jan 2020 10:16:29 +0000 Subject: [PATCH 185/567] Fix Appveyor build --- appveyor.yml | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/appveyor.yml b/appveyor.yml index 58e8a4eba..5095fe212 100644 --- a/appveyor.yml +++ b/appveyor.yml @@ -4,10 +4,6 @@ shallow_clone: false platform: x86 clone_folder: c:\projects\behat -environment: - matrix: - - php: 7.2 - branches: only: - master @@ -31,7 +27,7 @@ init: install: - ps: | if (!(Test-Path c:\tools\php)) { - appveyor-retry cinst --params '""/InstallDir:C:\tools\php""' --ignore-checksums -y php --version ((choco search php --exact --all-versions -r | select-string -pattern $env:php | sort { [version]($_ -split '\|' | select -last 1) } -Descending | Select-Object -first 1) -replace '[php|]','') + appveyor-retry cinst --params '""/InstallDir:C:\tools\php""' --ignore-checksums -y php --version 7.2 Get-ChildItem -Path c:\tools\php cd c:\tools\php From e60892311d20888bc6dd1556f72e9bb1f49e6dde Mon Sep 17 00:00:00 2001 From: Lctrs Date: Thu, 16 Jan 2020 17:23:24 +0100 Subject: [PATCH 186/567] ExtensionManager#getExtension() can also return null --- src/Behat/Testwork/ServiceContainer/ExtensionManager.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Behat/Testwork/ServiceContainer/ExtensionManager.php b/src/Behat/Testwork/ServiceContainer/ExtensionManager.php index 7e2d955dc..45e040442 100644 --- a/src/Behat/Testwork/ServiceContainer/ExtensionManager.php +++ b/src/Behat/Testwork/ServiceContainer/ExtensionManager.php @@ -81,7 +81,7 @@ public function activateExtension($locator) * * @param string $key * - * @return Extension + * @return Extension|null */ public function getExtension($key) { From f947c16dbc2bc63cbcce51b90912da6a5c9ea95e Mon Sep 17 00:00:00 2001 From: Daniel Marynicz Date: Fri, 31 Jan 2020 11:37:43 +0100 Subject: [PATCH 187/567] fix php 7.1 deprecation for ReflectionType::__toString --- .../Transformation/ReturnTypeTransformation.php | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/Behat/Behat/Transformation/Transformation/ReturnTypeTransformation.php b/src/Behat/Behat/Transformation/Transformation/ReturnTypeTransformation.php index ecdc613a1..bf5d2eb40 100644 --- a/src/Behat/Behat/Transformation/Transformation/ReturnTypeTransformation.php +++ b/src/Behat/Behat/Transformation/Transformation/ReturnTypeTransformation.php @@ -130,6 +130,10 @@ static private function getReturnClass(ReflectionFunctionAbstract $reflection) return null; } + if (PHP_VERSION_ID >= 70100) { + return $type->getName(); + } + return (string) $type; } From 557a1ffedff0a7fe1b0990121efe5e26ee98d1ae Mon Sep 17 00:00:00 2001 From: Daniel Marynicz Date: Fri, 31 Jan 2020 14:39:36 +0100 Subject: [PATCH 188/567] fix php 7.1 deprecation for ReflectionType::__toString --- .../Transformation/Transformation/ReturnTypeTransformation.php | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/Behat/Behat/Transformation/Transformation/ReturnTypeTransformation.php b/src/Behat/Behat/Transformation/Transformation/ReturnTypeTransformation.php index bf5d2eb40..7f43e2398 100644 --- a/src/Behat/Behat/Transformation/Transformation/ReturnTypeTransformation.php +++ b/src/Behat/Behat/Transformation/Transformation/ReturnTypeTransformation.php @@ -19,6 +19,7 @@ use ReflectionFunctionAbstract; use ReflectionMethod; use ReflectionParameter; +use ReflectionNamedType; /** * By-type object transformation. @@ -130,7 +131,7 @@ static private function getReturnClass(ReflectionFunctionAbstract $reflection) return null; } - if (PHP_VERSION_ID >= 70100) { + if ($type instanceof ReflectionNamedType) { return $type->getName(); } From e652e8bde3a69170ce2337ad1b47de1d5092164f Mon Sep 17 00:00:00 2001 From: Ciaran McNulty Date: Tue, 4 Feb 2020 16:23:41 +0000 Subject: [PATCH 189/567] Update CHANGELOG.md --- CHANGELOG.md | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 8bbc0645c..955d00946 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,10 +4,17 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](http://keepachangelog.com/) and this project adheres to [Semantic Versioning](http://semver.org/). -## [Unreleased] +## [3.6.0] - 2019-02-04 * [#1256](https://github.com/Behat/Behat/pull/1256): Update dependencies to support Symfony 5.x ### Added * [#1244](https://github.com/Behat/Behat/pull/1244): Hide internal steps from stack traces in very verbose mode +### Fixed + * [#1238](https://github.com/Behat/Behat/pull/1238): Don't run Junit output if ext-dom is not present (and suggest in composer) +### Changed + * [#1171](https://github.com/Behat/Behat/pull/1171): Remove symfony/class-loader dependency + * [#1170](https://github.com/Behat/Behat/pull/1170): Switch to PSR-4 autoloading + * [#1230](https://github.com/Behat/Behat/pull/1230): PHP 7.3 support + * [#1230](https://github.com/Behat/Behat/pull/1230): Suggest ext-dom for JUnit support ## [3.5.0] - 2018-08-10 ### Added From ed416583883e2565a00973f61b58c25b98e75a19 Mon Sep 17 00:00:00 2001 From: Ciaran McNulty Date: Tue, 4 Feb 2020 16:24:29 +0000 Subject: [PATCH 190/567] Update composer.json --- composer.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/composer.json b/composer.json index 7390a5018..3dec2c213 100644 --- a/composer.json +++ b/composer.json @@ -53,7 +53,7 @@ "extra": { "branch-alias": { - "dev-master": "3.5.x-dev" + "dev-master": "3.6.x-dev" } }, From de002f40188e74fcd442c5a6480cee76a9cfc84a Mon Sep 17 00:00:00 2001 From: Ciaran McNulty Date: Tue, 4 Feb 2020 16:26:31 +0000 Subject: [PATCH 191/567] Update version number for 3.6.0 --- src/Behat/Behat/ApplicationFactory.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Behat/Behat/ApplicationFactory.php b/src/Behat/Behat/ApplicationFactory.php index d9838a1fb..316ebff0d 100644 --- a/src/Behat/Behat/ApplicationFactory.php +++ b/src/Behat/Behat/ApplicationFactory.php @@ -46,7 +46,7 @@ */ final class ApplicationFactory extends BaseFactory { - const VERSION = '3.5.0'; + const VERSION = '3.6.0'; /** * {@inheritdoc} From ea5923ec6fd830d6ae22c17b469dd3390362a49b Mon Sep 17 00:00:00 2001 From: acoulton Date: Wed, 5 Feb 2020 11:51:09 +0000 Subject: [PATCH 192/567] Fix fatal due to wrong symfony/event-dispatcher version detection The version detection added in #1256 to support symfony 5 relies only on checking for the presence of a class provided by the (separate) symfony/event-dispatcher-contracts package. However, symfony/console 4.2 also requires symfony/contracts but can coexist with older versions of symfony/event-dispatcher. Therefore for example if a project has a constraint on updating symfony/event-dispatcher (e.g. because of using Guzzle 3, which requires event-dispatcher ~2.1) composer will install: * symfony/console @ 4.2.12 (latest that doesn't advertise a conflict with newer event-dispatcher) * symfony/contracts @ 1.1.8 (latest that satisfies the console requirement) * symfony/event-dispatcher @ 2.8.52 (latest that satisfies guzzle) In this setup the presence of symfony/contracts incorrectly signals to behat that we are running symfony 5 and causes a fatal error when it loads the new implementation of TestworkEventDispatcher. The only change between the two versions is that the method signature for dispatch has changed order and types. Instead of looking at packages, it is more robust just to use reflection to detect which version of the dispatch() method is defined, and then load the extension class that matches that signature. Fixes #1277 --- .../TestworkEventDispatcher.php | 92 +++++++------------ .../TestworkEventDispatcherPhp72Trait.php | 27 ------ .../TestworkEventDispatcherSymfony5.php | 55 +++++++++++ .../TestworkEventDispatcherSymfonyLegacy.php | 56 +++++++++++ 4 files changed, 145 insertions(+), 85 deletions(-) delete mode 100644 src/Behat/Testwork/EventDispatcher/TestworkEventDispatcherPhp72Trait.php create mode 100644 src/Behat/Testwork/EventDispatcher/TestworkEventDispatcherSymfony5.php create mode 100644 src/Behat/Testwork/EventDispatcher/TestworkEventDispatcherSymfonyLegacy.php diff --git a/src/Behat/Testwork/EventDispatcher/TestworkEventDispatcher.php b/src/Behat/Testwork/EventDispatcher/TestworkEventDispatcher.php index 66afc961a..0523301d3 100644 --- a/src/Behat/Testwork/EventDispatcher/TestworkEventDispatcher.php +++ b/src/Behat/Testwork/EventDispatcher/TestworkEventDispatcher.php @@ -17,73 +17,49 @@ * * @author Konstantin Kudryashov */ +$identifyEventDispatcherClassVersion = function() { + $reflection = new \ReflectionClass(\Symfony\Component\EventDispatcher\EventDispatcher::class); + $dispatch = $reflection->getMethod('dispatch'); -if (class_exists(\Symfony\Contracts\EventDispatcher\Event::class) && PHP_VERSION_ID > 70200) { - // Assert: This is Symfony 5 and PHP >= 7.2 - include_once __DIR__.'/TestworkEventDispatcherPhp72Trait.php'; + if ($dispatch->getNumberOfParameters() === 1) { + // This is the 4.3 / 4.4 version, which has `public function dispatch($event/*, string $eventName = null*/)` and + // internally uses func_get_args to work parameters it got in what order. The legacy Testwork class can still + // extend this because its signature only adds an extra optional param. It may however produce unexpected + // results as it assumes all dispatch calls are with the legacy sequence of $eventName, $event. + return TestworkEventDispatcherSymfonyLegacy::class; + } - final class TestworkEventDispatcher extends EventDispatcher - { - use \TestworkEventDispatcherPhp72Trait; - const BEFORE_ALL_EVENTS = '*~'; - const AFTER_ALL_EVENTS = '~*'; - const DISPATCHER_VERSION = 2; + $first_param = $dispatch->getParameters()[0]; + switch ($first_param->getName()) { + case 'event': + // This is the new Symfony 5 event dispatcher interface + // public function dispatch(object $event, string $eventName = null): object + return TestworkEventDispatcherSymfony5::class; - /** - * {@inheritdoc} - */ - public function getListeners($eventName = null) - { - if (null == $eventName || self::BEFORE_ALL_EVENTS === $eventName) { - return parent::getListeners($eventName); - } + case 'eventName': + // This is the Symfony <= 4.2 version + // public function dispatch($eventName, Event $event = null) + return TestworkEventDispatcherSymfonyLegacy::class; - return array_merge( - parent::getListeners(self::BEFORE_ALL_EVENTS), - parent::getListeners($eventName), - parent::getListeners(self::AFTER_ALL_EVENTS) - ); - } + default: + throw new \UnexpectedValueException('Could not identify which version of symfony/event-dispatcher is in use, could not define a compatible TestworkEventDispatcher'); } -} else { +}; + +class_alias($identifyEventDispatcherClassVersion(), \Behat\Testwork\EventDispatcher\TestworkEventDispatcher::class); +unset($identifyEventDispatcherClassVersion); - final class TestworkEventDispatcher extends EventDispatcher - { - const BEFORE_ALL_EVENTS = '*~'; - const AFTER_ALL_EVENTS = '~*'; - const DISPATCHER_VERSION = 1; - /** - * {@inheritdoc} - */ - public function dispatch($eventName, \Symfony\Component\EventDispatcher\Event $event = null) - { - if (null === $event) { - $event = new \Symfony\Component\EventDispatcher\Event(); - } - if (method_exists($event, 'setName')) { - $event->setName($eventName); - } - /** @scrutinizer ignore-call */ - $this->doDispatch($this->getListeners($eventName), $eventName, $event); +if (false) { - return $event; - } - /** - * {@inheritdoc} - */ - public function getListeners($eventName = null) - { - if (null == $eventName || self::BEFORE_ALL_EVENTS === $eventName) { - return parent::getListeners($eventName); - } + // Empty, never-actually-defined, class definition to fool any tooling looking for a class in this file + final class TestworkEventDispatcher + { - return array_merge( - parent::getListeners(self::BEFORE_ALL_EVENTS), - parent::getListeners($eventName), - parent::getListeners(self::AFTER_ALL_EVENTS) - ); - } + // These constant definitions are required to prevent scrutinizer failing static analysis + const BEFORE_ALL_EVENTS = '*~'; + const AFTER_ALL_EVENTS = '~*'; + const DISPATCHER_VERSION = 'undefined'; } } diff --git a/src/Behat/Testwork/EventDispatcher/TestworkEventDispatcherPhp72Trait.php b/src/Behat/Testwork/EventDispatcher/TestworkEventDispatcherPhp72Trait.php deleted file mode 100644 index 1387bec4f..000000000 --- a/src/Behat/Testwork/EventDispatcher/TestworkEventDispatcherPhp72Trait.php +++ /dev/null @@ -1,27 +0,0 @@ - - */ -trait TestworkEventDispatcherPhp72Trait -{ - /** - * {@inheritdoc} - */ - public function dispatch($event, string $eventName = null): object - { - if (null === $event) { - $event = new \Symfony\Contracts\EventDispatcher\Event(); - } - if (method_exists($event, 'setName')) { - $event->setName($eventName); - } - - $this->callListeners($this->getListeners($eventName), $eventName, $event); - - return $event; - } -} \ No newline at end of file diff --git a/src/Behat/Testwork/EventDispatcher/TestworkEventDispatcherSymfony5.php b/src/Behat/Testwork/EventDispatcher/TestworkEventDispatcherSymfony5.php new file mode 100644 index 000000000..42da5ce54 --- /dev/null +++ b/src/Behat/Testwork/EventDispatcher/TestworkEventDispatcherSymfony5.php @@ -0,0 +1,55 @@ +=5.0) event dispatcher with catch-all listeners. + * + * This is magically aliased to TestworkEventDispatcher by the code in TestworkEventDispatcher.php + * if the new symfony interface is detected. + * + * @deprecated Do not reference this class directly, use TestworkEventDispatcher + */ +final class TestworkEventDispatcherSymfony5 extends EventDispatcher +{ + const BEFORE_ALL_EVENTS = '*~'; + const AFTER_ALL_EVENTS = '~*'; + const DISPATCHER_VERSION = 2; + + /** + * {@inheritdoc} + */ + public function dispatch($event, string $eventName = null): object + { + if (null === $event) { + $event = new \Symfony\Contracts\EventDispatcher\Event(); + } + if (method_exists($event, 'setName')) { + $event->setName($eventName); + } + + $this->callListeners($this->getListeners($eventName), $eventName, $event); + + return $event; + } + + /** + * {@inheritdoc} + */ + public function getListeners($eventName = null) + { + if (null == $eventName || self::BEFORE_ALL_EVENTS === $eventName) { + return parent::getListeners($eventName); + } + + return array_merge( + parent::getListeners(self::BEFORE_ALL_EVENTS), + parent::getListeners($eventName), + parent::getListeners(self::AFTER_ALL_EVENTS) + ); + } +} diff --git a/src/Behat/Testwork/EventDispatcher/TestworkEventDispatcherSymfonyLegacy.php b/src/Behat/Testwork/EventDispatcher/TestworkEventDispatcherSymfonyLegacy.php new file mode 100644 index 000000000..475fc4d00 --- /dev/null +++ b/src/Behat/Testwork/EventDispatcher/TestworkEventDispatcherSymfonyLegacy.php @@ -0,0 +1,56 @@ +setName($eventName); + } + /** @scrutinizer ignore-call */ + $this->doDispatch($this->getListeners($eventName), $eventName, $event); + + return $event; + } + + /** + * {@inheritdoc} + */ + public function getListeners($eventName = null) + { + if (null == $eventName || self::BEFORE_ALL_EVENTS === $eventName) { + return parent::getListeners($eventName); + } + + return array_merge( + parent::getListeners(self::BEFORE_ALL_EVENTS), + parent::getListeners($eventName), + parent::getListeners(self::AFTER_ALL_EVENTS) + ); + } +} From b45d6842daeeeb8311badf76ebe0f0dcdde2a9f8 Mon Sep 17 00:00:00 2001 From: Ciaran McNulty Date: Thu, 6 Feb 2020 09:55:35 +0100 Subject: [PATCH 193/567] Update for 3.6.1 release --- CHANGELOG.md | 6 +++++- src/Behat/Behat/ApplicationFactory.php | 2 +- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 955d00946..6b2b26442 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,13 +4,17 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](http://keepachangelog.com/) and this project adheres to [Semantic Versioning](http://semver.org/). +## [3.6.1] - 2019-02-06 +### Fixed + * [#1278](https://github.com/Behat/Behat/pull/1278): Fix fatal when unexpected symfony/event-dispatcher version is installed + ## [3.6.0] - 2019-02-04 - * [#1256](https://github.com/Behat/Behat/pull/1256): Update dependencies to support Symfony 5.x ### Added * [#1244](https://github.com/Behat/Behat/pull/1244): Hide internal steps from stack traces in very verbose mode ### Fixed * [#1238](https://github.com/Behat/Behat/pull/1238): Don't run Junit output if ext-dom is not present (and suggest in composer) ### Changed + * [#1256](https://github.com/Behat/Behat/pull/1256): Update dependencies to support Symfony 5.x * [#1171](https://github.com/Behat/Behat/pull/1171): Remove symfony/class-loader dependency * [#1170](https://github.com/Behat/Behat/pull/1170): Switch to PSR-4 autoloading * [#1230](https://github.com/Behat/Behat/pull/1230): PHP 7.3 support diff --git a/src/Behat/Behat/ApplicationFactory.php b/src/Behat/Behat/ApplicationFactory.php index 316ebff0d..8fba06a7e 100644 --- a/src/Behat/Behat/ApplicationFactory.php +++ b/src/Behat/Behat/ApplicationFactory.php @@ -46,7 +46,7 @@ */ final class ApplicationFactory extends BaseFactory { - const VERSION = '3.6.0'; + const VERSION = '3.6.1'; /** * {@inheritdoc} From d133f0040f9d255a098cab4775381b5893b8cd4d Mon Sep 17 00:00:00 2001 From: Sam Burns Date: Wed, 15 Jan 2020 23:19:13 +0000 Subject: [PATCH 194/567] Fix bug with build command introduced in 0353b4b85ca9182643c18648980fccccb761e9fa. Exposes issue with PHP5.4 tests running in PHP7.4, etc. --- .travis.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index fafcca5b0..c58fe9793 100644 --- a/.travis.yml +++ b/.travis.yml @@ -37,7 +37,7 @@ before_script: - if [ "$DEPENDENCIES" != "low" ]; then composer update; fi; - if [ "$DEPENDENCIES" = "low" ]; then composer update --prefer-lowest; fi; - export PATH=./bin:$PATH - - echo " php_version_tags.php + - echo " php_version_tags.php script: - ./vendor/bin/phpunit From 13b91d8e0bb34622bb5e2b40785a5027d2d9b7a8 Mon Sep 17 00:00:00 2001 From: Sam Burns Date: Wed, 15 Jan 2020 23:30:45 +0000 Subject: [PATCH 195/567] Make tests use correct PHP major version --- .travis.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index c58fe9793..8804bb3c7 100644 --- a/.travis.yml +++ b/.travis.yml @@ -37,7 +37,7 @@ before_script: - if [ "$DEPENDENCIES" != "low" ]; then composer update; fi; - if [ "$DEPENDENCIES" = "low" ]; then composer update --prefer-lowest; fi; - export PATH=./bin:$PATH - - echo " php_version_tags.php + - echo " php_version_tags.php script: - ./vendor/bin/phpunit From 3aeb45e3497b17cc28c7adb56c814a8e931c7e5f Mon Sep 17 00:00:00 2001 From: Sam Burns Date: Wed, 15 Jan 2020 23:41:36 +0000 Subject: [PATCH 196/567] Simplify build commands, and approach to language version dependent tests --- .gitignore | 1 - .travis.yml | 3 +-- appveyor.yml | 2 +- features/definitions_transformations.feature | 4 ++-- features/extensions.feature | 2 +- features/junit_format.feature | 2 +- features/traits.feature | 3 +-- 7 files changed, 7 insertions(+), 10 deletions(-) diff --git a/.gitignore b/.gitignore index 2c4468f44..fce40dae4 100644 --- a/.gitignore +++ b/.gitignore @@ -1,7 +1,6 @@ *.tgz *.phar *.phar.asc -php_version_tags.php behat.yml vendor composer.lock diff --git a/.travis.yml b/.travis.yml index 8804bb3c7..d547d2e74 100644 --- a/.travis.yml +++ b/.travis.yml @@ -37,11 +37,10 @@ before_script: - if [ "$DEPENDENCIES" != "low" ]; then composer update; fi; - if [ "$DEPENDENCIES" = "low" ]; then composer update --prefer-lowest; fi; - export PATH=./bin:$PATH - - echo " php_version_tags.php script: - ./vendor/bin/phpunit - - behat -fprogress --strict --tags '~@php-version,'`php php_version_tags.php` + - behat -fprogress --strict --tags '~@php-version,@php'`php -r 'echo PHP_MAJOR_VERSION;'` before_deploy: - curl -LSs https://box-project.github.io/box2/installer.php | php diff --git a/appveyor.yml b/appveyor.yml index 5095fe212..3871fe757 100644 --- a/appveyor.yml +++ b/appveyor.yml @@ -57,5 +57,5 @@ install: test_script: - cd c:\projects\behat - - php bin\behat --tags="~@php-version,@php53,@php5.2,@php5.1,@php5.0" --format=progress + - php bin\behat --tags="~@php-version,@php7" --format=progress - php vendor\phpunit\phpunit\phpunit --testdox diff --git a/features/definitions_transformations.feature b/features/definitions_transformations.feature index 3063d6a13..d24e033ee 100644 --- a/features/definitions_transformations.feature +++ b/features/definitions_transformations.feature @@ -420,7 +420,7 @@ Feature: Step Arguments Transformations 8 steps (8 passed) """ - @php-version @php7.0 + @php-version @php7 Scenario: By-type object transformations Given a file named "features/my.feature" with: """ @@ -488,7 +488,7 @@ Feature: Step Arguments Transformations 4 steps (4 passed) """ - @php-version @php7.0 + @php-version @php7 Scenario: By-type and by-name object transformations Given a file named "features/my.feature" with: """ diff --git a/features/extensions.feature b/features/extensions.feature index eefaa76a7..ab155f4c9 100644 --- a/features/extensions.feature +++ b/features/extensions.feature @@ -122,7 +122,7 @@ Feature: Extensions `inexistent_extension` extension file or class could not be located. """ - @php-version @php7.0 + @php-version @php7 Scenario: Exception handlers extension Given a file named "behat.yml" with: """ diff --git a/features/junit_format.feature b/features/junit_format.feature index 24997aa2b..aef765ba8 100644 --- a/features/junit_format.feature +++ b/features/junit_format.feature @@ -526,7 +526,7 @@ """ And the file "junit/default.xml" should be a valid document according to "junit.xsd" - @php-version @php5.3 @php5.4 + @php-version @php5 Scenario: Aborting due to PHP error Given a file named "features/bootstrap/FeatureContext.php" with: """ diff --git a/features/traits.feature b/features/traits.feature index dc2c6a519..b4a5f6913 100644 --- a/features/traits.feature +++ b/features/traits.feature @@ -1,5 +1,4 @@ -@php-version @php5.4 -Feature: Support php 5.4 traits +Feature: Support traits In order to have much cleaner horizontal reusability As a context developer I need to be able to use definition traits in my context From 0b055340efa52cd129984101936f3a52b1a6fd35 Mon Sep 17 00:00:00 2001 From: Christopher Hoult Date: Thu, 13 Feb 2020 12:12:03 +0000 Subject: [PATCH 197/567] Updated the year on Changelog dates for v3.6.0 and v3.6.1 to match release dates --- CHANGELOG.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 6b2b26442..3fef3b386 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,11 +4,11 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](http://keepachangelog.com/) and this project adheres to [Semantic Versioning](http://semver.org/). -## [3.6.1] - 2019-02-06 +## [3.6.1] - 2020-02-06 ### Fixed * [#1278](https://github.com/Behat/Behat/pull/1278): Fix fatal when unexpected symfony/event-dispatcher version is installed -## [3.6.0] - 2019-02-04 +## [3.6.0] - 2020-02-04 ### Added * [#1244](https://github.com/Behat/Behat/pull/1244): Hide internal steps from stack traces in very verbose mode ### Fixed From 3af455b72db77680603d64bf830509ab4d543d72 Mon Sep 17 00:00:00 2001 From: Sergey Rabochiy Date: Tue, 11 Feb 2020 18:50:39 +0700 Subject: [PATCH 198/567] Make container-interop/container-interop optional dependency --- .travis.yml | 5 ++- composer.json | 10 +++--- features/helper_containers.feature | 35 +++++++++++++++++++ .../HelperContainer/ArgumentAutowirer.php | 8 ++--- .../BuiltInServiceContainer.php | 1 - .../HelperContainer/ContainerInterface.php | 27 ++++++++++++++ .../Exception/ContainerException.php | 27 ++++++++++++++ .../Exception/HelperContainerException.php | 1 - .../Exception/NotFoundException.php | 27 ++++++++++++++ .../Exception/ServiceNotFoundException.php | 1 - 10 files changed, 129 insertions(+), 13 deletions(-) create mode 100644 src/Behat/Behat/HelperContainer/ContainerInterface.php create mode 100644 src/Behat/Behat/HelperContainer/Exception/ContainerException.php create mode 100644 src/Behat/Behat/HelperContainer/Exception/NotFoundException.php diff --git a/.travis.yml b/.travis.yml index d547d2e74..abdf63a18 100644 --- a/.travis.yml +++ b/.travis.yml @@ -16,6 +16,8 @@ matrix: include: - php: 5.6 env: DEPENDENCIES='low' + - php: 5.6 + env: SKIP_INTEROP='~@interop&&' - php: 5.6 env: SYMFONY_VERSION='2.7.*' - php: 5.6 @@ -34,13 +36,14 @@ before_install: before_script: - if [ "$SYMFONY_VERSION" != "" ]; then composer require --no-update "symfony/symfony:${SYMFONY_VERSION}"; fi; + - if [ "$SKIP_INTEROP" != "" ]; then composer remove --dev --no-update container-interop/container-interop; fi; - if [ "$DEPENDENCIES" != "low" ]; then composer update; fi; - if [ "$DEPENDENCIES" = "low" ]; then composer update --prefer-lowest; fi; - export PATH=./bin:$PATH script: - ./vendor/bin/phpunit - - behat -fprogress --strict --tags '~@php-version,@php'`php -r 'echo PHP_MAJOR_VERSION;'` + - behat -fprogress --strict --tags "$SKIP_INTEROP"'~@php-version,@php'`php -r 'echo PHP_MAJOR_VERSION;'` before_deploy: - curl -LSs https://box-project.github.io/box2/installer.php | php diff --git a/composer.json b/composer.json index 3dec2c213..2719819a0 100644 --- a/composer.json +++ b/composer.json @@ -24,14 +24,14 @@ "symfony/event-dispatcher": "^2.7.51 || ^3.0 || ^4.0 || ^5.0", "symfony/translation": "^2.7.51 || ^3.0 || ^4.0 || ^5.0", "symfony/yaml": "^2.7.51 || ^3.0 || ^4.0 || ^5.0", - "psr/container": "^1.0", - "container-interop/container-interop": "^1.2" + "psr/container": "^1.0" }, "require-dev": { "symfony/process": "~2.5 || ^3.0 || ^4.0 || ^5.0", "phpunit/phpunit": "^4.8.36 || ^6.3", - "herrera-io/box": "~1.6.1" + "herrera-io/box": "~1.6.1", + "container-interop/container-interop": "^1.2" }, "suggest": { @@ -44,13 +44,13 @@ "Behat\\Testwork\\": "src/Behat/Testwork/" } }, - + "autoload-dev": { "psr-4": { "Behat\\Tests\\": "tests/" } }, - + "extra": { "branch-alias": { "dev-master": "3.6.x-dev" diff --git a/features/helper_containers.feature b/features/helper_containers.feature index 4ef1bddb6..e24d5f0eb 100644 --- a/features/helper_containers.feature +++ b/features/helper_containers.feature @@ -177,6 +177,7 @@ Feature: Per-suite helper containers When I run "behat --no-colors -f progress features/container.feature" Then it should pass + @interop Scenario: Interop container Given a file named "behat.yml" with: """ @@ -211,6 +212,40 @@ Feature: Per-suite helper containers When I run "behat --no-colors -f progress features/container.feature" Then it should pass + Scenario: PSR container + Given a file named "behat.yml" with: + """ + default: + suites: + default: + contexts: + - FirstContext: + - "@shared_service" + - SecondContext: + - "@shared_service" + + services: MyContainer + """ + And a file named "features/bootstrap/MyContainer.php" with: + """ + service) ? $this->service : $this->service = new SharedService(); + } + } + """ + When I run "behat --no-colors -f progress features/container.feature" + Then it should pass + Scenario: Simplest built-in container configuration Given a file named "behat.yml" with: """ diff --git a/src/Behat/Behat/HelperContainer/ArgumentAutowirer.php b/src/Behat/Behat/HelperContainer/ArgumentAutowirer.php index 8771eabdc..8fd2712a0 100644 --- a/src/Behat/Behat/HelperContainer/ArgumentAutowirer.php +++ b/src/Behat/Behat/HelperContainer/ArgumentAutowirer.php @@ -11,7 +11,7 @@ namespace Behat\Behat\HelperContainer; use Psr\Container\ContainerExceptionInterface; -use Psr\Container\ContainerInterface; +use Psr\Container\ContainerInterface as PsrContainerInterface; use ReflectionFunctionAbstract; use ReflectionParameter; use ReflectionException; @@ -24,16 +24,16 @@ final class ArgumentAutowirer { /** - * @var ContainerInterface + * @var PsrContainerInterface */ private $container; /** * Initialises wirer. * - * @param ContainerInterface $container + * @param PsrContainerInterface $container */ - public function __construct(ContainerInterface $container) + public function __construct(PsrContainerInterface $container) { $this->container = $container; } diff --git a/src/Behat/Behat/HelperContainer/BuiltInServiceContainer.php b/src/Behat/Behat/HelperContainer/BuiltInServiceContainer.php index 624bd28e5..fc474436b 100644 --- a/src/Behat/Behat/HelperContainer/BuiltInServiceContainer.php +++ b/src/Behat/Behat/HelperContainer/BuiltInServiceContainer.php @@ -12,7 +12,6 @@ use Behat\Behat\HelperContainer\Exception\ServiceNotFoundException; use Behat\Behat\HelperContainer\Exception\WrongServicesConfigurationException; -use Interop\Container\ContainerInterface; use ReflectionClass; use ReflectionMethod; diff --git a/src/Behat/Behat/HelperContainer/ContainerInterface.php b/src/Behat/Behat/HelperContainer/ContainerInterface.php new file mode 100644 index 000000000..75fb43fa8 --- /dev/null +++ b/src/Behat/Behat/HelperContainer/ContainerInterface.php @@ -0,0 +1,27 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Behat\Behat\HelperContainer; + +class_alias( + interface_exists('Interop\\Container\\ContainerInterface') + ? 'Interop\\Container\\ContainerInterface' + : 'Psr\\Container\\ContainerInterface', + 'Behat\\Behat\\HelperContainer\\ContainerInterface' +); + +if (false) { + /** + * @internal + */ + interface ContainerInterface + { + } +} diff --git a/src/Behat/Behat/HelperContainer/Exception/ContainerException.php b/src/Behat/Behat/HelperContainer/Exception/ContainerException.php new file mode 100644 index 000000000..fd5543ad0 --- /dev/null +++ b/src/Behat/Behat/HelperContainer/Exception/ContainerException.php @@ -0,0 +1,27 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Behat\Behat\HelperContainer\Exception; + +class_alias( + interface_exists('Interop\\Container\\Exception\\ContainerException') + ? 'Interop\\Container\\Exception\\ContainerException' + : 'Psr\\Container\\ContainerExceptionInterface', + 'Behat\\Behat\\HelperContainer\\Exception\\ContainerException' +); + +if (false) { + /** + * @internal + */ + interface ContainerException + { + } +} diff --git a/src/Behat/Behat/HelperContainer/Exception/HelperContainerException.php b/src/Behat/Behat/HelperContainer/Exception/HelperContainerException.php index 04ab35f96..d61919225 100644 --- a/src/Behat/Behat/HelperContainer/Exception/HelperContainerException.php +++ b/src/Behat/Behat/HelperContainer/Exception/HelperContainerException.php @@ -11,7 +11,6 @@ namespace Behat\Behat\HelperContainer\Exception; use Behat\Testwork\Environment\Exception\EnvironmentException; -use Interop\Container\Exception\ContainerException; /** * All HelperContainer exceptions implement this interface. diff --git a/src/Behat/Behat/HelperContainer/Exception/NotFoundException.php b/src/Behat/Behat/HelperContainer/Exception/NotFoundException.php new file mode 100644 index 000000000..739e5181f --- /dev/null +++ b/src/Behat/Behat/HelperContainer/Exception/NotFoundException.php @@ -0,0 +1,27 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Behat\Behat\HelperContainer\Exception; + +class_alias( + interface_exists('Interop\\Container\\Exception\\NotFoundException') + ? 'Interop\\Container\\Exception\\NotFoundException' + : 'Psr\\Container\\NotFoundExceptionInterface', + 'Behat\\Behat\\HelperContainer\\Exception\\NotFoundException' +); + +if (false) { + /** + * @internal + */ + interface NotFoundException + { + } +} diff --git a/src/Behat/Behat/HelperContainer/Exception/ServiceNotFoundException.php b/src/Behat/Behat/HelperContainer/Exception/ServiceNotFoundException.php index 02bd601b7..a82b63ed0 100644 --- a/src/Behat/Behat/HelperContainer/Exception/ServiceNotFoundException.php +++ b/src/Behat/Behat/HelperContainer/Exception/ServiceNotFoundException.php @@ -10,7 +10,6 @@ namespace Behat\Behat\HelperContainer\Exception; -use Interop\Container\Exception\NotFoundException; use InvalidArgumentException; /** From 8a9585a3547bc612c05c5feb7b39fb4610a47f36 Mon Sep 17 00:00:00 2001 From: Doug Wright Date: Sat, 15 Feb 2020 21:08:24 +0000 Subject: [PATCH 199/567] Add missing supported PHP versions to CI --- .travis.yml | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/.travis.yml b/.travis.yml index abdf63a18..2cb9392d0 100644 --- a/.travis.yml +++ b/.travis.yml @@ -14,6 +14,15 @@ branches: matrix: include: + - php: 5.3 + dist: precise + env: DEPENDENCIES='low' + - php: 5.4 + dist: trusty + env: DEPENDENCIES='low' + - php: 5.5 + dist: trusty + env: DEPENDENCIES='low' - php: 5.6 env: DEPENDENCIES='low' - php: 5.6 From 72da5306cd7eff7fa7141d8a8eba3c0b9a309c6e Mon Sep 17 00:00:00 2001 From: Doug Wright Date: Sat, 15 Feb 2020 21:07:58 +0000 Subject: [PATCH 200/567] Remove PHP5.5isms --- .../Definition/Translator/TranslatorInterface.php | 4 ++-- .../EventDispatcher/TestworkEventDispatcher.php | 10 +++++----- .../Configuration/ConfigurationTree.php | 2 +- .../Definition/Pattern/PatternTransformerTest.php | 8 ++++---- 4 files changed, 12 insertions(+), 12 deletions(-) diff --git a/src/Behat/Behat/Definition/Translator/TranslatorInterface.php b/src/Behat/Behat/Definition/Translator/TranslatorInterface.php index 9ad91e381..75418211a 100644 --- a/src/Behat/Behat/Definition/Translator/TranslatorInterface.php +++ b/src/Behat/Behat/Definition/Translator/TranslatorInterface.php @@ -2,11 +2,11 @@ namespace Behat\Behat\Definition\Translator; -if (interface_exists(\Symfony\Contracts\Translation\TranslatorInterface::class)) { +if (interface_exists('\Symfony\Contracts\Translation\TranslatorInterface')) { interface TranslatorInterface extends \Symfony\Contracts\Translation\TranslatorInterface { } -} elseif (interface_exists(\Symfony\Component\Translation\TranslatorInterface::class)) { +} elseif (interface_exists('\Symfony\Component\Translation\TranslatorInterface')) { interface TranslatorInterface extends \Symfony\Component\Translation\TranslatorInterface { } diff --git a/src/Behat/Testwork/EventDispatcher/TestworkEventDispatcher.php b/src/Behat/Testwork/EventDispatcher/TestworkEventDispatcher.php index 0523301d3..2020a60a8 100644 --- a/src/Behat/Testwork/EventDispatcher/TestworkEventDispatcher.php +++ b/src/Behat/Testwork/EventDispatcher/TestworkEventDispatcher.php @@ -18,7 +18,7 @@ * @author Konstantin Kudryashov */ $identifyEventDispatcherClassVersion = function() { - $reflection = new \ReflectionClass(\Symfony\Component\EventDispatcher\EventDispatcher::class); + $reflection = new \ReflectionClass('\Symfony\Component\EventDispatcher\EventDispatcher'); $dispatch = $reflection->getMethod('dispatch'); if ($dispatch->getNumberOfParameters() === 1) { @@ -26,7 +26,7 @@ // internally uses func_get_args to work parameters it got in what order. The legacy Testwork class can still // extend this because its signature only adds an extra optional param. It may however produce unexpected // results as it assumes all dispatch calls are with the legacy sequence of $eventName, $event. - return TestworkEventDispatcherSymfonyLegacy::class; + return 'Behat\Testwork\EventDispatcher\TestworkEventDispatcherSymfonyLegacy'; } $first_param = $dispatch->getParameters()[0]; @@ -34,19 +34,19 @@ case 'event': // This is the new Symfony 5 event dispatcher interface // public function dispatch(object $event, string $eventName = null): object - return TestworkEventDispatcherSymfony5::class; + return 'Behat\Testwork\EventDispatcher\TestworkEventDispatcherSymfony5'; case 'eventName': // This is the Symfony <= 4.2 version // public function dispatch($eventName, Event $event = null) - return TestworkEventDispatcherSymfonyLegacy::class; + return 'Behat\Testwork\EventDispatcher\TestworkEventDispatcherSymfonyLegacy'; default: throw new \UnexpectedValueException('Could not identify which version of symfony/event-dispatcher is in use, could not define a compatible TestworkEventDispatcher'); } }; -class_alias($identifyEventDispatcherClassVersion(), \Behat\Testwork\EventDispatcher\TestworkEventDispatcher::class); +class_alias($identifyEventDispatcherClassVersion(), '\Behat\Testwork\EventDispatcher\TestworkEventDispatcher'); unset($identifyEventDispatcherClassVersion); diff --git a/src/Behat/Testwork/ServiceContainer/Configuration/ConfigurationTree.php b/src/Behat/Testwork/ServiceContainer/Configuration/ConfigurationTree.php index 7fe010956..3c3f317ec 100644 --- a/src/Behat/Testwork/ServiceContainer/Configuration/ConfigurationTree.php +++ b/src/Behat/Testwork/ServiceContainer/Configuration/ConfigurationTree.php @@ -31,7 +31,7 @@ final class ConfigurationTree */ public function getConfigTree(array $extensions) { - if (method_exists(TreeBuilder::class, 'getRootNode')) { + if (method_exists('Symfony\Component\Config\Definition\Builder\TreeBuilder', 'getRootNode')) { $treeBuilder = new TreeBuilder('testwork'); /** @var ArrayNodeDefinition $rootNode */ $rootNode = $treeBuilder->getRootNode(); diff --git a/tests/Behat/Tests/Definition/Pattern/PatternTransformerTest.php b/tests/Behat/Tests/Definition/Pattern/PatternTransformerTest.php index 44aca4825..4a2c45462 100644 --- a/tests/Behat/Tests/Definition/Pattern/PatternTransformerTest.php +++ b/tests/Behat/Tests/Definition/Pattern/PatternTransformerTest.php @@ -14,7 +14,7 @@ class PatternTransformerTest extends TestCase { public function testTransformPatternToRegexCache() { - $observer = $this->prophesize(PatternPolicy::class); + $observer = $this->prophesize('Behat\Behat\Definition\Pattern\Policy\PatternPolicy'); // first pattern $observer->supportsPattern('hello world')->willReturn(true); $observer->transformPatternToRegex('hello world') @@ -42,14 +42,14 @@ public function testTransformPatternToRegexCache() public function testTransformPatternToRegexCacheAndRegisterNewPolicy() { // first pattern - $policy1Prophecy = $this->prophesize(PatternPolicy::class); + $policy1Prophecy = $this->prophesize('Behat\Behat\Definition\Pattern\Policy\PatternPolicy'); $policy1Prophecy->supportsPattern('hello world')->willReturn(true); $policy1Prophecy->transformPatternToRegex('hello world') ->shouldBeCalledTimes(2) ->willReturn('/hello world/'); // second pattern - $policy2Prophecy = $this->prophesize(PatternPolicy::class); + $policy2Prophecy = $this->prophesize('Behat\Behat\Definition\Pattern\Policy\PatternPolicy'); $policy1Prophecy->supportsPattern()->shouldNotBeCalled(); $policy1Prophecy->transformPatternToRegex()->shouldNotBeCalled(); @@ -73,7 +73,7 @@ public function testTransformPatternToRegexCacheAndRegisterNewPolicy() public function testTransformPatternToRegexNoMatch() { // first pattern - $policy1Prophecy = $this->prophesize(PatternPolicy::class); + $policy1Prophecy = $this->prophesize('Behat\Behat\Definition\Pattern\Policy\PatternPolicy'); $policy1Prophecy->supportsPattern('hello world')->willReturn(false); $policy1Prophecy->transformPatternToRegex('hello world') ->shouldNotBeCalled(); From dfba74516d64f3da6457710465da84560e816de8 Mon Sep 17 00:00:00 2001 From: Doug Wright Date: Sat, 15 Feb 2020 21:47:17 +0000 Subject: [PATCH 201/567] Remove PHP5.4ism --- features/bootstrap/FeatureContext.php | 2 +- src/Behat/Testwork/EventDispatcher/TestworkEventDispatcher.php | 3 ++- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/features/bootstrap/FeatureContext.php b/features/bootstrap/FeatureContext.php index 4aaf6f795..bbf45921d 100644 --- a/features/bootstrap/FeatureContext.php +++ b/features/bootstrap/FeatureContext.php @@ -41,7 +41,7 @@ class FeatureContext implements Context /** * @var array */ - private $env = []; + private $env = array(); /** * @var string */ diff --git a/src/Behat/Testwork/EventDispatcher/TestworkEventDispatcher.php b/src/Behat/Testwork/EventDispatcher/TestworkEventDispatcher.php index 2020a60a8..8bd215c88 100644 --- a/src/Behat/Testwork/EventDispatcher/TestworkEventDispatcher.php +++ b/src/Behat/Testwork/EventDispatcher/TestworkEventDispatcher.php @@ -29,7 +29,8 @@ return 'Behat\Testwork\EventDispatcher\TestworkEventDispatcherSymfonyLegacy'; } - $first_param = $dispatch->getParameters()[0]; + $params = $dispatch->getParameters(); + $first_param = reset($params); switch ($first_param->getName()) { case 'event': // This is the new Symfony 5 event dispatcher interface From ec83ffa08aa874b0161e789b1f25176c169351e4 Mon Sep 17 00:00:00 2001 From: Doug Wright Date: Mon, 17 Feb 2020 10:25:01 +0000 Subject: [PATCH 202/567] Remove leading \ from FQCN --- src/Behat/Behat/Definition/Translator/TranslatorInterface.php | 4 ++-- .../Testwork/EventDispatcher/TestworkEventDispatcher.php | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/Behat/Behat/Definition/Translator/TranslatorInterface.php b/src/Behat/Behat/Definition/Translator/TranslatorInterface.php index 75418211a..d2af2b99c 100644 --- a/src/Behat/Behat/Definition/Translator/TranslatorInterface.php +++ b/src/Behat/Behat/Definition/Translator/TranslatorInterface.php @@ -2,11 +2,11 @@ namespace Behat\Behat\Definition\Translator; -if (interface_exists('\Symfony\Contracts\Translation\TranslatorInterface')) { +if (interface_exists('Symfony\Contracts\Translation\TranslatorInterface')) { interface TranslatorInterface extends \Symfony\Contracts\Translation\TranslatorInterface { } -} elseif (interface_exists('\Symfony\Component\Translation\TranslatorInterface')) { +} elseif (interface_exists('Symfony\Component\Translation\TranslatorInterface')) { interface TranslatorInterface extends \Symfony\Component\Translation\TranslatorInterface { } diff --git a/src/Behat/Testwork/EventDispatcher/TestworkEventDispatcher.php b/src/Behat/Testwork/EventDispatcher/TestworkEventDispatcher.php index 8bd215c88..8c1e928a0 100644 --- a/src/Behat/Testwork/EventDispatcher/TestworkEventDispatcher.php +++ b/src/Behat/Testwork/EventDispatcher/TestworkEventDispatcher.php @@ -18,7 +18,7 @@ * @author Konstantin Kudryashov */ $identifyEventDispatcherClassVersion = function() { - $reflection = new \ReflectionClass('\Symfony\Component\EventDispatcher\EventDispatcher'); + $reflection = new \ReflectionClass('Symfony\Component\EventDispatcher\EventDispatcher'); $dispatch = $reflection->getMethod('dispatch'); if ($dispatch->getNumberOfParameters() === 1) { @@ -47,7 +47,7 @@ } }; -class_alias($identifyEventDispatcherClassVersion(), '\Behat\Testwork\EventDispatcher\TestworkEventDispatcher'); +class_alias($identifyEventDispatcherClassVersion(), 'Behat\Testwork\EventDispatcher\TestworkEventDispatcher'); unset($identifyEventDispatcherClassVersion); From b8758e9415692bd78a7e05215088b6a90bd99205 Mon Sep 17 00:00:00 2001 From: Doug Wright Date: Mon, 17 Feb 2020 11:20:17 +0000 Subject: [PATCH 203/567] Don't force DEPENDENCIES='low' on old PHP --- .travis.yml | 3 --- 1 file changed, 3 deletions(-) diff --git a/.travis.yml b/.travis.yml index 2cb9392d0..11a34c19f 100644 --- a/.travis.yml +++ b/.travis.yml @@ -16,13 +16,10 @@ matrix: include: - php: 5.3 dist: precise - env: DEPENDENCIES='low' - php: 5.4 dist: trusty - env: DEPENDENCIES='low' - php: 5.5 dist: trusty - env: DEPENDENCIES='low' - php: 5.6 env: DEPENDENCIES='low' - php: 5.6 From aac74e2e759a611b0cee32fe7d0068408207173d Mon Sep 17 00:00:00 2001 From: Sam Burns Date: Mon, 24 Feb 2020 10:53:24 +0000 Subject: [PATCH 204/567] Allow some tests to be PHP 5.4+, as we apparently still support PHP 5.3 to some extent --- .travis.yml | 11 ++++++----- features/junit_format.feature | 2 +- features/traits.feature | 1 + 3 files changed, 8 insertions(+), 6 deletions(-) diff --git a/.travis.yml b/.travis.yml index 11a34c19f..774ad4f9e 100644 --- a/.travis.yml +++ b/.travis.yml @@ -8,20 +8,20 @@ cache: directories: - $HOME/.composer/cache -branches: - only: - - master - matrix: include: - php: 5.3 dist: precise + env: PHP_VERSION=53 - php: 5.4 dist: trusty + env: PHP_VERSION=54+ - php: 5.5 dist: trusty + env: PHP_VERSION=54+ - php: 5.6 env: DEPENDENCIES='low' + env: PHP_VERSION=54+ - php: 5.6 env: SKIP_INTEROP='~@interop&&' - php: 5.6 @@ -45,11 +45,12 @@ before_script: - if [ "$SKIP_INTEROP" != "" ]; then composer remove --dev --no-update container-interop/container-interop; fi; - if [ "$DEPENDENCIES" != "low" ]; then composer update; fi; - if [ "$DEPENDENCIES" = "low" ]; then composer update --prefer-lowest; fi; + - if [ ! "$PHP_VERSION" ]; then export PHP_VERSION=`php -r 'echo PHP_MAJOR_VERSION;'`; fi; - export PATH=./bin:$PATH script: - ./vendor/bin/phpunit - - behat -fprogress --strict --tags "$SKIP_INTEROP"'~@php-version,@php'`php -r 'echo PHP_MAJOR_VERSION;'` + - behat -fprogress --strict --tags '~@php-version,@php'$PHP_VERSION before_deploy: - curl -LSs https://box-project.github.io/box2/installer.php | php diff --git a/features/junit_format.feature b/features/junit_format.feature index aef765ba8..5b2e7b7b4 100644 --- a/features/junit_format.feature +++ b/features/junit_format.feature @@ -526,7 +526,7 @@ """ And the file "junit/default.xml" should be a valid document according to "junit.xsd" - @php-version @php5 + @php-version @php53 @php54+ Scenario: Aborting due to PHP error Given a file named "features/bootstrap/FeatureContext.php" with: """ diff --git a/features/traits.feature b/features/traits.feature index b4a5f6913..7a8a17092 100644 --- a/features/traits.feature +++ b/features/traits.feature @@ -86,6 +86,7 @@ Feature: Support traits | 2 | 2 | 3 | """ + @php-version @php54+ @php7 Scenario: Run feature with failing scenarios When I run "behat --no-colors -f progress" Then it should pass with: From b36ab42452baf87e39bf6ed51a274db6dffe4672 Mon Sep 17 00:00:00 2001 From: Kamil Kokot Date: Tue, 2 Jun 2020 17:31:44 +0200 Subject: [PATCH 205/567] Skip interop correctly on Travis --- .travis.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index 774ad4f9e..fecd1acd7 100644 --- a/.travis.yml +++ b/.travis.yml @@ -50,7 +50,7 @@ before_script: script: - ./vendor/bin/phpunit - - behat -fprogress --strict --tags '~@php-version,@php'$PHP_VERSION + - behat -fprogress --strict --tags "${SKIP_INTEROP}~@php-version,@php${PHP_VERSION}" before_deploy: - curl -LSs https://box-project.github.io/box2/installer.php | php From a7735e6d1e2e752ca62d22615061e4f199fa8f7d Mon Sep 17 00:00:00 2001 From: Witold Wasiczko Date: Tue, 24 Sep 2019 11:00:50 +0200 Subject: [PATCH 206/567] Support for php 7.4 --- .travis.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index fecd1acd7..a9f833940 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,6 +1,6 @@ language: php -php: [5.6, 7.0, 7.1, 7.2, 7.3] +php: [5.6, 7.0, 7.1, 7.2, 7.3, 7.4snapshot] sudo: false From d3c1ad916d48217e22d9587005e63a17bf5d94cd Mon Sep 17 00:00:00 2001 From: Witold Wasiczko Date: Wed, 15 Jan 2020 09:55:37 +0100 Subject: [PATCH 207/567] Use stable php 7.4 --- .travis.yml | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index a9f833940..6c97dbcea 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,6 +1,6 @@ language: php -php: [5.6, 7.0, 7.1, 7.2, 7.3, 7.4snapshot] +php: [5.6, 7.0, 7.1, 7.2, 7.3, 7.4] sudo: false @@ -36,6 +36,12 @@ matrix: env: SYMFONY_VERSION='^4.3' - php: 7.3 env: SYMFONY_VERSION='^5.0' + - php: 7.4 + env: SYMFONY_VERSION='^3.4' + - php: 7.4 + env: SYMFONY_VERSION='^4.3' + - php: 7.4 + env: SYMFONY_VERSION='^5.0' before_install: - phpenv config-rm xdebug.ini || echo "XDebug is not enabled" From bbf87da10b0536e0c590a5a215c7d1d26d66ecdd Mon Sep 17 00:00:00 2001 From: Witold Wasiczko Date: Wed, 15 Jan 2020 09:57:43 +0100 Subject: [PATCH 208/567] Remove test php 7.4 against all symfony lts --- .travis.yml | 6 ------ 1 file changed, 6 deletions(-) diff --git a/.travis.yml b/.travis.yml index 6c97dbcea..6684ee606 100644 --- a/.travis.yml +++ b/.travis.yml @@ -36,12 +36,6 @@ matrix: env: SYMFONY_VERSION='^4.3' - php: 7.3 env: SYMFONY_VERSION='^5.0' - - php: 7.4 - env: SYMFONY_VERSION='^3.4' - - php: 7.4 - env: SYMFONY_VERSION='^4.3' - - php: 7.4 - env: SYMFONY_VERSION='^5.0' before_install: - phpenv config-rm xdebug.ini || echo "XDebug is not enabled" From c57fdb2ad6b8989a73feabfdf409fcf7ba110d61 Mon Sep 17 00:00:00 2001 From: Witold Wasiczko Date: Wed, 15 Jan 2020 10:07:14 +0100 Subject: [PATCH 209/567] Restrict phpunit to new version --- composer.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/composer.json b/composer.json index 2719819a0..a61866af4 100644 --- a/composer.json +++ b/composer.json @@ -29,7 +29,7 @@ "require-dev": { "symfony/process": "~2.5 || ^3.0 || ^4.0 || ^5.0", - "phpunit/phpunit": "^4.8.36 || ^6.3", + "phpunit/phpunit": "^4.8.36 || ^6.5.14 || ^7.5.20", "herrera-io/box": "~1.6.1", "container-interop/container-interop": "^1.2" }, From d957267bf1568076bacb80a14364ec8ea6bee00a Mon Sep 17 00:00:00 2001 From: Kamil Kokot Date: Wed, 3 Jun 2020 13:58:11 +0200 Subject: [PATCH 210/567] Prepare v3.7.0 release --- CHANGELOG.md | 19 ++++++++++++++++++- src/Behat/Behat/ApplicationFactory.php | 2 +- 2 files changed, 19 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 3fef3b386..df67f3c3d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,8 +4,22 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](http://keepachangelog.com/) and this project adheres to [Semantic Versioning](http://semver.org/). +## [3.7.0] - 2020-06-03 + +### Added + * [#1236](https://github.com/Behat/Behat/pull/1236): Add support for php 7.4 ([@snapshotpl](https://github.com/snapshotpl)) + +### Fixed + * [#1270](https://github.com/Behat/Behat/pull/1270): Fix issues with PHP version handling in build ([@Sam-Burns](https://github.com/Sam-Burns)) + * [#1282](https://github.com/Behat/Behat/pull/1282): Updated the year on Changelog dates ([@choult](https://github.com/choult)) + * [#1284](https://github.com/Behat/Behat/pull/1284): Restore PHP 5.3/5.4 compat ([@dvdoug](https://github.com/dvdoug), [@Sam-Burns](https://github.com/Sam-Burns), [@pamil](https://github.com/pamil)) + +### Changed + * [#1281](https://github.com/Behat/Behat/pull/1281): Make container-interop/container-interop optional dependency ([@upyx](https://github.com/upyx)) + ## [3.6.1] - 2020-02-06 ### Fixed + * [#1275](https://github.com/Behat/Behat/pull/1275): fix php 7.1 deprecation for ReflectionType::__toString * [#1278](https://github.com/Behat/Behat/pull/1278): Fix fatal when unexpected symfony/event-dispatcher version is installed ## [3.6.0] - 2020-02-04 @@ -901,7 +915,10 @@ and this project adheres to [Semantic Versioning](http://semver.org/). ### Changed * Initial release -[Unreleased]: https://github.com/Behat/Behat/compare/v3.5.0...master +[Unreleased]: https://github.com/Behat/Behat/compare/v3.7.0...master +[3.7.0]: https://github.com/Behat/Behat/compare/v3.6.1...v3.7.0 +[3.6.1]: https://github.com/Behat/Behat/compare/v3.6.0...v3.6.1 +[3.6.0]: https://github.com/Behat/Behat/compare/v3.5.0...v3.6.0 [3.5.0]: https://github.com/Behat/Behat/compare/v3.4.3...v3.5.0 [3.4.3]: https://github.com/Behat/Behat/compare/v3.4.2...v3.4.3 [3.4.2]: https://github.com/Behat/Behat/compare/v3.4.1...v3.4.2 diff --git a/src/Behat/Behat/ApplicationFactory.php b/src/Behat/Behat/ApplicationFactory.php index 8fba06a7e..78fa6d92f 100644 --- a/src/Behat/Behat/ApplicationFactory.php +++ b/src/Behat/Behat/ApplicationFactory.php @@ -46,7 +46,7 @@ */ final class ApplicationFactory extends BaseFactory { - const VERSION = '3.6.1'; + const VERSION = '3.7.0'; /** * {@inheritdoc} From 6dcf3002d9772c1ace103d6ec392adbddd1ba930 Mon Sep 17 00:00:00 2001 From: Kamil Kokot Date: Wed, 3 Jun 2020 15:56:47 +0200 Subject: [PATCH 211/567] Bump requirements to PHP ^7.2 and Symfony ^4.4|^5.0 --- .travis.yml | 37 +++--------- appveyor.yml | 2 +- composer.json | 22 +++---- features/catch_throwable.feature | 1 - features/definitions_transformations.feature | 2 - features/error_reporting.feature | 2 - features/extensions.feature | 1 - features/junit_format.feature | 60 -------------------- features/traits.feature | 1 - 9 files changed, 21 insertions(+), 107 deletions(-) diff --git a/.travis.yml b/.travis.yml index 6684ee606..55200c509 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,8 +1,6 @@ language: php -php: [5.6, 7.0, 7.1, 7.2, 7.3, 7.4] - -sudo: false +php: [7.2, 7.3, 7.4] cache: directories: @@ -10,32 +8,16 @@ cache: matrix: include: - - php: 5.3 - dist: precise - env: PHP_VERSION=53 - - php: 5.4 - dist: trusty - env: PHP_VERSION=54+ - - php: 5.5 - dist: trusty - env: PHP_VERSION=54+ - - php: 5.6 - env: DEPENDENCIES='low' - env: PHP_VERSION=54+ - - php: 5.6 + - php: 7.2 env: SKIP_INTEROP='~@interop&&' - - php: 5.6 - env: SYMFONY_VERSION='2.7.*' - - php: 5.6 - env: SYMFONY_VERSION='2.8.*' - php: 7.2 - env: SYMFONY_VERSION='^3.4' - - php: 7.3 - env: SYMFONY_VERSION='^3.4' - - php: 7.3 - env: SYMFONY_VERSION='^4.3' + env: DEPENDENCIES='low' + - php: 7.2 + env: SYMFONY_VERSION='^4.4' - php: 7.3 - env: SYMFONY_VERSION='^5.0' + env: SYMFONY_VERSION='^4.4' + - php: 7.4 + env: SYMFONY_VERSION='^4.4' before_install: - phpenv config-rm xdebug.ini || echo "XDebug is not enabled" @@ -45,12 +27,11 @@ before_script: - if [ "$SKIP_INTEROP" != "" ]; then composer remove --dev --no-update container-interop/container-interop; fi; - if [ "$DEPENDENCIES" != "low" ]; then composer update; fi; - if [ "$DEPENDENCIES" = "low" ]; then composer update --prefer-lowest; fi; - - if [ ! "$PHP_VERSION" ]; then export PHP_VERSION=`php -r 'echo PHP_MAJOR_VERSION;'`; fi; - export PATH=./bin:$PATH script: - ./vendor/bin/phpunit - - behat -fprogress --strict --tags "${SKIP_INTEROP}~@php-version,@php${PHP_VERSION}" + - behat -fprogress --strict --tags "${SKIP_INTEROP}~@random" before_deploy: - curl -LSs https://box-project.github.io/box2/installer.php | php diff --git a/appveyor.yml b/appveyor.yml index 3871fe757..ca6beea26 100644 --- a/appveyor.yml +++ b/appveyor.yml @@ -57,5 +57,5 @@ install: test_script: - cd c:\projects\behat - - php bin\behat --tags="~@php-version,@php7" --format=progress + - php bin\behat --format=progress - php vendor\phpunit\phpunit\phpunit --testdox diff --git a/composer.json b/composer.json index a61866af4..b9676e5d7 100644 --- a/composer.json +++ b/composer.json @@ -1,6 +1,6 @@ { "name": "behat/behat", - "description": "Scenario-oriented BDD framework for PHP 5.3", + "description": "Scenario-oriented BDD framework for PHP", "keywords": ["BDD", "ScenarioBDD", "StoryBDD", "Examples", "Scrum", "Agile", "User story", "Symfony", "business", "development", "testing", "documentation"], "homepage": "http://behat.org/", "type": "library", @@ -14,22 +14,22 @@ ], "require": { - "php": ">=5.3.3", + "php": "^7.2", "ext-mbstring": "*", "behat/gherkin": "^4.6.0", "behat/transliterator": "^1.2", - "symfony/console": "^2.7.51 || ^2.8.33 || ^3.3.15 || ^3.4.3 || ^4.0.3 || ^5.0", - "symfony/config": "^2.7.51 || ^3.0 || ^4.0 || ^5.0", - "symfony/dependency-injection": "^2.7.51 || ^3.0 || ^4.0 || ^5.0", - "symfony/event-dispatcher": "^2.7.51 || ^3.0 || ^4.0 || ^5.0", - "symfony/translation": "^2.7.51 || ^3.0 || ^4.0 || ^5.0", - "symfony/yaml": "^2.7.51 || ^3.0 || ^4.0 || ^5.0", + "symfony/console": "^4.4 || ^5.0", + "symfony/config": "^4.4 || ^5.0", + "symfony/dependency-injection": "^4.4 || ^5.0", + "symfony/event-dispatcher": "^4.4 || ^5.0", + "symfony/translation": "^4.4 || ^5.0", + "symfony/yaml": "^4.4 || ^5.0", "psr/container": "^1.0" }, "require-dev": { - "symfony/process": "~2.5 || ^3.0 || ^4.0 || ^5.0", - "phpunit/phpunit": "^4.8.36 || ^6.5.14 || ^7.5.20", + "symfony/process": "^4.4 || ^5.0", + "phpunit/phpunit": "^7.5.20", "herrera-io/box": "~1.6.1", "container-interop/container-interop": "^1.2" }, @@ -53,7 +53,7 @@ "extra": { "branch-alias": { - "dev-master": "3.6.x-dev" + "dev-master": "3.8.x-dev" } }, diff --git a/features/catch_throwable.feature b/features/catch_throwable.feature index ae3e8ff15..28e5a5574 100644 --- a/features/catch_throwable.feature +++ b/features/catch_throwable.feature @@ -1,4 +1,3 @@ -@php-version @php7 Feature: Support PHP 7 Throwable In order for my test suite to continue running despite fatal errors in my code As a feature developer diff --git a/features/definitions_transformations.feature b/features/definitions_transformations.feature index d24e033ee..e881a823b 100644 --- a/features/definitions_transformations.feature +++ b/features/definitions_transformations.feature @@ -420,7 +420,6 @@ Feature: Step Arguments Transformations 8 steps (8 passed) """ - @php-version @php7 Scenario: By-type object transformations Given a file named "features/my.feature" with: """ @@ -488,7 +487,6 @@ Feature: Step Arguments Transformations 4 steps (4 passed) """ - @php-version @php7 Scenario: By-type and by-name object transformations Given a file named "features/my.feature" with: """ diff --git a/features/error_reporting.feature b/features/error_reporting.feature index de192df2a..5900b7ff1 100644 --- a/features/error_reporting.feature +++ b/features/error_reporting.feature @@ -121,7 +121,6 @@ Feature: Error Reporting When I run "behat -f progress --no-colors features/e_notice_in_scenario.feature" Then it should pass - @php-version @php7 Scenario: With very verbose error reporting When I run "behat -f progress --no-colors -vv features/exception_in_scenario.feature" Then it should fail @@ -139,7 +138,6 @@ Feature: Error Reporting 1 step (1 failed) """ - @php-version @php7 Scenario: With debug verbose error reporting When I run "behat -f progress --no-colors -vvv features/exception_in_scenario.feature" Then it should fail diff --git a/features/extensions.feature b/features/extensions.feature index ab155f4c9..113abd2f7 100644 --- a/features/extensions.feature +++ b/features/extensions.feature @@ -122,7 +122,6 @@ Feature: Extensions `inexistent_extension` extension file or class could not be located. """ - @php-version @php7 Scenario: Exception handlers extension Given a file named "behat.yml" with: """ diff --git a/features/junit_format.feature b/features/junit_format.feature index 5b2e7b7b4..bd87431f4 100644 --- a/features/junit_format.feature +++ b/features/junit_format.feature @@ -526,66 +526,6 @@ """ And the file "junit/default.xml" should be a valid document according to "junit.xsd" - @php-version @php53 @php54+ - Scenario: Aborting due to PHP error - Given a file named "features/bootstrap/FeatureContext.php" with: - """ - value = $num; - } - - /** - * @Then /I must have (\d+)/ - */ - public function iMustHave($num) { - PHPUnit\Framework\Assert::assertEqual($num, $this->value); - } - - /** - * @When /I add (\d+)/ - */ - public function iAdd($num) { - $this->value += $num; - } - } - """ - And a file named "features/World.feature" with: - """ - Feature: World consistency - In order to maintain stable behaviors - As a features developer - I want, that "World" flushes between scenarios - - Background: - Given I have entered 10 - - Scenario: Failed - When I add 4 - Then I must have 14 - """ - When I run "behat --no-colors -f junit -o junit" - Then it should fail with: - """ - Call to undefined method PHPUnit\Framework\Assert::assertEqual - """ - And "junit/default.xml" file xml should be like: - """ - - - """ - Scenario: Aborting due invalid output path Given a file named "features/bootstrap/FeatureContext.php" with: """ diff --git a/features/traits.feature b/features/traits.feature index 7a8a17092..b4a5f6913 100644 --- a/features/traits.feature +++ b/features/traits.feature @@ -86,7 +86,6 @@ Feature: Support traits | 2 | 2 | 3 | """ - @php-version @php54+ @php7 Scenario: Run feature with failing scenarios When I run "behat --no-colors -f progress" Then it should pass with: From 93f4564310e37e9865083cf64251db7f3f8b7d67 Mon Sep 17 00:00:00 2001 From: Toni Kolev Date: Fri, 29 Mar 2019 16:00:28 +0200 Subject: [PATCH 212/567] Adding Bulgarian language. --- i18n.php | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/i18n.php b/i18n.php index 897e17413..64e46f710 100644 --- a/i18n.php +++ b/i18n.php @@ -247,4 +247,21 @@ 'undefined_count' => '[1,Inf] %1% meghatározatlan', 'skipped_count' => '[1,Inf] %1% kihagyott', ), + 'bg' => array( + 'snippet_context_choice' => 'В сет %1% има недекларирани стъпки. Изберете в кой Context да бъдат създадени:', + 'snippet_proposal_title' => '%1% има липсващи стъпки. Можете да ги създадете чрез:', + 'snippet_missing_title' => 'Използвайте този снипет --snippets-for за да генерирате кода за следните стъпки %1% през конзолата:', + 'skipped_scenarios_title' => 'Пропуснати сценарии:', + 'failed_scenarios_title' => 'Провалени сценарии:', + 'failed_hooks_title' => 'Провалени хукове:', + 'failed_steps_title' => 'Провалени стъпки:', + 'pending_steps_title' => 'Изчакващи стъпки:', + 'scenarios_count' => '{0} Няма сценарий|{1} 1 сценарий|]1,Inf] %1% сценарии', + 'steps_count' => '{0} Няма стъпки|{1} 1 стъпка|]1,Inf] %1% стъпки', + 'passed_count' => '[1,Inf] %1% успешни', + 'failed_count' => '[1,Inf] %1% провалени', + 'pending_count' => '[1,Inf] %1% изчакващи', + 'undefined_count' => '[1,Inf] %1% неопределени', + 'skipped_count' => '[1,Inf] %1% пропуснати', + ), ); From 0672b33293b1ee82f6f8aaadf8372aa40d7a2727 Mon Sep 17 00:00:00 2001 From: Kamil Kokot Date: Fri, 5 Jun 2020 11:36:12 +0200 Subject: [PATCH 213/567] Sort translations list by language --- i18n.php | 100 +++++++++++++++++++++++++++---------------------------- 1 file changed, 50 insertions(+), 50 deletions(-) diff --git a/i18n.php b/i18n.php index 64e46f710..8b0beff99 100644 --- a/i18n.php +++ b/i18n.php @@ -16,6 +16,23 @@ 'undefined_count' => '[1,Inf] %count% undefined', 'skipped_count' => '[1,Inf] %count% skipped', ), + 'bg' => array( + 'snippet_context_choice' => 'В сет %1% има недекларирани стъпки. Изберете в кой Context да бъдат създадени:', + 'snippet_proposal_title' => '%1% има липсващи стъпки. Можете да ги създадете чрез:', + 'snippet_missing_title' => 'Използвайте този снипет --snippets-for за да генерирате кода за следните стъпки %1% през конзолата:', + 'skipped_scenarios_title' => 'Пропуснати сценарии:', + 'failed_scenarios_title' => 'Провалени сценарии:', + 'failed_hooks_title' => 'Провалени хукове:', + 'failed_steps_title' => 'Провалени стъпки:', + 'pending_steps_title' => 'Изчакващи стъпки:', + 'scenarios_count' => '{0} Няма сценарий|{1} 1 сценарий|]1,Inf] %1% сценарии', + 'steps_count' => '{0} Няма стъпки|{1} 1 стъпка|]1,Inf] %1% стъпки', + 'passed_count' => '[1,Inf] %1% успешни', + 'failed_count' => '[1,Inf] %1% провалени', + 'pending_count' => '[1,Inf] %1% изчакващи', + 'undefined_count' => '[1,Inf] %1% неопределени', + 'skipped_count' => '[1,Inf] %1% пропуснати', + ), 'cs' => array( 'snippet_proposal_title' => '%count% obsahuje chybné kroky. Definujte je za použití následujícího kódu:', 'snippet_missing_title' => 'Snippety pro následující kroky v sadě %count% nebyly vygenerovány (zkontrolujte správnost konfigurace):', @@ -76,6 +93,23 @@ 'undefined_count' => '[1,Inf] %count% indéfinis', 'skipped_count' => '[1,Inf] %count% ignorés', ), + 'hu' => array( + 'snippet_context_choice' => '%1% sorozat meghatározatlan lépéseket tartalmaz. Válaszd ki a környezetet kódrészlet készítéséhez:', + 'snippet_proposal_title' => '%1% lépései hiányosak. Hozd létre az alábbi kódrészletekkel:', + 'snippet_missing_title' => 'Használd a --snippets-for parancssori kapcsolót kódrészletek készítéséhez a %1% sorozat lépéseihez:', + 'skipped_scenarios_title' => 'Kihagyott forgatókönyvek:', + 'failed_scenarios_title' => 'Sikertelen forgatókönyvek:', + 'failed_hooks_title' => 'Sikertelen kampók:', + 'failed_steps_title' => 'Sikertelen lépések:', + 'pending_steps_title' => 'Elintézendő lépések:', + 'scenarios_count' => '{0} Nem volt forgatókönyv|{1} 1 forgatókönyv|]1,Inf] %1% forgatókönyv', + 'steps_count' => '{0} Nem volt lépés|{1} 1 lépés|]1,Inf] %1% lépés', + 'passed_count' => '[1,Inf] %1% sikeres', + 'failed_count' => '[1,Inf] %1% sikertelen', + 'pending_count' => '[1,Inf] %1% elintézendő', + 'undefined_count' => '[1,Inf] %1% meghatározatlan', + 'skipped_count' => '[1,Inf] %1% kihagyott', + ), 'it' => array( 'snippet_proposal_title' => '%count% ha dei passaggi mancanti. Definiscili con questi snippet:', 'snippet_missing_title' => 'Gli snippet per i seguenti passaggi della suite %count% non sono stati generati (verifica la configurazione):', @@ -107,6 +141,22 @@ 'undefined_count' => '[1,Inf] %count% 個未定義', 'skipped_count' => '[1,Inf] %count% 個スキップ', ), + 'ko' => array( + 'snippet_proposal_title' => '%1% 정의가 되지 않았습니다. 스니펫을 생성할 컨텍스트를 선택하십시오:', + 'snippet_missing_title' => '%1% 단계가 누락되었습니다. 스니펫을 정의해주세요:', + 'skipped_scenarios_title' => '건너뛴 시나리오:', + 'failed_scenarios_title' => '실패한 시나리오:', + 'failed_hooks_title' => '실패한 훅 연결:', + 'failed_steps_title' => '실패한 단계:', + 'pending_steps_title' => '준비중인 단계:', + 'scenarios_count' => '{0} 없는 시나리오들|{1} 1 시나리오|]1,Inf] %1% 시나리오들', + 'steps_count' => '{0} 없는 단계들|{1} 1 단계|]1,Inf] %1% 단계들', + 'passed_count' => '[1,Inf] %1% 통과', + 'failed_count' => '[1,Inf] %1% 실패', + 'pending_count' => '[1,Inf] %1% 준비중', + 'undefined_count' => '[1,Inf] %1% 정의되지 않았습니다.', + 'skipped_count' => '[1,Inf] %1% 건너뜀', + ), 'nl' => array( 'snippet_proposal_title' => 'Ontbrekende stappen in %count%. Definieer ze met de volgende fragmenten:', 'snippet_missing_title' => 'Fragmenten voor de volgende stappen in de %count% suite werden niet gegenereerd (controleer de configuratie):', @@ -214,54 +264,4 @@ 'undefined_count' => '{1,21,31} %count% не определен|]1,Inf] %count% не определено', 'skipped_count' => '{1,21,31} %count% пропущен|]1,Inf] %count% пропущено', ), - 'ko' => array( - 'snippet_proposal_title' => '%1% 정의가 되지 않았습니다. 스니펫을 생성할 컨텍스트를 선택하십시오:', - 'snippet_missing_title' => '%1% 단계가 누락되었습니다. 스니펫을 정의해주세요:', - 'skipped_scenarios_title' => '건너뛴 시나리오:', - 'failed_scenarios_title' => '실패한 시나리오:', - 'failed_hooks_title' => '실패한 훅 연결:', - 'failed_steps_title' => '실패한 단계:', - 'pending_steps_title' => '준비중인 단계:', - 'scenarios_count' => '{0} 없는 시나리오들|{1} 1 시나리오|]1,Inf] %1% 시나리오들', - 'steps_count' => '{0} 없는 단계들|{1} 1 단계|]1,Inf] %1% 단계들', - 'passed_count' => '[1,Inf] %1% 통과', - 'failed_count' => '[1,Inf] %1% 실패', - 'pending_count' => '[1,Inf] %1% 준비중', - 'undefined_count' => '[1,Inf] %1% 정의되지 않았습니다.', - 'skipped_count' => '[1,Inf] %1% 건너뜀', - ), - 'hu' => array( - 'snippet_context_choice' => '%1% sorozat meghatározatlan lépéseket tartalmaz. Válaszd ki a környezetet kódrészlet készítéséhez:', - 'snippet_proposal_title' => '%1% lépései hiányosak. Hozd létre az alábbi kódrészletekkel:', - 'snippet_missing_title' => 'Használd a --snippets-for parancssori kapcsolót kódrészletek készítéséhez a %1% sorozat lépéseihez:', - 'skipped_scenarios_title' => 'Kihagyott forgatókönyvek:', - 'failed_scenarios_title' => 'Sikertelen forgatókönyvek:', - 'failed_hooks_title' => 'Sikertelen kampók:', - 'failed_steps_title' => 'Sikertelen lépések:', - 'pending_steps_title' => 'Elintézendő lépések:', - 'scenarios_count' => '{0} Nem volt forgatókönyv|{1} 1 forgatókönyv|]1,Inf] %1% forgatókönyv', - 'steps_count' => '{0} Nem volt lépés|{1} 1 lépés|]1,Inf] %1% lépés', - 'passed_count' => '[1,Inf] %1% sikeres', - 'failed_count' => '[1,Inf] %1% sikertelen', - 'pending_count' => '[1,Inf] %1% elintézendő', - 'undefined_count' => '[1,Inf] %1% meghatározatlan', - 'skipped_count' => '[1,Inf] %1% kihagyott', - ), - 'bg' => array( - 'snippet_context_choice' => 'В сет %1% има недекларирани стъпки. Изберете в кой Context да бъдат създадени:', - 'snippet_proposal_title' => '%1% има липсващи стъпки. Можете да ги създадете чрез:', - 'snippet_missing_title' => 'Използвайте този снипет --snippets-for за да генерирате кода за следните стъпки %1% през конзолата:', - 'skipped_scenarios_title' => 'Пропуснати сценарии:', - 'failed_scenarios_title' => 'Провалени сценарии:', - 'failed_hooks_title' => 'Провалени хукове:', - 'failed_steps_title' => 'Провалени стъпки:', - 'pending_steps_title' => 'Изчакващи стъпки:', - 'scenarios_count' => '{0} Няма сценарий|{1} 1 сценарий|]1,Inf] %1% сценарии', - 'steps_count' => '{0} Няма стъпки|{1} 1 стъпка|]1,Inf] %1% стъпки', - 'passed_count' => '[1,Inf] %1% успешни', - 'failed_count' => '[1,Inf] %1% провалени', - 'pending_count' => '[1,Inf] %1% изчакващи', - 'undefined_count' => '[1,Inf] %1% неопределени', - 'skipped_count' => '[1,Inf] %1% пропуснати', - ), ); From 75610185263865a334937aefa0c9c51fd653c51f Mon Sep 17 00:00:00 2001 From: Kamil Kokot Date: Fri, 5 Jun 2020 11:56:56 +0200 Subject: [PATCH 214/567] Leave just one job testing Symfony ^4.4 --- .travis.yml | 4 ---- 1 file changed, 4 deletions(-) diff --git a/.travis.yml b/.travis.yml index 55200c509..10d1ca9ae 100644 --- a/.travis.yml +++ b/.travis.yml @@ -12,10 +12,6 @@ matrix: env: SKIP_INTEROP='~@interop&&' - php: 7.2 env: DEPENDENCIES='low' - - php: 7.2 - env: SYMFONY_VERSION='^4.4' - - php: 7.3 - env: SYMFONY_VERSION='^4.4' - php: 7.4 env: SYMFONY_VERSION='^4.4' From ef68c388bb0dff05a902fbf0feeaae186d4ced32 Mon Sep 17 00:00:00 2001 From: Kamil Kokot Date: Fri, 5 Jun 2020 12:01:23 +0200 Subject: [PATCH 215/567] Fix deprecations in Travis configuration --- .travis.yml | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/.travis.yml b/.travis.yml index 10d1ca9ae..dda7e584a 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,12 +1,16 @@ language: php +os: linux + +dist: xenial + php: [7.2, 7.3, 7.4] cache: directories: - $HOME/.composer/cache -matrix: +jobs: include: - php: 7.2 env: SKIP_INTEROP='~@interop&&' @@ -38,9 +42,9 @@ before_deploy: deploy: provider: releases - api_key: $GITHUB_API_KEY + token: $GITHUB_API_KEY file: behat.phar - skip_cleanup: true + cleanup: false on: tags: true php: 5.6 From 48a3636297233081954c952ebaf6530711e34467 Mon Sep 17 00:00:00 2001 From: jawira Date: Fri, 12 Jun 2020 11:01:16 +0200 Subject: [PATCH 216/567] Add "return 0" in DebugCommand.php --- src/Behat/Testwork/Cli/DebugCommand.php | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/Behat/Testwork/Cli/DebugCommand.php b/src/Behat/Testwork/Cli/DebugCommand.php index d888cb90b..d24ffd5d0 100644 --- a/src/Behat/Testwork/Cli/DebugCommand.php +++ b/src/Behat/Testwork/Cli/DebugCommand.php @@ -76,5 +76,7 @@ protected function execute(InputInterface $input, OutputInterface $output) $output->writeln(sprintf(' extensions loaded: %s', count($debug['extensions_list']) ? implode(', ', $debug['extensions_list']) : 'none')); $output->writeln(''); + + return 0; } } From c5fb89f13029811bfa39808359c64605f35e3df9 Mon Sep 17 00:00:00 2001 From: Kamil Kokot Date: Wed, 17 Jun 2020 17:49:04 +0200 Subject: [PATCH 217/567] Apply code review fixes --- .travis.yml | 4 +-- features/junit_format.feature | 53 +++++++++++++++++++++++++++++++++++ 2 files changed, 55 insertions(+), 2 deletions(-) diff --git a/.travis.yml b/.travis.yml index dda7e584a..c8d5cb105 100644 --- a/.travis.yml +++ b/.travis.yml @@ -13,7 +13,7 @@ cache: jobs: include: - php: 7.2 - env: SKIP_INTEROP='~@interop&&' + env: SKIP_INTEROP=true - php: 7.2 env: DEPENDENCIES='low' - php: 7.4 @@ -31,7 +31,7 @@ before_script: script: - ./vendor/bin/phpunit - - behat -fprogress --strict --tags "${SKIP_INTEROP}~@random" + - behat -fprogress --strict $([ -z "$SKIP_INTEROP" ] || echo "--tags ~@interop") before_deploy: - curl -LSs https://box-project.github.io/box2/installer.php | php diff --git a/features/junit_format.feature b/features/junit_format.feature index bd87431f4..82fe02ace 100644 --- a/features/junit_format.feature +++ b/features/junit_format.feature @@ -526,6 +526,59 @@ """ And the file "junit/default.xml" should be a valid document according to "junit.xsd" + Scenario: Aborting due to PHP error + Given a file named "features/bootstrap/FeatureContext.php" with: + """ + value = $num; + } + /** + * @Then /I must have (\d+)/ + */ + public function iMustHave($num) { + $foo = new class extends Foo implements Foo {}; + } + /** + * @When /I add (\d+)/ + */ + public function iAdd($num) { + $this->value += $num; + } + } + """ + And a file named "features/World.feature" with: + """ + Feature: World consistency + In order to maintain stable behaviors + As a features developer + I want, that "World" flushes between scenarios + Background: + Given I have entered 10 + Scenario: Failed + When I add 4 + Then I must have 14 + """ + When I run "behat --no-colors -f junit -o junit" + Then it should fail with: + """ + PHP Fatal error: class@anonymous cannot implement Foo - it is not an interface + """ + And "junit/default.xml" file xml should be like: + """ + + + """ + Scenario: Aborting due invalid output path Given a file named "features/bootstrap/FeatureContext.php" with: """ From 902b3c6a42414c3b7135ae6e2d6733a409b1e62e Mon Sep 17 00:00:00 2001 From: jawira Date: Thu, 18 Jun 2020 15:18:27 +0200 Subject: [PATCH 218/567] Add debug test --- features/debug.feature | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) create mode 100644 features/debug.feature diff --git a/features/debug.feature b/features/debug.feature new file mode 100644 index 000000000..68b9f4523 --- /dev/null +++ b/features/debug.feature @@ -0,0 +1,16 @@ +Feature: Debug info + In order to know more about current environment + As a Behat user + I need an ability to get debugging information + + Scenario: Debug + When I run behat in debug mode + Then it should pass + And the output should contain: + """ + --- configuration + """ + And the output should contain: + """ + --- extensions + """ From e239f05827eec3b670837ca98aa0008748546bdc Mon Sep 17 00:00:00 2001 From: Remon van de Kamp Date: Fri, 19 Jun 2020 10:29:00 +0200 Subject: [PATCH 219/567] Always load PHP 7.0+ transformation readers PHP < 7.0 is no longer supported, so the check has become moot --- .../TransformationAnnotationReader.php | 21 +++++++------------ 1 file changed, 8 insertions(+), 13 deletions(-) diff --git a/src/Behat/Behat/Transformation/Context/Annotation/TransformationAnnotationReader.php b/src/Behat/Behat/Transformation/Context/Annotation/TransformationAnnotationReader.php index a32ac5cca..680d19685 100644 --- a/src/Behat/Behat/Transformation/Context/Annotation/TransformationAnnotationReader.php +++ b/src/Behat/Behat/Transformation/Context/Annotation/TransformationAnnotationReader.php @@ -64,18 +64,13 @@ public function readCallee($contextClass, ReflectionMethod $method, $docLine, $d */ private function simpleTransformations() { - $transformations = array(); - $transformations[] = 'Behat\Behat\Transformation\Transformation\RowBasedTableTransformation'; - $transformations[] = 'Behat\Behat\Transformation\Transformation\ColumnBasedTableTransformation'; - $transformations[] = 'Behat\Behat\Transformation\Transformation\TableRowTransformation'; - - if (PHP_VERSION_ID >= 70000) { - $transformations[] = 'Behat\Behat\Transformation\Transformation\TokenNameAndReturnTypeTransformation'; - $transformations[] = 'Behat\Behat\Transformation\Transformation\ReturnTypeTransformation'; - } - - $transformations[] = 'Behat\Behat\Transformation\Transformation\TokenNameTransformation'; - - return $transformations; + return array( + 'Behat\Behat\Transformation\Transformation\RowBasedTableTransformation', + 'Behat\Behat\Transformation\Transformation\ColumnBasedTableTransformation', + 'Behat\Behat\Transformation\Transformation\TableRowTransformation', + 'Behat\Behat\Transformation\Transformation\TokenNameAndReturnTypeTransformation', + 'Behat\Behat\Transformation\Transformation\ReturnTypeTransformation', + 'Behat\Behat\Transformation\Transformation\TokenNameTransformation' + ); } } From 1a1812b2cbb41cf67f5c8a9f478e4117a0afbbb3 Mon Sep 17 00:00:00 2001 From: Remon van de Kamp Date: Fri, 19 Jun 2020 10:30:16 +0200 Subject: [PATCH 220/567] Switch from ticks to pcntl_async_signals This is more lightweight and can be instantiated globally, removing the need for Behat\Behat\EventDispatcher\Tester. That class has been left to prevent breaking BC, but should be removed. See https://wiki.php.net/rfc/async_signals --- .../EventDispatcherExtension.php | 18 ++++++++---------- .../Tester/TickingStepTester.php | 5 +++++ .../EventDispatcher/Cli/SigintController.php | 2 +- 3 files changed, 14 insertions(+), 11 deletions(-) diff --git a/src/Behat/Behat/EventDispatcher/ServiceContainer/EventDispatcherExtension.php b/src/Behat/Behat/EventDispatcher/ServiceContainer/EventDispatcherExtension.php index 252cd03f5..0aa06952c 100644 --- a/src/Behat/Behat/EventDispatcher/ServiceContainer/EventDispatcherExtension.php +++ b/src/Behat/Behat/EventDispatcher/ServiceContainer/EventDispatcherExtension.php @@ -156,20 +156,18 @@ protected function loadEventDispatchingStepTester(ContainerBuilder $container) } /** - * Loads ticking step tester. + * This method used in the past to load the TickingStepTester to work around + * a bug with the scope of declare(ticks) in PHP < 7.1. Since we don't + * support those PHP versions anymore loading the TickingStepTester is + * no longer needed. This method is left here to prevent breaking BC. + * + * @todo Remove this method in next major + * + * @deprecated * * @param ContainerBuilder $container */ protected function loadTickingStepTester(ContainerBuilder $container) { - if (!function_exists('pcntl_signal')) { - return; - } - - $definition = new Definition('Behat\Behat\EventDispatcher\Tester\TickingStepTester', array( - new Reference(TesterExtension::STEP_TESTER_ID) - )); - $definition->addTag(TesterExtension::STEP_TESTER_WRAPPER_TAG, array('priority' => 9999)); - $container->setDefinition(TesterExtension::STEP_TESTER_WRAPPER_TAG . '.ticking', $definition); } } diff --git a/src/Behat/Behat/EventDispatcher/Tester/TickingStepTester.php b/src/Behat/Behat/EventDispatcher/Tester/TickingStepTester.php index 401725495..dcbdf4c24 100644 --- a/src/Behat/Behat/EventDispatcher/Tester/TickingStepTester.php +++ b/src/Behat/Behat/EventDispatcher/Tester/TickingStepTester.php @@ -21,6 +21,11 @@ * to handle an interupt (on PHP7) * * @see Behat\Testwork\EventDispatcher\Cli\SigintController + * + * @deprecated Since the way signals are handled changed to use pcntl_signal_dispatch + * this class is no longer needed. + * + * @todo Remove this class in the next major version * * @author Peter Mitchell */ diff --git a/src/Behat/Testwork/EventDispatcher/Cli/SigintController.php b/src/Behat/Testwork/EventDispatcher/Cli/SigintController.php index cf9338b25..d12bcb1a9 100644 --- a/src/Behat/Testwork/EventDispatcher/Cli/SigintController.php +++ b/src/Behat/Testwork/EventDispatcher/Cli/SigintController.php @@ -54,7 +54,7 @@ public function configure(Command $command) public function execute(InputInterface $input, OutputInterface $output) { if (function_exists('pcntl_signal')) { - declare(ticks = 1); + pcntl_async_signals(true); pcntl_signal(SIGINT, array($this, 'abortExercise')); } } From 1d3ca76e415ba7bac4d2724c1143e0b1bd86dce5 Mon Sep 17 00:00:00 2001 From: Remon van de Kamp Date: Fri, 19 Jun 2020 10:58:59 +0200 Subject: [PATCH 221/567] Add constant visibility For now everything has to be public, because protected or private would be a BC break. Later version can change visibility if needed. --- src/Behat/Behat/ApplicationFactory.php | 2 +- .../Context/Reader/AnnotatedContextReader.php | 2 +- .../ServiceContainer/ContextExtension.php | 20 +++++++++---------- .../Appender/ContextSnippetAppender.php | 2 +- .../Pattern/Policy/TurnipPatternPolicy.php | 8 ++++---- .../ServiceContainer/DefinitionExtension.php | 14 ++++++------- .../Event/BackgroundTested.php | 8 ++++---- .../EventDispatcher/Event/ExampleTested.php | 8 ++++---- .../EventDispatcher/Event/FeatureTested.php | 8 ++++---- .../EventDispatcher/Event/OutlineTested.php | 8 ++++---- .../EventDispatcher/Event/ScenarioTested.php | 8 ++++---- .../EventDispatcher/Event/StepTested.php | 8 ++++---- .../ServiceContainer/GherkinExtension.php | 8 ++++---- .../HelperContainerExtension.php | 2 +- src/Behat/Behat/Hook/Scope/FeatureScope.php | 4 ++-- src/Behat/Behat/Hook/Scope/ScenarioScope.php | 4 ++-- src/Behat/Behat/Hook/Scope/StepScope.php | 4 ++-- .../Printer/Formatter/ConsoleFormatter.php | 2 +- .../Formatter/JUnitFormatterFactory.php | 4 ++-- .../Formatter/PrettyFormatterFactory.php | 6 +++--- .../Formatter/ProgressFormatterFactory.php | 6 +++--- .../ServiceContainer/SnippetExtension.php | 8 ++++---- src/Behat/Behat/Tester/Result/StepResult.php | 2 +- .../ServiceContainer/TesterExtension.php | 20 +++++++++---------- .../TransformationExtension.php | 4 ++-- .../ColumnBasedTableTransformation.php | 2 +- .../RowBasedTableTransformation.php | 2 +- .../Transformation/TableRowTransformation.php | 2 +- .../TokenNameTransformation.php | 2 +- .../ServiceContainer/ArgumentExtension.php | 6 +++--- .../ServiceContainer/AutoloaderExtension.php | 2 +- .../Exception/ClassNotFoundHandler.php | 2 +- .../Exception/MethodNotFoundHandler.php | 2 +- .../Call/ServiceContainer/CallExtension.php | 10 +++++----- .../Cli/ServiceContainer/CliExtension.php | 8 ++++---- .../ServiceContainer/EnvironmentExtension.php | 6 +++--- .../Event/ExerciseCompleted.php | 8 ++++---- .../EventDispatcher/Event/SuiteTested.php | 8 ++++---- .../EventDispatcherExtension.php | 4 ++-- .../TestworkEventDispatcher.php | 6 +++--- .../TestworkEventDispatcherSymfony5.php | 6 +++--- .../TestworkEventDispatcherSymfonyLegacy.php | 6 +++--- .../ServiceContainer/ExceptionExtension.php | 4 ++-- .../ServiceContainer/FilesystemExtension.php | 2 +- src/Behat/Testwork/Hook/Scope/SuiteScope.php | 4 ++-- .../Hook/ServiceContainer/HookExtension.php | 4 ++-- .../ServiceContainer/OrderingExtension.php | 2 +- .../Output/Printer/Factory/OutputFactory.php | 8 ++++---- .../Output/Printer/JUnitOutputPrinter.php | 4 ++-- .../Testwork/Output/Printer/OutputPrinter.php | 8 ++++---- .../ServiceContainer/OutputExtension.php | 4 ++-- .../SpecificationExtension.php | 4 ++-- .../Suite/ServiceContainer/SuiteExtension.php | 8 ++++---- .../Testwork/Tester/Result/TestResult.php | 8 ++++---- .../Testwork/Tester/Result/TestResults.php | 2 +- .../ServiceContainer/TesterExtension.php | 16 +++++++-------- .../ServiceContainer/TranslatorExtension.php | 2 +- 57 files changed, 166 insertions(+), 166 deletions(-) diff --git a/src/Behat/Behat/ApplicationFactory.php b/src/Behat/Behat/ApplicationFactory.php index 78fa6d92f..87d71d720 100644 --- a/src/Behat/Behat/ApplicationFactory.php +++ b/src/Behat/Behat/ApplicationFactory.php @@ -46,7 +46,7 @@ */ final class ApplicationFactory extends BaseFactory { - const VERSION = '3.7.0'; + public const VERSION = '3.7.0'; /** * {@inheritdoc} diff --git a/src/Behat/Behat/Context/Reader/AnnotatedContextReader.php b/src/Behat/Behat/Context/Reader/AnnotatedContextReader.php index 02baea625..2d5963415 100644 --- a/src/Behat/Behat/Context/Reader/AnnotatedContextReader.php +++ b/src/Behat/Behat/Context/Reader/AnnotatedContextReader.php @@ -24,7 +24,7 @@ */ final class AnnotatedContextReader implements ContextReader { - const DOCLINE_TRIMMER_REGEX = '/^\/\*\*\s*|^\s*\*\s*|\s*\*\/$|\s*$/'; + public const DOCLINE_TRIMMER_REGEX = '/^\/\*\*\s*|^\s*\*\s*|\s*\*\/$|\s*$/'; /** * @var string[] diff --git a/src/Behat/Behat/Context/ServiceContainer/ContextExtension.php b/src/Behat/Behat/Context/ServiceContainer/ContextExtension.php index f4c6917b7..1da6fdc3a 100644 --- a/src/Behat/Behat/Context/ServiceContainer/ContextExtension.php +++ b/src/Behat/Behat/Context/ServiceContainer/ContextExtension.php @@ -39,20 +39,20 @@ final class ContextExtension implements Extension /** * Available services */ - const FACTORY_ID = 'context.factory'; - const CONTEXT_SNIPPET_GENERATOR_ID = 'snippet.generator.context'; - const AGGREGATE_RESOLVER_FACTORY_ID = 'context.argument.aggregate_resolver_factory'; + public const FACTORY_ID = 'context.factory'; + public const CONTEXT_SNIPPET_GENERATOR_ID = 'snippet.generator.context'; + public const AGGREGATE_RESOLVER_FACTORY_ID = 'context.argument.aggregate_resolver_factory'; /* * Available extension points */ - const CLASS_RESOLVER_TAG = 'context.class_resolver'; - const ARGUMENT_RESOLVER_TAG = 'context.argument_resolver'; - const INITIALIZER_TAG = 'context.initializer'; - const READER_TAG = 'context.reader'; - const ANNOTATION_READER_TAG = 'context.annotation_reader'; - const CLASS_GENERATOR_TAG = 'context.class_generator'; - const SUITE_SCOPED_RESOLVER_FACTORY_TAG = 'context.argument.suite_resolver_factory'; + public const CLASS_RESOLVER_TAG = 'context.class_resolver'; + public const ARGUMENT_RESOLVER_TAG = 'context.argument_resolver'; + public const INITIALIZER_TAG = 'context.initializer'; + public const READER_TAG = 'context.reader'; + public const ANNOTATION_READER_TAG = 'context.annotation_reader'; + public const CLASS_GENERATOR_TAG = 'context.class_generator'; + public const SUITE_SCOPED_RESOLVER_FACTORY_TAG = 'context.argument.suite_resolver_factory'; /** * @var ServiceProcessor diff --git a/src/Behat/Behat/Context/Snippet/Appender/ContextSnippetAppender.php b/src/Behat/Behat/Context/Snippet/Appender/ContextSnippetAppender.php index 82e6ec35a..456809bc2 100644 --- a/src/Behat/Behat/Context/Snippet/Appender/ContextSnippetAppender.php +++ b/src/Behat/Behat/Context/Snippet/Appender/ContextSnippetAppender.php @@ -25,7 +25,7 @@ final class ContextSnippetAppender implements SnippetAppender /** * @const PendingException class */ - const PENDING_EXCEPTION_CLASS = 'Behat\Behat\Tester\Exception\PendingException'; + public const PENDING_EXCEPTION_CLASS = 'Behat\Behat\Tester\Exception\PendingException'; /** * @var FilesystemLogger diff --git a/src/Behat/Behat/Definition/Pattern/Policy/TurnipPatternPolicy.php b/src/Behat/Behat/Definition/Pattern/Policy/TurnipPatternPolicy.php index 0fbb8fc32..aa37f9e62 100644 --- a/src/Behat/Behat/Definition/Pattern/Policy/TurnipPatternPolicy.php +++ b/src/Behat/Behat/Definition/Pattern/Policy/TurnipPatternPolicy.php @@ -21,11 +21,11 @@ */ final class TurnipPatternPolicy implements PatternPolicy { - const TOKEN_REGEX = "[\"']?(?P<%s>(?<=\")[^\"]*(?=\")|(?<=')[^']*(?=')|\-?[\w\.\,]+)['\"]?"; + public const TOKEN_REGEX = "[\"']?(?P<%s>(?<=\")[^\"]*(?=\")|(?<=')[^']*(?=')|\-?[\w\.\,]+)['\"]?"; - const PLACEHOLDER_REGEXP = "/\\\:(\w+)/"; - const OPTIONAL_WORD_REGEXP = '/(\s)?\\\\\(([^\\\]+)\\\\\)(\s)?/'; - const ALTERNATIVE_WORD_REGEXP = '/(\w+)\\\\\/(\w+)/'; + public const PLACEHOLDER_REGEXP = "/\\\:(\w+)/"; + public const OPTIONAL_WORD_REGEXP = '/(\s)?\\\\\(([^\\\]+)\\\\\)(\s)?/'; + public const ALTERNATIVE_WORD_REGEXP = '/(\w+)\\\\\/(\w+)/'; /** * @var string[] diff --git a/src/Behat/Behat/Definition/ServiceContainer/DefinitionExtension.php b/src/Behat/Behat/Definition/ServiceContainer/DefinitionExtension.php index cce43415b..2b014da5d 100644 --- a/src/Behat/Behat/Definition/ServiceContainer/DefinitionExtension.php +++ b/src/Behat/Behat/Definition/ServiceContainer/DefinitionExtension.php @@ -35,17 +35,17 @@ final class DefinitionExtension implements Extension /* * Available services */ - const FINDER_ID = 'definition.finder'; - const REPOSITORY_ID = 'definition.repository'; - const PATTERN_TRANSFORMER_ID = 'definition.pattern_transformer'; - const WRITER_ID = 'definition.writer'; - const DEFINITION_TRANSLATOR_ID = 'definition.translator'; + public const FINDER_ID = 'definition.finder'; + public const REPOSITORY_ID = 'definition.repository'; + public const PATTERN_TRANSFORMER_ID = 'definition.pattern_transformer'; + public const WRITER_ID = 'definition.writer'; + public const DEFINITION_TRANSLATOR_ID = 'definition.translator'; /* * Available extension points */ - const SEARCH_ENGINE_TAG = 'definition.search_engine'; - const PATTERN_POLICY_TAG = 'definition.pattern_policy'; + public const SEARCH_ENGINE_TAG = 'definition.search_engine'; + public const PATTERN_POLICY_TAG = 'definition.pattern_policy'; /** * @var ServiceProcessor diff --git a/src/Behat/Behat/EventDispatcher/Event/BackgroundTested.php b/src/Behat/Behat/EventDispatcher/Event/BackgroundTested.php index f67f855c2..dd43ae066 100644 --- a/src/Behat/Behat/EventDispatcher/Event/BackgroundTested.php +++ b/src/Behat/Behat/EventDispatcher/Event/BackgroundTested.php @@ -21,10 +21,10 @@ */ abstract class BackgroundTested extends LifecycleEvent implements ScenarioLikeTested { - const BEFORE = 'tester.background_tested.before'; - const AFTER_SETUP = 'tester.background_tested.after_setup'; - const BEFORE_TEARDOWN = 'tester.background_tested.before_teardown'; - const AFTER = 'tester.background_tested.after'; + public const BEFORE = 'tester.background_tested.before'; + public const AFTER_SETUP = 'tester.background_tested.after_setup'; + public const BEFORE_TEARDOWN = 'tester.background_tested.before_teardown'; + public const AFTER = 'tester.background_tested.after'; /** * Returns background node. diff --git a/src/Behat/Behat/EventDispatcher/Event/ExampleTested.php b/src/Behat/Behat/EventDispatcher/Event/ExampleTested.php index 1bb1a4206..9a107670e 100644 --- a/src/Behat/Behat/EventDispatcher/Event/ExampleTested.php +++ b/src/Behat/Behat/EventDispatcher/Event/ExampleTested.php @@ -17,8 +17,8 @@ */ interface ExampleTested { - const BEFORE = 'tester.example_tested.before'; - const AFTER_SETUP = 'tester.example_tested.after_setup'; - const BEFORE_TEARDOWN = 'tester.example_tested.before_teardown'; - const AFTER = 'tester.example_tested.after'; + public const BEFORE = 'tester.example_tested.before'; + public const AFTER_SETUP = 'tester.example_tested.after_setup'; + public const BEFORE_TEARDOWN = 'tester.example_tested.before_teardown'; + public const AFTER = 'tester.example_tested.after'; } diff --git a/src/Behat/Behat/EventDispatcher/Event/FeatureTested.php b/src/Behat/Behat/EventDispatcher/Event/FeatureTested.php index f29c31c1a..a75d81ff2 100644 --- a/src/Behat/Behat/EventDispatcher/Event/FeatureTested.php +++ b/src/Behat/Behat/EventDispatcher/Event/FeatureTested.php @@ -21,10 +21,10 @@ */ abstract class FeatureTested extends LifecycleEvent implements GherkinNodeTested { - const BEFORE = 'tester.feature_tested.before'; - const AFTER_SETUP = 'tester.feature_tested.after_setup'; - const BEFORE_TEARDOWN = 'tester.feature_tested.before_teardown'; - const AFTER = 'tester.feature_tested.after'; + public const BEFORE = 'tester.feature_tested.before'; + public const AFTER_SETUP = 'tester.feature_tested.after_setup'; + public const BEFORE_TEARDOWN = 'tester.feature_tested.before_teardown'; + public const AFTER = 'tester.feature_tested.after'; /** * Returns feature. diff --git a/src/Behat/Behat/EventDispatcher/Event/OutlineTested.php b/src/Behat/Behat/EventDispatcher/Event/OutlineTested.php index 149fc4ff7..557e429d2 100644 --- a/src/Behat/Behat/EventDispatcher/Event/OutlineTested.php +++ b/src/Behat/Behat/EventDispatcher/Event/OutlineTested.php @@ -22,10 +22,10 @@ */ abstract class OutlineTested extends LifecycleEvent implements GherkinNodeTested { - const BEFORE = 'tester.outline_tested.before'; - const AFTER_SETUP = 'tester.outline_tested.after_setup'; - const BEFORE_TEARDOWN = 'tester.outline_tested.before_teardown'; - const AFTER = 'tester.outline_tested.after'; + public const BEFORE = 'tester.outline_tested.before'; + public const AFTER_SETUP = 'tester.outline_tested.after_setup'; + public const BEFORE_TEARDOWN = 'tester.outline_tested.before_teardown'; + public const AFTER = 'tester.outline_tested.after'; /** * Returns feature. diff --git a/src/Behat/Behat/EventDispatcher/Event/ScenarioTested.php b/src/Behat/Behat/EventDispatcher/Event/ScenarioTested.php index 2251b4a27..6a27ae5d6 100644 --- a/src/Behat/Behat/EventDispatcher/Event/ScenarioTested.php +++ b/src/Behat/Behat/EventDispatcher/Event/ScenarioTested.php @@ -19,10 +19,10 @@ */ abstract class ScenarioTested extends LifecycleEvent implements ScenarioLikeTested { - const BEFORE = 'tester.scenario_tested.before'; - const AFTER_SETUP = 'tester.scenario_tested.after_setup'; - const BEFORE_TEARDOWN = 'tester.scenario_tested.before_teardown'; - const AFTER = 'tester.scenario_tested.after'; + public const BEFORE = 'tester.scenario_tested.before'; + public const AFTER_SETUP = 'tester.scenario_tested.after_setup'; + public const BEFORE_TEARDOWN = 'tester.scenario_tested.before_teardown'; + public const AFTER = 'tester.scenario_tested.after'; /** * {@inheritdoc} diff --git a/src/Behat/Behat/EventDispatcher/Event/StepTested.php b/src/Behat/Behat/EventDispatcher/Event/StepTested.php index 7053d0d55..9df91fbb1 100644 --- a/src/Behat/Behat/EventDispatcher/Event/StepTested.php +++ b/src/Behat/Behat/EventDispatcher/Event/StepTested.php @@ -21,10 +21,10 @@ */ abstract class StepTested extends LifecycleEvent implements GherkinNodeTested { - const BEFORE = 'tester.step_tested.before'; - const AFTER_SETUP = 'tester.step_tested.after_setup'; - const BEFORE_TEARDOWN = 'tester.step_tested.before_teardown'; - const AFTER = 'tester.step_tested.after'; + public const BEFORE = 'tester.step_tested.before'; + public const AFTER_SETUP = 'tester.step_tested.after_setup'; + public const BEFORE_TEARDOWN = 'tester.step_tested.before_teardown'; + public const AFTER = 'tester.step_tested.after'; /** * Returns feature. diff --git a/src/Behat/Behat/Gherkin/ServiceContainer/GherkinExtension.php b/src/Behat/Behat/Gherkin/ServiceContainer/GherkinExtension.php index c24ddce17..60aef8e60 100644 --- a/src/Behat/Behat/Gherkin/ServiceContainer/GherkinExtension.php +++ b/src/Behat/Behat/Gherkin/ServiceContainer/GherkinExtension.php @@ -35,14 +35,14 @@ final class GherkinExtension implements Extension /* * Available services */ - const MANAGER_ID = 'gherkin'; - const KEYWORDS_DUMPER_ID = 'gherkin.keywords_dumper'; - const KEYWORDS_ID = 'gherkin.keywords'; + public const MANAGER_ID = 'gherkin'; + public const KEYWORDS_DUMPER_ID = 'gherkin.keywords_dumper'; + public const KEYWORDS_ID = 'gherkin.keywords'; /* * Available extension points */ - const LOADER_TAG = 'gherkin.loader'; + public const LOADER_TAG = 'gherkin.loader'; /** * @var ServiceProcessor diff --git a/src/Behat/Behat/HelperContainer/ServiceContainer/HelperContainerExtension.php b/src/Behat/Behat/HelperContainer/ServiceContainer/HelperContainerExtension.php index ab9c3cb53..a52d6f786 100644 --- a/src/Behat/Behat/HelperContainer/ServiceContainer/HelperContainerExtension.php +++ b/src/Behat/Behat/HelperContainer/ServiceContainer/HelperContainerExtension.php @@ -33,7 +33,7 @@ final class HelperContainerExtension implements Extension /* * Available extension points */ - const HELPER_CONTAINER_TAG = 'helper_container.container'; + public const HELPER_CONTAINER_TAG = 'helper_container.container'; /** * @var ServiceProcessor diff --git a/src/Behat/Behat/Hook/Scope/FeatureScope.php b/src/Behat/Behat/Hook/Scope/FeatureScope.php index fe87469de..6b27b8271 100644 --- a/src/Behat/Behat/Hook/Scope/FeatureScope.php +++ b/src/Behat/Behat/Hook/Scope/FeatureScope.php @@ -20,8 +20,8 @@ */ interface FeatureScope extends HookScope { - const BEFORE = 'feature.before'; - const AFTER = 'feature.after'; + public const BEFORE = 'feature.before'; + public const AFTER = 'feature.after'; /** * Returns scope feature. diff --git a/src/Behat/Behat/Hook/Scope/ScenarioScope.php b/src/Behat/Behat/Hook/Scope/ScenarioScope.php index c5238bc79..c7dbe513a 100644 --- a/src/Behat/Behat/Hook/Scope/ScenarioScope.php +++ b/src/Behat/Behat/Hook/Scope/ScenarioScope.php @@ -21,8 +21,8 @@ */ interface ScenarioScope extends HookScope { - const BEFORE = 'scenario.before'; - const AFTER = 'scenario.after'; + public const BEFORE = 'scenario.before'; + public const AFTER = 'scenario.after'; /** * Returns scope feature. diff --git a/src/Behat/Behat/Hook/Scope/StepScope.php b/src/Behat/Behat/Hook/Scope/StepScope.php index c07a79b02..449154dd0 100644 --- a/src/Behat/Behat/Hook/Scope/StepScope.php +++ b/src/Behat/Behat/Hook/Scope/StepScope.php @@ -21,8 +21,8 @@ */ interface StepScope extends HookScope { - const BEFORE = 'step.before'; - const AFTER = 'step.after'; + public const BEFORE = 'step.before'; + public const AFTER = 'step.after'; /** * Returns scope feature. diff --git a/src/Behat/Behat/Output/Printer/Formatter/ConsoleFormatter.php b/src/Behat/Behat/Output/Printer/Formatter/ConsoleFormatter.php index 9b403a68e..1e1f695e1 100644 --- a/src/Behat/Behat/Output/Printer/Formatter/ConsoleFormatter.php +++ b/src/Behat/Behat/Output/Printer/Formatter/ConsoleFormatter.php @@ -19,7 +19,7 @@ */ final class ConsoleFormatter extends BaseOutputFormatter { - const CUSTOM_PATTERN = '/{\+([a-z-_]+)}(.*?){\-\\1}/si'; + public const CUSTOM_PATTERN = '/{\+([a-z-_]+)}(.*?){\-\\1}/si'; /** * Formats a message according to the given styles. diff --git a/src/Behat/Behat/Output/ServiceContainer/Formatter/JUnitFormatterFactory.php b/src/Behat/Behat/Output/ServiceContainer/Formatter/JUnitFormatterFactory.php index 4212fbb01..c28d2cda5 100644 --- a/src/Behat/Behat/Output/ServiceContainer/Formatter/JUnitFormatterFactory.php +++ b/src/Behat/Behat/Output/ServiceContainer/Formatter/JUnitFormatterFactory.php @@ -27,8 +27,8 @@ final class JUnitFormatterFactory implements FormatterFactory /* * Available services */ - const ROOT_LISTENER_ID = 'output.node.listener.junit'; - const RESULT_TO_STRING_CONVERTER_ID = 'output.node.printer.result_to_string'; + public const ROOT_LISTENER_ID = 'output.node.listener.junit'; + public const RESULT_TO_STRING_CONVERTER_ID = 'output.node.printer.result_to_string'; /** * {@inheritdoc} diff --git a/src/Behat/Behat/Output/ServiceContainer/Formatter/PrettyFormatterFactory.php b/src/Behat/Behat/Output/ServiceContainer/Formatter/PrettyFormatterFactory.php index 261b509a8..b2d266025 100644 --- a/src/Behat/Behat/Output/ServiceContainer/Formatter/PrettyFormatterFactory.php +++ b/src/Behat/Behat/Output/ServiceContainer/Formatter/PrettyFormatterFactory.php @@ -38,13 +38,13 @@ class PrettyFormatterFactory implements FormatterFactory /* * Available services */ - const ROOT_LISTENER_ID = 'output.node.listener.pretty'; - const RESULT_TO_STRING_CONVERTER_ID = 'output.node.printer.result_to_string'; + public const ROOT_LISTENER_ID = 'output.node.listener.pretty'; + public const RESULT_TO_STRING_CONVERTER_ID = 'output.node.printer.result_to_string'; /* * Available extension points */ - const ROOT_LISTENER_WRAPPER_TAG = 'output.node.listener.pretty.wrapper'; + public const ROOT_LISTENER_WRAPPER_TAG = 'output.node.listener.pretty.wrapper'; /** * Initializes extension. diff --git a/src/Behat/Behat/Output/ServiceContainer/Formatter/ProgressFormatterFactory.php b/src/Behat/Behat/Output/ServiceContainer/Formatter/ProgressFormatterFactory.php index e19acdc05..3e02154da 100644 --- a/src/Behat/Behat/Output/ServiceContainer/Formatter/ProgressFormatterFactory.php +++ b/src/Behat/Behat/Output/ServiceContainer/Formatter/ProgressFormatterFactory.php @@ -34,13 +34,13 @@ class ProgressFormatterFactory implements FormatterFactory /* * Available services */ - const ROOT_LISTENER_ID = 'output.node.listener.progress'; - const RESULT_TO_STRING_CONVERTER_ID = 'output.node.printer.result_to_string'; + public const ROOT_LISTENER_ID = 'output.node.listener.progress'; + public const RESULT_TO_STRING_CONVERTER_ID = 'output.node.printer.result_to_string'; /* * Available extension points */ - const ROOT_LISTENER_WRAPPER_TAG = 'output.node.listener.progress.wrapper'; + public const ROOT_LISTENER_WRAPPER_TAG = 'output.node.listener.progress.wrapper'; /** * Initializes extension. diff --git a/src/Behat/Behat/Snippet/ServiceContainer/SnippetExtension.php b/src/Behat/Behat/Snippet/ServiceContainer/SnippetExtension.php index 992c3716d..6c68821af 100644 --- a/src/Behat/Behat/Snippet/ServiceContainer/SnippetExtension.php +++ b/src/Behat/Behat/Snippet/ServiceContainer/SnippetExtension.php @@ -31,14 +31,14 @@ class SnippetExtension implements Extension /* * Available services */ - const REGISTRY_ID = 'snippet.registry'; - const WRITER_ID = 'snippet.writer'; + public const REGISTRY_ID = 'snippet.registry'; + public const WRITER_ID = 'snippet.writer'; /* * Available extension points */ - const GENERATOR_TAG = 'snippet.generator'; - const APPENDER_TAG = 'snippet.appender'; + public const GENERATOR_TAG = 'snippet.generator'; + public const APPENDER_TAG = 'snippet.appender'; /** * @var ServiceProcessor diff --git a/src/Behat/Behat/Tester/Result/StepResult.php b/src/Behat/Behat/Tester/Result/StepResult.php index 0a898c996..87cec353d 100644 --- a/src/Behat/Behat/Tester/Result/StepResult.php +++ b/src/Behat/Behat/Tester/Result/StepResult.php @@ -19,5 +19,5 @@ */ interface StepResult extends TestResult { - const UNDEFINED = 30; + public const UNDEFINED = 30; } diff --git a/src/Behat/Behat/Tester/ServiceContainer/TesterExtension.php b/src/Behat/Behat/Tester/ServiceContainer/TesterExtension.php index 394ee9317..e8ba129d1 100644 --- a/src/Behat/Behat/Tester/ServiceContainer/TesterExtension.php +++ b/src/Behat/Behat/Tester/ServiceContainer/TesterExtension.php @@ -33,20 +33,20 @@ class TesterExtension extends BaseExtension /* * Available services */ - const SCENARIO_TESTER_ID = 'tester.scenario'; - const OUTLINE_TESTER_ID = 'tester.outline'; - const EXAMPLE_TESTER_ID = 'tester.example'; - const BACKGROUND_TESTER_ID = 'tester.background'; - const STEP_TESTER_ID = 'tester.step'; + public const SCENARIO_TESTER_ID = 'tester.scenario'; + public const OUTLINE_TESTER_ID = 'tester.outline'; + public const EXAMPLE_TESTER_ID = 'tester.example'; + public const BACKGROUND_TESTER_ID = 'tester.background'; + public const STEP_TESTER_ID = 'tester.step'; /** * Available extension points */ - const SCENARIO_TESTER_WRAPPER_TAG = 'tester.scenario.wrapper'; - const OUTLINE_TESTER_WRAPPER_TAG = 'tester.outline.wrapper'; - const EXAMPLE_TESTER_WRAPPER_TAG = 'tester.example.wrapper'; - const BACKGROUND_TESTER_WRAPPER_TAG = 'tester.background.wrapper'; - const STEP_TESTER_WRAPPER_TAG = 'tester.step.wrapper'; + public const SCENARIO_TESTER_WRAPPER_TAG = 'tester.scenario.wrapper'; + public const OUTLINE_TESTER_WRAPPER_TAG = 'tester.outline.wrapper'; + public const EXAMPLE_TESTER_WRAPPER_TAG = 'tester.example.wrapper'; + public const BACKGROUND_TESTER_WRAPPER_TAG = 'tester.background.wrapper'; + public const STEP_TESTER_WRAPPER_TAG = 'tester.step.wrapper'; /** * @var ServiceProcessor diff --git a/src/Behat/Behat/Transformation/ServiceContainer/TransformationExtension.php b/src/Behat/Behat/Transformation/ServiceContainer/TransformationExtension.php index f322ee926..acbb15967 100644 --- a/src/Behat/Behat/Transformation/ServiceContainer/TransformationExtension.php +++ b/src/Behat/Behat/Transformation/ServiceContainer/TransformationExtension.php @@ -33,12 +33,12 @@ class TransformationExtension implements Extension /* * Available services */ - const REPOSITORY_ID = 'transformation.repository'; + public const REPOSITORY_ID = 'transformation.repository'; /* * Available extension points */ - const ARGUMENT_TRANSFORMER_TAG = 'transformation.argument_transformer'; + public const ARGUMENT_TRANSFORMER_TAG = 'transformation.argument_transformer'; /** * @var ServiceProcessor diff --git a/src/Behat/Behat/Transformation/Transformation/ColumnBasedTableTransformation.php b/src/Behat/Behat/Transformation/Transformation/ColumnBasedTableTransformation.php index 1c8cc0ec3..c26df56d2 100644 --- a/src/Behat/Behat/Transformation/Transformation/ColumnBasedTableTransformation.php +++ b/src/Behat/Behat/Transformation/Transformation/ColumnBasedTableTransformation.php @@ -25,7 +25,7 @@ */ final class ColumnBasedTableTransformation extends RuntimeCallee implements SimpleArgumentTransformation { - const PATTERN_REGEX = '/^table\:(?:\*|[[:print:]]+)$/'; + public const PATTERN_REGEX = '/^table\:(?:\*|[[:print:]]+)$/'; /** * @var string diff --git a/src/Behat/Behat/Transformation/Transformation/RowBasedTableTransformation.php b/src/Behat/Behat/Transformation/Transformation/RowBasedTableTransformation.php index 61389834d..a5b1c5123 100644 --- a/src/Behat/Behat/Transformation/Transformation/RowBasedTableTransformation.php +++ b/src/Behat/Behat/Transformation/Transformation/RowBasedTableTransformation.php @@ -26,7 +26,7 @@ */ final class RowBasedTableTransformation extends RuntimeCallee implements SimpleArgumentTransformation { - const PATTERN_REGEX = '/^rowtable\:[[:print:]]+$/'; + public const PATTERN_REGEX = '/^rowtable\:[[:print:]]+$/'; /** * @var string diff --git a/src/Behat/Behat/Transformation/Transformation/TableRowTransformation.php b/src/Behat/Behat/Transformation/Transformation/TableRowTransformation.php index 571f1f0cd..1a71c0b7b 100644 --- a/src/Behat/Behat/Transformation/Transformation/TableRowTransformation.php +++ b/src/Behat/Behat/Transformation/Transformation/TableRowTransformation.php @@ -25,7 +25,7 @@ */ final class TableRowTransformation extends RuntimeCallee implements SimpleArgumentTransformation { - const PATTERN_REGEX = '/^row\:[[:print:]]+$/'; + public const PATTERN_REGEX = '/^row\:[[:print:]]+$/'; /** * @var string diff --git a/src/Behat/Behat/Transformation/Transformation/TokenNameTransformation.php b/src/Behat/Behat/Transformation/Transformation/TokenNameTransformation.php index cd4f4ab0b..a64d86e64 100644 --- a/src/Behat/Behat/Transformation/Transformation/TokenNameTransformation.php +++ b/src/Behat/Behat/Transformation/Transformation/TokenNameTransformation.php @@ -24,7 +24,7 @@ */ final class TokenNameTransformation extends RuntimeCallee implements SimpleArgumentTransformation { - const PATTERN_REGEX = '/^\:\w+$/'; + public const PATTERN_REGEX = '/^\:\w+$/'; /** * @var string diff --git a/src/Behat/Testwork/Argument/ServiceContainer/ArgumentExtension.php b/src/Behat/Testwork/Argument/ServiceContainer/ArgumentExtension.php index 9aa5afeff..88172a979 100644 --- a/src/Behat/Testwork/Argument/ServiceContainer/ArgumentExtension.php +++ b/src/Behat/Testwork/Argument/ServiceContainer/ArgumentExtension.php @@ -27,9 +27,9 @@ final class ArgumentExtension implements Extension /* * Available services */ - const MIXED_ARGUMENT_ORGANISER_ID = 'argument.mixed_organiser'; - const PREG_MATCH_ARGUMENT_ORGANISER_ID = 'argument.preg_match_organiser'; - const CONSTRUCTOR_ARGUMENT_ORGANISER_ID = 'argument.constructor_organiser'; + public const MIXED_ARGUMENT_ORGANISER_ID = 'argument.mixed_organiser'; + public const PREG_MATCH_ARGUMENT_ORGANISER_ID = 'argument.preg_match_organiser'; + public const CONSTRUCTOR_ARGUMENT_ORGANISER_ID = 'argument.constructor_organiser'; /** * {@inheritdoc} diff --git a/src/Behat/Testwork/Autoloader/ServiceContainer/AutoloaderExtension.php b/src/Behat/Testwork/Autoloader/ServiceContainer/AutoloaderExtension.php index 40f0fa226..3908e0f15 100644 --- a/src/Behat/Testwork/Autoloader/ServiceContainer/AutoloaderExtension.php +++ b/src/Behat/Testwork/Autoloader/ServiceContainer/AutoloaderExtension.php @@ -28,7 +28,7 @@ final class AutoloaderExtension implements Extension /* * Available services */ - const CLASS_LOADER_ID = 'class_loader'; + public const CLASS_LOADER_ID = 'class_loader'; /** * @var array diff --git a/src/Behat/Testwork/Call/Handler/Exception/ClassNotFoundHandler.php b/src/Behat/Testwork/Call/Handler/Exception/ClassNotFoundHandler.php index 8d0f488fd..b63d0fed1 100644 --- a/src/Behat/Testwork/Call/Handler/Exception/ClassNotFoundHandler.php +++ b/src/Behat/Testwork/Call/Handler/Exception/ClassNotFoundHandler.php @@ -22,7 +22,7 @@ */ abstract class ClassNotFoundHandler implements ExceptionHandler { - const PATTERN = "/^Class '([^']+)' not found$/"; + public const PATTERN = "/^Class '([^']+)' not found$/"; /** * {@inheritdoc} diff --git a/src/Behat/Testwork/Call/Handler/Exception/MethodNotFoundHandler.php b/src/Behat/Testwork/Call/Handler/Exception/MethodNotFoundHandler.php index 3ca680dae..f35890999 100644 --- a/src/Behat/Testwork/Call/Handler/Exception/MethodNotFoundHandler.php +++ b/src/Behat/Testwork/Call/Handler/Exception/MethodNotFoundHandler.php @@ -22,7 +22,7 @@ */ abstract class MethodNotFoundHandler implements ExceptionHandler { - const PATTERN = '/^Call to undefined method ([^:]+)::([^\)]+)\(\)$/'; + public const PATTERN = '/^Call to undefined method ([^:]+)::([^\)]+)\(\)$/'; /** * {@inheritdoc} diff --git a/src/Behat/Testwork/Call/ServiceContainer/CallExtension.php b/src/Behat/Testwork/Call/ServiceContainer/CallExtension.php index b9df7ea22..81bf25825 100644 --- a/src/Behat/Testwork/Call/ServiceContainer/CallExtension.php +++ b/src/Behat/Testwork/Call/ServiceContainer/CallExtension.php @@ -27,15 +27,15 @@ final class CallExtension implements Extension /* * Available services */ - const CALL_CENTER_ID = 'call.center'; + public const CALL_CENTER_ID = 'call.center'; /* * Available extension points */ - const CALL_FILTER_TAG = 'call.call_filter'; - const CALL_HANDLER_TAG = 'call.call_handler'; - const RESULT_FILTER_TAG = 'call.result_filter'; - const EXCEPTION_HANDLER_TAG = 'call.exception_handler'; + public const CALL_FILTER_TAG = 'call.call_filter'; + public const CALL_HANDLER_TAG = 'call.call_handler'; + public const RESULT_FILTER_TAG = 'call.result_filter'; + public const EXCEPTION_HANDLER_TAG = 'call.exception_handler'; /** * @var ServiceProcessor diff --git a/src/Behat/Testwork/Cli/ServiceContainer/CliExtension.php b/src/Behat/Testwork/Cli/ServiceContainer/CliExtension.php index 352b2d6a6..faca4ce61 100644 --- a/src/Behat/Testwork/Cli/ServiceContainer/CliExtension.php +++ b/src/Behat/Testwork/Cli/ServiceContainer/CliExtension.php @@ -27,14 +27,14 @@ final class CliExtension implements Extension /* * Available services */ - const COMMAND_ID = 'cli.command'; - const INPUT_ID = 'cli.input'; - const OUTPUT_ID = 'cli.output'; + public const COMMAND_ID = 'cli.command'; + public const INPUT_ID = 'cli.input'; + public const OUTPUT_ID = 'cli.output'; /* * Available extension points */ - const CONTROLLER_TAG = 'cli.controller'; + public const CONTROLLER_TAG = 'cli.controller'; /** * @var ServiceProcessor diff --git a/src/Behat/Testwork/Environment/ServiceContainer/EnvironmentExtension.php b/src/Behat/Testwork/Environment/ServiceContainer/EnvironmentExtension.php index e06f058c7..389b36143 100644 --- a/src/Behat/Testwork/Environment/ServiceContainer/EnvironmentExtension.php +++ b/src/Behat/Testwork/Environment/ServiceContainer/EnvironmentExtension.php @@ -29,13 +29,13 @@ final class EnvironmentExtension implements Extension /* * Available services */ - const MANAGER_ID = 'environment.manager'; + public const MANAGER_ID = 'environment.manager'; /* * Available extension points */ - const HANDLER_TAG = 'environment.handler'; - const READER_TAG = 'environment.reader'; + public const HANDLER_TAG = 'environment.handler'; + public const READER_TAG = 'environment.reader'; /** * @var ServiceProcessor diff --git a/src/Behat/Testwork/EventDispatcher/Event/ExerciseCompleted.php b/src/Behat/Testwork/EventDispatcher/Event/ExerciseCompleted.php index ebd076393..4a88dfbff 100644 --- a/src/Behat/Testwork/EventDispatcher/Event/ExerciseCompleted.php +++ b/src/Behat/Testwork/EventDispatcher/Event/ExerciseCompleted.php @@ -21,10 +21,10 @@ */ abstract class ExerciseCompleted extends Event { - const BEFORE = 'tester.exercise_completed.before'; - const AFTER_SETUP = 'tester.exercise_completed.after_setup'; - const BEFORE_TEARDOWN = 'tester.exercise_completed.before_teardown'; - const AFTER = 'tester.exercise_completed.after'; + public const BEFORE = 'tester.exercise_completed.before'; + public const AFTER_SETUP = 'tester.exercise_completed.after_setup'; + public const BEFORE_TEARDOWN = 'tester.exercise_completed.before_teardown'; + public const AFTER = 'tester.exercise_completed.after'; /** * Returns specification iterators. diff --git a/src/Behat/Testwork/EventDispatcher/Event/SuiteTested.php b/src/Behat/Testwork/EventDispatcher/Event/SuiteTested.php index 2ded66a28..de56d077b 100644 --- a/src/Behat/Testwork/EventDispatcher/Event/SuiteTested.php +++ b/src/Behat/Testwork/EventDispatcher/Event/SuiteTested.php @@ -19,10 +19,10 @@ */ abstract class SuiteTested extends LifecycleEvent { - const BEFORE = 'tester.suite_tested.before'; - const AFTER_SETUP = 'tester.suite_tested.after_setup'; - const BEFORE_TEARDOWN = 'tester.suite_tested.before_teardown'; - const AFTER = 'tester.suite_tested.after'; + public const BEFORE = 'tester.suite_tested.before'; + public const AFTER_SETUP = 'tester.suite_tested.after_setup'; + public const BEFORE_TEARDOWN = 'tester.suite_tested.before_teardown'; + public const AFTER = 'tester.suite_tested.after'; /** * Returns specification iterator. diff --git a/src/Behat/Testwork/EventDispatcher/ServiceContainer/EventDispatcherExtension.php b/src/Behat/Testwork/EventDispatcher/ServiceContainer/EventDispatcherExtension.php index 72376dac5..502740a5f 100644 --- a/src/Behat/Testwork/EventDispatcher/ServiceContainer/EventDispatcherExtension.php +++ b/src/Behat/Testwork/EventDispatcher/ServiceContainer/EventDispatcherExtension.php @@ -30,12 +30,12 @@ class EventDispatcherExtension implements Extension /* * Available services */ - const DISPATCHER_ID = 'event_dispatcher'; + public const DISPATCHER_ID = 'event_dispatcher'; /* * Available extension points */ - const SUBSCRIBER_TAG = 'event_dispatcher.subscriber'; + public const SUBSCRIBER_TAG = 'event_dispatcher.subscriber'; /** * @var ServiceProcessor diff --git a/src/Behat/Testwork/EventDispatcher/TestworkEventDispatcher.php b/src/Behat/Testwork/EventDispatcher/TestworkEventDispatcher.php index 8c1e928a0..8802dc6c9 100644 --- a/src/Behat/Testwork/EventDispatcher/TestworkEventDispatcher.php +++ b/src/Behat/Testwork/EventDispatcher/TestworkEventDispatcher.php @@ -58,9 +58,9 @@ final class TestworkEventDispatcher { // These constant definitions are required to prevent scrutinizer failing static analysis - const BEFORE_ALL_EVENTS = '*~'; - const AFTER_ALL_EVENTS = '~*'; - const DISPATCHER_VERSION = 'undefined'; + public const BEFORE_ALL_EVENTS = '*~'; + public const AFTER_ALL_EVENTS = '~*'; + public const DISPATCHER_VERSION = 'undefined'; } } diff --git a/src/Behat/Testwork/EventDispatcher/TestworkEventDispatcherSymfony5.php b/src/Behat/Testwork/EventDispatcher/TestworkEventDispatcherSymfony5.php index 42da5ce54..e7a38c09a 100644 --- a/src/Behat/Testwork/EventDispatcher/TestworkEventDispatcherSymfony5.php +++ b/src/Behat/Testwork/EventDispatcher/TestworkEventDispatcherSymfony5.php @@ -16,9 +16,9 @@ */ final class TestworkEventDispatcherSymfony5 extends EventDispatcher { - const BEFORE_ALL_EVENTS = '*~'; - const AFTER_ALL_EVENTS = '~*'; - const DISPATCHER_VERSION = 2; + public const BEFORE_ALL_EVENTS = '*~'; + public const AFTER_ALL_EVENTS = '~*'; + public const DISPATCHER_VERSION = 2; /** * {@inheritdoc} diff --git a/src/Behat/Testwork/EventDispatcher/TestworkEventDispatcherSymfonyLegacy.php b/src/Behat/Testwork/EventDispatcher/TestworkEventDispatcherSymfonyLegacy.php index 475fc4d00..0e25f29d8 100644 --- a/src/Behat/Testwork/EventDispatcher/TestworkEventDispatcherSymfonyLegacy.php +++ b/src/Behat/Testwork/EventDispatcher/TestworkEventDispatcherSymfonyLegacy.php @@ -16,9 +16,9 @@ */ final class TestworkEventDispatcherSymfonyLegacy extends EventDispatcher { - const BEFORE_ALL_EVENTS = '*~'; - const AFTER_ALL_EVENTS = '~*'; - const DISPATCHER_VERSION = 1; + public const BEFORE_ALL_EVENTS = '*~'; + public const AFTER_ALL_EVENTS = '~*'; + public const DISPATCHER_VERSION = 1; /** * {@inheritdoc} diff --git a/src/Behat/Testwork/Exception/ServiceContainer/ExceptionExtension.php b/src/Behat/Testwork/Exception/ServiceContainer/ExceptionExtension.php index ac89715e5..92ae6afee 100644 --- a/src/Behat/Testwork/Exception/ServiceContainer/ExceptionExtension.php +++ b/src/Behat/Testwork/Exception/ServiceContainer/ExceptionExtension.php @@ -30,12 +30,12 @@ final class ExceptionExtension implements Extension /* * Available services */ - const PRESENTER_ID = 'exception.presenter'; + public const PRESENTER_ID = 'exception.presenter'; /* * Available extension points */ - const STRINGER_TAG = 'exception.stringer'; + public const STRINGER_TAG = 'exception.stringer'; /** * @var ServiceProcessor diff --git a/src/Behat/Testwork/Filesystem/ServiceContainer/FilesystemExtension.php b/src/Behat/Testwork/Filesystem/ServiceContainer/FilesystemExtension.php index 4fdc537ca..0d668ff11 100644 --- a/src/Behat/Testwork/Filesystem/ServiceContainer/FilesystemExtension.php +++ b/src/Behat/Testwork/Filesystem/ServiceContainer/FilesystemExtension.php @@ -28,7 +28,7 @@ final class FilesystemExtension implements Extension /* * Available services */ - const LOGGER_ID = 'filesystem.logger'; + public const LOGGER_ID = 'filesystem.logger'; /** * {@inheritdoc} diff --git a/src/Behat/Testwork/Hook/Scope/SuiteScope.php b/src/Behat/Testwork/Hook/Scope/SuiteScope.php index 6cc308f00..659a8f6cd 100644 --- a/src/Behat/Testwork/Hook/Scope/SuiteScope.php +++ b/src/Behat/Testwork/Hook/Scope/SuiteScope.php @@ -19,8 +19,8 @@ */ interface SuiteScope extends HookScope { - const BEFORE = 'suite.before'; - const AFTER = 'suite.after'; + public const BEFORE = 'suite.before'; + public const AFTER = 'suite.after'; /** * Returns specification iterator. diff --git a/src/Behat/Testwork/Hook/ServiceContainer/HookExtension.php b/src/Behat/Testwork/Hook/ServiceContainer/HookExtension.php index fee6de4d4..9697c98e5 100644 --- a/src/Behat/Testwork/Hook/ServiceContainer/HookExtension.php +++ b/src/Behat/Testwork/Hook/ServiceContainer/HookExtension.php @@ -30,8 +30,8 @@ class HookExtension implements Extension /* * Available services */ - const DISPATCHER_ID = 'hook.dispatcher'; - const REPOSITORY_ID = 'hook.repository'; + public const DISPATCHER_ID = 'hook.dispatcher'; + public const REPOSITORY_ID = 'hook.repository'; /** * {@inheritdoc} diff --git a/src/Behat/Testwork/Ordering/ServiceContainer/OrderingExtension.php b/src/Behat/Testwork/Ordering/ServiceContainer/OrderingExtension.php index 2a9d5a7fa..329227330 100644 --- a/src/Behat/Testwork/Ordering/ServiceContainer/OrderingExtension.php +++ b/src/Behat/Testwork/Ordering/ServiceContainer/OrderingExtension.php @@ -28,7 +28,7 @@ */ final class OrderingExtension implements Extension { - const ORDERER_TAG = 'tester.orderer'; + public const ORDERER_TAG = 'tester.orderer'; /** * @var ServiceProcessor diff --git a/src/Behat/Testwork/Output/Printer/Factory/OutputFactory.php b/src/Behat/Testwork/Output/Printer/Factory/OutputFactory.php index 6571555ee..99bd7c11d 100644 --- a/src/Behat/Testwork/Output/Printer/Factory/OutputFactory.php +++ b/src/Behat/Testwork/Output/Printer/Factory/OutputFactory.php @@ -18,10 +18,10 @@ */ abstract class OutputFactory { - const VERBOSITY_NORMAL = 1; - const VERBOSITY_VERBOSE = 2; - const VERBOSITY_VERY_VERBOSE = 3; - const VERBOSITY_DEBUG = 4; + public const VERBOSITY_NORMAL = 1; + public const VERBOSITY_VERBOSE = 2; + public const VERBOSITY_VERY_VERBOSE = 3; + public const VERBOSITY_DEBUG = 4; /** * @var null|string diff --git a/src/Behat/Testwork/Output/Printer/JUnitOutputPrinter.php b/src/Behat/Testwork/Output/Printer/JUnitOutputPrinter.php index fa2308553..edb6f3ae6 100644 --- a/src/Behat/Testwork/Output/Printer/JUnitOutputPrinter.php +++ b/src/Behat/Testwork/Output/Printer/JUnitOutputPrinter.php @@ -23,8 +23,8 @@ */ final class JUnitOutputPrinter extends StreamOutputPrinter { - const XML_VERSION = '1.0'; - const XML_ENCODING = 'UTF-8'; + public const XML_VERSION = '1.0'; + public const XML_ENCODING = 'UTF-8'; /** * @var \DOMDocument diff --git a/src/Behat/Testwork/Output/Printer/OutputPrinter.php b/src/Behat/Testwork/Output/Printer/OutputPrinter.php index 56fe45793..fc6452a8f 100644 --- a/src/Behat/Testwork/Output/Printer/OutputPrinter.php +++ b/src/Behat/Testwork/Output/Printer/OutputPrinter.php @@ -20,19 +20,19 @@ interface OutputPrinter /** * @deprecated since 3.1, to be removed in 4.0 */ - const VERBOSITY_NORMAL = 1; + public const VERBOSITY_NORMAL = 1; /** * @deprecated since 3.1, to be removed in 4.0 */ - const VERBOSITY_VERBOSE = 2; + public const VERBOSITY_VERBOSE = 2; /** * @deprecated since 3.1, to be removed in 4.0 */ - const VERBOSITY_VERY_VERBOSE = 3; + public const VERBOSITY_VERY_VERBOSE = 3; /** * @deprecated since 3.1, to be removed in 4.0 */ - const VERBOSITY_DEBUG = 4; + public const VERBOSITY_DEBUG = 4; /** * Sets output path. diff --git a/src/Behat/Testwork/Output/ServiceContainer/OutputExtension.php b/src/Behat/Testwork/Output/ServiceContainer/OutputExtension.php index f49babe97..dff83fde1 100644 --- a/src/Behat/Testwork/Output/ServiceContainer/OutputExtension.php +++ b/src/Behat/Testwork/Output/ServiceContainer/OutputExtension.php @@ -31,12 +31,12 @@ final class OutputExtension implements Extension /* * Available services */ - const MANAGER_ID = 'output.manager'; + public const MANAGER_ID = 'output.manager'; /* * Available extension points */ - const FORMATTER_TAG = 'output.formatter'; + public const FORMATTER_TAG = 'output.formatter'; /** * @var string diff --git a/src/Behat/Testwork/Specification/ServiceContainer/SpecificationExtension.php b/src/Behat/Testwork/Specification/ServiceContainer/SpecificationExtension.php index 03ca52de7..d369d458c 100644 --- a/src/Behat/Testwork/Specification/ServiceContainer/SpecificationExtension.php +++ b/src/Behat/Testwork/Specification/ServiceContainer/SpecificationExtension.php @@ -27,12 +27,12 @@ final class SpecificationExtension implements Extension /* * Available services */ - const FINDER_ID = 'specifications.finder'; + public const FINDER_ID = 'specifications.finder'; /* * Available extension points */ - const LOCATOR_TAG = 'specifications.locator'; + public const LOCATOR_TAG = 'specifications.locator'; /** * @var ServiceProcessor diff --git a/src/Behat/Testwork/Suite/ServiceContainer/SuiteExtension.php b/src/Behat/Testwork/Suite/ServiceContainer/SuiteExtension.php index 79fbcda84..94d5b56e7 100644 --- a/src/Behat/Testwork/Suite/ServiceContainer/SuiteExtension.php +++ b/src/Behat/Testwork/Suite/ServiceContainer/SuiteExtension.php @@ -29,14 +29,14 @@ final class SuiteExtension implements Extension /* * Available services */ - const REGISTRY_ID = 'suite.registry'; - const BOOTSTRAPPER_ID = 'suite.bootstrapper'; + public const REGISTRY_ID = 'suite.registry'; + public const BOOTSTRAPPER_ID = 'suite.bootstrapper'; /* * Available extension points */ - const GENERATOR_TAG = 'suite.generator'; - const SETUP_TAG = 'suite.setup'; + public const GENERATOR_TAG = 'suite.generator'; + public const SETUP_TAG = 'suite.setup'; /** * @var ServiceProcessor diff --git a/src/Behat/Testwork/Tester/Result/TestResult.php b/src/Behat/Testwork/Tester/Result/TestResult.php index 77281b785..7c3df6ffe 100644 --- a/src/Behat/Testwork/Tester/Result/TestResult.php +++ b/src/Behat/Testwork/Tester/Result/TestResult.php @@ -17,10 +17,10 @@ */ interface TestResult { - const PASSED = 0; - const SKIPPED = 10; - const PENDING = 20; - const FAILED = 99; + public const PASSED = 0; + public const SKIPPED = 10; + public const PENDING = 20; + public const FAILED = 99; /** * Checks that test has passed. diff --git a/src/Behat/Testwork/Tester/Result/TestResults.php b/src/Behat/Testwork/Tester/Result/TestResults.php index 5102f3747..1bd8516e6 100644 --- a/src/Behat/Testwork/Tester/Result/TestResults.php +++ b/src/Behat/Testwork/Tester/Result/TestResults.php @@ -21,7 +21,7 @@ */ final class TestResults implements TestResult, Countable, IteratorAggregate { - const NO_TESTS = -100; + public const NO_TESTS = -100; /** * @var TestResult[] diff --git a/src/Behat/Testwork/Tester/ServiceContainer/TesterExtension.php b/src/Behat/Testwork/Tester/ServiceContainer/TesterExtension.php index 85509d5d3..8892992ce 100644 --- a/src/Behat/Testwork/Tester/ServiceContainer/TesterExtension.php +++ b/src/Behat/Testwork/Tester/ServiceContainer/TesterExtension.php @@ -32,18 +32,18 @@ abstract class TesterExtension implements Extension /* * Available services */ - const EXERCISE_ID = 'tester.exercise'; - const SUITE_TESTER_ID = 'tester.suite'; - const SPECIFICATION_TESTER_ID = 'tester.specification'; - const RESULT_INTERPRETER_ID = 'tester.result.interpreter'; + public const EXERCISE_ID = 'tester.exercise'; + public const SUITE_TESTER_ID = 'tester.suite'; + public const SPECIFICATION_TESTER_ID = 'tester.specification'; + public const RESULT_INTERPRETER_ID = 'tester.result.interpreter'; /** * Available extension points */ - const EXERCISE_WRAPPER_TAG = 'tester.exercise.wrapper'; - const SUITE_TESTER_WRAPPER_TAG = 'tester.suite.wrapper'; - const SPECIFICATION_TESTER_WRAPPER_TAG = 'tester.specification.wrapper'; - const RESULT_INTERPRETATION_TAG = 'test.result.interpretation'; + public const EXERCISE_WRAPPER_TAG = 'tester.exercise.wrapper'; + public const SUITE_TESTER_WRAPPER_TAG = 'tester.suite.wrapper'; + public const SPECIFICATION_TESTER_WRAPPER_TAG = 'tester.specification.wrapper'; + public const RESULT_INTERPRETATION_TAG = 'test.result.interpretation'; /** * @var ServiceProcessor diff --git a/src/Behat/Testwork/Translator/ServiceContainer/TranslatorExtension.php b/src/Behat/Testwork/Translator/ServiceContainer/TranslatorExtension.php index b6e06184e..5fc53f0b9 100644 --- a/src/Behat/Testwork/Translator/ServiceContainer/TranslatorExtension.php +++ b/src/Behat/Testwork/Translator/ServiceContainer/TranslatorExtension.php @@ -28,7 +28,7 @@ final class TranslatorExtension implements Extension /* * Available services */ - const TRANSLATOR_ID = 'translator'; + public const TRANSLATOR_ID = 'translator'; /** * {@inheritdoc} From 55a59891322316b67283f0501fd67b60066227d3 Mon Sep 17 00:00:00 2001 From: Remon van de Kamp Date: Fri, 19 Jun 2020 11:11:49 +0200 Subject: [PATCH 222/567] Use scalar expressions in const instead of methods This was introduced in PHP 5.6 and since this package now supports PHP >= 7.2 only we are able to use it. --- .../ServiceContainer/ContextExtension.php | 65 +++++-------------- .../TransformationExtension.php | 12 +++- 2 files changed, 24 insertions(+), 53 deletions(-) diff --git a/src/Behat/Behat/Context/ServiceContainer/ContextExtension.php b/src/Behat/Behat/Context/ServiceContainer/ContextExtension.php index 1da6fdc3a..1aa833600 100644 --- a/src/Behat/Behat/Context/ServiceContainer/ContextExtension.php +++ b/src/Behat/Behat/Context/ServiceContainer/ContextExtension.php @@ -42,6 +42,11 @@ final class ContextExtension implements Extension public const FACTORY_ID = 'context.factory'; public const CONTEXT_SNIPPET_GENERATOR_ID = 'snippet.generator.context'; public const AGGREGATE_RESOLVER_FACTORY_ID = 'context.argument.aggregate_resolver_factory'; + private const ENVIRONMENT_HANDLER_ID = EnvironmentExtension::HANDLER_TAG . '.context'; + private const ENVIRONMENT_READER_ID = EnvironmentExtension::READER_TAG . '.context'; + private const SUITE_SETUP_ID = SuiteExtension::SETUP_TAG . '.suite_with_contexts'; + private const ANNOTATED_CONTEXT_READER_ID = self::READER_TAG . '.annotated'; + /* * Available extension points @@ -158,7 +163,7 @@ private function loadEnvironmentHandler(ContainerBuilder $container) new Reference(self::AGGREGATE_RESOLVER_FACTORY_ID) )); $definition->addTag(EnvironmentExtension::HANDLER_TAG, array('priority' => 50)); - $container->setDefinition(self::getEnvironmentHandlerId(), $definition); + $container->setDefinition(self::ENVIRONMENT_HANDLER_ID, $definition); } /** @@ -170,7 +175,7 @@ private function loadEnvironmentReader(ContainerBuilder $container) { $definition = new Definition('Behat\Behat\Context\Environment\Reader\ContextEnvironmentReader'); $definition->addTag(EnvironmentExtension::READER_TAG, array('priority' => 50)); - $container->setDefinition(self::getEnvironmentReaderId(), $definition); + $container->setDefinition(self::ENVIRONMENT_READER_ID, $definition); } /** @@ -185,7 +190,7 @@ private function loadSuiteSetup(ContainerBuilder $container) new Reference(FilesystemExtension::LOGGER_ID) )); $definition->addTag(SuiteExtension::SETUP_TAG, array('priority' => 20)); - $container->setDefinition(self::getSuiteSetupId(), $definition); + $container->setDefinition(self::SUITE_SETUP_ID, $definition); } /** @@ -249,13 +254,13 @@ private function loadDefaultClassGenerators(ContainerBuilder $container) private function loadDefaultContextReaders(ContainerBuilder $container) { $definition = new Definition('Behat\Behat\Context\Reader\AnnotatedContextReader'); - $container->setDefinition(self::getAnnotatedContextReaderId(), $definition); + $container->setDefinition(self::ANNOTATED_CONTEXT_READER_ID, $definition); $definition = new Definition('Behat\Behat\Context\Reader\ContextReaderCachedPerContext', array( - new Reference(self::getAnnotatedContextReaderId()) + new Reference(self::ANNOTATED_CONTEXT_READER_ID) )); $definition->addTag(self::READER_TAG, array('priority' => 50)); - $container->setDefinition(self::getAnnotatedContextReaderId() . '.cached', $definition); + $container->setDefinition(self::ANNOTATED_CONTEXT_READER_ID . '.cached', $definition); $definition = new Definition('Behat\Behat\Context\Reader\TranslatableContextReader', array( new Reference(TranslatorExtension::TRANSLATOR_ID) @@ -277,7 +282,7 @@ private function loadDefaultContextReaders(ContainerBuilder $container) private function processClassResolvers(ContainerBuilder $container) { $references = $this->processor->findAndSortTaggedServices($container, self::CLASS_RESOLVER_TAG); - $definition = $container->getDefinition(self::getEnvironmentHandlerId()); + $definition = $container->getDefinition(self::ENVIRONMENT_HANDLER_ID); foreach ($references as $reference) { $definition->addMethodCall('registerClassResolver', array($reference)); @@ -337,7 +342,7 @@ private function processContextInitializers(ContainerBuilder $container) private function processContextReaders(ContainerBuilder $container) { $references = $this->processor->findAndSortTaggedServices($container, self::READER_TAG); - $definition = $container->getDefinition(self::getEnvironmentReaderId()); + $definition = $container->getDefinition(self::ENVIRONMENT_READER_ID); foreach ($references as $reference) { $definition->addMethodCall('registerContextReader', array($reference)); @@ -352,7 +357,7 @@ private function processContextReaders(ContainerBuilder $container) private function processClassGenerators(ContainerBuilder $container) { $references = $this->processor->findAndSortTaggedServices($container, self::CLASS_GENERATOR_TAG); - $definition = $container->getDefinition(self::getSuiteSetupId()); + $definition = $container->getDefinition(self::SUITE_SETUP_ID); foreach ($references as $reference) { $definition->addMethodCall('registerClassGenerator', array($reference)); @@ -367,50 +372,10 @@ private function processClassGenerators(ContainerBuilder $container) private function processAnnotationReaders(ContainerBuilder $container) { $references = $this->processor->findAndSortTaggedServices($container, self::ANNOTATION_READER_TAG); - $definition = $container->getDefinition(self::getAnnotatedContextReaderId()); + $definition = $container->getDefinition(self::ANNOTATED_CONTEXT_READER_ID); foreach ($references as $reference) { $definition->addMethodCall('registerAnnotationReader', array($reference)); } } - - /** - * Returns context environment handler service id. - * - * @return string - */ - private static function getEnvironmentHandlerId() - { - return EnvironmentExtension::HANDLER_TAG . '.context'; - } - - /** - * Returns context environment reader id. - * - * @return string - */ - private static function getEnvironmentReaderId() - { - return EnvironmentExtension::READER_TAG . '.context'; - } - - /** - * Returns context suite setup id. - * - * @return string - */ - private static function getSuiteSetupId() - { - return SuiteExtension::SETUP_TAG . '.suite_with_contexts'; - } - - /** - * Returns annotated context reader id. - * - * @return string - */ - private static function getAnnotatedContextReaderId() - { - return self::READER_TAG . '.annotated'; - } } diff --git a/src/Behat/Behat/Transformation/ServiceContainer/TransformationExtension.php b/src/Behat/Behat/Transformation/ServiceContainer/TransformationExtension.php index acbb15967..9c767b90e 100644 --- a/src/Behat/Behat/Transformation/ServiceContainer/TransformationExtension.php +++ b/src/Behat/Behat/Transformation/ServiceContainer/TransformationExtension.php @@ -40,6 +40,8 @@ class TransformationExtension implements Extension */ public const ARGUMENT_TRANSFORMER_TAG = 'transformation.argument_transformer'; + protected const DEFINITION_ARGUMENT_TRANSFORMER_ID = CallExtension::CALL_FILTER_TAG . '.definition_argument_transformer'; + /** * @var ServiceProcessor */ @@ -105,7 +107,7 @@ protected function loadDefinitionArgumentsTransformer(ContainerBuilder $containe { $definition = new Definition('Behat\Behat\Transformation\Call\Filter\DefinitionArgumentsTransformer'); $definition->addTag(CallExtension::CALL_FILTER_TAG, array('priority' => 200)); - $container->setDefinition($this->getDefinitionArgumentTransformerId(), $definition); + $container->setDefinition(self::DEFINITION_ARGUMENT_TRANSFORMER_ID, $definition); } /** @@ -158,7 +160,7 @@ protected function loadRepository(ContainerBuilder $container) protected function processArgumentsTransformers(ContainerBuilder $container) { $references = $this->processor->findAndSortTaggedServices($container, self::ARGUMENT_TRANSFORMER_TAG); - $definition = $container->getDefinition($this->getDefinitionArgumentTransformerId()); + $definition = $container->getDefinition(self::DEFINITION_ARGUMENT_TRANSFORMER_ID); foreach ($references as $reference) { $definition->addMethodCall('registerArgumentTransformer', array($reference)); @@ -169,9 +171,13 @@ protected function processArgumentsTransformers(ContainerBuilder $container) * Returns definition argument transformer service id. * * @return string + * + * @deprecated Use DEFINITION_ARGUMENT_TRANSFORMER_ID constant instead + * + * @todo Remove method in next major version */ protected function getDefinitionArgumentTransformerId() { - return CallExtension::CALL_FILTER_TAG . '.definition_argument_transformer'; + return self::DEFINITION_ARGUMENT_TRANSFORMER_ID; } } From d96dd39ad20a8d0dcfdb4c5162f163bfdf80f160 Mon Sep 17 00:00:00 2001 From: Remon van de Kamp Date: Fri, 19 Jun 2020 11:27:16 +0200 Subject: [PATCH 223/567] Use argument unpacking instead of call_user_func_array This was introduced in PHP 5.6 and can be used now that this package no longer supports PHP < 7.2 --- features/error_reporting.feature | 1 - src/Behat/Behat/Snippet/AggregateSnippet.php | 5 ++--- src/Behat/Testwork/Argument/MixedArgumentOrganiser.php | 2 +- src/Behat/Testwork/Call/Handler/RuntimeCallHandler.php | 2 +- 4 files changed, 4 insertions(+), 6 deletions(-) diff --git a/features/error_reporting.feature b/features/error_reporting.feature index 5900b7ff1..578ece4a5 100644 --- a/features/error_reporting.feature +++ b/features/error_reporting.feature @@ -132,7 +132,6 @@ Feature: Error Reporting When an exception is thrown # features/exception_in_scenario.feature:7 Exception: Exception is thrown in features/bootstrap/FeatureContext.php:56 Stack trace: - #0 [internal function]: FeatureContext->anExceptionIsThrown() 1 scenario (1 failed) 1 step (1 failed) diff --git a/src/Behat/Behat/Snippet/AggregateSnippet.php b/src/Behat/Behat/Snippet/AggregateSnippet.php index cbadc0566..c63e8f1d7 100644 --- a/src/Behat/Behat/Snippet/AggregateSnippet.php +++ b/src/Behat/Behat/Snippet/AggregateSnippet.php @@ -112,9 +112,8 @@ public function getUsedClasses() } return array_unique( - call_user_func_array( - 'array_merge', - array_map( + array_merge( + ...array_map( function (Snippet $snippet) { if (!$snippet instanceof ContextSnippet) { return array(); diff --git a/src/Behat/Testwork/Argument/MixedArgumentOrganiser.php b/src/Behat/Testwork/Argument/MixedArgumentOrganiser.php index 6acea5fdd..1210ccbcd 100644 --- a/src/Behat/Testwork/Argument/MixedArgumentOrganiser.php +++ b/src/Behat/Testwork/Argument/MixedArgumentOrganiser.php @@ -283,7 +283,7 @@ public function matchParameterToCandidateUsingPredicate( $predicate ) { foreach ($candidates as $candidateIndex => $candidate) { - if (call_user_func_array($predicate, array($parameter->getClass(), $candidate))) { + if ($predicate($parameter->getClass(), $candidate)) { $num = $parameter->getPosition(); $arguments[$num] = $candidate; diff --git a/src/Behat/Testwork/Call/Handler/RuntimeCallHandler.php b/src/Behat/Testwork/Call/Handler/RuntimeCallHandler.php index 7db716556..097273c21 100644 --- a/src/Behat/Testwork/Call/Handler/RuntimeCallHandler.php +++ b/src/Behat/Testwork/Call/Handler/RuntimeCallHandler.php @@ -106,7 +106,7 @@ private function executeCall(Call $call) try { $this->validator->validateArguments($reflection, $arguments); - $return = call_user_func_array($callable, $arguments); + $return = $callable(...array_values($arguments)); } catch (Exception $caught) { $exception = $caught; } From d93ca113ab108effdf157a159e54ec50fc3a740c Mon Sep 17 00:00:00 2001 From: Remon van de Kamp Date: Fri, 19 Jun 2020 11:35:47 +0200 Subject: [PATCH 224/567] Use Null coalescing operator This was introduced in PHP 7.0 and can be used now that this package no longer supports PHP < 7.2 --- .../Context/Snippet/Generator/ContextSnippetGenerator.php | 2 +- .../Behat/Definition/Pattern/Policy/RegexPatternPolicy.php | 2 +- src/Behat/Behat/HelperContainer/BuiltInServiceContainer.php | 2 +- .../Behat/Hook/Context/Annotation/HookAnnotationReader.php | 2 +- src/Behat/Testwork/Call/Exception/CallErrorException.php | 2 +- src/Behat/Testwork/Output/NodeEventListeningFormatter.php | 2 +- src/Behat/Testwork/ServiceContainer/ExtensionManager.php | 2 +- src/Behat/Testwork/Suite/ServiceContainer/SuiteExtension.php | 4 +--- 8 files changed, 8 insertions(+), 10 deletions(-) diff --git a/src/Behat/Behat/Context/Snippet/Generator/ContextSnippetGenerator.php b/src/Behat/Behat/Context/Snippet/Generator/ContextSnippetGenerator.php index edb2227f5..2373220a7 100644 --- a/src/Behat/Behat/Context/Snippet/Generator/ContextSnippetGenerator.php +++ b/src/Behat/Behat/Context/Snippet/Generator/ContextSnippetGenerator.php @@ -324,7 +324,7 @@ private function getMethodNameNotProposedEarlier($contextClass, $stepPattern, $n */ private function getAlreadyProposedMethods($contextClass) { - return isset(self::$proposedMethods[$contextClass]) ? self::$proposedMethods[$contextClass] : array(); + return self::$proposedMethods[$contextClass] ?? array(); } /** diff --git a/src/Behat/Behat/Definition/Pattern/Policy/RegexPatternPolicy.php b/src/Behat/Behat/Definition/Pattern/Policy/RegexPatternPolicy.php index 6ea50a277..76498b91b 100644 --- a/src/Behat/Behat/Definition/Pattern/Policy/RegexPatternPolicy.php +++ b/src/Behat/Behat/Definition/Pattern/Policy/RegexPatternPolicy.php @@ -65,7 +65,7 @@ public function transformPatternToRegex($pattern) { if (false === @preg_match($pattern, 'anything')) { $error = error_get_last(); - $errorMessage = isset($error['message']) ? $error['message'] : ''; + $errorMessage = $error['message'] ?? ''; throw new InvalidPatternException(sprintf('The regex `%s` is invalid: %s', $pattern, $errorMessage)); } diff --git a/src/Behat/Behat/HelperContainer/BuiltInServiceContainer.php b/src/Behat/Behat/HelperContainer/BuiltInServiceContainer.php index fc474436b..0f131cbc0 100644 --- a/src/Behat/Behat/HelperContainer/BuiltInServiceContainer.php +++ b/src/Behat/Behat/HelperContainer/BuiltInServiceContainer.php @@ -61,7 +61,7 @@ public function get($id) ); } - return $this->instances[$id] = isset($this->instances[$id]) ? $this->instances[$id] : $this->createInstance($id); + return $this->instances[$id] = $this->instances[$id] ?? $this->createInstance($id); } /** diff --git a/src/Behat/Behat/Hook/Context/Annotation/HookAnnotationReader.php b/src/Behat/Behat/Hook/Context/Annotation/HookAnnotationReader.php index 86a95cca5..663245ee0 100644 --- a/src/Behat/Behat/Hook/Context/Annotation/HookAnnotationReader.php +++ b/src/Behat/Behat/Hook/Context/Annotation/HookAnnotationReader.php @@ -57,7 +57,7 @@ public function readCallee($contextClass, ReflectionMethod $method, $docLine, $d $type = strtolower($match[1]); $class = self::$classes[$type]; - $pattern = isset($match[2]) ? $match[2] : null; + $pattern = $match[2] ?? null; $callable = array($contextClass, $method->getName()); return new $class($pattern, $callable, $description); diff --git a/src/Behat/Testwork/Call/Exception/CallErrorException.php b/src/Behat/Testwork/Call/Exception/CallErrorException.php index 423abf38f..1622f0fe2 100644 --- a/src/Behat/Testwork/Call/Exception/CallErrorException.php +++ b/src/Behat/Testwork/Call/Exception/CallErrorException.php @@ -42,7 +42,7 @@ public function __construct($level, $message, $file, $line) parent::__construct( sprintf( '%s: %s in %s line %d', - isset($this->levels[$level]) ? $this->levels[$level] : $level, + $this->levels[$level] ?? $level, $message, $file, $line diff --git a/src/Behat/Testwork/Output/NodeEventListeningFormatter.php b/src/Behat/Testwork/Output/NodeEventListeningFormatter.php index 272e08041..20173a5bf 100644 --- a/src/Behat/Testwork/Output/NodeEventListeningFormatter.php +++ b/src/Behat/Testwork/Output/NodeEventListeningFormatter.php @@ -121,6 +121,6 @@ public function setParameter($name, $value) */ public function getParameter($name) { - return isset($this->parameters[$name]) ? $this->parameters[$name] : null; + return $this->parameters[$name] ?? null; } } diff --git a/src/Behat/Testwork/ServiceContainer/ExtensionManager.php b/src/Behat/Testwork/ServiceContainer/ExtensionManager.php index 45e040442..ad49484c8 100644 --- a/src/Behat/Testwork/ServiceContainer/ExtensionManager.php +++ b/src/Behat/Testwork/ServiceContainer/ExtensionManager.php @@ -85,7 +85,7 @@ public function activateExtension($locator) */ public function getExtension($key) { - return isset($this->extensions[$key]) ? $this->extensions[$key] : null; + return $this->extensions[$key] ?? null; } /** diff --git a/src/Behat/Testwork/Suite/ServiceContainer/SuiteExtension.php b/src/Behat/Testwork/Suite/ServiceContainer/SuiteExtension.php index 94d5b56e7..804cb92e4 100644 --- a/src/Behat/Testwork/Suite/ServiceContainer/SuiteExtension.php +++ b/src/Behat/Testwork/Suite/ServiceContainer/SuiteExtension.php @@ -89,9 +89,7 @@ public function configure(ArrayNodeDefinition $builder) return is_array($suite) && count($suite); }) ->then(function ($suite) { - $suite['settings'] = isset($suite['settings']) - ? $suite['settings'] - : array(); + $suite['settings'] = $suite['settings'] ?? array(); foreach ($suite as $key => $val) { $suiteKeys = array('enabled', 'type', 'settings'); From ae3c31bb3bf8250fb0ad2999dce5e227d7a66d10 Mon Sep 17 00:00:00 2001 From: Remon van de Kamp Date: Fri, 19 Jun 2020 11:42:31 +0200 Subject: [PATCH 225/567] Use spaceship operator in custom sort It was introduced in PHP 7.0 and can be used now that this package no longer supports PHP < 7.2 --- .../Transformer/RepositoryArgumentTransformer.php | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/src/Behat/Behat/Transformation/Transformer/RepositoryArgumentTransformer.php b/src/Behat/Behat/Transformation/Transformer/RepositoryArgumentTransformer.php index 62b14bd1f..4bdca2378 100644 --- a/src/Behat/Behat/Transformation/Transformer/RepositoryArgumentTransformer.php +++ b/src/Behat/Behat/Transformation/Transformer/RepositoryArgumentTransformer.php @@ -115,11 +115,7 @@ public function generateRegex($suiteName, $pattern, $language) private function applySimpleTransformations(array $transformations, DefinitionCall $definitionCall, $index, $value) { usort($transformations, function (SimpleArgumentTransformation $t1, SimpleArgumentTransformation $t2) { - if ($t1->getPriority() == $t2->getPriority()) { - return 0; - } - - return ($t1->getPriority() > $t2->getPriority()) ? -1 : 1; + return $t2->getPriority() <=> $t1->getPriority(); }); $newValue = $value; From 9dace126d2b6c8fe5f0cd6787bbce12d3bbae92e Mon Sep 17 00:00:00 2001 From: Remon van de Kamp Date: Fri, 19 Jun 2020 11:47:56 +0200 Subject: [PATCH 226/567] No longer catch Exception before catching Throwable All Exceptions are Throwable in PHP 7, so since this package no longer supports PHP < 7 the BC layer to catch Exception is no longer needed. --- src/Behat/Testwork/Call/CallCenter.php | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/Behat/Testwork/Call/CallCenter.php b/src/Behat/Testwork/Call/CallCenter.php index 448367b2d..2798acf68 100644 --- a/src/Behat/Testwork/Call/CallCenter.php +++ b/src/Behat/Testwork/Call/CallCenter.php @@ -94,8 +94,6 @@ public function makeCall(Call $call) { try { return $this->filterResult($this->handleCall($this->filterCall($call))); - } catch (Exception $exception) { - return new CallResult($call, null, $this->handleException($exception), null); } catch (Throwable $exception) { return new CallResult($call, null, $this->handleException($exception), null); } From 53ab71cc55b5e8495036601e3dfaf6800e9226ae Mon Sep 17 00:00:00 2001 From: Remon van de Kamp Date: Sat, 20 Jun 2020 09:39:41 +0200 Subject: [PATCH 227/567] Adapt failing test to changes in code Failing test still assumed use of call_user_func_array that is no longer in use --- features/error_reporting.feature | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/features/error_reporting.feature b/features/error_reporting.feature index 578ece4a5..12676cb4b 100644 --- a/features/error_reporting.feature +++ b/features/error_reporting.feature @@ -148,7 +148,6 @@ Feature: Error Reporting When an exception is thrown # features/exception_in_scenario.feature:7 Exception: Exception is thrown in features/bootstrap/FeatureContext.php:56 Stack trace: - #0 [internal function]: FeatureContext->anExceptionIsThrown() - #1 src/Behat/Testwork/Call/Handler/RuntimeCallHandler.php(109): call_user_func_array(Array, Array) - #2 src/Behat/Testwork/Call/Handler/RuntimeCallHandler.php(64): Behat\Testwork\Call\Handler\RuntimeCallHandler->executeCall(Object(Behat\Behat\Definition\Call\DefinitionCall)) + #0 src/Behat/Testwork/Call/Handler/RuntimeCallHandler.php(109): FeatureContext->anExceptionIsThrown() + #1 src/Behat/Testwork/Call/Handler/RuntimeCallHandler.php(64): Behat\Testwork\Call\Handler\RuntimeCallHandler->executeCall() """ From 1d86627a410702be3b81c9a277ab369939659053 Mon Sep 17 00:00:00 2001 From: Remon van de Kamp Date: Sat, 20 Jun 2020 10:05:39 +0200 Subject: [PATCH 228/567] Add back object output in feature --- features/error_reporting.feature | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/features/error_reporting.feature b/features/error_reporting.feature index 12676cb4b..888d9b090 100644 --- a/features/error_reporting.feature +++ b/features/error_reporting.feature @@ -149,5 +149,5 @@ Feature: Error Reporting Exception: Exception is thrown in features/bootstrap/FeatureContext.php:56 Stack trace: #0 src/Behat/Testwork/Call/Handler/RuntimeCallHandler.php(109): FeatureContext->anExceptionIsThrown() - #1 src/Behat/Testwork/Call/Handler/RuntimeCallHandler.php(64): Behat\Testwork\Call\Handler\RuntimeCallHandler->executeCall() + #1 src/Behat/Testwork/Call/Handler/RuntimeCallHandler.php(64): Behat\Testwork\Call\Handler\RuntimeCallHandler->executeCall(Object(Behat\Behat\Definition\Call\DefinitionCall)) """ From fe967304ba90ee2bcc32ccb1be0b27062e72e75c Mon Sep 17 00:00:00 2001 From: Guilliam Xavier Date: Tue, 23 Jun 2020 10:15:55 +0200 Subject: [PATCH 229/567] Avoid deprecated transChoice on Symfony 4.4 --- src/Behat/Behat/Definition/Translator/Translator.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Behat/Behat/Definition/Translator/Translator.php b/src/Behat/Behat/Definition/Translator/Translator.php index 858e6445d..a1ee055fe 100644 --- a/src/Behat/Behat/Definition/Translator/Translator.php +++ b/src/Behat/Behat/Definition/Translator/Translator.php @@ -7,7 +7,7 @@ class Translator extends \Symfony\Component\Translation\Translator implements Tr public function trans($id, array $parameters = array(), $domain = null, $locale = null ) { - if(array_key_exists('%count%', $parameters) && method_exists($this, 'transChoice')){ + if(array_key_exists('%count%', $parameters) && method_exists($this, 'transChoice') && !$this instanceof \Symfony\Contracts\Translation\TranslatorInterface){ return parent::transChoice($id, $parameters['%count%'], $parameters, $domain, $locale); } return parent::trans($id, $parameters, $domain, $locale); From 9e16f0c7981ef088769bf81e3747329c56d053e7 Mon Sep 17 00:00:00 2001 From: Remon van de Kamp Date: Tue, 23 Jun 2020 19:55:46 +0200 Subject: [PATCH 230/567] Ensure zend.exception_ignore_args is disabled in CI When enabled the stack trace output for exceptions changes, which causes the tests to fail as the changed output does not match the expected output. --- .travis.yml | 1 + appveyor.yml | 1 + 2 files changed, 2 insertions(+) diff --git a/.travis.yml b/.travis.yml index c8d5cb105..c32b389c8 100644 --- a/.travis.yml +++ b/.travis.yml @@ -27,6 +27,7 @@ before_script: - if [ "$SKIP_INTEROP" != "" ]; then composer remove --dev --no-update container-interop/container-interop; fi; - if [ "$DEPENDENCIES" != "low" ]; then composer update; fi; - if [ "$DEPENDENCIES" = "low" ]; then composer update --prefer-lowest; fi; + - echo 'zend.exception_ignore_args=Off' >> ~/.phpenv/versions/$(phpenv version-name)/etc/conf.d/travis.ini - export PATH=./bin:$PATH script: diff --git a/appveyor.yml b/appveyor.yml index ca6beea26..12f5af0a1 100644 --- a/appveyor.yml +++ b/appveyor.yml @@ -39,6 +39,7 @@ install: Add-Content php.ini "`n extension=php_curl.dll" Add-Content php.ini "`n extension=php_mbstring.dll" Add-Content php.ini "`n extension=php_fileinfo.dll" + Add-Content php.ini "`n zend.exception_ignore_args=Off" # download Composer if (!(Test-Path C:\tools\composer)) { From 3a74eceeaee06ab5f294123e9689193f3ef6792a Mon Sep 17 00:00:00 2001 From: Remon van de Kamp Date: Fri, 3 Jul 2020 15:51:54 +0200 Subject: [PATCH 231/567] Remove BC Layer for Symfony Translator versions 3 and lower --- src/Behat/Behat/Definition/Translator/Translator.php | 8 -------- .../Definition/Translator/TranslatorInterface.php | 10 ++-------- 2 files changed, 2 insertions(+), 16 deletions(-) diff --git a/src/Behat/Behat/Definition/Translator/Translator.php b/src/Behat/Behat/Definition/Translator/Translator.php index a1ee055fe..97cdb4071 100644 --- a/src/Behat/Behat/Definition/Translator/Translator.php +++ b/src/Behat/Behat/Definition/Translator/Translator.php @@ -4,12 +4,4 @@ class Translator extends \Symfony\Component\Translation\Translator implements TranslatorInterface { - - public function trans($id, array $parameters = array(), $domain = null, $locale = null ) { - - if(array_key_exists('%count%', $parameters) && method_exists($this, 'transChoice') && !$this instanceof \Symfony\Contracts\Translation\TranslatorInterface){ - return parent::transChoice($id, $parameters['%count%'], $parameters, $domain, $locale); - } - return parent::trans($id, $parameters, $domain, $locale); - } } diff --git a/src/Behat/Behat/Definition/Translator/TranslatorInterface.php b/src/Behat/Behat/Definition/Translator/TranslatorInterface.php index d2af2b99c..245686ff3 100644 --- a/src/Behat/Behat/Definition/Translator/TranslatorInterface.php +++ b/src/Behat/Behat/Definition/Translator/TranslatorInterface.php @@ -2,12 +2,6 @@ namespace Behat\Behat\Definition\Translator; -if (interface_exists('Symfony\Contracts\Translation\TranslatorInterface')) { - interface TranslatorInterface extends \Symfony\Contracts\Translation\TranslatorInterface - { - } -} elseif (interface_exists('Symfony\Component\Translation\TranslatorInterface')) { - interface TranslatorInterface extends \Symfony\Component\Translation\TranslatorInterface - { - } +interface TranslatorInterface extends \Symfony\Contracts\Translation\TranslatorInterface +{ } From 70880ddf3f2108c951626fdea5a73ab5f9c2c1f3 Mon Sep 17 00:00:00 2001 From: Remon van de Kamp Date: Sat, 4 Jul 2020 10:51:20 +0200 Subject: [PATCH 232/567] Remove BC Layer for Symfony Dispatcher versions 4.3 and lower --- .../Cli/StopOnFailureController.php | 9 +- .../EventDispatchingBackgroundTester.php | 24 +--- .../Tester/EventDispatchingFeatureTester.php | 24 +--- .../Tester/EventDispatchingOutlineTester.php | 24 +--- .../Tester/EventDispatchingScenarioTester.php | 24 +--- .../Tester/EventDispatchingStepTester.php | 24 +--- src/Behat/Testwork/Event/Event.php | 11 +- .../EventDispatcher/Cli/SigintController.php | 6 +- .../Tester/EventDispatchingExercise.php | 24 +--- .../Tester/EventDispatchingSuiteTester.php | 24 +--- .../TestworkEventDispatcher.php | 72 ++++++------ .../TestworkEventDispatcherSymfony5.php | 3 + .../TestworkEventDispatcherSymfonyLegacy.php | 3 + .../TestworkEventDispatcherTest.php | 106 ++++++++++++++++++ 14 files changed, 180 insertions(+), 198 deletions(-) create mode 100644 tests/Behat/Tests/Testwork/EventDispatcher/TestworkEventDispatcherTest.php diff --git a/src/Behat/Behat/EventDispatcher/Cli/StopOnFailureController.php b/src/Behat/Behat/EventDispatcher/Cli/StopOnFailureController.php index 637f99dd0..b4e13e081 100644 --- a/src/Behat/Behat/EventDispatcher/Cli/StopOnFailureController.php +++ b/src/Behat/Behat/EventDispatcher/Cli/StopOnFailureController.php @@ -101,13 +101,8 @@ public function exitOnFailure(AfterScenarioTested $event) return; } - if (TestworkEventDispatcher::DISPATCHER_VERSION === 2) { - $this->eventDispatcher->dispatch(new AfterSuiteAborted($event->getEnvironment()), SuiteTested::AFTER); - $this->eventDispatcher->dispatch(new AfterExerciseAborted(), ExerciseCompleted::AFTER); - } else { - $this->eventDispatcher->dispatch(SuiteTested::AFTER, new AfterSuiteAborted($event->getEnvironment())); - $this->eventDispatcher->dispatch(ExerciseCompleted::AFTER, new AfterExerciseAborted()); - } + $this->eventDispatcher->dispatch(new AfterSuiteAborted($event->getEnvironment()), SuiteTested::AFTER); + $this->eventDispatcher->dispatch(new AfterExerciseAborted(), ExerciseCompleted::AFTER); exit(1); } diff --git a/src/Behat/Behat/EventDispatcher/Tester/EventDispatchingBackgroundTester.php b/src/Behat/Behat/EventDispatcher/Tester/EventDispatchingBackgroundTester.php index 2c50db1f5..cb5d32d32 100644 --- a/src/Behat/Behat/EventDispatcher/Tester/EventDispatchingBackgroundTester.php +++ b/src/Behat/Behat/EventDispatcher/Tester/EventDispatchingBackgroundTester.php @@ -57,21 +57,13 @@ public function setUp(Environment $env, FeatureNode $feature, $skip) { $event = new BeforeBackgroundTested($env, $feature, $feature->getBackground()); - if (TestworkEventDispatcher::DISPATCHER_VERSION === 2) { - $this->eventDispatcher->dispatch($event, $event::BEFORE); - } else { - $this->eventDispatcher->dispatch($event::BEFORE, $event); - } + $this->eventDispatcher->dispatch($event, $event::BEFORE); $setup = $this->baseTester->setUp($env, $feature, $skip); $event = new AfterBackgroundSetup($env, $feature, $feature->getBackground(), $setup); - if (TestworkEventDispatcher::DISPATCHER_VERSION === 2) { - $this->eventDispatcher->dispatch($event, $event::AFTER_SETUP); - } else { - $this->eventDispatcher->dispatch($event::AFTER_SETUP, $event); - } + $this->eventDispatcher->dispatch($event, $event::AFTER_SETUP); return $setup; } @@ -91,21 +83,13 @@ public function tearDown(Environment $env, FeatureNode $feature, $skip, TestResu { $event = new BeforeBackgroundTeardown($env, $feature, $feature->getBackground(), $result); - if (TestworkEventDispatcher::DISPATCHER_VERSION === 2) { - $this->eventDispatcher->dispatch($event, BackgroundTested::BEFORE_TEARDOWN); - } else { - $this->eventDispatcher->dispatch(BackgroundTested::BEFORE_TEARDOWN, $event); - } + $this->eventDispatcher->dispatch($event, BackgroundTested::BEFORE_TEARDOWN); $teardown = $this->baseTester->tearDown($env, $feature, $skip, $result); $event = new AfterBackgroundTested($env, $feature, $feature->getBackground(), $result, $teardown); - if (TestworkEventDispatcher::DISPATCHER_VERSION === 2) { - $this->eventDispatcher->dispatch($event, BackgroundTested::AFTER); - } else { - $this->eventDispatcher->dispatch(BackgroundTested::AFTER, $event); - } + $this->eventDispatcher->dispatch($event, BackgroundTested::AFTER); return $teardown; } diff --git a/src/Behat/Behat/EventDispatcher/Tester/EventDispatchingFeatureTester.php b/src/Behat/Behat/EventDispatcher/Tester/EventDispatchingFeatureTester.php index c07313b61..a0ce588f6 100644 --- a/src/Behat/Behat/EventDispatcher/Tester/EventDispatchingFeatureTester.php +++ b/src/Behat/Behat/EventDispatcher/Tester/EventDispatchingFeatureTester.php @@ -55,21 +55,13 @@ public function setUp(Environment $env, $feature, $skip) { $event = new BeforeFeatureTested($env, $feature); - if (TestworkEventDispatcher::DISPATCHER_VERSION === 2) { - $this->eventDispatcher->dispatch($event, $event::BEFORE); - } else { - $this->eventDispatcher->dispatch($event::BEFORE, $event); - } + $this->eventDispatcher->dispatch($event, $event::BEFORE); $setup = $this->baseTester->setUp($env, $feature, $skip); $event = new AfterFeatureSetup($env, $feature, $setup); - if (TestworkEventDispatcher::DISPATCHER_VERSION === 2) { - $this->eventDispatcher->dispatch($event, $event::AFTER_SETUP); - } else { - $this->eventDispatcher->dispatch($event::AFTER_SETUP, $event); - } + $this->eventDispatcher->dispatch($event, $event::AFTER_SETUP); return $setup; } @@ -89,21 +81,13 @@ public function tearDown(Environment $env, $feature, $skip, TestResult $result) { $event = new BeforeFeatureTeardown($env, $feature, $result); - if (TestworkEventDispatcher::DISPATCHER_VERSION === 2) { - $this->eventDispatcher->dispatch($event, $event::BEFORE_TEARDOWN); - } else { - $this->eventDispatcher->dispatch($event::BEFORE_TEARDOWN, $event); - } + $this->eventDispatcher->dispatch($event, $event::BEFORE_TEARDOWN); $teardown = $this->baseTester->tearDown($env, $feature, $skip, $result); $event = new AfterFeatureTested($env, $feature, $result, $teardown); - if (TestworkEventDispatcher::DISPATCHER_VERSION === 2) { - $this->eventDispatcher->dispatch($event, $event::AFTER); - } else { - $this->eventDispatcher->dispatch($event::AFTER, $event); - } + $this->eventDispatcher->dispatch($event, $event::AFTER); return $teardown; } diff --git a/src/Behat/Behat/EventDispatcher/Tester/EventDispatchingOutlineTester.php b/src/Behat/Behat/EventDispatcher/Tester/EventDispatchingOutlineTester.php index 3b1d77fa9..132f584fb 100644 --- a/src/Behat/Behat/EventDispatcher/Tester/EventDispatchingOutlineTester.php +++ b/src/Behat/Behat/EventDispatcher/Tester/EventDispatchingOutlineTester.php @@ -57,21 +57,13 @@ public function setUp(Environment $env, FeatureNode $feature, OutlineNode $outli { $event = new BeforeOutlineTested($env, $feature, $outline); - if (TestworkEventDispatcher::DISPATCHER_VERSION === 2) { - $this->eventDispatcher->dispatch($event, $event::BEFORE); - } else { - $this->eventDispatcher->dispatch($event::BEFORE, $event); - } + $this->eventDispatcher->dispatch($event, $event::BEFORE); $setup = $this->baseTester->setUp($env, $feature, $outline, $skip); $event = new AfterOutlineSetup($env, $feature, $outline, $setup); - if (TestworkEventDispatcher::DISPATCHER_VERSION === 2) { - $this->eventDispatcher->dispatch($event, $event::AFTER_SETUP); - } else { - $this->eventDispatcher->dispatch($event::AFTER_SETUP, $event); - } + $this->eventDispatcher->dispatch($event, $event::AFTER_SETUP); return $setup; } @@ -91,21 +83,13 @@ public function tearDown(Environment $env, FeatureNode $feature, OutlineNode $ou { $event = new BeforeOutlineTeardown($env, $feature, $outline, $result); - if (TestworkEventDispatcher::DISPATCHER_VERSION === 2) { - $this->eventDispatcher->dispatch( $event,$event::BEFORE_TEARDOWN); - } else { - $this->eventDispatcher->dispatch($event::BEFORE_TEARDOWN, $event); - } + $this->eventDispatcher->dispatch( $event,$event::BEFORE_TEARDOWN); $teardown = $this->baseTester->tearDown($env, $feature, $outline, $skip, $result); $event = new AfterOutlineTested($env, $feature, $outline, $result, $teardown); - if (TestworkEventDispatcher::DISPATCHER_VERSION === 2) { - $this->eventDispatcher->dispatch($event, $event::AFTER); - } else { - $this->eventDispatcher->dispatch($event::AFTER, $event); - } + $this->eventDispatcher->dispatch($event, $event::AFTER); return $teardown; } diff --git a/src/Behat/Behat/EventDispatcher/Tester/EventDispatchingScenarioTester.php b/src/Behat/Behat/EventDispatcher/Tester/EventDispatchingScenarioTester.php index a45ee5ac9..882be52ed 100644 --- a/src/Behat/Behat/EventDispatcher/Tester/EventDispatchingScenarioTester.php +++ b/src/Behat/Behat/EventDispatcher/Tester/EventDispatchingScenarioTester.php @@ -87,21 +87,13 @@ public function setUp(Environment $env, FeatureNode $feature, Scenario $scenario { $event = new BeforeScenarioTested($env, $feature, $scenario); - if (TestworkEventDispatcher::DISPATCHER_VERSION === 2) { - $this->eventDispatcher->dispatch($event, $this->beforeEventName); - } else { - $this->eventDispatcher->dispatch($this->beforeEventName, $event); - } + $this->eventDispatcher->dispatch($event, $this->beforeEventName); $setup = $this->baseTester->setUp($env, $feature, $scenario, $skip); $event = new AfterScenarioSetup($env, $feature, $scenario, $setup); - if (TestworkEventDispatcher::DISPATCHER_VERSION === 2) { - $this->eventDispatcher->dispatch($event, $this->afterSetupEventName); - } else { - $this->eventDispatcher->dispatch($this->afterSetupEventName, $event); - } + $this->eventDispatcher->dispatch($event, $this->afterSetupEventName); return $setup; } @@ -121,21 +113,13 @@ public function tearDown(Environment $env, FeatureNode $feature, Scenario $scena { $event = new BeforeScenarioTeardown($env, $feature, $scenario, $result); - if (TestworkEventDispatcher::DISPATCHER_VERSION === 2) { - $this->eventDispatcher->dispatch($event, $this->beforeTeardownEventName); - } else { - $this->eventDispatcher->dispatch($this->beforeTeardownEventName, $event); - } + $this->eventDispatcher->dispatch($event, $this->beforeTeardownEventName); $teardown = $this->baseTester->tearDown($env, $feature, $scenario, $skip, $result); $event = new AfterScenarioTested($env, $feature, $scenario, $result, $teardown); - if (TestworkEventDispatcher::DISPATCHER_VERSION === 2) { - $this->eventDispatcher->dispatch($event, $this->afterEventName); - } else { - $this->eventDispatcher->dispatch($this->afterEventName, $event); - } + $this->eventDispatcher->dispatch($event, $this->afterEventName); return $teardown; } diff --git a/src/Behat/Behat/EventDispatcher/Tester/EventDispatchingStepTester.php b/src/Behat/Behat/EventDispatcher/Tester/EventDispatchingStepTester.php index 3fa53f8df..1daafadce 100644 --- a/src/Behat/Behat/EventDispatcher/Tester/EventDispatchingStepTester.php +++ b/src/Behat/Behat/EventDispatcher/Tester/EventDispatchingStepTester.php @@ -57,21 +57,13 @@ public function setUp(Environment $env, FeatureNode $feature, StepNode $step, $s { $event = new BeforeStepTested($env, $feature, $step); - if (TestworkEventDispatcher::DISPATCHER_VERSION === 2) { - $this->eventDispatcher->dispatch($event, $event::BEFORE); - } else { - $this->eventDispatcher->dispatch($event::BEFORE, $event); - } + $this->eventDispatcher->dispatch($event, $event::BEFORE); $setup = $this->baseTester->setUp($env, $feature, $step, $skip); $event = new AfterStepSetup($env, $feature, $step, $setup); - if (TestworkEventDispatcher::DISPATCHER_VERSION === 2) { - $this->eventDispatcher->dispatch($event, $event::AFTER_SETUP); - } else { - $this->eventDispatcher->dispatch($event::AFTER_SETUP, $event); - } + $this->eventDispatcher->dispatch($event, $event::AFTER_SETUP); return $setup; } @@ -91,21 +83,13 @@ public function tearDown(Environment $env, FeatureNode $feature, StepNode $step, { $event = new BeforeStepTeardown($env, $feature, $step, $result); - if (TestworkEventDispatcher::DISPATCHER_VERSION === 2) { - $this->eventDispatcher->dispatch($event, $event::BEFORE_TEARDOWN); - } else { - $this->eventDispatcher->dispatch($event::BEFORE_TEARDOWN, $event); - } + $this->eventDispatcher->dispatch($event, $event::BEFORE_TEARDOWN); $teardown = $this->baseTester->tearDown($env, $feature, $step, $skip, $result); $event = new AfterStepTested($env, $feature, $step, $result, $teardown); - if (TestworkEventDispatcher::DISPATCHER_VERSION === 2) { - $this->eventDispatcher->dispatch($event, $event::AFTER); - } else { - $this->eventDispatcher->dispatch($event::AFTER, $event); - } + $this->eventDispatcher->dispatch($event, $event::AFTER); return $teardown; } diff --git a/src/Behat/Testwork/Event/Event.php b/src/Behat/Testwork/Event/Event.php index 859a9d0f1..61c65cac3 100644 --- a/src/Behat/Testwork/Event/Event.php +++ b/src/Behat/Testwork/Event/Event.php @@ -4,13 +4,6 @@ use Behat\Testwork\EventDispatcher\TestworkEventDispatcher; -if (TestworkEventDispatcher::DISPATCHER_VERSION === 2) { - class Event extends \Symfony\Contracts\EventDispatcher\Event - { - } - -} else { - class Event extends \Symfony\Component\EventDispatcher\Event - { - } +class Event extends \Symfony\Contracts\EventDispatcher\Event +{ } diff --git a/src/Behat/Testwork/EventDispatcher/Cli/SigintController.php b/src/Behat/Testwork/EventDispatcher/Cli/SigintController.php index d12bcb1a9..4569391a7 100644 --- a/src/Behat/Testwork/EventDispatcher/Cli/SigintController.php +++ b/src/Behat/Testwork/EventDispatcher/Cli/SigintController.php @@ -64,11 +64,7 @@ public function execute(InputInterface $input, OutputInterface $output) */ public function abortExercise() { - if (TestworkEventDispatcher::DISPATCHER_VERSION === 2) { - $this->eventDispatcher->dispatch(new AfterExerciseAborted(), ExerciseCompleted::AFTER); - } else { - $this->eventDispatcher->dispatch(ExerciseCompleted::AFTER, new AfterExerciseAborted()); - } + $this->eventDispatcher->dispatch(new AfterExerciseAborted(), ExerciseCompleted::AFTER); exit(1); } diff --git a/src/Behat/Testwork/EventDispatcher/Tester/EventDispatchingExercise.php b/src/Behat/Testwork/EventDispatcher/Tester/EventDispatchingExercise.php index 0ea275d6c..9c319761d 100644 --- a/src/Behat/Testwork/EventDispatcher/Tester/EventDispatchingExercise.php +++ b/src/Behat/Testwork/EventDispatcher/Tester/EventDispatchingExercise.php @@ -54,21 +54,13 @@ public function setUp(array $iterators, $skip) { $event = new BeforeExerciseCompleted($iterators); - if (TestworkEventDispatcher::DISPATCHER_VERSION === 2) { - $this->eventDispatcher->dispatch($event, $event::BEFORE); - } else { - $this->eventDispatcher->dispatch($event::BEFORE, $event); - } + $this->eventDispatcher->dispatch($event, $event::BEFORE); $setup = $this->baseExercise->setUp($iterators, $skip); $event = new AfterExerciseSetup($iterators, $setup); - if (TestworkEventDispatcher::DISPATCHER_VERSION === 2) { - $this->eventDispatcher->dispatch($event, $event::AFTER_SETUP); - } else { - $this->eventDispatcher->dispatch($event::AFTER_SETUP, $event); - } + $this->eventDispatcher->dispatch($event, $event::AFTER_SETUP); return $setup; } @@ -88,21 +80,13 @@ public function tearDown(array $iterators, $skip, TestResult $result) { $event = new BeforeExerciseTeardown($iterators, $result); - if (TestworkEventDispatcher::DISPATCHER_VERSION === 2) { - $this->eventDispatcher->dispatch($event, $event::BEFORE_TEARDOWN); - } else { - $this->eventDispatcher->dispatch($event::BEFORE_TEARDOWN, $event); - } + $this->eventDispatcher->dispatch($event, $event::BEFORE_TEARDOWN); $teardown = $this->baseExercise->tearDown($iterators, $skip, $result); $event = new AfterExerciseCompleted($iterators, $result, $teardown); - if (TestworkEventDispatcher::DISPATCHER_VERSION === 2) { - $this->eventDispatcher->dispatch($event, $event::AFTER); - } else { - $this->eventDispatcher->dispatch($event::AFTER, $event); - } + $this->eventDispatcher->dispatch($event, $event::AFTER); return $teardown; } diff --git a/src/Behat/Testwork/EventDispatcher/Tester/EventDispatchingSuiteTester.php b/src/Behat/Testwork/EventDispatcher/Tester/EventDispatchingSuiteTester.php index 466a759f1..acfef275a 100644 --- a/src/Behat/Testwork/EventDispatcher/Tester/EventDispatchingSuiteTester.php +++ b/src/Behat/Testwork/EventDispatcher/Tester/EventDispatchingSuiteTester.php @@ -56,21 +56,13 @@ public function setUp(Environment $env, SpecificationIterator $iterator, $skip) { $event = new BeforeSuiteTested($env, $iterator); - if (TestworkEventDispatcher::DISPATCHER_VERSION === 2) { - $this->eventDispatcher->dispatch($event, $event::BEFORE); - } else { - $this->eventDispatcher->dispatch($event::BEFORE, $event); - } + $this->eventDispatcher->dispatch($event, $event::BEFORE); $setup = $this->baseTester->setUp($env, $iterator, $skip); $event = new AfterSuiteSetup($env, $iterator, $setup); - if (TestworkEventDispatcher::DISPATCHER_VERSION === 2) { - $this->eventDispatcher->dispatch($event, $event::AFTER_SETUP); - } else { - $this->eventDispatcher->dispatch($event::AFTER_SETUP, $event); - } + $this->eventDispatcher->dispatch($event, $event::AFTER_SETUP); return $setup; } @@ -89,21 +81,13 @@ public function test(Environment $env, SpecificationIterator $iterator, $skip = public function tearDown(Environment $env, SpecificationIterator $iterator, $skip, TestResult $result) { $event = new BeforeSuiteTeardown($env, $iterator, $result); - if (TestworkEventDispatcher::DISPATCHER_VERSION === 2) { - $this->eventDispatcher->dispatch( $event, $event::BEFORE_TEARDOWN); - } else { - $this->eventDispatcher->dispatch($event::BEFORE_TEARDOWN, $event); - } + $this->eventDispatcher->dispatch( $event, $event::BEFORE_TEARDOWN); $teardown = $this->baseTester->tearDown($env, $iterator, $skip, $result); $event = new AfterSuiteTested($env, $iterator, $result, $teardown); - if (TestworkEventDispatcher::DISPATCHER_VERSION === 2) { - $this->eventDispatcher->dispatch( $event, $event::AFTER); - } else { - $this->eventDispatcher->dispatch($event::AFTER, $event); - } + $this->eventDispatcher->dispatch( $event, $event::AFTER); return $teardown; } diff --git a/src/Behat/Testwork/EventDispatcher/TestworkEventDispatcher.php b/src/Behat/Testwork/EventDispatcher/TestworkEventDispatcher.php index 8802dc6c9..50a8ec957 100644 --- a/src/Behat/Testwork/EventDispatcher/TestworkEventDispatcher.php +++ b/src/Behat/Testwork/EventDispatcher/TestworkEventDispatcher.php @@ -11,56 +11,54 @@ namespace Behat\Testwork\EventDispatcher; use Symfony\Component\EventDispatcher\EventDispatcher; +use Symfony\Contracts\EventDispatcher\Event; /** * Extends Symfony2 event dispatcher with catch-all listeners. * * @author Konstantin Kudryashov */ -$identifyEventDispatcherClassVersion = function() { - $reflection = new \ReflectionClass('Symfony\Component\EventDispatcher\EventDispatcher'); - $dispatch = $reflection->getMethod('dispatch'); +final class TestworkEventDispatcher extends EventDispatcher +{ + public const BEFORE_ALL_EVENTS = '*~'; + public const AFTER_ALL_EVENTS = '~*'; + public const DISPATCHER_VERSION = 2; - if ($dispatch->getNumberOfParameters() === 1) { - // This is the 4.3 / 4.4 version, which has `public function dispatch($event/*, string $eventName = null*/)` and - // internally uses func_get_args to work parameters it got in what order. The legacy Testwork class can still - // extend this because its signature only adds an extra optional param. It may however produce unexpected - // results as it assumes all dispatch calls are with the legacy sequence of $eventName, $event. - return 'Behat\Testwork\EventDispatcher\TestworkEventDispatcherSymfonyLegacy'; - } - - $params = $dispatch->getParameters(); - $first_param = reset($params); - switch ($first_param->getName()) { - case 'event': - // This is the new Symfony 5 event dispatcher interface - // public function dispatch(object $event, string $eventName = null): object - return 'Behat\Testwork\EventDispatcher\TestworkEventDispatcherSymfony5'; - - case 'eventName': - // This is the Symfony <= 4.2 version - // public function dispatch($eventName, Event $event = null) - return 'Behat\Testwork\EventDispatcher\TestworkEventDispatcherSymfonyLegacy'; + /** + * {@inheritdoc} + */ + public function getListeners($eventName = null) + { + if (null == $eventName || self::BEFORE_ALL_EVENTS === $eventName) { + return parent::getListeners($eventName); + } - default: - throw new \UnexpectedValueException('Could not identify which version of symfony/event-dispatcher is in use, could not define a compatible TestworkEventDispatcher'); + return array_merge( + parent::getListeners(self::BEFORE_ALL_EVENTS), + parent::getListeners($eventName), + parent::getListeners(self::AFTER_ALL_EVENTS) + ); } -}; - -class_alias($identifyEventDispatcherClassVersion(), 'Behat\Testwork\EventDispatcher\TestworkEventDispatcher'); -unset($identifyEventDispatcherClassVersion); + public function dispatch($event, $eventName = null): object + { + if (is_object($event)) { + return $this->bcAwareDispatch($event, $eventName); + } -if (false) { + return $this->bcAwareDispatch($eventName, $event); + } - // Empty, never-actually-defined, class definition to fool any tooling looking for a class in this file - final class TestworkEventDispatcher + private function bcAwareDispatch(object $event, $eventName) { + if (null === $event) { + $event = new Event(); + } - // These constant definitions are required to prevent scrutinizer failing static analysis - public const BEFORE_ALL_EVENTS = '*~'; - public const AFTER_ALL_EVENTS = '~*'; - public const DISPATCHER_VERSION = 'undefined'; - } + if (method_exists($event, 'setName')) { + $event->setName($eventName); + } + return parent::dispatch($event, $eventName); + } } diff --git a/src/Behat/Testwork/EventDispatcher/TestworkEventDispatcherSymfony5.php b/src/Behat/Testwork/EventDispatcher/TestworkEventDispatcherSymfony5.php index e7a38c09a..0991a72f7 100644 --- a/src/Behat/Testwork/EventDispatcher/TestworkEventDispatcherSymfony5.php +++ b/src/Behat/Testwork/EventDispatcher/TestworkEventDispatcherSymfony5.php @@ -13,6 +13,9 @@ * if the new symfony interface is detected. * * @deprecated Do not reference this class directly, use TestworkEventDispatcher + * + * @todo Remove this class in the next major version. It's not used anymore, but just left here + * for BC purposes. */ final class TestworkEventDispatcherSymfony5 extends EventDispatcher { diff --git a/src/Behat/Testwork/EventDispatcher/TestworkEventDispatcherSymfonyLegacy.php b/src/Behat/Testwork/EventDispatcher/TestworkEventDispatcherSymfonyLegacy.php index 0e25f29d8..0e5849ba5 100644 --- a/src/Behat/Testwork/EventDispatcher/TestworkEventDispatcherSymfonyLegacy.php +++ b/src/Behat/Testwork/EventDispatcher/TestworkEventDispatcherSymfonyLegacy.php @@ -13,6 +13,9 @@ * if the old symfony interface is detected. * * @deprecated Do not reference this class directly, use TestworkEventDispatcher + * + * @todo Remove this class in the next major version. It's not used anymore, but just left here + * for BC purposes. */ final class TestworkEventDispatcherSymfonyLegacy extends EventDispatcher { diff --git a/tests/Behat/Tests/Testwork/EventDispatcher/TestworkEventDispatcherTest.php b/tests/Behat/Tests/Testwork/EventDispatcher/TestworkEventDispatcherTest.php new file mode 100644 index 000000000..62910abc0 --- /dev/null +++ b/tests/Behat/Tests/Testwork/EventDispatcher/TestworkEventDispatcherTest.php @@ -0,0 +1,106 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Behat\Tests\Testwork\EventDispatcher; + +use Behat\Testwork\EventDispatcher\TestworkEventDispatcher; +use PHPUnit\Framework\TestCase; +use Symfony\Contracts\EventDispatcher\Event; + +class TestworkEventDispatcherTest extends TestCase +{ + public function testDispatchLegacyCall(): void + { + $dispatcher = new TestworkEventDispatcher(); + $event = new class extends Event {}; + $eventName = 'TEST_EVENT'; + $listener = $this->createListenerSpy(); + + $dispatcher->addListener($eventName, $listener); + $dispatcher->dispatch($eventName, $event); + + $this->assertCount(1, $listener->receivedEvents); + $this->assertEquals($event, $listener->receivedEvents[0]); + } + + public function testDispatchCurrentCall(): void + { + $dispatcher = new TestworkEventDispatcher(); + $event = new class extends Event {}; + $listener = $this->createListenerSpy(); + + $dispatcher->addListener(get_class($event), $listener); + $dispatcher->dispatch($event); + + $this->assertCount(1, $listener->receivedEvents); + $this->assertEquals($event, $listener->receivedEvents[0]); + } + + public function testSetNameOnEvent(): void + { + $dispatcher = new TestworkEventDispatcher(); + $event = new class extends Event { + public $name; + public function setName($name): void + { + $this->name = $name; + } + }; + $eventName = 'TEST_EVENT'; + $listener = $this->createListenerSpy(); + + $dispatcher->addListener($eventName, $listener); + $dispatcher->dispatch($eventName, $event); + + $this->assertCount(1, $listener->receivedEvents); + $this->assertEquals($eventName, $event->name); + } + + public function testBeforeAllListener(): void + { + $dispatcher = new TestworkEventDispatcher(); + $event = new class extends Event {}; + $listener = $this->createListenerSpy(); + + $dispatcher->addListener(TestworkEventDispatcher::BEFORE_ALL_EVENTS, $listener); + $dispatcher->dispatch($event); + + $this->assertCount(1, $listener->receivedEvents); + $this->assertEquals($event, $listener->receivedEvents[0]); + } + + public function testAfterAllListener(): void + { + $dispatcher = new TestworkEventDispatcher(); + $event = new class extends Event {}; + $listener = $this->createListenerSpy(); + + $dispatcher->addListener(TestworkEventDispatcher::AFTER_ALL_EVENTS, $listener); + $dispatcher->dispatch($event); + + $this->assertCount(1, $listener->receivedEvents); + $this->assertEquals($event, $listener->receivedEvents[0]); + } + + /** + * @return callable + */ + public function createListenerSpy() + { + return new class() { + public $receivedEvents = []; + + public function __invoke(Event $event) + { + $this->receivedEvents[] = $event; + } + }; + } +} From bd28bee5e13607aefa357456d872153171da5f26 Mon Sep 17 00:00:00 2001 From: Remon van de Kamp Date: Sat, 4 Jul 2020 11:00:52 +0200 Subject: [PATCH 233/567] Add getLocale method to Behat TranslatorInterface The old Symfony interfaces had this method, but the new one doesn't. However, some parts of the depend on this method existing on the interface. --- src/Behat/Behat/Definition/Translator/TranslatorInterface.php | 1 + 1 file changed, 1 insertion(+) diff --git a/src/Behat/Behat/Definition/Translator/TranslatorInterface.php b/src/Behat/Behat/Definition/Translator/TranslatorInterface.php index 245686ff3..ba9b49558 100644 --- a/src/Behat/Behat/Definition/Translator/TranslatorInterface.php +++ b/src/Behat/Behat/Definition/Translator/TranslatorInterface.php @@ -4,4 +4,5 @@ interface TranslatorInterface extends \Symfony\Contracts\Translation\TranslatorInterface { + public function getLocale(); } From b5660f8b445bcc56f8ba6424f490f630008543ec Mon Sep 17 00:00:00 2001 From: Remon van de Kamp Date: Sat, 4 Jul 2020 11:12:18 +0200 Subject: [PATCH 234/567] Resolve correct event name in NodeEventListeningFormatter --- src/Behat/Testwork/Output/NodeEventListeningFormatter.php | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/src/Behat/Testwork/Output/NodeEventListeningFormatter.php b/src/Behat/Testwork/Output/NodeEventListeningFormatter.php index 20173a5bf..4ecdd2085 100644 --- a/src/Behat/Testwork/Output/NodeEventListeningFormatter.php +++ b/src/Behat/Testwork/Output/NodeEventListeningFormatter.php @@ -79,7 +79,13 @@ public static function getSubscribedEvents() */ public function listenEvent(Event $event, $eventName = null) { - $eventName = $eventName ?: $event->getName(); + if (null === $eventName) { + if (method_exists($event, 'getName')) { + $eventName = $event->getName(); + } else { + $eventName = get_class($event); + } + } $this->listener->listenEvent($this, $event, $eventName); } From de538abc0b0cc134b5efd82fc585ead330983acd Mon Sep 17 00:00:00 2001 From: Remon van de Kamp Date: Sat, 4 Jul 2020 20:24:13 +0200 Subject: [PATCH 235/567] Trigger E_USER_DEPRECATED on use of deprecated EventDispatcher classes --- .../TestworkEventDispatcherSymfony5.php | 16 +++++++++++++--- .../TestworkEventDispatcherSymfonyLegacy.php | 17 ++++++++++++++--- 2 files changed, 27 insertions(+), 6 deletions(-) diff --git a/src/Behat/Testwork/EventDispatcher/TestworkEventDispatcherSymfony5.php b/src/Behat/Testwork/EventDispatcher/TestworkEventDispatcherSymfony5.php index 0991a72f7..d82c500dd 100644 --- a/src/Behat/Testwork/EventDispatcher/TestworkEventDispatcherSymfony5.php +++ b/src/Behat/Testwork/EventDispatcher/TestworkEventDispatcherSymfony5.php @@ -13,9 +13,6 @@ * if the new symfony interface is detected. * * @deprecated Do not reference this class directly, use TestworkEventDispatcher - * - * @todo Remove this class in the next major version. It's not used anymore, but just left here - * for BC purposes. */ final class TestworkEventDispatcherSymfony5 extends EventDispatcher { @@ -28,6 +25,12 @@ final class TestworkEventDispatcherSymfony5 extends EventDispatcher */ public function dispatch($event, string $eventName = null): object { + trigger_error( + 'Class "\Behat\Testwork\EventDispatcher\TestworkEventDispatcherSymfony5" is deprecated ' . + 'and should not be relied upon anymore. Use "Behat\Testwork\EventDispatcher\TestworkEventDispatcher" ' . + 'instead', + E_USER_DEPRECATED + ); if (null === $event) { $event = new \Symfony\Contracts\EventDispatcher\Event(); } @@ -45,6 +48,13 @@ public function dispatch($event, string $eventName = null): object */ public function getListeners($eventName = null) { + trigger_error( + 'Class "\Behat\Testwork\EventDispatcher\TestworkEventDispatcherSymfony5" is deprecated ' . + 'and should not be relied upon anymore. Use "Behat\Testwork\EventDispatcher\TestworkEventDispatcher" ' . + 'instead', + E_USER_DEPRECATED + ); + if (null == $eventName || self::BEFORE_ALL_EVENTS === $eventName) { return parent::getListeners($eventName); } diff --git a/src/Behat/Testwork/EventDispatcher/TestworkEventDispatcherSymfonyLegacy.php b/src/Behat/Testwork/EventDispatcher/TestworkEventDispatcherSymfonyLegacy.php index 0e5849ba5..2e2b93076 100644 --- a/src/Behat/Testwork/EventDispatcher/TestworkEventDispatcherSymfonyLegacy.php +++ b/src/Behat/Testwork/EventDispatcher/TestworkEventDispatcherSymfonyLegacy.php @@ -13,9 +13,6 @@ * if the old symfony interface is detected. * * @deprecated Do not reference this class directly, use TestworkEventDispatcher - * - * @todo Remove this class in the next major version. It's not used anymore, but just left here - * for BC purposes. */ final class TestworkEventDispatcherSymfonyLegacy extends EventDispatcher { @@ -29,6 +26,13 @@ final class TestworkEventDispatcherSymfonyLegacy extends EventDispatcher */ public function dispatch($eventName, \Symfony\Component\EventDispatcher\Event $event = null) { + trigger_error( + 'Class "\Behat\Testwork\EventDispatcher\TestworkEventDispatcherSymfonyLegacy" is deprecated ' . + 'and should not be relied upon anymore. Use "Behat\Testwork\EventDispatcher\TestworkEventDispatcher" ' . + 'instead', + E_USER_DEPRECATED + ); + if (null === $event) { $event = new \Symfony\Component\EventDispatcher\Event(); } @@ -46,6 +50,13 @@ public function dispatch($eventName, \Symfony\Component\EventDispatcher\Event $e */ public function getListeners($eventName = null) { + trigger_error( + 'Class "\Behat\Testwork\EventDispatcher\TestworkEventDispatcherSymfonyLegacy" is deprecated ' . + 'and should not be relied upon anymore. Use "Behat\Testwork\EventDispatcher\TestworkEventDispatcher" ' . + 'instead', + E_USER_DEPRECATED + ); + if (null == $eventName || self::BEFORE_ALL_EVENTS === $eventName) { return parent::getListeners($eventName); } From 035629e6049d327362362ae926188934ea7c0dd4 Mon Sep 17 00:00:00 2001 From: Phil Davis Date: Thu, 9 Jul 2020 21:56:47 +0545 Subject: [PATCH 236/567] Use PHPUnit8 for unit testing --- .gitignore | 1 + composer.json | 2 +- .../Tests/Definition/Pattern/PatternTransformerTest.php | 6 ++---- 3 files changed, 4 insertions(+), 5 deletions(-) diff --git a/.gitignore b/.gitignore index fce40dae4..97d5112f8 100644 --- a/.gitignore +++ b/.gitignore @@ -4,3 +4,4 @@ behat.yml vendor composer.lock +.phpunit.result.cache diff --git a/composer.json b/composer.json index b9676e5d7..5d3b7a2d4 100644 --- a/composer.json +++ b/composer.json @@ -29,7 +29,7 @@ "require-dev": { "symfony/process": "^4.4 || ^5.0", - "phpunit/phpunit": "^7.5.20", + "phpunit/phpunit": "^8.5", "herrera-io/box": "~1.6.1", "container-interop/container-interop": "^1.2" }, diff --git a/tests/Behat/Tests/Definition/Pattern/PatternTransformerTest.php b/tests/Behat/Tests/Definition/Pattern/PatternTransformerTest.php index 4a2c45462..81f605926 100644 --- a/tests/Behat/Tests/Definition/Pattern/PatternTransformerTest.php +++ b/tests/Behat/Tests/Definition/Pattern/PatternTransformerTest.php @@ -66,12 +66,10 @@ public function testTransformPatternToRegexCacheAndRegisterNewPolicy() $this->assertEquals('/hello world/', $regex3); } - /** - * @expectedException \Behat\Behat\Definition\Exception\UnknownPatternException - * @expectedExceptionMessage Can not find policy for a pattern `hello world`. - */ public function testTransformPatternToRegexNoMatch() { + $this->expectException('\Behat\Behat\Definition\Exception\UnknownPatternException'); + $this->expectExceptionMessage("Can not find policy for a pattern `hello world`."); // first pattern $policy1Prophecy = $this->prophesize('Behat\Behat\Definition\Pattern\Policy\PatternPolicy'); $policy1Prophecy->supportsPattern('hello world')->willReturn(false); From e27fac57935c88e08593172decc4f61efd1e33d0 Mon Sep 17 00:00:00 2001 From: Andrew Nicols Date: Fri, 10 Jul 2020 09:34:22 +0800 Subject: [PATCH 237/567] Scenario Hook should allowed neated filters (fixes #1235) Scenario hooks support filtering by tag. The tag can be filtered on either the Feature tags, or the Scenario tags. When checking these tags, the tags must be combined before checking to allow support of negated tags. The `TagFilter::isScenarioMatch()` function in Gherkin takes both the FeatureNode, and ScenarioNode as arguments, and then combines the tags on both of these. This fix addresses an issue whereby the Feature does not contain a tag, but the Scenario does, and the hook is filtered on the absence of that Scenario tag. For example, Given the following Feature: ``` Feature: @doNotMatch Scenario: I should not be called with the @~doNotMatch filter ``` And the following Hooks: ``` /** * @BeforeScenario @~doNotMatch */ public negatedBeforeScenarioHook($event) { throw new \Exception('I should not have been called'); } ``` The Feature contains no hooks, but the Scenario contains the `@doNotMatch` hook. When processed before applying this patch the call to `TagFilter::isFeatureMatch($feature)` will not not match (i.e. it _will_ match), the `isMatchTagFilter` function returns early with a true value, and therefore the hook incorrectly applies. Following this change the, `TagFilter::isScenarioMatch($scenario)` function is called and checks the values of all tags on _both_ the Feature, _and_ the Scenario. The tag does _not_ match, the `isMatchTagFilter()` function return false,a dn the tag _does not_ apply which is the correct behaviour. --- features/hooks.feature | 47 ++++++++++++++++++- .../Behat/Hook/Call/RuntimeScenarioHook.php | 4 -- 2 files changed, 45 insertions(+), 6 deletions(-) diff --git a/features/hooks.feature b/features/hooks.feature index 20066b000..e4ed416ff 100644 --- a/features/hooks.feature +++ b/features/hooks.feature @@ -83,6 +83,20 @@ Feature: hooks throw new \Exception('Exception'); } + /** + * @BeforeScenario @filtered + */ + public function beforeScenarioFiltered($event) { + $this->scenarioFilter = 'filtered'; + } + + /** + * @BeforeScenario @~filtered + */ + public function beforeScenarioNotFiltered($event) { + $this->scenarioFilter = '~filtered'; + } + /** * @BeforeStep I must have 100 */ @@ -103,6 +117,13 @@ Feature: hooks public function iMustHave($number) { \PHPUnit\Framework\Assert::assertEquals(intval($number), $this->number); } + + /** + * @Then I must have a scenario filter value of :value + */ + public function iMustHaveScenarioFilter($filterValue) { + \PHPUnit\Framework\Assert::assertEquals($filterValue, $this->scenarioFilter); + } } """ @@ -129,6 +150,17 @@ Feature: hooks Scenario: 130 Given I must have 130 + + @filtered + Scenario: + Then I must have a scenario filter value of "filtered" + + @~filtered + Scenario: + Then I must have a scenario filter value of "~filtered" + + Scenario: + Then I must have a scenario filter value of "~filtered" """ When I run "behat --no-colors -f pretty" Then it should pass with: @@ -161,13 +193,24 @@ Feature: hooks Scenario: 130 # features/test.feature:19 Given I must have 130 # FeatureContext::iMustHave() + @filtered + Scenario: # features/test.feature:23 + Then I must have a scenario filter value of "filtered" # FeatureContext::iMustHaveScenarioFilter() + + @~filtered + Scenario: # features/test.feature:27 + Then I must have a scenario filter value of "~filtered" # FeatureContext::iMustHaveScenarioFilter() + + Scenario: # features/test.feature:30 + Then I must have a scenario filter value of "~filtered" # FeatureContext::iMustHaveScenarioFilter() + │ │ = do something AFTER EVERY FEATURE │ └─ @AfterFeature # FeatureContext::doSomethingAfterFeature() - 5 scenarios (5 passed) - 10 steps (10 passed) + 8 scenarios (8 passed) + 13 steps (13 passed) """ Scenario: Filter features diff --git a/src/Behat/Behat/Hook/Call/RuntimeScenarioHook.php b/src/Behat/Behat/Hook/Call/RuntimeScenarioHook.php index d8a401d48..429fafef2 100644 --- a/src/Behat/Behat/Hook/Call/RuntimeScenarioHook.php +++ b/src/Behat/Behat/Hook/Call/RuntimeScenarioHook.php @@ -76,10 +76,6 @@ protected function isMatchTagFilter(FeatureNode $feature, ScenarioInterface $sce { $filter = new TagFilter($filterString); - if ($filter->isFeatureMatch($feature)) { - return true; - } - return $filter->isScenarioMatch($feature, $scenario); } From 6558732121c1be25494340e7a53bf7982d2a69ea Mon Sep 17 00:00:00 2001 From: Phil Davis Date: Thu, 16 Jul 2020 12:03:12 +0545 Subject: [PATCH 238/567] Use assertStringContainsString in tests --- features/bootstrap/FeatureContext.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/features/bootstrap/FeatureContext.php b/features/bootstrap/FeatureContext.php index bbf45921d..be491f4f3 100644 --- a/features/bootstrap/FeatureContext.php +++ b/features/bootstrap/FeatureContext.php @@ -337,7 +337,7 @@ public function fileXmlShouldBeLike($path, PyStringNode $text) */ public function theOutputShouldContain(PyStringNode $text) { - Assert::assertContains($this->getExpectedOutput($text), $this->getOutput()); + Assert::assertStringContainsString($this->getExpectedOutput($text), $this->getOutput()); } private function getExpectedOutput(PyStringNode $expectedText) From 037952071fc109174a941a2672d2c83a96cb9fd0 Mon Sep 17 00:00:00 2001 From: Phil Davis Date: Thu, 16 Jul 2020 12:31:14 +0545 Subject: [PATCH 239/567] Remove deprecated assertInternalType --- features/append_snippets.feature | 12 ++++++------ features/context.feature | 4 ++-- features/definitions_transformations.feature | 2 +- features/format_options.feature | 2 +- features/multiple_formats.feature | 2 +- features/rerun.feature | 2 +- features/rerun_with_multiple_suite.feature | 2 +- 7 files changed, 13 insertions(+), 13 deletions(-) diff --git a/features/append_snippets.feature b/features/append_snippets.feature index e1727bdb4..57c64d903 100644 --- a/features/append_snippets.feature +++ b/features/append_snippets.feature @@ -61,7 +61,7 @@ Feature: Append snippets option * @Given /^context parameter "([^"]*)" should be array with (\d+) elements$/ */ public function contextParameterShouldBeArrayWithElements($key, $count) { - \PHPUnit\Framework\Assert::assertInternalType('array', $this->parameters[$key]); + \PHPUnit\Framework\Assert::assertIsArray($this->parameters[$key]); \PHPUnit\Framework\Assert::assertEquals(2, count($this->parameters[$key])); } @@ -176,7 +176,7 @@ Feature: Append snippets option * @Given /^context parameter "([^"]*)" should be array with (\d+) elements$/ */ public function contextParameterShouldBeArrayWithElements($key, $count) { - \PHPUnit\Framework\Assert::assertInternalType('array', $this->parameters[$key]); + \PHPUnit\Framework\Assert::assertIsArray($this->parameters[$key]); \PHPUnit\Framework\Assert::assertEquals(2, count($this->parameters[$key])); } @@ -281,7 +281,7 @@ Feature: Append snippets option * @Given /^context parameter "([^"]*)" should be array with (\d+) elements$/ */ public function contextParameterShouldBeArrayWithElements($key, $count) { - \PHPUnit\Framework\Assert::assertInternalType('array', $this->parameters[$key]); + \PHPUnit\Framework\Assert::assertIsArray($this->parameters[$key]); \PHPUnit\Framework\Assert::assertEquals(2, count($this->parameters[$key])); } @@ -346,7 +346,7 @@ Feature: Append snippets option * @Given /^context parameter "([^"]*)" should be array with (\d+) elements$/ */ public function contextParameterShouldBeArrayWithElements($key, $count) { - \PHPUnit\Framework\Assert::assertInternalType('array', $this->parameters[$key]); + \PHPUnit\Framework\Assert::assertIsArray($this->parameters[$key]); \PHPUnit\Framework\Assert::assertEquals(2, count($this->parameters[$key])); } @@ -449,7 +449,7 @@ Feature: Append snippets option * @Given /^context parameter "([^"]*)" should be array with (\d+) elements$/ */ public function contextParameterShouldBeArrayWithElements($key, $count) { - \PHPUnit\Framework\Assert::assertInternalType('array', $this->parameters[$key]); + \PHPUnit\Framework\Assert::assertIsArray($this->parameters[$key]); \PHPUnit\Framework\Assert::assertEquals(2, count($this->parameters[$key])); } @@ -514,7 +514,7 @@ Feature: Append snippets option * @Given /^context parameter "([^"]*)" should be array with (\d+) elements$/ */ public function contextParameterShouldBeArrayWithElements($key, $count) { - \PHPUnit\Framework\Assert::assertInternalType('array', $this->parameters[$key]); + \PHPUnit\Framework\Assert::assertIsArray($this->parameters[$key]); \PHPUnit\Framework\Assert::assertEquals(2, count($this->parameters[$key])); } diff --git a/features/context.feature b/features/context.feature index 684f23330..900f1824d 100644 --- a/features/context.feature +++ b/features/context.feature @@ -61,7 +61,7 @@ Feature: Context consistency * @Given /^context parameter "([^"]*)" should be array with (\d+) elements$/ */ public function contextParameterShouldBeArrayWithElements($key, $count) { - PHPUnit\Framework\Assert::assertInternalType('array', $this->parameters[$key]); + PHPUnit\Framework\Assert::assertIsArray($this->parameters[$key]); PHPUnit\Framework\Assert::assertEquals(2, count($this->parameters[$key])); } } @@ -496,7 +496,7 @@ Feature: Context consistency /** @Given foo */ public function foo() { - PHPUnit\Framework\Assert::assertInternalType('array', $this->foo); + PHPUnit\Framework\Assert::assertIsArray($this->foo); PHPUnit\Framework\Assert::assertSame('foo', $this->foo[0]); PHPUnit\Framework\Assert::assertSame('bar', $this->foo[1]); diff --git a/features/definitions_transformations.feature b/features/definitions_transformations.feature index e881a823b..0a620d33e 100644 --- a/features/definitions_transformations.feature +++ b/features/definitions_transformations.feature @@ -125,7 +125,7 @@ Feature: Step Arguments Transformations */ public function ageMustBe($age) { PHPUnit\Framework\Assert::assertEquals($age, $this->user->getAge()); - PHPUnit\Framework\Assert::assertInternalType('int', $age); + PHPUnit\Framework\Assert::assertIsInt($age); } /** diff --git a/features/format_options.feature b/features/format_options.feature index f523e42c9..7efc1722a 100644 --- a/features/format_options.feature +++ b/features/format_options.feature @@ -61,7 +61,7 @@ Feature: Format options * @Given /^context parameter "([^"]*)" should be array with (\d+) elements$/ */ public function contextParameterShouldBeArrayWithElements($key, $count) { - PHPUnit\Framework\Assert::assertInternalType('array', $this->parameters[$key]); + PHPUnit\Framework\Assert::assertIsArray($this->parameters[$key]); PHPUnit\Framework\Assert::assertEquals(2, count($this->parameters[$key])); } } diff --git a/features/multiple_formats.feature b/features/multiple_formats.feature index ecbb2605c..b4063c667 100644 --- a/features/multiple_formats.feature +++ b/features/multiple_formats.feature @@ -61,7 +61,7 @@ Feature: Multiple formats * @Given /^context parameter "([^"]*)" should be array with (\d+) elements$/ */ public function contextParameterShouldBeArrayWithElements($key, $count) { - PHPUnit\Framework\Assert::assertInternalType('array', $this->parameters[$key]); + PHPUnit\Framework\Assert::assertIsArray($this->parameters[$key]); PHPUnit\Framework\Assert::assertEquals(2, count($this->parameters[$key])); } } diff --git a/features/rerun.feature b/features/rerun.feature index 0aa3000c4..4b3ac21fa 100644 --- a/features/rerun.feature +++ b/features/rerun.feature @@ -58,7 +58,7 @@ Feature: Rerun * @Given /^context parameter "([^"]*)" should be array with (\d+) elements$/ */ public function contextParameterShouldBeArrayWithElements($key, $count) { - PHPUnit\Framework\Assert::assertInternalType('array', $this->parameters[$key]); + PHPUnit\Framework\Assert::assertIsArray($this->parameters[$key]); PHPUnit\Framework\Assert::assertEquals(2, count($this->parameters[$key])); } } diff --git a/features/rerun_with_multiple_suite.feature b/features/rerun_with_multiple_suite.feature index a706b8d1e..cb6ac2814 100644 --- a/features/rerun_with_multiple_suite.feature +++ b/features/rerun_with_multiple_suite.feature @@ -74,7 +74,7 @@ Feature: Rerun with multiple suite * @Given /^context parameter "([^"]*)" should be array with (\d+) elements$/ */ public function contextParameterShouldBeArrayWithElements($key, $count) { - PHPUnit\Framework\Assert::assertInternalType('array', $this->parameters[$key]); + PHPUnit\Framework\Assert::assertIsArray($this->parameters[$key]); PHPUnit\Framework\Assert::assertEquals(2, count($this->parameters[$key])); } } From 3880e9ceeb40a85ecd1ef707105a7d72ef272aac Mon Sep 17 00:00:00 2001 From: Phil Davis Date: Thu, 16 Jul 2020 15:37:09 +0545 Subject: [PATCH 240/567] Move expectException to just above where the exception is expected --- .../Behat/Tests/Definition/Pattern/PatternTransformerTest.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/Behat/Tests/Definition/Pattern/PatternTransformerTest.php b/tests/Behat/Tests/Definition/Pattern/PatternTransformerTest.php index 81f605926..b306b34ac 100644 --- a/tests/Behat/Tests/Definition/Pattern/PatternTransformerTest.php +++ b/tests/Behat/Tests/Definition/Pattern/PatternTransformerTest.php @@ -68,8 +68,6 @@ public function testTransformPatternToRegexCacheAndRegisterNewPolicy() public function testTransformPatternToRegexNoMatch() { - $this->expectException('\Behat\Behat\Definition\Exception\UnknownPatternException'); - $this->expectExceptionMessage("Can not find policy for a pattern `hello world`."); // first pattern $policy1Prophecy = $this->prophesize('Behat\Behat\Definition\Pattern\Policy\PatternPolicy'); $policy1Prophecy->supportsPattern('hello world')->willReturn(false); @@ -79,6 +77,8 @@ public function testTransformPatternToRegexNoMatch() $testedInstance = new PatternTransformer(); $testedInstance->registerPatternPolicy($policy1Prophecy->reveal()); + $this->expectException('\Behat\Behat\Definition\Exception\UnknownPatternException'); + $this->expectExceptionMessage("Can not find policy for a pattern `hello world`."); $regex = $testedInstance->transformPatternToRegex('hello world'); } } From 5f2cf2df3e4a04594590d533bd008b877f11de68 Mon Sep 17 00:00:00 2001 From: Steef Min Date: Wed, 23 Sep 2020 09:53:37 +0200 Subject: [PATCH 241/567] Add classname to junit testcase output --- features/junit_format.feature | 38 +++++++++---------- .../Printer/JUnit/JUnitScenarioPrinter.php | 1 + 2 files changed, 20 insertions(+), 19 deletions(-) diff --git a/features/junit_format.feature b/features/junit_format.feature index 82fe02ace..631fb85a5 100644 --- a/features/junit_format.feature +++ b/features/junit_format.feature @@ -105,24 +105,24 @@ - + - + - + - + - - + + - - + + """ @@ -192,10 +192,10 @@ - + - + """ @@ -267,8 +267,8 @@ - - + + """ @@ -387,7 +387,7 @@ - + """ @@ -397,7 +397,7 @@ - + @@ -456,8 +456,8 @@ - - + + """ @@ -518,7 +518,7 @@ - + @@ -648,7 +648,7 @@ - + @@ -704,7 +704,7 @@ - + diff --git a/src/Behat/Behat/Output/Node/Printer/JUnit/JUnitScenarioPrinter.php b/src/Behat/Behat/Output/Node/Printer/JUnit/JUnitScenarioPrinter.php index 57f8906e9..0ca46e987 100644 --- a/src/Behat/Behat/Output/Node/Printer/JUnit/JUnitScenarioPrinter.php +++ b/src/Behat/Behat/Output/Node/Printer/JUnit/JUnitScenarioPrinter.php @@ -78,6 +78,7 @@ public function printOpenTag(Formatter $formatter, FeatureNode $feature, Scenari $outputPrinter->addTestcase(array( 'name' => $name, + 'classname' => $feature->getTitle(), 'status' => $this->resultConverter->convertResultToString($result), 'time' => $this->durationListener ? $this->durationListener->getDuration($scenario) : '' )); From 0028e44be50ff076e3ec4859b41cfb860612a51c Mon Sep 17 00:00:00 2001 From: Steef Min Date: Wed, 23 Sep 2020 10:01:20 +0200 Subject: [PATCH 242/567] append changelog --- CHANGELOG.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index df67f3c3d..7d4bcdd8c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -916,6 +916,9 @@ and this project adheres to [Semantic Versioning](http://semver.org/). * Initial release [Unreleased]: https://github.com/Behat/Behat/compare/v3.7.0...master +### Changed + * Added feature title as classname of testcase in junit output + [3.7.0]: https://github.com/Behat/Behat/compare/v3.6.1...v3.7.0 [3.6.1]: https://github.com/Behat/Behat/compare/v3.6.0...v3.6.1 [3.6.0]: https://github.com/Behat/Behat/compare/v3.5.0...v3.6.0 From 48b08db95309c7209c14483783ef8ff5bb83b7d1 Mon Sep 17 00:00:00 2001 From: Ciaran McNulty Date: Thu, 1 Oct 2020 12:18:38 +0100 Subject: [PATCH 243/567] Start testing on PHP8 in travis --- .travis.yml | 7 +++++-- behat.yml.dist | 4 ++++ 2 files changed, 9 insertions(+), 2 deletions(-) create mode 100644 behat.yml.dist diff --git a/.travis.yml b/.travis.yml index c32b389c8..afa03fbaf 100644 --- a/.travis.yml +++ b/.travis.yml @@ -18,6 +18,8 @@ jobs: env: DEPENDENCIES='low' - php: 7.4 env: SYMFONY_VERSION='^4.4' + - php: nightly + env: PHP8=true before_install: - phpenv config-rm xdebug.ini || echo "XDebug is not enabled" @@ -25,14 +27,15 @@ before_install: before_script: - if [ "$SYMFONY_VERSION" != "" ]; then composer require --no-update "symfony/symfony:${SYMFONY_VERSION}"; fi; - if [ "$SKIP_INTEROP" != "" ]; then composer remove --dev --no-update container-interop/container-interop; fi; - - if [ "$DEPENDENCIES" != "low" ]; then composer update; fi; + - if [ "$DEPENDENCIES" != "low" ]; then composer update $([ -z "$PHP8" ] || echo "--ignore-platform-reqs") ; fi; - if [ "$DEPENDENCIES" = "low" ]; then composer update --prefer-lowest; fi; - echo 'zend.exception_ignore_args=Off' >> ~/.phpenv/versions/$(phpenv version-name)/etc/conf.d/travis.ini - export PATH=./bin:$PATH script: - ./vendor/bin/phpunit - - behat -fprogress --strict $([ -z "$SKIP_INTEROP" ] || echo "--tags ~@interop") + - behat -fprogress --strict $([ -z "$SKIP_INTEROP" ] || echo "--tags ~@interop&&~@php8") + - if [ "$PHP8" = true ]; then behat -fprogress --strict --tags=@php8; fi; before_deploy: - curl -LSs https://box-project.github.io/box2/installer.php | php diff --git a/behat.yml.dist b/behat.yml.dist new file mode 100644 index 000000000..b2c042fa1 --- /dev/null +++ b/behat.yml.dist @@ -0,0 +1,4 @@ +default: + gherkin: + filters: + tags: ~@php8 From 19e57bc72fdbcd03e8fb0cdef01f79337fc37bb2 Mon Sep 17 00:00:00 2001 From: Ciaran McNulty Date: Wed, 30 Sep 2020 13:10:26 +0100 Subject: [PATCH 244/567] Allow newer PHPUnit --- composer.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/composer.json b/composer.json index 5d3b7a2d4..b534907d2 100644 --- a/composer.json +++ b/composer.json @@ -29,7 +29,7 @@ "require-dev": { "symfony/process": "^4.4 || ^5.0", - "phpunit/phpunit": "^8.5", + "phpunit/phpunit": "^8.5 || ^9.0", "herrera-io/box": "~1.6.1", "container-interop/container-interop": "^1.2" }, From 4a06eb9d61bab9aec8d436b68659e3604e4234df Mon Sep 17 00:00:00 2001 From: Ciaran McNulty Date: Wed, 30 Sep 2020 13:10:57 +0100 Subject: [PATCH 245/567] Remove deprecated reflection from MixedArgumentOrganiser --- .../Argument/MixedArgumentOrganiser.php | 52 +++++----- .../Argument/MixedArgumentOrganiserTest.php | 95 +++++++++++++++++++ 2 files changed, 123 insertions(+), 24 deletions(-) create mode 100644 tests/Behat/Tests/Testwork/Argument/MixedArgumentOrganiserTest.php diff --git a/src/Behat/Testwork/Argument/MixedArgumentOrganiser.php b/src/Behat/Testwork/Argument/MixedArgumentOrganiser.php index 1210ccbcd..264963ddf 100644 --- a/src/Behat/Testwork/Argument/MixedArgumentOrganiser.php +++ b/src/Behat/Testwork/Argument/MixedArgumentOrganiser.php @@ -131,17 +131,14 @@ private function isParameterTypehintedInArgumentList(array $parameters, $value) /** * Checks if value matches typehint of provided parameter. - * - * @param object $value - * @param ReflectionParameter $parameter - * - * @return bool */ - private function isValueMatchesTypehintedParameter($value, ReflectionParameter $parameter) + private function isValueMatchesTypehintedParameter($value, ReflectionParameter $parameter) : bool { - $typehintRefl = $parameter->getClass(); + if ($typehintRefl = $this->getReflectionClassFromParameter($parameter)) { + return $typehintRefl->isInstance($value); + } - return $typehintRefl && $typehintRefl->isInstance($value); + return false; } /** @@ -217,29 +214,36 @@ private function prepareTypehintedArguments(array $parameters, array $typehinted * @param ReflectionParameter[] $parameters Constructor Arguments * @return ReflectionParameter[] Filtered $parameters */ - private function filterApplicableTypehintedParameters(array $parameters) + private function filterApplicableTypehintedParameters(array $parameters) : array { - $filtered = array(); + return array_filter($parameters, + function($parameter, $num) { + return !$this->isArgumentDefined($num) + && $this->getReflectionClassFromParameter($parameter); + }, + ARRAY_FILTER_USE_BOTH + ); - foreach ($parameters as $num => $parameter) { - if ($this->isArgumentDefined($num)) { - continue; - } + } - try { - $reflectionClass = $parameter->getClass(); - } catch (ReflectionException $e) { - continue; + private function getReflectionClassFromParameter(\ReflectionParameter $parameter) : ?ReflectionClass + { + try { + if (!$parameter->hasType()) { + return null; } + $type = $parameter->getType()->getName(); - if (!$reflectionClass) { - continue; + if ($type == 'self') { + $type = $parameter->getDeclaringClass(); + } elseif ($type == 'parent') { + $type = $parameter->getDeclaringClass()->getParentClass(); } - $filtered[$num] = $parameter; + return new ReflectionClass($type); // will throw + } catch (ReflectionException $e) { + return null; } - - return $filtered; } /** @@ -283,7 +287,7 @@ public function matchParameterToCandidateUsingPredicate( $predicate ) { foreach ($candidates as $candidateIndex => $candidate) { - if ($predicate($parameter->getClass(), $candidate)) { + if (($class = $this->getReflectionClassFromParameter($parameter)) && $predicate($class, $candidate)) { $num = $parameter->getPosition(); $arguments[$num] = $candidate; diff --git a/tests/Behat/Tests/Testwork/Argument/MixedArgumentOrganiserTest.php b/tests/Behat/Tests/Testwork/Argument/MixedArgumentOrganiserTest.php new file mode 100644 index 000000000..558c46948 --- /dev/null +++ b/tests/Behat/Tests/Testwork/Argument/MixedArgumentOrganiserTest.php @@ -0,0 +1,95 @@ +organiser = new MixedArgumentOrganiser(); + } + + /** @test */ + function it_organises_nothing_if_no_args() + { + $r = new \ReflectionFunction( + function(\DateTimeInterface $d) {} + ); + $args = []; + + $organised = $this->organiser->organiseArguments($r, $args); + + $this->assertSame([], $organised); + } + + /** @test */ + function it_matches_args_by_position() + { + $r = new \ReflectionFunction( + function($x, $y) {} + ); + $args = [ + 1, + 2, + 3 + ]; + + $organised = $this->organiser->organiseArguments($r, $args); + + $this->assertSame([1,2], $organised); + } + + /** @test */ + function it_matches_args_by_name() + { + $r = new \ReflectionFunction( + function($date) {} + ); + $args = [ + 'date' => $date = new \DateTime(), + 'x' => new \stdClass() + ]; + + $organised = $this->organiser->organiseArguments($r, $args); + + $this->assertSame(['date' => $date], $organised); + } + + /** @test */ + function it_matches_args_by_type() + { + $r = new \ReflectionFunction( + function(\DateTimeInterface $d) {} + ); + $args = [ + 'x' => $date = new \DateTime(), + 'y' => new \stdClass() + ]; + + $organised = $this->organiser->organiseArguments($r, $args); + + $this->assertSame([$date], $organised); + } + + /** @test */ + function it_matches_args_by_name_over_type() + { + $r = new \ReflectionFunction( + function(\DateTimeInterface $a, $date) {} + ); + $args = [ + 'date' => $date = new \DateTime(), + 'x' => 1 + ]; + + $organised = $this->organiser->organiseArguments($r, $args); + + $this->assertSame([1, 'date' => $date], $organised); + } +} From 3506a99a8bb9c85622973a8685ffa9065b4d4604 Mon Sep 17 00:00:00 2001 From: Ciaran McNulty Date: Wed, 30 Sep 2020 14:30:32 +0100 Subject: [PATCH 246/567] Let MixedArgumentOrganiser deal with union types --- .../Argument/MixedArgumentOrganiser.php | 71 +++++++++++++------ .../Argument/MixedArgumentOrganiserTest.php | 23 ++++++ 2 files changed, 72 insertions(+), 22 deletions(-) diff --git a/src/Behat/Testwork/Argument/MixedArgumentOrganiser.php b/src/Behat/Testwork/Argument/MixedArgumentOrganiser.php index 264963ddf..b01232296 100644 --- a/src/Behat/Testwork/Argument/MixedArgumentOrganiser.php +++ b/src/Behat/Testwork/Argument/MixedArgumentOrganiser.php @@ -134,8 +134,10 @@ private function isParameterTypehintedInArgumentList(array $parameters, $value) */ private function isValueMatchesTypehintedParameter($value, ReflectionParameter $parameter) : bool { - if ($typehintRefl = $this->getReflectionClassFromParameter($parameter)) { - return $typehintRefl->isInstance($value); + foreach($this->getReflectionClassesFromParameter($parameter) as $typehintRefl) { + if($typehintRefl->isInstance($value)) { + return true; + } } return false; @@ -219,31 +221,54 @@ private function filterApplicableTypehintedParameters(array $parameters) : array return array_filter($parameters, function($parameter, $num) { return !$this->isArgumentDefined($num) - && $this->getReflectionClassFromParameter($parameter); + && $this->getReflectionClassesFromParameter($parameter); }, ARRAY_FILTER_USE_BOTH ); } - private function getReflectionClassFromParameter(\ReflectionParameter $parameter) : ?ReflectionClass + /** + * @return ReflectionClass[] + */ + private function getReflectionClassesFromParameter(\ReflectionParameter $parameter): array { - try { - if (!$parameter->hasType()) { - return null; - } - $type = $parameter->getType()->getName(); + $classes = []; - if ($type == 'self') { - $type = $parameter->getDeclaringClass(); - } elseif ($type == 'parent') { - $type = $parameter->getDeclaringClass()->getParentClass(); + if (!$parameter->hasType()) { + return $classes; + } + + $type = $parameter->getType(); + + if ($type instanceof \ReflectionNamedType) { + $types = [$type]; + } + elseif ($parameter->getType() instanceof \ReflectionUnionType) { + $types = $type->getTypes(); + } + else { + $types = []; + } + + foreach ($types as $type) { + + $typeString = $type->getName(); + + if ($typeString == 'self') { + $typeString = $parameter->getDeclaringClass(); + } elseif ($typeString == 'parent') { + $typeString = $parameter->getDeclaringClass()->getParentClass(); } - return new ReflectionClass($type); // will throw - } catch (ReflectionException $e) { - return null; + try { + $classes[] = new ReflectionClass($typeString); + } catch (ReflectionException $e) { + continue; + } } + + return $classes; } /** @@ -287,16 +312,18 @@ public function matchParameterToCandidateUsingPredicate( $predicate ) { foreach ($candidates as $candidateIndex => $candidate) { - if (($class = $this->getReflectionClassFromParameter($parameter)) && $predicate($class, $candidate)) { - $num = $parameter->getPosition(); + foreach($this->getReflectionClassesFromParameter($parameter) as $class) { + if ($predicate($class, $candidate)) { + $num = $parameter->getPosition(); - $arguments[$num] = $candidate; + $arguments[$num] = $candidate; - $this->markArgumentDefined($num); + $this->markArgumentDefined($num); - unset($candidates[$candidateIndex]); + unset($candidates[$candidateIndex]); - return true; + return true; + } } } diff --git a/tests/Behat/Tests/Testwork/Argument/MixedArgumentOrganiserTest.php b/tests/Behat/Tests/Testwork/Argument/MixedArgumentOrganiserTest.php index 558c46948..0f9334b11 100644 --- a/tests/Behat/Tests/Testwork/Argument/MixedArgumentOrganiserTest.php +++ b/tests/Behat/Tests/Testwork/Argument/MixedArgumentOrganiserTest.php @@ -92,4 +92,27 @@ function(\DateTimeInterface $a, $date) {} $this->assertSame([1, 'date' => $date], $organised); } + + /** @test */ + function it_matches_union_types() + { + if (\PHP_VERSION_ID < 80000) { + $this->markTestSkipped('Union types are not supported'); + } + + $r = eval(<< $date = new \DateTime(), + 'x' => 1 + ]; + + $organised = $this->organiser->organiseArguments($r, $args); + + $this->assertSame([$date], $organised); + } } From 2e84cbf9cf89a856af3c080a5d381ca90b3ec31d Mon Sep 17 00:00:00 2001 From: Ciaran McNulty Date: Thu, 1 Oct 2020 12:19:05 +0100 Subject: [PATCH 247/567] Remove deprecated reflection calls from ReturnTypeTransformation --- features/definitions_transformations.feature | 37 +++++++++++++++++++ .../ReturnTypeTransformation.php | 22 ++++++++--- 2 files changed, 54 insertions(+), 5 deletions(-) diff --git a/features/definitions_transformations.feature b/features/definitions_transformations.feature index 0a620d33e..77a5694c3 100644 --- a/features/definitions_transformations.feature +++ b/features/definitions_transformations.feature @@ -637,3 +637,40 @@ Feature: Step Arguments Transformations 4 scenarios (4 passed) 8 steps (8 passed) """ + + @php8 + Scenario: By-type transformations don't trigger from union types + Given a file named "features/union-transforms.feature" with: + """ + Feature: + Scenario: + Given I am "everzet" + And she is "lunivore" + """ + And a file named "features/bootstrap/FeatureContext.php" with: + """ + I = $user; + } + } + """ + When I run "behat -f progress --no-colors" + Then it should fail with: + """ + string given + """ diff --git a/src/Behat/Behat/Transformation/Transformation/ReturnTypeTransformation.php b/src/Behat/Behat/Transformation/Transformation/ReturnTypeTransformation.php index 7f43e2398..dd8a000b7 100644 --- a/src/Behat/Behat/Transformation/Transformation/ReturnTypeTransformation.php +++ b/src/Behat/Behat/Transformation/Transformation/ReturnTypeTransformation.php @@ -16,6 +16,7 @@ use Behat\Testwork\Call\CallCenter; use Behat\Testwork\Call\RuntimeCallee; use Closure; +use ReflectionClass; use ReflectionFunctionAbstract; use ReflectionMethod; use ReflectionParameter; @@ -127,7 +128,8 @@ static private function getReturnClass(ReflectionFunctionAbstract $reflection) { $type = $reflection->getReturnType(); - if (null === $type || $type->isBuiltin()) { + // Skip ReflectionUnionType as they can't be relied on for a transform + if (null === $type || !($type instanceof \ReflectionNamedType) || $type->isBuiltin()) { return null; } @@ -152,9 +154,12 @@ private function getParameterClassNameByIndex(DefinitionCall $definitionCall, $a array_filter($this->getCallParameters($definitionCall), $this->hasIndex($argumentIndex) ), - $this->isClass() + $this->getClassReflection() ); - return count($parameters) ? current($parameters)->getClass()->getName() : null; + + if (count($parameters)) { + return ($this->getClassReflection())(current($parameters))->getName(); + } } /** @@ -214,10 +219,17 @@ private function hasPosition($index) * * @return Closure */ - private function isClass() + private function getClassReflection() { return function (ReflectionParameter $parameter) { - return $parameter->getClass(); + $t = $parameter->getType(); + + if ($t instanceof ReflectionNamedType) { + try { + return new ReflectionClass($t->getName()); + } + catch (\TypeError $t) {} + } }; } } From 9808a3b8250bb939742bbf454dae23623b6bab39 Mon Sep 17 00:00:00 2001 From: Ciaran McNulty Date: Thu, 1 Oct 2020 12:34:16 +0100 Subject: [PATCH 248/567] Make JUnit test looser for new format error --- features/junit_format.feature | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/features/junit_format.feature b/features/junit_format.feature index 82fe02ace..78ffb1a33 100644 --- a/features/junit_format.feature +++ b/features/junit_format.feature @@ -571,7 +571,7 @@ When I run "behat --no-colors -f junit -o junit" Then it should fail with: """ - PHP Fatal error: class@anonymous cannot implement Foo - it is not an interface + cannot implement Foo - it is not an interface """ And "junit/default.xml" file xml should be like: """ From ba4c3989a89c7d40eb35537ce8a8c2ed66a72092 Mon Sep 17 00:00:00 2001 From: Ciaran McNulty Date: Thu, 1 Oct 2020 16:23:14 +0100 Subject: [PATCH 249/567] Fix error reporting tests that broke due to an E_NOTICE becoming an E_WARNING I decided to patch over this rather than re-write the tests as they can easily become E_WARNING once we drop PHP 7 --- features/bootstrap/FeatureContext.php | 3 +++ features/error_reporting.feature | 4 ++-- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/features/bootstrap/FeatureContext.php b/features/bootstrap/FeatureContext.php index be491f4f3..05a6affd1 100644 --- a/features/bootstrap/FeatureContext.php +++ b/features/bootstrap/FeatureContext.php @@ -438,6 +438,9 @@ private function getOutput() // Replace wrong warning message of HHVM $output = str_replace('Notice: Undefined index: ', 'Notice: Undefined offset: ', $output); + // replace error message that changed in PHP + $output = str_replace('Warning: Undefined array key','Notice: Undefined offset:', $output); + return trim(preg_replace("/ +$/m", '', $output)); } diff --git a/features/error_reporting.feature b/features/error_reporting.feature index 888d9b090..25945b32a 100644 --- a/features/error_reporting.feature +++ b/features/error_reporting.feature @@ -111,12 +111,12 @@ Feature: Error Reporting 7 steps (5 passed, 1 failed, 1 skipped) """ - Scenario: With error reporting ignoring E_NOTICE + Scenario: With error reporting ignoring E_NOTICE and E_WARNING Given a file named "behat.yml" with: """ default: calls: - error_reporting: 32759 + error_reporting: 32757 """ When I run "behat -f progress --no-colors features/e_notice_in_scenario.feature" Then it should pass From 8f62643c800051c63fdc5772730168e7bc5a51e5 Mon Sep 17 00:00:00 2001 From: Ciaran McNulty Date: Thu, 1 Oct 2020 16:39:15 +0100 Subject: [PATCH 250/567] Code review fixes --- .../Transformation/ReturnTypeTransformation.php | 8 +++++--- src/Behat/Testwork/Argument/MixedArgumentOrganiser.php | 5 +++++ .../Testwork/Argument/MixedArgumentOrganiserTest.php | 10 ++++------ 3 files changed, 14 insertions(+), 9 deletions(-) diff --git a/src/Behat/Behat/Transformation/Transformation/ReturnTypeTransformation.php b/src/Behat/Behat/Transformation/Transformation/ReturnTypeTransformation.php index dd8a000b7..fa39a31d5 100644 --- a/src/Behat/Behat/Transformation/Transformation/ReturnTypeTransformation.php +++ b/src/Behat/Behat/Transformation/Transformation/ReturnTypeTransformation.php @@ -157,9 +157,11 @@ private function getParameterClassNameByIndex(DefinitionCall $definitionCall, $a $this->getClassReflection() ); - if (count($parameters)) { - return ($this->getClassReflection())(current($parameters))->getName(); + if (count($parameters) == 0) { + return null; } + + return ($this->getClassReflection())(current($parameters))->getName(); } /** @@ -219,7 +221,7 @@ private function hasPosition($index) * * @return Closure */ - private function getClassReflection() + private function getClassReflection() : closure { return function (ReflectionParameter $parameter) { $t = $parameter->getType(); diff --git a/src/Behat/Testwork/Argument/MixedArgumentOrganiser.php b/src/Behat/Testwork/Argument/MixedArgumentOrganiser.php index b01232296..49694e298 100644 --- a/src/Behat/Testwork/Argument/MixedArgumentOrganiser.php +++ b/src/Behat/Testwork/Argument/MixedArgumentOrganiser.php @@ -253,6 +253,11 @@ private function getReflectionClassesFromParameter(\ReflectionParameter $paramet foreach ($types as $type) { + // ReflectionUnionType::getTypes is only documented as returning ReflectionType[] + if (!$type instanceof \ReflectionNamedType) { + continue; + } + $typeString = $type->getName(); if ($typeString == 'self') { diff --git a/tests/Behat/Tests/Testwork/Argument/MixedArgumentOrganiserTest.php b/tests/Behat/Tests/Testwork/Argument/MixedArgumentOrganiserTest.php index 0f9334b11..5527f4738 100644 --- a/tests/Behat/Tests/Testwork/Argument/MixedArgumentOrganiserTest.php +++ b/tests/Behat/Tests/Testwork/Argument/MixedArgumentOrganiserTest.php @@ -1,5 +1,4 @@ assertSame([1, 'date' => $date], $organised); } - /** @test */ + /** + * @test + * @requires PHP >= 8.0 + */ function it_matches_union_types() { - if (\PHP_VERSION_ID < 80000) { - $this->markTestSkipped('Union types are not supported'); - } - $r = eval(<< Date: Thu, 1 Oct 2020 20:26:48 +0100 Subject: [PATCH 251/567] Remove deprecated reflection calls from ArgumentAutowirer and related named arguments fix --- features/autowire.feature | 26 +++++++++++++++ src/Behat/Behat/Context/ContextFactory.php | 2 +- .../HelperContainer/ArgumentAutowirer.php | 32 ++++++++++++++++--- 3 files changed, 55 insertions(+), 5 deletions(-) diff --git a/features/autowire.feature b/features/autowire.feature index 5e2be789a..35f53e4b5 100644 --- a/features/autowire.feature +++ b/features/autowire.feature @@ -12,6 +12,7 @@ Feature: Helper services autowire - It only wires arguments that weren't otherwise set - Services must be last arguments in step definitions - Services must be last arguments in transformations + - Autowiring is not yet triggered for union types Background: Given a file named "behat.yaml" with: @@ -245,3 +246,28 @@ Feature: Helper services autowire """ When I run "behat --no-colors -f progress features/autowire.feature" Then it should pass + + @php8 + Scenario: Union constructor arguments + Given a file named "features/autowire.feature" with: + """ + Feature: + Scenario: + Given a step + """ + And a file named "features/bootstrap/FeatureContext.php" with: + """ + newInstanceArgs($arguments); + return $reflection->newInstanceArgs(array_values($arguments)); } return $reflection->newInstance(); diff --git a/src/Behat/Behat/HelperContainer/ArgumentAutowirer.php b/src/Behat/Behat/HelperContainer/ArgumentAutowirer.php index 8fd2712a0..fdb4aaa44 100644 --- a/src/Behat/Behat/HelperContainer/ArgumentAutowirer.php +++ b/src/Behat/Behat/HelperContainer/ArgumentAutowirer.php @@ -12,12 +12,14 @@ use Psr\Container\ContainerExceptionInterface; use Psr\Container\ContainerInterface as PsrContainerInterface; +use ReflectionClass; use ReflectionFunctionAbstract; +use ReflectionNamedType; use ReflectionParameter; use ReflectionException; /** - * Automatically wires arguments of a given function from inside the container by using type-hitns. + * Automatically wires arguments of a given function from inside the container by using type-hints. * * @author Konstantin Kudryashov */ @@ -53,7 +55,7 @@ public function autowireArguments(ReflectionFunctionAbstract $reflection, array $newArguments = $arguments; foreach ($reflection->getParameters() as $index => $parameter) { if ($this->isArgumentWireable($newArguments, $index, $parameter)) { - $newArguments[$index] = $this->container->get($parameter->getClass()->getName()); + $newArguments[$index] = $this->container->get($this->getClassFromParameter($parameter)); } } @@ -81,10 +83,32 @@ private function isArgumentWireable(array $arguments, $index, ReflectionParamete return false; } + if (!$parameter->getType() instanceof ReflectionNamedType) { + return false; + } + + return (bool) $this->getClassFromParameter($parameter); + } + + private function getClassFromParameter(ReflectionParameter $parameter) : ?string + { try { - return (bool) $parameter->getClass(); + $typeString = $parameter->getType()->getName(); + + if ($typeString == 'self') { + return $parameter->getDeclaringClass()->getName(); + } + elseif ($typeString == 'parent') { + return $parameter->getDeclaringClass()->getParentClass()->getName(); + } + + // will throw if not valid class + new ReflectionClass($typeString); + + return $typeString; + } catch (ReflectionException $e) { - return false; + return null; } } } From bdadad0d682dfa59a70c8682cb561ae494324025 Mon Sep 17 00:00:00 2001 From: Ciaran McNulty Date: Thu, 1 Oct 2020 21:13:11 +0100 Subject: [PATCH 252/567] Use COMPOSER_FLAGS in travis config --- .travis.yml | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/.travis.yml b/.travis.yml index afa03fbaf..b9f009dbf 100644 --- a/.travis.yml +++ b/.travis.yml @@ -15,11 +15,13 @@ jobs: - php: 7.2 env: SKIP_INTEROP=true - php: 7.2 - env: DEPENDENCIES='low' + env: COMPOSER_FLAGS='--prefer-lowest' - php: 7.4 env: SYMFONY_VERSION='^4.4' - php: nightly - env: PHP8=true + env: + - PHP8=true + - COMPOSER_FLAGS='--ignore-platform-reqs' before_install: - phpenv config-rm xdebug.ini || echo "XDebug is not enabled" @@ -27,8 +29,7 @@ before_install: before_script: - if [ "$SYMFONY_VERSION" != "" ]; then composer require --no-update "symfony/symfony:${SYMFONY_VERSION}"; fi; - if [ "$SKIP_INTEROP" != "" ]; then composer remove --dev --no-update container-interop/container-interop; fi; - - if [ "$DEPENDENCIES" != "low" ]; then composer update $([ -z "$PHP8" ] || echo "--ignore-platform-reqs") ; fi; - - if [ "$DEPENDENCIES" = "low" ]; then composer update --prefer-lowest; fi; + - composer update $COMPOSER_FLAGS - echo 'zend.exception_ignore_args=Off' >> ~/.phpenv/versions/$(phpenv version-name)/etc/conf.d/travis.ini - export PATH=./bin:$PATH From 5274cbef74870fb614c04e0e65df9a07d193867e Mon Sep 17 00:00:00 2001 From: Ciaran McNulty Date: Thu, 1 Oct 2020 21:13:29 +0100 Subject: [PATCH 253/567] Handle different error message when class does not exist --- features/bootstrap/FeatureContext.php | 3 ++- .../Testwork/Call/Handler/Exception/ClassNotFoundHandler.php | 2 +- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/features/bootstrap/FeatureContext.php b/features/bootstrap/FeatureContext.php index 05a6affd1..937c6c002 100644 --- a/features/bootstrap/FeatureContext.php +++ b/features/bootstrap/FeatureContext.php @@ -438,8 +438,9 @@ private function getOutput() // Replace wrong warning message of HHVM $output = str_replace('Notice: Undefined index: ', 'Notice: Undefined offset: ', $output); - // replace error message that changed in PHP + // replace error messages that changed in PHP8 $output = str_replace('Warning: Undefined array key','Notice: Undefined offset:', $output); + $output = preg_replace('/Class "([^"]+)" not found/', 'Class \'$1\' not found', $output); return trim(preg_replace("/ +$/m", '', $output)); } diff --git a/src/Behat/Testwork/Call/Handler/Exception/ClassNotFoundHandler.php b/src/Behat/Testwork/Call/Handler/Exception/ClassNotFoundHandler.php index b63d0fed1..6ddeee21e 100644 --- a/src/Behat/Testwork/Call/Handler/Exception/ClassNotFoundHandler.php +++ b/src/Behat/Testwork/Call/Handler/Exception/ClassNotFoundHandler.php @@ -22,7 +22,7 @@ */ abstract class ClassNotFoundHandler implements ExceptionHandler { - public const PATTERN = "/^Class '([^']+)' not found$/"; + public const PATTERN = "/^Class (?:'|\")([^'\"]+)(?:'|\") not found$/"; /** * {@inheritdoc} From cca91affa10111bb85e54034e734d3cb0fb28456 Mon Sep 17 00:00:00 2001 From: Ciaran McNulty Date: Thu, 1 Oct 2020 21:24:54 +0100 Subject: [PATCH 254/567] More explicit null returns --- .../Transformation/ReturnTypeTransformation.php | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/src/Behat/Behat/Transformation/Transformation/ReturnTypeTransformation.php b/src/Behat/Behat/Transformation/Transformation/ReturnTypeTransformation.php index fa39a31d5..7ac05d8f9 100644 --- a/src/Behat/Behat/Transformation/Transformation/ReturnTypeTransformation.php +++ b/src/Behat/Behat/Transformation/Transformation/ReturnTypeTransformation.php @@ -223,15 +223,20 @@ private function hasPosition($index) */ private function getClassReflection() : closure { - return function (ReflectionParameter $parameter) { + return function (ReflectionParameter $parameter) : ?ReflectionClass + { $t = $parameter->getType(); if ($t instanceof ReflectionNamedType) { try { return new ReflectionClass($t->getName()); } - catch (\TypeError $t) {} + catch (\TypeError $t) { + return null; + } } + + return null; }; } } From 200e8b36a402b1db02acdeb474349be3a31b386f Mon Sep 17 00:00:00 2001 From: Steef Min Date: Fri, 2 Oct 2020 17:50:41 +0200 Subject: [PATCH 255/567] undo changelog update --- CHANGELOG.md | 3 --- 1 file changed, 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 7d4bcdd8c..df67f3c3d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -916,9 +916,6 @@ and this project adheres to [Semantic Versioning](http://semver.org/). * Initial release [Unreleased]: https://github.com/Behat/Behat/compare/v3.7.0...master -### Changed - * Added feature title as classname of testcase in junit output - [3.7.0]: https://github.com/Behat/Behat/compare/v3.6.1...v3.7.0 [3.6.1]: https://github.com/Behat/Behat/compare/v3.6.0...v3.6.1 [3.6.0]: https://github.com/Behat/Behat/compare/v3.5.0...v3.6.0 From f0f16bd1dbed28abbba36ef0e980a8a0adba1b66 Mon Sep 17 00:00:00 2001 From: Dariusz Gafka Date: Thu, 15 Oct 2020 15:53:12 +0200 Subject: [PATCH 256/567] Solves ambiguous usage of named arguments in PHP 8 --- src/Behat/Testwork/Call/Handler/RuntimeCallHandler.php | 1 + 1 file changed, 1 insertion(+) diff --git a/src/Behat/Testwork/Call/Handler/RuntimeCallHandler.php b/src/Behat/Testwork/Call/Handler/RuntimeCallHandler.php index 097273c21..1fbac8c47 100644 --- a/src/Behat/Testwork/Call/Handler/RuntimeCallHandler.php +++ b/src/Behat/Testwork/Call/Handler/RuntimeCallHandler.php @@ -105,6 +105,7 @@ private function executeCall(Call $call) $return = $exception = null; try { + $arguments = array_values($arguments); $this->validator->validateArguments($reflection, $arguments); $return = $callable(...array_values($arguments)); } catch (Exception $caught) { From ba84eed94a3c61ee56b9be5b057c8277b1594278 Mon Sep 17 00:00:00 2001 From: Dariusz Gafka Date: Fri, 16 Oct 2020 13:29:23 +0200 Subject: [PATCH 257/567] Update RuntimeCallHandler.php --- src/Behat/Testwork/Call/Handler/RuntimeCallHandler.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Behat/Testwork/Call/Handler/RuntimeCallHandler.php b/src/Behat/Testwork/Call/Handler/RuntimeCallHandler.php index 1fbac8c47..9f51cd06c 100644 --- a/src/Behat/Testwork/Call/Handler/RuntimeCallHandler.php +++ b/src/Behat/Testwork/Call/Handler/RuntimeCallHandler.php @@ -107,7 +107,7 @@ private function executeCall(Call $call) try { $arguments = array_values($arguments); $this->validator->validateArguments($reflection, $arguments); - $return = $callable(...array_values($arguments)); + $return = $callable(...$arguments); } catch (Exception $caught) { $exception = $caught; } From 8ab0276d20397b8ff182e0b61b42056fae1b8a93 Mon Sep 17 00:00:00 2001 From: Ciaran McNulty Date: Wed, 28 Oct 2020 16:48:40 +0000 Subject: [PATCH 258/567] Extra check when asking for the type --- src/Behat/Behat/HelperContainer/ArgumentAutowirer.php | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/Behat/Behat/HelperContainer/ArgumentAutowirer.php b/src/Behat/Behat/HelperContainer/ArgumentAutowirer.php index fdb4aaa44..0fbbe210c 100644 --- a/src/Behat/Behat/HelperContainer/ArgumentAutowirer.php +++ b/src/Behat/Behat/HelperContainer/ArgumentAutowirer.php @@ -83,17 +83,17 @@ private function isArgumentWireable(array $arguments, $index, ReflectionParamete return false; } - if (!$parameter->getType() instanceof ReflectionNamedType) { - return false; - } - return (bool) $this->getClassFromParameter($parameter); } private function getClassFromParameter(ReflectionParameter $parameter) : ?string { + if (!($type = $parameter->getType()) || !($type instanceof ReflectionNamedType)) { + return null; + } + try { - $typeString = $parameter->getType()->getName(); + $typeString = $type->getName(); if ($typeString == 'self') { return $parameter->getDeclaringClass()->getName(); From f6c7eb8e08684e4926d2443b93e7a540a46f6043 Mon Sep 17 00:00:00 2001 From: Ciaran McNulty Date: Sat, 31 Oct 2020 14:59:46 +0000 Subject: [PATCH 259/567] Remove whitespace MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Kévin Dunglas --- features/autowire.feature | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/features/autowire.feature b/features/autowire.feature index 35f53e4b5..4d31b6514 100644 --- a/features/autowire.feature +++ b/features/autowire.feature @@ -247,7 +247,7 @@ Feature: Helper services autowire When I run "behat --no-colors -f progress features/autowire.feature" Then it should pass - @php8 + @php8 Scenario: Union constructor arguments Given a file named "features/autowire.feature" with: """ From a72e81ba9b1fd686ad6031b428acf35d1ce02c71 Mon Sep 17 00:00:00 2001 From: Ciaran McNulty Date: Sat, 31 Oct 2020 15:11:13 +0000 Subject: [PATCH 260/567] Fix line number in feature --- features/error_reporting.feature | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/features/error_reporting.feature b/features/error_reporting.feature index 888d9b090..84895644f 100644 --- a/features/error_reporting.feature +++ b/features/error_reporting.feature @@ -148,6 +148,6 @@ Feature: Error Reporting When an exception is thrown # features/exception_in_scenario.feature:7 Exception: Exception is thrown in features/bootstrap/FeatureContext.php:56 Stack trace: - #0 src/Behat/Testwork/Call/Handler/RuntimeCallHandler.php(109): FeatureContext->anExceptionIsThrown() + #0 src/Behat/Testwork/Call/Handler/RuntimeCallHandler.php(110): FeatureContext->anExceptionIsThrown() #1 src/Behat/Testwork/Call/Handler/RuntimeCallHandler.php(64): Behat\Testwork\Call\Handler\RuntimeCallHandler->executeCall(Object(Behat\Behat\Definition\Call\DefinitionCall)) """ From 926ac7d7f73a50a0731bdbc0a0c8e369c8880138 Mon Sep 17 00:00:00 2001 From: Ciaran McNulty Date: Sun, 1 Nov 2020 15:12:53 +0000 Subject: [PATCH 261/567] Allow installation with PHP 8 --- composer.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/composer.json b/composer.json index b534907d2..eb62e92ea 100644 --- a/composer.json +++ b/composer.json @@ -14,7 +14,7 @@ ], "require": { - "php": "^7.2", + "php": "^7.2 || ^8.0", "ext-mbstring": "*", "behat/gherkin": "^4.6.0", "behat/transliterator": "^1.2", From 304661d4bc00934314c835c79fe36c0ce38da268 Mon Sep 17 00:00:00 2001 From: Ciaran McNulty Date: Sun, 1 Nov 2020 16:09:28 +0000 Subject: [PATCH 262/567] Prepare for 3.8.0 release --- CHANGELOG.md | 24 ++++++++++++++++++++++++ src/Behat/Behat/ApplicationFactory.php | 2 +- 2 files changed, 25 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index df67f3c3d..dec43ee9d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,30 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](http://keepachangelog.com/) and this project adheres to [Semantic Versioning](http://semver.org/). +## [3.8.0] - 2020-11-01 + +### Added + * [1198](https://github.com/Behat/Behat/pull/1198): Korean language translations ([@getsolaris](https://github.com/getsolaris)) + * [1252](https://github.com/Behat/Behat/pull/1252): Hungarian language translations ([@kolesar-andras](https://github.com/kolesar-andras)) + * [1217](https://github.com/Behat/Behat/pull/1217): Bulgarian language translations ([@toni-kolev](https://github.com/toni-kolev)) + * [1322](https://github.com/Behat/Behat/pull/1322): Feature title as classname in JUnit output ([@steefmin](https://github.com/steefmin)) + * [1313](https://github.com/Behat/Behat/pull/1313): PHP 8 support ([@ciaranmcnulty](https://github.com/ciaranmcnulty)) + * [1313](https://github.com/Behat/Behat/pull/1323): Further PHP 8 support ([@dgafka](https://github.com/dgafka)) + +### Fixed + + * [#1303](https://github.com/Behat/Behat/pull/1303): Error when running `--debug` with recent Symfony versions ([@jawira](https://github.com/jawira)) + * [#1311](https://github.com/Behat/Behat/pull/1311): Remove symfony deprecation messages about transChoice ([@guilliamxavier](https://github.com/guilliamxavier)) + * [#1318](https://github.com/Behat/Behat/pull/1318): Allow negated filters on scenario hoooks ([@andrewnicols ](https://github.com/andrewnicols)) + +### Changed + * [#1299](https://github.com/Behat/Behat/pull/1299): Removed support for PHP <7.2, Symfony <4.4 ([@upamil](https://github.com/pamil)) + * [#1310](https://github.com/Behat/Behat/pull/1310): Refactoring to use newer language features ([@rpkamp](https://github.com/rpkamp)) + * [#1315](https://github.com/Behat/Behat/pull/1315): Remove BC layer for unsuppored symfony dispatcher ([@rpkamp](https://github.com/rpkamp)) + * [#1314](https://github.com/Behat/Behat/pull/1314): Remove BC layer for unsuppored symfony translator ([@rpkamp](https://github.com/rpkamp)) + * [#1212](https://github.com/Behat/Behat/pull/1212): Updated composer description ([@tkotosz](https://github.com/tkotosz)) + * [#1317](https://github.com/Behat/Behat/pull/1317): Use PHPUnit8 for unit testing ([@phil-davis](https://github.com/phil-davis)) + ## [3.7.0] - 2020-06-03 ### Added diff --git a/src/Behat/Behat/ApplicationFactory.php b/src/Behat/Behat/ApplicationFactory.php index 87d71d720..f620c1c6e 100644 --- a/src/Behat/Behat/ApplicationFactory.php +++ b/src/Behat/Behat/ApplicationFactory.php @@ -46,7 +46,7 @@ */ final class ApplicationFactory extends BaseFactory { - public const VERSION = '3.7.0'; + public const VERSION = '3.8.0'; /** * {@inheritdoc} From 8fb8f0c85b5b1e07ee2a7409b643c03c0c9ffc96 Mon Sep 17 00:00:00 2001 From: Jakub Zalas Date: Mon, 2 Nov 2020 17:33:57 +0000 Subject: [PATCH 263/567] Migrate builds from Travis CI to GitHub actions --- .gitattributes | 2 +- .github/workflows/build.yml | 95 +++++++++++++++++++++++++++++++++++++ .travis.yml | 55 --------------------- CONTRIBUTING.md | 4 +- README.md | 2 +- 5 files changed, 99 insertions(+), 59 deletions(-) create mode 100644 .github/workflows/build.yml delete mode 100644 .travis.yml diff --git a/.gitattributes b/.gitattributes index 36a6efc3e..f2414cb29 100644 --- a/.gitattributes +++ b/.gitattributes @@ -3,7 +3,7 @@ .gitattributes export-ignore .gitignore export-ignore .scrutinizer.yml export-ignore -.travis.yml export-ignore +.github export-ignore appveyor.yml export-ignore box.json export-ignore phpunit.xml.dist export-ignore diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml new file mode 100644 index 000000000..9106dd456 --- /dev/null +++ b/.github/workflows/build.yml @@ -0,0 +1,95 @@ +name: Build + +on: + push: + branches: [master] + pull_request: + release: + types: [created] + +jobs: + tests: + runs-on: ubuntu-latest + name: Build and test + strategy: + fail-fast: false + matrix: + include: + - php: 7.2 + publish-phar: true + - php: 7.2 + skip-interop: true + - php: 7.2 + composer-flags: --prefer-lowest + - php: 7.3 + - php: 7.4 + - php: 7.4 + symfony-version: ^4.4 + - php: 8.0 + + steps: + - uses: actions/checkout@v2 + + - name: Setup PHP + uses: shivammathur/setup-php@v2 + with: + php-version: "${{ matrix.php }}" + ini-values: "phar.readonly=0,zend.exception_ignore_args=Off" + coverage: none + + - name: Update Symfony version + if: matrix.symfony-version != '' + run: composer require --no-update "symfony/symfony:${{ matrix.symfony-version }}" + + - name: Uninstall container interop + if: matrix.skip-interop + run: composer remove --dev --no-update container-interop/container-interop + + - name: Install dependencies + run: composer update ${{ matrix.composer-flags }} + + - name: Run tests (phpunit) + run: ./vendor/bin/phpunit + + - name: Run tests (Behat) + run: ./bin/behat -fprogress --strict $([ -z "${{ matrix.skip-interop }}" ] || echo "--tags ~@interop&&~@php8") + + - name: Run tests (Behat for PHP 8.0) + if: matrix.php >= 8.0 + run: ./bin/behat -fprogress --strict --tags=@php8 + + - name: Build the PHAR + if: matrix.php != '8.0' + run: | + curl -LSs https://box-project.github.io/box2/installer.php | php && + export PATH=.:$PATH && + rm -Rf ./vendor && + composer install --no-dev -o && + box.phar build + + - uses: actions/upload-artifact@v1 + name: Publish the PHAR + if: matrix.publish-phar + with: + name: behat.phar + path: behat.phar + + publish-phar: + runs-on: ubuntu-latest + name: Publish the PHAR + needs: tests + if: github.event_name == 'release' + steps: + - uses: actions/download-artifact@v1 + with: + name: behat.phar + path: . + - name: Upload behat.phar + uses: actions/upload-release-asset@v1 + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + with: + upload_url: ${{ github.event.release.upload_url }} + asset_path: behat.phar + asset_name: behat.phar + asset_content_type: application/zip diff --git a/.travis.yml b/.travis.yml deleted file mode 100644 index b9f009dbf..000000000 --- a/.travis.yml +++ /dev/null @@ -1,55 +0,0 @@ -language: php - -os: linux - -dist: xenial - -php: [7.2, 7.3, 7.4] - -cache: - directories: - - $HOME/.composer/cache - -jobs: - include: - - php: 7.2 - env: SKIP_INTEROP=true - - php: 7.2 - env: COMPOSER_FLAGS='--prefer-lowest' - - php: 7.4 - env: SYMFONY_VERSION='^4.4' - - php: nightly - env: - - PHP8=true - - COMPOSER_FLAGS='--ignore-platform-reqs' - -before_install: - - phpenv config-rm xdebug.ini || echo "XDebug is not enabled" - -before_script: - - if [ "$SYMFONY_VERSION" != "" ]; then composer require --no-update "symfony/symfony:${SYMFONY_VERSION}"; fi; - - if [ "$SKIP_INTEROP" != "" ]; then composer remove --dev --no-update container-interop/container-interop; fi; - - composer update $COMPOSER_FLAGS - - echo 'zend.exception_ignore_args=Off' >> ~/.phpenv/versions/$(phpenv version-name)/etc/conf.d/travis.ini - - export PATH=./bin:$PATH - -script: - - ./vendor/bin/phpunit - - behat -fprogress --strict $([ -z "$SKIP_INTEROP" ] || echo "--tags ~@interop&&~@php8") - - if [ "$PHP8" = true ]; then behat -fprogress --strict --tags=@php8; fi; - -before_deploy: - - curl -LSs https://box-project.github.io/box2/installer.php | php - - export PATH=.:$PATH - - rm -Rf ./vendor - - composer install --no-dev -o - - box.phar build - -deploy: - provider: releases - token: $GITHUB_API_KEY - file: behat.phar - cleanup: false - on: - tags: true - php: 5.6 diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 88e0b63b6..5754932c1 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -11,7 +11,7 @@ issues quicker than adding new features 2. Outline clearly in one/two sentences why that feature is important to you or why that problem causes you grief (and at what scale). This helps us properly prioritise what we're working on -3. Behat is [automatically tested](https://travis-ci.org/Behat/Behat) on every change. +3. Behat is [automatically tested](https://github.com/Behat/Behat/actions) on every change. If you have a problem, chances are high it is something very specific to your context and the more we know about it the more likely we would be able help. At the very least provide us with enough information about your feature files, context classes and local @@ -35,7 +35,7 @@ so that we adhere to [Semantic Versioning v2.0.0](http://semver.org/spec/v2.0.0. [CHANGELOG.md](CHANGELOG.md). You'd make our life even easier if you stick to [Keep a Changelog](http://keepachangelog.com/en/0.3.0/) format 5. Do not mess with the [`BehatApplication::VERSION`](src/Behat/Behat/ApplicationFactory.php#L48) version 6. Make sure you [ran tests](#running-tests) and didn't break anything. That will save some time for -[Travis](https://travis-ci.org) +[GitHub](https://github.com/Behat/Behat/actions) 7. Commit your code and submit a Pull Request, providing a clear description of a change, similar to the one you did in the changelog diff --git a/README.md b/README.md index 9aeb64e57..a666ce704 100644 --- a/README.md +++ b/README.md @@ -4,7 +4,7 @@ Behat is a BDD framework for PHP to help you test business expectations. [![Gitter chat](https://badges.gitter.im/Behat/Behat.svg)](https://gitter.im/Behat/Behat) [![License](https://poser.pugx.org/behat/behat/license.svg)](https://packagist.org/packages/behat/behat) -[![Unix Status](https://travis-ci.org/Behat/Behat.svg?branch=master)](https://travis-ci.org/Behat/Behat) +[![Unix Status](https://github.com/Behat/Behat/workflows/Build/badge.svg)](https://github.com/Behat/Behat/actions?query=workflow%3ABuild) [![Windows status](https://ci.appveyor.com/api/projects/status/9uc5sellmvbv02ei/branch/master?svg=true)](https://ci.appveyor.com/project/everzet/behat/branch/master) [![Scrutinizer Quality Score](https://scrutinizer-ci.com/g/Behat/Behat/badges/quality-score.png?s=ad84e95fc2405712f88a96d89b4f31dfe5c80fae)](https://scrutinizer-ci.com/g/Behat/Behat/) From 6b76871e98e3b0701ec2e608d6ee5d2eb82a0b46 Mon Sep 17 00:00:00 2001 From: Ciaran McNulty Date: Sat, 7 Nov 2020 14:14:00 +0000 Subject: [PATCH 264/567] Reproducer that triggers error Co-authored-by: Adam Quaile --- features/definitions_transformations.feature | 33 ++++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/features/definitions_transformations.feature b/features/definitions_transformations.feature index 77a5694c3..4598e102f 100644 --- a/features/definitions_transformations.feature +++ b/features/definitions_transformations.feature @@ -674,3 +674,36 @@ Feature: Step Arguments Transformations """ string given """ + + Scenario: Return type transformations don't cause issues with scalar type hints (regression) + Given a file named "features/scalar-transforms.feature" with: + """ + Feature: + + Scenario: + Then "string" should be passed + """ + And a file named "features/bootstrap/FeatureContext.php" with: + """ + Date: Sat, 7 Nov 2020 14:16:03 +0000 Subject: [PATCH 265/567] Catch the correct Exception when matching return type transforms --- .../Transformation/Transformation/ReturnTypeTransformation.php | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/Behat/Behat/Transformation/Transformation/ReturnTypeTransformation.php b/src/Behat/Behat/Transformation/Transformation/ReturnTypeTransformation.php index 7ac05d8f9..dd2e9c08c 100644 --- a/src/Behat/Behat/Transformation/Transformation/ReturnTypeTransformation.php +++ b/src/Behat/Behat/Transformation/Transformation/ReturnTypeTransformation.php @@ -17,6 +17,7 @@ use Behat\Testwork\Call\RuntimeCallee; use Closure; use ReflectionClass; +use ReflectionException; use ReflectionFunctionAbstract; use ReflectionMethod; use ReflectionParameter; @@ -231,7 +232,7 @@ private function getClassReflection() : closure try { return new ReflectionClass($t->getName()); } - catch (\TypeError $t) { + catch (ReflectionException $t) { return null; } } From fbb065457d523d9856d4b50775b4151a7598b510 Mon Sep 17 00:00:00 2001 From: Ciaran McNulty Date: Sat, 7 Nov 2020 15:55:18 +0000 Subject: [PATCH 266/567] Ready for 3.8.1 release --- CHANGELOG.md | 6 ++++++ src/Behat/Behat/ApplicationFactory.php | 2 +- 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index dec43ee9d..02347d1e9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,12 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](http://keepachangelog.com/) and this project adheres to [Semantic Versioning](http://semver.org/). +## [3.8.1] - 2020-11-07 + +### Fixed + + * [1329](https://github.com/Behat/Behat/pull/1329): Regression when using scalar type hints ([@ciaranmcnulty](https://github.com/ciaranmcnulty)) + ## [3.8.0] - 2020-11-01 ### Added diff --git a/src/Behat/Behat/ApplicationFactory.php b/src/Behat/Behat/ApplicationFactory.php index f620c1c6e..df699077e 100644 --- a/src/Behat/Behat/ApplicationFactory.php +++ b/src/Behat/Behat/ApplicationFactory.php @@ -46,7 +46,7 @@ */ final class ApplicationFactory extends BaseFactory { - public const VERSION = '3.8.0'; + public const VERSION = '3.8.1'; /** * {@inheritdoc} From 180fe7d111629cbc101705b5acabb2df0ad73e0b Mon Sep 17 00:00:00 2001 From: Ciaran McNulty Date: Mon, 15 Feb 2021 12:40:13 +0000 Subject: [PATCH 267/567] Fix syntax help test and bump gherkin dependency The change in the sort order of the translations broke this test --- composer.json | 2 +- features/syntax_help.feature | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/composer.json b/composer.json index eb62e92ea..4d60911a8 100644 --- a/composer.json +++ b/composer.json @@ -16,7 +16,7 @@ "require": { "php": "^7.2 || ^8.0", "ext-mbstring": "*", - "behat/gherkin": "^4.6.0", + "behat/gherkin": "^4.8.0", "behat/transliterator": "^1.2", "symfony/console": "^4.4 || ^5.0", "symfony/config": "^4.4 || ^5.0", diff --git a/features/syntax_help.feature b/features/syntax_help.feature index d0027901e..53905240f 100644 --- a/features/syntax_help.feature +++ b/features/syntax_help.feature @@ -11,7 +11,7 @@ Feature: Syntax helpers When I run "behat --no-colors --story-syntax" Then the output should contain: """ - [Business Need|Feature|Ability]: Internal operations + [Business Need|Ability|Feature]: Internal operations In order to stay secret As a secret organization We need to be able to erase past agents' memory From de435f2786a43527906c911cb60d05dd10934c3c Mon Sep 17 00:00:00 2001 From: konakona Date: Fri, 9 Apr 2021 15:11:55 +0800 Subject: [PATCH 268/567] Added Chiniese language Added Chiniese language --- i18n.php | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/i18n.php b/i18n.php index 8b0beff99..731a64f59 100644 --- a/i18n.php +++ b/i18n.php @@ -264,4 +264,21 @@ 'undefined_count' => '{1,21,31} %count% не определен|]1,Inf] %count% не определено', 'skipped_count' => '{1,21,31} %count% пропущен|]1,Inf] %count% пропущено', ), + 'cn' => array( + 'snippet_context_choice' => '%count% 有新的场景步骤, 请选择要生成代码片段的ContextClass:', + 'snippet_proposal_title' => '%count% 已经更新。 请检查生成片段:', + 'snippet_missing_title' => '您可以使用 --snippets-for CLI命令更新 %count% 的ContextClass:', + 'skipped_scenarios_title' => '跳过场景:', + 'failed_scenarios_title' => '失败的场景:', + 'failed_hooks_title' => '失败的挂钩(hooks):', + 'failed_steps_title' => '失败的步骤:', + 'pending_steps_title' => '生成的步骤:', + 'scenarios_count' => '{0} No scenarios|{1} 1 个场景|]1,Inf] %count% 个场景', + 'steps_count' => '{0} 没有步骤|{1} 1 个步骤|]1,Inf] %count% 个步骤', + 'passed_count' => '[1,Inf] %count% 个成功', + 'failed_count' => '[1,Inf] %count% 个失败', + 'pending_count' => '[1,Inf] %count% 个待实现方法', + 'undefined_count' => '[1,Inf] %count% 个未定义', + 'skipped_count' => '[1,Inf] %count% 个跳过', + ), ); From 1c37e81c6e212c23b628e7a2c7df288410526e7a Mon Sep 17 00:00:00 2001 From: konakona Date: Sat, 10 Apr 2021 21:15:33 +0800 Subject: [PATCH 269/567] Update i18n.php --- i18n.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/i18n.php b/i18n.php index 731a64f59..057be35d4 100644 --- a/i18n.php +++ b/i18n.php @@ -264,7 +264,7 @@ 'undefined_count' => '{1,21,31} %count% не определен|]1,Inf] %count% не определено', 'skipped_count' => '{1,21,31} %count% пропущен|]1,Inf] %count% пропущено', ), - 'cn' => array( + 'zh' => array( 'snippet_context_choice' => '%count% 有新的场景步骤, 请选择要生成代码片段的ContextClass:', 'snippet_proposal_title' => '%count% 已经更新。 请检查生成片段:', 'snippet_missing_title' => '您可以使用 --snippets-for CLI命令更新 %count% 的ContextClass:', From dc4f755930661d469f82050c6dbee02262ce1cb9 Mon Sep 17 00:00:00 2001 From: Remon van de Kamp Date: Tue, 27 Apr 2021 20:08:12 +0200 Subject: [PATCH 270/567] Introduce reading PHP8 Attributes for Given, When and Then steps --- features/attributes.feature | 54 ++++++++++++++ .../Context/Attribute/AttributeReader.php | 33 +++++++++ .../Reader/AttributedContextReader.php | 70 +++++++++++++++++++ .../ServiceContainer/ContextExtension.php | 59 +++++++++++++++- .../Behat/Definition/Attribute/Definition.php | 19 +++++ .../Behat/Definition/Attribute/Given.php | 28 ++++++++ src/Behat/Behat/Definition/Attribute/Then.php | 28 ++++++++ src/Behat/Behat/Definition/Attribute/When.php | 28 ++++++++ .../Attribute/DefinitionAttributeReader.php | 57 +++++++++++++++ .../ServiceContainer/DefinitionExtension.php | 13 ++++ 10 files changed, 388 insertions(+), 1 deletion(-) create mode 100644 features/attributes.feature create mode 100644 src/Behat/Behat/Context/Attribute/AttributeReader.php create mode 100644 src/Behat/Behat/Context/Reader/AttributedContextReader.php create mode 100644 src/Behat/Behat/Definition/Attribute/Definition.php create mode 100644 src/Behat/Behat/Definition/Attribute/Given.php create mode 100644 src/Behat/Behat/Definition/Attribute/Then.php create mode 100644 src/Behat/Behat/Definition/Attribute/When.php create mode 100644 src/Behat/Behat/Definition/Context/Attribute/DefinitionAttributeReader.php diff --git a/features/attributes.feature b/features/attributes.feature new file mode 100644 index 000000000..d5eae84a3 --- /dev/null +++ b/features/attributes.feature @@ -0,0 +1,54 @@ +Feature: attributes + In order to keep annotations shorter and faster to parse + As a tester + I need to be able to use PHP8 Attributes + + @php8 + Scenario: + Given a file named "features/bootstrap/FeatureContext.php" with: + """ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Behat\Behat\Context\Attribute; + +use ReflectionMethod; + +/** + * Reads Attributes of a provided context method into a Callee. + * + * @see AttributedContextReader + * + * @author Konstantin Kudryashov + */ +interface AttributeReader +{ + /** + * Reads all callees associated with a provided method. + * + * @param string $contextClass + * @param ReflectionMethod $method + * + * @return array + */ + public function readCallees($contextClass, ReflectionMethod $method); +} diff --git a/src/Behat/Behat/Context/Reader/AttributedContextReader.php b/src/Behat/Behat/Context/Reader/AttributedContextReader.php new file mode 100644 index 000000000..f6396b5be --- /dev/null +++ b/src/Behat/Behat/Context/Reader/AttributedContextReader.php @@ -0,0 +1,70 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Behat\Behat\Context\Reader; + +use Behat\Behat\Context\Attribute\AttributeReader; +use Behat\Behat\Context\Environment\ContextEnvironment; +use ReflectionClass; +use ReflectionMethod; + +/** + * Reads context callees by Attributes using registered Attribute readers. + * + * @author Konstantin Kudryashov + */ +class AttributedContextReader implements ContextReader +{ + /** + * @var AttributeReader[] + */ + private $readers = array(); + + /** + * Registers attribute reader. + * + * @param AttributeReader $reader + */ + public function registerAttributeReader(AttributeReader $reader) + { + $this->readers[] = $reader; + } + + /** + * {@inheritdoc} + */ + public function readContextCallees(ContextEnvironment $environment, $contextClass) + { + if (PHP_MAJOR_VERSION < 8) { + return []; + } + + $reflection = new ReflectionClass($contextClass); + + $callees = array(); + foreach ($reflection->getMethods(ReflectionMethod::IS_PUBLIC) as $method) { + foreach ($this->readMethodCallees($reflection->getName(), $method) as $callee) { + $callees[] = $callee; + } + } + + return $callees; + } + + private function readMethodCallees(string $contextClass, ReflectionMethod $method) + { + $callees = []; + foreach ($this->readers as $reader) { + $callees = array_merge($callees, $reader->readCallees($contextClass, $method)); + } + + return $callees; + } +} diff --git a/src/Behat/Behat/Context/ServiceContainer/ContextExtension.php b/src/Behat/Behat/Context/ServiceContainer/ContextExtension.php index 1aa833600..26c2796a4 100644 --- a/src/Behat/Behat/Context/ServiceContainer/ContextExtension.php +++ b/src/Behat/Behat/Context/ServiceContainer/ContextExtension.php @@ -46,7 +46,7 @@ final class ContextExtension implements Extension private const ENVIRONMENT_READER_ID = EnvironmentExtension::READER_TAG . '.context'; private const SUITE_SETUP_ID = SuiteExtension::SETUP_TAG . '.suite_with_contexts'; private const ANNOTATED_CONTEXT_READER_ID = self::READER_TAG . '.annotated'; - + private const ATTRIBUTED_CONTEXT_READER_ID = self::READER_TAG . '.attributed'; /* * Available extension points @@ -56,6 +56,7 @@ final class ContextExtension implements Extension public const INITIALIZER_TAG = 'context.initializer'; public const READER_TAG = 'context.reader'; public const ANNOTATION_READER_TAG = 'context.annotation_reader'; + public const ATTRIBUTE_READER_TAG = 'context.attribute_reader'; public const CLASS_GENERATOR_TAG = 'context.class_generator'; public const SUITE_SCOPED_RESOLVER_FACTORY_TAG = 'context.argument.suite_resolver_factory'; @@ -125,6 +126,7 @@ public function process(ContainerBuilder $container) $this->processContextReaders($container); $this->processClassGenerators($container); $this->processAnnotationReaders($container); + $this->processAttributeReaders($container); } /** @@ -252,6 +254,20 @@ private function loadDefaultClassGenerators(ContainerBuilder $container) * @param ContainerBuilder $container */ private function loadDefaultContextReaders(ContainerBuilder $container) + { + $this->loadAnnotatedContextReader($container); + + $this->loadAttributedContextReader($container); + + $this->loadTranslatableContextReader($container); + } + + /** + * Loads AnnotatedContextReader + * + * @param ContainerBuilder $container + */ + private function loadAnnotatedContextReader(ContainerBuilder $container) { $definition = new Definition('Behat\Behat\Context\Reader\AnnotatedContextReader'); $container->setDefinition(self::ANNOTATED_CONTEXT_READER_ID, $definition); @@ -261,7 +277,33 @@ private function loadDefaultContextReaders(ContainerBuilder $container) )); $definition->addTag(self::READER_TAG, array('priority' => 50)); $container->setDefinition(self::ANNOTATED_CONTEXT_READER_ID . '.cached', $definition); + } + /** + * Loads AttributedContextReader + * + * @param ContainerBuilder $container + */ + private function loadAttributedContextReader(ContainerBuilder $container) + { + $definition = new Definition('Behat\Behat\Context\Reader\AttributedContextReader'); + $container->setDefinition(self::ATTRIBUTED_CONTEXT_READER_ID, $definition); + + $definition = new Definition('Behat\Behat\Context\Reader\ContextReaderCachedPerContext', array( + new Reference(self::ATTRIBUTED_CONTEXT_READER_ID) + )); + $definition->addTag(self::READER_TAG, array('priority' => 50)); + $container->setDefinition(self::ATTRIBUTED_CONTEXT_READER_ID . '.cached', $definition); + return $definition; + } + + /** + * Loads TranslatableContextReader + * + * @param ContainerBuilder $container + */ + private function loadTranslatableContextReader(ContainerBuilder $container) + { $definition = new Definition('Behat\Behat\Context\Reader\TranslatableContextReader', array( new Reference(TranslatorExtension::TRANSLATOR_ID) )); @@ -378,4 +420,19 @@ private function processAnnotationReaders(ContainerBuilder $container) $definition->addMethodCall('registerAnnotationReader', array($reference)); } } + + /** + * Processes all attribute readers. + * + * @param ContainerBuilder $container + */ + private function processAttributeReaders(ContainerBuilder $container) + { + $references = $this->processor->findAndSortTaggedServices($container, self::ATTRIBUTE_READER_TAG); + $definition = $container->getDefinition(self::ATTRIBUTED_CONTEXT_READER_ID); + + foreach ($references as $reference) { + $definition->addMethodCall('registerAttributeReader', array($reference)); + } + } } diff --git a/src/Behat/Behat/Definition/Attribute/Definition.php b/src/Behat/Behat/Definition/Attribute/Definition.php new file mode 100644 index 000000000..64f691bb9 --- /dev/null +++ b/src/Behat/Behat/Definition/Attribute/Definition.php @@ -0,0 +1,19 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Behat\Behat\Definition\Attribute; + +/** + * Marker interface for all Attributes regarding + * Call definitions + */ +interface Definition +{ +} diff --git a/src/Behat/Behat/Definition/Attribute/Given.php b/src/Behat/Behat/Definition/Attribute/Given.php new file mode 100644 index 000000000..42a9e9345 --- /dev/null +++ b/src/Behat/Behat/Definition/Attribute/Given.php @@ -0,0 +1,28 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Behat\Behat\Definition\Attribute; + +/** + * Represents an Attribute for Given steps + */ +#[\Attribute(\Attribute::TARGET_METHOD)] +class Given implements Definition +{ + /** + * @var string + */ + public $pattern; + + public function __construct($pattern = null) + { + $this->pattern = $pattern; + } +} diff --git a/src/Behat/Behat/Definition/Attribute/Then.php b/src/Behat/Behat/Definition/Attribute/Then.php new file mode 100644 index 000000000..b14911d7f --- /dev/null +++ b/src/Behat/Behat/Definition/Attribute/Then.php @@ -0,0 +1,28 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Behat\Behat\Definition\Attribute; + +/** + * Represents an Attribute for Then steps + */ +#[\Attribute(\Attribute::TARGET_METHOD)] +class Then implements Definition +{ + /** + * @var string + */ + public $pattern; + + public function __construct($pattern = null) + { + $this->pattern = $pattern; + } +} diff --git a/src/Behat/Behat/Definition/Attribute/When.php b/src/Behat/Behat/Definition/Attribute/When.php new file mode 100644 index 000000000..a7c134111 --- /dev/null +++ b/src/Behat/Behat/Definition/Attribute/When.php @@ -0,0 +1,28 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Behat\Behat\Definition\Attribute; + +/** + * Represents an Attribute for When steps + */ +#[\Attribute(\Attribute::TARGET_METHOD)] +class When implements Definition +{ + /** + * @var string + */ + public $pattern; + + public function __construct($pattern = null) + { + $this->pattern = $pattern; + } +} diff --git a/src/Behat/Behat/Definition/Context/Attribute/DefinitionAttributeReader.php b/src/Behat/Behat/Definition/Context/Attribute/DefinitionAttributeReader.php new file mode 100644 index 000000000..9f506d864 --- /dev/null +++ b/src/Behat/Behat/Definition/Context/Attribute/DefinitionAttributeReader.php @@ -0,0 +1,57 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Behat\Behat\Definition\Context\Attribute; + +use Behat\Behat\Context\Attribute\AttributeReader; +use Behat\Behat\Definition\Attribute\Definition; +use Behat\Behat\Definition\Attribute\Given; +use Behat\Behat\Definition\Attribute\Then; +use Behat\Behat\Definition\Attribute\When; +use ReflectionMethod; + +/** + * Reads definition Attributes from the context class. + * + * @author Konstantin Kudryashov + */ +class DefinitionAttributeReader implements AttributeReader +{ + /** + * @var string[] + */ + private static $classes = array( + Given::class => 'Behat\Behat\Definition\Call\Given', + When::class => 'Behat\Behat\Definition\Call\When', + Then::class => 'Behat\Behat\Definition\Call\Then', + ); + + /** + * @{inheritdoc} + */ + public function readCallees($contextClass, ReflectionMethod $method) + { + if (PHP_MAJOR_VERSION < 8) { + return []; + } + + $attributes = $method->getAttributes(Definition::class, \ReflectionAttribute::IS_INSTANCEOF); + + $callees = []; + foreach ($attributes as $attribute) { + $class = static::$classes[$attribute->getName()]; + $callable = array($contextClass, $method->getName()); + + $callees[] = new $class($attribute->newInstance()->pattern, $callable, null); + } + + return $callees; + } +} diff --git a/src/Behat/Behat/Definition/ServiceContainer/DefinitionExtension.php b/src/Behat/Behat/Definition/ServiceContainer/DefinitionExtension.php index 2b014da5d..7730f71ed 100644 --- a/src/Behat/Behat/Definition/ServiceContainer/DefinitionExtension.php +++ b/src/Behat/Behat/Definition/ServiceContainer/DefinitionExtension.php @@ -97,6 +97,7 @@ public function load(ContainerBuilder $container, array $config) $this->loadDefaultSearchEngines($container); $this->loadDefaultPatternPolicies($container); $this->loadAnnotationReader($container); + $this->loadAttributeReader($container); $this->loadDefinitionPrinters($container); $this->loadController($container); } @@ -217,6 +218,18 @@ private function loadAnnotationReader(ContainerBuilder $container) $container->setDefinition(ContextExtension::ANNOTATION_READER_TAG . '.definition', $definition); } + /** + * Loads definition Attribute reader. + * + * @param ContainerBuilder $container + */ + private function loadAttributeReader(ContainerBuilder $container) + { + $definition = new Definition('\Behat\Behat\Definition\Context\Attribute\DefinitionAttributeReader'); + $definition->addTag(ContextExtension::ATTRIBUTE_READER_TAG, array('priority' => 50)); + $container->setDefinition(ContextExtension::ATTRIBUTE_READER_TAG . '.definition', $definition); + } + /** * Loads definition printers. * From 839f551f601f9c75f229722f09e081f141dbf577 Mon Sep 17 00:00:00 2001 From: Remon van de Kamp Date: Fri, 30 Apr 2021 10:33:03 +0200 Subject: [PATCH 271/567] Rename AttributedContextReader to AttributeContextReader It just reads nicer and makes it a little bit more clear what going on. I.e. it's not a reader that attributed to something/someone, it's just a reader that reads Attributes. --- src/Behat/Behat/Context/Attribute/AttributeReader.php | 2 +- .../{AttributedContextReader.php => AttributeContextReader.php} | 2 +- src/Behat/Behat/Context/ServiceContainer/ContextExtension.php | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) rename src/Behat/Behat/Context/Reader/{AttributedContextReader.php => AttributeContextReader.php} (96%) diff --git a/src/Behat/Behat/Context/Attribute/AttributeReader.php b/src/Behat/Behat/Context/Attribute/AttributeReader.php index fbc838b1f..b08ff8b77 100644 --- a/src/Behat/Behat/Context/Attribute/AttributeReader.php +++ b/src/Behat/Behat/Context/Attribute/AttributeReader.php @@ -15,7 +15,7 @@ /** * Reads Attributes of a provided context method into a Callee. * - * @see AttributedContextReader + * @see AttributeContextReader * * @author Konstantin Kudryashov */ diff --git a/src/Behat/Behat/Context/Reader/AttributedContextReader.php b/src/Behat/Behat/Context/Reader/AttributeContextReader.php similarity index 96% rename from src/Behat/Behat/Context/Reader/AttributedContextReader.php rename to src/Behat/Behat/Context/Reader/AttributeContextReader.php index f6396b5be..625e9955d 100644 --- a/src/Behat/Behat/Context/Reader/AttributedContextReader.php +++ b/src/Behat/Behat/Context/Reader/AttributeContextReader.php @@ -20,7 +20,7 @@ * * @author Konstantin Kudryashov */ -class AttributedContextReader implements ContextReader +class AttributeContextReader implements ContextReader { /** * @var AttributeReader[] diff --git a/src/Behat/Behat/Context/ServiceContainer/ContextExtension.php b/src/Behat/Behat/Context/ServiceContainer/ContextExtension.php index 26c2796a4..6dba2568e 100644 --- a/src/Behat/Behat/Context/ServiceContainer/ContextExtension.php +++ b/src/Behat/Behat/Context/ServiceContainer/ContextExtension.php @@ -286,7 +286,7 @@ private function loadAnnotatedContextReader(ContainerBuilder $container) */ private function loadAttributedContextReader(ContainerBuilder $container) { - $definition = new Definition('Behat\Behat\Context\Reader\AttributedContextReader'); + $definition = new Definition('Behat\Behat\Context\Reader\AttributeContextReader'); $container->setDefinition(self::ATTRIBUTED_CONTEXT_READER_ID, $definition); $definition = new Definition('Behat\Behat\Context\Reader\ContextReaderCachedPerContext', array( From 7736793acd8a06c48b0d59b89736bd4849de09bd Mon Sep 17 00:00:00 2001 From: Remon van de Kamp Date: Fri, 30 Apr 2021 11:07:47 +0200 Subject: [PATCH 272/567] Extract DocBlock description extraction to helper class --- .../Context/Annotation/DocBlockHelper.php | 42 +++++++++++++++++++ .../Context/Reader/AnnotatedContextReader.php | 34 +-------------- 2 files changed, 44 insertions(+), 32 deletions(-) create mode 100644 src/Behat/Behat/Context/Annotation/DocBlockHelper.php diff --git a/src/Behat/Behat/Context/Annotation/DocBlockHelper.php b/src/Behat/Behat/Context/Annotation/DocBlockHelper.php new file mode 100644 index 000000000..9118b82f9 --- /dev/null +++ b/src/Behat/Behat/Context/Annotation/DocBlockHelper.php @@ -0,0 +1,42 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Behat\Behat\Context\Annotation; + +/** + * Helper class for DocBlock parsing + */ +class DocBlockHelper +{ + /** + * Extracts a description from the provided docblock, + * with support for multiline descriptions. + */ + public static function extractDescription(string $docBlock): string + { + // Remove indentation + $description = preg_replace('/^[\s\t]*/m', '', $docBlock); + + // Remove block comment syntax + $description = preg_replace('/^\/\*\*\s*|^\s*\*\s|^\s*\*\/$/m', '', $description); + + // Remove annotations + $description = preg_replace('/^@.*$/m', '', $description); + + // Ignore docs after a "--" separator + if (preg_match('/^--.*$/m', $description)) { + $descriptionParts = preg_split('/^--.*$/m', $description); + $description = array_shift($descriptionParts); + } + + // Trim leading and trailing newlines + return trim($description, "\r\n"); + } +} diff --git a/src/Behat/Behat/Context/Reader/AnnotatedContextReader.php b/src/Behat/Behat/Context/Reader/AnnotatedContextReader.php index 2d5963415..3904f1b65 100644 --- a/src/Behat/Behat/Context/Reader/AnnotatedContextReader.php +++ b/src/Behat/Behat/Context/Reader/AnnotatedContextReader.php @@ -11,6 +11,7 @@ namespace Behat\Behat\Context\Reader; use Behat\Behat\Context\Annotation\AnnotationReader; +use Behat\Behat\Context\Annotation\DocBlockHelper; use Behat\Behat\Context\Environment\ContextEnvironment; use Behat\Testwork\Call\Callee; use ReflectionClass; @@ -110,7 +111,7 @@ private function readMethodCallees($class, ReflectionMethod $method) private function readDocBlockCallees($class, ReflectionMethod $method, $docBlock) { $callees = array(); - $description = $this->readDescription($docBlock); + $description = DocBlockHelper::extractDescription($docBlock); $docBlock = $this->mergeMultilines($docBlock); foreach (explode("\n", $docBlock) as $docLine) { @@ -144,37 +145,6 @@ private function mergeMultilines($docBlock) return preg_replace("#\\\\$\s*+\*\s*+([^\\\\$]++)#m", '$1', $docBlock); } - /** - * Extracts a description from the provided docblock, - * with support for multiline descriptions. - * - * @param string $docBlock - * - * @return string - */ - private function readDescription($docBlock) - { - // Remove indentation - $description = preg_replace('/^[\s\t]*/m', '', $docBlock); - - // Remove block comment syntax - $description = preg_replace('/^\/\*\*\s*|^\s*\*\s|^\s*\*\/$/m', '', $description); - - // Remove annotations - $description = preg_replace('/^@.*$/m', '', $description); - - // Ignore docs after a "--" separator - if (preg_match('/^--.*$/m', $description)) { - $descriptionParts = preg_split('/^--.*$/m', $description); - $description = array_shift($descriptionParts); - } - - // Trim leading and trailing newlines - $description = trim($description, "\r\n"); - - return $description; - } - /** * Checks if provided doc lien is empty. * From 5c589d1f6af10e4208a4add256bf3f4722e13e2e Mon Sep 17 00:00:00 2001 From: Remon van de Kamp Date: Fri, 30 Apr 2021 11:08:13 +0200 Subject: [PATCH 273/567] Read description from docblock in DefinitionAttributeReader --- .../Context/Attribute/DefinitionAttributeReader.php | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/src/Behat/Behat/Definition/Context/Attribute/DefinitionAttributeReader.php b/src/Behat/Behat/Definition/Context/Attribute/DefinitionAttributeReader.php index 9f506d864..5ee6ae0c5 100644 --- a/src/Behat/Behat/Definition/Context/Attribute/DefinitionAttributeReader.php +++ b/src/Behat/Behat/Definition/Context/Attribute/DefinitionAttributeReader.php @@ -10,6 +10,7 @@ namespace Behat\Behat\Definition\Context\Attribute; +use Behat\Behat\Context\Annotation\DocBlockHelper; use Behat\Behat\Context\Attribute\AttributeReader; use Behat\Behat\Definition\Attribute\Definition; use Behat\Behat\Definition\Attribute\Given; @@ -48,8 +49,12 @@ public function readCallees($contextClass, ReflectionMethod $method) foreach ($attributes as $attribute) { $class = static::$classes[$attribute->getName()]; $callable = array($contextClass, $method->getName()); + $description = null; + if ($docBlock = $method->getDocComment()) { + $description = DocBlockHelper::extractDescription($docBlock); + } - $callees[] = new $class($attribute->newInstance()->pattern, $callable, null); + $callees[] = new $class($attribute->newInstance()->pattern, $callable, $description); } return $callees; From 959f7c7927445efc1b2ef37c0b061227dfde9010 Mon Sep 17 00:00:00 2001 From: Remon van de Kamp Date: Fri, 30 Apr 2021 11:10:51 +0200 Subject: [PATCH 274/567] Mark Attribute related classes as final --- src/Behat/Behat/Context/Reader/AttributeContextReader.php | 2 +- src/Behat/Behat/Definition/Attribute/Given.php | 2 +- src/Behat/Behat/Definition/Attribute/Then.php | 2 +- src/Behat/Behat/Definition/Attribute/When.php | 2 +- .../Context/Attribute/DefinitionAttributeReader.php | 4 ++-- 5 files changed, 6 insertions(+), 6 deletions(-) diff --git a/src/Behat/Behat/Context/Reader/AttributeContextReader.php b/src/Behat/Behat/Context/Reader/AttributeContextReader.php index 625e9955d..46f616282 100644 --- a/src/Behat/Behat/Context/Reader/AttributeContextReader.php +++ b/src/Behat/Behat/Context/Reader/AttributeContextReader.php @@ -20,7 +20,7 @@ * * @author Konstantin Kudryashov */ -class AttributeContextReader implements ContextReader +final class AttributeContextReader implements ContextReader { /** * @var AttributeReader[] diff --git a/src/Behat/Behat/Definition/Attribute/Given.php b/src/Behat/Behat/Definition/Attribute/Given.php index 42a9e9345..7f43b3fcd 100644 --- a/src/Behat/Behat/Definition/Attribute/Given.php +++ b/src/Behat/Behat/Definition/Attribute/Given.php @@ -14,7 +14,7 @@ * Represents an Attribute for Given steps */ #[\Attribute(\Attribute::TARGET_METHOD)] -class Given implements Definition +final class Given implements Definition { /** * @var string diff --git a/src/Behat/Behat/Definition/Attribute/Then.php b/src/Behat/Behat/Definition/Attribute/Then.php index b14911d7f..f0f38d1f0 100644 --- a/src/Behat/Behat/Definition/Attribute/Then.php +++ b/src/Behat/Behat/Definition/Attribute/Then.php @@ -14,7 +14,7 @@ * Represents an Attribute for Then steps */ #[\Attribute(\Attribute::TARGET_METHOD)] -class Then implements Definition +final class Then implements Definition { /** * @var string diff --git a/src/Behat/Behat/Definition/Attribute/When.php b/src/Behat/Behat/Definition/Attribute/When.php index a7c134111..3487547f0 100644 --- a/src/Behat/Behat/Definition/Attribute/When.php +++ b/src/Behat/Behat/Definition/Attribute/When.php @@ -14,7 +14,7 @@ * Represents an Attribute for When steps */ #[\Attribute(\Attribute::TARGET_METHOD)] -class When implements Definition +final class When implements Definition { /** * @var string diff --git a/src/Behat/Behat/Definition/Context/Attribute/DefinitionAttributeReader.php b/src/Behat/Behat/Definition/Context/Attribute/DefinitionAttributeReader.php index 5ee6ae0c5..380c1c896 100644 --- a/src/Behat/Behat/Definition/Context/Attribute/DefinitionAttributeReader.php +++ b/src/Behat/Behat/Definition/Context/Attribute/DefinitionAttributeReader.php @@ -23,7 +23,7 @@ * * @author Konstantin Kudryashov */ -class DefinitionAttributeReader implements AttributeReader +final class DefinitionAttributeReader implements AttributeReader { /** * @var string[] @@ -47,7 +47,7 @@ public function readCallees($contextClass, ReflectionMethod $method) $callees = []; foreach ($attributes as $attribute) { - $class = static::$classes[$attribute->getName()]; + $class = self::$classes[$attribute->getName()]; $callable = array($contextClass, $method->getName()); $description = null; if ($docBlock = $method->getDocComment()) { From c352f2427378f99478df0a571043a934c8b03f3c Mon Sep 17 00:00:00 2001 From: Remon van de Kamp Date: Fri, 30 Apr 2021 11:11:29 +0200 Subject: [PATCH 275/567] Mark Attribute Definition as internal --- src/Behat/Behat/Definition/Attribute/Definition.php | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/Behat/Behat/Definition/Attribute/Definition.php b/src/Behat/Behat/Definition/Attribute/Definition.php index 64f691bb9..300c0c3c4 100644 --- a/src/Behat/Behat/Definition/Attribute/Definition.php +++ b/src/Behat/Behat/Definition/Attribute/Definition.php @@ -13,6 +13,8 @@ /** * Marker interface for all Attributes regarding * Call definitions + * + * @internal Only meant as marker, not as an extension point */ interface Definition { From b18555b0e7044c1e7eeca46ce8f4167bfd197a09 Mon Sep 17 00:00:00 2001 From: Remon van de Kamp Date: Fri, 30 Apr 2021 11:22:32 +0200 Subject: [PATCH 276/567] Allow repetition of definition attributes --- features/attributes.feature | 49 ++++++++++++------- .../Behat/Definition/Attribute/Given.php | 2 +- src/Behat/Behat/Definition/Attribute/Then.php | 2 +- src/Behat/Behat/Definition/Attribute/When.php | 2 +- 4 files changed, 34 insertions(+), 21 deletions(-) diff --git a/features/attributes.feature b/features/attributes.feature index d5eae84a3..6b994802a 100644 --- a/features/attributes.feature +++ b/features/attributes.feature @@ -15,40 +15,53 @@ Feature: attributes class FeatureContext implements \Behat\Behat\Context\Context { #[Given('I have :count apple(s)')] - public function iHaveApples($count) { } + #[Given('I have :count banana(s)')] + public function iHaveFruit($count) { } - #[When('I ate :count apple(s)')] - public function iAteApples($count) { } + #[When('I eat :count apple(s)')] + #[When('I eat :count banana(s)')] + public function iEatFruit($count) { } #[Then('I should have :count apple(s)')] - public function iShouldHaveApples($count) { } + #[Then('I should have :count banana(s)')] + public function iShouldHaveFruit($count) { } } """ And a file named "features/some.feature" with: """ - Feature: Apples story - In order to eat apple + Feature: Fruit story + In order to eat fruit As a little kid - I need to have an apple in my pocket + I need to have fruit in my pocket - Scenario: I'm little hungry + Scenario: I'm little hungry for apples Given I have 3 apples - When I ate 1 apple + When I eat 1 apple Then I should have 2 apples + + Scenario: I'm little hungry for bananas + Given I have 3 bananas + When I eat 1 banana + Then I should have 2 bananas """ When I run "behat --no-colors -fpretty --format-settings='{\"paths\": true}' features" Then it should pass with: """ - Feature: Apples story - In order to eat apple + Feature: Fruit story + In order to eat fruit As a little kid - I need to have an apple in my pocket + I need to have fruit in my pocket + + Scenario: I'm little hungry for apples # features/some.feature:6 + Given I have 3 apples # FeatureContext::iHaveFruit() + When I eat 1 apple # FeatureContext::iEatFruit() + Then I should have 2 apples # FeatureContext::iShouldHaveFruit() - Scenario: I'm little hungry # features/some.feature:6 - Given I have 3 apples # FeatureContext::iHaveApples() - When I ate 1 apple # FeatureContext::iAteApples() - Then I should have 2 apples # FeatureContext::iShouldHaveApples() + Scenario: I'm little hungry for bananas # features/some.feature:11 + Given I have 3 bananas # FeatureContext::iHaveFruit() + When I eat 1 banana # FeatureContext::iEatFruit() + Then I should have 2 bananas # FeatureContext::iShouldHaveFruit() - 1 scenario (1 passed) - 3 steps (3 passed) + 2 scenarios (2 passed) + 6 steps (6 passed) """ diff --git a/src/Behat/Behat/Definition/Attribute/Given.php b/src/Behat/Behat/Definition/Attribute/Given.php index 7f43b3fcd..951ed0a94 100644 --- a/src/Behat/Behat/Definition/Attribute/Given.php +++ b/src/Behat/Behat/Definition/Attribute/Given.php @@ -13,7 +13,7 @@ /** * Represents an Attribute for Given steps */ -#[\Attribute(\Attribute::TARGET_METHOD)] +#[\Attribute(\Attribute::TARGET_METHOD | \Attribute::IS_REPEATABLE)] final class Given implements Definition { /** diff --git a/src/Behat/Behat/Definition/Attribute/Then.php b/src/Behat/Behat/Definition/Attribute/Then.php index f0f38d1f0..33c38bf42 100644 --- a/src/Behat/Behat/Definition/Attribute/Then.php +++ b/src/Behat/Behat/Definition/Attribute/Then.php @@ -13,7 +13,7 @@ /** * Represents an Attribute for Then steps */ -#[\Attribute(\Attribute::TARGET_METHOD)] +#[\Attribute(\Attribute::TARGET_METHOD | \Attribute::IS_REPEATABLE)] final class Then implements Definition { /** diff --git a/src/Behat/Behat/Definition/Attribute/When.php b/src/Behat/Behat/Definition/Attribute/When.php index 3487547f0..64d2a1b68 100644 --- a/src/Behat/Behat/Definition/Attribute/When.php +++ b/src/Behat/Behat/Definition/Attribute/When.php @@ -13,7 +13,7 @@ /** * Represents an Attribute for When steps */ -#[\Attribute(\Attribute::TARGET_METHOD)] +#[\Attribute(\Attribute::TARGET_METHOD | \Attribute::IS_REPEATABLE)] final class When implements Definition { /** From 5c571cc43da5fcd8adef0731268a2c8891dc140d Mon Sep 17 00:00:00 2001 From: Remon van de Kamp Date: Fri, 30 Apr 2021 11:24:03 +0200 Subject: [PATCH 277/567] Use scalar type hints in AttributeReader --- src/Behat/Behat/Context/Attribute/AttributeReader.php | 2 +- .../Definition/Context/Attribute/DefinitionAttributeReader.php | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Behat/Behat/Context/Attribute/AttributeReader.php b/src/Behat/Behat/Context/Attribute/AttributeReader.php index b08ff8b77..bd15dff7a 100644 --- a/src/Behat/Behat/Context/Attribute/AttributeReader.php +++ b/src/Behat/Behat/Context/Attribute/AttributeReader.php @@ -29,5 +29,5 @@ interface AttributeReader * * @return array */ - public function readCallees($contextClass, ReflectionMethod $method); + public function readCallees(string $contextClass, ReflectionMethod $method); } diff --git a/src/Behat/Behat/Definition/Context/Attribute/DefinitionAttributeReader.php b/src/Behat/Behat/Definition/Context/Attribute/DefinitionAttributeReader.php index 380c1c896..f2e37bda5 100644 --- a/src/Behat/Behat/Definition/Context/Attribute/DefinitionAttributeReader.php +++ b/src/Behat/Behat/Definition/Context/Attribute/DefinitionAttributeReader.php @@ -37,7 +37,7 @@ final class DefinitionAttributeReader implements AttributeReader /** * @{inheritdoc} */ - public function readCallees($contextClass, ReflectionMethod $method) + public function readCallees(string $contextClass, ReflectionMethod $method) { if (PHP_MAJOR_VERSION < 8) { return []; From c17856437a34f09c698c97621a2afd0902aa26ce Mon Sep 17 00:00:00 2001 From: Remon van de Kamp Date: Fri, 30 Apr 2021 11:29:37 +0200 Subject: [PATCH 278/567] Move step definition Attributes to (new) Behat\Step namespace --- composer.json | 3 ++- features/attributes.feature | 3 +-- .../Context/Attribute/DefinitionAttributeReader.php | 8 ++++---- .../{Behat/Definition/Attribute => Step}/Definition.php | 2 +- src/Behat/{Behat/Definition/Attribute => Step}/Given.php | 2 +- src/Behat/{Behat/Definition/Attribute => Step}/Then.php | 2 +- src/Behat/{Behat/Definition/Attribute => Step}/When.php | 2 +- 7 files changed, 11 insertions(+), 11 deletions(-) rename src/Behat/{Behat/Definition/Attribute => Step}/Definition.php (90%) rename src/Behat/{Behat/Definition/Attribute => Step}/Given.php (92%) rename src/Behat/{Behat/Definition/Attribute => Step}/Then.php (92%) rename src/Behat/{Behat/Definition/Attribute => Step}/When.php (92%) diff --git a/composer.json b/composer.json index 4d60911a8..5cc083a4b 100644 --- a/composer.json +++ b/composer.json @@ -41,7 +41,8 @@ "autoload": { "psr-4": { "Behat\\Behat\\": "src/Behat/Behat/", - "Behat\\Testwork\\": "src/Behat/Testwork/" + "Behat\\Testwork\\": "src/Behat/Testwork/", + "Behat\\Step\\": "src/Behat/Step/" } }, diff --git a/features/attributes.feature b/features/attributes.feature index 6b994802a..831bc5405 100644 --- a/features/attributes.feature +++ b/features/attributes.feature @@ -9,8 +9,7 @@ Feature: attributes """ Date: Tue, 7 Jan 2020 12:02:27 +0100 Subject: [PATCH 279/567] Enable env placholder resolution --- src/Behat/Testwork/Cli/Application.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Behat/Testwork/Cli/Application.php b/src/Behat/Testwork/Cli/Application.php index f9f35212e..4189224e0 100644 --- a/src/Behat/Testwork/Cli/Application.php +++ b/src/Behat/Testwork/Cli/Application.php @@ -184,7 +184,7 @@ private function createContainer(InputInterface $input, OutputInterface $output) $extension = new ContainerLoader($this->extensionManager); $extension->load($container, $this->loadConfiguration($input)); $container->addObjectResource($extension); - $container->compile(); + $container->compile(true); return $container; } From fe52ccc1b9649a4fe63fff66aa3b855c05512b7d Mon Sep 17 00:00:00 2001 From: Matthias Pigulla Date: Mon, 31 May 2021 12:23:27 +0000 Subject: [PATCH 280/567] Add a feature testing env var placeholders --- features/bootstrap/FeatureContext.php | 12 ++++++- features/env_var_placeholders.feature | 52 +++++++++++++++++++++++++++ 2 files changed, 63 insertions(+), 1 deletion(-) create mode 100644 features/env_var_placeholders.feature diff --git a/features/bootstrap/FeatureContext.php b/features/bootstrap/FeatureContext.php index 937c6c002..fedacaa91 100644 --- a/features/bootstrap/FeatureContext.php +++ b/features/bootstrap/FeatureContext.php @@ -170,11 +170,21 @@ public function fileShouldExist($path) /** * Sets specified ENV variable * + * @When /^the "([^"]*)" environment variable is set to "([^"]*)"$/ + */ + public function iSetEnvironmentVariable($name, $value) + { + $this->env = array($name => (string) $value); + } + + /** + * Sets the BEHAT_PARAMS env variable + * * @When /^"BEHAT_PARAMS" environment variable is set to:$/ * * @param PyStringNode $value */ - public function iSetEnvironmentVariable(PyStringNode $value) + public function iSetBehatParamsEnvironmentVariable(PyStringNode $value) { $this->env = array('BEHAT_PARAMS' => (string) $value); } diff --git a/features/env_var_placeholders.feature b/features/env_var_placeholders.feature new file mode 100644 index 000000000..558927fee --- /dev/null +++ b/features/env_var_placeholders.feature @@ -0,0 +1,52 @@ +Feature: Symfony Env Var Placeholders + In order to support different setups + As a tester + I need to be able to use environment variables in the behat.yml configuration file + + Background: + Given a file named "features/bootstrap/FeatureContext.php" with: + """ + value = $value; + } + + /** + * @Then /the value should be configured as "([^"]+)"/ + */ + public function theValueShouldBeConfiguredAs($expected) { + PHPUnit\Framework\Assert::assertEquals($expected, $this->value); + } + } + """ + And a file named "features/env_var.feature" with: + """ + Feature: Environment variables + + Scenario: + Then the value should be configured as "some environment variable value" + """ + And a file named "behat.yml" with: + """ + default: + suites: + default: + contexts: + - FeatureContext: + - '%env(MY_ENV_VAR)%' + """ + + Scenario: + When the "MY_ENV_VAR" environment variable is set to "some environment variable value" + And I run "behat --no-colors" + Then it should pass with: + """ + 1 scenario (1 passed) + """ From caf6c7b2d338bdc7020d914bef0162e97efcae8a Mon Sep 17 00:00:00 2001 From: Simon Date: Sun, 4 Jul 2021 11:27:39 +0200 Subject: [PATCH 281/567] Remove Symfony < 4.4 compatibility --- features/bootstrap/FeatureContext.php | 8 +------ .../Cli/InteractiveContextIdentifier.php | 19 +--------------- .../HelperContainerExtension.php | 22 +------------------ .../Testwork/Cli/DumpReferenceCommand.php | 8 +------ .../Configuration/ConfigurationTree.php | 14 +++--------- 5 files changed, 7 insertions(+), 64 deletions(-) diff --git a/features/bootstrap/FeatureContext.php b/features/bootstrap/FeatureContext.php index 937c6c002..db8128a23 100644 --- a/features/bootstrap/FeatureContext.php +++ b/features/bootstrap/FeatureContext.php @@ -198,13 +198,7 @@ public function iRunBehat($argumentsString = '') strtr($this->options, array('\'' => '"', '"' => '\"')) ); - if (method_exists('\\Symfony\\Component\\Process\\Process', 'fromShellCommandline')) { - $this->process = Process::fromShellCommandline($cmd); - } else { - // BC layer for symfony/process 4.1 and older - $this->process = new Process(null); - $this->process->setCommandLine($cmd); - } + $this->process = Process::fromShellCommandline($cmd); // Prepare the process parameters. $this->process->setTimeout(20); diff --git a/src/Behat/Behat/Context/Cli/InteractiveContextIdentifier.php b/src/Behat/Behat/Context/Cli/InteractiveContextIdentifier.php index 137cac797..78be23b6d 100644 --- a/src/Behat/Behat/Context/Cli/InteractiveContextIdentifier.php +++ b/src/Behat/Behat/Context/Cli/InteractiveContextIdentifier.php @@ -57,7 +57,7 @@ public function __construct(TranslatorInterface $translator, InputInterface $inp */ public function guessTargetContextClass(ContextEnvironment $environment) { - if ($this->interactionIsNotSupported()) { + if (!$this->input->isInteractive()) { return null; } @@ -94,21 +94,4 @@ private function askQuestion($message, $choices, $default) return $helper->ask($this->input, $this->output, $question); } - - /** - * Checks if interactive mode is supported. - * - * @return bool - * - * @deprecated there is a better way to do it - `InputInterface::isInteractive()` method. - * Sadly, this doesn't work properly prior Symfony\Console 2.7 and as we need - * to support 2.5+ until the next major, we are forced to do a more explicit - * check for the CLI option. This should be reverted back to proper a - * `InputInterface::isInteractive()` call as soon as we bump dependencies - * to Symfony\Console 3.x in Behat 4.x. - */ - private function interactionIsNotSupported() - { - return $this->input->hasParameterOption('--no-interaction'); - } } diff --git a/src/Behat/Behat/HelperContainer/ServiceContainer/HelperContainerExtension.php b/src/Behat/Behat/HelperContainer/ServiceContainer/HelperContainerExtension.php index a52d6f786..399ffff09 100644 --- a/src/Behat/Behat/HelperContainer/ServiceContainer/HelperContainerExtension.php +++ b/src/Behat/Behat/HelperContainer/ServiceContainer/HelperContainerExtension.php @@ -96,31 +96,11 @@ public function process(ContainerBuilder $container) $references = $this->processor->findAndSortTaggedServices($container, self::HELPER_CONTAINER_TAG); foreach ($references as $reference) { - if ($this->isDefinitionShared($container->getDefinition((string) $reference))) { + if ($container->getDefinition((string) $reference)->isShared()) { throw new WrongServicesConfigurationException(sprintf( 'Container services must not be configured as shared, but `@%s` is.', $reference )); } } } - - /** - * Checks if provided definition is shared. - * - * @param Definition $definition - * - * @return bool - * - * @todo Remove after upgrading to Symfony 2.8+ - */ - private function isDefinitionShared(Definition $definition) - { - if (method_exists($definition, 'isShared')) { - return $definition->isShared(); - } else if (method_exists($definition, 'getScope')) { - return $definition->getScope() !== ContainerBuilder::SCOPE_PROTOTYPE; - } - - return false; - } } diff --git a/src/Behat/Testwork/Cli/DumpReferenceCommand.php b/src/Behat/Testwork/Cli/DumpReferenceCommand.php index 57416d8b7..e4242bbb5 100644 --- a/src/Behat/Testwork/Cli/DumpReferenceCommand.php +++ b/src/Behat/Testwork/Cli/DumpReferenceCommand.php @@ -47,13 +47,7 @@ public function __construct(ExtensionManager $extensionManager) */ protected function execute(InputInterface $input, OutputInterface $output) { - if (class_exists('Symfony\Component\Config\Definition\Dumper\YamlReferenceDumper')) { - $dumper = new YamlReferenceDumper(); - } else { - // Support Symfony Config 2.3 - $dumper = new ReferenceDumper(); - } - + $dumper = new YamlReferenceDumper(); $configTree = new ConfigurationTree(); $output->writeln($dumper->dumpNode($configTree->getConfigTree($this->extensionManager->getExtensions()))); diff --git a/src/Behat/Testwork/ServiceContainer/Configuration/ConfigurationTree.php b/src/Behat/Testwork/ServiceContainer/Configuration/ConfigurationTree.php index 3c3f317ec..f5b215fab 100644 --- a/src/Behat/Testwork/ServiceContainer/Configuration/ConfigurationTree.php +++ b/src/Behat/Testwork/ServiceContainer/Configuration/ConfigurationTree.php @@ -31,17 +31,9 @@ final class ConfigurationTree */ public function getConfigTree(array $extensions) { - if (method_exists('Symfony\Component\Config\Definition\Builder\TreeBuilder', 'getRootNode')) { - $treeBuilder = new TreeBuilder('testwork'); - /** @var ArrayNodeDefinition $rootNode */ - $rootNode = $treeBuilder->getRootNode(); - } else { - // BC layer for symfony/config 4.1 and older - $treeBuilder = new TreeBuilder(); - /** @var ArrayNodeDefinition $rootNode */ - /** @scrutinizer ignore-call */ - $rootNode = $treeBuilder->root('testwork'); - } + $treeBuilder = new TreeBuilder('testwork'); + /** @var ArrayNodeDefinition $rootNode */ + $rootNode = $treeBuilder->getRootNode(); foreach ($extensions as $extension) { $extension->configure($rootNode->children()->arrayNode($extension->getConfigKey())); From ff61e709cebd38b634968c83e69478919ee4f94f Mon Sep 17 00:00:00 2001 From: Remon van de Kamp Date: Sat, 24 Jul 2021 16:12:37 +0200 Subject: [PATCH 282/567] Configure DocBocHelper as service, so it can be overriden by extensions --- .../Context/Annotation/DocBlockHelper.php | 2 +- .../Context/Reader/AnnotatedContextReader.php | 17 ++++++++++++++++- .../ServiceContainer/ContextExtension.php | 18 +++++++++++++++++- .../Attribute/DefinitionAttributeReader.php | 17 ++++++++++++++++- .../ServiceContainer/DefinitionExtension.php | 18 +++++++++++++++++- 5 files changed, 67 insertions(+), 5 deletions(-) diff --git a/src/Behat/Behat/Context/Annotation/DocBlockHelper.php b/src/Behat/Behat/Context/Annotation/DocBlockHelper.php index 9118b82f9..6b4d4ae53 100644 --- a/src/Behat/Behat/Context/Annotation/DocBlockHelper.php +++ b/src/Behat/Behat/Context/Annotation/DocBlockHelper.php @@ -19,7 +19,7 @@ class DocBlockHelper * Extracts a description from the provided docblock, * with support for multiline descriptions. */ - public static function extractDescription(string $docBlock): string + public function extractDescription(string $docBlock): string { // Remove indentation $description = preg_replace('/^[\s\t]*/m', '', $docBlock); diff --git a/src/Behat/Behat/Context/Reader/AnnotatedContextReader.php b/src/Behat/Behat/Context/Reader/AnnotatedContextReader.php index 3904f1b65..6fe0b0751 100644 --- a/src/Behat/Behat/Context/Reader/AnnotatedContextReader.php +++ b/src/Behat/Behat/Context/Reader/AnnotatedContextReader.php @@ -43,6 +43,21 @@ final class AnnotatedContextReader implements ContextReader */ private $readers = array(); + /** + * @var DocBlockHelper + */ + private $docBlockHelper; + + /** + * Initializes reader. + * + * @param DocBlockHelper $docBlockHelper + */ + public function __construct(DocBlockHelper $docBlockHelper) + { + $this->docBlockHelper = $docBlockHelper; + } + /** * Registers annotation reader. * @@ -111,7 +126,7 @@ private function readMethodCallees($class, ReflectionMethod $method) private function readDocBlockCallees($class, ReflectionMethod $method, $docBlock) { $callees = array(); - $description = DocBlockHelper::extractDescription($docBlock); + $description = $this->docBlockHelper->extractDescription($docBlock); $docBlock = $this->mergeMultilines($docBlock); foreach (explode("\n", $docBlock) as $docLine) { diff --git a/src/Behat/Behat/Context/ServiceContainer/ContextExtension.php b/src/Behat/Behat/Context/ServiceContainer/ContextExtension.php index 6dba2568e..1ae669fac 100644 --- a/src/Behat/Behat/Context/ServiceContainer/ContextExtension.php +++ b/src/Behat/Behat/Context/ServiceContainer/ContextExtension.php @@ -59,6 +59,7 @@ final class ContextExtension implements Extension public const ATTRIBUTE_READER_TAG = 'context.attribute_reader'; public const CLASS_GENERATOR_TAG = 'context.class_generator'; public const SUITE_SCOPED_RESOLVER_FACTORY_TAG = 'context.argument.suite_resolver_factory'; + public const DOC_BLOCK_HELPER_ID = 'context.docblock_helper'; /** * @var ServiceProcessor @@ -112,6 +113,7 @@ public function load(ContainerBuilder $container, array $config) $this->loadSnippetsController($container); $this->loadDefaultClassGenerators($container); $this->loadDefaultContextReaders($container); + $this->loadDocblockHelper($container); } /** @@ -269,7 +271,9 @@ private function loadDefaultContextReaders(ContainerBuilder $container) */ private function loadAnnotatedContextReader(ContainerBuilder $container) { - $definition = new Definition('Behat\Behat\Context\Reader\AnnotatedContextReader'); + $definition = new Definition('Behat\Behat\Context\Reader\AnnotatedContextReader', array( + new Reference(self::DOC_BLOCK_HELPER_ID) + )); $container->setDefinition(self::ANNOTATED_CONTEXT_READER_ID, $definition); $definition = new Definition('Behat\Behat\Context\Reader\ContextReaderCachedPerContext', array( @@ -316,6 +320,18 @@ private function loadTranslatableContextReader(ContainerBuilder $container) $container->setDefinition(self::READER_TAG . '.translatable.cached', $definition); } + /** + * Loads DocBlockHelper + * + * @param ContainerBuilder $container + */ + private function loadDocblockHelper(ContainerBuilder $container) + { + $definition = new Definition('Behat\Behat\Context\Annotation\DocBlockHelper'); + + $container->setDefinition(self::DOC_BLOCK_HELPER_ID, $definition); + } + /** * Processes all class resolvers. * diff --git a/src/Behat/Behat/Definition/Context/Attribute/DefinitionAttributeReader.php b/src/Behat/Behat/Definition/Context/Attribute/DefinitionAttributeReader.php index 249d03e15..fa3ac5844 100644 --- a/src/Behat/Behat/Definition/Context/Attribute/DefinitionAttributeReader.php +++ b/src/Behat/Behat/Definition/Context/Attribute/DefinitionAttributeReader.php @@ -34,6 +34,21 @@ final class DefinitionAttributeReader implements AttributeReader Then::class => 'Behat\Behat\Definition\Call\Then', ); + /** + * @var DocBlockHelper + */ + private $docBlockHelper; + + /** + * Initializes reader. + * + * @param DocBlockHelper $docBlockHelper + */ + public function __construct(DocBlockHelper $docBlockHelper) + { + $this->docBlockHelper = $docBlockHelper; + } + /** * @{inheritdoc} */ @@ -51,7 +66,7 @@ public function readCallees(string $contextClass, ReflectionMethod $method) $callable = array($contextClass, $method->getName()); $description = null; if ($docBlock = $method->getDocComment()) { - $description = DocBlockHelper::extractDescription($docBlock); + $description = $this->docBlockHelper->extractDescription($docBlock); } $callees[] = new $class($attribute->newInstance()->pattern, $callable, $description); diff --git a/src/Behat/Behat/Definition/ServiceContainer/DefinitionExtension.php b/src/Behat/Behat/Definition/ServiceContainer/DefinitionExtension.php index 7730f71ed..e408f5358 100644 --- a/src/Behat/Behat/Definition/ServiceContainer/DefinitionExtension.php +++ b/src/Behat/Behat/Definition/ServiceContainer/DefinitionExtension.php @@ -46,6 +46,7 @@ final class DefinitionExtension implements Extension */ public const SEARCH_ENGINE_TAG = 'definition.search_engine'; public const PATTERN_POLICY_TAG = 'definition.pattern_policy'; + public const DOC_BLOCK_HELPER_ID = 'definition.doc_block_helper'; /** * @var ServiceProcessor @@ -100,6 +101,7 @@ public function load(ContainerBuilder $container, array $config) $this->loadAttributeReader($container); $this->loadDefinitionPrinters($container); $this->loadController($container); + $this->loadDocblockHelper($container); } /** @@ -225,7 +227,9 @@ private function loadAnnotationReader(ContainerBuilder $container) */ private function loadAttributeReader(ContainerBuilder $container) { - $definition = new Definition('\Behat\Behat\Definition\Context\Attribute\DefinitionAttributeReader'); + $definition = new Definition('\Behat\Behat\Definition\Context\Attribute\DefinitionAttributeReader', array( + new Reference(self::DOC_BLOCK_HELPER_ID) + )); $definition->addTag(ContextExtension::ATTRIBUTE_READER_TAG, array('priority' => 50)); $container->setDefinition(ContextExtension::ATTRIBUTE_READER_TAG . '.definition', $definition); } @@ -271,6 +275,18 @@ private function loadController(ContainerBuilder $container) $container->setDefinition(CliExtension::CONTROLLER_TAG . '.available_definitions', $definition); } + /** + * Loads DocBlockHelper + * + * @param ContainerBuilder $container + */ + private function loadDocblockHelper(ContainerBuilder $container) + { + $definition = new Definition('Behat\Behat\Context\Annotation\DocBlockHelper'); + + $container->setDefinition(self::DOC_BLOCK_HELPER_ID, $definition); + } + /** * Processes all search engines in the container. * From 70b07e070373854b9b3c5e184b498f97d18322fb Mon Sep 17 00:00:00 2001 From: javer Date: Sat, 11 Sep 2021 23:36:07 +0300 Subject: [PATCH 283/567] Add PHP 8.1 support --- .github/workflows/build.yml | 1 + .../Gherkin/Specification/LazyFeatureIterator.php | 10 +++++----- .../Locator/FilesystemRerunScenariosListLocator.php | 2 +- .../Locator/FilesystemScenariosListLocator.php | 2 +- .../Output/Node/Printer/Helper/WidthCalculator.php | 2 +- .../Node/Printer/Pretty/PrettyScenarioPrinter.php | 4 ++-- src/Behat/Testwork/Call/CallResults.php | 7 +++---- .../Output/Node/EventListener/ChainEventListener.php | 4 ++-- .../Testwork/Output/Printer/JUnitOutputPrinter.php | 2 +- .../Specification/GroupedSpecificationIterator.php | 9 +++++---- src/Behat/Testwork/Tester/Result/TestResults.php | 4 ++-- 11 files changed, 24 insertions(+), 23 deletions(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 9106dd456..7711bf3ad 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -26,6 +26,7 @@ jobs: - php: 7.4 symfony-version: ^4.4 - php: 8.0 + - php: 8.1 steps: - uses: actions/checkout@v2 diff --git a/src/Behat/Behat/Gherkin/Specification/LazyFeatureIterator.php b/src/Behat/Behat/Gherkin/Specification/LazyFeatureIterator.php index 61dd9bdb2..1883a0c6b 100644 --- a/src/Behat/Behat/Gherkin/Specification/LazyFeatureIterator.php +++ b/src/Behat/Behat/Gherkin/Specification/LazyFeatureIterator.php @@ -84,7 +84,7 @@ public function getSuite() /** * {@inheritdoc} */ - public function rewind() + public function rewind(): void { $this->position = 0; $this->moveToNextAvailableFeature(); @@ -93,7 +93,7 @@ public function rewind() /** * {@inheritdoc} */ - public function next() + public function next(): void { $this->moveToNextAvailableFeature(); } @@ -101,7 +101,7 @@ public function next() /** * {@inheritdoc} */ - public function valid() + public function valid(): bool { return null !== $this->currentFeature; } @@ -109,7 +109,7 @@ public function valid() /** * {@inheritdoc} */ - public function key() + public function key(): int { return $this->position; } @@ -117,7 +117,7 @@ public function key() /** * {@inheritdoc} */ - public function current() + public function current(): FeatureNode { return $this->currentFeature; } diff --git a/src/Behat/Behat/Gherkin/Specification/Locator/FilesystemRerunScenariosListLocator.php b/src/Behat/Behat/Gherkin/Specification/Locator/FilesystemRerunScenariosListLocator.php index d5ac5b3a3..8636d3279 100644 --- a/src/Behat/Behat/Gherkin/Specification/Locator/FilesystemRerunScenariosListLocator.php +++ b/src/Behat/Behat/Gherkin/Specification/Locator/FilesystemRerunScenariosListLocator.php @@ -51,7 +51,7 @@ public function getLocatorExamples() */ public function locateSpecifications(Suite $suite, $locator) { - if (!is_file($locator) || 'rerun' !== pathinfo($locator, PATHINFO_EXTENSION)) { + if (null === $locator || !is_file($locator) || 'rerun' !== pathinfo($locator, PATHINFO_EXTENSION)) { return new NoSpecificationsIterator($suite); } diff --git a/src/Behat/Behat/Gherkin/Specification/Locator/FilesystemScenariosListLocator.php b/src/Behat/Behat/Gherkin/Specification/Locator/FilesystemScenariosListLocator.php index 59141df80..ccacedd0f 100644 --- a/src/Behat/Behat/Gherkin/Specification/Locator/FilesystemScenariosListLocator.php +++ b/src/Behat/Behat/Gherkin/Specification/Locator/FilesystemScenariosListLocator.php @@ -51,7 +51,7 @@ public function getLocatorExamples() */ public function locateSpecifications(Suite $suite, $locator) { - if (!is_file($locator) || 'scenarios' !== pathinfo($locator, PATHINFO_EXTENSION)) { + if (null === $locator || !is_file($locator) || 'scenarios' !== pathinfo($locator, PATHINFO_EXTENSION)) { return new NoSpecificationsIterator($suite); } diff --git a/src/Behat/Behat/Output/Node/Printer/Helper/WidthCalculator.php b/src/Behat/Behat/Output/Node/Printer/Helper/WidthCalculator.php index bef188128..c7a1fa96d 100644 --- a/src/Behat/Behat/Output/Node/Printer/Helper/WidthCalculator.php +++ b/src/Behat/Behat/Output/Node/Printer/Helper/WidthCalculator.php @@ -79,7 +79,7 @@ public function calculateScenarioHeaderWidth(Scenario $scenario, $indentation) $header = sprintf('%s%s', $indentText, $scenario->getTitle()); } else { $title = $scenario->getTitle(); - $lines = explode("\n", $title); + $lines = explode("\n", $title ?? ''); $header = sprintf('%s%s: %s', $indentText, $scenario->getKeyword(), array_shift($lines)); } diff --git a/src/Behat/Behat/Output/Node/Printer/Pretty/PrettyScenarioPrinter.php b/src/Behat/Behat/Output/Node/Printer/Pretty/PrettyScenarioPrinter.php index 378a99118..28f3adccc 100644 --- a/src/Behat/Behat/Output/Node/Printer/Pretty/PrettyScenarioPrinter.php +++ b/src/Behat/Behat/Output/Node/Printer/Pretty/PrettyScenarioPrinter.php @@ -110,7 +110,7 @@ private function printKeyword(OutputPrinter $printer, $keyword) */ private function printTitle(OutputPrinter $printer, $longTitle) { - $description = explode("\n", $longTitle); + $description = explode("\n", $longTitle ?? ''); $title = array_shift($description); if ('' !== $title) { @@ -126,7 +126,7 @@ private function printTitle(OutputPrinter $printer, $longTitle) */ private function printDescription(OutputPrinter $printer, $longTitle) { - $lines = explode("\n", $longTitle); + $lines = explode("\n", $longTitle ?? ''); array_shift($lines); foreach ($lines as $line) { diff --git a/src/Behat/Testwork/Call/CallResults.php b/src/Behat/Testwork/Call/CallResults.php index d1aeeda57..6bc3e8b11 100644 --- a/src/Behat/Testwork/Call/CallResults.php +++ b/src/Behat/Testwork/Call/CallResults.php @@ -12,7 +12,6 @@ use ArrayIterator; use Countable; -use Iterator; use IteratorAggregate; /** @@ -87,7 +86,7 @@ public function hasStdOuts() * * @return integer */ - public function count() + public function count(): int { return count($this->results); } @@ -95,9 +94,9 @@ public function count() /** * Returns collection iterator. * - * @return Iterator + * @return ArrayIterator */ - public function getIterator() + public function getIterator(): ArrayIterator { return new ArrayIterator($this->results); } diff --git a/src/Behat/Testwork/Output/Node/EventListener/ChainEventListener.php b/src/Behat/Testwork/Output/Node/EventListener/ChainEventListener.php index a360581ee..2fb8d44cb 100644 --- a/src/Behat/Testwork/Output/Node/EventListener/ChainEventListener.php +++ b/src/Behat/Testwork/Output/Node/EventListener/ChainEventListener.php @@ -51,7 +51,7 @@ public function listenEvent(Formatter $formatter, Event $event, $eventName) /** * {@inheritdoc} */ - public function count() + public function count(): int { return count($this->listeners); } @@ -59,7 +59,7 @@ public function count() /** * {@inheritdoc} */ - public function getIterator() + public function getIterator(): ArrayIterator { return new ArrayIterator($this->listeners); } diff --git a/src/Behat/Testwork/Output/Printer/JUnitOutputPrinter.php b/src/Behat/Testwork/Output/Printer/JUnitOutputPrinter.php index edb6f3ae6..f415b96a1 100644 --- a/src/Behat/Testwork/Output/Printer/JUnitOutputPrinter.php +++ b/src/Behat/Testwork/Output/Printer/JUnitOutputPrinter.php @@ -107,7 +107,7 @@ public function addTestcase(array $testcaseAttributes = array()) */ public function addTestcaseChild($nodeName, array $nodeAttributes = array(), $nodeValue = null) { - $childNode = $this->domDocument->createElement($nodeName, $nodeValue); + $childNode = $this->domDocument->createElement($nodeName, $nodeValue ?? ''); $this->currentTestcase->appendChild($childNode); $this->addAttributesToNode($childNode, $nodeAttributes); } diff --git a/src/Behat/Testwork/Specification/GroupedSpecificationIterator.php b/src/Behat/Testwork/Specification/GroupedSpecificationIterator.php index bac556d05..8975040fc 100644 --- a/src/Behat/Testwork/Specification/GroupedSpecificationIterator.php +++ b/src/Behat/Testwork/Specification/GroupedSpecificationIterator.php @@ -77,7 +77,7 @@ public function getSuite() /** * {@inheritdoc} */ - public function rewind() + public function rewind(): void { $this->position = 0; while (isset($this->iterators[$this->position])) { @@ -93,7 +93,7 @@ public function rewind() /** * {@inheritdoc} */ - public function next() + public function next(): void { if (!isset($this->iterators[$this->position])) { return; @@ -114,7 +114,7 @@ public function next() /** * {@inheritdoc} */ - public function valid() + public function valid(): bool { return isset($this->iterators[$this->position]) && $this->iterators[$this->position]->valid(); } @@ -122,6 +122,7 @@ public function valid() /** * {@inheritdoc} */ + #[\ReturnTypeWillChange] public function current() { return $this->iterators[$this->position]->current(); @@ -130,7 +131,7 @@ public function current() /** * {@inheritdoc} */ - public function key() + public function key(): int { return $this->position + $this->iterators[$this->position]->key(); } diff --git a/src/Behat/Testwork/Tester/Result/TestResults.php b/src/Behat/Testwork/Tester/Result/TestResults.php index 1bd8516e6..cf8e4aa52 100644 --- a/src/Behat/Testwork/Tester/Result/TestResults.php +++ b/src/Behat/Testwork/Tester/Result/TestResults.php @@ -62,7 +62,7 @@ public function getResultCode() /** * {@inheritdoc} */ - public function count() + public function count(): int { return count($this->results); } @@ -70,7 +70,7 @@ public function count() /** * {@inheritdoc} */ - public function getIterator() + public function getIterator(): ArrayIterator { return new ArrayIterator($this->results); } From 4cad4c03b84399b680bc717831ce6987e70ff742 Mon Sep 17 00:00:00 2001 From: Hugo Alliaume Date: Sun, 20 Jun 2021 20:42:22 +0200 Subject: [PATCH 284/567] Allow Symfony 6 --- .github/workflows/build.yml | 7 +++++++ composer.json | 14 +++++++------- 2 files changed, 14 insertions(+), 7 deletions(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 7711bf3ad..4b0e9533c 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -26,6 +26,9 @@ jobs: - php: 7.4 symfony-version: ^4.4 - php: 8.0 + - php: 8.0 + stability: dev + symfony-version: ^6.0 - php: 8.1 steps: @@ -38,6 +41,10 @@ jobs: ini-values: "phar.readonly=0,zend.exception_ignore_args=Off" coverage: none + - name: Configure Composer minimum stability + if: matrix.stability + run: composer config minimum-stability ${{ matrix.stability }} + - name: Update Symfony version if: matrix.symfony-version != '' run: composer require --no-update "symfony/symfony:${{ matrix.symfony-version }}" diff --git a/composer.json b/composer.json index 4d60911a8..db6a4f770 100644 --- a/composer.json +++ b/composer.json @@ -18,17 +18,17 @@ "ext-mbstring": "*", "behat/gherkin": "^4.8.0", "behat/transliterator": "^1.2", - "symfony/console": "^4.4 || ^5.0", - "symfony/config": "^4.4 || ^5.0", - "symfony/dependency-injection": "^4.4 || ^5.0", - "symfony/event-dispatcher": "^4.4 || ^5.0", - "symfony/translation": "^4.4 || ^5.0", - "symfony/yaml": "^4.4 || ^5.0", + "symfony/console": "^4.4 || ^5.0 || ^6.0", + "symfony/config": "^4.4 || ^5.0 || ^6.0", + "symfony/dependency-injection": "^4.4 || ^5.0 || ^6.0", + "symfony/event-dispatcher": "^4.4 || ^5.0 || ^6.0", + "symfony/translation": "^4.4 || ^5.0 || ^6.0", + "symfony/yaml": "^4.4 || ^5.0 || ^6.0", "psr/container": "^1.0" }, "require-dev": { - "symfony/process": "^4.4 || ^5.0", + "symfony/process": "^4.4 || ^5.0 || ^6.0", "phpunit/phpunit": "^8.5 || ^9.0", "herrera-io/box": "~1.6.1", "container-interop/container-interop": "^1.2" From 8366919072ba7fdf8d7dabfe75d6d67ec7772b81 Mon Sep 17 00:00:00 2001 From: Hugo Alliaume Date: Sun, 20 Jun 2021 21:12:05 +0200 Subject: [PATCH 285/567] Make changes needed for Symfony 6 support No parameters are displayed in the stacktrace, so asserting Behat\Testwork\Call\Handler\RuntimeCallHandler->executeCall(...) fails --- composer.json | 3 ++- features/error_reporting.feature | 2 +- .../Behat/Output/Printer/Formatter/ConsoleFormatter.php | 2 +- src/Behat/Testwork/Cli/Application.php | 6 +++--- .../Testwork/EventDispatcher/TestworkEventDispatcher.php | 6 ++++-- 5 files changed, 11 insertions(+), 8 deletions(-) diff --git a/composer.json b/composer.json index db6a4f770..627a06356 100644 --- a/composer.json +++ b/composer.json @@ -57,5 +57,6 @@ } }, - "bin": ["bin/behat"] + "bin": ["bin/behat"], + "minimum-stability": "dev" } diff --git a/features/error_reporting.feature b/features/error_reporting.feature index b6981a8d9..945dabd78 100644 --- a/features/error_reporting.feature +++ b/features/error_reporting.feature @@ -149,5 +149,5 @@ Feature: Error Reporting Exception: Exception is thrown in features/bootstrap/FeatureContext.php:56 Stack trace: #0 src/Behat/Testwork/Call/Handler/RuntimeCallHandler.php(110): FeatureContext->anExceptionIsThrown() - #1 src/Behat/Testwork/Call/Handler/RuntimeCallHandler.php(64): Behat\Testwork\Call\Handler\RuntimeCallHandler->executeCall(Object(Behat\Behat\Definition\Call\DefinitionCall)) + #1 src/Behat/Testwork/Call/Handler/RuntimeCallHandler.php(64): Behat\Testwork\Call\Handler\RuntimeCallHandler->executeCall( """ diff --git a/src/Behat/Behat/Output/Printer/Formatter/ConsoleFormatter.php b/src/Behat/Behat/Output/Printer/Formatter/ConsoleFormatter.php index 1e1f695e1..57d3ef38b 100644 --- a/src/Behat/Behat/Output/Printer/Formatter/ConsoleFormatter.php +++ b/src/Behat/Behat/Output/Printer/Formatter/ConsoleFormatter.php @@ -28,7 +28,7 @@ final class ConsoleFormatter extends BaseOutputFormatter * * @return string The styled message */ - public function format($message) + public function format($message): string { return preg_replace_callback(self::CUSTOM_PATTERN, array($this, 'replaceStyle'), $message); } diff --git a/src/Behat/Testwork/Cli/Application.php b/src/Behat/Testwork/Cli/Application.php index f9f35212e..006b3f1b7 100644 --- a/src/Behat/Testwork/Cli/Application.php +++ b/src/Behat/Testwork/Cli/Application.php @@ -63,7 +63,7 @@ public function __construct($name, $version, ConfigurationLoader $configLoader, * * @return InputDefinition An InputDefinition instance */ - public function getDefaultInputDefinition() + public function getDefaultInputDefinition(): InputDefinition { return new InputDefinition(array( new InputOption('--profile', '-p', InputOption::VALUE_REQUIRED, 'Specify config profile to use.'), @@ -124,7 +124,7 @@ public function doRun(InputInterface $input, OutputInterface $output) return parent::doRun($input, $output); } - protected function getDefaultCommands() + protected function getDefaultCommands(): array { $commands = parent::getDefaultCommands(); @@ -210,7 +210,7 @@ private function getBasePath() * * @return string The command name */ - protected function getCommandName(InputInterface $input) + protected function getCommandName(InputInterface $input): string { if ($input->hasParameterOption(array('--config-reference'))) { return 'dump-reference'; diff --git a/src/Behat/Testwork/EventDispatcher/TestworkEventDispatcher.php b/src/Behat/Testwork/EventDispatcher/TestworkEventDispatcher.php index 50a8ec957..cf96c5d78 100644 --- a/src/Behat/Testwork/EventDispatcher/TestworkEventDispatcher.php +++ b/src/Behat/Testwork/EventDispatcher/TestworkEventDispatcher.php @@ -26,10 +26,12 @@ final class TestworkEventDispatcher extends EventDispatcher /** * {@inheritdoc} + * + * @param string|null $eventName */ - public function getListeners($eventName = null) + public function getListeners($eventName = null): array { - if (null == $eventName || self::BEFORE_ALL_EVENTS === $eventName) { + if (null === $eventName || self::BEFORE_ALL_EVENTS === $eventName) { return parent::getListeners($eventName); } From 706b5a549077fe04fb22808b0d19d95b628455f4 Mon Sep 17 00:00:00 2001 From: Simon Date: Thu, 1 Jul 2021 21:06:30 +0200 Subject: [PATCH 286/567] Add vimeo/psalm to composer.json --- composer.json | 3 ++- psalm.xml | 15 +++++++++++++++ 2 files changed, 17 insertions(+), 1 deletion(-) create mode 100644 psalm.xml diff --git a/composer.json b/composer.json index 4c2eb1b93..9de2baff4 100644 --- a/composer.json +++ b/composer.json @@ -31,7 +31,8 @@ "symfony/process": "^4.4 || ^5.0 || ^6.0", "phpunit/phpunit": "^8.5 || ^9.0", "herrera-io/box": "~1.6.1", - "container-interop/container-interop": "^1.2" + "container-interop/container-interop": "^1.2", + "vimeo/psalm": "^4.8" }, "suggest": { diff --git a/psalm.xml b/psalm.xml new file mode 100644 index 000000000..d234691b9 --- /dev/null +++ b/psalm.xml @@ -0,0 +1,15 @@ + + + + + + + + + From caace301f43c8969d27ada108285b6a0b52b4262 Mon Sep 17 00:00:00 2001 From: Simon Date: Thu, 1 Jul 2021 21:35:50 +0200 Subject: [PATCH 287/567] Replace Boolean with bool in DocBlocks --- src/Behat/Testwork/Output/Printer/Factory/OutputFactory.php | 4 ++-- src/Behat/Testwork/Output/Printer/OutputPrinter.php | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/Behat/Testwork/Output/Printer/Factory/OutputFactory.php b/src/Behat/Testwork/Output/Printer/Factory/OutputFactory.php index 99bd7c11d..e65f7f152 100644 --- a/src/Behat/Testwork/Output/Printer/Factory/OutputFactory.php +++ b/src/Behat/Testwork/Output/Printer/Factory/OutputFactory.php @@ -32,7 +32,7 @@ abstract class OutputFactory */ private $outputStyles = array(); /** - * @var null|Boolean + * @var null|bool */ private $outputDecorated = null; /** @@ -93,7 +93,7 @@ public function setOutputDecorated($decorated) /** * Returns output decoration status. * - * @return null|Boolean + * @return null|bool */ public function isOutputDecorated() { diff --git a/src/Behat/Testwork/Output/Printer/OutputPrinter.php b/src/Behat/Testwork/Output/Printer/OutputPrinter.php index fc6452a8f..6ef907439 100644 --- a/src/Behat/Testwork/Output/Printer/OutputPrinter.php +++ b/src/Behat/Testwork/Output/Printer/OutputPrinter.php @@ -76,7 +76,7 @@ public function setOutputDecorated($decorated); /** * Returns output decoration status. * - * @return null|Boolean + * @return null|bool * * @deprecated since 3.1, to be removed in 4.0 */ From 8e5ca49016b80b5ac63e11ca1207ad0cb33b3f1e Mon Sep 17 00:00:00 2001 From: Simon Date: Thu, 1 Jul 2021 21:39:10 +0200 Subject: [PATCH 288/567] Add use statement for SpecificationIterator --- src/Behat/Testwork/Ordering/Orderer/RandomOrderer.php | 1 + 1 file changed, 1 insertion(+) diff --git a/src/Behat/Testwork/Ordering/Orderer/RandomOrderer.php b/src/Behat/Testwork/Ordering/Orderer/RandomOrderer.php index 551e44796..8dc9c9e0e 100644 --- a/src/Behat/Testwork/Ordering/Orderer/RandomOrderer.php +++ b/src/Behat/Testwork/Ordering/Orderer/RandomOrderer.php @@ -11,6 +11,7 @@ namespace Behat\Testwork\Ordering\Orderer; use Behat\Testwork\Specification\SpecificationArrayIterator; +use Behat\Testwork\Specification\SpecificationIterator; /** * Prioritises Suites and Features into random order From 6f65eebf702fd0e225dfb5d16189771b869b955a Mon Sep 17 00:00:00 2001 From: Simon Date: Thu, 1 Jul 2021 21:52:58 +0200 Subject: [PATCH 289/567] Suppress Psalm issues for legacy compatibility solutions --- .../EventDispatcher/TestworkEventDispatcherSymfonyLegacy.php | 1 + 1 file changed, 1 insertion(+) diff --git a/src/Behat/Testwork/EventDispatcher/TestworkEventDispatcherSymfonyLegacy.php b/src/Behat/Testwork/EventDispatcher/TestworkEventDispatcherSymfonyLegacy.php index 2e2b93076..3a41ba6d5 100644 --- a/src/Behat/Testwork/EventDispatcher/TestworkEventDispatcherSymfonyLegacy.php +++ b/src/Behat/Testwork/EventDispatcher/TestworkEventDispatcherSymfonyLegacy.php @@ -34,6 +34,7 @@ public function dispatch($eventName, \Symfony\Component\EventDispatcher\Event $e ); if (null === $event) { + /** @psalm-suppress UndefinedClass */ $event = new \Symfony\Component\EventDispatcher\Event(); } if (method_exists($event, 'setName')) { From bb3369d8221de56ca234d0bdcb79a4e212f6a9fa Mon Sep 17 00:00:00 2001 From: Simon Hammes Date: Fri, 2 Jul 2021 22:17:09 +0200 Subject: [PATCH 290/567] Add @psalm-assert-if-true tags to CallResult::hasException() --- src/Behat/Testwork/Call/CallResult.php | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/Behat/Testwork/Call/CallResult.php b/src/Behat/Testwork/Call/CallResult.php index 924ce0d8a..4ee808b82 100644 --- a/src/Behat/Testwork/Call/CallResult.php +++ b/src/Behat/Testwork/Call/CallResult.php @@ -75,6 +75,9 @@ public function getReturn() /** * Check if call thrown exception. * + * @psalm-assert-if-true Exception $this->exception + * @psalm-assert-if-true Exception $this->getException() + * * @return bool */ public function hasException() From 77eb016ce58f268b7dbb921576fd4dd98c58c379 Mon Sep 17 00:00:00 2001 From: Simon Hammes Date: Fri, 2 Jul 2021 22:54:35 +0200 Subject: [PATCH 291/567] Suppress errors in psalm.xml --- psalm.xml | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/psalm.xml b/psalm.xml index d234691b9..99f6bdb8d 100644 --- a/psalm.xml +++ b/psalm.xml @@ -12,4 +12,32 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + From c5665620f48f1708b7eabcc433cea2469d9104af Mon Sep 17 00:00:00 2001 From: Simon Hammes Date: Fri, 2 Jul 2021 22:57:49 +0200 Subject: [PATCH 292/567] Add GA job for Psalm (PHP 8.0 only) --- .github/workflows/build.yml | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 4b0e9533c..9bc30864b 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -82,6 +82,25 @@ jobs: name: behat.phar path: behat.phar + psalm: + runs-on: ubuntu-latest + name: Psalm (PHP 8.0) + steps: + - uses: actions/checkout@v2 + + - name: Setup PHP + uses: shivammathur/setup-php@v2 + with: + php-version: 8.0 + ini-values: "phar.readonly=0,zend.exception_ignore_args=Off" + coverage: none + + - name: Install dependencies + run: composer update + + - name: Run Psalm + run: ./vendor/bin/psalm + publish-phar: runs-on: ubuntu-latest name: Publish the PHAR From fcc5a73a50e8df2d5b42e20d0bf75b6c8d8b6996 Mon Sep 17 00:00:00 2001 From: Simon Date: Fri, 17 Sep 2021 15:13:52 +0200 Subject: [PATCH 293/567] [CI] Set Psalm output format --- .github/workflows/build.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 9bc30864b..bb92aefd7 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -99,7 +99,7 @@ jobs: run: composer update - name: Run Psalm - run: ./vendor/bin/psalm + run: ./vendor/bin/psalm --output-format=github publish-phar: runs-on: ubuntu-latest From 0c5ede6cf58221041727390747f58f16bebf67a7 Mon Sep 17 00:00:00 2001 From: Simon Date: Fri, 17 Sep 2021 23:29:15 +0200 Subject: [PATCH 294/567] [CI] Remove vimeo/psalm in 'tests' job --- .github/workflows/build.yml | 3 +++ 1 file changed, 3 insertions(+) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index bb92aefd7..00f288abd 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -53,6 +53,9 @@ jobs: if: matrix.skip-interop run: composer remove --dev --no-update container-interop/container-interop + - name: Uninstall Psalm + run: composer remove --dev --no-update vimeo/psalm + - name: Install dependencies run: composer update ${{ matrix.composer-flags }} From c88d33cf1122228e213227d78b0988bb08f43545 Mon Sep 17 00:00:00 2001 From: Kamil Kokot Date: Tue, 12 Oct 2021 15:08:33 +0200 Subject: [PATCH 295/567] Allow to manually run GitHub Actions --- .github/workflows/build.yml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 4b0e9533c..ee73b527c 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -3,9 +3,10 @@ name: Build on: push: branches: [master] - pull_request: + pull_request: ~ release: types: [created] + workflow_dispatch: ~ jobs: tests: From f983353cbb35953e14e64cf39d3335daa88c55c9 Mon Sep 17 00:00:00 2001 From: Kamil Kokot Date: Sat, 16 Oct 2021 19:07:48 +0200 Subject: [PATCH 296/567] Remove minimum-stability dev from composer.json --- composer.json | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/composer.json b/composer.json index 4c2eb1b93..d0baa5fdf 100644 --- a/composer.json +++ b/composer.json @@ -58,6 +58,5 @@ } }, - "bin": ["bin/behat"], - "minimum-stability": "dev" + "bin": ["bin/behat"] } From eb7f35d8907931fc1ccb206ac7e81543d1a74563 Mon Sep 17 00:00:00 2001 From: Kamil Kokot Date: Sun, 17 Oct 2021 16:23:22 +0200 Subject: [PATCH 297/567] Fix the build for Gherking v4.9.0 --- composer.json | 2 +- features/syntax_help.feature | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/composer.json b/composer.json index d0baa5fdf..94e68e9d2 100644 --- a/composer.json +++ b/composer.json @@ -16,7 +16,7 @@ "require": { "php": "^7.2 || ^8.0", "ext-mbstring": "*", - "behat/gherkin": "^4.8.0", + "behat/gherkin": "^4.9.0", "behat/transliterator": "^1.2", "symfony/console": "^4.4 || ^5.0 || ^6.0", "symfony/config": "^4.4 || ^5.0 || ^6.0", diff --git a/features/syntax_help.feature b/features/syntax_help.feature index 53905240f..16964a950 100644 --- a/features/syntax_help.feature +++ b/features/syntax_help.feature @@ -64,7 +64,7 @@ Feature: Syntax helpers [Затем|Тогда|То|*] there should be agent J [Иначе|Но|*|А] there should not be agent K - Структура сценария: Erasing other agents' memory + [Структура сценария|Шаблон сценария]: Erasing other agents' memory [Допустим|Пусть|Дано|*] there is agent [К тому же|Также|*|И] there is agent [Когда|Если|*] I erase agent 's memory From 5d2195ba7c00a0aa4dc5f68d6bc2251991db43f9 Mon Sep 17 00:00:00 2001 From: Kamil Kokot Date: Mon, 18 Oct 2021 09:31:21 +0200 Subject: [PATCH 298/567] Update CHANGELOG for v3.9.0 release --- CHANGELOG.md | 22 +++++++++++++++++++++- 1 file changed, 21 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 02347d1e9..30abfca78 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,23 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](http://keepachangelog.com/) and this project adheres to [Semantic Versioning](http://semver.org/). +## [3.9.0] - 2021-10-18 + +### What's Changed +* Fix syntax help test and bump gherkin dependency by @ciaranmcnulty in https://github.com/Behat/Behat/pull/1336 +* Remove legacy Symfony compatibility layers (#1305, #1347) by @simonhammes in https://github.com/Behat/Behat/pull/1349 +* Add PHP 8.1 support by @javer in https://github.com/Behat/Behat/pull/1355 +* Introduce reading PHP8 Attributes for Given, When and Then steps by @rpkamp in https://github.com/Behat/Behat/pull/1342 +* Allow Symfony 6 by @Kocal in https://github.com/Behat/Behat/pull/1346 +* Remove minimum-stability dev from composer.json & require Gherkin ^4.9.0 by @pamil in https://github.com/Behat/Behat/pull/1365 +* Allow to manually run GitHub Actions by @pamil in https://github.com/Behat/Behat/pull/1361 +* Add vimeo/psalm (#1307) by @simonhammes in https://github.com/Behat/Behat/pull/1348 + +### New Contributors +* @simonhammes made their first contribution in https://github.com/Behat/Behat/pull/1349 +* @javer made their first contribution in https://github.com/Behat/Behat/pull/1355 +* @Kocal made their first contribution in https://github.com/Behat/Behat/pull/1346 + ## [3.8.1] - 2020-11-07 ### Fixed @@ -945,7 +962,10 @@ and this project adheres to [Semantic Versioning](http://semver.org/). ### Changed * Initial release -[Unreleased]: https://github.com/Behat/Behat/compare/v3.7.0...master +[Unreleased]: https://github.com/Behat/Behat/compare/v3.9.0...master +[3.9.0]: https://github.com/Behat/Behat/compare/v3.8.1...v3.9.0 +[3.8.1]: https://github.com/Behat/Behat/compare/v3.8.0...v3.8.1 +[3.8.0]: https://github.com/Behat/Behat/compare/v3.7.0...v3.8.0 [3.7.0]: https://github.com/Behat/Behat/compare/v3.6.1...v3.7.0 [3.6.1]: https://github.com/Behat/Behat/compare/v3.6.0...v3.6.1 [3.6.0]: https://github.com/Behat/Behat/compare/v3.5.0...v3.6.0 From bc2220f794ac944e85fbab69dbc10304c2209fa3 Mon Sep 17 00:00:00 2001 From: David Maicher Date: Mon, 25 Oct 2021 11:22:26 +0200 Subject: [PATCH 299/567] Fix issue 1363 (#1368) --- .github/workflows/build.yml | 11 ++++++----- .scrutinizer.yml | 2 +- .../Definition/Translator/TranslatorInterface.php | 4 +++- 3 files changed, 10 insertions(+), 7 deletions(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 04b6d90e9..91ade8519 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -25,11 +25,13 @@ jobs: - php: 7.3 - php: 7.4 - php: 7.4 - symfony-version: ^4.4 + env: + SYMFONY_REQUIRE: 4.4.* - php: 8.0 - php: 8.0 stability: dev - symfony-version: ^6.0 + env: + SYMFONY_REQUIRE: 6.0.* - php: 8.1 steps: @@ -46,9 +48,8 @@ jobs: if: matrix.stability run: composer config minimum-stability ${{ matrix.stability }} - - name: Update Symfony version - if: matrix.symfony-version != '' - run: composer require --no-update "symfony/symfony:${{ matrix.symfony-version }}" + - name: Install symfony/flex + run: composer global require symfony/flex - name: Uninstall container interop if: matrix.skip-interop diff --git a/.scrutinizer.yml b/.scrutinizer.yml index 04255e8ea..1f9349e13 100644 --- a/.scrutinizer.yml +++ b/.scrutinizer.yml @@ -50,7 +50,7 @@ checks: encourage_single_quotes: true classes_in_camel_caps: true check_method_contracts: - verify_interface_like_constraints: true + verify_interface_like_constraints: false verify_documented_constraints: true verify_parent_constraints: true avoid_perl_style_comments: true diff --git a/src/Behat/Behat/Definition/Translator/TranslatorInterface.php b/src/Behat/Behat/Definition/Translator/TranslatorInterface.php index ba9b49558..0c9e5e728 100644 --- a/src/Behat/Behat/Definition/Translator/TranslatorInterface.php +++ b/src/Behat/Behat/Definition/Translator/TranslatorInterface.php @@ -2,7 +2,9 @@ namespace Behat\Behat\Definition\Translator; +/** + * @method string getLocale() + */ interface TranslatorInterface extends \Symfony\Contracts\Translation\TranslatorInterface { - public function getLocale(); } From 205044c6c623fb95c529759db63bf78c07c4da27 Mon Sep 17 00:00:00 2001 From: David Maicher Date: Tue, 26 Oct 2021 17:05:52 +0200 Subject: [PATCH 300/567] update branch alias for dev-master --- composer.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/composer.json b/composer.json index 156bbb55a..f49f1c2c4 100644 --- a/composer.json +++ b/composer.json @@ -55,7 +55,7 @@ "extra": { "branch-alias": { - "dev-master": "3.8.x-dev" + "dev-master": "3.9.x-dev" } }, From 192986b21e47199098eaebab60dc16d00046b919 Mon Sep 17 00:00:00 2001 From: David Maicher Date: Tue, 26 Oct 2021 18:17:15 +0200 Subject: [PATCH 301/567] use 3.x-dev --- composer.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/composer.json b/composer.json index f49f1c2c4..f0718cae7 100644 --- a/composer.json +++ b/composer.json @@ -55,7 +55,7 @@ "extra": { "branch-alias": { - "dev-master": "3.9.x-dev" + "dev-master": "3.x-dev" } }, From 0fa82300bdad7fce8e1441e70e025e39639ad3fc Mon Sep 17 00:00:00 2001 From: David Maicher Date: Tue, 2 Nov 2021 20:50:12 +0100 Subject: [PATCH 302/567] Fix SYMFONY_REQUIRE for github action (#1370) --- .github/workflows/build.yml | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 91ade8519..79e458d0f 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -25,13 +25,11 @@ jobs: - php: 7.3 - php: 7.4 - php: 7.4 - env: - SYMFONY_REQUIRE: 4.4.* + SYMFONY_REQUIRE: 4.4.* - php: 8.0 - php: 8.0 stability: dev - env: - SYMFONY_REQUIRE: 6.0.* + SYMFONY_REQUIRE: 6.0.* - php: 8.1 steps: @@ -59,6 +57,8 @@ jobs: run: composer remove --dev --no-update vimeo/psalm - name: Install dependencies + env: + SYMFONY_REQUIRE: "${{ matrix.SYMFONY_REQUIRE }}" run: composer update ${{ matrix.composer-flags }} - name: Run tests (phpunit) From 8f84ba355a0a1bad786170f900abdde37c9ac879 Mon Sep 17 00:00:00 2001 From: Andor Date: Tue, 2 Nov 2021 20:50:56 +0100 Subject: [PATCH 303/567] Issue #1373 - Replace %1% with %count% in hu translations (#1374) --- i18n.php | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/i18n.php b/i18n.php index 8b0beff99..4cb059fbc 100644 --- a/i18n.php +++ b/i18n.php @@ -94,21 +94,21 @@ 'skipped_count' => '[1,Inf] %count% ignorés', ), 'hu' => array( - 'snippet_context_choice' => '%1% sorozat meghatározatlan lépéseket tartalmaz. Válaszd ki a környezetet kódrészlet készítéséhez:', - 'snippet_proposal_title' => '%1% lépései hiányosak. Hozd létre az alábbi kódrészletekkel:', - 'snippet_missing_title' => 'Használd a --snippets-for parancssori kapcsolót kódrészletek készítéséhez a %1% sorozat lépéseihez:', + 'snippet_context_choice' => '%count% sorozat meghatározatlan lépéseket tartalmaz. Válaszd ki a környezetet kódrészlet készítéséhez:', + 'snippet_proposal_title' => '%count% lépései hiányosak. Hozd létre az alábbi kódrészletekkel:', + 'snippet_missing_title' => 'Használd a --snippets-for parancssori kapcsolót kódrészletek készítéséhez a %count% sorozat lépéseihez:', 'skipped_scenarios_title' => 'Kihagyott forgatókönyvek:', 'failed_scenarios_title' => 'Sikertelen forgatókönyvek:', 'failed_hooks_title' => 'Sikertelen kampók:', 'failed_steps_title' => 'Sikertelen lépések:', 'pending_steps_title' => 'Elintézendő lépések:', - 'scenarios_count' => '{0} Nem volt forgatókönyv|{1} 1 forgatókönyv|]1,Inf] %1% forgatókönyv', - 'steps_count' => '{0} Nem volt lépés|{1} 1 lépés|]1,Inf] %1% lépés', - 'passed_count' => '[1,Inf] %1% sikeres', - 'failed_count' => '[1,Inf] %1% sikertelen', - 'pending_count' => '[1,Inf] %1% elintézendő', - 'undefined_count' => '[1,Inf] %1% meghatározatlan', - 'skipped_count' => '[1,Inf] %1% kihagyott', + 'scenarios_count' => '{0} Nem volt forgatókönyv|{1} 1 forgatókönyv|]1,Inf] %count% forgatókönyv', + 'steps_count' => '{0} Nem volt lépés|{1} 1 lépés|]1,Inf] %count% lépés', + 'passed_count' => '[1,Inf] %count% sikeres', + 'failed_count' => '[1,Inf] %count% sikertelen', + 'pending_count' => '[1,Inf] %count% elintézendő', + 'undefined_count' => '[1,Inf] %count% meghatározatlan', + 'skipped_count' => '[1,Inf] %count% kihagyott', ), 'it' => array( 'snippet_proposal_title' => '%count% ha dei passaggi mancanti. Definiscili con questi snippet:', From bfc5d8208584a0f5c8f086049b922a154b75491b Mon Sep 17 00:00:00 2001 From: Kamil Kokot Date: Tue, 2 Nov 2021 19:59:00 +0000 Subject: [PATCH 304/567] Add changelog for v3.9.1 (#1375) --- CHANGELOG.md | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 30abfca78..fb776955f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,20 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](http://keepachangelog.com/) and this project adheres to [Semantic Versioning](http://semver.org/). +## 3.9.1 - 2021-11-02 + +## What's Changed +* Fix issue 1363 (Symfony 6 compatibility) by @dmaicher in https://github.com/Behat/Behat/pull/1368 +* update branch alias for dev-master by @dmaicher in https://github.com/Behat/Behat/pull/1369 +* Fix SYMFONY_REQUIRE for github action by @dmaicher in https://github.com/Behat/Behat/pull/1370 +* Issue #1373 - Replace %1% with %count% in hu translations by @Sweetchuck in https://github.com/Behat/Behat/pull/1374 + +## New Contributors +* @dmaicher made their first contribution in https://github.com/Behat/Behat/pull/1368 +* @Sweetchuck made their first contribution in https://github.com/Behat/Behat/pull/1374 + +**Full Changelog**: https://github.com/Behat/Behat/compare/v3.9.0...v3.9.1 + ## [3.9.0] - 2021-10-18 ### What's Changed From e1129140cf338372ba8d8d6873d0c0c0d7905b96 Mon Sep 17 00:00:00 2001 From: Remon van de Kamp Date: Tue, 2 Nov 2021 21:00:18 +0100 Subject: [PATCH 305/567] PHP8 Hook attributes (#1372) --- composer.json | 3 +- features/attributes.feature | 363 +++++++++++++++++- .../Context/Reader/AttributeContextReader.php | 2 +- .../Attribute/DefinitionAttributeReader.php | 2 +- .../Context/Attribute/HookAttributeReader.php | 78 ++++ .../Hook/ServiceContainer/HookExtension.php | 16 + src/Behat/Hook/AfterFeature.php | 28 ++ src/Behat/Hook/AfterScenario.php | 28 ++ src/Behat/Hook/AfterStep.php | 28 ++ src/Behat/Hook/BeforeFeature.php | 28 ++ src/Behat/Hook/BeforeScenario.php | 28 ++ src/Behat/Hook/BeforeStep.php | 28 ++ src/Behat/Hook/Hook.php | 21 + 13 files changed, 649 insertions(+), 4 deletions(-) create mode 100644 src/Behat/Behat/Hook/Context/Attribute/HookAttributeReader.php create mode 100644 src/Behat/Hook/AfterFeature.php create mode 100644 src/Behat/Hook/AfterScenario.php create mode 100644 src/Behat/Hook/AfterStep.php create mode 100644 src/Behat/Hook/BeforeFeature.php create mode 100644 src/Behat/Hook/BeforeScenario.php create mode 100644 src/Behat/Hook/BeforeStep.php create mode 100644 src/Behat/Hook/Hook.php diff --git a/composer.json b/composer.json index f0718cae7..f4103d188 100644 --- a/composer.json +++ b/composer.json @@ -43,7 +43,8 @@ "psr-4": { "Behat\\Behat\\": "src/Behat/Behat/", "Behat\\Testwork\\": "src/Behat/Testwork/", - "Behat\\Step\\": "src/Behat/Step/" + "Behat\\Step\\": "src/Behat/Step/", + "Behat\\Hook\\": "src/Behat/Hook/" } }, diff --git a/features/attributes.feature b/features/attributes.feature index 831bc5405..28eca9bce 100644 --- a/features/attributes.feature +++ b/features/attributes.feature @@ -4,7 +4,7 @@ Feature: attributes I need to be able to use PHP8 Attributes @php8 - Scenario: + Scenario: PHP 8 Step Attributes Given a file named "features/bootstrap/FeatureContext.php" with: """ + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Behat\Behat\Hook\Context\Attribute; + +use Behat\Behat\Context\Annotation\DocBlockHelper; +use Behat\Behat\Context\Attribute\AttributeReader; +use Behat\Hook\AfterFeature; +use Behat\Hook\AfterScenario; +use Behat\Hook\AfterStep; +use Behat\Hook\BeforeFeature; +use Behat\Hook\BeforeScenario; +use Behat\Hook\BeforeStep; +use Behat\Hook\Hook; +use ReflectionMethod; + +final class HookAttributeReader implements AttributeReader +{ + /** + * @var string[] + */ + private const KNOWN_ATTRIBUTES = array( + AfterFeature::class => 'Behat\Behat\Hook\Call\AfterFeature', + AfterScenario::class => 'Behat\Behat\Hook\Call\AfterScenario', + AfterStep::class => 'Behat\Behat\Hook\Call\AfterStep', + BeforeFeature::class => 'Behat\Behat\Hook\Call\BeforeFeature', + BeforeScenario::class => 'Behat\Behat\Hook\Call\BeforeScenario', + BeforeStep::class => 'Behat\Behat\Hook\Call\BeforeStep', + ); + + /** + * @var DocBlockHelper + */ + private $docBlockHelper; + + /** + * Initializes reader. + * + * @param DocBlockHelper $docBlockHelper + */ + public function __construct(DocBlockHelper $docBlockHelper) + { + $this->docBlockHelper = $docBlockHelper; + } + + /** + * @{inheritdoc} + */ + public function readCallees(string $contextClass, ReflectionMethod $method) + { + if (\PHP_MAJOR_VERSION < 8) { + return []; + } + + $attributes = $method->getAttributes(Hook::class, \ReflectionAttribute::IS_INSTANCEOF); + + $callees = []; + foreach ($attributes as $attribute) { + $class = self::KNOWN_ATTRIBUTES[$attribute->getName()]; + $callable = array($contextClass, $method->getName()); + $description = null; + if ($docBlock = $method->getDocComment()) { + $description = $this->docBlockHelper->extractDescription($docBlock); + } + + $callees[] = new $class($attribute->newInstance()->filterString, $callable, $description); + } + + return $callees; + } +} diff --git a/src/Behat/Behat/Hook/ServiceContainer/HookExtension.php b/src/Behat/Behat/Hook/ServiceContainer/HookExtension.php index 76d4be9be..97742c392 100644 --- a/src/Behat/Behat/Hook/ServiceContainer/HookExtension.php +++ b/src/Behat/Behat/Hook/ServiceContainer/HookExtension.php @@ -11,6 +11,7 @@ namespace Behat\Behat\Hook\ServiceContainer; use Behat\Behat\Context\ServiceContainer\ContextExtension; +use Behat\Behat\Definition\ServiceContainer\DefinitionExtension; use Behat\Behat\Tester\ServiceContainer\TesterExtension; use Behat\Testwork\Hook\ServiceContainer\HookExtension as BaseExtension; use Symfony\Component\DependencyInjection\ContainerBuilder; @@ -32,6 +33,7 @@ public function load(ContainerBuilder $container, array $config) parent::load($container, $config); $this->loadAnnotationReader($container); + $this->loadAttributeReader($container); } /** @@ -85,4 +87,18 @@ private function loadAnnotationReader(ContainerBuilder $container) $definition->addTag(ContextExtension::ANNOTATION_READER_TAG, array('priority' => 50)); $container->setDefinition(ContextExtension::ANNOTATION_READER_TAG . '.hook', $definition); } + + /** + * Loads hook attribute reader. + * + * @param ContainerBuilder $container + */ + private function loadAttributeReader(ContainerBuilder $container) + { + $definition = new Definition('\Behat\Behat\Hook\Context\Attribute\HookAttributeReader', array( + new Reference(DefinitionExtension::DOC_BLOCK_HELPER_ID) + )); + $definition->addTag(ContextExtension::ATTRIBUTE_READER_TAG, array('priority' => 50)); + $container->setDefinition(ContextExtension::ATTRIBUTE_READER_TAG . '.hook', $definition); + } } diff --git a/src/Behat/Hook/AfterFeature.php b/src/Behat/Hook/AfterFeature.php new file mode 100644 index 000000000..05c818009 --- /dev/null +++ b/src/Behat/Hook/AfterFeature.php @@ -0,0 +1,28 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Behat\Hook; + +/** + * Represents an Attribute for AfterFeature hook + */ +#[\Attribute(\Attribute::TARGET_METHOD | \Attribute::IS_REPEATABLE)] +final class AfterFeature implements Hook +{ + /** + * @var string + */ + public $filterString; + + public function __construct($filterString = null) + { + $this->filterString = $filterString; + } +} diff --git a/src/Behat/Hook/AfterScenario.php b/src/Behat/Hook/AfterScenario.php new file mode 100644 index 000000000..feb480cc1 --- /dev/null +++ b/src/Behat/Hook/AfterScenario.php @@ -0,0 +1,28 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Behat\Hook; + +/** + * Represents an Attribute for AfterScenario hook + */ +#[\Attribute(\Attribute::TARGET_METHOD | \Attribute::IS_REPEATABLE)] +final class AfterScenario implements Hook +{ + /** + * @var string + */ + public $filterString; + + public function __construct($filterString = null) + { + $this->filterString = $filterString; + } +} diff --git a/src/Behat/Hook/AfterStep.php b/src/Behat/Hook/AfterStep.php new file mode 100644 index 000000000..8a27ff646 --- /dev/null +++ b/src/Behat/Hook/AfterStep.php @@ -0,0 +1,28 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Behat\Hook; + +/** + * Represents an Attribute for AfterStep hook + */ +#[\Attribute(\Attribute::TARGET_METHOD | \Attribute::IS_REPEATABLE)] +final class AfterStep implements Hook +{ + /** + * @var string + */ + public $filterString; + + public function __construct($filterString = null) + { + $this->filterString = $filterString; + } +} diff --git a/src/Behat/Hook/BeforeFeature.php b/src/Behat/Hook/BeforeFeature.php new file mode 100644 index 000000000..401ae2e75 --- /dev/null +++ b/src/Behat/Hook/BeforeFeature.php @@ -0,0 +1,28 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Behat\Hook; + +/** + * Represents an Attribute for BeforeFeature hook + */ +#[\Attribute(\Attribute::TARGET_METHOD | \Attribute::IS_REPEATABLE)] +final class BeforeFeature implements Hook +{ + /** + * @var string + */ + public $filterString; + + public function __construct($filterString = null) + { + $this->filterString = $filterString; + } +} diff --git a/src/Behat/Hook/BeforeScenario.php b/src/Behat/Hook/BeforeScenario.php new file mode 100644 index 000000000..d1d0bb7ef --- /dev/null +++ b/src/Behat/Hook/BeforeScenario.php @@ -0,0 +1,28 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Behat\Hook; + +/** + * Represents an Attribute for BeforeScenario hook + */ +#[\Attribute(\Attribute::TARGET_METHOD | \Attribute::IS_REPEATABLE)] +final class BeforeScenario implements Hook +{ + /** + * @var string + */ + public $filterString; + + public function __construct($filterString = null) + { + $this->filterString = $filterString; + } +} diff --git a/src/Behat/Hook/BeforeStep.php b/src/Behat/Hook/BeforeStep.php new file mode 100644 index 000000000..1c7097143 --- /dev/null +++ b/src/Behat/Hook/BeforeStep.php @@ -0,0 +1,28 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Behat\Hook; + +/** + * Represents an Attribute for BeforeStep hook + */ +#[\Attribute(\Attribute::TARGET_METHOD | \Attribute::IS_REPEATABLE)] +final class BeforeStep implements Hook +{ + /** + * @var string + */ + public $filterString; + + public function __construct($filterString = null) + { + $this->filterString = $filterString; + } +} diff --git a/src/Behat/Hook/Hook.php b/src/Behat/Hook/Hook.php new file mode 100644 index 000000000..8c6dc7d8b --- /dev/null +++ b/src/Behat/Hook/Hook.php @@ -0,0 +1,21 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Behat\Hook; + +/** + * Marker interface for all Attributes regarding + * Hooks + * + * @internal Only meant as marker, not as an extension point + */ +interface Hook +{ +} From a55661154079cf881ef643b303bfaf67bae3a09f Mon Sep 17 00:00:00 2001 From: Kamil Kokot Date: Tue, 2 Nov 2021 20:09:40 +0000 Subject: [PATCH 306/567] Add changelog for v3.10.0 (#1376) --- CHANGELOG.md | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index fb776955f..167b643e1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,13 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](http://keepachangelog.com/) and this project adheres to [Semantic Versioning](http://semver.org/). +## 3.10.0 - 2021-11-02 + +## What's Changed +* PHP8 Hook attributes by @rpkamp in https://github.com/Behat/Behat/pull/1372 + +**Full Changelog**: https://github.com/Behat/Behat/compare/v3.9.1...v3.10.0 + ## 3.9.1 - 2021-11-02 ## What's Changed From 0c6b45fd10198976941c059a3089ddd901228c17 Mon Sep 17 00:00:00 2001 From: Wouter de Jong Date: Sat, 25 Dec 2021 10:42:21 +0100 Subject: [PATCH 307/567] Add support for psr/container 2.0, remove container-interop --- .github/workflows/build.yml | 8 +--- composer.json | 3 +- features/autowire.feature | 2 +- features/helper_containers.feature | 43 ++----------------- .../BuiltInServiceContainer.php | 5 ++- .../HelperContainer/ContainerInterface.php | 7 +-- 6 files changed, 11 insertions(+), 57 deletions(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 79e458d0f..82733ebb9 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -18,8 +18,6 @@ jobs: include: - php: 7.2 publish-phar: true - - php: 7.2 - skip-interop: true - php: 7.2 composer-flags: --prefer-lowest - php: 7.3 @@ -49,10 +47,6 @@ jobs: - name: Install symfony/flex run: composer global require symfony/flex - - name: Uninstall container interop - if: matrix.skip-interop - run: composer remove --dev --no-update container-interop/container-interop - - name: Uninstall Psalm run: composer remove --dev --no-update vimeo/psalm @@ -65,7 +59,7 @@ jobs: run: ./vendor/bin/phpunit - name: Run tests (Behat) - run: ./bin/behat -fprogress --strict $([ -z "${{ matrix.skip-interop }}" ] || echo "--tags ~@interop&&~@php8") + run: ./bin/behat -fprogress --strict - name: Run tests (Behat for PHP 8.0) if: matrix.php >= 8.0 diff --git a/composer.json b/composer.json index f4103d188..072816bd9 100644 --- a/composer.json +++ b/composer.json @@ -24,14 +24,13 @@ "symfony/event-dispatcher": "^4.4 || ^5.0 || ^6.0", "symfony/translation": "^4.4 || ^5.0 || ^6.0", "symfony/yaml": "^4.4 || ^5.0 || ^6.0", - "psr/container": "^1.0" + "psr/container": "^1.0 || ^2.0" }, "require-dev": { "symfony/process": "^4.4 || ^5.0 || ^6.0", "phpunit/phpunit": "^8.5 || ^9.0", "herrera-io/box": "~1.6.1", - "container-interop/container-interop": "^1.2", "vimeo/psalm": "^4.8" }, diff --git a/features/autowire.feature b/features/autowire.feature index 4d31b6514..a69266b94 100644 --- a/features/autowire.feature +++ b/features/autowire.feature @@ -35,7 +35,7 @@ Feature: Helper services autowire class ServiceContainer implements ContainerInterface { private $services = array(); - public function has($class) { + public function has($class): bool { return in_array($class, array('Service1', 'Service2', 'Service3')); } diff --git a/features/helper_containers.feature b/features/helper_containers.feature index e24d5f0eb..45f6b0734 100644 --- a/features/helper_containers.feature +++ b/features/helper_containers.feature @@ -125,7 +125,7 @@ Feature: Per-suite helper containers class MyContainer implements ContainerInterface { private $service; - public function has($id) { + public function has($id): bool { return $id == 'shared_service'; } @@ -164,42 +164,7 @@ Feature: Per-suite helper containers return new self(); } - public function has($id) { - return $id == 'shared_service'; - } - - public function get($id) { - if ($id !== 'shared_service') throw new \InvalidArgumentException(); - return isset($this->service) ? $this->service : $this->service = new SharedService(); - } - } - """ - When I run "behat --no-colors -f progress features/container.feature" - Then it should pass - - @interop - Scenario: Interop container - Given a file named "behat.yml" with: - """ - default: - suites: - default: - contexts: - - FirstContext: - - "@shared_service" - - SecondContext: - - "@shared_service" - - services: MyContainer - """ - And a file named "features/bootstrap/MyContainer.php" with: - """ - */ -final class BuiltInServiceContainer implements ContainerInterface +final class BuiltInServiceContainer implements PsrContainerInterface { /** * @var array @@ -44,7 +45,7 @@ public function __construct(array $schema) /** * {@inheritdoc} */ - public function has($id) + public function has($id): bool { return array_key_exists($id, $this->schema); } diff --git a/src/Behat/Behat/HelperContainer/ContainerInterface.php b/src/Behat/Behat/HelperContainer/ContainerInterface.php index 75fb43fa8..88998ff4c 100644 --- a/src/Behat/Behat/HelperContainer/ContainerInterface.php +++ b/src/Behat/Behat/HelperContainer/ContainerInterface.php @@ -10,12 +10,7 @@ namespace Behat\Behat\HelperContainer; -class_alias( - interface_exists('Interop\\Container\\ContainerInterface') - ? 'Interop\\Container\\ContainerInterface' - : 'Psr\\Container\\ContainerInterface', - 'Behat\\Behat\\HelperContainer\\ContainerInterface' -); +class_alias('Psr\\Container\\ContainerInterface', 'Behat\\Behat\\HelperContainer\\ContainerInterface'); if (false) { /** From dd81416f1921c9a2c1635d40ddf9af94fed6c7cb Mon Sep 17 00:00:00 2001 From: Pascal Paulis Date: Wed, 6 Apr 2022 08:37:09 +0200 Subject: [PATCH 308/567] added file attribute to JUnit testcase-tag Signed-off-by: Pascal Paulis --- features/bootstrap/FeatureContext.php | 5 ++- features/bootstrap/schema/junit.xsd | 1 + features/junit_format.feature | 36 +++++++++---------- .../JUnit/JUnitFeatureElementListener.php | 8 ++++- .../Printer/JUnit/JUnitScenarioPrinter.php | 20 +++++++---- 5 files changed, 44 insertions(+), 26 deletions(-) diff --git a/features/bootstrap/FeatureContext.php b/features/bootstrap/FeatureContext.php index db8128a23..b49509cb8 100644 --- a/features/bootstrap/FeatureContext.php +++ b/features/bootstrap/FeatureContext.php @@ -312,7 +312,10 @@ public function fileXmlShouldBeLike($path, PyStringNode $text) $fileContent = trim(file_get_contents($path)); - $fileContent = preg_replace('/time="(.*)"/', 'time="-IGNORE-VALUE-"', $fileContent); + $fileContent = preg_replace('/time="(.*)"/U', 'time="-IGNORE-VALUE-"', $fileContent); + + // The placeholder is necessary because of different separators on Unix and Windows environments + $text = str_replace('-DIRECTORY-SEPARATOR-', DIRECTORY_SEPARATOR, $text); $dom = new DOMDocument(); $dom->loadXML($text); diff --git a/features/bootstrap/schema/junit.xsd b/features/bootstrap/schema/junit.xsd index 901a7f716..5b293589e 100644 --- a/features/bootstrap/schema/junit.xsd +++ b/features/bootstrap/schema/junit.xsd @@ -48,6 +48,7 @@ + diff --git a/features/junit_format.feature b/features/junit_format.feature index 5a73bfbd4..2ed6b972d 100644 --- a/features/junit_format.feature +++ b/features/junit_format.feature @@ -105,24 +105,24 @@ - + - + - + - + - - + + - - + + """ @@ -192,10 +192,10 @@ - + - + """ @@ -267,8 +267,8 @@ - - + + """ @@ -387,7 +387,7 @@ - + """ @@ -456,8 +456,8 @@ - - + + """ @@ -518,7 +518,7 @@ - + @@ -648,7 +648,7 @@ - + @@ -704,7 +704,7 @@ - + diff --git a/src/Behat/Behat/Output/Node/EventListener/JUnit/JUnitFeatureElementListener.php b/src/Behat/Behat/Output/Node/EventListener/JUnit/JUnitFeatureElementListener.php index 031accdaa..2aae5a2cf 100644 --- a/src/Behat/Behat/Output/Node/EventListener/JUnit/JUnitFeatureElementListener.php +++ b/src/Behat/Behat/Output/Node/EventListener/JUnit/JUnitFeatureElementListener.php @@ -169,7 +169,13 @@ public function printFeatureOnAfterEvent(Formatter $formatter, Event $event) foreach ($this->afterScenarioTestedEvents as $afterScenario) { $afterScenarioTested = $afterScenario['event']; - $this->scenarioPrinter->printOpenTag($formatter, $afterScenarioTested->getFeature(), $afterScenarioTested->getScenario(), $afterScenarioTested->getTestResult()); + $this->scenarioPrinter->printOpenTag( + $formatter, + $afterScenarioTested->getFeature(), + $afterScenarioTested->getScenario(), + $afterScenarioTested->getTestResult(), + $event->getFeature()->getFile() + ); /** @var AfterStepSetup $afterStepSetup */ foreach ($afterScenario['step_setup_events'] as $afterStepSetup) { diff --git a/src/Behat/Behat/Output/Node/Printer/JUnit/JUnitScenarioPrinter.php b/src/Behat/Behat/Output/Node/Printer/JUnit/JUnitScenarioPrinter.php index 0ca46e987..da162a15a 100644 --- a/src/Behat/Behat/Output/Node/Printer/JUnit/JUnitScenarioPrinter.php +++ b/src/Behat/Behat/Output/Node/Printer/JUnit/JUnitScenarioPrinter.php @@ -63,7 +63,7 @@ public function __construct(ResultToStringConverter $resultConverter, JUnitOutli /** * {@inheritDoc} */ - public function printOpenTag(Formatter $formatter, FeatureNode $feature, ScenarioLikeInterface $scenario, TestResult $result) + public function printOpenTag(Formatter $formatter, FeatureNode $feature, ScenarioLikeInterface $scenario, TestResult $result, string $file = null) { $name = implode(' ', array_map(function ($l) { return trim($l); @@ -76,12 +76,20 @@ public function printOpenTag(Formatter $formatter, FeatureNode $feature, Scenari /** @var JUnitOutputPrinter $outputPrinter */ $outputPrinter = $formatter->getOutputPrinter(); - $outputPrinter->addTestcase(array( - 'name' => $name, + $testCaseAttributes = array( + 'name' => $name, 'classname' => $feature->getTitle(), - 'status' => $this->resultConverter->convertResultToString($result), - 'time' => $this->durationListener ? $this->durationListener->getDuration($scenario) : '' - )); + 'status' => $this->resultConverter->convertResultToString($result), + 'time' => $this->durationListener ? $this->durationListener->getDuration($scenario) : '' + ); + + if ($file) { + $testCaseAttributes['file'] = + substr($file, 0, strlen(getcwd())) === getcwd() ? + ltrim(substr($file, strlen(getcwd())), DIRECTORY_SEPARATOR) : $file; + } + + $outputPrinter->addTestcase($testCaseAttributes); } /** From 0256f4285eaa3ccc81b144379a9007dd6b417790 Mon Sep 17 00:00:00 2001 From: Pascal Paulis Date: Wed, 6 Apr 2022 08:58:15 +0200 Subject: [PATCH 309/567] fixed tests Signed-off-by: Pascal Paulis --- features/junit_format.feature | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/features/junit_format.feature b/features/junit_format.feature index 2ed6b972d..c85759746 100644 --- a/features/junit_format.feature +++ b/features/junit_format.feature @@ -105,7 +105,7 @@ - + @@ -397,7 +397,7 @@ - + From 2eda9c78a3b72de1610d57a492a9d039c69e4aba Mon Sep 17 00:00:00 2001 From: Ciaran McNulty Date: Thu, 30 Jun 2022 14:36:52 +0100 Subject: [PATCH 310/567] Automerge script --- .github/workflows/automerge.yml | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 .github/workflows/automerge.yml diff --git a/.github/workflows/automerge.yml b/.github/workflows/automerge.yml new file mode 100644 index 000000000..2c8881ac1 --- /dev/null +++ b/.github/workflows/automerge.yml @@ -0,0 +1,20 @@ +name: 'Up merge' + +on: + push: + branches: [ master ] + +jobs: + nightly-merge: + + runs-on: ubuntu-latest + + steps: + - name: Checkout + uses: actions/checkout@v2 + + - name: Up Merge + uses: bambamboole/gha-upmerge@master + with: + stable_branch: 'master' + development_branch: '4.x' From aed1000a8c6c0f5d55d84cf0e6d26c9a04be785b Mon Sep 17 00:00:00 2001 From: Ciaran McNulty Date: Thu, 30 Jun 2022 14:39:56 +0100 Subject: [PATCH 311/567] Fix automerge GHA branch --- .github/workflows/automerge.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/automerge.yml b/.github/workflows/automerge.yml index 2c8881ac1..aee06468c 100644 --- a/.github/workflows/automerge.yml +++ b/.github/workflows/automerge.yml @@ -14,7 +14,7 @@ jobs: uses: actions/checkout@v2 - name: Up Merge - uses: bambamboole/gha-upmerge@master + uses: bambamboole/gha-upmerge@main with: stable_branch: 'master' development_branch: '4.x' From c618a0e11aec526a79449c5af932a4695f95bd4a Mon Sep 17 00:00:00 2001 From: Ciaran McNulty Date: Thu, 30 Jun 2022 14:41:28 +0100 Subject: [PATCH 312/567] Fix GHA upmerge field names --- .github/workflows/automerge.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/automerge.yml b/.github/workflows/automerge.yml index aee06468c..c27680151 100644 --- a/.github/workflows/automerge.yml +++ b/.github/workflows/automerge.yml @@ -16,5 +16,5 @@ jobs: - name: Up Merge uses: bambamboole/gha-upmerge@main with: - stable_branch: 'master' - development_branch: '4.x' + from_branch: 'master' + to_branch: '4.x' From cf98cc58cd5717b8ab7211aa9ca7cde64662f010 Mon Sep 17 00:00:00 2001 From: Ciaran McNulty Date: Thu, 30 Jun 2022 14:42:58 +0100 Subject: [PATCH 313/567] Fix GHA upmerge github token --- .github/workflows/automerge.yml | 2 ++ 1 file changed, 2 insertions(+) diff --git a/.github/workflows/automerge.yml b/.github/workflows/automerge.yml index c27680151..d2e951bab 100644 --- a/.github/workflows/automerge.yml +++ b/.github/workflows/automerge.yml @@ -18,3 +18,5 @@ jobs: with: from_branch: 'master' to_branch: '4.x' + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} From e1279d2575878b166d64e7a6ca3492454cdf84cc Mon Sep 17 00:00:00 2001 From: Ciaran McNulty Date: Thu, 30 Jun 2022 14:45:33 +0100 Subject: [PATCH 314/567] Remove failed merge-up script --- .github/workflows/automerge.yml | 22 ---------------------- 1 file changed, 22 deletions(-) delete mode 100644 .github/workflows/automerge.yml diff --git a/.github/workflows/automerge.yml b/.github/workflows/automerge.yml deleted file mode 100644 index d2e951bab..000000000 --- a/.github/workflows/automerge.yml +++ /dev/null @@ -1,22 +0,0 @@ -name: 'Up merge' - -on: - push: - branches: [ master ] - -jobs: - nightly-merge: - - runs-on: ubuntu-latest - - steps: - - name: Checkout - uses: actions/checkout@v2 - - - name: Up Merge - uses: bambamboole/gha-upmerge@main - with: - from_branch: 'master' - to_branch: '4.x' - env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} From c1e69346e2088513e5a82f6636d64124b35db987 Mon Sep 17 00:00:00 2001 From: Ciaran McNulty Date: Thu, 30 Jun 2022 16:21:39 +0100 Subject: [PATCH 315/567] Suppress false-positive static analysis issues --- psalm.xml | 7 +++++++ .../Context/Attribute/DefinitionAttributeReader.php | 3 +++ .../Behat/Hook/Context/Attribute/HookAttributeReader.php | 3 +++ src/Behat/Testwork/Argument/MixedArgumentOrganiser.php | 3 +++ .../Testwork/EventDispatcher/Cli/SigintController.php | 4 ++++ 5 files changed, 20 insertions(+) diff --git a/psalm.xml b/psalm.xml index 99f6bdb8d..067db6cc4 100644 --- a/psalm.xml +++ b/psalm.xml @@ -32,6 +32,13 @@ + + + + + + + diff --git a/src/Behat/Behat/Definition/Context/Attribute/DefinitionAttributeReader.php b/src/Behat/Behat/Definition/Context/Attribute/DefinitionAttributeReader.php index c37300f77..7fcfd2f7c 100644 --- a/src/Behat/Behat/Definition/Context/Attribute/DefinitionAttributeReader.php +++ b/src/Behat/Behat/Definition/Context/Attribute/DefinitionAttributeReader.php @@ -58,6 +58,9 @@ public function readCallees(string $contextClass, ReflectionMethod $method) return []; } + /** + * @psalm-suppress UndefinedClass (ReflectionAttribute is PHP 8.0 only) + */ $attributes = $method->getAttributes(Definition::class, \ReflectionAttribute::IS_INSTANCEOF); $callees = []; diff --git a/src/Behat/Behat/Hook/Context/Attribute/HookAttributeReader.php b/src/Behat/Behat/Hook/Context/Attribute/HookAttributeReader.php index f49dd93dc..4d569b28a 100644 --- a/src/Behat/Behat/Hook/Context/Attribute/HookAttributeReader.php +++ b/src/Behat/Behat/Hook/Context/Attribute/HookAttributeReader.php @@ -59,6 +59,9 @@ public function readCallees(string $contextClass, ReflectionMethod $method) return []; } + /** + * @psalm-suppress UndefinedClass (ReflectionAttribute is PHP 8.0 only) + */ $attributes = $method->getAttributes(Hook::class, \ReflectionAttribute::IS_INSTANCEOF); $callees = []; diff --git a/src/Behat/Testwork/Argument/MixedArgumentOrganiser.php b/src/Behat/Testwork/Argument/MixedArgumentOrganiser.php index 49694e298..f9a6a4b54 100644 --- a/src/Behat/Testwork/Argument/MixedArgumentOrganiser.php +++ b/src/Behat/Testwork/Argument/MixedArgumentOrganiser.php @@ -241,6 +241,9 @@ private function getReflectionClassesFromParameter(\ReflectionParameter $paramet $type = $parameter->getType(); + /** + * @psalm-suppress UndefinedClass (ReflectionUnionType) + */ if ($type instanceof \ReflectionNamedType) { $types = [$type]; } diff --git a/src/Behat/Testwork/EventDispatcher/Cli/SigintController.php b/src/Behat/Testwork/EventDispatcher/Cli/SigintController.php index 4569391a7..f0d7d2c3b 100644 --- a/src/Behat/Testwork/EventDispatcher/Cli/SigintController.php +++ b/src/Behat/Testwork/EventDispatcher/Cli/SigintController.php @@ -55,6 +55,10 @@ public function execute(InputInterface $input, OutputInterface $output) { if (function_exists('pcntl_signal')) { pcntl_async_signals(true); + + /** + * @psalm-suppress UndefinedConstant (SIGINT is defined in pcntl) + */ pcntl_signal(SIGINT, array($this, 'abortExercise')); } } From ee75a3d9d9bebdc7b01dabe0e4e9a84e33491308 Mon Sep 17 00:00:00 2001 From: Ciaran McNulty Date: Thu, 30 Jun 2022 16:33:50 +0100 Subject: [PATCH 316/567] Run GHA on windows --- .github/workflows/build.yml | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 79e458d0f..56af77b45 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -10,7 +10,7 @@ on: jobs: tests: - runs-on: ubuntu-latest + runs-on: ${{ matrix.os }} name: Build and test strategy: fail-fast: false @@ -18,19 +18,31 @@ jobs: include: - php: 7.2 publish-phar: true + os: ubuntu-latest - php: 7.2 skip-interop: true + os: ubuntu-latest - php: 7.2 composer-flags: --prefer-lowest + os: ubuntu-latest - php: 7.3 + os: ubuntu-latest - php: 7.4 + os: ubuntu-latest - php: 7.4 SYMFONY_REQUIRE: 4.4.* + os: ubuntu-latest - php: 8.0 + os: ubuntu-latest - php: 8.0 stability: dev SYMFONY_REQUIRE: 6.0.* + os: ubuntu-latest + - php: 8.1 + os: windows-latest - php: 8.1 + os: ubuntu-latest + steps: - uses: actions/checkout@v2 From 7cd44bdbeb0444151200be4b451b1befddf6a337 Mon Sep 17 00:00:00 2001 From: Ciaran McNulty Date: Thu, 30 Jun 2022 16:38:22 +0100 Subject: [PATCH 317/567] Run tests on MacOS --- .github/workflows/build.yml | 2 ++ 1 file changed, 2 insertions(+) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 56af77b45..9c9cf441e 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -38,6 +38,8 @@ jobs: stability: dev SYMFONY_REQUIRE: 6.0.* os: ubuntu-latest + - php: 8.1 + os: macos-latest - php: 8.1 os: windows-latest - php: 8.1 From a1a873ca5c664315c4086b632b0a16884fe81b41 Mon Sep 17 00:00:00 2001 From: Ciaran McNulty Date: Thu, 30 Jun 2022 16:40:02 +0100 Subject: [PATCH 318/567] Drop Appveyor --- appveyor.yml | 62 ---------------------------------------------------- 1 file changed, 62 deletions(-) delete mode 100644 appveyor.yml diff --git a/appveyor.yml b/appveyor.yml deleted file mode 100644 index 12f5af0a1..000000000 --- a/appveyor.yml +++ /dev/null @@ -1,62 +0,0 @@ -version: '{build}' -build: false -shallow_clone: false -platform: x86 -clone_folder: c:\projects\behat - -branches: - only: - - master - -skip_commits: - message: /\[ci skip\]/ - -cache: - - C:\ProgramData\chocolatey\bin -> appveyor.yml - - C:\ProgramData\chocolatey\lib -> appveyor.yml - - C:\tools\php -> appveyor.yml - - C:\tools\composer -> appveyor.yml - - '%LOCALAPPDATA%\Composer\files' - -init: - - SET PATH=C:\Program Files\OpenSSL;c:\tools\php;C:\tools\composer;%PATH% - - SET COMPOSER_NO_INTERACTION=1 - - SET ANSICON=121x90 (121x90) - - git config --global core.autocrlf input - -install: - - ps: | - if (!(Test-Path c:\tools\php)) { - appveyor-retry cinst --params '""/InstallDir:C:\tools\php""' --ignore-checksums -y php --version 7.2 - Get-ChildItem -Path c:\tools\php - cd c:\tools\php - - # Set PHP environment items that are always needed - copy php.ini-production php.ini - Add-Content php.ini "`n date.timezone=UTC" - Add-Content php.ini "`n extension_dir=ext" - Add-Content php.ini "`n extension=php_openssl.dll" - Add-Content php.ini "`n extension=php_curl.dll" - Add-Content php.ini "`n extension=php_mbstring.dll" - Add-Content php.ini "`n extension=php_fileinfo.dll" - Add-Content php.ini "`n zend.exception_ignore_args=Off" - - # download Composer - if (!(Test-Path C:\tools\composer)) { - New-Item -path c:\tools -name composer -itemtype directory - } - - if (!(Test-Path c:\tools\composer\composer.phar)) { - appveyor-retry appveyor DownloadFile https://getcomposer.org/composer.phar -Filename C:\tools\composer\composer.phar - Set-Content -path 'C:\tools\composer\composer.bat' -Value ('@php C:\tools\composer\composer.phar %*') - } - } - - - cd c:\projects\behat - - appveyor-retry composer self-update - - appveyor-retry composer install --no-progress --ansi - -test_script: - - cd c:\projects\behat - - php bin\behat --format=progress - - php vendor\phpunit\phpunit\phpunit --testdox From dc40a341ae3314ef56d456389605eabe478a4a62 Mon Sep 17 00:00:00 2001 From: Ciaran McNulty Date: Thu, 30 Jun 2022 16:44:36 +0100 Subject: [PATCH 319/567] Remove scrutinizer --- .scrutinizer.yml | 67 ------------------------------------------------ 1 file changed, 67 deletions(-) delete mode 100644 .scrutinizer.yml diff --git a/.scrutinizer.yml b/.scrutinizer.yml deleted file mode 100644 index 1f9349e13..000000000 --- a/.scrutinizer.yml +++ /dev/null @@ -1,67 +0,0 @@ -filter: - paths: [ 'src/*' ] - -build_failure_conditions: - - 'elements.rating(<= D).exists' - - 'elements.rating(<= B).new.exists' - - 'issues.label("coding-style").new.exists' - - 'issues.severity(>= MAJOR).new.exists' - -coding_style: - php: - spaces: - around_operators: - concatenation: true - braces: - classes_functions: - class: new-line - function: new-line - closure: end-of-line - if: - opening: end-of-line - for: - opening: end-of-line - while: - opening: end-of-line - do_while: - opening: end-of-line - switch: - opening: end-of-line - try: - opening: end-of-line - upper_lower_casing: - keywords: - general: lower - constants: - true_false_null: lower - -checks: - php: - code_rating: true - duplication: true - verify_property_names: true - uppercase_constants: true - remove_extra_empty_lines: true - properties_in_camelcaps: true - parameters_in_camelcaps: true - overriding_parameter: true - optional_parameters_at_the_end: true - function_in_camel_caps: true - encourage_single_quotes: true - classes_in_camel_caps: true - check_method_contracts: - verify_interface_like_constraints: false - verify_documented_constraints: true - verify_parent_constraints: true - avoid_perl_style_comments: true - avoid_usage_of_logical_operators: true - no_exit: false - no_unnecessary_final_modifier: false - overriding_private_members: false - -build: - nodes: - analysis: - tests: - override: - - php-scrutinizer-run From c2c3952bb3b2182886e793aa93883ff306af8042 Mon Sep 17 00:00:00 2001 From: Ciaran McNulty Date: Thu, 30 Jun 2022 16:46:33 +0100 Subject: [PATCH 320/567] Use less bash in the gha to avoid confusing windows --- .github/workflows/build.yml | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 9c9cf441e..bccf80193 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -79,7 +79,11 @@ jobs: run: ./vendor/bin/phpunit - name: Run tests (Behat) - run: ./bin/behat -fprogress --strict $([ -z "${{ matrix.skip-interop }}" ] || echo "--tags ~@interop&&~@php8") + run: ./bin/behat -fprogress --strict --tags="~@interop&&~@php8" + + - name: Run tests (Behat with Interop) + if: matrix.skip-interop != true + run: ./bin/behat -fprogress --strict --tags=@interop - name: Run tests (Behat for PHP 8.0) if: matrix.php >= 8.0 From f088203a79c38d39a9d3d108c777408cdd4733c6 Mon Sep 17 00:00:00 2001 From: Ciaran McNulty Date: Thu, 30 Jun 2022 16:54:15 +0100 Subject: [PATCH 321/567] Set default shell to bash --- .github/workflows/build.yml | 3 +++ 1 file changed, 3 insertions(+) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index bccf80193..f7191160e 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -11,6 +11,9 @@ on: jobs: tests: runs-on: ${{ matrix.os }} + defaults: + run: + shell: bash name: Build and test strategy: fail-fast: false From 85f3c832f28dfb176dc2da1181903d55f644ed31 Mon Sep 17 00:00:00 2001 From: Ciaran McNulty Date: Thu, 30 Jun 2022 17:38:57 +0100 Subject: [PATCH 322/567] Fix JUnit printer to use realpath when comparing folders --- .../Behat/Output/Node/Printer/JUnit/JUnitScenarioPrinter.php | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/Behat/Behat/Output/Node/Printer/JUnit/JUnitScenarioPrinter.php b/src/Behat/Behat/Output/Node/Printer/JUnit/JUnitScenarioPrinter.php index da162a15a..8ed7b09ab 100644 --- a/src/Behat/Behat/Output/Node/Printer/JUnit/JUnitScenarioPrinter.php +++ b/src/Behat/Behat/Output/Node/Printer/JUnit/JUnitScenarioPrinter.php @@ -84,9 +84,10 @@ public function printOpenTag(Formatter $formatter, FeatureNode $feature, Scenari ); if ($file) { + $cwd = realpath(getcwd()); $testCaseAttributes['file'] = - substr($file, 0, strlen(getcwd())) === getcwd() ? - ltrim(substr($file, strlen(getcwd())), DIRECTORY_SEPARATOR) : $file; + substr($file, 0, strlen($cwd)) === $cwd ? + ltrim(substr($file, strlen($cwd)), DIRECTORY_SEPARATOR) : $file; } $outputPrinter->addTestcase($testCaseAttributes); From 481aafce6849b70616c31c4fb4189762928dfc81 Mon Sep 17 00:00:00 2001 From: Tymoteusz <39466319+delyro@users.noreply.github.com> Date: Wed, 29 Jun 2022 01:05:09 +0200 Subject: [PATCH 323/567] Issue #1373 - Replace %1% with %count% in bg and ko translations --- i18n.php | 38 +++++++++++++++++++------------------- 1 file changed, 19 insertions(+), 19 deletions(-) diff --git a/i18n.php b/i18n.php index 4cb059fbc..8737b26fc 100644 --- a/i18n.php +++ b/i18n.php @@ -17,21 +17,21 @@ 'skipped_count' => '[1,Inf] %count% skipped', ), 'bg' => array( - 'snippet_context_choice' => 'В сет %1% има недекларирани стъпки. Изберете в кой Context да бъдат създадени:', - 'snippet_proposal_title' => '%1% има липсващи стъпки. Можете да ги създадете чрез:', - 'snippet_missing_title' => 'Използвайте този снипет --snippets-for за да генерирате кода за следните стъпки %1% през конзолата:', + 'snippet_context_choice' => 'В сет %count% има недекларирани стъпки. Изберете в кой Context да бъдат създадени:', + 'snippet_proposal_title' => '%count% има липсващи стъпки. Можете да ги създадете чрез:', + 'snippet_missing_title' => 'Използвайте този снипет --snippets-for за да генерирате кода за следните стъпки %count% през конзолата:', 'skipped_scenarios_title' => 'Пропуснати сценарии:', 'failed_scenarios_title' => 'Провалени сценарии:', 'failed_hooks_title' => 'Провалени хукове:', 'failed_steps_title' => 'Провалени стъпки:', 'pending_steps_title' => 'Изчакващи стъпки:', - 'scenarios_count' => '{0} Няма сценарий|{1} 1 сценарий|]1,Inf] %1% сценарии', - 'steps_count' => '{0} Няма стъпки|{1} 1 стъпка|]1,Inf] %1% стъпки', - 'passed_count' => '[1,Inf] %1% успешни', - 'failed_count' => '[1,Inf] %1% провалени', - 'pending_count' => '[1,Inf] %1% изчакващи', - 'undefined_count' => '[1,Inf] %1% неопределени', - 'skipped_count' => '[1,Inf] %1% пропуснати', + 'scenarios_count' => '{0} Няма сценарий|{1} 1 сценарий|]1,Inf] %count% сценарии', + 'steps_count' => '{0} Няма стъпки|{1} 1 стъпка|]1,Inf] %count% стъпки', + 'passed_count' => '[1,Inf] %count% успешни', + 'failed_count' => '[1,Inf] %count% провалени', + 'pending_count' => '[1,Inf] %count% изчакващи', + 'undefined_count' => '[1,Inf] %count% неопределени', + 'skipped_count' => '[1,Inf] %count% пропуснати', ), 'cs' => array( 'snippet_proposal_title' => '%count% obsahuje chybné kroky. Definujte je za použití následujícího kódu:', @@ -142,20 +142,20 @@ 'skipped_count' => '[1,Inf] %count% 個スキップ', ), 'ko' => array( - 'snippet_proposal_title' => '%1% 정의가 되지 않았습니다. 스니펫을 생성할 컨텍스트를 선택하십시오:', - 'snippet_missing_title' => '%1% 단계가 누락되었습니다. 스니펫을 정의해주세요:', + 'snippet_proposal_title' => '%count% 정의가 되지 않았습니다. 스니펫을 생성할 컨텍스트를 선택하십시오:', + 'snippet_missing_title' => '%count% 단계가 누락되었습니다. 스니펫을 정의해주세요:', 'skipped_scenarios_title' => '건너뛴 시나리오:', 'failed_scenarios_title' => '실패한 시나리오:', 'failed_hooks_title' => '실패한 훅 연결:', 'failed_steps_title' => '실패한 단계:', 'pending_steps_title' => '준비중인 단계:', - 'scenarios_count' => '{0} 없는 시나리오들|{1} 1 시나리오|]1,Inf] %1% 시나리오들', - 'steps_count' => '{0} 없는 단계들|{1} 1 단계|]1,Inf] %1% 단계들', - 'passed_count' => '[1,Inf] %1% 통과', - 'failed_count' => '[1,Inf] %1% 실패', - 'pending_count' => '[1,Inf] %1% 준비중', - 'undefined_count' => '[1,Inf] %1% 정의되지 않았습니다.', - 'skipped_count' => '[1,Inf] %1% 건너뜀', + 'scenarios_count' => '{0} 없는 시나리오들|{1} 1 시나리오|]1,Inf] %count% 시나리오들', + 'steps_count' => '{0} 없는 단계들|{1} 1 단계|]1,Inf] %count% 단계들', + 'passed_count' => '[1,Inf] %count% 통과', + 'failed_count' => '[1,Inf] %count% 실패', + 'pending_count' => '[1,Inf] %count% 준비중', + 'undefined_count' => '[1,Inf] %count% 정의되지 않았습니다.', + 'skipped_count' => '[1,Inf] %count% 건너뜀', ), 'nl' => array( 'snippet_proposal_title' => 'Ontbrekende stappen in %count%. Definieer ze met de volgende fragmenten:', From 0948c09630651ae649144a15d222745b85428b03 Mon Sep 17 00:00:00 2001 From: David Grayston Date: Thu, 18 Jun 2020 23:23:57 +0100 Subject: [PATCH 324/567] Print example row step text with exception --- features/format_options.feature | 4 ++++ features/i18n.feature | 2 ++ features/multiple_formats.feature | 5 +++++ features/pretty_format.feature | 2 ++ .../Node/Printer/Pretty/PrettyExampleRowPrinter.php | 8 ++++++-- 5 files changed, 19 insertions(+), 2 deletions(-) diff --git a/features/format_options.feature b/features/format_options.feature index 7efc1722a..090a482f1 100644 --- a/features/format_options.feature +++ b/features/format_options.feature @@ -145,6 +145,7 @@ Feature: Format options | ate | found | result | | 3 | 1 | 1 | | 0 | 4 | 8 | + I should have 8 apples Failed asserting that 7 matches expected 8. | 2 | 2 | 3 | @@ -227,6 +228,7 @@ Feature: Format options | ate | found | result | | 3 | 1 | 1 | | 0 | 4 | 8 | + I should have 8 apples Failed asserting that 7 matches expected 8. | 2 | 2 | 3 | @@ -309,6 +311,7 @@ Feature: Format options | ate | found | result | | 3 | 1 | 1 | | 0 | 4 | 8 | + I should have 8 apples Failed asserting that 7 matches expected 8. | 2 | 2 | 3 | @@ -456,6 +459,7 @@ Feature: Format options | ate | found | result | | 3 | 1 | 1 | | 0 | 4 | 8 | + I should have 8 apples Failed asserting that 7 matches expected 8. | 2 | 2 | 3 | diff --git a/features/i18n.feature b/features/i18n.feature index 1856d204f..7c9084b97 100644 --- a/features/i18n.feature +++ b/features/i18n.feature @@ -119,9 +119,11 @@ Feature: I18n Примеры: | значение | результат | | 5 | 16 | + Я должен иметь 16 Failed asserting that 15 matches expected 16. | 10 | 20 | | 23 | 32 | + Я должен иметь 32 Failed asserting that 33 matches expected 32. --- Проваленные сценарии: diff --git a/features/multiple_formats.feature b/features/multiple_formats.feature index b4063c667..e27bbfe38 100644 --- a/features/multiple_formats.feature +++ b/features/multiple_formats.feature @@ -145,6 +145,7 @@ Feature: Multiple formats | ate | found | result | | 3 | 1 | 1 | ...F | 0 | 4 | 8 | + I should have 8 apples Failed asserting that 7 matches expected 8. .... | 2 | 2 | 3 | @@ -238,6 +239,7 @@ Feature: Multiple formats | ate | found | result | | 3 | 1 | 1 | ...F | 0 | 4 | 8 | + I should have 8 apples Failed asserting that 7 matches expected 8. .... | 2 | 2 | 3 | @@ -374,6 +376,7 @@ Feature: Multiple formats | ate | found | result | | 3 | 1 | 1 | | 0 | 4 | 8 | + I should have 8 apples Failed asserting that 7 matches expected 8. | 2 | 2 | 3 | @@ -427,6 +430,7 @@ Feature: Multiple formats | ate | found | result | | 3 | 1 | 1 | | 0 | 4 | 8 | + I should have 8 apples Failed asserting that 7 matches expected 8. | 2 | 2 | 3 | @@ -551,6 +555,7 @@ Feature: Multiple formats | ate | found | result | | 3 | 1 | 1 | | 0 | 4 | 8 | + I should have 8 apples Failed asserting that 7 matches expected 8. | 2 | 2 | 3 | diff --git a/features/pretty_format.feature b/features/pretty_format.feature index 6f7a575ee..f01e9e625 100644 --- a/features/pretty_format.feature +++ b/features/pretty_format.feature @@ -116,9 +116,11 @@ Feature: Pretty Formatter Examples: | value | result | | 5 | 16 | + I must have 16 Failed asserting that 15 matches expected '16'. | 10 | 20 | | 23 | 32 | + I must have 32 Failed asserting that 33 matches expected '32'. --- Failed scenarios: diff --git a/src/Behat/Behat/Output/Node/Printer/Pretty/PrettyExampleRowPrinter.php b/src/Behat/Behat/Output/Node/Printer/Pretty/PrettyExampleRowPrinter.php index 109dd25d6..64411ce3f 100644 --- a/src/Behat/Behat/Output/Node/Printer/Pretty/PrettyExampleRowPrinter.php +++ b/src/Behat/Behat/Output/Node/Printer/Pretty/PrettyExampleRowPrinter.php @@ -17,6 +17,7 @@ use Behat\Behat\Tester\Result\StepResult; use Behat\Gherkin\Node\ExampleNode; use Behat\Gherkin\Node\OutlineNode; +use Behat\Gherkin\Node\StepNode; use Behat\Testwork\EventDispatcher\Event\AfterTested; use Behat\Testwork\Exception\ExceptionPresenter; use Behat\Testwork\Output\Formatter; @@ -124,7 +125,7 @@ private function printStepExceptionsAndStdOut(OutputPrinter $printer, array $eve { foreach ($events as $event) { $this->printStepStdOut($printer, $event->getTestResult()); - $this->printStepException($printer, $event->getTestResult()); + $this->printStepException($printer, $event->getStep(), $event->getTestResult()); } } @@ -132,9 +133,10 @@ private function printStepExceptionsAndStdOut(OutputPrinter $printer, array $eve * Prints step exception (if has one). * * @param OutputPrinter $printer + * @param StepNode $step * @param StepResult $result */ - private function printStepException(OutputPrinter $printer, StepResult $result) + private function printStepException(OutputPrinter $printer, StepNode $step, StepResult $result) { $style = $this->resultConverter->convertResultToString($result); @@ -142,6 +144,8 @@ private function printStepException(OutputPrinter $printer, StepResult $result) return; } + $printer->writeln(sprintf('{+%s}%s{-%s}', $style, $this->subIndent($step->getText()), $style)); + $text = $this->exceptionPresenter->presentException($result->getException()); $indentedText = implode("\n", array_map(array($this, 'subIndent'), explode("\n", $text))); $printer->writeln(sprintf('{+%s}%s{-%s}', $style, $indentedText, $style)); From cf3ee4112624cf1a848daf59fcab7a9d18e36639 Mon Sep 17 00:00:00 2001 From: David Grayston Date: Fri, 19 Jun 2020 00:40:20 +0100 Subject: [PATCH 325/567] Ensure event is instance of AfterStepTested before getting step text --- .../Printer/Pretty/PrettyExampleRowPrinter.php | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/src/Behat/Behat/Output/Node/Printer/Pretty/PrettyExampleRowPrinter.php b/src/Behat/Behat/Output/Node/Printer/Pretty/PrettyExampleRowPrinter.php index 64411ce3f..686684e1a 100644 --- a/src/Behat/Behat/Output/Node/Printer/Pretty/PrettyExampleRowPrinter.php +++ b/src/Behat/Behat/Output/Node/Printer/Pretty/PrettyExampleRowPrinter.php @@ -17,7 +17,6 @@ use Behat\Behat\Tester\Result\StepResult; use Behat\Gherkin\Node\ExampleNode; use Behat\Gherkin\Node\OutlineNode; -use Behat\Gherkin\Node\StepNode; use Behat\Testwork\EventDispatcher\Event\AfterTested; use Behat\Testwork\Exception\ExceptionPresenter; use Behat\Testwork\Output\Formatter; @@ -125,7 +124,7 @@ private function printStepExceptionsAndStdOut(OutputPrinter $printer, array $eve { foreach ($events as $event) { $this->printStepStdOut($printer, $event->getTestResult()); - $this->printStepException($printer, $event->getStep(), $event->getTestResult()); + $this->printStepException($printer, $event); } } @@ -133,18 +132,21 @@ private function printStepExceptionsAndStdOut(OutputPrinter $printer, array $eve * Prints step exception (if has one). * * @param OutputPrinter $printer - * @param StepNode $step - * @param StepResult $result + * @param AfterTested $event */ - private function printStepException(OutputPrinter $printer, StepNode $step, StepResult $result) + private function printStepException(OutputPrinter $printer, AfterTested $event) { + $result = $event->getTestResult(); + $style = $this->resultConverter->convertResultToString($result); if (!$result instanceof ExceptionResult || !$result->hasException()) { return; } - $printer->writeln(sprintf('{+%s}%s{-%s}', $style, $this->subIndent($step->getText()), $style)); + if ($event instanceof AfterStepTested) { + $printer->writeln(sprintf('{+%s}%s{-%s}', $style, $this->subIndent($event->getStep()->getText()), $style)); + } $text = $this->exceptionPresenter->presentException($result->getException()); $indentedText = implode("\n", array_map(array($this, 'subIndent'), explode("\n", $text))); From 28c21902916fb12283a957e531b558871e31f7a7 Mon Sep 17 00:00:00 2001 From: David Grayston Date: Fri, 19 Jun 2020 12:28:50 +0100 Subject: [PATCH 326/567] Prefix step text with keyword --- features/format_options.feature | 8 ++++---- features/i18n.feature | 4 ++-- features/multiple_formats.feature | 10 +++++----- features/pretty_format.feature | 4 ++-- .../Node/Printer/Pretty/PrettyExampleRowPrinter.php | 3 ++- 5 files changed, 15 insertions(+), 14 deletions(-) diff --git a/features/format_options.feature b/features/format_options.feature index 090a482f1..f02206d6b 100644 --- a/features/format_options.feature +++ b/features/format_options.feature @@ -145,7 +145,7 @@ Feature: Format options | ate | found | result | | 3 | 1 | 1 | | 0 | 4 | 8 | - I should have 8 apples + Then I should have 8 apples Failed asserting that 7 matches expected 8. | 2 | 2 | 3 | @@ -228,7 +228,7 @@ Feature: Format options | ate | found | result | | 3 | 1 | 1 | | 0 | 4 | 8 | - I should have 8 apples + Then I should have 8 apples Failed asserting that 7 matches expected 8. | 2 | 2 | 3 | @@ -311,7 +311,7 @@ Feature: Format options | ate | found | result | | 3 | 1 | 1 | | 0 | 4 | 8 | - I should have 8 apples + Then I should have 8 apples Failed asserting that 7 matches expected 8. | 2 | 2 | 3 | @@ -459,7 +459,7 @@ Feature: Format options | ate | found | result | | 3 | 1 | 1 | | 0 | 4 | 8 | - I should have 8 apples + Then I should have 8 apples Failed asserting that 7 matches expected 8. | 2 | 2 | 3 | diff --git a/features/i18n.feature b/features/i18n.feature index 7c9084b97..8c53f1804 100644 --- a/features/i18n.feature +++ b/features/i18n.feature @@ -119,11 +119,11 @@ Feature: I18n Примеры: | значение | результат | | 5 | 16 | - Я должен иметь 16 + То Я должен иметь 16 Failed asserting that 15 matches expected 16. | 10 | 20 | | 23 | 32 | - Я должен иметь 32 + То Я должен иметь 32 Failed asserting that 33 matches expected 32. --- Проваленные сценарии: diff --git a/features/multiple_formats.feature b/features/multiple_formats.feature index e27bbfe38..849d7b473 100644 --- a/features/multiple_formats.feature +++ b/features/multiple_formats.feature @@ -145,7 +145,7 @@ Feature: Multiple formats | ate | found | result | | 3 | 1 | 1 | ...F | 0 | 4 | 8 | - I should have 8 apples + Then I should have 8 apples Failed asserting that 7 matches expected 8. .... | 2 | 2 | 3 | @@ -239,7 +239,7 @@ Feature: Multiple formats | ate | found | result | | 3 | 1 | 1 | ...F | 0 | 4 | 8 | - I should have 8 apples + Then I should have 8 apples Failed asserting that 7 matches expected 8. .... | 2 | 2 | 3 | @@ -376,7 +376,7 @@ Feature: Multiple formats | ate | found | result | | 3 | 1 | 1 | | 0 | 4 | 8 | - I should have 8 apples + Then I should have 8 apples Failed asserting that 7 matches expected 8. | 2 | 2 | 3 | @@ -430,7 +430,7 @@ Feature: Multiple formats | ate | found | result | | 3 | 1 | 1 | | 0 | 4 | 8 | - I should have 8 apples + Then I should have 8 apples Failed asserting that 7 matches expected 8. | 2 | 2 | 3 | @@ -555,7 +555,7 @@ Feature: Multiple formats | ate | found | result | | 3 | 1 | 1 | | 0 | 4 | 8 | - I should have 8 apples + Then I should have 8 apples Failed asserting that 7 matches expected 8. | 2 | 2 | 3 | diff --git a/features/pretty_format.feature b/features/pretty_format.feature index f01e9e625..86f024dce 100644 --- a/features/pretty_format.feature +++ b/features/pretty_format.feature @@ -116,11 +116,11 @@ Feature: Pretty Formatter Examples: | value | result | | 5 | 16 | - I must have 16 + Then I must have 16 Failed asserting that 15 matches expected '16'. | 10 | 20 | | 23 | 32 | - I must have 32 + Then I must have 32 Failed asserting that 33 matches expected '32'. --- Failed scenarios: diff --git a/src/Behat/Behat/Output/Node/Printer/Pretty/PrettyExampleRowPrinter.php b/src/Behat/Behat/Output/Node/Printer/Pretty/PrettyExampleRowPrinter.php index 686684e1a..56c34391d 100644 --- a/src/Behat/Behat/Output/Node/Printer/Pretty/PrettyExampleRowPrinter.php +++ b/src/Behat/Behat/Output/Node/Printer/Pretty/PrettyExampleRowPrinter.php @@ -145,7 +145,8 @@ private function printStepException(OutputPrinter $printer, AfterTested $event) } if ($event instanceof AfterStepTested) { - $printer->writeln(sprintf('{+%s}%s{-%s}', $style, $this->subIndent($event->getStep()->getText()), $style)); + $step = $event->getStep(); + $printer->writeln(sprintf('{+%s}%s%s %s{-%s}', $style, $this->subIndentText, $step->getKeyword(), $step->getText(), $style)); } $text = $this->exceptionPresenter->presentException($result->getException()); From 8fa9f6006ad909b460ba0a1283dcd5cd3d2fc5a4 Mon Sep 17 00:00:00 2001 From: David Grayston Date: Sat, 3 Oct 2020 01:25:53 +0100 Subject: [PATCH 327/567] Prefix failing step with translated title --- features/format_options.feature | 8 ++++---- features/i18n.feature | 4 ++-- features/multiple_formats.feature | 10 +++++----- features/pretty_format.feature | 4 ++-- i18n.php | 17 +++++++++++++++++ .../Printer/Pretty/PrettyExampleRowPrinter.php | 10 +++++++++- .../Formatter/PrettyFormatterFactory.php | 3 ++- 7 files changed, 41 insertions(+), 15 deletions(-) diff --git a/features/format_options.feature b/features/format_options.feature index f02206d6b..c0ae5598a 100644 --- a/features/format_options.feature +++ b/features/format_options.feature @@ -145,7 +145,7 @@ Feature: Format options | ate | found | result | | 3 | 1 | 1 | | 0 | 4 | 8 | - Then I should have 8 apples + Failed step: Then I should have 8 apples Failed asserting that 7 matches expected 8. | 2 | 2 | 3 | @@ -228,7 +228,7 @@ Feature: Format options | ate | found | result | | 3 | 1 | 1 | | 0 | 4 | 8 | - Then I should have 8 apples + Failed step: Then I should have 8 apples Failed asserting that 7 matches expected 8. | 2 | 2 | 3 | @@ -311,7 +311,7 @@ Feature: Format options | ate | found | result | | 3 | 1 | 1 | | 0 | 4 | 8 | - Then I should have 8 apples + Failed step: Then I should have 8 apples Failed asserting that 7 matches expected 8. | 2 | 2 | 3 | @@ -459,7 +459,7 @@ Feature: Format options | ate | found | result | | 3 | 1 | 1 | | 0 | 4 | 8 | - Then I should have 8 apples + Failed step: Then I should have 8 apples Failed asserting that 7 matches expected 8. | 2 | 2 | 3 | diff --git a/features/i18n.feature b/features/i18n.feature index 8c53f1804..1d376dffe 100644 --- a/features/i18n.feature +++ b/features/i18n.feature @@ -119,11 +119,11 @@ Feature: I18n Примеры: | значение | результат | | 5 | 16 | - То Я должен иметь 16 + Проваленные шаг: То Я должен иметь 16 Failed asserting that 15 matches expected 16. | 10 | 20 | | 23 | 32 | - То Я должен иметь 32 + Проваленные шаг: То Я должен иметь 32 Failed asserting that 33 matches expected 32. --- Проваленные сценарии: diff --git a/features/multiple_formats.feature b/features/multiple_formats.feature index 849d7b473..e0087a126 100644 --- a/features/multiple_formats.feature +++ b/features/multiple_formats.feature @@ -145,7 +145,7 @@ Feature: Multiple formats | ate | found | result | | 3 | 1 | 1 | ...F | 0 | 4 | 8 | - Then I should have 8 apples + Failed step: Then I should have 8 apples Failed asserting that 7 matches expected 8. .... | 2 | 2 | 3 | @@ -239,7 +239,7 @@ Feature: Multiple formats | ate | found | result | | 3 | 1 | 1 | ...F | 0 | 4 | 8 | - Then I should have 8 apples + Failed step: Then I should have 8 apples Failed asserting that 7 matches expected 8. .... | 2 | 2 | 3 | @@ -376,7 +376,7 @@ Feature: Multiple formats | ate | found | result | | 3 | 1 | 1 | | 0 | 4 | 8 | - Then I should have 8 apples + Failed step: Then I should have 8 apples Failed asserting that 7 matches expected 8. | 2 | 2 | 3 | @@ -430,7 +430,7 @@ Feature: Multiple formats | ate | found | result | | 3 | 1 | 1 | | 0 | 4 | 8 | - Then I should have 8 apples + Failed step: Then I should have 8 apples Failed asserting that 7 matches expected 8. | 2 | 2 | 3 | @@ -555,7 +555,7 @@ Feature: Multiple formats | ate | found | result | | 3 | 1 | 1 | | 0 | 4 | 8 | - Then I should have 8 apples + Failed step: Then I should have 8 apples Failed asserting that 7 matches expected 8. | 2 | 2 | 3 | diff --git a/features/pretty_format.feature b/features/pretty_format.feature index 86f024dce..0a737a2c4 100644 --- a/features/pretty_format.feature +++ b/features/pretty_format.feature @@ -116,11 +116,11 @@ Feature: Pretty Formatter Examples: | value | result | | 5 | 16 | - Then I must have 16 + Failed step: Then I must have 16 Failed asserting that 15 matches expected '16'. | 10 | 20 | | 23 | 32 | - Then I must have 32 + Failed step: Then I must have 32 Failed asserting that 33 matches expected '32'. --- Failed scenarios: diff --git a/i18n.php b/i18n.php index 8737b26fc..29357df1a 100644 --- a/i18n.php +++ b/i18n.php @@ -7,6 +7,7 @@ 'failed_scenarios_title' => 'Failed scenarios:', 'failed_hooks_title' => 'Failed hooks:', 'failed_steps_title' => 'Failed steps:', + 'failed_step_title' => 'Failed step:', 'pending_steps_title' => 'Pending steps:', 'scenarios_count' => '{0} No scenarios|{1} 1 scenario|]1,Inf] %count% scenarios', 'steps_count' => '{0} No steps|{1} 1 step|]1,Inf] %count% steps', @@ -24,6 +25,7 @@ 'failed_scenarios_title' => 'Провалени сценарии:', 'failed_hooks_title' => 'Провалени хукове:', 'failed_steps_title' => 'Провалени стъпки:', + 'failed_step_title' => 'Провалени стъпка:', 'pending_steps_title' => 'Изчакващи стъпки:', 'scenarios_count' => '{0} Няма сценарий|{1} 1 сценарий|]1,Inf] %count% сценарии', 'steps_count' => '{0} Няма стъпки|{1} 1 стъпка|]1,Inf] %count% стъпки', @@ -39,6 +41,7 @@ 'failed_scenarios_title' => 'Chybné scénáře:', 'failed_hooks_title' => 'Chybné hooky:', 'failed_steps_title' => 'Chybné kroky:', + 'failed_step_title' => 'Chybné krok:', 'pending_steps_title' => 'Čekající kroky:', 'scenarios_count' => '{0} Žádný scénář|{1} 1 scénář|{2,3,4} %count% scénáře|]4,Inf] %count% scénářů', 'steps_count' => '{0} Žádné kroky|{1} 1 krok|{2,3,4} %count% kroky|]4,Inf] %count% kroků', @@ -54,6 +57,7 @@ 'failed_scenarios_title' => 'Fehlgeschlagene Szenarien:', 'failed_hooks_title' => 'Fehlgeschlagene Hooks:', 'failed_steps_title' => 'Fehlgeschlagene Schritte:', + 'failed_step_title' => 'Fehlgeschlagene Schritt:', 'pending_steps_title' => 'Ausstehende Schritte:', 'scenarios_count' => '{0} Kein Szenario|{1} 1 Szenario|]1,Inf] %count% Szenarien', 'steps_count' => '{0} Kein Schritt|{1} 1 Schritt|]1,Inf] %count% Schritte', @@ -69,6 +73,7 @@ 'failed_scenarios_title' => 'Escenarios fallidos:', 'failed_hooks_title' => 'Hooks fallidos:', 'failed_steps_title' => 'Pasos fallidos:', + 'failed_step_title' => 'Paso fallidos:', 'pending_steps_title' => 'Pasos pendientes:', 'scenarios_count' => '{0} Ningún escenario|{1} 1 escenario|]1,Inf] %count% escenarios', 'steps_count' => '{0} Ningún paso|{1} 1 paso|]1,Inf] %count% pasos', @@ -84,6 +89,7 @@ 'failed_scenarios_title' => 'Scénarios échoués:', 'failed_hooks_title' => 'Hooks échoués:', 'failed_steps_title' => 'Etapes échouées:', + 'failed_step_title' => 'Etape échouées:', 'pending_steps_title' => 'Etapes en attente:', 'scenarios_count' => '{0} Pas de scénario|{1} 1 scénario|]1,Inf] %count% scénarios', 'steps_count' => '{0} Pas d\'étape|{1} 1 étape|]1,Inf] %count% étapes', @@ -101,6 +107,7 @@ 'failed_scenarios_title' => 'Sikertelen forgatókönyvek:', 'failed_hooks_title' => 'Sikertelen kampók:', 'failed_steps_title' => 'Sikertelen lépések:', + 'failed_step_title' => 'Sikertelen lépés:', 'pending_steps_title' => 'Elintézendő lépések:', 'scenarios_count' => '{0} Nem volt forgatókönyv|{1} 1 forgatókönyv|]1,Inf] %count% forgatókönyv', 'steps_count' => '{0} Nem volt lépés|{1} 1 lépés|]1,Inf] %count% lépés', @@ -116,6 +123,7 @@ 'failed_scenarios_title' => 'Scenari falliti:', 'failed_hooks_title' => 'Hook falliti:', 'failed_steps_title' => 'Passaggi falliti:', + 'failed_step_title' => 'Passaggio fallito:', 'pending_steps_title' => 'Passaggi in sospeso:', 'scenarios_count' => '{0} Nessuno scenario|{1} 1 scenario|]1,Inf] %count% scenari', 'steps_count' => '{0} Nessun passaggio|{1} 1 passaggio|]1,Inf] %count% passaggi', @@ -132,6 +140,7 @@ 'failed_scenarios_title' => '失敗した シナリオ:', 'failed_hooks_title' => '失敗した フック:', 'failed_steps_title' => '失敗した ステップ:', + 'failed_step_title' => '失敗した ステップ:', 'pending_steps_title' => '保留中のステップ:', 'scenarios_count' => '{0} No scenarios|{1} 1 個のシナリオ|]1,Inf] %count% 個のシナリオ', 'steps_count' => '{0} ステップがありません|{1} 1 個のステップ|]1,Inf] %count% 個のステップ', @@ -148,6 +157,7 @@ 'failed_scenarios_title' => '실패한 시나리오:', 'failed_hooks_title' => '실패한 훅 연결:', 'failed_steps_title' => '실패한 단계:', + 'failed_step_title' => '실패한 단계:', 'pending_steps_title' => '준비중인 단계:', 'scenarios_count' => '{0} 없는 시나리오들|{1} 1 시나리오|]1,Inf] %count% 시나리오들', 'steps_count' => '{0} 없는 단계들|{1} 1 단계|]1,Inf] %count% 단계들', @@ -163,6 +173,7 @@ 'failed_scenarios_title' => 'Gefaalde scenario\'s:', 'failed_hooks_title' => 'Gefaalde hooks:', 'failed_steps_title' => 'Gefaalde stappen:', + 'failed_step_title' => 'Gefaalde stap:', 'pending_steps_title' => 'Onafgewerkte stappen:', 'scenarios_count' => '{0} Geen scenario\'s|{1} 1 scenario|]1,Inf] %count% scenario\'s', 'steps_count' => '{0} Geen stappen|{1} 1 stap|]1,Inf] %count% stappen', @@ -178,6 +189,7 @@ 'failed_scenarios_title' => 'Feilende scenarier:', 'failed_hooks_title' => 'Feilende hooks:', 'failed_steps_title' => 'Feilende steg:', + 'failed_step_title' => 'Feilende steg:', 'pending_steps_title' => 'Ikke implementerte steg:', 'scenarios_count' => '{0} Ingen scenarier|{1} 1 scenario|]1,Inf] %count% scenarier', 'steps_count' => '{0} Ingen steg|{1} 1 steg|]1,Inf] %count% steg', @@ -193,6 +205,7 @@ 'failed_scenarios_title' => 'Nieudane scenariusze:', 'failed_hooks_title' => 'Nieudane hooki:', 'failed_steps_title' => 'Nieudane kroki', + 'failed_step_title' => 'Nieudane krok:', 'pending_steps_title' => 'Oczekujące kroki', 'scenarios_count' => '{0} Brak scenariuszy|{1} 1 scenariusz|{2,3,4,22,23,24,32,33,34,42,43,44} %count% scenariusze|]4,Inf] %count% scenariuszy', 'steps_count' => '{0} Brak kroków|{1} 1 krok|{2,3,4,22,23,24,32,33,34,42,43,44} %count% kroki|]4,Inf] %count% kroków', @@ -208,6 +221,7 @@ 'failed_scenarios_title' => 'Cenários que falharam:', 'failed_hooks_title' => 'Hooks que falharam:', 'failed_steps_title' => 'Definições que falharam:', + 'failed_step_title' => 'Definição que falhou:', 'pending_steps_title' => 'Definições por definir:', 'scenarios_count' => '{0} Nenhum cenário|{1} 1 cenário|]1,Inf] %count% cenários', 'steps_count' => '{0} Nenhuma definição|{1} 1 definição|]1,Inf] %count% definições', @@ -223,6 +237,7 @@ 'failed_scenarios_title' => 'Cenários falhados:', 'failed_hooks_title' => 'Hooks falhados:', 'failed_steps_title' => 'Etapas falhadas:', + 'failed_step_title' => 'Etapa com falha:', 'pending_steps_title' => 'Etapas pendentes:', 'scenarios_count' => '{0} Nenhum cenário|{1} 1 cenário|]1,Inf] %count% cenários', 'steps_count' => '{0} Nenhuma etapa|{1} 1 etapa|]1,Inf] %count% etapas', @@ -239,6 +254,7 @@ 'failed_scenarios_title' => 'Scenarii eșuate:', 'failed_hooks_title' => 'Hook-uri eșuate:', 'failed_steps_title' => 'Pași esuați:', + 'failed_step_title' => 'Paș esuaț:', 'pending_steps_title' => 'Pași in așteptare:', 'scenarios_count' => '{0} Niciun scenariu|{1} 1 scenariu|]1,Inf] %count% scenarii', 'steps_count' => '{0} Niciun pas|{1} 1 pas|]1,Inf] %count% pasi', @@ -255,6 +271,7 @@ 'failed_scenarios_title' => 'Проваленные сценарии:', 'failed_hooks_title' => 'Проваленные хуки:', 'failed_steps_title' => 'Проваленные шаги:', + 'failed_step_title' => 'Проваленные шаг:', 'pending_steps_title' => 'Шаги в ожидании:', 'scenarios_count' => '{0} Нет сценариев|{1,21,31} %count% сценарий|{2,3,4,22,23,24} %count% сценария|]4,Inf] %count% сценариев', 'steps_count' => '{0} Нет шагов|{1,21,31} %count% шаг|{2,3,4,22,23,24} %count% шага|]4,Inf] %count% шагов', diff --git a/src/Behat/Behat/Output/Node/Printer/Pretty/PrettyExampleRowPrinter.php b/src/Behat/Behat/Output/Node/Printer/Pretty/PrettyExampleRowPrinter.php index 56c34391d..2713fc098 100644 --- a/src/Behat/Behat/Output/Node/Printer/Pretty/PrettyExampleRowPrinter.php +++ b/src/Behat/Behat/Output/Node/Printer/Pretty/PrettyExampleRowPrinter.php @@ -10,6 +10,7 @@ namespace Behat\Behat\Output\Node\Printer\Pretty; +use Behat\Behat\Definition\Translator\TranslatorInterface; use Behat\Behat\EventDispatcher\Event\AfterStepTested; use Behat\Behat\Output\Node\Printer\ExampleRowPrinter; use Behat\Behat\Output\Node\Printer\Helper\ResultToStringConverter; @@ -47,6 +48,10 @@ final class PrettyExampleRowPrinter implements ExampleRowPrinter * @var string */ private $subIndentText; + /** + * @var TranslatorInterface + */ + private $translator; /** * Initializes printer. @@ -59,11 +64,13 @@ final class PrettyExampleRowPrinter implements ExampleRowPrinter public function __construct( ResultToStringConverter $resultConverter, ExceptionPresenter $exceptionPresenter, + TranslatorInterface $translator, $indentation = 6, $subIndentation = 2 ) { $this->resultConverter = $resultConverter; $this->exceptionPresenter = $exceptionPresenter; + $this->translator = $translator; $this->indentText = str_repeat(' ', intval($indentation)); $this->subIndentText = $this->indentText . str_repeat(' ', intval($subIndentation)); } @@ -145,8 +152,9 @@ private function printStepException(OutputPrinter $printer, AfterTested $event) } if ($event instanceof AfterStepTested) { + $title = $this->translator->trans('failed_step_title', [], 'output'); $step = $event->getStep(); - $printer->writeln(sprintf('{+%s}%s%s %s{-%s}', $style, $this->subIndentText, $step->getKeyword(), $step->getText(), $style)); + $printer->writeln(sprintf('{+%s}%s%s %s %s{-%s}', $style, $this->subIndentText, $title, $step->getKeyword(), $step->getText(), $style)); } $text = $this->exceptionPresenter->presentException($result->getException()); diff --git a/src/Behat/Behat/Output/ServiceContainer/Formatter/PrettyFormatterFactory.php b/src/Behat/Behat/Output/ServiceContainer/Formatter/PrettyFormatterFactory.php index b2d266025..b737ef289 100644 --- a/src/Behat/Behat/Output/ServiceContainer/Formatter/PrettyFormatterFactory.php +++ b/src/Behat/Behat/Output/ServiceContainer/Formatter/PrettyFormatterFactory.php @@ -257,7 +257,8 @@ protected function loadTableOutlinePrinter(ContainerBuilder $container) $definition = new Definition('Behat\Behat\Output\Node\Printer\Pretty\PrettyExampleRowPrinter', array( new Reference(self::RESULT_TO_STRING_CONVERTER_ID), - new Reference(ExceptionExtension::PRESENTER_ID) + new Reference(ExceptionExtension::PRESENTER_ID), + new Reference(TranslatorExtension::TRANSLATOR_ID) )); $container->setDefinition('output.node.printer.pretty.example_row', $definition); } From cfd92cefdb5bf8bd58b9b9ee8d2b83d449b60c83 Mon Sep 17 00:00:00 2001 From: Donald Tyler Date: Wed, 6 Jul 2022 10:37:38 -0500 Subject: [PATCH 328/567] Fix CI fails because symfony/flex is blocked # Problem: When running the workflow, it fails at the "Install symfony/flex" step with the following error: Error: symfony/flex contains a Composer plugin which is blocked by your allow-plugins config. You may add it to the list if you consider it safe. ## Cause: A newer version of Composer has introduced a strict check whereby all plugins have to be explicitly allowed for security reasons. ## Fix: Explicitly allow the global plugin before installing it. --- .github/workflows/build.yml | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 7f900751b..d321b7165 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -61,7 +61,9 @@ jobs: run: composer config minimum-stability ${{ matrix.stability }} - name: Install symfony/flex - run: composer global require symfony/flex + run: | + composer config --global --no-plugins allow-plugins.symfony/flex true && + composer global require symfony/flex - name: Uninstall Psalm run: composer remove --dev --no-update vimeo/psalm From 481a7aa448560a6a6f2c94f41483aab96c1487d5 Mon Sep 17 00:00:00 2001 From: Ciaran McNulty Date: Thu, 7 Jul 2022 10:21:25 +0100 Subject: [PATCH 329/567] 3.11.0 release --- CHANGELOG.md | 17 ++++++++++++++++- src/Behat/Behat/ApplicationFactory.php | 2 +- 2 files changed, 17 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 167b643e1..338e4d47d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,21 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](http://keepachangelog.com/) and this project adheres to [Semantic Versioning](http://semver.org/). +## [3.11.0] - 2022-07-07 + +### Added +* [#1387](https://github.com/Behat/Behat/pull/1387) Added file attribute to Junit output [@ppaulis](https://github.com/ppaulis) +* [#1266](https://github.com/Behat/Behat/pull/1266) Enable env placeholder resolution in config [@mpdude](https://github.com/mpdude) +* [#1380](https://github.com/Behat/Behat/pull/1380) Support psr/container 2.0 [@wouterj](https://github.com/wouterj) +* [#1340](https://github.com/Behat/Behat/pull/1340) Added Chinese language [@54853315](https://github.com/54853315) + +### Fixed +* [#1374](https://github.com/Behat/Behat/pull/1374) Fixed counts in hu translations [@Sweetchuck](https://github.com/Sweetchuck) +* [#1393](https://github.com/Behat/Behat/pull/1393) Fixed counts in bg and jo translations [@delyro](https://github.com/delyro) + +### Other contributions +* [#1398](https://github.com/Behat/Behat/pull/1398) Fix failing builds due to composer --allow-plugins [@Chekote](https://github.com/Chekote) + ## 3.10.0 - 2021-11-02 ## What's Changed @@ -983,7 +998,7 @@ and this project adheres to [Semantic Versioning](http://semver.org/). ### Changed * Initial release -[Unreleased]: https://github.com/Behat/Behat/compare/v3.9.0...master +[3.11.0]: https://github.com/Behat/Behat/compare/v3.10.0...v3.11.0 [3.9.0]: https://github.com/Behat/Behat/compare/v3.8.1...v3.9.0 [3.8.1]: https://github.com/Behat/Behat/compare/v3.8.0...v3.8.1 [3.8.0]: https://github.com/Behat/Behat/compare/v3.7.0...v3.8.0 diff --git a/src/Behat/Behat/ApplicationFactory.php b/src/Behat/Behat/ApplicationFactory.php index df699077e..9c4e45055 100644 --- a/src/Behat/Behat/ApplicationFactory.php +++ b/src/Behat/Behat/ApplicationFactory.php @@ -46,7 +46,7 @@ */ final class ApplicationFactory extends BaseFactory { - public const VERSION = '3.8.1'; + public const VERSION = '3.11.0'; /** * {@inheritdoc} From ad81f8844c7c1f642422bf01a44a36cee7a6780a Mon Sep 17 00:00:00 2001 From: Ciaran McNulty Date: Thu, 7 Jul 2022 12:21:31 +0100 Subject: [PATCH 330/567] Don't always install symfony/flex / add separate symfony LTS jobs --- .github/workflows/build.yml | 79 ++++++++++++++++++++++--------------- 1 file changed, 47 insertions(+), 32 deletions(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index d321b7165..cc771ebae 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -18,33 +18,49 @@ jobs: strategy: fail-fast: false matrix: + php: [7.2, 7.3, 7.4, 8.0, 8.1] + os: [ubuntu-latest] + composer-mode: [update] + symfony-version: [''] include: + # Get the existing 7.2 to publish the phar - php: 7.2 - publish-phar: true os: ubuntu-latest + composer-mode: update + publish-phar: true + symfony-version: '' + + # 7.2 build with lowest dependencies - php: 7.2 - composer-flags: --prefer-lowest - os: ubuntu-latest - - php: 7.3 - os: ubuntu-latest - - php: 7.4 - os: ubuntu-latest - - php: 7.4 - SYMFONY_REQUIRE: 4.4.* - os: ubuntu-latest - - php: 8.0 - os: ubuntu-latest - - php: 8.0 - stability: dev - SYMFONY_REQUIRE: 6.0.* os: ubuntu-latest + composer-mode: lowest + symfony-version: '' + + # MacOS on latest PHP only - php: 8.1 os: macos-latest + composer-mode: update + symfony-version: '' + + # Windows on latest PHP only - php: 8.1 os: windows-latest + composer-mode: update + symfony-version: '' + + # Symfony jobs: - php: 8.1 os: ubuntu-latest - + composer-mode: update + symfony-version: '4.4' + - php: 8.1 + os: ubuntu-latest + composer-mode: update + symfony-version: '5.4' + - php: 8.1 + os: ubuntu-latest + composer-mode: update + symfony-version: '6.0' steps: - uses: actions/checkout@v2 @@ -56,22 +72,21 @@ jobs: ini-values: "phar.readonly=0,zend.exception_ignore_args=Off" coverage: none - - name: Configure Composer minimum stability - if: matrix.stability - run: composer config minimum-stability ${{ matrix.stability }} - - name: Install symfony/flex + if: matrix.symfony-version != '' run: | composer config --global --no-plugins allow-plugins.symfony/flex true && composer global require symfony/flex - - name: Uninstall Psalm - run: composer remove --dev --no-update vimeo/psalm - - - name: Install dependencies + - name: Install latest dependencies + if: matrix.composer-mode == 'update' env: - SYMFONY_REQUIRE: "${{ matrix.SYMFONY_REQUIRE }}" - run: composer update ${{ matrix.composer-flags }} + SYMFONY_REQUIRE: ${{ matrix.symfony-version }}.* + run: composer update + + - name: Install lowest dependencies + if: matrix.composer-mode == 'lowest' + run: composer update --prefer-lowest - name: Run tests (phpunit) run: ./vendor/bin/phpunit @@ -84,7 +99,7 @@ jobs: run: ./bin/behat -fprogress --strict --tags=@php8 - name: Build the PHAR - if: matrix.php != '8.0' + if: matrix.publish-phar == true run: | curl -LSs https://box-project.github.io/box2/installer.php | php && export PATH=.:$PATH && @@ -94,14 +109,14 @@ jobs: - uses: actions/upload-artifact@v1 name: Publish the PHAR - if: matrix.publish-phar + if: matrix.publish-phar == true with: name: behat.phar path: behat.phar - psalm: + static-analysis: runs-on: ubuntu-latest - name: Psalm (PHP 8.0) + name: Static analysis steps: - uses: actions/checkout@v2 @@ -109,7 +124,7 @@ jobs: uses: shivammathur/setup-php@v2 with: php-version: 8.0 - ini-values: "phar.readonly=0,zend.exception_ignore_args=Off" + ini-values: "zend.exception_ignore_args=Off" coverage: none - name: Install dependencies @@ -120,7 +135,7 @@ jobs: publish-phar: runs-on: ubuntu-latest - name: Publish the PHAR + name: Publish the PHAR for release needs: tests if: github.event_name == 'release' steps: From c6af896895475ca3bd9c00131eb563b5d78ace32 Mon Sep 17 00:00:00 2001 From: Ciaran McNulty Date: Thu, 7 Jul 2022 15:09:04 +0100 Subject: [PATCH 331/567] Remove Scrutiniser and Appveyor badges (#1402) --- README.md | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/README.md b/README.md index a666ce704..0f118b5b5 100644 --- a/README.md +++ b/README.md @@ -4,9 +4,7 @@ Behat is a BDD framework for PHP to help you test business expectations. [![Gitter chat](https://badges.gitter.im/Behat/Behat.svg)](https://gitter.im/Behat/Behat) [![License](https://poser.pugx.org/behat/behat/license.svg)](https://packagist.org/packages/behat/behat) -[![Unix Status](https://github.com/Behat/Behat/workflows/Build/badge.svg)](https://github.com/Behat/Behat/actions?query=workflow%3ABuild) -[![Windows status](https://ci.appveyor.com/api/projects/status/9uc5sellmvbv02ei/branch/master?svg=true)](https://ci.appveyor.com/project/everzet/behat/branch/master) -[![Scrutinizer Quality Score](https://scrutinizer-ci.com/g/Behat/Behat/badges/quality-score.png?s=ad84e95fc2405712f88a96d89b4f31dfe5c80fae)](https://scrutinizer-ci.com/g/Behat/Behat/) +[![Build Status](https://github.com/Behat/Behat/workflows/Build/badge.svg)](https://github.com/Behat/Behat/actions?query=workflow%3ABuild) Installing Behat ---------------- From 79f7e0408060c8c4e9a1dcfc41837bff96920c86 Mon Sep 17 00:00:00 2001 From: Alberto Ortega Date: Tue, 23 Aug 2022 14:42:02 +0200 Subject: [PATCH 332/567] Replace with an empty string if null which is deprecated PHP8.1 --- src/Behat/Testwork/Output/Printer/JUnitOutputPrinter.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Behat/Testwork/Output/Printer/JUnitOutputPrinter.php b/src/Behat/Testwork/Output/Printer/JUnitOutputPrinter.php index f415b96a1..ce1371c93 100644 --- a/src/Behat/Testwork/Output/Printer/JUnitOutputPrinter.php +++ b/src/Behat/Testwork/Output/Printer/JUnitOutputPrinter.php @@ -115,7 +115,7 @@ public function addTestcaseChild($nodeName, array $nodeAttributes = array(), $no private function addAttributesToNode(\DOMElement $node, array $attributes) { foreach ($attributes as $name => $value){ - $node->setAttribute($name, $value); + $node->setAttribute($name, $value ?? ''); } } From 728e446296ea9f651eccc9c825c487c5f36edd8f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gildas=20Qu=C3=A9m=C3=A9ner?= Date: Sat, 3 Sep 2022 22:58:53 +0200 Subject: [PATCH 333/567] Fix dynamic property deprecation notices --- features/autowire.feature | 2 +- features/definitions_transformations.feature | 8 +++++++- features/error_reporting.feature | 9 ++++++--- features/hooks.feature | 1 + 4 files changed, 15 insertions(+), 5 deletions(-) diff --git a/features/autowire.feature b/features/autowire.feature index a69266b94..4e221bfe9 100644 --- a/features/autowire.feature +++ b/features/autowire.feature @@ -28,7 +28,7 @@ Feature: Helper services autowire value); @@ -434,6 +436,7 @@ Feature: Step Arguments Transformations """ name = $name; } static public function named($name) { return new static($name); } } @@ -501,13 +504,14 @@ Feature: Step Arguments Transformations """ name = $name; } static public function named($name) { return new static($name); } } class FeatureContext implements Behat\Behat\Context\Context { private $I; - private $he; + private $she; /** @Transform */ public function userFromName($name) : User { @@ -654,6 +658,8 @@ Feature: Step Arguments Transformations } class FeatureContext implements Behat\Behat\Context\Context { + private $I; + /** @Transform */ public function userFromName($name) : User|int { diff --git a/features/error_reporting.feature b/features/error_reporting.feature index 945dabd78..d9fb305c2 100644 --- a/features/error_reporting.feature +++ b/features/error_reporting.feature @@ -15,6 +15,9 @@ Feature: Error Reporting class FeatureContext implements Context { + private $array; + private $result; + /** * @Given /^I have an empty array$/ */ @@ -105,7 +108,7 @@ Feature: Error Reporting 001 Scenario: Access undefined index # features/e_notice_in_scenario.feature:9 When I access array index 0 # features/e_notice_in_scenario.feature:10 - Notice: Undefined offset: 0 in features/bootstrap/FeatureContext.php line 24 + Notice: Undefined offset: 0 in features/bootstrap/FeatureContext.php line 27 2 scenarios (1 passed, 1 failed) 7 steps (5 passed, 1 failed, 1 skipped) @@ -130,7 +133,7 @@ Feature: Error Reporting 001 Scenario: Exception thrown # features/exception_in_scenario.feature:6 When an exception is thrown # features/exception_in_scenario.feature:7 - Exception: Exception is thrown in features/bootstrap/FeatureContext.php:56 + Exception: Exception is thrown in features/bootstrap/FeatureContext.php:59 Stack trace: 1 scenario (1 failed) @@ -146,7 +149,7 @@ Feature: Error Reporting 001 Scenario: Exception thrown # features/exception_in_scenario.feature:6 When an exception is thrown # features/exception_in_scenario.feature:7 - Exception: Exception is thrown in features/bootstrap/FeatureContext.php:56 + Exception: Exception is thrown in features/bootstrap/FeatureContext.php:59 Stack trace: #0 src/Behat/Testwork/Call/Handler/RuntimeCallHandler.php(110): FeatureContext->anExceptionIsThrown() #1 src/Behat/Testwork/Call/Handler/RuntimeCallHandler.php(64): Behat\Testwork\Call\Handler\RuntimeCallHandler->executeCall( diff --git a/features/hooks.feature b/features/hooks.feature index e4ed416ff..fbe94dd92 100644 --- a/features/hooks.feature +++ b/features/hooks.feature @@ -24,6 +24,7 @@ Feature: hooks class FeatureContext implements Context { private $number; + private $scenarioFilter; /** * @BeforeFeature From b545d036688e856b1f3e9320622b74c0100aeabe Mon Sep 17 00:00:00 2001 From: Vincent Amstoutz <46444652+vinceAmstoutz@users.noreply.github.com> Date: Wed, 9 Nov 2022 16:45:47 +0100 Subject: [PATCH 334/567] From Symfony 2 to Symfony --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 0f118b5b5..cbe269118 100644 --- a/README.md +++ b/README.md @@ -51,7 +51,7 @@ you would not have any backwards compatibility issues with Behat up until `v4.0. is released. Exception could be an extremely rare case where BC break is introduced as a measure to fix a serious issue. -You can read detailed guidance on what BC means in [Symfony2 BC guide](http://symfony.com/doc/current/contributing/code/bc.html). +You can read detailed guidance on what BC means in [Symfony BC guide](http://symfony.com/doc/current/contributing/code/bc.html). Useful Links ------------ From 4b302f3e74166b30483e25e9582cec1c7509c79a Mon Sep 17 00:00:00 2001 From: Ciaran McNulty Date: Tue, 29 Nov 2022 12:58:50 +0000 Subject: [PATCH 335/567] Add prophecy dependency --- composer.json | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/composer.json b/composer.json index 072816bd9..333713bf4 100644 --- a/composer.json +++ b/composer.json @@ -31,7 +31,8 @@ "symfony/process": "^4.4 || ^5.0 || ^6.0", "phpunit/phpunit": "^8.5 || ^9.0", "herrera-io/box": "~1.6.1", - "vimeo/psalm": "^4.8" + "vimeo/psalm": "^4.8", + "phpspec/prophecy": "^1.15" }, "suggest": { From 0389e0eda84d9f693779c0ecb4c2680bb950fb5e Mon Sep 17 00:00:00 2001 From: Ciaran McNulty Date: Tue, 29 Nov 2022 13:54:00 +0000 Subject: [PATCH 336/567] Add PHP 8.2 to the test grid --- .github/workflows/build.yml | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index cc771ebae..88dfd05c7 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -18,7 +18,7 @@ jobs: strategy: fail-fast: false matrix: - php: [7.2, 7.3, 7.4, 8.0, 8.1] + php: [7.2, 7.3, 7.4, 8.0, 8.1, 8.2] os: [ubuntu-latest] composer-mode: [update] symfony-version: [''] @@ -37,27 +37,27 @@ jobs: symfony-version: '' # MacOS on latest PHP only - - php: 8.1 + - php: 8.2 os: macos-latest composer-mode: update symfony-version: '' # Windows on latest PHP only - - php: 8.1 + - php: 8.2 os: windows-latest composer-mode: update symfony-version: '' # Symfony jobs: - - php: 8.1 + - php: 8.2 os: ubuntu-latest composer-mode: update symfony-version: '4.4' - - php: 8.1 + - php: 8.2 os: ubuntu-latest composer-mode: update symfony-version: '5.4' - - php: 8.1 + - php: 8.2 os: ubuntu-latest composer-mode: update symfony-version: '6.0' @@ -123,7 +123,7 @@ jobs: - name: Setup PHP uses: shivammathur/setup-php@v2 with: - php-version: 8.0 + php-version: 8.2 ini-values: "zend.exception_ignore_args=Off" coverage: none From 3e0aa928dbaac4a4e8aa13b1a79d675b65795f57 Mon Sep 17 00:00:00 2001 From: Ciaran McNulty Date: Tue, 29 Nov 2022 15:14:23 +0000 Subject: [PATCH 337/567] Revert version of PHP for the symfony 4.4 test 4.4 will not be supported when 8.2 is released, despite the composer.json --- .github/workflows/build.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 88dfd05c7..684402495 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -49,7 +49,7 @@ jobs: symfony-version: '' # Symfony jobs: - - php: 8.2 + - php: 8.1 os: ubuntu-latest composer-mode: update symfony-version: '4.4' From b33d9075fc0011bc222f3c79d83b28e478f28235 Mon Sep 17 00:00:00 2001 From: Ciaran McNulty Date: Tue, 29 Nov 2022 15:29:20 +0000 Subject: [PATCH 338/567] Update changelog for 3.12.0 release --- CHANGELOG.md | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 338e4d47d..2471c3749 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,18 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](http://keepachangelog.com/) and this project adheres to [Semantic Versioning](http://semver.org/). +## [3.12.0] - 2022-11-29 + +### Added +* [#1417](https://github.com/Behat/Behat/pull/1417) Allow install with PHP 8.2 [@ciaranmcnulty](https://github.com/ciaranmcnulty) + +### Fixed +* [#1412](https://github.com/Behat/Behat/pull/1412) Fix dynamic property deprecation notices in PHP 8.2 [@gquemener](https://github.com/gquemener) +* [#1410](https://github.com/Behat/Behat/pull/1410) Fix deprecation errors in Junit formatter for PHP 8.1 [@albeorte96](https://github.com/albeorte96) + +### Other contributions +* [#1415](https://github.com/Behat/Behat/pull/1415) Fix README typo [@vinceAmstoutz](https://github.com/vinceAmstoutz) + ## [3.11.0] - 2022-07-07 ### Added @@ -998,6 +1010,7 @@ and this project adheres to [Semantic Versioning](http://semver.org/). ### Changed * Initial release +[3.12.0]: https://github.com/Behat/Behat/compare/v3.11.0...v3.12.0 [3.11.0]: https://github.com/Behat/Behat/compare/v3.10.0...v3.11.0 [3.9.0]: https://github.com/Behat/Behat/compare/v3.8.1...v3.9.0 [3.8.1]: https://github.com/Behat/Behat/compare/v3.8.0...v3.8.1 From 2f059c9172764ba1f1759b3679aca499b665330a Mon Sep 17 00:00:00 2001 From: Ciaran McNulty Date: Tue, 29 Nov 2022 15:30:11 +0000 Subject: [PATCH 339/567] Update version number for 3.12.0 release --- src/Behat/Behat/ApplicationFactory.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Behat/Behat/ApplicationFactory.php b/src/Behat/Behat/ApplicationFactory.php index 9c4e45055..cab14a5e4 100644 --- a/src/Behat/Behat/ApplicationFactory.php +++ b/src/Behat/Behat/ApplicationFactory.php @@ -46,7 +46,7 @@ */ final class ApplicationFactory extends BaseFactory { - public const VERSION = '3.11.0'; + public const VERSION = '3.12.0'; /** * {@inheritdoc} From f4cd0baaf4f2a9ce2d2ba2499637d107273efa7f Mon Sep 17 00:00:00 2001 From: Rod Elias Date: Fri, 2 Dec 2022 18:54:10 -0300 Subject: [PATCH 340/567] add .editorconfig file --- .editorconfig | 11 +++++++++++ 1 file changed, 11 insertions(+) create mode 100644 .editorconfig diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 000000000..033f8a6da --- /dev/null +++ b/.editorconfig @@ -0,0 +1,11 @@ +root = true + +[*] +charset = utf-8 +indent_size = 4 +indent_style = space +insert_final_newline = true +trim_trailing_whitespace = true + +[*.yml] +indent_size = 2 From ccb5ee669b65e20641a65164e6bbaff0c5ce0154 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Marek=20Noco=C5=84?= Date: Wed, 8 Feb 2023 10:36:31 +0100 Subject: [PATCH 341/567] Added support for ThrowableToStringMapper from PHPUnit 10 --- .../Exception/Stringer/PHPUnitExceptionStringer.php | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/src/Behat/Testwork/Exception/Stringer/PHPUnitExceptionStringer.php b/src/Behat/Testwork/Exception/Stringer/PHPUnitExceptionStringer.php index 0b06299ef..4551b5308 100644 --- a/src/Behat/Testwork/Exception/Stringer/PHPUnitExceptionStringer.php +++ b/src/Behat/Testwork/Exception/Stringer/PHPUnitExceptionStringer.php @@ -35,7 +35,11 @@ public function supportsException(Exception $exception) */ public function stringException(Exception $exception, $verbosity) { - if (!class_exists('PHPUnit\\Framework\\TestFailure')) { + if (class_exists('PHPUnit\\Util\\ThrowableToStringMapper')) { + return trim(\PHPUnit\Util\ThrowableToStringMapper::map($exception)); + } + + if (class_exists('PHPUnit_Framework_TestFailure')) { return trim(\PHPUnit_Framework_TestFailure::exceptionToString($exception)); } From 3bd0114c741935fe5ccc3b58d8e29bd21fd2cb61 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Marek=20Noco=C5=84?= Date: Wed, 8 Feb 2023 11:17:24 +0100 Subject: [PATCH 342/567] Reverted condition change --- .../Testwork/Exception/Stringer/PHPUnitExceptionStringer.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Behat/Testwork/Exception/Stringer/PHPUnitExceptionStringer.php b/src/Behat/Testwork/Exception/Stringer/PHPUnitExceptionStringer.php index 4551b5308..17343f15a 100644 --- a/src/Behat/Testwork/Exception/Stringer/PHPUnitExceptionStringer.php +++ b/src/Behat/Testwork/Exception/Stringer/PHPUnitExceptionStringer.php @@ -39,7 +39,7 @@ public function stringException(Exception $exception, $verbosity) return trim(\PHPUnit\Util\ThrowableToStringMapper::map($exception)); } - if (class_exists('PHPUnit_Framework_TestFailure')) { + if (!class_exists('PHPUnit\\Framework\\TestFailure')) { return trim(\PHPUnit_Framework_TestFailure::exceptionToString($exception)); } From edfb1f01d6f1acfdedfcec68ab6512b4959e06c6 Mon Sep 17 00:00:00 2001 From: Simon Auch Date: Fri, 17 Feb 2023 13:27:26 +0100 Subject: [PATCH 343/567] Fix high memory consumption when using Junit formatter The high memory consumption is caused by the formatter keeping many events for the lifetime of a feature. Some events contain references to the BehatContext, resulting in the BehatContext not being dropped. If a feature contains many scenarios/examples and the BehatContext is big, this can lead to OoM errors. This commit drastically reduces the amount of events the Junit formatter keeps and limits the lifetime of those it keeps to the lifetime of an example. --- .../JUnit/JUnitFeatureElementListener.php | 90 +++++++------------ .../Printer/JUnit/JUnitFeaturePrinter.php | 32 ++++--- .../Output/Printer/JUnitOutputPrinter.php | 9 ++ 3 files changed, 61 insertions(+), 70 deletions(-) diff --git a/src/Behat/Behat/Output/Node/EventListener/JUnit/JUnitFeatureElementListener.php b/src/Behat/Behat/Output/Node/EventListener/JUnit/JUnitFeatureElementListener.php index 2aae5a2cf..7e95cf6c7 100644 --- a/src/Behat/Behat/Output/Node/EventListener/JUnit/JUnitFeatureElementListener.php +++ b/src/Behat/Behat/Output/Node/EventListener/JUnit/JUnitFeatureElementListener.php @@ -16,7 +16,6 @@ use Behat\Behat\EventDispatcher\Event\AfterStepTested; use Behat\Behat\EventDispatcher\Event\BeforeFeatureTested; use Behat\Behat\EventDispatcher\Event\ScenarioTested; -use Behat\Behat\EventDispatcher\Event\StepTested; use Behat\Behat\Output\Node\Printer\FeaturePrinter; use Behat\Behat\Output\Node\Printer\JUnit\JUnitScenarioPrinter; use Behat\Behat\Output\Node\Printer\SetupPrinter; @@ -50,14 +49,6 @@ final class JUnitFeatureElementListener implements EventListener * @var SetupPrinter */ private $setupPrinter; - /** - * @var FeatureNode - */ - private $beforeFeatureTestedEvent; - /** - * @var AfterScenarioTested[] - */ - private $afterScenarioTestedEvents = array(); /** * @var AfterStepTested[] */ @@ -91,51 +82,23 @@ public function __construct(FeaturePrinter $featurePrinter, */ public function listenEvent(Formatter $formatter, Event $event, $eventName) { - if ($event instanceof ScenarioTested) { - $this->captureScenarioEvent($event); - } - - if ($event instanceof StepTested - || $event instanceof AfterStepSetup - ) { - $this->captureStepEvent($event); - } - - $this->captureFeatureOnBeforeEvent($event); + $this->printFeatureOnBeforeEvent($formatter, $event); + $this->captureStepEvent($event); + $this->printScenarioEvent($formatter, $event); $this->printFeatureOnAfterEvent($formatter, $event); } /** - * Captures scenario tested event. - * - * @param ScenarioTested $event - */ - private function captureScenarioEvent(ScenarioTested $event) - { - if ($event instanceof AfterScenarioTested) { - $this->afterScenarioTestedEvents[$event->getScenario()->getLine()] = array( - 'event' => $event, - 'step_events' => $this->afterStepTestedEvents, - 'step_setup_events' => $this->afterStepSetupEvents, - ); - - $this->afterStepTestedEvents = array(); - $this->afterStepSetupEvents = array(); - } - } - - /** - * Captures feature on BEFORE event. + * Prints the header for the feature. * + * @param Formatter $formatter * @param Event $event */ - private function captureFeatureOnBeforeEvent(Event $event) + private function printFeatureOnBeforeEvent(Formatter $formatter, Event $event) { - if (!$event instanceof BeforeFeatureTested) { - return; + if ($event instanceof BeforeFeatureTested) { + $this->featurePrinter->printHeader($formatter, $event->getFeature()); } - - $this->beforeFeatureTestedEvent = $event->getFeature(); } /** @@ -154,21 +117,15 @@ private function captureStepEvent(Event $event) } /** - * Prints the feature on AFTER event. + * Captures scenario tested event. * * @param Formatter $formatter - * @param Event $event + * @param ScenarioTested $event */ - public function printFeatureOnAfterEvent(Formatter $formatter, Event $event) + private function printScenarioEvent(Formatter $formatter, Event $event) { - if (!$event instanceof AfterFeatureTested) { - return; - } - - $this->featurePrinter->printHeader($formatter, $this->beforeFeatureTestedEvent); - - foreach ($this->afterScenarioTestedEvents as $afterScenario) { - $afterScenarioTested = $afterScenario['event']; + if ($event instanceof AfterScenarioTested) { + $afterScenarioTested = $event; $this->scenarioPrinter->printOpenTag( $formatter, $afterScenarioTested->getFeature(), @@ -178,16 +135,29 @@ public function printFeatureOnAfterEvent(Formatter $formatter, Event $event) ); /** @var AfterStepSetup $afterStepSetup */ - foreach ($afterScenario['step_setup_events'] as $afterStepSetup) { + foreach ($this->afterStepSetupEvents as $afterStepSetup) { $this->setupPrinter->printSetup($formatter, $afterStepSetup->getSetup()); } - foreach ($afterScenario['step_events'] as $afterStepTested) { + foreach ($this->afterStepTestedEvents as $afterStepTested) { $this->stepPrinter->printStep($formatter, $afterScenarioTested->getScenario(), $afterStepTested->getStep(), $afterStepTested->getTestResult()); $this->setupPrinter->printTeardown($formatter, $afterStepTested->getTeardown()); } + + $this->afterStepTestedEvents = array(); + $this->afterStepSetupEvents = array(); } + } - $this->featurePrinter->printFooter($formatter, $event->getTestResult()); - $this->afterScenarioTestedEvents = array(); + /** + * Prints the feature on AFTER event. + * + * @param Formatter $formatter + * @param Event $event + */ + private function printFeatureOnAfterEvent(Formatter $formatter, Event $event) + { + if ($event instanceof AfterFeatureTested) { + $this->featurePrinter->printFooter($formatter, $event->getTestResult()); + } } } diff --git a/src/Behat/Behat/Output/Node/Printer/JUnit/JUnitFeaturePrinter.php b/src/Behat/Behat/Output/Node/Printer/JUnit/JUnitFeaturePrinter.php index 651c4a650..2c46435da 100644 --- a/src/Behat/Behat/Output/Node/Printer/JUnit/JUnitFeaturePrinter.php +++ b/src/Behat/Behat/Output/Node/Printer/JUnit/JUnitFeaturePrinter.php @@ -31,6 +31,11 @@ final class JUnitFeaturePrinter implements FeaturePrinter */ private $statistics; + /** + * @var FeatureNode + */ + private $currentFeature; + /** * @var JUnitDurationListener|null */ @@ -46,6 +51,18 @@ public function __construct(PhaseStatistics $statistics, JUnitDurationListener $ * {@inheritDoc} */ public function printHeader(Formatter $formatter, FeatureNode $feature) + { + $this->statistics->reset(); + $this->currentFeature = $feature; + /** @var JUnitOutputPrinter $outputPrinter */ + $outputPrinter = $formatter->getOutputPrinter(); + $outputPrinter->addTestsuite(); + } + + /** + * {@inheritDoc} + */ + public function printFooter(Formatter $formatter, TestResult $result) { $stats = $this->statistics->getScenarioStatCounts(); @@ -58,21 +75,16 @@ public function printHeader(Formatter $formatter, FeatureNode $feature) /** @var JUnitOutputPrinter $outputPrinter */ $outputPrinter = $formatter->getOutputPrinter(); - $outputPrinter->addTestsuite(array( - 'name' => $feature->getTitle(), + $outputPrinter->extendTestsuiteAttributes(array( + 'name' => $this->currentFeature->getTitle(), 'tests' => $totalCount, 'skipped' => $stats[TestResult::SKIPPED], 'failures' => $stats[TestResult::FAILED], 'errors' => $stats[TestResult::PENDING] + $stats[StepResult::UNDEFINED], - 'time' => $this->durationListener ? $this->durationListener->getFeatureDuration($feature) : '', + 'time' => $this->durationListener ? $this->durationListener->getFeatureDuration($this->currentFeature) : '', )); - $this->statistics->reset(); - } - /** - * {@inheritDoc} - */ - public function printFooter(Formatter $formatter, TestResult $result) - { + $this->statistics->reset(); + $this->currentFeature = null; } } diff --git a/src/Behat/Testwork/Output/Printer/JUnitOutputPrinter.php b/src/Behat/Testwork/Output/Printer/JUnitOutputPrinter.php index ce1371c93..960e9cb62 100644 --- a/src/Behat/Testwork/Output/Printer/JUnitOutputPrinter.php +++ b/src/Behat/Testwork/Output/Printer/JUnitOutputPrinter.php @@ -85,6 +85,15 @@ public function addTestsuite(array $testsuiteAttributes = array()) $this->addAttributesToNode($this->currentTestsuite, $testsuiteAttributes); } + /** + * Extends the current node. + * + * @param array $testsuiteAttributes + */ + public function extendTestsuiteAttributes(array $testsuiteAttributes = array()){ + $this->addAttributesToNode($this->currentTestsuite, $testsuiteAttributes); + } + /** * Adds a new node. From 81e869a0ece38345ba6a760436282aca6da10e7d Mon Sep 17 00:00:00 2001 From: Simon Auch Date: Fri, 17 Feb 2023 13:28:37 +0100 Subject: [PATCH 344/567] Update CHANGELOG.md --- CHANGELOG.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2471c3749..c3d8e478d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,11 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](http://keepachangelog.com/) and this project adheres to [Semantic Versioning](http://semver.org/). +## [Unreleased] + +### Fixed +* [#1103](https://github.com/Behat/Behat/issues/1103) Reduce memory consumption of Junit formatter [@simon-auch](https://github.com/simon-auch) + ## [3.12.0] - 2022-11-29 ### Added From bb6fd440ee591260972bf480771830e2e55b029f Mon Sep 17 00:00:00 2001 From: Simon Auch Date: Fri, 17 Feb 2023 23:36:06 +0100 Subject: [PATCH 345/567] revert to early return and fix phpdoc --- .../JUnit/JUnitFeatureElementListener.php | 53 ++++++++++--------- 1 file changed, 28 insertions(+), 25 deletions(-) diff --git a/src/Behat/Behat/Output/Node/EventListener/JUnit/JUnitFeatureElementListener.php b/src/Behat/Behat/Output/Node/EventListener/JUnit/JUnitFeatureElementListener.php index 7e95cf6c7..1691f6a6c 100644 --- a/src/Behat/Behat/Output/Node/EventListener/JUnit/JUnitFeatureElementListener.php +++ b/src/Behat/Behat/Output/Node/EventListener/JUnit/JUnitFeatureElementListener.php @@ -96,9 +96,10 @@ public function listenEvent(Formatter $formatter, Event $event, $eventName) */ private function printFeatureOnBeforeEvent(Formatter $formatter, Event $event) { - if ($event instanceof BeforeFeatureTested) { - $this->featurePrinter->printHeader($formatter, $event->getFeature()); + if (!$event instanceof BeforeFeatureTested) { + return; } + $this->featurePrinter->printHeader($formatter, $event->getFeature()); } /** @@ -120,32 +121,33 @@ private function captureStepEvent(Event $event) * Captures scenario tested event. * * @param Formatter $formatter - * @param ScenarioTested $event + * @param Event $event */ private function printScenarioEvent(Formatter $formatter, Event $event) { - if ($event instanceof AfterScenarioTested) { - $afterScenarioTested = $event; - $this->scenarioPrinter->printOpenTag( - $formatter, - $afterScenarioTested->getFeature(), - $afterScenarioTested->getScenario(), - $afterScenarioTested->getTestResult(), - $event->getFeature()->getFile() - ); - - /** @var AfterStepSetup $afterStepSetup */ - foreach ($this->afterStepSetupEvents as $afterStepSetup) { - $this->setupPrinter->printSetup($formatter, $afterStepSetup->getSetup()); - } - foreach ($this->afterStepTestedEvents as $afterStepTested) { - $this->stepPrinter->printStep($formatter, $afterScenarioTested->getScenario(), $afterStepTested->getStep(), $afterStepTested->getTestResult()); - $this->setupPrinter->printTeardown($formatter, $afterStepTested->getTeardown()); - } + if (!$event instanceof AfterScenarioTested) { + return; + } + $afterScenarioTested = $event; + $this->scenarioPrinter->printOpenTag( + $formatter, + $afterScenarioTested->getFeature(), + $afterScenarioTested->getScenario(), + $afterScenarioTested->getTestResult(), + $event->getFeature()->getFile() + ); - $this->afterStepTestedEvents = array(); - $this->afterStepSetupEvents = array(); + /** @var AfterStepSetup $afterStepSetup */ + foreach ($this->afterStepSetupEvents as $afterStepSetup) { + $this->setupPrinter->printSetup($formatter, $afterStepSetup->getSetup()); } + foreach ($this->afterStepTestedEvents as $afterStepTested) { + $this->stepPrinter->printStep($formatter, $afterScenarioTested->getScenario(), $afterStepTested->getStep(), $afterStepTested->getTestResult()); + $this->setupPrinter->printTeardown($formatter, $afterStepTested->getTeardown()); + } + + $this->afterStepTestedEvents = array(); + $this->afterStepSetupEvents = array(); } /** @@ -156,8 +158,9 @@ private function printScenarioEvent(Formatter $formatter, Event $event) */ private function printFeatureOnAfterEvent(Formatter $formatter, Event $event) { - if ($event instanceof AfterFeatureTested) { - $this->featurePrinter->printFooter($formatter, $event->getTestResult()); + if (!$event instanceof AfterFeatureTested) { + return; } + $this->featurePrinter->printFooter($formatter, $event->getTestResult()); } } From 21095d60b89497514028de58d50d61b735e9ce17 Mon Sep 17 00:00:00 2001 From: Simon Auch Date: Sat, 4 Mar 2023 15:48:50 +0100 Subject: [PATCH 346/567] fix codestyle --- src/Behat/Testwork/Output/Printer/JUnitOutputPrinter.php | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/Behat/Testwork/Output/Printer/JUnitOutputPrinter.php b/src/Behat/Testwork/Output/Printer/JUnitOutputPrinter.php index 960e9cb62..bbc76eab6 100644 --- a/src/Behat/Testwork/Output/Printer/JUnitOutputPrinter.php +++ b/src/Behat/Testwork/Output/Printer/JUnitOutputPrinter.php @@ -90,7 +90,8 @@ public function addTestsuite(array $testsuiteAttributes = array()) * * @param array $testsuiteAttributes */ - public function extendTestsuiteAttributes(array $testsuiteAttributes = array()){ + public function extendTestsuiteAttributes(array $testsuiteAttributes = array()) + { $this->addAttributesToNode($this->currentTestsuite, $testsuiteAttributes); } From 2c987562694b0c679318f6de4b06de6d00eefe99 Mon Sep 17 00:00:00 2001 From: Christian Sciberras Date: Sat, 8 Apr 2023 18:40:54 +0200 Subject: [PATCH 347/567] Improved unit tests; fixed autoload for tests --- composer.json | 4 +- .../Pattern/PatternTransformerTest.php | 22 ++++----- .../Argument/MixedArgumentOrganiserTest.php | 49 +++++++++---------- .../TestworkEventDispatcherTest.php | 4 +- .../Subject/GroupedSubjectIteratorTest.php | 9 ++-- 5 files changed, 43 insertions(+), 45 deletions(-) diff --git a/composer.json b/composer.json index 333713bf4..f40a9ae8c 100644 --- a/composer.json +++ b/composer.json @@ -2,7 +2,7 @@ "name": "behat/behat", "description": "Scenario-oriented BDD framework for PHP", "keywords": ["BDD", "ScenarioBDD", "StoryBDD", "Examples", "Scrum", "Agile", "User story", "Symfony", "business", "development", "testing", "documentation"], - "homepage": "http://behat.org/", + "homepage": "https://behat.org/", "type": "library", "license": "MIT", "authors": [ @@ -50,7 +50,7 @@ "autoload-dev": { "psr-4": { - "Behat\\Tests\\": "tests/" + "Behat\\Tests\\": "tests/Behat/Tests" } }, diff --git a/tests/Behat/Tests/Definition/Pattern/PatternTransformerTest.php b/tests/Behat/Tests/Definition/Pattern/PatternTransformerTest.php index b306b34ac..4903b15f8 100644 --- a/tests/Behat/Tests/Definition/Pattern/PatternTransformerTest.php +++ b/tests/Behat/Tests/Definition/Pattern/PatternTransformerTest.php @@ -5,16 +5,16 @@ use Behat\Behat\Definition\Pattern\PatternTransformer; use Behat\Behat\Definition\Pattern\Policy\PatternPolicy; use PHPUnit\Framework\TestCase; +use Behat\Behat\Definition\Exception\UnknownPatternException; /** - * Class PatternTransformerTest * @author Julien Deniau */ class PatternTransformerTest extends TestCase { - public function testTransformPatternToRegexCache() + public function testTransformPatternToRegexCache(): void { - $observer = $this->prophesize('Behat\Behat\Definition\Pattern\Policy\PatternPolicy'); + $observer = $this->prophesize(PatternPolicy::class); // first pattern $observer->supportsPattern('hello world')->willReturn(true); $observer->transformPatternToRegex('hello world') @@ -39,19 +39,19 @@ public function testTransformPatternToRegexCache() $this->assertEquals('/hi world/', $regex3); } - public function testTransformPatternToRegexCacheAndRegisterNewPolicy() + public function testTransformPatternToRegexCacheAndRegisterNewPolicy(): void { // first pattern - $policy1Prophecy = $this->prophesize('Behat\Behat\Definition\Pattern\Policy\PatternPolicy'); + $policy1Prophecy = $this->prophesize(PatternPolicy::class); $policy1Prophecy->supportsPattern('hello world')->willReturn(true); $policy1Prophecy->transformPatternToRegex('hello world') ->shouldBeCalledTimes(2) ->willReturn('/hello world/'); // second pattern - $policy2Prophecy = $this->prophesize('Behat\Behat\Definition\Pattern\Policy\PatternPolicy'); - $policy1Prophecy->supportsPattern()->shouldNotBeCalled(); - $policy1Prophecy->transformPatternToRegex()->shouldNotBeCalled(); + $policy2Prophecy = $this->prophesize(PatternPolicy::class); + $policy1Prophecy->supportsPattern('')->shouldNotBeCalled(); + $policy1Prophecy->transformPatternToRegex('')->shouldNotBeCalled(); $testedInstance = new PatternTransformer(); $testedInstance->registerPatternPolicy($policy1Prophecy->reveal()); @@ -66,10 +66,10 @@ public function testTransformPatternToRegexCacheAndRegisterNewPolicy() $this->assertEquals('/hello world/', $regex3); } - public function testTransformPatternToRegexNoMatch() + public function testTransformPatternToRegexNoMatch(): void { // first pattern - $policy1Prophecy = $this->prophesize('Behat\Behat\Definition\Pattern\Policy\PatternPolicy'); + $policy1Prophecy = $this->prophesize(PatternPolicy::class); $policy1Prophecy->supportsPattern('hello world')->willReturn(false); $policy1Prophecy->transformPatternToRegex('hello world') ->shouldNotBeCalled(); @@ -77,7 +77,7 @@ public function testTransformPatternToRegexNoMatch() $testedInstance = new PatternTransformer(); $testedInstance->registerPatternPolicy($policy1Prophecy->reveal()); - $this->expectException('\Behat\Behat\Definition\Exception\UnknownPatternException'); + $this->expectException(UnknownPatternException::class); $this->expectExceptionMessage("Can not find policy for a pattern `hello world`."); $regex = $testedInstance->transformPatternToRegex('hello world'); } diff --git a/tests/Behat/Tests/Testwork/Argument/MixedArgumentOrganiserTest.php b/tests/Behat/Tests/Testwork/Argument/MixedArgumentOrganiserTest.php index 5527f4738..d66f685ef 100644 --- a/tests/Behat/Tests/Testwork/Argument/MixedArgumentOrganiserTest.php +++ b/tests/Behat/Tests/Testwork/Argument/MixedArgumentOrganiserTest.php @@ -1,24 +1,26 @@ organiser = new MixedArgumentOrganiser(); } - /** @test */ - function it_organises_nothing_if_no_args() + public function testThatItOrganisesNothingIfNoArgs(): void { - $r = new \ReflectionFunction( - function(\DateTimeInterface $d) {} + $r = new ReflectionFunction( + static function(\DateTimeInterface $d) {} ); $args = []; @@ -27,11 +29,10 @@ function(\DateTimeInterface $d) {} $this->assertSame([], $organised); } - /** @test */ - function it_matches_args_by_position() + public function testThatItMatchesArgsByPosition(): void { - $r = new \ReflectionFunction( - function($x, $y) {} + $r = new ReflectionFunction( + static function($x, $y) {} ); $args = [ 1, @@ -41,14 +42,13 @@ function($x, $y) {} $organised = $this->organiser->organiseArguments($r, $args); - $this->assertSame([1,2], $organised); + $this->assertSame([1, 2], $organised); } - /** @test */ - function it_matches_args_by_name() + public function testThatItMatchesArgsByName(): void { - $r = new \ReflectionFunction( - function($date) {} + $r = new ReflectionFunction( + static function($date) {} ); $args = [ 'date' => $date = new \DateTime(), @@ -60,11 +60,10 @@ function($date) {} $this->assertSame(['date' => $date], $organised); } - /** @test */ - function it_matches_args_by_type() + public function testThatItMatchesArgsByType(): void { - $r = new \ReflectionFunction( - function(\DateTimeInterface $d) {} + $r = new ReflectionFunction( + static function(\DateTimeInterface $d) {} ); $args = [ 'x' => $date = new \DateTime(), @@ -76,11 +75,10 @@ function(\DateTimeInterface $d) {} $this->assertSame([$date], $organised); } - /** @test */ - function it_matches_args_by_name_over_type() + public function testThatItMatchesArgsByNameOverType(): void { - $r = new \ReflectionFunction( - function(\DateTimeInterface $a, $date) {} + $r = new ReflectionFunction( + static function(\DateTimeInterface $a, $date) {} ); $args = [ 'date' => $date = new \DateTime(), @@ -93,16 +91,15 @@ function(\DateTimeInterface $a, $date) {} } /** - * @test * @requires PHP >= 8.0 */ - function it_matches_union_types() + public function testThatItMatchesUnionTypes(): void { - $r = eval(<< $date = new \DateTime(), diff --git a/tests/Behat/Tests/Testwork/EventDispatcher/TestworkEventDispatcherTest.php b/tests/Behat/Tests/Testwork/EventDispatcher/TestworkEventDispatcherTest.php index 62910abc0..4abf24910 100644 --- a/tests/Behat/Tests/Testwork/EventDispatcher/TestworkEventDispatcherTest.php +++ b/tests/Behat/Tests/Testwork/EventDispatcher/TestworkEventDispatcherTest.php @@ -24,7 +24,7 @@ public function testDispatchLegacyCall(): void $listener = $this->createListenerSpy(); $dispatcher->addListener($eventName, $listener); - $dispatcher->dispatch($eventName, $event); + $dispatcher->dispatch($event, $eventName); $this->assertCount(1, $listener->receivedEvents); $this->assertEquals($event, $listener->receivedEvents[0]); @@ -57,7 +57,7 @@ public function setName($name): void $listener = $this->createListenerSpy(); $dispatcher->addListener($eventName, $listener); - $dispatcher->dispatch($eventName, $event); + $dispatcher->dispatch($event, $eventName); $this->assertCount(1, $listener->receivedEvents); $this->assertEquals($eventName, $event->name); diff --git a/tests/Behat/Tests/Testwork/Subject/GroupedSubjectIteratorTest.php b/tests/Behat/Tests/Testwork/Subject/GroupedSubjectIteratorTest.php index 84b8dd18f..711696cc0 100644 --- a/tests/Behat/Tests/Testwork/Subject/GroupedSubjectIteratorTest.php +++ b/tests/Behat/Tests/Testwork/Subject/GroupedSubjectIteratorTest.php @@ -6,12 +6,13 @@ use Behat\Testwork\Specification\NoSpecificationsIterator; use Behat\Testwork\Specification\SpecificationArrayIterator; use PHPUnit\Framework\TestCase; +use Behat\Testwork\Suite\Suite; class GroupedSubjectIteratorTest extends TestCase { - public function testIterationWithEmptyAtBeginning() + public function testIterationWithEmptyAtBeginning(): void { - $suite = $this->prophesize('Behat\Testwork\Suite\Suite')->reveal(); + $suite = $this->prophesize(Suite::class)->reveal(); $iterator = new GroupedSpecificationIterator($suite, array( new NoSpecificationsIterator($suite), @@ -21,9 +22,9 @@ public function testIterationWithEmptyAtBeginning() $this->assertEquals(1, iterator_count($iterator)); } - public function testIterationWithEmptyInMiddle() + public function testIterationWithEmptyInMiddle(): void { - $suite = $this->prophesize('Behat\Testwork\Suite\Suite')->reveal(); + $suite = $this->prophesize(Suite::class)->reveal(); $iterator = new GroupedSpecificationIterator($suite, array( new SpecificationArrayIterator($suite, array($this->prophesize()->reveal())), From 01d624e2b899d5b3e3527e3c392eee2331d90103 Mon Sep 17 00:00:00 2001 From: Christian Sciberras Date: Sat, 8 Apr 2023 20:36:59 +0200 Subject: [PATCH 348/567] Minor fix --- composer.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/composer.json b/composer.json index f40a9ae8c..d9567b3d0 100644 --- a/composer.json +++ b/composer.json @@ -50,7 +50,7 @@ "autoload-dev": { "psr-4": { - "Behat\\Tests\\": "tests/Behat/Tests" + "Behat\\Tests\\": "tests/Behat/Tests/" } }, From 885b6641f2a0ae0b0ce5c83325b2667b6e86617f Mon Sep 17 00:00:00 2001 From: Yassine Guedidi Date: Mon, 17 Apr 2023 14:35:54 +0200 Subject: [PATCH 349/567] Add more precise types to context environments --- .../Behat/Context/Environment/ContextEnvironment.php | 5 +++-- .../Environment/InitializedContextEnvironment.php | 10 ++++++---- .../Environment/UninitializedContextEnvironment.php | 9 +++++---- 3 files changed, 14 insertions(+), 10 deletions(-) diff --git a/src/Behat/Behat/Context/Environment/ContextEnvironment.php b/src/Behat/Behat/Context/Environment/ContextEnvironment.php index 44bcf29b8..c63543eb6 100644 --- a/src/Behat/Behat/Context/Environment/ContextEnvironment.php +++ b/src/Behat/Behat/Context/Environment/ContextEnvironment.php @@ -10,6 +10,7 @@ namespace Behat\Behat\Context\Environment; +use Behat\Behat\Context\Context; use Behat\Behat\Context\Environment\Handler\ContextEnvironmentHandler; use Behat\Testwork\Environment\Environment; @@ -32,14 +33,14 @@ public function hasContexts(); /** * Returns list of registered context classes. * - * @return string[] + * @return list> */ public function getContextClasses(); /** * Checks if environment contains context with the specified class name. * - * @param string $class + * @param class-string $class * * @return bool */ diff --git a/src/Behat/Behat/Context/Environment/InitializedContextEnvironment.php b/src/Behat/Behat/Context/Environment/InitializedContextEnvironment.php index 053354963..63a6bb3c6 100644 --- a/src/Behat/Behat/Context/Environment/InitializedContextEnvironment.php +++ b/src/Behat/Behat/Context/Environment/InitializedContextEnvironment.php @@ -36,7 +36,7 @@ final class InitializedContextEnvironment implements ContextEnvironment, Service */ private $serviceContainer; /** - * @var Context[] + * @var array, Context> */ private $contexts = array(); @@ -103,7 +103,7 @@ public function hasContextClass($class) /** * Returns list of registered context instances. * - * @return Context[] + * @return list */ public function getContexts() { @@ -113,9 +113,11 @@ public function getContexts() /** * Returns registered context by its class name. * - * @param string $class + * @template T of Context * - * @return Context + * @param class-string $class + * + * @return T * * @throws ContextNotFoundException If context is not in the environment */ diff --git a/src/Behat/Behat/Context/Environment/UninitializedContextEnvironment.php b/src/Behat/Behat/Context/Environment/UninitializedContextEnvironment.php index d0ff98551..a517d5f74 100644 --- a/src/Behat/Behat/Context/Environment/UninitializedContextEnvironment.php +++ b/src/Behat/Behat/Context/Environment/UninitializedContextEnvironment.php @@ -10,6 +10,7 @@ namespace Behat\Behat\Context\Environment; +use Behat\Behat\Context\Context; use Behat\Behat\Context\Environment\Handler\ContextEnvironmentHandler; use Behat\Behat\Context\Exception\ContextNotFoundException; use Behat\Behat\Context\Exception\WrongContextClassException; @@ -25,15 +26,15 @@ final class UninitializedContextEnvironment extends StaticEnvironment implements ContextEnvironment { /** - * @var array[] + * @var array, array> */ private $contextClasses = array(); /** * Registers context class. * - * @param string $contextClass - * @param null|array $arguments + * @param class-string $contextClass + * @param null|array $arguments * * @throws ContextNotFoundException If class does not exist * @throws WrongContextClassException if class does not implement Context interface @@ -86,7 +87,7 @@ public function hasContextClass($class) /** * Returns context classes with their arguments. * - * @return array[] + * @return array, array> */ public function getContextClassesWithArguments() { From b3a19f8779f89a052a996293ae5315024c6eb39f Mon Sep 17 00:00:00 2001 From: Yassine Guedidi Date: Mon, 17 Apr 2023 14:36:47 +0200 Subject: [PATCH 350/567] Add more precise types to testwork service container extension --- .../Context/Environment/InitializedContextEnvironment.php | 1 + src/Behat/Testwork/ServiceContainer/Extension.php | 4 ++-- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/src/Behat/Behat/Context/Environment/InitializedContextEnvironment.php b/src/Behat/Behat/Context/Environment/InitializedContextEnvironment.php index 63a6bb3c6..45774d1d2 100644 --- a/src/Behat/Behat/Context/Environment/InitializedContextEnvironment.php +++ b/src/Behat/Behat/Context/Environment/InitializedContextEnvironment.php @@ -37,6 +37,7 @@ final class InitializedContextEnvironment implements ContextEnvironment, Service private $serviceContainer; /** * @var array, Context> + * @psalm-var class-string-map */ private $contexts = array(); diff --git a/src/Behat/Testwork/ServiceContainer/Extension.php b/src/Behat/Testwork/ServiceContainer/Extension.php index 9533dcaa3..68e62f576 100644 --- a/src/Behat/Testwork/ServiceContainer/Extension.php +++ b/src/Behat/Testwork/ServiceContainer/Extension.php @@ -53,8 +53,8 @@ public function configure(ArrayNodeDefinition $builder); /** * Loads extension services into temporary container. * - * @param ContainerBuilder $container - * @param array $config + * @param ContainerBuilder $container + * @param array $config */ public function load(ContainerBuilder $container, array $config); } From f65d1d6c6a67b83c193ef3aeec8f11d4ea9c020c Mon Sep 17 00:00:00 2001 From: Christophe Coevoet Date: Tue, 18 Apr 2023 17:39:43 +0200 Subject: [PATCH 351/567] Update the changelog for the 3.13.0 release --- CHANGELOG.md | 25 ++++++++++++++++--------- 1 file changed, 16 insertions(+), 9 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2471c3749..0a87f7474 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,12 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](http://keepachangelog.com/) and this project adheres to [Semantic Versioning](http://semver.org/). +## [3.13.0] - 2023-04-18 + +### Added +* [#1422](https://github.com/Behat/Behat/pull/1422) Add support for displaying PHPUnit 10 exceptions [@mnocon](https://github.com/mnocon) +* [#1429](https://github.com/Behat/Behat/pull/1429) Add more precise types for static analysis [@yguedidi](https://github.com/yguedidi) + ## [3.12.0] - 2022-11-29 ### Added @@ -84,14 +90,14 @@ and this project adheres to [Semantic Versioning](http://semver.org/). * [1322](https://github.com/Behat/Behat/pull/1322): Feature title as classname in JUnit output ([@steefmin](https://github.com/steefmin)) * [1313](https://github.com/Behat/Behat/pull/1313): PHP 8 support ([@ciaranmcnulty](https://github.com/ciaranmcnulty)) * [1313](https://github.com/Behat/Behat/pull/1323): Further PHP 8 support ([@dgafka](https://github.com/dgafka)) - + ### Fixed * [#1303](https://github.com/Behat/Behat/pull/1303): Error when running `--debug` with recent Symfony versions ([@jawira](https://github.com/jawira)) * [#1311](https://github.com/Behat/Behat/pull/1311): Remove symfony deprecation messages about transChoice ([@guilliamxavier](https://github.com/guilliamxavier)) * [#1318](https://github.com/Behat/Behat/pull/1318): Allow negated filters on scenario hoooks ([@andrewnicols ](https://github.com/andrewnicols)) -### Changed +### Changed * [#1299](https://github.com/Behat/Behat/pull/1299): Removed support for PHP <7.2, Symfony <4.4 ([@upamil](https://github.com/pamil)) * [#1310](https://github.com/Behat/Behat/pull/1310): Refactoring to use newer language features ([@rpkamp](https://github.com/rpkamp)) * [#1315](https://github.com/Behat/Behat/pull/1315): Remove BC layer for unsuppored symfony dispatcher ([@rpkamp](https://github.com/rpkamp)) @@ -108,8 +114,8 @@ and this project adheres to [Semantic Versioning](http://semver.org/). * [#1270](https://github.com/Behat/Behat/pull/1270): Fix issues with PHP version handling in build ([@Sam-Burns](https://github.com/Sam-Burns)) * [#1282](https://github.com/Behat/Behat/pull/1282): Updated the year on Changelog dates ([@choult](https://github.com/choult)) * [#1284](https://github.com/Behat/Behat/pull/1284): Restore PHP 5.3/5.4 compat ([@dvdoug](https://github.com/dvdoug), [@Sam-Burns](https://github.com/Sam-Burns), [@pamil](https://github.com/pamil)) - -### Changed + +### Changed * [#1281](https://github.com/Behat/Behat/pull/1281): Make container-interop/container-interop optional dependency ([@upyx](https://github.com/upyx)) ## [3.6.1] - 2020-02-06 @@ -131,16 +137,16 @@ and this project adheres to [Semantic Versioning](http://semver.org/). ## [3.5.0] - 2018-08-10 ### Added - * [#1144](https://github.com/Behat/Behat/pull/1144): Allow to use arrays as context parameters + * [#1144](https://github.com/Behat/Behat/pull/1144): Allow to use arrays as context parameters * [#1081](https://github.com/Behat/Behat/pull/1081): Allow passing null as a named context parameter * [#1083](https://github.com/Behat/Behat/pull/1083): Time attribute in JUnit output - + ### Changed - * [#1153](https://github.com/Behat/Behat/pull/1153): Cache pattern to regex transformations + * [#1153](https://github.com/Behat/Behat/pull/1153): Cache pattern to regex transformations * [#1155](https://github.com/Behat/Behat/pull/1155): Remove composer suggestions - + ### Fixed - * Custom container must be public for symfony 4 + * Custom container must be public for symfony 4 * [#1160](https://github.com/Behat/Behat/pull/1160): Register CLI services as synthetic * [#1163](https://github.com/Behat/Behat/pull/1163): Allow for new-style symfony serialisation * [#1130](https://github.com/Behat/Behat/pull/1130): Fix quoteless definition arguments matching with unicode characters @@ -1010,6 +1016,7 @@ and this project adheres to [Semantic Versioning](http://semver.org/). ### Changed * Initial release +[3.13.0]: https://github.com/Behat/Behat/compare/v3.12.0...v3.13.0 [3.12.0]: https://github.com/Behat/Behat/compare/v3.11.0...v3.12.0 [3.11.0]: https://github.com/Behat/Behat/compare/v3.10.0...v3.11.0 [3.9.0]: https://github.com/Behat/Behat/compare/v3.8.1...v3.9.0 From 9dd7cdb309e464ddeab095cd1a5151c2dccba4ab Mon Sep 17 00:00:00 2001 From: Christophe Coevoet Date: Tue, 18 Apr 2023 17:40:53 +0200 Subject: [PATCH 352/567] Update the version for the 3.13.0 release --- src/Behat/Behat/ApplicationFactory.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Behat/Behat/ApplicationFactory.php b/src/Behat/Behat/ApplicationFactory.php index cab14a5e4..f2870ae53 100644 --- a/src/Behat/Behat/ApplicationFactory.php +++ b/src/Behat/Behat/ApplicationFactory.php @@ -46,7 +46,7 @@ */ final class ApplicationFactory extends BaseFactory { - public const VERSION = '3.12.0'; + public const VERSION = '3.13.0'; /** * {@inheritdoc} From 7470472ccbb346928a248cf86fa1222cf28f3460 Mon Sep 17 00:00:00 2001 From: Christophe Coevoet Date: Tue, 18 Apr 2023 17:59:31 +0200 Subject: [PATCH 353/567] Upgrade the CI setup to stop using deprecation GHA features --- .github/workflows/build.yml | 13 ++++++------- 1 file changed, 6 insertions(+), 7 deletions(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 684402495..794257929 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -63,7 +63,7 @@ jobs: symfony-version: '6.0' steps: - - uses: actions/checkout@v2 + - uses: actions/checkout@v3 - name: Setup PHP uses: shivammathur/setup-php@v2 @@ -107,7 +107,7 @@ jobs: composer install --no-dev -o && box.phar build - - uses: actions/upload-artifact@v1 + - uses: actions/upload-artifact@v3 name: Publish the PHAR if: matrix.publish-phar == true with: @@ -118,7 +118,7 @@ jobs: runs-on: ubuntu-latest name: Static analysis steps: - - uses: actions/checkout@v2 + - uses: actions/checkout@v3 - name: Setup PHP uses: shivammathur/setup-php@v2 @@ -139,16 +139,15 @@ jobs: needs: tests if: github.event_name == 'release' steps: - - uses: actions/download-artifact@v1 + - uses: actions/download-artifact@v3 with: name: behat.phar path: . - name: Upload behat.phar - uses: actions/upload-release-asset@v1 + uses: basefas/upload-release-asset-action@v1 env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} with: - upload_url: ${{ github.event.release.upload_url }} + release_id: ${{ github.event.release.id }} asset_path: behat.phar asset_name: behat.phar - asset_content_type: application/zip From 391b7724b48e7fd5c5dfe4bb29c1082c9c21a828 Mon Sep 17 00:00:00 2001 From: Ciaran McNulty Date: Sun, 21 May 2023 15:46:47 +0100 Subject: [PATCH 354/567] Fix all mismatching parameter names In some places the mismatches make some sense, but I think it makes sense to remove where possible --- psalm.xml | 7 ++++++ .../Handler/ContextEnvironmentHandler.php | 18 +++++++------- .../Tester/EventDispatchingFeatureTester.php | 20 ++++++++-------- .../Tester/Runtime/RuntimeFeatureTester.php | 10 ++++---- .../Tester/Runtime/RuntimeScenarioTester.php | 2 +- .../Filter/DefinitionArgumentsTransformer.php | 24 +++++++++---------- .../SimpleArgumentTransformation.php | 4 ++-- .../ColumnBasedTableTransformation.php | 6 ++--- .../ReturnTypeTransformation.php | 2 +- .../RowBasedTableTransformation.php | 10 ++++---- .../Transformation/TableRowTransformation.php | 6 ++--- .../TokenNameAndReturnTypeTransformation.php | 6 ++--- .../TokenNameTransformation.php | 2 +- .../Argument/ConstructorArgumentOrganiser.php | 10 ++++---- .../Argument/PregMatchArgumentOrganiser.php | 6 ++--- .../TestworkEventDispatcherSymfonyLegacy.php | 5 ++-- 16 files changed, 73 insertions(+), 65 deletions(-) diff --git a/psalm.xml b/psalm.xml index 067db6cc4..3c845f461 100644 --- a/psalm.xml +++ b/psalm.xml @@ -46,5 +46,12 @@ + + + + + + + diff --git a/src/Behat/Behat/Context/Environment/Handler/ContextEnvironmentHandler.php b/src/Behat/Behat/Context/Environment/Handler/ContextEnvironmentHandler.php index d686400dd..7c610c9c6 100644 --- a/src/Behat/Behat/Context/Environment/Handler/ContextEnvironmentHandler.php +++ b/src/Behat/Behat/Context/Environment/Handler/ContextEnvironmentHandler.php @@ -105,24 +105,24 @@ public function supportsEnvironmentAndSubject(Environment $environment, $testSub /** * {@inheritdoc} */ - public function isolateEnvironment(Environment $uninitializedEnvironment, $testSubject = null) + public function isolateEnvironment(Environment $environment, $testSubject = null) { - if (!$uninitializedEnvironment instanceof UninitializedContextEnvironment) { + if (!$environment instanceof UninitializedContextEnvironment) { throw new EnvironmentIsolationException(sprintf( 'ContextEnvironmentHandler does not support isolation of `%s` environment.', - get_class($uninitializedEnvironment) - ), $uninitializedEnvironment); + get_class($environment) + ), $environment); } - $environment = new InitializedContextEnvironment($uninitializedEnvironment->getSuite()); - $resolvers = $this->resolverFactory->createArgumentResolvers($environment); + $initialisedEnvironment = new InitializedContextEnvironment($environment->getSuite()); + $resolvers = $this->resolverFactory->createArgumentResolvers($initialisedEnvironment); - foreach ($uninitializedEnvironment->getContextClassesWithArguments() as $class => $arguments) { + foreach ($environment->getContextClassesWithArguments() as $class => $arguments) { $context = $this->contextFactory->createContext($class, $arguments, $resolvers); - $environment->registerContext($context); + $initialisedEnvironment->registerContext($context); } - return $environment; + return $initialisedEnvironment; } /** diff --git a/src/Behat/Behat/EventDispatcher/Tester/EventDispatchingFeatureTester.php b/src/Behat/Behat/EventDispatcher/Tester/EventDispatchingFeatureTester.php index a0ce588f6..ef95f5d41 100644 --- a/src/Behat/Behat/EventDispatcher/Tester/EventDispatchingFeatureTester.php +++ b/src/Behat/Behat/EventDispatcher/Tester/EventDispatchingFeatureTester.php @@ -51,15 +51,15 @@ public function __construct(SpecificationTester $baseTester, EventDispatcherInte /** * {@inheritdoc} */ - public function setUp(Environment $env, $feature, $skip) + public function setUp(Environment $env, $spec, $skip) { - $event = new BeforeFeatureTested($env, $feature); + $event = new BeforeFeatureTested($env, $spec); $this->eventDispatcher->dispatch($event, $event::BEFORE); - $setup = $this->baseTester->setUp($env, $feature, $skip); + $setup = $this->baseTester->setUp($env, $spec, $skip); - $event = new AfterFeatureSetup($env, $feature, $setup); + $event = new AfterFeatureSetup($env, $spec, $setup); $this->eventDispatcher->dispatch($event, $event::AFTER_SETUP); @@ -69,23 +69,23 @@ public function setUp(Environment $env, $feature, $skip) /** * {@inheritdoc} */ - public function test(Environment $env, $feature, $skip) + public function test(Environment $env, $spec, $skip) { - return $this->baseTester->test($env, $feature, $skip); + return $this->baseTester->test($env, $spec, $skip); } /** * {@inheritdoc} */ - public function tearDown(Environment $env, $feature, $skip, TestResult $result) + public function tearDown(Environment $env, $spec, $skip, TestResult $result) { - $event = new BeforeFeatureTeardown($env, $feature, $result); + $event = new BeforeFeatureTeardown($env, $spec, $result); $this->eventDispatcher->dispatch($event, $event::BEFORE_TEARDOWN); - $teardown = $this->baseTester->tearDown($env, $feature, $skip, $result); + $teardown = $this->baseTester->tearDown($env, $spec, $skip, $result); - $event = new AfterFeatureTested($env, $feature, $result, $teardown); + $event = new AfterFeatureTested($env, $spec, $result, $teardown); $this->eventDispatcher->dispatch($event, $event::AFTER); diff --git a/src/Behat/Behat/Tester/Runtime/RuntimeFeatureTester.php b/src/Behat/Behat/Tester/Runtime/RuntimeFeatureTester.php index dcafc7ef2..bb7077877 100644 --- a/src/Behat/Behat/Tester/Runtime/RuntimeFeatureTester.php +++ b/src/Behat/Behat/Tester/Runtime/RuntimeFeatureTester.php @@ -73,16 +73,16 @@ public function setUp(Environment $env, $spec, $skip) /** * {@inheritdoc} */ - public function test(Environment $env, $feature, $skip = false) + public function test(Environment $env, $spec, $skip = false) { $results = array(); - foreach ($feature->getScenarios() as $scenario) { + foreach ($spec->getScenarios() as $scenario) { $tester = $scenario instanceof OutlineNode ? $this->outlineTester : $this->scenarioTester; - $setup = $tester->setUp($env, $feature, $scenario, $skip); + $setup = $tester->setUp($env, $spec, $scenario, $skip); $localSkip = !$setup->isSuccessful() || $skip; - $testResult = $tester->test($env, $feature, $scenario, $localSkip); - $teardown = $tester->tearDown($env, $feature, $scenario, $localSkip, $testResult); + $testResult = $tester->test($env, $spec, $scenario, $localSkip); + $teardown = $tester->tearDown($env, $spec, $scenario, $localSkip, $testResult); $integerResult = new IntegerTestResult($testResult->getResultCode()); $results[] = new TestWithSetupResult($setup, $integerResult, $teardown); diff --git a/src/Behat/Behat/Tester/Runtime/RuntimeScenarioTester.php b/src/Behat/Behat/Tester/Runtime/RuntimeScenarioTester.php index 08b8ca951..0c29fa7f9 100644 --- a/src/Behat/Behat/Tester/Runtime/RuntimeScenarioTester.php +++ b/src/Behat/Behat/Tester/Runtime/RuntimeScenarioTester.php @@ -54,7 +54,7 @@ public function __construct(StepContainerTester $containerTester, BackgroundTest /** * {@inheritdoc} */ - public function setUp(Environment $env, FeatureNode $feature, Scenario $example, $skip) + public function setUp(Environment $env, FeatureNode $feature, Scenario $scenario, $skip) { return new SuccessfulSetup(); } diff --git a/src/Behat/Behat/Transformation/Call/Filter/DefinitionArgumentsTransformer.php b/src/Behat/Behat/Transformation/Call/Filter/DefinitionArgumentsTransformer.php index d6cde918d..0f0b42745 100644 --- a/src/Behat/Behat/Transformation/Call/Filter/DefinitionArgumentsTransformer.php +++ b/src/Behat/Behat/Transformation/Call/Filter/DefinitionArgumentsTransformer.php @@ -49,19 +49,19 @@ public function supportsCall(Call $call) /** * {@inheritdoc} */ - public function filterCall(Call $definitionCall) + public function filterCall(Call $call) { - if (!$definitionCall instanceof DefinitionCall) { + if (!$call instanceof DefinitionCall) { throw new UnsupportedCallException(sprintf( 'DefinitionArgumentTransformer can not filter `%s` call.', - get_class($definitionCall) - ), $definitionCall); + get_class($call) + ), $call); } $newArguments = array(); $transformed = false; - foreach ($definitionCall->getArguments() as $index => $value) { - $newValue = $this->transformArgument($definitionCall, $index, $value); + foreach ($call->getArguments() as $index => $value) { + $newValue = $this->transformArgument($call, $index, $value); if ($newValue !== $value) { $transformed = true; @@ -71,16 +71,16 @@ public function filterCall(Call $definitionCall) } if (!$transformed) { - return $definitionCall; + return $call; } return new DefinitionCall( - $definitionCall->getEnvironment(), - $definitionCall->getFeature(), - $definitionCall->getStep(), - $definitionCall->getCallee(), + $call->getEnvironment(), + $call->getFeature(), + $call->getStep(), + $call->getCallee(), $newArguments, - $definitionCall->getErrorReportingLevel() + $call->getErrorReportingLevel() ); } diff --git a/src/Behat/Behat/Transformation/SimpleArgumentTransformation.php b/src/Behat/Behat/Transformation/SimpleArgumentTransformation.php index 16530c3f7..d11c4ff19 100644 --- a/src/Behat/Behat/Transformation/SimpleArgumentTransformation.php +++ b/src/Behat/Behat/Transformation/SimpleArgumentTransformation.php @@ -43,11 +43,11 @@ public function getPriority(); * * @param DefinitionCall $definitionCall * @param integer|string $argumentIndex - * @param mixed $argumentValue + * @param mixed $argumentArgumentValue * * @return bool */ - public function supportsDefinitionAndArgument(DefinitionCall $definitionCall, $argumentIndex, $argumentValue); + public function supportsDefinitionAndArgument(DefinitionCall $definitionCall, $argumentIndex, $argumentArgumentValue); /** * Transforms argument value using transformation and returns a new one. diff --git a/src/Behat/Behat/Transformation/Transformation/ColumnBasedTableTransformation.php b/src/Behat/Behat/Transformation/Transformation/ColumnBasedTableTransformation.php index c26df56d2..eda2ff2a4 100644 --- a/src/Behat/Behat/Transformation/Transformation/ColumnBasedTableTransformation.php +++ b/src/Behat/Behat/Transformation/Transformation/ColumnBasedTableTransformation.php @@ -57,13 +57,13 @@ public function __construct($pattern, $callable, $description = null) /** * {@inheritdoc} */ - public function supportsDefinitionAndArgument(DefinitionCall $definitionCall, $argumentIndex, $argumentValue) + public function supportsDefinitionAndArgument(DefinitionCall $definitionCall, $argumentIndex, $argumentArgumentValue) { - if (!$argumentValue instanceof TableNode) { + if (!$argumentArgumentValue instanceof TableNode) { return false; }; - return $this->pattern === 'table:' . implode(',', $argumentValue->getRow(0)) + return $this->pattern === 'table:' . implode(',', $argumentArgumentValue->getRow(0)) || $this->pattern === 'table:*'; } diff --git a/src/Behat/Behat/Transformation/Transformation/ReturnTypeTransformation.php b/src/Behat/Behat/Transformation/Transformation/ReturnTypeTransformation.php index dd2e9c08c..79ed7960a 100644 --- a/src/Behat/Behat/Transformation/Transformation/ReturnTypeTransformation.php +++ b/src/Behat/Behat/Transformation/Transformation/ReturnTypeTransformation.php @@ -60,7 +60,7 @@ public function __construct($pattern, $callable, $description = null) /** * {@inheritdoc} */ - public function supportsDefinitionAndArgument(DefinitionCall $definitionCall, $argumentIndex, $argumentValue) + public function supportsDefinitionAndArgument(DefinitionCall $definitionCall, $argumentIndex, $argumentArgumentValue) { $returnClass = self::getReturnClass($this->getReflection()); diff --git a/src/Behat/Behat/Transformation/Transformation/RowBasedTableTransformation.php b/src/Behat/Behat/Transformation/Transformation/RowBasedTableTransformation.php index a5b1c5123..aeb277b8d 100644 --- a/src/Behat/Behat/Transformation/Transformation/RowBasedTableTransformation.php +++ b/src/Behat/Behat/Transformation/Transformation/RowBasedTableTransformation.php @@ -58,26 +58,26 @@ public function __construct($pattern, $callable, $description = null) /** * {@inheritdoc} */ - public function supportsDefinitionAndArgument(DefinitionCall $definitionCall, $argumentIndex, $value) + public function supportsDefinitionAndArgument(DefinitionCall $definitionCall, $argumentIndex, $argumentArgumentValue) { - if (!$value instanceof TableNode) { + if (!$argumentArgumentValue instanceof TableNode) { return false; }; // What we're doing here is checking that we have a 2 column table. // This bit checks we have two columns try { - $value->getColumn(1); + $argumentArgumentValue->getColumn(1); } catch (NodeException $e) { return false; } // And here we check we don't have a 3rd column try { - $value->getColumn(2); + $argumentArgumentValue->getColumn(2); } catch (NodeException $e) { // Once we know the table could be a row table, we check against the pattern. - return $this->pattern === 'rowtable:' . implode(',', $value->getColumn(0)); + return $this->pattern === 'rowtable:' . implode(',', $argumentArgumentValue->getColumn(0)); } return false; diff --git a/src/Behat/Behat/Transformation/Transformation/TableRowTransformation.php b/src/Behat/Behat/Transformation/Transformation/TableRowTransformation.php index 1a71c0b7b..37143d262 100644 --- a/src/Behat/Behat/Transformation/Transformation/TableRowTransformation.php +++ b/src/Behat/Behat/Transformation/Transformation/TableRowTransformation.php @@ -57,13 +57,13 @@ public function __construct($pattern, $callable, $description = null) /** * {@inheritdoc} */ - public function supportsDefinitionAndArgument(DefinitionCall $definitionCall, $argumentIndex, $argumentValue) + public function supportsDefinitionAndArgument(DefinitionCall $definitionCall, $argumentIndex, $argumentArgumentValue) { - if (!$argumentValue instanceof TableNode) { + if (!$argumentArgumentValue instanceof TableNode) { return false; }; - return $this->pattern === 'row:' . implode(',', $argumentValue->getRow(0)); + return $this->pattern === 'row:' . implode(',', $argumentArgumentValue->getRow(0)); } /** diff --git a/src/Behat/Behat/Transformation/Transformation/TokenNameAndReturnTypeTransformation.php b/src/Behat/Behat/Transformation/Transformation/TokenNameAndReturnTypeTransformation.php index 32f954d65..c0086213a 100644 --- a/src/Behat/Behat/Transformation/Transformation/TokenNameAndReturnTypeTransformation.php +++ b/src/Behat/Behat/Transformation/Transformation/TokenNameAndReturnTypeTransformation.php @@ -60,10 +60,10 @@ public function __construct($pattern, $callable, $description = null) /** * {@inheritdoc} */ - public function supportsDefinitionAndArgument(DefinitionCall $definitionCall, $argumentIndex, $argumentValue) + public function supportsDefinitionAndArgument(DefinitionCall $definitionCall, $argumentIndex, $argumentArgumentValue) { - return $this->tokenTransformation->supportsDefinitionAndArgument($definitionCall, $argumentIndex, $argumentValue) - && $this->returnTransformation->supportsDefinitionAndArgument($definitionCall, $argumentIndex, $argumentValue); + return $this->tokenTransformation->supportsDefinitionAndArgument($definitionCall, $argumentIndex, $argumentArgumentValue) + && $this->returnTransformation->supportsDefinitionAndArgument($definitionCall, $argumentIndex, $argumentArgumentValue); } /** diff --git a/src/Behat/Behat/Transformation/Transformation/TokenNameTransformation.php b/src/Behat/Behat/Transformation/Transformation/TokenNameTransformation.php index a64d86e64..807ffdf67 100644 --- a/src/Behat/Behat/Transformation/Transformation/TokenNameTransformation.php +++ b/src/Behat/Behat/Transformation/Transformation/TokenNameTransformation.php @@ -57,7 +57,7 @@ public function __construct($pattern, $callable, $description = null) /** * {@inheritdoc} */ - public function supportsDefinitionAndArgument(DefinitionCall $definitionCall, $argumentIndex, $argumentValue) + public function supportsDefinitionAndArgument(DefinitionCall $definitionCall, $argumentIndex, $argumentArgumentValue) { return ':' . $argumentIndex === $this->pattern; } diff --git a/src/Behat/Testwork/Argument/ConstructorArgumentOrganiser.php b/src/Behat/Testwork/Argument/ConstructorArgumentOrganiser.php index 5ab612713..7dc01def6 100644 --- a/src/Behat/Testwork/Argument/ConstructorArgumentOrganiser.php +++ b/src/Behat/Testwork/Argument/ConstructorArgumentOrganiser.php @@ -40,21 +40,21 @@ public function __construct(ArgumentOrganiser $organiser) /** * {@inheritdoc} */ - public function organiseArguments(ReflectionFunctionAbstract $constructor, array $arguments) + public function organiseArguments(ReflectionFunctionAbstract $function, array $arguments) { - if (!$constructor instanceof ReflectionMethod) { + if (!$function instanceof ReflectionMethod) { throw new UnsupportedFunctionException(sprintf( 'ConstructorArgumentOrganiser can only work with ReflectionMethod, but `%s` given.', - get_class($constructor) + get_class($function) )); } $organisedArguments = $this->baseOrganiser->organiseArguments( - $constructor, + $function, $arguments ); - $this->validateArguments($constructor, $arguments, $organisedArguments); + $this->validateArguments($function, $arguments, $organisedArguments); return $organisedArguments; } diff --git a/src/Behat/Testwork/Argument/PregMatchArgumentOrganiser.php b/src/Behat/Testwork/Argument/PregMatchArgumentOrganiser.php index 8a03b884f..a85c426a7 100644 --- a/src/Behat/Testwork/Argument/PregMatchArgumentOrganiser.php +++ b/src/Behat/Testwork/Argument/PregMatchArgumentOrganiser.php @@ -37,11 +37,11 @@ public function __construct(ArgumentOrganiser $organiser) /** * {@inheritdoc} */ - public function organiseArguments(ReflectionFunctionAbstract $function, array $match) + public function organiseArguments(ReflectionFunctionAbstract $function, array $arguments) { - $arguments = $this->cleanupMatchDuplicates($match); + $cleanedArguments = $this->cleanupMatchDuplicates($arguments); - return $this->baseOrganiser->organiseArguments($function, $arguments); + return $this->baseOrganiser->organiseArguments($function, $cleanedArguments); } /** diff --git a/src/Behat/Testwork/EventDispatcher/TestworkEventDispatcherSymfonyLegacy.php b/src/Behat/Testwork/EventDispatcher/TestworkEventDispatcherSymfonyLegacy.php index 3a41ba6d5..0503f5b64 100644 --- a/src/Behat/Testwork/EventDispatcher/TestworkEventDispatcherSymfonyLegacy.php +++ b/src/Behat/Testwork/EventDispatcher/TestworkEventDispatcherSymfonyLegacy.php @@ -4,6 +4,7 @@ namespace Behat\Testwork\EventDispatcher; +use Symfony\Component\EventDispatcher\Event; use Symfony\Component\EventDispatcher\EventDispatcher; /** @@ -24,7 +25,7 @@ final class TestworkEventDispatcherSymfonyLegacy extends EventDispatcher * {@inheritdoc} * */ - public function dispatch($eventName, \Symfony\Component\EventDispatcher\Event $event = null) + public function dispatch($eventName, Event $event = null) { trigger_error( 'Class "\Behat\Testwork\EventDispatcher\TestworkEventDispatcherSymfonyLegacy" is deprecated ' . @@ -35,7 +36,7 @@ public function dispatch($eventName, \Symfony\Component\EventDispatcher\Event $e if (null === $event) { /** @psalm-suppress UndefinedClass */ - $event = new \Symfony\Component\EventDispatcher\Event(); + $event = new Event(); } if (method_exists($event, 'setName')) { $event->setName($eventName); From 7d478637ae9cef1a89f0efd1db6cd8ac53e4de94 Mon Sep 17 00:00:00 2001 From: Ciaran McNulty Date: Sun, 21 May 2023 16:02:04 +0100 Subject: [PATCH 355/567] Exclude MethodSignatureMismatch errors and bump psalm support level to 7 --- psalm.xml | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/psalm.xml b/psalm.xml index 3c845f461..34d6caeae 100644 --- a/psalm.xml +++ b/psalm.xml @@ -1,6 +1,6 @@ - + + + + + + From 04fd50148c39f8047416eac402f51cd1159a6740 Mon Sep 17 00:00:00 2001 From: Ciaran McNulty Date: Sun, 21 May 2023 16:14:57 +0100 Subject: [PATCH 356/567] Run SA with the lowest supported PHP version --- .github/workflows/build.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 794257929..680a157fa 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -123,7 +123,7 @@ jobs: - name: Setup PHP uses: shivammathur/setup-php@v2 with: - php-version: 8.2 + php-version: 7.2 ini-values: "zend.exception_ignore_args=Off" coverage: none From e5b8fd4c693a8d68dd6966b3c521666745e1ab8c Mon Sep 17 00:00:00 2001 From: jrfnl Date: Mon, 28 Aug 2023 17:27:18 +0200 Subject: [PATCH 357/567] GH Actions: start running the tests against PHP 8.3 PHP 8.3 is nearing the RC phase. As this tool is used in the build processes of plenty of other PHP package, I believe it would be beneficial to start supporting PHP 8.3 officially sooner rather than later. This commit adds PHP 8.3 to the build matrix to start running the tests against PHP 8.3. As the build currently passes against PHP 8.3, I've not added a `continue-on-error` for PHP 8.3. --- .github/workflows/build.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 680a157fa..78c976980 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -18,7 +18,7 @@ jobs: strategy: fail-fast: false matrix: - php: [7.2, 7.3, 7.4, 8.0, 8.1, 8.2] + php: [7.2, 7.3, 7.4, 8.0, 8.1, 8.2, 8.3] os: [ubuntu-latest] composer-mode: [update] symfony-version: [''] @@ -82,7 +82,7 @@ jobs: if: matrix.composer-mode == 'update' env: SYMFONY_REQUIRE: ${{ matrix.symfony-version }}.* - run: composer update + run: composer update ${{ matrix.php == '8.3' && '--ignore-platform-req=php+' || '' }} - name: Install lowest dependencies if: matrix.composer-mode == 'lowest' From 693aa07b873d35e571b4f210028f0e1897e9bd4d Mon Sep 17 00:00:00 2001 From: Simon Auch Date: Sat, 23 Sep 2023 20:49:09 +0000 Subject: [PATCH 358/567] incorporate review comments --- .../Node/EventListener/JUnit/JUnitFeatureElementListener.php | 5 ++--- src/Behat/Testwork/Output/Printer/JUnitOutputPrinter.php | 2 +- 2 files changed, 3 insertions(+), 4 deletions(-) diff --git a/src/Behat/Behat/Output/Node/EventListener/JUnit/JUnitFeatureElementListener.php b/src/Behat/Behat/Output/Node/EventListener/JUnit/JUnitFeatureElementListener.php index 1691f6a6c..febd11533 100644 --- a/src/Behat/Behat/Output/Node/EventListener/JUnit/JUnitFeatureElementListener.php +++ b/src/Behat/Behat/Output/Node/EventListener/JUnit/JUnitFeatureElementListener.php @@ -54,7 +54,7 @@ final class JUnitFeatureElementListener implements EventListener */ private $afterStepTestedEvents = array(); /** - * @var AfterSetup[] + * @var AfterStepSetup[] */ private $afterStepSetupEvents = array(); @@ -118,7 +118,7 @@ private function captureStepEvent(Event $event) } /** - * Captures scenario tested event. + * Prints the scenario tested event. * * @param Formatter $formatter * @param Event $event @@ -137,7 +137,6 @@ private function printScenarioEvent(Formatter $formatter, Event $event) $event->getFeature()->getFile() ); - /** @var AfterStepSetup $afterStepSetup */ foreach ($this->afterStepSetupEvents as $afterStepSetup) { $this->setupPrinter->printSetup($formatter, $afterStepSetup->getSetup()); } diff --git a/src/Behat/Testwork/Output/Printer/JUnitOutputPrinter.php b/src/Behat/Testwork/Output/Printer/JUnitOutputPrinter.php index bbc76eab6..c7fc8716e 100644 --- a/src/Behat/Testwork/Output/Printer/JUnitOutputPrinter.php +++ b/src/Behat/Testwork/Output/Printer/JUnitOutputPrinter.php @@ -90,7 +90,7 @@ public function addTestsuite(array $testsuiteAttributes = array()) * * @param array $testsuiteAttributes */ - public function extendTestsuiteAttributes(array $testsuiteAttributes = array()) + public function extendTestsuiteAttributes(array $testsuiteAttributes) { $this->addAttributesToNode($this->currentTestsuite, $testsuiteAttributes); } From 68dbf63410243cabe414723e319853d07da7f63c Mon Sep 17 00:00:00 2001 From: David Maicher Date: Thu, 30 Nov 2023 12:07:55 +0100 Subject: [PATCH 359/567] add compatibility with Symfony 7 --- .github/workflows/build.yml | 9 +++++++++ composer.json | 14 +++++++------- src/Behat/Testwork/Cli/Application.php | 4 ++-- src/Behat/Testwork/Cli/Command.php | 2 +- src/Behat/Testwork/Cli/DebugCommand.php | 2 +- src/Behat/Testwork/Cli/DumpReferenceCommand.php | 2 +- 6 files changed, 21 insertions(+), 12 deletions(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 78c976980..9ed80ac68 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -61,6 +61,10 @@ jobs: os: ubuntu-latest composer-mode: update symfony-version: '6.0' + - php: 8.2 + os: ubuntu-latest + composer-mode: update + symfony-version: '7.0' steps: - uses: actions/checkout@v3 @@ -78,6 +82,11 @@ jobs: composer config --global --no-plugins allow-plugins.symfony/flex true && composer global require symfony/flex + # until psalm is updated to v5 which is compatible with Symfony 7 + - name: Remove vimeo/psalm + if: matrix.symfony-version == '7.0' + run: composer remove vimeo/psalm --no-update --dev + - name: Install latest dependencies if: matrix.composer-mode == 'update' env: diff --git a/composer.json b/composer.json index 333713bf4..077fc7850 100644 --- a/composer.json +++ b/composer.json @@ -18,17 +18,17 @@ "ext-mbstring": "*", "behat/gherkin": "^4.9.0", "behat/transliterator": "^1.2", - "symfony/console": "^4.4 || ^5.0 || ^6.0", - "symfony/config": "^4.4 || ^5.0 || ^6.0", - "symfony/dependency-injection": "^4.4 || ^5.0 || ^6.0", - "symfony/event-dispatcher": "^4.4 || ^5.0 || ^6.0", - "symfony/translation": "^4.4 || ^5.0 || ^6.0", - "symfony/yaml": "^4.4 || ^5.0 || ^6.0", + "symfony/console": "^4.4 || ^5.0 || ^6.0 || ^7.0", + "symfony/config": "^4.4 || ^5.0 || ^6.0 || ^7.0", + "symfony/dependency-injection": "^4.4 || ^5.0 || ^6.0 || ^7.0", + "symfony/event-dispatcher": "^4.4 || ^5.0 || ^6.0 || ^7.0", + "symfony/translation": "^4.4 || ^5.0 || ^6.0 || ^7.0", + "symfony/yaml": "^4.4 || ^5.0 || ^6.0 || ^7.0", "psr/container": "^1.0 || ^2.0" }, "require-dev": { - "symfony/process": "^4.4 || ^5.0 || ^6.0", + "symfony/process": "^4.4 || ^5.0 || ^6.0 || ^7.0", "phpunit/phpunit": "^8.5 || ^9.0", "herrera-io/box": "~1.6.1", "vimeo/psalm": "^4.8", diff --git a/src/Behat/Testwork/Cli/Application.php b/src/Behat/Testwork/Cli/Application.php index ad57803d5..080fee021 100644 --- a/src/Behat/Testwork/Cli/Application.php +++ b/src/Behat/Testwork/Cli/Application.php @@ -95,7 +95,7 @@ public function getDefaultInputDefinition(): InputDefinition * * @return integer 0 if everything went fine, or an error code */ - public function doRun(InputInterface $input, OutputInterface $output) + public function doRun(InputInterface $input, OutputInterface $output): int { // xdebug's default nesting level of 100 is not enough if (extension_loaded('xdebug') @@ -223,7 +223,7 @@ protected function getCommandName(InputInterface $input): string return $this->getName(); } - protected function configureIO(InputInterface $input, OutputInterface $output) + protected function configureIO(InputInterface $input, OutputInterface $output): void { if (true === $input->hasParameterOption(array('--colors'))) { $output->setDecorated(true); diff --git a/src/Behat/Testwork/Cli/Command.php b/src/Behat/Testwork/Cli/Command.php index ae53dfa99..35d085962 100644 --- a/src/Behat/Testwork/Cli/Command.php +++ b/src/Behat/Testwork/Cli/Command.php @@ -57,7 +57,7 @@ protected function configure() * * @return integer Return code of one of the processors or 0 if none of them returned integer */ - protected function execute(InputInterface $input, OutputInterface $output) + protected function execute(InputInterface $input, OutputInterface $output): int { foreach ($this->controllers as $controller) { if (is_int($return = $controller->execute($input, $output))) { diff --git a/src/Behat/Testwork/Cli/DebugCommand.php b/src/Behat/Testwork/Cli/DebugCommand.php index d24ffd5d0..8abe338a0 100644 --- a/src/Behat/Testwork/Cli/DebugCommand.php +++ b/src/Behat/Testwork/Cli/DebugCommand.php @@ -58,7 +58,7 @@ public function __construct( /** * {@inheritdoc} */ - protected function execute(InputInterface $input, OutputInterface $output) + protected function execute(InputInterface $input, OutputInterface $output): int { $output->writeln(sprintf('%s version %s', $this->application->getName(), $this->application->getVersion())); diff --git a/src/Behat/Testwork/Cli/DumpReferenceCommand.php b/src/Behat/Testwork/Cli/DumpReferenceCommand.php index e4242bbb5..a8ddd6274 100644 --- a/src/Behat/Testwork/Cli/DumpReferenceCommand.php +++ b/src/Behat/Testwork/Cli/DumpReferenceCommand.php @@ -45,7 +45,7 @@ public function __construct(ExtensionManager $extensionManager) /** * {@inheritdoc} */ - protected function execute(InputInterface $input, OutputInterface $output) + protected function execute(InputInterface $input, OutputInterface $output): int { $dumper = new YamlReferenceDumper(); $configTree = new ConfigurationTree(); From a04abcb7b68ff4860c9fb1a21de41134fc88ca80 Mon Sep 17 00:00:00 2001 From: "vasily.pyatykh" Date: Thu, 18 Jan 2024 17:50:49 +0100 Subject: [PATCH 360/567] fix a bug around maximum token length in turnip notation implementation (maximum was 31, must be 32) --- features/definitions_patterns.feature | 2 +- .../Behat/Definition/Pattern/Policy/TurnipPatternPolicy.php | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/features/definitions_patterns.feature b/features/definitions_patterns.feature index bc62dc4a3..50b862ee1 100644 --- a/features/definitions_patterns.feature +++ b/features/definitions_patterns.feature @@ -220,7 +220,7 @@ Feature: Step Definition Pattern class FeatureContext implements Context { /** - * @Given I provide parameter :too1234567891123456789012345678901 + * @Given I provide parameter :too12345678911234567890123456789012 */ public function parameterCouldBeNull($param) {} } diff --git a/src/Behat/Behat/Definition/Pattern/Policy/TurnipPatternPolicy.php b/src/Behat/Behat/Definition/Pattern/Policy/TurnipPatternPolicy.php index aa37f9e62..a9ceb9d06 100644 --- a/src/Behat/Behat/Definition/Pattern/Policy/TurnipPatternPolicy.php +++ b/src/Behat/Behat/Definition/Pattern/Policy/TurnipPatternPolicy.php @@ -140,7 +140,7 @@ private function replaceTokensWithRegexCaptureGroups($regex) private function replaceTokenWithRegexCaptureGroup($tokenMatch) { - if (strlen($tokenMatch[1]) >= 32) { + if (strlen($tokenMatch[1]) > 32) { throw new InvalidPatternException( "Token name should not exceed 32 characters, but `{$tokenMatch[1]}` was used." ); From dfaa04d46816418e2d7f05a7d71489536a52567e Mon Sep 17 00:00:00 2001 From: Christian Sciberras Date: Sun, 3 Mar 2024 21:03:04 +0100 Subject: [PATCH 361/567] Improve JUnit test duration precision --- .../JUnit/JUnitDurationListener.php | 35 +++++++++++-------- 1 file changed, 21 insertions(+), 14 deletions(-) diff --git a/src/Behat/Behat/Output/Node/EventListener/JUnit/JUnitDurationListener.php b/src/Behat/Behat/Output/Node/EventListener/JUnit/JUnitDurationListener.php index 12604d5b7..2874087be 100644 --- a/src/Behat/Behat/Output/Node/EventListener/JUnit/JUnitDurationListener.php +++ b/src/Behat/Behat/Output/Node/EventListener/JUnit/JUnitDurationListener.php @@ -15,13 +15,17 @@ final class JUnitDurationListener implements EventListener { + /** @var array */ private $scenarioTimerStore = array(); + /** @var array */ private $featureTimerStore = array(); + /** @var array */ private $resultStore = array(); + /** @var array */ private $featureResultStore = array(); /** @inheritdoc */ - public function listenEvent(Formatter $formatter, Event $event, $eventName) + public function listenEvent(Formatter $formatter, Event $event, $eventName): void { $this->captureBeforeScenarioEvent($event); $this->captureBeforeFeatureTested($event); @@ -29,19 +33,23 @@ public function listenEvent(Formatter $formatter, Event $event, $eventName) $this->captureAfterFeatureEvent($event); } - public function getDuration(ScenarioLikeInterface $scenario) + public function getDuration(ScenarioLikeInterface $scenario): string { $key = $this->getHash($scenario); - return array_key_exists($key, $this->resultStore) ? $this->resultStore[$key] : ''; + return array_key_exists($key, $this->resultStore) + ? number_format($this->resultStore[$key], 3, '.', '') + : ''; } - public function getFeatureDuration(FeatureNode $feature) + public function getFeatureDuration(FeatureNode $feature): string { $key = $this->getHash($feature); - return array_key_exists($key, $this->featureResultStore) ? $this->featureResultStore[$key] : ''; + return array_key_exists($key, $this->featureResultStore) + ? number_format($this->featureResultStore[$key], 3, '.', '') + : ''; } - private function captureBeforeFeatureTested(Event $event) + private function captureBeforeFeatureTested(Event $event): void { if (!$event instanceof BeforeFeatureTested) { return; @@ -50,7 +58,7 @@ private function captureBeforeFeatureTested(Event $event) $this->featureTimerStore[$this->getHash($event->getFeature())] = $this->startTimer(); } - private function captureBeforeScenarioEvent(Event $event) + private function captureBeforeScenarioEvent(Event $event): void { if (!$event instanceof BeforeScenarioTested) { return; @@ -59,7 +67,7 @@ private function captureBeforeScenarioEvent(Event $event) $this->scenarioTimerStore[$this->getHash($event->getScenario())] = $this->startTimer(); } - private function captureAfterScenarioEvent(Event $event) + private function captureAfterScenarioEvent(Event $event): void { if (!$event instanceof AfterScenarioTested) { return; @@ -69,11 +77,11 @@ private function captureAfterScenarioEvent(Event $event) $timer = $this->scenarioTimerStore[$key]; if ($timer instanceof Timer) { $timer->stop(); - $this->resultStore[$key] = round($timer->getTime()); + $this->resultStore[$key] = $timer->getTime(); } } - private function captureAfterFeatureEvent(Event $event) + private function captureAfterFeatureEvent(Event $event): void { if (!$event instanceof AfterFeatureTested) { return; @@ -83,17 +91,16 @@ private function captureAfterFeatureEvent(Event $event) $timer = $this->featureTimerStore[$key]; if ($timer instanceof Timer) { $timer->stop(); - $this->featureResultStore[$key] = round($timer->getTime()); + $this->featureResultStore[$key] = $timer->getTime(); } } - private function getHash(KeywordNodeInterface $node) + private function getHash(KeywordNodeInterface $node): string { return spl_object_hash($node); } - /** @return Timer */ - private function startTimer() + private function startTimer(): Timer { $timer = new Timer(); $timer->start(); From 82e11de7becf465776b613c450553e90c9586ab6 Mon Sep 17 00:00:00 2001 From: Andreas Heigl Date: Sun, 10 Mar 2024 09:53:10 +0100 Subject: [PATCH 362/567] Use shivamaturs tool installer to install box That way we do not have to install box ourselves which simplifies the PHAR creation --- .github/workflows/build.yml | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 9ed80ac68..826153be7 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -75,6 +75,7 @@ jobs: php-version: "${{ matrix.php }}" ini-values: "phar.readonly=0,zend.exception_ignore_args=Off" coverage: none + tools: box - name: Install symfony/flex if: matrix.symfony-version != '' @@ -110,11 +111,8 @@ jobs: - name: Build the PHAR if: matrix.publish-phar == true run: | - curl -LSs https://box-project.github.io/box2/installer.php | php && - export PATH=.:$PATH && - rm -Rf ./vendor && composer install --no-dev -o && - box.phar build + box build - uses: actions/upload-artifact@v3 name: Publish the PHAR From 80e7c6dca4eecf43872cbf39f0b5e855a1cc7f0c Mon Sep 17 00:00:00 2001 From: Andreas Heigl Date: Mon, 11 Mar 2024 07:59:42 +0100 Subject: [PATCH 363/567] Update box-config This removes some defaults that are no longer necessary as well as the files config that stopped Box from applying it'S own logic of figuring out what is necessary. This should now produce a working PHAR file that is similar to the one based on box2 but now with the latest box-releases so that bugfixes are much easier to be applied. This still is - similar to the previous version - not a scoped build so that there might be circumstances where the executed code uses code from the PHAR file instead of from their own code. This though is a separate issue. --- box.json | 15 +++------------ 1 file changed, 3 insertions(+), 12 deletions(-) diff --git a/box.json b/box.json index 63118b841..144879964 100644 --- a/box.json +++ b/box.json @@ -1,19 +1,10 @@ { - "chmod": "0755", - "directories": ["src"], "files": [ "LICENSE", "i18n.php" ], - "finder": [ - { - "name": ["*.php", "*.xsd", "LICENSE"], - "exclude": ["Tests", "tests", "sebastian", "phpunit", "phpspec", "process", "filesystem"], - "in": "vendor" - } + "compactors": [ + "KevinGH\\Box\\Compactor\\Php" ], - "compactors": "Herrera\\Box\\Compactor\\Php", - "main": "bin/behat", - "output": "behat.phar", - "stub": true + "output": "behat.phar" } From 108c8f528b10fd6af601c0a4da452d45c6d15209 Mon Sep 17 00:00:00 2001 From: Andreas Heigl Date: Wed, 13 Mar 2024 13:17:44 +0100 Subject: [PATCH 364/567] Add build-step to also test the PHAR It will only check whether the PHAR file can be basically executed. It is not testing every functionality of the PHAR! --- .github/workflows/build.yml | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 826153be7..4e3ebb8e0 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -114,6 +114,11 @@ jobs: composer install --no-dev -o && box build + - name: Test the PHAR + if: matrix.publish-phar == true + run: | + behat.phar --version + - uses: actions/upload-artifact@v3 name: Publish the PHAR if: matrix.publish-phar == true From 575b02a0febe14b86dc289f490a5a0590231da89 Mon Sep 17 00:00:00 2001 From: Andreas Heigl Date: Wed, 13 Mar 2024 13:38:46 +0100 Subject: [PATCH 365/567] Use the latest stable release to biuld the PHAR Previously that was the lowest possible PHP-version. But as the build-tools only work with a more recent version of PHP and the PHP-version used to create the PHAR has no impact on the PHAR itself it makes sense to use the latest (or at least a rather recent) PHP-Version --- .github/workflows/build.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 4e3ebb8e0..9b2dbb9cd 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -23,8 +23,8 @@ jobs: composer-mode: [update] symfony-version: [''] include: - # Get the existing 7.2 to publish the phar - - php: 7.2 + # Get the latest stable PHP to publish the phar + - php: 8.3 os: ubuntu-latest composer-mode: update publish-phar: true From 90776271cf092e11874ced6cc728930c142ce754 Mon Sep 17 00:00:00 2001 From: Andreas Heigl Date: Sat, 16 Mar 2024 06:56:10 +0100 Subject: [PATCH 366/567] Move PHAR build into separate build-step This commit moves building the PHAR file out of the test-suite and moves it into it's own step that requires all biulds to pass to be executed. That makes it for one thing easier to make sure that all tests in all versions of PHP work before creating the PHAR and it also allows to easier optimize the build of the PHAR without interfering with tests. The build-steps from the test-part were taken over into the build-phar part and appropriately extended. Also this makes sure that the PHAr is build based on the PHP7.2 version so taht it can be ran in all supported PHP-Versions. --- .github/workflows/build.yml | 55 +++++++++++++++++++++++-------------- 1 file changed, 34 insertions(+), 21 deletions(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 9b2dbb9cd..b45c591a0 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -14,7 +14,7 @@ jobs: defaults: run: shell: bash - name: Build and test + name: Test strategy: fail-fast: false matrix: @@ -75,7 +75,6 @@ jobs: php-version: "${{ matrix.php }}" ini-values: "phar.readonly=0,zend.exception_ignore_args=Off" coverage: none - tools: box - name: Install symfony/flex if: matrix.symfony-version != '' @@ -108,24 +107,6 @@ jobs: if: matrix.php >= 8.0 run: ./bin/behat -fprogress --strict --tags=@php8 - - name: Build the PHAR - if: matrix.publish-phar == true - run: | - composer install --no-dev -o && - box build - - - name: Test the PHAR - if: matrix.publish-phar == true - run: | - behat.phar --version - - - uses: actions/upload-artifact@v3 - name: Publish the PHAR - if: matrix.publish-phar == true - with: - name: behat.phar - path: behat.phar - static-analysis: runs-on: ubuntu-latest name: Static analysis @@ -145,10 +126,42 @@ jobs: - name: Run Psalm run: ./vendor/bin/psalm --output-format=github + build-phar: + needs: tests + runs-on: ubuntu-latest + name: Build PHAR file + steps: + - uses: actions/checkout@v3 + + - name: Setup PHP + uses: shivammathur/setup-php@v2 + with: + php-version: "8.3" + ini-values: "phar.readonly=0,zend.exception_ignore_args=Off" + coverage: none + tools: box + + - name: Build the PHAR + run: | + composer config platform.php ^7.2.34 + composer update --no-dev -o + box build + + - name: Test the PHAR + run: | + behat.phar --version + + - uses: actions/upload-artifact@v3 + name: Upload PHAR artifact + with: + name: behat.phar + path: behat.phar + + publish-phar: runs-on: ubuntu-latest name: Publish the PHAR for release - needs: tests + needs: build-phar if: github.event_name == 'release' steps: - uses: actions/download-artifact@v3 From 7850f3d2452cfe2d77638d21f7d3ec19c0fdaf4c Mon Sep 17 00:00:00 2001 From: Carlos Granados Date: Mon, 15 Apr 2024 11:09:19 +0200 Subject: [PATCH 367/567] Adds void return type to generated snippets --- features/append_snippets.feature | 50 +++++++++--------- features/context.feature | 4 +- features/format_options.feature | 24 ++++----- features/i18n.feature | 8 +-- features/junit_format.feature | 2 +- features/legacy_snippets.feature | 34 ++++++------ features/multiple_formats.feature | 30 +++++------ features/pretty_format.feature | 2 +- features/result_types.feature | 26 +++++----- features/snippets.feature | 52 +++++++++---------- .../Generator/ContextSnippetGenerator.php | 2 +- 11 files changed, 117 insertions(+), 117 deletions(-) diff --git a/features/append_snippets.feature b/features/append_snippets.feature index 57c64d903..bd7e7cf1e 100644 --- a/features/append_snippets.feature +++ b/features/append_snippets.feature @@ -185,7 +185,7 @@ Feature: Append snippets option /** * @Then /^do something undefined with \$$/ */ - public function doSomethingUndefinedWith2() + public function doSomethingUndefinedWith2(): void { throw new PendingException(); } @@ -193,7 +193,7 @@ Feature: Append snippets option /** * @Then /^do something undefined with \\(\d+)$/ */ - public function doSomethingUndefinedWith3($arg1) + public function doSomethingUndefinedWith3($arg1): void { throw new PendingException(); } @@ -201,7 +201,7 @@ Feature: Append snippets option /** * @Given /^pystring:$/ */ - public function pystring(PyStringNode $string) + public function pystring(PyStringNode $string): void { throw new PendingException(); } @@ -209,7 +209,7 @@ Feature: Append snippets option /** * @Given /^pystring (\d+):$/ */ - public function pystring2($arg1, PyStringNode $string) + public function pystring2($arg1, PyStringNode $string): void { throw new PendingException(); } @@ -217,7 +217,7 @@ Feature: Append snippets option /** * @Given /^table:$/ */ - public function table(TableNode $table) + public function table(TableNode $table): void { throw new PendingException(); } @@ -355,7 +355,7 @@ Feature: Append snippets option /** * @Then /^do something undefined with \$$/ */ - public function doSomethingUndefinedWith2() + public function doSomethingUndefinedWith2(): void { throw new PendingException(); } @@ -363,7 +363,7 @@ Feature: Append snippets option /** * @Then /^do something undefined with \\(\d+)$/ */ - public function doSomethingUndefinedWith3($arg1) + public function doSomethingUndefinedWith3($arg1): void { throw new PendingException(); } @@ -371,7 +371,7 @@ Feature: Append snippets option /** * @Given /^pystring:$/ */ - public function pystring(PyStringNode $string) + public function pystring(PyStringNode $string): void { throw new PendingException(); } @@ -379,7 +379,7 @@ Feature: Append snippets option /** * @Given /^pystring (\d+):$/ */ - public function pystring2($arg1, PyStringNode $string) + public function pystring2($arg1, PyStringNode $string): void { throw new PendingException(); } @@ -387,7 +387,7 @@ Feature: Append snippets option /** * @Given /^table:$/ */ - public function table(TableNode $table) + public function table(TableNode $table): void { throw new PendingException(); } @@ -523,7 +523,7 @@ Feature: Append snippets option /** * @Then /^do something undefined with \$$/ */ - public function doSomethingUndefinedWith2() + public function doSomethingUndefinedWith2(): void { throw new PendingException(); } @@ -531,7 +531,7 @@ Feature: Append snippets option /** * @Then /^do something undefined with \\(\d+)$/ */ - public function doSomethingUndefinedWith3($arg1) + public function doSomethingUndefinedWith3($arg1): void { throw new PendingException(); } @@ -539,7 +539,7 @@ Feature: Append snippets option /** * @Given /^pystring:$/ */ - public function pystring(PyStringNode $string) + public function pystring(PyStringNode $string): void { throw new PendingException(); } @@ -547,7 +547,7 @@ Feature: Append snippets option /** * @Given /^pystring (\d+):$/ */ - public function pystring2($arg1, PyStringNode $string) + public function pystring2($arg1, PyStringNode $string): void { throw new PendingException(); } @@ -555,7 +555,7 @@ Feature: Append snippets option /** * @Given /^table:$/ */ - public function table(TableNode $table) + public function table(TableNode $table): void { throw new PendingException(); } @@ -652,7 +652,7 @@ Feature: Append snippets option /** * @Given /^I have (\d+) apples$/ */ - public function iHaveApples($arg1) + public function iHaveApples($arg1): void { throw new PendingException(); } @@ -660,7 +660,7 @@ Feature: Append snippets option /** * @When /^I ate (\d+) apple$/ */ - public function iAteApple($arg1) + public function iAteApple($arg1): void { throw new PendingException(); } @@ -668,7 +668,7 @@ Feature: Append snippets option /** * @Then /^I should have (\d+) apples$/ */ - public function iShouldHaveApples($arg1) + public function iShouldHaveApples($arg1): void { throw new PendingException(); } @@ -676,7 +676,7 @@ Feature: Append snippets option /** * @When /^I found (\d+) apples$/ */ - public function iFoundApples($arg1) + public function iFoundApples($arg1): void { throw new PendingException(); } @@ -684,7 +684,7 @@ Feature: Append snippets option /** * @Then /^do something undefined with \$$/ */ - public function doSomethingUndefinedWith() + public function doSomethingUndefinedWith(): void { throw new PendingException(); } @@ -692,7 +692,7 @@ Feature: Append snippets option /** * @When /^I ate (\d+) apples$/ */ - public function iAteApples($arg1) + public function iAteApples($arg1): void { throw new PendingException(); } @@ -700,7 +700,7 @@ Feature: Append snippets option /** * @Then /^do something undefined with \\(\d+)$/ */ - public function doSomethingUndefinedWith2($arg1) + public function doSomethingUndefinedWith2($arg1): void { throw new PendingException(); } @@ -708,7 +708,7 @@ Feature: Append snippets option /** * @Given /^pystring:$/ */ - public function pystring(PyStringNode $string) + public function pystring(PyStringNode $string): void { throw new PendingException(); } @@ -716,7 +716,7 @@ Feature: Append snippets option /** * @Given /^pystring (\d+):$/ */ - public function pystring2($arg1, PyStringNode $string) + public function pystring2($arg1, PyStringNode $string): void { throw new PendingException(); } @@ -724,7 +724,7 @@ Feature: Append snippets option /** * @Given /^table:$/ */ - public function table(TableNode $table) + public function table(TableNode $table): void { throw new PendingException(); } diff --git a/features/context.feature b/features/context.feature index 900f1824d..8428d614e 100644 --- a/features/context.feature +++ b/features/context.feature @@ -275,7 +275,7 @@ Feature: Context consistency /** * @Then /^context parameter "([^"]*)" should be equal to "([^"]*)"$/ */ - public function contextParameterShouldBeEqualTo($arg1, $arg2) + public function contextParameterShouldBeEqualTo($arg1, $arg2): void { throw new PendingException(); } @@ -283,7 +283,7 @@ Feature: Context consistency /** * @Then /^context parameter "([^"]*)" should be array with (\d+) elements$/ */ - public function contextParameterShouldBeArrayWithElements($arg1, $arg2) + public function contextParameterShouldBeArrayWithElements($arg1, $arg2): void { throw new PendingException(); } diff --git a/features/format_options.feature b/features/format_options.feature index c0ae5598a..8b9594b0c 100644 --- a/features/format_options.feature +++ b/features/format_options.feature @@ -171,7 +171,7 @@ Feature: Format options /** * @Then /^do something undefined$/ */ - public function doSomethingUndefined() + public function doSomethingUndefined(): void { throw new PendingException(); } @@ -179,7 +179,7 @@ Feature: Format options /** * @Given /^pystring:$/ */ - public function pystring(PyStringNode $string) + public function pystring(PyStringNode $string): void { throw new PendingException(); } @@ -187,7 +187,7 @@ Feature: Format options /** * @Given /^table:$/ */ - public function table(TableNode $table) + public function table(TableNode $table): void { throw new PendingException(); } @@ -254,7 +254,7 @@ Feature: Format options /** * @Then /^do something undefined$/ */ - public function doSomethingUndefined() + public function doSomethingUndefined(): void { throw new PendingException(); } @@ -262,7 +262,7 @@ Feature: Format options /** * @Given /^pystring:$/ */ - public function pystring(PyStringNode $string) + public function pystring(PyStringNode $string): void { throw new PendingException(); } @@ -270,7 +270,7 @@ Feature: Format options /** * @Given /^table:$/ */ - public function table(TableNode $table) + public function table(TableNode $table): void { throw new PendingException(); } @@ -402,7 +402,7 @@ Feature: Format options /** * @Then /^do something undefined$/ */ - public function doSomethingUndefined() + public function doSomethingUndefined(): void { throw new PendingException(); } @@ -410,7 +410,7 @@ Feature: Format options /** * @Given /^pystring:$/ */ - public function pystring(PyStringNode $string) + public function pystring(PyStringNode $string): void { throw new PendingException(); } @@ -418,7 +418,7 @@ Feature: Format options /** * @Given /^table:$/ */ - public function table(TableNode $table) + public function table(TableNode $table): void { throw new PendingException(); } @@ -482,7 +482,7 @@ Feature: Format options /** * @Then /^do something undefined$/ */ - public function doSomethingUndefined() + public function doSomethingUndefined(): void { throw new PendingException(); } @@ -490,7 +490,7 @@ Feature: Format options /** * @Given /^pystring:$/ */ - public function pystring(PyStringNode $string) + public function pystring(PyStringNode $string): void { throw new PendingException(); } @@ -498,7 +498,7 @@ Feature: Format options /** * @Given /^table:$/ */ - public function table(TableNode $table) + public function table(TableNode $table): void { throw new PendingException(); } diff --git a/features/i18n.feature b/features/i18n.feature index 1d376dffe..13b345a41 100644 --- a/features/i18n.feature +++ b/features/i18n.feature @@ -140,7 +140,7 @@ Feature: I18n /** * @Then /^Добавить "([^"]*)" число$/ */ - public function dobavitChislo($arg1) + public function dobavitChislo($arg1): void { throw new PendingException(); } @@ -180,7 +180,7 @@ Feature: I18n /** * @Then /^Добавить "([^"]*)" число$/ */ - public function dobavitChislo($arg1) + public function dobavitChislo($arg1): void { throw new PendingException(); } @@ -220,7 +220,7 @@ Feature: I18n /** * @Then /^Добавить "([^"]*)" число$/ */ - public function dobavitChislo($arg1) + public function dobavitChislo($arg1): void { throw new PendingException(); } @@ -260,7 +260,7 @@ Feature: I18n /** * @Then /^Добавить "([^"]*)" число$/ */ - public function dobavitChislo($arg1) + public function dobavitChislo($arg1): void { throw new PendingException(); } diff --git a/features/junit_format.feature b/features/junit_format.feature index c85759746..2943fb60f 100644 --- a/features/junit_format.feature +++ b/features/junit_format.feature @@ -95,7 +95,7 @@ /** * @Then /^Something new$/ */ - public function somethingNew() + public function somethingNew(): void { throw new PendingException(); } diff --git a/features/legacy_snippets.feature b/features/legacy_snippets.feature index 2f9bd906f..447014d25 100644 --- a/features/legacy_snippets.feature +++ b/features/legacy_snippets.feature @@ -64,7 +64,7 @@ Feature: Legacy Snippets /** * @Given /^I have magically created (\d+)\$$/ */ - public function iHaveMagicallyCreated($arg1) + public function iHaveMagicallyCreated($arg1): void { throw new PendingException(); } @@ -72,7 +72,7 @@ Feature: Legacy Snippets /** * @When /^I have chose '([^']*)' in coffee machine$/ */ - public function iHaveChoseCoffeeWithTurkeyInCoffeeMachine($arg1) + public function iHaveChoseCoffeeWithTurkeyInCoffeeMachine($arg1): void { throw new PendingException(); } @@ -80,7 +80,7 @@ Feature: Legacy Snippets /** * @Then /^I should have '([^']*)'$/ */ - public function iShouldHaveTurkeyWithCoffeeSauce($arg1) + public function iShouldHaveTurkeyWithCoffeeSauce($arg1): void { throw new PendingException(); } @@ -88,7 +88,7 @@ Feature: Legacy Snippets /** * @Then /^I should get a '([^']*)':$/ */ - public function iShouldGetASuperString($arg1, PyStringNode $string) + public function iShouldGetASuperString($arg1, PyStringNode $string): void { throw new PendingException(); } @@ -96,7 +96,7 @@ Feature: Legacy Snippets /** * @Then /^I should get a simple string:$/ */ - public function iShouldGetASimpleString(PyStringNode $string) + public function iShouldGetASimpleString(PyStringNode $string): void { throw new PendingException(); } @@ -104,7 +104,7 @@ Feature: Legacy Snippets /** * @When /^I have chose "([^"]*)" in coffee machine$/ */ - public function iHaveChoseInCoffeeMachine($arg1) + public function iHaveChoseInCoffeeMachine($arg1): void { throw new PendingException(); } @@ -112,7 +112,7 @@ Feature: Legacy Snippets /** * @When /^do something undefined with \\(\d+)$/ */ - public function doSomethingUndefinedWith($arg1) + public function doSomethingUndefinedWith($arg1): void { throw new PendingException(); } @@ -120,7 +120,7 @@ Feature: Legacy Snippets /** * @Then /^I should have "([^"]*)"$/ */ - public function iShouldHave($arg1) + public function iShouldHave($arg1): void { throw new PendingException(); } @@ -128,7 +128,7 @@ Feature: Legacy Snippets /** * @Then /^I should get a "([^"]*)":$/ */ - public function iShouldGetA($arg1, PyStringNode $string) + public function iShouldGetA($arg1, PyStringNode $string): void { throw new PendingException(); } @@ -193,7 +193,7 @@ Feature: Legacy Snippets /** * @Given I have magically created :arg1$ */ - public function iHaveMagicallyCreated($arg1) + public function iHaveMagicallyCreated($arg1): void { throw new PendingException(); } @@ -201,7 +201,7 @@ Feature: Legacy Snippets /** * @When I have chose :arg1 in coffee machine */ - public function iHaveChoseInCoffeeMachine($arg1) + public function iHaveChoseInCoffeeMachine($arg1): void { throw new PendingException(); } @@ -209,7 +209,7 @@ Feature: Legacy Snippets /** * @Then I should have :arg1 */ - public function iShouldHave($arg1) + public function iShouldHave($arg1): void { throw new PendingException(); } @@ -217,7 +217,7 @@ Feature: Legacy Snippets /** * @Then I should get a :arg1: */ - public function iShouldGetA($arg1, PyStringNode $string) + public function iShouldGetA($arg1, PyStringNode $string): void { throw new PendingException(); } @@ -225,7 +225,7 @@ Feature: Legacy Snippets /** * @Then I should get a simple string: */ - public function iShouldGetASimpleString(PyStringNode $string) + public function iShouldGetASimpleString(PyStringNode $string): void { throw new PendingException(); } @@ -233,7 +233,7 @@ Feature: Legacy Snippets /** * @When do something undefined with \:arg1 */ - public function doSomethingUndefinedWith($arg1) + public function doSomethingUndefinedWith($arg1): void { throw new PendingException(); } @@ -333,7 +333,7 @@ Feature: Legacy Snippets /** * @Given I have a package v2.5 */ - public function iHaveAPackageV() + public function iHaveAPackageV(): void { throw new PendingException(); } @@ -370,7 +370,7 @@ Feature: Legacy Snippets /** * @Then images should be uploaded to web\/uploads\/media\/default\/:arg1\/:arg2\/ */ - public function imagesShouldBeUploadedToWebUploadsMediaDefault($arg1, $arg2) + public function imagesShouldBeUploadedToWebUploadsMediaDefault($arg1, $arg2): void { throw new PendingException(); } diff --git a/features/multiple_formats.feature b/features/multiple_formats.feature index e0087a126..ade3c7fe8 100644 --- a/features/multiple_formats.feature +++ b/features/multiple_formats.feature @@ -182,7 +182,7 @@ Feature: Multiple formats /** * @Then /^do something undefined$/ */ - public function doSomethingUndefined() + public function doSomethingUndefined(): void { throw new PendingException(); } @@ -190,7 +190,7 @@ Feature: Multiple formats /** * @Given /^pystring:$/ */ - public function pystring(PyStringNode $string) + public function pystring(PyStringNode $string): void { throw new PendingException(); } @@ -198,7 +198,7 @@ Feature: Multiple formats /** * @Given /^table:$/ */ - public function table(TableNode $table) + public function table(TableNode $table): void { throw new PendingException(); } @@ -276,7 +276,7 @@ Feature: Multiple formats /** * @Then /^do something undefined$/ */ - public function doSomethingUndefined() + public function doSomethingUndefined(): void { throw new PendingException(); } @@ -284,7 +284,7 @@ Feature: Multiple formats /** * @Given /^pystring:$/ */ - public function pystring(PyStringNode $string) + public function pystring(PyStringNode $string): void { throw new PendingException(); } @@ -292,7 +292,7 @@ Feature: Multiple formats /** * @Given /^table:$/ */ - public function table(TableNode $table) + public function table(TableNode $table): void { throw new PendingException(); } @@ -322,7 +322,7 @@ Feature: Multiple formats /** * @Then /^do something undefined$/ */ - public function doSomethingUndefined() + public function doSomethingUndefined(): void { throw new PendingException(); } @@ -330,7 +330,7 @@ Feature: Multiple formats /** * @Given /^pystring:$/ */ - public function pystring(PyStringNode $string) + public function pystring(PyStringNode $string): void { throw new PendingException(); } @@ -338,7 +338,7 @@ Feature: Multiple formats /** * @Given /^table:$/ */ - public function table(TableNode $table) + public function table(TableNode $table): void { throw new PendingException(); } @@ -453,7 +453,7 @@ Feature: Multiple formats /** * @Then /^do something undefined$/ */ - public function doSomethingUndefined() + public function doSomethingUndefined(): void { throw new PendingException(); } @@ -461,7 +461,7 @@ Feature: Multiple formats /** * @Given /^pystring:$/ */ - public function pystring(PyStringNode $string) + public function pystring(PyStringNode $string): void { throw new PendingException(); } @@ -469,7 +469,7 @@ Feature: Multiple formats /** * @Given /^table:$/ */ - public function table(TableNode $table) + public function table(TableNode $table): void { throw new PendingException(); } @@ -501,7 +501,7 @@ Feature: Multiple formats /** * @Then /^do something undefined$/ */ - public function doSomethingUndefined() + public function doSomethingUndefined(): void { throw new PendingException(); } @@ -509,7 +509,7 @@ Feature: Multiple formats /** * @Given /^pystring:$/ */ - public function pystring(PyStringNode $string) + public function pystring(PyStringNode $string): void { throw new PendingException(); } @@ -517,7 +517,7 @@ Feature: Multiple formats /** * @Given /^table:$/ */ - public function table(TableNode $table) + public function table(TableNode $table): void { throw new PendingException(); } diff --git a/features/pretty_format.feature b/features/pretty_format.feature index 0a737a2c4..39c23ff3d 100644 --- a/features/pretty_format.feature +++ b/features/pretty_format.feature @@ -137,7 +137,7 @@ Feature: Pretty Formatter /** * @Then /^Something new$/ */ - public function somethingNew() + public function somethingNew(): void { throw new PendingException(); } diff --git a/features/result_types.feature b/features/result_types.feature index 04feb95a5..cb27d336c 100644 --- a/features/result_types.feature +++ b/features/result_types.feature @@ -47,7 +47,7 @@ Feature: Different result types /** * @Given /^I have magically created (\d+)\$$/ */ - public function iHaveMagicallyCreated($arg1) + public function iHaveMagicallyCreated($arg1): void { throw new PendingException(); } @@ -55,7 +55,7 @@ Feature: Different result types /** * @When /^I have chose "([^"]*)" in coffee machine$/ */ - public function iHaveChoseInCoffeeMachine($arg1) + public function iHaveChoseInCoffeeMachine($arg1): void { throw new PendingException(); } @@ -63,7 +63,7 @@ Feature: Different result types /** * @Then /^I should have "([^"]*)"$/ */ - public function iShouldHave($arg1) + public function iShouldHave($arg1): void { throw new PendingException(); } @@ -81,7 +81,7 @@ Feature: Different result types /** * @Given /^I have magically created (\d+)\$$/ */ - public function iHaveMagicallyCreated($arg1) + public function iHaveMagicallyCreated($arg1): void { throw new PendingException(); } @@ -89,7 +89,7 @@ Feature: Different result types /** * @When /^I have chose "([^"]*)" in coffee machine$/ */ - public function iHaveChoseInCoffeeMachine($arg1) + public function iHaveChoseInCoffeeMachine($arg1): void { throw new PendingException(); } @@ -97,7 +97,7 @@ Feature: Different result types /** * @Then /^I should have "([^"]*)"$/ */ - public function iShouldHave($arg1) + public function iShouldHave($arg1): void { throw new PendingException(); } @@ -132,14 +132,14 @@ Feature: Different result types /** * @Given /^human have ordered very very very hot "([^"]*)"$/ */ - public function humanOrdered($arg1) { + public function humanOrdered($arg1): void { throw new PendingException; } /** * @When the coffee will be ready */ - public function theCoffeeWillBeReady() { + public function theCoffeeWillBeReady(): void { throw new PendingException; } } @@ -163,7 +163,7 @@ Feature: Different result types /** * @Then /^I should say "([^"]*)"$/ */ - public function iShouldSay($arg1) + public function iShouldSay($arg1): void { throw new PendingException(); } @@ -187,7 +187,7 @@ Feature: Different result types /** * @Then /^I should say "([^"]*)"$/ */ - public function iShouldSay($arg1) + public function iShouldSay($arg1): void { throw new PendingException(); } @@ -371,19 +371,19 @@ Feature: Different result types class FeatureContext implements Context { /** @Given /^human have chosen "([^"]*)"$/ */ - public function chosen($arg1) { + public function chosen($arg1): void { throw new PendingException; } /** @Given /^human have chosen "Latte"$/ */ - public function chosenLatte() { + public function chosenLatte(): void { throw new PendingException; } /** * @Then /^I should make him "([^"]*)"$/ */ - public function iShouldSee($money) { + public function iShouldSee($money): void { throw new PendingException; } } diff --git a/features/snippets.feature b/features/snippets.feature index c3617d355..196ed727d 100644 --- a/features/snippets.feature +++ b/features/snippets.feature @@ -62,7 +62,7 @@ Feature: Snippets generation and addition /** * @Given /^I have magically created (\d+)\$$/ */ - public function iHaveMagicallyCreated($arg1) + public function iHaveMagicallyCreated($arg1): void { throw new PendingException(); } @@ -70,7 +70,7 @@ Feature: Snippets generation and addition /** * @When /^I have chose '([^']*)' in coffee machine$/ */ - public function iHaveChoseCoffeeWithTurkeyInCoffeeMachine($arg1) + public function iHaveChoseCoffeeWithTurkeyInCoffeeMachine($arg1): void { throw new PendingException(); } @@ -78,7 +78,7 @@ Feature: Snippets generation and addition /** * @Then /^I should have '([^']*)'$/ */ - public function iShouldHaveTurkeyWithCoffeeSauce($arg1) + public function iShouldHaveTurkeyWithCoffeeSauce($arg1): void { throw new PendingException(); } @@ -86,7 +86,7 @@ Feature: Snippets generation and addition /** * @Then /^I should get a '([^']*)':$/ */ - public function iShouldGetASuperString($arg1, PyStringNode $string) + public function iShouldGetASuperString($arg1, PyStringNode $string): void { throw new PendingException(); } @@ -94,7 +94,7 @@ Feature: Snippets generation and addition /** * @Then /^I should get a simple string:$/ */ - public function iShouldGetASimpleString(PyStringNode $string) + public function iShouldGetASimpleString(PyStringNode $string): void { throw new PendingException(); } @@ -102,7 +102,7 @@ Feature: Snippets generation and addition /** * @When /^I have chose "([^"]*)" in coffee machine$/ */ - public function iHaveChoseInCoffeeMachine($arg1) + public function iHaveChoseInCoffeeMachine($arg1): void { throw new PendingException(); } @@ -110,7 +110,7 @@ Feature: Snippets generation and addition /** * @When /^do something undefined with \\(\d+)$/ */ - public function doSomethingUndefinedWith($arg1) + public function doSomethingUndefinedWith($arg1): void { throw new PendingException(); } @@ -118,7 +118,7 @@ Feature: Snippets generation and addition /** * @Then /^I should have "([^"]*)"$/ */ - public function iShouldHave($arg1) + public function iShouldHave($arg1): void { throw new PendingException(); } @@ -126,7 +126,7 @@ Feature: Snippets generation and addition /** * @Then /^I should get a "([^"]*)":$/ */ - public function iShouldGetA($arg1, PyStringNode $string) + public function iShouldGetA($arg1, PyStringNode $string): void { throw new PendingException(); } @@ -189,7 +189,7 @@ Feature: Snippets generation and addition /** * @Given I have magically created :arg1$ */ - public function iHaveMagicallyCreated($arg1) + public function iHaveMagicallyCreated($arg1): void { throw new PendingException(); } @@ -197,7 +197,7 @@ Feature: Snippets generation and addition /** * @When I have chose :arg1 in coffee machine */ - public function iHaveChoseInCoffeeMachine($arg1) + public function iHaveChoseInCoffeeMachine($arg1): void { throw new PendingException(); } @@ -205,7 +205,7 @@ Feature: Snippets generation and addition /** * @Then I should have :arg1 */ - public function iShouldHave($arg1) + public function iShouldHave($arg1): void { throw new PendingException(); } @@ -213,7 +213,7 @@ Feature: Snippets generation and addition /** * @Then I should get a :arg1: */ - public function iShouldGetA($arg1, PyStringNode $string) + public function iShouldGetA($arg1, PyStringNode $string): void { throw new PendingException(); } @@ -221,7 +221,7 @@ Feature: Snippets generation and addition /** * @Then I should get a simple string: */ - public function iShouldGetASimpleString(PyStringNode $string) + public function iShouldGetASimpleString(PyStringNode $string): void { throw new PendingException(); } @@ -229,7 +229,7 @@ Feature: Snippets generation and addition /** * @When do something undefined with \:arg1 */ - public function doSomethingUndefinedWith($arg1) + public function doSomethingUndefinedWith($arg1): void { throw new PendingException(); } @@ -326,7 +326,7 @@ Feature: Snippets generation and addition /** * @Given I have a package v2.5 */ - public function iHaveAPackageV() + public function iHaveAPackageV(): void { throw new PendingException(); } @@ -360,7 +360,7 @@ Feature: Snippets generation and addition /** * @Then images should be uploaded to web\/uploads\/media\/default\/:arg1\/:arg2\/ */ - public function imagesShouldBeUploadedToWebUploadsMediaDefault($arg1, $arg2) + public function imagesShouldBeUploadedToWebUploadsMediaDefault($arg1, $arg2): void { throw new PendingException(); } @@ -387,7 +387,7 @@ Feature: Snippets generation and addition /** * @Given I have magically created :arg1$ */ - public function iHaveMagicallyCreated($arg1) + public function iHaveMagicallyCreated($arg1): void { throw new PendingException(); } @@ -395,7 +395,7 @@ Feature: Snippets generation and addition /** * @When I have chose :arg1 in coffee machine */ - public function iHaveChoseInCoffeeMachine($arg1) + public function iHaveChoseInCoffeeMachine($arg1): void { throw new PendingException(); } @@ -403,7 +403,7 @@ Feature: Snippets generation and addition /** * @Then I should have :arg1 */ - public function iShouldHave($arg1) + public function iShouldHave($arg1): void { throw new PendingException(); } @@ -411,7 +411,7 @@ Feature: Snippets generation and addition /** * @Then I should get a :arg1: */ - public function iShouldGetA($arg1, PyStringNode $string) + public function iShouldGetA($arg1, PyStringNode $string): void { throw new PendingException(); } @@ -419,7 +419,7 @@ Feature: Snippets generation and addition /** * @Then I should get a simple string: */ - public function iShouldGetASimpleString(PyStringNode $string) + public function iShouldGetASimpleString(PyStringNode $string): void { throw new PendingException(); } @@ -427,7 +427,7 @@ Feature: Snippets generation and addition /** * @When do something undefined with \:arg1 */ - public function doSomethingUndefinedWith($arg1) + public function doSomethingUndefinedWith($arg1): void { throw new PendingException(); } @@ -463,7 +463,7 @@ Feature: Snippets generation and addition /** * @Given that it's eleven o'clock */ - public function thatItsElevenOclock() + public function thatItsElevenOclock(): void { throw new PendingException(); } @@ -471,7 +471,7 @@ Feature: Snippets generation and addition /** * @When the guest's taxi has arrived */ - public function theGuestsTaxiHasArrived() + public function theGuestsTaxiHasArrived(): void { throw new PendingException(); } @@ -479,7 +479,7 @@ Feature: Snippets generation and addition /** * @Then the guest says :arg1 */ - public function theGuestSays($arg1) + public function theGuestSays($arg1): void { throw new PendingException(); } diff --git a/src/Behat/Behat/Context/Snippet/Generator/ContextSnippetGenerator.php b/src/Behat/Behat/Context/Snippet/Generator/ContextSnippetGenerator.php index 2373220a7..2baa16866 100644 --- a/src/Behat/Behat/Context/Snippet/Generator/ContextSnippetGenerator.php +++ b/src/Behat/Behat/Context/Snippet/Generator/ContextSnippetGenerator.php @@ -39,7 +39,7 @@ final class ContextSnippetGenerator implements SnippetGenerator /** * @%%s %s */ - public function %s(%s) + public function %s(%s): void { throw new PendingException(); } From 25acee5071c019b296cb415ec1fb833300bc99ec Mon Sep 17 00:00:00 2001 From: Christian Sciberras Date: Sun, 5 May 2024 18:30:12 +0200 Subject: [PATCH 368/567] Support behat.dist.y[a]ml format --- src/Behat/Behat/ApplicationFactory.php | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/Behat/Behat/ApplicationFactory.php b/src/Behat/Behat/ApplicationFactory.php index f2870ae53..0a71ec956 100644 --- a/src/Behat/Behat/ApplicationFactory.php +++ b/src/Behat/Behat/ApplicationFactory.php @@ -117,10 +117,14 @@ protected function getConfigPath() $cwd . 'behat.yml', $cwd . 'behat.yaml.dist', $cwd . 'behat.yml.dist', + $cwd . 'behat.dist.yaml', + $cwd . 'behat.dist.yml', $configDir . 'behat.yaml', $configDir . 'behat.yml', $configDir . 'behat.yaml.dist', $configDir . 'behat.yml.dist', + $configDir . 'behat.dist.yaml', + $configDir . 'behat.dist.yml', ); foreach ($paths as $path) { From 79bb2712ecc7622903236dd2299116218d2caef0 Mon Sep 17 00:00:00 2001 From: Vincent Riva Date: Mon, 6 May 2024 17:23:01 +0200 Subject: [PATCH 369/567] Add --rerun-only option --- features/rerun-only.feature | 180 ++++++++++++++++++ .../Behat/Tester/Cli/RerunController.php | 7 +- 2 files changed, 185 insertions(+), 2 deletions(-) create mode 100644 features/rerun-only.feature diff --git a/features/rerun-only.feature b/features/rerun-only.feature new file mode 100644 index 000000000..77dc9440d --- /dev/null +++ b/features/rerun-only.feature @@ -0,0 +1,180 @@ +Feature: Rerun + In order to test only failed scenarios and exit if none is found + As a feature developer + I need to have an ability to rerun failed previously scenarios + + Background: + Given a file named "features/bootstrap/FeatureContext.php" with: + """ + parameters = $parameters; + } + + /** + * @Given /^I have (\d+) apples?$/ + */ + public function iHaveApples($count) { + $this->apples = intval($count); + } + + /** + * @When /^I ate (\d+) apples?$/ + */ + public function iAteApples($count) { + $this->apples -= intval($count); + } + + /** + * @When /^I found (\d+) apples?$/ + */ + public function iFoundApples($count) { + $this->apples += intval($count); + } + + /** + * @Then /^I should have (\d+) apples$/ + */ + public function iShouldHaveApples($count) { + PHPUnit\Framework\Assert::assertEquals(intval($count), $this->apples); + } + + /** + * @Then /^context parameter "([^"]*)" should be equal to "([^"]*)"$/ + */ + public function contextParameterShouldBeEqualTo($key, $val) { + PHPUnit\Framework\Assert::assertEquals($val, $this->parameters[$key]); + } + + /** + * @Given /^context parameter "([^"]*)" should be array with (\d+) elements$/ + */ + public function contextParameterShouldBeArrayWithElements($key, $count) { + PHPUnit\Framework\Assert::assertIsArray($this->parameters[$key]); + PHPUnit\Framework\Assert::assertEquals(2, count($this->parameters[$key])); + } + } + """ + And a file named "features/apples.feature" with: + """ + Feature: Apples story + In order to eat apple + As a little kid + I need to have an apple in my pocket + + Background: + Given I have 3 apples + + Scenario: I'm little hungry + When I ate 1 apple + Then I should have 3 apples + + Scenario: Found more apples + When I found 5 apples + Then I should have 8 apples + + Scenario: Found more apples + When I found 2 apples + Then I should have 5 apples + + Scenario Outline: Other situations + When I ate apples + And I found apples + Then I should have apples + + Examples: + | ate | found | result | + | 3 | 1 | 1 | + | 0 | 4 | 8 | + | 2 | 2 | 3 | + """ + + Scenario: Run one feature with 2 failed and 3 passing scenarios + When I run "behat --no-colors -f progress features/apples.feature" + Then it should fail with: + """ + ..F.............F.... + + --- Failed steps: + + 001 Scenario: I'm little hungry # features/apples.feature:9 + Then I should have 3 apples # features/apples.feature:11 + Failed asserting that 2 matches expected 3. + + 002 Example: | 0 | 4 | 8 | # features/apples.feature:29 + Then I should have 8 apples # features/apples.feature:24 + Failed asserting that 7 matches expected 8. + + 6 scenarios (4 passed, 2 failed) + 21 steps (19 passed, 2 failed) + """ + + Scenario: Rerun only failed scenarios + Given I run "behat --no-colors -f progress features/apples.feature" + When I run "behat --no-colors -f progress features/apples.feature --rerun-only" + Then it should fail with: + """ + ..F...F + + --- Failed steps: + + 001 Scenario: I'm little hungry # features/apples.feature:9 + Then I should have 3 apples # features/apples.feature:11 + Failed asserting that 2 matches expected 3. + + 002 Example: | 0 | 4 | 8 | # features/apples.feature:29 + Then I should have 8 apples # features/apples.feature:24 + Failed asserting that 7 matches expected 8. + + 2 scenarios (2 failed) + 7 steps (5 passed, 2 failed) + """ + + Scenario: Fixing scenario removes it from the rerun log + Given I run "behat --no-colors -f progress features/apples.feature" + And there is a file named "features/apples.feature" with: + """ + Feature: Apples story + In order to eat apple + As a little kid + I need to have an apple in my pocket + + Background: + Given I have 3 apples + + Scenario: I'm little hungry + When I ate 1 apple + Then I should have 2 apples + + Scenario: Found more apples + When I found 5 apples + Then I should have 8 apples + + Scenario: Found more apples + When I found 2 apples + Then I should have 5 apples + + Scenario Outline: Other situations + When I ate apples + And I found apples + Then I should have apples + + Examples: + | ate | found | result | + | 3 | 1 | 1 | + | 0 | 4 | 7 | + | 2 | 2 | 3 | + """ + When I run "behat --no-colors -f progress features/apples.feature" + And I run "behat --no-colors -f progress features/apples.feature --rerun-only" + Then it should pass with: + """ + """ diff --git a/src/Behat/Behat/Tester/Cli/RerunController.php b/src/Behat/Behat/Tester/Cli/RerunController.php index 93bd84ff9..b2443b4ba 100644 --- a/src/Behat/Behat/Tester/Cli/RerunController.php +++ b/src/Behat/Behat/Tester/Cli/RerunController.php @@ -74,6 +74,9 @@ public function configure(Command $command) $command->addOption('--rerun', null, InputOption::VALUE_NONE, 'Re-run scenarios that failed during last execution.' ); + $command->addOption('--rerun-only', null, InputOption::VALUE_NONE, + 'Re-run scenarios that failed during last execution or exit if no file is found.' + ); } /** @@ -92,12 +95,12 @@ public function execute(InputInterface $input, OutputInterface $output) $this->key = $this->generateKey($input); - if (!$input->getOption('rerun')) { + if (!$input->getOption('rerun') && !$input->getOption('rerun-only')) { return; } if (!$this->getFileName() || !file_exists($this->getFileName())) { - return; + return $input->getOption('rerun-only') ? 0: null; } $input->setArgument('paths', $this->getFileName()); From 6d7bea40ec38335a5e1582a0f78e1e393c13cf94 Mon Sep 17 00:00:00 2001 From: Vincent Riva Date: Mon, 6 May 2024 17:28:51 +0200 Subject: [PATCH 370/567] Improve CS --- src/Behat/Behat/Tester/Cli/RerunController.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Behat/Behat/Tester/Cli/RerunController.php b/src/Behat/Behat/Tester/Cli/RerunController.php index b2443b4ba..bb62d8c8a 100644 --- a/src/Behat/Behat/Tester/Cli/RerunController.php +++ b/src/Behat/Behat/Tester/Cli/RerunController.php @@ -100,7 +100,7 @@ public function execute(InputInterface $input, OutputInterface $output) } if (!$this->getFileName() || !file_exists($this->getFileName())) { - return $input->getOption('rerun-only') ? 0: null; + return $input->getOption('rerun-only') ? 0 : null; } $input->setArgument('paths', $this->getFileName()); From 65234d39e23641fe576c660fe87761a5ab8a1aeb Mon Sep 17 00:00:00 2001 From: Andreas Heigl Date: Sun, 18 Aug 2024 11:18:04 +0200 Subject: [PATCH 371/567] Remove deprecations in PHP8.4 PHP8.4 has deprecated implicit nullable parameters. Some of those are used within Behat and now render a lot of deprecation messages. This PR replaces the implicit nullables with an explicit nullable wherever they are encountered. This should not have any influence on the code-execution but merely updates the function signature to make more explicit what is expected. --- .github/workflows/build.yml | 2 +- .../Context/Environment/InitializedContextEnvironment.php | 2 +- .../Context/Environment/UninitializedContextEnvironment.php | 2 +- src/Behat/Behat/Context/ServiceContainer/ContextExtension.php | 2 +- .../Behat/Context/Snippet/Appender/ContextSnippetAppender.php | 2 +- .../Behat/Context/Suite/Setup/SuiteWithContextsSetup.php | 2 +- src/Behat/Behat/Definition/SearchResult.php | 2 +- .../Behat/Definition/ServiceContainer/DefinitionExtension.php | 2 +- src/Behat/Behat/Gherkin/ServiceContainer/GherkinExtension.php | 2 +- src/Behat/Behat/Gherkin/Suite/Setup/SuiteWithPathsSetup.php | 2 +- .../Environment/ServiceContainerEnvironment.php | 2 +- .../ServiceContainer/HelperContainerExtension.php | 2 +- .../Output/Node/EventListener/AST/ScenarioNodeListener.php | 2 +- .../Behat/Output/Node/EventListener/AST/StepListener.php | 2 +- .../Node/EventListener/Statistics/StepStatsListener.php | 2 +- .../Behat/Output/Node/Printer/JUnit/JUnitFeaturePrinter.php | 2 +- .../Behat/Output/Node/Printer/JUnit/JUnitScenarioPrinter.php | 4 ++-- .../Behat/Output/Node/Printer/JUnit/JUnitSuitePrinter.php | 2 +- .../ServiceContainer/Formatter/PrettyFormatterFactory.php | 2 +- .../ServiceContainer/Formatter/ProgressFormatterFactory.php | 2 +- src/Behat/Behat/Snippet/ServiceContainer/SnippetExtension.php | 2 +- src/Behat/Behat/Tester/ServiceContainer/TesterExtension.php | 2 +- .../ServiceContainer/TransformationExtension.php | 2 +- src/Behat/Testwork/Call/CallResult.php | 2 +- src/Behat/Testwork/Call/ServiceContainer/CallExtension.php | 2 +- src/Behat/Testwork/Cli/ServiceContainer/CliExtension.php | 2 +- .../Environment/ServiceContainer/EnvironmentExtension.php | 2 +- .../ServiceContainer/EventDispatcherExtension.php | 2 +- .../EventDispatcher/TestworkEventDispatcherSymfony5.php | 2 +- .../EventDispatcher/TestworkEventDispatcherSymfonyLegacy.php | 2 +- .../Exception/ServiceContainer/ExceptionExtension.php | 2 +- .../Testwork/Ordering/ServiceContainer/OrderingExtension.php | 2 +- .../Testwork/Output/ServiceContainer/OutputExtension.php | 2 +- src/Behat/Testwork/ServiceContainer/ContainerLoader.php | 4 ++-- .../Specification/ServiceContainer/SpecificationExtension.php | 2 +- src/Behat/Testwork/Suite/Exception/SuiteException.php | 2 +- src/Behat/Testwork/Suite/ServiceContainer/SuiteExtension.php | 2 +- .../Testwork/Tester/ServiceContainer/TesterExtension.php | 2 +- 38 files changed, 40 insertions(+), 40 deletions(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 9ed80ac68..a3b9c3c2e 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -18,7 +18,7 @@ jobs: strategy: fail-fast: false matrix: - php: [7.2, 7.3, 7.4, 8.0, 8.1, 8.2, 8.3] + php: [7.2, 7.3, 7.4, 8.0, 8.1, 8.2, 8.3, 8.4] os: [ubuntu-latest] composer-mode: [update] symfony-version: [''] diff --git a/src/Behat/Behat/Context/Environment/InitializedContextEnvironment.php b/src/Behat/Behat/Context/Environment/InitializedContextEnvironment.php index 45774d1d2..d377f61b1 100644 --- a/src/Behat/Behat/Context/Environment/InitializedContextEnvironment.php +++ b/src/Behat/Behat/Context/Environment/InitializedContextEnvironment.php @@ -64,7 +64,7 @@ public function registerContext(Context $context) /** * {@inheritdoc} */ - public function setServiceContainer(ContainerInterface $container = null) + public function setServiceContainer(?ContainerInterface $container = null) { $this->serviceContainer = $container; } diff --git a/src/Behat/Behat/Context/Environment/UninitializedContextEnvironment.php b/src/Behat/Behat/Context/Environment/UninitializedContextEnvironment.php index a517d5f74..d36593b3d 100644 --- a/src/Behat/Behat/Context/Environment/UninitializedContextEnvironment.php +++ b/src/Behat/Behat/Context/Environment/UninitializedContextEnvironment.php @@ -39,7 +39,7 @@ final class UninitializedContextEnvironment extends StaticEnvironment implements * @throws ContextNotFoundException If class does not exist * @throws WrongContextClassException if class does not implement Context interface */ - public function registerContextClass($contextClass, array $arguments = null) + public function registerContextClass($contextClass, ?array $arguments = null) { if (!class_exists($contextClass)) { throw new ContextNotFoundException(sprintf( diff --git a/src/Behat/Behat/Context/ServiceContainer/ContextExtension.php b/src/Behat/Behat/Context/ServiceContainer/ContextExtension.php index 1ae669fac..1e21bbb25 100644 --- a/src/Behat/Behat/Context/ServiceContainer/ContextExtension.php +++ b/src/Behat/Behat/Context/ServiceContainer/ContextExtension.php @@ -71,7 +71,7 @@ final class ContextExtension implements Extension * * @param null|ServiceProcessor $processor */ - public function __construct(ServiceProcessor $processor = null) + public function __construct(?ServiceProcessor $processor = null) { $this->processor = $processor ? : new ServiceProcessor(); } diff --git a/src/Behat/Behat/Context/Snippet/Appender/ContextSnippetAppender.php b/src/Behat/Behat/Context/Snippet/Appender/ContextSnippetAppender.php index 456809bc2..dc4df1603 100644 --- a/src/Behat/Behat/Context/Snippet/Appender/ContextSnippetAppender.php +++ b/src/Behat/Behat/Context/Snippet/Appender/ContextSnippetAppender.php @@ -37,7 +37,7 @@ final class ContextSnippetAppender implements SnippetAppender * * @param null|FilesystemLogger $logger */ - public function __construct(FilesystemLogger $logger = null) + public function __construct(?FilesystemLogger $logger = null) { $this->logger = $logger; } diff --git a/src/Behat/Behat/Context/Suite/Setup/SuiteWithContextsSetup.php b/src/Behat/Behat/Context/Suite/Setup/SuiteWithContextsSetup.php index 9fc219d3a..4260e2df1 100644 --- a/src/Behat/Behat/Context/Suite/Setup/SuiteWithContextsSetup.php +++ b/src/Behat/Behat/Context/Suite/Setup/SuiteWithContextsSetup.php @@ -44,7 +44,7 @@ final class SuiteWithContextsSetup implements SuiteSetup * @param ClassLoader $autoloader * @param null|FilesystemLogger $logger */ - public function __construct(ClassLoader $autoloader, FilesystemLogger $logger = null) + public function __construct(ClassLoader $autoloader, ?FilesystemLogger $logger = null) { $this->autoloader = $autoloader; $this->logger = $logger; diff --git a/src/Behat/Behat/Definition/SearchResult.php b/src/Behat/Behat/Definition/SearchResult.php index cdb4191ad..0663680ff 100644 --- a/src/Behat/Behat/Definition/SearchResult.php +++ b/src/Behat/Behat/Definition/SearchResult.php @@ -37,7 +37,7 @@ final class SearchResult * @param null|string $matchedText * @param null|array $arguments */ - public function __construct(Definition $definition = null, $matchedText = null, array $arguments = null) + public function __construct(?Definition $definition = null, $matchedText = null, ?array $arguments = null) { $this->definition = $definition; $this->matchedText = $matchedText; diff --git a/src/Behat/Behat/Definition/ServiceContainer/DefinitionExtension.php b/src/Behat/Behat/Definition/ServiceContainer/DefinitionExtension.php index e408f5358..8a947a8e6 100644 --- a/src/Behat/Behat/Definition/ServiceContainer/DefinitionExtension.php +++ b/src/Behat/Behat/Definition/ServiceContainer/DefinitionExtension.php @@ -58,7 +58,7 @@ final class DefinitionExtension implements Extension * * @param null|ServiceProcessor $processor */ - public function __construct(ServiceProcessor $processor = null) + public function __construct(?ServiceProcessor $processor = null) { $this->processor = $processor ? : new ServiceProcessor(); } diff --git a/src/Behat/Behat/Gherkin/ServiceContainer/GherkinExtension.php b/src/Behat/Behat/Gherkin/ServiceContainer/GherkinExtension.php index 60aef8e60..a96a70447 100644 --- a/src/Behat/Behat/Gherkin/ServiceContainer/GherkinExtension.php +++ b/src/Behat/Behat/Gherkin/ServiceContainer/GherkinExtension.php @@ -54,7 +54,7 @@ final class GherkinExtension implements Extension * * @param null|ServiceProcessor $processor */ - public function __construct(ServiceProcessor $processor = null) + public function __construct(?ServiceProcessor $processor = null) { $this->processor = $processor ? : new ServiceProcessor(); } diff --git a/src/Behat/Behat/Gherkin/Suite/Setup/SuiteWithPathsSetup.php b/src/Behat/Behat/Gherkin/Suite/Setup/SuiteWithPathsSetup.php index f50249f6e..ff507f372 100644 --- a/src/Behat/Behat/Gherkin/Suite/Setup/SuiteWithPathsSetup.php +++ b/src/Behat/Behat/Gherkin/Suite/Setup/SuiteWithPathsSetup.php @@ -36,7 +36,7 @@ final class SuiteWithPathsSetup implements SuiteSetup * @param string $basePath * @param null|FilesystemLogger $logger */ - public function __construct($basePath, FilesystemLogger $logger = null) + public function __construct($basePath, ?FilesystemLogger $logger = null) { $this->basePath = $basePath; $this->logger = $logger; diff --git a/src/Behat/Behat/HelperContainer/Environment/ServiceContainerEnvironment.php b/src/Behat/Behat/HelperContainer/Environment/ServiceContainerEnvironment.php index 8f58ba623..d78b2c30b 100644 --- a/src/Behat/Behat/HelperContainer/Environment/ServiceContainerEnvironment.php +++ b/src/Behat/Behat/HelperContainer/Environment/ServiceContainerEnvironment.php @@ -27,7 +27,7 @@ interface ServiceContainerEnvironment extends Environment * * @param ContainerInterface|null $container */ - public function setServiceContainer(ContainerInterface $container = null); + public function setServiceContainer(?ContainerInterface $container = null); /** * Returns environment service container if set. diff --git a/src/Behat/Behat/HelperContainer/ServiceContainer/HelperContainerExtension.php b/src/Behat/Behat/HelperContainer/ServiceContainer/HelperContainerExtension.php index 399ffff09..8357dae06 100644 --- a/src/Behat/Behat/HelperContainer/ServiceContainer/HelperContainerExtension.php +++ b/src/Behat/Behat/HelperContainer/ServiceContainer/HelperContainerExtension.php @@ -45,7 +45,7 @@ final class HelperContainerExtension implements Extension * * @param null|ServiceProcessor $processor */ - public function __construct(ServiceProcessor $processor = null) + public function __construct(?ServiceProcessor $processor = null) { $this->processor = $processor ? : new ServiceProcessor(); } diff --git a/src/Behat/Behat/Output/Node/EventListener/AST/ScenarioNodeListener.php b/src/Behat/Behat/Output/Node/EventListener/AST/ScenarioNodeListener.php index bcc9f206a..d5a58d426 100644 --- a/src/Behat/Behat/Output/Node/EventListener/AST/ScenarioNodeListener.php +++ b/src/Behat/Behat/Output/Node/EventListener/AST/ScenarioNodeListener.php @@ -55,7 +55,7 @@ public function __construct( $beforeEventName, $afterEventName, ScenarioPrinter $scenarioPrinter, - SetupPrinter $setupPrinter = null + ?SetupPrinter $setupPrinter = null ) { $this->beforeEventName = $beforeEventName; $this->afterEventName = $afterEventName; diff --git a/src/Behat/Behat/Output/Node/EventListener/AST/StepListener.php b/src/Behat/Behat/Output/Node/EventListener/AST/StepListener.php index dda597b72..7892193b9 100644 --- a/src/Behat/Behat/Output/Node/EventListener/AST/StepListener.php +++ b/src/Behat/Behat/Output/Node/EventListener/AST/StepListener.php @@ -48,7 +48,7 @@ final class StepListener implements EventListener * @param StepPrinter $stepPrinter * @param null|SetupPrinter $setupPrinter */ - public function __construct(StepPrinter $stepPrinter, SetupPrinter $setupPrinter = null) + public function __construct(StepPrinter $stepPrinter, ?SetupPrinter $setupPrinter = null) { $this->stepPrinter = $stepPrinter; $this->setupPrinter = $setupPrinter; diff --git a/src/Behat/Behat/Output/Node/EventListener/Statistics/StepStatsListener.php b/src/Behat/Behat/Output/Node/EventListener/Statistics/StepStatsListener.php index 2e4a2f7ba..a4a32b2f9 100644 --- a/src/Behat/Behat/Output/Node/EventListener/Statistics/StepStatsListener.php +++ b/src/Behat/Behat/Output/Node/EventListener/Statistics/StepStatsListener.php @@ -181,7 +181,7 @@ private function getStepException(StepResult $result) * * @return string */ - private function getStepPath(AfterStepTested $event, Exception $exception = null) + private function getStepPath(AfterStepTested $event, ?Exception $exception = null) { $path = sprintf('%s:%d', $this->currentFeaturePath, $event->getStep()->getLine()); diff --git a/src/Behat/Behat/Output/Node/Printer/JUnit/JUnitFeaturePrinter.php b/src/Behat/Behat/Output/Node/Printer/JUnit/JUnitFeaturePrinter.php index 651c4a650..8eb7c8cee 100644 --- a/src/Behat/Behat/Output/Node/Printer/JUnit/JUnitFeaturePrinter.php +++ b/src/Behat/Behat/Output/Node/Printer/JUnit/JUnitFeaturePrinter.php @@ -36,7 +36,7 @@ final class JUnitFeaturePrinter implements FeaturePrinter */ private $durationListener; - public function __construct(PhaseStatistics $statistics, JUnitDurationListener $durationListener = null) + public function __construct(PhaseStatistics $statistics, ?JUnitDurationListener $durationListener = null) { $this->statistics = $statistics; $this->durationListener = $durationListener; diff --git a/src/Behat/Behat/Output/Node/Printer/JUnit/JUnitScenarioPrinter.php b/src/Behat/Behat/Output/Node/Printer/JUnit/JUnitScenarioPrinter.php index 8ed7b09ab..5010652bf 100644 --- a/src/Behat/Behat/Output/Node/Printer/JUnit/JUnitScenarioPrinter.php +++ b/src/Behat/Behat/Output/Node/Printer/JUnit/JUnitScenarioPrinter.php @@ -53,7 +53,7 @@ final class JUnitScenarioPrinter */ private $durationListener; - public function __construct(ResultToStringConverter $resultConverter, JUnitOutlineStoreListener $outlineListener, JUnitDurationListener $durationListener = null) + public function __construct(ResultToStringConverter $resultConverter, JUnitOutlineStoreListener $outlineListener, ?JUnitDurationListener $durationListener = null) { $this->resultConverter = $resultConverter; $this->outlineStoreListener = $outlineListener; @@ -63,7 +63,7 @@ public function __construct(ResultToStringConverter $resultConverter, JUnitOutli /** * {@inheritDoc} */ - public function printOpenTag(Formatter $formatter, FeatureNode $feature, ScenarioLikeInterface $scenario, TestResult $result, string $file = null) + public function printOpenTag(Formatter $formatter, FeatureNode $feature, ScenarioLikeInterface $scenario, TestResult $result, ?string $file = null) { $name = implode(' ', array_map(function ($l) { return trim($l); diff --git a/src/Behat/Behat/Output/Node/Printer/JUnit/JUnitSuitePrinter.php b/src/Behat/Behat/Output/Node/Printer/JUnit/JUnitSuitePrinter.php index 7e5efadc8..eb68e89d0 100644 --- a/src/Behat/Behat/Output/Node/Printer/JUnit/JUnitSuitePrinter.php +++ b/src/Behat/Behat/Output/Node/Printer/JUnit/JUnitSuitePrinter.php @@ -28,7 +28,7 @@ final class JUnitSuitePrinter implements SuitePrinter */ private $statistics; - public function __construct(PhaseStatistics $statistics = null) + public function __construct(?PhaseStatistics $statistics = null) { $this->statistics = $statistics; } diff --git a/src/Behat/Behat/Output/ServiceContainer/Formatter/PrettyFormatterFactory.php b/src/Behat/Behat/Output/ServiceContainer/Formatter/PrettyFormatterFactory.php index b737ef289..7a1dd0e02 100644 --- a/src/Behat/Behat/Output/ServiceContainer/Formatter/PrettyFormatterFactory.php +++ b/src/Behat/Behat/Output/ServiceContainer/Formatter/PrettyFormatterFactory.php @@ -51,7 +51,7 @@ class PrettyFormatterFactory implements FormatterFactory * * @param null|ServiceProcessor $processor */ - public function __construct(ServiceProcessor $processor = null) + public function __construct(?ServiceProcessor $processor = null) { $this->processor = $processor ? : new ServiceProcessor(); } diff --git a/src/Behat/Behat/Output/ServiceContainer/Formatter/ProgressFormatterFactory.php b/src/Behat/Behat/Output/ServiceContainer/Formatter/ProgressFormatterFactory.php index 3e02154da..77d474c93 100644 --- a/src/Behat/Behat/Output/ServiceContainer/Formatter/ProgressFormatterFactory.php +++ b/src/Behat/Behat/Output/ServiceContainer/Formatter/ProgressFormatterFactory.php @@ -47,7 +47,7 @@ class ProgressFormatterFactory implements FormatterFactory * * @param null|ServiceProcessor $processor */ - public function __construct(ServiceProcessor $processor = null) + public function __construct(?ServiceProcessor $processor = null) { $this->processor = $processor ? : new ServiceProcessor(); } diff --git a/src/Behat/Behat/Snippet/ServiceContainer/SnippetExtension.php b/src/Behat/Behat/Snippet/ServiceContainer/SnippetExtension.php index 6c68821af..8d2855edb 100644 --- a/src/Behat/Behat/Snippet/ServiceContainer/SnippetExtension.php +++ b/src/Behat/Behat/Snippet/ServiceContainer/SnippetExtension.php @@ -50,7 +50,7 @@ class SnippetExtension implements Extension * * @param null|ServiceProcessor $processor */ - public function __construct(ServiceProcessor $processor = null) + public function __construct(?ServiceProcessor $processor = null) { $this->processor = $processor ? : new ServiceProcessor(); } diff --git a/src/Behat/Behat/Tester/ServiceContainer/TesterExtension.php b/src/Behat/Behat/Tester/ServiceContainer/TesterExtension.php index e8ba129d1..843f750c1 100644 --- a/src/Behat/Behat/Tester/ServiceContainer/TesterExtension.php +++ b/src/Behat/Behat/Tester/ServiceContainer/TesterExtension.php @@ -58,7 +58,7 @@ class TesterExtension extends BaseExtension * * @param null|ServiceProcessor $processor */ - public function __construct(ServiceProcessor $processor = null) + public function __construct(?ServiceProcessor $processor = null) { $this->processor = $processor ? : new ServiceProcessor(); diff --git a/src/Behat/Behat/Transformation/ServiceContainer/TransformationExtension.php b/src/Behat/Behat/Transformation/ServiceContainer/TransformationExtension.php index 9c767b90e..86df51b90 100644 --- a/src/Behat/Behat/Transformation/ServiceContainer/TransformationExtension.php +++ b/src/Behat/Behat/Transformation/ServiceContainer/TransformationExtension.php @@ -52,7 +52,7 @@ class TransformationExtension implements Extension * * @param null|ServiceProcessor $processor */ - public function __construct(ServiceProcessor $processor = null) + public function __construct(?ServiceProcessor $processor = null) { $this->processor = $processor ?: new ServiceProcessor(); } diff --git a/src/Behat/Testwork/Call/CallResult.php b/src/Behat/Testwork/Call/CallResult.php index 4ee808b82..15f7ee36c 100644 --- a/src/Behat/Testwork/Call/CallResult.php +++ b/src/Behat/Testwork/Call/CallResult.php @@ -44,7 +44,7 @@ final class CallResult * @param null|Exception $exception * @param null|string $stdOut */ - public function __construct(Call $call, $return, Exception $exception = null, $stdOut = null) + public function __construct(Call $call, $return, ?Exception $exception = null, $stdOut = null) { $this->call = $call; $this->return = $return; diff --git a/src/Behat/Testwork/Call/ServiceContainer/CallExtension.php b/src/Behat/Testwork/Call/ServiceContainer/CallExtension.php index 81bf25825..09d87fc76 100644 --- a/src/Behat/Testwork/Call/ServiceContainer/CallExtension.php +++ b/src/Behat/Testwork/Call/ServiceContainer/CallExtension.php @@ -47,7 +47,7 @@ final class CallExtension implements Extension * * @param null|ServiceProcessor $processor */ - public function __construct(ServiceProcessor $processor = null) + public function __construct(?ServiceProcessor $processor = null) { $this->processor = $processor ? : new ServiceProcessor(); } diff --git a/src/Behat/Testwork/Cli/ServiceContainer/CliExtension.php b/src/Behat/Testwork/Cli/ServiceContainer/CliExtension.php index faca4ce61..31f663ce4 100644 --- a/src/Behat/Testwork/Cli/ServiceContainer/CliExtension.php +++ b/src/Behat/Testwork/Cli/ServiceContainer/CliExtension.php @@ -46,7 +46,7 @@ final class CliExtension implements Extension * * @param null|ServiceProcessor $processor */ - public function __construct(ServiceProcessor $processor = null) + public function __construct(?ServiceProcessor $processor = null) { $this->processor = $processor ?: new ServiceProcessor(); } diff --git a/src/Behat/Testwork/Environment/ServiceContainer/EnvironmentExtension.php b/src/Behat/Testwork/Environment/ServiceContainer/EnvironmentExtension.php index 389b36143..23c67cc30 100644 --- a/src/Behat/Testwork/Environment/ServiceContainer/EnvironmentExtension.php +++ b/src/Behat/Testwork/Environment/ServiceContainer/EnvironmentExtension.php @@ -47,7 +47,7 @@ final class EnvironmentExtension implements Extension * * @param null|ServiceProcessor $processor */ - public function __construct(ServiceProcessor $processor = null) + public function __construct(?ServiceProcessor $processor = null) { $this->processor = $processor ? : new ServiceProcessor(); } diff --git a/src/Behat/Testwork/EventDispatcher/ServiceContainer/EventDispatcherExtension.php b/src/Behat/Testwork/EventDispatcher/ServiceContainer/EventDispatcherExtension.php index 502740a5f..782247ff6 100644 --- a/src/Behat/Testwork/EventDispatcher/ServiceContainer/EventDispatcherExtension.php +++ b/src/Behat/Testwork/EventDispatcher/ServiceContainer/EventDispatcherExtension.php @@ -47,7 +47,7 @@ class EventDispatcherExtension implements Extension * * @param null|ServiceProcessor $processor */ - public function __construct(ServiceProcessor $processor = null) + public function __construct(?ServiceProcessor $processor = null) { $this->processor = $processor ? : new ServiceProcessor(); } diff --git a/src/Behat/Testwork/EventDispatcher/TestworkEventDispatcherSymfony5.php b/src/Behat/Testwork/EventDispatcher/TestworkEventDispatcherSymfony5.php index d82c500dd..1ff0b5f9c 100644 --- a/src/Behat/Testwork/EventDispatcher/TestworkEventDispatcherSymfony5.php +++ b/src/Behat/Testwork/EventDispatcher/TestworkEventDispatcherSymfony5.php @@ -23,7 +23,7 @@ final class TestworkEventDispatcherSymfony5 extends EventDispatcher /** * {@inheritdoc} */ - public function dispatch($event, string $eventName = null): object + public function dispatch($event, ?string $eventName = null): object { trigger_error( 'Class "\Behat\Testwork\EventDispatcher\TestworkEventDispatcherSymfony5" is deprecated ' . diff --git a/src/Behat/Testwork/EventDispatcher/TestworkEventDispatcherSymfonyLegacy.php b/src/Behat/Testwork/EventDispatcher/TestworkEventDispatcherSymfonyLegacy.php index 0503f5b64..21f446743 100644 --- a/src/Behat/Testwork/EventDispatcher/TestworkEventDispatcherSymfonyLegacy.php +++ b/src/Behat/Testwork/EventDispatcher/TestworkEventDispatcherSymfonyLegacy.php @@ -25,7 +25,7 @@ final class TestworkEventDispatcherSymfonyLegacy extends EventDispatcher * {@inheritdoc} * */ - public function dispatch($eventName, Event $event = null) + public function dispatch($eventName, ?Event $event = null) { trigger_error( 'Class "\Behat\Testwork\EventDispatcher\TestworkEventDispatcherSymfonyLegacy" is deprecated ' . diff --git a/src/Behat/Testwork/Exception/ServiceContainer/ExceptionExtension.php b/src/Behat/Testwork/Exception/ServiceContainer/ExceptionExtension.php index 92ae6afee..8b2001d73 100644 --- a/src/Behat/Testwork/Exception/ServiceContainer/ExceptionExtension.php +++ b/src/Behat/Testwork/Exception/ServiceContainer/ExceptionExtension.php @@ -47,7 +47,7 @@ final class ExceptionExtension implements Extension * * @param null|ServiceProcessor $processor */ - public function __construct(ServiceProcessor $processor = null) + public function __construct(?ServiceProcessor $processor = null) { $this->processor = $processor ? : new ServiceProcessor(); } diff --git a/src/Behat/Testwork/Ordering/ServiceContainer/OrderingExtension.php b/src/Behat/Testwork/Ordering/ServiceContainer/OrderingExtension.php index 329227330..31160f347 100644 --- a/src/Behat/Testwork/Ordering/ServiceContainer/OrderingExtension.php +++ b/src/Behat/Testwork/Ordering/ServiceContainer/OrderingExtension.php @@ -40,7 +40,7 @@ final class OrderingExtension implements Extension * * @param null|ServiceProcessor $processor */ - public function __construct(ServiceProcessor $processor = null) + public function __construct(?ServiceProcessor $processor = null) { $this->processor = $processor ?: new ServiceProcessor(); } diff --git a/src/Behat/Testwork/Output/ServiceContainer/OutputExtension.php b/src/Behat/Testwork/Output/ServiceContainer/OutputExtension.php index dff83fde1..65f5609f2 100644 --- a/src/Behat/Testwork/Output/ServiceContainer/OutputExtension.php +++ b/src/Behat/Testwork/Output/ServiceContainer/OutputExtension.php @@ -58,7 +58,7 @@ final class OutputExtension implements Extension * @param FormatterFactory[] $formatterFactories * @param null|ServiceProcessor $processor */ - public function __construct($defaultFormatter, array $formatterFactories, ServiceProcessor $processor = null) + public function __construct($defaultFormatter, array $formatterFactories, ?ServiceProcessor $processor = null) { $this->defaultFormatter = $defaultFormatter; $this->factories = $formatterFactories; diff --git a/src/Behat/Testwork/ServiceContainer/ContainerLoader.php b/src/Behat/Testwork/ServiceContainer/ContainerLoader.php index a72377762..5c343a6ef 100644 --- a/src/Behat/Testwork/ServiceContainer/ContainerLoader.php +++ b/src/Behat/Testwork/ServiceContainer/ContainerLoader.php @@ -45,8 +45,8 @@ final class ContainerLoader */ public function __construct( ExtensionManager $extensionManager, - ConfigurationTree $configuration = null, - Processor $processor = null + ?ConfigurationTree $configuration = null, + ?Processor $processor = null ) { $this->extensionManager = $extensionManager; $this->configuration = $configuration ? : new ConfigurationTree(); diff --git a/src/Behat/Testwork/Specification/ServiceContainer/SpecificationExtension.php b/src/Behat/Testwork/Specification/ServiceContainer/SpecificationExtension.php index d369d458c..4154f80ed 100644 --- a/src/Behat/Testwork/Specification/ServiceContainer/SpecificationExtension.php +++ b/src/Behat/Testwork/Specification/ServiceContainer/SpecificationExtension.php @@ -44,7 +44,7 @@ final class SpecificationExtension implements Extension * * @param null|ServiceProcessor $processor */ - public function __construct(ServiceProcessor $processor = null) + public function __construct(?ServiceProcessor $processor = null) { $this->processor = $processor ? : new ServiceProcessor(); } diff --git a/src/Behat/Testwork/Suite/Exception/SuiteException.php b/src/Behat/Testwork/Suite/Exception/SuiteException.php index 2027089b3..acb9154de 100644 --- a/src/Behat/Testwork/Suite/Exception/SuiteException.php +++ b/src/Behat/Testwork/Suite/Exception/SuiteException.php @@ -33,7 +33,7 @@ class SuiteException extends InvalidArgumentException implements TestworkExcepti * @param string $name * @param Exception|null $previous */ - public function __construct($message, $name, Exception $previous = null) + public function __construct($message, $name, ?Exception $previous = null) { $this->name = $name; diff --git a/src/Behat/Testwork/Suite/ServiceContainer/SuiteExtension.php b/src/Behat/Testwork/Suite/ServiceContainer/SuiteExtension.php index 804cb92e4..9999cb7ba 100644 --- a/src/Behat/Testwork/Suite/ServiceContainer/SuiteExtension.php +++ b/src/Behat/Testwork/Suite/ServiceContainer/SuiteExtension.php @@ -48,7 +48,7 @@ final class SuiteExtension implements Extension * * @param null|ServiceProcessor $processor */ - public function __construct(ServiceProcessor $processor = null) + public function __construct(?ServiceProcessor $processor = null) { $this->processor = $processor ? : new ServiceProcessor(); } diff --git a/src/Behat/Testwork/Tester/ServiceContainer/TesterExtension.php b/src/Behat/Testwork/Tester/ServiceContainer/TesterExtension.php index 8892992ce..41cb7f695 100644 --- a/src/Behat/Testwork/Tester/ServiceContainer/TesterExtension.php +++ b/src/Behat/Testwork/Tester/ServiceContainer/TesterExtension.php @@ -55,7 +55,7 @@ abstract class TesterExtension implements Extension * * @param null|ServiceProcessor $processor */ - public function __construct(ServiceProcessor $processor = null) + public function __construct(?ServiceProcessor $processor = null) { $this->processor = $processor ? : new ServiceProcessor(); } From 13a99725803ab0a009d9b238f614f998312ca6e3 Mon Sep 17 00:00:00 2001 From: jrfnl Date: Tue, 1 Oct 2024 16:08:05 +0200 Subject: [PATCH 372/567] Add dependabot configuration file Node 16 is deprecated on GitHub Actions for action runners. Most, if not all, action runners have released new majors to run on Node 20 to fix this, but the workflows in this repo still use outdated versions. This commit adds an initial Dependabot configuration to: * Submit pull requests for security updates and version updates for GH Action runner dependencies. This PR doesn't include a config for the Composer dependencies, but this could be added later, if so desired. The configuration has been set up to: * Run weekly (for now). * Submit a maximum of 5 pull requests at a time. If additional pull requests are needed, these will subsequently be submitted the next time Dependabot runs after one or more of the open pull requests have been merged. Refs: * https://docs.github.com/en/code-security/dependabot/dependabot-version-updates/configuration-options-for-the-dependabot.yml-file * https://docs.github.com/en/code-security/dependabot/dependabot-version-updates/configuration-options-for-the-dependabot.yml-file#versioning-strategy Once this PR is merged, at least one Dependabot PR will be opened (for `actions/checkout`). Merging that will fix the following notice which currently shows in Actions run summaries: ``` The following actions use a deprecated Node.js version and will be forced to run on node20: actions/checkout@v3. For more info: https://github.blog/changelog/2024-03-07-github-actions-all-actions-will-run-on-node20-instead-of-node16-by-default/ ``` --- .github/dependabot.yml | 13 +++++++++++++ 1 file changed, 13 insertions(+) create mode 100644 .github/dependabot.yml diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 000000000..a4aeb8ee1 --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,13 @@ +# Dependabot configuration. +# +# Please see the documentation for all configuration options: +# https://docs.github.com/en/code-security/dependabot/dependabot-version-updates/configuration-options-for-the-dependabot.yml-file + +version: 2 +updates: + # Maintain dependencies for GitHub Actions. + - package-ecosystem: "github-actions" + directory: "/" + schedule: + interval: "weekly" + open-pull-requests-limit: 5 From d7bd9a29e503a1156fa8a8145c5e5cdf79daf285 Mon Sep 17 00:00:00 2001 From: jrfnl Date: Tue, 1 Oct 2024 15:58:32 +0200 Subject: [PATCH 373/567] GH Actions/tests: use "develop" ini file By default setupPHP uses the `production` ini file, which silences some errors. Changing this to the `development` ini file should surface all errors when running the tests. --- .github/workflows/build.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index a3b9c3c2e..cd0357f57 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -73,6 +73,7 @@ jobs: uses: shivammathur/setup-php@v2 with: php-version: "${{ matrix.php }}" + ini-file: "development" ini-values: "phar.readonly=0,zend.exception_ignore_args=Off" coverage: none From 676a39e32154263f3d7a6f8f1851644eff718d8b Mon Sep 17 00:00:00 2001 From: jrfnl Date: Tue, 1 Oct 2024 16:00:19 +0200 Subject: [PATCH 374/567] GH Actions/test: use `ignore-platform-reqs` ... on "PHP next", not on "PHP latest". --- .github/workflows/build.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index cd0357f57..40f6f57e6 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -92,7 +92,7 @@ jobs: if: matrix.composer-mode == 'update' env: SYMFONY_REQUIRE: ${{ matrix.symfony-version }}.* - run: composer update ${{ matrix.php == '8.3' && '--ignore-platform-req=php+' || '' }} + run: composer update ${{ matrix.php == '8.4' && '--ignore-platform-req=php+' || '' }} - name: Install lowest dependencies if: matrix.composer-mode == 'lowest' From 60d3c4bbaca6b618fb8ead174463832d8ceddd48 Mon Sep 17 00:00:00 2001 From: jrfnl Date: Tue, 1 Oct 2024 17:59:46 +0200 Subject: [PATCH 375/567] Dependabot: group updates Ref: https://docs.github.com/en/code-security/dependabot/dependabot-version-updates/configuration-options-for-the-dependabot.yml-file#groups --- .github/dependabot.yml | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/.github/dependabot.yml b/.github/dependabot.yml index a4aeb8ee1..3aa204b33 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -11,3 +11,8 @@ updates: schedule: interval: "weekly" open-pull-requests-limit: 5 + groups: + majors: + applies-to: version-updates + update-types: + - "major" From 308f9c411c82c9740524e77ab65eb4a1f27407a7 Mon Sep 17 00:00:00 2001 From: jrfnl Date: Tue, 1 Oct 2024 17:09:58 +0200 Subject: [PATCH 376/567] PHP 8.4 | CallErrorException: prevent deprecation for `E_STRICT` [2] The `E_STRICT` constant is deprecated as of PHP 8.4 and will be removed in PHP 9.0. The error level hasn't been in use since PHP 8.0 anyway and was only barely still used in PHP 7.x. All the same as this is an error handling class, I'm proposing to still handle it, but conditionally to prevent the deprecation notice. The solution applied is inspired by a similar fix made in PHPUnit by @sebastianbergmann. Ref: * https://wiki.php.net/rfc/deprecations_php_8_4#remove_e_strict_error_level_and_deprecate_e_strict_constant --- src/Behat/Testwork/Call/Exception/CallErrorException.php | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/src/Behat/Testwork/Call/Exception/CallErrorException.php b/src/Behat/Testwork/Call/Exception/CallErrorException.php index 1622f0fe2..21f7e90e8 100644 --- a/src/Behat/Testwork/Call/Exception/CallErrorException.php +++ b/src/Behat/Testwork/Call/Exception/CallErrorException.php @@ -25,7 +25,6 @@ final class CallErrorException extends ErrorException E_USER_ERROR => 'User Error', E_USER_WARNING => 'User Warning', E_USER_NOTICE => 'User Notice', - E_STRICT => 'Runtime Notice', E_RECOVERABLE_ERROR => 'Catchable Fatal Error', ); @@ -39,6 +38,11 @@ final class CallErrorException extends ErrorException */ public function __construct($level, $message, $file, $line) { + // E_STRICT is deprecated since PHP 8.4. + if (defined('E_STRICT') && $level === @E_STRICT) { + $this->levels[@E_STRICT] = 'Runtime Notice'; + } + parent::__construct( sprintf( '%s: %s in %s line %d', From aa0c61b096dff51818f3abc0368235905014d5a1 Mon Sep 17 00:00:00 2001 From: jrfnl Date: Wed, 2 Oct 2024 00:02:30 +0200 Subject: [PATCH 377/567] PHP 8.4 | Fix passing E_USER_ERROR to trigger_error() PHP 8.4 deprecates passing `E_USER_ERROR` to `trigger_error()`, with the recommendation being to replace these type of calls with either an Exception or an `exit` statement. This commit fixes the one instance found in this codebase. Based on my reading of this test, the test is not so much about the error _level_, but about the error _handling_. Given that, changing the error level from `E_USER_ERROR` to `E_USER_WARNING` preserves the value of the test while avoiding the PHP 8.4 deprecation notice. Ref: https://wiki.php.net/rfc/deprecations_php_8_4#deprecate_passing_e_user_error_to_trigger_error --- features/result_types.feature | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/features/result_types.feature b/features/result_types.feature index 04feb95a5..bd6d13598 100644 --- a/features/result_types.feature +++ b/features/result_types.feature @@ -446,11 +446,11 @@ Feature: Different result types Step "/^customer bought coffee$/" is already defined in FeatureContext::chosen() """ - Scenario: Error-containing steps + Scenario: Warning-containing steps Given a file named "features/coffee.feature" with: """ Feature: Redundant actions - In order to be able to know about errors in definitions as soon as possible + In order to be able to know about warnings in definitions as soon as possible As a coffee machine mechanic I need to be able to know about redundant menu definitions @@ -471,7 +471,7 @@ Feature: Different result types { /** @Given /^customer bought coffee$/ */ public function chosen() { - trigger_error("some error", E_USER_ERROR); + trigger_error("some warning", E_USER_WARNING); } /** @Given /^customer bought another one coffee$/ */ @@ -490,7 +490,7 @@ Feature: Different result types 001 Scenario: Redundant menu # features/coffee.feature:6 Given customer bought coffee # features/coffee.feature:7 - User Error: some error in features/bootstrap/FeatureContext.php line 12 + User Warning: some warning in features/bootstrap/FeatureContext.php line 12 1 scenario (1 failed) 2 steps (1 failed, 1 skipped) From 19016c0b3607453b0ab0638023e2867e1cd831c1 Mon Sep 17 00:00:00 2001 From: jrfnl Date: Wed, 2 Oct 2024 00:02:49 +0200 Subject: [PATCH 378/567] Tests: fix minor typo --- features/error_reporting.feature | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/features/error_reporting.feature b/features/error_reporting.feature index d9fb305c2..2c4b363d3 100644 --- a/features/error_reporting.feature +++ b/features/error_reporting.feature @@ -1,5 +1,5 @@ Feature: Error Reporting - In order to ignore E_NOTICE warnings of code I depend uppon + In order to ignore E_NOTICE warnings of code I depend upon As a feature developer I need to have an ability to set a custom error level for steps to be executed in From 35db72656ecfad4a17ca6c59fc9c6eaf75f6ca82 Mon Sep 17 00:00:00 2001 From: everzet Date: Sat, 19 Oct 2024 14:42:38 +0100 Subject: [PATCH 379/567] Drop dependency on Prophecy --- composer.json | 3 +- .../Pattern/PatternTransformerTest.php | 58 +++++++++---------- .../Subject/GroupedSubjectIteratorTest.php | 12 ++-- 3 files changed, 36 insertions(+), 37 deletions(-) diff --git a/composer.json b/composer.json index 077fc7850..90e41800e 100644 --- a/composer.json +++ b/composer.json @@ -31,8 +31,7 @@ "symfony/process": "^4.4 || ^5.0 || ^6.0 || ^7.0", "phpunit/phpunit": "^8.5 || ^9.0", "herrera-io/box": "~1.6.1", - "vimeo/psalm": "^4.8", - "phpspec/prophecy": "^1.15" + "vimeo/psalm": "^4.8" }, "suggest": { diff --git a/tests/Behat/Tests/Definition/Pattern/PatternTransformerTest.php b/tests/Behat/Tests/Definition/Pattern/PatternTransformerTest.php index b306b34ac..b9c07036c 100644 --- a/tests/Behat/Tests/Definition/Pattern/PatternTransformerTest.php +++ b/tests/Behat/Tests/Definition/Pattern/PatternTransformerTest.php @@ -14,24 +14,20 @@ class PatternTransformerTest extends TestCase { public function testTransformPatternToRegexCache() { - $observer = $this->prophesize('Behat\Behat\Definition\Pattern\Policy\PatternPolicy'); - // first pattern - $observer->supportsPattern('hello world')->willReturn(true); - $observer->transformPatternToRegex('hello world') - ->shouldBeCalledTimes(1) - ->willReturn('/hello world/'); - - // second pattern - $observer->supportsPattern('hi world')->willReturn(true); - $observer->transformPatternToRegex('hi world') - ->shouldBeCalledTimes(1) - ->willReturn('/hi world/'); + $policy = $this->createStub('Behat\Behat\Definition\Pattern\Policy\PatternPolicy'); + $policy->method('supportsPattern') + ->willReturn(true); + $policy->method('transformPatternToRegex') + ->will($this->returnValueMap([ + ['hello world', '/hello world/'], + ['hi world', '/hi world/'], + ])); $testedInstance = new PatternTransformer(); - $testedInstance->registerPatternPolicy($observer->reveal()); + $testedInstance->registerPatternPolicy($policy); + $regex = $testedInstance->transformPatternToRegex('hello world'); $regex2 = $testedInstance->transformPatternToRegex('hello world'); - $regex3 = $testedInstance->transformPatternToRegex('hi world'); $this->assertEquals('/hello world/', $regex); @@ -42,23 +38,24 @@ public function testTransformPatternToRegexCache() public function testTransformPatternToRegexCacheAndRegisterNewPolicy() { // first pattern - $policy1Prophecy = $this->prophesize('Behat\Behat\Definition\Pattern\Policy\PatternPolicy'); - $policy1Prophecy->supportsPattern('hello world')->willReturn(true); - $policy1Prophecy->transformPatternToRegex('hello world') - ->shouldBeCalledTimes(2) + $policy1 = $this->createMock('Behat\Behat\Definition\Pattern\Policy\PatternPolicy'); + $policy1->method('supportsPattern')->willReturn(true); + $policy1->expects($this->exactly(2)) + ->method('transformPatternToRegex') + ->with($this->equalTo('hello world')) ->willReturn('/hello world/'); // second pattern - $policy2Prophecy = $this->prophesize('Behat\Behat\Definition\Pattern\Policy\PatternPolicy'); - $policy1Prophecy->supportsPattern()->shouldNotBeCalled(); - $policy1Prophecy->transformPatternToRegex()->shouldNotBeCalled(); + $policy2 = $this->createMock('Behat\Behat\Definition\Pattern\Policy\PatternPolicy'); + $policy2->expects($this->never())->method('supportsPattern'); + $policy2->expects($this->never())->method('transformPatternToRegex'); $testedInstance = new PatternTransformer(); - $testedInstance->registerPatternPolicy($policy1Prophecy->reveal()); + $testedInstance->registerPatternPolicy($policy1); $regex = $testedInstance->transformPatternToRegex('hello world'); $regex2 = $testedInstance->transformPatternToRegex('hello world'); - $testedInstance->registerPatternPolicy($policy2Prophecy->reveal()); + $testedInstance->registerPatternPolicy($policy2); $regex3 = $testedInstance->transformPatternToRegex('hello world'); $this->assertEquals('/hello world/', $regex); @@ -68,15 +65,16 @@ public function testTransformPatternToRegexCacheAndRegisterNewPolicy() public function testTransformPatternToRegexNoMatch() { - // first pattern - $policy1Prophecy = $this->prophesize('Behat\Behat\Definition\Pattern\Policy\PatternPolicy'); - $policy1Prophecy->supportsPattern('hello world')->willReturn(false); - $policy1Prophecy->transformPatternToRegex('hello world') - ->shouldNotBeCalled(); - + $policy = $this->createMock('Behat\Behat\Definition\Pattern\Policy\PatternPolicy'); + $policy->method('supportsPattern') + ->with($this->equalTo('hello world')) + ->willReturn(false); + $policy->expects($this->never()) + ->method('transformPatternToRegex'); $testedInstance = new PatternTransformer(); - $testedInstance->registerPatternPolicy($policy1Prophecy->reveal()); + $testedInstance->registerPatternPolicy($policy); + $this->expectException('\Behat\Behat\Definition\Exception\UnknownPatternException'); $this->expectExceptionMessage("Can not find policy for a pattern `hello world`."); $regex = $testedInstance->transformPatternToRegex('hello world'); diff --git a/tests/Behat/Tests/Testwork/Subject/GroupedSubjectIteratorTest.php b/tests/Behat/Tests/Testwork/Subject/GroupedSubjectIteratorTest.php index 84b8dd18f..7693cbb87 100644 --- a/tests/Behat/Tests/Testwork/Subject/GroupedSubjectIteratorTest.php +++ b/tests/Behat/Tests/Testwork/Subject/GroupedSubjectIteratorTest.php @@ -11,11 +11,12 @@ class GroupedSubjectIteratorTest extends TestCase { public function testIterationWithEmptyAtBeginning() { - $suite = $this->prophesize('Behat\Testwork\Suite\Suite')->reveal(); + $suite = $this->createStub('Behat\Testwork\Suite\Suite'); + $subIterator = $this->createStub('Behat\Testwork\Specification\SpecificationIterator'); $iterator = new GroupedSpecificationIterator($suite, array( new NoSpecificationsIterator($suite), - new SpecificationArrayIterator($suite, array($this->prophesize()->reveal())), + new SpecificationArrayIterator($suite, array($subIterator)), )); $this->assertEquals(1, iterator_count($iterator)); @@ -23,12 +24,13 @@ public function testIterationWithEmptyAtBeginning() public function testIterationWithEmptyInMiddle() { - $suite = $this->prophesize('Behat\Testwork\Suite\Suite')->reveal(); + $suite = $this->createStub('Behat\Testwork\Suite\Suite'); + $subIterator = $this->createStub('Behat\Testwork\Specification\SpecificationIterator'); $iterator = new GroupedSpecificationIterator($suite, array( - new SpecificationArrayIterator($suite, array($this->prophesize()->reveal())), + new SpecificationArrayIterator($suite, array($subIterator)), new NoSpecificationsIterator($suite), - new SpecificationArrayIterator($suite, array($this->prophesize()->reveal())), + new SpecificationArrayIterator($suite, array($subIterator)), )); $this->assertEquals(2, iterator_count($iterator)); From 5fdc0bf16b8bdc18024031b5c18b233630063bf7 Mon Sep 17 00:00:00 2001 From: everzet Date: Sat, 19 Oct 2024 14:57:13 +0100 Subject: [PATCH 380/567] Get rid of deprecated E_STRICT --- src/Behat/Testwork/Call/Exception/CallErrorException.php | 1 - src/Behat/Testwork/Call/ServiceContainer/CallExtension.php | 2 +- 2 files changed, 1 insertion(+), 2 deletions(-) diff --git a/src/Behat/Testwork/Call/Exception/CallErrorException.php b/src/Behat/Testwork/Call/Exception/CallErrorException.php index 1622f0fe2..2a1e20d3d 100644 --- a/src/Behat/Testwork/Call/Exception/CallErrorException.php +++ b/src/Behat/Testwork/Call/Exception/CallErrorException.php @@ -25,7 +25,6 @@ final class CallErrorException extends ErrorException E_USER_ERROR => 'User Error', E_USER_WARNING => 'User Warning', E_USER_NOTICE => 'User Notice', - E_STRICT => 'Runtime Notice', E_RECOVERABLE_ERROR => 'Catchable Fatal Error', ); diff --git a/src/Behat/Testwork/Call/ServiceContainer/CallExtension.php b/src/Behat/Testwork/Call/ServiceContainer/CallExtension.php index 09d87fc76..239aadbd2 100644 --- a/src/Behat/Testwork/Call/ServiceContainer/CallExtension.php +++ b/src/Behat/Testwork/Call/ServiceContainer/CallExtension.php @@ -77,7 +77,7 @@ public function configure(ArrayNodeDefinition $builder) ->children() ->scalarNode('error_reporting') ->info('Call executor will catch exceptions matching this level') - ->defaultValue(E_ALL | E_STRICT) + ->defaultValue(E_ALL) ->end() ->end() ; From 382826ef35ee94c03a968d370f8878ea63335767 Mon Sep 17 00:00:00 2001 From: everzet Date: Sat, 19 Oct 2024 15:52:47 +0100 Subject: [PATCH 381/567] Upgrade to Gherkin 4.10 --- composer.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/composer.json b/composer.json index 90e41800e..ff04c1a99 100644 --- a/composer.json +++ b/composer.json @@ -16,7 +16,7 @@ "require": { "php": "^7.2 || ^8.0", "ext-mbstring": "*", - "behat/gherkin": "^4.9.0", + "behat/gherkin": "^4.10.0", "behat/transliterator": "^1.2", "symfony/console": "^4.4 || ^5.0 || ^6.0 || ^7.0", "symfony/config": "^4.4 || ^5.0 || ^6.0 || ^7.0", From 036c5d7489756c3cceccaf0345fca5520d14c8b1 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Sat, 19 Oct 2024 15:00:51 +0000 Subject: [PATCH 382/567] Bump the majors group with 3 updates Bumps the majors group with 3 updates: [actions/checkout](https://github.com/actions/checkout), [actions/upload-artifact](https://github.com/actions/upload-artifact) and [actions/download-artifact](https://github.com/actions/download-artifact). Updates `actions/checkout` from 3 to 4 - [Release notes](https://github.com/actions/checkout/releases) - [Changelog](https://github.com/actions/checkout/blob/main/CHANGELOG.md) - [Commits](https://github.com/actions/checkout/compare/v3...v4) Updates `actions/upload-artifact` from 3 to 4 - [Release notes](https://github.com/actions/upload-artifact/releases) - [Commits](https://github.com/actions/upload-artifact/compare/v3...v4) Updates `actions/download-artifact` from 3 to 4 - [Release notes](https://github.com/actions/download-artifact/releases) - [Commits](https://github.com/actions/download-artifact/compare/v3...v4) --- updated-dependencies: - dependency-name: actions/checkout dependency-type: direct:production update-type: version-update:semver-major dependency-group: majors - dependency-name: actions/upload-artifact dependency-type: direct:production update-type: version-update:semver-major dependency-group: majors - dependency-name: actions/download-artifact dependency-type: direct:production update-type: version-update:semver-major dependency-group: majors ... Signed-off-by: dependabot[bot] --- .github/workflows/build.yml | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 40f6f57e6..b40fad123 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -67,7 +67,7 @@ jobs: symfony-version: '7.0' steps: - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 - name: Setup PHP uses: shivammathur/setup-php@v2 @@ -117,7 +117,7 @@ jobs: composer install --no-dev -o && box.phar build - - uses: actions/upload-artifact@v3 + - uses: actions/upload-artifact@v4 name: Publish the PHAR if: matrix.publish-phar == true with: @@ -128,7 +128,7 @@ jobs: runs-on: ubuntu-latest name: Static analysis steps: - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 - name: Setup PHP uses: shivammathur/setup-php@v2 @@ -149,7 +149,7 @@ jobs: needs: tests if: github.event_name == 'release' steps: - - uses: actions/download-artifact@v3 + - uses: actions/download-artifact@v4 with: name: behat.phar path: . From f3f8e2c692ca315c09510b1640ddbe756a5e855a Mon Sep 17 00:00:00 2001 From: Andrew Coulton Date: Tue, 22 Oct 2024 09:44:31 +0100 Subject: [PATCH 383/567] Fix expected assertion failure for max token length test #1457 updated the policy for token lengths, and updated the test to trigger the assertion, but it missed changing the expected error message. Looks like we missed this till it hit master, because the PR was so stale that the CI either hadn't run on the commit, or ran but has since been archived from github. --- features/definitions_patterns.feature | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/features/definitions_patterns.feature b/features/definitions_patterns.feature index 50b862ee1..772a73a09 100644 --- a/features/definitions_patterns.feature +++ b/features/definitions_patterns.feature @@ -234,7 +234,7 @@ Feature: Step Definition Pattern When I run "behat -f progress --no-colors" Then it should fail with: """ - Token name should not exceed 32 characters, but `too1234567891123456789012345678901` was used. + Token name should not exceed 32 characters, but `too12345678911234567890123456789012` was used. """ Scenario: Multiline definitions From 3f9e62da7c53f1ce811b4f8f44e473bc4e55f9ba Mon Sep 17 00:00:00 2001 From: Vincent Riva Date: Tue, 22 Oct 2024 19:38:33 +0200 Subject: [PATCH 384/567] Update src/Behat/Behat/Tester/Cli/RerunController.php Clarify the description of the option Co-authored-by: Andrew Coulton --- src/Behat/Behat/Tester/Cli/RerunController.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Behat/Behat/Tester/Cli/RerunController.php b/src/Behat/Behat/Tester/Cli/RerunController.php index bb62d8c8a..8b247ed49 100644 --- a/src/Behat/Behat/Tester/Cli/RerunController.php +++ b/src/Behat/Behat/Tester/Cli/RerunController.php @@ -75,7 +75,7 @@ public function configure(Command $command) 'Re-run scenarios that failed during last execution.' ); $command->addOption('--rerun-only', null, InputOption::VALUE_NONE, - 'Re-run scenarios that failed during last execution or exit if no file is found.' + 'Re-run scenarios that failed during last execution, or exit if there were no failures.' ); } From 9c18278221534d0ab713f9930822aa5d74e04c6e Mon Sep 17 00:00:00 2001 From: Godinez Pablo Date: Fri, 9 Apr 2021 17:28:05 +0200 Subject: [PATCH 385/567] Allow profiles to override extensions Fixes #1339 --- features/extension_inheritance.feature | 184 ++++++++++++++++++ .../ServiceContainer/ContainerLoader.php | 22 ++- 2 files changed, 202 insertions(+), 4 deletions(-) create mode 100644 features/extension_inheritance.feature diff --git a/features/extension_inheritance.feature b/features/extension_inheritance.feature new file mode 100644 index 000000000..954098492 --- /dev/null +++ b/features/extension_inheritance.feature @@ -0,0 +1,184 @@ +Feature: Profile extension overrides + In order to organize my profiles + As a tester + I need to be able to override extensions in non-default profiles + + Background: + Given a file named "custom_extension.php" with: + """ + addExtension('custom extension 1'); + } + } + + class CustomExtension implements Behat\Testwork\ServiceContainer\Extension { + public function getConfigKey() + { + return 'custom_extension'; + } + + public function configure(ArrayNodeDefinition $builder) {} + + public function initialize(Behat\Testwork\ServiceContainer\ExtensionManager $extensionManager) {} + + public function load(ContainerBuilder $container, array $config) + { + $definition = $container->register('custom_initializer', 'CustomInitializer'); + $definition->addTag('context.initializer', array('priority' => 100)); + } + + public function process(ContainerBuilder $container) {} + } + + return new CustomExtension; + """ + And a file named "custom_extension2.php" with: + """ + addExtension('custom extension 2'); + } + } + + class CustomExtension2 implements Behat\Testwork\ServiceContainer\Extension { + public function getConfigKey() + { + return 'custom_extension2'; + } + + public function configure(ArrayNodeDefinition $builder) {} + + public function initialize(Behat\Testwork\ServiceContainer\ExtensionManager $extensionManager) {} + + public function load(ContainerBuilder $container, array $config) + { + $definition = $container->register('custom_initializer2', 'CustomInitializer2'); + $definition->addTag('context.initializer', array('priority' => 100)); + } + + public function process(ContainerBuilder $container) {} + } + + return new CustomExtension2; + """ + And a file named "features/bootstrap/FeatureContext.php" with: + """ + loadedExtensions[] = $extensionName; + } + + /** @When this scenario executes */ + public function thisScenarioExecutes() {} + + /** @Then the extension :name should be loaded */ + public function theExtensionLoaded($name) { + PHPUnit\Framework\Assert::assertContains($name, $this->loadedExtensions); + } + + /** @Then the extension :name should not be loaded */ + public function theExtensionNotLoaded($name) { + PHPUnit\Framework\Assert::assertNotContains($name, $this->loadedExtensions); + } + + /** @Then the extension :name should have :key set to :value */ + public function theExtensionHas($name, $key, $value) { + $this->theExtensionLoaded($name); + $this->theExtensionNotLoaded($name); + } + } + """ + + Scenario: Default profile has extension loaded + Given a file named "behat.yml.dist" with: + """ + default: + extensions: + custom_extension.php: ~ + + custom_profile: + extensions: ~ + """ + And a file named "features/extensions.feature" with: + """ + Feature: + Scenario: + When this scenario executes + Then the extension "custom extension 1" should be loaded + """ + When I run "behat -f progress" + Then it should pass + + Scenario: Custom profile disables all extensions + Given a file named "behat.yml.dist" with: + """ + default: + extensions: + custom_extension.php: ~ + + custom_profile: + extensions: ~ + """ + And a file named "features/extensions.feature" with: + """ + Feature: + Scenario: + When this scenario executes + Then the extension "custom extension 1" should not be loaded + """ + When I run "behat -f progress -p custom_profile -vvv" + Then it should pass + + Scenario: Custom profile has an additional extension + Given a file named "behat.yml.dist" with: + """ + default: + extensions: + custom_extension.php: ~ + + custom_profile: + extensions: + custom_extension2.php: ~ + """ + And a file named "features/extensions.feature" with: + """ + Feature: + Scenario: + When this scenario executes + Then the extension "custom extension 1" should be loaded + And the extension "custom extension 2" should be loaded + """ + When I run "behat -f progress -p custom_profile -vvv" + Then it should pass diff --git a/src/Behat/Testwork/ServiceContainer/ContainerLoader.php b/src/Behat/Testwork/ServiceContainer/ContainerLoader.php index 5c343a6ef..0c7b7f241 100644 --- a/src/Behat/Testwork/ServiceContainer/ContainerLoader.php +++ b/src/Behat/Testwork/ServiceContainer/ContainerLoader.php @@ -91,14 +91,28 @@ private function processConfig(array $configs) */ private function initializeExtensions(ContainerBuilder $container, array $configs) { + $extensions = []; foreach ($configs as $i => $config) { - if (isset($config['extensions'])) { + $extensions[$i] = []; + if (array_key_exists('extensions', $config)) { + if (null === $config['extensions']) { + $extensions = []; // Disable all extensions + break; + } foreach ($config['extensions'] as $extensionLocator => $extensionConfig) { - $extension = $this->extensionManager->activateExtension($extensionLocator); - $configs[$i][$extension->getConfigKey()] = $extensionConfig; + $extensions[$i][$extensionLocator] = $extensionConfig; } + } + } + + foreach ($configs as $i => $config) { + unset($configs[$i]['extensions']); + } - unset($configs[$i]['extensions']); + foreach ($extensions as $i => $extensionConfigs) { + foreach ($extensionConfigs as $extensionLocator => $extensionConfig) { + $extension = $this->extensionManager->activateExtension($extensionLocator); + $configs[$i][$extension->getConfigKey()] = $extensionConfig; } } From bc3fab37caf4a90fbb6b6642fec39efea41c42a4 Mon Sep 17 00:00:00 2001 From: Treast Date: Tue, 22 Oct 2024 19:58:32 +0200 Subject: [PATCH 386/567] Add a output if no failed scenario found --- features/rerun-only.feature | 4 ++- .../Behat/Tester/Cli/RerunController.php | 29 +++++++++++++------ 2 files changed, 23 insertions(+), 10 deletions(-) diff --git a/features/rerun-only.feature b/features/rerun-only.feature index 77dc9440d..3c1667351 100644 --- a/features/rerun-only.feature +++ b/features/rerun-only.feature @@ -1,3 +1,4 @@ +@wip Feature: Rerun In order to test only failed scenarios and exit if none is found As a feature developer @@ -139,7 +140,7 @@ Feature: Rerun """ Scenario: Fixing scenario removes it from the rerun log - Given I run "behat --no-colors -f progress features/apples.feature" + Given I run "behat --no-colors -f progress features/apples.feature --rerun-only" And there is a file named "features/apples.feature" with: """ Feature: Apples story @@ -177,4 +178,5 @@ Feature: Rerun And I run "behat --no-colors -f progress features/apples.feature --rerun-only" Then it should pass with: """ + No failure found, exiting """ diff --git a/src/Behat/Behat/Tester/Cli/RerunController.php b/src/Behat/Behat/Tester/Cli/RerunController.php index 8b247ed49..331397773 100644 --- a/src/Behat/Behat/Tester/Cli/RerunController.php +++ b/src/Behat/Behat/Tester/Cli/RerunController.php @@ -71,10 +71,16 @@ public function __construct(EventDispatcherInterface $eventDispatcher, $cachePat */ public function configure(Command $command) { - $command->addOption('--rerun', null, InputOption::VALUE_NONE, + $command->addOption( + '--rerun', + null, + InputOption::VALUE_NONE, 'Re-run scenarios that failed during last execution.' ); - $command->addOption('--rerun-only', null, InputOption::VALUE_NONE, + $command->addOption( + '--rerun-only', + null, + InputOption::VALUE_NONE, 'Re-run scenarios that failed during last execution, or exit if there were no failures.' ); } @@ -100,7 +106,12 @@ public function execute(InputInterface $input, OutputInterface $output) } if (!$this->getFileName() || !file_exists($this->getFileName())) { - return $input->getOption('rerun-only') ? 0 : null; + if ($input->getOption('rerun-only')) { + $output->writeln('No failure found, exiting.'); + return 0; + } + + return null; } $input->setArgument('paths', $this->getFileName()); @@ -159,12 +170,12 @@ private function generateKey(InputInterface $input) { return md5( $input->getParameterOption(array('--profile', '-p')) . - $input->getOption('suite') . - implode(' ', $input->getOption('name')) . - implode(' ', $input->getOption('tags')) . - $input->getOption('role') . - $input->getArgument('paths') . - $this->basepath + $input->getOption('suite') . + implode(' ', $input->getOption('name')) . + implode(' ', $input->getOption('tags')) . + $input->getOption('role') . + $input->getArgument('paths') . + $this->basepath ); } From 93c95a7d397a471002ebba148bfffe3fcaad72dd Mon Sep 17 00:00:00 2001 From: Treast Date: Tue, 22 Oct 2024 21:05:43 +0200 Subject: [PATCH 387/567] Change description on --rerun option & fix formatting --- .../Behat/Tester/Cli/RerunController.php | 24 +++++++------------ 1 file changed, 9 insertions(+), 15 deletions(-) diff --git a/src/Behat/Behat/Tester/Cli/RerunController.php b/src/Behat/Behat/Tester/Cli/RerunController.php index 331397773..0bf6889dd 100644 --- a/src/Behat/Behat/Tester/Cli/RerunController.php +++ b/src/Behat/Behat/Tester/Cli/RerunController.php @@ -71,16 +71,10 @@ public function __construct(EventDispatcherInterface $eventDispatcher, $cachePat */ public function configure(Command $command) { - $command->addOption( - '--rerun', - null, - InputOption::VALUE_NONE, - 'Re-run scenarios that failed during last execution.' + $command->addOption('--rerun', null, InputOption::VALUE_NONE, + 'Re-run scenarios that failed during last execution, or run everything if there were no failures.' ); - $command->addOption( - '--rerun-only', - null, - InputOption::VALUE_NONE, + $command->addOption('--rerun-only', null, InputOption::VALUE_NONE, 'Re-run scenarios that failed during last execution, or exit if there were no failures.' ); } @@ -170,12 +164,12 @@ private function generateKey(InputInterface $input) { return md5( $input->getParameterOption(array('--profile', '-p')) . - $input->getOption('suite') . - implode(' ', $input->getOption('name')) . - implode(' ', $input->getOption('tags')) . - $input->getOption('role') . - $input->getArgument('paths') . - $this->basepath + $input->getOption('suite') . + implode(' ', $input->getOption('name')) . + implode(' ', $input->getOption('tags')) . + $input->getOption('role') . + $input->getArgument('paths') . + $this->basepath ); } From d1dee4775aaf21961be836db560f7270bb04e5c4 Mon Sep 17 00:00:00 2001 From: Treast Date: Tue, 22 Oct 2024 21:10:01 +0200 Subject: [PATCH 388/567] Remove tag on feature --- features/rerun-only.feature | 1 - 1 file changed, 1 deletion(-) diff --git a/features/rerun-only.feature b/features/rerun-only.feature index 3c1667351..acbb45963 100644 --- a/features/rerun-only.feature +++ b/features/rerun-only.feature @@ -1,4 +1,3 @@ -@wip Feature: Rerun In order to test only failed scenarios and exit if none is found As a feature developer From 89160b5665375f06d598ca69416727e0a557628c Mon Sep 17 00:00:00 2001 From: Andrew Coulton Date: Wed, 23 Oct 2024 00:37:45 +0100 Subject: [PATCH 389/567] fix typo in merge conflict resolution --- .../Behat/Tests/Testwork/Subject/GroupedSubjectIteratorTest.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/Behat/Tests/Testwork/Subject/GroupedSubjectIteratorTest.php b/tests/Behat/Tests/Testwork/Subject/GroupedSubjectIteratorTest.php index a72b25ff4..ee7555bd4 100644 --- a/tests/Behat/Tests/Testwork/Subject/GroupedSubjectIteratorTest.php +++ b/tests/Behat/Tests/Testwork/Subject/GroupedSubjectIteratorTest.php @@ -7,7 +7,7 @@ use Behat\Testwork\Specification\SpecificationArrayIterator; use PHPUnit\Framework\TestCase; use Behat\Testwork\Suite\Suite; -Behat\Testwork\Specification\SpecificationIterator; +use Behat\Testwork\Specification\SpecificationIterator; class GroupedSubjectIteratorTest extends TestCase { From 88f2bf651f531306b93ee17bbb8a8aa9f4d3d15b Mon Sep 17 00:00:00 2001 From: Christian Sciberras Date: Wed, 23 Oct 2024 20:39:45 +0200 Subject: [PATCH 390/567] Improve code readability; use ::class references --- .../Annotation/DefinitionAnnotationReader.php | 9 ++++++--- .../Attribute/DefinitionAttributeReader.php | 20 +++++++++---------- 2 files changed, 15 insertions(+), 14 deletions(-) diff --git a/src/Behat/Behat/Definition/Context/Annotation/DefinitionAnnotationReader.php b/src/Behat/Behat/Definition/Context/Annotation/DefinitionAnnotationReader.php index baa6c88ec..9c1baf77a 100644 --- a/src/Behat/Behat/Definition/Context/Annotation/DefinitionAnnotationReader.php +++ b/src/Behat/Behat/Definition/Context/Annotation/DefinitionAnnotationReader.php @@ -12,6 +12,9 @@ use Behat\Behat\Context\Annotation\AnnotationReader; use ReflectionMethod; +use Behat\Behat\Definition\Call\Given; +use Behat\Behat\Definition\Call\When; +use Behat\Behat\Definition\Call\Then; /** * Reads definition annotations from the context class. @@ -28,9 +31,9 @@ final class DefinitionAnnotationReader implements AnnotationReader * @var string[] */ private static $classes = array( - 'given' => 'Behat\Behat\Definition\Call\Given', - 'when' => 'Behat\Behat\Definition\Call\When', - 'then' => 'Behat\Behat\Definition\Call\Then', + 'given' => Given::class, + 'when' => When::class, + 'then' => Then::class, ); /** diff --git a/src/Behat/Behat/Definition/Context/Attribute/DefinitionAttributeReader.php b/src/Behat/Behat/Definition/Context/Attribute/DefinitionAttributeReader.php index 7fcfd2f7c..e9ef4e9cb 100644 --- a/src/Behat/Behat/Definition/Context/Attribute/DefinitionAttributeReader.php +++ b/src/Behat/Behat/Definition/Context/Attribute/DefinitionAttributeReader.php @@ -12,10 +12,8 @@ use Behat\Behat\Context\Annotation\DocBlockHelper; use Behat\Behat\Context\Attribute\AttributeReader; -use Behat\Step\Definition; -use Behat\Step\Given; -use Behat\Step\Then; -use Behat\Step\When; +use Behat\Step as Attribute; +use Behat\Behat\Definition\Call; use ReflectionMethod; /** @@ -26,12 +24,12 @@ final class DefinitionAttributeReader implements AttributeReader { /** - * @var string[] + * @var array, class-string> */ - private static $classes = array( - Given::class => 'Behat\Behat\Definition\Call\Given', - When::class => 'Behat\Behat\Definition\Call\When', - Then::class => 'Behat\Behat\Definition\Call\Then', + private static $attributeToCallMap = array( + Attribute\Given::class => Call\Given::class, + Attribute\When::class => Call\When::class, + Attribute\Then::class => Call\Then::class, ); /** @@ -61,11 +59,11 @@ public function readCallees(string $contextClass, ReflectionMethod $method) /** * @psalm-suppress UndefinedClass (ReflectionAttribute is PHP 8.0 only) */ - $attributes = $method->getAttributes(Definition::class, \ReflectionAttribute::IS_INSTANCEOF); + $attributes = $method->getAttributes(Attribute\Definition::class, \ReflectionAttribute::IS_INSTANCEOF); $callees = []; foreach ($attributes as $attribute) { - $class = self::$classes[$attribute->getName()]; + $class = self::$attributeToCallMap[$attribute->getName()]; $callable = array($contextClass, $method->getName()); $description = null; if ($docBlock = $method->getDocComment()) { From 99cc84b31a27a267f51d99c3f26ce87df6cd9c89 Mon Sep 17 00:00:00 2001 From: Christian Sciberras Date: Wed, 23 Oct 2024 20:45:08 +0200 Subject: [PATCH 391/567] Change assertion order to optimize displayed output --- features/bootstrap/FeatureContext.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/features/bootstrap/FeatureContext.php b/features/bootstrap/FeatureContext.php index 43b1d2f81..ec23f0fb8 100644 --- a/features/bootstrap/FeatureContext.php +++ b/features/bootstrap/FeatureContext.php @@ -268,8 +268,8 @@ public function iRunBehatInDebugMode() */ public function itShouldPassWith($success, PyStringNode $text) { - $this->itShouldFail($success); $this->theOutputShouldContain($text); + $this->itShouldFail($success); } /** @@ -281,8 +281,8 @@ public function itShouldPassWith($success, PyStringNode $text) */ public function itShouldPassWithNoOutput($success) { - $this->itShouldFail($success); Assert::assertEmpty($this->getOutput()); + $this->itShouldFail($success); } /** From 9ee0a777666e7f1ce663e29c81a82fb5ecc0fdc3 Mon Sep 17 00:00:00 2001 From: Christian Sciberras Date: Wed, 23 Oct 2024 21:50:09 +0200 Subject: [PATCH 392/567] Avoid arbitrary output in tests --- features/bootstrap/FeatureContext.php | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/features/bootstrap/FeatureContext.php b/features/bootstrap/FeatureContext.php index 43b1d2f81..8651353fe 100644 --- a/features/bootstrap/FeatureContext.php +++ b/features/bootstrap/FeatureContext.php @@ -394,18 +394,20 @@ private function getExpectedOutput(PyStringNode $expectedText) */ public function itShouldFail($success) { + $message = ''; + if ('fail' === $success) { if (0 === $this->getExitCode()) { - echo 'Actual output:' . PHP_EOL . PHP_EOL . $this->getOutput(); + $message = 'Actual output:' . PHP_EOL . PHP_EOL . $this->getOutput(); } - Assert::assertNotEquals(0, $this->getExitCode()); + Assert::assertNotEquals(0, $this->getExitCode(), $message); } else { if (0 !== $this->getExitCode()) { - echo 'Actual output:' . PHP_EOL . PHP_EOL . $this->getOutput(); + $message = 'Actual output:' . PHP_EOL . PHP_EOL . $this->getOutput(); } - Assert::assertEquals(0, $this->getExitCode()); + Assert::assertEquals(0, $this->getExitCode(), $message); } } From 37f0ec59f291c82cc6406faa36d3dc6ee69eafb3 Mon Sep 17 00:00:00 2001 From: Christian Sciberras Date: Wed, 23 Oct 2024 22:00:20 +0200 Subject: [PATCH 393/567] Remove IDE-specific annotation --- .../Tests/Testwork/Argument/MixedArgumentOrganiserTest.php | 2 -- 1 file changed, 2 deletions(-) diff --git a/tests/Behat/Tests/Testwork/Argument/MixedArgumentOrganiserTest.php b/tests/Behat/Tests/Testwork/Argument/MixedArgumentOrganiserTest.php index d66f685ef..7408d0e44 100644 --- a/tests/Behat/Tests/Testwork/Argument/MixedArgumentOrganiserTest.php +++ b/tests/Behat/Tests/Testwork/Argument/MixedArgumentOrganiserTest.php @@ -1,7 +1,5 @@ Date: Wed, 23 Oct 2024 22:14:52 +0200 Subject: [PATCH 394/567] Remove unused timer instances --- .../Output/Node/EventListener/JUnit/JUnitDurationListener.php | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/Behat/Behat/Output/Node/EventListener/JUnit/JUnitDurationListener.php b/src/Behat/Behat/Output/Node/EventListener/JUnit/JUnitDurationListener.php index 2874087be..3e2af09f8 100644 --- a/src/Behat/Behat/Output/Node/EventListener/JUnit/JUnitDurationListener.php +++ b/src/Behat/Behat/Output/Node/EventListener/JUnit/JUnitDurationListener.php @@ -78,6 +78,7 @@ private function captureAfterScenarioEvent(Event $event): void if ($timer instanceof Timer) { $timer->stop(); $this->resultStore[$key] = $timer->getTime(); + unset($this->scenarioTimerStore[$key]); } } @@ -92,6 +93,7 @@ private function captureAfterFeatureEvent(Event $event): void if ($timer instanceof Timer) { $timer->stop(); $this->featureResultStore[$key] = $timer->getTime(); + unset($this->featureTimerStore[$key]); } } From 419053933ad8e613148269b35d1f48b0f6fa38b8 Mon Sep 17 00:00:00 2001 From: Andreas Heigl Date: Tue, 22 Oct 2024 23:25:17 -0700 Subject: [PATCH 395/567] Modifies biuld process to allow better tests --- .github/workflows/build.yml | 60 ++++++++++++++++++++++++++----------- 1 file changed, 42 insertions(+), 18 deletions(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index aeeecacff..0698e4d56 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -23,13 +23,6 @@ jobs: composer-mode: [update] symfony-version: [''] include: - # Get the latest stable PHP to publish the phar - - php: 8.3 - os: ubuntu-latest - composer-mode: update - publish-phar: true - symfony-version: '' - # 7.2 build with lowest dependencies - php: 7.2 os: ubuntu-latest @@ -144,25 +137,56 @@ jobs: - name: Build the PHAR run: | - composer config platform.php ^7.2.34 + composer config platform.php 7.2.34 composer update --no-dev -o - box build + box compile - - name: Test the PHAR - run: | - behat.phar --version - - - uses: actions/upload-artifact@v3 - name: Upload PHAR artifact + - name: cache artifact + uses: actions/upload-artifact@v4 with: - name: behat.phar - path: behat.phar + name: behat.phar + path: behat.phar + + + test-phar: + needs: build-phar + runs-on: ubuntu-latest + name: test PHAR file + strategy: + fail-fast: false + matrix: + php: [ '7.2', '7.3', '7.4', '8.0', '8.1', '8.2', '8.3', '8.4' ] + steps: + - uses: actions/checkout@v4 + - name: Setup PHP + uses: shivammathur/setup-php@v2 + with: + php-version: "${{ matrix.php }}" + ini-values: "phar.readonly=0,zend.exception_ignore_args=Off" + coverage: none + + - name: Install dependencies + run: composer install + + + - uses: actions/download-artifact@v4 + with: + name: behat.phar + + - name: "Check content" + run: | + ls -R . + + - name: Test the PHAR + run: | + php ./behat.phar --version + php ./behat.phar publish-phar: runs-on: ubuntu-latest name: Publish the PHAR for release - needs: build-phar + needs: test-phar if: github.event_name == 'release' steps: - uses: actions/download-artifact@v4 From 03d54d0296d122ca40f4102c4afbc9f48b7eed19 Mon Sep 17 00:00:00 2001 From: Andreas Heigl Date: Wed, 23 Oct 2024 16:08:52 -0700 Subject: [PATCH 396/567] Remove running behat against behat That causes some odd sideeffects when trying to run the tests inside the phar. This needs more investigation and a separate PR. The main reason for testing the PR was testing that no immediate problems arise in the PHAR file. That should already be tested when running the `--version` command --- .github/workflows/build.yml | 2 -- 1 file changed, 2 deletions(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 0698e4d56..e93422a50 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -180,8 +180,6 @@ jobs: - name: Test the PHAR run: | php ./behat.phar --version - php ./behat.phar - publish-phar: runs-on: ubuntu-latest From 3f4d84a58310a1003e510d40cc8552e633f91be8 Mon Sep 17 00:00:00 2001 From: Andreas Heigl Date: Fri, 25 Oct 2024 06:27:33 -0700 Subject: [PATCH 397/567] Build PHAR without waiting for tests This will bring down the build time as building and testing can happen in parallel to the testing. This will make publishing the PHAR though dependent on the PHAR tests as well as the general testruns to make sure that a PHAR is only published when all tests are green --- .github/workflows/build.yml | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index e93422a50..ebc0d07a5 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -121,7 +121,6 @@ jobs: run: ./vendor/bin/psalm --output-format=github build-phar: - needs: tests runs-on: ubuntu-latest name: Build PHAR file steps: @@ -184,7 +183,7 @@ jobs: publish-phar: runs-on: ubuntu-latest name: Publish the PHAR for release - needs: test-phar + needs: [test-phar, tests] if: github.event_name == 'release' steps: - uses: actions/download-artifact@v4 From b53791916b98ab061b9c2593692eccba74e543b9 Mon Sep 17 00:00:00 2001 From: Carlos Granados Date: Sat, 26 Oct 2024 12:08:42 +0100 Subject: [PATCH 398/567] docs: update the "Submitting a Pull Request" section of the "contributing" docs --- CONTRIBUTING.md | 14 ++++++-------- 1 file changed, 6 insertions(+), 8 deletions(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 5754932c1..ac5c297e1 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -26,18 +26,16 @@ us reduce the clutter of "silent issues" ## Submitting a Pull Request 1. Make your feature addition, bug fix or refactoring -2. Add new `Scenario` into [one of existing features](features) or create a new `.feature` file describing +2. Add a new `Scenario` into [one of the existing features](features) or create a new `.feature` file describing the changes. Check the [features/](features) folder for examples. This is important so we don't break the changes you introduced in a future version unintentionally -3. Make sure your changes adhere to [Backwards Compatibility](#backwards-compatibility) rules. This is important +3. Make sure your changes adhere to the [Backwards Compatibility](#backwards-compatibility) rules. This is important so that we adhere to [Semantic Versioning v2.0.0](http://semver.org/spec/v2.0.0.html) -4. Explain the kind of change you made under the [`[Unreleased]`](CHANGELOG.md#unreleased) section of the -[CHANGELOG.md](CHANGELOG.md). You'd make our life even easier if you stick to [Keep a Changelog](http://keepachangelog.com/en/0.3.0/) format 5. Do not mess with the [`BehatApplication::VERSION`](src/Behat/Behat/ApplicationFactory.php#L48) version -6. Make sure you [ran tests](#running-tests) and didn't break anything. That will save some time for -[GitHub](https://github.com/Behat/Behat/actions) -7. Commit your code and submit a Pull Request, providing a clear description of a change, -similar to the one you did in the changelog +6. Make sure you [ran the tests](#running-tests) and didn't break anything. That will save some time on +[GitHub actions](https://github.com/Behat/Behat/actions) +7. Commit your code and submit a Pull Request, providing a clear description of the change, including +the motivation for the proposal ## Backwards compatibility From 35e5b02d401954b455b94e512e64ab7c718a6509 Mon Sep 17 00:00:00 2001 From: Andrew Nicols Date: Sun, 14 Feb 2021 13:23:18 +0800 Subject: [PATCH 399/567] Add support for specification of a prefered profile In many situations it is desirable to have a specific profile that is used when none is specified, however because of the way in which all profiles inherit from the `default` profile, this is not currently possible. For example, if you have different MinkExtension configurations for a range of different browsers, then each browser may only be specified in its own profile. This works well, but often you will want to specify a default browser configuration. To achieve this you may think that you can set the Extension configuration for your preferred browser into the `default` profile, but this means that all other profiles will include this configuration, and may not work as expected. This change introduces the concept of a preferred profile, which is the profile which will be used unless the `--profile` CLI argument is provided to override it. This means that if you have profiles for chrome, headlesschrome, firefox, headlessfirefox, edge, and headlessedge, you can choose to specify a preferred profile of `headlesschrome`, which will be used unless you explicitly set the `--profile` argument when running behat. --- features/preferred_profile.feature | 144 ++++++++++++++++++ .../Configuration/ConfigurationLoader.php | 26 ++++ 2 files changed, 170 insertions(+) create mode 100644 features/preferred_profile.feature diff --git a/features/preferred_profile.feature b/features/preferred_profile.feature new file mode 100644 index 000000000..a4d22cbc1 --- /dev/null +++ b/features/preferred_profile.feature @@ -0,0 +1,144 @@ +Feature: Preferred Profiles + In order to test my preferred profile + As a tester + I need to be able to specify a preferred profile + + Background: + Given a file named "features/bootstrap/FeatureContext.php" with: + """ + result = 0; + $this->numbers = array(); + } + + /** + * @Given /I have entered (\d+)/ + */ + public function iHaveEntered($number) { + $this->numbers[] = intval($number); + } + + /** + * @When /I add/ + */ + public function iAdd() { + $this->result = array_sum($this->numbers); + $this->numbers = array(); + } + + /** + * @When /I sub/ + */ + public function iSub() { + $this->result = array_shift($this->numbers); + $this->result -= array_sum($this->numbers); + $this->numbers = array(); + } + + /** + * @Then /The result should be (\d+)/ + */ + public function theResultShouldBe($result) { + PHPUnit\Framework\Assert::assertEquals($result, $this->result); + } + } + """ + And a file named "features/math.feature" with: + """ + Feature: Math + Background: + Given I have basic calculator + + Scenario Outline: + Given I have entered + And I have entered + When I add + Then The result should be + + Examples: + | number1 | number2 | result | + | 10 | 12 | 22 | + | 5 | 3 | 8 | + | 5 | 5 | 10 | + """ + And a file named "pretty.yml" with: + """ + pretty_without_paths: + formatters: + progress: false + pretty: + paths: false + + """ + And a file named "behat.yml" with: + """ + default: + + progress: + formatters: + progress: true + pretty: false + + preferredProfileName: + progress + + imports: + - pretty.yml + """ + + Scenario: + Given I run "behat --no-colors features/math.feature" + Then it should pass with: + """ + ............... + + 3 scenarios (3 passed) + 15 steps (15 passed) + """ + + Scenario: + Given I run "behat --no-colors features/math.feature --profile progress" + Then it should pass with: + """ + ............... + + 3 scenarios (3 passed) + 15 steps (15 passed) + """ + + Scenario: + Given I run "behat --no-colors --profile pretty_without_paths" + Then it should pass with: + """ + Feature: Math + + Background: + Given I have basic calculator + + Scenario Outline: + Given I have entered + And I have entered + When I add + Then The result should be + + Examples: + | number1 | number2 | result | + | 10 | 12 | 22 | + | 5 | 3 | 8 | + | 5 | 5 | 10 | + + 3 scenarios (3 passed) + 15 steps (15 passed) + """ diff --git a/src/Behat/Testwork/ServiceContainer/Configuration/ConfigurationLoader.php b/src/Behat/Testwork/ServiceContainer/Configuration/ConfigurationLoader.php index dfc02eb4d..92f8dd7b1 100644 --- a/src/Behat/Testwork/ServiceContainer/Configuration/ConfigurationLoader.php +++ b/src/Behat/Testwork/ServiceContainer/Configuration/ConfigurationLoader.php @@ -213,6 +213,8 @@ private function loadConfigs($basePath, array $config, $profile) { $configs = array(); + $profile = $this->getProfileName($config, $profile); + // first load default profile from current config, but only if custom profile requested if ('default' !== $profile && isset($config['default'])) { $configs[] = $config['default']; @@ -229,9 +231,33 @@ private function loadConfigs($basePath, array $config, $profile) $this->profileFound = true; } + if (!$this->profileFound && isset($config['preferredProfileName'])) { + throw new ConfigurationLoadingException(sprintf( + 'Can not find configuration for `%s` profile.', + $config['preferredProfileName'] + )); + } + return $configs; } + /** + * Get the name of the requested profile, after considering any preferred profile name. + * + * @param array $config + * @param string $profile + * + * @return string + */ + private function getProfileName(array $config, string $profile): string + { + if (isset($config['preferredProfileName']) && 'default' === $profile) { + return $config['preferredProfileName']; + } + + return $profile; + } + /** * Loads all provided imports. * From 60c938febcd5f92ca0e0e3ff18bfb8345dbdc870 Mon Sep 17 00:00:00 2001 From: Andrew Coulton Date: Sun, 27 Oct 2024 01:39:50 +0100 Subject: [PATCH 400/567] chore: Update links in README to https, drop dead channels The freenode IRC no longer exists (as far as I know), and the google group exists but appears to be entirely spam emails. Neither of these are likely to be good destinations for community / support in 2024 so I have removed them. All other links are now https (some were http). Replaces #1468 --- README.md | 12 +++++------- 1 file changed, 5 insertions(+), 7 deletions(-) diff --git a/README.md b/README.md index cbe269118..47b9e004e 100644 --- a/README.md +++ b/README.md @@ -44,26 +44,24 @@ Before contributing to Behat, please take a look at the [CONTRIBUTING.md](CONTRI Versioning ---------- -Starting from `v3.0.0`, Behat is following [Semantic Versioning v2.0.0](http://semver.org/spec/v2.0.0.html). +Starting from `v3.0.0`, Behat is following [Semantic Versioning v2.0.0](https://semver.org/spec/v2.0.0.html). This basically means that if all you do is implement interfaces (like [this one](https://github.com/Behat/Behat/blob/v3.1.0/src/Behat/Behat/Context/ContextClass/ClassResolver.php#L15-L22)) and use service constants (like [this one](https://github.com/Behat/Behat/blob/v3.1.0/src/Behat/Behat/Context/ServiceContainer/ContextExtension.php#L46)), you would not have any backwards compatibility issues with Behat up until `v4.0.0` (or later major) is released. Exception could be an extremely rare case where BC break is introduced as a measure to fix a serious issue. -You can read detailed guidance on what BC means in [Symfony BC guide](http://symfony.com/doc/current/contributing/code/bc.html). +You can read detailed guidance on what BC means in [Symfony BC guide](https://symfony.com/doc/current/contributing/code/bc.html). Useful Links ------------ -- The main website is at [http://behat.org](http://behat.org) -- The documentation is at [http://docs.behat.org/en/latest/](http://docs.behat.org/en/latest/) -- Official Google Group is at [http://groups.google.com/group/behat](http://groups.google.com/group/behat) -- IRC channel on [#freenode](http://freenode.net/) is `#behat` +- The main website is at [https://behat.org](https://behat.org) +- The documentation is at [https://docs.behat.org/en/latest/](https://docs.behat.org/en/latest/) - [Note on Patches/Pull Requests](CONTRIBUTING.md) Contributors ------------ -- Konstantin Kudryashov [everzet](http://github.com/everzet) [lead developer] +- Konstantin Kudryashov [everzet](https://github.com/everzet) [lead developer] - Other [awesome developers](https://github.com/Behat/Behat/graphs/contributors) From 0bb3554548d122522a9666bf61ba321f60cc27dd Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 28 Oct 2024 21:00:20 +0000 Subject: [PATCH 401/567] Bump actions/checkout from 3 to 4 in the majors group Bumps the majors group with 1 update: [actions/checkout](https://github.com/actions/checkout). Updates `actions/checkout` from 3 to 4 - [Release notes](https://github.com/actions/checkout/releases) - [Changelog](https://github.com/actions/checkout/blob/main/CHANGELOG.md) - [Commits](https://github.com/actions/checkout/compare/v3...v4) --- updated-dependencies: - dependency-name: actions/checkout dependency-type: direct:production update-type: version-update:semver-major dependency-group: majors ... Signed-off-by: dependabot[bot] --- .github/workflows/build.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index ebc0d07a5..fe8feae6e 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -124,7 +124,7 @@ jobs: runs-on: ubuntu-latest name: Build PHAR file steps: - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 - name: Setup PHP uses: shivammathur/setup-php@v2 From 7944acfabfdf976a7588bb8357f3d9314814a091 Mon Sep 17 00:00:00 2001 From: acoulton Date: Tue, 29 Oct 2024 13:39:29 +0000 Subject: [PATCH 402/567] chore: Add changelog entries missing for 3.14.0 These were only published on the github release (I have reordered / reworded). --- CHANGELOG.md | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 0a87f7474..92dff7387 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,21 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](http://keepachangelog.com/) and this project adheres to [Semantic Versioning](http://semver.org/). +## [3.14.0] - 2024-01-10 + +### Added + +* 🎉 Symfony 7 is now supported 🎉 by @dmaicher in [#1442](https://github.com/Behat/Behat/pull/1442) +* PHP 8.3 is now supported (no code changes were required) by @jrfnl in [#1440](https://github.com/Behat/Behat/pull/1440) + +### Fixed + +* Renamed method parameters to match signatures from interfaces by @ciaranmcnulty in [#1434](https://github.com/Behat/Behat/pull/1434) + +### Internal + +* CI improvements by @stof in [#1430](https://github.com/Behat/Behat/pull/1430) + ## [3.13.0] - 2023-04-18 ### Added From 47fd4274faaae2760ce8238885b92297d69e8755 Mon Sep 17 00:00:00 2001 From: acoulton Date: Tue, 29 Oct 2024 16:17:58 +0000 Subject: [PATCH 403/567] chore: Add changelog for 3.15.0 --- CHANGELOG.md | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 92dff7387..4ef68c7e4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,37 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](http://keepachangelog.com/) and this project adheres to [Semantic Versioning](http://semver.org/). +## [3.15.0] - 2024-10-29 + +### Added + +* PHP 8.4 support by @heiglandreas in [#1473](https://github.com/Behat/Behat/pull/1473), @jrfnl in [#1478](https://github.com/Behat/Behat/pull/1478), + @jrfnl in [#1477](https://github.com/Behat/Behat/pull/1477) +* Support config files named `behat.dist.y[a]ml` by @uuf6429 in [#1464](https://github.com/Behat/Behat/pull/1464) +* Add a `--rerun-only` flag to immediately exit 0 without running anything if there were no failures on the previous run + by @Treast in [#1466](https://github.com/Behat/Behat/pull/1466) +* Allow profiles to override extensions in the config file by @Zayon in [#1341](https://github.com/Behat/Behat/pull/1341) +* Support configuring a preferred profile to use instead of `default` if nothing was specified at runtime + by @andrewnicols in [#1334](https://github.com/Behat/Behat/pull/1334) +* Add void return type when generating new snippets by @carlos-granados in [#1463](https://github.com/Behat/Behat/pull/1463) + +### Fixed + +* Fix enforcing that 32 character (or longer) turnip pattern names are not allowed + by @ivastly in [#1457](https://github.com/Behat/Behat/pull/1457) and @acoulton in [#1483](https://github.com/Behat/Behat/pull/1483) +* Fix generating the PHAR for releases by upgrading the build tooling by @heiglandreas in [#1462](https://github.com/Behat/Behat/pull/1462) + +### Internal + +* Improve code readability; use ::class references by @uuf6429 in [#1485](https://github.com/Behat/Behat/pull/1485) +* Fix autoloading unit tests and improve some code style & assertion failure messages by @uuf6429 in [#1427](https://github.com/Behat/Behat/pull/1427), + [#1486](https://github.com/Behat/Behat/pull/1486) and [#1487](https://github.com/Behat/Behat/pull/1487) and by + @jrfnl in [#1479](https://github.com/Behat/Behat/pull/1479) +* Add .editorconfig file by @chapeupreto in [#1418](https://github.com/Behat/Behat/pull/1418) +* Updates to github actions workflows @jrfnl in [#1475](https://github.com/Behat/Behat/pull/1475),[#1474](https://github.com/Behat/Behat/pull/1474), +* Update contributing docs and README links by @carlos-granados in [#1489](https://github.com/Behat/Behat/pull/1489) and + [#1492](https://github.com/Behat/Behat/pull/1492) + ## [3.14.0] - 2024-01-10 ### Added From a09e235f52841997da957ffb106f120f8c19c36a Mon Sep 17 00:00:00 2001 From: Julien Deniau Date: Wed, 30 Oct 2024 00:30:58 +0100 Subject: [PATCH 404/567] Add ConfigurationExtension And allows equivalent of `--stop-on-failure` cli argument --- .../stop_on_failure_configuration.feature | 113 ++++++++++++++++++ src/Behat/Behat/ApplicationFactory.php | 4 +- .../Handler/StopOnFailureHandler.php | 72 +++++++++++ .../ConfigurationExtension.php | 86 +++++++++++++ 4 files changed, 274 insertions(+), 1 deletion(-) create mode 100644 features/stop_on_failure_configuration.feature create mode 100644 src/Behat/Behat/Configuration/Handler/StopOnFailureHandler.php create mode 100644 src/Behat/Behat/Configuration/ServiceContainer/ConfigurationExtension.php diff --git a/features/stop_on_failure_configuration.feature b/features/stop_on_failure_configuration.feature new file mode 100644 index 000000000..642cf0f83 --- /dev/null +++ b/features/stop_on_failure_configuration.feature @@ -0,0 +1,113 @@ +Feature: Stop on failure via configuration + In order to stop further execution of steps when first step fails + As a feature developer + I need to have a configuration.stop_on_failure sets to true + + Background: + Given a file named "features/bootstrap/FeatureContext.php" with: + """ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Behat\Behat\Configuration\Handler; + +use Behat\Behat\EventDispatcher\Event\AfterScenarioTested; +use Behat\Behat\EventDispatcher\Event\ExampleTested; +use Behat\Behat\EventDispatcher\Event\ScenarioTested; +use Behat\Testwork\EventDispatcher\Event\AfterExerciseAborted; +use Behat\Testwork\EventDispatcher\Event\AfterSuiteAborted; +use Behat\Testwork\EventDispatcher\Event\ExerciseCompleted; +use Behat\Testwork\EventDispatcher\Event\SuiteTested; +use Behat\Testwork\Tester\Result\Interpretation\ResultInterpretation; +use Behat\Testwork\Tester\Result\Interpretation\StrictInterpretation; +use Symfony\Component\EventDispatcher\EventDispatcherInterface; +use Symfony\Component\EventDispatcher\EventSubscriberInterface; + +/** + * Enables stop on failure via configuration. + */ +final class StopOnFailureHandler implements EventSubscriberInterface +{ + + /** + * @var EventDispatcherInterface + */ + private $eventDispatcher; + + /** + * @var ResultInterpretation + */ + private $resultInterpretation; + + public function __construct(EventDispatcherInterface $eventDispatcher) + { + $this->eventDispatcher = $eventDispatcher; + $this->resultInterpretation = new StrictInterpretation(); + } + + public static function getSubscribedEvents() + { + return array( + ScenarioTested::AFTER => array('exitOnFailure', -100), + ExampleTested::AFTER => array('exitOnFailure', -100), + ); + } + + + /** + * Exits if scenario is a failure and if stopper is enabled. + * + * @param AfterScenarioTested $event + */ + public function exitOnFailure(AfterScenarioTested $event) + { + if (!$this->resultInterpretation->isFailure($event->getTestResult())) { + return; + } + + $this->eventDispatcher->dispatch(new AfterSuiteAborted($event->getEnvironment()), SuiteTested::AFTER); + $this->eventDispatcher->dispatch(new AfterExerciseAborted(), ExerciseCompleted::AFTER); + + exit(1); + } +} \ No newline at end of file diff --git a/src/Behat/Behat/Configuration/ServiceContainer/ConfigurationExtension.php b/src/Behat/Behat/Configuration/ServiceContainer/ConfigurationExtension.php new file mode 100644 index 000000000..aed37388a --- /dev/null +++ b/src/Behat/Behat/Configuration/ServiceContainer/ConfigurationExtension.php @@ -0,0 +1,86 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Behat\Behat\Configuration\ServiceContainer; + +use Behat\Testwork\EventDispatcher\ServiceContainer\EventDispatcherExtension; +use Behat\Testwork\ServiceContainer\Extension; +use Behat\Testwork\ServiceContainer\ExtensionManager; +use Symfony\Component\Config\Definition\Builder\ArrayNodeDefinition; +use Symfony\Component\DependencyInjection\ContainerBuilder; +use Symfony\Component\DependencyInjection\Definition; +use Symfony\Component\DependencyInjection\Reference; + +/** + * Enables stop on failure controller for Behat. + */ +final class ConfigurationExtension implements Extension +{ + /** + * {@inheritdoc} + */ + public function getConfigKey() + { + return 'configuration'; + } + + /** + * {@inheritdoc} + */ + public function initialize(ExtensionManager $extensionManager) + { + } + + /** + * {@inheritdoc} + */ + public function configure(ArrayNodeDefinition $builder) + { + $builder + ->addDefaultsIfNotSet() + ->children() + ->scalarNode('stop_on_failure') + ->defaultValue(false) + ->treatNullLike(false) + ->end() + ->end() + ; + } + + /** + * {@inheritdoc} + */ + public function load(ContainerBuilder $container, array $config) + { + if ($config['stop_on_failure'] === true) { + $this->loadStopOnFailureController($container); + } + } + + /** + * {@inheritdoc} + */ + public function process(ContainerBuilder $container) + { + } + + + /** + * Loads stop on failure controller. + */ + private function loadStopOnFailureController(ContainerBuilder $container) + { + $definition = new Definition('Behat\Behat\Configuration\Handler\StopOnFailureHandler', array( + new Reference(EventDispatcherExtension::DISPATCHER_ID) + )); + $definition->addTag(EventDispatcherExtension::SUBSCRIBER_TAG); + $container->setDefinition('configuration.stop_on_failure', $definition); + } +} From 84175abf6c12b2042bd5cae6ea3346bd17b021e2 Mon Sep 17 00:00:00 2001 From: Julien Deniau Date: Wed, 30 Oct 2024 01:15:49 +0100 Subject: [PATCH 405/567] deduplicate cli event listener --- .../Handler/StopOnFailureHandler.php | 20 +++++---- .../ConfigurationExtension.php | 14 ++++--- .../Cli/StopOnFailureController.php | 42 +++++-------------- .../EventDispatcherExtension.php | 3 +- 4 files changed, 33 insertions(+), 46 deletions(-) diff --git a/src/Behat/Behat/Configuration/Handler/StopOnFailureHandler.php b/src/Behat/Behat/Configuration/Handler/StopOnFailureHandler.php index fcc340b38..ed5fd1b14 100644 --- a/src/Behat/Behat/Configuration/Handler/StopOnFailureHandler.php +++ b/src/Behat/Behat/Configuration/Handler/StopOnFailureHandler.php @@ -25,7 +25,7 @@ /** * Enables stop on failure via configuration. */ -final class StopOnFailureHandler implements EventSubscriberInterface +final class StopOnFailureHandler { /** @@ -43,15 +43,19 @@ public function __construct(EventDispatcherInterface $eventDispatcher) $this->eventDispatcher = $eventDispatcher; $this->resultInterpretation = new StrictInterpretation(); } - - public static function getSubscribedEvents() + + /** + * @param ?ResultInterpretation $resultInterpretation + */ + public function registerListeners($resultInterpretation = null) { - return array( - ScenarioTested::AFTER => array('exitOnFailure', -100), - ExampleTested::AFTER => array('exitOnFailure', -100), - ); + if ($resultInterpretation) { + $this->resultInterpretation = $resultInterpretation; + } + + $this->eventDispatcher->addListener(ScenarioTested::AFTER, array($this, 'exitOnFailure'), -100); + $this->eventDispatcher->addListener(ExampleTested::AFTER, array($this, 'exitOnFailure'), -100); } - /** * Exits if scenario is a failure and if stopper is enabled. diff --git a/src/Behat/Behat/Configuration/ServiceContainer/ConfigurationExtension.php b/src/Behat/Behat/Configuration/ServiceContainer/ConfigurationExtension.php index aed37388a..5cbc68722 100644 --- a/src/Behat/Behat/Configuration/ServiceContainer/ConfigurationExtension.php +++ b/src/Behat/Behat/Configuration/ServiceContainer/ConfigurationExtension.php @@ -23,6 +23,8 @@ */ final class ConfigurationExtension implements Extension { + public const STOP_ON_FAILURE_ID = 'configuration.stop_on_failure'; + /** * {@inheritdoc} */ @@ -59,9 +61,7 @@ public function configure(ArrayNodeDefinition $builder) */ public function load(ContainerBuilder $container, array $config) { - if ($config['stop_on_failure'] === true) { - $this->loadStopOnFailureController($container); - } + $this->loadStopOnFailureController($container, $config); } /** @@ -75,12 +75,14 @@ public function process(ContainerBuilder $container) /** * Loads stop on failure controller. */ - private function loadStopOnFailureController(ContainerBuilder $container) + private function loadStopOnFailureController(ContainerBuilder $container, array $config) { $definition = new Definition('Behat\Behat\Configuration\Handler\StopOnFailureHandler', array( new Reference(EventDispatcherExtension::DISPATCHER_ID) )); - $definition->addTag(EventDispatcherExtension::SUBSCRIBER_TAG); - $container->setDefinition('configuration.stop_on_failure', $definition); + if ($config['stop_on_failure'] === true) { + $definition->addMethodCall('registerListeners'); + } + $container->setDefinition(self::STOP_ON_FAILURE_ID, $definition); } } diff --git a/src/Behat/Behat/EventDispatcher/Cli/StopOnFailureController.php b/src/Behat/Behat/EventDispatcher/Cli/StopOnFailureController.php index b4e13e081..61b009edd 100644 --- a/src/Behat/Behat/EventDispatcher/Cli/StopOnFailureController.php +++ b/src/Behat/Behat/EventDispatcher/Cli/StopOnFailureController.php @@ -10,6 +10,7 @@ namespace Behat\Behat\EventDispatcher\Cli; +use Behat\Behat\Configuration\Handler\StopOnFailureHandler; use Behat\Behat\EventDispatcher\Event\AfterScenarioTested; use Behat\Behat\EventDispatcher\Event\ExampleTested; use Behat\Behat\EventDispatcher\Event\ScenarioTested; @@ -26,7 +27,6 @@ use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; -use Symfony\Component\EventDispatcher\EventDispatcherInterface; /** * Stops tests on first scenario failure. @@ -36,24 +36,18 @@ final class StopOnFailureController implements Controller { /** - * @var EventDispatcherInterface + * @var StopOnFailureHandler */ - private $eventDispatcher; - - /** - * @var ResultInterpretation - */ - private $resultInterpretation; + private $stopOnFailureHandler; /** * Initializes controller. * - * @param EventDispatcherInterface $eventDispatcher + * @param StopOnFailureHandler $stopOnFailureHandler */ - public function __construct(EventDispatcherInterface $eventDispatcher) + public function __construct(StopOnFailureHandler $stopOnFailureHandler) { - $this->eventDispatcher = $eventDispatcher; - $this->resultInterpretation = new SoftInterpretation(); + $this->stopOnFailureHandler = $stopOnFailureHandler; } /** @@ -82,28 +76,14 @@ public function execute(InputInterface $input, OutputInterface $output) return null; } + if ($input->getOption('strict')) { - $this->resultInterpretation = new StrictInterpretation(); + $resultInterpretation = new StrictInterpretation(); + } else { + $resultInterpretation = new SoftInterpretation(); } - $this->eventDispatcher->addListener(ScenarioTested::AFTER, array($this, 'exitOnFailure'), -100); - $this->eventDispatcher->addListener(ExampleTested::AFTER, array($this, 'exitOnFailure'), -100); + $this->stopOnFailureHandler->registerListeners($resultInterpretation); } - /** - * Exits if scenario is a failure and if stopper is enabled. - * - * @param AfterScenarioTested $event - */ - public function exitOnFailure(AfterScenarioTested $event) - { - if (!$this->resultInterpretation->isFailure($event->getTestResult())) { - return; - } - - $this->eventDispatcher->dispatch(new AfterSuiteAborted($event->getEnvironment()), SuiteTested::AFTER); - $this->eventDispatcher->dispatch(new AfterExerciseAborted(), ExerciseCompleted::AFTER); - - exit(1); - } } diff --git a/src/Behat/Behat/EventDispatcher/ServiceContainer/EventDispatcherExtension.php b/src/Behat/Behat/EventDispatcher/ServiceContainer/EventDispatcherExtension.php index 0aa06952c..3b27d9a74 100644 --- a/src/Behat/Behat/EventDispatcher/ServiceContainer/EventDispatcherExtension.php +++ b/src/Behat/Behat/EventDispatcher/ServiceContainer/EventDispatcherExtension.php @@ -10,6 +10,7 @@ namespace Behat\Behat\EventDispatcher\ServiceContainer; +use Behat\Behat\Configuration\ServiceContainer\ConfigurationExtension; use Behat\Behat\EventDispatcher\Event\ExampleTested; use Behat\Behat\EventDispatcher\Event\ScenarioTested; use Behat\Behat\Tester\ServiceContainer\TesterExtension; @@ -51,7 +52,7 @@ public function load(ContainerBuilder $container, array $config) protected function loadStopOnFailureController(ContainerBuilder $container) { $definition = new Definition('Behat\Behat\EventDispatcher\Cli\StopOnFailureController', array( - new Reference(EventDispatcherExtension::DISPATCHER_ID) + new Reference(ConfigurationExtension::STOP_ON_FAILURE_ID) )); $definition->addTag(CliExtension::CONTROLLER_TAG, array('priority' => 100)); $container->setDefinition(CliExtension::CONTROLLER_TAG . '.stop_on_failure', $definition); From 99da70e54e8bc8241d4e239d7a2fb9d0083c1443 Mon Sep 17 00:00:00 2001 From: Carlos Granados Date: Tue, 29 Oct 2024 19:33:27 +0000 Subject: [PATCH 406/567] Removes the unnecessary alias of the ScenarioInterface as it just causes confusion --- src/Behat/Behat/Hook/Scope/AfterScenarioScope.php | 10 +++++----- src/Behat/Behat/Hook/Scope/BeforeScenarioScope.php | 10 +++++----- src/Behat/Behat/Hook/Scope/ScenarioScope.php | 4 ++-- 3 files changed, 12 insertions(+), 12 deletions(-) diff --git a/src/Behat/Behat/Hook/Scope/AfterScenarioScope.php b/src/Behat/Behat/Hook/Scope/AfterScenarioScope.php index 45985d9fb..496c625cc 100644 --- a/src/Behat/Behat/Hook/Scope/AfterScenarioScope.php +++ b/src/Behat/Behat/Hook/Scope/AfterScenarioScope.php @@ -11,7 +11,7 @@ namespace Behat\Behat\Hook\Scope; use Behat\Gherkin\Node\FeatureNode; -use Behat\Gherkin\Node\ScenarioInterface as Scenario; +use Behat\Gherkin\Node\ScenarioInterface; use Behat\Testwork\Environment\Environment; use Behat\Testwork\Hook\Scope\AfterTestScope; use Behat\Testwork\Suite\Suite; @@ -33,7 +33,7 @@ final class AfterScenarioScope implements ScenarioScope, AfterTestScope */ private $feature; /** - * @var Scenario + * @var ScenarioInterface */ private $scenario; /** @@ -46,10 +46,10 @@ final class AfterScenarioScope implements ScenarioScope, AfterTestScope * * @param Environment $env * @param FeatureNode $feature - * @param Scenario $scenario + * @param ScenarioInterface $scenario * @param TestResult $result */ - public function __construct(Environment $env, FeatureNode $feature, Scenario $scenario, TestResult $result) + public function __construct(Environment $env, FeatureNode $feature, ScenarioInterface $scenario, TestResult $result) { $this->environment = $env; $this->feature = $feature; @@ -100,7 +100,7 @@ public function getFeature() /** * Returns scenario. * - * @return Scenario + * @return ScenarioInterface */ public function getScenario() { diff --git a/src/Behat/Behat/Hook/Scope/BeforeScenarioScope.php b/src/Behat/Behat/Hook/Scope/BeforeScenarioScope.php index af4178eb6..b8a1c3e8b 100644 --- a/src/Behat/Behat/Hook/Scope/BeforeScenarioScope.php +++ b/src/Behat/Behat/Hook/Scope/BeforeScenarioScope.php @@ -11,7 +11,7 @@ namespace Behat\Behat\Hook\Scope; use Behat\Gherkin\Node\FeatureNode; -use Behat\Gherkin\Node\ScenarioInterface as Scenario; +use Behat\Gherkin\Node\ScenarioInterface; use Behat\Testwork\Environment\Environment; use Behat\Testwork\Suite\Suite; @@ -31,7 +31,7 @@ final class BeforeScenarioScope implements ScenarioScope */ private $feature; /** - * @var Scenario + * @var ScenarioInterface */ private $scenario; @@ -40,9 +40,9 @@ final class BeforeScenarioScope implements ScenarioScope * * @param Environment $env * @param FeatureNode $feature - * @param Scenario $scenario + * @param ScenarioInterface $scenario */ - public function __construct(Environment $env, FeatureNode $feature, Scenario $scenario) + public function __construct(Environment $env, FeatureNode $feature, ScenarioInterface $scenario) { $this->environment = $env; $this->feature = $feature; @@ -92,7 +92,7 @@ public function getFeature() /** * Returns scenario. * - * @return Scenario + * @return ScenarioInterface */ public function getScenario() { diff --git a/src/Behat/Behat/Hook/Scope/ScenarioScope.php b/src/Behat/Behat/Hook/Scope/ScenarioScope.php index c7dbe513a..e4842cbb9 100644 --- a/src/Behat/Behat/Hook/Scope/ScenarioScope.php +++ b/src/Behat/Behat/Hook/Scope/ScenarioScope.php @@ -11,7 +11,7 @@ namespace Behat\Behat\Hook\Scope; use Behat\Gherkin\Node\FeatureNode; -use Behat\Gherkin\Node\ScenarioInterface as Scenario; +use Behat\Gherkin\Node\ScenarioInterface; use Behat\Testwork\Hook\Scope\HookScope; /** @@ -34,7 +34,7 @@ public function getFeature(); /** * Returns scenario. * - * @return Scenario + * @return ScenarioInterface */ public function getScenario(); } From df070b7b2176a77fe00964953e14dba02e0889ff Mon Sep 17 00:00:00 2001 From: Alex Skrypnyk Date: Wed, 30 Oct 2024 20:40:21 +1100 Subject: [PATCH 407/567] Fixed indentation in GHA. --- .github/workflows/build.yml | 389 ++++++++++++++++++------------------ 1 file changed, 194 insertions(+), 195 deletions(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index fe8feae6e..c8094a200 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -1,200 +1,199 @@ name: Build on: - push: - branches: [master] - pull_request: ~ - release: - types: [created] - workflow_dispatch: ~ + push: + branches: [master] + pull_request: ~ + release: + types: [created] + workflow_dispatch: ~ jobs: - tests: - runs-on: ${{ matrix.os }} - defaults: - run: - shell: bash - name: Test - strategy: - fail-fast: false - matrix: - php: [7.2, 7.3, 7.4, 8.0, 8.1, 8.2, 8.3, 8.4] - os: [ubuntu-latest] - composer-mode: [update] - symfony-version: [''] - include: - # 7.2 build with lowest dependencies - - php: 7.2 - os: ubuntu-latest - composer-mode: lowest - symfony-version: '' - - # MacOS on latest PHP only - - php: 8.2 - os: macos-latest - composer-mode: update - symfony-version: '' - - # Windows on latest PHP only - - php: 8.2 - os: windows-latest - composer-mode: update - symfony-version: '' - - # Symfony jobs: - - php: 8.1 - os: ubuntu-latest - composer-mode: update - symfony-version: '4.4' - - php: 8.2 - os: ubuntu-latest - composer-mode: update - symfony-version: '5.4' - - php: 8.2 - os: ubuntu-latest - composer-mode: update - symfony-version: '6.0' - - php: 8.2 - os: ubuntu-latest - composer-mode: update - symfony-version: '7.0' - - steps: - - uses: actions/checkout@v4 - - - name: Setup PHP - uses: shivammathur/setup-php@v2 - with: - php-version: "${{ matrix.php }}" - ini-file: "development" - ini-values: "phar.readonly=0,zend.exception_ignore_args=Off" - coverage: none - - - name: Install symfony/flex - if: matrix.symfony-version != '' - run: | - composer config --global --no-plugins allow-plugins.symfony/flex true && - composer global require symfony/flex - - # until psalm is updated to v5 which is compatible with Symfony 7 - - name: Remove vimeo/psalm - if: matrix.symfony-version == '7.0' - run: composer remove vimeo/psalm --no-update --dev - - - name: Install latest dependencies - if: matrix.composer-mode == 'update' - env: - SYMFONY_REQUIRE: ${{ matrix.symfony-version }}.* - run: composer update ${{ matrix.php == '8.4' && '--ignore-platform-req=php+' || '' }} - - - name: Install lowest dependencies - if: matrix.composer-mode == 'lowest' - run: composer update --prefer-lowest - - - name: Run tests (phpunit) - run: ./vendor/bin/phpunit - - - name: Run tests (Behat) - run: ./bin/behat -fprogress --strict - - - name: Run tests (Behat for PHP 8.0) - if: matrix.php >= 8.0 - run: ./bin/behat -fprogress --strict --tags=@php8 - - static-analysis: - runs-on: ubuntu-latest - name: Static analysis - steps: - - uses: actions/checkout@v4 - - - name: Setup PHP - uses: shivammathur/setup-php@v2 - with: - php-version: 7.2 - ini-values: "zend.exception_ignore_args=Off" - coverage: none - - - name: Install dependencies - run: composer update - - - name: Run Psalm - run: ./vendor/bin/psalm --output-format=github - - build-phar: - runs-on: ubuntu-latest - name: Build PHAR file - steps: - - uses: actions/checkout@v4 - - - name: Setup PHP - uses: shivammathur/setup-php@v2 - with: - php-version: "8.3" - ini-values: "phar.readonly=0,zend.exception_ignore_args=Off" - coverage: none - tools: box - - - name: Build the PHAR - run: | - composer config platform.php 7.2.34 - composer update --no-dev -o - box compile - - - name: cache artifact - uses: actions/upload-artifact@v4 - with: - name: behat.phar - path: behat.phar - - - test-phar: - needs: build-phar - runs-on: ubuntu-latest - name: test PHAR file - strategy: - fail-fast: false - matrix: - php: [ '7.2', '7.3', '7.4', '8.0', '8.1', '8.2', '8.3', '8.4' ] - steps: - - uses: actions/checkout@v4 - - name: Setup PHP - uses: shivammathur/setup-php@v2 - with: - php-version: "${{ matrix.php }}" - ini-values: "phar.readonly=0,zend.exception_ignore_args=Off" - coverage: none - - - name: Install dependencies - run: composer install - - - - uses: actions/download-artifact@v4 - with: - name: behat.phar - - - name: "Check content" - run: | - ls -R . - - - name: Test the PHAR - run: | - php ./behat.phar --version - - publish-phar: - runs-on: ubuntu-latest - name: Publish the PHAR for release - needs: [test-phar, tests] - if: github.event_name == 'release' - steps: - - uses: actions/download-artifact@v4 - with: - name: behat.phar - path: . - - name: Upload behat.phar - uses: basefas/upload-release-asset-action@v1 - env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - with: - release_id: ${{ github.event.release.id }} - asset_path: behat.phar - asset_name: behat.phar + tests: + name: Tests + runs-on: ${{ matrix.os }} + defaults: + run: + shell: bash + strategy: + fail-fast: false + matrix: + php: [7.2, 7.3, 7.4, 8.0, 8.1, 8.2, 8.3, 8.4] + os: [ubuntu-latest] + composer-mode: [update] + symfony-version: [''] + include: + # 7.2 build with lowest dependencies + - php: 7.2 + os: ubuntu-latest + composer-mode: lowest + symfony-version: '' + + # MacOS on latest PHP only + - php: 8.2 + os: macos-latest + composer-mode: update + symfony-version: '' + + # Windows on latest PHP only + - php: 8.2 + os: windows-latest + composer-mode: update + symfony-version: '' + + # Symfony jobs: + - php: 8.1 + os: ubuntu-latest + composer-mode: update + symfony-version: '4.4' + - php: 8.2 + os: ubuntu-latest + composer-mode: update + symfony-version: '5.4' + - php: 8.2 + os: ubuntu-latest + composer-mode: update + symfony-version: '6.0' + - php: 8.2 + os: ubuntu-latest + composer-mode: update + symfony-version: '7.0' + + steps: + - uses: actions/checkout@v4 + + - name: Setup PHP + uses: shivammathur/setup-php@v2 + with: + php-version: "${{ matrix.php }}" + ini-file: "development" + ini-values: "phar.readonly=0,zend.exception_ignore_args=Off" + coverage: none + + - name: Install symfony/flex + if: matrix.symfony-version != '' + run: | + composer config --global --no-plugins allow-plugins.symfony/flex true && + composer global require symfony/flex + + # until psalm is updated to v5 which is compatible with Symfony 7 + - name: Remove vimeo/psalm + if: matrix.symfony-version == '7.0' + run: composer remove vimeo/psalm --no-update --dev + + - name: Install latest dependencies + if: matrix.composer-mode == 'update' + env: + SYMFONY_REQUIRE: ${{ matrix.symfony-version }}.* + run: composer update ${{ matrix.php == '8.4' && '--ignore-platform-req=php+' || '' }} + + - name: Install lowest dependencies + if: matrix.composer-mode == 'lowest' + run: composer update --prefer-lowest + + - name: Run tests (phpunit) + run: ./vendor/bin/phpunit + + - name: Run tests (Behat) + run: ./bin/behat -fprogress --strict + + - name: Run tests (Behat for PHP 8.0) + if: matrix.php >= 8.0 + run: ./bin/behat -fprogress --strict --tags=@php8 + + static-analysis: + name: Static analysis + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + + - name: Setup PHP + uses: shivammathur/setup-php@v2 + with: + php-version: 7.2 + ini-values: "zend.exception_ignore_args=Off" + coverage: none + + - name: Install dependencies + run: composer update + + - name: Run Psalm + run: ./vendor/bin/psalm --output-format=github + + build-phar: + name: Build PHAR file + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + + - name: Setup PHP + uses: shivammathur/setup-php@v2 + with: + php-version: "8.3" + ini-values: "phar.readonly=0,zend.exception_ignore_args=Off" + coverage: none + tools: box + + - name: Build the PHAR + run: | + composer config platform.php 7.2.34 + composer update --no-dev -o + box compile + + - name: cache artifact + uses: actions/upload-artifact@v4 + with: + name: behat.phar + path: behat.phar + + test-phar: + name: test PHAR file + needs: build-phar + runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + php: ['7.2', '7.3', '7.4', '8.0', '8.1', '8.2', '8.3', '8.4'] + steps: + - uses: actions/checkout@v4 + - name: Setup PHP + uses: shivammathur/setup-php@v2 + with: + php-version: "${{ matrix.php }}" + ini-values: "phar.readonly=0,zend.exception_ignore_args=Off" + coverage: none + + - name: Install dependencies + run: composer install + + + - uses: actions/download-artifact@v4 + with: + name: behat.phar + + - name: Check content + run: | + ls -R . + + - name: Test the PHAR + run: | + php ./behat.phar --version + + publish-phar: + name: Publish the PHAR for release + runs-on: ubuntu-latest + needs: [test-phar, tests] + if: github.event_name == 'release' + steps: + - uses: actions/download-artifact@v4 + with: + name: behat.phar + path: . + - name: Upload behat.phar + uses: basefas/upload-release-asset-action@v1 + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + with: + release_id: ${{ github.event.release.id }} + asset_path: behat.phar + asset_name: behat.phar From eb3d1d61d003864dc31238e62d60bbcab1e00cc6 Mon Sep 17 00:00:00 2001 From: Andrew Coulton Date: Thu, 31 Oct 2024 00:21:28 +0000 Subject: [PATCH 408/567] chore: Update guidance on submitting PRs As it looks like the proposed changes in #1489 didn't make it into the final version. --- CONTRIBUTING.md | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index ac5c297e1..da623b886 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -35,7 +35,14 @@ so that we adhere to [Semantic Versioning v2.0.0](http://semver.org/spec/v2.0.0. 6. Make sure you [ran the tests](#running-tests) and didn't break anything. That will save some time on [GitHub actions](https://github.com/Behat/Behat/actions) 7. Commit your code and submit a Pull Request, providing a clear description of the change, including -the motivation for the proposal +the motivation for the proposal. + +Please note: Each Pull Request should contain only one new feature or bugfix. If the changes are large, +please structure them into multiple smaller commits. If you need to make small refactorings or internal +changes - for example to fix an already-failing test, rename private variables, or reformat an existing +method to make your own change readable - this can be included in the Pull Request but must be +committed separately with its own commit message(s). If possible, make these the first commits on +your branch to make review easier. ## Backwards compatibility From 078ffb14f65d1fd84deb6e12785eae79bfc95b7f Mon Sep 17 00:00:00 2001 From: Julien Deniau Date: Thu, 31 Oct 2024 09:28:40 +0100 Subject: [PATCH 409/567] rename "configuration" to "config" and avoid BC break --- ...feature => stop_on_failure_config.feature} | 8 ++++---- src/Behat/Behat/ApplicationFactory.php | 4 ++-- .../Handler/StopOnFailureHandler.php | 5 ++--- .../ServiceContainer/ConfigExtension.php} | 13 ++++++------ .../Cli/StopOnFailureController.php | 20 ++++++++++++++++--- .../EventDispatcherExtension.php | 5 +++-- 6 files changed, 34 insertions(+), 21 deletions(-) rename features/{stop_on_failure_configuration.feature => stop_on_failure_config.feature} (95%) rename src/Behat/Behat/{Configuration => Config}/Handler/StopOnFailureHandler.php (93%) rename src/Behat/Behat/{Configuration/ServiceContainer/ConfigurationExtension.php => Config/ServiceContainer/ConfigExtension.php} (82%) diff --git a/features/stop_on_failure_configuration.feature b/features/stop_on_failure_config.feature similarity index 95% rename from features/stop_on_failure_configuration.feature rename to features/stop_on_failure_config.feature index 642cf0f83..2140f3d75 100644 --- a/features/stop_on_failure_configuration.feature +++ b/features/stop_on_failure_config.feature @@ -1,7 +1,7 @@ -Feature: Stop on failure via configuration +Feature: Stop on failure via config In order to stop further execution of steps when first step fails As a feature developer - I need to have a configuration.stop_on_failure sets to true + I need to have a config.stop_on_failure sets to true Background: Given a file named "features/bootstrap/FeatureContext.php" with: @@ -62,7 +62,7 @@ Feature: Stop on failure via configuration Given a file named "behat.yml" with: """ default: - configuration: + config: stop_on_failure: false """ When I run "behat --no-colors --format-settings='{\"paths\": false}' features/failing.feature" @@ -98,7 +98,7 @@ Feature: Stop on failure via configuration Given a file named "behat.yml" with: """ default: - configuration: + config: stop_on_failure: true """ When I run "behat --no-colors --format-settings='{\"paths\": false}' features/failing.feature" diff --git a/src/Behat/Behat/ApplicationFactory.php b/src/Behat/Behat/ApplicationFactory.php index da67dc1d6..664040829 100644 --- a/src/Behat/Behat/ApplicationFactory.php +++ b/src/Behat/Behat/ApplicationFactory.php @@ -10,7 +10,7 @@ namespace Behat\Behat; -use Behat\Behat\Configuration\ServiceContainer\ConfigurationExtension; +use Behat\Behat\Config\ServiceContainer\ConfigExtension; use Behat\Behat\Context\ServiceContainer\ContextExtension; use Behat\Behat\Definition\ServiceContainer\DefinitionExtension; use Behat\Behat\EventDispatcher\ServiceContainer\EventDispatcherExtension; @@ -95,7 +95,7 @@ protected function getDefaultExtensions() new TransformationExtension($processor), new OrderingExtension($processor), new HelperContainerExtension($processor), - new ConfigurationExtension() + new ConfigExtension() ); } diff --git a/src/Behat/Behat/Configuration/Handler/StopOnFailureHandler.php b/src/Behat/Behat/Config/Handler/StopOnFailureHandler.php similarity index 93% rename from src/Behat/Behat/Configuration/Handler/StopOnFailureHandler.php rename to src/Behat/Behat/Config/Handler/StopOnFailureHandler.php index ed5fd1b14..bad202d5f 100644 --- a/src/Behat/Behat/Configuration/Handler/StopOnFailureHandler.php +++ b/src/Behat/Behat/Config/Handler/StopOnFailureHandler.php @@ -8,7 +8,7 @@ * file that was distributed with this source code. */ -namespace Behat\Behat\Configuration\Handler; +namespace Behat\Behat\Config\Handler; use Behat\Behat\EventDispatcher\Event\AfterScenarioTested; use Behat\Behat\EventDispatcher\Event\ExampleTested; @@ -20,10 +20,9 @@ use Behat\Testwork\Tester\Result\Interpretation\ResultInterpretation; use Behat\Testwork\Tester\Result\Interpretation\StrictInterpretation; use Symfony\Component\EventDispatcher\EventDispatcherInterface; -use Symfony\Component\EventDispatcher\EventSubscriberInterface; /** - * Enables stop on failure via configuration. + * Enables stop on failure via config. */ final class StopOnFailureHandler { diff --git a/src/Behat/Behat/Configuration/ServiceContainer/ConfigurationExtension.php b/src/Behat/Behat/Config/ServiceContainer/ConfigExtension.php similarity index 82% rename from src/Behat/Behat/Configuration/ServiceContainer/ConfigurationExtension.php rename to src/Behat/Behat/Config/ServiceContainer/ConfigExtension.php index 5cbc68722..9a66bb0ec 100644 --- a/src/Behat/Behat/Configuration/ServiceContainer/ConfigurationExtension.php +++ b/src/Behat/Behat/Config/ServiceContainer/ConfigExtension.php @@ -8,7 +8,7 @@ * file that was distributed with this source code. */ -namespace Behat\Behat\Configuration\ServiceContainer; +namespace Behat\Behat\Config\ServiceContainer; use Behat\Testwork\EventDispatcher\ServiceContainer\EventDispatcherExtension; use Behat\Testwork\ServiceContainer\Extension; @@ -21,16 +21,16 @@ /** * Enables stop on failure controller for Behat. */ -final class ConfigurationExtension implements Extension +final class ConfigExtension implements Extension { - public const STOP_ON_FAILURE_ID = 'configuration.stop_on_failure'; + public const STOP_ON_FAILURE_ID = 'config.stop_on_failure'; /** * {@inheritdoc} */ public function getConfigKey() { - return 'configuration'; + return 'config'; } /** @@ -49,8 +49,7 @@ public function configure(ArrayNodeDefinition $builder) ->addDefaultsIfNotSet() ->children() ->scalarNode('stop_on_failure') - ->defaultValue(false) - ->treatNullLike(false) + ->defaultValue(null) ->end() ->end() ; @@ -77,7 +76,7 @@ public function process(ContainerBuilder $container) */ private function loadStopOnFailureController(ContainerBuilder $container, array $config) { - $definition = new Definition('Behat\Behat\Configuration\Handler\StopOnFailureHandler', array( + $definition = new Definition('Behat\Behat\Config\Handler\StopOnFailureHandler', array( new Reference(EventDispatcherExtension::DISPATCHER_ID) )); if ($config['stop_on_failure'] === true) { diff --git a/src/Behat/Behat/EventDispatcher/Cli/StopOnFailureController.php b/src/Behat/Behat/EventDispatcher/Cli/StopOnFailureController.php index 61b009edd..71da17d83 100644 --- a/src/Behat/Behat/EventDispatcher/Cli/StopOnFailureController.php +++ b/src/Behat/Behat/EventDispatcher/Cli/StopOnFailureController.php @@ -10,7 +10,7 @@ namespace Behat\Behat\EventDispatcher\Cli; -use Behat\Behat\Configuration\Handler\StopOnFailureHandler; +use Behat\Behat\Config\Handler\StopOnFailureHandler; use Behat\Behat\EventDispatcher\Event\AfterScenarioTested; use Behat\Behat\EventDispatcher\Event\ExampleTested; use Behat\Behat\EventDispatcher\Event\ScenarioTested; @@ -27,6 +27,7 @@ use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; +use Symfony\Component\EventDispatcher\EventDispatcherInterface; /** * Stops tests on first scenario failure. @@ -35,6 +36,11 @@ */ final class StopOnFailureController implements Controller { + /** + * @var EventDispatcherInterface + */ + private $eventDispatcher; + /** * @var StopOnFailureHandler */ @@ -43,9 +49,17 @@ final class StopOnFailureController implements Controller /** * Initializes controller. * - * @param StopOnFailureHandler $stopOnFailureHandler + * @param EventDispatcherInterface $eventDispatcher + */ + public function __construct(EventDispatcherInterface $eventDispatcher) + { + $this->eventDispatcher = $eventDispatcher; + } + + /** + * @required */ - public function __construct(StopOnFailureHandler $stopOnFailureHandler) + public function setStopOnFailureHandler(StopOnFailureHandler $stopOnFailureHandler) { $this->stopOnFailureHandler = $stopOnFailureHandler; } diff --git a/src/Behat/Behat/EventDispatcher/ServiceContainer/EventDispatcherExtension.php b/src/Behat/Behat/EventDispatcher/ServiceContainer/EventDispatcherExtension.php index 3b27d9a74..39d0bb342 100644 --- a/src/Behat/Behat/EventDispatcher/ServiceContainer/EventDispatcherExtension.php +++ b/src/Behat/Behat/EventDispatcher/ServiceContainer/EventDispatcherExtension.php @@ -10,7 +10,7 @@ namespace Behat\Behat\EventDispatcher\ServiceContainer; -use Behat\Behat\Configuration\ServiceContainer\ConfigurationExtension; +use Behat\Behat\Config\ServiceContainer\ConfigExtension; use Behat\Behat\EventDispatcher\Event\ExampleTested; use Behat\Behat\EventDispatcher\Event\ScenarioTested; use Behat\Behat\Tester\ServiceContainer\TesterExtension; @@ -52,8 +52,9 @@ public function load(ContainerBuilder $container, array $config) protected function loadStopOnFailureController(ContainerBuilder $container) { $definition = new Definition('Behat\Behat\EventDispatcher\Cli\StopOnFailureController', array( - new Reference(ConfigurationExtension::STOP_ON_FAILURE_ID) + new Reference(EventDispatcherExtension::DISPATCHER_ID) )); + $definition->addMethodCall(('setStopOnFailureHandler'), array(new Reference(ConfigExtension::STOP_ON_FAILURE_ID))); $definition->addTag(CliExtension::CONTROLLER_TAG, array('priority' => 100)); $container->setDefinition(CliExtension::CONTROLLER_TAG . '.stop_on_failure', $definition); } From a7cd02430b0b5c8eccfa1d17c471a1dabd38591f Mon Sep 17 00:00:00 2001 From: Julien Deniau Date: Thu, 31 Oct 2024 09:29:21 +0100 Subject: [PATCH 410/567] test with option sets to false and cli set to true --- features/stop_on_failure.feature | 4 ++-- features/stop_on_failure_config.feature | 20 ++++++++++++++++++- .../ServiceContainer/ConfigExtension.php | 4 ++-- .../Cli/StopOnFailureController.php | 1 + 4 files changed, 24 insertions(+), 5 deletions(-) diff --git a/features/stop_on_failure.feature b/features/stop_on_failure.feature index 9c866f776..7095f6304 100644 --- a/features/stop_on_failure.feature +++ b/features/stop_on_failure.feature @@ -53,7 +53,7 @@ Feature: Stop on failure And I have another step that fails Then I should have a scenario that failed - Scenario: 2st Failing + Scenario: 2nd Failing When I have a step that fails Then I should have a scenario that failed """ @@ -81,7 +81,7 @@ Feature: Stop on failure And I have another step that is missing Then I should have a scenario that failed - Scenario: 2st Failing + Scenario: 2nd Failing When I have a step that is missing Then I should have a scenario that failed """ diff --git a/features/stop_on_failure_config.feature b/features/stop_on_failure_config.feature index 2140f3d75..bf86b8fed 100644 --- a/features/stop_on_failure_config.feature +++ b/features/stop_on_failure_config.feature @@ -48,7 +48,7 @@ Feature: Stop on failure via config And I have another step that fails Then I should have a scenario that failed - Scenario: 2st Failing + Scenario: 2nd Failing When I have a step that fails Then I should have a scenario that failed @@ -102,6 +102,24 @@ Feature: Stop on failure via config stop_on_failure: true """ When I run "behat --no-colors --format-settings='{\"paths\": false}' features/failing.feature" + Then it should fail with: + """ + --- Failed scenarios: + + features/failing.feature:13 + + 2 scenarios (1 passed, 1 failed) + 7 steps (5 passed, 1 failed, 1 skipped) + """ + + Scenario: with stop_on_failure set to false, but cli option set to true + Given a file named "behat.yml" with: + """ + default: + config: + stop_on_failure: false + """ + When I run "behat --no-colors --stop-on-failure --format-settings='{\"paths\": false}' features/failing.feature" Then it should fail with: """ --- Failed scenarios: diff --git a/src/Behat/Behat/Config/ServiceContainer/ConfigExtension.php b/src/Behat/Behat/Config/ServiceContainer/ConfigExtension.php index 9a66bb0ec..0efd3c0dc 100644 --- a/src/Behat/Behat/Config/ServiceContainer/ConfigExtension.php +++ b/src/Behat/Behat/Config/ServiceContainer/ConfigExtension.php @@ -60,7 +60,7 @@ public function configure(ArrayNodeDefinition $builder) */ public function load(ContainerBuilder $container, array $config) { - $this->loadStopOnFailureController($container, $config); + $this->loadStopOnFailureHandler($container, $config); } /** @@ -74,7 +74,7 @@ public function process(ContainerBuilder $container) /** * Loads stop on failure controller. */ - private function loadStopOnFailureController(ContainerBuilder $container, array $config) + private function loadStopOnFailureHandler(ContainerBuilder $container, array $config) { $definition = new Definition('Behat\Behat\Config\Handler\StopOnFailureHandler', array( new Reference(EventDispatcherExtension::DISPATCHER_ID) diff --git a/src/Behat/Behat/EventDispatcher/Cli/StopOnFailureController.php b/src/Behat/Behat/EventDispatcher/Cli/StopOnFailureController.php index 71da17d83..93d066163 100644 --- a/src/Behat/Behat/EventDispatcher/Cli/StopOnFailureController.php +++ b/src/Behat/Behat/EventDispatcher/Cli/StopOnFailureController.php @@ -37,6 +37,7 @@ final class StopOnFailureController implements Controller { /** + * @deprecated events are now dispatched in the StopOnFailureHandler * @var EventDispatcherInterface */ private $eventDispatcher; From d6e233cb180fc3f814ee09fa830bc3563830583f Mon Sep 17 00:00:00 2001 From: Alex Skrypnyk Date: Thu, 31 Oct 2024 15:14:59 +0000 Subject: [PATCH 411/567] chore: Reformat github actions YAML --- .github/workflows/build.yml | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index c8094a200..2239303b1 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -156,6 +156,7 @@ jobs: php: ['7.2', '7.3', '7.4', '8.0', '8.1', '8.2', '8.3', '8.4'] steps: - uses: actions/checkout@v4 + - name: Setup PHP uses: shivammathur/setup-php@v2 with: @@ -166,18 +167,15 @@ jobs: - name: Install dependencies run: composer install - - uses: actions/download-artifact@v4 with: name: behat.phar - name: Check content - run: | - ls -R . + run: ls -R . - name: Test the PHAR - run: | - php ./behat.phar --version + run: php ./behat.phar --version publish-phar: name: Publish the PHAR for release @@ -189,6 +187,7 @@ jobs: with: name: behat.phar path: . + - name: Upload behat.phar uses: basefas/upload-release-asset-action@v1 env: From 2ea4cf51ed5d296982b4686a1067ae4bc5a3e123 Mon Sep 17 00:00:00 2001 From: Alex Skrypnyk Date: Thu, 31 Oct 2024 15:15:59 +0000 Subject: [PATCH 412/567] change: Drop support for PHP < 8.1, Symfony < 5.4 and Symfony 6.0 - 6.3 --- .github/workflows/build.yml | 44 +++++++++++++++++++++---------------- composer.json | 18 +++++++-------- 2 files changed, 34 insertions(+), 28 deletions(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 2239303b1..ad13ec1b3 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -18,13 +18,13 @@ jobs: strategy: fail-fast: false matrix: - php: [7.2, 7.3, 7.4, 8.0, 8.1, 8.2, 8.3, 8.4] + php: [8.1, 8.2, 8.3, 8.4] os: [ubuntu-latest] composer-mode: [update] symfony-version: [''] include: - # 7.2 build with lowest dependencies - - php: 7.2 + # Build on the lowest supported PHP with the lowest supported dependencies + - php: 8.1 os: ubuntu-latest composer-mode: lowest symfony-version: '' @@ -41,23 +41,16 @@ jobs: composer-mode: update symfony-version: '' - # Symfony jobs: - - php: 8.1 - os: ubuntu-latest - composer-mode: update - symfony-version: '4.4' + # Symfony LTS jobs: - php: 8.2 os: ubuntu-latest composer-mode: update symfony-version: '5.4' + - php: 8.2 os: ubuntu-latest composer-mode: update - symfony-version: '6.0' - - php: 8.2 - os: ubuntu-latest - composer-mode: update - symfony-version: '7.0' + symfony-version: '6.4' steps: - uses: actions/checkout@v4 @@ -110,11 +103,19 @@ jobs: - name: Setup PHP uses: shivammathur/setup-php@v2 with: - php-version: 7.2 + php-version: 8.1 ini-values: "zend.exception_ignore_args=Off" coverage: none + # until psalm is updated to v5 which is compatible with Symfony 7 + - name: Force symfony version for psalm compatibility + run: | + composer config --global --no-plugins allow-plugins.symfony/flex true && + composer global require symfony/flex + - name: Install dependencies + env: + SYMFONY_REQUIRE: 5.4.* run: composer update - name: Run Psalm @@ -129,16 +130,21 @@ jobs: - name: Setup PHP uses: shivammathur/setup-php@v2 with: - php-version: "8.3" + php-version: "8.2" ini-values: "phar.readonly=0,zend.exception_ignore_args=Off" coverage: none tools: box - - name: Build the PHAR + # We have to force the composer platform because box only runs on ^8.2, but we need to make sure the dependencies + # inside the phar support 8.1.0 (our lowest supported PHP version). + # When we drop 8.1, we may be able to drop this (if we can still get box to run on 8.2). + - name: Force dependencies for lowest supported PHP version run: | - composer config platform.php 7.2.34 + composer config platform.php 8.1.0 composer update --no-dev -o - box compile + + - name: Build the PHAR + run: box compile - name: cache artifact uses: actions/upload-artifact@v4 @@ -153,7 +159,7 @@ jobs: strategy: fail-fast: false matrix: - php: ['7.2', '7.3', '7.4', '8.0', '8.1', '8.2', '8.3', '8.4'] + php: ['8.1', '8.2', '8.3', '8.4'] steps: - uses: actions/checkout@v4 diff --git a/composer.json b/composer.json index 89f265940..85337aa31 100644 --- a/composer.json +++ b/composer.json @@ -14,21 +14,21 @@ ], "require": { - "php": "^7.2 || ^8.0", + "php": "8.1.* || 8.2.* || 8.3.* || 8.4.* ", "ext-mbstring": "*", "behat/gherkin": "^4.10.0", - "behat/transliterator": "^1.2", - "symfony/console": "^4.4 || ^5.0 || ^6.0 || ^7.0", - "symfony/config": "^4.4 || ^5.0 || ^6.0 || ^7.0", - "symfony/dependency-injection": "^4.4 || ^5.0 || ^6.0 || ^7.0", - "symfony/event-dispatcher": "^4.4 || ^5.0 || ^6.0 || ^7.0", - "symfony/translation": "^4.4 || ^5.0 || ^6.0 || ^7.0", - "symfony/yaml": "^4.4 || ^5.0 || ^6.0 || ^7.0", + "behat/transliterator": "^1.5", + "symfony/console": "^5.4 || ^6.4 || ^7.0", + "symfony/config": "^5.4 || ^6.4 || ^7.0", + "symfony/dependency-injection": "^5.4 || ^6.4 || ^7.0", + "symfony/event-dispatcher": "^5.4 || ^6.4 || ^7.0", + "symfony/translation": "^5.4 || ^6.4 || ^7.0", + "symfony/yaml": "^5.4 || ^6.4 || ^7.0", "psr/container": "^1.0 || ^2.0" }, "require-dev": { - "symfony/process": "^4.4 || ^5.0 || ^6.0 || ^7.0", + "symfony/process": "^5.4 || ^6.4 || ^7.0", "phpunit/phpunit": "^8.5 || ^9.0", "herrera-io/box": "~1.6.1", "vimeo/psalm": "^4.8" From dae339abfc56d2414affe178a84f9a4d3ebceece Mon Sep 17 00:00:00 2001 From: acoulton Date: Thu, 31 Oct 2024 14:36:15 +0000 Subject: [PATCH 413/567] chore: Bump phpunit dev dependency We only need to support the latest 9.x to run behat's own tests on supported PHP versions. --- composer.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/composer.json b/composer.json index 85337aa31..30a5125f0 100644 --- a/composer.json +++ b/composer.json @@ -29,7 +29,7 @@ "require-dev": { "symfony/process": "^5.4 || ^6.4 || ^7.0", - "phpunit/phpunit": "^8.5 || ^9.0", + "phpunit/phpunit": "^9.6", "herrera-io/box": "~1.6.1", "vimeo/psalm": "^4.8" }, From 3b144df71f6dfaa952728baa11cba48c07db6b82 Mon Sep 17 00:00:00 2001 From: Carlos Granados Date: Fri, 1 Nov 2024 22:39:46 +0000 Subject: [PATCH 414/567] fix: use a different "upload to release" GH action which does not break the phar on upload --- .github/workflows/build.yml | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index ad13ec1b3..6db17941f 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -195,10 +195,9 @@ jobs: path: . - name: Upload behat.phar - uses: basefas/upload-release-asset-action@v1 - env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + uses: svenstaro/upload-release-action@v2 with: - release_id: ${{ github.event.release.id }} - asset_path: behat.phar + repo_token: ${{ secrets.GITHUB_TOKEN }} + file: behat.phar asset_name: behat.phar + tag: ${{ github.ref }} From 756ff2dd0db43b094c3d8cd585013ffdce787033 Mon Sep 17 00:00:00 2001 From: Remon van de Kamp Date: Sun, 3 Nov 2024 11:57:05 +0100 Subject: [PATCH 415/567] Allow BeforeSuite/AfterSuite hooks to be marked with attributes --- features/attributes.feature | 102 ++++++++++++++++++ .../Context/Attribute/HookAttributeReader.php | 4 + src/Behat/Hook/AfterSuite.php | 28 +++++ src/Behat/Hook/BeforeSuite.php | 28 +++++ 4 files changed, 162 insertions(+) create mode 100644 src/Behat/Hook/AfterSuite.php create mode 100644 src/Behat/Hook/BeforeSuite.php diff --git a/features/attributes.feature b/features/attributes.feature index 28eca9bce..c4c6d4c8e 100644 --- a/features/attributes.feature +++ b/features/attributes.feature @@ -283,6 +283,108 @@ Feature: attributes 6 steps (6 passed) """ + @php8 @suite-hooks + Scenario: PHP 8 Hook Suite Hook Attributes + Given a file named "features/bootstrap/FeatureContext.php" with: + """ + 'Behat\Behat\Hook\Call\BeforeFeature', BeforeScenario::class => 'Behat\Behat\Hook\Call\BeforeScenario', BeforeStep::class => 'Behat\Behat\Hook\Call\BeforeStep', + BeforeSuite::class => 'Behat\Testwork\Hook\Call\BeforeSuite', + AfterSuite::class => 'Behat\Testwork\Hook\Call\AfterSuite', ); /** diff --git a/src/Behat/Hook/AfterSuite.php b/src/Behat/Hook/AfterSuite.php new file mode 100644 index 000000000..66cc4cb5e --- /dev/null +++ b/src/Behat/Hook/AfterSuite.php @@ -0,0 +1,28 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Behat\Hook; + +/** + * Represents an Attribute for AfterSuite hook. + */ +#[\Attribute(\Attribute::TARGET_METHOD | \Attribute::IS_REPEATABLE)] +final class AfterSuite implements Hook +{ + /** + * @var string + */ + public $filterString; + + public function __construct($filterString = null) + { + $this->filterString = $filterString; + } +} diff --git a/src/Behat/Hook/BeforeSuite.php b/src/Behat/Hook/BeforeSuite.php new file mode 100644 index 000000000..4d4c02f48 --- /dev/null +++ b/src/Behat/Hook/BeforeSuite.php @@ -0,0 +1,28 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Behat\Hook; + +/** + * Represents an Attribute for BeforeSuite hook. + */ +#[\Attribute(\Attribute::TARGET_METHOD | \Attribute::IS_REPEATABLE)] +final class BeforeSuite implements Hook +{ + /** + * @var string + */ + public $filterString; + + public function __construct($filterString = null) + { + $this->filterString = $filterString; + } +} From a615b8abc238817ce79fb558dec9d6bdc2bd0be8 Mon Sep 17 00:00:00 2001 From: Julien Deniau Date: Sun, 3 Nov 2024 22:42:23 +0100 Subject: [PATCH 416/567] handle --strict option with stop_on_failure config --- features/stop_on_failure_config.feature | 47 +++++++++++++++++++ .../Config/Handler/StopOnFailureHandler.php | 18 ++++--- .../Cli/StopOnFailureController.php | 13 ++--- 3 files changed, 60 insertions(+), 18 deletions(-) diff --git a/features/stop_on_failure_config.feature b/features/stop_on_failure_config.feature index bf86b8fed..9d59ecaf3 100644 --- a/features/stop_on_failure_config.feature +++ b/features/stop_on_failure_config.feature @@ -57,6 +57,24 @@ Feature: Stop on failure via config And I have another step that passes Then I should have a scenario that passed """ + And a file named "features/missing-step.feature" with: + """ + Feature: Missing Step Feature + In order to test the stop-on-failure and strict features + As a behat developer + I need to have a feature with a missing step + + Background: + Given I have a step that passes + + Scenario: 1st Failing + When I have a step that is missing + Then I should have a scenario that failed + + Scenario: 1st Passing + When I have a step that passes + Then I should have a scenario that passed + """ Scenario: with stop_on_failure set to false Given a file named "behat.yml" with: @@ -111,6 +129,35 @@ Feature: Stop on failure via config 2 scenarios (1 passed, 1 failed) 7 steps (5 passed, 1 failed, 1 skipped) """ + + Scenario: with stop_on_failure set to true and a missing step + Given a file named "behat.yml" with: + """ + default: + config: + stop_on_failure: true + """ + When I run "behat --no-colors --format-settings='{\"paths\": false}' features/missing-step.feature" + Then it should pass with: + """ + 2 scenarios (1 passed, 1 undefined) + 6 steps (4 passed, 1 undefined, 1 skipped) + """ + + Scenario: with stop_on_failure set to true and a missing step in strict mode + Given a file named "behat.yml" with: + """ + default: + config: + stop_on_failure: true + """ + + When I run "behat --no-colors --format-settings='{\"paths\": false}' --strict features/missing-step.feature" + Then it should fail with: + """ + 1 scenario (1 undefined) + 3 steps (1 passed, 1 undefined, 1 skipped) + """ Scenario: with stop_on_failure set to false, but cli option set to true Given a file named "behat.yml" with: diff --git a/src/Behat/Behat/Config/Handler/StopOnFailureHandler.php b/src/Behat/Behat/Config/Handler/StopOnFailureHandler.php index bad202d5f..28e40abae 100644 --- a/src/Behat/Behat/Config/Handler/StopOnFailureHandler.php +++ b/src/Behat/Behat/Config/Handler/StopOnFailureHandler.php @@ -18,7 +18,7 @@ use Behat\Testwork\EventDispatcher\Event\ExerciseCompleted; use Behat\Testwork\EventDispatcher\Event\SuiteTested; use Behat\Testwork\Tester\Result\Interpretation\ResultInterpretation; -use Behat\Testwork\Tester\Result\Interpretation\StrictInterpretation; +use Behat\Testwork\Tester\Result\Interpretation\SoftInterpretation; use Symfony\Component\EventDispatcher\EventDispatcherInterface; /** @@ -40,18 +40,16 @@ final class StopOnFailureHandler public function __construct(EventDispatcherInterface $eventDispatcher) { $this->eventDispatcher = $eventDispatcher; - $this->resultInterpretation = new StrictInterpretation(); + $this->resultInterpretation = new SoftInterpretation(); + } + + public function setResultInterpretation(ResultInterpretation $resultInterpretation) + { + $this->resultInterpretation = $resultInterpretation; } - /** - * @param ?ResultInterpretation $resultInterpretation - */ - public function registerListeners($resultInterpretation = null) + public function registerListeners() { - if ($resultInterpretation) { - $this->resultInterpretation = $resultInterpretation; - } - $this->eventDispatcher->addListener(ScenarioTested::AFTER, array($this, 'exitOnFailure'), -100); $this->eventDispatcher->addListener(ExampleTested::AFTER, array($this, 'exitOnFailure'), -100); } diff --git a/src/Behat/Behat/EventDispatcher/Cli/StopOnFailureController.php b/src/Behat/Behat/EventDispatcher/Cli/StopOnFailureController.php index 93d066163..6f993e591 100644 --- a/src/Behat/Behat/EventDispatcher/Cli/StopOnFailureController.php +++ b/src/Behat/Behat/EventDispatcher/Cli/StopOnFailureController.php @@ -87,18 +87,15 @@ public function configure(Command $command) */ public function execute(InputInterface $input, OutputInterface $output) { - if (!$input->getOption('stop-on-failure')) { - return null; + if ($input->getOption('strict')) { + $this->stopOnFailureHandler->setResultInterpretation(new StrictInterpretation()); } - - if ($input->getOption('strict')) { - $resultInterpretation = new StrictInterpretation(); - } else { - $resultInterpretation = new SoftInterpretation(); + if (!$input->getOption('stop-on-failure')) { + return null; } - $this->stopOnFailureHandler->registerListeners($resultInterpretation); + $this->stopOnFailureHandler->registerListeners(); } } From 14968281fa6a065d2b67f00911dfa2cb59ab09c1 Mon Sep 17 00:00:00 2001 From: Andrew Coulton Date: Tue, 5 Nov 2024 00:04:49 +0000 Subject: [PATCH 417/567] chore: Update CHANGELOG to mention behaviour change in Gherkin Further to #1514 and Behat/Gherkin#269, add a note to Behat's own CHANGELOG to mention the behaviour change in gherkin 4.10.0. --- CHANGELOG.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 4ef68c7e4..507421671 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,10 @@ and this project adheres to [Semantic Versioning](http://semver.org/). ## [3.15.0] - 2024-10-29 +***Note:** This release also bumps the minor version of behat/gherkin to 4.10.0, which was released on 2024-10-19 with + a behaviour-changing bugfix related to the parsing of `\` characters in scenarios. + See [the Behat/Gherkin CHANGELOG](https://github.com/Behat/Gherkin/blob/master/CHANGES.md#4100--2024-10-19).* + ### Added * PHP 8.4 support by @heiglandreas in [#1473](https://github.com/Behat/Behat/pull/1473), @jrfnl in [#1478](https://github.com/Behat/Behat/pull/1478), From 2c6ae31b2dcd6218078fa2ab55045e499ec18c10 Mon Sep 17 00:00:00 2001 From: Carlos Granados Date: Tue, 5 Nov 2024 12:35:22 +0100 Subject: [PATCH 418/567] Improve type hint --- src/Behat/Testwork/Output/Printer/JUnitOutputPrinter.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Behat/Testwork/Output/Printer/JUnitOutputPrinter.php b/src/Behat/Testwork/Output/Printer/JUnitOutputPrinter.php index c7fc8716e..7f48964d4 100644 --- a/src/Behat/Testwork/Output/Printer/JUnitOutputPrinter.php +++ b/src/Behat/Testwork/Output/Printer/JUnitOutputPrinter.php @@ -88,7 +88,7 @@ public function addTestsuite(array $testsuiteAttributes = array()) /** * Extends the current node. * - * @param array $testsuiteAttributes + * @param array $testsuiteAttributes */ public function extendTestsuiteAttributes(array $testsuiteAttributes) { From 204baff09b0ca214955fea008de1238dfa5e2db7 Mon Sep 17 00:00:00 2001 From: Jon Pugh Date: Tue, 22 Aug 2023 16:00:19 -0400 Subject: [PATCH 419/567] Make sure format() returns string. preg_replace_callback returns null|string|string[]. This change checks for null. Should we check for an array as well? --- src/Behat/Behat/Output/Printer/Formatter/ConsoleFormatter.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Behat/Behat/Output/Printer/Formatter/ConsoleFormatter.php b/src/Behat/Behat/Output/Printer/Formatter/ConsoleFormatter.php index 57d3ef38b..9f3293c17 100644 --- a/src/Behat/Behat/Output/Printer/Formatter/ConsoleFormatter.php +++ b/src/Behat/Behat/Output/Printer/Formatter/ConsoleFormatter.php @@ -30,7 +30,7 @@ final class ConsoleFormatter extends BaseOutputFormatter */ public function format($message): string { - return preg_replace_callback(self::CUSTOM_PATTERN, array($this, 'replaceStyle'), $message); + return preg_replace_callback(self::CUSTOM_PATTERN, array($this, 'replaceStyle'), $message) ?? ''; } /** From 6eba7e27e70760f71d50bb9a347a22f1ee6216a9 Mon Sep 17 00:00:00 2001 From: Carlos Granados Date: Tue, 5 Nov 2024 15:46:58 +0100 Subject: [PATCH 420/567] Display error message on error and add test --- .../Printer/Formatter/ConsoleFormatter.php | 3 +- .../Formatter/ConsoleFormatterTest.php | 42 +++++++++++++++++++ 2 files changed, 44 insertions(+), 1 deletion(-) create mode 100644 tests/Behat/Tests/Output/Printer/Formatter/ConsoleFormatterTest.php diff --git a/src/Behat/Behat/Output/Printer/Formatter/ConsoleFormatter.php b/src/Behat/Behat/Output/Printer/Formatter/ConsoleFormatter.php index 9f3293c17..98dfafabc 100644 --- a/src/Behat/Behat/Output/Printer/Formatter/ConsoleFormatter.php +++ b/src/Behat/Behat/Output/Printer/Formatter/ConsoleFormatter.php @@ -30,7 +30,8 @@ final class ConsoleFormatter extends BaseOutputFormatter */ public function format($message): string { - return preg_replace_callback(self::CUSTOM_PATTERN, array($this, 'replaceStyle'), $message) ?? ''; + return preg_replace_callback(self::CUSTOM_PATTERN, array($this, 'replaceStyle'), $message) ?? + 'Error formatting output: ' . preg_last_error_msg(); } /** diff --git a/tests/Behat/Tests/Output/Printer/Formatter/ConsoleFormatterTest.php b/tests/Behat/Tests/Output/Printer/Formatter/ConsoleFormatterTest.php new file mode 100644 index 000000000..109810356 --- /dev/null +++ b/tests/Behat/Tests/Output/Printer/Formatter/ConsoleFormatterTest.php @@ -0,0 +1,42 @@ +format('{+info}Info:{-info}'); + + $this->assertEquals('Info:', $formattedText); + } + + public function testFormatValidMessageWithDecoration(): void + { + $consoleFormatter = new ConsoleFormatter(true); + + $formattedText = $consoleFormatter->format('{+info}Info:{-info}'); + + $this->assertEquals('Info:', $formattedText); + } + + public function testFormatInvalidMessage(): void + { + $consoleFormatter = new ConsoleFormatter(true); + + $original_backtrack_limit = ini_get('pcre.backtrack_limit'); + + ini_set('pcre.backtrack_limit', '100'); + + $formattedText = $consoleFormatter->format('{+info}' . str_repeat('a', 1000) . '{-info}'); + + ini_set('pcre.backtrack_limit', $original_backtrack_limit); + + $this->assertEquals('Error formatting output: Backtrack limit exhausted', $formattedText); + } +} From 7cbbe211979b18c88b2f8e8d6a35652ac5bafe6b Mon Sep 17 00:00:00 2001 From: Carlos Granados Date: Tue, 5 Nov 2024 16:21:17 +0100 Subject: [PATCH 421/567] fix: save in the rerun file any test that is considered failed by the result interpreter --- features/rerun_strict.feature | 77 +++++++++++++++++++ .../Behat/Tester/Cli/RerunController.php | 10 ++- .../ServiceContainer/TesterExtension.php | 3 + 3 files changed, 89 insertions(+), 1 deletion(-) create mode 100644 features/rerun_strict.feature diff --git a/features/rerun_strict.feature b/features/rerun_strict.feature new file mode 100644 index 000000000..b6d47ec45 --- /dev/null +++ b/features/rerun_strict.feature @@ -0,0 +1,77 @@ +Feature: Rerun with strict + In order to test only failed scenarios with the strict option + As a feature developer + I need to have an ability to rerun failed previously scenarios, including those which failed due to the strict option + + Background: + Given a file named "features/bootstrap/FeatureContext.php" with: + """ + basepath = $basepath; } + public function setResultInterpreter(ResultInterpreter $resultInterpreter) + { + $this->resultInterpreter = $resultInterpreter; + } + /** * Configures command to be executable by the controller. * @@ -122,7 +130,7 @@ public function collectFailedScenario(AfterScenarioTested $event) return; } - if ($event->getTestResult()->getResultCode() !== TestResult::FAILED) { + if ($this->resultInterpreter->interpretResult($event->getTestResult()) === 0) { return; } diff --git a/src/Behat/Behat/Tester/ServiceContainer/TesterExtension.php b/src/Behat/Behat/Tester/ServiceContainer/TesterExtension.php index 843f750c1..ff90b4825 100644 --- a/src/Behat/Behat/Tester/ServiceContainer/TesterExtension.php +++ b/src/Behat/Behat/Tester/ServiceContainer/TesterExtension.php @@ -248,6 +248,9 @@ protected function loadRerunController(ContainerBuilder $container, $cachePath) $container->getParameter('paths.base') )); $definition->addTag(CliExtension::CONTROLLER_TAG, array('priority' => 200)); + $definition->addMethodCall('setResultInterpreter', array( + new Reference(TesterExtension::RESULT_INTERPRETER_ID) + )); $container->setDefinition(CliExtension::CONTROLLER_TAG . '.rerun', $definition); } From 61cfac527e2b1b48d826f258bc7c0193ed799611 Mon Sep 17 00:00:00 2001 From: Carlos Granados Date: Tue, 5 Nov 2024 17:07:09 +0100 Subject: [PATCH 422/567] fix: add result constants to ResultInterpreter --- src/Behat/Behat/Tester/Cli/RerunController.php | 2 +- src/Behat/Testwork/Tester/Result/ResultInterpreter.php | 7 +++++-- 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/src/Behat/Behat/Tester/Cli/RerunController.php b/src/Behat/Behat/Tester/Cli/RerunController.php index 0421fb59a..28f5d7bcf 100644 --- a/src/Behat/Behat/Tester/Cli/RerunController.php +++ b/src/Behat/Behat/Tester/Cli/RerunController.php @@ -130,7 +130,7 @@ public function collectFailedScenario(AfterScenarioTested $event) return; } - if ($this->resultInterpreter->interpretResult($event->getTestResult()) === 0) { + if ($this->resultInterpreter->interpretResult($event->getTestResult()) === ResultInterpreter::PASS) { return; } diff --git a/src/Behat/Testwork/Tester/Result/ResultInterpreter.php b/src/Behat/Testwork/Tester/Result/ResultInterpreter.php index 5ea9ad133..13dff7813 100644 --- a/src/Behat/Testwork/Tester/Result/ResultInterpreter.php +++ b/src/Behat/Testwork/Tester/Result/ResultInterpreter.php @@ -19,6 +19,9 @@ */ final class ResultInterpreter { + public const PASS = 0; + public const FAIL = 1; + /** * @var ResultInterpretation[] */ @@ -45,10 +48,10 @@ public function interpretResult(TestResult $result) { foreach ($this->interpretations as $interpretation) { if ($interpretation->isFailure($result)) { - return 1; + return self::FAIL; } } - return 0; + return self::PASS; } } From 8187e0b6601d1a25ee4efbe31b4b8dc277905344 Mon Sep 17 00:00:00 2001 From: Carlos Granados Date: Wed, 6 Nov 2024 09:45:37 +0100 Subject: [PATCH 423/567] Move resultInterpreter to the constructor --- .../Behat/Tester/Cli/RerunController.php | 25 +++++-------------- .../ServiceContainer/TesterExtension.php | 8 +++--- 2 files changed, 9 insertions(+), 24 deletions(-) diff --git a/src/Behat/Behat/Tester/Cli/RerunController.php b/src/Behat/Behat/Tester/Cli/RerunController.php index 28f5d7bcf..bafe75122 100644 --- a/src/Behat/Behat/Tester/Cli/RerunController.php +++ b/src/Behat/Behat/Tester/Cli/RerunController.php @@ -30,10 +30,6 @@ */ final class RerunController implements Controller { - /** - * @var EventDispatcherInterface - */ - private $eventDispatcher; /** * @var null|string */ @@ -46,12 +42,6 @@ final class RerunController implements Controller * @var string[] */ private $lines = array(); - /** - * @var string - */ - private $basepath; - - private ResultInterpreter $resultInterpreter; /** * Initializes controller. @@ -60,16 +50,13 @@ final class RerunController implements Controller * @param null|string $cachePath * @param string $basepath */ - public function __construct(EventDispatcherInterface $eventDispatcher, $cachePath, $basepath) - { - $this->eventDispatcher = $eventDispatcher; + public function __construct( + private EventDispatcherInterface $eventDispatcher, + private ResultInterpreter $resultInterpreter, + private string $basepath, + $cachePath, + ) { $this->cachePath = null !== $cachePath ? rtrim($cachePath, DIRECTORY_SEPARATOR) : null; - $this->basepath = $basepath; - } - - public function setResultInterpreter(ResultInterpreter $resultInterpreter) - { - $this->resultInterpreter = $resultInterpreter; } /** diff --git a/src/Behat/Behat/Tester/ServiceContainer/TesterExtension.php b/src/Behat/Behat/Tester/ServiceContainer/TesterExtension.php index ff90b4825..e0138472d 100644 --- a/src/Behat/Behat/Tester/ServiceContainer/TesterExtension.php +++ b/src/Behat/Behat/Tester/ServiceContainer/TesterExtension.php @@ -244,13 +244,11 @@ protected function loadRerunController(ContainerBuilder $container, $cachePath) { $definition = new Definition('Behat\Behat\Tester\Cli\RerunController', array( new Reference(EventDispatcherExtension::DISPATCHER_ID), - $cachePath, - $container->getParameter('paths.base') + new Reference(TesterExtension::RESULT_INTERPRETER_ID), + $container->getParameter('paths.base'), + $cachePath )); $definition->addTag(CliExtension::CONTROLLER_TAG, array('priority' => 200)); - $definition->addMethodCall('setResultInterpreter', array( - new Reference(TesterExtension::RESULT_INTERPRETER_ID) - )); $container->setDefinition(CliExtension::CONTROLLER_TAG . '.rerun', $definition); } From 9b31ac82ab666a79b542da3934a8dc359ea62ba1 Mon Sep 17 00:00:00 2001 From: Christian Sciberras Date: Wed, 6 Nov 2024 19:37:51 +0100 Subject: [PATCH 424/567] Use specific time matching pattern --- features/bootstrap/FeatureContext.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/features/bootstrap/FeatureContext.php b/features/bootstrap/FeatureContext.php index 5f56c8127..33cc0c088 100644 --- a/features/bootstrap/FeatureContext.php +++ b/features/bootstrap/FeatureContext.php @@ -322,7 +322,7 @@ public function fileXmlShouldBeLike($path, PyStringNode $text) $fileContent = trim(file_get_contents($path)); - $fileContent = preg_replace('/time="(.*)"/U', 'time="-IGNORE-VALUE-"', $fileContent); + $fileContent = preg_replace('/time="\d\.\d{3}"/U', 'time="-IGNORE-VALUE-"', $fileContent); // The placeholder is necessary because of different separators on Unix and Windows environments $text = str_replace('-DIRECTORY-SEPARATOR-', DIRECTORY_SEPARATOR, $text); From f105d4d3a373cfeb5bbd6f1ca47afdbe8751e370 Mon Sep 17 00:00:00 2001 From: Julien Deniau Date: Mon, 4 Nov 2024 10:45:47 +0100 Subject: [PATCH 425/567] Make "pass" and "fail" more readable if the result is not expected --- features/bootstrap/FeatureContext.php | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/features/bootstrap/FeatureContext.php b/features/bootstrap/FeatureContext.php index 33cc0c088..9c57f5e17 100644 --- a/features/bootstrap/FeatureContext.php +++ b/features/bootstrap/FeatureContext.php @@ -397,12 +397,17 @@ public function itShouldFail($success) $message = ''; if ('fail' === $success) { + Assert::assertNotEquals(0, $this->getExitCode(), 'Step should FAIL but it PASS.'); + if (0 === $this->getExitCode()) { $message = 'Actual output:' . PHP_EOL . PHP_EOL . $this->getOutput(); } Assert::assertNotEquals(0, $this->getExitCode(), $message); } else { + Assert::assertEquals(0, $this->getExitCode(), 'Step should PASS but it FAIL.'); + + if (0 !== $this->getExitCode()) { $message = 'Actual output:' . PHP_EOL . PHP_EOL . $this->getOutput(); } From fff0e3d9f0e5d673c46b875913dababe0f153630 Mon Sep 17 00:00:00 2001 From: Julien Deniau Date: Thu, 7 Nov 2024 09:30:19 +0100 Subject: [PATCH 426/567] re-set actual output but wrapped --- features/bootstrap/FeatureContext.php | 53 ++++++++++++--------------- 1 file changed, 24 insertions(+), 29 deletions(-) diff --git a/features/bootstrap/FeatureContext.php b/features/bootstrap/FeatureContext.php index 9c57f5e17..729756ecb 100644 --- a/features/bootstrap/FeatureContext.php +++ b/features/bootstrap/FeatureContext.php @@ -263,13 +263,12 @@ public function iRunBehatInDebugMode() * * @Then /^it should (fail|pass) with:$/ * - * @param string $success "fail" or "pass" - * @param PyStringNode $text PyString text instance + * @param 'pass'|'fail' $success */ - public function itShouldPassWith($success, PyStringNode $text) + public function itShouldPassOrFailWith($success, PyStringNode $text) { $this->theOutputShouldContain($text); - $this->itShouldFail($success); + $this->itShouldPassOrFail($success); } /** @@ -277,12 +276,12 @@ public function itShouldPassWith($success, PyStringNode $text) * * @Then /^it should (fail|pass) with no output$/ * - * @param string $success "fail" or "pass" + * @param 'pass'|'fail' $success */ - public function itShouldPassWithNoOutput($success) + public function itShouldPassOrFailWithNoOutput($success) { Assert::assertEmpty($this->getOutput()); - $this->itShouldFail($success); + $this->itShouldPassOrFail($success); } /** @@ -390,30 +389,26 @@ private function getExpectedOutput(PyStringNode $expectedText) * * @Then /^it should (fail|pass)$/ * - * @param string $success "fail" or "pass" + * @param 'pass'|'fail' $success */ - public function itShouldFail($success) + public function itShouldPassOrFail($success) { - $message = ''; - - if ('fail' === $success) { - Assert::assertNotEquals(0, $this->getExitCode(), 'Step should FAIL but it PASS.'); - - if (0 === $this->getExitCode()) { - $message = 'Actual output:' . PHP_EOL . PHP_EOL . $this->getOutput(); - } - - Assert::assertNotEquals(0, $this->getExitCode(), $message); - } else { - Assert::assertEquals(0, $this->getExitCode(), 'Step should PASS but it FAIL.'); - - - if (0 !== $this->getExitCode()) { - $message = 'Actual output:' . PHP_EOL . PHP_EOL . $this->getOutput(); - } - - Assert::assertEquals(0, $this->getExitCode(), $message); - } + $is_correct = match($success) { + 'fail' => 0 !== $this->getExitCode(), + 'pass' => 0 === $this->getExitCode(), + }; + + if ($is_correct) { + return; + } + + throw new UnexpectedValueException( + 'Expected previous command to ' . strtoupper($success) . ' but got exit code ' . $this->getExitCode() . PHP_EOL + . PHP_EOL + . '##### Actual output #####' . PHP_EOL + . '> ' . str_replace(PHP_EOL, PHP_EOL . '> ', $this->getOutput()) . PHP_EOL + . '##### End of output #####' + ); } /** From ce25c66606371f78d25286716f8045409658f393 Mon Sep 17 00:00:00 2001 From: acoulton Date: Thu, 7 Nov 2024 21:10:43 +0000 Subject: [PATCH 427/567] test: Specify behaviour for handling PHPUnit exceptions in scenarios --- composer.json | 1 + features/phpunit_exceptions.feature | 244 ++++++++++++++++++++++++++++ 2 files changed, 245 insertions(+) create mode 100644 features/phpunit_exceptions.feature diff --git a/composer.json b/composer.json index 30a5125f0..ad667d31e 100644 --- a/composer.json +++ b/composer.json @@ -28,6 +28,7 @@ }, "require-dev": { + "symfony/polyfill-php84": "^1.31", "symfony/process": "^5.4 || ^6.4 || ^7.0", "phpunit/phpunit": "^9.6", "herrera-io/box": "~1.6.1", diff --git a/features/phpunit_exceptions.feature b/features/phpunit_exceptions.feature new file mode 100644 index 000000000..76da5207f --- /dev/null +++ b/features/phpunit_exceptions.feature @@ -0,0 +1,244 @@ +Feature: Stringifying PHPUnit exceptions + In order to understand why a step has failed + As a feature developer + I need to see the details of failed PHPUnit assertions if I am using a supported version + + Background: + Given a file named "features/bootstrap/FeatureContext.php" with: + """ + true); + } + + $autoloaders = spl_autoload_functions(); + array_walk($autoloaders, fn($l) => spl_autoload_unregister($l)); + + spl_autoload_register( + function (string $class) use ($autoloaders) { + return match ($class) { + \PHPUnit\Framework\TestFailure::class => null, + \PHPUnit\Util\ThrowableToStringMapper::class => null, + default => array_find($autoloaders, fn($loader) => $loader($class)) + }; + }, + ); + } + + private static function assertClassNotLoaded(string $class): void + { + assert(!class_exists($class, autoload: false), 'Should not have already loaded ' . $class); + } + + #[Then('/^an array (?P.+?) should equal (?P.+)$/')] + public function arrayShouldMatch(string $actual_json, string $expected_json): void + { + // To prove the output with more complex diffs + Assert::assertEquals( + json_decode($expected_json, true), + json_decode($actual_json, true), + 'Should get the right value' + ); + } + + #[Then('an integer :actual should equal :expected')] + public function intShouldMatch(int $actual, int $expected): void + { + Assert::assertSame($expected, $actual, 'check the ints'); + } + } + """ + And a file named "features/bootstrap/IncompatibleThrowableToStringMapper.php" with: + """ + 'bar' + + 'value' => 'foo' + ) + + 002 Scenario: Compare mismatched ints # features/with_phpunit_9.feature:12 + Then an integer 1 should equal 2 # features/with_phpunit_9.feature:13 + check the ints + Failed asserting that 1 is identical to 2. + + 4 scenarios (2 passed, 2 failed) + 4 steps (2 passed, 2 failed) + """ + + Scenario: With a theoretically-supported PHPUnit that causes errors during stringification + # Because the classes we're calling are marked as internal and not guaranteed to provide BC + Given a file named "features/with_phpunit_10_broken.feature" with: + """ + @phpunit_10_broken + Feature: Values do not match + In order to test the stringification of PHPUnit assertions + As a contributor of behat + I need to have a scenario that demonstrates failing assertions + + Scenario: Compare mismatched array + Then an array {"value": "foo"} should equal {"value": "bar"} + + Scenario: Compare matching array + Then an array {"value": "foo"} should equal {"value": "foo"} + + Scenario: Compare mismatched ints + Then an integer 1 should equal 2 + + Scenario: Compare matching ints + Then an integer 1 should equal 1 + """ + When I run "behat -f progress --no-colors features/with_phpunit_10_broken.feature" + Then it should fail with: + """ + --- Failed steps: + + 001 Scenario: Compare mismatched array # features/with_phpunit_10_broken.feature:7 + Then an array {"value": "foo"} should equal {"value": "bar"} # features/with_phpunit_10_broken.feature:8 + Should get the right value + Failed asserting that two arrays are equal. + !! There was an error trying to render more details of this PHPUnit\Framework\ExpectationFailedException. + You are probably using a PHPUnit version that Behat cannot automatically display failures for. + See Behat\Testwork\Exception\Stringer\PHPUnitExceptionStringer for details of PHPUnit support. + [RuntimeException] Some internal problem at features/bootstrap/IncompatibleThrowableToStringMapper.php:9 + + 002 Scenario: Compare mismatched ints # features/with_phpunit_10_broken.feature:13 + Then an integer 1 should equal 2 # features/with_phpunit_10_broken.feature:14 + check the ints + Failed asserting that 1 is identical to 2. + !! There was an error trying to render more details of this PHPUnit\Framework\ExpectationFailedException. + You are probably using a PHPUnit version that Behat cannot automatically display failures for. + See Behat\Testwork\Exception\Stringer\PHPUnitExceptionStringer for details of PHPUnit support. + [RuntimeException] Some internal problem at features/bootstrap/IncompatibleThrowableToStringMapper.php:9 + + 4 scenarios (2 passed, 2 failed) + 4 steps (2 passed, 2 failed) + """ + + Scenario: With unsupported PHPUnit + Given a file named "features/with_unknown_phpunit_version.feature" with: + """ + @phpunit_incompatible + Feature: Values do not match + In order to test the stringification of PHPUnit assertions + As a contributor of behat + I need to have a scenario that demonstrates failing assertions + + Scenario: Compare mismatched array + Then an array {"value": "foo"} should equal {"value": "bar"} + + Scenario: Compare matching array + Then an array {"value": "foo"} should equal {"value": "foo"} + + Scenario: Compare mismatched ints + Then an integer 1 should equal 2 + + Scenario: Compare matching ints + Then an integer 1 should equal 1 + """ + When I run "behat -f progress --no-colors features/with_unknown_phpunit_version.feature" + Then it should fail with: + """ + --- Failed steps: + + 001 Scenario: Compare mismatched array # features/with_unknown_phpunit_version.feature:7 + Then an array {"value": "foo"} should equal {"value": "bar"} # features/with_unknown_phpunit_version.feature:8 + Should get the right value + Failed asserting that two arrays are equal. + !! Could not render more details of this PHPUnit\Framework\ExpectationFailedException. + Behat does not support automatically formatting assertion failures for your PHPUnit version. + See Behat\Testwork\Exception\Stringer\PHPUnitExceptionStringer for details. + + 002 Scenario: Compare mismatched ints # features/with_unknown_phpunit_version.feature:13 + Then an integer 1 should equal 2 # features/with_unknown_phpunit_version.feature:14 + check the ints + Failed asserting that 1 is identical to 2. + !! Could not render more details of this PHPUnit\Framework\ExpectationFailedException. + Behat does not support automatically formatting assertion failures for your PHPUnit version. + See Behat\Testwork\Exception\Stringer\PHPUnitExceptionStringer for details. + + 4 scenarios (2 passed, 2 failed) + 4 steps (2 passed, 2 failed) + """ From 0cf052d8713727457629494a8e3b1b7ef1ca209f Mon Sep 17 00:00:00 2001 From: acoulton Date: Wed, 6 Nov 2024 23:55:33 +0000 Subject: [PATCH 428/567] change: deprecate ApplicationFactory::VERSION, auto-detect behat version The ApplicationFactory::VERSION constant has not been bumped for the last couple of releases, and updating it manually every time is an avoidable maintenance burden. Deprecate the constant - it will not be updated in the future, and will be removed in next major. Instead, use composer's runtime API to detect the version at runtime (only really used for inclusion in tool output). This follows the pattern used by e.g. doctrine https://github.com/doctrine/orm/blob/44fa8bbde87238ad9b574e87325c7ff89c75837e/src/Tools/Console/ConsoleRunner.php#L45-L46 Composer's version is generated to a file at the time of `composer install` and therefore is baked into the `.phar` so that also works as expected. Note that in some cases composer versions are non-numeric (e.g. a dev branch may report a version of `dev-c629b4a773cf2dc11e0930bd8930adf22eae5031`). --- composer.json | 1 + src/Behat/Behat/ApplicationFactory.php | 9 ++++++++- 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/composer.json b/composer.json index 30a5125f0..b24d3cfaf 100644 --- a/composer.json +++ b/composer.json @@ -18,6 +18,7 @@ "ext-mbstring": "*", "behat/gherkin": "^4.10.0", "behat/transliterator": "^1.5", + "composer-runtime-api": "^2.2", "symfony/console": "^5.4 || ^6.4 || ^7.0", "symfony/config": "^5.4 || ^6.4 || ^7.0", "symfony/dependency-injection": "^5.4 || ^6.4 || ^7.0", diff --git a/src/Behat/Behat/ApplicationFactory.php b/src/Behat/Behat/ApplicationFactory.php index 664040829..326331214 100644 --- a/src/Behat/Behat/ApplicationFactory.php +++ b/src/Behat/Behat/ApplicationFactory.php @@ -39,6 +39,7 @@ use Behat\Testwork\Specification\ServiceContainer\SpecificationExtension; use Behat\Testwork\Suite\ServiceContainer\SuiteExtension; use Behat\Testwork\Translator\ServiceContainer\TranslatorExtension; +use Composer\InstalledVersions; /** * Defines the way behat is created. @@ -47,6 +48,11 @@ */ final class ApplicationFactory extends BaseFactory { + /** + * @deprecated this constant will not be updated for releases after 3.13.0 and will be removed in the next major. + * You can use composer's runtime API to get the behat version if you need it - see getVersion() in this class for + * an example. Note that composer's versions will not always be simple numeric values. + */ public const VERSION = '3.13.0'; /** @@ -62,7 +68,8 @@ protected function getName() */ protected function getVersion() { - return self::VERSION; + // Get the currently installed behat version from composer's runtime API + return InstalledVersions::getVersion('behat/behat'); } /** From cfbdb4e1c9a79bbca41e247cc0375efdddb0c2f3 Mon Sep 17 00:00:00 2001 From: Julien Deniau Date: Sun, 3 Nov 2024 23:40:38 +0100 Subject: [PATCH 429/567] Handle "strict" in behat configuration file --- features/config_strict.feature | 65 +++++++++++++++++++ .../Config/Handler/StopOnFailureHandler.php | 9 +-- .../Behat/Config/Handler/StrictHandler.php | 35 ++++++++++ .../ServiceContainer/ConfigExtension.php | 24 ++++++- .../Testwork/Tester/Cli/StrictController.php | 15 ++++- .../ServiceContainer/TesterExtension.php | 2 + 6 files changed, 142 insertions(+), 8 deletions(-) create mode 100644 features/config_strict.feature create mode 100644 src/Behat/Behat/Config/Handler/StrictHandler.php diff --git a/features/config_strict.feature b/features/config_strict.feature new file mode 100644 index 000000000..071082c5f --- /dev/null +++ b/features/config_strict.feature @@ -0,0 +1,65 @@ +Feature: Strict type defined in configuration file + As a feature writer + I need to be able to configure "strict" option in behat.yml config file + + Scenario: Undefined steps + Given a file named "features/coffee.feature" with: + """ + Feature: Undefined coffee machine actions + In order to make clients happy + As a coffee machine factory + We need to be able to tell customers + about what coffee type is supported + + Background: + Given I have magically created 10$ + + Scenario: Buy incredible coffee + When I have chose "coffee with turkey" in coffee machine + Then I should have "turkey with coffee sauce" + + Scenario: Buy incredible tea + When I have chose "pizza tea" in coffee machine + Then I should have "pizza tea" + """ + And a file named "features/bootstrap/FeatureContext.php" with: + """ + eventDispatcher = $eventDispatcher; - $this->resultInterpretation = new SoftInterpretation(); - } + $this->resultInterpretation = $strict ? new StrictInterpretation() : new SoftInterpretation(); - public function setResultInterpretation(ResultInterpretation $resultInterpretation) - { - $this->resultInterpretation = $resultInterpretation; } public function registerListeners() diff --git a/src/Behat/Behat/Config/Handler/StrictHandler.php b/src/Behat/Behat/Config/Handler/StrictHandler.php new file mode 100644 index 000000000..2e3c6e1ff --- /dev/null +++ b/src/Behat/Behat/Config/Handler/StrictHandler.php @@ -0,0 +1,35 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Behat\Behat\Config\Handler; + +use Behat\Testwork\Tester\Result\Interpretation\StrictInterpretation; +use Behat\Testwork\Tester\Result\ResultInterpreter; + +/** + * Enables strict mode via config. + */ +final class StrictHandler +{ + /** + * @var ResultInterpreter + */ + private $resultInterpreter; + + public function __construct(ResultInterpreter $resultInterpreter) + { + $this->resultInterpreter = $resultInterpreter; + } + + public function registerStrictInterpretation() + { + $this->resultInterpreter->registerResultInterpretation(new StrictInterpretation()); + } +} diff --git a/src/Behat/Behat/Config/ServiceContainer/ConfigExtension.php b/src/Behat/Behat/Config/ServiceContainer/ConfigExtension.php index 0efd3c0dc..08adfe27a 100644 --- a/src/Behat/Behat/Config/ServiceContainer/ConfigExtension.php +++ b/src/Behat/Behat/Config/ServiceContainer/ConfigExtension.php @@ -13,6 +13,7 @@ use Behat\Testwork\EventDispatcher\ServiceContainer\EventDispatcherExtension; use Behat\Testwork\ServiceContainer\Extension; use Behat\Testwork\ServiceContainer\ExtensionManager; +use Behat\Testwork\Tester\ServiceContainer\TesterExtension; use Symfony\Component\Config\Definition\Builder\ArrayNodeDefinition; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Definition; @@ -24,6 +25,7 @@ final class ConfigExtension implements Extension { public const STOP_ON_FAILURE_ID = 'config.stop_on_failure'; + public const STRICT_ID = 'config.strict'; /** * {@inheritdoc} @@ -51,6 +53,9 @@ public function configure(ArrayNodeDefinition $builder) ->scalarNode('stop_on_failure') ->defaultValue(null) ->end() + ->booleanNode('strict') + ->defaultFalse() + ->end() ->end() ; } @@ -61,6 +66,7 @@ public function configure(ArrayNodeDefinition $builder) public function load(ContainerBuilder $container, array $config) { $this->loadStopOnFailureHandler($container, $config); + $this->loadStrictHandler($container, $config); } /** @@ -77,11 +83,27 @@ public function process(ContainerBuilder $container) private function loadStopOnFailureHandler(ContainerBuilder $container, array $config) { $definition = new Definition('Behat\Behat\Config\Handler\StopOnFailureHandler', array( - new Reference(EventDispatcherExtension::DISPATCHER_ID) + new Reference(EventDispatcherExtension::DISPATCHER_ID), + $config['strict'] )); if ($config['stop_on_failure'] === true) { $definition->addMethodCall('registerListeners'); } $container->setDefinition(self::STOP_ON_FAILURE_ID, $definition); } + + /** + * Loads strict handler. + */ + private function loadStrictHandler(ContainerBuilder $container, array $config) + { + $definition = new Definition('Behat\Behat\Config\Handler\StrictHandler', array( + new Reference(TesterExtension::RESULT_INTERPRETER_ID) + )); + if ($config['strict'] === true) { + $definition->addMethodCall('registerStrictInterpretation'); + } + + $container->setDefinition(self::STRICT_ID, $definition); + } } diff --git a/src/Behat/Testwork/Tester/Cli/StrictController.php b/src/Behat/Testwork/Tester/Cli/StrictController.php index 697b881fc..43a326743 100644 --- a/src/Behat/Testwork/Tester/Cli/StrictController.php +++ b/src/Behat/Testwork/Tester/Cli/StrictController.php @@ -10,6 +10,7 @@ namespace Behat\Testwork\Tester\Cli; +use Behat\Behat\Config\Handler\StrictHandler; use Behat\Testwork\Cli\Controller; use Behat\Testwork\Tester\Result\Interpretation\StrictInterpretation; use Behat\Testwork\Tester\Result\ResultInterpreter; @@ -26,6 +27,7 @@ final class StrictController implements Controller { /** + * @deprecated resultInterpreter is handled in StrictHandler * @var ResultInterpreter */ private $resultInterpreter; @@ -34,6 +36,11 @@ final class StrictController implements Controller */ private $strict; + /** + * @var StrictHandler + */ + private $strictHandler; + /** * Initializes controller. * @@ -46,6 +53,12 @@ public function __construct(ResultInterpreter $resultInterpreter, $strict = fals $this->strict = $strict; } + /** @required */ + public function setStrictHandler(StrictHandler $strictHandler) + { + $this->strictHandler = $strictHandler; + } + /** * {@inheritdoc} */ @@ -65,6 +78,6 @@ public function execute(InputInterface $input, OutputInterface $output) return; } - $this->resultInterpreter->registerResultInterpretation(new StrictInterpretation()); + $this->strictHandler->registerStrictInterpretation(); } } diff --git a/src/Behat/Testwork/Tester/ServiceContainer/TesterExtension.php b/src/Behat/Testwork/Tester/ServiceContainer/TesterExtension.php index 41cb7f695..a610c52f8 100644 --- a/src/Behat/Testwork/Tester/ServiceContainer/TesterExtension.php +++ b/src/Behat/Testwork/Tester/ServiceContainer/TesterExtension.php @@ -10,6 +10,7 @@ namespace Behat\Testwork\Tester\ServiceContainer; +use Behat\Behat\Config\ServiceContainer\ConfigExtension; use Behat\Testwork\Cli\ServiceContainer\CliExtension; use Behat\Testwork\Environment\ServiceContainer\EnvironmentExtension; use Behat\Testwork\ServiceContainer\Extension; @@ -150,6 +151,7 @@ protected function loadStrictController(ContainerBuilder $container, $strict = f new Reference(self::RESULT_INTERPRETER_ID), $strict )); + $definition->addMethodCall(('setStrictHandler'), array(new Reference(ConfigExtension::STRICT_ID))); $definition->addTag(CliExtension::CONTROLLER_TAG, array('priority' => 300)); $container->setDefinition(CliExtension::CONTROLLER_TAG . '.strict', $definition); } From c7fd1741c546932344c1a0b336422ea457f7dc28 Mon Sep 17 00:00:00 2001 From: Julien Deniau Date: Mon, 4 Nov 2024 09:26:57 +0100 Subject: [PATCH 430/567] use modern PHP features --- .../Config/Handler/StopOnFailureHandler.php | 25 ++++++++----------- .../Behat/Config/Handler/StrictHandler.php | 11 +++----- .../Testwork/Tester/Cli/StrictController.php | 5 +--- .../ServiceContainer/TesterExtension.php | 2 +- 4 files changed, 15 insertions(+), 28 deletions(-) diff --git a/src/Behat/Behat/Config/Handler/StopOnFailureHandler.php b/src/Behat/Behat/Config/Handler/StopOnFailureHandler.php index 479c89429..5822a0f50 100644 --- a/src/Behat/Behat/Config/Handler/StopOnFailureHandler.php +++ b/src/Behat/Behat/Config/Handler/StopOnFailureHandler.php @@ -27,23 +27,20 @@ */ final class StopOnFailureHandler { - - /** - * @var EventDispatcherInterface - */ - private $eventDispatcher; - - /** - * @var ResultInterpretation - */ - private $resultInterpretation; + private ResultInterpretation $resultInterpretation; - public function __construct(EventDispatcherInterface $eventDispatcher, bool $strict) - { - $this->eventDispatcher = $eventDispatcher; + public function __construct( + private readonly EventDispatcherInterface $eventDispatcher, + bool $strict + ) { $this->resultInterpretation = $strict ? new StrictInterpretation() : new SoftInterpretation(); } + + public function setResultInterpretation(ResultInterpretation $resultInterpretation) + { + $this->resultInterpretation = $resultInterpretation; + } public function registerListeners() { @@ -53,8 +50,6 @@ public function registerListeners() /** * Exits if scenario is a failure and if stopper is enabled. - * - * @param AfterScenarioTested $event */ public function exitOnFailure(AfterScenarioTested $event) { diff --git a/src/Behat/Behat/Config/Handler/StrictHandler.php b/src/Behat/Behat/Config/Handler/StrictHandler.php index 2e3c6e1ff..3cd8eab5b 100644 --- a/src/Behat/Behat/Config/Handler/StrictHandler.php +++ b/src/Behat/Behat/Config/Handler/StrictHandler.php @@ -18,14 +18,9 @@ */ final class StrictHandler { - /** - * @var ResultInterpreter - */ - private $resultInterpreter; - - public function __construct(ResultInterpreter $resultInterpreter) - { - $this->resultInterpreter = $resultInterpreter; + public function __construct( + private readonly ResultInterpreter $resultInterpreter + ) { } public function registerStrictInterpretation() diff --git a/src/Behat/Testwork/Tester/Cli/StrictController.php b/src/Behat/Testwork/Tester/Cli/StrictController.php index 43a326743..44b66c16d 100644 --- a/src/Behat/Testwork/Tester/Cli/StrictController.php +++ b/src/Behat/Testwork/Tester/Cli/StrictController.php @@ -36,10 +36,7 @@ final class StrictController implements Controller */ private $strict; - /** - * @var StrictHandler - */ - private $strictHandler; + private StrictHandler $strictHandler; /** * Initializes controller. diff --git a/src/Behat/Testwork/Tester/ServiceContainer/TesterExtension.php b/src/Behat/Testwork/Tester/ServiceContainer/TesterExtension.php index a610c52f8..c951fcb81 100644 --- a/src/Behat/Testwork/Tester/ServiceContainer/TesterExtension.php +++ b/src/Behat/Testwork/Tester/ServiceContainer/TesterExtension.php @@ -151,7 +151,7 @@ protected function loadStrictController(ContainerBuilder $container, $strict = f new Reference(self::RESULT_INTERPRETER_ID), $strict )); - $definition->addMethodCall(('setStrictHandler'), array(new Reference(ConfigExtension::STRICT_ID))); + $definition->addMethodCall('setStrictHandler', array(new Reference(ConfigExtension::STRICT_ID))); $definition->addTag(CliExtension::CONTROLLER_TAG, array('priority' => 300)); $container->setDefinition(CliExtension::CONTROLLER_TAG . '.strict', $definition); } From c9420649acde3959a1de287c74c9c398f9052331 Mon Sep 17 00:00:00 2001 From: Julien Deniau Date: Mon, 4 Nov 2024 22:52:50 +0100 Subject: [PATCH 431/567] Use interpreter service instead of specific interpretation --- .../Config/Handler/StopOnFailureHandler.php | 16 ++++------ .../Behat/Config/Handler/StrictHandler.php | 30 ------------------- .../ServiceContainer/ConfigExtension.php | 15 ++++------ .../Cli/StopOnFailureController.php | 5 +--- .../Testwork/Tester/Cli/StrictController.php | 12 +------- .../ServiceContainer/TesterExtension.php | 2 -- 6 files changed, 14 insertions(+), 66 deletions(-) delete mode 100644 src/Behat/Behat/Config/Handler/StrictHandler.php diff --git a/src/Behat/Behat/Config/Handler/StopOnFailureHandler.php b/src/Behat/Behat/Config/Handler/StopOnFailureHandler.php index 5822a0f50..89a548391 100644 --- a/src/Behat/Behat/Config/Handler/StopOnFailureHandler.php +++ b/src/Behat/Behat/Config/Handler/StopOnFailureHandler.php @@ -17,9 +17,7 @@ use Behat\Testwork\EventDispatcher\Event\AfterSuiteAborted; use Behat\Testwork\EventDispatcher\Event\ExerciseCompleted; use Behat\Testwork\EventDispatcher\Event\SuiteTested; -use Behat\Testwork\Tester\Result\Interpretation\ResultInterpretation; -use Behat\Testwork\Tester\Result\Interpretation\SoftInterpretation; -use Behat\Testwork\Tester\Result\Interpretation\StrictInterpretation; +use Behat\Testwork\Tester\Result\ResultInterpreter; use Symfony\Component\EventDispatcher\EventDispatcherInterface; /** @@ -27,19 +25,17 @@ */ final class StopOnFailureHandler { - private ResultInterpretation $resultInterpretation; + private ResultInterpreter $resultInterpreter; public function __construct( - private readonly EventDispatcherInterface $eventDispatcher, - bool $strict + private readonly EventDispatcherInterface $eventDispatcher ) { - $this->resultInterpretation = $strict ? new StrictInterpretation() : new SoftInterpretation(); } - public function setResultInterpretation(ResultInterpretation $resultInterpretation) + public function setResultInterpreter(ResultInterpreter $resultInterpreter) { - $this->resultInterpretation = $resultInterpretation; + $this->resultInterpreter = $resultInterpreter; } public function registerListeners() @@ -53,7 +49,7 @@ public function registerListeners() */ public function exitOnFailure(AfterScenarioTested $event) { - if (!$this->resultInterpretation->isFailure($event->getTestResult())) { + if (0 === $this->resultInterpreter->interpretResult($event->getTestResult())) { return; } diff --git a/src/Behat/Behat/Config/Handler/StrictHandler.php b/src/Behat/Behat/Config/Handler/StrictHandler.php deleted file mode 100644 index 3cd8eab5b..000000000 --- a/src/Behat/Behat/Config/Handler/StrictHandler.php +++ /dev/null @@ -1,30 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Behat\Behat\Config\Handler; - -use Behat\Testwork\Tester\Result\Interpretation\StrictInterpretation; -use Behat\Testwork\Tester\Result\ResultInterpreter; - -/** - * Enables strict mode via config. - */ -final class StrictHandler -{ - public function __construct( - private readonly ResultInterpreter $resultInterpreter - ) { - } - - public function registerStrictInterpretation() - { - $this->resultInterpreter->registerResultInterpretation(new StrictInterpretation()); - } -} diff --git a/src/Behat/Behat/Config/ServiceContainer/ConfigExtension.php b/src/Behat/Behat/Config/ServiceContainer/ConfigExtension.php index 08adfe27a..d30512be3 100644 --- a/src/Behat/Behat/Config/ServiceContainer/ConfigExtension.php +++ b/src/Behat/Behat/Config/ServiceContainer/ConfigExtension.php @@ -25,7 +25,6 @@ final class ConfigExtension implements Extension { public const STOP_ON_FAILURE_ID = 'config.stop_on_failure'; - public const STRICT_ID = 'config.strict'; /** * {@inheritdoc} @@ -83,9 +82,10 @@ public function process(ContainerBuilder $container) private function loadStopOnFailureHandler(ContainerBuilder $container, array $config) { $definition = new Definition('Behat\Behat\Config\Handler\StopOnFailureHandler', array( - new Reference(EventDispatcherExtension::DISPATCHER_ID), - $config['strict'] + new Reference(EventDispatcherExtension::DISPATCHER_ID) )); + $definition->addMethodCall('setResultInterpreter', array(new Reference(TesterExtension::RESULT_INTERPRETER_ID))); + if ($config['stop_on_failure'] === true) { $definition->addMethodCall('registerListeners'); } @@ -97,13 +97,10 @@ private function loadStopOnFailureHandler(ContainerBuilder $container, array $co */ private function loadStrictHandler(ContainerBuilder $container, array $config) { - $definition = new Definition('Behat\Behat\Config\Handler\StrictHandler', array( - new Reference(TesterExtension::RESULT_INTERPRETER_ID) - )); if ($config['strict'] === true) { - $definition->addMethodCall('registerStrictInterpretation'); + $definition = new Definition('Behat\Testwork\Tester\Result\Interpretation\StrictInterpretation'); + $definition->addTag(TesterExtension::RESULT_INTERPRETATION_TAG); + $container->setDefinition(TesterExtension::RESULT_INTERPRETATION_TAG . '.strict', $definition); } - - $container->setDefinition(self::STRICT_ID, $definition); } } diff --git a/src/Behat/Behat/EventDispatcher/Cli/StopOnFailureController.php b/src/Behat/Behat/EventDispatcher/Cli/StopOnFailureController.php index 6f993e591..1543dfe30 100644 --- a/src/Behat/Behat/EventDispatcher/Cli/StopOnFailureController.php +++ b/src/Behat/Behat/EventDispatcher/Cli/StopOnFailureController.php @@ -23,6 +23,7 @@ use Behat\Testwork\Tester\Result\Interpretation\ResultInterpretation; use Behat\Testwork\Tester\Result\Interpretation\SoftInterpretation; use Behat\Testwork\Tester\Result\Interpretation\StrictInterpretation; +use Behat\Testwork\Tester\Result\ResultInterpreter; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputOption; @@ -87,10 +88,6 @@ public function configure(Command $command) */ public function execute(InputInterface $input, OutputInterface $output) { - if ($input->getOption('strict')) { - $this->stopOnFailureHandler->setResultInterpretation(new StrictInterpretation()); - } - if (!$input->getOption('stop-on-failure')) { return null; } diff --git a/src/Behat/Testwork/Tester/Cli/StrictController.php b/src/Behat/Testwork/Tester/Cli/StrictController.php index 44b66c16d..697b881fc 100644 --- a/src/Behat/Testwork/Tester/Cli/StrictController.php +++ b/src/Behat/Testwork/Tester/Cli/StrictController.php @@ -10,7 +10,6 @@ namespace Behat\Testwork\Tester\Cli; -use Behat\Behat\Config\Handler\StrictHandler; use Behat\Testwork\Cli\Controller; use Behat\Testwork\Tester\Result\Interpretation\StrictInterpretation; use Behat\Testwork\Tester\Result\ResultInterpreter; @@ -27,7 +26,6 @@ final class StrictController implements Controller { /** - * @deprecated resultInterpreter is handled in StrictHandler * @var ResultInterpreter */ private $resultInterpreter; @@ -36,8 +34,6 @@ final class StrictController implements Controller */ private $strict; - private StrictHandler $strictHandler; - /** * Initializes controller. * @@ -50,12 +46,6 @@ public function __construct(ResultInterpreter $resultInterpreter, $strict = fals $this->strict = $strict; } - /** @required */ - public function setStrictHandler(StrictHandler $strictHandler) - { - $this->strictHandler = $strictHandler; - } - /** * {@inheritdoc} */ @@ -75,6 +65,6 @@ public function execute(InputInterface $input, OutputInterface $output) return; } - $this->strictHandler->registerStrictInterpretation(); + $this->resultInterpreter->registerResultInterpretation(new StrictInterpretation()); } } diff --git a/src/Behat/Testwork/Tester/ServiceContainer/TesterExtension.php b/src/Behat/Testwork/Tester/ServiceContainer/TesterExtension.php index c951fcb81..41cb7f695 100644 --- a/src/Behat/Testwork/Tester/ServiceContainer/TesterExtension.php +++ b/src/Behat/Testwork/Tester/ServiceContainer/TesterExtension.php @@ -10,7 +10,6 @@ namespace Behat\Testwork\Tester\ServiceContainer; -use Behat\Behat\Config\ServiceContainer\ConfigExtension; use Behat\Testwork\Cli\ServiceContainer\CliExtension; use Behat\Testwork\Environment\ServiceContainer\EnvironmentExtension; use Behat\Testwork\ServiceContainer\Extension; @@ -151,7 +150,6 @@ protected function loadStrictController(ContainerBuilder $container, $strict = f new Reference(self::RESULT_INTERPRETER_ID), $strict )); - $definition->addMethodCall('setStrictHandler', array(new Reference(ConfigExtension::STRICT_ID))); $definition->addTag(CliExtension::CONTROLLER_TAG, array('priority' => 300)); $container->setDefinition(CliExtension::CONTROLLER_TAG . '.strict', $definition); } From 33ba21d8848fb6ef20304851ac4d4985ad62f419 Mon Sep 17 00:00:00 2001 From: Julien Deniau Date: Wed, 6 Nov 2024 23:26:31 +0100 Subject: [PATCH 432/567] remove Config namespace and use the already implemented "tester" parameter --- features/config_strict.feature | 4 +- features/stop_on_failure_config.feature | 10 +- src/Behat/Behat/ApplicationFactory.php | 2 - .../ServiceContainer/ConfigExtension.php | 106 ------------------ .../Cli/StopOnFailureController.php | 4 +- .../EventDispatcherExtension.php | 4 +- .../Testwork/Tester/Cli/StrictController.php | 9 +- .../Tester}/Handler/StopOnFailureHandler.php | 3 +- .../ServiceContainer/TesterExtension.php | 37 +++++- 9 files changed, 49 insertions(+), 130 deletions(-) delete mode 100644 src/Behat/Behat/Config/ServiceContainer/ConfigExtension.php rename src/Behat/{Behat/Config => Testwork/Tester}/Handler/StopOnFailureHandler.php (97%) diff --git a/features/config_strict.feature b/features/config_strict.feature index 071082c5f..f61c72c4d 100644 --- a/features/config_strict.feature +++ b/features/config_strict.feature @@ -36,7 +36,7 @@ Feature: Strict type defined in configuration file And a file named "behat.yml" with: """ default: - config: + testers: strict: false """ When I run "behat --no-colors -f progress features/coffee.feature" @@ -51,7 +51,7 @@ Feature: Strict type defined in configuration file Given a file named "behat.yml" with: """ default: - config: + testers: strict: true """ When I run "behat --no-colors -f progress features/coffee.feature" diff --git a/features/stop_on_failure_config.feature b/features/stop_on_failure_config.feature index 9d59ecaf3..ee7a35244 100644 --- a/features/stop_on_failure_config.feature +++ b/features/stop_on_failure_config.feature @@ -80,7 +80,7 @@ Feature: Stop on failure via config Given a file named "behat.yml" with: """ default: - config: + testers: stop_on_failure: false """ When I run "behat --no-colors --format-settings='{\"paths\": false}' features/failing.feature" @@ -116,7 +116,7 @@ Feature: Stop on failure via config Given a file named "behat.yml" with: """ default: - config: + testers: stop_on_failure: true """ When I run "behat --no-colors --format-settings='{\"paths\": false}' features/failing.feature" @@ -134,7 +134,7 @@ Feature: Stop on failure via config Given a file named "behat.yml" with: """ default: - config: + testers: stop_on_failure: true """ When I run "behat --no-colors --format-settings='{\"paths\": false}' features/missing-step.feature" @@ -148,7 +148,7 @@ Feature: Stop on failure via config Given a file named "behat.yml" with: """ default: - config: + testers: stop_on_failure: true """ @@ -163,7 +163,7 @@ Feature: Stop on failure via config Given a file named "behat.yml" with: """ default: - config: + testers: stop_on_failure: false """ When I run "behat --no-colors --stop-on-failure --format-settings='{\"paths\": false}' features/failing.feature" diff --git a/src/Behat/Behat/ApplicationFactory.php b/src/Behat/Behat/ApplicationFactory.php index 664040829..68930b5ea 100644 --- a/src/Behat/Behat/ApplicationFactory.php +++ b/src/Behat/Behat/ApplicationFactory.php @@ -10,7 +10,6 @@ namespace Behat\Behat; -use Behat\Behat\Config\ServiceContainer\ConfigExtension; use Behat\Behat\Context\ServiceContainer\ContextExtension; use Behat\Behat\Definition\ServiceContainer\DefinitionExtension; use Behat\Behat\EventDispatcher\ServiceContainer\EventDispatcherExtension; @@ -95,7 +94,6 @@ protected function getDefaultExtensions() new TransformationExtension($processor), new OrderingExtension($processor), new HelperContainerExtension($processor), - new ConfigExtension() ); } diff --git a/src/Behat/Behat/Config/ServiceContainer/ConfigExtension.php b/src/Behat/Behat/Config/ServiceContainer/ConfigExtension.php deleted file mode 100644 index d30512be3..000000000 --- a/src/Behat/Behat/Config/ServiceContainer/ConfigExtension.php +++ /dev/null @@ -1,106 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Behat\Behat\Config\ServiceContainer; - -use Behat\Testwork\EventDispatcher\ServiceContainer\EventDispatcherExtension; -use Behat\Testwork\ServiceContainer\Extension; -use Behat\Testwork\ServiceContainer\ExtensionManager; -use Behat\Testwork\Tester\ServiceContainer\TesterExtension; -use Symfony\Component\Config\Definition\Builder\ArrayNodeDefinition; -use Symfony\Component\DependencyInjection\ContainerBuilder; -use Symfony\Component\DependencyInjection\Definition; -use Symfony\Component\DependencyInjection\Reference; - -/** - * Enables stop on failure controller for Behat. - */ -final class ConfigExtension implements Extension -{ - public const STOP_ON_FAILURE_ID = 'config.stop_on_failure'; - - /** - * {@inheritdoc} - */ - public function getConfigKey() - { - return 'config'; - } - - /** - * {@inheritdoc} - */ - public function initialize(ExtensionManager $extensionManager) - { - } - - /** - * {@inheritdoc} - */ - public function configure(ArrayNodeDefinition $builder) - { - $builder - ->addDefaultsIfNotSet() - ->children() - ->scalarNode('stop_on_failure') - ->defaultValue(null) - ->end() - ->booleanNode('strict') - ->defaultFalse() - ->end() - ->end() - ; - } - - /** - * {@inheritdoc} - */ - public function load(ContainerBuilder $container, array $config) - { - $this->loadStopOnFailureHandler($container, $config); - $this->loadStrictHandler($container, $config); - } - - /** - * {@inheritdoc} - */ - public function process(ContainerBuilder $container) - { - } - - - /** - * Loads stop on failure controller. - */ - private function loadStopOnFailureHandler(ContainerBuilder $container, array $config) - { - $definition = new Definition('Behat\Behat\Config\Handler\StopOnFailureHandler', array( - new Reference(EventDispatcherExtension::DISPATCHER_ID) - )); - $definition->addMethodCall('setResultInterpreter', array(new Reference(TesterExtension::RESULT_INTERPRETER_ID))); - - if ($config['stop_on_failure'] === true) { - $definition->addMethodCall('registerListeners'); - } - $container->setDefinition(self::STOP_ON_FAILURE_ID, $definition); - } - - /** - * Loads strict handler. - */ - private function loadStrictHandler(ContainerBuilder $container, array $config) - { - if ($config['strict'] === true) { - $definition = new Definition('Behat\Testwork\Tester\Result\Interpretation\StrictInterpretation'); - $definition->addTag(TesterExtension::RESULT_INTERPRETATION_TAG); - $container->setDefinition(TesterExtension::RESULT_INTERPRETATION_TAG . '.strict', $definition); - } - } -} diff --git a/src/Behat/Behat/EventDispatcher/Cli/StopOnFailureController.php b/src/Behat/Behat/EventDispatcher/Cli/StopOnFailureController.php index 1543dfe30..3191d061f 100644 --- a/src/Behat/Behat/EventDispatcher/Cli/StopOnFailureController.php +++ b/src/Behat/Behat/EventDispatcher/Cli/StopOnFailureController.php @@ -10,7 +10,6 @@ namespace Behat\Behat\EventDispatcher\Cli; -use Behat\Behat\Config\Handler\StopOnFailureHandler; use Behat\Behat\EventDispatcher\Event\AfterScenarioTested; use Behat\Behat\EventDispatcher\Event\ExampleTested; use Behat\Behat\EventDispatcher\Event\ScenarioTested; @@ -20,6 +19,7 @@ use Behat\Testwork\EventDispatcher\Event\ExerciseCompleted; use Behat\Testwork\EventDispatcher\Event\SuiteTested; use Behat\Testwork\EventDispatcher\TestworkEventDispatcher; +use Behat\Testwork\Tester\Handler\StopOnFailureHandler; use Behat\Testwork\Tester\Result\Interpretation\ResultInterpretation; use Behat\Testwork\Tester\Result\Interpretation\SoftInterpretation; use Behat\Testwork\Tester\Result\Interpretation\StrictInterpretation; @@ -32,6 +32,8 @@ /** * Stops tests on first scenario failure. + * + * TODO this should be moved in the Behat\Testwork\Tester\Cli namespace * * @author Konstantin Kudryashov */ diff --git a/src/Behat/Behat/EventDispatcher/ServiceContainer/EventDispatcherExtension.php b/src/Behat/Behat/EventDispatcher/ServiceContainer/EventDispatcherExtension.php index 39d0bb342..91d488ceb 100644 --- a/src/Behat/Behat/EventDispatcher/ServiceContainer/EventDispatcherExtension.php +++ b/src/Behat/Behat/EventDispatcher/ServiceContainer/EventDispatcherExtension.php @@ -10,12 +10,12 @@ namespace Behat\Behat\EventDispatcher\ServiceContainer; -use Behat\Behat\Config\ServiceContainer\ConfigExtension; use Behat\Behat\EventDispatcher\Event\ExampleTested; use Behat\Behat\EventDispatcher\Event\ScenarioTested; use Behat\Behat\Tester\ServiceContainer\TesterExtension; use Behat\Testwork\Cli\ServiceContainer\CliExtension; use Behat\Testwork\EventDispatcher\ServiceContainer\EventDispatcherExtension as BaseExtension; +use Behat\Testwork\Tester\ServiceContainer\TesterExtension as TestworkTesterExtension; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Definition; use Symfony\Component\DependencyInjection\Reference; @@ -54,7 +54,7 @@ protected function loadStopOnFailureController(ContainerBuilder $container) $definition = new Definition('Behat\Behat\EventDispatcher\Cli\StopOnFailureController', array( new Reference(EventDispatcherExtension::DISPATCHER_ID) )); - $definition->addMethodCall(('setStopOnFailureHandler'), array(new Reference(ConfigExtension::STOP_ON_FAILURE_ID))); + $definition->addMethodCall(('setStopOnFailureHandler'), array(new Reference(TestworkTesterExtension::STOP_ON_FAILURE_ID))); $definition->addTag(CliExtension::CONTROLLER_TAG, array('priority' => 100)); $container->setDefinition(CliExtension::CONTROLLER_TAG . '.stop_on_failure', $definition); } diff --git a/src/Behat/Testwork/Tester/Cli/StrictController.php b/src/Behat/Testwork/Tester/Cli/StrictController.php index 697b881fc..ebe0d6dc3 100644 --- a/src/Behat/Testwork/Tester/Cli/StrictController.php +++ b/src/Behat/Testwork/Tester/Cli/StrictController.php @@ -29,10 +29,6 @@ final class StrictController implements Controller * @var ResultInterpreter */ private $resultInterpreter; - /** - * @var bool - */ - private $strict; /** * Initializes controller. @@ -40,10 +36,9 @@ final class StrictController implements Controller * @param ResultInterpreter $resultInterpreter * @param bool $strict */ - public function __construct(ResultInterpreter $resultInterpreter, $strict = false) + public function __construct(ResultInterpreter $resultInterpreter) { $this->resultInterpreter = $resultInterpreter; - $this->strict = $strict; } /** @@ -61,7 +56,7 @@ public function configure(Command $command) */ public function execute(InputInterface $input, OutputInterface $output) { - if (!$this->strict && !$input->getOption('strict')) { + if (!$input->getOption('strict')) { return; } diff --git a/src/Behat/Behat/Config/Handler/StopOnFailureHandler.php b/src/Behat/Testwork/Tester/Handler/StopOnFailureHandler.php similarity index 97% rename from src/Behat/Behat/Config/Handler/StopOnFailureHandler.php rename to src/Behat/Testwork/Tester/Handler/StopOnFailureHandler.php index 89a548391..ac762ad83 100644 --- a/src/Behat/Behat/Config/Handler/StopOnFailureHandler.php +++ b/src/Behat/Testwork/Tester/Handler/StopOnFailureHandler.php @@ -8,7 +8,8 @@ * file that was distributed with this source code. */ -namespace Behat\Behat\Config\Handler; +namespace Behat\Testwork\Tester\Handler; + use Behat\Behat\EventDispatcher\Event\AfterScenarioTested; use Behat\Behat\EventDispatcher\Event\ExampleTested; diff --git a/src/Behat/Testwork/Tester/ServiceContainer/TesterExtension.php b/src/Behat/Testwork/Tester/ServiceContainer/TesterExtension.php index 41cb7f695..526a926a9 100644 --- a/src/Behat/Testwork/Tester/ServiceContainer/TesterExtension.php +++ b/src/Behat/Testwork/Tester/ServiceContainer/TesterExtension.php @@ -12,6 +12,7 @@ use Behat\Testwork\Cli\ServiceContainer\CliExtension; use Behat\Testwork\Environment\ServiceContainer\EnvironmentExtension; +use Behat\Testwork\EventDispatcher\ServiceContainer\EventDispatcherExtension; use Behat\Testwork\ServiceContainer\Extension; use Behat\Testwork\ServiceContainer\ExtensionManager; use Behat\Testwork\ServiceContainer\ServiceProcessor; @@ -36,6 +37,7 @@ abstract class TesterExtension implements Extension public const SUITE_TESTER_ID = 'tester.suite'; public const SPECIFICATION_TESTER_ID = 'tester.specification'; public const RESULT_INTERPRETER_ID = 'tester.result.interpreter'; + public const STOP_ON_FAILURE_ID = 'tester.stop_on_failure'; /** * Available extension points @@ -83,6 +85,9 @@ public function configure(ArrayNodeDefinition $builder) $builder ->addDefaultsIfNotSet() ->children() + ->scalarNode('stop_on_failure') + ->defaultValue(null) + ->end() ->booleanNode('strict') ->info('Sets the strict mode for result interpretation') ->defaultFalse() @@ -101,8 +106,9 @@ public function configure(ArrayNodeDefinition $builder) public function load(ContainerBuilder $container, array $config) { $this->loadExerciseController($container, $config['skip']); + $this->loadStopOnFailureHandler($container, $config['stop_on_failure']); $this->loadStrictController($container, $config['strict']); - $this->loadResultInterpreter($container); + $this->loadResultInterpreter($container, $config['strict']); $this->loadExercise($container); $this->loadSuiteTester($container); $this->loadSpecificationTester($container); @@ -137,6 +143,23 @@ protected function loadExerciseController(ContainerBuilder $container, $skip = f $definition->addTag(CliExtension::CONTROLLER_TAG, array('priority' => 0)); $container->setDefinition(CliExtension::CONTROLLER_TAG . '.exercise', $definition); } + + + /** + * Loads stop on failure controller. + */ + private function loadStopOnFailureHandler(ContainerBuilder $container, ?bool $stopOnFailure) + { + $definition = new Definition('Behat\Testwork\Tester\Handler\StopOnFailureHandler', array( + new Reference(EventDispatcherExtension::DISPATCHER_ID) + )); + $definition->addMethodCall('setResultInterpreter', array(new Reference(TesterExtension::RESULT_INTERPRETER_ID))); + + if ($stopOnFailure === true) { + $definition->addMethodCall('registerListeners'); + } + $container->setDefinition(self::STOP_ON_FAILURE_ID, $definition); + } /** * Loads exercise cli controllers. @@ -147,8 +170,7 @@ protected function loadExerciseController(ContainerBuilder $container, $skip = f protected function loadStrictController(ContainerBuilder $container, $strict = false) { $definition = new Definition('Behat\Testwork\Tester\Cli\StrictController', array( - new Reference(self::RESULT_INTERPRETER_ID), - $strict + new Reference(self::RESULT_INTERPRETER_ID) )); $definition->addTag(CliExtension::CONTROLLER_TAG, array('priority' => 300)); $container->setDefinition(CliExtension::CONTROLLER_TAG . '.strict', $definition); @@ -159,7 +181,7 @@ protected function loadStrictController(ContainerBuilder $container, $strict = f * * @param ContainerBuilder $container */ - protected function loadResultInterpreter(ContainerBuilder $container) + protected function loadResultInterpreter(ContainerBuilder $container, bool $strict) { $definition = new Definition('Behat\Testwork\Tester\Result\ResultInterpreter'); $container->setDefinition(self::RESULT_INTERPRETER_ID, $definition); @@ -167,6 +189,13 @@ protected function loadResultInterpreter(ContainerBuilder $container) $definition = new Definition('Behat\Testwork\Tester\Result\Interpretation\SoftInterpretation'); $definition->addTag(self::RESULT_INTERPRETATION_TAG); $container->setDefinition(self::RESULT_INTERPRETATION_TAG . '.soft', $definition); + + + if ($strict) { + $definition = new Definition('Behat\Testwork\Tester\Result\Interpretation\StrictInterpretation'); + $definition->addTag(TesterExtension::RESULT_INTERPRETATION_TAG); + $container->setDefinition(TesterExtension::RESULT_INTERPRETATION_TAG . '.strict', $definition); + } } /** From 960df7c4794305f00f54d5703b300afc83fea8f5 Mon Sep 17 00:00:00 2001 From: Julien Deniau Date: Thu, 7 Nov 2024 09:13:44 +0100 Subject: [PATCH 433/567] rollback StrictController implementation --- src/Behat/Testwork/Tester/Cli/StrictController.php | 11 ++++++++--- .../Tester/Handler/StopOnFailureHandler.php | 2 +- .../Tester/ServiceContainer/TesterExtension.php | 14 ++++---------- 3 files changed, 13 insertions(+), 14 deletions(-) diff --git a/src/Behat/Testwork/Tester/Cli/StrictController.php b/src/Behat/Testwork/Tester/Cli/StrictController.php index ebe0d6dc3..09c51009b 100644 --- a/src/Behat/Testwork/Tester/Cli/StrictController.php +++ b/src/Behat/Testwork/Tester/Cli/StrictController.php @@ -29,16 +29,21 @@ final class StrictController implements Controller * @var ResultInterpreter */ private $resultInterpreter; - + /** + * @var bool + */ + private $strict; + /** * Initializes controller. * * @param ResultInterpreter $resultInterpreter * @param bool $strict */ - public function __construct(ResultInterpreter $resultInterpreter) + public function __construct(ResultInterpreter $resultInterpreter, $strict = false) { $this->resultInterpreter = $resultInterpreter; + $this->strict = $strict; } /** @@ -56,7 +61,7 @@ public function configure(Command $command) */ public function execute(InputInterface $input, OutputInterface $output) { - if (!$input->getOption('strict')) { + if (!$this->strict && !$input->getOption('strict')) { return; } diff --git a/src/Behat/Testwork/Tester/Handler/StopOnFailureHandler.php b/src/Behat/Testwork/Tester/Handler/StopOnFailureHandler.php index ac762ad83..e0455d54c 100644 --- a/src/Behat/Testwork/Tester/Handler/StopOnFailureHandler.php +++ b/src/Behat/Testwork/Tester/Handler/StopOnFailureHandler.php @@ -50,7 +50,7 @@ public function registerListeners() */ public function exitOnFailure(AfterScenarioTested $event) { - if (0 === $this->resultInterpreter->interpretResult($event->getTestResult())) { + if (ResultInterpreter::PASS === $this->resultInterpreter->interpretResult($event->getTestResult())) { return; } diff --git a/src/Behat/Testwork/Tester/ServiceContainer/TesterExtension.php b/src/Behat/Testwork/Tester/ServiceContainer/TesterExtension.php index 526a926a9..3c0765c87 100644 --- a/src/Behat/Testwork/Tester/ServiceContainer/TesterExtension.php +++ b/src/Behat/Testwork/Tester/ServiceContainer/TesterExtension.php @@ -108,7 +108,7 @@ public function load(ContainerBuilder $container, array $config) $this->loadExerciseController($container, $config['skip']); $this->loadStopOnFailureHandler($container, $config['stop_on_failure']); $this->loadStrictController($container, $config['strict']); - $this->loadResultInterpreter($container, $config['strict']); + $this->loadResultInterpreter($container); $this->loadExercise($container); $this->loadSuiteTester($container); $this->loadSpecificationTester($container); @@ -170,7 +170,8 @@ private function loadStopOnFailureHandler(ContainerBuilder $container, ?bool $st protected function loadStrictController(ContainerBuilder $container, $strict = false) { $definition = new Definition('Behat\Testwork\Tester\Cli\StrictController', array( - new Reference(self::RESULT_INTERPRETER_ID) + new Reference(self::RESULT_INTERPRETER_ID), + $strict )); $definition->addTag(CliExtension::CONTROLLER_TAG, array('priority' => 300)); $container->setDefinition(CliExtension::CONTROLLER_TAG . '.strict', $definition); @@ -181,7 +182,7 @@ protected function loadStrictController(ContainerBuilder $container, $strict = f * * @param ContainerBuilder $container */ - protected function loadResultInterpreter(ContainerBuilder $container, bool $strict) + protected function loadResultInterpreter(ContainerBuilder $container) { $definition = new Definition('Behat\Testwork\Tester\Result\ResultInterpreter'); $container->setDefinition(self::RESULT_INTERPRETER_ID, $definition); @@ -189,13 +190,6 @@ protected function loadResultInterpreter(ContainerBuilder $container, bool $stri $definition = new Definition('Behat\Testwork\Tester\Result\Interpretation\SoftInterpretation'); $definition->addTag(self::RESULT_INTERPRETATION_TAG); $container->setDefinition(self::RESULT_INTERPRETATION_TAG . '.soft', $definition); - - - if ($strict) { - $definition = new Definition('Behat\Testwork\Tester\Result\Interpretation\StrictInterpretation'); - $definition->addTag(TesterExtension::RESULT_INTERPRETATION_TAG); - $container->setDefinition(TesterExtension::RESULT_INTERPRETATION_TAG . '.strict', $definition); - } } /** From 7b414939d0e02ad239f049d198ccd24421ed149f Mon Sep 17 00:00:00 2001 From: Julien Deniau Date: Fri, 8 Nov 2024 07:58:12 +0000 Subject: [PATCH 434/567] inject ResultInterpreter in constructor directly --- .../Testwork/Tester/Handler/StopOnFailureHandler.php | 10 ++-------- .../Tester/ServiceContainer/TesterExtension.php | 6 +++--- 2 files changed, 5 insertions(+), 11 deletions(-) diff --git a/src/Behat/Testwork/Tester/Handler/StopOnFailureHandler.php b/src/Behat/Testwork/Tester/Handler/StopOnFailureHandler.php index e0455d54c..b875b46e1 100644 --- a/src/Behat/Testwork/Tester/Handler/StopOnFailureHandler.php +++ b/src/Behat/Testwork/Tester/Handler/StopOnFailureHandler.php @@ -26,18 +26,12 @@ */ final class StopOnFailureHandler { - private ResultInterpreter $resultInterpreter; - public function __construct( - private readonly EventDispatcherInterface $eventDispatcher + private readonly EventDispatcherInterface $eventDispatcher, + private readonly ResultInterpreter $resultInterpreter ) { } - - public function setResultInterpreter(ResultInterpreter $resultInterpreter) - { - $this->resultInterpreter = $resultInterpreter; - } public function registerListeners() { diff --git a/src/Behat/Testwork/Tester/ServiceContainer/TesterExtension.php b/src/Behat/Testwork/Tester/ServiceContainer/TesterExtension.php index 3c0765c87..0e96869b4 100644 --- a/src/Behat/Testwork/Tester/ServiceContainer/TesterExtension.php +++ b/src/Behat/Testwork/Tester/ServiceContainer/TesterExtension.php @@ -146,14 +146,14 @@ protected function loadExerciseController(ContainerBuilder $container, $skip = f /** - * Loads stop on failure controller. + * Loads stop on failure handler. */ private function loadStopOnFailureHandler(ContainerBuilder $container, ?bool $stopOnFailure) { $definition = new Definition('Behat\Testwork\Tester\Handler\StopOnFailureHandler', array( - new Reference(EventDispatcherExtension::DISPATCHER_ID) + new Reference(EventDispatcherExtension::DISPATCHER_ID), + new Reference(TesterExtension::RESULT_INTERPRETER_ID) )); - $definition->addMethodCall('setResultInterpreter', array(new Reference(TesterExtension::RESULT_INTERPRETER_ID))); if ($stopOnFailure === true) { $definition->addMethodCall('registerListeners'); From 2c7d664b4060e9f89044caf4505e25c0247c3c8c Mon Sep 17 00:00:00 2001 From: acoulton Date: Thu, 7 Nov 2024 21:14:18 +0000 Subject: [PATCH 435/567] bug: Improve handling exceptions from unsupported PHPUnit versions Attempting to render PHPUnit assertion failures is brittle, because a) we (intentionally) don't impose any PHPUnit version constraints in composer.json and b) PHPUnit's code for rendering exceptions is not covered by their BC promise. This update to the PHPUnitExceptionStringer ensures that we always render something useful - prioritising communicating that an assertion has failed - even if we don't correctly support the PHPUnit version in use. --- .../Stringer/PHPUnitExceptionStringer.php | 93 +++++++++++++++++-- 1 file changed, 83 insertions(+), 10 deletions(-) diff --git a/src/Behat/Testwork/Exception/Stringer/PHPUnitExceptionStringer.php b/src/Behat/Testwork/Exception/Stringer/PHPUnitExceptionStringer.php index 17343f15a..beb8a9b7f 100644 --- a/src/Behat/Testwork/Exception/Stringer/PHPUnitExceptionStringer.php +++ b/src/Behat/Testwork/Exception/Stringer/PHPUnitExceptionStringer.php @@ -11,6 +11,7 @@ namespace Behat\Testwork\Exception\Stringer; use Exception; +use Throwable; /** * Strings PHPUnit assertion exceptions. @@ -35,17 +36,89 @@ public function supportsException(Exception $exception) */ public function stringException(Exception $exception, $verbosity) { - if (class_exists('PHPUnit\\Util\\ThrowableToStringMapper')) { - return trim(\PHPUnit\Util\ThrowableToStringMapper::map($exception)); - } + // PHPUnit assertion exceptions do not include detailed expected / observed info in their messages. Instead, + // test result printers within PHPUnit are expected to format and present that information separately. The + // mechanism for this varies between PHPUnit major versions, and all the implementations are tagged with: + // + // * @internal This class is not covered by the backward compatibility promise for PHPUnit` + // + // Behat itself does not use PHPUnit at runtime, and user projects may use PHPUnit solely for unit tests with + // a completely separate assertion mechanism for their Behat steps. + // + // Therefore, Behat does not impose any formal PHPUnit version constraints. + // + // Instead, we make a best effort to render as much detail of a PHPUnit assertion failure as we can, without + // masking that the ultimate problem was caused by a failed assertion in the user's own code. + // + // ** + // * We cannot guarantee that this will work, or produce the same output, even across minor PHPUnit versions. + // * That said, historically this has been relatively stable for a given major version series. + // ** + // + // If you encounter a problem rendering PHPUnit assertions in your project, you have three options: + // + // * Roll back to a PHPUnit minor / patch version that you know works for you. + // * Catch the failures within your Context classes and format them yourself. For example, you could implement + // a generic wrapper to call like `MyClass::formatFailure(fn () => Assert::assertSame(1, 2, 'Uh-oh'))`. + // * Contribute a PR to Behat to add support for the newer PHPUnit version :) - if (!class_exists('PHPUnit\\Framework\\TestFailure')) { - return trim(\PHPUnit_Framework_TestFailure::exceptionToString($exception)); - } + try { + // Class names are intentionally fully qualified here to maximise clarity - particularly because a future + // PHPUnit version may reuse a class name in a different namespace. + + if (class_exists(\PHPUnit\Util\ThrowableToStringMapper::class)) { + // PHPUnit 10.0.0 onwards + return trim(\PHPUnit\Util\ThrowableToStringMapper::map($exception)); + } - // PHPUnit assertion exceptions do not include expected / observed info in their - // messages, but expect the test listeners to format that info like the following - // (see e.g. PHPUnit_TextUI_ResultPrinter::printDefectTrace) - return trim(\PHPUnit\Framework\TestFailure::exceptionToString($exception)); + if (class_exists(\PHPUnit\Framework\TestFailure::class)) { + // PHPUnit 6.0.0 - 9.x + return trim(\PHPUnit\Framework\TestFailure::exceptionToString($exception)); + } + + if (class_exists(\PHPUnit_Framework_TestFailure::class)) { + // PHPUnit < 6 (support ended in 2016) + return trim(\PHPUnit_Framework_TestFailure::exceptionToString($exception)); + } + + // PHPUnit must be present, because we got a PHPUnit exception. So it must be a newer version with a + // formatter class / method we don't know about. + return sprintf( + <<getMessage(), + $exception::class, + self::class, + ); + } catch (Throwable $phpunitException) { + // PHPUnit does not guarantee BC on the classes / methods we're calling. + // + // So it is likely that it looked like a version we expected, but the method signature or internal typing + // has changed, causing an error at runtime. + // + // It is also possible that there's something in the user input (e.g. a value passed to $expect) that is + // causing an error when PHPUnit tries to stringify it - but PHPUnit is generally quite robust about + // catching those situations and reporting them within the message body. + return sprintf( + <<getMessage(), + $exception::class, + self::class, + $phpunitException::class, + $phpunitException->getMessage(), + $phpunitException->getFile(), + $phpunitException->getLine(), + ); + } } } From 0a4af834c46cf2897560c1dc8be86b22f64c4669 Mon Sep 17 00:00:00 2001 From: acoulton Date: Fri, 8 Nov 2024 11:17:28 +0000 Subject: [PATCH 436/567] Add changelog for 3.16.0 release --- CHANGELOG.md | 38 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 507421671..516add15f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,41 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](http://keepachangelog.com/) and this project adheres to [Semantic Versioning](http://semver.org/). +## [3.16.0] - 2024-11-08 + +### Changed + +* Drop support for PHP < 8.1, Symfony < 5.4 and Symfony 6.0 - 6.3. In future Behat will drop support for PHP and symfony + versions as they reach EOL. by @AlexSkrypnyk in [#1504](https://github.com/Behat/Behat/pull/1504) +* ApplicationFactory::VERSION is deprecated and will not be updated, Behat now internally uses composer's runtime API + to report the running version. by @acoulton in [#1520](https://github.com/Behat/Behat/pull/1520) +* API changes to 2 final Behat classes that are not considered part of the public API (but were not explicitly marked + as such). This may affect users who are creating instances direct rather than through the DI container as expected. + See Behat\Behat\EventDispatcher\Cli\StopOnFailureController in #1501 and Behat\Behat\Tester\Cli\RerunController in #1518. + +### Added + +* Render JUnit test durations with millisecond precision e.g. `1.234` rather than only as integer seconds + by @uuf6429 in [#1460](https://github.com/Behat/Behat/pull/1460) +* Support specifying `stop_on_failure` within behat.yml by @jdeniau in [#1512](https://github.com/Behat/Behat/pull/1512), + [#1501](https://github.com/Behat/Behat/pull/1501) and [#1516](https://github.com/Behat/Behat/pull/1516) +* Allow BeforeSuite/AfterSuite hooks to be marked with attributes by @rpkamp in [#1511](https://github.com/Behat/Behat/pull/1511) + +### Fixed + +* `--rerun` all tests that should be considered failed (including undefined, when strict) by @carlos-granados in [#1518](https://github.com/Behat/Behat/pull/1518) +* Improve handling exceptions from unsupported PHPUnit versions by @acoulton and @uuf6429 in [#1521](https://github.com/Behat/Behat/pull/1521) +* Fix high memory consumption when using Junit formatter by @simon-auch in [#1423](https://github.com/Behat/Behat/pull/1423) +* Fix error when attempting to format long output messages by @jonpugh in [#1439](https://github.com/Behat/Behat/pull/1439) + +### Internal + +* Remove the unnecessary alias of the ScenarioInterface as it just causes confusion by @carlos-granados in [#1500](https://github.com/Behat/Behat/pull/1500) +* Improve output when behat's own tests pass or fail unexpectedly by @jdeniau in [#1515](https://github.com/Behat/Behat/pull/1515) +* Update guidance on submitting PRs by @acoulton in [#1505](https://github.com/Behat/Behat/pull/1505) +* Fix indentation in Github Actions config by @AlexSkrypnyk in [#1502](https://github.com/Behat/Behat/pull/1502) +* Fix Github Actions phar upload for the release by @carlos-granados in [#1509](https://github.com/Behat/Behat/pull/1509) + ## [3.15.0] - 2024-10-29 ***Note:** This release also bumps the minor version of behat/gherkin to 4.10.0, which was released on 2024-10-19 with @@ -1066,6 +1101,9 @@ and this project adheres to [Semantic Versioning](http://semver.org/). ### Changed * Initial release +[3.16.0]: https://github.com/Behat/Behat/compare/v3.15.0...v3.16.0 +[3.15.0]: https://github.com/Behat/Behat/compare/v3.14.0...v3.15.0 +[3.14.0]: https://github.com/Behat/Behat/compare/v3.13.0...v3.14.0 [3.13.0]: https://github.com/Behat/Behat/compare/v3.12.0...v3.13.0 [3.12.0]: https://github.com/Behat/Behat/compare/v3.11.0...v3.12.0 [3.11.0]: https://github.com/Behat/Behat/compare/v3.10.0...v3.11.0 From 1e2e60b9c3df69425149fd872c382b12af32f6aa Mon Sep 17 00:00:00 2001 From: Carlos Granados Date: Fri, 8 Nov 2024 13:37:08 +0100 Subject: [PATCH 437/567] fix: regex snippet generation for steps defined with single quotes --- features/legacy_snippets.feature | 24 ++++++++-------- features/snippets.feature | 28 +++++++++---------- .../Pattern/Policy/RegexPatternPolicy.php | 2 +- 3 files changed, 27 insertions(+), 27 deletions(-) diff --git a/features/legacy_snippets.feature b/features/legacy_snippets.feature index 447014d25..688c7e743 100644 --- a/features/legacy_snippets.feature +++ b/features/legacy_snippets.feature @@ -12,7 +12,7 @@ Feature: Legacy Snippets Given I have magically created 10$ Scenario: Single quotes - When I have chose 'coffee with turkey' in coffee machine + When I have chosen 'coffee with turkey' in coffee machine Then I should have 'turkey with coffee sauce' And I should get a 'super/string': ''' @@ -24,7 +24,7 @@ Feature: Legacy Snippets ''' Scenario: Double quotes - When I have chose "pizza tea" in coffee machine + When I have chosen "pizza tea" in coffee machine And do something undefined with \1 Then I should have "pizza tea" And I should get a "super/string": @@ -70,9 +70,9 @@ Feature: Legacy Snippets } /** - * @When /^I have chose '([^']*)' in coffee machine$/ + * @When /^I have chosen '([^']*)' in coffee machine$/ */ - public function iHaveChoseCoffeeWithTurkeyInCoffeeMachine($arg1): void + public function iHaveChosenInCoffeeMachine($arg1): void { throw new PendingException(); } @@ -80,7 +80,7 @@ Feature: Legacy Snippets /** * @Then /^I should have '([^']*)'$/ */ - public function iShouldHaveTurkeyWithCoffeeSauce($arg1): void + public function iShouldHave($arg1): void { throw new PendingException(); } @@ -88,7 +88,7 @@ Feature: Legacy Snippets /** * @Then /^I should get a '([^']*)':$/ */ - public function iShouldGetASuperString($arg1, PyStringNode $string): void + public function iShouldGetA($arg1, PyStringNode $string): void { throw new PendingException(); } @@ -102,9 +102,9 @@ Feature: Legacy Snippets } /** - * @When /^I have chose "([^"]*)" in coffee machine$/ + * @When /^I have chosen "([^"]*)" in coffee machine$/ */ - public function iHaveChoseInCoffeeMachine($arg1): void + public function iHaveChosenInCoffeeMachine2($arg1): void { throw new PendingException(); } @@ -120,7 +120,7 @@ Feature: Legacy Snippets /** * @Then /^I should have "([^"]*)"$/ */ - public function iShouldHave($arg1): void + public function iShouldHave2($arg1): void { throw new PendingException(); } @@ -128,7 +128,7 @@ Feature: Legacy Snippets /** * @Then /^I should get a "([^"]*)":$/ */ - public function iShouldGetA($arg1, PyStringNode $string): void + public function iShouldGetA2($arg1, PyStringNode $string): void { throw new PendingException(); } @@ -199,9 +199,9 @@ Feature: Legacy Snippets } /** - * @When I have chose :arg1 in coffee machine + * @When I have chosen :arg1 in coffee machine */ - public function iHaveChoseInCoffeeMachine($arg1): void + public function iHaveChosenInCoffeeMachine($arg1): void { throw new PendingException(); } diff --git a/features/snippets.feature b/features/snippets.feature index 196ed727d..b463db2d5 100644 --- a/features/snippets.feature +++ b/features/snippets.feature @@ -12,7 +12,7 @@ Feature: Snippets generation and addition Given I have magically created 10$ Scenario: Single quotes - When I have chose 'coffee with turkey' in coffee machine + When I have chosen 'coffee with turkey' in coffee machine Then I should have 'turkey with coffee sauce' And I should get a 'super/string': ''' @@ -24,7 +24,7 @@ Feature: Snippets generation and addition ''' Scenario: Double quotes - When I have chose "pizza tea" in coffee machine + When I have chosen "pizza tea" in coffee machine And do something undefined with \1 Then I should have "pizza tea" And I should get a "super/string": @@ -68,9 +68,9 @@ Feature: Snippets generation and addition } /** - * @When /^I have chose '([^']*)' in coffee machine$/ + * @When /^I have chosen '([^']*)' in coffee machine$/ */ - public function iHaveChoseCoffeeWithTurkeyInCoffeeMachine($arg1): void + public function iHaveChosenInCoffeeMachine($arg1): void { throw new PendingException(); } @@ -78,7 +78,7 @@ Feature: Snippets generation and addition /** * @Then /^I should have '([^']*)'$/ */ - public function iShouldHaveTurkeyWithCoffeeSauce($arg1): void + public function iShouldHave($arg1): void { throw new PendingException(); } @@ -86,7 +86,7 @@ Feature: Snippets generation and addition /** * @Then /^I should get a '([^']*)':$/ */ - public function iShouldGetASuperString($arg1, PyStringNode $string): void + public function iShouldGetA($arg1, PyStringNode $string): void { throw new PendingException(); } @@ -100,9 +100,9 @@ Feature: Snippets generation and addition } /** - * @When /^I have chose "([^"]*)" in coffee machine$/ + * @When /^I have chosen "([^"]*)" in coffee machine$/ */ - public function iHaveChoseInCoffeeMachine($arg1): void + public function iHaveChosenInCoffeeMachine2($arg1): void { throw new PendingException(); } @@ -118,7 +118,7 @@ Feature: Snippets generation and addition /** * @Then /^I should have "([^"]*)"$/ */ - public function iShouldHave($arg1): void + public function iShouldHave2($arg1): void { throw new PendingException(); } @@ -126,7 +126,7 @@ Feature: Snippets generation and addition /** * @Then /^I should get a "([^"]*)":$/ */ - public function iShouldGetA($arg1, PyStringNode $string): void + public function iShouldGetA2($arg1, PyStringNode $string): void { throw new PendingException(); } @@ -195,9 +195,9 @@ Feature: Snippets generation and addition } /** - * @When I have chose :arg1 in coffee machine + * @When I have chosen :arg1 in coffee machine */ - public function iHaveChoseInCoffeeMachine($arg1): void + public function iHaveChosenInCoffeeMachine($arg1): void { throw new PendingException(); } @@ -393,9 +393,9 @@ Feature: Snippets generation and addition } /** - * @When I have chose :arg1 in coffee machine + * @When I have chosen :arg1 in coffee machine */ - public function iHaveChoseInCoffeeMachine($arg1): void + public function iHaveChosenInCoffeeMachine($arg1): void { throw new PendingException(); } diff --git a/src/Behat/Behat/Definition/Pattern/Policy/RegexPatternPolicy.php b/src/Behat/Behat/Definition/Pattern/Policy/RegexPatternPolicy.php index 76498b91b..fe3f41fbd 100644 --- a/src/Behat/Behat/Definition/Pattern/Policy/RegexPatternPolicy.php +++ b/src/Behat/Behat/Definition/Pattern/Policy/RegexPatternPolicy.php @@ -98,7 +98,7 @@ private function generateRegex($stepText) */ private function generateCanonicalText($stepText) { - $canonicalText = preg_replace(array_keys(self::$replacePatterns), '', $stepText); + $canonicalText = preg_replace(array_keys(self::$replacePatterns), '', $this->escapeStepText($stepText)); $canonicalText = Transliterator::transliterate($canonicalText, ' '); $canonicalText = preg_replace('/[^a-zA-Z\_\ ]/', '', $canonicalText); $canonicalText = str_replace(' ', '', ucwords($canonicalText)); From 47a881b39821cc5032199a0571f8238e3062472e Mon Sep 17 00:00:00 2001 From: Michael Hirschler Date: Fri, 8 Nov 2024 14:09:02 +0100 Subject: [PATCH 438/567] fixes deprecated passing null to explode --- .../Behat/Output/Node/Printer/JUnit/JUnitScenarioPrinter.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Behat/Behat/Output/Node/Printer/JUnit/JUnitScenarioPrinter.php b/src/Behat/Behat/Output/Node/Printer/JUnit/JUnitScenarioPrinter.php index 5010652bf..a9d71a058 100644 --- a/src/Behat/Behat/Output/Node/Printer/JUnit/JUnitScenarioPrinter.php +++ b/src/Behat/Behat/Output/Node/Printer/JUnit/JUnitScenarioPrinter.php @@ -67,7 +67,7 @@ public function printOpenTag(Formatter $formatter, FeatureNode $feature, Scenari { $name = implode(' ', array_map(function ($l) { return trim($l); - }, explode("\n", $scenario->getTitle()))); + }, explode("\n", $scenario->getTitle() ?? ''))); if ($scenario instanceof ExampleNode) { $name = $this->buildExampleName($scenario); From b48fbd59d6dd84db24032028abd027119dcd7246 Mon Sep 17 00:00:00 2001 From: Carlos Granados Date: Sat, 9 Nov 2024 08:18:14 +0100 Subject: [PATCH 439/567] feature: display hook failures location in progress printer --- features/hooks_failures.feature | 213 ++++++++++++++++++ .../Statistics/HookStatsListener.php | 5 +- .../Behat/Output/Node/Printer/ListPrinter.php | 37 ++- .../Behat/Output/Statistics/HookStat.php | 16 ++ 4 files changed, 268 insertions(+), 3 deletions(-) create mode 100644 features/hooks_failures.feature diff --git a/features/hooks_failures.feature b/features/hooks_failures.feature new file mode 100644 index 000000000..6334765e3 --- /dev/null +++ b/features/hooks_failures.feature @@ -0,0 +1,213 @@ +Feature: Display hook failures location in progress printer + In order to be able to locate the code that generated a failure + As a feature developer using the progress printer + When a hook throws an error I want to see the related item where the code failed + + Background: + Given a file named "features/simple.feature" with: + """ + Feature: Simple feature + + Scenario: Simple scenario + When I have a simple step + """ + + Scenario: Handling of a error in beforeSuite hook + Given a file named "features/bootstrap/FeatureContext.php" with: + """ + getCall()->getCallee(); + $call = $hookCallResult->getCall(); + $callee = $call->getCallee(); $hook = (string) $callee; + $scope = $call->getScope(); $path = $callee->getPath(); $stdOut = $hookCallResult->getStdOut(); $error = $hookCallResult->getException() @@ -118,6 +120,7 @@ private function captureHookStat(CallResult $hookCallResult) : null; $stat = new HookStat($hook, $path, $error, $stdOut); + $stat->setScope($scope); $this->statistics->registerHookStat($stat); } } diff --git a/src/Behat/Behat/Output/Node/Printer/ListPrinter.php b/src/Behat/Behat/Output/Node/Printer/ListPrinter.php index 8f7193649..02bd36eb9 100644 --- a/src/Behat/Behat/Output/Node/Printer/ListPrinter.php +++ b/src/Behat/Behat/Output/Node/Printer/ListPrinter.php @@ -11,12 +11,21 @@ namespace Behat\Behat\Output\Node\Printer; use Behat\Behat\Definition\Translator\TranslatorInterface; +use Behat\Behat\Hook\Scope\AfterFeatureScope; +use Behat\Behat\Hook\Scope\AfterScenarioScope; +use Behat\Behat\Hook\Scope\AfterStepScope; +use Behat\Behat\Hook\Scope\BeforeFeatureScope; +use Behat\Behat\Hook\Scope\BeforeScenarioScope; +use Behat\Behat\Hook\Scope\BeforeStepScope; use Behat\Behat\Output\Node\Printer\Helper\ResultToStringConverter; use Behat\Behat\Output\Statistics\HookStat; use Behat\Behat\Output\Statistics\ScenarioStat; use Behat\Behat\Output\Statistics\StepStatV2; use Behat\Behat\Output\Statistics\StepStat; use Behat\Testwork\Exception\ExceptionPresenter; +use Behat\Testwork\Hook\Scope\AfterSuiteScope; +use Behat\Testwork\Hook\Scope\BeforeSuiteScope; +use Behat\Testwork\Hook\Scope\HookScope; use Behat\Testwork\Output\Printer\OutputPrinter; use Behat\Testwork\Tester\Result\TestResult; @@ -182,9 +191,14 @@ private function printStat(OutputPrinter $printer, $name, $path, $style, $stdOut */ private function printHookStat(OutputPrinter $printer, HookStat $hookStat, $style) { + $location = $this->getLocationFromScope($hookStat->getScope()); $printer->writeln( - sprintf(' {+%s}%s{-%s} {+comment}# %s{-comment}', - $style, $hookStat->getName(), $style, $this->relativizePaths($hookStat->getPath()) + sprintf(' {+%s}%s{-%s}%s {+comment}# %s{-comment}', + $style, + $hookStat->getName(), + $style, + $location ? " \"$location\"" : '', + $this->relativizePaths($hookStat->getPath()) ) ); @@ -268,4 +282,23 @@ private function relativizePaths($path) return str_replace($this->basePath . DIRECTORY_SEPARATOR, '', $path); } + + private function getLocationFromScope(?HookScope $scope): ?string + { + if ($scope !== null) { + return match(true) { + $scope instanceof BeforeSuiteScope, $scope instanceof AfterSuiteScope => + $scope->getSuite()->getName(), + $scope instanceof BeforeFeatureScope, $scope instanceof AfterFeatureScope => + $this->relativizePaths($scope->getFeature()->getFile()), + $scope instanceof BeforeScenarioScope, $scope instanceof AfterScenarioScope => + $this->relativizePaths($scope->getFeature()->getFile()) . + ':' . $scope->getScenario()->getLine(), + $scope instanceof BeforeStepScope, $scope instanceof AfterStepScope => + $this->relativizePaths($scope->getFeature()->getFile()) . + ':' . $scope->getStep()->getLine() + }; + } + return null; + } } diff --git a/src/Behat/Behat/Output/Statistics/HookStat.php b/src/Behat/Behat/Output/Statistics/HookStat.php index e8afc312a..26541a9d0 100644 --- a/src/Behat/Behat/Output/Statistics/HookStat.php +++ b/src/Behat/Behat/Output/Statistics/HookStat.php @@ -10,6 +10,8 @@ namespace Behat\Behat\Output\Statistics; +use Behat\Testwork\Hook\Scope\HookScope; + /** * Represents hook stat. * @@ -33,6 +35,10 @@ final class HookStat * @var string|null */ private $stdOut; + /** + * @var HookScope|null + */ + private $scope; /** * Initializes hook stat. @@ -50,6 +56,11 @@ public function __construct($name, $path, $error = null, $stdOut = null) $this->stdOut = $stdOut; } + public function setScope(HookScope $scope) + { + $this->scope = $scope; + } + /** * {@inheritdoc} */ @@ -95,4 +106,9 @@ public function getPath() { return $this->path; } + + public function getScope(): HookScope + { + return $this->scope; + } } From 0cc4440c691d206bfa520dbb0c53b11c36ab6748 Mon Sep 17 00:00:00 2001 From: Carlos Granados Date: Sat, 9 Nov 2024 10:47:40 +0100 Subject: [PATCH 440/567] feature: display hook failures location in progress printer --- .../Node/EventListener/Statistics/HookStatsListener.php | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/Behat/Behat/Output/Node/EventListener/Statistics/HookStatsListener.php b/src/Behat/Behat/Output/Node/EventListener/Statistics/HookStatsListener.php index 5364e0f33..36d4cc0a2 100644 --- a/src/Behat/Behat/Output/Node/EventListener/Statistics/HookStatsListener.php +++ b/src/Behat/Behat/Output/Node/EventListener/Statistics/HookStatsListener.php @@ -120,7 +120,9 @@ private function captureHookStat(CallResult $hookCallResult) : null; $stat = new HookStat($hook, $path, $error, $stdOut); - $stat->setScope($scope); + if (!$stat->isSuccessful()) { + $stat->setScope($scope); + } $this->statistics->registerHookStat($stat); } } From c333ba96c85efe5d133ca32eb8e295219d67fef0 Mon Sep 17 00:00:00 2001 From: Carlos Granados Date: Sat, 9 Nov 2024 19:46:56 +0100 Subject: [PATCH 441/567] Sets the tab size to 2 for feature files --- .editorconfig | 3 +++ 1 file changed, 3 insertions(+) diff --git a/.editorconfig b/.editorconfig index 033f8a6da..3b12e3337 100644 --- a/.editorconfig +++ b/.editorconfig @@ -9,3 +9,6 @@ trim_trailing_whitespace = true [*.yml] indent_size = 2 + +[*.feature] +indent_size = 2 From 77176985988130f3138420430bad0b49afdf8655 Mon Sep 17 00:00:00 2001 From: Carlos Granados Date: Sat, 9 Nov 2024 20:15:47 +0100 Subject: [PATCH 442/567] chore: fix some whitespace in newly added code --- features/bootstrap/FeatureContext.php | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/features/bootstrap/FeatureContext.php b/features/bootstrap/FeatureContext.php index 729756ecb..53933180f 100644 --- a/features/bootstrap/FeatureContext.php +++ b/features/bootstrap/FeatureContext.php @@ -389,7 +389,7 @@ private function getExpectedOutput(PyStringNode $expectedText) * * @Then /^it should (fail|pass)$/ * - * @param 'pass'|'fail' $success + * @param 'pass'|'fail' $success */ public function itShouldPassOrFail($success) { @@ -397,11 +397,11 @@ public function itShouldPassOrFail($success) 'fail' => 0 !== $this->getExitCode(), 'pass' => 0 === $this->getExitCode(), }; - + if ($is_correct) { return; } - + throw new UnexpectedValueException( 'Expected previous command to ' . strtoupper($success) . ' but got exit code ' . $this->getExitCode() . PHP_EOL . PHP_EOL From f14856b2c7a2c2a934e407269a70d2b4585400a2 Mon Sep 17 00:00:00 2001 From: Carlos Granados Date: Sat, 9 Nov 2024 20:13:03 +0100 Subject: [PATCH 443/567] feature: print failed hooks summary at the end of the pretty format run --- features/hooks.feature | 10 + features/hooks_failures.feature | 203 ++++++++++++++++++ .../Behat/Output/Node/Printer/ListPrinter.php | 24 ++- .../Pretty/PrettyStatisticsPrinter.php | 3 + .../Formatter/PrettyFormatterFactory.php | 4 + 5 files changed, 234 insertions(+), 10 deletions(-) diff --git a/features/hooks.feature b/features/hooks.feature index fbe94dd92..dfb9b5148 100644 --- a/features/hooks.feature +++ b/features/hooks.feature @@ -383,6 +383,11 @@ Feature: hooks │ └─ @AfterFeature # FeatureContext::doSomethingAfterFeature() + --- Failed hooks: + + BeforeScenario @exception "features/background.feature:4" # FeatureContext::beforeScenarioException() + BeforeScenario @exception "features/background.feature:11" # FeatureContext::beforeScenarioException() + --- Skipped scenarios: features/background.feature:4 @@ -546,6 +551,11 @@ Feature: hooks Scenario: # features/test.feature:13 Given passing step # FeatureContext::passingStep() + --- Failed hooks: + + BeforeStep passing step with failing hook "features/test.feature:10" # FeatureContext::failingBeforeStep() + BeforeScenario @failing-before-hook "features/test.feature:13" # FeatureContext::failingBeforeScenarioHook() + --- Skipped scenarios: features/test.feature:13 diff --git a/features/hooks_failures.feature b/features/hooks_failures.feature index 6334765e3..e72004501 100644 --- a/features/hooks_failures.feature +++ b/features/hooks_failures.feature @@ -12,6 +12,7 @@ Feature: Display hook failures location in progress printer When I have a simple step """ + #progress format Scenario: Handling of a error in beforeSuite hook Given a file named "features/bootstrap/FeatureContext.php" with: """ @@ -211,3 +212,205 @@ Feature: Display hook failures location in progress printer """ AfterStep "features/simple.feature:4" # FeatureContext::afterStepHook() """ + + #pretty format + Scenario: Handling of a error in beforeSuite hook + Given a file named "features/bootstrap/FeatureContext.php" with: + """ + writeln(sprintf('--- {+%s}%s{-%s}' . PHP_EOL, $style, $intro, $style)); foreach ($failedHookStats as $hookStat) { - $this->printHookStat($printer, $hookStat, $style); + $this->printHookStat($printer, $hookStat, $style, $simple); + } + if ($simple) { + $printer->writeln(); } } @@ -184,12 +189,8 @@ private function printStat(OutputPrinter $printer, $name, $path, $style, $stdOut /** * Prints hook stat. - * - * @param OutputPrinter $printer - * @param HookStat $hookStat - * @param string $style */ - private function printHookStat(OutputPrinter $printer, HookStat $hookStat, $style) + private function printHookStat(OutputPrinter $printer, HookStat $hookStat, string $style, bool $simple): void { $location = $this->getLocationFromScope($hookStat->getScope()); $printer->writeln( @@ -202,6 +203,9 @@ private function printHookStat(OutputPrinter $printer, HookStat $hookStat, $styl ) ); + if ($simple) { + return; + } $pad = function ($line) { return ' ' . $line; }; if (null !== $hookStat->getStdOut()) { diff --git a/src/Behat/Behat/Output/Node/Printer/Pretty/PrettyStatisticsPrinter.php b/src/Behat/Behat/Output/Node/Printer/Pretty/PrettyStatisticsPrinter.php index 23702c747..10ebf662c 100644 --- a/src/Behat/Behat/Output/Node/Printer/Pretty/PrettyStatisticsPrinter.php +++ b/src/Behat/Behat/Output/Node/Printer/Pretty/PrettyStatisticsPrinter.php @@ -52,6 +52,9 @@ public function printStatistics(Formatter $formatter, Statistics $statistics) { $printer = $formatter->getOutputPrinter(); + $hookStats = $statistics->getFailedHookStats(); + $this->listPrinter->printFailedHooksList($printer, 'failed_hooks_title', $hookStats, true); + $scenarioStats = $statistics->getSkippedScenarios(); $this->listPrinter->printScenariosList($printer, 'skipped_scenarios_title', TestResult::SKIPPED, $scenarioStats); diff --git a/src/Behat/Behat/Output/ServiceContainer/Formatter/PrettyFormatterFactory.php b/src/Behat/Behat/Output/ServiceContainer/Formatter/PrettyFormatterFactory.php index 7a1dd0e02..bc865b3d2 100644 --- a/src/Behat/Behat/Output/ServiceContainer/Formatter/PrettyFormatterFactory.php +++ b/src/Behat/Behat/Output/ServiceContainer/Formatter/PrettyFormatterFactory.php @@ -196,6 +196,10 @@ protected function loadFormatter(ContainerBuilder $container) new Reference('output.pretty.statistics'), new Reference(ExceptionExtension::PRESENTER_ID) )), + new Definition('Behat\Behat\Output\Node\EventListener\Statistics\HookStatsListener', array( + new Reference('output.pretty.statistics'), + new Reference(ExceptionExtension::PRESENTER_ID) + )), ) ) ) From d92f9d64f5e0f58de7bc3d0c60093c221c37f7b6 Mon Sep 17 00:00:00 2001 From: Carlos Granados Date: Wed, 13 Nov 2024 15:36:19 +0100 Subject: [PATCH 444/567] fix: show more meaningful message if no `output_path` is specified for the junit formatter --- .../Testwork/Output/Cli/OutputController.php | 2 +- .../Exception/MissingOutputPathException.php | 26 +++++++++++++++++++ .../Factory/FilesystemOutputFactory.php | 6 +++++ .../Output/Printer/JUnitOutputPrinter.php | 17 ++++++++---- 4 files changed, 45 insertions(+), 6 deletions(-) create mode 100644 src/Behat/Testwork/Output/Exception/MissingOutputPathException.php diff --git a/src/Behat/Testwork/Output/Cli/OutputController.php b/src/Behat/Testwork/Output/Cli/OutputController.php index bf8f94488..4130bcd8a 100644 --- a/src/Behat/Testwork/Output/Cli/OutputController.php +++ b/src/Behat/Testwork/Output/Cli/OutputController.php @@ -56,7 +56,7 @@ public function configure(Command $command) '--out', '-o', InputOption::VALUE_REQUIRED | InputOption::VALUE_IS_ARRAY, 'Write format output to a file/directory instead of' . PHP_EOL . 'STDOUT . You can also provide different' . PHP_EOL . - 'outputs to multiple formats.' + 'outputs to multiple formats. This option is mandatory for the junit formatter.' ) ->addOption( '--format-settings', null, InputOption::VALUE_REQUIRED | InputOption::VALUE_IS_ARRAY, diff --git a/src/Behat/Testwork/Output/Exception/MissingOutputPathException.php b/src/Behat/Testwork/Output/Exception/MissingOutputPathException.php new file mode 100644 index 000000000..9e3604f31 --- /dev/null +++ b/src/Behat/Testwork/Output/Exception/MissingOutputPathException.php @@ -0,0 +1,26 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Behat\Testwork\Output\Exception; + +use InvalidArgumentException; + +/** + * Represents an exception thrown because user did not provide an output path. + * + * @author Konstantin Kudryashov (output_path) + */ +class MissingOutputPathException extends InvalidArgumentException implements PrinterException +{ + public function __construct(string $message) + { + parent::__construct($message); + } +} diff --git a/src/Behat/Testwork/Output/Printer/Factory/FilesystemOutputFactory.php b/src/Behat/Testwork/Output/Printer/Factory/FilesystemOutputFactory.php index af982028c..142f3bcff 100644 --- a/src/Behat/Testwork/Output/Printer/Factory/FilesystemOutputFactory.php +++ b/src/Behat/Testwork/Output/Printer/Factory/FilesystemOutputFactory.php @@ -11,6 +11,7 @@ namespace Behat\Testwork\Output\Printer\Factory; use Behat\Testwork\Output\Exception\BadOutputPathException; +use Behat\Testwork\Output\Exception\MissingOutputPathException; use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Console\Output\StreamOutput; @@ -44,6 +45,11 @@ protected function configureOutputStream(OutputInterface $output) */ public function createOutput($stream = null) { + if ($this->getOutputPath() === null) { + throw new MissingOutputPathException( + 'The `output_path` option must be specified.', + ); + } if (is_file($this->getOutputPath())) { throw new BadOutputPathException( 'Directory expected for the `output_path` option, but a filename was given.', diff --git a/src/Behat/Testwork/Output/Printer/JUnitOutputPrinter.php b/src/Behat/Testwork/Output/Printer/JUnitOutputPrinter.php index 7f48964d4..833bf4b72 100644 --- a/src/Behat/Testwork/Output/Printer/JUnitOutputPrinter.php +++ b/src/Behat/Testwork/Output/Printer/JUnitOutputPrinter.php @@ -11,6 +11,7 @@ namespace Behat\Testwork\Output\Printer; use Behat\Testwork\Output\Exception\MissingExtensionException; +use Behat\Testwork\Output\Exception\MissingOutputPathException; use Behat\Testwork\Output\Printer\Factory\FilesystemOutputFactory; use Symfony\Component\Console\Output\OutputInterface; @@ -151,11 +152,17 @@ public function setFileName($fileName, $extension = 'xml') public function flush() { if($this->domDocument instanceof \DOMDocument){ - $this->getWritingStream()->write( - $this->domDocument->saveXML(null, LIBXML_NOEMPTYTAG), - false, - OutputInterface::OUTPUT_RAW - ); + try { + $this->getWritingStream()->write( + $this->domDocument->saveXML(null, LIBXML_NOEMPTYTAG), + false, + OutputInterface::OUTPUT_RAW + ); + } catch (MissingOutputPathException) { + throw new MissingOutputPathException( + 'The `output_path` option must be specified for the junit formatter.', + ); + } } parent::flush(); From 47f212b52954dd5c88323b0061534b8041b7cfaa Mon Sep 17 00:00:00 2001 From: Julien Deniau Date: Tue, 12 Nov 2024 22:34:29 +0000 Subject: [PATCH 445/567] Use diff to help investigating wrong status code or unexpected output. --- composer.json | 5 +- features/bootstrap/FeatureContext.php | 77 ++++++++++++++++++++------- 2 files changed, 62 insertions(+), 20 deletions(-) diff --git a/composer.json b/composer.json index cc77c4397..e3b34b9b9 100644 --- a/composer.json +++ b/composer.json @@ -29,10 +29,11 @@ }, "require-dev": { + "herrera-io/box": "~1.6.1", + "phpunit/phpunit": "^9.6", + "sebastian/diff": "^4.0", "symfony/polyfill-php84": "^1.31", "symfony/process": "^5.4 || ^6.4 || ^7.0", - "phpunit/phpunit": "^9.6", - "herrera-io/box": "~1.6.1", "vimeo/psalm": "^4.8" }, diff --git a/features/bootstrap/FeatureContext.php b/features/bootstrap/FeatureContext.php index 53933180f..1dd889045 100644 --- a/features/bootstrap/FeatureContext.php +++ b/features/bootstrap/FeatureContext.php @@ -14,6 +14,8 @@ use PHPUnit\Framework\Assert; use Symfony\Component\Process\PhpExecutableFinder; use Symfony\Component\Process\Process; +use SebastianBergmann\Diff\Differ; +use SebastianBergmann\Diff\Output\DiffOnlyOutputBuilder; /** * Behat test suite context. @@ -267,8 +269,30 @@ public function iRunBehatInDebugMode() */ public function itShouldPassOrFailWith($success, PyStringNode $text) { - $this->theOutputShouldContain($text); - $this->itShouldPassOrFail($success); + $isCorrect = $this->exitCodeIsCorrect($success); + + $outputMessage = []; + $hasError = false; + + if (!$isCorrect) { + $hasError = true; + $outputMessage[] = 'Expected previous command to ' . strtoupper($success) . ' but got exit code ' . $this->getExitCode(); + } else { + $outputMessage[] = 'Command did ' . strtoupper($success) . ' as expected.'; + } + + if (!str_contains($this->getOutput(), $this->getExpectedOutput($text))) { + $hasError = true; + $outputMessage[] = $this->getOutputDiff($text); + } else { + $outputMessage[] = 'Output is as expected.'; + } + + if ($hasError) { + throw new UnexpectedValueException( + implode(PHP_EOL . PHP_EOL, $outputMessage) + ); + } } /** @@ -343,7 +367,13 @@ public function fileXmlShouldBeLike($path, PyStringNode $text) */ public function theOutputShouldContain(PyStringNode $text) { - Assert::assertStringContainsString($this->getExpectedOutput($text), $this->getOutput()); + if (str_contains($this->getOutput(), $this->getExpectedOutput($text))) { + return; + } + + throw new UnexpectedValueException( + $this->getOutputDiff($text) + ); } private function getExpectedOutput(PyStringNode $expectedText) @@ -393,21 +423,14 @@ private function getExpectedOutput(PyStringNode $expectedText) */ public function itShouldPassOrFail($success) { - $is_correct = match($success) { - 'fail' => 0 !== $this->getExitCode(), - 'pass' => 0 === $this->getExitCode(), - }; - - if ($is_correct) { - return; - } - - throw new UnexpectedValueException( - 'Expected previous command to ' . strtoupper($success) . ' but got exit code ' . $this->getExitCode() . PHP_EOL - . PHP_EOL - . '##### Actual output #####' . PHP_EOL - . '> ' . str_replace(PHP_EOL, PHP_EOL . '> ', $this->getOutput()) . PHP_EOL - . '##### End of output #####' + $isCorrect = $this->exitCodeIsCorrect($success); + + if ($isCorrect) { + return; + } + + throw new UnexpectedValueException( + 'Expected previous command to ' . strtoupper($success) . ' but got exit code ' . $this->getExitCode() ); } @@ -478,6 +501,24 @@ private function moveToNewPath($path) $this->workingDir = $newWorkingDir; } + + /** + * @param 'fail'|'pass' $success + */ + private function exitCodeIsCorrect(string $success): bool + { + return match($success) { + 'fail' => 0 !== $this->getExitCode(), + 'pass' => 0 === $this->getExitCode(), + }; + } + + private function getOutputDiff(PyStringNode $expectedText): string + { + $differ = new Differ(new DiffOnlyOutputBuilder()); + + return $differ->diff($this->getExpectedOutput($expectedText), $this->getOutput()); + } private static function clearDirectory($path) { From 010188598979ebfe1959384da108fb9bf21cdadf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lo=C3=AFc=20Fr=C3=A9mont?= Date: Tue, 19 Nov 2024 09:45:36 +0100 Subject: [PATCH 446/567] Add PHP config --- behat.php.dist | 13 +++++ composer.json | 1 + features/config.feature | 50 ++++++++++++++++++- src/Behat/Behat/ApplicationFactory.php | 4 ++ src/Behat/Config/Config.php | 18 +++++++ .../Configuration/ConfigurationLoader.php | 16 +++++- tests/Behat/Tests/Config/ConfigTest.php | 33 ++++++++++++ 7 files changed, 133 insertions(+), 2 deletions(-) create mode 100644 behat.php.dist create mode 100644 src/Behat/Config/Config.php create mode 100644 tests/Behat/Tests/Config/ConfigTest.php diff --git a/behat.php.dist b/behat.php.dist new file mode 100644 index 000000000..a206b6891 --- /dev/null +++ b/behat.php.dist @@ -0,0 +1,13 @@ + [ + 'gherkin' => [ + 'filters' => [ + 'tags' => '~@php8' + ], + ], + ], +]); + +return $config; diff --git a/composer.json b/composer.json index e3b34b9b9..540059a78 100644 --- a/composer.json +++ b/composer.json @@ -44,6 +44,7 @@ "autoload": { "psr-4": { "Behat\\Behat\\": "src/Behat/Behat/", + "Behat\\Config\\": "src/Behat/Config/", "Behat\\Testwork\\": "src/Behat/Testwork/", "Behat\\Step\\": "src/Behat/Step/", "Behat\\Hook\\": "src/Behat/Hook/" diff --git a/features/config.feature b/features/config.feature index 53b84b09f..3705fff97 100644 --- a/features/config.feature +++ b/features/config.feature @@ -92,6 +92,43 @@ Feature: Config The requested config file does not exist """ + Scenario: PHP configuration file + Given a file named "behat.php" with: + """ + settings; + } +} diff --git a/src/Behat/Testwork/ServiceContainer/Configuration/ConfigurationLoader.php b/src/Behat/Testwork/ServiceContainer/Configuration/ConfigurationLoader.php index 92f8dd7b1..eb67db5b4 100644 --- a/src/Behat/Testwork/ServiceContainer/Configuration/ConfigurationLoader.php +++ b/src/Behat/Testwork/ServiceContainer/Configuration/ConfigurationLoader.php @@ -10,6 +10,7 @@ namespace Behat\Testwork\ServiceContainer\Configuration; +use Behat\Config\Config; use Behat\Testwork\ServiceContainer\Exception\ConfigurationLoadingException; use Symfony\Component\Yaml\Yaml; @@ -195,7 +196,20 @@ protected function loadFileConfiguration($configPath, $profile) } $basePath = rtrim(dirname($configPath), DIRECTORY_SEPARATOR); - $config = (array) Yaml::parse(file_get_contents($configPath)); + + if ( + \str_ends_with($configPath, '.php') + || \str_ends_with($configPath, '.php.dist') + ) { + $phpConfig = require $configPath; + if (!$phpConfig instanceof Config) { + throw new ConfigurationLoadingException(sprintf('Configuration file `%s` must be an instance of `%s`.', $configPath, Config::class)); + } + + $config = $phpConfig->toArray(); + } else { + $config = (array) Yaml::parse(file_get_contents($configPath)); + } return $this->loadConfigs($basePath, $config, $profile); } diff --git a/tests/Behat/Tests/Config/ConfigTest.php b/tests/Behat/Tests/Config/ConfigTest.php new file mode 100644 index 000000000..4df3737a7 --- /dev/null +++ b/tests/Behat/Tests/Config/ConfigTest.php @@ -0,0 +1,33 @@ +assertIsArray($config->toArray()); + } + + public function testItReturnsSettings(): void + { + $settings = [ + 'default' => [ + 'gherkin' => [ + 'filters' => [ + 'tags' => '~@php8' + ], + ], + ], + ]; + + $config = new Config($settings); + + $this->assertEquals($settings, $config->toArray()); + } +} From 9f26bd3d5777ec6e2e78e6c8ce8f103940ed5871 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lo=C3=AFc=20Fr=C3=A9mont?= Date: Tue, 19 Nov 2024 11:38:59 +0100 Subject: [PATCH 447/567] Apply changes from code review --- behat.php.dist | 4 +++- features/config.feature | 6 ++++-- 2 files changed, 7 insertions(+), 3 deletions(-) diff --git a/behat.php.dist b/behat.php.dist index a206b6891..d0b583adc 100644 --- a/behat.php.dist +++ b/behat.php.dist @@ -1,6 +1,8 @@ [ 'gherkin' => [ 'filters' => [ diff --git a/features/config.feature b/features/config.feature index 3705fff97..4bacb1599 100644 --- a/features/config.feature +++ b/features/config.feature @@ -97,7 +97,9 @@ Feature: Config """ Date: Tue, 19 Nov 2024 11:49:41 +0100 Subject: [PATCH 448/567] Test alternative PHP configuration file --- features/config.feature | 39 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) diff --git a/features/config.feature b/features/config.feature index 4bacb1599..99d1a2b22 100644 --- a/features/config.feature +++ b/features/config.feature @@ -131,6 +131,45 @@ Feature: Config When this scenario executes """ + Scenario: Alternative PHP configuration file + Given a file named "alternative-behat.php" with: + """ + Date: Tue, 19 Nov 2024 12:06:45 +0100 Subject: [PATCH 449/567] Proposal with custom config object --- features/config.feature | 47 +++++++++++++++++++ src/Behat/Config/Config.php | 2 +- src/Behat/Config/ConfigInterface.php | 10 ++++ .../Configuration/ConfigurationLoader.php | 5 +- 4 files changed, 61 insertions(+), 3 deletions(-) create mode 100644 src/Behat/Config/ConfigInterface.php diff --git a/features/config.feature b/features/config.feature index 99d1a2b22..824da4410 100644 --- a/features/config.feature +++ b/features/config.feature @@ -170,6 +170,53 @@ Feature: Config When this scenario executes """ + Scenario: Custom PHP configuration object + Given a file named "custom-config-object.php" with: + """ + toArray(); From eb10b59e52df4198f7e4307bd481a74ca9f785c2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lo=C3=AFc=20Fr=C3=A9mont?= Date: Tue, 19 Nov 2024 12:11:38 +0100 Subject: [PATCH 450/567] Add support for .dist.php configuration file --- src/Behat/Behat/ApplicationFactory.php | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/Behat/Behat/ApplicationFactory.php b/src/Behat/Behat/ApplicationFactory.php index 275c0c3d8..c5e3f71b0 100644 --- a/src/Behat/Behat/ApplicationFactory.php +++ b/src/Behat/Behat/ApplicationFactory.php @@ -128,6 +128,7 @@ protected function getConfigPath() $cwd . 'behat.dist.yml', $cwd . 'behat.php', $cwd . 'behat.php.dist', + $cwd . 'behat.dist.php', $configDir . 'behat.yaml', $configDir . 'behat.yml', $configDir . 'behat.yaml.dist', @@ -136,6 +137,7 @@ protected function getConfigPath() $configDir . 'behat.dist.yml', $configDir . 'behat.php', $configDir . 'behat.php.dist', + $configDir . 'behat.dist.php', ); foreach ($paths as $path) { From 0875046eebc522fb505f1d44a346693b3038593f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lo=C3=AFc=20Fr=C3=A9mont?= Date: Tue, 19 Nov 2024 14:51:56 +0100 Subject: [PATCH 451/567] Custom config to check the custom PHP configuration object --- features/config.feature | 19 ++++++++++++++++--- 1 file changed, 16 insertions(+), 3 deletions(-) diff --git a/features/config.feature b/features/config.feature index 824da4410..f530631b0 100644 --- a/features/config.feature +++ b/features/config.feature @@ -181,7 +181,15 @@ Feature: Config { public function toArray(): array { - return []; + return [ + 'default' => [ + 'gherkin' => [ + 'filters' => [ + 'tags' => '@second' + ], + ], + ], + ]; } } @@ -201,8 +209,13 @@ Feature: Config And a file named "features/config.feature" with: """ Feature: + @first Scenario: - When this scenario executes + When this first scenario executes + + @second + Scenario: + When this second scenario executes """ When I run "behat -f progress --no-colors --append-snippets --config=custom-config-object.php" Then it should pass with: @@ -214,7 +227,7 @@ Feature: Config --- Use --snippets-for CLI option to generate snippets for following default suite steps: - When this scenario executes + When this second scenario executes """ Scenario: Prioritize *.yaml config file From 5fa5aabc265a69cffc9b798b54bb8baeb43d445a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lo=C3=AFc=20Fr=C3=A9mont?= Date: Tue, 19 Nov 2024 15:01:58 +0100 Subject: [PATCH 452/567] Remove behat.php.dist support --- src/Behat/Behat/ApplicationFactory.php | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/Behat/Behat/ApplicationFactory.php b/src/Behat/Behat/ApplicationFactory.php index c5e3f71b0..8ea1f363c 100644 --- a/src/Behat/Behat/ApplicationFactory.php +++ b/src/Behat/Behat/ApplicationFactory.php @@ -127,7 +127,6 @@ protected function getConfigPath() $cwd . 'behat.dist.yaml', $cwd . 'behat.dist.yml', $cwd . 'behat.php', - $cwd . 'behat.php.dist', $cwd . 'behat.dist.php', $configDir . 'behat.yaml', $configDir . 'behat.yml', @@ -136,7 +135,6 @@ protected function getConfigPath() $configDir . 'behat.dist.yaml', $configDir . 'behat.dist.yml', $configDir . 'behat.php', - $configDir . 'behat.php.dist', $configDir . 'behat.dist.php', ); From 5c044f5985ed2e200b4810e864ee7448d13154e0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lo=C3=AFc=20Fr=C3=A9mont?= Date: Tue, 19 Nov 2024 17:38:44 +0100 Subject: [PATCH 453/567] Remove main behat.php.dist file --- behat.php.dist | 15 --------------- 1 file changed, 15 deletions(-) delete mode 100644 behat.php.dist diff --git a/behat.php.dist b/behat.php.dist deleted file mode 100644 index d0b583adc..000000000 --- a/behat.php.dist +++ /dev/null @@ -1,15 +0,0 @@ - [ - 'gherkin' => [ - 'filters' => [ - 'tags' => '~@php8' - ], - ], - ], -]); - -return $config; From 9aa9699f38d795d2e5575ab9a2f277e975c4ef57 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lo=C3=AFc=20Fr=C3=A9mont?= Date: Fri, 22 Nov 2024 14:39:00 +0100 Subject: [PATCH 454/567] Update src/Behat/Testwork/ServiceContainer/Configuration/ConfigurationLoader.php Co-authored-by: Andrew Coulton --- .../ServiceContainer/Configuration/ConfigurationLoader.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Behat/Testwork/ServiceContainer/Configuration/ConfigurationLoader.php b/src/Behat/Testwork/ServiceContainer/Configuration/ConfigurationLoader.php index a2fe5006e..55ae06628 100644 --- a/src/Behat/Testwork/ServiceContainer/Configuration/ConfigurationLoader.php +++ b/src/Behat/Testwork/ServiceContainer/Configuration/ConfigurationLoader.php @@ -204,7 +204,7 @@ protected function loadFileConfiguration($configPath, $profile) ) { $phpConfig = require $configPath; if (!$phpConfig instanceof ConfigInterface) { - throw new ConfigurationLoadingException(sprintf('Configuration file `%s` must implements `%s`.', $configPath, ConfigInterface::class)); + throw new ConfigurationLoadingException(sprintf('Configuration file `%s` must return an instance of `%s`.', $configPath, ConfigInterface::class)); } $config = $phpConfig->toArray(); From 43af9bba2b1b7c31035cf3ea07acedbd55e6c771 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lo=C3=AFc=20Fr=C3=A9mont?= Date: Fri, 22 Nov 2024 14:39:20 +0100 Subject: [PATCH 455/567] Apply suggestions --- features/config.feature | 17 +++++++---------- .../Configuration/ConfigurationLoader.php | 7 ++++--- 2 files changed, 11 insertions(+), 13 deletions(-) diff --git a/features/config.feature b/features/config.feature index f530631b0..db3727fcc 100644 --- a/features/config.feature +++ b/features/config.feature @@ -183,11 +183,7 @@ Feature: Config { return [ 'default' => [ - 'gherkin' => [ - 'filters' => [ - 'tags' => '@second' - ], - ], + 'testers' => ['strict' => true], ], ]; } @@ -217,16 +213,17 @@ Feature: Config Scenario: When this second scenario executes """ - When I run "behat -f progress --no-colors --append-snippets --config=custom-config-object.php" - Then it should pass with: + When I run "behat -f progress --no-colors -n --config=custom-config-object.php" + Then it should fail with: """ - U + UU - 1 scenario (1 undefined) - 1 step (1 undefined) + 2 scenarios (2 undefined) + 2 steps (2 undefined) --- Use --snippets-for CLI option to generate snippets for following default suite steps: + When this first scenario executes When this second scenario executes """ diff --git a/src/Behat/Testwork/ServiceContainer/Configuration/ConfigurationLoader.php b/src/Behat/Testwork/ServiceContainer/Configuration/ConfigurationLoader.php index 55ae06628..4881754f1 100644 --- a/src/Behat/Testwork/ServiceContainer/Configuration/ConfigurationLoader.php +++ b/src/Behat/Testwork/ServiceContainer/Configuration/ConfigurationLoader.php @@ -10,11 +10,12 @@ namespace Behat\Testwork\ServiceContainer\Configuration; -use Behat\Config\Config; use Behat\Config\ConfigInterface; use Behat\Testwork\ServiceContainer\Exception\ConfigurationLoadingException; use Symfony\Component\Yaml\Yaml; +use function str_ends_with; + /** * Loads configuration from different sources. * @@ -199,8 +200,8 @@ protected function loadFileConfiguration($configPath, $profile) $basePath = rtrim(dirname($configPath), DIRECTORY_SEPARATOR); if ( - \str_ends_with($configPath, '.php') - || \str_ends_with($configPath, '.php.dist') + str_ends_with($configPath, '.php') + || str_ends_with($configPath, '.php.dist') ) { $phpConfig = require $configPath; if (!$phpConfig instanceof ConfigInterface) { From fb01be1c7228a9db1a4567ea5e139b711d0159a9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lo=C3=AFc=20Fr=C3=A9mont?= Date: Fri, 22 Nov 2024 14:40:44 +0100 Subject: [PATCH 456/567] Apply suggestions from code review Co-authored-by: Andrew Coulton --- features/config.feature | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/features/config.feature b/features/config.feature index db3727fcc..a0b7e468f 100644 --- a/features/config.feature +++ b/features/config.feature @@ -251,7 +251,7 @@ Feature: Config Scenario: Load custom php config instead of distribution Given a file named "behat.php" - Given a file named "behat.php.dist" + Given a file named "behat.dist.php" Given a some feature context And a some feature scenarios When I run behat in debug mode From 057f1b1b1f1e5d04cb5e52dbbb7a019e8538c319 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lo=C3=AFc=20Fr=C3=A9mont?= Date: Fri, 22 Nov 2024 14:49:00 +0100 Subject: [PATCH 457/567] Apply other suggestions --- features/config.feature | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/features/config.feature b/features/config.feature index a0b7e468f..4d0c0b68c 100644 --- a/features/config.feature +++ b/features/config.feature @@ -99,7 +99,7 @@ Feature: Config use Behat\Config\Config; - return new Config(); + return new Config(['default' => ['formatters' => ['progress' => true]]]); """ And a file named "features/bootstrap/FeatureContext.php" with: @@ -118,7 +118,7 @@ Feature: Config Scenario: When this scenario executes """ - When I run "behat -f progress --no-colors --append-snippets" + When I run "behat --no-colors --append-snippets" Then it should pass with: """ U @@ -138,7 +138,7 @@ Feature: Config use Behat\Config\Config; - return new Config(); + return new Config(['default' => ['formatters' => ['progress' => true]]]); """ And a file named "features/bootstrap/FeatureContext.php" with: @@ -157,7 +157,7 @@ Feature: Config Scenario: When this scenario executes """ - When I run "behat -f progress --no-colors --append-snippets --config=alternative-behat.php" + When I run "behat --no-colors --append-snippets --config=alternative-behat.php" Then it should pass with: """ U From 27186b1ebee3327894f56a3da8c561c40f711a77 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lo=C3=AFc=20Fr=C3=A9mont?= Date: Fri, 22 Nov 2024 18:40:40 +0100 Subject: [PATCH 458/567] Remove php.dist support on Configuration Loader --- .../ServiceContainer/Configuration/ConfigurationLoader.php | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/src/Behat/Testwork/ServiceContainer/Configuration/ConfigurationLoader.php b/src/Behat/Testwork/ServiceContainer/Configuration/ConfigurationLoader.php index 4881754f1..0ab1a7f6b 100644 --- a/src/Behat/Testwork/ServiceContainer/Configuration/ConfigurationLoader.php +++ b/src/Behat/Testwork/ServiceContainer/Configuration/ConfigurationLoader.php @@ -199,10 +199,7 @@ protected function loadFileConfiguration($configPath, $profile) $basePath = rtrim(dirname($configPath), DIRECTORY_SEPARATOR); - if ( - str_ends_with($configPath, '.php') - || str_ends_with($configPath, '.php.dist') - ) { + if (str_ends_with($configPath, '.php')) { $phpConfig = require $configPath; if (!$phpConfig instanceof ConfigInterface) { throw new ConfigurationLoadingException(sprintf('Configuration file `%s` must return an instance of `%s`.', $configPath, ConfigInterface::class)); From 8b154c906e5b2a4841096f0f3219168c0dac18f2 Mon Sep 17 00:00:00 2001 From: Carlos Granados Date: Tue, 19 Nov 2024 17:34:23 +0100 Subject: [PATCH 459/567] fix: Print `` nodes for all hook failures in the junit output --- features/hooks_failures.feature | 320 ++++++++++++++++++ features/junit_format.feature | 12 +- .../JUnit/JUnitFeatureElementListener.php | 108 +++--- .../Node/Printer/JUnit/JUnitSetupPrinter.php | 6 +- .../Formatter/JUnitFormatterFactory.php | 2 +- 5 files changed, 396 insertions(+), 52 deletions(-) diff --git a/features/hooks_failures.feature b/features/hooks_failures.feature index e72004501..e59415692 100644 --- a/features/hooks_failures.feature +++ b/features/hooks_failures.feature @@ -414,3 +414,323 @@ Feature: Display hook failures location in progress printer AfterStep "features/simple.feature:4" # FeatureContext::afterStepHook() """ + #junit format + Scenario: Handling of a error in beforeSuite hook + Given a file named "features/bootstrap/FeatureContext.php" with: + """ + + + """ + And the file "junit/default.xml" should be a valid document according to "junit.xsd" + + Scenario: Handling of a error in afterSuite hook + Given a file named "features/bootstrap/FeatureContext.php" with: + """ + + + """ + And the file "junit/default.xml" should be a valid document according to "junit.xsd" + + Scenario: Handling of a error in beforeFeature hook + Given a file named "features/bootstrap/FeatureContext.php" with: + """ + + + """ + And the file "junit/default.xml" should be a valid document according to "junit.xsd" + + Scenario: Handling of a error in afterFeature hook + Given a file named "features/bootstrap/FeatureContext.php" with: + """ + + + """ + And the file "junit/default.xml" should be a valid document according to "junit.xsd" + + Scenario: Handling of a error in beforeScenario hook + Given a file named "features/bootstrap/FeatureContext.php" with: + """ + + + """ + And the file "junit/default.xml" should be a valid document according to "junit.xsd" + + Scenario: Handling of a error in afterScenario hook + Given a file named "features/bootstrap/FeatureContext.php" with: + """ + + + """ + And the file "junit/default.xml" should be a valid document according to "junit.xsd" + + Scenario: Handling of a error in beforeStep hook + Given a file named "features/bootstrap/FeatureContext.php" with: + """ + + + """ + And the file "junit/default.xml" should be a valid document according to "junit.xsd" + + Scenario: Handling of a error in afterStep hook + Given a file named "features/bootstrap/FeatureContext.php" with: + """ + + + """ + And the file "junit/default.xml" should be a valid document according to "junit.xsd" diff --git a/features/junit_format.feature b/features/junit_format.feature index 2943fb60f..daa8d82ac 100644 --- a/features/junit_format.feature +++ b/features/junit_format.feature @@ -456,8 +456,12 @@ """ @@ -649,7 +653,7 @@ @@ -705,7 +709,7 @@ diff --git a/src/Behat/Behat/Output/Node/EventListener/JUnit/JUnitFeatureElementListener.php b/src/Behat/Behat/Output/Node/EventListener/JUnit/JUnitFeatureElementListener.php index febd11533..a9a85e4c7 100644 --- a/src/Behat/Behat/Output/Node/EventListener/JUnit/JUnitFeatureElementListener.php +++ b/src/Behat/Behat/Output/Node/EventListener/JUnit/JUnitFeatureElementListener.php @@ -10,19 +10,20 @@ namespace Behat\Behat\Output\Node\EventListener\JUnit; +use Behat\Behat\EventDispatcher\Event\AfterFeatureSetup; use Behat\Behat\EventDispatcher\Event\AfterFeatureTested; +use Behat\Behat\EventDispatcher\Event\AfterScenarioSetup; use Behat\Behat\EventDispatcher\Event\AfterScenarioTested; use Behat\Behat\EventDispatcher\Event\AfterStepSetup; use Behat\Behat\EventDispatcher\Event\AfterStepTested; use Behat\Behat\EventDispatcher\Event\BeforeFeatureTested; -use Behat\Behat\EventDispatcher\Event\ScenarioTested; use Behat\Behat\Output\Node\Printer\FeaturePrinter; use Behat\Behat\Output\Node\Printer\JUnit\JUnitScenarioPrinter; use Behat\Behat\Output\Node\Printer\SetupPrinter; use Behat\Behat\Output\Node\Printer\StepPrinter; -use Behat\Gherkin\Node\FeatureNode; use Behat\Testwork\Event\Event; -use Behat\Testwork\EventDispatcher\Event\AfterSetup; +use Behat\Testwork\EventDispatcher\Event\AfterSuiteSetup; +use Behat\Testwork\EventDispatcher\Event\AfterSuiteTested; use Behat\Testwork\Output\Formatter; use Behat\Testwork\Output\Node\EventListener\EventListener; @@ -33,31 +34,22 @@ */ final class JUnitFeatureElementListener implements EventListener { - /** - * @var FeaturePrinter - */ - private $featurePrinter; - /** - * @var JUnitScenarioPrinter - */ - private $scenarioPrinter; - /** - * @var StepPrinter - */ - private $stepPrinter; - /** - * @var SetupPrinter - */ - private $setupPrinter; /** * @var AfterStepTested[] */ private $afterStepTestedEvents = array(); + /** * @var AfterStepSetup[] */ private $afterStepSetupEvents = array(); + private ?AfterSuiteSetup $afterSuiteSetup = null; + + private ?AfterFeatureSetup $afterFeatureSetup = null; + + private AfterScenarioSetup $afterScenarioSetup; + /** * Initializes listener. * @@ -66,15 +58,12 @@ final class JUnitFeatureElementListener implements EventListener * @param StepPrinter $stepPrinter * @param SetupPrinter $setupPrinter */ - public function __construct(FeaturePrinter $featurePrinter, - JUnitScenarioPrinter $scenarioPrinter, - StepPrinter $stepPrinter, - SetupPrinter $setupPrinter) - { - $this->featurePrinter = $featurePrinter; - $this->scenarioPrinter = $scenarioPrinter; - $this->stepPrinter = $stepPrinter; - $this->setupPrinter = $setupPrinter; + public function __construct( + private FeaturePrinter $featurePrinter, + private JUnitScenarioPrinter $scenarioPrinter, + private StepPrinter $stepPrinter, + private SetupPrinter $setupPrinter + ) { } /** @@ -82,32 +71,52 @@ public function __construct(FeaturePrinter $featurePrinter, */ public function listenEvent(Formatter $formatter, Event $event, $eventName) { + $this->printSuiteSetupEvent($formatter, $event); $this->printFeatureOnBeforeEvent($formatter, $event); $this->captureStepEvent($event); $this->printScenarioEvent($formatter, $event); $this->printFeatureOnAfterEvent($formatter, $event); + $this->printSuiteTeardownEvent($formatter, $event); + } + + /** + * Prints any failures in suite setup. + */ + private function printSuiteSetupEvent(Formatter $formatter, Event $event): void + { + if ($event instanceof AfterSuiteSetup) { + $this->afterSuiteSetup = $event; + } + } + + /** + * Prints any failures in suite teardown. + */ + private function printSuiteTeardownEvent(Formatter $formatter, Event $event): void + { + if ($event instanceof AfterSuiteTested) { + $this->setupPrinter->printTeardown($formatter, $event->getTeardown()); + } } /** * Prints the header for the feature. - * - * @param Formatter $formatter - * @param Event $event */ - private function printFeatureOnBeforeEvent(Formatter $formatter, Event $event) + private function printFeatureOnBeforeEvent(Formatter $formatter, Event $event): void { - if (!$event instanceof BeforeFeatureTested) { + if ($event instanceof BeforeFeatureTested) { + $this->featurePrinter->printHeader($formatter, $event->getFeature()); return; } - $this->featurePrinter->printHeader($formatter, $event->getFeature()); + if ($event instanceof AfterFeatureSetup) { + $this->afterFeatureSetup = $event; + } } /** * Captures step tested event. - * - * @param Event $event */ - private function captureStepEvent(Event $event) + private function captureStepEvent(Event $event): void { if ($event instanceof AfterStepTested) { $this->afterStepTestedEvents[$event->getStep()->getLine()] = $event; @@ -119,12 +128,13 @@ private function captureStepEvent(Event $event) /** * Prints the scenario tested event. - * - * @param Formatter $formatter - * @param Event $event */ - private function printScenarioEvent(Formatter $formatter, Event $event) + private function printScenarioEvent(Formatter $formatter, Event $event): void { + if ($event instanceof AfterScenarioSetup) { + $this->afterScenarioSetup = $event; + return; + } if (!$event instanceof AfterScenarioTested) { return; } @@ -137,6 +147,16 @@ private function printScenarioEvent(Formatter $formatter, Event $event) $event->getFeature()->getFile() ); + if ($this->afterSuiteSetup !== null) { + $this->setupPrinter->printSetup($formatter, $this->afterSuiteSetup->getSetup()); + $this->afterSuiteSetup = null; + } + if ($this->afterFeatureSetup !== null) { + $this->setupPrinter->printSetup($formatter, $this->afterFeatureSetup->getSetup()); + $this->afterFeatureSetup = null; + } + $this->setupPrinter->printSetup($formatter, $this->afterScenarioSetup->getSetup()); + foreach ($this->afterStepSetupEvents as $afterStepSetup) { $this->setupPrinter->printSetup($formatter, $afterStepSetup->getSetup()); } @@ -145,21 +165,21 @@ private function printScenarioEvent(Formatter $formatter, Event $event) $this->setupPrinter->printTeardown($formatter, $afterStepTested->getTeardown()); } + $this->setupPrinter->printTeardown($formatter, $afterScenarioTested->getTeardown()); + $this->afterStepTestedEvents = array(); $this->afterStepSetupEvents = array(); } /** * Prints the feature on AFTER event. - * - * @param Formatter $formatter - * @param Event $event */ private function printFeatureOnAfterEvent(Formatter $formatter, Event $event) { if (!$event instanceof AfterFeatureTested) { return; } + $this->setupPrinter->printTeardown($formatter, $event->getTeardown()); $this->featurePrinter->printFooter($formatter, $event->getTestResult()); } } diff --git a/src/Behat/Behat/Output/Node/Printer/JUnit/JUnitSetupPrinter.php b/src/Behat/Behat/Output/Node/Printer/JUnit/JUnitSetupPrinter.php index 401c7e911..31fcc40d3 100644 --- a/src/Behat/Behat/Output/Node/Printer/JUnit/JUnitSetupPrinter.php +++ b/src/Behat/Behat/Output/Node/Printer/JUnit/JUnitSetupPrinter.php @@ -68,11 +68,11 @@ private function handleHookCalls(Formatter $formatter, CallResults $results, $me /** @var JUnitOutputPrinter $outputPrinter */ $outputPrinter = $formatter->getOutputPrinter(); - $message = ''; + $message = $call->getCallee()->getName(); if ($scope instanceof StepScope) { - $message .= $scope->getStep()->getKeyword() . ' ' . $scope->getStep()->getText() . ': '; + $message .= ': ' . $scope->getStep()->getKeyword() . ' ' . $scope->getStep()->getText(); } - $message .= $this->exceptionPresenter->presentException($hookCallResult->getException()); + $message .= ': ' . $this->exceptionPresenter->presentException($hookCallResult->getException()); $attributes = array( 'message' => $message, diff --git a/src/Behat/Behat/Output/ServiceContainer/Formatter/JUnitFormatterFactory.php b/src/Behat/Behat/Output/ServiceContainer/Formatter/JUnitFormatterFactory.php index c28d2cda5..5726c972b 100644 --- a/src/Behat/Behat/Output/ServiceContainer/Formatter/JUnitFormatterFactory.php +++ b/src/Behat/Behat/Output/ServiceContainer/Formatter/JUnitFormatterFactory.php @@ -120,13 +120,13 @@ private function loadRootNodeListener(ContainerBuilder $container) $definition = new Definition('Behat\Testwork\Output\Node\EventListener\ChainEventListener', array( array( new Reference('output.node.listener.junit.duration'), - new Reference('output.node.listener.junit.outline'), new Definition('Behat\Behat\Output\Node\EventListener\JUnit\JUnitFeatureElementListener', array( new Reference('output.node.printer.junit.feature'), new Reference('output.node.printer.junit.scenario'), new Reference('output.node.printer.junit.step'), new Reference('output.node.printer.junit.setup'), )), + new Reference('output.node.listener.junit.outline'), ), )); $container->setDefinition(self::ROOT_LISTENER_ID, $definition); From b5943bd328077007ba54c3619a15e38fd8fa9284 Mon Sep 17 00:00:00 2001 From: Carlos Granados + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - - + + + + + + - + - + Date: Fri, 22 Nov 2024 18:58:32 +0100 Subject: [PATCH 460/567] Split hook tests in three feature files --- features/hooks_failures.feature | 736 ------------------ features/hooks_failures_junit.feature | 406 ++++++++++ features/hooks_failures_pretty.feature | 213 +++++ features/hooks_failures_progress.feature | 213 +++++ .../JUnit/JUnitFeatureElementListener.php | 10 +- 5 files changed, 839 insertions(+), 739 deletions(-) delete mode 100644 features/hooks_failures.feature create mode 100644 features/hooks_failures_junit.feature create mode 100644 features/hooks_failures_pretty.feature create mode 100644 features/hooks_failures_progress.feature diff --git a/features/hooks_failures.feature b/features/hooks_failures.feature deleted file mode 100644 index e59415692..000000000 --- a/features/hooks_failures.feature +++ /dev/null @@ -1,736 +0,0 @@ -Feature: Display hook failures location in progress printer - In order to be able to locate the code that generated a failure - As a feature developer using the progress printer - When a hook throws an error I want to see the related item where the code failed - - Background: - Given a file named "features/simple.feature" with: - """ - Feature: Simple feature - - Scenario: Simple scenario - When I have a simple step - """ - - #progress format - Scenario: Handling of a error in beforeSuite hook - Given a file named "features/bootstrap/FeatureContext.php" with: - """ - - - """ - And the file "junit/default.xml" should be a valid document according to "junit.xsd" - - Scenario: Handling of a error in afterSuite hook - Given a file named "features/bootstrap/FeatureContext.php" with: - """ - - - """ - And the file "junit/default.xml" should be a valid document according to "junit.xsd" - - Scenario: Handling of a error in beforeFeature hook - Given a file named "features/bootstrap/FeatureContext.php" with: - """ - - - """ - And the file "junit/default.xml" should be a valid document according to "junit.xsd" - - Scenario: Handling of a error in afterFeature hook - Given a file named "features/bootstrap/FeatureContext.php" with: - """ - - - """ - And the file "junit/default.xml" should be a valid document according to "junit.xsd" - - Scenario: Handling of a error in beforeScenario hook - Given a file named "features/bootstrap/FeatureContext.php" with: - """ - - - """ - And the file "junit/default.xml" should be a valid document according to "junit.xsd" - - Scenario: Handling of a error in afterScenario hook - Given a file named "features/bootstrap/FeatureContext.php" with: - """ - - - """ - And the file "junit/default.xml" should be a valid document according to "junit.xsd" - - Scenario: Handling of a error in beforeStep hook - Given a file named "features/bootstrap/FeatureContext.php" with: - """ - - - """ - And the file "junit/default.xml" should be a valid document according to "junit.xsd" - - Scenario: Handling of a error in afterStep hook - Given a file named "features/bootstrap/FeatureContext.php" with: - """ - - - """ - And the file "junit/default.xml" should be a valid document according to "junit.xsd" diff --git a/features/hooks_failures_junit.feature b/features/hooks_failures_junit.feature new file mode 100644 index 000000000..8b7f7e700 --- /dev/null +++ b/features/hooks_failures_junit.feature @@ -0,0 +1,406 @@ +Feature: Display hook failures location in junit printer + In order to be able to locate the code that generated a failure + As a feature developer using the junit printer + When a hook throws an error I want to see the related item where the code failed + + Background: + Given a file named "features/one.feature" with: + """ + Feature: First feature + + Scenario: First scenario + When I have a simple step + And I have a simple step + + Scenario: Second scenario + When I have a simple step + """ + Given a file named "features/two.feature" with: + """ + Feature: Second feature + + Scenario: First scenario + When I have a simple step + """ + + Scenario: Handling of a error in beforeSuite hook + Given a file named "features/bootstrap/FeatureContext.php" with: + """ + + + """ + And the file "junit/default.xml" should be a valid document according to "junit.xsd" + + Scenario: Handling of a error in afterSuite hook + Given a file named "features/bootstrap/FeatureContext.php" with: + """ + + + """ + And the file "junit/default.xml" should be a valid document according to "junit.xsd" + + Scenario: Handling of a error in beforeFeature hook + Given a file named "features/bootstrap/FeatureContext.php" with: + """ + + + """ + And the file "junit/default.xml" should be a valid document according to "junit.xsd" + + Scenario: Handling of a error in afterFeature hook + Given a file named "features/bootstrap/FeatureContext.php" with: + """ + + + """ + And the file "junit/default.xml" should be a valid document according to "junit.xsd" + + Scenario: Handling of a error in beforeScenario hook + Given a file named "features/bootstrap/FeatureContext.php" with: + """ + + + """ + And the file "junit/default.xml" should be a valid document according to "junit.xsd" + + Scenario: Handling of a error in afterScenario hook + Given a file named "features/bootstrap/FeatureContext.php" with: + """ + + + """ + And the file "junit/default.xml" should be a valid document according to "junit.xsd" + + Scenario: Handling of a error in beforeStep hook + Given a file named "features/bootstrap/FeatureContext.php" with: + """ + + + """ + And the file "junit/default.xml" should be a valid document according to "junit.xsd" + + Scenario: Handling of a error in afterStep hook + Given a file named "features/bootstrap/FeatureContext.php" with: + """ + + + """ + And the file "junit/default.xml" should be a valid document according to "junit.xsd" diff --git a/features/hooks_failures_pretty.feature b/features/hooks_failures_pretty.feature new file mode 100644 index 000000000..8757e94ab --- /dev/null +++ b/features/hooks_failures_pretty.feature @@ -0,0 +1,213 @@ +Feature: Display hook failures location in pretty printer + In order to be able to locate the code that generated a failure + As a feature developer using the pretty printer + When a hook throws an error I want to see the related item where the code failed + + Background: + Given a file named "features/simple.feature" with: + """ + Feature: Simple feature + + Scenario: Simple scenario + When I have a simple step + """ + + Scenario: Handling of a error in beforeSuite hook + Given a file named "features/bootstrap/FeatureContext.php" with: + """ + printSuiteSetupEvent($formatter, $event); + $this->captureSuiteSetupEvent($formatter, $event); $this->printFeatureOnBeforeEvent($formatter, $event); $this->captureStepEvent($event); $this->printScenarioEvent($formatter, $event); @@ -80,9 +80,10 @@ public function listenEvent(Formatter $formatter, Event $event, $eventName) } /** - * Prints any failures in suite setup. + * Captures any failures in suite setup. + * They will be printed later when the first scenario is printed */ - private function printSuiteSetupEvent(Formatter $formatter, Event $event): void + private function captureSuiteSetupEvent(Formatter $formatter, Event $event): void { if ($event instanceof AfterSuiteSetup) { $this->afterSuiteSetup = $event; @@ -95,6 +96,7 @@ private function printSuiteSetupEvent(Formatter $formatter, Event $event): void private function printSuiteTeardownEvent(Formatter $formatter, Event $event): void { if ($event instanceof AfterSuiteTested) { + // if needed, add a failure node to the last testCase node that has been created $this->setupPrinter->printTeardown($formatter, $event->getTeardown()); } } @@ -109,6 +111,8 @@ private function printFeatureOnBeforeEvent(Formatter $formatter, Event $event): return; } if ($event instanceof AfterFeatureSetup) { + // Captures any failures in feature setup. + // They will be printed later when the first scenario is printed $this->afterFeatureSetup = $event; } } From 93322352ed978c5152129c4a4d00875d3d92615d Mon Sep 17 00:00:00 2001 From: Carlos Granados - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Date: Sat, 23 Nov 2024 10:43:57 +0100 Subject: [PATCH 461/567] Removes redundant tests for hook failures in junit formatter --- features/junit_format.feature | 112 ---------------------------------- 1 file changed, 112 deletions(-) diff --git a/features/junit_format.feature b/features/junit_format.feature index daa8d82ac..c2156a775 100644 --- a/features/junit_format.feature +++ b/features/junit_format.feature @@ -603,115 +603,3 @@ """ Directory expected for the `output_path` option, but a filename was given. """ - - Scenario: Include BeforeStep Failures - Given a file named "features/bootstrap/FeatureContext.php" with: - """ - - - """ - And the file "junit/default.xml" should be a valid document according to "junit.xsd" - - Scenario: Include AfterStep Failures - Given a file named "features/bootstrap/FeatureContext.php" with: - """ - - - """ - And the file "junit/default.xml" should be a valid document according to "junit.xsd" From 97d747b92951b7bd82ee9025cd7623371086b164 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lo=C3=AFc=20Fr=C3=A9mont?= - - - - - - - - - - - - Date: Mon, 18 Nov 2024 17:43:10 +0100 Subject: [PATCH 462/567] [PHP Config] imports --- features/import_suites.feature | 180 +++++++++++++++++++++++++++++++++ src/Behat/Config/Config.php | 7 ++ 2 files changed, 187 insertions(+) create mode 100644 features/import_suites.feature diff --git a/features/import_suites.feature b/features/import_suites.feature new file mode 100644 index 000000000..fa373b61f --- /dev/null +++ b/features/import_suites.feature @@ -0,0 +1,180 @@ +Feature: Import suites + In order to add more suites + As a feature writer + I need an ability to import external suite configuration files + + Background: + Given a file named "features/bootstrap/FirstContext.php" with: + """ + [ + 'suites' => [ + 'first' => [ + 'contexts' => [ 'FirstContext' ], + ], + ], + ], + ]); + + return $config; + + """ + And a file named "config/suites/second.php" with: + """ + [ + 'suites' => [ + 'second' => [ + 'contexts' => [ 'SecondContext' ], + ], + ], + ], + ]); + + return $config; + + """ + + Scenario: Importing one suite + Given a file named "behat.php" with: + """ + import('config/suites/first.php'); + + return $config; + + """ + When I run "behat --suite=first --no-colors -fpretty --format-settings='{\"paths\": true}' features" + Then it should pass with: + """ + Feature: Apples story + In order to eat apple + As a little kid + I need to have an apple in my pocket + + Scenario: I'm little hungry # features/some.feature:6 + Given I have 3 apples # FirstContext::iHaveApples() + When I ate 1 apple # FirstContext::iAteApples() + Then I should have 2 apples # FirstContext::iShouldHaveApples() + + 1 scenario (1 passed) + 3 steps (3 passed) + """ + + Scenario: Importing two suites, running one + Given a file named "behat.php" with: + """ + import('config/suites/first.php'); + $config->import('config/suites/second.php'); + + return $config; + + """ + When I run "behat --suite=first --no-colors -fpretty --format-settings='{\"paths\": true}' features" + Then it should pass with: + """ + Feature: Apples story + In order to eat apple + As a little kid + I need to have an apple in my pocket + + Scenario: I'm little hungry # features/some.feature:6 + Given I have 3 apples # FirstContext::iHaveApples() + When I ate 1 apple # FirstContext::iAteApples() + Then I should have 2 apples # FirstContext::iShouldHaveApples() + + 1 scenario (1 passed) + 3 steps (3 passed) + """ + + Scenario: Importing two suites, running all + Given a file named "behat.php" with: + """ + import('config/suites/first.php'); + $config->import('config/suites/second.php'); + + return $config; + + """ + When I run "behat --no-colors -fpretty --format-settings='{\"paths\": true}' features" + Then it should pass with: + """ + Feature: Apples story + In order to eat apple + As a little kid + I need to have an apple in my pocket + + Scenario: I'm little hungry # features/some.feature:6 + Given I have 3 apples # FirstContext::iHaveApples() + When I ate 1 apple # FirstContext::iAteApples() + Then I should have 2 apples # FirstContext::iShouldHaveApples() + + Feature: Apples story + In order to eat apple + As a little kid + I need to have an apple in my pocket + + Scenario: I'm little hungry # features/some.feature:6 + Given I have 3 apples # SecondContext::iHaveApples() + When I ate 1 apple # SecondContext::iAteApples() + Then I should have 2 apples # SecondContext::iShouldHaveApples() + + 2 scenarios (2 passed) + 6 steps (6 passed) + """ diff --git a/src/Behat/Config/Config.php b/src/Behat/Config/Config.php index c9b3cc42a..9d1ad56a0 100644 --- a/src/Behat/Config/Config.php +++ b/src/Behat/Config/Config.php @@ -11,6 +11,13 @@ public function __construct( ) { } + public function import(string $file): self + { + $this->settings['imports'][] = $file; + + return $this; + } + public function toArray(): array { return $this->settings; From f356c62ebb077be48ecf3610874fa0d5a2a2cf6f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lo=C3=AFc=20Fr=C3=A9mont?= Date: Mon, 18 Nov 2024 17:47:02 +0100 Subject: [PATCH 463/567] Import multiple files in the same method --- ...t_suites.feature => importing_suites.feature} | 11 ++++++----- src/Behat/Config/Config.php | 10 ++++++++-- tests/Behat/Tests/Config/ConfigTest.php | 16 ++++++++++++++++ 3 files changed, 30 insertions(+), 7 deletions(-) rename features/{import_suites.feature => importing_suites.feature} (95%) diff --git a/features/import_suites.feature b/features/importing_suites.feature similarity index 95% rename from features/import_suites.feature rename to features/importing_suites.feature index fa373b61f..0928dd89c 100644 --- a/features/import_suites.feature +++ b/features/importing_suites.feature @@ -1,4 +1,4 @@ -Feature: Import suites +Feature: Importing suites In order to add more suites As a feature writer I need an ability to import external suite configuration files @@ -117,8 +117,10 @@ Feature: Import suites import('config/suites/first.php'); - $config->import('config/suites/second.php'); + $config + ->import('config/suites/first.php') + ->import('config/suites/second.php') + ; return $config; @@ -146,8 +148,7 @@ Feature: Import suites import('config/suites/first.php'); - $config->import('config/suites/second.php'); + $config->import(['config/suites/first.php', 'config/suites/second.php']); return $config; diff --git a/src/Behat/Config/Config.php b/src/Behat/Config/Config.php index 9d1ad56a0..4bcaf8bb3 100644 --- a/src/Behat/Config/Config.php +++ b/src/Behat/Config/Config.php @@ -4,6 +4,8 @@ namespace Behat\Config; +use function is_string; + final class Config implements ConfigInterface { public function __construct( @@ -11,9 +13,13 @@ public function __construct( ) { } - public function import(string $file): self + public function import(string|array $resource): self { - $this->settings['imports'][] = $file; + $resources = is_string($resource) ? [$resource] : $resource; + + foreach ($resources as $resource) { + $this->settings['imports'][] = $resource; + } return $this; } diff --git a/tests/Behat/Tests/Config/ConfigTest.php b/tests/Behat/Tests/Config/ConfigTest.php index 4df3737a7..4f67bee40 100644 --- a/tests/Behat/Tests/Config/ConfigTest.php +++ b/tests/Behat/Tests/Config/ConfigTest.php @@ -30,4 +30,20 @@ public function testItReturnsSettings(): void $this->assertEquals($settings, $config->toArray()); } + + public function testAddingImports(): void + { + $config = new Config(); + $config + ->import('config/first_suite.php') + ->import('config/second_suite.php') + ; + + $this->assertEquals([ + 'imports' => [ + 'config/first_suite.php', + 'config/second_suite.php', + ], + ], $config->toArray()); + } } From 9a9296730e6fd0e76abba69441a08507cdeae6fa Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lo=C3=AFc=20Fr=C3=A9mont?= Date: Tue, 26 Nov 2024 12:13:01 +0100 Subject: [PATCH 464/567] Update src/Behat/Config/Config.php --- src/Behat/Config/Config.php | 1 + 1 file changed, 1 insertion(+) diff --git a/src/Behat/Config/Config.php b/src/Behat/Config/Config.php index 4bcaf8bb3..3d2c378c5 100644 --- a/src/Behat/Config/Config.php +++ b/src/Behat/Config/Config.php @@ -13,6 +13,7 @@ public function __construct( ) { } + /** @param string|string[] $resource **/ public function import(string|array $resource): self { $resources = is_string($resource) ? [$resource] : $resource; From 064570ed8beb6fce18455f969ec13966b9a15141 Mon Sep 17 00:00:00 2001 From: Carlos Granados Date: Tue, 26 Nov 2024 08:50:10 +0100 Subject: [PATCH 465/567] feat: adds the `Transform` attribute, equivalent to the `@Transform` annotation --- composer.json | 3 +- ...initions_transformations_attribute.feature | 188 ++++++++++++++++++ .../Context/Reader/AttributeContextReader.php | 4 - .../Attribute/DefinitionAttributeReader.php | 7 - .../Context/Attribute/HookAttributeReader.php | 7 - .../TrasnformationAttributeReader.php | 70 +++++++ .../TransformationExtension.php | 19 +- src/Behat/Transformation/Transform.php | 25 +++ src/Behat/Transformation/Transformation.php | 21 ++ 9 files changed, 323 insertions(+), 21 deletions(-) create mode 100644 features/definitions_transformations_attribute.feature create mode 100644 src/Behat/Behat/Transformation/Context/Attribute/TrasnformationAttributeReader.php create mode 100644 src/Behat/Transformation/Transform.php create mode 100644 src/Behat/Transformation/Transformation.php diff --git a/composer.json b/composer.json index 540059a78..4d84ac19a 100644 --- a/composer.json +++ b/composer.json @@ -47,7 +47,8 @@ "Behat\\Config\\": "src/Behat/Config/", "Behat\\Testwork\\": "src/Behat/Testwork/", "Behat\\Step\\": "src/Behat/Step/", - "Behat\\Hook\\": "src/Behat/Hook/" + "Behat\\Hook\\": "src/Behat/Hook/", + "Behat\\Transformation\\": "src/Behat/Transformation/" } }, diff --git a/features/definitions_transformations_attribute.feature b/features/definitions_transformations_attribute.feature new file mode 100644 index 000000000..f2d683ce9 --- /dev/null +++ b/features/definitions_transformations_attribute.feature @@ -0,0 +1,188 @@ +Feature: Step Arguments Transformations with Attributes + In order to follow DRY + As a feature writer + I need to use transformation functions using PHP attributes + + Background: + Given a file named "features/bootstrap/User.php" with: + """ + username = $username; + $this->age = $age; + } + + public function getUsername() { return $this->username; } + public function getAge() { return $this->age; } + } + """ + + Scenario: Simple Arguments Transformations + Given a file named "features/bootstrap/FeatureContext.php" with: + """ + user = $user; + } + + #[Then('/Username must be "([^"]+)"/')] + public function usernameMustBe($username) { + Assert::assertEquals($username, $this->user->getUsername()); + } + + #[Then('/Age must be (\d+)/')] + public function ageMustBe($age) { + Assert::assertEquals($age, $this->user->getAge()); + } + } + """ + And a file named "features/step_arguments.feature" with: + """ + Feature: Step Arguments + Scenario: + Given I am "everzet" user + Then Username must be "everzet" + And Age must be 20 + + Scenario: + Given I am "antono - 29" user + Then Username must be "antono" + And Age must be 29 + """ + When I run "behat -f progress --no-colors" + Then it should pass with: + """ + ...... + + 2 scenarios (2 passed) + 6 steps (6 passed) + """ + + Scenario: Transformation without parameters + Given a file named "features/bootstrap/FeatureContext.php" with: + """ + user = $user; + } + + #[Then('I should be a user named :name')] + public function iShouldBeAUserNamed($username) { + Assert::assertEquals($username, $this->user->getUserName()); + } + } + """ + And a file named "features/my.feature" with: + """ + Feature: + Scenario: + Given I am "everzet" + Then I should be a user named "everzet" + """ + When I run "behat -f progress --no-colors" + Then it should pass with: + """ + .. + + 1 scenario (1 passed) + 2 steps (2 passed) + """ + + Scenario: Multiple Transformations in one function + Given a file named "features/bootstrap/FeatureContext.php" with: + """ + user = $user; + } + + #[Then('/Username must be "([^"]+)"/')] + public function usernameMustBe($username) { + Assert::assertEquals($username, $this->user->getUsername()); + } + + #[Then('/Age must be (\d+)/')] + public function ageMustBe($age) { + Assert::assertEquals($age, $this->user->getAge()); + } + } + """ + And a file named "features/step_arguments.feature" with: + """ + Feature: Step Arguments + Scenario: + Given I am everzet + Then Username must be "everzet" + And Age must be 20 + + Scenario: + Given I am "antono - 29" user + Then Username must be "antono" + And Age must be 29 + """ + When I run "behat -f progress --no-colors" + Then it should pass with: + """ + ...... + + 2 scenarios (2 passed) + 6 steps (6 passed) + """ diff --git a/src/Behat/Behat/Context/Reader/AttributeContextReader.php b/src/Behat/Behat/Context/Reader/AttributeContextReader.php index 0db164319..e190b4ab6 100644 --- a/src/Behat/Behat/Context/Reader/AttributeContextReader.php +++ b/src/Behat/Behat/Context/Reader/AttributeContextReader.php @@ -42,10 +42,6 @@ public function registerAttributeReader(AttributeReader $reader) */ public function readContextCallees(ContextEnvironment $environment, $contextClass) { - if (\PHP_MAJOR_VERSION < 8) { - return []; - } - $reflection = new ReflectionClass($contextClass); $callees = array(); diff --git a/src/Behat/Behat/Definition/Context/Attribute/DefinitionAttributeReader.php b/src/Behat/Behat/Definition/Context/Attribute/DefinitionAttributeReader.php index e9ef4e9cb..cd9ea3603 100644 --- a/src/Behat/Behat/Definition/Context/Attribute/DefinitionAttributeReader.php +++ b/src/Behat/Behat/Definition/Context/Attribute/DefinitionAttributeReader.php @@ -52,13 +52,6 @@ public function __construct(DocBlockHelper $docBlockHelper) */ public function readCallees(string $contextClass, ReflectionMethod $method) { - if (\PHP_MAJOR_VERSION < 8) { - return []; - } - - /** - * @psalm-suppress UndefinedClass (ReflectionAttribute is PHP 8.0 only) - */ $attributes = $method->getAttributes(Attribute\Definition::class, \ReflectionAttribute::IS_INSTANCEOF); $callees = []; diff --git a/src/Behat/Behat/Hook/Context/Attribute/HookAttributeReader.php b/src/Behat/Behat/Hook/Context/Attribute/HookAttributeReader.php index 6ef521c1b..ed1fd428b 100644 --- a/src/Behat/Behat/Hook/Context/Attribute/HookAttributeReader.php +++ b/src/Behat/Behat/Hook/Context/Attribute/HookAttributeReader.php @@ -59,13 +59,6 @@ public function __construct(DocBlockHelper $docBlockHelper) */ public function readCallees(string $contextClass, ReflectionMethod $method) { - if (\PHP_MAJOR_VERSION < 8) { - return []; - } - - /** - * @psalm-suppress UndefinedClass (ReflectionAttribute is PHP 8.0 only) - */ $attributes = $method->getAttributes(Hook::class, \ReflectionAttribute::IS_INSTANCEOF); $callees = []; diff --git a/src/Behat/Behat/Transformation/Context/Attribute/TrasnformationAttributeReader.php b/src/Behat/Behat/Transformation/Context/Attribute/TrasnformationAttributeReader.php new file mode 100644 index 000000000..dcc39cbb7 --- /dev/null +++ b/src/Behat/Behat/Transformation/Context/Attribute/TrasnformationAttributeReader.php @@ -0,0 +1,70 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Behat\Behat\Transformation\Context\Attribute; + +use Behat\Behat\Context\Annotation\DocBlockHelper; +use Behat\Behat\Context\Attribute\AttributeReader; +use Behat\Behat\Transformation\Context\Annotation\TransformationAnnotationReader; +use Behat\Transformation as Attribute; +use ReflectionMethod; + +/** + * Reads transformation Attributes from the context class. + * + * @author Konstantin Kudryashov + */ +final class TrasnformationAttributeReader extends TransformationAnnotationReader implements AttributeReader +{ + /** + * @var DocBlockHelper + */ + private $docBlockHelper; + + /** + * Initializes reader. + * + * @param DocBlockHelper $docBlockHelper + */ + public function __construct(DocBlockHelper $docBlockHelper) + { + $this->docBlockHelper = $docBlockHelper; + } + + /** + * @{inheritdoc} + */ + public function readCallees(string $contextClass, ReflectionMethod $method) + { + $attributes = $method->getAttributes(Attribute\Transformation::class, \ReflectionAttribute::IS_INSTANCEOF); + + $callees = []; + foreach ($attributes as $attribute) { + $docLine = '@Transform'; + $pattern = $attribute->newInstance()->pattern;; + if ($pattern !== null) { + $docLine .= ' ' . $pattern; + } + + $description = null; + if ($docBlock = $method->getDocComment()) { + $description = $this->docBlockHelper->extractDescription($docBlock); + } + + $callee = $this->readCallee($contextClass, $method, $docLine, $description); + + if ($callee !== null) { + $callees[] = $callee; + } + } + + return $callees; + } +} diff --git a/src/Behat/Behat/Transformation/ServiceContainer/TransformationExtension.php b/src/Behat/Behat/Transformation/ServiceContainer/TransformationExtension.php index 86df51b90..a1a069055 100644 --- a/src/Behat/Behat/Transformation/ServiceContainer/TransformationExtension.php +++ b/src/Behat/Behat/Transformation/ServiceContainer/TransformationExtension.php @@ -87,6 +87,7 @@ public function load(ContainerBuilder $container, array $config) $this->loadDefinitionArgumentsTransformer($container); $this->loadDefaultTransformers($container); $this->loadAnnotationReader($container); + $this->loadAttributeReader($container); $this->loadRepository($container); } @@ -139,6 +140,20 @@ protected function loadAnnotationReader(ContainerBuilder $container) $container->setDefinition(ContextExtension::ANNOTATION_READER_TAG . '.transformation', $definition); } + /** + * Loads transformation attribute reader. + * + * @param ContainerBuilder $container + */ + private function loadAttributeReader(ContainerBuilder $container) + { + $definition = new Definition('\Behat\Behat\Transformation\Context\Attribute\TrasnformationAttributeReader', array( + new Reference(DefinitionExtension::DOC_BLOCK_HELPER_ID) + )); + $definition->addTag(ContextExtension::ATTRIBUTE_READER_TAG, array('priority' => 50)); + $container->setDefinition(ContextExtension::ATTRIBUTE_READER_TAG . '.transformation', $definition); + } + /** * Loads transformations repository. * @@ -171,9 +186,9 @@ protected function processArgumentsTransformers(ContainerBuilder $container) * Returns definition argument transformer service id. * * @return string - * + * * @deprecated Use DEFINITION_ARGUMENT_TRANSFORMER_ID constant instead - * + * * @todo Remove method in next major version */ protected function getDefinitionArgumentTransformerId() diff --git a/src/Behat/Transformation/Transform.php b/src/Behat/Transformation/Transform.php new file mode 100644 index 000000000..a15597794 --- /dev/null +++ b/src/Behat/Transformation/Transform.php @@ -0,0 +1,25 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Behat\Transformation; + +/** + * Represents an Attribute for a Transform transformation + */ +#[\Attribute(\Attribute::TARGET_METHOD | \Attribute::IS_REPEATABLE)] +final class Transform implements Transformation +{ + public ?string $pattern; + + public function __construct(?string $pattern = null) + { + $this->pattern = $pattern; + } +} diff --git a/src/Behat/Transformation/Transformation.php b/src/Behat/Transformation/Transformation.php new file mode 100644 index 000000000..077b0bda4 --- /dev/null +++ b/src/Behat/Transformation/Transformation.php @@ -0,0 +1,21 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Behat\Transformation; + +/** + * Marker interface for all Attributes regarding + * Transformations + * + * @internal Only meant as marker, not as an extension point + */ +interface Transformation +{ +} From cddee6f887e28dbb0db6cd79a0b195a0fdc7e5d0 Mon Sep 17 00:00:00 2001 From: Carlos Granados Date: Tue, 26 Nov 2024 10:44:16 +0100 Subject: [PATCH 466/567] Use modern PHP --- ...initions_transformations_attribute.feature | 42 +++++++++---------- .../TrasnformationAttributeReader.php | 21 +++------- .../TransformationExtension.php | 4 +- 3 files changed, 27 insertions(+), 40 deletions(-) diff --git a/features/definitions_transformations_attribute.feature b/features/definitions_transformations_attribute.feature index f2d683ce9..e26fba829 100644 --- a/features/definitions_transformations_attribute.feature +++ b/features/definitions_transformations_attribute.feature @@ -9,16 +9,14 @@ Feature: Step Arguments Transformations with Attributes username = $username; - $this->age = $age; + public function __construct( + private string $username, + private int $age = 20 + ) { } - public function getUsername() { return $this->username; } - public function getAge() { return $this->age; } + public function getUsername(): string { return $this->username; } + public function getAge(): int { return $this->age; } } """ @@ -35,25 +33,25 @@ Feature: Step Arguments Transformations with Attributes class FeatureContext implements Context { - private $user; + private User $user; #[Transform('/"([^\ "]+)(?: - (\d+))?" user/')] - public function createUserFromUsername($username, $age = 20) { + public function createUserFromUsername(string $username, int $age = 20): User { return new User($username, $age); } #[Given('/I am (".*" user)/')] - public function iAmUser(User $user) { + public function iAmUser(User $user): void { $this->user = $user; } #[Then('/Username must be "([^"]+)"/')] - public function usernameMustBe($username) { + public function usernameMustBe(string $username): void { Assert::assertEquals($username, $this->user->getUsername()); } #[Then('/Age must be (\d+)/')] - public function ageMustBe($age) { + public function ageMustBe(string $age): void { Assert::assertEquals($age, $this->user->getAge()); } } @@ -93,20 +91,20 @@ Feature: Step Arguments Transformations with Attributes class FeatureContext implements Context { - private $user; + private User $user; #[Transform] - public function userFromName($username) : User { + public function userFromName(string $username): User { return new User($username); } #[Given('I am :user')] - public function iAm(User $user) { + public function iAm(User $user): void { $this->user = $user; } #[Then('I should be a user named :name')] - public function iShouldBeAUserNamed($username) { + public function iShouldBeAUserNamed(string $username): void { Assert::assertEquals($username, $this->user->getUserName()); } } @@ -140,27 +138,27 @@ Feature: Step Arguments Transformations with Attributes class FeatureContext implements Context { - private $user; + private User $user; #[Transform('/"([^\ "]+)(?: - (\d+))?" user/')] #[Transform(':user')] - public function createUserFromUsername($username, $age = 20) { + public function createUserFromUsername($username, $age = 20): User { return new User($username, $age); } #[Given('/I am (".*" user)/')] #[Given('I am :user')] - public function iAmUser(User $user) { + public function iAmUser(User $user): void { $this->user = $user; } #[Then('/Username must be "([^"]+)"/')] - public function usernameMustBe($username) { + public function usernameMustBe(string $username): void { Assert::assertEquals($username, $this->user->getUsername()); } #[Then('/Age must be (\d+)/')] - public function ageMustBe($age) { + public function ageMustBe(string $age): void { Assert::assertEquals($age, $this->user->getAge()); } } diff --git a/src/Behat/Behat/Transformation/Context/Attribute/TrasnformationAttributeReader.php b/src/Behat/Behat/Transformation/Context/Attribute/TrasnformationAttributeReader.php index dcc39cbb7..1d831d62e 100644 --- a/src/Behat/Behat/Transformation/Context/Attribute/TrasnformationAttributeReader.php +++ b/src/Behat/Behat/Transformation/Context/Attribute/TrasnformationAttributeReader.php @@ -13,6 +13,7 @@ use Behat\Behat\Context\Annotation\DocBlockHelper; use Behat\Behat\Context\Attribute\AttributeReader; use Behat\Behat\Transformation\Context\Annotation\TransformationAnnotationReader; +use Behat\Behat\Transformation\Transformation; use Behat\Transformation as Attribute; use ReflectionMethod; @@ -23,25 +24,15 @@ */ final class TrasnformationAttributeReader extends TransformationAnnotationReader implements AttributeReader { - /** - * @var DocBlockHelper - */ - private $docBlockHelper; - - /** - * Initializes reader. - * - * @param DocBlockHelper $docBlockHelper - */ - public function __construct(DocBlockHelper $docBlockHelper) - { - $this->docBlockHelper = $docBlockHelper; + public function __construct( + private DocBlockHelper $docBlockHelper + ) { } /** - * @{inheritdoc} + * @return Transformation[] */ - public function readCallees(string $contextClass, ReflectionMethod $method) + public function readCallees(string $contextClass, ReflectionMethod $method): array { $attributes = $method->getAttributes(Attribute\Transformation::class, \ReflectionAttribute::IS_INSTANCEOF); diff --git a/src/Behat/Behat/Transformation/ServiceContainer/TransformationExtension.php b/src/Behat/Behat/Transformation/ServiceContainer/TransformationExtension.php index a1a069055..fa9d2f6ce 100644 --- a/src/Behat/Behat/Transformation/ServiceContainer/TransformationExtension.php +++ b/src/Behat/Behat/Transformation/ServiceContainer/TransformationExtension.php @@ -142,10 +142,8 @@ protected function loadAnnotationReader(ContainerBuilder $container) /** * Loads transformation attribute reader. - * - * @param ContainerBuilder $container */ - private function loadAttributeReader(ContainerBuilder $container) + private function loadAttributeReader(ContainerBuilder $container): void { $definition = new Definition('\Behat\Behat\Transformation\Context\Attribute\TrasnformationAttributeReader', array( new Reference(DefinitionExtension::DOC_BLOCK_HELPER_ID) From aa74d05e5678545118609de6e7f61bc5dc6ddbdc Mon Sep 17 00:00:00 2001 From: Carlos Granados Date: Tue, 26 Nov 2024 11:31:15 +0100 Subject: [PATCH 467/567] Create callee factory, fix typo, remove interface --- .../TransformationAnnotationReader.php | 31 +--------- ....php => TransformationAttributeReader.php} | 18 ++---- .../Factory/TransformationCalleeFactory.php | 59 +++++++++++++++++++ .../TransformationExtension.php | 2 +- src/Behat/Transformation/Transform.php | 2 +- src/Behat/Transformation/Transformation.php | 21 ------- 6 files changed, 69 insertions(+), 64 deletions(-) rename src/Behat/Behat/Transformation/Context/Attribute/{TrasnformationAttributeReader.php => TransformationAttributeReader.php} (66%) create mode 100644 src/Behat/Behat/Transformation/Context/Factory/TransformationCalleeFactory.php delete mode 100644 src/Behat/Transformation/Transformation.php diff --git a/src/Behat/Behat/Transformation/Context/Annotation/TransformationAnnotationReader.php b/src/Behat/Behat/Transformation/Context/Annotation/TransformationAnnotationReader.php index 680d19685..57a259764 100644 --- a/src/Behat/Behat/Transformation/Context/Annotation/TransformationAnnotationReader.php +++ b/src/Behat/Behat/Transformation/Context/Annotation/TransformationAnnotationReader.php @@ -11,6 +11,7 @@ namespace Behat\Behat\Transformation\Context\Annotation; use Behat\Behat\Context\Annotation\AnnotationReader; +use Behat\Behat\Transformation\Context\Factory\TransformationCalleeFactory; use Behat\Behat\Transformation\Transformation\PatternTransformation; use Behat\Behat\Transformation\Transformation; use ReflectionMethod; @@ -36,41 +37,15 @@ class TransformationAnnotationReader implements AnnotationReader * @param ReflectionMethod $method * @param string $docLine * @param string $description - * - * @return null|Transformation */ - public function readCallee($contextClass, ReflectionMethod $method, $docLine, $description) + public function readCallee($contextClass, ReflectionMethod $method, $docLine, $description): ?Transformation { if (!preg_match(self::$regex, $docLine, $match)) { return null; } $pattern = $match[1]; - $callable = array($contextClass, $method->getName()); - - foreach ($this->simpleTransformations() as $transformation) { - if ($transformation::supportsPatternAndMethod($pattern, $method)) { - return new $transformation($pattern, $callable, $description); - } - } - - return new PatternTransformation($pattern, $callable, $description); - } - /** - * Returns list of default transformations. - * - * @return array - */ - private function simpleTransformations() - { - return array( - 'Behat\Behat\Transformation\Transformation\RowBasedTableTransformation', - 'Behat\Behat\Transformation\Transformation\ColumnBasedTableTransformation', - 'Behat\Behat\Transformation\Transformation\TableRowTransformation', - 'Behat\Behat\Transformation\Transformation\TokenNameAndReturnTypeTransformation', - 'Behat\Behat\Transformation\Transformation\ReturnTypeTransformation', - 'Behat\Behat\Transformation\Transformation\TokenNameTransformation' - ); + return TransformationCalleeFactory::create($contextClass, $method, $pattern, $description); } } diff --git a/src/Behat/Behat/Transformation/Context/Attribute/TrasnformationAttributeReader.php b/src/Behat/Behat/Transformation/Context/Attribute/TransformationAttributeReader.php similarity index 66% rename from src/Behat/Behat/Transformation/Context/Attribute/TrasnformationAttributeReader.php rename to src/Behat/Behat/Transformation/Context/Attribute/TransformationAttributeReader.php index 1d831d62e..46dfceaa7 100644 --- a/src/Behat/Behat/Transformation/Context/Attribute/TrasnformationAttributeReader.php +++ b/src/Behat/Behat/Transformation/Context/Attribute/TransformationAttributeReader.php @@ -12,7 +12,7 @@ use Behat\Behat\Context\Annotation\DocBlockHelper; use Behat\Behat\Context\Attribute\AttributeReader; -use Behat\Behat\Transformation\Context\Annotation\TransformationAnnotationReader; +use Behat\Behat\Transformation\Context\Factory\TransformationCalleeFactory; use Behat\Behat\Transformation\Transformation; use Behat\Transformation as Attribute; use ReflectionMethod; @@ -22,7 +22,7 @@ * * @author Konstantin Kudryashov */ -final class TrasnformationAttributeReader extends TransformationAnnotationReader implements AttributeReader +final class TransformationAttributeReader implements AttributeReader { public function __construct( private DocBlockHelper $docBlockHelper @@ -34,26 +34,18 @@ public function __construct( */ public function readCallees(string $contextClass, ReflectionMethod $method): array { - $attributes = $method->getAttributes(Attribute\Transformation::class, \ReflectionAttribute::IS_INSTANCEOF); + $attributes = $method->getAttributes(Attribute\Transform::class); $callees = []; foreach ($attributes as $attribute) { - $docLine = '@Transform'; - $pattern = $attribute->newInstance()->pattern;; - if ($pattern !== null) { - $docLine .= ' ' . $pattern; - } + $pattern = $attribute->newInstance()->pattern ?? ''; $description = null; if ($docBlock = $method->getDocComment()) { $description = $this->docBlockHelper->extractDescription($docBlock); } - $callee = $this->readCallee($contextClass, $method, $docLine, $description); - - if ($callee !== null) { - $callees[] = $callee; - } + $callees[] = TransformationCalleeFactory::create($contextClass, $method, $pattern, $description); } return $callees; diff --git a/src/Behat/Behat/Transformation/Context/Factory/TransformationCalleeFactory.php b/src/Behat/Behat/Transformation/Context/Factory/TransformationCalleeFactory.php new file mode 100644 index 000000000..7303cfae2 --- /dev/null +++ b/src/Behat/Behat/Transformation/Context/Factory/TransformationCalleeFactory.php @@ -0,0 +1,59 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Behat\Behat\Transformation\Context\Factory; + +use Behat\Behat\Transformation\Transformation; +use Behat\Behat\Transformation\Transformation\ColumnBasedTableTransformation; +use Behat\Behat\Transformation\Transformation\PatternTransformation; +use Behat\Behat\Transformation\Transformation\ReturnTypeTransformation; +use Behat\Behat\Transformation\Transformation\RowBasedTableTransformation; +use Behat\Behat\Transformation\Transformation\TableRowTransformation; +use Behat\Behat\Transformation\Transformation\TokenNameAndReturnTypeTransformation; +use Behat\Behat\Transformation\Transformation\TokenNameTransformation; +use ReflectionMethod; + +/** + * Generates the callee for a transformation + * + * @author Konstantin Kudryashov + */ +class TransformationCalleeFactory +{ + public static function create(string $contextClass, ReflectionMethod $method, string $pattern, ?string $description): Transformation + { + $callable = array($contextClass, $method->getName()); + + foreach (self::simpleTransformations() as $transformation) { + if ($transformation::supportsPatternAndMethod($pattern, $method)) { + return new $transformation($pattern, $callable, $description); + } + } + + return new PatternTransformation($pattern, $callable, $description); + } + + /** + * Returns list of default transformations. + * + * @return class-string[] + */ + private static function simpleTransformations() + { + return [ + RowBasedTableTransformation::class, + ColumnBasedTableTransformation::class, + TableRowTransformation::class, + TokenNameAndReturnTypeTransformation::class, + ReturnTypeTransformation::class, + TokenNameTransformation::class + ]; + } +} diff --git a/src/Behat/Behat/Transformation/ServiceContainer/TransformationExtension.php b/src/Behat/Behat/Transformation/ServiceContainer/TransformationExtension.php index fa9d2f6ce..d946070ca 100644 --- a/src/Behat/Behat/Transformation/ServiceContainer/TransformationExtension.php +++ b/src/Behat/Behat/Transformation/ServiceContainer/TransformationExtension.php @@ -145,7 +145,7 @@ protected function loadAnnotationReader(ContainerBuilder $container) */ private function loadAttributeReader(ContainerBuilder $container): void { - $definition = new Definition('\Behat\Behat\Transformation\Context\Attribute\TrasnformationAttributeReader', array( + $definition = new Definition('\Behat\Behat\Transformation\Context\Attribute\TransformationAttributeReader', array( new Reference(DefinitionExtension::DOC_BLOCK_HELPER_ID) )); $definition->addTag(ContextExtension::ATTRIBUTE_READER_TAG, array('priority' => 50)); diff --git a/src/Behat/Transformation/Transform.php b/src/Behat/Transformation/Transform.php index a15597794..e1b75c312 100644 --- a/src/Behat/Transformation/Transform.php +++ b/src/Behat/Transformation/Transform.php @@ -14,7 +14,7 @@ * Represents an Attribute for a Transform transformation */ #[\Attribute(\Attribute::TARGET_METHOD | \Attribute::IS_REPEATABLE)] -final class Transform implements Transformation +final class Transform { public ?string $pattern; diff --git a/src/Behat/Transformation/Transformation.php b/src/Behat/Transformation/Transformation.php deleted file mode 100644 index 077b0bda4..000000000 --- a/src/Behat/Transformation/Transformation.php +++ /dev/null @@ -1,21 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Behat\Transformation; - -/** - * Marker interface for all Attributes regarding - * Transformations - * - * @internal Only meant as marker, not as an extension point - */ -interface Transformation -{ -} From f18f0b135750d4849135cfceb802a5e1036b5492 Mon Sep 17 00:00:00 2001 From: Carlos Granados Date: Tue, 26 Nov 2024 11:48:42 +0100 Subject: [PATCH 468/567] Make pattern non-nullable, mark factory as internal --- .../Context/Attribute/TransformationAttributeReader.php | 2 +- .../Context/Factory/TransformationCalleeFactory.php | 2 ++ src/Behat/Transformation/Transform.php | 8 +++----- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/src/Behat/Behat/Transformation/Context/Attribute/TransformationAttributeReader.php b/src/Behat/Behat/Transformation/Context/Attribute/TransformationAttributeReader.php index 46dfceaa7..4e37c05b9 100644 --- a/src/Behat/Behat/Transformation/Context/Attribute/TransformationAttributeReader.php +++ b/src/Behat/Behat/Transformation/Context/Attribute/TransformationAttributeReader.php @@ -38,7 +38,7 @@ public function readCallees(string $contextClass, ReflectionMethod $method): arr $callees = []; foreach ($attributes as $attribute) { - $pattern = $attribute->newInstance()->pattern ?? ''; + $pattern = $attribute->newInstance()->pattern; $description = null; if ($docBlock = $method->getDocComment()) { diff --git a/src/Behat/Behat/Transformation/Context/Factory/TransformationCalleeFactory.php b/src/Behat/Behat/Transformation/Context/Factory/TransformationCalleeFactory.php index 7303cfae2..7207a2bb3 100644 --- a/src/Behat/Behat/Transformation/Context/Factory/TransformationCalleeFactory.php +++ b/src/Behat/Behat/Transformation/Context/Factory/TransformationCalleeFactory.php @@ -24,6 +24,8 @@ * Generates the callee for a transformation * * @author Konstantin Kudryashov + * + * @internal */ class TransformationCalleeFactory { diff --git a/src/Behat/Transformation/Transform.php b/src/Behat/Transformation/Transform.php index e1b75c312..0b5bd6362 100644 --- a/src/Behat/Transformation/Transform.php +++ b/src/Behat/Transformation/Transform.php @@ -16,10 +16,8 @@ #[\Attribute(\Attribute::TARGET_METHOD | \Attribute::IS_REPEATABLE)] final class Transform { - public ?string $pattern; - - public function __construct(?string $pattern = null) - { - $this->pattern = $pattern; + public function __construct( + public string $pattern = '' + ) { } } From adc76125e7950158c8484073e3737e4526c62fbb Mon Sep 17 00:00:00 2001 From: Carlos Granados Date: Tue, 26 Nov 2024 14:30:57 +0100 Subject: [PATCH 469/567] Make attribute pattern read only --- src/Behat/Transformation/Transform.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Behat/Transformation/Transform.php b/src/Behat/Transformation/Transform.php index 0b5bd6362..1ec267dbe 100644 --- a/src/Behat/Transformation/Transform.php +++ b/src/Behat/Transformation/Transform.php @@ -17,7 +17,7 @@ final class Transform { public function __construct( - public string $pattern = '' + public readonly string $pattern = '' ) { } } From 395c1479075f15ea71fcdcdf5dbc0ae2205d89fd Mon Sep 17 00:00:00 2001 From: Carlos Granados Date: Thu, 28 Nov 2024 10:13:34 +0100 Subject: [PATCH 470/567] Update to Psalm 5 --- .github/workflows/build.yml | 32 ++----------------- composer.json | 2 +- psalm.xml | 29 +++++++---------- .../Handler/ContextEnvironmentHandler.php | 2 +- .../Suite/Setup/SuiteWithContextsSetup.php | 2 +- .../Argument/ServicesResolverFactory.php | 2 +- src/Behat/Testwork/Call/CallResults.php | 2 ++ src/Behat/Testwork/Call/RuntimeCallee.php | 10 +----- .../Node/EventListener/ChainEventListener.php | 2 ++ .../SpecificationArrayIterator.php | 1 + .../Specification/SpecificationIterator.php | 2 ++ .../Testwork/Tester/Result/TestResults.php | 2 ++ 12 files changed, 27 insertions(+), 61 deletions(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 6db17941f..10576ad19 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -69,11 +69,6 @@ jobs: composer config --global --no-plugins allow-plugins.symfony/flex true && composer global require symfony/flex - # until psalm is updated to v5 which is compatible with Symfony 7 - - name: Remove vimeo/psalm - if: matrix.symfony-version == '7.0' - run: composer remove vimeo/psalm --no-update --dev - - name: Install latest dependencies if: matrix.composer-mode == 'update' env: @@ -94,31 +89,8 @@ jobs: if: matrix.php >= 8.0 run: ./bin/behat -fprogress --strict --tags=@php8 - static-analysis: - name: Static analysis - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v4 - - - name: Setup PHP - uses: shivammathur/setup-php@v2 - with: - php-version: 8.1 - ini-values: "zend.exception_ignore_args=Off" - coverage: none - - # until psalm is updated to v5 which is compatible with Symfony 7 - - name: Force symfony version for psalm compatibility - run: | - composer config --global --no-plugins allow-plugins.symfony/flex true && - composer global require symfony/flex - - - name: Install dependencies - env: - SYMFONY_REQUIRE: 5.4.* - run: composer update - - name: Run Psalm + if: matrix.php != 8.4 && matrix.composer-mode != 'lowest' run: ./vendor/bin/psalm --output-format=github build-phar: @@ -171,7 +143,7 @@ jobs: coverage: none - name: Install dependencies - run: composer install + run: composer install --no-dev ${{ matrix.php == '8.4' && '--ignore-platform-req=php+' || '' }} - uses: actions/download-artifact@v4 with: diff --git a/composer.json b/composer.json index 4d84ac19a..dc4a9db21 100644 --- a/composer.json +++ b/composer.json @@ -34,7 +34,7 @@ "sebastian/diff": "^4.0", "symfony/polyfill-php84": "^1.31", "symfony/process": "^5.4 || ^6.4 || ^7.0", - "vimeo/psalm": "^4.8" + "vimeo/psalm": "^5.0" }, "suggest": { diff --git a/psalm.xml b/psalm.xml index 34d6caeae..4b54b4c2f 100644 --- a/psalm.xml +++ b/psalm.xml @@ -2,15 +2,14 @@ diff --git a/src/Behat/Behat/Context/Environment/Handler/ContextEnvironmentHandler.php b/src/Behat/Behat/Context/Environment/Handler/ContextEnvironmentHandler.php index 7c610c9c6..02e438ee6 100644 --- a/src/Behat/Behat/Context/Environment/Handler/ContextEnvironmentHandler.php +++ b/src/Behat/Behat/Context/Environment/Handler/ContextEnvironmentHandler.php @@ -155,7 +155,7 @@ function ($context) { * * @param Suite $suite * - * @return string[] + * @return array + - - - @@ -24,21 +23,6 @@ - - - - - - - - - - - - - - - @@ -56,7 +40,16 @@ + + + + + + + + * * @throws SuiteConfigurationException If `contexts` setting is not an array */ diff --git a/src/Behat/Behat/Context/Suite/Setup/SuiteWithContextsSetup.php b/src/Behat/Behat/Context/Suite/Setup/SuiteWithContextsSetup.php index 4260e2df1..1273e3e1c 100644 --- a/src/Behat/Behat/Context/Suite/Setup/SuiteWithContextsSetup.php +++ b/src/Behat/Behat/Context/Suite/Setup/SuiteWithContextsSetup.php @@ -108,7 +108,7 @@ function ($context) { * * @param Suite $suite * - * @return string[] + * @return array * * @throws SuiteConfigurationException If `contexts` setting is not an array */ diff --git a/src/Behat/Behat/HelperContainer/Argument/ServicesResolverFactory.php b/src/Behat/Behat/HelperContainer/Argument/ServicesResolverFactory.php index 8820288c5..43d8ef490 100644 --- a/src/Behat/Behat/HelperContainer/Argument/ServicesResolverFactory.php +++ b/src/Behat/Behat/HelperContainer/Argument/ServicesResolverFactory.php @@ -98,7 +98,7 @@ public function createArgumentResolvers(Environment $environment) /** * Creates container from the setting passed. * - * @param string $settings + * @param string|array $settings * * @return mixed * diff --git a/src/Behat/Testwork/Call/CallResults.php b/src/Behat/Testwork/Call/CallResults.php index 6bc3e8b11..3c6e29689 100644 --- a/src/Behat/Testwork/Call/CallResults.php +++ b/src/Behat/Testwork/Call/CallResults.php @@ -18,6 +18,8 @@ * Aggregates multiple call results into a collection and provides an informational API on top of that. * * @author Konstantin Kudryashov + * + * @implements IteratorAggregate */ final class CallResults implements Countable, IteratorAggregate { diff --git a/src/Behat/Testwork/Call/RuntimeCallee.php b/src/Behat/Testwork/Call/RuntimeCallee.php index fa232f836..9d83a1c11 100644 --- a/src/Behat/Testwork/Call/RuntimeCallee.php +++ b/src/Behat/Testwork/Call/RuntimeCallee.php @@ -42,21 +42,13 @@ class RuntimeCallee implements Callee /** * Initializes callee. * - * @param callable $callable + * @param callable $callable * @param null|string $description * * @throws BadCallbackException If invalid callback provided */ public function __construct($callable, $description = null) { - if (!is_array($callable) && !is_callable($callable)) { - throw new BadCallbackException(sprintf( - '%s expects a valid callable, but `%s` given', - get_class($this), - gettype($callable) - ), $callable); - } - if (is_array($callable)) { $this->reflection = new ReflectionMethod($callable[0], $callable[1]); $this->path = $callable[0] . '::' . $callable[1] . '()'; diff --git a/src/Behat/Testwork/Output/Node/EventListener/ChainEventListener.php b/src/Behat/Testwork/Output/Node/EventListener/ChainEventListener.php index 2fb8d44cb..f4cc0d938 100644 --- a/src/Behat/Testwork/Output/Node/EventListener/ChainEventListener.php +++ b/src/Behat/Testwork/Output/Node/EventListener/ChainEventListener.php @@ -20,6 +20,8 @@ * Used to compose formatter event listeners. * * @author Konstantin Kudryashov + * + * @implements IteratorAggregate */ class ChainEventListener implements EventListener, Countable, IteratorAggregate { diff --git a/src/Behat/Testwork/Specification/SpecificationArrayIterator.php b/src/Behat/Testwork/Specification/SpecificationArrayIterator.php index c48292dc9..c59f16cd7 100644 --- a/src/Behat/Testwork/Specification/SpecificationArrayIterator.php +++ b/src/Behat/Testwork/Specification/SpecificationArrayIterator.php @@ -19,6 +19,7 @@ * Return instance of this class from locator if specifications cannot be searched lazily. * * @author Christophe Coevoet + * @extends ArrayIterator */ final class SpecificationArrayIterator extends ArrayIterator implements SpecificationIterator { diff --git a/src/Behat/Testwork/Specification/SpecificationIterator.php b/src/Behat/Testwork/Specification/SpecificationIterator.php index c96ad6c69..81544bc97 100644 --- a/src/Behat/Testwork/Specification/SpecificationIterator.php +++ b/src/Behat/Testwork/Specification/SpecificationIterator.php @@ -17,6 +17,8 @@ * Iterates over test specifications. * * @author Konstantin Kudryashov + * + * @extends Iterator */ interface SpecificationIterator extends Iterator { diff --git a/src/Behat/Testwork/Tester/Result/TestResults.php b/src/Behat/Testwork/Tester/Result/TestResults.php index cf8e4aa52..2929b130f 100644 --- a/src/Behat/Testwork/Tester/Result/TestResults.php +++ b/src/Behat/Testwork/Tester/Result/TestResults.php @@ -18,6 +18,8 @@ * Aggregates multiple test results into a collection and provides informational API on top of that. * * @author Konstantin Kudryashov + * + * @implements IteratorAggregate */ final class TestResults implements TestResult, Countable, IteratorAggregate { From 345b49dcabed8c2c99fa3c6b16c3d0527ec4259f Mon Sep 17 00:00:00 2001 From: Carlos Granados Date: Thu, 28 Nov 2024 15:47:35 +0100 Subject: [PATCH 471/567] Update to Psalm 5 --- .github/workflows/build.yml | 24 +++++++++++++++++++++-- src/Behat/Testwork/Call/RuntimeCallee.php | 7 +------ 2 files changed, 23 insertions(+), 8 deletions(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 10576ad19..1d1d048ba 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -89,9 +89,29 @@ jobs: if: matrix.php >= 8.0 run: ./bin/behat -fprogress --strict --tags=@php8 + static-analysis: + name: Static analysis + runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + #runs on the lowest and highest supported versions (change this to 8.4 once psalm supports it) + php: [8.1, 8.3] + steps: + - uses: actions/checkout@v4 + + - name: Setup PHP + uses: shivammathur/setup-php@v2 + with: + php-version: "${{ matrix.php }}" + ini-values: "zend.exception_ignore_args=Off" + coverage: none + + - name: Install dependencies + run: composer update + - name: Run Psalm - if: matrix.php != 8.4 && matrix.composer-mode != 'lowest' - run: ./vendor/bin/psalm --output-format=github + run: ./vendor/bin/psalm --output-format=github --php-version=${{ matrix.php }} build-phar: name: Build PHAR file diff --git a/src/Behat/Testwork/Call/RuntimeCallee.php b/src/Behat/Testwork/Call/RuntimeCallee.php index 9d83a1c11..c28de3eb6 100644 --- a/src/Behat/Testwork/Call/RuntimeCallee.php +++ b/src/Behat/Testwork/Call/RuntimeCallee.php @@ -41,13 +41,8 @@ class RuntimeCallee implements Callee /** * Initializes callee. - * - * @param callable $callable - * @param null|string $description - * - * @throws BadCallbackException If invalid callback provided */ - public function __construct($callable, $description = null) + public function __construct(callable $callable, ?string $description = null) { if (is_array($callable)) { $this->reflection = new ReflectionMethod($callable[0], $callable[1]); From 0d110628705d6265ba669deb664ee83b9c4748d2 Mon Sep 17 00:00:00 2001 From: Carlos Granados Date: Thu, 28 Nov 2024 16:01:56 +0100 Subject: [PATCH 472/567] Update to Psalm 5 --- src/Behat/Testwork/Call/RuntimeCallee.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Behat/Testwork/Call/RuntimeCallee.php b/src/Behat/Testwork/Call/RuntimeCallee.php index c28de3eb6..76e7a2740 100644 --- a/src/Behat/Testwork/Call/RuntimeCallee.php +++ b/src/Behat/Testwork/Call/RuntimeCallee.php @@ -42,7 +42,7 @@ class RuntimeCallee implements Callee /** * Initializes callee. */ - public function __construct(callable $callable, ?string $description = null) + public function __construct(callable|array $callable, ?string $description = null) { if (is_array($callable)) { $this->reflection = new ReflectionMethod($callable[0], $callable[1]); From 93abb0d9c345cb5e111ce9d809c39adf9ee343d0 Mon Sep 17 00:00:00 2001 From: Carlos Granados Date: Thu, 28 Nov 2024 16:11:45 +0100 Subject: [PATCH 473/567] Update to Psalm 5 --- .github/workflows/build.yml | 3 --- 1 file changed, 3 deletions(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 1d1d048ba..1141cf320 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -162,9 +162,6 @@ jobs: ini-values: "phar.readonly=0,zend.exception_ignore_args=Off" coverage: none - - name: Install dependencies - run: composer install --no-dev ${{ matrix.php == '8.4' && '--ignore-platform-req=php+' || '' }} - - uses: actions/download-artifact@v4 with: name: behat.phar From 27c6054dd07109db1bf8bd243da2b6181d01789c Mon Sep 17 00:00:00 2001 From: Carlos Granados Date: Thu, 28 Nov 2024 17:50:01 +0100 Subject: [PATCH 474/567] Update to Psalm 5 --- psalm.xml | 7 ------- src/Behat/Behat/Snippet/AggregateSnippet.php | 18 ++++++++++-------- 2 files changed, 10 insertions(+), 15 deletions(-) diff --git a/psalm.xml b/psalm.xml index 4b54b4c2f..71dfbfe83 100644 --- a/psalm.xml +++ b/psalm.xml @@ -43,13 +43,6 @@ - - - diff --git a/src/Behat/Behat/Snippet/AggregateSnippet.php b/src/Behat/Behat/Snippet/AggregateSnippet.php index c63e8f1d7..5fda19d02 100644 --- a/src/Behat/Behat/Snippet/AggregateSnippet.php +++ b/src/Behat/Behat/Snippet/AggregateSnippet.php @@ -113,15 +113,17 @@ public function getUsedClasses() return array_unique( array_merge( - ...array_map( - function (Snippet $snippet) { - if (!$snippet instanceof ContextSnippet) { - return array(); - } + ...array_values( + array_map( + function (Snippet $snippet) { + if (!$snippet instanceof ContextSnippet) { + return array(); + } - return $snippet->getUsedClasses(); - }, - $this->snippets + return $snippet->getUsedClasses(); + }, + $this->snippets + ) ) ) ); From 08aad34c0ff97893e7e97d54ee398062acce95a6 Mon Sep 17 00:00:00 2001 From: Carlos Granados - - - - Date: Sun, 1 Dec 2024 10:37:29 +0100 Subject: [PATCH 475/567] Make type more specific --- .../Context/Environment/Handler/ContextEnvironmentHandler.php | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/Behat/Behat/Context/Environment/Handler/ContextEnvironmentHandler.php b/src/Behat/Behat/Context/Environment/Handler/ContextEnvironmentHandler.php index 02e438ee6..8a710d069 100644 --- a/src/Behat/Behat/Context/Environment/Handler/ContextEnvironmentHandler.php +++ b/src/Behat/Behat/Context/Environment/Handler/ContextEnvironmentHandler.php @@ -14,6 +14,7 @@ use Behat\Behat\Context\Argument\SuiteScopedResolverFactoryAdapter; use Behat\Behat\Context\Argument\ArgumentResolverFactory; use Behat\Behat\Context\Argument\NullFactory; +use Behat\Behat\Context\Context; use Behat\Behat\Context\ContextClass\ClassResolver; use Behat\Behat\Context\ContextFactory; use Behat\Behat\Context\Environment\InitializedContextEnvironment; @@ -155,7 +156,7 @@ function ($context) { * * @param Suite $suite * - * @return array + * @return array|array,array>> * * @throws SuiteConfigurationException If `contexts` setting is not an array */ From ad1d7db847a1183c02c93648c77bb16ed897ae72 Mon Sep 17 00:00:00 2001 From: Carlos Granados Date: Fri, 29 Nov 2024 09:03:36 +0100 Subject: [PATCH 476/567] chore: remove mentions to php 8 --- .github/workflows/build.yml | 4 ---- behat.yml.dist | 3 --- features/attributes.feature | 18 +++++++----------- features/autowire.feature | 1 - features/definitions_transformations.feature | 1 - tests/Behat/Tests/Config/ConfigTest.php | 2 +- 6 files changed, 8 insertions(+), 21 deletions(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 1141cf320..7e1875882 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -85,10 +85,6 @@ jobs: - name: Run tests (Behat) run: ./bin/behat -fprogress --strict - - name: Run tests (Behat for PHP 8.0) - if: matrix.php >= 8.0 - run: ./bin/behat -fprogress --strict --tags=@php8 - static-analysis: name: Static analysis runs-on: ubuntu-latest diff --git a/behat.yml.dist b/behat.yml.dist index b2c042fa1..0f63330a2 100644 --- a/behat.yml.dist +++ b/behat.yml.dist @@ -1,4 +1 @@ default: - gherkin: - filters: - tags: ~@php8 diff --git a/features/attributes.feature b/features/attributes.feature index c4c6d4c8e..f257a50f8 100644 --- a/features/attributes.feature +++ b/features/attributes.feature @@ -1,10 +1,9 @@ Feature: attributes In order to keep annotations shorter and faster to parse As a tester - I need to be able to use PHP8 Attributes + I need to be able to use PHP Attributes - @php8 - Scenario: PHP 8 Step Attributes + Scenario: Step Attributes Given a file named "features/bootstrap/FeatureContext.php" with: """ [ 'gherkin' => [ 'filters' => [ - 'tags' => '~@php8' + 'tags' => '~@test' ], ], ], From 4fd952b547511995f5a06a452c8f05fbcbc1d6fc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lo=C3=AFc=20Fr=C3=A9mont?= Date: Wed, 27 Nov 2024 11:51:52 +0100 Subject: [PATCH 477/567] Isolate getting PHP Config object to prevent var collisions --- .../Configuration/ConfigurationLoader.php | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/src/Behat/Testwork/ServiceContainer/Configuration/ConfigurationLoader.php b/src/Behat/Testwork/ServiceContainer/Configuration/ConfigurationLoader.php index 0ab1a7f6b..d0a0fa560 100644 --- a/src/Behat/Testwork/ServiceContainer/Configuration/ConfigurationLoader.php +++ b/src/Behat/Testwork/ServiceContainer/Configuration/ConfigurationLoader.php @@ -200,7 +200,8 @@ protected function loadFileConfiguration($configPath, $profile) $basePath = rtrim(dirname($configPath), DIRECTORY_SEPARATOR); if (str_ends_with($configPath, '.php')) { - $phpConfig = require $configPath; + $phpConfig = $this->getPHPConfigObjectClosure($configPath)(); + if (!$phpConfig instanceof ConfigInterface) { throw new ConfigurationLoadingException(sprintf('Configuration file `%s` must return an instance of `%s`.', $configPath, ConfigInterface::class)); } @@ -213,6 +214,20 @@ protected function loadFileConfiguration($configPath, $profile) return $this->loadConfigs($basePath, $config, $profile); } + /** + * Scope isolated include. + * + * Prevents access to $this/self from included files. + */ + private function getPHPConfigObjectClosure(string $configPath): \Closure + { + return \Closure::bind(function () use ($configPath): mixed { + $config = require $configPath; + + return $config; + }, null, null); + } + /** * Loads configs for provided config and profile. * From 3e937679de2991f6592b9e7135a9f3c4d210732c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lo=C3=AFc=20Fr=C3=A9mont?= Date: Wed, 27 Nov 2024 08:47:25 +0100 Subject: [PATCH 478/567] PHP Config profiles --- features/extensions.feature | 25 ++++++++++++---- features/profiles.feature | 37 +++++++++++++++--------- src/Behat/Config/Config.php | 7 +++++ src/Behat/Config/Profile.php | 24 +++++++++++++++ tests/Behat/Tests/Config/ConfigTest.php | 22 ++++++++++++++ tests/Behat/Tests/Config/ProfileTest.php | 31 ++++++++++++++++++++ 6 files changed, 127 insertions(+), 19 deletions(-) create mode 100644 src/Behat/Config/Profile.php create mode 100644 tests/Behat/Tests/Config/ProfileTest.php diff --git a/features/extensions.feature b/features/extensions.feature index 113abd2f7..f28bf3a5f 100644 --- a/features/extensions.feature +++ b/features/extensions.feature @@ -4,13 +4,26 @@ Feature: Extensions I need to be able to write simple extensions Background: - Given a file named "behat.yml" with: + Given a file named "behat.php" with: """ - default: - extensions: - custom_extension.php: - param1: val1 - param2: val2 + [ + 'custom_extension.php' => [ + 'param1' => 'val1', + 'param2' => 'val2', + ], + ], + ]); + + $config = new Config(); + $config->withProfile($profile); + + return $config; """ And a file named "features/bootstrap/FeatureContext.php" with: """ diff --git a/features/profiles.feature b/features/profiles.feature index 6b726437b..7aec5bc72 100644 --- a/features/profiles.feature +++ b/features/profiles.feature @@ -80,21 +80,32 @@ Feature: Profiles progress: false pretty: ~ """ - And a file named "behat.yml" with: + And a file named "behat.php" with: """ - default: - formatters: - pretty: false - progress: ~ - - pretty_without_paths: - formatters: - progress: false - pretty: - paths: false + ['pretty.yml']]); + $config + ->withProfile(new Profile('default', [ + 'formatters' => [ + 'pretty' => false, + 'progress' => null, + ], + ])) + ->withProfile(new Profile('pretty_without_paths', [ + 'formatters' => [ + 'progress' => false, + 'pretty' => [ + 'paths' => false, + ], + ], + ])) + ; + + return $config; """ Scenario: diff --git a/src/Behat/Config/Config.php b/src/Behat/Config/Config.php index 3d2c378c5..0555b0d98 100644 --- a/src/Behat/Config/Config.php +++ b/src/Behat/Config/Config.php @@ -25,6 +25,13 @@ public function import(string|array $resource): self return $this; } + public function withProfile(Profile $profile): self + { + $this->settings[$profile->name()] = $profile->toArray(); + + return $this; + } + public function toArray(): array { return $this->settings; diff --git a/src/Behat/Config/Profile.php b/src/Behat/Config/Profile.php new file mode 100644 index 000000000..aa40402b2 --- /dev/null +++ b/src/Behat/Config/Profile.php @@ -0,0 +1,24 @@ +name; + } + + public function toArray(): array + { + return $this->settings; + } +} diff --git a/tests/Behat/Tests/Config/ConfigTest.php b/tests/Behat/Tests/Config/ConfigTest.php index 547288305..c49901384 100644 --- a/tests/Behat/Tests/Config/ConfigTest.php +++ b/tests/Behat/Tests/Config/ConfigTest.php @@ -1,8 +1,11 @@ toArray()); } + + public function testAddingProfile(): void + { + $config = new Config(); + + $config->withProfile(new Profile('default', [ + 'extensions' => [ + 'some_extension' => [], + ], + ])); + + $this->assertEquals([ + 'default' => [ + 'extensions' => [ + 'some_extension' => [], + ], + ], + ], $config->toArray()); + } } diff --git a/tests/Behat/Tests/Config/ProfileTest.php b/tests/Behat/Tests/Config/ProfileTest.php new file mode 100644 index 000000000..589f3ad5c --- /dev/null +++ b/tests/Behat/Tests/Config/ProfileTest.php @@ -0,0 +1,31 @@ +assertIsArray($profile->toArray()); + } + + public function testItReturnsSettings(): void + { + $settings = [ + 'extensions' => [ + 'some_extension' => [], + ], + ]; + + $profile = new Profile('default', $settings); + + $this->assertEquals($settings, $profile->toArray()); + } +} From 2b73d84ec0c5b821c3d1fa776ac6fbb5e8e9fc0b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lo=C3=AFc=20Fr=C3=A9mont?= Date: Mon, 2 Dec 2024 08:57:48 +0100 Subject: [PATCH 479/567] Check for existing key when adding a new profile --- src/Behat/Config/Config.php | 5 +++++ tests/Behat/Tests/Config/ConfigTest.php | 17 +++++++++++++++++ 2 files changed, 22 insertions(+) diff --git a/src/Behat/Config/Config.php b/src/Behat/Config/Config.php index 0555b0d98..c29f9f922 100644 --- a/src/Behat/Config/Config.php +++ b/src/Behat/Config/Config.php @@ -4,6 +4,7 @@ namespace Behat\Config; +use Behat\Testwork\ServiceContainer\Exception\ConfigurationLoadingException; use function is_string; final class Config implements ConfigInterface @@ -27,6 +28,10 @@ public function import(string|array $resource): self public function withProfile(Profile $profile): self { + if (array_key_exists($profile->name(), $this->settings)) { + throw new ConfigurationLoadingException(sprintf('The profile "%s" already exists.', $profile->name())); + } + $this->settings[$profile->name()] = $profile->toArray(); return $this; diff --git a/tests/Behat/Tests/Config/ConfigTest.php b/tests/Behat/Tests/Config/ConfigTest.php index c49901384..f758da243 100644 --- a/tests/Behat/Tests/Config/ConfigTest.php +++ b/tests/Behat/Tests/Config/ConfigTest.php @@ -6,6 +6,7 @@ use Behat\Config\Config; use Behat\Config\Profile; +use Behat\Testwork\ServiceContainer\Exception\ConfigurationLoadingException; use PHPUnit\Framework\TestCase; final class ConfigTest extends TestCase @@ -68,4 +69,20 @@ public function testAddingProfile(): void ], ], $config->toArray()); } + + public function testItThrowsAnExceptionWhenAddingExistingProfile(): void + { + $config = new Config(); + + $config->withProfile(new Profile('default')); + + $this->expectException(ConfigurationLoadingException::class); + $this->expectExceptionMessage('The profile "default" already exists.'); + + $config->withProfile(new Profile('default', [ + 'extensions' => [ + 'some_extension' => [], + ], + ])); + } } From 7fad656ed896051ff74c0b861410fa35995831b4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lo=C3=AFc=20Fr=C3=A9mont?= Date: Tue, 19 Nov 2024 17:37:13 +0100 Subject: [PATCH 480/567] Php config suites --- features/suite.feature | 20 +++++++---- src/Behat/Config/Profile.php | 13 +++++++ src/Behat/Config/Suite.php | 39 ++++++++++++++++++++ src/Behat/Config/SuiteConfigInterface.php | 12 +++++++ tests/Behat/Tests/Config/ProfileTest.php | 31 ++++++++++++++++ tests/Behat/Tests/Config/SuiteTest.php | 44 +++++++++++++++++++++++ 6 files changed, 152 insertions(+), 7 deletions(-) create mode 100644 src/Behat/Config/Suite.php create mode 100644 src/Behat/Config/SuiteConfigInterface.php create mode 100644 tests/Behat/Tests/Config/SuiteTest.php diff --git a/features/suite.feature b/features/suite.feature index e59919fb2..33611d731 100644 --- a/features/suite.feature +++ b/features/suite.feature @@ -48,14 +48,20 @@ Feature: Suites When I ate 1 apple Then I should have 2 apples """ - And a file named "behat.yml" with: + And a file named "behat.php" with: """ - default: - suites: - first: - contexts: [ FirstContext ] - second: - contexts: [ SecondContext ] + withSuite(new Suite('first', ['contexts' => ['FirstContext']])) + ->withSuite((new Suite('second'))->withContexts('SecondContext')) + ; + + return (new Config())->withProfile($profile); """ When I run "behat --no-colors -fpretty --format-settings='{\"paths\": true}' features" Then it should pass with: diff --git a/src/Behat/Config/Profile.php b/src/Behat/Config/Profile.php index aa40402b2..24d30db16 100644 --- a/src/Behat/Config/Profile.php +++ b/src/Behat/Config/Profile.php @@ -4,6 +4,8 @@ namespace Behat\Config; +use Behat\Testwork\ServiceContainer\Exception\ConfigurationLoadingException; + final class Profile { public function __construct( @@ -12,6 +14,17 @@ public function __construct( ) { } + public function withSuite(Suite $suite): self + { + if (array_key_exists($suite->name(), $this->settings['suites'] ?? [])) { + throw new ConfigurationLoadingException(sprintf('The suite "%s" already exists.', $suite->name())); + } + + $this->settings['suites'][$suite->name()] = $suite->toArray(); + + return $this; + } + public function name(): string { return $this->name; diff --git a/src/Behat/Config/Suite.php b/src/Behat/Config/Suite.php new file mode 100644 index 000000000..0f9acfe57 --- /dev/null +++ b/src/Behat/Config/Suite.php @@ -0,0 +1,39 @@ +settings['contexts'][] = $context; + } + + return $this; + } + + public function name(): string + { + return $this->name; + } + + public function profile(): ?string + { + return $this->profile; + } + + public function toArray(): array + { + return $this->settings; + } +} diff --git a/src/Behat/Config/SuiteConfigInterface.php b/src/Behat/Config/SuiteConfigInterface.php new file mode 100644 index 000000000..7dc995271 --- /dev/null +++ b/src/Behat/Config/SuiteConfigInterface.php @@ -0,0 +1,12 @@ +assertEquals($settings, $profile->toArray()); } + + public function testAddingSuites(): void + { + $profile = new Profile('default'); + $profile + ->withSuite(new Suite('admin_dashboard')) + ->withSuite(new Suite('managing_administrators')) + ; + + $this->assertEquals([ + 'suites' => [ + 'admin_dashboard' => [], + 'managing_administrators' => [], + ], + ], $profile->toArray()); + } + + public function testItThrowsAnExceptionWhenAddingExistingSuite(): void + { + $profile = new Profile('default'); + + $profile->withSuite(new Suite('admin_dashboard')); + + $this->expectException(ConfigurationLoadingException::class); + $this->expectExceptionMessage('The suite "admin_dashboard" already exists.'); + + $profile->withSuite(new Suite('admin_dashboard')); + } } diff --git a/tests/Behat/Tests/Config/SuiteTest.php b/tests/Behat/Tests/Config/SuiteTest.php new file mode 100644 index 000000000..a28fea8a6 --- /dev/null +++ b/tests/Behat/Tests/Config/SuiteTest.php @@ -0,0 +1,44 @@ +assertIsArray($suite->toArray()); + } + + public function testItReturnsSettings(): void + { + $settings = [ + 'contexts' => [ + 'FirstContext', + ], + ]; + + $suite = new Suite('first', $settings); + + $this->assertEquals($settings, $suite->toArray()); + } + + public function testAddingContexts(): void + { + $config = new Suite('first'); + $config->withContexts('FirstContext', 'SecondContext'); + $config->withContexts('ThirdContext'); + + $this->assertEquals([ + 'contexts' => [ + 'FirstContext', + 'SecondContext', + 'ThirdContext', + ] + ], $config->toArray()); + } +} From a7e8236fadb9e9fbdef2243b19200192ca2e55a9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lo=C3=AFc=20Fr=C3=A9mont?= Date: Mon, 2 Dec 2024 11:13:50 +0100 Subject: [PATCH 481/567] Adding 'withPaths' method --- features/suite.feature | 32 ++++++++++++++++------- src/Behat/Config/Suite.php | 13 +++++++-- src/Behat/Config/SuiteConfigInterface.php | 12 --------- tests/Behat/Tests/Config/SuiteTest.php | 15 +++++++++++ 4 files changed, 49 insertions(+), 23 deletions(-) delete mode 100644 src/Behat/Config/SuiteConfigInterface.php diff --git a/features/suite.feature b/features/suite.feature index 33611d731..6a28046d6 100644 --- a/features/suite.feature +++ b/features/suite.feature @@ -147,16 +147,30 @@ Feature: Suites When I ate 10 apple Then I should have 20 apples """ - And a file named "behat.yml" with: + And a file named "behat.php" with: """ - default: - suites: - first: - paths: [ '%paths.base%/features/first' ] - contexts: [ FirstContext ] - second: - paths: [ '%paths.base%/features/second' ] - contexts: [ SecondContext ] + withPaths('%paths.base%/features/first') + ->withContexts('FirstContext') + ; + + $secondSuite = (new Suite('second')) + ->withPaths('%paths.base%/features/second') + ->withContexts('SecondContext') + ; + + $profile = (new Profile('default')) + ->withSuite($firstSuite) + ->withSuite($secondSuite) + ; + + return (new Config())->withProfile($profile); """ When I run "behat --no-colors -fpretty --format-settings='{\"paths\": true}' features" Then it should pass with: diff --git a/src/Behat/Config/Suite.php b/src/Behat/Config/Suite.php index 0f9acfe57..8efbbb188 100644 --- a/src/Behat/Config/Suite.php +++ b/src/Behat/Config/Suite.php @@ -4,7 +4,7 @@ namespace Behat\Config; -final class Suite implements SuiteConfigInterface +final class Suite { public function __construct( private string $name, @@ -13,7 +13,7 @@ public function __construct( ) { } - public function withContexts(...$contexts): self + public function withContexts(string ...$contexts): self { foreach ($contexts as $context) { $this->settings['contexts'][] = $context; @@ -22,6 +22,15 @@ public function withContexts(...$contexts): self return $this; } + public function withPaths(string ...$paths): self + { + foreach ($paths as $path) { + $this->settings['paths'][] = $path; + } + + return $this; + } + public function name(): string { return $this->name; diff --git a/src/Behat/Config/SuiteConfigInterface.php b/src/Behat/Config/SuiteConfigInterface.php deleted file mode 100644 index 7dc995271..000000000 --- a/src/Behat/Config/SuiteConfigInterface.php +++ /dev/null @@ -1,12 +0,0 @@ -toArray()); } + + public function testAddingPaths(): void + { + $config = new Suite('first'); + $config->withPaths('features/admin/first', 'features/front/first'); + $config->withPaths('features/api/first'); + + $this->assertEquals([ + 'paths' => [ + 'features/admin/first', + 'features/front/first', + 'features/api/first', + ] + ], $config->toArray()); + } } From 0e6f06f53841de3f3b3585242810986f9aa3e0e8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lo=C3=AFc=20Fr=C3=A9mont?= Date: Mon, 2 Dec 2024 11:29:16 +0100 Subject: [PATCH 482/567] Allow context to be an array --- src/Behat/Config/Suite.php | 2 +- tests/Behat/Tests/Config/SuiteTest.php | 9 +++++++-- 2 files changed, 8 insertions(+), 3 deletions(-) diff --git a/src/Behat/Config/Suite.php b/src/Behat/Config/Suite.php index 8efbbb188..fa8fb9d9f 100644 --- a/src/Behat/Config/Suite.php +++ b/src/Behat/Config/Suite.php @@ -13,7 +13,7 @@ public function __construct( ) { } - public function withContexts(string ...$contexts): self + public function withContexts(string|array ...$contexts): self { foreach ($contexts as $context) { $this->settings['contexts'][] = $context; diff --git a/tests/Behat/Tests/Config/SuiteTest.php b/tests/Behat/Tests/Config/SuiteTest.php index 078ffc4dd..277c5e408 100644 --- a/tests/Behat/Tests/Config/SuiteTest.php +++ b/tests/Behat/Tests/Config/SuiteTest.php @@ -30,12 +30,17 @@ public function testItReturnsSettings(): void public function testAddingContexts(): void { $config = new Suite('first'); - $config->withContexts('FirstContext', 'SecondContext'); + $config->withContexts(['FirstContext' => ['http://localhost:8080', '/var/tmp']], 'SecondContext'); $config->withContexts('ThirdContext'); $this->assertEquals([ 'contexts' => [ - 'FirstContext', + [ + 'FirstContext' => [ + 'http://localhost:8080', + '/var/tmp' + ], + ], 'SecondContext', 'ThirdContext', ] From f61cc16bd946bc0542eea84708f77ad7100e4149 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lo=C3=AFc=20Fr=C3=A9mont?= Date: Mon, 2 Dec 2024 12:24:37 +0100 Subject: [PATCH 483/567] Add 'addContext' method on suite --- src/Behat/Config/Suite.php | 13 ++++++++++++- tests/Behat/Tests/Config/SuiteTest.php | 10 +++++----- 2 files changed, 17 insertions(+), 6 deletions(-) diff --git a/src/Behat/Config/Suite.php b/src/Behat/Config/Suite.php index fa8fb9d9f..f7d2d1067 100644 --- a/src/Behat/Config/Suite.php +++ b/src/Behat/Config/Suite.php @@ -13,7 +13,7 @@ public function __construct( ) { } - public function withContexts(string|array ...$contexts): self + public function withContexts(string ...$contexts): self { foreach ($contexts as $context) { $this->settings['contexts'][] = $context; @@ -22,6 +22,17 @@ public function withContexts(string|array ...$contexts): self return $this; } + /** + * @param array $constructorArgs + */ + + public function addContext(string $context, array $constructorArgs = []): self + { + $this->settings['contexts'][][$context] = $constructorArgs; + + return $this; + } + public function withPaths(string ...$paths): self { foreach ($paths as $path) { diff --git a/tests/Behat/Tests/Config/SuiteTest.php b/tests/Behat/Tests/Config/SuiteTest.php index 277c5e408..ee7d3f724 100644 --- a/tests/Behat/Tests/Config/SuiteTest.php +++ b/tests/Behat/Tests/Config/SuiteTest.php @@ -30,19 +30,19 @@ public function testItReturnsSettings(): void public function testAddingContexts(): void { $config = new Suite('first'); - $config->withContexts(['FirstContext' => ['http://localhost:8080', '/var/tmp']], 'SecondContext'); - $config->withContexts('ThirdContext'); + $config->withContexts('FirstContext', 'SecondContext'); + $config->addContext('ThirdContext', ['http://localhost:8080', '/var/tmp']); $this->assertEquals([ 'contexts' => [ + 'FirstContext', + 'SecondContext', [ - 'FirstContext' => [ + 'ThirdContext' => [ 'http://localhost:8080', '/var/tmp' ], ], - 'SecondContext', - 'ThirdContext', ] ], $config->toArray()); } From a5f9edc19f30bdd6185ae017fa7cb1e82ab65b36 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lo=C3=AFc=20Fr=C3=A9mont?= Date: Mon, 2 Dec 2024 12:39:11 +0100 Subject: [PATCH 484/567] Remove profile argument on suite --- src/Behat/Config/Suite.php | 6 ------ 1 file changed, 6 deletions(-) diff --git a/src/Behat/Config/Suite.php b/src/Behat/Config/Suite.php index f7d2d1067..d996ac8ea 100644 --- a/src/Behat/Config/Suite.php +++ b/src/Behat/Config/Suite.php @@ -9,7 +9,6 @@ final class Suite public function __construct( private string $name, private array $settings = [], - private string $profile = 'default', ) { } @@ -47,11 +46,6 @@ public function name(): string return $this->name; } - public function profile(): ?string - { - return $this->profile; - } - public function toArray(): array { return $this->settings; From 1daaf0d16f1737e07f3d17a8787a95899fe38c0a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lo=C3=AFc=20Fr=C3=A9mont?= Date: Mon, 2 Dec 2024 14:23:30 +0100 Subject: [PATCH 485/567] PHP Config extensions --- features/extensions.feature | 15 +++++----- src/Behat/Config/Extension.php | 24 ++++++++++++++++ src/Behat/Config/ExtensionConfigInterface.php | 10 +++++++ src/Behat/Config/Profile.php | 7 +++++ tests/Behat/Tests/Config/ExtensionTest.php | 28 +++++++++++++++++++ tests/Behat/Tests/Config/ProfileTest.php | 20 ++++++++++++- 6 files changed, 95 insertions(+), 9 deletions(-) create mode 100644 src/Behat/Config/Extension.php create mode 100644 src/Behat/Config/ExtensionConfigInterface.php create mode 100644 tests/Behat/Tests/Config/ExtensionTest.php diff --git a/features/extensions.feature b/features/extensions.feature index f28bf3a5f..691c9dbef 100644 --- a/features/extensions.feature +++ b/features/extensions.feature @@ -9,16 +9,15 @@ Feature: Extensions [ - 'custom_extension.php' => [ - 'param1' => 'val1', - 'param2' => 'val2', - ], - ], - ]); + $profile = (new Profile('default')) + ->withExtension(new Extension('custom_extension.php', [ + 'param1' => 'val1', + 'param2' => 'val2', + ]) + ); $config = new Config(); $config->withProfile($profile); diff --git a/src/Behat/Config/Extension.php b/src/Behat/Config/Extension.php new file mode 100644 index 000000000..1ae4c10fa --- /dev/null +++ b/src/Behat/Config/Extension.php @@ -0,0 +1,24 @@ +name; + } + + public function toArray(): array + { + return $this->settings; + } +} diff --git a/src/Behat/Config/ExtensionConfigInterface.php b/src/Behat/Config/ExtensionConfigInterface.php new file mode 100644 index 000000000..ba008375f --- /dev/null +++ b/src/Behat/Config/ExtensionConfigInterface.php @@ -0,0 +1,10 @@ +name; } + public function withExtension(ExtensionConfigInterface $extension): self + { + $this->settings['extensions'][$extension->name()] = $extension->toArray(); + + return $this; + } + public function toArray(): array { return $this->settings; diff --git a/tests/Behat/Tests/Config/ExtensionTest.php b/tests/Behat/Tests/Config/ExtensionTest.php new file mode 100644 index 000000000..6b867ae02 --- /dev/null +++ b/tests/Behat/Tests/Config/ExtensionTest.php @@ -0,0 +1,28 @@ +assertIsArray($extension->toArray()); + } + + public function testItReturnsSettings(): void + { + $settings = [ + 'base_url' => 'https://127.0.0.1:8080', + ]; + + $extension = new Extension('Behat\MinkExtension', $settings); + + $this->assertEquals($settings, $extension->toArray()); + } +} diff --git a/tests/Behat/Tests/Config/ProfileTest.php b/tests/Behat/Tests/Config/ProfileTest.php index fdad7bd85..b1effb6ae 100644 --- a/tests/Behat/Tests/Config/ProfileTest.php +++ b/tests/Behat/Tests/Config/ProfileTest.php @@ -4,7 +4,7 @@ namespace Behat\Tests\Config; -use Behat\Config\Config; +use Behat\Config\Extension; use Behat\Config\Profile; use Behat\Config\Suite; use Behat\Testwork\ServiceContainer\Exception\ConfigurationLoadingException; @@ -32,6 +32,24 @@ public function testItReturnsSettings(): void $this->assertEquals($settings, $profile->toArray()); } + public function testAddingExtensions(): void + { + $profile = new Profile('default'); + $profile->withExtension(new Extension('Behat\MinkExtension', ['base_url' => 'https://127.0.0.1:8080'])); + $profile->withExtension(new Extension('FriendsOfBehat\MinkDebugExtension', ['directory' => 'etc/build'])); + + $this->assertEquals([ + 'extensions' => [ + 'Behat\MinkExtension' => [ + 'base_url' => 'https://127.0.0.1:8080', + ], + 'FriendsOfBehat\MinkDebugExtension' => [ + 'directory' => 'etc/build', + ], + ], + ], $profile->toArray()); + } + public function testAddingSuites(): void { $profile = new Profile('default'); From 71e2e36c8e71e4498aa32c6fa96c8beb2464dd25 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lo=C3=AFc=20Fr=C3=A9mont?= Date: Mon, 2 Dec 2024 16:51:43 +0100 Subject: [PATCH 486/567] Prevent adding the same extension to the profile --- src/Behat/Config/Profile.php | 4 ++++ tests/Behat/Tests/Config/ProfileTest.php | 12 ++++++++++++ 2 files changed, 16 insertions(+) diff --git a/src/Behat/Config/Profile.php b/src/Behat/Config/Profile.php index 8753f0719..6a92e78eb 100644 --- a/src/Behat/Config/Profile.php +++ b/src/Behat/Config/Profile.php @@ -32,6 +32,10 @@ public function name(): string public function withExtension(ExtensionConfigInterface $extension): self { + if (array_key_exists($extension->name(), $this->settings['extensions'] ?? [])) { + throw new ConfigurationLoadingException(sprintf('The extension "%s" already exists.', $extension->name())); + } + $this->settings['extensions'][$extension->name()] = $extension->toArray(); return $this; diff --git a/tests/Behat/Tests/Config/ProfileTest.php b/tests/Behat/Tests/Config/ProfileTest.php index b1effb6ae..a71a9b23a 100644 --- a/tests/Behat/Tests/Config/ProfileTest.php +++ b/tests/Behat/Tests/Config/ProfileTest.php @@ -50,6 +50,18 @@ public function testAddingExtensions(): void ], $profile->toArray()); } + public function testItThrowsAnExceptionWhenAddingExistingExtension(): void + { + $profile = new Profile('default'); + + $profile->withExtension(new Extension('custom_extension')); + + $this->expectException(ConfigurationLoadingException::class); + $this->expectExceptionMessage('The extension "custom_extension" already exists.'); + + $profile->withExtension(new Extension('custom_extension')); + } + public function testAddingSuites(): void { $profile = new Profile('default'); From de2cde7bf787d484fc8c0a3ed347423668336ebe Mon Sep 17 00:00:00 2001 From: Carlos Granados Date: Fri, 29 Nov 2024 08:56:23 +0100 Subject: [PATCH 487/567] dx: add composer scripts for testing tools --- CONTRIBUTING.md | 7 +++++-- composer.json | 18 +++++++++++++++--- 2 files changed, 20 insertions(+), 5 deletions(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index da623b886..1eefade93 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -58,8 +58,11 @@ You can read detailed guidance on what BC means in [Symfony2 BC guide](http://sy ## Running tests Make sure that you don't break anything with your changes by running the test -suite with your locale set to english: +suite with this command: ```bash -$> LANG=C bin/behat --format=progress +composer all-tests ``` + +This will run all the Behat tests, all the PHPUnit tests and Psalm. If the tests find any issues, +you can run these tools individually by running `composer behat`, `composer phpunit` or `composer psalm`. diff --git a/composer.json b/composer.json index dc4a9db21..c0fbafb9f 100644 --- a/composer.json +++ b/composer.json @@ -19,13 +19,13 @@ "behat/gherkin": "^4.10.0", "behat/transliterator": "^1.5", "composer-runtime-api": "^2.2", - "symfony/console": "^5.4 || ^6.4 || ^7.0", + "psr/container": "^1.0 || ^2.0", "symfony/config": "^5.4 || ^6.4 || ^7.0", + "symfony/console": "^5.4 || ^6.4 || ^7.0", "symfony/dependency-injection": "^5.4 || ^6.4 || ^7.0", "symfony/event-dispatcher": "^5.4 || ^6.4 || ^7.0", "symfony/translation": "^5.4 || ^6.4 || ^7.0", - "symfony/yaml": "^5.4 || ^6.4 || ^7.0", - "psr/container": "^1.0 || ^2.0" + "symfony/yaml": "^5.4 || ^6.4 || ^7.0" }, "require-dev": { @@ -64,5 +64,17 @@ } }, + "scripts": { + "all-tests": [ + "@behat-progress", + "@phpunit", + "@psalm" + ], + "behat": "LANG=C bin/behat", + "behat-progress": "LANG=C bin/behat --format=progress", + "phpunit": "phpunit", + "psalm": "psalm" + }, + "bin": ["bin/behat"] } From 8d174d6e397ed2ac85a0f886c03a99dc06e4d8f1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lo=C3=AFc=20Fr=C3=A9mont?= Date: Tue, 3 Dec 2024 12:41:48 +0100 Subject: [PATCH 488/567] PHP Config - Add Gherkin filters --- features/profile_filters.feature | 74 +++++++++++++------ .../Config/Gherkin/Filter/FilterInterface.php | 12 +++ .../Config/Gherkin/Filter/NameFilter.php | 23 ++++++ .../Config/Gherkin/Filter/NarrativeFilter.php | 23 ++++++ .../Config/Gherkin/Filter/RoleFilter.php | 23 ++++++ src/Behat/Config/Gherkin/Filter/TagFilter.php | 23 ++++++ src/Behat/Config/Gherkin/SimpleFilter.php | 26 +++++++ src/Behat/Config/Profile.php | 12 +++ tests/Behat/Tests/Config/ProfileTest.php | 32 ++++++++ 9 files changed, 227 insertions(+), 21 deletions(-) create mode 100644 src/Behat/Config/Gherkin/Filter/FilterInterface.php create mode 100644 src/Behat/Config/Gherkin/Filter/NameFilter.php create mode 100644 src/Behat/Config/Gherkin/Filter/NarrativeFilter.php create mode 100644 src/Behat/Config/Gherkin/Filter/RoleFilter.php create mode 100644 src/Behat/Config/Gherkin/Filter/TagFilter.php create mode 100644 src/Behat/Config/Gherkin/SimpleFilter.php diff --git a/features/profile_filters.feature b/features/profile_filters.feature index d042f0442..aa4439bcf 100644 --- a/features/profile_filters.feature +++ b/features/profile_filters.feature @@ -84,12 +84,20 @@ Feature: Filters """ Scenario: Tag filters - Given a file named "behat.yml" with: + Given a file named "behat.php" with: """ - default: - gherkin: - filters: - tags: tag2 + withProfile( + (new Profile('default')) + ->withFilter(new TagFilter('tag2')) + ) + ; """ When I run "behat --no-colors -f pretty" Then it should pass with: @@ -131,12 +139,20 @@ Feature: Filters """ Scenario: Role filters - Given a file named "behat.yml" with: + Given a file named "behat.php" with: """ - default: - gherkin: - filters: - role: second user + withProfile( + (new Profile('default')) + ->withFilter(new RoleFilter('second user')) + ) + ; """ When I run "behat --no-colors -f pretty" Then it should pass with: @@ -161,13 +177,21 @@ Feature: Filters 5 steps (5 passed) """ - Scenario: Narrative Filter - Given a file named "behat.yml" with: + Scenario: Narrative filters + Given a file named "behat.php" with: """ - default: - gherkin: - filters: - narrative: /As a (?:second|third) user/ + withProfile( + (new Profile('default')) + ->withFilter(new NarrativeFilter('/As a (?:second|third) user/')) + ) + ; """ When I run "behat --no-colors -f pretty" Then it should pass with: @@ -209,12 +233,20 @@ Feature: Filters """ Scenario: Name filters - Given a file named "behat.yml" with: + Given a file named "behat.php" with: """ - default: - gherkin: - filters: - name: simple feature + withProfile( + (new Profile('default')) + ->withFilter(new NameFilter('simple feature')) + ) + ; """ When I run "behat --no-colors -f pretty" Then it should pass with: diff --git a/src/Behat/Config/Gherkin/Filter/FilterInterface.php b/src/Behat/Config/Gherkin/Filter/FilterInterface.php new file mode 100644 index 000000000..923480e37 --- /dev/null +++ b/src/Behat/Config/Gherkin/Filter/FilterInterface.php @@ -0,0 +1,12 @@ +value; + } +} diff --git a/src/Behat/Config/Gherkin/Filter/NarrativeFilter.php b/src/Behat/Config/Gherkin/Filter/NarrativeFilter.php new file mode 100644 index 000000000..60263cdc7 --- /dev/null +++ b/src/Behat/Config/Gherkin/Filter/NarrativeFilter.php @@ -0,0 +1,23 @@ +value; + } +} diff --git a/src/Behat/Config/Gherkin/Filter/RoleFilter.php b/src/Behat/Config/Gherkin/Filter/RoleFilter.php new file mode 100644 index 000000000..72e3d0a5b --- /dev/null +++ b/src/Behat/Config/Gherkin/Filter/RoleFilter.php @@ -0,0 +1,23 @@ +value; + } +} diff --git a/src/Behat/Config/Gherkin/Filter/TagFilter.php b/src/Behat/Config/Gherkin/Filter/TagFilter.php new file mode 100644 index 000000000..2c968686d --- /dev/null +++ b/src/Behat/Config/Gherkin/Filter/TagFilter.php @@ -0,0 +1,23 @@ +value; + } +} diff --git a/src/Behat/Config/Gherkin/SimpleFilter.php b/src/Behat/Config/Gherkin/SimpleFilter.php new file mode 100644 index 000000000..6f52445c0 --- /dev/null +++ b/src/Behat/Config/Gherkin/SimpleFilter.php @@ -0,0 +1,26 @@ +name; + } + + public function value(): string + { + return $this->value; + } +} diff --git a/src/Behat/Config/Profile.php b/src/Behat/Config/Profile.php index 6a92e78eb..9482b900f 100644 --- a/src/Behat/Config/Profile.php +++ b/src/Behat/Config/Profile.php @@ -4,6 +4,7 @@ namespace Behat\Config; +use Behat\Config\Gherkin\Filter\FilterInterface; use Behat\Testwork\ServiceContainer\Exception\ConfigurationLoadingException; final class Profile @@ -41,6 +42,17 @@ public function withExtension(ExtensionConfigInterface $extension): self return $this; } + public function withFilter(FilterInterface $filter): self + { + if (array_key_exists($filter->name(), $this->settings['gherkin']['filters'] ?? [])) { + throw new ConfigurationLoadingException(sprintf('The filter "%s" already exists.', $filter->name())); + } + + $this->settings['gherkin']['filters'][$filter->name()] = $filter->value(); + + return $this; + } + public function toArray(): array { return $this->settings; diff --git a/tests/Behat/Tests/Config/ProfileTest.php b/tests/Behat/Tests/Config/ProfileTest.php index a71a9b23a..476c232bd 100644 --- a/tests/Behat/Tests/Config/ProfileTest.php +++ b/tests/Behat/Tests/Config/ProfileTest.php @@ -5,6 +5,8 @@ namespace Behat\Tests\Config; use Behat\Config\Extension; +use Behat\Config\Gherkin\Filter\NameFilter; +use Behat\Config\Gherkin\Filter\TagFilter; use Behat\Config\Profile; use Behat\Config\Suite; use Behat\Testwork\ServiceContainer\Exception\ConfigurationLoadingException; @@ -89,4 +91,34 @@ public function testItThrowsAnExceptionWhenAddingExistingSuite(): void $profile->withSuite(new Suite('admin_dashboard')); } + + public function testAddingFilters(): void + { + $profile = new Profile('default'); + $profile + ->withFilter(new TagFilter('admin')) + ->withFilter(new NameFilter('Managing administrators')) + ; + + $this->assertEquals([ + 'gherkin' => [ + 'filters' => [ + 'tags' => 'admin', + 'name' => 'Managing administrators', + ], + ], + ], $profile->toArray()); + } + + public function testItThrowsAnExceptionWhenAddingExistingFilter(): void + { + $profile = new Profile('default'); + + $profile->withFilter(new TagFilter('tag1')); + + $this->expectException(ConfigurationLoadingException::class); + $this->expectExceptionMessage('The filter "tags" already exists.'); + + $profile->withFilter(new TagFilter('tag1')); + } } From 0bbbdcfd46fc011227ecdcdb0e74235646887d6e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lo=C3=AFc=20Fr=C3=A9mont?= Date: Wed, 4 Dec 2024 10:45:07 +0100 Subject: [PATCH 489/567] Remove Gherkin namespace --- features/profile_filters.feature | 8 +++--- .../{Gherkin => }/Filter/FilterInterface.php | 2 +- .../{Gherkin => }/Filter/NameFilter.php | 2 +- .../{Gherkin => }/Filter/NarrativeFilter.php | 2 +- .../{Gherkin => }/Filter/RoleFilter.php | 2 +- .../Config/{Gherkin => }/Filter/TagFilter.php | 2 +- src/Behat/Config/Gherkin/SimpleFilter.php | 26 ------------------- src/Behat/Config/Profile.php | 2 +- tests/Behat/Tests/Config/ProfileTest.php | 4 +-- 9 files changed, 12 insertions(+), 38 deletions(-) rename src/Behat/Config/{Gherkin => }/Filter/FilterInterface.php (77%) rename src/Behat/Config/{Gherkin => }/Filter/NameFilter.php (89%) rename src/Behat/Config/{Gherkin => }/Filter/NarrativeFilter.php (89%) rename src/Behat/Config/{Gherkin => }/Filter/RoleFilter.php (89%) rename src/Behat/Config/{Gherkin => }/Filter/TagFilter.php (89%) delete mode 100644 src/Behat/Config/Gherkin/SimpleFilter.php diff --git a/features/profile_filters.feature b/features/profile_filters.feature index aa4439bcf..400f0e521 100644 --- a/features/profile_filters.feature +++ b/features/profile_filters.feature @@ -90,7 +90,7 @@ Feature: Filters use Behat\Config\Config; use Behat\Config\Profile; - use Behat\Config\Gherkin\Filter\TagFilter; + use Behat\Config\Filter\TagFilter; return (new Config()) ->withProfile( @@ -145,7 +145,7 @@ Feature: Filters use Behat\Config\Config; use Behat\Config\Profile; - use Behat\Config\Gherkin\Filter\RoleFilter; + use Behat\Config\Filter\RoleFilter; return (new Config()) ->withProfile( @@ -184,7 +184,7 @@ Feature: Filters use Behat\Config\Config; use Behat\Config\Profile; - use Behat\Config\Gherkin\Filter\NarrativeFilter; + use Behat\Config\Filter\NarrativeFilter; return (new Config()) ->withProfile( @@ -239,7 +239,7 @@ Feature: Filters use Behat\Config\Config; use Behat\Config\Profile; - use Behat\Config\Gherkin\Filter\NameFilter; + use Behat\Config\Filter\NameFilter; return (new Config()) ->withProfile( diff --git a/src/Behat/Config/Gherkin/Filter/FilterInterface.php b/src/Behat/Config/Filter/FilterInterface.php similarity index 77% rename from src/Behat/Config/Gherkin/Filter/FilterInterface.php rename to src/Behat/Config/Filter/FilterInterface.php index 923480e37..63f3836d4 100644 --- a/src/Behat/Config/Gherkin/Filter/FilterInterface.php +++ b/src/Behat/Config/Filter/FilterInterface.php @@ -2,7 +2,7 @@ declare(strict_types=1); -namespace Behat\Config\Gherkin\Filter; +namespace Behat\Config\Filter; interface FilterInterface { diff --git a/src/Behat/Config/Gherkin/Filter/NameFilter.php b/src/Behat/Config/Filter/NameFilter.php similarity index 89% rename from src/Behat/Config/Gherkin/Filter/NameFilter.php rename to src/Behat/Config/Filter/NameFilter.php index 9a318e0bf..fa4f2ae5c 100644 --- a/src/Behat/Config/Gherkin/Filter/NameFilter.php +++ b/src/Behat/Config/Filter/NameFilter.php @@ -2,7 +2,7 @@ declare(strict_types=1); -namespace Behat\Config\Gherkin\Filter; +namespace Behat\Config\Filter; final class NameFilter implements FilterInterface { diff --git a/src/Behat/Config/Gherkin/Filter/NarrativeFilter.php b/src/Behat/Config/Filter/NarrativeFilter.php similarity index 89% rename from src/Behat/Config/Gherkin/Filter/NarrativeFilter.php rename to src/Behat/Config/Filter/NarrativeFilter.php index 60263cdc7..07ccc0f01 100644 --- a/src/Behat/Config/Gherkin/Filter/NarrativeFilter.php +++ b/src/Behat/Config/Filter/NarrativeFilter.php @@ -2,7 +2,7 @@ declare(strict_types=1); -namespace Behat\Config\Gherkin\Filter; +namespace Behat\Config\Filter; final class NarrativeFilter implements FilterInterface { diff --git a/src/Behat/Config/Gherkin/Filter/RoleFilter.php b/src/Behat/Config/Filter/RoleFilter.php similarity index 89% rename from src/Behat/Config/Gherkin/Filter/RoleFilter.php rename to src/Behat/Config/Filter/RoleFilter.php index 72e3d0a5b..121358d55 100644 --- a/src/Behat/Config/Gherkin/Filter/RoleFilter.php +++ b/src/Behat/Config/Filter/RoleFilter.php @@ -2,7 +2,7 @@ declare(strict_types=1); -namespace Behat\Config\Gherkin\Filter; +namespace Behat\Config\Filter; final class RoleFilter implements FilterInterface { diff --git a/src/Behat/Config/Gherkin/Filter/TagFilter.php b/src/Behat/Config/Filter/TagFilter.php similarity index 89% rename from src/Behat/Config/Gherkin/Filter/TagFilter.php rename to src/Behat/Config/Filter/TagFilter.php index 2c968686d..606580a44 100644 --- a/src/Behat/Config/Gherkin/Filter/TagFilter.php +++ b/src/Behat/Config/Filter/TagFilter.php @@ -2,7 +2,7 @@ declare(strict_types=1); -namespace Behat\Config\Gherkin\Filter; +namespace Behat\Config\Filter; final class TagFilter implements FilterInterface { diff --git a/src/Behat/Config/Gherkin/SimpleFilter.php b/src/Behat/Config/Gherkin/SimpleFilter.php deleted file mode 100644 index 6f52445c0..000000000 --- a/src/Behat/Config/Gherkin/SimpleFilter.php +++ /dev/null @@ -1,26 +0,0 @@ -name; - } - - public function value(): string - { - return $this->value; - } -} diff --git a/src/Behat/Config/Profile.php b/src/Behat/Config/Profile.php index 9482b900f..ebc434f6f 100644 --- a/src/Behat/Config/Profile.php +++ b/src/Behat/Config/Profile.php @@ -4,7 +4,7 @@ namespace Behat\Config; -use Behat\Config\Gherkin\Filter\FilterInterface; +use Behat\Config\Filter\FilterInterface; use Behat\Testwork\ServiceContainer\Exception\ConfigurationLoadingException; final class Profile diff --git a/tests/Behat/Tests/Config/ProfileTest.php b/tests/Behat/Tests/Config/ProfileTest.php index 476c232bd..296ab8539 100644 --- a/tests/Behat/Tests/Config/ProfileTest.php +++ b/tests/Behat/Tests/Config/ProfileTest.php @@ -5,8 +5,8 @@ namespace Behat\Tests\Config; use Behat\Config\Extension; -use Behat\Config\Gherkin\Filter\NameFilter; -use Behat\Config\Gherkin\Filter\TagFilter; +use Behat\Config\Filter\NameFilter; +use Behat\Config\Filter\TagFilter; use Behat\Config\Profile; use Behat\Config\Suite; use Behat\Testwork\ServiceContainer\Exception\ConfigurationLoadingException; From e55b5fafa2faddb7e1be0812a6a95e65070feb4e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lo=C3=AFc=20Fr=C3=A9mont?= Date: Wed, 4 Dec 2024 10:45:50 +0100 Subject: [PATCH 490/567] Restrict value from filter interface to be a string --- src/Behat/Config/Filter/FilterInterface.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Behat/Config/Filter/FilterInterface.php b/src/Behat/Config/Filter/FilterInterface.php index 63f3836d4..7fbc3b233 100644 --- a/src/Behat/Config/Filter/FilterInterface.php +++ b/src/Behat/Config/Filter/FilterInterface.php @@ -8,5 +8,5 @@ interface FilterInterface { public function name(): string; - public function value(): mixed; + public function value(): string; } From ab10d18c5338aa1d445623936eefa19b6fc273c3 Mon Sep 17 00:00:00 2001 From: Carlos Granados Date: Wed, 4 Dec 2024 12:08:59 +0100 Subject: [PATCH 491/567] Add rerun option to behat script --- composer.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/composer.json b/composer.json index c0fbafb9f..4e157d73f 100644 --- a/composer.json +++ b/composer.json @@ -70,7 +70,7 @@ "@phpunit", "@psalm" ], - "behat": "LANG=C bin/behat", + "behat": "LANG=C bin/behat --rerun", "behat-progress": "LANG=C bin/behat --format=progress", "phpunit": "phpunit", "psalm": "psalm" From d65f4ebea281ace0a68f0fda6fd3273f7a6653b6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lo=C3=AFc=20Fr=C3=A9mont?= Date: Wed, 4 Dec 2024 14:44:43 +0100 Subject: [PATCH 492/567] PHP Config - suite filters --- features/suite.feature | 99 ++++++++++++++-------- src/Behat/Config/Suite.php | 14 +++ tests/Behat/Tests/Config/ExtensionTest.php | 2 + tests/Behat/Tests/Config/SuiteTest.php | 18 ++++ 4 files changed, 100 insertions(+), 33 deletions(-) diff --git a/features/suite.feature b/features/suite.feature index 6a28046d6..5dc47b868 100644 --- a/features/suite.feature +++ b/features/suite.feature @@ -330,18 +330,29 @@ Feature: Suites When I ate 10 apple Then I should have 5 apples """ - And a file named "behat.yml" with: + And a file named "behat.php" with: """ - default: - suites: - little_kid: - contexts: [ LittleKidContext ] - filters: - role: little kid - big_brother: - contexts: [ BigBrotherContext ] - filters: - role: big brother + withSuite( + (new Suite('little_kid')) + ->withContexts(LittleKidContext::class) + ->withFilter(new RoleFilter('little kid')) + ) + ->withSuite( + (new Suite('big_brother')) + ->withContexts(BigBrotherContext::class) + ->withFilter(new RoleFilter('big brother')) + ) + ; + + return (new Config())->withProfile($profile); """ When I run "behat --no-colors -fpretty --format-settings='{\"paths\": true}' features" Then it should pass with: @@ -427,18 +438,29 @@ Feature: Suites When I ate 10 apple Then I should have 5 apples """ - And a file named "behat.yml" with: + And a file named "behat.php" with: """ - default: - suites: - little_kid: - contexts: [ LittleKidContext ] - filters: - narrative: '/As a little kid/' - big_brother: - contexts: [ BigBrotherContext ] - filters: - narrative: '/As a big brother/' + withSuite( + (new Suite('little_kid')) + ->withContexts(LittleKidContext::class) + ->withFilter(new NarrativeFilter('/As a little kid/')) + ) + ->withSuite( + (new Suite('big_brother')) + ->withContexts(BigBrotherContext::class) + ->withFilter(new NarrativeFilter('/As a big brother/')) + ) + ; + + return (new Config())->withProfile($profile); """ When I run "behat --no-colors -fpretty --format-settings='{\"paths\": true}' features" Then it should pass with: @@ -524,18 +546,29 @@ Feature: Suites When I ate 10 apple Then I should have 5 apples """ - And a file named "behat.yml" with: + And a file named "behat.php" with: """ - default: - suites: - little_kid: - contexts: [ LittleKidContext ] - filters: - role: little kid - big_brother: - contexts: [ BigBrotherContext ] - filters: - role: big brother + withSuite( + (new Suite('little_kid')) + ->withContexts(LittleKidContext::class) + ->withFilter(new RoleFilter('little kid')) + ) + ->withSuite( + (new Suite('big_brother')) + ->withContexts(BigBrotherContext::class) + ->withFilter(new RoleFilter('big brother')) + ) + ; + + return (new Config())->withProfile($profile); """ When I run "behat --no-colors -s big_brother -fpretty --format-settings='{\"paths\": true}' features" Then it should pass with: diff --git a/src/Behat/Config/Suite.php b/src/Behat/Config/Suite.php index d996ac8ea..918429db5 100644 --- a/src/Behat/Config/Suite.php +++ b/src/Behat/Config/Suite.php @@ -4,6 +4,9 @@ namespace Behat\Config; +use Behat\Config\Filter\FilterInterface; +use Behat\Testwork\ServiceContainer\Exception\ConfigurationLoadingException; + final class Suite { public function __construct( @@ -41,6 +44,17 @@ public function withPaths(string ...$paths): self return $this; } + public function withFilter(FilterInterface $filter): self + { + if (array_key_exists($filter->name(), $this->settings['filters'] ?? [])) { + throw new ConfigurationLoadingException(sprintf('The filter "%s" already exists.', $filter->name())); + } + + $this->settings['filters'][$filter->name()] = $filter->value(); + + return $this; + } + public function name(): string { return $this->name; diff --git a/tests/Behat/Tests/Config/ExtensionTest.php b/tests/Behat/Tests/Config/ExtensionTest.php index 6b867ae02..6518dee3a 100644 --- a/tests/Behat/Tests/Config/ExtensionTest.php +++ b/tests/Behat/Tests/Config/ExtensionTest.php @@ -1,5 +1,7 @@ toArray()); } + + public function testAddingFilters(): void + { + $config = new Suite('first'); + $config->withFilter(new TagFilter('tag1')); + $config->withFilter(new NameFilter('name1')); + + $this->assertEquals([ + 'filters' => [ + 'tags' => 'tag1', + 'name' => 'name1', + ] + ], $config->toArray()); + } } From 487d815e89f92fc772234b08307a4d17999c3103 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lo=C3=AFc=20Fr=C3=A9mont?= Date: Wed, 4 Dec 2024 15:11:55 +0100 Subject: [PATCH 493/567] Add missing test --- tests/Behat/Tests/Config/SuiteTest.php | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/tests/Behat/Tests/Config/SuiteTest.php b/tests/Behat/Tests/Config/SuiteTest.php index 8f7eb2918..06b72b790 100644 --- a/tests/Behat/Tests/Config/SuiteTest.php +++ b/tests/Behat/Tests/Config/SuiteTest.php @@ -7,6 +7,7 @@ use Behat\Config\Filter\NameFilter; use Behat\Config\Filter\TagFilter; use Behat\Config\Suite; +use Behat\Testwork\ServiceContainer\Exception\ConfigurationLoadingException; use PHPUnit\Framework\TestCase; final class SuiteTest extends TestCase @@ -79,4 +80,16 @@ public function testAddingFilters(): void ] ], $config->toArray()); } + + public function testItThrowsAnExceptionWhenAddingExistingFilter(): void + { + $suite = new Suite('first'); + + $suite->withFilter(new TagFilter('tag1')); + + $this->expectException(ConfigurationLoadingException::class); + $this->expectExceptionMessage('The filter "tags" already exists.'); + + $suite->withFilter(new TagFilter('tag1')); + } } From 94cfa9a8437a00cf23ee4081f7c8ffb68809ea56 Mon Sep 17 00:00:00 2001 From: Carlos Granados Date: Fri, 6 Dec 2024 09:39:29 +0100 Subject: [PATCH 494/567] fix: allow using the narrative filter on the command line --- features/narrative_filters.feature | 63 +++++++++++++++++++ features/role_filters.feature | 63 +++++++++++++++++++ .../Behat/Gherkin/Cli/FilterController.php | 19 ++++-- .../Specification/LazyFeatureIterator.php | 2 +- 4 files changed, 142 insertions(+), 5 deletions(-) create mode 100644 features/narrative_filters.feature create mode 100644 features/role_filters.feature diff --git a/features/narrative_filters.feature b/features/narrative_filters.feature new file mode 100644 index 000000000..bae1caaba --- /dev/null +++ b/features/narrative_filters.feature @@ -0,0 +1,63 @@ +Feature: Narrative filters + In order to run only needed features + As a Behat user + I need Behat to support features filtering based on a regex filter on the narrative + + Scenario: Brothers + Given a file named "features/bootstrap/FeatureContext.php" with: + """ + addOption( '--name', null, InputOption::VALUE_REQUIRED | InputOption::VALUE_IS_ARRAY, - "Only executeCall the feature elements which match part" . PHP_EOL . + "Only execute the feature elements which match part" . PHP_EOL . "of the given name or regex." ) ->addOption( '--tags', null, InputOption::VALUE_REQUIRED | InputOption::VALUE_IS_ARRAY, - "Only executeCall the features or scenarios with tags" . PHP_EOL . + "Only execute the features or scenarios with tags" . PHP_EOL . "matching tag filter expression." ) ->addOption( '--role', null, InputOption::VALUE_REQUIRED, - "Only executeCall the features with actor role matching" . PHP_EOL . + "Only execute the features with actor role matching" . PHP_EOL . "a wildcard." - ); + ) + ->addOption( + '--narrative', null, InputOption::VALUE_REQUIRED, + "Only execute the features with actor description" . PHP_EOL . + "matching a regex." + ) + ; } /** @@ -91,6 +98,10 @@ public function execute(InputInterface $input, OutputInterface $output) $filters[] = new RoleFilter($role); } + if ($narrative = $input->getOption('narrative')) { + $filters[] = new NarrativeFilter($narrative); + } + if (count($filters)) { $this->gherkin->setFilters($filters); } diff --git a/src/Behat/Behat/Gherkin/Specification/LazyFeatureIterator.php b/src/Behat/Behat/Gherkin/Specification/LazyFeatureIterator.php index 1883a0c6b..b205ebea0 100644 --- a/src/Behat/Behat/Gherkin/Specification/LazyFeatureIterator.php +++ b/src/Behat/Behat/Gherkin/Specification/LazyFeatureIterator.php @@ -176,7 +176,7 @@ private function createFilter($type, $filterString, Suite $suite) '`%s` filter is not supported by the `%s` suite. Supported types are `%s`.', $type, $suite->getName(), - implode('`, `', array('role', 'name', 'tags')) + implode('`, `', array('narrative', 'role', 'name', 'tags')) ), $suite->getName()); } From ec1caaa2c9910d1b5d6d7c2b1eef3b238c764926 Mon Sep 17 00:00:00 2001 From: Carlos Granados Date: Sun, 8 Dec 2024 20:28:21 +0100 Subject: [PATCH 495/567] DX: disable Xdebug by default and provide a CLI option to activate it --- composer.json | 1 + src/Behat/Testwork/Cli/Application.php | 10 ++++++++++ 2 files changed, 11 insertions(+) diff --git a/composer.json b/composer.json index 4e157d73f..0e1a72ebb 100644 --- a/composer.json +++ b/composer.json @@ -19,6 +19,7 @@ "behat/gherkin": "^4.10.0", "behat/transliterator": "^1.5", "composer-runtime-api": "^2.2", + "composer/xdebug-handler": "^3.0", "psr/container": "^1.0 || ^2.0", "symfony/config": "^5.4 || ^6.4 || ^7.0", "symfony/console": "^5.4 || ^6.4 || ^7.0", diff --git a/src/Behat/Testwork/Cli/Application.php b/src/Behat/Testwork/Cli/Application.php index 080fee021..25435a9b0 100644 --- a/src/Behat/Testwork/Cli/Application.php +++ b/src/Behat/Testwork/Cli/Application.php @@ -14,6 +14,7 @@ use Behat\Testwork\ServiceContainer\ContainerLoader; use Behat\Testwork\ServiceContainer\Exception\ConfigurationLoadingException; use Behat\Testwork\ServiceContainer\ExtensionManager; +use Composer\XdebugHandler\XdebugHandler; use Symfony\Component\Console\Application as BaseApplication; use Symfony\Component\Console\Command\Command as SymfonyCommand; use Symfony\Component\Console\Input\ArrayInput; @@ -84,6 +85,7 @@ public function getDefaultInputDefinition(): InputDefinition 'guessed based on your platform and the output if not specified.' ), new InputOption('--no-colors', null, InputOption::VALUE_NONE, 'Force no ANSI color in the output.'), + new InputOption('--xdebug', null, InputOption::VALUE_NONE, 'Allow Xdebug to run.'), )); } @@ -97,6 +99,14 @@ public function getDefaultInputDefinition(): InputDefinition */ public function doRun(InputInterface $input, OutputInterface $output): int { + $isXdebugAllowed = $input->hasParameterOption('--xdebug'); + if (!$isXdebugAllowed) { + $xdebugHandler = new XdebugHandler('behat'); + $xdebugHandler->setPersistent(); + $xdebugHandler->check(); + unset($xdebugHandler); + } + // xdebug's default nesting level of 100 is not enough if (extension_loaded('xdebug') && false === strpos(ini_get('disable_functions'), 'ini_set') From 1c2fc474d0cf87e4958982db09d305114a379572 Mon Sep 17 00:00:00 2001 From: Franck Matsos Date: Thu, 28 Nov 2024 16:38:18 +0100 Subject: [PATCH 496/567] feat: use attributes by default for snippets Signed-off-by: Franck Matsos --- .../Behat/Context/Snippet/ContextSnippet.php | 37 ++-- .../Generator/ContextSnippetGenerator.php | 186 +++++++----------- .../Generator/FixedContextIdentifier.php | 11 +- .../Generator/FixedPatternIdentifier.php | 13 +- src/Behat/Behat/Definition/Call/Given.php | 10 +- src/Behat/Behat/Definition/Call/Then.php | 10 +- src/Behat/Behat/Definition/Call/When.php | 10 +- src/Behat/Behat/Snippet/AggregateSnippet.php | 20 +- .../Snippet/Generator/SnippetGenerator.php | 6 - 9 files changed, 108 insertions(+), 195 deletions(-) diff --git a/src/Behat/Behat/Context/Snippet/ContextSnippet.php b/src/Behat/Behat/Context/Snippet/ContextSnippet.php index 6ece5f198..67db2a1f6 100644 --- a/src/Behat/Behat/Context/Snippet/ContextSnippet.php +++ b/src/Behat/Behat/Context/Snippet/ContextSnippet.php @@ -20,32 +20,23 @@ */ final class ContextSnippet implements Snippet { - /** - * @var StepNode - */ - private $step; - /** - * @var string - */ - private $template; - /** - * @var string - */ - private $contextClass; + private StepNode $step; + + private string $template; + + private string $contextClass; + /** * @var string[] */ - private $usedClasses; + private array $usedClasses; /** * Initializes definition snippet. * - * @param StepNode $step - * @param string $template - * @param string $contextClass * @param string[] $usedClasses */ - public function __construct(StepNode $step, $template, $contextClass, array $usedClasses = array()) + public function __construct(StepNode $step, string $template, string $contextClass, array $usedClasses = []) { $this->step = $step; $this->template = $template; @@ -56,7 +47,7 @@ public function __construct(StepNode $step, $template, $contextClass, array $use /** * {@inheritdoc} */ - public function getType() + public function getType(): string { return 'context'; } @@ -64,7 +55,7 @@ public function getType() /** * {@inheritdoc} */ - public function getHash() + public function getHash(): string { return md5($this->template); } @@ -72,7 +63,7 @@ public function getHash() /** * {@inheritdoc} */ - public function getSnippet() + public function getSnippet(): string { return sprintf($this->template, $this->step->getKeywordType()); } @@ -80,7 +71,7 @@ public function getSnippet() /** * {@inheritdoc} */ - public function getStep() + public function getStep(): StepNode { return $this->step; } @@ -88,7 +79,7 @@ public function getStep() /** * {@inheritdoc} */ - public function getTarget() + public function getTarget(): string { return $this->contextClass; } @@ -98,7 +89,7 @@ public function getTarget() * * @return string[] */ - public function getUsedClasses() + public function getUsedClasses(): array { return $this->usedClasses; } diff --git a/src/Behat/Behat/Context/Snippet/Generator/ContextSnippetGenerator.php b/src/Behat/Behat/Context/Snippet/Generator/ContextSnippetGenerator.php index 2baa16866..cadd73340 100644 --- a/src/Behat/Behat/Context/Snippet/Generator/ContextSnippetGenerator.php +++ b/src/Behat/Behat/Context/Snippet/Generator/ContextSnippetGenerator.php @@ -12,12 +12,18 @@ use Behat\Behat\Context\Environment\ContextEnvironment; use Behat\Behat\Context\Snippet\ContextSnippet; +use Behat\Behat\Definition\Call as DefinitionCall; use Behat\Behat\Definition\Pattern\PatternTransformer; use Behat\Behat\Snippet\Exception\EnvironmentSnippetGenerationException; use Behat\Behat\Snippet\Generator\SnippetGenerator; +use Behat\Behat\Snippet\Snippet; +use Behat\Behat\Tester\Exception\PendingException; use Behat\Gherkin\Node\PyStringNode; use Behat\Gherkin\Node\StepNode; use Behat\Gherkin\Node\TableNode; +use Behat\Step\Given; +use Behat\Step\Then; +use Behat\Step\When; use Behat\Testwork\Environment\Environment; use ReflectionClass; @@ -29,63 +35,47 @@ final class ContextSnippetGenerator implements SnippetGenerator { /** - * @var string[string] - */ - private static $proposedMethods = array(); - /** - * @var string - */ - private static $templateTemplate = <<> */ + private static array $proposedMethods = []; + + private static string $snippetTemplate = <<patternTransformer = $patternTransformer; - $this->setContextIdentifier(new FixedContextIdentifier(null)); - $this->setPatternIdentifier(new FixedPatternIdentifier(null)); + $this->setContextIdentifier(new FixedContextIdentifier()); + $this->setPatternIdentifier(new FixedPatternIdentifier()); } /** * Sets target context identifier. - * - * @param TargetContextIdentifier $identifier */ - public function setContextIdentifier(TargetContextIdentifier $identifier) + public function setContextIdentifier(TargetContextIdentifier $identifier): void { $this->contextIdentifier = new CachedContextIdentifier($identifier); } /** * Sets target pattern type identifier. - * - * @param PatternIdentifier $identifier */ - public function setPatternIdentifier(PatternIdentifier $identifier) + public function setPatternIdentifier(PatternIdentifier $identifier): void { $this->patternIdentifier = $identifier; } @@ -93,7 +83,7 @@ public function setPatternIdentifier(PatternIdentifier $identifier) /** * {@inheritdoc} */ - public function supportsEnvironmentAndStep(Environment $environment, StepNode $step) + public function supportsEnvironmentAndStep(Environment $environment, StepNode $step): bool { if (!$environment instanceof ContextEnvironment) { return false; @@ -109,7 +99,7 @@ public function supportsEnvironmentAndStep(Environment $environment, StepNode $s /** * {@inheritdoc} */ - public function generateSnippet(Environment $environment, StepNode $step) + public function generateSnippet(Environment $environment, StepNode $step): Snippet { if (!$environment instanceof ContextEnvironment) { throw new EnvironmentSnippetGenerationException(sprintf( @@ -134,30 +124,20 @@ public function generateSnippet(Environment $environment, StepNode $step) /** * Generates method name using step text and regex. - * - * @param string $contextClass - * @param string $canonicalText - * @param string $pattern - * - * @return string */ - private function getMethodName($contextClass, $canonicalText, $pattern) + private function getMethodName(string $contextClass, string $canonicalText, string $pattern): string { $methodName = $this->deduceMethodName($canonicalText); - $methodName = $this->getUniqueMethodName($contextClass, $pattern, $methodName); - return $methodName; + return $this->getUniqueMethodName($contextClass, $pattern, $methodName); } /** * Returns an array of method argument names from step and token count. * - * @param StepNode $step - * @param integer $tokenCount - * * @return string[] */ - private function getMethodArguments(StepNode $step, $tokenCount) + private function getMethodArguments(StepNode $step, int $tokenCount): array { $args = array(); for ($i = 0; $i < $tokenCount; $i++) { @@ -174,20 +154,23 @@ private function getMethodArguments(StepNode $step, $tokenCount) /** * Returns an array of classes used by the snippet template * - * @param StepNode $step - * * @return string[] */ - private function getUsedClasses(StepNode $step) + private function getUsedClasses(StepNode $step): array { - $usedClasses = array('Behat\Behat\Tester\Exception\PendingException'); + $usedClasses = [PendingException::class]; + + $usedClasses[] = match ($step->getKeywordType()) { + DefinitionCall\Given::KEYWORD => Given::class, + DefinitionCall\When::KEYWORD => When::class, + DefinitionCall\Then::KEYWORD => Then::class, + }; foreach ($step->getArguments() as $argument) { - if ($argument instanceof TableNode) { - $usedClasses[] = 'Behat\Gherkin\Node\TableNode'; - } elseif ($argument instanceof PyStringNode) { - $usedClasses[] = 'Behat\Gherkin\Node\PyStringNode'; - } + $usedClasses[] = match (true) { + $argument instanceof TableNode => TableNode::class, + $argument instanceof PyStringNode => PyStringNode::class, + }; } return $usedClasses; @@ -196,30 +179,29 @@ private function getUsedClasses(StepNode $step) /** * Generates snippet template using regex, method name and arguments. * - * @param string $pattern - * @param string $methodName * @param string[] $methodArguments - * - * @return string */ - private function getSnippetTemplate($pattern, $methodName, array $methodArguments) + private function getSnippetTemplate(string $pattern, string $methodName, array $methodArguments): string { return sprintf( - self::$templateTemplate, - str_replace('%', '%%', $pattern), + self::$snippetTemplate, + $this->preparePattern($pattern), $methodName, implode(', ', $methodArguments) ); } + private function preparePattern(string $pattern): string + { + $pattern = str_replace('%', '%%', $pattern); + + return str_replace("'", "\'", $pattern); + } + /** * Generates definition method name based on the step text. - * - * @param string $canonicalText - * - * @return string */ - private function deduceMethodName($canonicalText) + private function deduceMethodName(string $canonicalText): string { // check that method name is not empty if (0 !== strlen($canonicalText)) { @@ -233,32 +215,20 @@ private function deduceMethodName($canonicalText) /** * Ensures uniqueness of the method name in the context. - * - * @param string $contextClass - * @param string $stepPattern - * @param string $name - * - * @return string */ - private function getUniqueMethodName($contextClass, $stepPattern, $name) + private function getUniqueMethodName(string $contextClass, string $stepPattern, string $name): string { $reflection = new ReflectionClass($contextClass); - $number = $this->getMethodNumberFromTheMethodName($name); list($name, $number) = $this->getMethodNameNotExistentInContext($reflection, $name, $number); - $name = $this->getMethodNameNotProposedEarlier($contextClass, $stepPattern, $name, $number); - return $name; + return $this->getMethodNameNotProposedEarlier($contextClass, $stepPattern, $name, $number); } /** * Tries to deduct method number from the provided method name. - * - * @param string $methodName - * - * @return integer */ - private function getMethodNumberFromTheMethodName($methodName) + private function getMethodNumberFromTheMethodName(string $methodName): int { $methodNumber = 2; if (preg_match('/(\d+)$/', $methodName, $matches)) { @@ -271,33 +241,22 @@ private function getMethodNumberFromTheMethodName($methodName) /** * Tries to guess method name that is not yet defined in the context class. * - * @param ReflectionClass $reflection - * @param string $methodName - * @param integer $methodNumber - * - * @return array + * @return array */ - private function getMethodNameNotExistentInContext(ReflectionClass $reflection, $methodName, $methodNumber) + private function getMethodNameNotExistentInContext(ReflectionClass $reflection, string $methodName, int $methodNumber): array { while ($reflection->hasMethod($methodName)) { $methodName = preg_replace('/\d+$/', '', $methodName); $methodName .= $methodNumber++; } - return array($methodName, $methodNumber); + return [$methodName, $methodNumber]; } /** * Tries to guess method name that is not yet proposed to the context class. - * - * @param string $contextClass - * @param string $stepPattern - * @param string $name - * @param integer $number - * - * @return string */ - private function getMethodNameNotProposedEarlier($contextClass, $stepPattern, $name, $number) + private function getMethodNameNotProposedEarlier(string $contextClass, string $stepPattern, string $name, int $number): string { foreach ($this->getAlreadyProposedMethods($contextClass) as $proposedPattern => $proposedMethod) { if ($proposedPattern === $stepPattern) { @@ -318,43 +277,30 @@ private function getMethodNameNotProposedEarlier($contextClass, $stepPattern, $n /** * Returns already proposed method names. * - * @param string $contextClass - * - * @return string[] + * @return array */ - private function getAlreadyProposedMethods($contextClass) + private function getAlreadyProposedMethods(string $contextClass): array { - return self::$proposedMethods[$contextClass] ?? array(); + return self::$proposedMethods[$contextClass] ?? []; } /** * Marks method as proposed one. - * - * @param string $contextClass - * @param string $stepPattern - * @param string $methodName */ - private function markMethodAsAlreadyProposed($contextClass, $stepPattern, $methodName) + private function markMethodAsAlreadyProposed(string $contextClass, string $stepPattern, string $methodName): void { self::$proposedMethods[$contextClass][$stepPattern] = $methodName; } /** * Returns method argument. - * - * @param string $argument - * - * @return string */ - private function getMethodArgument($argument) + private function getMethodArgument(mixed $argument): string { - $arg = '__unknown__'; - if ($argument instanceof PyStringNode) { - $arg = 'PyStringNode $string'; - } elseif ($argument instanceof TableNode) { - $arg = 'TableNode $table'; - } - - return $arg; + return match (true) { + $argument instanceof PyStringNode => 'PyStringNode $string', + $argument instanceof TableNode => 'TableNode $table', + default => '__unknown__', + }; } } diff --git a/src/Behat/Behat/Context/Snippet/Generator/FixedContextIdentifier.php b/src/Behat/Behat/Context/Snippet/Generator/FixedContextIdentifier.php index 0d4b8e653..a1d39fad2 100644 --- a/src/Behat/Behat/Context/Snippet/Generator/FixedContextIdentifier.php +++ b/src/Behat/Behat/Context/Snippet/Generator/FixedContextIdentifier.php @@ -19,17 +19,12 @@ */ final class FixedContextIdentifier implements TargetContextIdentifier { - /** - * @var - */ - private $contextClass; + private ?string $contextClass; /** * Initialises identifier. - * - * @param string $contextClass */ - public function __construct($contextClass) + public function __construct(?string $contextClass = null) { $this->contextClass = $contextClass; } @@ -37,7 +32,7 @@ public function __construct($contextClass) /** * {@inheritdoc} */ - public function guessTargetContextClass(ContextEnvironment $environment) + public function guessTargetContextClass(ContextEnvironment $environment): ?string { if ($environment->hasContextClass($this->contextClass)) { return $this->contextClass; diff --git a/src/Behat/Behat/Context/Snippet/Generator/FixedPatternIdentifier.php b/src/Behat/Behat/Context/Snippet/Generator/FixedPatternIdentifier.php index 7358bd41b..7aecd3c80 100644 --- a/src/Behat/Behat/Context/Snippet/Generator/FixedPatternIdentifier.php +++ b/src/Behat/Behat/Context/Snippet/Generator/FixedPatternIdentifier.php @@ -10,8 +10,6 @@ namespace Behat\Behat\Context\Snippet\Generator; -use Behat\Behat\Context\Context; - /** * Identifier that always returns same pattern type. * @@ -19,17 +17,12 @@ */ final class FixedPatternIdentifier implements PatternIdentifier { - /** - * @var string - */ - private $patternType; + private ?string $patternType; /** * Initialises identifier. - * - * @param string $patternType */ - public function __construct($patternType) + public function __construct(?string $patternType = null) { $this->patternType = $patternType; } @@ -37,7 +30,7 @@ public function __construct($patternType) /** * {@inheritdoc} */ - public function guessPatternType($contextClass) + public function guessPatternType($contextClass): ?string { return $this->patternType; } diff --git a/src/Behat/Behat/Definition/Call/Given.php b/src/Behat/Behat/Definition/Call/Given.php index 324ffb8b9..c3337f159 100644 --- a/src/Behat/Behat/Definition/Call/Given.php +++ b/src/Behat/Behat/Definition/Call/Given.php @@ -17,15 +17,15 @@ */ final class Given extends RuntimeDefinition { + public const KEYWORD = 'Given'; + /** * Initializes definition. * - * @param string $pattern - * @param callable $callable - * @param null|string $description + * @param array|callable $callable */ - public function __construct($pattern, $callable, $description = null) + public function __construct(string $pattern, $callable, ?string $description = null) { - parent::__construct('Given', $pattern, $callable, $description); + parent::__construct(self::KEYWORD, $pattern, $callable, $description); } } diff --git a/src/Behat/Behat/Definition/Call/Then.php b/src/Behat/Behat/Definition/Call/Then.php index 50dabc176..9b519de3e 100644 --- a/src/Behat/Behat/Definition/Call/Then.php +++ b/src/Behat/Behat/Definition/Call/Then.php @@ -17,15 +17,15 @@ */ final class Then extends RuntimeDefinition { + public const KEYWORD = 'Then'; + /** * Initializes definition. * - * @param string $pattern - * @param callable $callable - * @param null|string $description + * @param array|callable $callable */ - public function __construct($pattern, $callable, $description = null) + public function __construct(string $pattern, $callable, ?string $description = null) { - parent::__construct('Then', $pattern, $callable, $description); + parent::__construct(self::KEYWORD, $pattern, $callable, $description); } } diff --git a/src/Behat/Behat/Definition/Call/When.php b/src/Behat/Behat/Definition/Call/When.php index 1ff6560e2..8ef14613e 100644 --- a/src/Behat/Behat/Definition/Call/When.php +++ b/src/Behat/Behat/Definition/Call/When.php @@ -17,15 +17,15 @@ */ final class When extends RuntimeDefinition { + public const KEYWORD = 'When'; + /** * Initializes definition. * - * @param string $pattern - * @param callable $callable - * @param null|string $description + * @param array|callable $callable */ - public function __construct($pattern, $callable, $description = null) + public function __construct(string $pattern, $callable, ?string $description = null) { - parent::__construct('When', $pattern, $callable, $description); + parent::__construct(self::KEYWORD, $pattern, $callable, $description); } } diff --git a/src/Behat/Behat/Snippet/AggregateSnippet.php b/src/Behat/Behat/Snippet/AggregateSnippet.php index c63e8f1d7..477a088ef 100644 --- a/src/Behat/Behat/Snippet/AggregateSnippet.php +++ b/src/Behat/Behat/Snippet/AggregateSnippet.php @@ -23,7 +23,7 @@ final class AggregateSnippet /** * @var Snippet[] */ - private $snippets; + private array $snippets; /** * Initializes snippet. @@ -37,30 +37,24 @@ public function __construct(array $snippets) /** * Returns snippet type. - * - * @return string */ - public function getType() + public function getType(): string { return current($this->snippets)->getType(); } /** * Returns snippet unique ID (step type independent). - * - * @return string */ - public function getHash() + public function getHash(): string { return current($this->snippets)->getHash(); } /** * Returns definition snippet text. - * - * @return string */ - public function getSnippet() + public function getSnippet(): string { return current($this->snippets)->getSnippet(); } @@ -70,7 +64,7 @@ public function getSnippet() * * @return StepNode[] */ - public function getSteps() + public function getSteps(): array { return array_unique( array_map( @@ -88,7 +82,7 @@ function (Snippet $snippet) { * * @return string[] */ - public function getTargets() + public function getTargets(): array { return array_unique( array_map( @@ -105,7 +99,7 @@ function (Snippet $snippet) { * * @return string[] */ - public function getUsedClasses() + public function getUsedClasses(): array { if (empty($this->snippets)) { return array(); diff --git a/src/Behat/Behat/Snippet/Generator/SnippetGenerator.php b/src/Behat/Behat/Snippet/Generator/SnippetGenerator.php index 09bbd1164..0202e56de 100644 --- a/src/Behat/Behat/Snippet/Generator/SnippetGenerator.php +++ b/src/Behat/Behat/Snippet/Generator/SnippetGenerator.php @@ -27,9 +27,6 @@ interface SnippetGenerator /** * Checks if generator supports search query. * - * @param Environment $environment - * @param StepNode $step - * * @return bool */ public function supportsEnvironmentAndStep(Environment $environment, StepNode $step); @@ -37,9 +34,6 @@ public function supportsEnvironmentAndStep(Environment $environment, StepNode $s /** * Generates snippet from search. * - * @param Environment $environment - * @param StepNode $step - * * @return Snippet */ public function generateSnippet(Environment $environment, StepNode $step); From f00543e07df009ec9b0ca8cec50a622b8ece5ba1 Mon Sep 17 00:00:00 2001 From: Franck Matsos Date: Tue, 3 Dec 2024 13:52:27 +0100 Subject: [PATCH 497/567] test: update tests for attributes snippets Signed-off-by: Franck Matsos --- features/append_snippets.feature | 109 ++++++------------ features/context.feature | 8 +- features/format_options.feature | 48 ++------ features/i18n.feature | 16 +-- features/junit_format.feature | 4 +- features/legacy_snippets.feature | 68 +++-------- features/multiple_formats.feature | 60 +++------- features/pretty_format.feature | 4 +- features/result_types.feature | 32 ++--- features/snippets.feature | 104 +++++------------ .../Generator/ContextSnippetGenerator.php | 2 +- 11 files changed, 121 insertions(+), 334 deletions(-) diff --git a/features/append_snippets.feature b/features/append_snippets.feature index bd7e7cf1e..42eee611f 100644 --- a/features/append_snippets.feature +++ b/features/append_snippets.feature @@ -123,6 +123,8 @@ Feature: Append snippets option """ Date: Fri, 6 Dec 2024 16:19:49 +0100 Subject: [PATCH 498/567] feat: add use statements output Signed-off-by: Franck Matsos --- features/i18n.feature | 20 +++++++++ features/snippets.feature | 41 +++++++++++++++++++ i18n.php | 18 ++++++++ .../Behat/Context/Snippet/ContextSnippet.php | 23 +++-------- .../Generator/FixedContextIdentifier.php | 8 ++-- .../Generator/FixedPatternIdentifier.php | 8 ++-- .../Snippet/Printer/ConsoleSnippetPrinter.php | 27 +++++++++++- 7 files changed, 117 insertions(+), 28 deletions(-) diff --git a/features/i18n.feature b/features/i18n.feature index c6544186a..b0c357855 100644 --- a/features/i18n.feature +++ b/features/i18n.feature @@ -142,6 +142,11 @@ Feature: I18n { throw new PendingException(); } + + --- Не забудьте эти 2 use утверждения: + + use Behat\Behat\Tester\Exception\PendingException; + use Behat\Step\Then; """ Scenario: Progress @@ -180,6 +185,11 @@ Feature: I18n { throw new PendingException(); } + + --- Не забудьте эти 2 use утверждения: + + use Behat\Behat\Tester\Exception\PendingException; + use Behat\Step\Then; """ Scenario: Progress with unexisting locale @@ -218,6 +228,11 @@ Feature: I18n { throw new PendingException(); } + + --- Don't forget these 2 use statements: + + use Behat\Behat\Tester\Exception\PendingException; + use Behat\Step\Then; """ Scenario: Progress with unexisting locale @@ -256,4 +271,9 @@ Feature: I18n { throw new PendingException(); } + + --- Don't forget these 2 use statements: + + use Behat\Behat\Tester\Exception\PendingException; + use Behat\Step\Then; """ diff --git a/features/snippets.feature b/features/snippets.feature index c1cd84fa9..440d95ae7 100644 --- a/features/snippets.feature +++ b/features/snippets.feature @@ -112,6 +112,14 @@ Feature: Snippets generation and addition { throw new PendingException(); } + + --- Don't forget these 5 use statements: + + use Behat\Behat\Tester\Exception\PendingException; + use Behat\Step\Given; + use Behat\Step\When; + use Behat\Step\Then; + use Behat\Gherkin\Node\PyStringNode; """ Scenario: Appending regex snippets to a particular context @@ -203,6 +211,14 @@ Feature: Snippets generation and addition { throw new PendingException(); } + + --- Don't forget these 5 use statements: + + use Behat\Behat\Tester\Exception\PendingException; + use Behat\Step\Given; + use Behat\Step\When; + use Behat\Step\Then; + use Behat\Gherkin\Node\PyStringNode; """ Scenario: Appending turnip snippets to a particular context @@ -298,6 +314,11 @@ Feature: Snippets generation and addition { throw new PendingException(); } + + --- Don't forget these 2 use statements: + + use Behat\Behat\Tester\Exception\PendingException; + use Behat\Step\Given; """ Scenario: Generating snippets for steps with slashes @@ -330,6 +351,11 @@ Feature: Snippets generation and addition { throw new PendingException(); } + + --- Don't forget these 2 use statements: + + use Behat\Behat\Tester\Exception\PendingException; + use Behat\Step\Then; """ Scenario: Generating snippets using interactive --snippets-for @@ -385,6 +411,14 @@ Feature: Snippets generation and addition { throw new PendingException(); } + + --- Don't forget these 5 use statements: + + use Behat\Behat\Tester\Exception\PendingException; + use Behat\Step\Given; + use Behat\Step\When; + use Behat\Step\Then; + use Behat\Gherkin\Node\PyStringNode; """ Scenario: Generating snippets for steps with apostrophes @@ -431,4 +465,11 @@ Feature: Snippets generation and addition { throw new PendingException(); } + + --- Don't forget these 4 use statements: + + use Behat\Behat\Tester\Exception\PendingException; + use Behat\Step\Given; + use Behat\Step\When; + use Behat\Step\Then; """ diff --git a/i18n.php b/i18n.php index 8b4150372..4dda4786d 100644 --- a/i18n.php +++ b/i18n.php @@ -2,6 +2,7 @@ 'en' => array( 'snippet_context_choice' => '', 'snippet_proposal_title' => '', + 'snippet_proposal_use' => 'Don\'t forget these %count% use statements:', 'snippet_missing_title' => '', 'skipped_scenarios_title' => 'Skipped scenarios:', 'failed_scenarios_title' => 'Failed scenarios:', @@ -20,6 +21,7 @@ 'bg' => array( 'snippet_context_choice' => 'В сет ', 'snippet_proposal_title' => '', + 'snippet_proposal_use' => 'Не забравяйте тези %count% use изрази:', 'snippet_missing_title' => '', 'skipped_scenarios_title' => 'Пропуснати сценарии:', 'failed_scenarios_title' => 'Провалени сценарии:', @@ -37,6 +39,7 @@ ), 'cs' => array( 'snippet_proposal_title' => '', + 'snippet_proposal_use' => 'Nezapomeňte na těchto %count% use příkazů:', 'snippet_missing_title' => '', 'failed_scenarios_title' => 'Chybné scénáře:', 'failed_hooks_title' => 'Chybné hooky:', @@ -53,6 +56,7 @@ ), 'de' => array( 'snippet_proposal_title' => '', + 'snippet_proposal_use' => 'Vergessen Sie nicht diese %count% use-Anweisungen:', 'snippet_missing_title' => '', 'failed_scenarios_title' => 'Fehlgeschlagene Szenarien:', 'failed_hooks_title' => 'Fehlgeschlagene Hooks:', @@ -69,6 +73,7 @@ ), 'es' => array( 'snippet_proposal_title' => '', + 'snippet_proposal_use' => 'No olvides estas %count% declaraciones de use:', 'snippet_missing_title' => '', 'failed_scenarios_title' => 'Escenarios fallidos:', 'failed_hooks_title' => 'Hooks fallidos:', @@ -85,6 +90,7 @@ ), 'fr' => array( 'snippet_proposal_title' => '', + 'snippet_proposal_use' => 'N\'oubliez pas d\'ajouter ces %count% use :', 'snippet_missing_title' => '', 'failed_scenarios_title' => 'Scénarios échoués:', 'failed_hooks_title' => 'Hooks échoués:', @@ -102,6 +108,7 @@ 'hu' => array( 'snippet_context_choice' => '', 'snippet_proposal_title' => '', + 'snippet_proposal_use' => 'Ne felejtsd el ezeket a %count% use utasításokat:', 'snippet_missing_title' => '', 'skipped_scenarios_title' => 'Kihagyott forgatókönyvek:', 'failed_scenarios_title' => 'Sikertelen forgatókönyvek:', @@ -120,6 +127,7 @@ 'it' => array( 'snippet_proposal_title' => '', 'snippet_missing_title' => '', + 'snippet_proposal_use' => 'Non dimenticare queste %count% istruzioni di use:', 'failed_scenarios_title' => 'Scenari falliti:', 'failed_hooks_title' => 'Hook falliti:', 'failed_steps_title' => 'Passaggi falliti:', @@ -136,6 +144,7 @@ 'ja' => array( 'snippet_proposal_title' => '', 'snippet_missing_title' => '', + 'snippet_proposal_use' => 'これらの %count% use 文を忘れずに:', 'skipped_scenarios_title' => 'スキップした シナリオ:', 'failed_scenarios_title' => '失敗した シナリオ:', 'failed_hooks_title' => '失敗した フック:', @@ -153,6 +162,7 @@ 'ko' => array( 'snippet_proposal_title' => ' ', 'snippet_missing_title' => '', + 'snippet_proposal_use' => '이 %count% 개의 use 문을 잊지 마세요:', 'skipped_scenarios_title' => '건너뛴 시나리오:', 'failed_scenarios_title' => '실패한 시나리오:', 'failed_hooks_title' => '실패한 훅 연결:', @@ -170,6 +180,7 @@ 'nl' => array( 'snippet_proposal_title' => '', 'snippet_missing_title' => '', + 'snippet_proposal_use' => 'Vergeet deze %count% use-verklaringen niet:', 'failed_scenarios_title' => 'Gefaalde scenario\'s:', 'failed_hooks_title' => 'Gefaalde hooks:', 'failed_steps_title' => 'Gefaalde stappen:', @@ -186,6 +197,7 @@ 'no' => array( 'snippet_proposal_title' => '', 'snippet_missing_title' => '', + 'snippet_proposal_use' => 'Ikke glem disse %count% use-setningene:', 'failed_scenarios_title' => 'Feilende scenarier:', 'failed_hooks_title' => 'Feilende hooks:', 'failed_steps_title' => 'Feilende steg:', @@ -202,6 +214,7 @@ 'pl' => array( 'snippet_proposal_title' => '', 'snippet_missing_title' => '', + 'snippet_proposal_use' => 'Nie zapomnij o tych %count% wpisach use:', 'failed_scenarios_title' => 'Nieudane scenariusze:', 'failed_hooks_title' => 'Nieudane hooki:', 'failed_steps_title' => 'Nieudane kroki', @@ -218,6 +231,7 @@ 'pt' => array( 'snippet_proposal_title' => '', 'snippet_missing_title' => '', + 'snippet_proposal_use' => 'Não te esqueças destas %count% declarações de use:', 'failed_scenarios_title' => 'Cenários que falharam:', 'failed_hooks_title' => 'Hooks que falharam:', 'failed_steps_title' => 'Definições que falharam:', @@ -234,6 +248,7 @@ 'pt-BR' => array( 'snippet_proposal_title' => '', 'snippet_missing_title' => '', + 'snippet_proposal_use' => 'Não se esqueça destas %count% declarações de use:', 'failed_scenarios_title' => 'Cenários falhados:', 'failed_hooks_title' => 'Hooks falhados:', 'failed_steps_title' => 'Etapas falhadas:', @@ -250,6 +265,7 @@ 'ro' => array( 'snippet_proposal_title' => '', 'snippet_missing_title' => '', + 'snippet_proposal_use' => 'Nu uitați aceste %count% instrucțiuni de use:', 'skipped_scenarios_title' => 'Scenarii omise:', 'failed_scenarios_title' => 'Scenarii eșuate:', 'failed_hooks_title' => 'Hook-uri eșuate:', @@ -267,6 +283,7 @@ 'ru' => array( 'snippet_proposal_title' => ' ', 'snippet_missing_title' => '', + 'snippet_proposal_use' => 'Не забудьте эти %count% use утверждения:', 'skipped_scenarios_title' => 'Пропущенные сценарии:', 'failed_scenarios_title' => 'Проваленные сценарии:', 'failed_hooks_title' => 'Проваленные хуки:', @@ -284,6 +301,7 @@ 'zh' => array( 'snippet_context_choice' => '', 'snippet_proposal_title' => '', + 'snippet_proposal_use' => '别忘了这 %count% 个 use 声明:', 'snippet_missing_title' => '', 'skipped_scenarios_title' => '跳过场景:', 'failed_scenarios_title' => '失败的场景:', diff --git a/src/Behat/Behat/Context/Snippet/ContextSnippet.php b/src/Behat/Behat/Context/Snippet/ContextSnippet.php index 67db2a1f6..37784c303 100644 --- a/src/Behat/Behat/Context/Snippet/ContextSnippet.php +++ b/src/Behat/Behat/Context/Snippet/ContextSnippet.php @@ -20,28 +20,17 @@ */ final class ContextSnippet implements Snippet { - private StepNode $step; - - private string $template; - - private string $contextClass; - - /** - * @var string[] - */ - private array $usedClasses; - /** * Initializes definition snippet. * * @param string[] $usedClasses */ - public function __construct(StepNode $step, string $template, string $contextClass, array $usedClasses = []) - { - $this->step = $step; - $this->template = $template; - $this->contextClass = $contextClass; - $this->usedClasses = $usedClasses; + public function __construct( + private readonly StepNode $step, + private readonly string $template, + private readonly string $contextClass, + private readonly array $usedClasses = [], + ) { } /** diff --git a/src/Behat/Behat/Context/Snippet/Generator/FixedContextIdentifier.php b/src/Behat/Behat/Context/Snippet/Generator/FixedContextIdentifier.php index a1d39fad2..b194b9b96 100644 --- a/src/Behat/Behat/Context/Snippet/Generator/FixedContextIdentifier.php +++ b/src/Behat/Behat/Context/Snippet/Generator/FixedContextIdentifier.php @@ -19,14 +19,12 @@ */ final class FixedContextIdentifier implements TargetContextIdentifier { - private ?string $contextClass; - /** * Initialises identifier. */ - public function __construct(?string $contextClass = null) - { - $this->contextClass = $contextClass; + public function __construct( + private readonly ?string $contextClass = null + ) { } /** diff --git a/src/Behat/Behat/Context/Snippet/Generator/FixedPatternIdentifier.php b/src/Behat/Behat/Context/Snippet/Generator/FixedPatternIdentifier.php index 7aecd3c80..c5dabd78b 100644 --- a/src/Behat/Behat/Context/Snippet/Generator/FixedPatternIdentifier.php +++ b/src/Behat/Behat/Context/Snippet/Generator/FixedPatternIdentifier.php @@ -17,14 +17,12 @@ */ final class FixedPatternIdentifier implements PatternIdentifier { - private ?string $patternType; - /** * Initialises identifier. */ - public function __construct(?string $patternType = null) - { - $this->patternType = $patternType; + public function __construct( + private readonly ?string $patternType = null + ) { } /** diff --git a/src/Behat/Behat/Snippet/Printer/ConsoleSnippetPrinter.php b/src/Behat/Behat/Snippet/Printer/ConsoleSnippetPrinter.php index 4112b695d..147a42dfc 100644 --- a/src/Behat/Behat/Snippet/Printer/ConsoleSnippetPrinter.php +++ b/src/Behat/Behat/Snippet/Printer/ConsoleSnippetPrinter.php @@ -57,13 +57,20 @@ public function __construct(OutputInterface $output, TranslatorInterface $transl */ public function printSnippets($targetName, array $snippets) { - $message = $this->translator->trans('snippet_proposal_title', array('%count%' => $targetName), 'output'); + $message = $this->translator->trans('snippet_proposal_title', ['%count%' => $targetName], 'output'); $this->output->writeln('--- ' . $message . PHP_EOL); + $usedClasses = []; foreach ($snippets as $snippet) { + foreach ($snippet->getUsedClasses() as $usedClass) { + $usedClasses[$usedClass] = true; + } + $this->output->writeln(sprintf('', $snippet->getSnippet()) . PHP_EOL); } + + $this->outputClassesUsesStatements(array_keys($usedClasses)); } /** @@ -84,4 +91,22 @@ public function printUndefinedSteps($suiteName, array $steps) $this->output->writeln(''); } + + /** + * @param array suite has undefined steps. Please choose the context to generate snippets:%count% has missing steps. Define them with these snippets:%count%Use CLI option to generate snippets for following suite steps:--snippets-for%count% има недекларирани стъпки. Изберете в кой Context да бъдат създадени:%count% има липсващи стъпки. Можете да ги създадете чрез:%count%Използвайте този снипет за да генерирате кода за следните стъпки през конзолата:--snippets-for%count% obsahuje chybné kroky. Definujte je za použití následujícího kódu:%count%Snippety pro následující kroky v sadě nebyly vygenerovány (zkontrolujte správnost konfigurace):%count% hat fehlende Schritte. Definiere diese mit den folgenden Snippets:%count%Snippets für die folgenden Schritte in der Suite wurden nicht generiert (Konfiguration überprüfen):%count%A le faltan pasos. Defínelos con estos pasos:%count%Las plantillas para los siguientes pasos en no fueron generadas (revisa tu configuración):%count% a des étapes manquantes. Définissez-les avec les modèles suivants :%count%Les modèles des étapes de la suite n\'ont pas été générés (vérifiez votre configuration):%count% sorozat meghatározatlan lépéseket tartalmaz. Válaszd ki a környezetet kódrészlet készítéséhez:%count% lépései hiányosak. Hozd létre az alábbi kódrészletekkel:%count%Használd a parancssori kapcsolót kódrészletek készítéséhez a sorozat lépéseihez:--snippets-for%count% ha dei passaggi mancanti. Definiscili con questi snippet:%count%Gli snippet per i seguenti passaggi della suite non sono stati generati (verifica la configurazione):%count% のステップが見つかりません。 次のスニペットで定義できます:%count%以下のステップのスニペットはスイートに生成されませんでした(設定を確認してください):%count%%count% 정의가 되지 않았습니다. 스니펫을 생성할 컨텍스트를 선택하십시오: 단계가 누락되었습니다. 스니펫을 정의해주세요:%count%Ontbrekende stappen in . Definieer ze met de volgende fragmenten:%count%Fragmenten voor de volgende stappen in de suite werden niet gegenereerd (controleer de configuratie):%count% mangler steg. Definer dem med disse snuttene:%count%Snutter for de følgende stegene i -samlingen ble ikke laget. (Sjekk konfigurasjonen din.):%count% zawiera brakujące kroki. Utwórz je korzystając z tych fragmentów kodu:%count%Fragmenty kodu dla następujących kroków nie zostały wygenerowane (sprawdź swoją konfigurację):%count% contém definições em falta. Defina-as com estes exemplos:%count%Os exemplos para as seguintes definições da suite não foram gerados (verifique a configuração):%count% possue etapas faltando. Defina elas com esse(s) trecho(s) de código:%count%Trecho de códigos para as seguintes etapas em suite não foram geradas (verique sua configuração):%count% are pași lipsa. Puteți implementa pașii cu ajutorul acestor fragmente de cod:%count%Fragmentele de cod pentru urmatorii pași din suita nu au fost generate (contextul tau implementeaza interfata SnippetAcceptingContext?):%count%%count%не содержит необходимых определений. Вы можете добавить их используя шаблоны:Шаблоны для следующих шагов в среде не были сгенерированы (проверьте ваши настройки):%count% 有新的场景步骤, 请选择要生成代码片段的ContextClass:%count% 已经更新。 请检查生成片段:%count%您可以使用 CLI命令更新 的ContextClass:--snippets-for%count%%s $usedClasses + */ + public function outputClassesUsesStatements(array $usedClasses): void + { + if ([] === $usedClasses) { + return; + } + + $message = $this->translator->trans('snippet_proposal_use', ['%count%' => \count($usedClasses)], 'output'); + + $this->output->writeln('--- '.$message.PHP_EOL); + + foreach ($usedClasses as $usedClass) { + $this->output->writeln(sprintf(' ', $usedClass)); + } + } } From 91c9e0da6407578e54751c2d77c9a575c6942ffe Mon Sep 17 00:00:00 2001 From: Carlos Granados use %s; Date: Mon, 9 Dec 2024 10:41:13 +0100 Subject: [PATCH 499/567] chore: first step towards Psalm level 6 (#1554) --- psalm.xml | 8 ++++++++ .../Behat/Context/Cli/InteractiveContextIdentifier.php | 2 +- .../Context/Exception/WrongContextClassException.php | 5 +---- .../Snippet/Generator/ContextSnippetGenerator.php | 10 ++-------- .../Definition/Exception/UnknownPatternException.php | 8 +------- .../Behat/Definition/Search/RepositorySearchEngine.php | 5 ++++- .../Exception/WrongContainerClassException.php | 8 +------- .../Output/Node/EventListener/AST/OutlineListener.php | 5 +++-- .../Node/EventListener/AST/OutlineTableListener.php | 2 ++ .../Output/Node/Printer/JUnit/JUnitFeaturePrinter.php | 2 +- .../Output/Node/Printer/Pretty/PrettySetupPrinter.php | 6 ++++-- src/Behat/Behat/Output/Statistics/PhaseStatistics.php | 7 ++++--- src/Behat/Behat/Output/Statistics/TotalStatistics.php | 6 +++--- .../EventDispatcher/TestworkEventDispatcher.php | 2 +- 14 files changed, 36 insertions(+), 40 deletions(-) diff --git a/psalm.xml b/psalm.xml index 71dfbfe83..de9787aef 100644 --- a/psalm.xml +++ b/psalm.xml @@ -43,6 +43,14 @@ + + diff --git a/src/Behat/Behat/Context/Cli/InteractiveContextIdentifier.php b/src/Behat/Behat/Context/Cli/InteractiveContextIdentifier.php index 78be23b6d..08e08e4f3 100644 --- a/src/Behat/Behat/Context/Cli/InteractiveContextIdentifier.php +++ b/src/Behat/Behat/Context/Cli/InteractiveContextIdentifier.php @@ -70,7 +70,7 @@ public function guessTargetContextClass(ContextEnvironment $environment) $message = $this->translator->trans('snippet_context_choice', array('%count%' => $suiteName), 'output'); $choices = array_values(array_merge(array('None'), $contextClasses)); - $default = 1; + $default = '1'; $answer = $this->askQuestion('>> ' . $message, $choices, $default); diff --git a/src/Behat/Behat/Context/Exception/WrongContextClassException.php b/src/Behat/Behat/Context/Exception/WrongContextClassException.php index 69ccc8cab..23c8a9311 100644 --- a/src/Behat/Behat/Context/Exception/WrongContextClassException.php +++ b/src/Behat/Behat/Context/Exception/WrongContextClassException.php @@ -26,11 +26,8 @@ final class WrongContextClassException extends InvalidArgumentException implemen /** * Initializes exception. - * - * @param integer $message - * @param string $class */ - public function __construct($message, $class) + public function __construct(string $message, string $class) { $this->class = $class; diff --git a/src/Behat/Behat/Context/Snippet/Generator/ContextSnippetGenerator.php b/src/Behat/Behat/Context/Snippet/Generator/ContextSnippetGenerator.php index 2baa16866..059f810a8 100644 --- a/src/Behat/Behat/Context/Snippet/Generator/ContextSnippetGenerator.php +++ b/src/Behat/Behat/Context/Snippet/Generator/ContextSnippetGenerator.php @@ -15,6 +15,7 @@ use Behat\Behat\Definition\Pattern\PatternTransformer; use Behat\Behat\Snippet\Exception\EnvironmentSnippetGenerationException; use Behat\Behat\Snippet\Generator\SnippetGenerator; +use Behat\Gherkin\Node\ArgumentInterface; use Behat\Gherkin\Node\PyStringNode; use Behat\Gherkin\Node\StepNode; use Behat\Gherkin\Node\TableNode; @@ -339,14 +340,7 @@ private function markMethodAsAlreadyProposed($contextClass, $stepPattern, $metho self::$proposedMethods[$contextClass][$stepPattern] = $methodName; } - /** - * Returns method argument. - * - * @param string $argument - * - * @return string - */ - private function getMethodArgument($argument) + private function getMethodArgument(ArgumentInterface $argument): string { $arg = '__unknown__'; if ($argument instanceof PyStringNode) { diff --git a/src/Behat/Behat/Definition/Exception/UnknownPatternException.php b/src/Behat/Behat/Definition/Exception/UnknownPatternException.php index bc23cb31f..3f249f19b 100644 --- a/src/Behat/Behat/Definition/Exception/UnknownPatternException.php +++ b/src/Behat/Behat/Definition/Exception/UnknownPatternException.php @@ -24,13 +24,7 @@ final class UnknownPatternException extends InvalidArgumentException implements */ private $pattern; - /** - * Initializes exception. - * - * @param string $message - * @param integer $pattern - */ - public function __construct($message, $pattern) + public function __construct(string $message, string $pattern) { $this->pattern = $pattern; diff --git a/src/Behat/Behat/Definition/Search/RepositorySearchEngine.php b/src/Behat/Behat/Definition/Search/RepositorySearchEngine.php index 6b694851b..118808d63 100644 --- a/src/Behat/Behat/Definition/Search/RepositorySearchEngine.php +++ b/src/Behat/Behat/Definition/Search/RepositorySearchEngine.php @@ -94,7 +94,10 @@ public function searchDefinition( } $result = $newResult; - $definitions[] = $newResult->getMatchedDefinition(); + $matchedDefinition = $newResult->getMatchedDefinition(); + if ($matchedDefinition instanceof Definition) { + $definitions[] = $matchedDefinition; + } } if (count($definitions) > 1) { diff --git a/src/Behat/Behat/HelperContainer/Exception/WrongContainerClassException.php b/src/Behat/Behat/HelperContainer/Exception/WrongContainerClassException.php index 5dd8321c6..22a08e78a 100644 --- a/src/Behat/Behat/HelperContainer/Exception/WrongContainerClassException.php +++ b/src/Behat/Behat/HelperContainer/Exception/WrongContainerClassException.php @@ -24,13 +24,7 @@ final class WrongContainerClassException extends InvalidArgumentException implem */ private $class; - /** - * Initializes exception. - * - * @param integer $message - * @param string $class - */ - public function __construct($message, $class) + public function __construct(string $message, string $class) { $this->class = $class; diff --git a/src/Behat/Behat/Output/Node/EventListener/AST/OutlineListener.php b/src/Behat/Behat/Output/Node/EventListener/AST/OutlineListener.php index 85b602b7b..f49116a5e 100644 --- a/src/Behat/Behat/Output/Node/EventListener/AST/OutlineListener.php +++ b/src/Behat/Behat/Output/Node/EventListener/AST/OutlineListener.php @@ -136,9 +136,10 @@ private function printExampleHeaderOnBeforeExampleEvent(Formatter $formatter, Ev return; } - $this->example = $event->getScenario(); - $this->exampleSetupPrinter->printSetup($formatter, $event->getSetup()); + + $this->example = $event->getScenario(); + assert($this->example instanceof ExampleNode); $this->examplePrinter->printHeader($formatter, $event->getFeature(), $this->example); } diff --git a/src/Behat/Behat/Output/Node/EventListener/AST/OutlineTableListener.php b/src/Behat/Behat/Output/Node/EventListener/AST/OutlineTableListener.php index 09a179bc1..5ca8ca30e 100644 --- a/src/Behat/Behat/Output/Node/EventListener/AST/OutlineTableListener.php +++ b/src/Behat/Behat/Output/Node/EventListener/AST/OutlineTableListener.php @@ -23,6 +23,7 @@ use Behat\Behat\Output\Node\Printer\OutlineTablePrinter; use Behat\Behat\Output\Node\Printer\SetupPrinter; use Behat\Behat\Tester\Result\StepResult; +use Behat\Gherkin\Node\ExampleNode; use Behat\Gherkin\Node\OutlineNode; use Behat\Testwork\Event\Event; use Behat\Testwork\Output\Formatter; @@ -215,6 +216,7 @@ private function printExampleRowOnAfterExampleEvent(Formatter $formatter, Event $this->stepSetupPrinter->printSetup($formatter, $beforeEvent->getSetup()); } + assert($example instanceof ExampleNode); $this->exampleRowPrinter->printExampleRow($formatter, $this->outline, $example, $this->stepAfterTestedEvents); foreach ($this->stepAfterTestedEvents as $afterEvent) { diff --git a/src/Behat/Behat/Output/Node/Printer/JUnit/JUnitFeaturePrinter.php b/src/Behat/Behat/Output/Node/Printer/JUnit/JUnitFeaturePrinter.php index b275d1653..4f3c8c4a4 100644 --- a/src/Behat/Behat/Output/Node/Printer/JUnit/JUnitFeaturePrinter.php +++ b/src/Behat/Behat/Output/Node/Printer/JUnit/JUnitFeaturePrinter.php @@ -69,7 +69,7 @@ public function printFooter(Formatter $formatter, TestResult $result) if (0 === count($stats)) { $totalCount = 0; } else { - $totalCount = array_sum($stats); + $totalCount = (int) array_sum($stats); } /** @var JUnitOutputPrinter $outputPrinter */ diff --git a/src/Behat/Behat/Output/Node/Printer/Pretty/PrettySetupPrinter.php b/src/Behat/Behat/Output/Node/Printer/Pretty/PrettySetupPrinter.php index 5475f51fe..6fda6aeca 100644 --- a/src/Behat/Behat/Output/Node/Printer/Pretty/PrettySetupPrinter.php +++ b/src/Behat/Behat/Output/Node/Printer/Pretty/PrettySetupPrinter.php @@ -117,9 +117,10 @@ private function printSetupHookCallResult(OutputPrinter $printer, CallResult $ca $style = $this->resultConverter->convertResultCodeToString($resultCode); $hook = $callResult->getCall()->getCallee(); $path = $hook->getPath(); + $hookName = (string) $hook; $printer->writeln( - sprintf('%s┌─ {+%s}@%s{-%s} {+comment}# %s{-comment}', $this->indentText, $style, $hook, $style, $path) + sprintf('%s┌─ {+%s}@%s{-%s} {+comment}# %s{-comment}', $this->indentText, $style, $hookName, $style, $path) ); $printer->writeln(sprintf('%s│', $this->indentText)); @@ -148,6 +149,7 @@ private function printTeardownHookCallResult(OutputPrinter $printer, CallResult $style = $this->resultConverter->convertResultCodeToString($resultCode); $hook = $callResult->getCall()->getCallee(); $path = $hook->getPath(); + $hookName = (string) $hook; $printer->writeln(sprintf('%s│', $this->indentText)); @@ -155,7 +157,7 @@ private function printTeardownHookCallResult(OutputPrinter $printer, CallResult $this->printHookCallException($printer, $callResult, $this->indentText); $printer->writeln( - sprintf('%s└─ {+%s}@%s{-%s} {+comment}# %s{-comment}', $this->indentText, $style, $hook, $style, $path) + sprintf('%s└─ {+%s}@%s{-%s} {+comment}# %s{-comment}', $this->indentText, $style, $hookName, $style, $path) ); if ($this->newlineAfter) { diff --git a/src/Behat/Behat/Output/Statistics/PhaseStatistics.php b/src/Behat/Behat/Output/Statistics/PhaseStatistics.php index c21e942c0..23bf0c94e 100644 --- a/src/Behat/Behat/Output/Statistics/PhaseStatistics.php +++ b/src/Behat/Behat/Output/Statistics/PhaseStatistics.php @@ -12,6 +12,7 @@ use Behat\Testwork\Counter\Timer; use Behat\Testwork\Counter\Memory; +use Behat\Testwork\Tester\Result\TestResult; /** * A TotalStatistics decorator to get statistics per phase. @@ -110,9 +111,9 @@ public function registerHookStat(HookStat $stat) /** * Returns counters for different scenario result codes. * - * @return array[] + * @return array + + + + + + */ - public function getScenarioStatCounts() + public function getScenarioStatCounts(): array { return $this->statistics->getScenarioStatCounts(); } @@ -140,7 +141,7 @@ public function getFailedScenarios() /** * Returns counters for different step result codes. * - * @return array[] + * @return array */ public function getStepStatCounts() { diff --git a/src/Behat/Behat/Output/Statistics/TotalStatistics.php b/src/Behat/Behat/Output/Statistics/TotalStatistics.php index 1b89e87a9..381354ec8 100644 --- a/src/Behat/Behat/Output/Statistics/TotalStatistics.php +++ b/src/Behat/Behat/Output/Statistics/TotalStatistics.php @@ -175,9 +175,9 @@ public function registerHookStat(HookStat $stat) /** * Returns counters for different scenario result codes. * - * @return array[] + * @return array */ - public function getScenarioStatCounts() + public function getScenarioStatCounts(): array { return $this->scenarioCounters; } @@ -205,7 +205,7 @@ public function getFailedScenarios() /** * Returns counters for different step result codes. * - * @return array[] + * @return array */ public function getStepStatCounts() { diff --git a/src/Behat/Testwork/EventDispatcher/TestworkEventDispatcher.php b/src/Behat/Testwork/EventDispatcher/TestworkEventDispatcher.php index cf96c5d78..7d276a63f 100644 --- a/src/Behat/Testwork/EventDispatcher/TestworkEventDispatcher.php +++ b/src/Behat/Testwork/EventDispatcher/TestworkEventDispatcher.php @@ -51,7 +51,7 @@ public function dispatch($event, $eventName = null): object return $this->bcAwareDispatch($eventName, $event); } - private function bcAwareDispatch(object $event, $eventName) + private function bcAwareDispatch(?object $event, $eventName) { if (null === $event) { $event = new Event(); From 3f20dd18516b2207f155a9672cf3227fe269a0ca Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lo=C3=AFc=20Fr=C3=A9mont?= Date: Thu, 5 Dec 2024 11:17:52 +0100 Subject: [PATCH 500/567] PHP Config - profile formatters --- features/preferred_profile.feature | 22 ++++--- .../Formatter/JUnitFormatterFactory.php | 7 +-- .../Formatter/PrettyFormatterFactory.php | 10 +-- .../Formatter/ProgressFormatterFactory.php | 7 +-- src/Behat/Config/Formatter/Formatter.php | 62 +++++++++++++++++++ .../Formatter/FormatterConfigInterface.php | 14 +++++ src/Behat/Config/Formatter/JUnitFormatter.php | 15 +++++ .../Config/Formatter/PrettyFormatter.php | 36 +++++++++++ .../Config/Formatter/ProgressFormatter.php | 26 ++++++++ src/Behat/Config/Profile.php | 15 +++++ tests/Behat/Tests/Config/ProfileTest.php | 48 ++++++++++++++ 11 files changed, 240 insertions(+), 22 deletions(-) create mode 100644 src/Behat/Config/Formatter/Formatter.php create mode 100644 src/Behat/Config/Formatter/FormatterConfigInterface.php create mode 100644 src/Behat/Config/Formatter/JUnitFormatter.php create mode 100644 src/Behat/Config/Formatter/PrettyFormatter.php create mode 100644 src/Behat/Config/Formatter/ProgressFormatter.php diff --git a/features/preferred_profile.feature b/features/preferred_profile.feature index a4d22cbc1..a6337210d 100644 --- a/features/preferred_profile.feature +++ b/features/preferred_profile.feature @@ -73,13 +73,21 @@ Feature: Preferred Profiles | 5 | 3 | 8 | | 5 | 5 | 10 | """ - And a file named "pretty.yml" with: + And a file named "pretty.php" with: """ - pretty_without_paths: - formatters: - progress: false - pretty: - paths: false + disableFormatter(ProgressFormatter::NAME) + ->withFormatter(new PrettyFormatter(paths: false)) + ; + + return (new Config())->withProfile($profile); """ And a file named "behat.yml" with: @@ -95,7 +103,7 @@ Feature: Preferred Profiles progress imports: - - pretty.yml + - pretty.php """ Scenario: diff --git a/src/Behat/Behat/Output/ServiceContainer/Formatter/JUnitFormatterFactory.php b/src/Behat/Behat/Output/ServiceContainer/Formatter/JUnitFormatterFactory.php index 5726c972b..ffd7934d8 100644 --- a/src/Behat/Behat/Output/ServiceContainer/Formatter/JUnitFormatterFactory.php +++ b/src/Behat/Behat/Output/ServiceContainer/Formatter/JUnitFormatterFactory.php @@ -10,6 +10,7 @@ namespace Behat\Behat\Output\ServiceContainer\Formatter; +use Behat\Config\Formatter\JUnitFormatter; use Behat\Testwork\Exception\ServiceContainer\ExceptionExtension; use Behat\Testwork\Output\ServiceContainer\Formatter\FormatterFactory; use Behat\Testwork\Output\ServiceContainer\OutputExtension; @@ -143,11 +144,9 @@ private function loadFormatter(ContainerBuilder $container) $container->setDefinition('output.junit.statistics', $definition); $definition = new Definition('Behat\Testwork\Output\NodeEventListeningFormatter', array( - 'junit', + JUnitFormatter::NAME, 'Outputs the failures in JUnit compatible files.', - array( - 'timer' => true, - ), + JUnitFormatter::defaults(), $this->createOutputPrinterDefinition(), new Definition('Behat\Testwork\Output\Node\EventListener\ChainEventListener', array( array( diff --git a/src/Behat/Behat/Output/ServiceContainer/Formatter/PrettyFormatterFactory.php b/src/Behat/Behat/Output/ServiceContainer/Formatter/PrettyFormatterFactory.php index bc865b3d2..eb574f844 100644 --- a/src/Behat/Behat/Output/ServiceContainer/Formatter/PrettyFormatterFactory.php +++ b/src/Behat/Behat/Output/ServiceContainer/Formatter/PrettyFormatterFactory.php @@ -14,6 +14,7 @@ use Behat\Behat\EventDispatcher\Event\BackgroundTested; use Behat\Behat\EventDispatcher\Event\OutlineTested; use Behat\Behat\EventDispatcher\Event\ScenarioTested; +use Behat\Config\Formatter\PrettyFormatter; use Behat\Testwork\Exception\ServiceContainer\ExceptionExtension; use Behat\Testwork\Output\ServiceContainer\Formatter\FormatterFactory; use Behat\Testwork\Output\ServiceContainer\OutputExtension; @@ -171,14 +172,9 @@ protected function loadFormatter(ContainerBuilder $container) $container->setDefinition('output.pretty.statistics', $definition); $definition = new Definition('Behat\Testwork\Output\NodeEventListeningFormatter', array( - 'pretty', + PrettyFormatter::NAME, 'Prints the feature as is.', - array( - 'timer' => true, - 'expand' => false, - 'paths' => true, - 'multiline' => true, - ), + PrettyFormatter::defaults(), $this->createOutputPrinterDefinition(), new Definition('Behat\Testwork\Output\Node\EventListener\ChainEventListener', array( array( diff --git a/src/Behat/Behat/Output/ServiceContainer/Formatter/ProgressFormatterFactory.php b/src/Behat/Behat/Output/ServiceContainer/Formatter/ProgressFormatterFactory.php index 77d474c93..c2c0ea2e5 100644 --- a/src/Behat/Behat/Output/ServiceContainer/Formatter/ProgressFormatterFactory.php +++ b/src/Behat/Behat/Output/ServiceContainer/Formatter/ProgressFormatterFactory.php @@ -10,6 +10,7 @@ namespace Behat\Behat\Output\ServiceContainer\Formatter; +use Behat\Config\Formatter\ProgressFormatter; use Behat\Testwork\Exception\ServiceContainer\ExceptionExtension; use Behat\Testwork\Output\ServiceContainer\Formatter\FormatterFactory; use Behat\Testwork\Output\ServiceContainer\OutputExtension; @@ -139,11 +140,9 @@ protected function loadFormatter(ContainerBuilder $container) $container->setDefinition('output.progress.statistics', $definition); $definition = new Definition('Behat\Testwork\Output\NodeEventListeningFormatter', array( - 'progress', + ProgressFormatter::NAME, 'Prints one character per step.', - array( - 'timer' => true - ), + ProgressFormatter::defaults(), $this->createOutputPrinterDefinition(), new Definition('Behat\Testwork\Output\Node\EventListener\ChainEventListener', array( array( diff --git a/src/Behat/Config/Formatter/Formatter.php b/src/Behat/Config/Formatter/Formatter.php new file mode 100644 index 000000000..e1ed4a8af --- /dev/null +++ b/src/Behat/Config/Formatter/Formatter.php @@ -0,0 +1,62 @@ +settings['output_verbosity'] = $level; + + return $this; + } + + public function withOutputPath(string $path): self + { + $this->settings['output_path'] = $path; + + return $this; + } + + public function withOutputDecorated(bool $decorated = true): self + { + $this->settings['output_decorate'] = $decorated; + + return $this; + } + + public function withOutputStyles(array $styles): self + { + $this->settings['output_styles'] = $styles; + + return $this; + } + + public function name(): string + { + return $this->name; + } + + public function toArray(): array + { + return $this->settings; + } + + public static function defaults(): array + { + return []; + } +} diff --git a/src/Behat/Config/Formatter/FormatterConfigInterface.php b/src/Behat/Config/Formatter/FormatterConfigInterface.php new file mode 100644 index 000000000..04537c970 --- /dev/null +++ b/src/Behat/Config/Formatter/FormatterConfigInterface.php @@ -0,0 +1,14 @@ + $timer, + 'expand' => $expand, + 'paths' => $paths, + 'multiline' => $multiline, + ]); + } + + public static function defaults(): array + { + return (new self())->toArray(); + } +} diff --git a/src/Behat/Config/Formatter/ProgressFormatter.php b/src/Behat/Config/Formatter/ProgressFormatter.php new file mode 100644 index 000000000..4efdf1803 --- /dev/null +++ b/src/Behat/Config/Formatter/ProgressFormatter.php @@ -0,0 +1,26 @@ + $timer, + ]); + } + + public static function defaults(): array + { + return (new self())->toArray(); + } +} diff --git a/src/Behat/Config/Profile.php b/src/Behat/Config/Profile.php index ebc434f6f..70664c090 100644 --- a/src/Behat/Config/Profile.php +++ b/src/Behat/Config/Profile.php @@ -5,6 +5,7 @@ namespace Behat\Config; use Behat\Config\Filter\FilterInterface; +use Behat\Config\Formatter\FormatterConfigInterface; use Behat\Testwork\ServiceContainer\Exception\ConfigurationLoadingException; final class Profile @@ -53,6 +54,20 @@ public function withFilter(FilterInterface $filter): self return $this; } + public function withFormatter(FormatterConfigInterface $formatter): self + { + $this->settings['formatters'][$formatter->name()] = $formatter->toArray(); + + return $this; + } + + public function disableFormatter(string $name): self + { + $this->settings['formatters'][$name] = false; + + return $this; + } + public function toArray(): array { return $this->settings; diff --git a/tests/Behat/Tests/Config/ProfileTest.php b/tests/Behat/Tests/Config/ProfileTest.php index 296ab8539..fe551ac6d 100644 --- a/tests/Behat/Tests/Config/ProfileTest.php +++ b/tests/Behat/Tests/Config/ProfileTest.php @@ -7,8 +7,12 @@ use Behat\Config\Extension; use Behat\Config\Filter\NameFilter; use Behat\Config\Filter\TagFilter; +use Behat\Config\Formatter\JUnitFormatter; +use Behat\Config\Formatter\PrettyFormatter; +use Behat\Config\Formatter\ProgressFormatter; use Behat\Config\Profile; use Behat\Config\Suite; +use Behat\Testwork\Output\Printer\Factory\OutputFactory; use Behat\Testwork\ServiceContainer\Exception\ConfigurationLoadingException; use PHPUnit\Framework\TestCase; @@ -121,4 +125,48 @@ public function testItThrowsAnExceptionWhenAddingExistingFilter(): void $profile->withFilter(new TagFilter('tag1')); } + + public function testAddingFormatters(): void + { + $profile = new Profile('default'); + + $profile + ->withFormatter((new PrettyFormatter(expand: true, paths: false))->withOutputVerbosity(OutputFactory::VERBOSITY_VERBOSE)) + ->withFormatter(new ProgressFormatter(timer: false)) + ->withFormatter(new JUnitFormatter()) + ; + + $this->assertEquals([ + 'formatters' => [ + 'pretty' => [ + 'timer' => true, + 'expand' => true, + 'paths' => false, + 'multiline' => true, + 'output_verbosity' => 2, + ], + 'progress' => [ + 'timer' => false, + ], + 'junit' => [], + ], + ], $profile->toArray()); + } + + public function testDisablingFormatters(): void + { + $profile = new Profile('default'); + + $profile->disableFormatter(PrettyFormatter::NAME); + $profile->disableFormatter(ProgressFormatter::NAME); + $profile->disableFormatter(JUnitFormatter::NAME); + + $this->assertEquals([ + 'formatters' => [ + 'pretty' => false, + 'progress' => false, + 'junit' => false, + ], + ], $profile->toArray()); + } } From 9c82cc56d0583ee8a9e365504c3d45ec73248e19 Mon Sep 17 00:00:00 2001 From: Carlos Granados Date: Tue, 3 Dec 2024 16:10:56 +0100 Subject: [PATCH 501/567] Apply InvalidArrayAccess rule --- psalm.xml | 3 +++ .../InitializedContextEnvironment.php | 2 +- .../Behat/Hook/Call/RuntimeFeatureHook.php | 17 ++++++++++++++--- .../Flow/FirstBackgroundFiresFirstListener.php | 2 +- src/Behat/Testwork/Call/Callee.php | 2 +- src/Behat/Testwork/Call/RuntimeCallee.php | 4 ++-- .../Testwork/Hook/Call/RuntimeSuiteHook.php | 16 +++++++++++++--- 7 files changed, 35 insertions(+), 11 deletions(-) diff --git a/psalm.xml b/psalm.xml index de9787aef..4c9cd0096 100644 --- a/psalm.xml +++ b/psalm.xml @@ -51,6 +51,9 @@ + diff --git a/src/Behat/Behat/Context/Environment/InitializedContextEnvironment.php b/src/Behat/Behat/Context/Environment/InitializedContextEnvironment.php index d377f61b1..16ef1d51a 100644 --- a/src/Behat/Behat/Context/Environment/InitializedContextEnvironment.php +++ b/src/Behat/Behat/Context/Environment/InitializedContextEnvironment.php @@ -149,7 +149,7 @@ public function bindCallee(Callee $callee) { $callable = $callee->getCallable(); - if ($callee->isAnInstanceMethod()) { + if ($callee->isAnInstanceMethod() && is_array($callable)) { return array($this->getContext($callable[0]), $callable[1]); } diff --git a/src/Behat/Behat/Hook/Call/RuntimeFeatureHook.php b/src/Behat/Behat/Hook/Call/RuntimeFeatureHook.php index 9bc9a554f..6d5d39df3 100644 --- a/src/Behat/Behat/Hook/Call/RuntimeFeatureHook.php +++ b/src/Behat/Behat/Hook/Call/RuntimeFeatureHook.php @@ -17,6 +17,8 @@ use Behat\Testwork\Call\Exception\BadCallbackException; use Behat\Testwork\Hook\Call\RuntimeFilterableHook; use Behat\Testwork\Hook\Scope\HookScope; +use ReflectionFunction; +use ReflectionMethod; /** * Represents a feature hook. @@ -30,7 +32,7 @@ abstract class RuntimeFeatureHook extends RuntimeFilterableHook * * @param string $scopeName * @param null|string $filterString - * @param callable $callable + * @param callable|array $callable * @param null|string $description * * @throws BadCallbackException If callback is method, but not a static one @@ -40,10 +42,19 @@ public function __construct($scopeName, $filterString, $callable, $description = parent::__construct($scopeName, $filterString, $callable, $description); if ($this->isAnInstanceMethod()) { + if (is_array($callable)) { + $className = $callable[0]; + $methodName = $callable[1]; + } else { + $reflection = new ReflectionMethod($callable); + $className = $reflection->getDeclaringClass()->getShortName(); + $methodName = $reflection->getName(); + } + throw new BadCallbackException(sprintf( 'Feature hook callback: %s::%s() must be a static method', - $callable[0], - $callable[1] + $className, + $methodName ), $callable); } } diff --git a/src/Behat/Behat/Output/Node/EventListener/Flow/FirstBackgroundFiresFirstListener.php b/src/Behat/Behat/Output/Node/EventListener/Flow/FirstBackgroundFiresFirstListener.php index 78983627a..e10f494fd 100644 --- a/src/Behat/Behat/Output/Node/EventListener/Flow/FirstBackgroundFiresFirstListener.php +++ b/src/Behat/Behat/Output/Node/EventListener/Flow/FirstBackgroundFiresFirstListener.php @@ -38,7 +38,7 @@ class FirstBackgroundFiresFirstListener implements EventListener */ private $firstBackgroundEnded = false; /** - * @var Event[] + * @var array + + */ private $delayedUntilBackgroundEnd = array(); diff --git a/src/Behat/Testwork/Call/Callee.php b/src/Behat/Testwork/Call/Callee.php index 17ed0f5cc..dd0c51e25 100644 --- a/src/Behat/Testwork/Call/Callee.php +++ b/src/Behat/Testwork/Call/Callee.php @@ -50,7 +50,7 @@ public function isAnInstanceMethod(); /** * Returns callable. * - * @return callable + * @return callable|array */ public function getCallable(); diff --git a/src/Behat/Testwork/Call/RuntimeCallee.php b/src/Behat/Testwork/Call/RuntimeCallee.php index 76e7a2740..f14d63d03 100644 --- a/src/Behat/Testwork/Call/RuntimeCallee.php +++ b/src/Behat/Testwork/Call/RuntimeCallee.php @@ -23,7 +23,7 @@ class RuntimeCallee implements Callee { /** - * @var callable + * @var callable|array */ private $callable; /** @@ -79,7 +79,7 @@ public function getPath() /** * Returns callable. * - * @return callable + * @return callable|array */ public function getCallable() { diff --git a/src/Behat/Testwork/Hook/Call/RuntimeSuiteHook.php b/src/Behat/Testwork/Hook/Call/RuntimeSuiteHook.php index 44b7f6573..49c5b9463 100644 --- a/src/Behat/Testwork/Hook/Call/RuntimeSuiteHook.php +++ b/src/Behat/Testwork/Hook/Call/RuntimeSuiteHook.php @@ -14,6 +14,7 @@ use Behat\Testwork\Hook\Scope\HookScope; use Behat\Testwork\Hook\Scope\SuiteScope; use Behat\Testwork\Suite\Suite; +use ReflectionMethod; /** * Represents suite hook executed in the runtime. @@ -27,7 +28,7 @@ abstract class RuntimeSuiteHook extends RuntimeFilterableHook * * @param string $scopeName * @param null|string $filterString - * @param callable $callable + * @param callable|array $callable * @param null|string $description * * @throws BadCallbackException If callback is method, but not a static one @@ -37,10 +38,19 @@ public function __construct($scopeName, $filterString, $callable, $description = parent::__construct($scopeName, $filterString, $callable, $description); if ($this->isAnInstanceMethod()) { + if (is_array($callable)) { + $className = $callable[0]; + $methodName = $callable[1]; + } else { + $reflection = new ReflectionMethod($callable); + $className = $reflection->getDeclaringClass()->getShortName(); + $methodName = $reflection->getName(); + } + throw new BadCallbackException(sprintf( 'Suite hook callback: %s::%s() must be a static method', - $callable[0], - $callable[1] + $className, + $methodName ), $callable); } } From 23c1c715ec930011eab9258cc6ce8ed6e1f1f951 Mon Sep 17 00:00:00 2001 From: Carlos Granados Date: Tue, 3 Dec 2024 16:23:13 +0100 Subject: [PATCH 502/567] Apply InvalidArrayAssignment and InvalidArrayOffset rules --- psalm.xml | 6 ++++++ src/Behat/Behat/Output/Statistics/PhaseStatistics.php | 6 +++--- src/Behat/Behat/Output/Statistics/TotalStatistics.php | 8 ++++---- 3 files changed, 13 insertions(+), 7 deletions(-) diff --git a/psalm.xml b/psalm.xml index 4c9cd0096..b5a68c3bf 100644 --- a/psalm.xml +++ b/psalm.xml @@ -54,6 +54,12 @@ + + diff --git a/src/Behat/Behat/Output/Statistics/PhaseStatistics.php b/src/Behat/Behat/Output/Statistics/PhaseStatistics.php index 23bf0c94e..fc4b045fb 100644 --- a/src/Behat/Behat/Output/Statistics/PhaseStatistics.php +++ b/src/Behat/Behat/Output/Statistics/PhaseStatistics.php @@ -10,9 +10,9 @@ namespace Behat\Behat\Output\Statistics; +use Behat\Behat\Tester\Result\StepResult; use Behat\Testwork\Counter\Timer; use Behat\Testwork\Counter\Memory; -use Behat\Testwork\Tester\Result\TestResult; /** * A TotalStatistics decorator to get statistics per phase. @@ -111,7 +111,7 @@ public function registerHookStat(HookStat $stat) /** * Returns counters for different scenario result codes. * - * @return array + + + + + * @return array */ public function getScenarioStatCounts(): array { @@ -141,7 +141,7 @@ public function getFailedScenarios() /** * Returns counters for different step result codes. * - * @return array + * @return array */ public function getStepStatCounts() { diff --git a/src/Behat/Behat/Output/Statistics/TotalStatistics.php b/src/Behat/Behat/Output/Statistics/TotalStatistics.php index 381354ec8..cdc641700 100644 --- a/src/Behat/Behat/Output/Statistics/TotalStatistics.php +++ b/src/Behat/Behat/Output/Statistics/TotalStatistics.php @@ -32,11 +32,11 @@ final class TotalStatistics implements Statistics */ private $memory; /** - * @var array + * @var array */ private $scenarioCounters = array(); /** - * @var array + * @var array */ private $stepCounters = array(); /** @@ -175,7 +175,7 @@ public function registerHookStat(HookStat $stat) /** * Returns counters for different scenario result codes. * - * @return array + * @return array */ public function getScenarioStatCounts(): array { @@ -205,7 +205,7 @@ public function getFailedScenarios() /** * Returns counters for different step result codes. * - * @return array + * @return array */ public function getStepStatCounts() { From 2f2c6c555e3980010bc58ab49132147d5cc106c9 Mon Sep 17 00:00:00 2001 From: Carlos Granados Date: Mon, 9 Dec 2024 16:56:36 +0000 Subject: [PATCH 503/567] Update callable doc type, move constant to TestResult --- src/Behat/Behat/Hook/Call/RuntimeFeatureHook.php | 3 +-- .../Output/Node/Printer/Helper/ResultToStringConverter.php | 3 +-- .../Behat/Output/Node/Printer/JUnit/JUnitFeaturePrinter.php | 3 +-- .../Behat/Output/Node/Printer/JUnit/JUnitStepPrinter.php | 2 +- .../Output/Node/Printer/Progress/ProgressStepPrinter.php | 2 +- src/Behat/Behat/Output/Statistics/PhaseStatistics.php | 3 ++- src/Behat/Behat/Output/Statistics/TotalStatistics.php | 6 +++--- src/Behat/Behat/Snippet/Cli/SnippetsController.php | 4 ++-- src/Behat/Behat/Tester/Result/StepResult.php | 1 - src/Behat/Testwork/Call/Callee.php | 2 +- src/Behat/Testwork/Call/RuntimeCallee.php | 4 ++-- src/Behat/Testwork/Hook/Call/RuntimeSuiteHook.php | 2 +- src/Behat/Testwork/Tester/Result/TestResult.php | 1 + 13 files changed, 17 insertions(+), 19 deletions(-) diff --git a/src/Behat/Behat/Hook/Call/RuntimeFeatureHook.php b/src/Behat/Behat/Hook/Call/RuntimeFeatureHook.php index 6d5d39df3..b4e8cfeff 100644 --- a/src/Behat/Behat/Hook/Call/RuntimeFeatureHook.php +++ b/src/Behat/Behat/Hook/Call/RuntimeFeatureHook.php @@ -17,7 +17,6 @@ use Behat\Testwork\Call\Exception\BadCallbackException; use Behat\Testwork\Hook\Call\RuntimeFilterableHook; use Behat\Testwork\Hook\Scope\HookScope; -use ReflectionFunction; use ReflectionMethod; /** @@ -32,7 +31,7 @@ abstract class RuntimeFeatureHook extends RuntimeFilterableHook * * @param string $scopeName * @param null|string $filterString - * @param callable|array $callable + * @param callable|array{class-string, string} $callable * @param null|string $description * * @throws BadCallbackException If callback is method, but not a static one diff --git a/src/Behat/Behat/Output/Node/Printer/Helper/ResultToStringConverter.php b/src/Behat/Behat/Output/Node/Printer/Helper/ResultToStringConverter.php index dabddfd7d..14f0fb7e3 100644 --- a/src/Behat/Behat/Output/Node/Printer/Helper/ResultToStringConverter.php +++ b/src/Behat/Behat/Output/Node/Printer/Helper/ResultToStringConverter.php @@ -10,7 +10,6 @@ namespace Behat\Behat\Output\Node\Printer\Helper; -use Behat\Behat\Tester\Result\StepResult; use Behat\Testwork\Tester\Result\TestResult; /** @@ -48,7 +47,7 @@ public function convertResultCodeToString($resultCode) return 'pending'; case TestResult::FAILED: return 'failed'; - case StepResult::UNDEFINED: + case TestResult::UNDEFINED: return 'undefined'; } diff --git a/src/Behat/Behat/Output/Node/Printer/JUnit/JUnitFeaturePrinter.php b/src/Behat/Behat/Output/Node/Printer/JUnit/JUnitFeaturePrinter.php index 4f3c8c4a4..5ad882bc6 100644 --- a/src/Behat/Behat/Output/Node/Printer/JUnit/JUnitFeaturePrinter.php +++ b/src/Behat/Behat/Output/Node/Printer/JUnit/JUnitFeaturePrinter.php @@ -13,7 +13,6 @@ use Behat\Behat\Output\Node\EventListener\JUnit\JUnitDurationListener; use Behat\Behat\Output\Node\Printer\FeaturePrinter; use Behat\Behat\Output\Statistics\PhaseStatistics; -use Behat\Behat\Tester\Result\StepResult; use Behat\Gherkin\Node\FeatureNode; use Behat\Testwork\Output\Formatter; use Behat\Testwork\Output\Printer\JUnitOutputPrinter; @@ -80,7 +79,7 @@ public function printFooter(Formatter $formatter, TestResult $result) 'tests' => $totalCount, 'skipped' => $stats[TestResult::SKIPPED], 'failures' => $stats[TestResult::FAILED], - 'errors' => $stats[TestResult::PENDING] + $stats[StepResult::UNDEFINED], + 'errors' => $stats[TestResult::PENDING] + $stats[TestResult::UNDEFINED], 'time' => $this->durationListener ? $this->durationListener->getFeatureDuration($this->currentFeature) : '', )); diff --git a/src/Behat/Behat/Output/Node/Printer/JUnit/JUnitStepPrinter.php b/src/Behat/Behat/Output/Node/Printer/JUnit/JUnitStepPrinter.php index dcca50d76..0fc7c1dae 100644 --- a/src/Behat/Behat/Output/Node/Printer/JUnit/JUnitStepPrinter.php +++ b/src/Behat/Behat/Output/Node/Printer/JUnit/JUnitStepPrinter.php @@ -69,7 +69,7 @@ public function printStep(Formatter $formatter, Scenario $scenario, StepNode $st $outputPrinter->addTestcaseChild('error', $attributes); break; - case StepResult::UNDEFINED: + case TestResult::UNDEFINED: $attributes['type'] = 'undefined'; $outputPrinter->addTestcaseChild('error', $attributes); break; diff --git a/src/Behat/Behat/Output/Node/Printer/Progress/ProgressStepPrinter.php b/src/Behat/Behat/Output/Node/Printer/Progress/ProgressStepPrinter.php index ca1656f9a..0d1f388b0 100644 --- a/src/Behat/Behat/Output/Node/Printer/Progress/ProgressStepPrinter.php +++ b/src/Behat/Behat/Output/Node/Printer/Progress/ProgressStepPrinter.php @@ -62,7 +62,7 @@ public function printStep(Formatter $formatter, Scenario $scenario, StepNode $st case TestResult::PENDING: $printer->write("{+$style}P{-$style}"); break; - case StepResult::UNDEFINED: + case TestResult::UNDEFINED: $printer->write("{+$style}U{-$style}"); break; case TestResult::FAILED: diff --git a/src/Behat/Behat/Output/Statistics/PhaseStatistics.php b/src/Behat/Behat/Output/Statistics/PhaseStatistics.php index fc4b045fb..dce642592 100644 --- a/src/Behat/Behat/Output/Statistics/PhaseStatistics.php +++ b/src/Behat/Behat/Output/Statistics/PhaseStatistics.php @@ -13,6 +13,7 @@ use Behat\Behat\Tester\Result\StepResult; use Behat\Testwork\Counter\Timer; use Behat\Testwork\Counter\Memory; +use Behat\Testwork\Tester\Result\TestResult; /** * A TotalStatistics decorator to get statistics per phase. @@ -111,7 +112,7 @@ public function registerHookStat(HookStat $stat) /** * Returns counters for different scenario result codes. * - * @return array + * @return array */ public function getScenarioStatCounts(): array { diff --git a/src/Behat/Behat/Output/Statistics/TotalStatistics.php b/src/Behat/Behat/Output/Statistics/TotalStatistics.php index cdc641700..398aad7d0 100644 --- a/src/Behat/Behat/Output/Statistics/TotalStatistics.php +++ b/src/Behat/Behat/Output/Statistics/TotalStatistics.php @@ -32,7 +32,7 @@ final class TotalStatistics implements Statistics */ private $memory; /** - * @var array + * @var array */ private $scenarioCounters = array(); /** @@ -76,7 +76,7 @@ public function resetAllCounters() $this->scenarioCounters = $this->stepCounters = array( TestResult::PASSED => 0, TestResult::FAILED => 0, - StepResult::UNDEFINED => 0, + TestResult::UNDEFINED => 0, TestResult::PENDING => 0, TestResult::SKIPPED => 0 ); @@ -175,7 +175,7 @@ public function registerHookStat(HookStat $stat) /** * Returns counters for different scenario result codes. * - * @return array + * @return array */ public function getScenarioStatCounts(): array { diff --git a/src/Behat/Behat/Snippet/Cli/SnippetsController.php b/src/Behat/Behat/Snippet/Cli/SnippetsController.php index 8ecdac5fb..58d480877 100644 --- a/src/Behat/Behat/Snippet/Cli/SnippetsController.php +++ b/src/Behat/Behat/Snippet/Cli/SnippetsController.php @@ -15,9 +15,9 @@ use Behat\Behat\Snippet\Printer\ConsoleSnippetPrinter; use Behat\Behat\Snippet\SnippetRegistry; use Behat\Behat\Snippet\SnippetWriter; -use Behat\Behat\Tester\Result\StepResult; use Behat\Testwork\Cli\Controller; use Behat\Testwork\EventDispatcher\Event\ExerciseCompleted; +use Behat\Testwork\Tester\Result\TestResult; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputOption; @@ -123,7 +123,7 @@ public function execute(InputInterface $input, OutputInterface $output) */ public function registerUndefinedStep(AfterStepTested $event) { - if (StepResult::UNDEFINED === $event->getTestResult()->getResultCode()) { + if (TestResult::UNDEFINED === $event->getTestResult()->getResultCode()) { $this->registry->registerUndefinedStep($event->getEnvironment(), $event->getStep()); } } diff --git a/src/Behat/Behat/Tester/Result/StepResult.php b/src/Behat/Behat/Tester/Result/StepResult.php index 87cec353d..b2e45cd17 100644 --- a/src/Behat/Behat/Tester/Result/StepResult.php +++ b/src/Behat/Behat/Tester/Result/StepResult.php @@ -19,5 +19,4 @@ */ interface StepResult extends TestResult { - public const UNDEFINED = 30; } diff --git a/src/Behat/Testwork/Call/Callee.php b/src/Behat/Testwork/Call/Callee.php index dd0c51e25..a2d66781d 100644 --- a/src/Behat/Testwork/Call/Callee.php +++ b/src/Behat/Testwork/Call/Callee.php @@ -50,7 +50,7 @@ public function isAnInstanceMethod(); /** * Returns callable. * - * @return callable|array + * @return callable|array{class-string, string} */ public function getCallable(); diff --git a/src/Behat/Testwork/Call/RuntimeCallee.php b/src/Behat/Testwork/Call/RuntimeCallee.php index f14d63d03..323523c5d 100644 --- a/src/Behat/Testwork/Call/RuntimeCallee.php +++ b/src/Behat/Testwork/Call/RuntimeCallee.php @@ -23,7 +23,7 @@ class RuntimeCallee implements Callee { /** - * @var callable|array + * @var callable|array{class-string, string} */ private $callable; /** @@ -79,7 +79,7 @@ public function getPath() /** * Returns callable. * - * @return callable|array + * @return callable|array{class-string, string} */ public function getCallable() { diff --git a/src/Behat/Testwork/Hook/Call/RuntimeSuiteHook.php b/src/Behat/Testwork/Hook/Call/RuntimeSuiteHook.php index 49c5b9463..71c7cde39 100644 --- a/src/Behat/Testwork/Hook/Call/RuntimeSuiteHook.php +++ b/src/Behat/Testwork/Hook/Call/RuntimeSuiteHook.php @@ -28,7 +28,7 @@ abstract class RuntimeSuiteHook extends RuntimeFilterableHook * * @param string $scopeName * @param null|string $filterString - * @param callable|array $callable + * @param callable|array{class-string, string} $callable * @param null|string $description * * @throws BadCallbackException If callback is method, but not a static one diff --git a/src/Behat/Testwork/Tester/Result/TestResult.php b/src/Behat/Testwork/Tester/Result/TestResult.php index 7c3df6ffe..e4c0d6565 100644 --- a/src/Behat/Testwork/Tester/Result/TestResult.php +++ b/src/Behat/Testwork/Tester/Result/TestResult.php @@ -20,6 +20,7 @@ interface TestResult public const PASSED = 0; public const SKIPPED = 10; public const PENDING = 20; + public const UNDEFINED = 30; public const FAILED = 99; /** From 6eff22440c5d3bea360f6d0ae9908cfaf209f0de Mon Sep 17 00:00:00 2001 From: Carlos Granados Date: Tue, 10 Dec 2024 10:12:32 +0100 Subject: [PATCH 504/567] Move functionality to common base class --- .../Behat/Hook/Call/RuntimeFeatureHook.php | 17 +-------------- src/Behat/Testwork/Call/RuntimeCallee.php | 21 +++++++++++++++++++ .../Testwork/Hook/Call/RuntimeSuiteHook.php | 17 +-------------- 3 files changed, 23 insertions(+), 32 deletions(-) diff --git a/src/Behat/Behat/Hook/Call/RuntimeFeatureHook.php b/src/Behat/Behat/Hook/Call/RuntimeFeatureHook.php index b4e8cfeff..bc3ae9a41 100644 --- a/src/Behat/Behat/Hook/Call/RuntimeFeatureHook.php +++ b/src/Behat/Behat/Hook/Call/RuntimeFeatureHook.php @@ -40,22 +40,7 @@ public function __construct($scopeName, $filterString, $callable, $description = { parent::__construct($scopeName, $filterString, $callable, $description); - if ($this->isAnInstanceMethod()) { - if (is_array($callable)) { - $className = $callable[0]; - $methodName = $callable[1]; - } else { - $reflection = new ReflectionMethod($callable); - $className = $reflection->getDeclaringClass()->getShortName(); - $methodName = $reflection->getName(); - } - - throw new BadCallbackException(sprintf( - 'Feature hook callback: %s::%s() must be a static method', - $className, - $methodName - ), $callable); - } + $this->throwIfInstanceMethod($callable, 'Feature'); } /** diff --git a/src/Behat/Testwork/Call/RuntimeCallee.php b/src/Behat/Testwork/Call/RuntimeCallee.php index 323523c5d..9c5978113 100644 --- a/src/Behat/Testwork/Call/RuntimeCallee.php +++ b/src/Behat/Testwork/Call/RuntimeCallee.php @@ -116,4 +116,25 @@ public function isAnInstanceMethod() return $this->reflection instanceof ReflectionMethod && !$this->reflection->isStatic(); } + + public function throwIfInstanceMethod(callable|array $callable, string $hookType): void + { + if ($this->isAnInstanceMethod()) { + if (is_array($callable)) { + $className = $callable[0]; + $methodName = $callable[1]; + } else { + $reflection = new ReflectionMethod($callable); + $className = $reflection->getDeclaringClass()->getShortName(); + $methodName = $reflection->getName(); + } + + throw new BadCallbackException(sprintf( + '%s hook callback: %s::%s() must be a static method', + $hookType, + $className, + $methodName + ), $callable); + } + } } diff --git a/src/Behat/Testwork/Hook/Call/RuntimeSuiteHook.php b/src/Behat/Testwork/Hook/Call/RuntimeSuiteHook.php index 71c7cde39..aa202e17c 100644 --- a/src/Behat/Testwork/Hook/Call/RuntimeSuiteHook.php +++ b/src/Behat/Testwork/Hook/Call/RuntimeSuiteHook.php @@ -37,22 +37,7 @@ public function __construct($scopeName, $filterString, $callable, $description = { parent::__construct($scopeName, $filterString, $callable, $description); - if ($this->isAnInstanceMethod()) { - if (is_array($callable)) { - $className = $callable[0]; - $methodName = $callable[1]; - } else { - $reflection = new ReflectionMethod($callable); - $className = $reflection->getDeclaringClass()->getShortName(); - $methodName = $reflection->getName(); - } - - throw new BadCallbackException(sprintf( - 'Suite hook callback: %s::%s() must be a static method', - $className, - $methodName - ), $callable); - } + $this->throwIfInstanceMethod($callable, 'Suite'); } /** From ecb165849b3454f53c76d47c68a503947c698259 Mon Sep 17 00:00:00 2001 From: Carlos Granados Date: Tue, 10 Dec 2024 10:37:48 +0100 Subject: [PATCH 505/567] Make method protected and add type definition Co-authored-by: Andrew Coulton --- src/Behat/Testwork/Call/RuntimeCallee.php | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/Behat/Testwork/Call/RuntimeCallee.php b/src/Behat/Testwork/Call/RuntimeCallee.php index 9c5978113..45bec20ce 100644 --- a/src/Behat/Testwork/Call/RuntimeCallee.php +++ b/src/Behat/Testwork/Call/RuntimeCallee.php @@ -117,7 +117,10 @@ public function isAnInstanceMethod() && !$this->reflection->isStatic(); } - public function throwIfInstanceMethod(callable|array $callable, string $hookType): void + /** + * @param callable|array{class-string, string} $callable + */ + protected function throwIfInstanceMethod(callable|array $callable, string $hookType): void { if ($this->isAnInstanceMethod()) { if (is_array($callable)) { From bd3e89993c5ca17886025a3094ee5f7e3d3221e6 Mon Sep 17 00:00:00 2001 From: Carlos Granados Date: Tue, 3 Dec 2024 17:42:20 +0100 Subject: [PATCH 506/567] Apply InvalidCast rule --- psalm.xml | 3 +++ .../Node/EventListener/Statistics/HookStatsListener.php | 2 +- .../Behat/Output/Node/Printer/Pretty/PrettySetupPrinter.php | 4 ++-- .../Output/Node/Printer/Pretty/PrettySkippedStepPrinter.php | 2 +- .../Behat/Output/Node/Printer/Pretty/PrettyStepPrinter.php | 2 +- 5 files changed, 8 insertions(+), 5 deletions(-) diff --git a/psalm.xml b/psalm.xml index b5a68c3bf..94d70aebf 100644 --- a/psalm.xml +++ b/psalm.xml @@ -60,6 +60,9 @@ + diff --git a/src/Behat/Behat/Output/Node/EventListener/Statistics/HookStatsListener.php b/src/Behat/Behat/Output/Node/EventListener/Statistics/HookStatsListener.php index 36d4cc0a2..2dbd6b542 100644 --- a/src/Behat/Behat/Output/Node/EventListener/Statistics/HookStatsListener.php +++ b/src/Behat/Behat/Output/Node/EventListener/Statistics/HookStatsListener.php @@ -111,7 +111,7 @@ private function captureHookStat(CallResult $hookCallResult) { $call = $hookCallResult->getCall(); $callee = $call->getCallee(); - $hook = (string) $callee; + $hook = $callee->__toString(); $scope = $call->getScope(); $path = $callee->getPath(); $stdOut = $hookCallResult->getStdOut(); diff --git a/src/Behat/Behat/Output/Node/Printer/Pretty/PrettySetupPrinter.php b/src/Behat/Behat/Output/Node/Printer/Pretty/PrettySetupPrinter.php index 6fda6aeca..a9d7970fc 100644 --- a/src/Behat/Behat/Output/Node/Printer/Pretty/PrettySetupPrinter.php +++ b/src/Behat/Behat/Output/Node/Printer/Pretty/PrettySetupPrinter.php @@ -117,7 +117,7 @@ private function printSetupHookCallResult(OutputPrinter $printer, CallResult $ca $style = $this->resultConverter->convertResultCodeToString($resultCode); $hook = $callResult->getCall()->getCallee(); $path = $hook->getPath(); - $hookName = (string) $hook; + $hookName = $hook->__toString(); $printer->writeln( sprintf('%s┌─ {+%s}@%s{-%s} {+comment}# %s{-comment}', $this->indentText, $style, $hookName, $style, $path) @@ -149,7 +149,7 @@ private function printTeardownHookCallResult(OutputPrinter $printer, CallResult $style = $this->resultConverter->convertResultCodeToString($resultCode); $hook = $callResult->getCall()->getCallee(); $path = $hook->getPath(); - $hookName = (string) $hook; + $hookName = $hook->__toString(); $printer->writeln(sprintf('%s│', $this->indentText)); diff --git a/src/Behat/Behat/Output/Node/Printer/Pretty/PrettySkippedStepPrinter.php b/src/Behat/Behat/Output/Node/Printer/Pretty/PrettySkippedStepPrinter.php index b8c8d464a..c179c41d0 100644 --- a/src/Behat/Behat/Output/Node/Printer/Pretty/PrettySkippedStepPrinter.php +++ b/src/Behat/Behat/Output/Node/Printer/Pretty/PrettySkippedStepPrinter.php @@ -145,7 +145,7 @@ private function getArgumentString(ArgumentInterface $argument, $collapse = fals return $text; } - return (string) $argument; + return $argument->__toString(); } /** diff --git a/src/Behat/Behat/Output/Node/Printer/Pretty/PrettyStepPrinter.php b/src/Behat/Behat/Output/Node/Printer/Pretty/PrettyStepPrinter.php index ee2e5d09e..755a771a2 100644 --- a/src/Behat/Behat/Output/Node/Printer/Pretty/PrettyStepPrinter.php +++ b/src/Behat/Behat/Output/Node/Printer/Pretty/PrettyStepPrinter.php @@ -196,7 +196,7 @@ private function getArgumentString(ArgumentInterface $argument, $collapse = fals return $text; } - return (string) $argument; + return $argument->__toString(); } /** From d7f65698ef9accf61ee2dd0294bb93a3be811d44 Mon Sep 17 00:00:00 2001 From: Carlos Granados + + Date: Tue, 3 Dec 2024 18:13:04 +0100 Subject: [PATCH 507/567] Apply InvalidCatch rule --- psalm.xml | 3 +++ src/Behat/Testwork/Exception/TestworkException.php | 4 +++- 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/psalm.xml b/psalm.xml index 94d70aebf..e73e9d371 100644 --- a/psalm.xml +++ b/psalm.xml @@ -63,6 +63,9 @@ + diff --git a/src/Behat/Testwork/Exception/TestworkException.php b/src/Behat/Testwork/Exception/TestworkException.php index a140b0053..e84c5137a 100644 --- a/src/Behat/Testwork/Exception/TestworkException.php +++ b/src/Behat/Testwork/Exception/TestworkException.php @@ -10,11 +10,13 @@ namespace Behat\Testwork\Exception; +use Throwable; + /** * All testwork exceptions implement this interface. * * @author Konstantin Kudryashov + + */ -interface TestworkException +interface TestworkException extends Throwable { } From 4ecdaea7e6a94c744b5d9e84d6f74c2b1241500a Mon Sep 17 00:00:00 2001 From: Carlos Granados Date: Tue, 3 Dec 2024 18:14:12 +0100 Subject: [PATCH 508/567] Apply several rules up to InvalidPropertyAssignmentValue --- psalm.xml | 27 +++++++++++++++++++ .../InitializedContextEnvironment.php | 2 +- .../EventListener/AST/OutlineListener.php | 5 ++-- .../Behat/Tester/Cli/RerunController.php | 2 +- src/Behat/Testwork/Counter/Timer.php | 2 +- 5 files changed, 33 insertions(+), 5 deletions(-) diff --git a/psalm.xml b/psalm.xml index e73e9d371..66c98969e 100644 --- a/psalm.xml +++ b/psalm.xml @@ -66,6 +66,33 @@ + + + + + + + + diff --git a/src/Behat/Behat/Context/Environment/InitializedContextEnvironment.php b/src/Behat/Behat/Context/Environment/InitializedContextEnvironment.php index 16ef1d51a..1c68e34be 100644 --- a/src/Behat/Behat/Context/Environment/InitializedContextEnvironment.php +++ b/src/Behat/Behat/Context/Environment/InitializedContextEnvironment.php @@ -28,7 +28,7 @@ final class InitializedContextEnvironment implements ContextEnvironment, ServiceContainerEnvironment { /** - * @var string + * @var Suite */ private $suite; /** diff --git a/src/Behat/Behat/Output/Node/EventListener/AST/OutlineListener.php b/src/Behat/Behat/Output/Node/EventListener/AST/OutlineListener.php index f49116a5e..e1ce4ada7 100644 --- a/src/Behat/Behat/Output/Node/EventListener/AST/OutlineListener.php +++ b/src/Behat/Behat/Output/Node/EventListener/AST/OutlineListener.php @@ -138,8 +138,9 @@ private function printExampleHeaderOnBeforeExampleEvent(Formatter $formatter, Ev $this->exampleSetupPrinter->printSetup($formatter, $event->getSetup()); - $this->example = $event->getScenario(); - assert($this->example instanceof ExampleNode); + $scenario = $event->getScenario(); + assert($scenario instanceof ExampleNode); + $this->example = $scenario; $this->examplePrinter->printHeader($formatter, $event->getFeature(), $this->example); } diff --git a/src/Behat/Behat/Tester/Cli/RerunController.php b/src/Behat/Behat/Tester/Cli/RerunController.php index bafe75122..b798968c6 100644 --- a/src/Behat/Behat/Tester/Cli/RerunController.php +++ b/src/Behat/Behat/Tester/Cli/RerunController.php @@ -39,7 +39,7 @@ final class RerunController implements Controller */ private $key; /** - * @var string[] + * @var array + + + + + + + + + + + + + + + + + + + */ private $lines = array(); diff --git a/src/Behat/Testwork/Counter/Timer.php b/src/Behat/Testwork/Counter/Timer.php index 65025a33e..d6d7405e7 100644 --- a/src/Behat/Testwork/Counter/Timer.php +++ b/src/Behat/Testwork/Counter/Timer.php @@ -51,7 +51,7 @@ public function stop() } /** - * @return null|float + * @return float * * @throws TimerException If timer has not been started */ From ee3164716140e9f01b7cb88c5bf7baa3d62a0534 Mon Sep 17 00:00:00 2001 From: Carlos Granados Date: Thu, 12 Dec 2024 17:23:58 +0100 Subject: [PATCH 509/567] Narrow types before string conversion --- .../Node/EventListener/Statistics/HookStatsListener.php | 5 +++-- .../Output/Node/Printer/Pretty/PrettySetupPrinter.php | 9 +++++---- .../Node/Printer/Pretty/PrettySkippedStepPrinter.php | 7 +++++-- .../Output/Node/Printer/Pretty/PrettyStepPrinter.php | 7 +++++-- 4 files changed, 18 insertions(+), 10 deletions(-) diff --git a/src/Behat/Behat/Output/Node/EventListener/Statistics/HookStatsListener.php b/src/Behat/Behat/Output/Node/EventListener/Statistics/HookStatsListener.php index 2dbd6b542..0c0a1e20f 100644 --- a/src/Behat/Behat/Output/Node/EventListener/Statistics/HookStatsListener.php +++ b/src/Behat/Behat/Output/Node/EventListener/Statistics/HookStatsListener.php @@ -17,6 +17,7 @@ use Behat\Testwork\EventDispatcher\Event\AfterSetup; use Behat\Testwork\EventDispatcher\Event\AfterTested; use Behat\Testwork\Exception\ExceptionPresenter; +use Behat\Testwork\Hook\Call\RuntimeHook; use Behat\Testwork\Hook\Tester\Setup\HookedSetup; use Behat\Testwork\Hook\Tester\Setup\HookedTeardown; use Behat\Testwork\Output\Formatter; @@ -111,7 +112,6 @@ private function captureHookStat(CallResult $hookCallResult) { $call = $hookCallResult->getCall(); $callee = $call->getCallee(); - $hook = $callee->__toString(); $scope = $call->getScope(); $path = $callee->getPath(); $stdOut = $hookCallResult->getStdOut(); @@ -119,7 +119,8 @@ private function captureHookStat(CallResult $hookCallResult) ? $this->exceptionPresenter->presentException($hookCallResult->getException()) : null; - $stat = new HookStat($hook, $path, $error, $stdOut); + assert($callee instanceof RuntimeHook); + $stat = new HookStat((string) $callee, $path, $error, $stdOut); if (!$stat->isSuccessful()) { $stat->setScope($scope); } diff --git a/src/Behat/Behat/Output/Node/Printer/Pretty/PrettySetupPrinter.php b/src/Behat/Behat/Output/Node/Printer/Pretty/PrettySetupPrinter.php index a9d7970fc..def94cc5d 100644 --- a/src/Behat/Behat/Output/Node/Printer/Pretty/PrettySetupPrinter.php +++ b/src/Behat/Behat/Output/Node/Printer/Pretty/PrettySetupPrinter.php @@ -14,6 +14,7 @@ use Behat\Behat\Output\Node\Printer\SetupPrinter; use Behat\Testwork\Call\CallResult; use Behat\Testwork\Exception\ExceptionPresenter; +use Behat\Testwork\Hook\Call\RuntimeHook; use Behat\Testwork\Hook\Tester\Setup\HookedSetup; use Behat\Testwork\Hook\Tester\Setup\HookedTeardown; use Behat\Testwork\Output\Formatter; @@ -117,10 +118,10 @@ private function printSetupHookCallResult(OutputPrinter $printer, CallResult $ca $style = $this->resultConverter->convertResultCodeToString($resultCode); $hook = $callResult->getCall()->getCallee(); $path = $hook->getPath(); - $hookName = $hook->__toString(); + assert($hook instanceof RuntimeHook); $printer->writeln( - sprintf('%s┌─ {+%s}@%s{-%s} {+comment}# %s{-comment}', $this->indentText, $style, $hookName, $style, $path) + sprintf('%s┌─ {+%s}@%s{-%s} {+comment}# %s{-comment}', $this->indentText, $style, $hook, $style, $path) ); $printer->writeln(sprintf('%s│', $this->indentText)); @@ -149,15 +150,15 @@ private function printTeardownHookCallResult(OutputPrinter $printer, CallResult $style = $this->resultConverter->convertResultCodeToString($resultCode); $hook = $callResult->getCall()->getCallee(); $path = $hook->getPath(); - $hookName = $hook->__toString(); $printer->writeln(sprintf('%s│', $this->indentText)); $this->printHookCallStdOut($printer, $callResult, $this->indentText); $this->printHookCallException($printer, $callResult, $this->indentText); + assert($hook instanceof RuntimeHook); $printer->writeln( - sprintf('%s└─ {+%s}@%s{-%s} {+comment}# %s{-comment}', $this->indentText, $style, $hookName, $style, $path) + sprintf('%s└─ {+%s}@%s{-%s} {+comment}# %s{-comment}', $this->indentText, $style, $hook, $style, $path) ); if ($this->newlineAfter) { diff --git a/src/Behat/Behat/Output/Node/Printer/Pretty/PrettySkippedStepPrinter.php b/src/Behat/Behat/Output/Node/Printer/Pretty/PrettySkippedStepPrinter.php index c179c41d0..49eb53dc1 100644 --- a/src/Behat/Behat/Output/Node/Printer/Pretty/PrettySkippedStepPrinter.php +++ b/src/Behat/Behat/Output/Node/Printer/Pretty/PrettySkippedStepPrinter.php @@ -19,6 +19,7 @@ use Behat\Gherkin\Node\PyStringNode; use Behat\Gherkin\Node\ScenarioLikeInterface as Scenario; use Behat\Gherkin\Node\StepNode; +use Behat\Gherkin\Node\TableNode; use Behat\Testwork\Output\Formatter; use Behat\Testwork\Output\Printer\OutputPrinter; use Behat\Testwork\Tester\Result\IntegerTestResult; @@ -144,8 +145,10 @@ private function getArgumentString(ArgumentInterface $argument, $collapse = fals return $text; } - - return $argument->__toString(); + if ($argument instanceof TableNode) { + return (string) $argument; + } + return ''; } /** diff --git a/src/Behat/Behat/Output/Node/Printer/Pretty/PrettyStepPrinter.php b/src/Behat/Behat/Output/Node/Printer/Pretty/PrettyStepPrinter.php index 755a771a2..47d98e549 100644 --- a/src/Behat/Behat/Output/Node/Printer/Pretty/PrettyStepPrinter.php +++ b/src/Behat/Behat/Output/Node/Printer/Pretty/PrettyStepPrinter.php @@ -20,6 +20,7 @@ use Behat\Gherkin\Node\PyStringNode; use Behat\Gherkin\Node\ScenarioLikeInterface as Scenario; use Behat\Gherkin\Node\StepNode; +use Behat\Gherkin\Node\TableNode; use Behat\Testwork\Exception\ExceptionPresenter; use Behat\Testwork\Output\Formatter; use Behat\Testwork\Output\Printer\OutputPrinter; @@ -195,8 +196,10 @@ private function getArgumentString(ArgumentInterface $argument, $collapse = fals return $text; } - - return $argument->__toString(); + if ($argument instanceof TableNode) { + return (string) $argument; + } + return ''; } /** From df27a0936e2b8d66166ca49c15e3a5a7f7252c20 Mon Sep 17 00:00:00 2001 From: Carlos Granados Date: Tue, 3 Dec 2024 18:53:28 +0100 Subject: [PATCH 510/567] Apply InvalidPropertyFetch and InvalidReturnStatement rules --- psalm.xml | 11 +++++++++++ .../Snippet/Generator/ContextSnippetGenerator.php | 2 +- .../EventDispatcher/Event/AfterBackgroundSetup.php | 4 ++-- .../EventDispatcher/Event/AfterBackgroundTested.php | 4 ++-- .../Event/BeforeBackgroundTeardown.php | 4 ++-- .../EventDispatcher/Event/BeforeBackgroundTested.php | 4 ++-- .../Gherkin/Specification/LazyFeatureIterator.php | 10 +++++----- src/Behat/Testwork/Tester/Result/ExceptionResult.php | 4 ++-- 8 files changed, 27 insertions(+), 16 deletions(-) diff --git a/psalm.xml b/psalm.xml index 66c98969e..970100fcd 100644 --- a/psalm.xml +++ b/psalm.xml @@ -93,6 +93,17 @@ + + diff --git a/src/Behat/Behat/Context/Snippet/Generator/ContextSnippetGenerator.php b/src/Behat/Behat/Context/Snippet/Generator/ContextSnippetGenerator.php index 8a2ddce66..6ac393a44 100644 --- a/src/Behat/Behat/Context/Snippet/Generator/ContextSnippetGenerator.php +++ b/src/Behat/Behat/Context/Snippet/Generator/ContextSnippetGenerator.php @@ -242,7 +242,7 @@ private function getMethodNumberFromTheMethodName(string $methodName): int /** * Tries to guess method name that is not yet defined in the context class. * - * @return array + + + + + + + + + + * @return array{string, int} */ private function getMethodNameNotExistentInContext(ReflectionClass $reflection, string $methodName, int $methodNumber): array { diff --git a/src/Behat/Behat/EventDispatcher/Event/AfterBackgroundSetup.php b/src/Behat/Behat/EventDispatcher/Event/AfterBackgroundSetup.php index 59b32ad63..151aef606 100644 --- a/src/Behat/Behat/EventDispatcher/Event/AfterBackgroundSetup.php +++ b/src/Behat/Behat/EventDispatcher/Event/AfterBackgroundSetup.php @@ -12,7 +12,7 @@ use Behat\Gherkin\Node\BackgroundNode; use Behat\Gherkin\Node\FeatureNode; -use Behat\Gherkin\Node\ScenarioInterface; +use Behat\Gherkin\Node\ScenarioLikeInterface; use Behat\Testwork\Environment\Environment; use Behat\Testwork\EventDispatcher\Event\AfterSetup; use Behat\Testwork\Tester\Setup\Setup; @@ -67,7 +67,7 @@ public function getFeature() /** * Returns scenario node. * - * @return ScenarioInterface + * @return ScenarioLikeInterface */ public function getScenario() { diff --git a/src/Behat/Behat/EventDispatcher/Event/AfterBackgroundTested.php b/src/Behat/Behat/EventDispatcher/Event/AfterBackgroundTested.php index 76e15774c..68e8215e9 100644 --- a/src/Behat/Behat/EventDispatcher/Event/AfterBackgroundTested.php +++ b/src/Behat/Behat/EventDispatcher/Event/AfterBackgroundTested.php @@ -12,7 +12,7 @@ use Behat\Gherkin\Node\BackgroundNode; use Behat\Gherkin\Node\FeatureNode; -use Behat\Gherkin\Node\ScenarioInterface; +use Behat\Gherkin\Node\ScenarioLikeInterface; use Behat\Testwork\Environment\Environment; use Behat\Testwork\EventDispatcher\Event\AfterTested; use Behat\Testwork\Tester\Result\TestResult; @@ -79,7 +79,7 @@ public function getFeature() /** * Returns scenario node. * - * @return ScenarioInterface + * @return ScenarioLikeInterface */ public function getScenario() { diff --git a/src/Behat/Behat/EventDispatcher/Event/BeforeBackgroundTeardown.php b/src/Behat/Behat/EventDispatcher/Event/BeforeBackgroundTeardown.php index b41671723..08f85b83b 100644 --- a/src/Behat/Behat/EventDispatcher/Event/BeforeBackgroundTeardown.php +++ b/src/Behat/Behat/EventDispatcher/Event/BeforeBackgroundTeardown.php @@ -12,7 +12,7 @@ use Behat\Gherkin\Node\BackgroundNode; use Behat\Gherkin\Node\FeatureNode; -use Behat\Gherkin\Node\ScenarioInterface; +use Behat\Gherkin\Node\ScenarioLikeInterface; use Behat\Testwork\Environment\Environment; use Behat\Testwork\EventDispatcher\Event\BeforeTeardown; use Behat\Testwork\Tester\Result\TestResult; @@ -71,7 +71,7 @@ public function getFeature() /** * Returns scenario node. * - * @return ScenarioInterface + * @return ScenarioLikeInterface */ public function getScenario() { diff --git a/src/Behat/Behat/EventDispatcher/Event/BeforeBackgroundTested.php b/src/Behat/Behat/EventDispatcher/Event/BeforeBackgroundTested.php index d88a6f969..73e0ae780 100644 --- a/src/Behat/Behat/EventDispatcher/Event/BeforeBackgroundTested.php +++ b/src/Behat/Behat/EventDispatcher/Event/BeforeBackgroundTested.php @@ -12,7 +12,7 @@ use Behat\Gherkin\Node\BackgroundNode; use Behat\Gherkin\Node\FeatureNode; -use Behat\Gherkin\Node\ScenarioInterface; +use Behat\Gherkin\Node\ScenarioLikeInterface; use Behat\Testwork\Environment\Environment; use Behat\Testwork\EventDispatcher\Event\BeforeTested; @@ -60,7 +60,7 @@ public function getFeature() /** * Returns scenario node. * - * @return ScenarioInterface + * @return ScenarioLikeInterface */ public function getScenario() { diff --git a/src/Behat/Behat/Gherkin/Specification/LazyFeatureIterator.php b/src/Behat/Behat/Gherkin/Specification/LazyFeatureIterator.php index b205ebea0..fe605b4cd 100644 --- a/src/Behat/Behat/Gherkin/Specification/LazyFeatureIterator.php +++ b/src/Behat/Behat/Gherkin/Specification/LazyFeatureIterator.php @@ -10,7 +10,7 @@ namespace Behat\Behat\Gherkin\Specification; -use Behat\Gherkin\Filter\FilterInterface; +use Behat\Gherkin\Filter\FeatureFilterInterface; use Behat\Gherkin\Filter\NameFilter; use Behat\Gherkin\Filter\NarrativeFilter; use Behat\Gherkin\Filter\RoleFilter; @@ -41,7 +41,7 @@ final class LazyFeatureIterator implements SpecificationIterator */ private $paths = array(); /** - * @var FilterInterface[] + * @var FeatureFilterInterface[] */ private $filters = array(); /** @@ -63,7 +63,7 @@ final class LazyFeatureIterator implements SpecificationIterator * @param Suite $suite * @param Gherkin $gherkin * @param string[] $paths - * @param FilterInterface[] $filters + * @param FeatureFilterInterface[] $filters */ public function __construct(Suite $suite, Gherkin $gherkin, array $paths, array $filters = array()) { @@ -127,7 +127,7 @@ public function current(): FeatureNode * * @param Suite $suite * - * @return FilterInterface[] + * @return FeatureFilterInterface[] */ private function getSuiteFilters(Suite $suite) { @@ -150,7 +150,7 @@ private function getSuiteFilters(Suite $suite) * @param string $filterString * @param Suite $suite * - * @return FilterInterface + * @return FeatureFilterInterface * * @throws SuiteConfigurationException If filter type is not recognised */ diff --git a/src/Behat/Testwork/Tester/Result/ExceptionResult.php b/src/Behat/Testwork/Tester/Result/ExceptionResult.php index 1b724f5c3..819648819 100644 --- a/src/Behat/Testwork/Tester/Result/ExceptionResult.php +++ b/src/Behat/Testwork/Tester/Result/ExceptionResult.php @@ -10,7 +10,7 @@ namespace Behat\Testwork\Tester\Result; -use Exception; +use Throwable; /** * Represents a result, that possibly produced an exception. @@ -29,7 +29,7 @@ public function hasException(); /** * Returns exception that test result has. * - * @return null|Exception + * @return null|Throwable */ public function getException(); } From 26116ef9c8666e0c71e577b4ea04b5e405e5c186 Mon Sep 17 00:00:00 2001 From: Carlos Granados Date: Tue, 3 Dec 2024 19:52:21 +0100 Subject: [PATCH 511/567] Apply InvalidTemplateParam and NullArgument rules --- psalm.xml | 6 ++++++ .../Context/Snippet/Generator/FixedContextIdentifier.php | 3 --- .../Context/Snippet/Generator/FixedPatternIdentifier.php | 3 --- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/psalm.xml b/psalm.xml index 970100fcd..3d441db40 100644 --- a/psalm.xml +++ b/psalm.xml @@ -104,6 +104,12 @@ + + diff --git a/src/Behat/Behat/Context/Snippet/Generator/FixedContextIdentifier.php b/src/Behat/Behat/Context/Snippet/Generator/FixedContextIdentifier.php index b194b9b96..be6c008c4 100644 --- a/src/Behat/Behat/Context/Snippet/Generator/FixedContextIdentifier.php +++ b/src/Behat/Behat/Context/Snippet/Generator/FixedContextIdentifier.php @@ -19,9 +19,6 @@ */ final class FixedContextIdentifier implements TargetContextIdentifier { - /** - * Initialises identifier. - */ public function __construct( private readonly ?string $contextClass = null ) { diff --git a/src/Behat/Behat/Context/Snippet/Generator/FixedPatternIdentifier.php b/src/Behat/Behat/Context/Snippet/Generator/FixedPatternIdentifier.php index c5dabd78b..8fa8ef24d 100644 --- a/src/Behat/Behat/Context/Snippet/Generator/FixedPatternIdentifier.php +++ b/src/Behat/Behat/Context/Snippet/Generator/FixedPatternIdentifier.php @@ -17,9 +17,6 @@ */ final class FixedPatternIdentifier implements PatternIdentifier { - /** - * Initialises identifier. - */ public function __construct( private readonly ?string $patternType = null ) { From d0b63d2d8a375153036539632b7b5c3aee309b7c Mon Sep 17 00:00:00 2001 From: Carlos Granados + + + + Date: Tue, 17 Dec 2024 17:14:15 +0100 Subject: [PATCH 512/567] Use doc-block to suppress Psalm error --- psalm.xml | 1 - .../Behat/Context/Environment/InitializedContextEnvironment.php | 2 ++ 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/psalm.xml b/psalm.xml index 3d441db40..1d731c795 100644 --- a/psalm.xml +++ b/psalm.xml @@ -99,7 +99,6 @@ diff --git a/src/Behat/Behat/Context/Environment/InitializedContextEnvironment.php b/src/Behat/Behat/Context/Environment/InitializedContextEnvironment.php index 1c68e34be..216111ad9 100644 --- a/src/Behat/Behat/Context/Environment/InitializedContextEnvironment.php +++ b/src/Behat/Behat/Context/Environment/InitializedContextEnvironment.php @@ -87,6 +87,7 @@ public function hasContexts() /** * {@inheritdoc} + * @psalm-suppress InvalidReturnStatement */ public function getContextClasses() { @@ -105,6 +106,7 @@ public function hasContextClass($class) * Returns list of registered context instances. * * @return list - + * @psalm-suppress InvalidReturnStatement */ public function getContexts() { From f978f4b76374f6b2f3964fc556b55b0a52945137 Mon Sep 17 00:00:00 2001 From: Carlos Granados Date: Tue, 17 Dec 2024 17:20:22 +0100 Subject: [PATCH 513/567] Add deprecations in getScenario methods in Background classes --- src/Behat/Behat/EventDispatcher/Event/AfterBackgroundSetup.php | 2 ++ src/Behat/Behat/EventDispatcher/Event/AfterBackgroundTested.php | 2 ++ .../Behat/EventDispatcher/Event/BeforeBackgroundTeardown.php | 2 ++ .../Behat/EventDispatcher/Event/BeforeBackgroundTested.php | 2 ++ 4 files changed, 8 insertions(+) diff --git a/src/Behat/Behat/EventDispatcher/Event/AfterBackgroundSetup.php b/src/Behat/Behat/EventDispatcher/Event/AfterBackgroundSetup.php index 151aef606..144475f80 100644 --- a/src/Behat/Behat/EventDispatcher/Event/AfterBackgroundSetup.php +++ b/src/Behat/Behat/EventDispatcher/Event/AfterBackgroundSetup.php @@ -67,6 +67,8 @@ public function getFeature() /** * Returns scenario node. * + * @deprecated Use getBackground() instead + * * @return ScenarioLikeInterface */ public function getScenario() diff --git a/src/Behat/Behat/EventDispatcher/Event/AfterBackgroundTested.php b/src/Behat/Behat/EventDispatcher/Event/AfterBackgroundTested.php index 68e8215e9..d84c85084 100644 --- a/src/Behat/Behat/EventDispatcher/Event/AfterBackgroundTested.php +++ b/src/Behat/Behat/EventDispatcher/Event/AfterBackgroundTested.php @@ -79,6 +79,8 @@ public function getFeature() /** * Returns scenario node. * + * @deprecated Use getBackground() instead + * * @return ScenarioLikeInterface */ public function getScenario() diff --git a/src/Behat/Behat/EventDispatcher/Event/BeforeBackgroundTeardown.php b/src/Behat/Behat/EventDispatcher/Event/BeforeBackgroundTeardown.php index 08f85b83b..d09a5eecd 100644 --- a/src/Behat/Behat/EventDispatcher/Event/BeforeBackgroundTeardown.php +++ b/src/Behat/Behat/EventDispatcher/Event/BeforeBackgroundTeardown.php @@ -71,6 +71,8 @@ public function getFeature() /** * Returns scenario node. * + * @deprecated Use getBackground() instead + * * @return ScenarioLikeInterface */ public function getScenario() diff --git a/src/Behat/Behat/EventDispatcher/Event/BeforeBackgroundTested.php b/src/Behat/Behat/EventDispatcher/Event/BeforeBackgroundTested.php index 73e0ae780..ed9832267 100644 --- a/src/Behat/Behat/EventDispatcher/Event/BeforeBackgroundTested.php +++ b/src/Behat/Behat/EventDispatcher/Event/BeforeBackgroundTested.php @@ -60,6 +60,8 @@ public function getFeature() /** * Returns scenario node. * + * @deprecated Use getBackground() instead + * * @return ScenarioLikeInterface */ public function getScenario() From 9acb63727f9586aca376287d61f54b9792244b00 Mon Sep 17 00:00:00 2001 From: Andrew Coulton Date: Tue, 17 Dec 2024 18:20:10 +0000 Subject: [PATCH 514/567] chore: Fix typo in return type annotation Fixes a typo that slipped in with #1549 as per https://github.com/Behat/Behat/pull/1549#discussion_r1875747963 --- .../Behat/Context/Snippet/Generator/ContextSnippetGenerator.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Behat/Behat/Context/Snippet/Generator/ContextSnippetGenerator.php b/src/Behat/Behat/Context/Snippet/Generator/ContextSnippetGenerator.php index 8a2ddce66..0dbbd4fd6 100644 --- a/src/Behat/Behat/Context/Snippet/Generator/ContextSnippetGenerator.php +++ b/src/Behat/Behat/Context/Snippet/Generator/ContextSnippetGenerator.php @@ -278,7 +278,7 @@ private function getMethodNameNotProposedEarlier(string $contextClass, string $s /** * Returns already proposed method names. * - * @return array + * @return array */ private function getAlreadyProposedMethods(string $contextClass): array { From e0bdcb9c7039c64bbaf712b5dff35b01dcb8859a Mon Sep 17 00:00:00 2001 From: Carlos Granados Date: Tue, 3 Dec 2024 20:35:00 +0100 Subject: [PATCH 515/567] Apply several rules up to UndefinedMethod --- psalm.xml | 15 +++++++++++++++ .../Factory/TransformationCalleeFactory.php | 3 ++- .../Testwork/Argument/MixedArgumentOrganiser.php | 9 ++++----- .../ServiceContainer/AutoloaderExtension.php | 6 ++++-- .../Output/Printer/JUnitOutputPrinter.php | 5 +++-- .../Output/ServiceContainer/OutputExtension.php | 5 ++++- .../Suite/ServiceContainer/SuiteExtension.php | 5 ++++- 7 files changed, 36 insertions(+), 12 deletions(-) diff --git a/psalm.xml b/psalm.xml index 1d731c795..71fe28935 100644 --- a/psalm.xml +++ b/psalm.xml @@ -109,6 +109,21 @@ + + + + diff --git a/src/Behat/Behat/Transformation/Context/Factory/TransformationCalleeFactory.php b/src/Behat/Behat/Transformation/Context/Factory/TransformationCalleeFactory.php index 7207a2bb3..7e16ffe30 100644 --- a/src/Behat/Behat/Transformation/Context/Factory/TransformationCalleeFactory.php +++ b/src/Behat/Behat/Transformation/Context/Factory/TransformationCalleeFactory.php @@ -10,6 +10,7 @@ namespace Behat\Behat\Transformation\Context\Factory; +use Behat\Behat\Transformation\SimpleArgumentTransformation; use Behat\Behat\Transformation\Transformation; use Behat\Behat\Transformation\Transformation\ColumnBasedTableTransformation; use Behat\Behat\Transformation\Transformation\PatternTransformation; @@ -45,7 +46,7 @@ public static function create(string $contextClass, ReflectionMethod $method, st /** * Returns list of default transformations. * - * @return class-string + + + + + + + + + + + [] + * @return class-string[] */ private static function simpleTransformations() { diff --git a/src/Behat/Testwork/Argument/MixedArgumentOrganiser.php b/src/Behat/Testwork/Argument/MixedArgumentOrganiser.php index f9a6a4b54..a51510e54 100644 --- a/src/Behat/Testwork/Argument/MixedArgumentOrganiser.php +++ b/src/Behat/Testwork/Argument/MixedArgumentOrganiser.php @@ -12,8 +12,10 @@ use ReflectionFunctionAbstract; use ReflectionClass; +use ReflectionNamedType; use ReflectionParameter; use ReflectionException; +use ReflectionUnionType; /** * Organises function arguments using its reflection. @@ -241,13 +243,10 @@ private function getReflectionClassesFromParameter(\ReflectionParameter $paramet $type = $parameter->getType(); - /** - * @psalm-suppress UndefinedClass (ReflectionUnionType) - */ - if ($type instanceof \ReflectionNamedType) { + if ($type instanceof ReflectionNamedType) { $types = [$type]; } - elseif ($parameter->getType() instanceof \ReflectionUnionType) { + elseif ($type instanceof ReflectionUnionType) { $types = $type->getTypes(); } else { diff --git a/src/Behat/Testwork/Autoloader/ServiceContainer/AutoloaderExtension.php b/src/Behat/Testwork/Autoloader/ServiceContainer/AutoloaderExtension.php index 3908e0f15..7b2cd7ddf 100644 --- a/src/Behat/Testwork/Autoloader/ServiceContainer/AutoloaderExtension.php +++ b/src/Behat/Testwork/Autoloader/ServiceContainer/AutoloaderExtension.php @@ -67,7 +67,7 @@ public function initialize(ExtensionManager $extensionManager) */ public function configure(ArrayNodeDefinition $builder) { - $builder + $builder = $builder ->beforeNormalization() ->ifString()->then(function ($path) { return array('' => $path); @@ -78,7 +78,9 @@ public function configure(ArrayNodeDefinition $builder) ->treatTrueLike($this->defaultPaths) ->treatNullLike(array()) ->treatFalseLike(array()) - + ; + assert($builder instanceof ArrayNodeDefinition); + $builder ->prototype('scalar')->end() ; } diff --git a/src/Behat/Testwork/Output/Printer/JUnitOutputPrinter.php b/src/Behat/Testwork/Output/Printer/JUnitOutputPrinter.php index 833bf4b72..19428d046 100644 --- a/src/Behat/Testwork/Output/Printer/JUnitOutputPrinter.php +++ b/src/Behat/Testwork/Output/Printer/JUnitOutputPrinter.php @@ -141,8 +141,9 @@ public function setFileName($fileName, $extension = 'xml') if ('.'.$extension !== substr($fileName, strlen($extension) + 1)) { $fileName .= '.'.$extension; } - - $this->getOutputFactory()->setFileName($fileName); + $outputFactory = $this->getOutputFactory(); + assert($outputFactory instanceof FilesystemOutputFactory); + $outputFactory->setFileName($fileName); $this->flush(); } diff --git a/src/Behat/Testwork/Output/ServiceContainer/OutputExtension.php b/src/Behat/Testwork/Output/ServiceContainer/OutputExtension.php index 65f5609f2..bffaf38b8 100644 --- a/src/Behat/Testwork/Output/ServiceContainer/OutputExtension.php +++ b/src/Behat/Testwork/Output/ServiceContainer/OutputExtension.php @@ -95,7 +95,7 @@ public function initialize(ExtensionManager $extensionManager) */ public function configure(ArrayNodeDefinition $builder) { - $builder + $builder = $builder ->defaultValue(array($this->defaultFormatter => array('enabled' => true))) ->useAttributeAsKey('name') ->prototype('array') @@ -107,6 +107,9 @@ public function configure(ArrayNodeDefinition $builder) return array_merge($a, array('enabled' => true)); }) ->end() + ; + assert($builder instanceof ArrayNodeDefinition); + $builder ->useAttributeAsKey('name') ->treatTrueLike(array('enabled' => true)) ->treatNullLike(array('enabled' => true)) diff --git a/src/Behat/Testwork/Suite/ServiceContainer/SuiteExtension.php b/src/Behat/Testwork/Suite/ServiceContainer/SuiteExtension.php index 9999cb7ba..a684a2965 100644 --- a/src/Behat/Testwork/Suite/ServiceContainer/SuiteExtension.php +++ b/src/Behat/Testwork/Suite/ServiceContainer/SuiteExtension.php @@ -73,7 +73,7 @@ public function initialize(ExtensionManager $extensionManager) */ public function configure(ArrayNodeDefinition $builder) { - $builder + $builder = $builder ->defaultValue(array('default' => array( 'enabled' => true, 'type' => null, @@ -102,6 +102,9 @@ public function configure(ArrayNodeDefinition $builder) return $suite; }) ->end() + ; + assert($builder instanceof ArrayNodeDefinition); + $builder ->normalizeKeys(false) ->addDefaultsIfNotSet() ->treatTrueLike(array('enabled' => true)) From 936699a2798c4b967241a94e4f07d3eb78bbe84a Mon Sep 17 00:00:00 2001 From: Carlos Granados Date: Wed, 4 Dec 2024 10:02:03 +0100 Subject: [PATCH 516/567] Apply InvalidReturnType and fully move to level 6 --- psalm.xml | 69 +++---------------- .../InitializedContextEnvironment.php | 4 +- .../Testwork/Ordering/Cli/OrderController.php | 3 +- 3 files changed, 12 insertions(+), 64 deletions(-) diff --git a/psalm.xml b/psalm.xml index 71fe28935..c8fe029b7 100644 --- a/psalm.xml +++ b/psalm.xml @@ -1,6 +1,6 @@ - + - - - - - - - - - - - - - - - - - - - + @@ -43,83 +43,30 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + - diff --git a/src/Behat/Behat/Context/Environment/InitializedContextEnvironment.php b/src/Behat/Behat/Context/Environment/InitializedContextEnvironment.php index 216111ad9..64a6a1343 100644 --- a/src/Behat/Behat/Context/Environment/InitializedContextEnvironment.php +++ b/src/Behat/Behat/Context/Environment/InitializedContextEnvironment.php @@ -87,7 +87,7 @@ public function hasContexts() /** * {@inheritdoc} - * @psalm-suppress InvalidReturnStatement + * @psalm-suppress InvalidReturnStatement, InvalidReturnType */ public function getContextClasses() { @@ -106,7 +106,7 @@ public function hasContextClass($class) * Returns list of registered context instances. * * @return list - * @psalm-suppress InvalidReturnStatement + * @psalm-suppress InvalidReturnStatement, InvalidReturnType */ public function getContexts() { diff --git a/src/Behat/Testwork/Ordering/Cli/OrderController.php b/src/Behat/Testwork/Ordering/Cli/OrderController.php index 12edd91f1..b73487317 100644 --- a/src/Behat/Testwork/Ordering/Cli/OrderController.php +++ b/src/Behat/Testwork/Ordering/Cli/OrderController.php @@ -77,7 +77,7 @@ public function execute(InputInterface $input, OutputInterface $output) $orderer = $input->getOption('order'); if (!$orderer) { - return; + return null; } if (!array_key_exists($orderer, $this->orderers)) { @@ -85,6 +85,7 @@ public function execute(InputInterface $input, OutputInterface $output) } $this->exercise->setOrderer($this->orderers[$orderer]); + return null; } /** From b729b10862b6190e81a81bfde62f34644a1edfca Mon Sep 17 00:00:00 2001 From: acoulton Date: Wed, 18 Dec 2024 09:30:21 +0000 Subject: [PATCH 517/567] chore: Add changelog for 3.17.0 release --- CHANGELOG.md | 42 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 516add15f..56b1a548c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,47 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](http://keepachangelog.com/) and this project adheres to [Semantic Versioning](http://semver.org/). +## [3.17.0] - 2024-12-18 + +### Changed + +* Use attributes rather than annotations when generating suggested Context snippets + by @fmatsos in [#1549](https://github.com/Behat/Behat/pull/1549) and [#1569](https://github.com/Behat/Behat/pull/1569) +* Disable Xdebug unless `--xdebug` is specified on the CLI, to improve performance by @carlos-granados in [#1560](https://github.com/Behat/Behat/pull/1560) + +### Added + +* :partying_face: Support configuring Behat with a PHP file and helper objects / methods - see [the docs](https://docs.behat.org/en/latest/user_guide/configuration/suites.html) + by @loic425 in [#1537](https://github.com/Behat/Behat/pull/1537), [#1538](https://github.com/Behat/Behat/pull/1538), + [#1550](https://github.com/Behat/Behat/pull/1550), [#1547](https://github.com/Behat/Behat/pull/1547), + [#1540](https://github.com/Behat/Behat/pull/1540), [#1546](https://github.com/Behat/Behat/pull/1546), + [#1556](https://github.com/Behat/Behat/pull/1556), [#1557](https://github.com/Behat/Behat/pull/1557) and + [#1558](https://github.com/Behat/Behat/pull/1558). +* Display location of hook failure in progress printer by @carlos-granados in [#1526](https://github.com/Behat/Behat/pull/1526) +* Print failed hooks summary at the end of the pretty format by @carlos-granados in [#1530](https://github.com/Behat/Behat/pull/1530) +* Print `` nodes for all hook failures in the junit output by @carlos-granados in [#1536](https://github.com/Behat/Behat/pull/1536) +* Add the `#[Transform]` attribute, equivalent to the `@Transform` annotation by @carlos-granados in [#1545](https://github.com/Behat/Behat/pull/1545) +* Allow using the `--narrative` filter on the command line by @carlos-granados in [#1559](https://github.com/Behat/Behat/pull/1559) + +### Fixed + +* Show more meaningful message if no `output_path` is specified for the junit formatter by @carlos-granados in [#1533](https://github.com/Behat/Behat/pull/1533) +* Fix error from the JUnit printer if scenario has no title by @mvhirsch in [#1525](https://github.com/Behat/Behat/pull/1525) +* Fix naming of suggested methods when generating regex snippets for steps defined with single quotes by @carlos-granados in [#1524](https://github.com/Behat/Behat/pull/1524) + +### Internal + +* Improve / fix docblock annotations and type-safety within methods to achieve Psalm level 6 + by @carlos-granados in [#1554](https://github.com/Behat/Behat/pull/1554), [#1562](https://github.com/Behat/Behat/pull/1562), + [#1566](https://github.com/Behat/Behat/pull/1566), [#1568](https://github.com/Behat/Behat/pull/1568) + [#1570](https://github.com/Behat/Behat/pull/1570). +* Improve failure output of Behat's own tests with unexpected status code or output by @jdeniau in [#1532](https://github.com/Behat/Behat/pull/1532) +* Remove redundant tests for hook failures in junit formatter by @carlos-granados in [#1543](https://github.com/Behat/Behat/pull/1543) +* Update .editorconfig indent size to 2 for feature files by @carlos-granados in [#1528](https://github.com/Behat/Behat/pull/1528) +* Update static analysis to use Psalm v5 by @carlos-granados in [#1548](https://github.com/Behat/Behat/pull/1548) +* Remove tagging of tests that require PHP8, as these now always run by @carlos-granados in [#1551](https://github.com/Behat/Behat/pull/1551) +* Add composer scripts for testing tools by @carlos-granados in [#1555](https://github.com/Behat/Behat/pull/1555) + ## [3.16.0] - 2024-11-08 ### Changed @@ -1101,6 +1142,7 @@ and this project adheres to [Semantic Versioning](http://semver.org/). ### Changed * Initial release +[3.17.0]: https://github.com/Behat/Behat/compare/v3.16.0...v3.17.0 [3.16.0]: https://github.com/Behat/Behat/compare/v3.15.0...v3.16.0 [3.15.0]: https://github.com/Behat/Behat/compare/v3.14.0...v3.15.0 [3.14.0]: https://github.com/Behat/Behat/compare/v3.13.0...v3.14.0 From 02c6cf1ec28d561559adfd05c8e1e23a581ffe8b Mon Sep 17 00:00:00 2001 From: Franck Matsos Date: Fri, 13 Dec 2024 11:02:25 +0100 Subject: [PATCH 518/567] fix: override context parent attributes Closes #1565 Signed-off-by: Franck Matsos --- features/definitions_override.feature | 2 +- .../definitions_override_attributes.feature | 112 ++++++++++++++++++ .../Context/Reader/AttributeContextReader.php | 29 ++++- 3 files changed, 141 insertions(+), 2 deletions(-) create mode 100644 features/definitions_override_attributes.feature diff --git a/features/definitions_override.feature b/features/definitions_override.feature index 6ee2ebdf3..e3008d108 100644 --- a/features/definitions_override.feature +++ b/features/definitions_override.feature @@ -1,7 +1,7 @@ Feature: Step Definitions Override In order to fine-tune definitions defined in parent classes As a step definitions developer - I need to be able to override definition methods + I need to be able to override definition methods using annotations Scenario: Overridden method without own annotation will inherit parent pattern Given a file named "features/bootstrap/FeatureContext.php" with: diff --git a/features/definitions_override_attributes.feature b/features/definitions_override_attributes.feature new file mode 100644 index 000000000..72128d311 --- /dev/null +++ b/features/definitions_override_attributes.feature @@ -0,0 +1,112 @@ +Feature: Step Definitions Override Attributes + In order to fine-tune definitions defined in parent classes + As a step definitions developer + I need to be able to override definition methods using step definition attributes + + Scenario: Overridden method without own attribute will inherit parent pattern + Given a file named "features/bootstrap/FeatureContext.php" with: + """ + getMethods(ReflectionMethod::IS_PUBLIC) as $method) { foreach ($this->readMethodCallees($reflection->getName(), $method) as $callee) { $callees[] = $callee; @@ -57,8 +59,33 @@ public function readContextCallees(ContextEnvironment $environment, $contextClas private function readMethodCallees(string $contextClass, ReflectionMethod $method) { $callees = []; + foreach ($this->readers as $reader) { - $callees = array_merge($callees, $reader->readCallees($contextClass, $method)); + $callees = array_merge( + $this->readParentCallees($contextClass, $method, $reader, $callees), + $reader->readCallees($contextClass, $method) + ); + } + + return $callees; + } + + /** + * @return array + */ + public function readParentCallees( + string $contextClass, + ReflectionMethod $method, + AttributeReader $reader, + array $callees + ): array { + try { + $prototype = $method->getPrototype(); + + if ($prototype->getDeclaringClass()->getName() !== $method->getDeclaringClass()->getName()) { + $callees = array_merge($callees, $reader->readCallees($contextClass, $prototype)); + } + } catch (\ReflectionException) { } return $callees; From 85574a5f39cf81525f078f6f5f7858dcf2933e9d Mon Sep 17 00:00:00 2001 From: Carlos Granados Date: Wed, 18 Dec 2024 10:01:22 +0100 Subject: [PATCH 519/567] DX: initial install of PHPStan --- .github/workflows/build.yml | 3 +++ composer.json | 5 ++++- phpstan.dist.neon | 16 ++++++++++++++++ .../Printer/Pretty/PrettyScenarioPrinter.php | 4 ++-- .../Exception/FormatterNotFoundException.php | 1 + 5 files changed, 26 insertions(+), 3 deletions(-) create mode 100644 phpstan.dist.neon diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 7e1875882..18ca6e7ec 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -109,6 +109,9 @@ jobs: - name: Run Psalm run: ./vendor/bin/psalm --output-format=github --php-version=${{ matrix.php }} + - name: Run PHPStan + run: ./vendor/bin/phpstan + build-phar: name: Build PHAR file runs-on: ubuntu-latest diff --git a/composer.json b/composer.json index 0e1a72ebb..9b0cbcd99 100644 --- a/composer.json +++ b/composer.json @@ -31,6 +31,7 @@ "require-dev": { "herrera-io/box": "~1.6.1", + "phpstan/phpstan": "^2.0", "phpunit/phpunit": "^9.6", "sebastian/diff": "^4.0", "symfony/polyfill-php84": "^1.31", @@ -69,10 +70,12 @@ "all-tests": [ "@behat-progress", "@phpunit", - "@psalm" + "@psalm", + "@phpstan" ], "behat": "LANG=C bin/behat --rerun", "behat-progress": "LANG=C bin/behat --format=progress", + "phpstan": "phpstan", "phpunit": "phpunit", "psalm": "psalm" }, diff --git a/phpstan.dist.neon b/phpstan.dist.neon new file mode 100644 index 000000000..fce48e6f0 --- /dev/null +++ b/phpstan.dist.neon @@ -0,0 +1,16 @@ +parameters: + level: 1 + paths: + - src + excludePaths: + - src/Behat/Testwork/EventDispatcher/TestworkEventDispatcherSymfonyLegacy.php + - src/Behat/Testwork/EventDispatcher/TestworkEventDispatcherSymfony5.php + ignoreErrors: + - + identifier: class.notFound + paths: + - src/Behat/Testwork/Exception/Stringer/PHPUnitExceptionStringer.php + - + identifier: constructor.unusedParameter + paths: + - src/Behat/Behat/Transformation/Transformation/ReturnTypeTransformation.php diff --git a/src/Behat/Behat/Output/Node/Printer/Pretty/PrettyScenarioPrinter.php b/src/Behat/Behat/Output/Node/Printer/Pretty/PrettyScenarioPrinter.php index 28f3adccc..94e264ae7 100644 --- a/src/Behat/Behat/Output/Node/Printer/Pretty/PrettyScenarioPrinter.php +++ b/src/Behat/Behat/Output/Node/Printer/Pretty/PrettyScenarioPrinter.php @@ -106,7 +106,7 @@ private function printKeyword(OutputPrinter $printer, $keyword) * Prints scenario title (first line of long title). * * @param OutputPrinter $printer - * @param string $longTitle + * @param string|null $longTitle */ private function printTitle(OutputPrinter $printer, $longTitle) { @@ -122,7 +122,7 @@ private function printTitle(OutputPrinter $printer, $longTitle) * Prints scenario description (other lines of long title). * * @param OutputPrinter $printer - * @param string $longTitle + * @param string|null $longTitle */ private function printDescription(OutputPrinter $printer, $longTitle) { diff --git a/src/Behat/Testwork/Output/Exception/FormatterNotFoundException.php b/src/Behat/Testwork/Output/Exception/FormatterNotFoundException.php index 43b33718d..3d857ec27 100644 --- a/src/Behat/Testwork/Output/Exception/FormatterNotFoundException.php +++ b/src/Behat/Testwork/Output/Exception/FormatterNotFoundException.php @@ -33,6 +33,7 @@ class FormatterNotFoundException extends InvalidArgumentException implements Out public function __construct($message, $name) { parent::__construct($message); + $this->name = $name; } /** From 1540046ae5fedf3c929262f7cae24c12bb90e147 Mon Sep 17 00:00:00 2001 From: Franck Matsos Date: Tue, 10 Dec 2024 12:10:56 +0100 Subject: [PATCH 520/567] feat: migrate annotations to attributes for features Signed-off-by: Franck Matsos feat: migrate annotations to attributes for features Signed-off-by: Franck Matsos --- features/append_snippets.feature | 168 ++--- features/arguments.feature | 22 +- features/catch_throwable.feature | 10 +- ...xt.feature => context_annotations.feature} | 4 +- features/context_attributes.feature | 505 ++++++++++++++ ... definitions_override_annotations.feature} | 4 +- .../definitions_override_attributes.feature | 38 ++ ... definitions_patterns_annotations.feature} | 4 +- .../definitions_patterns_attributes.feature | 619 ++++++++++++++++++ ...tions_transformations_annotations.feature} | 6 +- ...itions_transformations_attributes.feature} | 0 ...initions_translations_annotations.feature} | 4 +- ...efinitions_translations_attributes.feature | 423 ++++++++++++ features/dry_run.feature | 24 +- features/env_var_placeholders.feature | 5 +- features/error_reporting.feature | 33 +- features/execution_order.feature | 5 +- features/format_options.feature | 27 +- ...ooks.feature => hooks_annotations.feature} | 4 +- features/hooks_attributes.feature | 551 ++++++++++++++++ ... hooks_failures_junit_annotations.feature} | 4 +- .../hooks_failures_junit_attributes.feature | 390 +++++++++++ ...hooks_failures_pretty_annotations.feature} | 4 +- .../hooks_failures_pretty_attributes.feature | 205 ++++++ ...oks_failures_progress_annotations.feature} | 4 +- ...hooks_failures_progress_attributes.feature | 206 ++++++ ...{i18n.feature => i18n_annotations.feature} | 4 +- features/i18n_attributes.feature | 274 ++++++++ features/junit_format.feature | 127 ++-- features/multiple_formats.feature | 27 +- features/name_filters.feature | 13 +- features/outlines.feature | 41 +- features/parameters.feature | 23 +- features/preferred_profile.feature | 23 +- features/pretty_format.feature | 49 +- features/profile_filters.feature | 13 +- features/profiles.feature | 23 +- features/rerun-only.feature | 27 +- features/rerun.feature | 27 +- features/rerun_strict.feature | 9 +- features/rerun_with_multiple_suite.feature | 27 +- features/result_types.feature | 68 +- features/syntax_help.feature | 102 ++- features/tag_filters.feature | 13 +- features/traits.feature | 20 +- .../Context/Reader/AttributeContextReader.php | 2 +- 46 files changed, 3576 insertions(+), 605 deletions(-) rename features/{context.feature => context_annotations.feature} (99%) create mode 100644 features/context_attributes.feature rename features/{definitions_override.feature => definitions_override_annotations.feature} (93%) rename features/{definitions_patterns.feature => definitions_patterns_annotations.feature} (99%) create mode 100644 features/definitions_patterns_attributes.feature rename features/{definitions_transformations.feature => definitions_transformations_annotations.feature} (99%) rename features/{definitions_transformations_attribute.feature => definitions_transformations_attributes.feature} (100%) rename features/{definitions_translations.feature => definitions_translations_annotations.feature} (99%) create mode 100644 features/definitions_translations_attributes.feature rename features/{hooks.feature => hooks_annotations.feature} (99%) create mode 100644 features/hooks_attributes.feature rename features/{hooks_failures_junit.feature => hooks_failures_junit_annotations.feature} (99%) create mode 100644 features/hooks_failures_junit_attributes.feature rename features/{hooks_failures_pretty.feature => hooks_failures_pretty_annotations.feature} (98%) create mode 100644 features/hooks_failures_pretty_attributes.feature rename features/{hooks_failures_progress.feature => hooks_failures_progress_annotations.feature} (98%) create mode 100644 features/hooks_failures_progress_attributes.feature rename features/{i18n.feature => i18n_annotations.feature} (99%) create mode 100644 features/i18n_attributes.feature diff --git a/features/append_snippets.feature b/features/append_snippets.feature index 42eee611f..7080d307a 100644 --- a/features/append_snippets.feature +++ b/features/append_snippets.feature @@ -12,6 +12,9 @@ Feature: Append snippets option Behat\Behat\Tester\Exception\PendingException; use Behat\Gherkin\Node\PyStringNode, Behat\Gherkin\Node\TableNode; + use Behat\Step\Given; + use Behat\Step\Then; + use Behat\Step\When; class FeatureContext implements Context { @@ -22,44 +25,32 @@ Feature: Append snippets option $this->parameters = $parameters; } - /** - * @Given /^I have (\d+) apples?$/ - */ + #[Given('/^I have (\d+) apples?$/')] public function iHaveApples($count) { $this->apples = intval($count); } - /** - * @When /^I ate (\d+) apples?$/ - */ + #[When('/^I ate (\d+) apples?$/')] public function iAteApples($count) { $this->apples -= intval($count); } - /** - * @When /^I found (\d+) apples?$/ - */ + #[When('/^I found (\d+) apples?$/')] public function iFoundApples($count) { $this->apples += intval($count); } - /** - * @Then /^I should have (\d+) apples$/ - */ + #[Then('/^I should have (\d+) apples$/')] public function iShouldHaveApples($count) { \PHPUnit\Framework\Assert::assertEquals(intval($count), $this->apples); } - /** - * @Then /^context parameter "([^"]*)" should be equal to "([^"]*)"$/ - */ + #[Then('/^context parameter "([^"]*)" should be equal to "([^"]*)"$/')] public function contextParameterShouldBeEqualTo($key, $val) { \PHPUnit\Framework\Assert::assertEquals($val, $this->parameters[$key]); } - /** - * @Given /^context parameter "([^"]*)" should be array with (\d+) elements$/ - */ + #[Given('/^context parameter "([^"]*)" should be array with (\d+) elements$/')] public function contextParameterShouldBeArrayWithElements($key, $count) { \PHPUnit\Framework\Assert::assertIsArray($this->parameters[$key]); \PHPUnit\Framework\Assert::assertEquals(2, count($this->parameters[$key])); @@ -123,12 +114,13 @@ Feature: Append snippets option """ parameters = $parameters; } - /** - * @Given /^I have (\d+) apples?$/ - */ + #[Given('/^I have (\d+) apples?$/')] public function iHaveApples($count) { $this->apples = intval($count); } - /** - * @When /^I ate (\d+) apples?$/ - */ + #[When('/^I ate (\d+) apples?$/')] public function iAteApples($count) { $this->apples -= intval($count); } - /** - * @When /^I found (\d+) apples?$/ - */ + #[When('/^I found (\d+) apples?$/')] public function iFoundApples($count) { $this->apples += intval($count); } - /** - * @Then /^I should have (\d+) apples$/ - */ + #[Then('/^I should have (\d+) apples$/')] public function iShouldHaveApples($count) { \PHPUnit\Framework\Assert::assertEquals(intval($count), $this->apples); } - /** - * @Then /^context parameter "([^"]*)" should be equal to "([^"]*)"$/ - */ + #[Then('/^context parameter "([^"]*)" should be equal to "([^"]*)"$/')] public function contextParameterShouldBeEqualTo($key, $val) { \PHPUnit\Framework\Assert::assertEquals($val, $this->parameters[$key]); } - /** - * @Given /^context parameter "([^"]*)" should be array with (\d+) elements$/ - */ + #[Given('/^context parameter "([^"]*)" should be array with (\d+) elements$/')] public function contextParameterShouldBeArrayWithElements($key, $count) { \PHPUnit\Framework\Assert::assertIsArray($this->parameters[$key]); \PHPUnit\Framework\Assert::assertEquals(2, count($this->parameters[$key])); @@ -224,6 +204,9 @@ Feature: Append snippets option use Behat\Behat\Context\Context; use Behat\Gherkin\Node\PyStringNode, Behat\Gherkin\Node\TableNode; + use Behat\Step\Given; + use Behat\Step\Then; + use Behat\Step\When; class FeatureContext implements Context { @@ -234,44 +217,32 @@ Feature: Append snippets option $this->parameters = $parameters; } - /** - * @Given /^I have (\d+) apples?$/ - */ + #[Given('/^I have (\d+) apples?$/')] public function iHaveApples($count) { $this->apples = intval($count); } - /** - * @When /^I ate (\d+) apples?$/ - */ + #[When('/^I ate (\d+) apples?$/')] public function iAteApples($count) { $this->apples -= intval($count); } - /** - * @When /^I found (\d+) apples?$/ - */ + #[When('/^I found (\d+) apples?$/')] public function iFoundApples($count) { $this->apples += intval($count); } - /** - * @Then /^I should have (\d+) apples$/ - */ + #[Then('/^I should have (\d+) apples$/')] public function iShouldHaveApples($count) { \PHPUnit\Framework\Assert::assertEquals(intval($count), $this->apples); } - /** - * @Then /^context parameter "([^"]*)" should be equal to "([^"]*)"$/ - */ + #[Then('/^context parameter "([^"]*)" should be equal to "([^"]*)"$/')] public function contextParameterShouldBeEqualTo($key, $val) { \PHPUnit\Framework\Assert::assertEquals($val, $this->parameters[$key]); } - /** - * @Given /^context parameter "([^"]*)" should be array with (\d+) elements$/ - */ + #[Given('/^context parameter "([^"]*)" should be array with (\d+) elements$/')] public function contextParameterShouldBeArrayWithElements($key, $count) { \PHPUnit\Framework\Assert::assertIsArray($this->parameters[$key]); \PHPUnit\Framework\Assert::assertEquals(2, count($this->parameters[$key])); @@ -285,12 +256,13 @@ Feature: Append snippets option """ parameters = $parameters; } - /** - * @Given /^I have (\d+) apples?$/ - */ + #[Given('/^I have (\d+) apples?$/')] public function iHaveApples($count) { $this->apples = intval($count); } - /** - * @When /^I ate (\d+) apples?$/ - */ + #[When('/^I ate (\d+) apples?$/')] public function iAteApples($count) { $this->apples -= intval($count); } - /** - * @When /^I found (\d+) apples?$/ - */ + #[When('/^I found (\d+) apples?$/')] public function iFoundApples($count) { $this->apples += intval($count); } - /** - * @Then /^I should have (\d+) apples$/ - */ + #[Then('/^I should have (\d+) apples$/')] public function iShouldHaveApples($count) { \PHPUnit\Framework\Assert::assertEquals(intval($count), $this->apples); } - /** - * @Then /^context parameter "([^"]*)" should be equal to "([^"]*)"$/ - */ + #[Then('/^context parameter "([^"]*)" should be equal to "([^"]*)"$/')] public function contextParameterShouldBeEqualTo($key, $val) { \PHPUnit\Framework\Assert::assertEquals($val, $this->parameters[$key]); } - /** - * @Given /^context parameter "([^"]*)" should be array with (\d+) elements$/ - */ + #[Given('/^context parameter "([^"]*)" should be array with (\d+) elements$/')] public function contextParameterShouldBeArrayWithElements($key, $count) { \PHPUnit\Framework\Assert::assertIsArray($this->parameters[$key]); \PHPUnit\Framework\Assert::assertEquals(2, count($this->parameters[$key])); @@ -384,6 +344,9 @@ Feature: Append snippets option parameters = $parameters; } - /** - * @Given /^I have (\d+) apples?$/ - */ + #[Given('/^I have (\d+) apples?$/')] public function iHaveApples($count) { $this->apples = intval($count); } - /** - * @When /^I ate (\d+) apples?$/ - */ + #[When('/^I ate (\d+) apples?$/')] public function iAteApples($count) { $this->apples -= intval($count); } - /** - * @When /^I found (\d+) apples?$/ - */ + #[When('/^I found (\d+) apples?$/')] public function iFoundApples($count) { $this->apples += intval($count); } - /** - * @Then /^I should have (\d+) apples$/ - */ + #[Then('/^I should have (\d+) apples$/')] public function iShouldHaveApples($count) { \PHPUnit\Framework\Assert::assertEquals(intval($count), $this->apples); } - /** - * @Then /^context parameter "([^"]*)" should be equal to "([^"]*)"$/ - */ + #[Then('/^context parameter "([^"]*)" should be equal to "([^"]*)"$/')] public function contextParameterShouldBeEqualTo($key, $val) { \PHPUnit\Framework\Assert::assertEquals($val, $this->parameters[$key]); } - /** - * @Given /^context parameter "([^"]*)" should be array with (\d+) elements$/ - */ + #[Given('/^context parameter "([^"]*)" should be array with (\d+) elements$/')] public function contextParameterShouldBeArrayWithElements($key, $count) { \PHPUnit\Framework\Assert::assertIsArray($this->parameters[$key]); \PHPUnit\Framework\Assert::assertEquals(2, count($this->parameters[$key])); @@ -447,10 +398,11 @@ Feature: Append snippets option use Behat\Gherkin\Node\TableNode; use Behat\Gherkin\Node\PyStringNode; - use Behat\Step\Given; - use Behat\Step\Then; use Behat\Behat\Tester\Exception\PendingException; use Behat\Behat\Context\Context; + use Behat\Step\Given; + use Behat\Step\Then; + use Behat\Step\When; class FeatureContext implements Context { @@ -461,44 +413,32 @@ Feature: Append snippets option $this->parameters = $parameters; } - /** - * @Given /^I have (\d+) apples?$/ - */ + #[Given('/^I have (\d+) apples?$/')] public function iHaveApples($count) { $this->apples = intval($count); } - /** - * @When /^I ate (\d+) apples?$/ - */ + #[When('/^I ate (\d+) apples?$/')] public function iAteApples($count) { $this->apples -= intval($count); } - /** - * @When /^I found (\d+) apples?$/ - */ + #[When('/^I found (\d+) apples?$/')] public function iFoundApples($count) { $this->apples += intval($count); } - /** - * @Then /^I should have (\d+) apples$/ - */ + #[Then('/^I should have (\d+) apples$/')] public function iShouldHaveApples($count) { \PHPUnit\Framework\Assert::assertEquals(intval($count), $this->apples); } - /** - * @Then /^context parameter "([^"]*)" should be equal to "([^"]*)"$/ - */ + #[Then('/^context parameter "([^"]*)" should be equal to "([^"]*)"$/')] public function contextParameterShouldBeEqualTo($key, $val) { \PHPUnit\Framework\Assert::assertEquals($val, $this->parameters[$key]); } - /** - * @Given /^context parameter "([^"]*)" should be array with (\d+) elements$/ - */ + #[Given('/^context parameter "([^"]*)" should be array with (\d+) elements$/')] public function contextParameterShouldBeArrayWithElements($key, $count) { \PHPUnit\Framework\Assert::assertIsArray($this->parameters[$key]); \PHPUnit\Framework\Assert::assertEquals(2, count($this->parameters[$key])); diff --git a/features/arguments.feature b/features/arguments.feature index 161a18111..b784dcf11 100644 --- a/features/arguments.feature +++ b/features/arguments.feature @@ -11,6 +11,8 @@ Feature: Step Arguments use Behat\Behat\Context\Context; use Behat\Gherkin\Node\PyStringNode, Behat\Gherkin\Node\TableNode; + use Behat\Step\Given; + use Behat\Step\Then; class FeatureContext implements Context { @@ -26,37 +28,27 @@ Feature: Step Arguments ); } - /** - * @Given /^a pystring:$/ - */ + #[Given('/^a pystring:$/')] public function aPystring(PyStringNode $string) { $this->input = $string; } - /** - * @Given /^a table:$/ - */ + #[Given('/^a table:$/')] public function aTable(TableNode $table) { $this->input = $table; } - /** - * @Then /^it must be equals to string (\d+)$/ - */ + #[Then('/^it must be equals to string (\d+)$/')] public function itMustBeEqualsToString($number) { \PHPUnit\Framework\Assert::assertEquals($this->strings[intval($number)], (string) $this->input); } - /** - * @Then /^it must be equals to table (\d+)$/ - */ + #[Then('/^it must be equals to table (\d+)$/')] public function itMustBeEqualsToTable($number) { \PHPUnit\Framework\Assert::assertEquals($this->tables[intval($number)], $this->input->getHash()); } - /** - * @Given /^I have number2 = (?P\d+) and number1 = (?P\d+)$/ - */ + #[Given('/^I have number2 = (?P\d+) and number1 = (?P\d+)$/')] public function iHaveNumberAndNumber($number1, $number2) { \PHPUnit\Framework\Assert::assertEquals(13, intval($number1)); \PHPUnit\Framework\Assert::assertEquals(243, intval($number2)); diff --git a/features/catch_throwable.feature b/features/catch_throwable.feature index 28e5a5574..4d3c0f62e 100644 --- a/features/catch_throwable.feature +++ b/features/catch_throwable.feature @@ -12,20 +12,18 @@ Feature: Support PHP 7 Throwable Behat\Behat\Exception\PendingException; use Behat\Gherkin\Node\PyStringNode, Behat\Gherkin\Node\TableNode; + use Behat\Step\Then; + use Behat\Step\When; class FeatureContext implements Context { - /** - * @When /^I have some code with a fatal error$/ - */ + #[When('/^I have some code with a fatal error$/')] public function iHaveSomeCodeWithFatalError() { ("not an object")->method(); } - /** - * @Then /^I should be skipped$/ - */ + #[Then('/^I should be skipped$/')] public function iShouldBeSkipped() { } diff --git a/features/context.feature b/features/context_annotations.feature similarity index 99% rename from features/context.feature rename to features/context_annotations.feature index 496d5a690..bb16d262b 100644 --- a/features/context.feature +++ b/features/context_annotations.feature @@ -1,7 +1,7 @@ -Feature: Context consistency +Feature: Context Consistency Annotations In order to maintain stable behavior tests As a feature writer - I need a separate context for every scenario/outline + I need a separate context for every scenario/outline using annotations Background: Given a file named "features/bootstrap/FeatureContext.php" with: diff --git a/features/context_attributes.feature b/features/context_attributes.feature new file mode 100644 index 000000000..e91f61379 --- /dev/null +++ b/features/context_attributes.feature @@ -0,0 +1,505 @@ +Feature: Context Consistency Attributes + In order to maintain stable behavior tests + As a feature writer + I need a separate context for every scenario/outline using attributes + + Background: + Given a file named "features/bootstrap/FeatureContext.php" with: + """ + parameters = array('parameter1' => $parameter1, 'parameter2' => $parameter2); + } + + #[Given('/^I have (\d+) apples?$/')] + public function iHaveApples($count) { + $this->apples = intval($count); + } + + #[When('/^I ate (\d+) apples?$/')] + public function iAteApples($count) { + $this->apples -= intval($count); + } + + #[When('/^I found (\d+) apples?$/')] + public function iFoundApples($count) { + $this->apples += intval($count); + } + + #[Then('/^I should have (\d+) apples$/')] + public function iShouldHaveApples($count) { + PHPUnit\Framework\Assert::assertEquals(intval($count), $this->apples); + } + + #[Then('/^context parameter "([^"]*)" should be equal to "([^"]*)"$/')] + public function contextParameterShouldBeEqualTo($key, $val) { + PHPUnit\Framework\Assert::assertEquals($val, $this->parameters[$key]); + } + + /** + * You can always use annotations with PHP attributes until the attributes will be default. + * + * @Given /^context parameter "([^"]*)" should be array with (\d+) elements$/ + */ + public function contextParameterShouldBeArrayWithElements($key, $count) { + PHPUnit\Framework\Assert::assertIsArray($this->parameters[$key]); + PHPUnit\Framework\Assert::assertEquals(2, count($this->parameters[$key])); + } + } + + class FeatureContext extends CoreContext implements Context + { + } + """ + And a file named "features/bootstrap/CustomContext.php" with: + """ + apples + And I found apples + Then I should have apples + + Examples: + | ate | found | result | + | 3 | 1 | 1 | + | 0 | 5 | 8 | + | 2 | 2 | 3 | + """ + When I run "behat --no-colors -f progress features/apples.feature" + Then it should pass with: + """ + .................. + + 5 scenarios (5 passed) + 18 steps (18 passed) + """ + + Scenario: False "apples story" + Given a file named "features/apples.feature" with: + """ + Feature: Apples story + In order to eat apple + As a little kid + I need to have an apple in my pocket + + Background: + Given I have 3 apples + + Scenario: I'm little hungry + When I ate 1 apple + Then I should have 5 apples + + Scenario: Found more apples + When I found 10 apples + Then I should have 10 apples + + Scenario Outline: Other situations + When I ate apples + And I found apples + Then I should have apples + + Examples: + | ate | found | result | + | 3 | 1 | 3 | + | 0 | 5 | 8 | + | 2 | 2 | 4 | + """ + When I run "behat --no-colors -f progress features/apples.feature" + Then it should fail with: + """ + ..F..F...F.......F + + --- Failed steps: + + 001 Scenario: I'm little hungry # features/apples.feature:9 + Then I should have 5 apples # features/apples.feature:11 + Failed asserting that 2 matches expected 5. + + 002 Scenario: Found more apples # features/apples.feature:13 + Then I should have 10 apples # features/apples.feature:15 + Failed asserting that 13 matches expected 10. + + 003 Example: | 3 | 1 | 3 | # features/apples.feature:24 + Then I should have 3 apples # features/apples.feature:20 + Failed asserting that 1 matches expected 3. + + 004 Example: | 2 | 2 | 4 | # features/apples.feature:26 + Then I should have 4 apples # features/apples.feature:20 + Failed asserting that 3 matches expected 4. + + 5 scenarios (1 passed, 4 failed) + 18 steps (14 passed, 4 failed) + """ + + Scenario: Context parameters + Given a file named "behat.yml" with: + """ + default: + suites: + default: + contexts: + - FeatureContext: + parameter1: val_one + parameter2: + everzet: behat_admin + avalanche123: behat_admin + """ + And a file named "features/params.feature" with: + """ + Feature: Context parameters + In order to run a browser + As feature runner + I need to be able to configure behat context + + Scenario: I'm little hungry + Then context parameter "parameter1" should be equal to "val_one" + And context parameter "parameter2" should be array with 2 elements + """ + When I run "behat --no-colors -f progress features/params.feature" + Then it should pass with: + """ + .. + + 1 scenario (1 passed) + 2 steps (2 passed) + """ + + Scenario: Context parameters including optional + Given a file named "behat.yml" with: + """ + default: + suites: + default: + contexts: + - FeatureContext: + parameter1: val_one + """ + And a file named "features/params.feature" with: + """ + Feature: Context parameters + In order to run a browser + As feature runner + I need to be able to configure behat context + + Scenario: I'm little hungry + Then context parameter "parameter1" should be equal to "val_one" + Then context parameter "parameter2" should be equal to "val2_default" + """ + When I run "behat --no-colors -f progress features/params.feature" + Then it should pass with: + """ + .. + + 1 scenario (1 passed) + 2 steps (2 passed) + """ + + Scenario: Existing custom context class + Given a file named "behat.yml" with: + """ + default: + suites: + default: + contexts: [ CustomContext ] + """ + And a file named "features/params.feature" with: + """ + Feature: Context parameters + In order to run a browser + As feature runner + I need to be able to configure behat context + + Scenario: I'm little hungry + Then context parameter "parameter1" should be equal to "val_one" + And context parameter "parameter2" should be array with 2 elements + """ + When I run "behat --no-colors -f progress --snippets-type=regex --snippets-for=CustomContext features/params.feature" + Then it should pass with: + """ + UU + + 1 scenario (1 undefined) + 2 steps (2 undefined) + + --- CustomContext has missing steps. Define them with these snippets: + + #[Then('/^context parameter "([^"]*)" should be equal to "([^"]*)"$/')] + public function contextParameterShouldBeEqualTo($arg1, $arg2): void + { + throw new PendingException(); + } + + #[Then('/^context parameter "([^"]*)" should be array with (\d+) elements$/')] + public function contextParameterShouldBeArrayWithElements($arg1, $arg2): void + { + throw new PendingException(); + } + """ + + Scenario: Single context class instead of an array provided as `contexts` option + Given a file named "behat.yml" with: + """ + default: + suites: + default: + contexts: UnexistentContext + """ + And a file named "features/params.feature" with: + """ + Feature: Context parameters + In order to run a browser + As feature runner + I need to be able to configure behat context + + Scenario: I'm little hungry + Then context parameter "parameter1" should be equal to "val_one" + And context parameter "parameter2" should be array with 2 elements + """ + When I run "behat --no-colors -f progress features/params.feature" + Then it should fail with: + """ + `contexts` setting of the "default" suite is expected to be an array, string given. + """ + + Scenario: Unexisting custom context class + Given a file named "behat.yml" with: + """ + default: + suites: + default: + contexts: [ UnexistentContext ] + """ + And a file named "features/params.feature" with: + """ + Feature: Context parameters + In order to run a browser + As feature runner + I need to be able to configure behat context + + Scenario: I'm little hungry + Then context parameter "parameter1" should be equal to "val_one" + And context parameter "parameter2" should be array with 2 elements + """ + When I run "behat --no-colors -f progress features/params.feature" + Then it should fail with: + """ + `UnexistentContext` context class not found and can not be used. + """ + + Scenario: Unexisting context argument + Given a file named "behat.yml" with: + """ + default: + suites: + default: + contexts: + - FeatureContext: + unexistingParam: 'value' + """ + And a file named "features/params.feature" with: + """ + Feature: Context parameters + In order to run a browser + As feature runner + I need to be able to configure behat context + + Scenario: I'm little hungry + Then context parameter "parameter1" should be equal to "val_one" + And context parameter "parameter2" should be array with 2 elements + """ + When I run "behat --no-colors -f progress features/params.feature" + Then it should fail with: + """ + `CoreContext::__construct()` does not expect argument `$unexistingParam`. + """ + + Scenario: Suite without contexts and FeatureContext available + Given a file named "behat.yml" with: + """ + default: + suites: + first: + contexts: [] + """ + And a file named "features/some.feature" with: + """ + Feature: Apples story + In order to eat apple + As a little kid + I need to have an apple in my pocket + + Scenario: I'm little hungry + Given I have 3 apples + When I ate 1 apple + Then I should have 2 apples + """ + When I run "behat --no-colors -fpretty --format-settings='{\"paths\": true}' features" + Then it should pass with: + """ + Feature: Apples story + In order to eat apple + As a little kid + I need to have an apple in my pocket + + Scenario: I'm little hungry # features/some.feature:6 + Given I have 3 apples + When I ate 1 apple + Then I should have 2 apples + + 1 scenario (1 undefined) + 3 steps (3 undefined) + + --- Use --snippets-for CLI option to generate snippets for following first suite steps: + + Given I have 3 apples + When I ate 1 apple + Then I should have 2 apples + """ + + Scenario: Suite with custom context and FeatureContext available + Given a file named "behat.yml" with: + """ + default: + suites: + first: + contexts: + - CustomContext + """ + And a file named "features/bootstrap/FeatureContext.php" with: + """ + foo = $foo; + } + + #[Given('foo')] + public function foo() { + PHPUnit\Framework\Assert::assertIsArray($this->foo); + + PHPUnit\Framework\Assert::assertSame('foo', $this->foo[0]); + PHPUnit\Framework\Assert::assertSame('bar', $this->foo[1]); + } + } + """ + When I run "behat --no-colors -f progress features/context-args-array.feature" + Then it should pass diff --git a/features/definitions_override.feature b/features/definitions_override_annotations.feature similarity index 93% rename from features/definitions_override.feature rename to features/definitions_override_annotations.feature index e3008d108..688eb14b3 100644 --- a/features/definitions_override.feature +++ b/features/definitions_override_annotations.feature @@ -1,7 +1,7 @@ -Feature: Step Definitions Override +Feature: Step Definitions Override Annotations In order to fine-tune definitions defined in parent classes As a step definitions developer - I need to be able to override definition methods using annotations + I need to be able to override definition methods using step definition annotations Scenario: Overridden method without own annotation will inherit parent pattern Given a file named "features/bootstrap/FeatureContext.php" with: diff --git a/features/definitions_override_attributes.feature b/features/definitions_override_attributes.feature index 72128d311..1a54743d5 100644 --- a/features/definitions_override_attributes.feature +++ b/features/definitions_override_attributes.feature @@ -110,3 +110,41 @@ Feature: Step Definitions Override Attributes 1 scenario (1 passed) 2 steps (2 passed) """ + + Scenario: Overridden method with parent annotation and child attribute + Given a file named "features/bootstrap/FeatureContext.php" with: + """ + .*)")? should(? not)? be:$/')] + public function checkEquality($path = null, $isNegative = null, PyStringNode $json = null) + { + PHPUnit\Framework\Assert::assertNull($path); + PHPUnit\Framework\Assert::assertNull($isNegative); + PHPUnit\Framework\Assert::assertNotNull($json); + } + + #[Then('/^the other (?:JSON|json)(?: response)?(?: at "(?.*)")? should(? not)? be:$/')] + public function checkEquality2($json = null, $path = null, $isNegative = null) + { + PHPUnit\Framework\Assert::assertNull($path); + PHPUnit\Framework\Assert::assertNull($isNegative); + PHPUnit\Framework\Assert::assertNotNull($json); + } + } + """ + And a file named "features/step_patterns.feature" with: + """ + Feature: Step Pattern + Scenario: + Then the JSON should be: + ''' + Test + ''' + And the other JSON should be: + ''' + Test + ''' + """ + When I run "behat -f progress --no-colors" + Then it should pass with: + """ + .. + + 1 scenario (1 passed) + 2 steps (2 passed) + """ + + Scenario: Definition parameter with decimal number following string + Given a file named "features/bootstrap/FeatureContext.php" with: + """ + numbers[] = intval($number); + } + + #[Given('/^I have clicked "+"$/')] + public function iHaveClickedPlus() { + $this->result = array_sum($this->numbers); + } + + #[Then('/^I should see (\d+) on the screen$/')] + public function iShouldSeeOnTheScreen($result) { + PHPUnit\Framework\Assert::assertEquals(intval($result), $this->result); + } + + #[Transform('/"([^"]+)" user/')] + public static function createUserFromUsername($username) { + return (Object) array('name' => $username); + } + + #[Then('/^the ("[^"]+" user) name should be "([^"]*)"$/')] + public function theUserUsername($user, $username) { + PHPUnit\Framework\Assert::assertEquals($username, $user->name); + } + + public static function getTranslationResources() { + return array(__DIR__ . DIRECTORY_SEPARATOR . 'i18n' . DIRECTORY_SEPARATOR . 'ru.xliff'); + } + } + """ + And a file named "features/bootstrap/i18n/ru.xliff" with: + """ + + +
+ + + + + + + + + + """ + When I run "behat --no-colors -f progress features/calc_ru.feature" + Then it should pass with: + """ + ..... + + 1 scenario (1 passed) + 5 steps (5 passed) + """ + + Scenario: In place YAML translations + Given a file named "features/calc_ru.feature" with: + """ + # language: ru + Функция: Базовая калькуляция + + Сценарий: + Допустим Я набрал число 10 на калькуляторе + И Я набрал число 4 на калькуляторе + И Я нажал "+" + То Я должен увидеть на экране 14 + И пользователь "everzet" должен иметь имя "everzet" + """ + And a file named "features/bootstrap/FeatureContext.php" with: + """ + numbers[] = intval($number); + } + + #[Given('/^I have clicked "+"$/')] + public function iHaveClickedPlus() { + $this->result = array_sum($this->numbers); + } + + #[Then('/^I should see (\d+) on the screen$/')] + public function iShouldSeeOnTheScreen($result) { + PHPUnit\Framework\Assert::assertEquals(intval($result), $this->result); + } + + #[Transform('/"([^"]+)" user/')] + public static function createUserFromUsername($username) { + return (Object) array('name' => $username); + } + + #[Then('/^the ("[^"]+" user) name should be "([^"]*)"$/')] + public function theUserUsername($user, $username) { + PHPUnit\Framework\Assert::assertEquals($username, $user->name); + } + + public static function getTranslationResources() { + return array(__DIR__ . DIRECTORY_SEPARATOR . 'i18n' . DIRECTORY_SEPARATOR . 'ru.yml'); + } + } + """ + And a file named "features/bootstrap/i18n/ru.yml" with: + """ + '/^I have entered (\d+) into calculator$/': '/^Я набрал число (\d+) на калькуляторе$/' + '/^I have clicked "+"$/': '/^Я нажал "([^"]*)"$/' + '/^I should see (\d+) on the screen$/': '/^Я должен увидеть на экране (\d+)$/' + '/"([^"]+)" user/': '/пользователь "([^"]+)"/' + '/^the ("[^"]+" user) name should be "([^"]*)"$/': '/^(пользователь "[^"]+") должен иметь имя "([^"]*)"$/' + """ + When I run "behat --no-colors -f progress features/calc_ru.feature" + Then it should pass with: + """ + ..... + + 1 scenario (1 passed) + 5 steps (5 passed) + """ + + Scenario: In place PHP translations + Given a file named "features/calc_ru.feature" with: + """ + # language: ru + Функция: Базовая калькуляция + + Сценарий: + Допустим Я набрал число 10 на калькуляторе + И Я набрал число 4 на калькуляторе + И Я нажал "+" + То Я должен увидеть на экране 14 + И пользователь "everzet" должен иметь имя "everzet" + """ + And a file named "features/bootstrap/FeatureContext.php" with: + """ + numbers[] = intval($number); + } + + #[Given('/^I have clicked "+"$/')] + public function iHaveClickedPlus() { + $this->result = array_sum($this->numbers); + } + + #[Then('/^I should see (\d+) on the screen$/')] + public function iShouldSeeOnTheScreen($result) { + PHPUnit\Framework\Assert::assertEquals(intval($result), $this->result); + } + + #[Transform('/"([^"]+)" user/')] + public static function createUserFromUsername($username) { + return (Object) array('name' => $username); + } + + #[Then('/^the ("[^"]+" user) name should be "([^"]*)"$/')] + public function theUserUsername($user, $username) { + PHPUnit\Framework\Assert::assertEquals($username, $user->name); + } + + public static function getTranslationResources() { + return array(__DIR__ . DIRECTORY_SEPARATOR . 'i18n' . DIRECTORY_SEPARATOR . 'ru.php'); + } + } + """ + And a file named "features/bootstrap/i18n/ru.php" with: + """ + '/^Я набрал число (\d+) на калькуляторе$/', + '/^I have clicked "+"$/' => '/^Я нажал "([^"]*)"$/', + '/^I should see (\d+) on the screen$/' => '/^Я должен увидеть на экране (\d+)$/', + '/"([^"]+)" user/' => '/пользователь "([^"]+)"/', + '/^the ("[^"]+" user) name should be "([^"]*)"$/' => '/^(пользователь "[^"]+") должен иметь имя "([^"]*)"$/', + ); + """ + When I run "behat --no-colors -f progress features/calc_ru.feature" + Then it should pass with: + """ + ..... + + 1 scenario (1 passed) + 5 steps (5 passed) + """ + + Scenario: Translations with 2 suites + Given a file named "behat.yml" with: + """ + default: + suites: + frontend: ~ + backend: ~ + """ + Given a file named "features/calc_ru.feature" with: + """ + # language: ru + Функция: Базовая калькуляция + + Сценарий: + Допустим Я набрал число 10 на калькуляторе + И Я набрал число 4 на калькуляторе + И Я нажал "+" + То Я должен увидеть на экране 14 + И пользователь "everzet" должен иметь имя "everzet" + """ + And a file named "features/bootstrap/FeatureContext.php" with: + """ + numbers[] = intval($number); + } + + #[Given('/^I have clicked "+"$/')] + public function iHaveClickedPlus() { + $this->result = array_sum($this->numbers); + } + + #[Then('/^I should see (\d+) on the screen$/')] + public function iShouldSeeOnTheScreen($result) { + PHPUnit\Framework\Assert::assertEquals(intval($result), $this->result); + } + + #[Transform('/"([^"]+)" user/')] + public static function createUserFromUsername($username) { + return (Object) array('name' => $username); + } + + #[Then('/^the ("[^"]+" user) name should be "([^"]*)"$/')] + public function theUserUsername($user, $username) { + PHPUnit\Framework\Assert::assertEquals($username, $user->name); + } + + public static function getTranslationResources() { + return array(__DIR__ . DIRECTORY_SEPARATOR . 'i18n' . DIRECTORY_SEPARATOR . 'ru.php'); + } + } + """ + And a file named "features/bootstrap/i18n/ru.php" with: + """ + '/^Я набрал число (\d+) на калькуляторе$/', + '/^I have clicked "+"$/' => '/^Я нажал "([^"]*)"$/', + '/^I should see (\d+) on the screen$/' => '/^Я должен увидеть на экране (\d+)$/', + '/"([^"]+)" user/' => '/пользователь "([^"]+)"/', + '/^the ("[^"]+" user) name should be "([^"]*)"$/' => '/^(пользователь "[^"]+") должен иметь имя "([^"]*)"$/', + ); + """ + When I run "behat --no-colors -f progress features/calc_ru.feature" + Then it should pass with: + """ + .......... + + 2 scenarios (2 passed) + 10 steps (10 passed) + """ + + Scenario: Translations with arguments without quotes + Given a file named "features/calc_ru_arguments.feature" with: + """ + # language: ru + Функция: Индексы + + Сценарий: + Допустим Я беру 14ую вещь + То индекс должен быть "14" + + Сценарий: + Допустим Я беру "2ю" вещь + То индекс должен быть "2" + + Сценарий: + Допустим Я беру 5 вещь + То индекс должен быть "5" + + Сценарий: + Допустим Я беру "10" вещь + То индекс должен быть "10" + """ + And a file named "features/bootstrap/FeatureContext.php" with: + """ + index = $index; + } + + #[Then('/^the index should be "([^"]*)"$/')] + public function theIndexShouldBe($value) { + PHPUnit\Framework\Assert::assertSame($value, $this->index); + } + + public static function getTranslationResources() { + return array(__DIR__ . DIRECTORY_SEPARATOR . 'i18n' . DIRECTORY_SEPARATOR . 'ru.xliff'); + } + } + """ + And a file named "features/bootstrap/i18n/ru.xliff" with: + """ +
+ /^I have entered (\d+) into calculator$/ + + /^Я набрал число (\d+) на калькуляторе$/ + /^I have clicked "+"$/ + + /^Я нажал "([^"]*)"$/ + /^I should see (\d+) on the screen$/ + + /^Я должен увидеть на экране (\d+)$/ + /"([^"]+)" user/ + + /пользователь "([^"]+)"/ + /^the ("[^"]+" user) name should be "([^"]*)"$/ + + /^(пользователь "[^"]+") должен иметь имя "([^"]*)"$/ + +
+ + + + + + + """ + When I run "behat --no-colors -f progress features/calc_ru_arguments.feature" + Then it should pass with: + """ + ........ + + 4 scenarios (4 passed) + 8 steps (8 passed) + """ diff --git a/features/dry_run.feature b/features/dry_run.feature index 961786c52..38ded2d1c 100644 --- a/features/dry_run.feature +++ b/features/dry_run.feature @@ -11,40 +11,34 @@ Feature: Dry run use Behat\Behat\Context\Context; use Behat\Gherkin\Node\PyStringNode, Behat\Gherkin\Node\TableNode; + use Behat\Hook\BeforeScenario; + use Behat\Step\Given; + use Behat\Step\Then; + use Behat\Step\When; class FeatureContext implements Context { - /** - * @BeforeScenario - */ + #[BeforeScenario] public static function beforeScenario() { echo "HOOK: before scenario"; } - /** - * @Given /^I have (\d+) apples?$/ - */ + #[Given('/^I have (\d+) apples?$/')] public function iHaveApples($count) { echo "STEP: I have $count apples"; } - /** - * @When /^I ate (\d+) apples?$/ - */ + #[When('/^I ate (\d+) apples?$/')] public function iAteApples($count) { echo "STEP: I ate $count apples"; } - /** - * @When /^I found (\d+) apples?$/ - */ + #[When('/^I found (\d+) apples?$/')] public function iFoundApples($count) { echo "STEP: I found $count apples"; } - /** - * @Then /^I should have (\d+) apples$/ - */ + #[Then('/^I should have (\d+) apples$/')] public function iShouldHaveApples($count) { echo "STEP: I should have $count apples"; } diff --git a/features/env_var_placeholders.feature b/features/env_var_placeholders.feature index 558927fee..e6ce432b6 100644 --- a/features/env_var_placeholders.feature +++ b/features/env_var_placeholders.feature @@ -9,6 +9,7 @@ Feature: Symfony Env Var Placeholders value = $value; } - /** - * @Then /the value should be configured as "([^"]+)"/ - */ + #[Then('/the value should be configured as "([^"]+)"/')] public function theValueShouldBeConfiguredAs($expected) { PHPUnit\Framework\Assert::assertEquals($expected, $this->value); } diff --git a/features/error_reporting.feature b/features/error_reporting.feature index 2c4b363d3..073ccacc9 100644 --- a/features/error_reporting.feature +++ b/features/error_reporting.feature @@ -12,56 +12,47 @@ Feature: Error Reporting Behat\Behat\Exception\PendingException; use Behat\Gherkin\Node\PyStringNode, Behat\Gherkin\Node\TableNode; + use Behat\Step\Given; + use Behat\Step\Then; + use Behat\Step\When; class FeatureContext implements Context { private $array; private $result; - /** - * @Given /^I have an empty array$/ - */ + #[Given('/^I have an empty array$/')] public function iHaveAnEmptyArray() { $this->array = array(); } - /** - * @When /^I access array index (\d+)$/ - */ + #[When('/^I access array index (\d+)$/')] public function iAccessArrayIndex($arg1) { $index = intval($arg1); $this->result = $this->array[$index]; } - /** - * @Then /^I should get NULL$/ - */ + #[Then('/^I should get NULL$/')] public function iShouldGetNull() { PHPUnit\Framework\Assert::assertNull($this->result); } - /** - * @When /^I push "([^"]*)" to that array$/ - */ + #[When('/^I push "([^"]*)" to that array$/')] public function iPushToThatArray($arg1) { array_push($this->array, $arg1); } - /** - * @Then /^I should get "([^"]*)"$/ - */ + #[Then('/^I should get "([^"]*)"$/')] public function iShouldGet($arg1) { PHPUnit\Framework\Assert::assertEquals($arg1, $this->result); } - /** - * @When an exception is thrown - */ + #[When('an exception is thrown')] public function anExceptionIsThrown() { throw new \Exception('Exception is thrown'); @@ -108,7 +99,7 @@ Feature: Error Reporting 001 Scenario: Access undefined index # features/e_notice_in_scenario.feature:9 When I access array index 0 # features/e_notice_in_scenario.feature:10 - Notice: Undefined offset: 0 in features/bootstrap/FeatureContext.php line 27 + Notice: Undefined offset: 0 in features/bootstrap/FeatureContext.php line 26 2 scenarios (1 passed, 1 failed) 7 steps (5 passed, 1 failed, 1 skipped) @@ -133,7 +124,7 @@ Feature: Error Reporting 001 Scenario: Exception thrown # features/exception_in_scenario.feature:6 When an exception is thrown # features/exception_in_scenario.feature:7 - Exception: Exception is thrown in features/bootstrap/FeatureContext.php:59 + Exception: Exception is thrown in features/bootstrap/FeatureContext.php:50 Stack trace: 1 scenario (1 failed) @@ -149,7 +140,7 @@ Feature: Error Reporting 001 Scenario: Exception thrown # features/exception_in_scenario.feature:6 When an exception is thrown # features/exception_in_scenario.feature:7 - Exception: Exception is thrown in features/bootstrap/FeatureContext.php:59 + Exception: Exception is thrown in features/bootstrap/FeatureContext.php:50 Stack trace: #0 src/Behat/Testwork/Call/Handler/RuntimeCallHandler.php(110): FeatureContext->anExceptionIsThrown() #1 src/Behat/Testwork/Call/Handler/RuntimeCallHandler.php(64): Behat\Testwork\Call\Handler\RuntimeCallHandler->executeCall( diff --git a/features/execution_order.feature b/features/execution_order.feature index 4348fe6b6..6da12c01f 100644 --- a/features/execution_order.feature +++ b/features/execution_order.feature @@ -11,12 +11,11 @@ Feature: Setting order of execution use Behat\Behat\Context\Context; use Behat\Gherkin\Node\PyStringNode, Behat\Gherkin\Node\TableNode; + use Behat\Step\Given; class FeatureContext implements Context { - /** - * @Given I have :num orange(s) - */ + #[Given('I have :num orange(s)')] public function iHaveOranges($num){} } """ diff --git a/features/format_options.feature b/features/format_options.feature index f36698ce6..f14d53bf4 100644 --- a/features/format_options.feature +++ b/features/format_options.feature @@ -12,6 +12,9 @@ Feature: Format options Behat\Behat\Exception\PendingException; use Behat\Gherkin\Node\PyStringNode, Behat\Gherkin\Node\TableNode; + use Behat\Step\Given; + use Behat\Step\Then; + use Behat\Step\When; class FeatureContext implements Context { @@ -22,44 +25,32 @@ Feature: Format options $this->parameters = $parameters; } - /** - * @Given /^I have (\d+) apples?$/ - */ + #[Given('/^I have (\d+) apples?$/')] public function iHaveApples($count) { $this->apples = intval($count); } - /** - * @When /^I ate (\d+) apples?$/ - */ + #[When('/^I ate (\d+) apples?$/')] public function iAteApples($count) { $this->apples -= intval($count); } - /** - * @When /^I found (\d+) apples?$/ - */ + #[When('/^I found (\d+) apples?$/')] public function iFoundApples($count) { $this->apples += intval($count); } - /** - * @Then /^I should have (\d+) apples$/ - */ + #[Then('/^I should have (\d+) apples$/')] public function iShouldHaveApples($count) { PHPUnit\Framework\Assert::assertEquals(intval($count), $this->apples); } - /** - * @Then /^context parameter "([^"]*)" should be equal to "([^"]*)"$/ - */ + #[Then('/^context parameter "([^"]*)" should be equal to "([^"]*)"$/')] public function contextParameterShouldBeEqualTo($key, $val) { PHPUnit\Framework\Assert::assertEquals($val, $this->parameters[$key]); } - /** - * @Given /^context parameter "([^"]*)" should be array with (\d+) elements$/ - */ + #[Given('/^context parameter "([^"]*)" should be array with (\d+) elements$/')] public function contextParameterShouldBeArrayWithElements($key, $count) { PHPUnit\Framework\Assert::assertIsArray($this->parameters[$key]); PHPUnit\Framework\Assert::assertEquals(2, count($this->parameters[$key])); diff --git a/features/hooks.feature b/features/hooks_annotations.feature similarity index 99% rename from features/hooks.feature rename to features/hooks_annotations.feature index dfb9b5148..6dce0fcd5 100644 --- a/features/hooks.feature +++ b/features/hooks_annotations.feature @@ -1,7 +1,7 @@ -Feature: hooks +Feature: Hooks Annotations In order to hook into Behat testing process As a tester - I need to be able to write hooks + I need to be able to write hooks using annotations Background: Given a file named "behat.yml" with: diff --git a/features/hooks_attributes.feature b/features/hooks_attributes.feature new file mode 100644 index 000000000..0463cc360 --- /dev/null +++ b/features/hooks_attributes.feature @@ -0,0 +1,551 @@ +Feature: Hooks Attributes + In order to hook into Behat testing process + As a tester + I need to be able to write hooks using attributes + + Background: + Given a file named "behat.yml" with: + """ + default: + suites: + default: + parameters: + before_feature: BEFORE EVERY FEATURE + after_feature: AFTER EVERY FEATURE + """ + And a file named "features/bootstrap/FeatureContext.php" with: + """ + getSuite()->getSetting('parameters'); + echo "= do something ".$params['before_feature']; + } + + #[AfterFeature] + static public function doSomethingAfterFeature($event) { + $params = $event->getSuite()->getSetting('parameters'); + echo "= do something ".$params['after_feature']; + } + + #[BeforeFeature('@someFeature')] + static public function doSomethingBeforeSomeFeature($event) { + echo "= do something before SOME feature"; + } + + #[AfterFeature('@someFeature')] + static public function doSomethingAfterSomeFeature($event) { + echo "= do something after SOME feature"; + } + + #[BeforeScenario] + public function beforeScenario($event) { + $this->number = 50; + } + + #[BeforeScenario('130')] + public function beforeScenario130($event) { + $this->number = 130; + } + + #[BeforeScenario('@thirty')] + public function beforeScenarioThirty($event) { + $this->number = 30; + } + + #[BeforeScenario('@exception')] + public function beforeScenarioException($event) { + throw new \Exception('Exception'); + } + + #[BeforeScenario('@filtered')] + public function beforeScenarioFiltered($event) { + $this->scenarioFilter = 'filtered'; + } + + #[BeforeScenario('@~filtered')] + public function beforeScenarioNotFiltered($event) { + $this->scenarioFilter = '~filtered'; + } + + #[BeforeStep('I must have 100')] + public function beforeStep100($event) { + $this->number = 100; + } + + #[Given('/^I have entered (\d+)$/')] + public function iHaveEntered($number) { + $this->number = intval($number); + } + + #[Then('/^I must have (\d+)$/')] + public function iMustHave($number) { + \PHPUnit\Framework\Assert::assertEquals(intval($number), $this->number); + } + + #[Then('I must have a scenario filter value of :value')] + public function iMustHaveScenarioFilter($filterValue) { + \PHPUnit\Framework\Assert::assertEquals($filterValue, $this->scenarioFilter); + } + } + """ + + Scenario: + Given a file named "features/test.feature" with: + """ + Feature: + Scenario: + Then I must have 50 + Scenario: + Given I have entered 12 + Then I must have 12 + + @thirty + Scenario: + Given I must have 30 + When I have entered 23 + Then I must have 23 + @100 @thirty + Scenario: + Given I must have 30 + When I have entered 1 + Then I must have 100 + + Scenario: 130 + Given I must have 130 + + @filtered + Scenario: + Then I must have a scenario filter value of "filtered" + + @~filtered + Scenario: + Then I must have a scenario filter value of "~filtered" + + Scenario: + Then I must have a scenario filter value of "~filtered" + """ + When I run "behat --no-colors -f pretty" + Then it should pass with: + """ + ┌─ @BeforeFeature # FeatureContext::doSomethingBeforeFeature() + │ + │ = do something BEFORE EVERY FEATURE + │ + Feature: + + Scenario: # features/test.feature:2 + Then I must have 50 # FeatureContext::iMustHave() + + Scenario: # features/test.feature:4 + Given I have entered 12 # FeatureContext::iHaveEntered() + Then I must have 12 # FeatureContext::iMustHave() + + @thirty + Scenario: # features/test.feature:9 + Given I must have 30 # FeatureContext::iMustHave() + When I have entered 23 # FeatureContext::iHaveEntered() + Then I must have 23 # FeatureContext::iMustHave() + + @100 @thirty + Scenario: # features/test.feature:14 + Given I must have 30 # FeatureContext::iMustHave() + When I have entered 1 # FeatureContext::iHaveEntered() + Then I must have 100 # FeatureContext::iMustHave() + + Scenario: 130 # features/test.feature:19 + Given I must have 130 # FeatureContext::iMustHave() + + @filtered + Scenario: # features/test.feature:23 + Then I must have a scenario filter value of "filtered" # FeatureContext::iMustHaveScenarioFilter() + + @~filtered + Scenario: # features/test.feature:27 + Then I must have a scenario filter value of "~filtered" # FeatureContext::iMustHaveScenarioFilter() + + Scenario: # features/test.feature:30 + Then I must have a scenario filter value of "~filtered" # FeatureContext::iMustHaveScenarioFilter() + + │ + │ = do something AFTER EVERY FEATURE + │ + └─ @AfterFeature # FeatureContext::doSomethingAfterFeature() + + 8 scenarios (8 passed) + 13 steps (13 passed) + """ + + Scenario: Filter features + Given a file named "features/1-one.feature" with: + """ + Feature: + Scenario: + Then I must have 50 + + Scenario: + Given I have entered 12 + Then I must have 12 + + Scenario: 130 + Given I must have 130 + """ + Given a file named "features/2-two.feature" with: + """ + @someFeature + Feature: + Scenario: 130 + Given I must have 130 + """ + When I run "behat --no-colors -f pretty" + Then it should pass with: + """ + ┌─ @BeforeFeature # FeatureContext::doSomethingBeforeFeature() + │ + │ = do something BEFORE EVERY FEATURE + │ + Feature: + + Scenario: # features/1-one.feature:2 + Then I must have 50 # FeatureContext::iMustHave() + + Scenario: # features/1-one.feature:5 + Given I have entered 12 # FeatureContext::iHaveEntered() + Then I must have 12 # FeatureContext::iMustHave() + + Scenario: 130 # features/1-one.feature:9 + Given I must have 130 # FeatureContext::iMustHave() + + │ + │ = do something AFTER EVERY FEATURE + │ + └─ @AfterFeature # FeatureContext::doSomethingAfterFeature() + + ┌─ @BeforeFeature # FeatureContext::doSomethingBeforeFeature() + │ + │ = do something BEFORE EVERY FEATURE + │ + ┌─ @BeforeFeature @someFeature # FeatureContext::doSomethingBeforeSomeFeature() + │ + │ = do something before SOME feature + │ + @someFeature + Feature: + + Scenario: 130 # features/2-two.feature:3 + Given I must have 130 # FeatureContext::iMustHave() + + │ + │ = do something AFTER EVERY FEATURE + │ + └─ @AfterFeature # FeatureContext::doSomethingAfterFeature() + + │ + │ = do something after SOME feature + │ + └─ @AfterFeature @someFeature # FeatureContext::doSomethingAfterSomeFeature() + + 4 scenarios (4 passed) + 5 steps (5 passed) + """ + + Scenario: Background step hooks + Given a file named "features/background.feature" with: + """ + Feature: + Background: + Given I must have 50 + + Scenario: + Given I have entered 12 + Then I must have 12 + """ + When I run "behat --no-colors -f pretty" + Then it should pass with: + """ + ┌─ @BeforeFeature # FeatureContext::doSomethingBeforeFeature() + │ + │ = do something BEFORE EVERY FEATURE + │ + Feature: + + Background: # features/background.feature:2 + Given I must have 50 # FeatureContext::iMustHave() + + Scenario: # features/background.feature:5 + Given I have entered 12 # FeatureContext::iHaveEntered() + Then I must have 12 # FeatureContext::iMustHave() + + │ + │ = do something AFTER EVERY FEATURE + │ + └─ @AfterFeature # FeatureContext::doSomethingAfterFeature() + + 1 scenario (1 passed) + 3 steps (3 passed) + """ + + Scenario: Background exceptions + Given a file named "features/background.feature" with: + """ + Feature: + + @exception + Scenario: + Then I must have 50 + Scenario: + Given I have entered 12 + Then I must have 12 + + @exception + Scenario: + Given I must have 30 + When I have entered 23 + Then I must have 23 + + Scenario: 130 + Given I must have 130 + """ + When I run "behat --no-colors -f pretty" + Then it should fail with: + """ + ┌─ @BeforeFeature # FeatureContext::doSomethingBeforeFeature() + │ + │ = do something BEFORE EVERY FEATURE + │ + Feature: + + ┌─ @BeforeScenario @exception # FeatureContext::beforeScenarioException() + │ + ╳ Exception (Exception) + │ + @exception + Scenario: # features/background.feature:4 + Then I must have 50 # FeatureContext::iMustHave() + + Scenario: # features/background.feature:6 + Given I have entered 12 # FeatureContext::iHaveEntered() + Then I must have 12 # FeatureContext::iMustHave() + + ┌─ @BeforeScenario @exception # FeatureContext::beforeScenarioException() + │ + ╳ Exception (Exception) + │ + @exception + Scenario: # features/background.feature:11 + Given I must have 30 # FeatureContext::iMustHave() + When I have entered 23 # FeatureContext::iHaveEntered() + Then I must have 23 # FeatureContext::iMustHave() + + Scenario: 130 # features/background.feature:16 + Given I must have 130 # FeatureContext::iMustHave() + + │ + │ = do something AFTER EVERY FEATURE + │ + └─ @AfterFeature # FeatureContext::doSomethingAfterFeature() + + --- Failed hooks: + + BeforeScenario @exception "features/background.feature:4" # FeatureContext::beforeScenarioException() + BeforeScenario @exception "features/background.feature:11" # FeatureContext::beforeScenarioException() + + --- Skipped scenarios: + + features/background.feature:4 + features/background.feature:11 + + 4 scenarios (2 passed, 2 skipped) + 7 steps (3 passed, 4 skipped) + """ + + Scenario: Step state doesn't affect after hooks + Given a file named "features/test.feature" with: + """ + Feature: + + Scenario: + Given passing step + + Scenario: + Given failing step + + Scenario: + Given passing step with failing hook + + @failing-before-hook + Scenario: + Given passing step + """ + And a file named "features/bootstrap/FeatureContext.php" with: + """ + + + """ + And the file "junit/default.xml" should be a valid document according to "junit.xsd" + + Scenario: Handling of a error in afterSuite hook + Given a file named "features/bootstrap/FeatureContext.php" with: + """ + + + """ + And the file "junit/default.xml" should be a valid document according to "junit.xsd" + + Scenario: Handling of a error in beforeFeature hook + Given a file named "features/bootstrap/FeatureContext.php" with: + """ + + + """ + And the file "junit/default.xml" should be a valid document according to "junit.xsd" + + Scenario: Handling of a error in afterFeature hook + Given a file named "features/bootstrap/FeatureContext.php" with: + """ + + + """ + And the file "junit/default.xml" should be a valid document according to "junit.xsd" + + Scenario: Handling of a error in beforeScenario hook + Given a file named "features/bootstrap/FeatureContext.php" with: + """ + + + """ + And the file "junit/default.xml" should be a valid document according to "junit.xsd" + + Scenario: Handling of a error in afterScenario hook + Given a file named "features/bootstrap/FeatureContext.php" with: + """ + + + """ + And the file "junit/default.xml" should be a valid document according to "junit.xsd" + + Scenario: Handling of a error in beforeStep hook + Given a file named "features/bootstrap/FeatureContext.php" with: + """ + + + """ + And the file "junit/default.xml" should be a valid document according to "junit.xsd" + + Scenario: Handling of a error in afterStep hook + Given a file named "features/bootstrap/FeatureContext.php" with: + """ + + + """ + And the file "junit/default.xml" should be a valid document according to "junit.xsd" diff --git a/features/hooks_failures_pretty.feature b/features/hooks_failures_pretty_annotations.feature similarity index 98% rename from features/hooks_failures_pretty.feature rename to features/hooks_failures_pretty_annotations.feature index 8757e94ab..a0ca986c2 100644 --- a/features/hooks_failures_pretty.feature +++ b/features/hooks_failures_pretty_annotations.feature @@ -1,7 +1,7 @@ -Feature: Display hook failures location in pretty printer +Feature: Display hook failures location in pretty printer using annotations In order to be able to locate the code that generated a failure As a feature developer using the pretty printer - When a hook throws an error I want to see the related item where the code failed + When a hook throws an error I want to see the related item where the code failed using annotations Background: Given a file named "features/simple.feature" with: diff --git a/features/hooks_failures_pretty_attributes.feature b/features/hooks_failures_pretty_attributes.feature new file mode 100644 index 000000000..f075b45bc --- /dev/null +++ b/features/hooks_failures_pretty_attributes.feature @@ -0,0 +1,205 @@ +Feature: Display hook failures location in pretty printer using attributes + In order to be able to locate the code that generated a failure + As a feature developer using the pretty printer + When a hook throws an error I want to see the related item where the code failed using attributes + + Background: + Given a file named "features/simple.feature" with: + """ + Feature: Simple feature + + Scenario: Simple scenario + When I have a simple step + """ + + Scenario: Handling of a error in beforeSuite hook + Given a file named "features/bootstrap/FeatureContext.php" with: + """ + value = intval($number); + } + + #[Then('/Я должен иметь (\d+)/')] + public function iShouldHave($number) { + PHPUnit\Framework\Assert::assertEquals(intval($number), $this->value); + } + + #[When('/Я добавлю (\d+)/')] + public function iAdd($number) { + $this->value += intval($number); + } + + #[When('/^Что-то еще не сделано$/')] + public function somethingNotDone() { + throw new PendingException(); + } + } + """ + And a file named "features/World.feature" with: + """ + # language: ru + Функционал: Постоянство мира + Чтобы поддерживать стабильными тесты + Как разработчик функционала + Я хочу чтобы Мир сбрасывался между сценариями + + Предыстория: + Если Я ввел 10 + + Сценарий: Неопределен + То Я должен иметь 10 + И Добавить "нормальное" число + То Я должен иметь 10 + + Сценарий: В ожидании + То Я должен иметь 10 + И Что-то еще не сделано + То Я должен иметь 10 + + Сценарий: Провален + Если Я добавлю 4 + То Я должен иметь 13 + + Структура сценария: Пройдено и Провалено + Допустим Я должен иметь 10 + Если Я добавлю <значение> + То Я должен иметь <результат> + + Примеры: + | значение | результат | + | 5 | 16 | + | 10 | 20 | + | 23 | 32 | + """ + + Scenario: Pretty + When I run "behat --no-colors -f pretty --lang=ru --snippets-for=FeatureContext --snippets-type=regex" + Then it should fail with: + """ + Функционал: Постоянство мира + Чтобы поддерживать стабильными тесты + Как разработчик функционала + Я хочу чтобы Мир сбрасывался между сценариями + + Предыстория: # features/World.feature:7 + Если Я ввел 10 # FeatureContext::iHaveEntered() + + Сценарий: Неопределен # features/World.feature:10 + То Я должен иметь 10 # FeatureContext::iShouldHave() + И Добавить "нормальное" число + То Я должен иметь 10 # FeatureContext::iShouldHave() + + Сценарий: В ожидании # features/World.feature:15 + То Я должен иметь 10 # FeatureContext::iShouldHave() + И Что-то еще не сделано # FeatureContext::somethingNotDone() + TODO: write pending definition + То Я должен иметь 10 # FeatureContext::iShouldHave() + + Сценарий: Провален # features/World.feature:20 + Если Я добавлю 4 # FeatureContext::iAdd() + То Я должен иметь 13 # FeatureContext::iShouldHave() + Failed asserting that 14 matches expected 13. + + Структура сценария: Пройдено и Провалено # features/World.feature:24 + Допустим Я должен иметь 10 # FeatureContext::iShouldHave() + Если Я добавлю <значение> # FeatureContext::iAdd() + То Я должен иметь <результат> # FeatureContext::iShouldHave() + + Примеры: + | значение | результат | + | 5 | 16 | + Проваленные шаг: То Я должен иметь 16 + Failed asserting that 15 matches expected 16. + | 10 | 20 | + | 23 | 32 | + Проваленные шаг: То Я должен иметь 32 + Failed asserting that 33 matches expected 32. + + --- Проваленные сценарии: + + features/World.feature:20 + features/World.feature:31 + features/World.feature:33 + + 6 сценариев (1 пройден, 3 провалено, 1 не определен, 1 в ожидании) + 23 шага (16 пройдено, 3 провалено, 1 не определен, 1 в ожидании, 2 пропущено) + + --- FeatureContext не содержит необходимых определений. Вы можете добавить их используя шаблоны: + + #[Then('/^Добавить "([^"]*)" число$/')] + public function dobavitChislo($arg1): void + { + throw new PendingException(); + } + + --- Не забудьте эти 2 use утверждения: + + use Behat\Behat\Tester\Exception\PendingException; + use Behat\Step\Then; + """ + + Scenario: Progress + When I run "behat --no-colors -f progress --lang=ru --snippets-for=FeatureContext --snippets-type=regex" + Then it should fail with: + """ + ..U-..P-..F...F.......F + + --- Проваленные шаги: + + 001 Сценарий: Провален # features/World.feature:20 + То Я должен иметь 13 # features/World.feature:22 + Failed asserting that 14 matches expected 13. + + 002 Example: | 5 | 16 | # features/World.feature:31 + То Я должен иметь 16 # features/World.feature:27 + Failed asserting that 15 matches expected 16. + + 003 Example: | 23 | 32 | # features/World.feature:33 + То Я должен иметь 32 # features/World.feature:27 + Failed asserting that 33 matches expected 32. + + --- Шаги в ожидании: + + 001 Сценарий: В ожидании # features/World.feature:15 + И Что-то еще не сделано # FeatureContext::somethingNotDone() + TODO: write pending definition + + 6 сценариев (1 пройден, 3 провалено, 1 не определен, 1 в ожидании) + 23 шага (16 пройдено, 3 провалено, 1 не определен, 1 в ожидании, 2 пропущено) + + --- FeatureContext не содержит необходимых определений. Вы можете добавить их используя шаблоны: + + #[Then('/^Добавить "([^"]*)" число$/')] + public function dobavitChislo($arg1): void + { + throw new PendingException(); + } + + --- Не забудьте эти 2 use утверждения: + + use Behat\Behat\Tester\Exception\PendingException; + use Behat\Step\Then; + """ + + Scenario: Progress with unexisting locale + When I run "behat --no-colors -f progress --lang=xx --snippets-for=FeatureContext --snippets-type=regex" + Then it should fail with: + """ + ..U-..P-..F...F.......F + + --- Failed steps: + + 001 Сценарий: Провален # features/World.feature:20 + То Я должен иметь 13 # features/World.feature:22 + Failed asserting that 14 matches expected 13. + + 002 Example: | 5 | 16 | # features/World.feature:31 + То Я должен иметь 16 # features/World.feature:27 + Failed asserting that 15 matches expected 16. + + 003 Example: | 23 | 32 | # features/World.feature:33 + То Я должен иметь 32 # features/World.feature:27 + Failed asserting that 33 matches expected 32. + + --- Pending steps: + + 001 Сценарий: В ожидании # features/World.feature:15 + И Что-то еще не сделано # FeatureContext::somethingNotDone() + TODO: write pending definition + + 6 scenarios (1 passed, 3 failed, 1 undefined, 1 pending) + 23 steps (16 passed, 3 failed, 1 undefined, 1 pending, 2 skipped) + + --- FeatureContext has missing steps. Define them with these snippets: + + #[Then('/^Добавить "([^"]*)" число$/')] + public function dobavitChislo($arg1): void + { + throw new PendingException(); + } + + --- Don't forget these 2 use statements: + + use Behat\Behat\Tester\Exception\PendingException; + use Behat\Step\Then; + """ + + Scenario: Progress with unexisting locale + When I run "behat --no-colors -f progress --lang=xx --snippets-for=FeatureContext --snippets-type=regex" + Then it should fail with: + """ + ..U-..P-..F...F.......F + + --- Failed steps: + + 001 Сценарий: Провален # features/World.feature:20 + То Я должен иметь 13 # features/World.feature:22 + Failed asserting that 14 matches expected 13. + + 002 Example: | 5 | 16 | # features/World.feature:31 + То Я должен иметь 16 # features/World.feature:27 + Failed asserting that 15 matches expected 16. + + 003 Example: | 23 | 32 | # features/World.feature:33 + То Я должен иметь 32 # features/World.feature:27 + Failed asserting that 33 matches expected 32. + + --- Pending steps: + + 001 Сценарий: В ожидании # features/World.feature:15 + И Что-то еще не сделано # FeatureContext::somethingNotDone() + TODO: write pending definition + + 6 scenarios (1 passed, 3 failed, 1 undefined, 1 pending) + 23 steps (16 passed, 3 failed, 1 undefined, 1 pending, 2 skipped) + + --- FeatureContext has missing steps. Define them with these snippets: + + #[Then('/^Добавить "([^"]*)" число$/')] + public function dobavitChislo($arg1): void + { + throw new PendingException(); + } + + --- Don't forget these 2 use statements: + + use Behat\Behat\Tester\Exception\PendingException; + use Behat\Step\Then; + """ diff --git a/features/junit_format.feature b/features/junit_format.feature index 47339a002..b29251b09 100644 --- a/features/junit_format.feature +++ b/features/junit_format.feature @@ -10,35 +10,30 @@ use Behat\Behat\Context\Context, Behat\Behat\Tester\Exception\PendingException; + use Behat\Step\Given; + use Behat\Step\Then; + use Behat\Step\When; class FeatureContext implements Context { private $value; - /** - * @Given /I have entered (\d+)/ - */ + #[Given('/I have entered (\d+)/')] public function iHaveEntered($num) { $this->value = $num; } - /** - * @Then /I must have (\d+)/ - */ + #[Then('/I must have (\d+)/')] public function iMustHave($num) { PHPUnit\Framework\Assert::assertEquals($num, $this->value); } - /** - * @When /I add (\d+)/ - */ + #[When('/I add (\d+)/')] public function iAdd($num) { $this->value += $num; } - /** - * @When /^Something not done yet$/ - */ + #[When('/^Something not done yet$/')] public function somethingNotDoneYet() { throw new PendingException(); } @@ -133,28 +128,25 @@ use Behat\Behat\Context\Context, Behat\Behat\Tester\Exception\PendingException; + use Behat\Step\Given; + use Behat\Step\Then; + use Behat\Step\When; class FeatureContext implements Context { private $value; - /** - * @Given /I have entered (\d+)/ - */ + #[Given('/I have entered (\d+)/')] public function iHaveEntered($num) { $this->value = $num; } - /** - * @Then /I must have (\d+)/ - */ + #[Then('/I must have (\d+)/')] public function iMustHave($num) { PHPUnit\Framework\Assert::assertEquals($num, $this->value); } - /** - * @When /I add (\d+)/ - */ + #[When('/I add (\d+)/')] public function iAdd($num) { $this->value += $num; } @@ -205,28 +197,25 @@ value = $num; } - /** - * @Then /I must have (\d+)/ - */ + #[Then('/I must have (\d+)/')] public function iMustHave($num) { PHPUnit\Framework\Assert::assertEquals($num, $this->value); } - /** - * @When /I (add|subtract) the value (\d+)/ - */ + #[When('/I (add|subtract) the value (\d+)/')] public function iAddOrSubstact($op, $num) { if ($op == 'add') $this->value += $num; @@ -278,28 +267,25 @@ strongLevel = 0; } - /** - * @When /I eat an apple/ - */ + #[When('/I eat an apple/')] public function iEatAnApple() { $this->strongLevel += 2; } - /** - * @Then /I will be stronger/ - */ + #[Then('/I will be stronger/')] public function iWillBeStronger() { PHPUnit\Framework\Assert::assertNotEquals(0, $this->strongLevel); } @@ -310,26 +296,23 @@ strongLevel = 0; } - /** - * @When /I eat an apple/ - */ + #[When('/I eat an apple/')] public function iEatAnApple() { } - /** - * @Then /I will be stronger/ - */ + #[Then('/I will be stronger/')] public function iWillBeStronger() { PHPUnit\Framework\Assert::assertNotEquals(0, $this->strongLevel); } @@ -410,22 +393,21 @@ use Behat\Behat\Context\Context, Behat\Behat\Tester\Exception\PendingException; + use Behat\Hook\BeforeScenario; + use Behat\Step\Given; + use Behat\Step\Then; class FeatureContext implements Context { private $value; - /** - * @BeforeScenario - */ + #[BeforeScenario] public function setup() { throw new \Exception(); } - /** - * @Given /I have entered (\d+)/ - * @Then /^I must have (\d+)$/ - */ + #[Given('/I have entered (\d+)/')] + #[Then('/^I must have (\d+)$/')] public function action($num) { } @@ -472,28 +454,25 @@ use Behat\Behat\Context\Context, Behat\Behat\Tester\Exception\PendingException; + use Behat\Step\Given; + use Behat\Step\Then; + use Behat\Step\When; class FeatureContext implements Context { private $value; - /** - * @Given /I have entered (\d+)/ - */ + #[Given('/I have entered (\d+)/')] public function iHaveEntered($num) { $this->value = $num; } - /** - * @Then /I must have (\d+)/ - */ + #[Then('/I must have (\d+)/')] public function iMustHave($num) { PHPUnit\Framework\Assert::assertEquals($num, $this->value); } - /** - * @When /I add (\d+)/ - */ + #[When('/I add (\d+)/')] public function iAdd($num) { $this->value += $num; } @@ -534,25 +513,27 @@ value = $num; } - /** - * @Then /I must have (\d+)/ - */ + + #[Then('/I must have (\d+)/')] public function iMustHave($num) { $foo = new class extends Foo implements Foo {}; } - /** - * @When /I add (\d+)/ - */ + + #[When('/I add (\d+)/')] public function iAdd($num) { $this->value += $num; } diff --git a/features/multiple_formats.feature b/features/multiple_formats.feature index eeb893f4e..4b9b493d0 100644 --- a/features/multiple_formats.feature +++ b/features/multiple_formats.feature @@ -12,6 +12,9 @@ Feature: Multiple formats Behat\Behat\Tester\Exception\PendingException; use Behat\Gherkin\Node\PyStringNode, Behat\Gherkin\Node\TableNode; + use Behat\Step\Given; + use Behat\Step\Then; + use Behat\Step\When; class FeatureContext implements Context { @@ -22,44 +25,32 @@ Feature: Multiple formats $this->parameters = $parameters; } - /** - * @Given /^I have (\d+) apples?$/ - */ + #[Given('/^I have (\d+) apples?$/')] public function iHaveApples($count) { $this->apples = intval($count); } - /** - * @When /^I ate (\d+) apples?$/ - */ + #[When('/^I ate (\d+) apples?$/')] public function iAteApples($count) { $this->apples -= intval($count); } - /** - * @When /^I found (\d+) apples?$/ - */ + #[When('/^I found (\d+) apples?$/')] public function iFoundApples($count) { $this->apples += intval($count); } - /** - * @Then /^I should have (\d+) apples$/ - */ + #[Then('/^I should have (\d+) apples$/')] public function iShouldHaveApples($count) { PHPUnit\Framework\Assert::assertEquals(intval($count), $this->apples); } - /** - * @Then /^context parameter "([^"]*)" should be equal to "([^"]*)"$/ - */ + #[Then('/^context parameter "([^"]*)" should be equal to "([^"]*)"$/')] public function contextParameterShouldBeEqualTo($key, $val) { PHPUnit\Framework\Assert::assertEquals($val, $this->parameters[$key]); } - /** - * @Given /^context parameter "([^"]*)" should be array with (\d+) elements$/ - */ + #[Given('/^context parameter "([^"]*)" should be array with (\d+) elements$/')] public function contextParameterShouldBeArrayWithElements($key, $count) { PHPUnit\Framework\Assert::assertIsArray($this->parameters[$key]); PHPUnit\Framework\Assert::assertEquals(2, count($this->parameters[$key])); diff --git a/features/name_filters.feature b/features/name_filters.feature index 519537502..33c97974c 100644 --- a/features/name_filters.feature +++ b/features/name_filters.feature @@ -11,22 +11,17 @@ Feature: Name filters use Behat\Behat\Context\Context; use Behat\Gherkin\Node\PyStringNode, Behat\Gherkin\Node\TableNode; + use Behat\Step\Given; class FeatureContext implements Context { - /** - * @Given /^Some slow step N(\d+)$/ - */ + #[Given('/^Some slow step N(\d+)$/')] public function someSlowStepN($num) {} - /** - * @Given /^Some normal step N(\d+)$/ - */ + #[Given('/^Some normal step N(\d+)$/')] public function someNormalStepN($num) {} - /** - * @Given /^Some fast step N(\d+)$/ - */ + #[Given('/^Some fast step N(\d+)$/')] public function someFastStepN($num) {} } """ diff --git a/features/outlines.feature b/features/outlines.feature index 352fca98c..91d618b13 100644 --- a/features/outlines.feature +++ b/features/outlines.feature @@ -12,30 +12,27 @@ Feature: Scenario Outlines Behat\Behat\Exception\PendingException; use Behat\Gherkin\Node\PyStringNode, Behat\Gherkin\Node\TableNode; + use Behat\Step\Given; + use Behat\Step\Then; + use Behat\Step\When; class FeatureContext implements Context { private $result; private $numbers; - /** - * @Given /^I have basic calculator$/ - */ + #[Given('/^I have basic calculator$/')] public function iHaveBasicCalculator() { $this->result = 0; $this->numbers = array(); } - /** - * @Given /^I have entered (\d+)$/ - */ + #[Given('/^I have entered (\d+)$/')] public function iHaveEntered($number) { $this->numbers[] = intval($number); } - /** - * @When /^I add$/ - */ + #[When('/^I add$/')] public function iAdd() { foreach ($this->numbers as $number) { $this->result += $number; @@ -43,9 +40,7 @@ Feature: Scenario Outlines $this->numbers = array(); } - /** - * @When /^I sub$/ - */ + #[When('/^I sub$/')] public function iSub() { $this->result = array_shift($this->numbers); foreach ($this->numbers as $number) { @@ -54,9 +49,7 @@ Feature: Scenario Outlines $this->numbers = array(); } - /** - * @When /^I multiply$/ - */ + #[When('/^I multiply$/')] public function iMultiply() { $this->result = array_shift($this->numbers); foreach ($this->numbers as $number) { @@ -65,9 +58,7 @@ Feature: Scenario Outlines $this->numbers = array(); } - /** - * @When /^I div$/ - */ + #[When('/^I div$/')] public function iDiv() { $this->result = array_shift($this->numbers); foreach ($this->numbers as $number) { @@ -76,9 +67,7 @@ Feature: Scenario Outlines $this->numbers = array(); } - /** - * @Then /^The result should be (\d+)$/ - */ + #[Then('/^The result should be (\d+)$/')] public function theResultShouldBe($result) { PHPUnit\Framework\Assert::assertEquals(intval($result), $this->result); } @@ -226,21 +215,19 @@ Feature: Scenario Outlines number += intval($number); } - /** - * @Then the result should be :result - */ + #[Then('the result should be :result')] public function theResultShouldBe($result) { PHPUnit\Framework\Assert::assertEquals(intval($result), $this->number); } diff --git a/features/parameters.feature b/features/parameters.feature index 784c542ac..020f7a407 100644 --- a/features/parameters.feature +++ b/features/parameters.feature @@ -11,47 +11,40 @@ Feature: Parameters use Behat\Behat\Context\Context; use Behat\Gherkin\Node\PyStringNode, Behat\Gherkin\Node\TableNode; + use Behat\Step\Given; + use Behat\Step\Then; + use Behat\Step\When; class FeatureContext implements Context { private $result; private $numbers; - /** - * @Given /I have basic calculator/ - */ + #[Given('/I have basic calculator/')] public function iHaveBasicCalculator() { $this->result = 0; $this->numbers = array(); } - /** - * @Given /I have entered (\d+)/ - */ + #[Given('/I have entered (\d+)/')] public function iHaveEntered($number) { $this->numbers[] = intval($number); } - /** - * @When /I add/ - */ + #[When('/I add/')] public function iAdd() { $this->result = array_sum($this->numbers); $this->numbers = array(); } - /** - * @When /I sub/ - */ + #[When('/I sub/')] public function iSub() { $this->result = array_shift($this->numbers); $this->result -= array_sum($this->numbers); $this->numbers = array(); } - /** - * @Then /The result should be (\d+)/ - */ + #[Then('/The result should be (\d+)/')] public function theResultShouldBe($result) { PHPUnit\Framework\Assert::assertEquals($result, $this->result); } diff --git a/features/preferred_profile.feature b/features/preferred_profile.feature index a6337210d..8e7c9a904 100644 --- a/features/preferred_profile.feature +++ b/features/preferred_profile.feature @@ -9,47 +9,40 @@ Feature: Preferred Profiles result = 0; $this->numbers = array(); } - /** - * @Given /I have entered (\d+)/ - */ + #[Given('/I have entered (\d+)/')] public function iHaveEntered($number) { $this->numbers[] = intval($number); } - /** - * @When /I add/ - */ + #[When('/I add/')] public function iAdd() { $this->result = array_sum($this->numbers); $this->numbers = array(); } - /** - * @When /I sub/ - */ + #[When('/I sub/')] public function iSub() { $this->result = array_shift($this->numbers); $this->result -= array_sum($this->numbers); $this->numbers = array(); } - /** - * @Then /The result should be (\d+)/ - */ + #[Then('/The result should be (\d+)/')] public function theResultShouldBe($result) { PHPUnit\Framework\Assert::assertEquals($result, $this->result); } diff --git a/features/pretty_format.feature b/features/pretty_format.feature index 17220c365..72d6c9cbc 100644 --- a/features/pretty_format.feature +++ b/features/pretty_format.feature @@ -12,35 +12,30 @@ Feature: Pretty Formatter Behat\Behat\Tester\Exception\PendingException; use Behat\Gherkin\Node\PyStringNode, Behat\Gherkin\Node\TableNode; + use Behat\Step\Given; + use Behat\Step\Then; + use Behat\Step\When; class FeatureContext implements Context { private $value; - /** - * @Given /I have entered (\d+)/ - */ + #[Given('/I have entered (\d+)/')] public function iHaveEntered($num) { $this->value = $num; } - /** - * @Then /I must have (\d+)/ - */ + #[Then('/I must have (\d+)/')] public function iMustHave($num) { PHPUnit\Framework\Assert::assertEquals($num, $this->value); } - /** - * @When /I add (\d+)/ - */ + #[When('/I add (\d+)/')] public function iAdd($num) { $this->value += $num; } - /** - * @When /^Something not done yet$/ - */ + #[When('/^Something not done yet$/')] public function somethingNotDoneYet() { throw new PendingException(); } @@ -147,28 +142,25 @@ Feature: Pretty Formatter value = $num; } - /** - * @Then /I must have (\d+)/ - */ + #[Then('/I must have (\d+)/')] public function iMustHave($num) { PHPUnit\Framework\Assert::assertEquals($num, $this->value); } - /** - * @When /I (add|subtract) the value (\d+)/ - */ + #[When('/I (add|subtract) the value (\d+)/')] public function iAddOrSubtract($op, $num) { if ($op == 'add') $this->value += $num; @@ -236,21 +228,19 @@ Feature: Pretty Formatter use Behat\Behat\Context\Context; use Behat\Gherkin\Node\PyStringNode, Behat\Gherkin\Node\TableNode; + use Behat\Step\Then; + use Behat\Step\When; class FeatureContext implements Context { private $value = 10; - /** - * @Then /I must have "([^"]+)"/ - */ + #[Then('/I must have "([^"]+)"/')] public function iMustHave($num) { PHPUnit\Framework\Assert::assertEquals(intval(preg_replace('/[^\d]+/', '', $num)), $this->value); } - /** - * @When /I add "([^"]+)"/ - */ + #[When('/I add "([^"]+)"/')] public function iAdd($num) { $this->value += intval(preg_replace('/[^\d]+/', '', $num)); } @@ -420,12 +410,11 @@ Feature: Pretty Formatter use Behat\Behat\Context\Context; use Behat\Behat\Tester\Exception\PendingException; + use Behat\Step\Given; class FeatureContext implements Context { - /** - * @Given /^.*$/ - */ + #[Given('/^.*$/')] public function anything() { throw new PendingException(); } diff --git a/features/profile_filters.feature b/features/profile_filters.feature index 400f0e521..10276b46d 100644 --- a/features/profile_filters.feature +++ b/features/profile_filters.feature @@ -9,22 +9,17 @@ Feature: Filters result = 0; $this->numbers = array(); } - /** - * @Given /I have entered (\d+)/ - */ + #[Given('/I have entered (\d+)/')] public function iHaveEntered($number) { $this->numbers[] = intval($number); } - /** - * @When /I add/ - */ + #[When('/I add/')] public function iAdd() { $this->result = array_sum($this->numbers); $this->numbers = array(); } - /** - * @When /I sub/ - */ + #[When('/I sub/')] public function iSub() { $this->result = array_shift($this->numbers); $this->result -= array_sum($this->numbers); $this->numbers = array(); } - /** - * @Then /The result should be (\d+)/ - */ + #[Then('/The result should be (\d+)/')] public function theResultShouldBe($result) { PHPUnit\Framework\Assert::assertEquals($result, $this->result); } diff --git a/features/rerun-only.feature b/features/rerun-only.feature index acbb45963..e79015d5e 100644 --- a/features/rerun-only.feature +++ b/features/rerun-only.feature @@ -9,6 +9,9 @@ Feature: Rerun parameters = $parameters; } - /** - * @Given /^I have (\d+) apples?$/ - */ + #[Given('/^I have (\d+) apples?$/')] public function iHaveApples($count) { $this->apples = intval($count); } - /** - * @When /^I ate (\d+) apples?$/ - */ + #[When('/^I ate (\d+) apples?$/')] public function iAteApples($count) { $this->apples -= intval($count); } - /** - * @When /^I found (\d+) apples?$/ - */ + #[When('/^I found (\d+) apples?$/')] public function iFoundApples($count) { $this->apples += intval($count); } - /** - * @Then /^I should have (\d+) apples$/ - */ + #[Then('/^I should have (\d+) apples$/')] public function iShouldHaveApples($count) { PHPUnit\Framework\Assert::assertEquals(intval($count), $this->apples); } - /** - * @Then /^context parameter "([^"]*)" should be equal to "([^"]*)"$/ - */ + #[Then('/^context parameter "([^"]*)" should be equal to "([^"]*)"$/')] public function contextParameterShouldBeEqualTo($key, $val) { PHPUnit\Framework\Assert::assertEquals($val, $this->parameters[$key]); } - /** - * @Given /^context parameter "([^"]*)" should be array with (\d+) elements$/ - */ + #[Given('/^context parameter "([^"]*)" should be array with (\d+) elements$/')] public function contextParameterShouldBeArrayWithElements($key, $count) { PHPUnit\Framework\Assert::assertIsArray($this->parameters[$key]); PHPUnit\Framework\Assert::assertEquals(2, count($this->parameters[$key])); diff --git a/features/rerun.feature b/features/rerun.feature index 4b3ac21fa..cc845d20c 100644 --- a/features/rerun.feature +++ b/features/rerun.feature @@ -9,6 +9,9 @@ Feature: Rerun parameters = $parameters; } - /** - * @Given /^I have (\d+) apples?$/ - */ + #[Given('/^I have (\d+) apples?$/')] public function iHaveApples($count) { $this->apples = intval($count); } - /** - * @When /^I ate (\d+) apples?$/ - */ + #[When('/^I ate (\d+) apples?$/')] public function iAteApples($count) { $this->apples -= intval($count); } - /** - * @When /^I found (\d+) apples?$/ - */ + #[When('/^I found (\d+) apples?$/')] public function iFoundApples($count) { $this->apples += intval($count); } - /** - * @Then /^I should have (\d+) apples$/ - */ + #[Then('/^I should have (\d+) apples$/')] public function iShouldHaveApples($count) { PHPUnit\Framework\Assert::assertEquals(intval($count), $this->apples); } - /** - * @Then /^context parameter "([^"]*)" should be equal to "([^"]*)"$/ - */ + #[Then('/^context parameter "([^"]*)" should be equal to "([^"]*)"$/')] public function contextParameterShouldBeEqualTo($key, $val) { PHPUnit\Framework\Assert::assertEquals($val, $this->parameters[$key]); } - /** - * @Given /^context parameter "([^"]*)" should be array with (\d+) elements$/ - */ + #[Given('/^context parameter "([^"]*)" should be array with (\d+) elements$/')] public function contextParameterShouldBeArrayWithElements($key, $count) { PHPUnit\Framework\Assert::assertIsArray($this->parameters[$key]); PHPUnit\Framework\Assert::assertEquals(2, count($this->parameters[$key])); diff --git a/features/rerun_strict.feature b/features/rerun_strict.feature index b6d47ec45..1caef9f13 100644 --- a/features/rerun_strict.feature +++ b/features/rerun_strict.feature @@ -9,20 +9,17 @@ Feature: Rerun with strict parameters = $parameters; } - /** - * @Given /^I have (\d+) (apples|bananas)$/ - */ + #[Given('/^I have (\d+) (apples|bananas)$/')] public function iHaveFruit($count, $fruit) { $this->fruits[$fruit] = intval($count); } - /** - * @When /^I ate (\d+) (apples|bananas)$/ - */ + #[When('/^I ate (\d+) (apples|bananas)$/')] public function iAteFruit($count, $fruit) { $this->fruits[$fruit] -= intval($count); } - /** - * @When /^I found (\d+) (apples|bananas)$/ - */ + #[When('/^I found (\d+) (apples|bananas)$/')] public function iFoundFruit($count, $fruit) { $this->fruits[$fruit] += intval($count); } - /** - * @Then /^I should have (\d+) (apples|bananas)$/ - */ + #[Then('/^I should have (\d+) (apples|bananas)$/')] public function iShouldHaveFruit($count, $fruit) { PHPUnit\Framework\Assert::assertEquals(intval($count), $this->fruits[$fruit]); } - /** - * @Then /^context parameter "([^"]*)" should be equal to "([^"]*)"$/ - */ + #[Then('/^context parameter "([^"]*)" should be equal to "([^"]*)"$/')] public function contextParameterShouldBeEqualTo($key, $val) { PHPUnit\Framework\Assert::assertEquals($val, $this->parameters[$key]); } - /** - * @Given /^context parameter "([^"]*)" should be array with (\d+) elements$/ - */ + #[Given('/^context parameter "([^"]*)" should be array with (\d+) elements$/')] public function contextParameterShouldBeArrayWithElements($key, $count) { PHPUnit\Framework\Assert::assertIsArray($this->parameters[$key]); PHPUnit\Framework\Assert::assertEquals(2, count($this->parameters[$key])); diff --git a/features/result_types.feature b/features/result_types.feature index 93db1847a..902185754 100644 --- a/features/result_types.feature +++ b/features/result_types.feature @@ -114,19 +114,17 @@ Feature: Different result types Behat\Behat\Tester\Exception\PendingException; use Behat\Gherkin\Node\PyStringNode, Behat\Gherkin\Node\TableNode; + use Behat\Step\Given; + use Behat\Step\When; class FeatureContext implements Context { - /** - * @Given /^human have ordered very very very hot "([^"]*)"$/ - */ + #[Given('/^human have ordered very very very hot "([^"]*)"$/')] public function humanOrdered($arg1): void { throw new PendingException; } - /** - * @When the coffee will be ready - */ + #[When('the coffee will be ready')] public function theCoffeeWillBeReady(): void { throw new PendingException; } @@ -153,6 +151,11 @@ Feature: Different result types { throw new PendingException(); } + + --- Don't forget these 2 use statements: + + use Behat\Behat\Tester\Exception\PendingException; + use Behat\Step\Then; """ When I run "behat --no-colors --strict -f progress features/coffee.feature --snippets-for=FeatureContext --snippets-type=regex" Then it should fail with: @@ -204,21 +207,19 @@ Feature: Different result types Behat\Behat\Tester\Exception\PendingException; use Behat\Gherkin\Node\PyStringNode, Behat\Gherkin\Node\TableNode; + use Behat\Step\Given; + use Behat\Step\Then; class FeatureContext implements Context { private $money = 0; - /** - * @Given /^I have thrown (\d+)\$ into machine$/ - */ + #[Given('/^I have thrown (\d+)\$ into machine$/')] public function pay($money) { $this->money += $money; } - /** - * @Then /^I should see (\d+)\$ on the screen$/ - */ + #[Then('/^I should see (\d+)\$ on the screen$/')] public function iShouldSee($money) { PHPUnit\Framework\Assert::assertEquals($money, $this->money); } @@ -274,39 +275,40 @@ Feature: Different result types Behat\Behat\Tester\Exception\PendingException; use Behat\Gherkin\Node\PyStringNode, Behat\Gherkin\Node\TableNode; + use Behat\Step\Given; + use Behat\Step\Then; + use Behat\Step\When; class FeatureContext implements Context { private $money = 0; - /** @Given /^human bought coffee$/ */ + #[Given('/^human bought coffee$/')] public function humanBoughtCoffee() {} - /** @Given /^I have water$/ */ + #[Given('/^I have water$/')] public function water() {} - /** @Given /^I have no water$/ */ + #[Given('/^I have no water$/')] public function noWater() { throw new Exception('NO water in coffee machine!!!'); } - /** @Given /^I have electricity$/ */ + #[Given('/^I have electricity$/')] public function haveElectricity() {} - /** @Given /^I have no electricity$/ */ + #[Given('/^I have no electricity$/')] public function haveNoElectricity() { throw new Exception('NO electricity in coffee machine!!!'); } - /** @When /^I boil water$/ */ + #[When('/^I boil water$/')] public function boilWater() {} - /** @Then /^the coffee should be almost done$/ */ + #[Then('/^the coffee should be almost done$/')] public function coffeeAlmostDone() {} - /** - * @Then /^I should see (\d+)\$ on the screen$/ - */ + #[Then('/^I should see (\d+)\$ on the screen$/')] public function iShouldSee($money) { PHPUnit\Framework\Assert::assertEquals($money, $this->money); } @@ -351,22 +353,22 @@ Feature: Different result types Behat\Behat\Tester\Exception\PendingException; use Behat\Gherkin\Node\PyStringNode, Behat\Gherkin\Node\TableNode; + use Behat\Step\Given; + use Behat\Step\Then; class FeatureContext implements Context { - /** @Given /^human have chosen "([^"]*)"$/ */ + #[Given('/^human have chosen "([^"]*)"$/')] public function chosen($arg1): void { throw new PendingException; } - /** @Given /^human have chosen "Latte"$/ */ + #[Given('/^human have chosen "Latte"$/')] public function chosenLatte(): void { throw new PendingException; } - /** - * @Then /^I should make him "([^"]*)"$/ - */ + #[Then('/^I should make him "([^"]*)"$/')] public function iShouldSee($money): void { throw new PendingException; } @@ -409,15 +411,16 @@ Feature: Different result types Behat\Behat\Exception\PendingException; use Behat\Gherkin\Node\PyStringNode, Behat\Gherkin\Node\TableNode; + use Behat\Step\Given; class FeatureContext implements Context { - /** @Given /^customer bought coffee$/ */ + #[Given('/^customer bought coffee$/')] public function chosen($arg1) { // do something } - /** @Given /^customer bought coffee$/ */ + #[Given('/^customer bought coffee$/')] public function chosenLatte() { // do something else } @@ -450,15 +453,16 @@ Feature: Different result types Behat\Behat\Tester\Exception\PendingException; use Behat\Gherkin\Node\PyStringNode, Behat\Gherkin\Node\TableNode; + use Behat\Step\Given; class FeatureContext implements Context { - /** @Given /^customer bought coffee$/ */ + #[Given('/^customer bought coffee$/')] public function chosen() { trigger_error("some warning", E_USER_WARNING); } - /** @Given /^customer bought another one coffee$/ */ + #[Given('/^customer bought another one coffee$/')] public function chosenLatte() { // do something else } @@ -474,7 +478,7 @@ Feature: Different result types 001 Scenario: Redundant menu # features/coffee.feature:6 Given customer bought coffee # features/coffee.feature:7 - User Warning: some warning in features/bootstrap/FeatureContext.php line 12 + User Warning: some warning in features/bootstrap/FeatureContext.php line 13 1 scenario (1 failed) 2 steps (1 failed, 1 skipped) diff --git a/features/syntax_help.feature b/features/syntax_help.feature index 16964a950..5dab0cc1f 100644 --- a/features/syntax_help.feature +++ b/features/syntax_help.feature @@ -83,33 +83,28 @@ Feature: Syntax helpers use Behat\Behat\Context\Context, Behat\Behat\Exception\PendingException; + use Behat\Step\Given; + use Behat\Step\Then; + use Behat\Step\When; class FeatureContext implements Context { - /** - * @Given /^(?:I|We) have (\d+) apples?$/ - */ + #[Given('/^(?:I|We) have (\d+) apples?$/')] public function iHaveApples($count) { throw new PendingException(); } - /** - * @When /^(?:I|We) ate (\d+) apples?$/ - */ + #[When('/^(?:I|We) ate (\d+) apples?$/')] public function iAteApples($count) { throw new PendingException(); } - /** - * @When /^(?:I|We) found (\d+) apples?$/ - */ + #[When('/^(?:I|We) found (\d+) apples?$/')] public function iFoundApples($count) { throw new PendingException(); } - /** - * @Then /^(?:I|We) should have (\d+) apples$/ - */ + #[Then('/^(?:I|We) should have (\d+) apples$/')] public function iShouldHaveApples($count) { throw new PendingException(); } @@ -132,33 +127,28 @@ Feature: Syntax helpers use Behat\Behat\Context\Context, Behat\Behat\Exception\PendingException, Behat\Behat\Context\TranslatableContext; + use Behat\Step\Given; + use Behat\Step\Then; + use Behat\Step\When; class FeatureContext implements TranslatableContext { - /** - * @Given /^I have (\d+) apples?$/ - */ + #[Given('/^I have (\d+) apples?$/')] public function iHaveApples($count) { throw new PendingException(); } - /** - * @When /^I ate (\d+) apples?$/ - */ + #[When('/^I ate (\d+) apples?$/')] public function iAteApples($count) { throw new PendingException(); } - /** - * @When /^I found (\d+) apples?$/ - */ + #[When('/^I found (\d+) apples?$/')] public function iFoundApples($count) { throw new PendingException(); } - /** - * @Then /^I should have (\d+) apples$/ - */ + #[Then('/^I should have (\d+) apples$/')] public function iShouldHaveApples($count) { throw new PendingException(); } @@ -202,12 +192,13 @@ Feature: Syntax helpers use Behat\Behat\Context\Context, Behat\Behat\Exception\PendingException; + use Behat\Step\Given; + use Behat\Step\Then; + use Behat\Step\When; class FeatureContext implements Context { - /** - * @Given /^I have (\d+) apples?$/ - */ + #[Given('/^I have (\d+) apples?$/')] public function iHaveApples($count) { throw new PendingException(); } @@ -220,23 +211,18 @@ Feature: Syntax helpers * - two * -- * Internal note not showing in help - * - * @When /^I ate (\d+) apples?$/ */ + #[When('/^I ate (\d+) apples?$/')] public function iAteApples($count) { throw new PendingException(); } - /** - * @When /^I found (\d+) apples?$/ - */ + #[When('/^I found (\d+) apples?$/')] public function iFoundApples($count) { throw new PendingException(); } - /** - * @Then /^I should have (\d+) apples$/ - */ + #[Then('/^I should have (\d+) apples$/')] public function iShouldHaveApples($count) { throw new PendingException(); } @@ -269,41 +255,37 @@ Feature: Syntax helpers use Behat\Behat\Context\Context, Behat\Behat\Exception\PendingException; + use Behat\Step\Given; + use Behat\Step\Then; + use Behat\Step\When; class FeatureContext implements Context { - /** - * @Given /^I have (\d+) apples?$/ - */ + #[Given('/^I have (\d+) apples?$/')] public function iHaveApples($count) { throw new PendingException(); } /** * Eating apples - * + * * More details on eating apples, and a list: * - one * - two * -- * Internal note not showing in help - * - * @When /^I ate (\d+) apples?$/ */ + #[When('/^I ate (\d+) apples?$/')] public function iAteApples($count) { throw new PendingException(); } - /** - * @When /^I found (\d+) apples?$/ - */ + #[When('/^I found (\d+) apples?$/')] public function iFoundApples($count) { throw new PendingException(); } - /** - * @Then /^I should have (\d+) apples$/ - */ + #[Then('/^I should have (\d+) apples$/')] public function iShouldHaveApples($count) { throw new PendingException(); } @@ -314,11 +296,10 @@ Feature: Syntax helpers """ default | [Given|*] /^I have (\d+) apples?$/ | at `FeatureContext::iHaveApples()` - | on `%%WORKING_DIR%%features%%DS%%bootstrap%%DS%%FeatureContext.php[11:13]` + | on `%%WORKING_DIR%%features%%DS%%bootstrap%%DS%%FeatureContext.php[12:14]` default | [When|*] /^I ate (\d+) apples?$/ | Eating apples - | | More details on eating apples, and a list: | - one | - two @@ -327,11 +308,11 @@ Feature: Syntax helpers default | [When|*] /^I found (\d+) apples?$/ | at `FeatureContext::iFoundApples()` - | on `%%WORKING_DIR%%features%%DS%%bootstrap%%DS%%FeatureContext.php[33:35]` + | on `%%WORKING_DIR%%features%%DS%%bootstrap%%DS%%FeatureContext.php[31:33]` default | [Then|*] /^I should have (\d+) apples$/ | at `FeatureContext::iShouldHaveApples()` - | on `%%WORKING_DIR%%features%%DS%%bootstrap%%DS%%FeatureContext.php[40:42]` + | on `%%WORKING_DIR%%features%%DS%%bootstrap%%DS%%FeatureContext.php[36:38]` """ Scenario: Search definition @@ -342,33 +323,28 @@ Feature: Syntax helpers use Behat\Behat\Context\Context, Behat\Behat\Exception\PendingException, Behat\Behat\Context\TranslatableContext; + use Behat\Step\Given; + use Behat\Step\Then; + use Behat\Step\When; class FeatureContext implements TranslatableContext { - /** - * @Given /^I have (\d+) apples?$/ - */ + #[Given('/^I have (\d+) apples?$/')] public function iHaveApples($count) { throw new PendingException(); } - /** - * @When /^I ate (\d+) apples?$/ - */ + #[When('/^I ate (\d+) apples?$/')] public function iAteApples($count) { throw new PendingException(); } - /** - * @When /^I found (\d+) apples?$/ - */ + #[When('/^I found (\d+) apples?$/')] public function iFoundApples($count) { throw new PendingException(); } - /** - * @Then /^I should have (\d+) apples$/ - */ + #[Then('/^I should have (\d+) apples$/')] public function iShouldHaveApples($count) { throw new PendingException(); } diff --git a/features/tag_filters.feature b/features/tag_filters.feature index e20a3beb5..e2a95b185 100644 --- a/features/tag_filters.feature +++ b/features/tag_filters.feature @@ -9,22 +9,17 @@ Feature: Tags apples = intval($count); } - /** - * @When /^I ate (\d+) apples?$/ - */ + #[When('/^I ate (\d+) apples?$/')] public function iAteApples($count) { $this->apples -= intval($count); } - /** - * @When /^I found (\d+) apples?$/ - */ + #[When('/^I found (\d+) apples?$/')] public function iFoundApples($count) { $this->apples += intval($count); } - /** - * @Then /^I should have (\d+) apples$/ - */ + #[Then('/^I should have (\d+) apples$/')] public function iShouldHaveApples($count) { PHPUnit\Framework\Assert::assertEquals(intval($count), $this->apples); } diff --git a/src/Behat/Behat/Context/Reader/AttributeContextReader.php b/src/Behat/Behat/Context/Reader/AttributeContextReader.php index fded9218d..1e56bcae5 100644 --- a/src/Behat/Behat/Context/Reader/AttributeContextReader.php +++ b/src/Behat/Behat/Context/Reader/AttributeContextReader.php @@ -73,7 +73,7 @@ private function readMethodCallees(string $contextClass, ReflectionMethod $metho /** * @return array
+ I pick the :index thing + + я беру :index вещь + /^the index should be "([^"]*)"$/ + + /^индекс должен быть "([^"]*)"$/ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + */ - public function readParentCallees( + private function readParentCallees( string $contextClass, ReflectionMethod $method, AttributeReader $reader, From 84449d4b5cb50b500f84bfc87e82c8f470bc616d Mon Sep 17 00:00:00 2001 From: Christophe Coevoet Date: Sat, 21 Dec 2024 16:01:16 +0100 Subject: [PATCH 521/567] Add generic types for the specification type for SpecificationIterator --- .../Tester/EventDispatchingFeatureTester.php | 9 +++-- .../Specification/LazyFeatureIterator.php | 2 + .../Locator/FilesystemFeatureLocator.php | 3 ++ .../FilesystemRerunScenariosListLocator.php | 3 ++ .../FilesystemScenariosListLocator.php | 3 ++ .../Hook/Tester/HookableFeatureTester.php | 9 +++-- .../Tester/Runtime/RuntimeFeatureTester.php | 3 ++ .../Event/AfterExerciseCompleted.php | 9 +---- .../Event/AfterExerciseSetup.php | 9 +---- .../EventDispatcher/Event/AfterSuiteSetup.php | 9 +---- .../Event/AfterSuiteTested.php | 9 +---- .../Event/BeforeExerciseCompleted.php | 9 +---- .../Event/BeforeExerciseTeardown.php | 9 +---- .../Event/BeforeSuiteTeardown.php | 9 +---- .../Event/BeforeSuiteTested.php | 9 +---- .../Event/ExerciseCompleted.php | 2 +- .../EventDispatcher/Event/SuiteTested.php | 2 +- .../Tester/EventDispatchingExercise.php | 7 +++- .../Tester/EventDispatchingSuiteTester.php | 16 +++----- .../Testwork/Hook/Scope/AfterSuiteScope.php | 4 +- .../Testwork/Hook/Scope/BeforeSuiteScope.php | 7 +--- src/Behat/Testwork/Hook/Scope/SuiteScope.php | 2 +- .../Hook/Tester/HookableSuiteTester.php | 16 +++----- .../Testwork/Ordering/OrderedExercise.php | 40 +++++-------------- .../Testwork/Ordering/Orderer/NoopOrderer.php | 7 ---- .../Testwork/Ordering/Orderer/Orderer.php | 6 ++- .../Ordering/Orderer/RandomOrderer.php | 9 ++--- .../Ordering/Orderer/ReverseOrderer.php | 14 +++---- .../GroupedSpecificationIterator.php | 13 ++++-- .../Locator/SpecificationLocator.php | 4 +- .../NoSpecificationsIterator.php | 2 + .../SpecificationArrayIterator.php | 8 ++-- .../Specification/SpecificationFinder.php | 10 +++-- .../Specification/SpecificationIterator.php | 3 +- src/Behat/Testwork/Tester/Exercise.php | 8 ++-- .../Tester/Runtime/RuntimeExercise.php | 7 +++- .../Tester/Runtime/RuntimeSuiteTester.php | 16 +++----- .../Testwork/Tester/SpecificationTester.php | 8 ++-- src/Behat/Testwork/Tester/SuiteTester.php | 8 ++-- 39 files changed, 138 insertions(+), 185 deletions(-) diff --git a/src/Behat/Behat/EventDispatcher/Tester/EventDispatchingFeatureTester.php b/src/Behat/Behat/EventDispatcher/Tester/EventDispatchingFeatureTester.php index ef95f5d41..47fd15367 100644 --- a/src/Behat/Behat/EventDispatcher/Tester/EventDispatchingFeatureTester.php +++ b/src/Behat/Behat/EventDispatcher/Tester/EventDispatchingFeatureTester.php @@ -14,6 +14,7 @@ use Behat\Behat\EventDispatcher\Event\AfterFeatureTested; use Behat\Behat\EventDispatcher\Event\BeforeFeatureTeardown; use Behat\Behat\EventDispatcher\Event\BeforeFeatureTested; +use Behat\Gherkin\Node\FeatureNode; use Behat\Testwork\Environment\Environment; use Behat\Testwork\EventDispatcher\TestworkEventDispatcher; use Behat\Testwork\Tester\Result\TestResult; @@ -24,11 +25,13 @@ * Feature tester dispatching BEFORE/AFTER events during tests. * * @author Konstantin Kudryashov + * + * @implements SpecificationTester */ final class EventDispatchingFeatureTester implements SpecificationTester { /** - * @var SpecificationTester + * @var SpecificationTester */ private $baseTester; /** @@ -39,8 +42,8 @@ final class EventDispatchingFeatureTester implements SpecificationTester /** * Initializes tester. * - * @param SpecificationTester $baseTester - * @param EventDispatcherInterface $eventDispatcher + * @param SpecificationTester $baseTester + * @param EventDispatcherInterface $eventDispatcher */ public function __construct(SpecificationTester $baseTester, EventDispatcherInterface $eventDispatcher) { diff --git a/src/Behat/Behat/Gherkin/Specification/LazyFeatureIterator.php b/src/Behat/Behat/Gherkin/Specification/LazyFeatureIterator.php index fe605b4cd..94bef6167 100644 --- a/src/Behat/Behat/Gherkin/Specification/LazyFeatureIterator.php +++ b/src/Behat/Behat/Gherkin/Specification/LazyFeatureIterator.php @@ -25,6 +25,8 @@ * Lazily iterates (parses one-by-one) over features. * * @author Konstantin Kudryashov + * + * @implements SpecificationIterator */ final class LazyFeatureIterator implements SpecificationIterator { diff --git a/src/Behat/Behat/Gherkin/Specification/Locator/FilesystemFeatureLocator.php b/src/Behat/Behat/Gherkin/Specification/Locator/FilesystemFeatureLocator.php index d96cf8e1d..3d3305d88 100644 --- a/src/Behat/Behat/Gherkin/Specification/Locator/FilesystemFeatureLocator.php +++ b/src/Behat/Behat/Gherkin/Specification/Locator/FilesystemFeatureLocator.php @@ -13,6 +13,7 @@ use Behat\Behat\Gherkin\Specification\LazyFeatureIterator; use Behat\Gherkin\Filter\PathsFilter; use Behat\Gherkin\Gherkin; +use Behat\Gherkin\Node\FeatureNode; use Behat\Testwork\Specification\Locator\SpecificationLocator; use Behat\Testwork\Specification\NoSpecificationsIterator; use Behat\Testwork\Suite\Exception\SuiteConfigurationException; @@ -25,6 +26,8 @@ * Loads gherkin features from the filesystem using gherkin parser. * * @author Konstantin Kudryashov + * + * @implements SpecificationLocator */ final class FilesystemFeatureLocator implements SpecificationLocator { diff --git a/src/Behat/Behat/Gherkin/Specification/Locator/FilesystemRerunScenariosListLocator.php b/src/Behat/Behat/Gherkin/Specification/Locator/FilesystemRerunScenariosListLocator.php index 8636d3279..5db0c634e 100644 --- a/src/Behat/Behat/Gherkin/Specification/Locator/FilesystemRerunScenariosListLocator.php +++ b/src/Behat/Behat/Gherkin/Specification/Locator/FilesystemRerunScenariosListLocator.php @@ -12,6 +12,7 @@ use Behat\Behat\Gherkin\Specification\LazyFeatureIterator; use Behat\Gherkin\Gherkin; +use Behat\Gherkin\Node\FeatureNode; use Behat\Testwork\Specification\Locator\SpecificationLocator; use Behat\Testwork\Specification\NoSpecificationsIterator; use Behat\Testwork\Suite\Suite; @@ -20,6 +21,8 @@ * Loads gherkin features using a file with the list of scenarios. * * @author Konstantin Kudryashov + * + * @implements SpecificationLocator */ final class FilesystemRerunScenariosListLocator implements SpecificationLocator { diff --git a/src/Behat/Behat/Gherkin/Specification/Locator/FilesystemScenariosListLocator.php b/src/Behat/Behat/Gherkin/Specification/Locator/FilesystemScenariosListLocator.php index ccacedd0f..57e1a3fd9 100644 --- a/src/Behat/Behat/Gherkin/Specification/Locator/FilesystemScenariosListLocator.php +++ b/src/Behat/Behat/Gherkin/Specification/Locator/FilesystemScenariosListLocator.php @@ -12,6 +12,7 @@ use Behat\Behat\Gherkin\Specification\LazyFeatureIterator; use Behat\Gherkin\Gherkin; +use Behat\Gherkin\Node\FeatureNode; use Behat\Testwork\Specification\Locator\SpecificationLocator; use Behat\Testwork\Specification\NoSpecificationsIterator; use Behat\Testwork\Suite\Suite; @@ -20,6 +21,8 @@ * Loads gherkin features using a file with the list of scenarios. * * @author Konstantin Kudryashov + * + * @implements SpecificationLocator */ final class FilesystemScenariosListLocator implements SpecificationLocator { diff --git a/src/Behat/Behat/Hook/Tester/HookableFeatureTester.php b/src/Behat/Behat/Hook/Tester/HookableFeatureTester.php index 288c6c006..491c121d0 100644 --- a/src/Behat/Behat/Hook/Tester/HookableFeatureTester.php +++ b/src/Behat/Behat/Hook/Tester/HookableFeatureTester.php @@ -12,6 +12,7 @@ use Behat\Behat\Hook\Scope\AfterFeatureScope; use Behat\Behat\Hook\Scope\BeforeFeatureScope; +use Behat\Gherkin\Node\FeatureNode; use Behat\Testwork\Environment\Environment; use Behat\Testwork\Hook\HookDispatcher; use Behat\Testwork\Hook\Tester\Setup\HookedSetup; @@ -23,11 +24,13 @@ * Feature tester which dispatches hooks during its execution. * * @author Konstantin Kudryashov + * + * @implements SpecificationTester */ final class HookableFeatureTester implements SpecificationTester { /** - * @var SpecificationTester + * @var SpecificationTester */ private $baseTester; /** @@ -38,8 +41,8 @@ final class HookableFeatureTester implements SpecificationTester /** * Initializes tester. * - * @param SpecificationTester $baseTester - * @param HookDispatcher $hookDispatcher + * @param SpecificationTester $baseTester + * @param HookDispatcher $hookDispatcher */ public function __construct(SpecificationTester $baseTester, HookDispatcher $hookDispatcher) { diff --git a/src/Behat/Behat/Tester/Runtime/RuntimeFeatureTester.php b/src/Behat/Behat/Tester/Runtime/RuntimeFeatureTester.php index bb7077877..c6c03ddb8 100644 --- a/src/Behat/Behat/Tester/Runtime/RuntimeFeatureTester.php +++ b/src/Behat/Behat/Tester/Runtime/RuntimeFeatureTester.php @@ -12,6 +12,7 @@ use Behat\Behat\Tester\OutlineTester; use Behat\Behat\Tester\ScenarioTester; +use Behat\Gherkin\Node\FeatureNode; use Behat\Gherkin\Node\OutlineNode; use Behat\Testwork\Environment\Environment; use Behat\Testwork\Environment\EnvironmentManager; @@ -27,6 +28,8 @@ * Tester executing feature tests in the runtime. * * @author Konstantin Kudryashov + * + * @implements SpecificationTester */ final class RuntimeFeatureTester implements SpecificationTester { diff --git a/src/Behat/Testwork/EventDispatcher/Event/AfterExerciseCompleted.php b/src/Behat/Testwork/EventDispatcher/Event/AfterExerciseCompleted.php index b2eec9f49..f3f004cb8 100644 --- a/src/Behat/Testwork/EventDispatcher/Event/AfterExerciseCompleted.php +++ b/src/Behat/Testwork/EventDispatcher/Event/AfterExerciseCompleted.php @@ -22,7 +22,7 @@ final class AfterExerciseCompleted extends ExerciseCompleted implements AfterTested { /** - * @var SpecificationIterator[] + * @var SpecificationIterator[] */ private $specificationIterators; /** @@ -37,7 +37,7 @@ final class AfterExerciseCompleted extends ExerciseCompleted implements AfterTes /** * Initializes event. * - * @param SpecificationIterator[] $specificationIterators + * @param SpecificationIterator[] $specificationIterators * @param TestResult $result * @param Teardown $teardown */ @@ -48,11 +48,6 @@ public function __construct(array $specificationIterators, TestResult $result, T $this->teardown = $teardown; } - /** - * Returns specification iterators. - * - * @return SpecificationIterator[] - */ public function getSpecificationIterators() { return $this->specificationIterators; diff --git a/src/Behat/Testwork/EventDispatcher/Event/AfterExerciseSetup.php b/src/Behat/Testwork/EventDispatcher/Event/AfterExerciseSetup.php index b77de0610..a828f7d72 100644 --- a/src/Behat/Testwork/EventDispatcher/Event/AfterExerciseSetup.php +++ b/src/Behat/Testwork/EventDispatcher/Event/AfterExerciseSetup.php @@ -21,7 +21,7 @@ final class AfterExerciseSetup extends ExerciseCompleted implements AfterSetup { /** - * @var SpecificationIterator[] + * @var SpecificationIterator[] */ private $specificationIterators; /** @@ -32,7 +32,7 @@ final class AfterExerciseSetup extends ExerciseCompleted implements AfterSetup /** * Initializes event. * - * @param SpecificationIterator[] $specificationIterators + * @param SpecificationIterator[] $specificationIterators * @param Setup $setup */ public function __construct(array $specificationIterators, Setup $setup) @@ -41,11 +41,6 @@ public function __construct(array $specificationIterators, Setup $setup) $this->setup = $setup; } - /** - * Returns specification iterators. - * - * @return SpecificationIterator[] - */ public function getSpecificationIterators() { return $this->specificationIterators; diff --git a/src/Behat/Testwork/EventDispatcher/Event/AfterSuiteSetup.php b/src/Behat/Testwork/EventDispatcher/Event/AfterSuiteSetup.php index 591e54ba3..4e1c6473d 100644 --- a/src/Behat/Testwork/EventDispatcher/Event/AfterSuiteSetup.php +++ b/src/Behat/Testwork/EventDispatcher/Event/AfterSuiteSetup.php @@ -22,7 +22,7 @@ final class AfterSuiteSetup extends SuiteTested implements AfterSetup { /** - * @var SpecificationIterator + * @var SpecificationIterator */ private $iterator; /** @@ -34,7 +34,7 @@ final class AfterSuiteSetup extends SuiteTested implements AfterSetup * Initializes event. * * @param Environment $env - * @param SpecificationIterator $iterator + * @param SpecificationIterator $iterator * @param Setup $setup */ public function __construct(Environment $env, SpecificationIterator $iterator, Setup $setup) @@ -45,11 +45,6 @@ public function __construct(Environment $env, SpecificationIterator $iterator, S $this->setup = $setup; } - /** - * Returns specification iterator. - * - * @return SpecificationIterator - */ public function getSpecificationIterator() { return $this->iterator; diff --git a/src/Behat/Testwork/EventDispatcher/Event/AfterSuiteTested.php b/src/Behat/Testwork/EventDispatcher/Event/AfterSuiteTested.php index b68a4ec97..7d40bed34 100644 --- a/src/Behat/Testwork/EventDispatcher/Event/AfterSuiteTested.php +++ b/src/Behat/Testwork/EventDispatcher/Event/AfterSuiteTested.php @@ -23,7 +23,7 @@ final class AfterSuiteTested extends SuiteTested implements AfterTested { /** - * @var SpecificationIterator + * @var SpecificationIterator */ private $iterator; /** @@ -39,7 +39,7 @@ final class AfterSuiteTested extends SuiteTested implements AfterTested * Initializes event. * * @param Environment $env - * @param SpecificationIterator $iterator + * @param SpecificationIterator $iterator * @param TestResult $result * @param Teardown $teardown */ @@ -56,11 +56,6 @@ public function __construct( $this->teardown = $teardown; } - /** - * Returns specification iterator. - * - * @return SpecificationIterator - */ public function getSpecificationIterator() { return $this->iterator; diff --git a/src/Behat/Testwork/EventDispatcher/Event/BeforeExerciseCompleted.php b/src/Behat/Testwork/EventDispatcher/Event/BeforeExerciseCompleted.php index dc0a22cd0..303a68105 100644 --- a/src/Behat/Testwork/EventDispatcher/Event/BeforeExerciseCompleted.php +++ b/src/Behat/Testwork/EventDispatcher/Event/BeforeExerciseCompleted.php @@ -20,25 +20,20 @@ final class BeforeExerciseCompleted extends ExerciseCompleted implements BeforeTested { /** - * @var SpecificationIterator[] + * @var SpecificationIterator[] */ private $specificationIterators; /** * Initializes event. * - * @param SpecificationIterator[] $specificationIterators + * @param SpecificationIterator[] $specificationIterators */ public function __construct(array $specificationIterators) { $this->specificationIterators = $specificationIterators; } - /** - * Returns specification iterators. - * - * @return SpecificationIterator[] - */ public function getSpecificationIterators() { return $this->specificationIterators; diff --git a/src/Behat/Testwork/EventDispatcher/Event/BeforeExerciseTeardown.php b/src/Behat/Testwork/EventDispatcher/Event/BeforeExerciseTeardown.php index 5892a0849..22ad745bb 100644 --- a/src/Behat/Testwork/EventDispatcher/Event/BeforeExerciseTeardown.php +++ b/src/Behat/Testwork/EventDispatcher/Event/BeforeExerciseTeardown.php @@ -21,7 +21,7 @@ final class BeforeExerciseTeardown extends ExerciseCompleted implements BeforeTeardown { /** - * @var SpecificationIterator[] + * @var SpecificationIterator[] */ private $specificationIterators; /** @@ -32,7 +32,7 @@ final class BeforeExerciseTeardown extends ExerciseCompleted implements BeforeTe /** * Initializes event. * - * @param SpecificationIterator[] $specificationIterators + * @param SpecificationIterator[] $specificationIterators * @param TestResult $result */ public function __construct(array $specificationIterators, TestResult $result) @@ -41,11 +41,6 @@ public function __construct(array $specificationIterators, TestResult $result) $this->result = $result; } - /** - * Returns specification iterators. - * - * @return SpecificationIterator[] - */ public function getSpecificationIterators() { return $this->specificationIterators; diff --git a/src/Behat/Testwork/EventDispatcher/Event/BeforeSuiteTeardown.php b/src/Behat/Testwork/EventDispatcher/Event/BeforeSuiteTeardown.php index 31382172e..ba145d473 100644 --- a/src/Behat/Testwork/EventDispatcher/Event/BeforeSuiteTeardown.php +++ b/src/Behat/Testwork/EventDispatcher/Event/BeforeSuiteTeardown.php @@ -22,7 +22,7 @@ final class BeforeSuiteTeardown extends SuiteTested implements BeforeTeardown { /** - * @var SpecificationIterator + * @var SpecificationIterator */ private $iterator; /** @@ -34,7 +34,7 @@ final class BeforeSuiteTeardown extends SuiteTested implements BeforeTeardown * Initializes event. * * @param Environment $env - * @param SpecificationIterator $iterator + * @param SpecificationIterator $iterator * @param TestResult $result */ public function __construct(Environment $env, SpecificationIterator $iterator, TestResult $result) @@ -45,11 +45,6 @@ public function __construct(Environment $env, SpecificationIterator $iterator, T $this->result = $result; } - /** - * Returns specification iterator. - * - * @return SpecificationIterator - */ public function getSpecificationIterator() { return $this->iterator; diff --git a/src/Behat/Testwork/EventDispatcher/Event/BeforeSuiteTested.php b/src/Behat/Testwork/EventDispatcher/Event/BeforeSuiteTested.php index 819be30d5..f08695d61 100644 --- a/src/Behat/Testwork/EventDispatcher/Event/BeforeSuiteTested.php +++ b/src/Behat/Testwork/EventDispatcher/Event/BeforeSuiteTested.php @@ -21,7 +21,7 @@ final class BeforeSuiteTested extends SuiteTested implements BeforeTested { /** - * @var SpecificationIterator + * @var SpecificationIterator */ private $iterator; @@ -29,7 +29,7 @@ final class BeforeSuiteTested extends SuiteTested implements BeforeTested * Initializes event. * * @param Environment $env - * @param SpecificationIterator $iterator + * @param SpecificationIterator $iterator */ public function __construct(Environment $env, SpecificationIterator $iterator) { @@ -38,11 +38,6 @@ public function __construct(Environment $env, SpecificationIterator $iterator) $this->iterator = $iterator; } - /** - * Returns specification iterator. - * - * @return SpecificationIterator - */ public function getSpecificationIterator() { return $this->iterator; diff --git a/src/Behat/Testwork/EventDispatcher/Event/ExerciseCompleted.php b/src/Behat/Testwork/EventDispatcher/Event/ExerciseCompleted.php index 4a88dfbff..9927c006d 100644 --- a/src/Behat/Testwork/EventDispatcher/Event/ExerciseCompleted.php +++ b/src/Behat/Testwork/EventDispatcher/Event/ExerciseCompleted.php @@ -29,7 +29,7 @@ abstract class ExerciseCompleted extends Event /** * Returns specification iterators. * - * @return SpecificationIterator[] + * @return SpecificationIterator[] */ abstract public function getSpecificationIterators(); } diff --git a/src/Behat/Testwork/EventDispatcher/Event/SuiteTested.php b/src/Behat/Testwork/EventDispatcher/Event/SuiteTested.php index de56d077b..45a5b506d 100644 --- a/src/Behat/Testwork/EventDispatcher/Event/SuiteTested.php +++ b/src/Behat/Testwork/EventDispatcher/Event/SuiteTested.php @@ -27,7 +27,7 @@ abstract class SuiteTested extends LifecycleEvent /** * Returns specification iterator. * - * @return SpecificationIterator + * @return SpecificationIterator */ abstract public function getSpecificationIterator(); } diff --git a/src/Behat/Testwork/EventDispatcher/Tester/EventDispatchingExercise.php b/src/Behat/Testwork/EventDispatcher/Tester/EventDispatchingExercise.php index 9c319761d..03c66dbed 100644 --- a/src/Behat/Testwork/EventDispatcher/Tester/EventDispatchingExercise.php +++ b/src/Behat/Testwork/EventDispatcher/Tester/EventDispatchingExercise.php @@ -23,11 +23,14 @@ * Exercise dispatching BEFORE/AFTER events during its execution. * * @author Konstantin Kudryashov + * + * @template TSpec + * @implements Exercise */ final class EventDispatchingExercise implements Exercise { /** - * @var Exercise + * @var Exercise */ private $baseExercise; /** @@ -38,7 +41,7 @@ final class EventDispatchingExercise implements Exercise /** * Initializes exercise. * - * @param Exercise $baseExercise + * @param Exercise $baseExercise * @param EventDispatcherInterface $eventDispatcher */ public function __construct(Exercise $baseExercise, EventDispatcherInterface $eventDispatcher) diff --git a/src/Behat/Testwork/EventDispatcher/Tester/EventDispatchingSuiteTester.php b/src/Behat/Testwork/EventDispatcher/Tester/EventDispatchingSuiteTester.php index acfef275a..d47645977 100644 --- a/src/Behat/Testwork/EventDispatcher/Tester/EventDispatchingSuiteTester.php +++ b/src/Behat/Testwork/EventDispatcher/Tester/EventDispatchingSuiteTester.php @@ -25,11 +25,14 @@ * Suite tester dispatching BEFORE/AFTER events during testing. * * @author Konstantin Kudryashov + * + * @template TSpec + * @implements SuiteTester */ final class EventDispatchingSuiteTester implements SuiteTester { /** - * @var SuiteTester + * @var SuiteTester */ private $baseTester; /** @@ -40,7 +43,7 @@ final class EventDispatchingSuiteTester implements SuiteTester /** * Initializes tester. * - * @param SuiteTester $baseTester + * @param SuiteTester $baseTester * @param EventDispatcherInterface $eventDispatcher */ public function __construct(SuiteTester $baseTester, EventDispatcherInterface $eventDispatcher) @@ -49,9 +52,6 @@ public function __construct(SuiteTester $baseTester, EventDispatcherInterface $e $this->eventDispatcher = $eventDispatcher; } - /** - * {@inheritdoc} - */ public function setUp(Environment $env, SpecificationIterator $iterator, $skip) { $event = new BeforeSuiteTested($env, $iterator); @@ -67,17 +67,11 @@ public function setUp(Environment $env, SpecificationIterator $iterator, $skip) return $setup; } - /** - * {@inheritdoc} - */ public function test(Environment $env, SpecificationIterator $iterator, $skip = false) { return $this->baseTester->test($env, $iterator, $skip); } - /** - * {@inheritdoc} - */ public function tearDown(Environment $env, SpecificationIterator $iterator, $skip, TestResult $result) { $event = new BeforeSuiteTeardown($env, $iterator, $result); diff --git a/src/Behat/Testwork/Hook/Scope/AfterSuiteScope.php b/src/Behat/Testwork/Hook/Scope/AfterSuiteScope.php index 59b07c791..ef2d11e75 100644 --- a/src/Behat/Testwork/Hook/Scope/AfterSuiteScope.php +++ b/src/Behat/Testwork/Hook/Scope/AfterSuiteScope.php @@ -26,7 +26,7 @@ final class AfterSuiteScope implements SuiteScope, AfterTestScope */ private $environment; /** - * @var SpecificationIterator + * @var SpecificationIterator */ private $iterator; /** @@ -38,7 +38,7 @@ final class AfterSuiteScope implements SuiteScope, AfterTestScope * Initializes scope. * * @param Environment $environment - * @param SpecificationIterator $iterator + * @param SpecificationIterator $iterator * @param TestResult $result */ public function __construct(Environment $environment, SpecificationIterator $iterator, TestResult $result) diff --git a/src/Behat/Testwork/Hook/Scope/BeforeSuiteScope.php b/src/Behat/Testwork/Hook/Scope/BeforeSuiteScope.php index 5c982cbe1..506825f2c 100644 --- a/src/Behat/Testwork/Hook/Scope/BeforeSuiteScope.php +++ b/src/Behat/Testwork/Hook/Scope/BeforeSuiteScope.php @@ -25,7 +25,7 @@ final class BeforeSuiteScope implements SuiteScope */ private $environment; /** - * @var SpecificationIterator + * @var SpecificationIterator */ private $iterator; @@ -33,7 +33,7 @@ final class BeforeSuiteScope implements SuiteScope * Initializes scope. * * @param Environment $env - * @param SpecificationIterator $iterator + * @param SpecificationIterator $iterator */ public function __construct(Environment $env, SpecificationIterator $iterator) { @@ -65,9 +65,6 @@ public function getEnvironment() return $this->environment; } - /** - * {@inheritdoc} - */ public function getSpecificationIterator() { return $this->iterator; diff --git a/src/Behat/Testwork/Hook/Scope/SuiteScope.php b/src/Behat/Testwork/Hook/Scope/SuiteScope.php index 659a8f6cd..f77865684 100644 --- a/src/Behat/Testwork/Hook/Scope/SuiteScope.php +++ b/src/Behat/Testwork/Hook/Scope/SuiteScope.php @@ -25,7 +25,7 @@ interface SuiteScope extends HookScope /** * Returns specification iterator. * - * @return SpecificationIterator + * @return SpecificationIterator */ public function getSpecificationIterator(); } diff --git a/src/Behat/Testwork/Hook/Tester/HookableSuiteTester.php b/src/Behat/Testwork/Hook/Tester/HookableSuiteTester.php index 1277e824a..8fc1e60f5 100644 --- a/src/Behat/Testwork/Hook/Tester/HookableSuiteTester.php +++ b/src/Behat/Testwork/Hook/Tester/HookableSuiteTester.php @@ -24,11 +24,14 @@ * Suite tester which dispatches hooks during its execution. * * @author Konstantin Kudryashov + * + * @template TSpec + * @implements SuiteTester */ final class HookableSuiteTester implements SuiteTester { /** - * @var SuiteTester + * @var SuiteTester */ private $baseTester; /** @@ -39,7 +42,7 @@ final class HookableSuiteTester implements SuiteTester /** * Initializes tester. * - * @param SuiteTester $baseTester + * @param SuiteTester $baseTester * @param HookDispatcher $hookDispatcher */ public function __construct(SuiteTester $baseTester, HookDispatcher $hookDispatcher) @@ -48,9 +51,6 @@ public function __construct(SuiteTester $baseTester, HookDispatcher $hookDispatc $this->hookDispatcher = $hookDispatcher; } - /** - * {@inheritdoc} - */ public function setUp(Environment $env, SpecificationIterator $iterator, $skip) { $setup = $this->baseTester->setUp($env, $iterator, $skip); @@ -65,17 +65,11 @@ public function setUp(Environment $env, SpecificationIterator $iterator, $skip) return new HookedSetup($setup, $hookCallResults); } - /** - * {@inheritdoc} - */ public function test(Environment $env, SpecificationIterator $iterator, $skip) { return $this->baseTester->test($env, $iterator, $skip); } - /** - * {@inheritdoc} - */ public function tearDown(Environment $env, SpecificationIterator $iterator, $skip, TestResult $result) { $teardown = $this->baseTester->tearDown($env, $iterator, $skip, $result); diff --git a/src/Behat/Testwork/Ordering/OrderedExercise.php b/src/Behat/Testwork/Ordering/OrderedExercise.php index aba9ba894..4eefe3d99 100644 --- a/src/Behat/Testwork/Ordering/OrderedExercise.php +++ b/src/Behat/Testwork/Ordering/OrderedExercise.php @@ -22,6 +22,9 @@ * Exercise that is ordered according to a specified algorithm * * @author Ciaran McNulty + * + * @template TSpec + * @implements Exercise */ final class OrderedExercise implements Exercise { @@ -31,22 +34,22 @@ final class OrderedExercise implements Exercise private $orderer; /** - * @var SpecificationIterator[] + * @var SpecificationIterator[]|null */ private $unordered; /** - * @var SpecificationIterator[] + * @var SpecificationIterator[]|null */ private $ordered; /** - * @var Exercise + * @var Exercise */ private $decoratedExercise; /** - * @param Exercise $decoratedExercise + * @param Exercise $decoratedExercise */ public function __construct(Exercise $decoratedExercise) { @@ -54,41 +57,16 @@ public function __construct(Exercise $decoratedExercise) $this->decoratedExercise = $decoratedExercise; } - /** - * Sets up exercise for a test. - * - * @param SpecificationIterator[] $iterators - * @param bool $skip - * - * @return Setup - */ public function setUp(array $iterators, $skip) { return $this->decoratedExercise->setUp($this->order($iterators), $skip); } - /** - * Tests suites specifications. - * - * @param SpecificationIterator[] $iterators - * @param bool $skip - * - * @return TestResult - */ public function test(array $iterators, $skip) { return $this->decoratedExercise->test($this->order($iterators), $skip); } - /** - * Tears down exercise after a test. - * - * @param SpecificationIterator[] $iterators - * @param bool $skip - * @param TestResult $result - * - * @return Teardown - */ public function tearDown(array $iterators, $skip, TestResult $result) { return $this->decoratedExercise->tearDown($this->order($iterators), $skip, $result); @@ -105,8 +83,8 @@ public function setOrderer(Orderer $orderer) } /** - * @param SpecificationIterator[] $iterators - * @return SpecificationIterator[] + * @param SpecificationIterator[] $iterators + * @return SpecificationIterator[] */ private function order(array $iterators) { diff --git a/src/Behat/Testwork/Ordering/Orderer/NoopOrderer.php b/src/Behat/Testwork/Ordering/Orderer/NoopOrderer.php index a2257f98f..652c4d972 100644 --- a/src/Behat/Testwork/Ordering/Orderer/NoopOrderer.php +++ b/src/Behat/Testwork/Ordering/Orderer/NoopOrderer.php @@ -10,8 +10,6 @@ namespace Behat\Testwork\Ordering\Orderer; -use Behat\Testwork\Specification\SpecificationIterator; - /** * Null implementation of Orderer that does no ordering * @@ -19,11 +17,6 @@ */ final class NoopOrderer implements Orderer { - - /** - * @param SpecificationIterator[] $scenarioIterators - * @return SpecificationIterator[] - */ public function order(array $scenarioIterators) { return $scenarioIterators; diff --git a/src/Behat/Testwork/Ordering/Orderer/Orderer.php b/src/Behat/Testwork/Ordering/Orderer/Orderer.php index 1f29c528c..b5977bd42 100644 --- a/src/Behat/Testwork/Ordering/Orderer/Orderer.php +++ b/src/Behat/Testwork/Ordering/Orderer/Orderer.php @@ -20,8 +20,10 @@ interface Orderer { /** - * @param SpecificationIterator[] $scenarioIterators - * @return SpecificationIterator[] + * @template T + * + * @param SpecificationIterator[] $scenarioIterators + * @return SpecificationIterator[] */ public function order(array $scenarioIterators); diff --git a/src/Behat/Testwork/Ordering/Orderer/RandomOrderer.php b/src/Behat/Testwork/Ordering/Orderer/RandomOrderer.php index 8dc9c9e0e..252b38631 100644 --- a/src/Behat/Testwork/Ordering/Orderer/RandomOrderer.php +++ b/src/Behat/Testwork/Ordering/Orderer/RandomOrderer.php @@ -20,10 +20,6 @@ */ final class RandomOrderer implements Orderer { - /** - * @param SpecificationIterator[] $scenarioIterators - * @return SpecificationIterator[] - */ public function order(array $scenarioIterators) { $orderedFeatures = $this->orderFeatures($scenarioIterators); @@ -33,8 +29,9 @@ public function order(array $scenarioIterators) } /** - * @param array $scenarioIterators - * @return array + * @template T + * @param SpecificationIterator[] $scenarioIterators + * @return SpecificationIterator[] */ private function orderFeatures(array $scenarioIterators) { diff --git a/src/Behat/Testwork/Ordering/Orderer/ReverseOrderer.php b/src/Behat/Testwork/Ordering/Orderer/ReverseOrderer.php index 9a23a4dc7..4ce26d4a8 100644 --- a/src/Behat/Testwork/Ordering/Orderer/ReverseOrderer.php +++ b/src/Behat/Testwork/Ordering/Orderer/ReverseOrderer.php @@ -20,10 +20,6 @@ */ final class ReverseOrderer implements Orderer { - /** - * @param SpecificationIterator[] $scenarioIterators - * @return SpecificationIterator[] - */ public function order(array $scenarioIterators) { $orderedFeatures = $this->orderFeatures($scenarioIterators); @@ -33,8 +29,9 @@ public function order(array $scenarioIterators) } /** - * @param array $scenarioIterators - * @return array + * @template T + * @param SpecificationIterator[] $scenarioIterators + * @return SpecificationIterator[] */ private function orderFeatures(array $scenarioIterators) { @@ -52,8 +49,9 @@ private function orderFeatures(array $scenarioIterators) } /** - * @param $orderedSuites - * @return array + * @template T + * @param SpecificationIterator[] $orderedSuites + * @return SpecificationIterator[] */ private function orderSuites($orderedSuites) { diff --git a/src/Behat/Testwork/Specification/GroupedSpecificationIterator.php b/src/Behat/Testwork/Specification/GroupedSpecificationIterator.php index 8975040fc..8f740ccf8 100644 --- a/src/Behat/Testwork/Specification/GroupedSpecificationIterator.php +++ b/src/Behat/Testwork/Specification/GroupedSpecificationIterator.php @@ -16,6 +16,9 @@ * Iterates over specification iterators grouped by their suite. * * @author Konstantin Kudryashov + * + * @template T + * @implements SpecificationIterator */ final class GroupedSpecificationIterator implements SpecificationIterator { @@ -35,8 +38,8 @@ final class GroupedSpecificationIterator implements SpecificationIterator /** * Initializes iterator. * - * @param Suite $suite - * @param SpecificationIterator[] $specificationIterators + * @param Suite $suite + * @param list> $specificationIterators */ public function __construct(Suite $suite, array $specificationIterators) { @@ -47,9 +50,11 @@ public function __construct(Suite $suite, array $specificationIterators) /** * Groups specifications by their suite. * - * @param SpecificationIterator[] $specificationIterators + * @template TSpec + * + * @param SpecificationIterator[] $specificationIterators * - * @return GroupedSpecificationIterator[] + * @return array> */ public static function group(array $specificationIterators) { diff --git a/src/Behat/Testwork/Specification/Locator/SpecificationLocator.php b/src/Behat/Testwork/Specification/Locator/SpecificationLocator.php index 372fbea32..f91679c67 100644 --- a/src/Behat/Testwork/Specification/Locator/SpecificationLocator.php +++ b/src/Behat/Testwork/Specification/Locator/SpecificationLocator.php @@ -20,6 +20,8 @@ * @see SpecificationFinder * * @author Konstantin Kudryashov + * + * @template-covariant T */ interface SpecificationLocator { @@ -36,7 +38,7 @@ public function getLocatorExamples(); * @param Suite $suite * @param string $locator * - * @return SpecificationIterator + * @return SpecificationIterator */ public function locateSpecifications(Suite $suite, $locator); } diff --git a/src/Behat/Testwork/Specification/NoSpecificationsIterator.php b/src/Behat/Testwork/Specification/NoSpecificationsIterator.php index 95cfc6a3a..d0cdf93d1 100644 --- a/src/Behat/Testwork/Specification/NoSpecificationsIterator.php +++ b/src/Behat/Testwork/Specification/NoSpecificationsIterator.php @@ -19,6 +19,8 @@ * Return an instance of this class from locator if no specifications are found. * * @author Konstantin Kudryashov + * + * @implements SpecificationIterator */ final class NoSpecificationsIterator extends EmptyIterator implements SpecificationIterator { diff --git a/src/Behat/Testwork/Specification/SpecificationArrayIterator.php b/src/Behat/Testwork/Specification/SpecificationArrayIterator.php index c59f16cd7..99ded8bc1 100644 --- a/src/Behat/Testwork/Specification/SpecificationArrayIterator.php +++ b/src/Behat/Testwork/Specification/SpecificationArrayIterator.php @@ -19,7 +19,9 @@ * Return instance of this class from locator if specifications cannot be searched lazily. * * @author Christophe Coevoet - * @extends ArrayIterator + * @template T + * @implements SpecificationIterator + * @extends ArrayIterator */ final class SpecificationArrayIterator extends ArrayIterator implements SpecificationIterator { @@ -31,8 +33,8 @@ final class SpecificationArrayIterator extends ArrayIterator implements Specific /** * Initializes iterator. * - * @param Suite $suite - * @param mixed[] $specifications + * @param Suite $suite + * @param array $specifications */ public function __construct(Suite $suite, $specifications = array()) { diff --git a/src/Behat/Testwork/Specification/SpecificationFinder.php b/src/Behat/Testwork/Specification/SpecificationFinder.php index 5204bd503..f34e132c5 100644 --- a/src/Behat/Testwork/Specification/SpecificationFinder.php +++ b/src/Behat/Testwork/Specification/SpecificationFinder.php @@ -17,18 +17,20 @@ * Finds test specifications for provided suites using registered locators. * * @author Konstantin Kudryashov + * + * @template T */ final class SpecificationFinder { /** - * @var SpecificationLocator[] + * @var SpecificationLocator[] */ private $specificationLocators = array(); /** * Registers specification locator. * - * @param SpecificationLocator $locator + * @param SpecificationLocator $locator */ public function registerSpecificationLocator(SpecificationLocator $locator) { @@ -56,7 +58,7 @@ public function getExampleLocators() * @param Suite[] $suites * @param null|string $locator * - * @return SpecificationIterator[] + * @return list> */ public function findSuitesSpecifications(array $suites, $locator = null) { @@ -74,7 +76,7 @@ public function findSuitesSpecifications(array $suites, $locator = null) * @param Suite $suite * @param null|string $locator * - * @return SpecificationIterator[] + * @return list> */ private function findSuiteSpecifications(Suite $suite, $locator = null) { diff --git a/src/Behat/Testwork/Specification/SpecificationIterator.php b/src/Behat/Testwork/Specification/SpecificationIterator.php index 81544bc97..84f751f15 100644 --- a/src/Behat/Testwork/Specification/SpecificationIterator.php +++ b/src/Behat/Testwork/Specification/SpecificationIterator.php @@ -18,7 +18,8 @@ * * @author Konstantin Kudryashov * - * @extends Iterator + * @template-covariant T + * @extends Iterator */ interface SpecificationIterator extends Iterator { diff --git a/src/Behat/Testwork/Tester/Exercise.php b/src/Behat/Testwork/Tester/Exercise.php index e63883d8c..1e0a704e2 100644 --- a/src/Behat/Testwork/Tester/Exercise.php +++ b/src/Behat/Testwork/Tester/Exercise.php @@ -19,13 +19,15 @@ * Prepares and tests provided exercise specifications. * * @author Konstantin Kudryashov + * + * @template TSpec */ interface Exercise { /** * Sets up exercise for a test. * - * @param SpecificationIterator[] $iterators + * @param SpecificationIterator[] $iterators * @param bool $skip * * @return Setup @@ -35,7 +37,7 @@ public function setUp(array $iterators, $skip); /** * Tests suites specifications. * - * @param SpecificationIterator[] $iterators + * @param SpecificationIterator[] $iterators * @param bool $skip * * @return TestResult @@ -45,7 +47,7 @@ public function test(array $iterators, $skip); /** * Tears down exercise after a test. * - * @param SpecificationIterator[] $iterators + * @param SpecificationIterator[] $iterators * @param bool $skip * @param TestResult $result * diff --git a/src/Behat/Testwork/Tester/Runtime/RuntimeExercise.php b/src/Behat/Testwork/Tester/Runtime/RuntimeExercise.php index 2f831dd74..e9c405f9a 100644 --- a/src/Behat/Testwork/Tester/Runtime/RuntimeExercise.php +++ b/src/Behat/Testwork/Tester/Runtime/RuntimeExercise.php @@ -25,6 +25,9 @@ * Tester executing exercises in the runtime. * * @author Konstantin Kudryashov + * + * @template TSpec + * @implements Exercise */ final class RuntimeExercise implements Exercise { @@ -33,7 +36,7 @@ final class RuntimeExercise implements Exercise */ private $envManager; /** - * @var SuiteTester + * @var SuiteTester */ private $suiteTester; @@ -41,7 +44,7 @@ final class RuntimeExercise implements Exercise * Initializes tester. * * @param EnvironmentManager $envManager - * @param SuiteTester $suiteTester + * @param SuiteTester $suiteTester */ public function __construct(EnvironmentManager $envManager, SuiteTester $suiteTester) { diff --git a/src/Behat/Testwork/Tester/Runtime/RuntimeSuiteTester.php b/src/Behat/Testwork/Tester/Runtime/RuntimeSuiteTester.php index b67838d28..5e597d383 100644 --- a/src/Behat/Testwork/Tester/Runtime/RuntimeSuiteTester.php +++ b/src/Behat/Testwork/Tester/Runtime/RuntimeSuiteTester.php @@ -25,35 +25,32 @@ * Tester executing suite tests in the runtime. * * @author Konstantin Kudryashov + * + * @template TSpec + * @implements SuiteTester */ final class RuntimeSuiteTester implements SuiteTester { /** - * @var SpecificationTester + * @var SpecificationTester */ private $specTester; /** * Initializes tester. * - * @param SpecificationTester $specTester + * @param SpecificationTester $specTester */ public function __construct(SpecificationTester $specTester) { $this->specTester = $specTester; } - /** - * {@inheritdoc} - */ public function setUp(Environment $env, SpecificationIterator $iterator, $skip) { return new SuccessfulSetup(); } - /** - * {@inheritdoc} - */ public function test(Environment $env, SpecificationIterator $iterator, $skip = false) { $results = array(); @@ -70,9 +67,6 @@ public function test(Environment $env, SpecificationIterator $iterator, $skip = return new TestResults($results); } - /** - * {@inheritdoc} - */ public function tearDown(Environment $env, SpecificationIterator $iterator, $skip, TestResult $result) { return new SuccessfulTeardown(); diff --git a/src/Behat/Testwork/Tester/SpecificationTester.php b/src/Behat/Testwork/Tester/SpecificationTester.php index b6e06ff41..d582f1b01 100644 --- a/src/Behat/Testwork/Tester/SpecificationTester.php +++ b/src/Behat/Testwork/Tester/SpecificationTester.php @@ -19,6 +19,8 @@ * Prepares and tests provided specification against provided environment. * * @author Konstantin Kudryashov + * + * @template TSpec */ interface SpecificationTester { @@ -26,7 +28,7 @@ interface SpecificationTester * Sets up specification for a test. * * @param Environment $env - * @param mixed $spec + * @param TSpec $spec * @param bool $skip * * @return Setup @@ -37,7 +39,7 @@ public function setUp(Environment $env, $spec, $skip); * Tests provided specification. * * @param Environment $env - * @param mixed $spec + * @param TSpec $spec * @param bool $skip * * @return TestResult @@ -48,7 +50,7 @@ public function test(Environment $env, $spec, $skip); * Tears down specification after a test. * * @param Environment $env - * @param mixed $spec + * @param TSpec $spec * @param bool $skip * @param TestResult $result * diff --git a/src/Behat/Testwork/Tester/SuiteTester.php b/src/Behat/Testwork/Tester/SuiteTester.php index 61dffad7f..a35e3729d 100644 --- a/src/Behat/Testwork/Tester/SuiteTester.php +++ b/src/Behat/Testwork/Tester/SuiteTester.php @@ -20,6 +20,8 @@ * Prepares and tests provided suite specifications against provided environment. * * @author Konstantin Kudryashov + * + * @template TSpec */ interface SuiteTester { @@ -27,7 +29,7 @@ interface SuiteTester * Sets up suite for a test. * * @param Environment $env - * @param SpecificationIterator $iterator + * @param SpecificationIterator $iterator * @param bool $skip * * @return Setup @@ -38,7 +40,7 @@ public function setUp(Environment $env, SpecificationIterator $iterator, $skip); * Tests provided suite specifications. * * @param Environment $env - * @param SpecificationIterator $iterator + * @param SpecificationIterator $iterator * @param bool $skip * * @return TestResult @@ -49,7 +51,7 @@ public function test(Environment $env, SpecificationIterator $iterator, $skip); * Tears down suite after a test. * * @param Environment $env - * @param SpecificationIterator $iterator + * @param SpecificationIterator $iterator * @param bool $skip * @param TestResult $result * From ce3c014bdcbdde21992b0c33d86963abfcedd676 Mon Sep 17 00:00:00 2001 From: Carlos Granados Date: Thu, 19 Dec 2024 08:59:39 +0100 Subject: [PATCH 522/567] chore: update code to PHPStan level 2 --- .gitignore | 1 + phpstan.dist.neon | 2 +- .../Context/Cli/ContextSnippetsController.php | 1 + .../Attribute/DefinitionAttributeReader.php | 2 +- .../Pattern/Policy/RegexPatternPolicy.php | 2 +- .../Cli/StopOnFailureController.php | 8 ++--- .../Behat/Gherkin/Cli/FilterController.php | 8 ++--- .../ServiceContainer/GherkinExtension.php | 35 ++++++++++--------- .../BuiltInServiceContainer.php | 7 +--- .../Context/Attribute/HookAttributeReader.php | 2 +- .../AST/ScenarioNodeListener.php | 6 ++-- .../Statistics/HookStatsListener.php | 2 ++ .../Statistics/StepStatsListener.php | 5 ++- .../Node/Printer/JUnit/JUnitSetupPrinter.php | 19 +++++----- .../Formatter/PrettyFormatterFactory.php | 1 - .../Behat/Snippet/Cli/SnippetsController.php | 8 ++--- src/Behat/Behat/Snippet/SnippetRegistry.php | 2 +- .../Behat/Tester/Cli/RerunController.php | 10 ++---- .../ServiceContainer/TesterExtension.php | 2 -- .../Cli/GherkinTranslationsController.php | 1 + src/Behat/Hook/AfterFeature.php | 7 +++- src/Behat/Hook/AfterScenario.php | 7 +++- src/Behat/Hook/AfterStep.php | 7 +++- src/Behat/Hook/AfterSuite.php | 7 +++- src/Behat/Hook/BeforeFeature.php | 7 +++- src/Behat/Hook/BeforeScenario.php | 7 +++- src/Behat/Hook/BeforeStep.php | 7 +++- src/Behat/Hook/BeforeSuite.php | 7 +++- src/Behat/Hook/Hook.php | 1 + src/Behat/Step/Definition.php | 1 + src/Behat/Step/Given.php | 7 +++- src/Behat/Step/Then.php | 7 +++- src/Behat/Step/When.php | 7 +++- .../Autoloader/Cli/AutoloaderController.php | 1 + .../Call/ServiceContainer/CallExtension.php | 2 -- .../EventDispatcher/Cli/SigintController.php | 1 + .../Exception/Cli/VerbosityController.php | 8 ++--- .../ServiceContainer/ExceptionExtension.php | 2 -- .../Testwork/Output/Cli/OutputController.php | 1 + .../ServiceContainer/OutputExtension.php | 1 - .../Testwork/Suite/Cli/SuiteController.php | 1 + .../Suite/ServiceContainer/SuiteExtension.php | 13 +++---- .../Testwork/Tester/Cli/StrictController.php | 1 + .../ServiceContainer/TesterExtension.php | 16 +++++---- .../Translator/Cli/LanguageController.php | 1 + .../ServiceContainer/TranslatorExtension.php | 10 +++--- 46 files changed, 152 insertions(+), 109 deletions(-) diff --git a/.gitignore b/.gitignore index 97d5112f8..91507e81e 100644 --- a/.gitignore +++ b/.gitignore @@ -5,3 +5,4 @@ behat.yml vendor composer.lock .phpunit.result.cache +phpstan.neon diff --git a/phpstan.dist.neon b/phpstan.dist.neon index fce48e6f0..41112f5ec 100644 --- a/phpstan.dist.neon +++ b/phpstan.dist.neon @@ -1,5 +1,5 @@ parameters: - level: 1 + level: 2 paths: - src excludePaths: diff --git a/src/Behat/Behat/Context/Cli/ContextSnippetsController.php b/src/Behat/Behat/Context/Cli/ContextSnippetsController.php index 3bfbc40bd..5d6708088 100644 --- a/src/Behat/Behat/Context/Cli/ContextSnippetsController.php +++ b/src/Behat/Behat/Context/Cli/ContextSnippetsController.php @@ -87,5 +87,6 @@ public function execute(InputInterface $input, OutputInterface $output) new FixedPatternIdentifier($input->getOption('snippets-type')) )) ); + return null; } } diff --git a/src/Behat/Behat/Definition/Context/Attribute/DefinitionAttributeReader.php b/src/Behat/Behat/Definition/Context/Attribute/DefinitionAttributeReader.php index cd9ea3603..9cd22a8e7 100644 --- a/src/Behat/Behat/Definition/Context/Attribute/DefinitionAttributeReader.php +++ b/src/Behat/Behat/Definition/Context/Attribute/DefinitionAttributeReader.php @@ -63,7 +63,7 @@ public function readCallees(string $contextClass, ReflectionMethod $method) $description = $this->docBlockHelper->extractDescription($docBlock); } - $callees[] = new $class($attribute->newInstance()->pattern, $callable, $description); + $callees[] = new $class($attribute->newInstance()->getPattern(), $callable, $description); } return $callees; diff --git a/src/Behat/Behat/Definition/Pattern/Policy/RegexPatternPolicy.php b/src/Behat/Behat/Definition/Pattern/Policy/RegexPatternPolicy.php index fe3f41fbd..e6deb2b76 100644 --- a/src/Behat/Behat/Definition/Pattern/Policy/RegexPatternPolicy.php +++ b/src/Behat/Behat/Definition/Pattern/Policy/RegexPatternPolicy.php @@ -22,7 +22,7 @@ final class RegexPatternPolicy implements PatternPolicy { /** - * @var string[string] + * @var array */ private static $replacePatterns = array( "/(?<=\W|^)\\\'(?:((?!\\').)*)\\\'(?=\W|$)/" => "'([^']*)'", // Single quoted strings diff --git a/src/Behat/Behat/EventDispatcher/Cli/StopOnFailureController.php b/src/Behat/Behat/EventDispatcher/Cli/StopOnFailureController.php index 3191d061f..7dc443d98 100644 --- a/src/Behat/Behat/EventDispatcher/Cli/StopOnFailureController.php +++ b/src/Behat/Behat/EventDispatcher/Cli/StopOnFailureController.php @@ -81,12 +81,7 @@ public function configure(Command $command) } /** - * Executes controller. - * - * @param InputInterface $input - * @param OutputInterface $output - * - * @return null|integer + * {@inheritdoc} */ public function execute(InputInterface $input, OutputInterface $output) { @@ -95,6 +90,7 @@ public function execute(InputInterface $input, OutputInterface $output) } $this->stopOnFailureHandler->registerListeners(); + return null; } } diff --git a/src/Behat/Behat/Gherkin/Cli/FilterController.php b/src/Behat/Behat/Gherkin/Cli/FilterController.php index 9647bc3d4..a40e87b04 100644 --- a/src/Behat/Behat/Gherkin/Cli/FilterController.php +++ b/src/Behat/Behat/Gherkin/Cli/FilterController.php @@ -75,12 +75,7 @@ public function configure(Command $command) } /** - * Executes controller. - * - * @param InputInterface $input - * @param OutputInterface $output - * - * @return null|integer + * {@inheritdoc} */ public function execute(InputInterface $input, OutputInterface $output) { @@ -105,5 +100,6 @@ public function execute(InputInterface $input, OutputInterface $output) if (count($filters)) { $this->gherkin->setFilters($filters); } + return null; } } diff --git a/src/Behat/Behat/Gherkin/ServiceContainer/GherkinExtension.php b/src/Behat/Behat/Gherkin/ServiceContainer/GherkinExtension.php index a96a70447..3699248f0 100644 --- a/src/Behat/Behat/Gherkin/ServiceContainer/GherkinExtension.php +++ b/src/Behat/Behat/Gherkin/ServiceContainer/GherkinExtension.php @@ -79,25 +79,26 @@ public function initialize(ExtensionManager $extensionManager) */ public function configure(ArrayNodeDefinition $builder) { - $builder + $childrenBuilder = $builder ->addDefaultsIfNotSet() ->children() - ->scalarNode('cache') - ->info('Sets the gherkin parser cache folder') - ->defaultValue( - is_writable(sys_get_temp_dir()) - ? sys_get_temp_dir() . DIRECTORY_SEPARATOR . 'behat_gherkin_cache' - : null - ) - ->end() - ->arrayNode('filters') - ->info('Sets the gherkin filters (overridable by CLI options)') - ->performNoDeepMerging() - ->defaultValue(array()) - ->useAttributeAsKey('name') - ->prototype('scalar')->end() - ->end() - ->end() + ; + $childrenBuilder + ->scalarNode('cache') + ->info('Sets the gherkin parser cache folder') + ->defaultValue( + is_writable(sys_get_temp_dir()) + ? sys_get_temp_dir() . DIRECTORY_SEPARATOR . 'behat_gherkin_cache' + : null + ) + ; + $childrenBuilder + ->arrayNode('filters') + ->info('Sets the gherkin filters (overridable by CLI options)') + ->performNoDeepMerging() + ->defaultValue(array()) + ->useAttributeAsKey('name') + ->prototype('scalar')->end() ; } diff --git a/src/Behat/Behat/HelperContainer/BuiltInServiceContainer.php b/src/Behat/Behat/HelperContainer/BuiltInServiceContainer.php index 85d302fb9..e6e5b5a86 100644 --- a/src/Behat/Behat/HelperContainer/BuiltInServiceContainer.php +++ b/src/Behat/Behat/HelperContainer/BuiltInServiceContainer.php @@ -115,13 +115,8 @@ private function getAndValidateServiceSchema($id) /** * Gets and validates a class from schema. - * - * @param string $id - * @param string|array $schema - * - * @return string */ - private function getAndValidateClass($id, array $schema) + private function getAndValidateClass(string $id, array $schema): string { if (!isset($schema['class'])) { $schema['class'] = $id; diff --git a/src/Behat/Behat/Hook/Context/Attribute/HookAttributeReader.php b/src/Behat/Behat/Hook/Context/Attribute/HookAttributeReader.php index ed1fd428b..b153a4442 100644 --- a/src/Behat/Behat/Hook/Context/Attribute/HookAttributeReader.php +++ b/src/Behat/Behat/Hook/Context/Attribute/HookAttributeReader.php @@ -70,7 +70,7 @@ public function readCallees(string $contextClass, ReflectionMethod $method) $description = $this->docBlockHelper->extractDescription($docBlock); } - $callees[] = new $class($attribute->newInstance()->filterString, $callable, $description); + $callees[] = new $class($attribute->newInstance()->getFilterString(), $callable, $description); } return $callees; diff --git a/src/Behat/Behat/Output/Node/EventListener/AST/ScenarioNodeListener.php b/src/Behat/Behat/Output/Node/EventListener/AST/ScenarioNodeListener.php index d5a58d426..b0f1a142f 100644 --- a/src/Behat/Behat/Output/Node/EventListener/AST/ScenarioNodeListener.php +++ b/src/Behat/Behat/Output/Node/EventListener/AST/ScenarioNodeListener.php @@ -83,9 +83,9 @@ public function listenEvent(Formatter $formatter, Event $event, $eventName) * @param ScenarioLikeTested|AfterSetup $event * @param string $eventName */ - private function printHeaderOnBeforeEvent(Formatter $formatter, ScenarioLikeTested $event, $eventName) + private function printHeaderOnBeforeEvent(Formatter $formatter, ScenarioLikeTested|AfterSetup $event, $eventName) { - if ($this->beforeEventName !== $eventName || !$event instanceof AfterSetup) { + if ($this->beforeEventName !== $eventName || !$event instanceof AfterSetup || !$event instanceof ScenarioLikeTested) { return; } @@ -103,7 +103,7 @@ private function printHeaderOnBeforeEvent(Formatter $formatter, ScenarioLikeTest * @param ScenarioLikeTested|AfterTested $event * @param string $eventName */ - private function printFooterOnAfterEvent(Formatter $formatter, ScenarioLikeTested $event, $eventName) + private function printFooterOnAfterEvent(Formatter $formatter, ScenarioLikeTested|AfterTested $event, $eventName) { if ($this->afterEventName !== $eventName || !$event instanceof AfterTested) { return; diff --git a/src/Behat/Behat/Output/Node/EventListener/Statistics/HookStatsListener.php b/src/Behat/Behat/Output/Node/EventListener/Statistics/HookStatsListener.php index 0c0a1e20f..870b08116 100644 --- a/src/Behat/Behat/Output/Node/EventListener/Statistics/HookStatsListener.php +++ b/src/Behat/Behat/Output/Node/EventListener/Statistics/HookStatsListener.php @@ -17,6 +17,7 @@ use Behat\Testwork\EventDispatcher\Event\AfterSetup; use Behat\Testwork\EventDispatcher\Event\AfterTested; use Behat\Testwork\Exception\ExceptionPresenter; +use Behat\Testwork\Hook\Call\HookCall; use Behat\Testwork\Hook\Call\RuntimeHook; use Behat\Testwork\Hook\Tester\Setup\HookedSetup; use Behat\Testwork\Hook\Tester\Setup\HookedTeardown; @@ -111,6 +112,7 @@ private function captureAfterHookStats(HookedTeardown $teardown) private function captureHookStat(CallResult $hookCallResult) { $call = $hookCallResult->getCall(); + assert($call instanceof HookCall); $callee = $call->getCallee(); $scope = $call->getScope(); $path = $callee->getPath(); diff --git a/src/Behat/Behat/Output/Node/EventListener/Statistics/StepStatsListener.php b/src/Behat/Behat/Output/Node/EventListener/Statistics/StepStatsListener.php index a4a32b2f9..c7ab312b4 100644 --- a/src/Behat/Behat/Output/Node/EventListener/Statistics/StepStatsListener.php +++ b/src/Behat/Behat/Output/Node/EventListener/Statistics/StepStatsListener.php @@ -18,6 +18,7 @@ use Behat\Behat\Output\Statistics\StepStatV2; use Behat\Behat\Output\Statistics\Statistics; use Behat\Behat\Tester\Exception\PendingException; +use Behat\Behat\Tester\Result\DefinedStepResult; use Behat\Behat\Tester\Result\ExecutedStepResult; use Behat\Behat\Tester\Result\StepResult; use Behat\Testwork\Event\Event; @@ -186,7 +187,9 @@ private function getStepPath(AfterStepTested $event, ?Exception $exception = nul $path = sprintf('%s:%d', $this->currentFeaturePath, $event->getStep()->getLine()); if ($exception && $exception instanceof PendingException) { - $path = $event->getTestResult()->getStepDefinition()->getPath(); + $testResult = $event->getTestResult(); + assert($testResult instanceof DefinedStepResult); + $path = $testResult->getStepDefinition()->getPath(); } return $path; diff --git a/src/Behat/Behat/Output/Node/Printer/JUnit/JUnitSetupPrinter.php b/src/Behat/Behat/Output/Node/Printer/JUnit/JUnitSetupPrinter.php index 31fcc40d3..0da8c7138 100644 --- a/src/Behat/Behat/Output/Node/Printer/JUnit/JUnitSetupPrinter.php +++ b/src/Behat/Behat/Output/Node/Printer/JUnit/JUnitSetupPrinter.php @@ -7,10 +7,12 @@ use Behat\Testwork\Call\CallResults; use Behat\Testwork\Exception\ExceptionPresenter; use Behat\Testwork\Hook\Call\HookCall; +use Behat\Testwork\Hook\Hook; use Behat\Testwork\Hook\Tester\Setup\HookedSetup; use Behat\Testwork\Hook\Tester\Setup\HookedTeardown; use Behat\Testwork\Output\Formatter; use Behat\Testwork\Output\Printer\JUnitOutputPrinter; +use Behat\Testwork\Output\Printer\OutputPrinter; use Behat\Testwork\Tester\Setup\Setup; use Behat\Testwork\Tester\Setup\Teardown; @@ -52,23 +54,20 @@ public function printTeardown(Formatter $formatter, Teardown $teardown) } } - /** - * @param Formatter $formatter - * @param CallResults $results - * @param string $messageType - */ - private function handleHookCalls(Formatter $formatter, CallResults $results, $messageType) + private function handleHookCalls(Formatter $formatter, CallResults $results, string $messageType): void { - /** @var CallResult $hookCallResult */ foreach ($results as $hookCallResult) { + assert($hookCallResult instanceof CallResult); if ($hookCallResult->hasException()) { - /** @var HookCall $call */ $call = $hookCallResult->getCall(); + assert($call instanceof HookCall); $scope = $call->getScope(); - /** @var JUnitOutputPrinter $outputPrinter */ $outputPrinter = $formatter->getOutputPrinter(); + assert($outputPrinter instanceof JUnitOutputPrinter); - $message = $call->getCallee()->getName(); + $callee = $call->getCallee(); + assert($callee instanceof Hook); + $message = $callee->getName(); if ($scope instanceof StepScope) { $message .= ': ' . $scope->getStep()->getKeyword() . ' ' . $scope->getStep()->getText(); } diff --git a/src/Behat/Behat/Output/ServiceContainer/Formatter/PrettyFormatterFactory.php b/src/Behat/Behat/Output/ServiceContainer/Formatter/PrettyFormatterFactory.php index eb574f844..96fcd5995 100644 --- a/src/Behat/Behat/Output/ServiceContainer/Formatter/PrettyFormatterFactory.php +++ b/src/Behat/Behat/Output/ServiceContainer/Formatter/PrettyFormatterFactory.php @@ -447,7 +447,6 @@ protected function proxySiblingEvents($beforeEventName, $afterEventName, array $ * * @param string $name * @param mixed $value - * @param mixed $listener * * @return Definition */ diff --git a/src/Behat/Behat/Snippet/Cli/SnippetsController.php b/src/Behat/Behat/Snippet/Cli/SnippetsController.php index 58d480877..5f87fb58d 100644 --- a/src/Behat/Behat/Snippet/Cli/SnippetsController.php +++ b/src/Behat/Behat/Snippet/Cli/SnippetsController.php @@ -91,12 +91,7 @@ public function configure(Command $command) } /** - * Executes controller. - * - * @param InputInterface $input - * @param OutputInterface $output - * - * @return null|integer + * {@inheritdoc} */ public function execute(InputInterface $input, OutputInterface $output) { @@ -114,6 +109,7 @@ public function execute(InputInterface $input, OutputInterface $output) if (!$input->getOption('no-snippets')) { $this->eventDispatcher->addListener(ExerciseCompleted::AFTER, array($this, 'printUndefinedSteps'), -995); } + return null; } /** diff --git a/src/Behat/Behat/Snippet/SnippetRegistry.php b/src/Behat/Behat/Snippet/SnippetRegistry.php index 7b9257263..eaa62076b 100644 --- a/src/Behat/Behat/Snippet/SnippetRegistry.php +++ b/src/Behat/Behat/Snippet/SnippetRegistry.php @@ -55,7 +55,7 @@ public function registerSnippetGenerator(SnippetGenerator $generator) * @param Environment $environment * @param StepNode $step * - * @return null|Snippet + * @return void */ public function registerUndefinedStep(Environment $environment, StepNode $step) { diff --git a/src/Behat/Behat/Tester/Cli/RerunController.php b/src/Behat/Behat/Tester/Cli/RerunController.php index b798968c6..a6d7982da 100644 --- a/src/Behat/Behat/Tester/Cli/RerunController.php +++ b/src/Behat/Behat/Tester/Cli/RerunController.php @@ -75,12 +75,7 @@ public function configure(Command $command) } /** - * Executes controller. - * - * @param InputInterface $input - * @param OutputInterface $output - * - * @return null|integer + * {@inheritdoc} */ public function execute(InputInterface $input, OutputInterface $output) { @@ -91,7 +86,7 @@ public function execute(InputInterface $input, OutputInterface $output) $this->key = $this->generateKey($input); if (!$input->getOption('rerun') && !$input->getOption('rerun-only')) { - return; + return null; } if (!$this->getFileName() || !file_exists($this->getFileName())) { @@ -104,6 +99,7 @@ public function execute(InputInterface $input, OutputInterface $output) } $input->setArgument('paths', $this->getFileName()); + return null; } /** diff --git a/src/Behat/Behat/Tester/ServiceContainer/TesterExtension.php b/src/Behat/Behat/Tester/ServiceContainer/TesterExtension.php index e0138472d..0dd89db1f 100644 --- a/src/Behat/Behat/Tester/ServiceContainer/TesterExtension.php +++ b/src/Behat/Behat/Tester/ServiceContainer/TesterExtension.php @@ -81,8 +81,6 @@ public function configure(ArrayNodeDefinition $builder) ? sys_get_temp_dir() . DIRECTORY_SEPARATOR . 'behat_rerun_cache' : null ) - ->end() - ->end() ; } diff --git a/src/Behat/Behat/Translator/Cli/GherkinTranslationsController.php b/src/Behat/Behat/Translator/Cli/GherkinTranslationsController.php index 439ad0968..876889664 100644 --- a/src/Behat/Behat/Translator/Cli/GherkinTranslationsController.php +++ b/src/Behat/Behat/Translator/Cli/GherkinTranslationsController.php @@ -55,5 +55,6 @@ public function execute(InputInterface $input, OutputInterface $output) foreach (require($i18nPath) as $lang => $messages) { $this->translator->addResource('array', $messages, $lang, 'output'); } + return null; } } diff --git a/src/Behat/Hook/AfterFeature.php b/src/Behat/Hook/AfterFeature.php index 05c818009..258de3c18 100644 --- a/src/Behat/Hook/AfterFeature.php +++ b/src/Behat/Hook/AfterFeature.php @@ -17,7 +17,7 @@ final class AfterFeature implements Hook { /** - * @var string + * @var string|null */ public $filterString; @@ -25,4 +25,9 @@ public function __construct($filterString = null) { $this->filterString = $filterString; } + + public function getFilterString(): ?string + { + return $this->filterString; + } } diff --git a/src/Behat/Hook/AfterScenario.php b/src/Behat/Hook/AfterScenario.php index feb480cc1..1882d8a11 100644 --- a/src/Behat/Hook/AfterScenario.php +++ b/src/Behat/Hook/AfterScenario.php @@ -17,7 +17,7 @@ final class AfterScenario implements Hook { /** - * @var string + * @var string|null */ public $filterString; @@ -25,4 +25,9 @@ public function __construct($filterString = null) { $this->filterString = $filterString; } + + public function getFilterString(): ?string + { + return $this->filterString; + } } diff --git a/src/Behat/Hook/AfterStep.php b/src/Behat/Hook/AfterStep.php index 8a27ff646..c1cb562e8 100644 --- a/src/Behat/Hook/AfterStep.php +++ b/src/Behat/Hook/AfterStep.php @@ -17,7 +17,7 @@ final class AfterStep implements Hook { /** - * @var string + * @var string|null */ public $filterString; @@ -25,4 +25,9 @@ public function __construct($filterString = null) { $this->filterString = $filterString; } + + public function getFilterString(): ?string + { + return $this->filterString; + } } diff --git a/src/Behat/Hook/AfterSuite.php b/src/Behat/Hook/AfterSuite.php index 66cc4cb5e..a5938c198 100644 --- a/src/Behat/Hook/AfterSuite.php +++ b/src/Behat/Hook/AfterSuite.php @@ -17,7 +17,7 @@ final class AfterSuite implements Hook { /** - * @var string + * @var string|null */ public $filterString; @@ -25,4 +25,9 @@ public function __construct($filterString = null) { $this->filterString = $filterString; } + + public function getFilterString(): ?string + { + return $this->filterString; + } } diff --git a/src/Behat/Hook/BeforeFeature.php b/src/Behat/Hook/BeforeFeature.php index 401ae2e75..09f035dbb 100644 --- a/src/Behat/Hook/BeforeFeature.php +++ b/src/Behat/Hook/BeforeFeature.php @@ -17,7 +17,7 @@ final class BeforeFeature implements Hook { /** - * @var string + * @var string|null */ public $filterString; @@ -25,4 +25,9 @@ public function __construct($filterString = null) { $this->filterString = $filterString; } + + public function getFilterString(): ?string + { + return $this->filterString; + } } diff --git a/src/Behat/Hook/BeforeScenario.php b/src/Behat/Hook/BeforeScenario.php index d1d0bb7ef..1b18f79ee 100644 --- a/src/Behat/Hook/BeforeScenario.php +++ b/src/Behat/Hook/BeforeScenario.php @@ -17,7 +17,7 @@ final class BeforeScenario implements Hook { /** - * @var string + * @var string|null */ public $filterString; @@ -25,4 +25,9 @@ public function __construct($filterString = null) { $this->filterString = $filterString; } + + public function getFilterString(): ?string + { + return $this->filterString; + } } diff --git a/src/Behat/Hook/BeforeStep.php b/src/Behat/Hook/BeforeStep.php index 1c7097143..16a4dc816 100644 --- a/src/Behat/Hook/BeforeStep.php +++ b/src/Behat/Hook/BeforeStep.php @@ -17,7 +17,7 @@ final class BeforeStep implements Hook { /** - * @var string + * @var string|null */ public $filterString; @@ -25,4 +25,9 @@ public function __construct($filterString = null) { $this->filterString = $filterString; } + + public function getFilterString(): ?string + { + return $this->filterString; + } } diff --git a/src/Behat/Hook/BeforeSuite.php b/src/Behat/Hook/BeforeSuite.php index 4d4c02f48..72191e1b5 100644 --- a/src/Behat/Hook/BeforeSuite.php +++ b/src/Behat/Hook/BeforeSuite.php @@ -17,7 +17,7 @@ final class BeforeSuite implements Hook { /** - * @var string + * @var string|null */ public $filterString; @@ -25,4 +25,9 @@ public function __construct($filterString = null) { $this->filterString = $filterString; } + + public function getFilterString(): ?string + { + return $this->filterString; + } } diff --git a/src/Behat/Hook/Hook.php b/src/Behat/Hook/Hook.php index 8c6dc7d8b..740a30474 100644 --- a/src/Behat/Hook/Hook.php +++ b/src/Behat/Hook/Hook.php @@ -18,4 +18,5 @@ */ interface Hook { + public function getFilterString(): ?string; } diff --git a/src/Behat/Step/Definition.php b/src/Behat/Step/Definition.php index 29578aebd..536d30409 100644 --- a/src/Behat/Step/Definition.php +++ b/src/Behat/Step/Definition.php @@ -18,4 +18,5 @@ */ interface Definition { + public function getPattern(): ?string; } diff --git a/src/Behat/Step/Given.php b/src/Behat/Step/Given.php index 6e07bf1a2..0fa606c0f 100644 --- a/src/Behat/Step/Given.php +++ b/src/Behat/Step/Given.php @@ -17,7 +17,7 @@ final class Given implements Definition { /** - * @var string + * @var string|null */ public $pattern; @@ -25,4 +25,9 @@ public function __construct($pattern = null) { $this->pattern = $pattern; } + + public function getPattern(): ?string + { + return $this->pattern; + } } diff --git a/src/Behat/Step/Then.php b/src/Behat/Step/Then.php index a3b9923c7..cfc04fb41 100644 --- a/src/Behat/Step/Then.php +++ b/src/Behat/Step/Then.php @@ -17,7 +17,7 @@ final class Then implements Definition { /** - * @var string + * @var string|null */ public $pattern; @@ -25,4 +25,9 @@ public function __construct($pattern = null) { $this->pattern = $pattern; } + + public function getPattern(): ?string + { + return $this->pattern; + } } diff --git a/src/Behat/Step/When.php b/src/Behat/Step/When.php index d6727e4c2..b00d4e01c 100644 --- a/src/Behat/Step/When.php +++ b/src/Behat/Step/When.php @@ -17,7 +17,7 @@ final class When implements Definition { /** - * @var string + * @var string|null */ public $pattern; @@ -25,4 +25,9 @@ public function __construct($pattern = null) { $this->pattern = $pattern; } + + public function getPattern(): ?string + { + return $this->pattern; + } } diff --git a/src/Behat/Testwork/Autoloader/Cli/AutoloaderController.php b/src/Behat/Testwork/Autoloader/Cli/AutoloaderController.php index 70ebe94af..0e6fc7c33 100644 --- a/src/Behat/Testwork/Autoloader/Cli/AutoloaderController.php +++ b/src/Behat/Testwork/Autoloader/Cli/AutoloaderController.php @@ -51,5 +51,6 @@ public function configure(Command $command) public function execute(InputInterface $input, OutputInterface $output) { $this->loader->register(); + return null; } } diff --git a/src/Behat/Testwork/Call/ServiceContainer/CallExtension.php b/src/Behat/Testwork/Call/ServiceContainer/CallExtension.php index 239aadbd2..e7aa9f9f4 100644 --- a/src/Behat/Testwork/Call/ServiceContainer/CallExtension.php +++ b/src/Behat/Testwork/Call/ServiceContainer/CallExtension.php @@ -78,8 +78,6 @@ public function configure(ArrayNodeDefinition $builder) ->scalarNode('error_reporting') ->info('Call executor will catch exceptions matching this level') ->defaultValue(E_ALL) - ->end() - ->end() ; } diff --git a/src/Behat/Testwork/EventDispatcher/Cli/SigintController.php b/src/Behat/Testwork/EventDispatcher/Cli/SigintController.php index f0d7d2c3b..ee3ab828a 100644 --- a/src/Behat/Testwork/EventDispatcher/Cli/SigintController.php +++ b/src/Behat/Testwork/EventDispatcher/Cli/SigintController.php @@ -61,6 +61,7 @@ public function execute(InputInterface $input, OutputInterface $output) */ pcntl_signal(SIGINT, array($this, 'abortExercise')); } + return null; } /** diff --git a/src/Behat/Testwork/Exception/Cli/VerbosityController.php b/src/Behat/Testwork/Exception/Cli/VerbosityController.php index bc86fb542..54fb09622 100644 --- a/src/Behat/Testwork/Exception/Cli/VerbosityController.php +++ b/src/Behat/Testwork/Exception/Cli/VerbosityController.php @@ -48,17 +48,13 @@ public function configure(Command $command) } /** - * Executes controller. - * - * @param InputInterface $input - * @param OutputInterface $output - * - * @return null|integer + * {@inheritdoc} */ public function execute(InputInterface $input, OutputInterface $output) { if ($output->getVerbosity() !== OutputInterface::VERBOSITY_NORMAL) { $this->exceptionPresenter->setDefaultVerbosity($output->getVerbosity()); } + return null; } } diff --git a/src/Behat/Testwork/Exception/ServiceContainer/ExceptionExtension.php b/src/Behat/Testwork/Exception/ServiceContainer/ExceptionExtension.php index 8b2001d73..4086df591 100644 --- a/src/Behat/Testwork/Exception/ServiceContainer/ExceptionExtension.php +++ b/src/Behat/Testwork/Exception/ServiceContainer/ExceptionExtension.php @@ -84,8 +84,6 @@ public function configure(ArrayNodeDefinition $builder) OutputPrinter::VERBOSITY_DEBUG )) ->defaultValue(OutputPrinter::VERBOSITY_NORMAL) - ->end() - ->end() ; } diff --git a/src/Behat/Testwork/Output/Cli/OutputController.php b/src/Behat/Testwork/Output/Cli/OutputController.php index 4130bcd8a..2310dc4b4 100644 --- a/src/Behat/Testwork/Output/Cli/OutputController.php +++ b/src/Behat/Testwork/Output/Cli/OutputController.php @@ -75,6 +75,7 @@ public function execute(InputInterface $input, OutputInterface $output) $this->configureFormatters($formats, $input, $output); $this->configureOutputs($formats, $outputs, $output->isDecorated()); + return null; } /** diff --git a/src/Behat/Testwork/Output/ServiceContainer/OutputExtension.php b/src/Behat/Testwork/Output/ServiceContainer/OutputExtension.php index bffaf38b8..b624ed24b 100644 --- a/src/Behat/Testwork/Output/ServiceContainer/OutputExtension.php +++ b/src/Behat/Testwork/Output/ServiceContainer/OutputExtension.php @@ -115,7 +115,6 @@ public function configure(ArrayNodeDefinition $builder) ->treatNullLike(array('enabled' => true)) ->treatFalseLike(array('enabled' => false)) ->prototype('variable')->end() - ->end() ; } diff --git a/src/Behat/Testwork/Suite/Cli/SuiteController.php b/src/Behat/Testwork/Suite/Cli/SuiteController.php index ea1a23aa6..e230a9191 100644 --- a/src/Behat/Testwork/Suite/Cli/SuiteController.php +++ b/src/Behat/Testwork/Suite/Cli/SuiteController.php @@ -79,5 +79,6 @@ public function execute(InputInterface $input, OutputInterface $output) $name, $config['type'], $config['settings'] ); } + return null; } } diff --git a/src/Behat/Testwork/Suite/ServiceContainer/SuiteExtension.php b/src/Behat/Testwork/Suite/ServiceContainer/SuiteExtension.php index a684a2965..c8ec896d9 100644 --- a/src/Behat/Testwork/Suite/ServiceContainer/SuiteExtension.php +++ b/src/Behat/Testwork/Suite/ServiceContainer/SuiteExtension.php @@ -104,29 +104,30 @@ public function configure(ArrayNodeDefinition $builder) ->end() ; assert($builder instanceof ArrayNodeDefinition); - $builder + $childrenBuilder = $builder ->normalizeKeys(false) ->addDefaultsIfNotSet() ->treatTrueLike(array('enabled' => true)) ->treatNullLike(array('enabled' => true)) ->treatFalseLike(array('enabled' => false)) ->children() + ; + $childrenBuilder ->booleanNode('enabled') ->info('Enables/disables suite') ->defaultTrue() - ->end() + ; + $childrenBuilder ->scalarNode('type') ->info('Specifies suite type') ->defaultValue(null) - ->end() + ; + $childrenBuilder ->arrayNode('settings') ->info('Specifies suite extra settings') ->defaultValue(array()) ->useAttributeAsKey('name') ->prototype('variable')->end() - ->end() - ->end() - ->end() ; } diff --git a/src/Behat/Testwork/Tester/Cli/StrictController.php b/src/Behat/Testwork/Tester/Cli/StrictController.php index 09c51009b..29121f640 100644 --- a/src/Behat/Testwork/Tester/Cli/StrictController.php +++ b/src/Behat/Testwork/Tester/Cli/StrictController.php @@ -66,5 +66,6 @@ public function execute(InputInterface $input, OutputInterface $output) } $this->resultInterpreter->registerResultInterpretation(new StrictInterpretation()); + return null; } } diff --git a/src/Behat/Testwork/Tester/ServiceContainer/TesterExtension.php b/src/Behat/Testwork/Tester/ServiceContainer/TesterExtension.php index 0e96869b4..172ffa561 100644 --- a/src/Behat/Testwork/Tester/ServiceContainer/TesterExtension.php +++ b/src/Behat/Testwork/Tester/ServiceContainer/TesterExtension.php @@ -82,21 +82,23 @@ public function initialize(ExtensionManager $extensionManager) */ public function configure(ArrayNodeDefinition $builder) { - $builder + $childrenBuilder = $builder ->addDefaultsIfNotSet() ->children() - ->scalarNode('stop_on_failure') - ->defaultValue(null) - ->end() + ; + $childrenBuilder + ->scalarNode('stop_on_failure') + ->defaultValue(null) + ; + $childrenBuilder ->booleanNode('strict') ->info('Sets the strict mode for result interpretation') ->defaultFalse() - ->end() + ; + $childrenBuilder ->booleanNode('skip') ->info('Tells tester to skip all tests') ->defaultFalse() - ->end() - ->end() ; } diff --git a/src/Behat/Testwork/Translator/Cli/LanguageController.php b/src/Behat/Testwork/Translator/Cli/LanguageController.php index 676b8917d..4c25dee4c 100644 --- a/src/Behat/Testwork/Translator/Cli/LanguageController.php +++ b/src/Behat/Testwork/Translator/Cli/LanguageController.php @@ -59,5 +59,6 @@ public function execute(InputInterface $input, OutputInterface $output) } $this->translator->setLocale($input->getOption('lang')); + return null; } } diff --git a/src/Behat/Testwork/Translator/ServiceContainer/TranslatorExtension.php b/src/Behat/Testwork/Translator/ServiceContainer/TranslatorExtension.php index 5fc53f0b9..2037cb9e5 100644 --- a/src/Behat/Testwork/Translator/ServiceContainer/TranslatorExtension.php +++ b/src/Behat/Testwork/Translator/ServiceContainer/TranslatorExtension.php @@ -52,18 +52,20 @@ public function configure(ArrayNodeDefinition $builder) { $defaultLanguage = $this->getDefaultLanguage() ?: 'en'; - $builder + $childrenBuilder = $builder ->addDefaultsIfNotSet() ->children() + ; + $childrenBuilder ->scalarNode('locale') ->info('Sets output locale for the tester') ->defaultValue($defaultLanguage) - ->end() + ; + $childrenBuilder ->scalarNode('fallback_locale') ->info('Sets fallback output locale for the tester') ->defaultValue('en') - ->end() - ->end(); + ; } /** From 90862253ad3f509a349294eb2a56d8b378ca21c1 Mon Sep 17 00:00:00 2001 From: Carlos Granados Date: Thu, 19 Dec 2024 12:04:47 +0100 Subject: [PATCH 523/567] Some fixes after PR review --- .../Cli/StopOnFailureController.php | 3 --- src/Behat/Behat/Gherkin/Cli/FilterController.php | 3 --- .../EventListener/AST/ScenarioNodeListener.php | 14 +++----------- .../Node/Printer/JUnit/JUnitSetupPrinter.php | 3 --- src/Behat/Behat/Snippet/Cli/SnippetsController.php | 3 --- src/Behat/Behat/Tester/Cli/RerunController.php | 3 --- .../Cli/GherkinTranslationsController.php | 3 --- .../Autoloader/Cli/AutoloaderController.php | 3 --- .../EventDispatcher/Cli/SigintController.php | 3 --- .../Testwork/Exception/Cli/VerbosityController.php | 3 --- src/Behat/Testwork/Output/Cli/OutputController.php | 3 --- src/Behat/Testwork/Suite/Cli/SuiteController.php | 3 --- src/Behat/Testwork/Tester/Cli/StrictController.php | 5 +---- .../Testwork/Translator/Cli/LanguageController.php | 5 +---- 14 files changed, 5 insertions(+), 52 deletions(-) diff --git a/src/Behat/Behat/EventDispatcher/Cli/StopOnFailureController.php b/src/Behat/Behat/EventDispatcher/Cli/StopOnFailureController.php index 7dc443d98..c0726d370 100644 --- a/src/Behat/Behat/EventDispatcher/Cli/StopOnFailureController.php +++ b/src/Behat/Behat/EventDispatcher/Cli/StopOnFailureController.php @@ -80,9 +80,6 @@ public function configure(Command $command) ); } - /** - * {@inheritdoc} - */ public function execute(InputInterface $input, OutputInterface $output) { if (!$input->getOption('stop-on-failure')) { diff --git a/src/Behat/Behat/Gherkin/Cli/FilterController.php b/src/Behat/Behat/Gherkin/Cli/FilterController.php index a40e87b04..8fb3de84e 100644 --- a/src/Behat/Behat/Gherkin/Cli/FilterController.php +++ b/src/Behat/Behat/Gherkin/Cli/FilterController.php @@ -74,9 +74,6 @@ public function configure(Command $command) ; } - /** - * {@inheritdoc} - */ public function execute(InputInterface $input, OutputInterface $output) { $filters = array(); diff --git a/src/Behat/Behat/Output/Node/EventListener/AST/ScenarioNodeListener.php b/src/Behat/Behat/Output/Node/EventListener/AST/ScenarioNodeListener.php index b0f1a142f..e002ec938 100644 --- a/src/Behat/Behat/Output/Node/EventListener/AST/ScenarioNodeListener.php +++ b/src/Behat/Behat/Output/Node/EventListener/AST/ScenarioNodeListener.php @@ -78,14 +78,10 @@ public function listenEvent(Formatter $formatter, Event $event, $eventName) /** * Prints scenario/background header on BEFORE event. - * - * @param Formatter $formatter - * @param ScenarioLikeTested|AfterSetup $event - * @param string $eventName */ - private function printHeaderOnBeforeEvent(Formatter $formatter, ScenarioLikeTested|AfterSetup $event, $eventName) + private function printHeaderOnBeforeEvent(Formatter $formatter, ScenarioLikeTested $event, string $eventName) { - if ($this->beforeEventName !== $eventName || !$event instanceof AfterSetup || !$event instanceof ScenarioLikeTested) { + if ($this->beforeEventName !== $eventName || !$event instanceof AfterSetup) { return; } @@ -98,12 +94,8 @@ private function printHeaderOnBeforeEvent(Formatter $formatter, ScenarioLikeTest /** * Prints scenario/background footer on AFTER event. - * - * @param Formatter $formatter - * @param ScenarioLikeTested|AfterTested $event - * @param string $eventName */ - private function printFooterOnAfterEvent(Formatter $formatter, ScenarioLikeTested|AfterTested $event, $eventName) + private function printFooterOnAfterEvent(Formatter $formatter, ScenarioLikeTested $event, string $eventName) { if ($this->afterEventName !== $eventName || !$event instanceof AfterTested) { return; diff --git a/src/Behat/Behat/Output/Node/Printer/JUnit/JUnitSetupPrinter.php b/src/Behat/Behat/Output/Node/Printer/JUnit/JUnitSetupPrinter.php index 0da8c7138..1571a59e4 100644 --- a/src/Behat/Behat/Output/Node/Printer/JUnit/JUnitSetupPrinter.php +++ b/src/Behat/Behat/Output/Node/Printer/JUnit/JUnitSetupPrinter.php @@ -57,16 +57,13 @@ public function printTeardown(Formatter $formatter, Teardown $teardown) private function handleHookCalls(Formatter $formatter, CallResults $results, string $messageType): void { foreach ($results as $hookCallResult) { - assert($hookCallResult instanceof CallResult); if ($hookCallResult->hasException()) { $call = $hookCallResult->getCall(); - assert($call instanceof HookCall); $scope = $call->getScope(); $outputPrinter = $formatter->getOutputPrinter(); assert($outputPrinter instanceof JUnitOutputPrinter); $callee = $call->getCallee(); - assert($callee instanceof Hook); $message = $callee->getName(); if ($scope instanceof StepScope) { $message .= ': ' . $scope->getStep()->getKeyword() . ' ' . $scope->getStep()->getText(); diff --git a/src/Behat/Behat/Snippet/Cli/SnippetsController.php b/src/Behat/Behat/Snippet/Cli/SnippetsController.php index 5f87fb58d..ce84e68bf 100644 --- a/src/Behat/Behat/Snippet/Cli/SnippetsController.php +++ b/src/Behat/Behat/Snippet/Cli/SnippetsController.php @@ -90,9 +90,6 @@ public function configure(Command $command) ); } - /** - * {@inheritdoc} - */ public function execute(InputInterface $input, OutputInterface $output) { $this->eventDispatcher->addListener(StepTested::AFTER, array($this, 'registerUndefinedStep'), -999); diff --git a/src/Behat/Behat/Tester/Cli/RerunController.php b/src/Behat/Behat/Tester/Cli/RerunController.php index a6d7982da..7951ebd4d 100644 --- a/src/Behat/Behat/Tester/Cli/RerunController.php +++ b/src/Behat/Behat/Tester/Cli/RerunController.php @@ -74,9 +74,6 @@ public function configure(Command $command) ); } - /** - * {@inheritdoc} - */ public function execute(InputInterface $input, OutputInterface $output) { $this->eventDispatcher->addListener(ScenarioTested::AFTER, array($this, 'collectFailedScenario'), -50); diff --git a/src/Behat/Behat/Translator/Cli/GherkinTranslationsController.php b/src/Behat/Behat/Translator/Cli/GherkinTranslationsController.php index 876889664..0d8441e43 100644 --- a/src/Behat/Behat/Translator/Cli/GherkinTranslationsController.php +++ b/src/Behat/Behat/Translator/Cli/GherkinTranslationsController.php @@ -45,9 +45,6 @@ public function configure(SymfonyCommand $command) { } - /** - * {@inheritdoc} - */ public function execute(InputInterface $input, OutputInterface $output) { $i18nPath = dirname(dirname(dirname(dirname(dirname(__DIR__))))) . DIRECTORY_SEPARATOR . 'i18n.php'; diff --git a/src/Behat/Testwork/Autoloader/Cli/AutoloaderController.php b/src/Behat/Testwork/Autoloader/Cli/AutoloaderController.php index 0e6fc7c33..d6658883b 100644 --- a/src/Behat/Testwork/Autoloader/Cli/AutoloaderController.php +++ b/src/Behat/Testwork/Autoloader/Cli/AutoloaderController.php @@ -38,9 +38,6 @@ public function __construct(ClassLoader $loader) $this->loader = $loader; } - /** - * {@inheritdoc} - */ public function configure(Command $command) { } diff --git a/src/Behat/Testwork/EventDispatcher/Cli/SigintController.php b/src/Behat/Testwork/EventDispatcher/Cli/SigintController.php index ee3ab828a..f0f0539b7 100644 --- a/src/Behat/Testwork/EventDispatcher/Cli/SigintController.php +++ b/src/Behat/Testwork/EventDispatcher/Cli/SigintController.php @@ -48,9 +48,6 @@ public function configure(Command $command) { } - /** - * {@inheritdoc} - */ public function execute(InputInterface $input, OutputInterface $output) { if (function_exists('pcntl_signal')) { diff --git a/src/Behat/Testwork/Exception/Cli/VerbosityController.php b/src/Behat/Testwork/Exception/Cli/VerbosityController.php index 54fb09622..7b6473dc1 100644 --- a/src/Behat/Testwork/Exception/Cli/VerbosityController.php +++ b/src/Behat/Testwork/Exception/Cli/VerbosityController.php @@ -47,9 +47,6 @@ public function configure(Command $command) { } - /** - * {@inheritdoc} - */ public function execute(InputInterface $input, OutputInterface $output) { if ($output->getVerbosity() !== OutputInterface::VERBOSITY_NORMAL) { diff --git a/src/Behat/Testwork/Output/Cli/OutputController.php b/src/Behat/Testwork/Output/Cli/OutputController.php index 2310dc4b4..89137ac2e 100644 --- a/src/Behat/Testwork/Output/Cli/OutputController.php +++ b/src/Behat/Testwork/Output/Cli/OutputController.php @@ -65,9 +65,6 @@ public function configure(Command $command) ); } - /** - * {@inheritdoc} - */ public function execute(InputInterface $input, OutputInterface $output) { $formats = $input->getOption('format'); diff --git a/src/Behat/Testwork/Suite/Cli/SuiteController.php b/src/Behat/Testwork/Suite/Cli/SuiteController.php index e230a9191..a46c3f228 100644 --- a/src/Behat/Testwork/Suite/Cli/SuiteController.php +++ b/src/Behat/Testwork/Suite/Cli/SuiteController.php @@ -56,9 +56,6 @@ public function configure(Command $command) ); } - /** - * {@inheritdoc} - */ public function execute(InputInterface $input, OutputInterface $output) { $exerciseSuiteName = $input->getOption('suite'); diff --git a/src/Behat/Testwork/Tester/Cli/StrictController.php b/src/Behat/Testwork/Tester/Cli/StrictController.php index 29121f640..ebd2d3b5d 100644 --- a/src/Behat/Testwork/Tester/Cli/StrictController.php +++ b/src/Behat/Testwork/Tester/Cli/StrictController.php @@ -46,9 +46,6 @@ public function __construct(ResultInterpreter $resultInterpreter, $strict = fals $this->strict = $strict; } - /** - * {@inheritdoc} - */ public function configure(Command $command) { $command->addOption('--strict', null, InputOption::VALUE_NONE, @@ -62,7 +59,7 @@ public function configure(Command $command) public function execute(InputInterface $input, OutputInterface $output) { if (!$this->strict && !$input->getOption('strict')) { - return; + return null; } $this->resultInterpreter->registerResultInterpretation(new StrictInterpretation()); diff --git a/src/Behat/Testwork/Translator/Cli/LanguageController.php b/src/Behat/Testwork/Translator/Cli/LanguageController.php index 4c25dee4c..c7b826e57 100644 --- a/src/Behat/Testwork/Translator/Cli/LanguageController.php +++ b/src/Behat/Testwork/Translator/Cli/LanguageController.php @@ -49,13 +49,10 @@ public function configure(Command $command) ); } - /** - * {@inheritdoc} - */ public function execute(InputInterface $input, OutputInterface $output) { if (!$input->getOption('lang')) { - return; + return null; } $this->translator->setLocale($input->getOption('lang')); From b303c31f63e00a2a9c9a237e5eeba85cf3f673fc Mon Sep 17 00:00:00 2001 From: Carlos Granados Date: Thu, 19 Dec 2024 17:06:45 +0100 Subject: [PATCH 524/567] chore: update code to PHPStan level 3 --- phpstan.dist.neon | 2 +- .../Event/AfterScenarioSetup.php | 4 +- .../Event/AfterScenarioTested.php | 4 +- .../EventDispatcher/Event/AfterStepTested.php | 2 +- .../Event/BeforeScenarioTeardown.php | 4 +- .../Event/BeforeScenarioTested.php | 4 +- .../Locator/FilesystemFeatureLocator.php | 6 +- .../EventListener/AST/OutlineListener.php | 49 ++------------ .../AST/OutlineTableListener.php | 63 +++++------------- .../Node/EventListener/AST/StepListener.php | 27 ++------ .../Statistics/ScenarioStatsListener.php | 20 ++---- .../Statistics/StepStatsListener.php | 46 ++++--------- .../Printer/JUnit/JUnitFeaturePrinter.php | 23 ++----- .../Behat/Output/Statistics/ScenarioStat.php | 33 +++------- .../Behat/Output/Statistics/Statistics.php | 6 +- .../Behat/Output/Statistics/StepStat.php | 47 ++++---------- .../Behat/Output/Statistics/StepStatV2.php | 64 ++++--------------- .../ReturnTypeTransformation.php | 2 +- .../Output/Printer/StreamOutputPrinter.php | 15 ++--- 19 files changed, 96 insertions(+), 325 deletions(-) diff --git a/phpstan.dist.neon b/phpstan.dist.neon index 41112f5ec..7894fbdf1 100644 --- a/phpstan.dist.neon +++ b/phpstan.dist.neon @@ -1,5 +1,5 @@ parameters: - level: 2 + level: 3 paths: - src excludePaths: diff --git a/src/Behat/Behat/EventDispatcher/Event/AfterScenarioSetup.php b/src/Behat/Behat/EventDispatcher/Event/AfterScenarioSetup.php index 38666bfe1..5d02a9d9a 100644 --- a/src/Behat/Behat/EventDispatcher/Event/AfterScenarioSetup.php +++ b/src/Behat/Behat/EventDispatcher/Event/AfterScenarioSetup.php @@ -65,9 +65,7 @@ public function getFeature() } /** - * Returns scenario node. - * - * @return ScenarioNode + * @return Scenario */ public function getScenario() { diff --git a/src/Behat/Behat/EventDispatcher/Event/AfterScenarioTested.php b/src/Behat/Behat/EventDispatcher/Event/AfterScenarioTested.php index 6af6f181c..b770481c6 100644 --- a/src/Behat/Behat/EventDispatcher/Event/AfterScenarioTested.php +++ b/src/Behat/Behat/EventDispatcher/Event/AfterScenarioTested.php @@ -77,9 +77,7 @@ public function getFeature() } /** - * Returns scenario node. - * - * @return ScenarioNode + * @return Scenario */ public function getScenario() { diff --git a/src/Behat/Behat/EventDispatcher/Event/AfterStepTested.php b/src/Behat/Behat/EventDispatcher/Event/AfterStepTested.php index d5829b77a..cf0aa2cb5 100644 --- a/src/Behat/Behat/EventDispatcher/Event/AfterStepTested.php +++ b/src/Behat/Behat/EventDispatcher/Event/AfterStepTested.php @@ -91,7 +91,7 @@ public function getStep() /** * Returns current test result. * - * @return TestResult + * @return StepResult */ public function getTestResult() { diff --git a/src/Behat/Behat/EventDispatcher/Event/BeforeScenarioTeardown.php b/src/Behat/Behat/EventDispatcher/Event/BeforeScenarioTeardown.php index da413b4eb..05ab5d955 100644 --- a/src/Behat/Behat/EventDispatcher/Event/BeforeScenarioTeardown.php +++ b/src/Behat/Behat/EventDispatcher/Event/BeforeScenarioTeardown.php @@ -69,9 +69,7 @@ public function getFeature() } /** - * Returns scenario node. - * - * @return ScenarioNode + * @return Scenario */ public function getScenario() { diff --git a/src/Behat/Behat/EventDispatcher/Event/BeforeScenarioTested.php b/src/Behat/Behat/EventDispatcher/Event/BeforeScenarioTested.php index d2737b850..071b8d682 100644 --- a/src/Behat/Behat/EventDispatcher/Event/BeforeScenarioTested.php +++ b/src/Behat/Behat/EventDispatcher/Event/BeforeScenarioTested.php @@ -58,9 +58,7 @@ public function getFeature() } /** - * Returns scenario node. - * - * @return ScenarioNode + * @return Scenario */ public function getScenario() { diff --git a/src/Behat/Behat/Gherkin/Specification/Locator/FilesystemFeatureLocator.php b/src/Behat/Behat/Gherkin/Specification/Locator/FilesystemFeatureLocator.php index 3d3305d88..8f7b67363 100644 --- a/src/Behat/Behat/Gherkin/Specification/Locator/FilesystemFeatureLocator.php +++ b/src/Behat/Behat/Gherkin/Specification/Locator/FilesystemFeatureLocator.php @@ -153,12 +153,8 @@ private function findFeatureFiles($path) /** * Finds absolute path for provided relative (relative to base features path). - * - * @param string $path Relative path - * - * @return string */ - private function findAbsolutePath($path) + private function findAbsolutePath(string $path): string|false { if (is_file($path) || is_dir($path)) { return realpath($path); diff --git a/src/Behat/Behat/Output/Node/EventListener/AST/OutlineListener.php b/src/Behat/Behat/Output/Node/EventListener/AST/OutlineListener.php index e1ce4ada7..0dd14fe52 100644 --- a/src/Behat/Behat/Output/Node/EventListener/AST/OutlineListener.php +++ b/src/Behat/Behat/Output/Node/EventListener/AST/OutlineListener.php @@ -33,52 +33,15 @@ */ final class OutlineListener implements EventListener { - /** - * @var OutlinePrinter - */ - private $outlinePrinter; - /** - * @var ExamplePrinter - */ - private $examplePrinter; - /** - * @var StepPrinter - */ - private $stepPrinter; - /** - * @var SetupPrinter - */ - private $stepSetupPrinter; - /** - * @var SetupPrinter - */ - private $exampleSetupPrinter; - /** - * @var ExampleNode - */ - private $example; + private ?ExampleNode $example; - /** - * Initializes listener. - * - * @param OutlinePrinter $outlinePrinter - * @param ExamplePrinter $examplePrinter - * @param StepPrinter $stepPrinter - * @param SetupPrinter $exampleSetupPrinter - * @param SetupPrinter $stepSetupPrinter - */ public function __construct( - OutlinePrinter $outlinePrinter, - ExamplePrinter $examplePrinter, - StepPrinter $stepPrinter, - SetupPrinter $exampleSetupPrinter, - SetupPrinter $stepSetupPrinter + private OutlinePrinter $outlinePrinter, + private ExamplePrinter $examplePrinter, + private StepPrinter $stepPrinter, + private SetupPrinter $exampleSetupPrinter, + private SetupPrinter $stepSetupPrinter ) { - $this->outlinePrinter = $outlinePrinter; - $this->examplePrinter = $examplePrinter; - $this->stepPrinter = $stepPrinter; - $this->exampleSetupPrinter = $exampleSetupPrinter; - $this->stepSetupPrinter = $stepSetupPrinter; } /** diff --git a/src/Behat/Behat/Output/Node/EventListener/AST/OutlineTableListener.php b/src/Behat/Behat/Output/Node/EventListener/AST/OutlineTableListener.php index 5ca8ca30e..beae4187f 100644 --- a/src/Behat/Behat/Output/Node/EventListener/AST/OutlineTableListener.php +++ b/src/Behat/Behat/Output/Node/EventListener/AST/OutlineTableListener.php @@ -37,61 +37,28 @@ */ final class OutlineTableListener implements EventListener { - /** - * @var OutlineTablePrinter - */ - private $tablePrinter; - /** - * @var ExampleRowPrinter - */ - private $exampleRowPrinter; - /** - * @var SetupPrinter - */ - private $stepSetupPrinter; - /** - * @var SetupPrinter - */ - private $exampleSetupPrinter; - /** - * @var OutlineNode - */ - private $outline; - /** - * @var Setup - */ - private $exampleSetup; - /** - * @var bool - */ - private $headerPrinted = false; + private ?OutlineNode $outline; + + private ?Setup $exampleSetup; + + private bool $headerPrinted = false; + /** * @var AfterStepSetup[] */ - private $stepBeforeTestedEvents = array(); + private array $stepBeforeTestedEvents = []; + /** * @var AfterStepTested[] */ - private $stepAfterTestedEvents = array(); + private array $stepAfterTestedEvents = []; - /** - * Initializes listener. - * - * @param OutlineTablePrinter $tablePrinter - * @param ExampleRowPrinter $exampleRowPrinter - * @param SetupPrinter $exampleSetupPrinter - * @param SetupPrinter $stepSetupPrinter - */ public function __construct( - OutlineTablePrinter $tablePrinter, - ExampleRowPrinter $exampleRowPrinter, - SetupPrinter $exampleSetupPrinter, - SetupPrinter $stepSetupPrinter + private OutlineTablePrinter $tablePrinter, + private ExampleRowPrinter $exampleRowPrinter, + private SetupPrinter $exampleSetupPrinter, + private SetupPrinter $stepSetupPrinter ) { - $this->tablePrinter = $tablePrinter; - $this->exampleRowPrinter = $exampleRowPrinter; - $this->exampleSetupPrinter = $exampleSetupPrinter; - $this->stepSetupPrinter = $stepSetupPrinter; } /** @@ -123,7 +90,7 @@ private function captureStepEvent(StepTested $event) { if ($event instanceof AfterStepSetup) { $this->stepBeforeTestedEvents[$event->getStep()->getLine()] = $event; - } else { + } elseif ($event instanceof AfterStepTested) { $this->stepAfterTestedEvents[$event->getStep()->getLine()] = $event; } } @@ -250,7 +217,7 @@ private function printFooterOnAfterEvent(Formatter $formatter, Event $event) * * @return StepResult[] */ - private function getStepTestResults() + private function getStepTestResults(): array { return array_map( function (AfterStepTested $event) { diff --git a/src/Behat/Behat/Output/Node/EventListener/AST/StepListener.php b/src/Behat/Behat/Output/Node/EventListener/AST/StepListener.php index 7892193b9..a7bc8516e 100644 --- a/src/Behat/Behat/Output/Node/EventListener/AST/StepListener.php +++ b/src/Behat/Behat/Output/Node/EventListener/AST/StepListener.php @@ -29,29 +29,12 @@ */ final class StepListener implements EventListener { - /** - * @var StepPrinter - */ - private $stepPrinter; - /** - * @var ScenarioLikeInterface - */ - private $scenario; - /** - * @var null|SetupPrinter - */ - private $setupPrinter; + private ?ScenarioLikeInterface $scenario; - /** - * Initializes listener. - * - * @param StepPrinter $stepPrinter - * @param null|SetupPrinter $setupPrinter - */ - public function __construct(StepPrinter $stepPrinter, ?SetupPrinter $setupPrinter = null) - { - $this->stepPrinter = $stepPrinter; - $this->setupPrinter = $setupPrinter; + public function __construct( + private StepPrinter $stepPrinter, + private ?SetupPrinter $setupPrinter = null + ) { } /** diff --git a/src/Behat/Behat/Output/Node/EventListener/Statistics/ScenarioStatsListener.php b/src/Behat/Behat/Output/Node/EventListener/Statistics/ScenarioStatsListener.php index ce94b2b2f..53380bedc 100644 --- a/src/Behat/Behat/Output/Node/EventListener/Statistics/ScenarioStatsListener.php +++ b/src/Behat/Behat/Output/Node/EventListener/Statistics/ScenarioStatsListener.php @@ -26,23 +26,11 @@ */ final class ScenarioStatsListener implements EventListener { - /** - * @var Statistics - */ - private $statistics; - /** - * @var string - */ - private $currentFeaturePath; + private ?string $currentFeaturePath; - /** - * Initializes listener. - * - * @param Statistics $statistics - */ - public function __construct(Statistics $statistics) - { - $this->statistics = $statistics; + public function __construct( + private Statistics $statistics + ) { } /** diff --git a/src/Behat/Behat/Output/Node/EventListener/Statistics/StepStatsListener.php b/src/Behat/Behat/Output/Node/EventListener/Statistics/StepStatsListener.php index c7ab312b4..10d3cc24d 100644 --- a/src/Behat/Behat/Output/Node/EventListener/Statistics/StepStatsListener.php +++ b/src/Behat/Behat/Output/Node/EventListener/Statistics/StepStatsListener.php @@ -27,6 +27,7 @@ use Behat\Testwork\Output\Node\EventListener\EventListener; use Behat\Testwork\Tester\Result\ExceptionResult; use Exception; +use Throwable; /** * Listens and records step events to statistics. @@ -35,37 +36,16 @@ */ final class StepStatsListener implements EventListener { - /** - * @var Statistics - */ - private $statistics; - /** - * @var string - */ - private $currentFeaturePath; - /** - * @var ExceptionPresenter - */ - private $exceptionPresenter; - /** - * @var string - */ - private $scenarioTitle; - /** - * @var string - */ - private $scenarioPath; + private ?string $currentFeaturePath; - /** - * Initializes listener. - * - * @param Statistics $statistics - * @param ExceptionPresenter $exceptionPresenter - */ - public function __construct(Statistics $statistics, ExceptionPresenter $exceptionPresenter) - { - $this->statistics = $statistics; - $this->exceptionPresenter = $exceptionPresenter; + private ?string $scenarioTitle; + + private ?string $scenarioPath; + + public function __construct( + private Statistics $statistics, + private ExceptionPresenter $exceptionPresenter + ) { } /** @@ -160,12 +140,8 @@ private function captureStepStatsOnAfterEvent(Event $event) /** * Gets exception from the step test results. - * - * @param StepResult $result - * - * @return null|Exception */ - private function getStepException(StepResult $result) + private function getStepException(StepResult $result): ?Throwable { if ($result instanceof ExceptionResult) { return $result->getException(); diff --git a/src/Behat/Behat/Output/Node/Printer/JUnit/JUnitFeaturePrinter.php b/src/Behat/Behat/Output/Node/Printer/JUnit/JUnitFeaturePrinter.php index 5ad882bc6..83be7d6e2 100644 --- a/src/Behat/Behat/Output/Node/Printer/JUnit/JUnitFeaturePrinter.php +++ b/src/Behat/Behat/Output/Node/Printer/JUnit/JUnitFeaturePrinter.php @@ -25,25 +25,12 @@ */ final class JUnitFeaturePrinter implements FeaturePrinter { - /** - * @var PhaseStatistics - */ - private $statistics; - - /** - * @var FeatureNode - */ - private $currentFeature; + private ?FeatureNode $currentFeature; - /** - * @var JUnitDurationListener|null - */ - private $durationListener; - - public function __construct(PhaseStatistics $statistics, ?JUnitDurationListener $durationListener = null) - { - $this->statistics = $statistics; - $this->durationListener = $durationListener; + public function __construct( + private PhaseStatistics $statistics, + private ?JUnitDurationListener $durationListener = null + ) { } /** diff --git a/src/Behat/Behat/Output/Statistics/ScenarioStat.php b/src/Behat/Behat/Output/Statistics/ScenarioStat.php index 0af5005d1..558b0ed29 100644 --- a/src/Behat/Behat/Output/Statistics/ScenarioStat.php +++ b/src/Behat/Behat/Output/Statistics/ScenarioStat.php @@ -10,6 +10,8 @@ namespace Behat\Behat\Output\Statistics; +use Behat\Testwork\Tester\Result\TestResult; + /** * Behat scenario stat. * @@ -18,30 +20,13 @@ final class ScenarioStat { /** - * @var string - */ - private $title; - /** - * @var string - */ - private $path; - /** - * @var integer + * @param TestResult::* $resultCode */ - private $resultCode; - - /** - * Initializes scenario stat. - * - * @param string $title - * @param string $path - * @param integer $resultCode - */ - public function __construct($title, $path, $resultCode) - { - $this->title = $title; - $this->path = $path; - $this->resultCode = $resultCode; + public function __construct( + private ?string $title, + private string $path, + private int $resultCode + ) { } /** @@ -67,7 +52,7 @@ public function getPath() /** * Returns scenario result code. * - * @return integer + * @return TestResult::* */ public function getResultCode() { diff --git a/src/Behat/Behat/Output/Statistics/Statistics.php b/src/Behat/Behat/Output/Statistics/Statistics.php index 4d20de9ec..24903b94d 100644 --- a/src/Behat/Behat/Output/Statistics/Statistics.php +++ b/src/Behat/Behat/Output/Statistics/Statistics.php @@ -10,8 +10,10 @@ namespace Behat\Behat\Output\Statistics; +use Behat\Behat\Tester\Result\StepResult; use Behat\Testwork\Counter\Memory; use Behat\Testwork\Counter\Timer; +use Behat\Testwork\Tester\Result\TestResult; /** @@ -69,7 +71,7 @@ public function registerHookStat(HookStat $stat); /** * Returns counters for different scenario result codes. * - * @return array[] + * @return array */ public function getScenarioStatCounts(); @@ -90,7 +92,7 @@ public function getFailedScenarios(); /** * Returns counters for different step result codes. * - * @return array[] + * @return array */ public function getStepStatCounts(); diff --git a/src/Behat/Behat/Output/Statistics/StepStat.php b/src/Behat/Behat/Output/Statistics/StepStat.php index 320d287d8..c87a39dea 100644 --- a/src/Behat/Behat/Output/Statistics/StepStat.php +++ b/src/Behat/Behat/Output/Statistics/StepStat.php @@ -10,6 +10,8 @@ namespace Behat\Behat\Output\Statistics; +use Behat\Behat\Tester\Result\StepResult; + /** * Behat step stat. * @@ -20,42 +22,15 @@ class StepStat { /** - * @var string - */ - private $text; - /** - * @var string - */ - private $path; - /** - * @var integer - */ - private $resultCode; - /** - * @var null|string + * @param StepResult::* $resultCode */ - private $error; - /** - * @var null|string - */ - private $stdOut; - - /** - * Initializes step stat. - * - * @param string $text - * @param string $path - * @param integer $resultCode - * @param null|string $error - * @param null|string $stdOut - */ - public function __construct($text, $path, $resultCode, $error = null, $stdOut = null) - { - $this->text = $text; - $this->path = $path; - $this->resultCode = $resultCode; - $this->error = $error; - $this->stdOut = $stdOut; + public function __construct( + private string $text, + private string $path, + private int $resultCode, + private ?string $error = null, + private ?string $stdOut = null + ) { } /** @@ -81,7 +56,7 @@ public function getPath() /** * Returns step result code. * - * @return integer + * @return StepResult::* */ public function getResultCode() { diff --git a/src/Behat/Behat/Output/Statistics/StepStatV2.php b/src/Behat/Behat/Output/Statistics/StepStatV2.php index ae13fc6bf..ecb7159cf 100644 --- a/src/Behat/Behat/Output/Statistics/StepStatV2.php +++ b/src/Behat/Behat/Output/Statistics/StepStatV2.php @@ -10,6 +10,8 @@ namespace Behat\Behat\Output\Statistics; +use Behat\Behat\Tester\Result\StepResult; + /** * Second iteration of Behat step stat, with a scenario information. * @@ -18,56 +20,18 @@ final class StepStatV2 extends StepStat { /** - * @var string - */ - private $scenarioTitle; - /** - * @var string - */ - private $scenarioPath; - /** - * @var string - */ - private $stepText; - /** - * @var string - */ - private $stepPath; - /** - * @var integer - */ - private $resultCode; - /** - * @var null|string - */ - private $error; - /** - * @var null|string - */ - private $stdOut; - - /** - * Initializes step stat. - * - * @param string $scenarioTitle - * @param string $scenarioPath - * @param string $stepText - * @param string $stepPath - * @param integer $resultCode - * @param null|string $error - * @param null|string $stdOut - */ - public function __construct($scenarioTitle, $scenarioPath, $stepText, $stepPath, $resultCode, $error = null, $stdOut = null) - { + * @param StepResult::* $resultCode + */ + public function __construct( + private string $scenarioTitle, + private string $scenarioPath, + private string $stepText, + private string $stepPath, + private int $resultCode, + private ?string $error = null, + private ?string $stdOut = null + ) { parent::__construct($stepText, $stepPath, $resultCode, $error, $stdOut); - - $this->scenarioTitle = $scenarioTitle; - $this->scenarioPath = $scenarioPath; - $this->stepText = $stepText; - $this->stepPath = $stepPath; - $this->resultCode = $resultCode; - $this->error = $error; - $this->stdOut = $stdOut; } /** @@ -113,7 +77,7 @@ public function getStepPath() /** * Returns step result code. * - * @return integer + * @return StepResult::* */ public function getResultCode() { diff --git a/src/Behat/Behat/Transformation/Transformation/ReturnTypeTransformation.php b/src/Behat/Behat/Transformation/Transformation/ReturnTypeTransformation.php index 79ed7960a..63917474c 100644 --- a/src/Behat/Behat/Transformation/Transformation/ReturnTypeTransformation.php +++ b/src/Behat/Behat/Transformation/Transformation/ReturnTypeTransformation.php @@ -107,7 +107,7 @@ public function getPriority() */ public function getPattern() { - return null; + return ''; } /** diff --git a/src/Behat/Testwork/Output/Printer/StreamOutputPrinter.php b/src/Behat/Testwork/Output/Printer/StreamOutputPrinter.php index 6b3fb4e49..bfae31d64 100644 --- a/src/Behat/Testwork/Output/Printer/StreamOutputPrinter.php +++ b/src/Behat/Testwork/Output/Printer/StreamOutputPrinter.php @@ -19,18 +19,11 @@ */ class StreamOutputPrinter implements OutputPrinter { - /** - * @var OutputInterface - */ - private $output; - /** - * @var OutputFactory - */ - private $outputFactory; + private ?OutputInterface $output; - public function __construct(OutputFactory $outputFactory) - { - $this->outputFactory = $outputFactory; + public function __construct( + private OutputFactory $outputFactory + ) { } /** From c2223810f43d48f5338d62d56e4cbd8f5f30fbe2 Mon Sep 17 00:00:00 2001 From: Carlos Granados Date: Mon, 23 Dec 2024 18:21:41 +0100 Subject: [PATCH 525/567] Add default values for nullable properties --- .../Behat/Output/Node/EventListener/AST/OutlineListener.php | 2 +- .../Output/Node/EventListener/AST/OutlineTableListener.php | 4 ++-- .../Behat/Output/Node/EventListener/AST/StepListener.php | 2 +- .../Node/EventListener/Statistics/ScenarioStatsListener.php | 2 +- .../Node/EventListener/Statistics/StepStatsListener.php | 6 +++--- .../Behat/Output/Node/Printer/JUnit/JUnitFeaturePrinter.php | 2 +- src/Behat/Behat/Output/Statistics/ScenarioStat.php | 1 + src/Behat/Testwork/Output/Printer/StreamOutputPrinter.php | 2 +- 8 files changed, 11 insertions(+), 10 deletions(-) diff --git a/src/Behat/Behat/Output/Node/EventListener/AST/OutlineListener.php b/src/Behat/Behat/Output/Node/EventListener/AST/OutlineListener.php index 0dd14fe52..46d641eaa 100644 --- a/src/Behat/Behat/Output/Node/EventListener/AST/OutlineListener.php +++ b/src/Behat/Behat/Output/Node/EventListener/AST/OutlineListener.php @@ -33,7 +33,7 @@ */ final class OutlineListener implements EventListener { - private ?ExampleNode $example; + private ?ExampleNode $example = null; public function __construct( private OutlinePrinter $outlinePrinter, diff --git a/src/Behat/Behat/Output/Node/EventListener/AST/OutlineTableListener.php b/src/Behat/Behat/Output/Node/EventListener/AST/OutlineTableListener.php index beae4187f..f4d539a07 100644 --- a/src/Behat/Behat/Output/Node/EventListener/AST/OutlineTableListener.php +++ b/src/Behat/Behat/Output/Node/EventListener/AST/OutlineTableListener.php @@ -37,9 +37,9 @@ */ final class OutlineTableListener implements EventListener { - private ?OutlineNode $outline; + private ?OutlineNode $outline = null; - private ?Setup $exampleSetup; + private ?Setup $exampleSetup = null; private bool $headerPrinted = false; diff --git a/src/Behat/Behat/Output/Node/EventListener/AST/StepListener.php b/src/Behat/Behat/Output/Node/EventListener/AST/StepListener.php index a7bc8516e..03afa083f 100644 --- a/src/Behat/Behat/Output/Node/EventListener/AST/StepListener.php +++ b/src/Behat/Behat/Output/Node/EventListener/AST/StepListener.php @@ -29,7 +29,7 @@ */ final class StepListener implements EventListener { - private ?ScenarioLikeInterface $scenario; + private ?ScenarioLikeInterface $scenario = null; public function __construct( private StepPrinter $stepPrinter, diff --git a/src/Behat/Behat/Output/Node/EventListener/Statistics/ScenarioStatsListener.php b/src/Behat/Behat/Output/Node/EventListener/Statistics/ScenarioStatsListener.php index 53380bedc..461c28b87 100644 --- a/src/Behat/Behat/Output/Node/EventListener/Statistics/ScenarioStatsListener.php +++ b/src/Behat/Behat/Output/Node/EventListener/Statistics/ScenarioStatsListener.php @@ -26,7 +26,7 @@ */ final class ScenarioStatsListener implements EventListener { - private ?string $currentFeaturePath; + private ?string $currentFeaturePath = null; public function __construct( private Statistics $statistics diff --git a/src/Behat/Behat/Output/Node/EventListener/Statistics/StepStatsListener.php b/src/Behat/Behat/Output/Node/EventListener/Statistics/StepStatsListener.php index 10d3cc24d..6da219738 100644 --- a/src/Behat/Behat/Output/Node/EventListener/Statistics/StepStatsListener.php +++ b/src/Behat/Behat/Output/Node/EventListener/Statistics/StepStatsListener.php @@ -36,11 +36,11 @@ */ final class StepStatsListener implements EventListener { - private ?string $currentFeaturePath; + private ?string $currentFeaturePath = null; - private ?string $scenarioTitle; + private ?string $scenarioTitle = null; - private ?string $scenarioPath; + private ?string $scenarioPath = null; public function __construct( private Statistics $statistics, diff --git a/src/Behat/Behat/Output/Node/Printer/JUnit/JUnitFeaturePrinter.php b/src/Behat/Behat/Output/Node/Printer/JUnit/JUnitFeaturePrinter.php index 83be7d6e2..d1856b042 100644 --- a/src/Behat/Behat/Output/Node/Printer/JUnit/JUnitFeaturePrinter.php +++ b/src/Behat/Behat/Output/Node/Printer/JUnit/JUnitFeaturePrinter.php @@ -25,7 +25,7 @@ */ final class JUnitFeaturePrinter implements FeaturePrinter { - private ?FeatureNode $currentFeature; + private ?FeatureNode $currentFeature = null; public function __construct( private PhaseStatistics $statistics, diff --git a/src/Behat/Behat/Output/Statistics/ScenarioStat.php b/src/Behat/Behat/Output/Statistics/ScenarioStat.php index 558b0ed29..197172556 100644 --- a/src/Behat/Behat/Output/Statistics/ScenarioStat.php +++ b/src/Behat/Behat/Output/Statistics/ScenarioStat.php @@ -27,6 +27,7 @@ public function __construct( private string $path, private int $resultCode ) { + $this->title = null; } /** diff --git a/src/Behat/Testwork/Output/Printer/StreamOutputPrinter.php b/src/Behat/Testwork/Output/Printer/StreamOutputPrinter.php index bfae31d64..0958b15d6 100644 --- a/src/Behat/Testwork/Output/Printer/StreamOutputPrinter.php +++ b/src/Behat/Testwork/Output/Printer/StreamOutputPrinter.php @@ -19,7 +19,7 @@ */ class StreamOutputPrinter implements OutputPrinter { - private ?OutputInterface $output; + private ?OutputInterface $output = null; public function __construct( private OutputFactory $outputFactory From 9513178eb7aae19bc71a572a61edc17c2f697e5b Mon Sep 17 00:00:00 2001 From: Carlos Granados Date: Sat, 21 Dec 2024 18:13:29 +0100 Subject: [PATCH 526/567] feat: adds a formatter option that allows you to set if you want stdout displayed as part of the formatter output --- features/show_output.feature | 220 ++++++++++++++++++ .../Behat/Output/Node/Printer/ListPrinter.php | 55 +++-- .../Node/Printer/Pretty/PrettyStepPrinter.php | 5 +- .../Progress/ProgressStatisticsPrinter.php | 5 +- .../Printer/Progress/ProgressStepPrinter.php | 34 +++ .../Config/Formatter/PrettyFormatter.php | 3 + .../Config/Formatter/ProgressFormatter.php | 3 + tests/Behat/Tests/Config/ProfileTest.php | 2 + 8 files changed, 304 insertions(+), 23 deletions(-) create mode 100644 features/show_output.feature diff --git a/features/show_output.feature b/features/show_output.feature new file mode 100644 index 000000000..2af0d13f3 --- /dev/null +++ b/features/show_output.feature @@ -0,0 +1,220 @@ +Feature: Show output + In order to see the stdout output of the code being tested + As a feature developer + I need to be able to set if this output will be shown or not + + Background: + Given a file named "features/bootstrap/FeatureContext.php" with: + """ + withFormatter(new ProgressFormatter(showOutput: 'no')) + ; + + return (new Config())->withProfile($profile); + + """ + When I run "behat --no-colors --format=progress" + Then it should fail with: + """ + ..F + + --- Failed steps: + + 001 Scenario: Some steps with output # features/show_output.feature:6 + And I have a step that shows some output and fails # features/show_output.feature:9 + step failed as supposed (Exception) + + 1 scenario (1 failed) + 3 steps (2 passed, 1 failed) + """ diff --git a/src/Behat/Behat/Output/Node/Printer/ListPrinter.php b/src/Behat/Behat/Output/Node/Printer/ListPrinter.php index e747db2e9..4d91fdcb1 100644 --- a/src/Behat/Behat/Output/Node/Printer/ListPrinter.php +++ b/src/Behat/Behat/Output/Node/Printer/ListPrinter.php @@ -102,13 +102,17 @@ public function printScenariosList(OutputPrinter $printer, $intro, $resultCode, /** * Prints step list. * - * @param OutputPrinter $printer * @param string $intro * @param integer $resultCode * @param StepStat[] $stepStats */ - public function printStepList(OutputPrinter $printer, $intro, $resultCode, array $stepStats) - { + public function printStepList( + OutputPrinter $printer, + $intro, + $resultCode, + array $stepStats, + string $showOutput = "in-summary" + ) { if (!count($stepStats)) { return; } @@ -120,9 +124,17 @@ public function printStepList(OutputPrinter $printer, $intro, $resultCode, array foreach ($stepStats as $num => $stepStat) { if ($stepStat instanceof StepStatV2) { - $this->printStepStat($printer, $num + 1, $stepStat, $style); + $this->printStepStat($printer, $num + 1, $stepStat, $style, $showOutput); } elseif ($stepStat instanceof StepStat) { - $this->printStat($printer, $stepStat->getText(), $stepStat->getPath(), $style, $stepStat->getStdOut(), $stepStat->getError()); + $this->printStat( + $printer, + $stepStat->getText(), + $stepStat->getPath(), + $style, + $stepStat->getStdOut(), + $stepStat->getError(), + $showOutput + ); } } } @@ -157,7 +169,6 @@ public function printFailedHooksList( /** * Prints hook stat. * - * @param OutputPrinter $printer * @param string $name * @param string $path * @param string $style @@ -166,14 +177,21 @@ public function printFailedHooksList( * * @deprecated Remove in 4.0 */ - private function printStat(OutputPrinter $printer, $name, $path, $style, $stdOut, $error) - { + private function printStat( + OutputPrinter $printer, + string $name, + string $path, + string $style, + ?string $stdOut, + ?string $error, + string $showOutput + ) { $path = $this->relativizePaths($path); $printer->writeln(sprintf(' {+%s}%s{-%s} {+comment}# %s{-comment}', $style, $name, $style, $path)); $pad = function ($line) { return ' ' . $line; }; - if (null !== $stdOut) { + if (null !== $stdOut && $showOutput !== 'no') { $padText = function ($line) { return ' │ ' . $line; }; $stdOutString = array_map($padText, explode("\n", $stdOut)); $printer->writeln(implode("\n", $stdOutString)); @@ -222,16 +240,13 @@ private function printHookStat(OutputPrinter $printer, HookStat $hookStat, strin $printer->writeln(); } - /** - * Prints hook stat. - * - * @param OutputPrinter $printer - * @param integer $number - * @param StepStatV2 $stat - * @param string $style - */ - private function printStepStat(OutputPrinter $printer, $number, StepStatV2 $stat, $style) - { + private function printStepStat( + OutputPrinter $printer, + int $number, + StepStatV2 $stat, + string $style, + string $showOutput + ) { $maxLength = max(mb_strlen($stat->getScenarioText(), 'utf8'), mb_strlen($stat->getStepText(), 'utf8') + 2) + 1; $printer->writeln( @@ -257,7 +272,7 @@ private function printStepStat(OutputPrinter $printer, $number, StepStatV2 $stat $pad = function ($line) { return ' ' . $line; }; - if (null !== $stat->getStdOut()) { + if (null !== $stat->getStdOut() && $showOutput !== 'no') { $padText = function ($line) { return ' │ ' . $line; }; $stdOutString = array_map($padText, explode("\n", $stat->getStdOut())); $printer->writeln(implode("\n", $stdOutString)); diff --git a/src/Behat/Behat/Output/Node/Printer/Pretty/PrettyStepPrinter.php b/src/Behat/Behat/Output/Node/Printer/Pretty/PrettyStepPrinter.php index 47d98e549..4654d11e4 100644 --- a/src/Behat/Behat/Output/Node/Printer/Pretty/PrettyStepPrinter.php +++ b/src/Behat/Behat/Output/Node/Printer/Pretty/PrettyStepPrinter.php @@ -92,7 +92,10 @@ public function printStep(Formatter $formatter, Scenario $scenario, StepNode $st $this->printText($formatter->getOutputPrinter(), $step->getKeyword(), $step->getText(), $result); $this->pathPrinter->printStepPath($formatter, $scenario, $step, $result, mb_strlen($this->indentText, 'utf8')); $this->printArguments($formatter, $step->getArguments(), $result); - $this->printStdOut($formatter->getOutputPrinter(), $result); + $showOutput = $formatter->getParameter('show_output'); + if ($showOutput === 'yes' || ($showOutput === 'on-fail' && !$result->isPassed())) { + $this->printStdOut($formatter->getOutputPrinter(), $result); + } $this->printException($formatter->getOutputPrinter(), $result); } diff --git a/src/Behat/Behat/Output/Node/Printer/Progress/ProgressStatisticsPrinter.php b/src/Behat/Behat/Output/Node/Printer/Progress/ProgressStatisticsPrinter.php index a104178d2..5d05ec2d2 100644 --- a/src/Behat/Behat/Output/Node/Printer/Progress/ProgressStatisticsPrinter.php +++ b/src/Behat/Behat/Output/Node/Printer/Progress/ProgressStatisticsPrinter.php @@ -58,11 +58,12 @@ public function printStatistics(Formatter $formatter, Statistics $statistics) $hookStats = $statistics->getFailedHookStats(); $this->listPrinter->printFailedHooksList($printer, 'failed_hooks_title', $hookStats); + $showOutput = $formatter->getParameter('show_output'); $stepStats = $statistics->getFailedSteps(); - $this->listPrinter->printStepList($printer, 'failed_steps_title', TestResult::FAILED, $stepStats); + $this->listPrinter->printStepList($printer, 'failed_steps_title', TestResult::FAILED, $stepStats, $showOutput); $stepStats = $statistics->getPendingSteps(); - $this->listPrinter->printStepList($printer, 'pending_steps_title', TestResult::PENDING, $stepStats); + $this->listPrinter->printStepList($printer, 'pending_steps_title', TestResult::PENDING, $stepStats, $showOutput); $this->counterPrinter->printCounters($printer, 'scenarios_count', $statistics->getScenarioStatCounts()); $this->counterPrinter->printCounters($printer, 'steps_count', $statistics->getStepStatCounts()); diff --git a/src/Behat/Behat/Output/Node/Printer/Progress/ProgressStepPrinter.php b/src/Behat/Behat/Output/Node/Printer/Progress/ProgressStepPrinter.php index 0d1f388b0..12907c1a2 100644 --- a/src/Behat/Behat/Output/Node/Printer/Progress/ProgressStepPrinter.php +++ b/src/Behat/Behat/Output/Node/Printer/Progress/ProgressStepPrinter.php @@ -12,10 +12,12 @@ use Behat\Behat\Output\Node\Printer\Helper\ResultToStringConverter; use Behat\Behat\Output\Node\Printer\StepPrinter; +use Behat\Behat\Tester\Result\ExecutedStepResult; use Behat\Behat\Tester\Result\StepResult; use Behat\Gherkin\Node\ScenarioLikeInterface as Scenario; use Behat\Gherkin\Node\StepNode; use Behat\Testwork\Output\Formatter; +use Behat\Testwork\Output\Printer\OutputPrinter; use Behat\Testwork\Tester\Result\TestResult; /** @@ -34,6 +36,8 @@ final class ProgressStepPrinter implements StepPrinter */ private $stepsPrinted = 0; + private bool $hasPrintedOutput = false; + /** * Initializes printer. * @@ -52,6 +56,10 @@ public function printStep(Formatter $formatter, Scenario $scenario, StepNode $st $printer = $formatter->getOutputPrinter(); $style = $this->resultConverter->convertResultToString($result); + if ($this->hasPrintedOutput) { + $printer->writeln(''); + } + switch ($result->getResultCode()) { case TestResult::PASSED: $printer->write("{+$style}.{-$style}"); @@ -70,8 +78,34 @@ public function printStep(Formatter $formatter, Scenario $scenario, StepNode $st break; } + $showOutput = $formatter->getParameter('show_output'); + if ($showOutput === 'yes' || ($showOutput === 'on-fail' && !$result->isPassed())) { + $this->printStdOut($formatter->getOutputPrinter(), $result); + } + if (++$this->stepsPrinted % 70 == 0) { $printer->writeln(' ' . $this->stepsPrinted); } } + + /** + * Prints step output (if has one). + */ + private function printStdOut(OutputPrinter $printer, StepResult $result): void + { + if (!$result instanceof ExecutedStepResult || null === $result->getCallResult()->getStdOut()) { + return; + } + + $printer->writeln("\n" . $result->getStepDefinition()->getPath() . ':'); + $callResult = $result->getCallResult(); + $pad = function ($line) { + return sprintf( + ' | {+stdout}%s{-stdout}', $line + ); + }; + + $printer->write(implode("\n", array_map($pad, explode("\n", $callResult->getStdOut())))); + $this->hasPrintedOutput = true; + } } diff --git a/src/Behat/Config/Formatter/PrettyFormatter.php b/src/Behat/Config/Formatter/PrettyFormatter.php index 6e6b27b9c..985d176b6 100644 --- a/src/Behat/Config/Formatter/PrettyFormatter.php +++ b/src/Behat/Config/Formatter/PrettyFormatter.php @@ -14,18 +14,21 @@ final class PrettyFormatter extends Formatter * @param bool $paths display the file path and line number for each scenario * and the context file and method for each step * @param bool $multiline print out PyStrings and TableNodes in full + * @param string $showOutput show the test stdout output as part of the formatter output (yes, no, on-fail) */ public function __construct( bool $timer = true, bool $expand = false, bool $paths = true, bool $multiline = true, + string $showOutput = 'yes', ) { parent::__construct(name: self::NAME, settings: [ 'timer' => $timer, 'expand' => $expand, 'paths' => $paths, 'multiline' => $multiline, + 'show_output' => $showOutput ]); } diff --git a/src/Behat/Config/Formatter/ProgressFormatter.php b/src/Behat/Config/Formatter/ProgressFormatter.php index 4efdf1803..a6fa8b02c 100644 --- a/src/Behat/Config/Formatter/ProgressFormatter.php +++ b/src/Behat/Config/Formatter/ProgressFormatter.php @@ -10,12 +10,15 @@ final class ProgressFormatter extends Formatter /** * @param bool $timer show time and memory usage at the end of the test run + * @param string $showOutput show the test stdout output as part of the formatter output (yes, no, on-fail, in-summary) */ public function __construct( bool $timer = true, + string $showOutput = 'in-summary', ) { parent::__construct(name: self::NAME, settings: [ 'timer' => $timer, + 'show_output' => $showOutput ]); } diff --git a/tests/Behat/Tests/Config/ProfileTest.php b/tests/Behat/Tests/Config/ProfileTest.php index fe551ac6d..69a89ffda 100644 --- a/tests/Behat/Tests/Config/ProfileTest.php +++ b/tests/Behat/Tests/Config/ProfileTest.php @@ -144,9 +144,11 @@ public function testAddingFormatters(): void 'paths' => false, 'multiline' => true, 'output_verbosity' => 2, + 'show_output' => 'yes' ], 'progress' => [ 'timer' => false, + 'show_output' => 'in-summary' ], 'junit' => [], ], From f1dbf3f5a9292d6452aab01cf5aaa3a113a0ef41 Mon Sep 17 00:00:00 2001 From: Carlos Granados Date: Mon, 23 Dec 2024 19:22:50 +0100 Subject: [PATCH 527/567] Use backed enum for the option values, fix progress step printer --- features/show_output.feature | 3 +- .../Behat/Output/Node/Printer/ListPrinter.php | 11 ++++--- .../Node/Printer/Pretty/PrettyStepPrinter.php | 6 ++-- .../Progress/ProgressStatisticsPrinter.php | 3 +- .../Printer/Progress/ProgressStepPrinter.php | 9 ++++-- .../Config/Formatter/PrettyFormatter.php | 22 ++++++++----- .../Config/Formatter/ProgressFormatter.php | 9 +++--- .../Config/Formatter/ShowOutputOption.php | 13 ++++++++ .../Output/NodeEventListeningFormatter.php | 7 ++++- tests/Behat/Tests/Config/ProfileTest.php | 31 +++++++++++++++++++ 10 files changed, 91 insertions(+), 23 deletions(-) create mode 100644 src/Behat/Config/Formatter/ShowOutputOption.php diff --git a/features/show_output.feature b/features/show_output.feature index 2af0d13f3..05f69775f 100644 --- a/features/show_output.feature +++ b/features/show_output.feature @@ -196,9 +196,10 @@ Feature: Show output use Behat\Config\Config; use Behat\Config\Profile; use Behat\Config\Formatter\ProgressFormatter; + use Behat\Config\Formatter\ShowOutputOption; $profile = (new Profile('default')) - ->withFormatter(new ProgressFormatter(showOutput: 'no')) + ->withFormatter(new ProgressFormatter(showOutput: ShowOutputOption::No)) ; return (new Config())->withProfile($profile); diff --git a/src/Behat/Behat/Output/Node/Printer/ListPrinter.php b/src/Behat/Behat/Output/Node/Printer/ListPrinter.php index 4d91fdcb1..096292be5 100644 --- a/src/Behat/Behat/Output/Node/Printer/ListPrinter.php +++ b/src/Behat/Behat/Output/Node/Printer/ListPrinter.php @@ -22,6 +22,7 @@ use Behat\Behat\Output\Statistics\ScenarioStat; use Behat\Behat\Output\Statistics\StepStatV2; use Behat\Behat\Output\Statistics\StepStat; +use Behat\Config\Formatter\ShowOutputOption; use Behat\Testwork\Exception\ExceptionPresenter; use Behat\Testwork\Hook\Scope\AfterSuiteScope; use Behat\Testwork\Hook\Scope\BeforeSuiteScope; @@ -111,7 +112,7 @@ public function printStepList( $intro, $resultCode, array $stepStats, - string $showOutput = "in-summary" + ShowOutputOption $showOutput = ShowOutputOption::InSummary ) { if (!count($stepStats)) { return; @@ -184,14 +185,14 @@ private function printStat( string $style, ?string $stdOut, ?string $error, - string $showOutput + ShowOutputOption $showOutput ) { $path = $this->relativizePaths($path); $printer->writeln(sprintf(' {+%s}%s{-%s} {+comment}# %s{-comment}', $style, $name, $style, $path)); $pad = function ($line) { return ' ' . $line; }; - if (null !== $stdOut && $showOutput !== 'no') { + if (null !== $stdOut && $showOutput !== ShowOutputOption::No) { $padText = function ($line) { return ' │ ' . $line; }; $stdOutString = array_map($padText, explode("\n", $stdOut)); $printer->writeln(implode("\n", $stdOutString)); @@ -245,7 +246,7 @@ private function printStepStat( int $number, StepStatV2 $stat, string $style, - string $showOutput + ShowOutputOption $showOutput ) { $maxLength = max(mb_strlen($stat->getScenarioText(), 'utf8'), mb_strlen($stat->getStepText(), 'utf8') + 2) + 1; @@ -272,7 +273,7 @@ private function printStepStat( $pad = function ($line) { return ' ' . $line; }; - if (null !== $stat->getStdOut() && $showOutput !== 'no') { + if (null !== $stat->getStdOut() && $showOutput !== ShowOutputOption::No) { $padText = function ($line) { return ' │ ' . $line; }; $stdOutString = array_map($padText, explode("\n", $stat->getStdOut())); $printer->writeln(implode("\n", $stdOutString)); diff --git a/src/Behat/Behat/Output/Node/Printer/Pretty/PrettyStepPrinter.php b/src/Behat/Behat/Output/Node/Printer/Pretty/PrettyStepPrinter.php index 4654d11e4..787c5d11b 100644 --- a/src/Behat/Behat/Output/Node/Printer/Pretty/PrettyStepPrinter.php +++ b/src/Behat/Behat/Output/Node/Printer/Pretty/PrettyStepPrinter.php @@ -16,6 +16,7 @@ use Behat\Behat\Tester\Result\DefinedStepResult; use Behat\Behat\Tester\Result\ExecutedStepResult; use Behat\Behat\Tester\Result\StepResult; +use Behat\Config\Formatter\ShowOutputOption; use Behat\Gherkin\Node\ArgumentInterface; use Behat\Gherkin\Node\PyStringNode; use Behat\Gherkin\Node\ScenarioLikeInterface as Scenario; @@ -92,8 +93,9 @@ public function printStep(Formatter $formatter, Scenario $scenario, StepNode $st $this->printText($formatter->getOutputPrinter(), $step->getKeyword(), $step->getText(), $result); $this->pathPrinter->printStepPath($formatter, $scenario, $step, $result, mb_strlen($this->indentText, 'utf8')); $this->printArguments($formatter, $step->getArguments(), $result); - $showOutput = $formatter->getParameter('show_output'); - if ($showOutput === 'yes' || ($showOutput === 'on-fail' && !$result->isPassed())) { + $showOutput = $formatter->getParameter(ShowOutputOption::OPTION_NAME); + if ($showOutput === ShowOutputOption::Yes || + ($showOutput === ShowOutputOption::OnFail && !$result->isPassed())) { $this->printStdOut($formatter->getOutputPrinter(), $result); } $this->printException($formatter->getOutputPrinter(), $result); diff --git a/src/Behat/Behat/Output/Node/Printer/Progress/ProgressStatisticsPrinter.php b/src/Behat/Behat/Output/Node/Printer/Progress/ProgressStatisticsPrinter.php index 5d05ec2d2..3d36946b8 100644 --- a/src/Behat/Behat/Output/Node/Printer/Progress/ProgressStatisticsPrinter.php +++ b/src/Behat/Behat/Output/Node/Printer/Progress/ProgressStatisticsPrinter.php @@ -14,6 +14,7 @@ use Behat\Behat\Output\Node\Printer\ListPrinter; use Behat\Behat\Output\Node\Printer\StatisticsPrinter; use Behat\Behat\Output\Statistics\Statistics; +use Behat\Config\Formatter\ShowOutputOption; use Behat\Testwork\Output\Formatter; use Behat\Testwork\Tester\Result\TestResult; @@ -58,7 +59,7 @@ public function printStatistics(Formatter $formatter, Statistics $statistics) $hookStats = $statistics->getFailedHookStats(); $this->listPrinter->printFailedHooksList($printer, 'failed_hooks_title', $hookStats); - $showOutput = $formatter->getParameter('show_output'); + $showOutput = $formatter->getParameter(ShowOutputOption::OPTION_NAME); $stepStats = $statistics->getFailedSteps(); $this->listPrinter->printStepList($printer, 'failed_steps_title', TestResult::FAILED, $stepStats, $showOutput); diff --git a/src/Behat/Behat/Output/Node/Printer/Progress/ProgressStepPrinter.php b/src/Behat/Behat/Output/Node/Printer/Progress/ProgressStepPrinter.php index 12907c1a2..1bb7970f1 100644 --- a/src/Behat/Behat/Output/Node/Printer/Progress/ProgressStepPrinter.php +++ b/src/Behat/Behat/Output/Node/Printer/Progress/ProgressStepPrinter.php @@ -14,6 +14,7 @@ use Behat\Behat\Output\Node\Printer\StepPrinter; use Behat\Behat\Tester\Result\ExecutedStepResult; use Behat\Behat\Tester\Result\StepResult; +use Behat\Config\Formatter\ShowOutputOption; use Behat\Gherkin\Node\ScenarioLikeInterface as Scenario; use Behat\Gherkin\Node\StepNode; use Behat\Testwork\Output\Formatter; @@ -56,8 +57,11 @@ public function printStep(Formatter $formatter, Scenario $scenario, StepNode $st $printer = $formatter->getOutputPrinter(); $style = $this->resultConverter->convertResultToString($result); + // After printing any output, we need to print a new line before continuing + // to print the "dots" of the progress if ($this->hasPrintedOutput) { $printer->writeln(''); + $this->hasPrintedOutput = false; } switch ($result->getResultCode()) { @@ -78,8 +82,9 @@ public function printStep(Formatter $formatter, Scenario $scenario, StepNode $st break; } - $showOutput = $formatter->getParameter('show_output'); - if ($showOutput === 'yes' || ($showOutput === 'on-fail' && !$result->isPassed())) { + $showOutput = $formatter->getParameter(ShowOutputOption::OPTION_NAME); + if ($showOutput === ShowOutputOption::Yes || + ($showOutput === ShowOutputOption::OnFail && !$result->isPassed())) { $this->printStdOut($formatter->getOutputPrinter(), $result); } diff --git a/src/Behat/Config/Formatter/PrettyFormatter.php b/src/Behat/Config/Formatter/PrettyFormatter.php index 985d176b6..38defa153 100644 --- a/src/Behat/Config/Formatter/PrettyFormatter.php +++ b/src/Behat/Config/Formatter/PrettyFormatter.php @@ -4,6 +4,8 @@ namespace Behat\Config\Formatter; +use UnexpectedValueException; + final class PrettyFormatter extends Formatter { public const NAME = 'pretty'; @@ -14,21 +16,27 @@ final class PrettyFormatter extends Formatter * @param bool $paths display the file path and line number for each scenario * and the context file and method for each step * @param bool $multiline print out PyStrings and TableNodes in full - * @param string $showOutput show the test stdout output as part of the formatter output (yes, no, on-fail) + * @param ShowOutputOption $showOutput show the test stdout output as part of the + * formatter output (yes, no, on-fail) */ public function __construct( - bool $timer = true, - bool $expand = false, - bool $paths = true, - bool $multiline = true, - string $showOutput = 'yes', + bool $timer = true, + bool $expand = false, + bool $paths = true, + bool $multiline = true, + ShowOutputOption $showOutput = ShowOutputOption::Yes, ) { + if ($showOutput === ShowOutputOption::InSummary) { + throw new UnexpectedValueException( + 'The pretty formatter does not support the "in-summary" show output option' + ); + } parent::__construct(name: self::NAME, settings: [ 'timer' => $timer, 'expand' => $expand, 'paths' => $paths, 'multiline' => $multiline, - 'show_output' => $showOutput + ShowOutputOption::OPTION_NAME => $showOutput->value ]); } diff --git a/src/Behat/Config/Formatter/ProgressFormatter.php b/src/Behat/Config/Formatter/ProgressFormatter.php index a6fa8b02c..2b02272db 100644 --- a/src/Behat/Config/Formatter/ProgressFormatter.php +++ b/src/Behat/Config/Formatter/ProgressFormatter.php @@ -10,15 +10,16 @@ final class ProgressFormatter extends Formatter /** * @param bool $timer show time and memory usage at the end of the test run - * @param string $showOutput show the test stdout output as part of the formatter output (yes, no, on-fail, in-summary) + * @param ShowOutputOption $showOutput show the test stdout output as part of the + * formatter output (yes, no, on-fail, in-summary) */ public function __construct( - bool $timer = true, - string $showOutput = 'in-summary', + bool $timer = true, + ShowOutputOption $showOutput = ShowOutputOption::InSummary, ) { parent::__construct(name: self::NAME, settings: [ 'timer' => $timer, - 'show_output' => $showOutput + ShowOutputOption::OPTION_NAME => $showOutput->value ]); } diff --git a/src/Behat/Config/Formatter/ShowOutputOption.php b/src/Behat/Config/Formatter/ShowOutputOption.php new file mode 100644 index 000000000..e5d5f6d1a --- /dev/null +++ b/src/Behat/Config/Formatter/ShowOutputOption.php @@ -0,0 +1,13 @@ +parameters[$name] ?? null; + $value = $this->parameters[$name] ?? null; + if ($value !== null && $name === ShowOutputOption::OPTION_NAME) { + return ShowOutputOption::from($value); + } + return $value; } } diff --git a/tests/Behat/Tests/Config/ProfileTest.php b/tests/Behat/Tests/Config/ProfileTest.php index 69a89ffda..d9115dce5 100644 --- a/tests/Behat/Tests/Config/ProfileTest.php +++ b/tests/Behat/Tests/Config/ProfileTest.php @@ -10,11 +10,13 @@ use Behat\Config\Formatter\JUnitFormatter; use Behat\Config\Formatter\PrettyFormatter; use Behat\Config\Formatter\ProgressFormatter; +use Behat\Config\Formatter\ShowOutputOption; use Behat\Config\Profile; use Behat\Config\Suite; use Behat\Testwork\Output\Printer\Factory\OutputFactory; use Behat\Testwork\ServiceContainer\Exception\ConfigurationLoadingException; use PHPUnit\Framework\TestCase; +use UnexpectedValueException; final class ProfileTest extends TestCase { @@ -171,4 +173,33 @@ public function testDisablingFormatters(): void ], ], $profile->toArray()); } + + public function testSettingShowOutputOption(): void + { + $profile = new Profile('default'); + + $profile->disableFormatter(PrettyFormatter::NAME); + $profile->disableFormatter(JUnitFormatter::NAME); + $profile->withFormatter(new ProgressFormatter(showOutput: ShowOutputOption::Yes)); + + $this->assertEquals([ + 'formatters' => [ + 'pretty' => false, + 'progress' => [ + 'timer' => true, + 'show_output' => 'yes' + ], + 'junit' => false, + ], + ], $profile->toArray()); + } + + public function testSettingInvalidShowOutputOption(): void + { + $profile = new Profile('default'); + + $this->expectException(UnexpectedValueException::class); + + $profile->withFormatter(new PrettyFormatter(showOutput: ShowOutputOption::InSummary)); + } } From 4ca3b15c05bb8589ad56cfa84ce58cf22bd6bc31 Mon Sep 17 00:00:00 2001 From: acoulton Date: Tue, 24 Dec 2024 15:43:16 +0000 Subject: [PATCH 528/567] chore: Remove composer dev dependency on legacy herrera-io/box This has not actually been used since #1462 which switched to installing box-project/box [directly in github actions]( https://github.com/Behat/Behat/pull/1462/files#diff-5c3fa597431eda03ac3339ae6bf7f05e1a50d6fc7333679ec38e21b337cb6721R135). --- composer.json | 1 - 1 file changed, 1 deletion(-) diff --git a/composer.json b/composer.json index 9b0cbcd99..036d9df5f 100644 --- a/composer.json +++ b/composer.json @@ -30,7 +30,6 @@ }, "require-dev": { - "herrera-io/box": "~1.6.1", "phpstan/phpstan": "^2.0", "phpunit/phpunit": "^9.6", "sebastian/diff": "^4.0", From 0c92a1756b5c3710880cd62f01c16b7fa28fa0db Mon Sep 17 00:00:00 2001 From: Carlos Granados Date: Tue, 24 Dec 2024 20:23:48 +0100 Subject: [PATCH 529/567] Do not disable xdebug if there is an active debugging connection --- src/Behat/Testwork/Cli/Application.php | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/Behat/Testwork/Cli/Application.php b/src/Behat/Testwork/Cli/Application.php index 25435a9b0..669cc5b8b 100644 --- a/src/Behat/Testwork/Cli/Application.php +++ b/src/Behat/Testwork/Cli/Application.php @@ -99,7 +99,9 @@ public function getDefaultInputDefinition(): InputDefinition */ public function doRun(InputInterface $input, OutputInterface $output): int { - $isXdebugAllowed = $input->hasParameterOption('--xdebug'); + $isXdebugAllowed = $input->hasParameterOption('--xdebug') || + (extension_loaded('xdebug') && xdebug_is_debugger_active()); + if (!$isXdebugAllowed) { $xdebugHandler = new XdebugHandler('behat'); $xdebugHandler->setPersistent(); From 9047f22538d3b695f5eb96562bbfef8d6f62207e Mon Sep 17 00:00:00 2001 From: Louis Celier Date: Sat, 28 Dec 2024 17:35:36 +0100 Subject: [PATCH 530/567] ci: #1405 do not run ci builds for some specific files fix latest php version for matrix strategy --- .github/workflows/build.yml | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 18ca6e7ec..c2aef45a0 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -3,7 +3,11 @@ name: Build on: push: branches: [master] - pull_request: ~ + paths-ignore: + - '**.md' + pull_request: + paths-ignore: + - '**.md' release: types: [created] workflow_dispatch: ~ @@ -30,13 +34,13 @@ jobs: symfony-version: '' # MacOS on latest PHP only - - php: 8.2 + - php: 8.4 os: macos-latest composer-mode: update symfony-version: '' # Windows on latest PHP only - - php: 8.2 + - php: 8.4 os: windows-latest composer-mode: update symfony-version: '' From bc50d7005d0ed5b5bc9c4f7e14dbb85ca3a0db61 Mon Sep 17 00:00:00 2001 From: Carlos Granados Date: Thu, 9 Jan 2025 17:55:56 +0100 Subject: [PATCH 531/567] Remove legacy Symfony event dispatchers --- phpstan.dist.neon | 3 - psalm.xml | 41 ----------- .../TestworkEventDispatcher.php | 15 +--- .../TestworkEventDispatcherSymfony5.php | 68 ------------------ .../TestworkEventDispatcherSymfonyLegacy.php | 72 ------------------- 5 files changed, 1 insertion(+), 198 deletions(-) delete mode 100644 src/Behat/Testwork/EventDispatcher/TestworkEventDispatcherSymfony5.php delete mode 100644 src/Behat/Testwork/EventDispatcher/TestworkEventDispatcherSymfonyLegacy.php diff --git a/phpstan.dist.neon b/phpstan.dist.neon index 7894fbdf1..f55980fbf 100644 --- a/phpstan.dist.neon +++ b/phpstan.dist.neon @@ -2,9 +2,6 @@ parameters: level: 3 paths: - src - excludePaths: - - src/Behat/Testwork/EventDispatcher/TestworkEventDispatcherSymfonyLegacy.php - - src/Behat/Testwork/EventDispatcher/TestworkEventDispatcherSymfony5.php ignoreErrors: - identifier: class.notFound diff --git a/psalm.xml b/psalm.xml index c8fe029b7..e43273ffe 100644 --- a/psalm.xml +++ b/psalm.xml @@ -30,47 +30,6 @@ - - - - - - - - - diff --git a/src/Behat/Testwork/EventDispatcher/TestworkEventDispatcher.php b/src/Behat/Testwork/EventDispatcher/TestworkEventDispatcher.php index 7d276a63f..bd6ca63aa 100644 --- a/src/Behat/Testwork/EventDispatcher/TestworkEventDispatcher.php +++ b/src/Behat/Testwork/EventDispatcher/TestworkEventDispatcher.php @@ -42,21 +42,8 @@ public function getListeners($eventName = null): array ); } - public function dispatch($event, $eventName = null): object + public function dispatch(object $event, ?string $eventName = null): object { - if (is_object($event)) { - return $this->bcAwareDispatch($event, $eventName); - } - - return $this->bcAwareDispatch($eventName, $event); - } - - private function bcAwareDispatch(?object $event, $eventName) - { - if (null === $event) { - $event = new Event(); - } - if (method_exists($event, 'setName')) { $event->setName($eventName); } diff --git a/src/Behat/Testwork/EventDispatcher/TestworkEventDispatcherSymfony5.php b/src/Behat/Testwork/EventDispatcher/TestworkEventDispatcherSymfony5.php deleted file mode 100644 index 1ff0b5f9c..000000000 --- a/src/Behat/Testwork/EventDispatcher/TestworkEventDispatcherSymfony5.php +++ /dev/null @@ -1,68 +0,0 @@ -=5.0) event dispatcher with catch-all listeners. - * - * This is magically aliased to TestworkEventDispatcher by the code in TestworkEventDispatcher.php - * if the new symfony interface is detected. - * - * @deprecated Do not reference this class directly, use TestworkEventDispatcher - */ -final class TestworkEventDispatcherSymfony5 extends EventDispatcher -{ - public const BEFORE_ALL_EVENTS = '*~'; - public const AFTER_ALL_EVENTS = '~*'; - public const DISPATCHER_VERSION = 2; - - /** - * {@inheritdoc} - */ - public function dispatch($event, ?string $eventName = null): object - { - trigger_error( - 'Class "\Behat\Testwork\EventDispatcher\TestworkEventDispatcherSymfony5" is deprecated ' . - 'and should not be relied upon anymore. Use "Behat\Testwork\EventDispatcher\TestworkEventDispatcher" ' . - 'instead', - E_USER_DEPRECATED - ); - if (null === $event) { - $event = new \Symfony\Contracts\EventDispatcher\Event(); - } - if (method_exists($event, 'setName')) { - $event->setName($eventName); - } - - $this->callListeners($this->getListeners($eventName), $eventName, $event); - - return $event; - } - - /** - * {@inheritdoc} - */ - public function getListeners($eventName = null) - { - trigger_error( - 'Class "\Behat\Testwork\EventDispatcher\TestworkEventDispatcherSymfony5" is deprecated ' . - 'and should not be relied upon anymore. Use "Behat\Testwork\EventDispatcher\TestworkEventDispatcher" ' . - 'instead', - E_USER_DEPRECATED - ); - - if (null == $eventName || self::BEFORE_ALL_EVENTS === $eventName) { - return parent::getListeners($eventName); - } - - return array_merge( - parent::getListeners(self::BEFORE_ALL_EVENTS), - parent::getListeners($eventName), - parent::getListeners(self::AFTER_ALL_EVENTS) - ); - } -} diff --git a/src/Behat/Testwork/EventDispatcher/TestworkEventDispatcherSymfonyLegacy.php b/src/Behat/Testwork/EventDispatcher/TestworkEventDispatcherSymfonyLegacy.php deleted file mode 100644 index 21f446743..000000000 --- a/src/Behat/Testwork/EventDispatcher/TestworkEventDispatcherSymfonyLegacy.php +++ /dev/null @@ -1,72 +0,0 @@ -setName($eventName); - } - /** @scrutinizer ignore-call */ - $this->doDispatch($this->getListeners($eventName), $eventName, $event); - - return $event; - } - - /** - * {@inheritdoc} - */ - public function getListeners($eventName = null) - { - trigger_error( - 'Class "\Behat\Testwork\EventDispatcher\TestworkEventDispatcherSymfonyLegacy" is deprecated ' . - 'and should not be relied upon anymore. Use "Behat\Testwork\EventDispatcher\TestworkEventDispatcher" ' . - 'instead', - E_USER_DEPRECATED - ); - - if (null == $eventName || self::BEFORE_ALL_EVENTS === $eventName) { - return parent::getListeners($eventName); - } - - return array_merge( - parent::getListeners(self::BEFORE_ALL_EVENTS), - parent::getListeners($eventName), - parent::getListeners(self::AFTER_ALL_EVENTS) - ); - } -} From cbf2b7c511a880de6253ea523b7eaf9969066301 Mon Sep 17 00:00:00 2001 From: acoulton - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Date: Thu, 9 Jan 2025 18:09:03 +0000 Subject: [PATCH 532/567] chore: Add changelog for 3.18.0 release --- CHANGELOG.md | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 56b1a548c..35895e419 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,32 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](http://keepachangelog.com/) and this project adheres to [Semantic Versioning](http://semver.org/). +## [3.18.0] - 2025-01-09 + +### Changed + +* Add new methods to the `Behat\Hook\Hook` and `Behat\Step\Definition` interfaces used internally by step definition + attributes by @carlos-granados in [#1573](https://github.com/Behat/Behat/pull/1573) + +### Added + +* Add `show_output` formatter option to control if/when to display stdout generated during tests + by @carlos-granados in [#1576](https://github.com/Behat/Behat/pull/1576) + +### Fixed + +* Do not disable xdebug if there is an active debugging connection by @carlos-granados in [#1581](https://github.com/Behat/Behat/pull/1581) +* Inherit step definition attributes on methods extended from parent Context by @fmatsos in [#1567](https://github.com/Behat/Behat/pull/1567) + +### Internal + +* Add PHPStan and improve / fix docblock annotations and type-safety within methods to achieve level 3 by + @carlos-granados in [#1571](https://github.com/Behat/Behat/pull/1571), [#1573](https://github.com/Behat/Behat/pull/1573) + [#1578](https://github.com/Behat/Behat/pull/1578) and by @stof in [#1575](https://github.com/Behat/Behat/pull/1575) +* Use annotations rather than attributes for step definitions in Behat's own feature suites by @fmatsos in [#1564](https://github.com/Behat/Behat/pull/1564) +* Remove composer dev dependency on legacy herrera-io/box by @acoulton in [#1580](https://github.com/Behat/Behat/pull/1580) +* Do not run ci builds if only markdown files have changed by @codisart in [#1582](https://github.com/Behat/Behat/pull/1582) + ## [3.17.0] - 2024-12-18 ### Changed @@ -1142,6 +1168,7 @@ and this project adheres to [Semantic Versioning](http://semver.org/). ### Changed * Initial release +[3.18.0]: https://github.com/Behat/Behat/compare/v3.17.0...v3.18.0 [3.17.0]: https://github.com/Behat/Behat/compare/v3.16.0...v3.17.0 [3.16.0]: https://github.com/Behat/Behat/compare/v3.15.0...v3.16.0 [3.15.0]: https://github.com/Behat/Behat/compare/v3.14.0...v3.15.0 From dffe5f16dda638368e29b69e0dc87503583d3a90 Mon Sep 17 00:00:00 2001 From: Carlos Granados Date: Fri, 10 Jan 2025 09:01:43 +0100 Subject: [PATCH 533/567] Fix ShowOutputOption handling to allow for the case when a formatter does not define it --- src/Behat/Behat/Output/Node/Printer/ListPrinter.php | 6 +++--- .../Behat/Output/Node/Printer/Pretty/PrettyStepPrinter.php | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/Behat/Behat/Output/Node/Printer/ListPrinter.php b/src/Behat/Behat/Output/Node/Printer/ListPrinter.php index 096292be5..ca71a0daa 100644 --- a/src/Behat/Behat/Output/Node/Printer/ListPrinter.php +++ b/src/Behat/Behat/Output/Node/Printer/ListPrinter.php @@ -112,7 +112,7 @@ public function printStepList( $intro, $resultCode, array $stepStats, - ShowOutputOption $showOutput = ShowOutputOption::InSummary + ?ShowOutputOption $showOutput = ShowOutputOption::InSummary ) { if (!count($stepStats)) { return; @@ -185,7 +185,7 @@ private function printStat( string $style, ?string $stdOut, ?string $error, - ShowOutputOption $showOutput + ?ShowOutputOption $showOutput ) { $path = $this->relativizePaths($path); $printer->writeln(sprintf(' {+%s}%s{-%s} {+comment}# %s{-comment}', $style, $name, $style, $path)); @@ -246,7 +246,7 @@ private function printStepStat( int $number, StepStatV2 $stat, string $style, - ShowOutputOption $showOutput + ?ShowOutputOption $showOutput ) { $maxLength = max(mb_strlen($stat->getScenarioText(), 'utf8'), mb_strlen($stat->getStepText(), 'utf8') + 2) + 1; diff --git a/src/Behat/Behat/Output/Node/Printer/Pretty/PrettyStepPrinter.php b/src/Behat/Behat/Output/Node/Printer/Pretty/PrettyStepPrinter.php index 787c5d11b..749873871 100644 --- a/src/Behat/Behat/Output/Node/Printer/Pretty/PrettyStepPrinter.php +++ b/src/Behat/Behat/Output/Node/Printer/Pretty/PrettyStepPrinter.php @@ -94,7 +94,7 @@ public function printStep(Formatter $formatter, Scenario $scenario, StepNode $st $this->pathPrinter->printStepPath($formatter, $scenario, $step, $result, mb_strlen($this->indentText, 'utf8')); $this->printArguments($formatter, $step->getArguments(), $result); $showOutput = $formatter->getParameter(ShowOutputOption::OPTION_NAME); - if ($showOutput === ShowOutputOption::Yes || + if ($showOutput === null || $showOutput === ShowOutputOption::Yes || ($showOutput === ShowOutputOption::OnFail && !$result->isPassed())) { $this->printStdOut($formatter->getOutputPrinter(), $result); } From 069ea64d03ed911105e1525d07b5e2bd17fd808e Mon Sep 17 00:00:00 2001 From: acoulton Date: Fri, 10 Jan 2025 09:56:58 +0000 Subject: [PATCH 534/567] chore: Add changelog for 3.18.1 release --- CHANGELOG.md | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 35895e419..15ed76996 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,13 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](http://keepachangelog.com/) and this project adheres to [Semantic Versioning](http://semver.org/). +## [3.18.1] - 2025-01-10 + +### Fixed + +* Fix handling of `show_output` option when used with a custom formatter that does not define it by @carlos-granados in + [#1587](https://github.com/Behat/Behat/pull/1587) + ## [3.18.0] - 2025-01-09 ### Changed From 99ef05f5d922aba2304a28709bac121f2188a775 Mon Sep 17 00:00:00 2001 From: acoulton Date: Mon, 6 Jan 2025 12:04:26 +0000 Subject: [PATCH 535/567] change: Remove internal wrappers for PSR Container interfaces These were previously provided to support either container-interop or psr/container at runtime. container-interop has been deprecated since 2017 and Behat removed support for it in #1380. The interfaces were already marked `@internal` and therefore should not be in use by any end-user code. --- psalm.xml | 9 ------- .../HelperContainer/ContainerInterface.php | 22 --------------- .../Exception/ContainerException.php | 27 ------------------- .../Exception/HelperContainerException.php | 3 ++- .../Exception/NotFoundException.php | 27 ------------------- .../Exception/ServiceNotFoundException.php | 3 ++- 6 files changed, 4 insertions(+), 87 deletions(-) delete mode 100644 src/Behat/Behat/HelperContainer/ContainerInterface.php delete mode 100644 src/Behat/Behat/HelperContainer/Exception/ContainerException.php delete mode 100644 src/Behat/Behat/HelperContainer/Exception/NotFoundException.php diff --git a/psalm.xml b/psalm.xml index c8fe029b7..020fb3044 100644 --- a/psalm.xml +++ b/psalm.xml @@ -13,15 +13,6 @@ - - - - - - - - - diff --git a/src/Behat/Behat/HelperContainer/ContainerInterface.php b/src/Behat/Behat/HelperContainer/ContainerInterface.php deleted file mode 100644 index 88998ff4c..000000000 --- a/src/Behat/Behat/HelperContainer/ContainerInterface.php +++ /dev/null @@ -1,22 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Behat\Behat\HelperContainer; - -class_alias('Psr\\Container\\ContainerInterface', 'Behat\\Behat\\HelperContainer\\ContainerInterface'); - -if (false) { - /** - * @internal - */ - interface ContainerInterface - { - } -} diff --git a/src/Behat/Behat/HelperContainer/Exception/ContainerException.php b/src/Behat/Behat/HelperContainer/Exception/ContainerException.php deleted file mode 100644 index fd5543ad0..000000000 --- a/src/Behat/Behat/HelperContainer/Exception/ContainerException.php +++ /dev/null @@ -1,27 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Behat\Behat\HelperContainer\Exception; - -class_alias( - interface_exists('Interop\\Container\\Exception\\ContainerException') - ? 'Interop\\Container\\Exception\\ContainerException' - : 'Psr\\Container\\ContainerExceptionInterface', - 'Behat\\Behat\\HelperContainer\\Exception\\ContainerException' -); - -if (false) { - /** - * @internal - */ - interface ContainerException - { - } -} diff --git a/src/Behat/Behat/HelperContainer/Exception/HelperContainerException.php b/src/Behat/Behat/HelperContainer/Exception/HelperContainerException.php index d61919225..317175af3 100644 --- a/src/Behat/Behat/HelperContainer/Exception/HelperContainerException.php +++ b/src/Behat/Behat/HelperContainer/Exception/HelperContainerException.php @@ -11,12 +11,13 @@ namespace Behat\Behat\HelperContainer\Exception; use Behat\Testwork\Environment\Exception\EnvironmentException; +use Psr\Container\ContainerExceptionInterface; /** * All HelperContainer exceptions implement this interface. * * @author Konstantin Kudryashov */ -interface HelperContainerException extends ContainerException, EnvironmentException +interface HelperContainerException extends ContainerExceptionInterface, EnvironmentException { } diff --git a/src/Behat/Behat/HelperContainer/Exception/NotFoundException.php b/src/Behat/Behat/HelperContainer/Exception/NotFoundException.php deleted file mode 100644 index 739e5181f..000000000 --- a/src/Behat/Behat/HelperContainer/Exception/NotFoundException.php +++ /dev/null @@ -1,27 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Behat\Behat\HelperContainer\Exception; - -class_alias( - interface_exists('Interop\\Container\\Exception\\NotFoundException') - ? 'Interop\\Container\\Exception\\NotFoundException' - : 'Psr\\Container\\NotFoundExceptionInterface', - 'Behat\\Behat\\HelperContainer\\Exception\\NotFoundException' -); - -if (false) { - /** - * @internal - */ - interface NotFoundException - { - } -} diff --git a/src/Behat/Behat/HelperContainer/Exception/ServiceNotFoundException.php b/src/Behat/Behat/HelperContainer/Exception/ServiceNotFoundException.php index a82b63ed0..9d4046002 100644 --- a/src/Behat/Behat/HelperContainer/Exception/ServiceNotFoundException.php +++ b/src/Behat/Behat/HelperContainer/Exception/ServiceNotFoundException.php @@ -11,13 +11,14 @@ namespace Behat\Behat\HelperContainer\Exception; use InvalidArgumentException; +use Psr\Container\NotFoundExceptionInterface; /** * Represents an exception thrown when service ID is not found inside the container. * * @author Konstantin Kudryashov */ -final class ServiceNotFoundException extends InvalidArgumentException implements HelperContainerException, NotFoundException +final class ServiceNotFoundException extends InvalidArgumentException implements HelperContainerException, NotFoundExceptionInterface { /** * @var string From adc3f232dfe54761b068f15d507d664f2af4a023 Mon Sep 17 00:00:00 2001 From: Carlos Granados Date: Fri, 20 Dec 2024 10:36:04 +0100 Subject: [PATCH 536/567] chore: update code to PHPStan level 4 --- phpstan.dist.neon | 7 +++- .../InitializedContextEnvironment.php | 7 ++-- .../Appender/ContextSnippetAppender.php | 16 ++------ .../Generator/ContextSnippetGenerator.php | 13 ++++--- .../Exception/AmbiguousMatchException.php | 12 ------ .../Pattern/Policy/PatternPolicy.php | 2 +- .../Printer/ConsoleDefinitionPrinter.php | 5 --- .../Cli/StopOnFailureController.php | 9 +---- .../Argument/ServicesResolverFactory.php | 2 +- .../AST/ScenarioNodeListener.php | 37 ++----------------- .../JUnit/JUnitDurationListener.php | 8 ++-- .../Node/Printer/JUnit/JUnitSuitePrinter.php | 11 ++---- .../Behat/Output/Node/Printer/ListPrinter.php | 8 +--- .../Printer/Pretty/PrettyFeaturePrinter.php | 4 +- .../Node/Printer/Pretty/PrettyStepPrinter.php | 2 +- .../Behat/Output/Statistics/ScenarioStat.php | 5 ++- .../Tester/Result/FailedStepSearchResult.php | 3 +- .../Tester/Runtime/RuntimeFeatureTester.php | 5 --- .../ReturnTypeTransformation.php | 6 +-- src/Behat/Testwork/Call/CallCenter.php | 4 +- .../Testwork/Ordering/Cli/OrderController.php | 5 --- .../Output/Printer/JUnitOutputPrinter.php | 25 +++++-------- .../Configuration/ConfigurationLoader.php | 2 + .../ServiceContainer/ExtensionManager.php | 17 ++------- .../Locator/SpecificationLocator.php | 2 +- .../Suite/Generator/SuiteGenerator.php | 2 +- src/Behat/Testwork/Suite/SuiteRegistry.php | 8 +--- .../Tester/Cli/ExerciseController.php | 2 +- 28 files changed, 64 insertions(+), 165 deletions(-) diff --git a/phpstan.dist.neon b/phpstan.dist.neon index f55980fbf..aad617b3a 100644 --- a/phpstan.dist.neon +++ b/phpstan.dist.neon @@ -1,5 +1,5 @@ parameters: - level: 3 + level: 4 paths: - src ignoreErrors: @@ -10,4 +10,9 @@ parameters: - identifier: constructor.unusedParameter paths: + - src/Behat/Behat/Definition/Printer/ConsoleDefinitionPrinter.php + - src/Behat/Behat/EventDispatcher/Cli/StopOnFailureController.php + - src/Behat/Behat/Output/Node/Printer/ListPrinter.php + - src/Behat/Behat/Tester/Runtime/RuntimeFeatureTester.php - src/Behat/Behat/Transformation/Transformation/ReturnTypeTransformation.php + - src/Behat/Testwork/Ordering/Cli/OrderController.php diff --git a/src/Behat/Behat/Context/Environment/InitializedContextEnvironment.php b/src/Behat/Behat/Context/Environment/InitializedContextEnvironment.php index 64a6a1343..39a0b00d9 100644 --- a/src/Behat/Behat/Context/Environment/InitializedContextEnvironment.php +++ b/src/Behat/Behat/Context/Environment/InitializedContextEnvironment.php @@ -31,10 +31,9 @@ final class InitializedContextEnvironment implements ContextEnvironment, Service * @var Suite */ private $suite; - /** - * @var ContainerInterface - */ - private $serviceContainer; + + private ?ContainerInterface $serviceContainer = null; + /** * @var array, Context> * @psalm-var class-string-map diff --git a/src/Behat/Behat/Context/Snippet/Appender/ContextSnippetAppender.php b/src/Behat/Behat/Context/Snippet/Appender/ContextSnippetAppender.php index dc4df1603..66c6cce16 100644 --- a/src/Behat/Behat/Context/Snippet/Appender/ContextSnippetAppender.php +++ b/src/Behat/Behat/Context/Snippet/Appender/ContextSnippetAppender.php @@ -27,19 +27,9 @@ final class ContextSnippetAppender implements SnippetAppender */ public const PENDING_EXCEPTION_CLASS = 'Behat\Behat\Tester\Exception\PendingException'; - /** - * @var FilesystemLogger - */ - private $logger; - - /** - * Initializes appender. - * - * @param null|FilesystemLogger $logger - */ - public function __construct(?FilesystemLogger $logger = null) - { - $this->logger = $logger; + public function __construct( + private ?FilesystemLogger $logger = null + ) { } /** diff --git a/src/Behat/Behat/Context/Snippet/Generator/ContextSnippetGenerator.php b/src/Behat/Behat/Context/Snippet/Generator/ContextSnippetGenerator.php index d5a07699c..e8f3fc388 100644 --- a/src/Behat/Behat/Context/Snippet/Generator/ContextSnippetGenerator.php +++ b/src/Behat/Behat/Context/Snippet/Generator/ContextSnippetGenerator.php @@ -161,17 +161,20 @@ private function getUsedClasses(StepNode $step): array { $usedClasses = [PendingException::class]; - $usedClasses[] = match ($step->getKeywordType()) { + $keywordType = $step->getKeywordType(); + assert( + $keywordType === DefinitionCall\Given::KEYWORD || + $keywordType === DefinitionCall\When::KEYWORD || + $keywordType === DefinitionCall\Then::KEYWORD + ); + $usedClasses[] = match ($keywordType) { DefinitionCall\Given::KEYWORD => Given::class, DefinitionCall\When::KEYWORD => When::class, DefinitionCall\Then::KEYWORD => Then::class, }; foreach ($step->getArguments() as $argument) { - $usedClasses[] = match (true) { - $argument instanceof TableNode => TableNode::class, - $argument instanceof PyStringNode => PyStringNode::class, - }; + $usedClasses[] = $argument::class; } return $usedClasses; diff --git a/src/Behat/Behat/Definition/Exception/AmbiguousMatchException.php b/src/Behat/Behat/Definition/Exception/AmbiguousMatchException.php index bb5ba339a..fe9550673 100644 --- a/src/Behat/Behat/Definition/Exception/AmbiguousMatchException.php +++ b/src/Behat/Behat/Definition/Exception/AmbiguousMatchException.php @@ -23,15 +23,6 @@ */ final class AmbiguousMatchException extends RuntimeException implements SearchException { - /** - * @var string - */ - private $text; - /** - * @var Definition[] - */ - private $matches = array(); - /** * Initializes ambiguous exception. * @@ -40,9 +31,6 @@ final class AmbiguousMatchException extends RuntimeException implements SearchEx */ public function __construct($text, array $matches) { - $this->text = $text; - $this->matches = $matches; - $message = sprintf("Ambiguous match of \"%s\":", $text); foreach ($matches as $definition) { $message .= sprintf( diff --git a/src/Behat/Behat/Definition/Pattern/Policy/PatternPolicy.php b/src/Behat/Behat/Definition/Pattern/Policy/PatternPolicy.php index cd3daac5c..a1fbcf404 100644 --- a/src/Behat/Behat/Definition/Pattern/Policy/PatternPolicy.php +++ b/src/Behat/Behat/Definition/Pattern/Policy/PatternPolicy.php @@ -25,7 +25,7 @@ interface PatternPolicy /** * Checks if policy supports pattern type. * - * @param string $type + * @param string|null $type * * @return bool */ diff --git a/src/Behat/Behat/Definition/Printer/ConsoleDefinitionPrinter.php b/src/Behat/Behat/Definition/Printer/ConsoleDefinitionPrinter.php index bd0546f41..b509f304a 100644 --- a/src/Behat/Behat/Definition/Printer/ConsoleDefinitionPrinter.php +++ b/src/Behat/Behat/Definition/Printer/ConsoleDefinitionPrinter.php @@ -29,10 +29,6 @@ abstract class ConsoleDefinitionPrinter implements DefinitionPrinter * @var OutputInterface */ private $output; - /** - * @var PatternTransformer - */ - private $patternTransformer; /** * @var DefinitionTranslator */ @@ -57,7 +53,6 @@ public function __construct( KeywordsInterface $keywords ) { $this->output = $output; - $this->patternTransformer = $patternTransformer; $this->translator = $translator; $this->keywords = $keywords; diff --git a/src/Behat/Behat/EventDispatcher/Cli/StopOnFailureController.php b/src/Behat/Behat/EventDispatcher/Cli/StopOnFailureController.php index c0726d370..be1e40c15 100644 --- a/src/Behat/Behat/EventDispatcher/Cli/StopOnFailureController.php +++ b/src/Behat/Behat/EventDispatcher/Cli/StopOnFailureController.php @@ -39,12 +39,6 @@ */ final class StopOnFailureController implements Controller { - /** - * @deprecated events are now dispatched in the StopOnFailureHandler - * @var EventDispatcherInterface - */ - private $eventDispatcher; - /** * @var StopOnFailureHandler */ @@ -53,11 +47,10 @@ final class StopOnFailureController implements Controller /** * Initializes controller. * - * @param EventDispatcherInterface $eventDispatcher + * @param EventDispatcherInterface $eventDispatcher deprecated, events are now dispatched in the StopOnFailureHandler */ public function __construct(EventDispatcherInterface $eventDispatcher) { - $this->eventDispatcher = $eventDispatcher; } /** diff --git a/src/Behat/Behat/HelperContainer/Argument/ServicesResolverFactory.php b/src/Behat/Behat/HelperContainer/Argument/ServicesResolverFactory.php index 43d8ef490..7389e28b6 100644 --- a/src/Behat/Behat/HelperContainer/Argument/ServicesResolverFactory.php +++ b/src/Behat/Behat/HelperContainer/Argument/ServicesResolverFactory.php @@ -98,7 +98,7 @@ public function createArgumentResolvers(Environment $environment) /** * Creates container from the setting passed. * - * @param string|array $settings + * @param mixed $settings * * @return mixed * diff --git a/src/Behat/Behat/Output/Node/EventListener/AST/ScenarioNodeListener.php b/src/Behat/Behat/Output/Node/EventListener/AST/ScenarioNodeListener.php index e002ec938..f33223a07 100644 --- a/src/Behat/Behat/Output/Node/EventListener/AST/ScenarioNodeListener.php +++ b/src/Behat/Behat/Output/Node/EventListener/AST/ScenarioNodeListener.php @@ -26,41 +26,12 @@ */ final class ScenarioNodeListener implements EventListener { - /** - * @var string - */ - private $beforeEventName; - /** - * @var string - */ - private $afterEventName; - /** - * @var ScenarioPrinter - */ - private $scenarioPrinter; - /** - * @var SetupPrinter - */ - private $setupPrinter; - - /** - * Initializes listener. - * - * @param string $beforeEventName - * @param string $afterEventName - * @param ScenarioPrinter $scenarioPrinter - * @param null|SetupPrinter $setupPrinter - */ public function __construct( - $beforeEventName, - $afterEventName, - ScenarioPrinter $scenarioPrinter, - ?SetupPrinter $setupPrinter = null + private string $beforeEventName, + private string $afterEventName, + private ScenarioPrinter $scenarioPrinter, + private ?SetupPrinter $setupPrinter = null ) { - $this->beforeEventName = $beforeEventName; - $this->afterEventName = $afterEventName; - $this->scenarioPrinter = $scenarioPrinter; - $this->setupPrinter = $setupPrinter; } /** diff --git a/src/Behat/Behat/Output/Node/EventListener/JUnit/JUnitDurationListener.php b/src/Behat/Behat/Output/Node/EventListener/JUnit/JUnitDurationListener.php index 3e2af09f8..d8ca7c951 100644 --- a/src/Behat/Behat/Output/Node/EventListener/JUnit/JUnitDurationListener.php +++ b/src/Behat/Behat/Output/Node/EventListener/JUnit/JUnitDurationListener.php @@ -74,8 +74,8 @@ private function captureAfterScenarioEvent(Event $event): void } $key = $this->getHash($event->getScenario()); - $timer = $this->scenarioTimerStore[$key]; - if ($timer instanceof Timer) { + if (isset($this->scenarioTimerStore[$key])) { + $timer = $this->scenarioTimerStore[$key]; $timer->stop(); $this->resultStore[$key] = $timer->getTime(); unset($this->scenarioTimerStore[$key]); @@ -89,8 +89,8 @@ private function captureAfterFeatureEvent(Event $event): void } $key = $this->getHash($event->getFeature()); - $timer = $this->featureTimerStore[$key]; - if ($timer instanceof Timer) { + if (isset($this->featureTimerStore[$key])) { + $timer = $this->featureTimerStore[$key]; $timer->stop(); $this->featureResultStore[$key] = $timer->getTime(); unset($this->featureTimerStore[$key]); diff --git a/src/Behat/Behat/Output/Node/Printer/JUnit/JUnitSuitePrinter.php b/src/Behat/Behat/Output/Node/Printer/JUnit/JUnitSuitePrinter.php index eb68e89d0..59c65b5ca 100644 --- a/src/Behat/Behat/Output/Node/Printer/JUnit/JUnitSuitePrinter.php +++ b/src/Behat/Behat/Output/Node/Printer/JUnit/JUnitSuitePrinter.php @@ -23,14 +23,9 @@ */ final class JUnitSuitePrinter implements SuitePrinter { - /** - * @var PhaseStatistics - */ - private $statistics; - - public function __construct(?PhaseStatistics $statistics = null) - { - $this->statistics = $statistics; + public function __construct( + private ?PhaseStatistics $statistics = null + ) { } /** diff --git a/src/Behat/Behat/Output/Node/Printer/ListPrinter.php b/src/Behat/Behat/Output/Node/Printer/ListPrinter.php index ca71a0daa..449409cc9 100644 --- a/src/Behat/Behat/Output/Node/Printer/ListPrinter.php +++ b/src/Behat/Behat/Output/Node/Printer/ListPrinter.php @@ -41,10 +41,6 @@ final class ListPrinter * @var ResultToStringConverter */ private $resultConverter; - /** - * @var ExceptionPresenter - */ - private $exceptionPresenter; /** * @var TranslatorInterface */ @@ -69,7 +65,6 @@ public function __construct( $basePath ) { $this->resultConverter = $resultConverter; - $this->exceptionPresenter = $exceptionPresenter; $this->translator = $translator; $this->basePath = $basePath; } @@ -316,7 +311,8 @@ private function getLocationFromScope(?HookScope $scope): ?string ':' . $scope->getScenario()->getLine(), $scope instanceof BeforeStepScope, $scope instanceof AfterStepScope => $this->relativizePaths($scope->getFeature()->getFile()) . - ':' . $scope->getStep()->getLine() + ':' . $scope->getStep()->getLine(), + default => null }; } return null; diff --git a/src/Behat/Behat/Output/Node/Printer/Pretty/PrettyFeaturePrinter.php b/src/Behat/Behat/Output/Node/Printer/Pretty/PrettyFeaturePrinter.php index 1a352c756..76c525349 100644 --- a/src/Behat/Behat/Output/Node/Printer/Pretty/PrettyFeaturePrinter.php +++ b/src/Behat/Behat/Output/Node/Printer/Pretty/PrettyFeaturePrinter.php @@ -50,9 +50,7 @@ public function __construct($indentation = 0, $subIndentation = 2) */ public function printHeader(Formatter $formatter, FeatureNode $feature) { - if ($feature instanceof TaggedNodeInterface) { - $this->printTags($formatter->getOutputPrinter(), $feature->getTags()); - } + $this->printTags($formatter->getOutputPrinter(), $feature->getTags()); $this->printTitle($formatter->getOutputPrinter(), $feature); $this->printDescription($formatter->getOutputPrinter(), $feature); diff --git a/src/Behat/Behat/Output/Node/Printer/Pretty/PrettyStepPrinter.php b/src/Behat/Behat/Output/Node/Printer/Pretty/PrettyStepPrinter.php index 749873871..3766b40fd 100644 --- a/src/Behat/Behat/Output/Node/Printer/Pretty/PrettyStepPrinter.php +++ b/src/Behat/Behat/Output/Node/Printer/Pretty/PrettyStepPrinter.php @@ -111,7 +111,7 @@ public function printStep(Formatter $formatter, Scenario $scenario, StepNode $st */ private function printText(OutputPrinter $printer, $stepType, $stepText, StepResult $result) { - if ($result && $result instanceof DefinedStepResult && $result->getStepDefinition()) { + if ($result instanceof DefinedStepResult && $result->getStepDefinition()) { $definition = $result->getStepDefinition(); $stepText = $this->textPainter->paintText($stepText, $definition, $result); } diff --git a/src/Behat/Behat/Output/Statistics/ScenarioStat.php b/src/Behat/Behat/Output/Statistics/ScenarioStat.php index 197172556..6fda2fa1d 100644 --- a/src/Behat/Behat/Output/Statistics/ScenarioStat.php +++ b/src/Behat/Behat/Output/Statistics/ScenarioStat.php @@ -11,6 +11,7 @@ namespace Behat\Behat\Output\Statistics; use Behat\Testwork\Tester\Result\TestResult; +use Behat\Testwork\Tester\Result\TestResults; /** * Behat scenario stat. @@ -20,7 +21,7 @@ final class ScenarioStat { /** - * @param TestResult::* $resultCode + * @param TestResult::*|TestResults::NO_TESTS $resultCode */ public function __construct( private ?string $title, @@ -53,7 +54,7 @@ public function getPath() /** * Returns scenario result code. * - * @return TestResult::* + * @return TestResult::*|TestResults::NO_TESTS */ public function getResultCode() { diff --git a/src/Behat/Behat/Tester/Result/FailedStepSearchResult.php b/src/Behat/Behat/Tester/Result/FailedStepSearchResult.php index 94fe072ec..6d162204b 100644 --- a/src/Behat/Behat/Tester/Result/FailedStepSearchResult.php +++ b/src/Behat/Behat/Tester/Result/FailedStepSearchResult.php @@ -12,6 +12,7 @@ use Behat\Behat\Definition\Exception\SearchException; use Behat\Testwork\Tester\Result\ExceptionResult; +use Throwable; /** * Represents a step test result with a failed definition search. @@ -44,7 +45,7 @@ public function hasException() } /** - * {@inheritdoc} + * @return Throwable */ public function getException() { diff --git a/src/Behat/Behat/Tester/Runtime/RuntimeFeatureTester.php b/src/Behat/Behat/Tester/Runtime/RuntimeFeatureTester.php index c6c03ddb8..970996bb4 100644 --- a/src/Behat/Behat/Tester/Runtime/RuntimeFeatureTester.php +++ b/src/Behat/Behat/Tester/Runtime/RuntimeFeatureTester.php @@ -41,10 +41,6 @@ final class RuntimeFeatureTester implements SpecificationTester * @var OutlineTester */ private $outlineTester; - /** - * @var EnvironmentManager - */ - private $envManager; /** * Initializes tester. @@ -62,7 +58,6 @@ public function __construct( ) { $this->scenarioTester = $scenarioTester; $this->outlineTester = $outlineTester; - $this->envManager = $envManager; } /** diff --git a/src/Behat/Behat/Transformation/Transformation/ReturnTypeTransformation.php b/src/Behat/Behat/Transformation/Transformation/ReturnTypeTransformation.php index 63917474c..11d275fff 100644 --- a/src/Behat/Behat/Transformation/Transformation/ReturnTypeTransformation.php +++ b/src/Behat/Behat/Transformation/Transformation/ReturnTypeTransformation.php @@ -134,11 +134,7 @@ static private function getReturnClass(ReflectionFunctionAbstract $reflection) return null; } - if ($type instanceof ReflectionNamedType) { - return $type->getName(); - } - - return (string) $type; + return $type->getName(); } /** diff --git a/src/Behat/Testwork/Call/CallCenter.php b/src/Behat/Testwork/Call/CallCenter.php index 2798acf68..24265a56c 100644 --- a/src/Behat/Testwork/Call/CallCenter.php +++ b/src/Behat/Testwork/Call/CallCenter.php @@ -169,7 +169,7 @@ private function filterResult(CallResult $result) * * @param Throwable $exception * - * @return Throwable + * @return Exception */ private function handleException($exception) { @@ -181,7 +181,7 @@ private function handleException($exception) $exception = $handler->handleException($exception); } - if ($exception instanceof Throwable) { + if (!$exception instanceof Exception) { return new FatalThrowableError($exception); } diff --git a/src/Behat/Testwork/Ordering/Cli/OrderController.php b/src/Behat/Testwork/Ordering/Cli/OrderController.php index b73487317..e2a31fb36 100644 --- a/src/Behat/Testwork/Ordering/Cli/OrderController.php +++ b/src/Behat/Testwork/Ordering/Cli/OrderController.php @@ -27,10 +27,6 @@ */ final class OrderController implements Controller { - /** - * @var EventDispatcherInterface - */ - private $eventDispatcher; /** * @var OrderedExercise */ @@ -48,7 +44,6 @@ final class OrderController implements Controller */ public function __construct(EventDispatcherInterface $eventDispatcher, OrderedExercise $exercise) { - $this->eventDispatcher = $eventDispatcher; $this->exercise = $exercise; } diff --git a/src/Behat/Testwork/Output/Printer/JUnitOutputPrinter.php b/src/Behat/Testwork/Output/Printer/JUnitOutputPrinter.php index 19428d046..81e094def 100644 --- a/src/Behat/Testwork/Output/Printer/JUnitOutputPrinter.php +++ b/src/Behat/Testwork/Output/Printer/JUnitOutputPrinter.php @@ -13,6 +13,8 @@ use Behat\Testwork\Output\Exception\MissingExtensionException; use Behat\Testwork\Output\Exception\MissingOutputPathException; use Behat\Testwork\Output\Printer\Factory\FilesystemOutputFactory; +use DOMDocument; +use DOMElement; use Symfony\Component\Console\Output\OutputInterface; /** @@ -27,22 +29,13 @@ final class JUnitOutputPrinter extends StreamOutputPrinter public const XML_VERSION = '1.0'; public const XML_ENCODING = 'UTF-8'; - /** - * @var \DOMDocument - */ - private $domDocument; - /** - * @var \DOMElement - */ - private $currentTestsuite; - /** - * @var \DOMElement - */ - private $currentTestcase; - /** - * @var \DOMElement - */ - private $testSuites; + private ?DOMDocument $domDocument = null; + + private DOMElement $currentTestsuite; + + private DOMElement $currentTestcase; + + private DOMElement $testSuites; public function __construct(FilesystemOutputFactory $outputFactory) { diff --git a/src/Behat/Testwork/ServiceContainer/Configuration/ConfigurationLoader.php b/src/Behat/Testwork/ServiceContainer/Configuration/ConfigurationLoader.php index d0a0fa560..47ceba5e2 100644 --- a/src/Behat/Testwork/ServiceContainer/Configuration/ConfigurationLoader.php +++ b/src/Behat/Testwork/ServiceContainer/Configuration/ConfigurationLoader.php @@ -190,6 +190,8 @@ protected function loadEnvironmentConfiguration() * @return array * * @throws ConfigurationLoadingException If config file is not found + * + * @phpstan-impure */ protected function loadFileConfiguration($configPath, $profile) { diff --git a/src/Behat/Testwork/ServiceContainer/ExtensionManager.php b/src/Behat/Testwork/ServiceContainer/ExtensionManager.php index ad49484c8..4388be21f 100644 --- a/src/Behat/Testwork/ServiceContainer/ExtensionManager.php +++ b/src/Behat/Testwork/ServiceContainer/ExtensionManager.php @@ -146,13 +146,9 @@ private function getFullExtensionClass($locator) /** * Initializes extension by id. * - * @param string $locator - * - * @return Extension - * * @throws ExtensionInitializationException */ - private function initialize($locator) + private function initialize(string $locator): Extension { if (isset($this->locatedExtensions[$locator])) { return $this->locatedExtensions[$locator]; @@ -167,13 +163,9 @@ private function initialize($locator) /** * Instantiates extension from its locator. * - * @param string $locator - * - * @return Extension - * * @throws ExtensionInitializationException */ - private function instantiateExtension($locator) + private function instantiateExtension(string $locator): mixed { if (class_exists($class = $locator)) { return new $class; @@ -200,12 +192,9 @@ private function instantiateExtension($locator) /** * Validates extension instance. * - * @param Extension $extension - * @param string $locator - * * @throws ExtensionInitializationException */ - private function validateExtensionInstance($extension, $locator) + private function validateExtensionInstance(mixed $extension, string $locator): void { if (null === $extension) { throw new ExtensionInitializationException(sprintf( diff --git a/src/Behat/Testwork/Specification/Locator/SpecificationLocator.php b/src/Behat/Testwork/Specification/Locator/SpecificationLocator.php index f91679c67..c6c7447e1 100644 --- a/src/Behat/Testwork/Specification/Locator/SpecificationLocator.php +++ b/src/Behat/Testwork/Specification/Locator/SpecificationLocator.php @@ -36,7 +36,7 @@ public function getLocatorExamples(); * Locates specifications and wraps them into iterator. * * @param Suite $suite - * @param string $locator + * @param string|null $locator * * @return SpecificationIterator */ diff --git a/src/Behat/Testwork/Suite/Generator/SuiteGenerator.php b/src/Behat/Testwork/Suite/Generator/SuiteGenerator.php index 5d8934683..580f54ac8 100644 --- a/src/Behat/Testwork/Suite/Generator/SuiteGenerator.php +++ b/src/Behat/Testwork/Suite/Generator/SuiteGenerator.php @@ -25,7 +25,7 @@ interface SuiteGenerator /** * Checks if generator support provided suite type and settings. * - * @param string $type + * @param string|null $type * @param array $settings * * @return bool diff --git a/src/Behat/Testwork/Suite/SuiteRegistry.php b/src/Behat/Testwork/Suite/SuiteRegistry.php index b5f90df46..1af2ad8f6 100644 --- a/src/Behat/Testwork/Suite/SuiteRegistry.php +++ b/src/Behat/Testwork/Suite/SuiteRegistry.php @@ -98,15 +98,9 @@ public function getSuites() /** * Generates suite using registered generators. * - * @param string $name - * @param string $type - * @param array $settings - * - * @return Suite - * * @throws SuiteGenerationException If no appropriate generator found */ - private function generateSuite($name, $type, array $settings) + private function generateSuite(string $name, ?string $type, array $settings): Suite { foreach ($this->generators as $generator) { if (!$generator->supportsTypeAndSettings($type, $settings)) { diff --git a/src/Behat/Testwork/Tester/Cli/ExerciseController.php b/src/Behat/Testwork/Tester/Cli/ExerciseController.php index 2fc5642e1..031387647 100644 --- a/src/Behat/Testwork/Tester/Cli/ExerciseController.php +++ b/src/Behat/Testwork/Tester/Cli/ExerciseController.php @@ -100,7 +100,7 @@ function ($locator) { } /** - * {@inheritdoc} + * @return int */ public function execute(InputInterface $input, OutputInterface $output) { From b6f6fbbf727050cdffab989e49047cee38801c14 Mon Sep 17 00:00:00 2001 From: Carlos Granados Date: Mon, 13 Jan 2025 19:19:20 +0100 Subject: [PATCH 537/567] Add deprecated information to ignored constructor parameters --- .../Behat/Definition/Printer/ConsoleDefinitionPrinter.php | 7 +------ src/Behat/Behat/Output/Node/Printer/ListPrinter.php | 8 ++------ src/Behat/Behat/Tester/Runtime/RuntimeFeatureTester.php | 8 +------- src/Behat/Testwork/Ordering/Cli/OrderController.php | 5 +---- 4 files changed, 5 insertions(+), 23 deletions(-) diff --git a/src/Behat/Behat/Definition/Printer/ConsoleDefinitionPrinter.php b/src/Behat/Behat/Definition/Printer/ConsoleDefinitionPrinter.php index b509f304a..f4a0fc4d3 100644 --- a/src/Behat/Behat/Definition/Printer/ConsoleDefinitionPrinter.php +++ b/src/Behat/Behat/Definition/Printer/ConsoleDefinitionPrinter.php @@ -39,12 +39,7 @@ abstract class ConsoleDefinitionPrinter implements DefinitionPrinter private $keywords; /** - * Initializes printer. - * - * @param OutputInterface $output - * @param PatternTransformer $patternTransformer - * @param DefinitionTranslator $translator - * @param KeywordsInterface $keywords + * @param PatternTransformer $patternTransformer deprecated, will be removed in the next major version */ public function __construct( OutputInterface $output, diff --git a/src/Behat/Behat/Output/Node/Printer/ListPrinter.php b/src/Behat/Behat/Output/Node/Printer/ListPrinter.php index 449409cc9..6156ef55f 100644 --- a/src/Behat/Behat/Output/Node/Printer/ListPrinter.php +++ b/src/Behat/Behat/Output/Node/Printer/ListPrinter.php @@ -51,12 +51,8 @@ final class ListPrinter private $basePath; /** - * Initializes printer. - * - * @param ResultToStringConverter $resultConverter - * @param ExceptionPresenter $exceptionPresenter - * @param TranslatorInterface $translator - * @param string $basePath + * @param ExceptionPresenter $exceptionPresenter deprecated , will be removed in the next major version + * @param string $basePath */ public function __construct( ResultToStringConverter $resultConverter, diff --git a/src/Behat/Behat/Tester/Runtime/RuntimeFeatureTester.php b/src/Behat/Behat/Tester/Runtime/RuntimeFeatureTester.php index 970996bb4..59f064486 100644 --- a/src/Behat/Behat/Tester/Runtime/RuntimeFeatureTester.php +++ b/src/Behat/Behat/Tester/Runtime/RuntimeFeatureTester.php @@ -43,13 +43,7 @@ final class RuntimeFeatureTester implements SpecificationTester private $outlineTester; /** - * Initializes tester. - * - * @param ScenarioTester $scenarioTester - * @param OutlineTester $outlineTester - * @param EnvironmentManager $envManager - * - * TODO: Remove EnvironmentManager parameter in next major + * @param EnvironmentManager $envManager deprecated , will be removed in the next major version */ public function __construct( ScenarioTester $scenarioTester, diff --git a/src/Behat/Testwork/Ordering/Cli/OrderController.php b/src/Behat/Testwork/Ordering/Cli/OrderController.php index e2a31fb36..2c6978b61 100644 --- a/src/Behat/Testwork/Ordering/Cli/OrderController.php +++ b/src/Behat/Testwork/Ordering/Cli/OrderController.php @@ -37,10 +37,7 @@ final class OrderController implements Controller private $orderers = array(); /** - * Initializes controller. - * - * @param EventDispatcherInterface $eventDispatcher - * @param OrderedExercise $exercise + * @param EventDispatcherInterface $eventDispatcher deprecated, will be removed in the next major version */ public function __construct(EventDispatcherInterface $eventDispatcher, OrderedExercise $exercise) { From 0d4b5b652e3692b225660e9d763add3b59b0fbb1 Mon Sep 17 00:00:00 2001 From: Carlos Granados Date: Thu, 16 Jan 2025 17:47:25 +0100 Subject: [PATCH 538/567] Changes to achieve PHPStan level 5 --- phpstan.dist.neon | 2 +- .../Context/Cli/InteractiveContextIdentifier.php | 2 +- src/Behat/Behat/Definition/Call/DefinitionCall.php | 2 ++ .../Call/Filter/ServicesResolver.php | 9 --------- .../EventListener/Statistics/StepStatsListener.php | 7 +------ .../Node/Printer/Pretty/PrettyExampleRowPrinter.php | 4 +++- .../Behat/Tester/Result/ExecutedStepResult.php | 2 +- .../Behat/Tester/Result/FailedStepSearchResult.php | 2 +- src/Behat/Behat/Tester/Result/SkippedStepResult.php | 2 +- .../Behat/Tester/Result/UndefinedStepResult.php | 2 +- .../Call/Handler/Exception/ClassNotFoundHandler.php | 1 + .../Handler/Exception/MethodNotFoundHandler.php | 1 + src/Behat/Testwork/Exception/ExceptionPresenter.php | 13 +++++++------ .../Testwork/Tester/Result/IntegerTestResult.php | 6 +++--- src/Behat/Testwork/Tester/Result/TestResult.php | 2 +- src/Behat/Testwork/Tester/Result/TestResults.php | 2 +- 16 files changed, 26 insertions(+), 33 deletions(-) diff --git a/phpstan.dist.neon b/phpstan.dist.neon index aad617b3a..5043b83ef 100644 --- a/phpstan.dist.neon +++ b/phpstan.dist.neon @@ -1,5 +1,5 @@ parameters: - level: 4 + level: 5 paths: - src ignoreErrors: diff --git a/src/Behat/Behat/Context/Cli/InteractiveContextIdentifier.php b/src/Behat/Behat/Context/Cli/InteractiveContextIdentifier.php index 08e08e4f3..44a304b7e 100644 --- a/src/Behat/Behat/Context/Cli/InteractiveContextIdentifier.php +++ b/src/Behat/Behat/Context/Cli/InteractiveContextIdentifier.php @@ -69,7 +69,7 @@ public function guessTargetContextClass(ContextEnvironment $environment) } $message = $this->translator->trans('snippet_context_choice', array('%count%' => $suiteName), 'output'); - $choices = array_values(array_merge(array('None'), $contextClasses)); + $choices = array_merge(array('None'), $contextClasses); $default = '1'; $answer = $this->askQuestion('>> ' . $message, $choices, $default); diff --git a/src/Behat/Behat/Definition/Call/DefinitionCall.php b/src/Behat/Behat/Definition/Call/DefinitionCall.php index 0c68af2b5..d50be46c8 100644 --- a/src/Behat/Behat/Definition/Call/DefinitionCall.php +++ b/src/Behat/Behat/Definition/Call/DefinitionCall.php @@ -20,6 +20,8 @@ * Enhances environment call with definition information. * * @author Konstantin Kudryashov + * + * @method Definition getCallee() */ final class DefinitionCall extends EnvironmentCall { diff --git a/src/Behat/Behat/HelperContainer/Call/Filter/ServicesResolver.php b/src/Behat/Behat/HelperContainer/Call/Filter/ServicesResolver.php index 0c70fef71..4fcfed4ed 100644 --- a/src/Behat/Behat/HelperContainer/Call/Filter/ServicesResolver.php +++ b/src/Behat/Behat/HelperContainer/Call/Filter/ServicesResolver.php @@ -152,15 +152,6 @@ private function repackageDefinitionCall(DefinitionCall $call, array $newArgumen { $definition = $call->getCallee(); - if (!$definition instanceof Definition) { - throw new UnsupportedCallException( - sprintf( - 'Something is wrong in callee associated with `%s` call.', - get_class($call) - ), $call - ); - } - return new DefinitionCall( $call->getEnvironment(), $call->getFeature(), diff --git a/src/Behat/Behat/Output/Node/EventListener/Statistics/StepStatsListener.php b/src/Behat/Behat/Output/Node/EventListener/Statistics/StepStatsListener.php index 6da219738..63c6a50d1 100644 --- a/src/Behat/Behat/Output/Node/EventListener/Statistics/StepStatsListener.php +++ b/src/Behat/Behat/Output/Node/EventListener/Statistics/StepStatsListener.php @@ -152,13 +152,8 @@ private function getStepException(StepResult $result): ?Throwable /** * Gets step path from the AFTER test event and exception. - * - * @param AfterStepTested $event - * @param null|Exception $exception - * - * @return string */ - private function getStepPath(AfterStepTested $event, ?Exception $exception = null) + private function getStepPath(AfterStepTested $event, ?Throwable $exception = null): string { $path = sprintf('%s:%d', $this->currentFeaturePath, $event->getStep()->getLine()); diff --git a/src/Behat/Behat/Output/Node/Printer/Pretty/PrettyExampleRowPrinter.php b/src/Behat/Behat/Output/Node/Printer/Pretty/PrettyExampleRowPrinter.php index 2713fc098..bf32202d5 100644 --- a/src/Behat/Behat/Output/Node/Printer/Pretty/PrettyExampleRowPrinter.php +++ b/src/Behat/Behat/Output/Node/Printer/Pretty/PrettyExampleRowPrinter.php @@ -130,7 +130,9 @@ private function getWrapperClosure(OutlineNode $outline, ExampleNode $example, a private function printStepExceptionsAndStdOut(OutputPrinter $printer, array $events) { foreach ($events as $event) { - $this->printStepStdOut($printer, $event->getTestResult()); + $stepResult = $event->getTestResult(); + assert($stepResult instanceof StepResult); + $this->printStepStdOut($printer, $stepResult); $this->printStepException($printer, $event); } } diff --git a/src/Behat/Behat/Tester/Result/ExecutedStepResult.php b/src/Behat/Behat/Tester/Result/ExecutedStepResult.php index 40633ec7d..61399807f 100644 --- a/src/Behat/Behat/Tester/Result/ExecutedStepResult.php +++ b/src/Behat/Behat/Tester/Result/ExecutedStepResult.php @@ -88,7 +88,7 @@ public function getException() } /** - * {@inheritdoc} + * @return self::PENDING | self::FAILED | self::PASSED */ public function getResultCode() { diff --git a/src/Behat/Behat/Tester/Result/FailedStepSearchResult.php b/src/Behat/Behat/Tester/Result/FailedStepSearchResult.php index 6d162204b..99a1ead6d 100644 --- a/src/Behat/Behat/Tester/Result/FailedStepSearchResult.php +++ b/src/Behat/Behat/Tester/Result/FailedStepSearchResult.php @@ -61,7 +61,7 @@ public function isPassed() } /** - * {@inheritdoc} + * @return self::FAILED */ public function getResultCode() { diff --git a/src/Behat/Behat/Tester/Result/SkippedStepResult.php b/src/Behat/Behat/Tester/Result/SkippedStepResult.php index 4788d247f..95b44a73d 100644 --- a/src/Behat/Behat/Tester/Result/SkippedStepResult.php +++ b/src/Behat/Behat/Tester/Result/SkippedStepResult.php @@ -61,7 +61,7 @@ public function isPassed() } /** - * {@inheritdoc} + * @return self::SKIPPED */ public function getResultCode() { diff --git a/src/Behat/Behat/Tester/Result/UndefinedStepResult.php b/src/Behat/Behat/Tester/Result/UndefinedStepResult.php index 1268cb798..2257fb06f 100644 --- a/src/Behat/Behat/Tester/Result/UndefinedStepResult.php +++ b/src/Behat/Behat/Tester/Result/UndefinedStepResult.php @@ -26,7 +26,7 @@ public function isPassed() } /** - * {@inheritdoc} + * @return self::UNDEFINED */ public function getResultCode() { diff --git a/src/Behat/Testwork/Call/Handler/Exception/ClassNotFoundHandler.php b/src/Behat/Testwork/Call/Handler/Exception/ClassNotFoundHandler.php index 6ddeee21e..3154ea7a4 100644 --- a/src/Behat/Testwork/Call/Handler/Exception/ClassNotFoundHandler.php +++ b/src/Behat/Testwork/Call/Handler/Exception/ClassNotFoundHandler.php @@ -41,6 +41,7 @@ final public function supportsException($exception) */ final public function handleException($exception) { + assert($exception instanceof Error); $this->handleNonExistentClass($this->extractNonExistentClass($exception)); return $exception; diff --git a/src/Behat/Testwork/Call/Handler/Exception/MethodNotFoundHandler.php b/src/Behat/Testwork/Call/Handler/Exception/MethodNotFoundHandler.php index f35890999..2e3d07331 100644 --- a/src/Behat/Testwork/Call/Handler/Exception/MethodNotFoundHandler.php +++ b/src/Behat/Testwork/Call/Handler/Exception/MethodNotFoundHandler.php @@ -41,6 +41,7 @@ final public function supportsException($exception) */ final public function handleException($exception) { + assert($exception instanceof Error); $this->handleNonExistentMethod($this->extractNonExistentCallable($exception)); return $exception; diff --git a/src/Behat/Testwork/Exception/ExceptionPresenter.php b/src/Behat/Testwork/Exception/ExceptionPresenter.php index 9ad0d14c2..a633dd1cb 100644 --- a/src/Behat/Testwork/Exception/ExceptionPresenter.php +++ b/src/Behat/Testwork/Exception/ExceptionPresenter.php @@ -10,10 +10,12 @@ namespace Behat\Testwork\Exception; +use Behat\Testwork\Call\Exception\FatalThrowableError; use Behat\Testwork\Exception\Stringer\ExceptionStringer; use Behat\Testwork\Output\Printer\OutputPrinter; use Exception; use Symfony\Component\Console\Output\OutputInterface; +use Throwable; /** * Presents exceptions as strings using registered stringers. @@ -78,16 +80,15 @@ public function setDefaultVerbosity($defaultVerbosity) /** * Presents exception as a string. - * - * @param Exception $exception - * @param integer $verbosity - * - * @return string */ - public function presentException(Exception $exception, $verbosity = null) + public function presentException(Throwable $exception, ?int $verbosity = null): string { $verbosity = $verbosity ?: $this->defaultVerbosity; + if (!$exception instanceof Exception) { + $exception = new FatalThrowableError($exception); + } + foreach ($this->stringers as $stringer) { if ($stringer->supportsException($exception)) { return $this->relativizePaths($stringer->stringException($exception, $verbosity)); diff --git a/src/Behat/Testwork/Tester/Result/IntegerTestResult.php b/src/Behat/Testwork/Tester/Result/IntegerTestResult.php index 8dad2fc59..2af944ef9 100644 --- a/src/Behat/Testwork/Tester/Result/IntegerTestResult.php +++ b/src/Behat/Testwork/Tester/Result/IntegerTestResult.php @@ -18,14 +18,14 @@ final class IntegerTestResult implements TestResult { /** - * @var integer + * @var TestResult::* */ private $resultCode; /** * Initializes test result. * - * @param integer $resultCode + * @param TestResult::* $resultCode */ public function __construct($resultCode) { @@ -41,7 +41,7 @@ public function isPassed() } /** - * {@inheritdoc} + * @return TestResult::* */ public function getResultCode() { diff --git a/src/Behat/Testwork/Tester/Result/TestResult.php b/src/Behat/Testwork/Tester/Result/TestResult.php index e4c0d6565..d53c6f868 100644 --- a/src/Behat/Testwork/Tester/Result/TestResult.php +++ b/src/Behat/Testwork/Tester/Result/TestResult.php @@ -33,7 +33,7 @@ public function isPassed(); /** * Returns tester result code. * - * @return integer + * @return TestResult::*|TestResults::NO_TESTS */ public function getResultCode(); } diff --git a/src/Behat/Testwork/Tester/Result/TestResults.php b/src/Behat/Testwork/Tester/Result/TestResults.php index 2929b130f..9d6f0516d 100644 --- a/src/Behat/Testwork/Tester/Result/TestResults.php +++ b/src/Behat/Testwork/Tester/Result/TestResults.php @@ -49,7 +49,7 @@ public function isPassed() } /** - * {@inheritdoc} + * @return TestResult::*|TestResults::NO_TESTS */ public function getResultCode() { From 44309087d64182efcb9724976b4527aacbba70b6 Mon Sep 17 00:00:00 2001 From: Carlos Granados Date: Fri, 20 Dec 2024 11:46:39 +0100 Subject: [PATCH 539/567] chore: remove Psalm --- .github/workflows/build.yml | 6 +---- composer.json | 7 ++--- psalm.xml | 26 ------------------- .../InitializedContextEnvironment.php | 9 +++---- src/Behat/Testwork/Call/CallResult.php | 4 +-- .../EventDispatcher/Cli/SigintController.php | 3 --- 6 files changed, 8 insertions(+), 47 deletions(-) delete mode 100644 psalm.xml diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index c2aef45a0..280e892ce 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -95,8 +95,7 @@ jobs: strategy: fail-fast: false matrix: - #runs on the lowest and highest supported versions (change this to 8.4 once psalm supports it) - php: [8.1, 8.3] + php: [8.1, 8.4] steps: - uses: actions/checkout@v4 @@ -110,9 +109,6 @@ jobs: - name: Install dependencies run: composer update - - name: Run Psalm - run: ./vendor/bin/psalm --output-format=github --php-version=${{ matrix.php }} - - name: Run PHPStan run: ./vendor/bin/phpstan diff --git a/composer.json b/composer.json index 036d9df5f..3f367adea 100644 --- a/composer.json +++ b/composer.json @@ -34,8 +34,7 @@ "phpunit/phpunit": "^9.6", "sebastian/diff": "^4.0", "symfony/polyfill-php84": "^1.31", - "symfony/process": "^5.4 || ^6.4 || ^7.0", - "vimeo/psalm": "^5.0" + "symfony/process": "^5.4 || ^6.4 || ^7.0" }, "suggest": { @@ -69,14 +68,12 @@ "all-tests": [ "@behat-progress", "@phpunit", - "@psalm", "@phpstan" ], "behat": "LANG=C bin/behat --rerun", "behat-progress": "LANG=C bin/behat --format=progress", "phpstan": "phpstan", - "phpunit": "phpunit", - "psalm": "psalm" + "phpunit": "phpunit" }, "bin": ["bin/behat"] diff --git a/psalm.xml b/psalm.xml deleted file mode 100644 index 2455fe573..000000000 --- a/psalm.xml +++ /dev/null @@ -1,26 +0,0 @@ - - diff --git a/src/Behat/Behat/Context/Environment/InitializedContextEnvironment.php b/src/Behat/Behat/Context/Environment/InitializedContextEnvironment.php index 39a0b00d9..bc01d79cf 100644 --- a/src/Behat/Behat/Context/Environment/InitializedContextEnvironment.php +++ b/src/Behat/Behat/Context/Environment/InitializedContextEnvironment.php @@ -24,6 +24,8 @@ * @see ContextEnvironmentHandler * * @author Konstantin Kudryashov - - - - - - - - - - - - - - - - + * + * @template T of Context */ final class InitializedContextEnvironment implements ContextEnvironment, ServiceContainerEnvironment { @@ -35,8 +37,7 @@ final class InitializedContextEnvironment implements ContextEnvironment, Service private ?ContainerInterface $serviceContainer = null; /** - * @var array, Context> - * @psalm-var class-string-map + * @var array, T> */ private $contexts = array(); @@ -86,7 +87,6 @@ public function hasContexts() /** * {@inheritdoc} - * @psalm-suppress InvalidReturnStatement, InvalidReturnType */ public function getContextClasses() { @@ -105,7 +105,6 @@ public function hasContextClass($class) * Returns list of registered context instances. * * @return list - * @psalm-suppress InvalidReturnStatement, InvalidReturnType */ public function getContexts() { @@ -115,8 +114,6 @@ public function getContexts() /** * Returns registered context by its class name. * - * @template T of Context - * * @param class-string $class * * @return T diff --git a/src/Behat/Testwork/Call/CallResult.php b/src/Behat/Testwork/Call/CallResult.php index 15f7ee36c..a8c50e028 100644 --- a/src/Behat/Testwork/Call/CallResult.php +++ b/src/Behat/Testwork/Call/CallResult.php @@ -75,8 +75,8 @@ public function getReturn() /** * Check if call thrown exception. * - * @psalm-assert-if-true Exception $this->exception - * @psalm-assert-if-true Exception $this->getException() + * @phpstan-assert-if-true Exception $this->exception + * @phpstan-assert-if-true Exception $this->getException() * * @return bool */ diff --git a/src/Behat/Testwork/EventDispatcher/Cli/SigintController.php b/src/Behat/Testwork/EventDispatcher/Cli/SigintController.php index f0f0539b7..2149e00d8 100644 --- a/src/Behat/Testwork/EventDispatcher/Cli/SigintController.php +++ b/src/Behat/Testwork/EventDispatcher/Cli/SigintController.php @@ -53,9 +53,6 @@ public function execute(InputInterface $input, OutputInterface $output) if (function_exists('pcntl_signal')) { pcntl_async_signals(true); - /** - * @psalm-suppress UndefinedConstant (SIGINT is defined in pcntl) - */ pcntl_signal(SIGINT, array($this, 'abortExercise')); } return null; From fc89bea66a0507cb3415dfa67a11af9a63ed82a9 Mon Sep 17 00:00:00 2001 From: Christophe Coevoet Date: Wed, 22 Jan 2025 13:58:59 +0100 Subject: [PATCH 540/567] Fix types for InitializedContextEnvironment This class has no reason to become generic. And its `getContext` method must keep using a method-level generic type. --- .../Context/Environment/InitializedContextEnvironment.php | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/src/Behat/Behat/Context/Environment/InitializedContextEnvironment.php b/src/Behat/Behat/Context/Environment/InitializedContextEnvironment.php index bc01d79cf..d4d6b2d29 100644 --- a/src/Behat/Behat/Context/Environment/InitializedContextEnvironment.php +++ b/src/Behat/Behat/Context/Environment/InitializedContextEnvironment.php @@ -24,8 +24,6 @@ * @see ContextEnvironmentHandler * * @author Konstantin Kudryashov - * - * @template T of Context */ final class InitializedContextEnvironment implements ContextEnvironment, ServiceContainerEnvironment { @@ -37,7 +35,9 @@ final class InitializedContextEnvironment implements ContextEnvironment, Service private ?ContainerInterface $serviceContainer = null; /** - * @var array, T> + * @var array, Context> + * + * TODO use a class-string-map type to have an accurate type once https://github.com/phpstan/phpstan/issues/9521 is implemented */ private $contexts = array(); @@ -114,6 +114,8 @@ public function getContexts() /** * Returns registered context by its class name. * + * @template T of Context + * * @param class-string $class * * @return T From 24483d9c0e5ff3b2fe68dc2b015da30a93c95b9c Mon Sep 17 00:00:00 2001 From: Carlos Granados Date: Fri, 17 Jan 2025 15:28:45 +0100 Subject: [PATCH 541/567] DX: Use real files instead of generated files in local tests --- features/bootstrap/FeatureContext.php | 96 ++- features/junit_format.feature | 591 +++--------------- tests/Fixtures/JunitFormat/behat.php | 40 ++ .../features/abort_on_php_error.feature | 11 + .../features/bootstrap/FeatureContext.php | 43 ++ .../features/multiline_titles.feature | 20 + .../features/multiple_features_1.feature | 9 + .../features/multiple_features_2.feature | 9 + .../features/multiple_suites_1.feature | 11 + .../features/multiple_suites_2.feature | 11 + .../features/single_feature.feature | 44 ++ .../features/skipped_test_cases.feature | 16 + .../features/stop_on_failure.feature | 11 + tests/Fixtures/JunitFormat/two_suites.php | 28 + 14 files changed, 435 insertions(+), 505 deletions(-) create mode 100644 tests/Fixtures/JunitFormat/behat.php create mode 100644 tests/Fixtures/JunitFormat/features/abort_on_php_error.feature create mode 100644 tests/Fixtures/JunitFormat/features/bootstrap/FeatureContext.php create mode 100644 tests/Fixtures/JunitFormat/features/multiline_titles.feature create mode 100644 tests/Fixtures/JunitFormat/features/multiple_features_1.feature create mode 100644 tests/Fixtures/JunitFormat/features/multiple_features_2.feature create mode 100644 tests/Fixtures/JunitFormat/features/multiple_suites_1.feature create mode 100644 tests/Fixtures/JunitFormat/features/multiple_suites_2.feature create mode 100644 tests/Fixtures/JunitFormat/features/single_feature.feature create mode 100644 tests/Fixtures/JunitFormat/features/skipped_test_cases.feature create mode 100644 tests/Fixtures/JunitFormat/features/stop_on_failure.feature create mode 100644 tests/Fixtures/JunitFormat/two_suites.php diff --git a/features/bootstrap/FeatureContext.php b/features/bootstrap/FeatureContext.php index 1dd889045..23eb9c860 100644 --- a/features/bootstrap/FeatureContext.php +++ b/features/bootstrap/FeatureContext.php @@ -9,8 +9,10 @@ */ use Behat\Behat\Context\Context; -use Behat\Behat\Output\Node\EventListener\JUnit\JUnitDurationListener; use Behat\Gherkin\Node\PyStringNode; +use Behat\Gherkin\Node\TableNode; +use Behat\Step\Given; +use Behat\Step\When; use PHPUnit\Framework\Assert; use Symfony\Component\Process\PhpExecutableFinder; use Symfony\Component\Process\Process; @@ -36,6 +38,10 @@ class FeatureContext implements Context * @var string */ private $workingDir; + /** + * @var string + */ + private $tempDir; /** * @var string */ @@ -49,6 +55,8 @@ class FeatureContext implements Context */ private $answerString; + private bool $workingDirChanged = false; + /** * Cleans test folders in the temporary directory. * @@ -73,13 +81,13 @@ public function prepareTestFolders() md5(microtime() . rand(0, 10000)); mkdir($dir . '/features/bootstrap/i18n', 0777, true); - mkdir($dir . '/junit'); $phpFinder = new PhpExecutableFinder(); if (false === $php = $phpFinder->find()) { throw new \RuntimeException('Unable to find the PHP executable.'); } $this->workingDir = $dir; + $this->tempDir = $dir; $this->phpBin = $php; } @@ -191,6 +199,33 @@ public function iSetBehatParamsEnvironmentVariable(PyStringNode $value) $this->env = array('BEHAT_PARAMS' => (string) $value); } + /** + * @When I set the working directory to the :dir fixtures folder + */ + public function iSetTheWorkingDirectoryToTheFixturesFolder($dir): void + { + $basePath = dirname(__DIR__, 2) . '/tests/Fixtures/'; + $dir = $basePath . $dir; + if (!is_dir($dir)) { + throw new RuntimeException(sprintf('The directory "%s" does not exist', $dir)); + } + $this->workingDir = $dir; ; + $this->workingDirChanged = true; + } + + #[Given('I provide the following options for all behat invocations:')] + public function iProvideTheFollowingOptionsForAllBehatInvocations(TableNode $table): void + { + $this->addBehatOptions($table); + } + + #[When('I run behat with the following additional options:')] + public function iRunBehatWithTheFollowingAdditionalOptions(TableNode $table): void + { + $this->addBehatOptions($table); + $this->iRunBehat(); + } + /** * Runs behat command with provided parameters * @@ -333,7 +368,7 @@ public function fileShouldContain($path, PyStringNode $text) /** * Checks whether specified content and structure of the xml is correct without worrying about layout. * - * @Then /^"([^"]*)" file xml should be like:$/ + * @Then /^(?:the\s)?"([^"]*)" file xml should be like:$/ * * @param string $path file path * @param PyStringNode $text file content @@ -341,6 +376,20 @@ public function fileShouldContain($path, PyStringNode $text) public function fileXmlShouldBeLike($path, PyStringNode $text) { $path = $this->workingDir . '/' . $path; + $this->checkXmlFileContents($path, $text); + } + + /** + * @Then the temp :path file xml should be like: + */ + public function theTempFileFileXmlShouldBeLike($path, PyStringNode $text): void + { + $path = $this->tempDir . '/' . $path; + $this->checkXmlFileContents($path, $text); + } + + private function checkXmlFileContents($path, PyStringNode $text) + { Assert::assertFileExists($path); $fileContent = trim(file_get_contents($path)); @@ -357,7 +406,6 @@ public function fileXmlShouldBeLike($path, PyStringNode $text) Assert::assertEquals(trim($dom->saveXML(null, LIBXML_NOEMPTYTAG)), $fileContent); } - /** * Checks whether last command output contains provided string. * @@ -443,9 +491,24 @@ public function itShouldPassOrFail($success) * @param string $schemaPath relative to features/bootstrap/schema */ public function xmlShouldBeValid($xmlFile, $schemaPath) + { + $path = $this->workingDir . '/' . $xmlFile; + $this->checkXmlIsValid($path, $schemaPath); + } + + /** + * @Then the temp file :xmlFile should be a valid document according to :schemaPath + */ + public function theTempFileShouldBeAValidDocumentAccordingTo($xmlFile, $schemaPath): void + { + $path = $this->tempDir . '/' . $xmlFile; + $this->checkXmlIsValid($path, $schemaPath); + } + + private function checkXmlIsValid(string $xmlFile, string $schemaPath): void { $dom = new DomDocument(); - $dom->load($this->workingDir . '/' . $xmlFile); + $dom->load($xmlFile); $dom->schemaValidate(__DIR__ . '/schema/' . $schemaPath); } @@ -479,6 +542,9 @@ private function getOutput() private function createFile($filename, $content) { + if ($this->workingDirChanged) { + throw new RuntimeException('Trying to write a file in a fixtures folder'); + } $path = dirname($filename); $this->createDirectory($path); @@ -501,7 +567,7 @@ private function moveToNewPath($path) $this->workingDir = $newWorkingDir; } - + /** * @param 'fail'|'pass' $success */ @@ -516,7 +582,7 @@ private function exitCodeIsCorrect(string $success): bool private function getOutputDiff(PyStringNode $expectedText): string { $differ = new Differ(new DiffOnlyOutputBuilder()); - + return $differ->diff($this->getExpectedOutput($expectedText), $this->getOutput()); } @@ -534,7 +600,21 @@ private static function clearDirectory($path) unlink($file); } } + } - rmdir($path); + private function addBehatOptions(TableNode $table): void + { + $rows = $table->getHash(); + foreach ($rows as $row) { + $option = $row['option']; + $value = $row['value']; + if ($value !== '') { + if ($value === '{SYSTEM_TMP_DIR}') { + $value = $this->tempDir; + } + $option .= '=' . $value; + } + $this->options .= ' ' . $option; + } } } diff --git a/features/junit_format.feature b/features/junit_format.feature index b29251b09..8568624a0 100644 --- a/features/junit_format.feature +++ b/features/junit_format.feature @@ -1,88 +1,22 @@ Feature: JUnit Formatter - In order integrate with other development tools + In order to integrate with other development tools As a developer I need to be able to generate a JUnit-compatible report - Scenario: Normal Scenario's - Given a file named "features/bootstrap/FeatureContext.php" with: - """ - value = $num; - } - - #[Then('/I must have (\d+)/')] - public function iMustHave($num) { - PHPUnit\Framework\Assert::assertEquals($num, $this->value); - } - - #[When('/I add (\d+)/')] - public function iAdd($num) { - $this->value += $num; - } - - #[When('/^Something not done yet$/')] - public function somethingNotDoneYet() { - throw new PendingException(); - } - } - """ - And a file named "features/World.feature" with: - """ - Feature: World consistency - In order to maintain stable behaviors - As a features developer - I want, that "World" flushes between scenarios - - Background: - Given I have entered 10 - - Scenario: Undefined - Then I must have 10 - And Something new - Then I must have 10 - - Scenario: Pending - Then I must have 10 - And Something not done yet - Then I must have 10 - - Scenario: Failed - When I add 4 - Then I must have 13 - - Scenario Outline: Passed & Failed - When I add - Then I must have - - Examples: - | value | result | - | 5 | 16 | - | 10 | 20 | - | 23 | 32 | - - Scenario Outline: Another Outline - When I add - Then I must have - - Examples: - | value | result | - | 5 | 15 | - | 10 | 20 | - """ - When I run "behat --no-colors -f junit -o junit --snippets-for=FeatureContext --snippets-type=regex" + Background: + Given I set the working directory to the "JunitFormat" fixtures folder + And I provide the following options for all behat invocations: + | option | value | + | --no-colors | | + | --snippets-type | regex | + | --format | junit | + | --out | {SYSTEM_TMP_DIR} | + + Scenario: Run a single feature + When I run behat with the following additional options: + | option | value | + | --snippets-for | FeatureContext | + | --suite | single_feature | Then it should fail with: """ --- FeatureContext has missing steps. Define them with these snippets: @@ -93,491 +27,154 @@ throw new PendingException(); } """ - And "junit/default.xml" file xml should be like: + And the temp "single_feature.xml" file xml should be like: """ - - - + """ - And the file "junit/default.xml" should be a valid document according to "junit.xsd" - - Scenario: Multiple Features - Given a file named "features/bootstrap/FeatureContext.php" with: - """ - value = $num; - } - - #[Then('/I must have (\d+)/')] - public function iMustHave($num) { - PHPUnit\Framework\Assert::assertEquals($num, $this->value); - } - - #[When('/I add (\d+)/')] - public function iAdd($num) { - $this->value += $num; - } - } - """ - And a file named "features/adding_feature_1.feature" with: - """ - Feature: Adding Feature 1 - In order to add number together - As a mathematician - I want, something that acts like a calculator + And the temp file "single_feature.xml" should be a valid document according to "junit.xsd" - Scenario: Adding 4 to 10 - Given I have entered 10 - When I add 4 - Then I must have 14 - """ - And a file named "features/adding_feature_2.feature" with: - """ - Feature: Adding Feature 2 - In order to add number together - As a mathematician - I want, something that acts like a calculator - - Scenario: Adding 8 to 10 - Given I have entered 10 - When I add 8 - Then I must have 18 - """ - When I run "behat --no-colors -f junit -o junit" - And "junit/default.xml" file xml should be like: + Scenario: Run multiple Features + When I run behat with the following additional options: + | option | value | + | --suite | multiple_features | + Then it should pass with no output + And the temp "multiple_features.xml" file xml should be like: """ - + + + - + - + - + - - + + - - + + + """ - And the file "junit/default.xml" should be a valid document according to "junit.xsd" - - Scenario: Multiline titles - Given a file named "features/bootstrap/FeatureContext.php" with: - """ - value = $num; - } - - #[Then('/I must have (\d+)/')] - public function iMustHave($num) { - PHPUnit\Framework\Assert::assertEquals($num, $this->value); - } - - #[When('/I (add|subtract) the value (\d+)/')] - public function iAddOrSubstact($op, $num) { - if ($op == 'add') - $this->value += $num; - elseif ($op == 'subtract') - $this->value -= $num; - } - } - """ - And a file named "features/World.feature" with: - """ - Feature: World consistency - In order to maintain stable behaviors - As a features developer - I want, that "World" flushes between scenarios - - Background: - Given I have entered 10 - - Scenario: Adding some interesting - value - Then I must have 10 - And I add the value 6 - Then I must have 16 + And the temp file "multiple_features.xml" should be a valid document according to "junit.xsd" - Scenario: Subtracting - some - value - Then I must have 10 - And I subtract the value 6 - Then I must have 4 - """ - When I run "behat --no-colors -f junit -o junit" + Scenario: Confirm multiline scenario titles are printed correctly + When I run behat with the following additional options: + | option | value | + | --suite | multiline_titles | Then it should pass with no output - And "junit/default.xml" file xml should be like: + And the temp "multiline_titles.xml" file xml should be like: """ - - + - + - - - + """ - And the file "junit/default.xml" should be a valid document according to "junit.xsd" + And the temp file "multiline_titles.xml" should be a valid document according to "junit.xsd" Scenario: Multiple suites - Given a file named "features/bootstrap/SmallKidContext.php" with: - """ - strongLevel = 0; - } - - #[When('/I eat an apple/')] - public function iEatAnApple() { - $this->strongLevel += 2; - } - - #[Then('/I will be stronger/')] - public function iWillBeStronger() { - PHPUnit\Framework\Assert::assertNotEquals(0, $this->strongLevel); - } - } - """ - And a file named "features/bootstrap/OldManContext.php" with: - """ - strongLevel = 0; - } - - #[When('/I eat an apple/')] - public function iEatAnApple() { } - - #[Then('/I will be stronger/')] - public function iWillBeStronger() { - PHPUnit\Framework\Assert::assertNotEquals(0, $this->strongLevel); - } - } - """ - And a file named "features/apple_eating_smallkid.feature" with: - """ - Feature: Apple Eating - In order to be stronger - As a small kid - I want to get stronger from eating apples - - Background: - Given I am not strong - - Scenario: Eating one apple - When I eat an apple - Then I will be stronger - """ - And a file named "features/apple_eating_oldmen.feature" with: - """ - Feature: Apple Eating - In order to be stronger - As an old man - I want to get stronger from eating apples - - Background: - Given I am not strong - - Scenario: Eating one apple - When I eat an apple - Then I will be stronger - """ - And a file named "behat.yml" with: - """ - default: - suites: - small_kid: - contexts: [SmallKidContext] - filters: - role: small kid - path: '%paths.base%/features' - old_man: - contexts: [OldManContext] - path: '%paths.base%/features' - filters: - role: old man - """ - When I run "behat --no-colors -f junit -o junit" + When I run behat with the following additional options: + | option | value | + | --config | two_suites.php | Then it should fail with no output - And "junit/small_kid.xml" file xml should be like: + And the temp "small_kid.xml" file xml should be like: """ """ - And the file "junit/small_kid.xml" should be a valid document according to "junit.xsd" - And "junit/old_man.xml" file xml should be like: + And the temp file "small_kid.xml" should be a valid document according to "junit.xsd" + And the temp "old_man.xml" file xml should be like: """ """ - And the file "junit/old_man.xml" should be a valid document according to "junit.xsd" + And the temp file "old_man.xml" should be a valid document according to "junit.xsd" Scenario: Report skipped testcases - Given a file named "features/bootstrap/FeatureContext.php" with: - """ - - + + + - - + + - - - + + + - - - + """ - And the file "junit/default.xml" should be a valid document according to "junit.xsd" + And the temp file "skipped_test_cases.xml" should be a valid document according to "junit.xsd" Scenario: Stop on Failure - Given a file named "features/bootstrap/FeatureContext.php" with: - """ - value = $num; - } - - #[Then('/I must have (\d+)/')] - public function iMustHave($num) { - PHPUnit\Framework\Assert::assertEquals($num, $this->value); - } - - #[When('/I add (\d+)/')] - public function iAdd($num) { - $this->value += $num; - } - } - """ - And a file named "features/World.feature" with: - """ - Feature: World consistency - In order to maintain stable behaviors - As a features developer - I want, that "World" flushes between scenarios - - Background: - Given I have entered 10 - - Scenario: Failed - When I add 4 - Then I must have 13 - """ - When I run "behat --no-colors -f junit -o junit" + When I run behat with the following additional options: + | option | value | + | --suite | stop_on_failure | Then it should fail with no output - And "junit/default.xml" file xml should be like: + And the temp "stop_on_failure.xml" file xml should be like: """ - + + - + - + + - - + """ - And the file "junit/default.xml" should be a valid document according to "junit.xsd" - - Scenario: Aborting due to PHP error - Given a file named "features/bootstrap/FeatureContext.php" with: - """ - value = $num; - } - - #[Then('/I must have (\d+)/')] - public function iMustHave($num) { - $foo = new class extends Foo implements Foo {}; - } - - #[When('/I add (\d+)/')] - public function iAdd($num) { - $this->value += $num; - } - } - """ - And a file named "features/World.feature" with: - """ - Feature: World consistency - In order to maintain stable behaviors - As a features developer - I want, that "World" flushes between scenarios - Background: - Given I have entered 10 - Scenario: Failed - When I add 4 - Then I must have 14 - """ - When I run "behat --no-colors -f junit -o junit" - Then it should fail with: - """ - cannot implement Foo - it is not an interface - """ - And "junit/default.xml" file xml should be like: - """ - - + + - """ + Scenario: Aborting due to PHP error + When I run behat with the following additional options: + | option | value | + | --suite | abort_on_php_error | + Then it should fail with: + """ + cannot extend interface Behat\Behat\Context\Context + """ + And the temp "abort_on_php_error.xml" file xml should be like: + """ + + + """ Scenario: Aborting due invalid output path - Given a file named "features/bootstrap/FeatureContext.php" with: - """ - withProfile((new Profile('default')) + ->withSuite((new Suite('single_feature')) + ->withPaths( + 'features/single_feature.feature' + ) + ) + ->withSuite((new Suite('multiple_features')) + ->withPaths( + 'features/multiple_features_1.feature', + 'features/multiple_features_2.feature' + ) + ) + ->withSuite((new Suite('multiline_titles')) + ->withPaths( + 'features/multiline_titles.feature' + ) + ) + ->withSuite((new Suite('skipped_test_cases')) + ->withPaths( + 'features/skipped_test_cases.feature' + ) + ) + ->withSuite((new Suite('stop_on_failure')) + ->withPaths( + 'features/stop_on_failure.feature' + ) + ) + ->withSuite((new Suite('abort_on_php_error')) + ->withPaths( + 'features/abort_on_php_error.feature' + ) + ) + ); diff --git a/tests/Fixtures/JunitFormat/features/abort_on_php_error.feature b/tests/Fixtures/JunitFormat/features/abort_on_php_error.feature new file mode 100644 index 000000000..d6741e5aa --- /dev/null +++ b/tests/Fixtures/JunitFormat/features/abort_on_php_error.feature @@ -0,0 +1,11 @@ +Feature: Abort on PHP error + In order to see correct information + As a features developer + I want to see the right output in JUnit when I abort due to a PHP error + + Background: + Given I have entered 10 + + Scenario: Failed + When I have a PHP error + Then I must have 14 diff --git a/tests/Fixtures/JunitFormat/features/bootstrap/FeatureContext.php b/tests/Fixtures/JunitFormat/features/bootstrap/FeatureContext.php new file mode 100644 index 000000000..a4c8b33ec --- /dev/null +++ b/tests/Fixtures/JunitFormat/features/bootstrap/FeatureContext.php @@ -0,0 +1,43 @@ +value = $num; + } + + #[When('/I add (\d+)/')] + public function iAdd($num) { + $this->value += $num; + } + + #[When('/^Something not done yet$/')] + public function somethingNotDoneYet() { + throw new PendingException(); + } + + #[Then('/I must have (\d+)/')] + public function iMustHave($num) { + PHPUnit\Framework\Assert::assertEquals($num, $this->value); + } + + #[BeforeScenario('@setup-error')] + public function setup() { + throw new Exception('This scenario has a failed setup'); + } + + #[When('/^I have a PHP error$/')] + public function iHaveAPHPError() { + $foo = new class extends Context {}; + } +} diff --git a/tests/Fixtures/JunitFormat/features/multiline_titles.feature b/tests/Fixtures/JunitFormat/features/multiline_titles.feature new file mode 100644 index 000000000..0b613af38 --- /dev/null +++ b/tests/Fixtures/JunitFormat/features/multiline_titles.feature @@ -0,0 +1,20 @@ +Feature: Use multiline titles + In order to keep all information + As a features developer + I want that the full text of multiline titles is kept in JUnit reports + + Background: + Given I have entered 10 + + Scenario: Adding some interesting + value + Then I must have 10 + And I add 6 + Then I must have 16 + + Scenario: Adding + another + value + Then I must have 10 + And I add 8 + Then I must have 18 diff --git a/tests/Fixtures/JunitFormat/features/multiple_features_1.feature b/tests/Fixtures/JunitFormat/features/multiple_features_1.feature new file mode 100644 index 000000000..00eaa863c --- /dev/null +++ b/tests/Fixtures/JunitFormat/features/multiple_features_1.feature @@ -0,0 +1,9 @@ +Feature: Adding Feature 1 + In order to add numbers together + As a mathematician + I want something that acts like a calculator + + Scenario: Adding 4 to 10 + Given I have entered 10 + When I add 4 + Then I must have 14 diff --git a/tests/Fixtures/JunitFormat/features/multiple_features_2.feature b/tests/Fixtures/JunitFormat/features/multiple_features_2.feature new file mode 100644 index 000000000..9a4976adc --- /dev/null +++ b/tests/Fixtures/JunitFormat/features/multiple_features_2.feature @@ -0,0 +1,9 @@ +Feature: Adding Feature 2 + In order to add numbers together + As a mathematician + I want something that acts like a calculator + + Scenario: Adding 8 to 10 + Given I have entered 10 + When I add 8 + Then I must have 18 diff --git a/tests/Fixtures/JunitFormat/features/multiple_suites_1.feature b/tests/Fixtures/JunitFormat/features/multiple_suites_1.feature new file mode 100644 index 000000000..e43ed0600 --- /dev/null +++ b/tests/Fixtures/JunitFormat/features/multiple_suites_1.feature @@ -0,0 +1,11 @@ +Feature: Adding easy numbers + In order to add numbers together + As a small kid + I want something that acts like a calculator for easy sums + + Background: + Given I have entered 1 + + Scenario: Easy sum + When I add 2 + Then I must have 3 diff --git a/tests/Fixtures/JunitFormat/features/multiple_suites_2.feature b/tests/Fixtures/JunitFormat/features/multiple_suites_2.feature new file mode 100644 index 000000000..661b56b56 --- /dev/null +++ b/tests/Fixtures/JunitFormat/features/multiple_suites_2.feature @@ -0,0 +1,11 @@ +Feature: Adding difficult numbers + In order to add numbers together + As an old man + I want something that acts like a calculator for difficult sums + + Background: + Given I have entered 131 + + Scenario: Difficult sum + When I add 247 + Then I must have 477 diff --git a/tests/Fixtures/JunitFormat/features/single_feature.feature b/tests/Fixtures/JunitFormat/features/single_feature.feature new file mode 100644 index 000000000..2624f21e0 --- /dev/null +++ b/tests/Fixtures/JunitFormat/features/single_feature.feature @@ -0,0 +1,44 @@ +Feature: Adding numbers + In order to add numbers together + As a mathematician + I want something that acts like a calculator + + Background: + Given I have entered 10 + + Scenario: Passed + When I add 4 + Then I must have 14 + + Scenario: Undefined + Then I must have 10 + And Something new + Then I must have 10 + + Scenario: Pending + Then I must have 10 + And Something not done yet + Then I must have 10 + + Scenario: Failed + When I add 4 + Then I must have 13 + + Scenario Outline: Passed & Failed + When I add + Then I must have + + Examples: + | value | result | + | 5 | 16 | + | 10 | 20 | + | 23 | 32 | + + Scenario Outline: Another Outline + When I add + Then I must have + + Examples: + | value | result | + | 5 | 15 | + | 10 | 20 | diff --git a/tests/Fixtures/JunitFormat/features/skipped_test_cases.feature b/tests/Fixtures/JunitFormat/features/skipped_test_cases.feature new file mode 100644 index 000000000..fb914c776 --- /dev/null +++ b/tests/Fixtures/JunitFormat/features/skipped_test_cases.feature @@ -0,0 +1,16 @@ +Feature: Skipped test cases + In order to see all information + As a features developer + I want to see skipped test cases in JUnit reports + + Background: + Given I have entered 10 + + @setup-error + Scenario: Skipped + Then I must have 10 + + @setup-error + Scenario: Another skipped + Then I must have 10 + diff --git a/tests/Fixtures/JunitFormat/features/stop_on_failure.feature b/tests/Fixtures/JunitFormat/features/stop_on_failure.feature new file mode 100644 index 000000000..34ddec788 --- /dev/null +++ b/tests/Fixtures/JunitFormat/features/stop_on_failure.feature @@ -0,0 +1,11 @@ +Feature: Stop on failure + In order to see test information + As a features developer + I want to see the right output in JUnit when I stop on a failure + + Background: + Given I have entered 10 + + Scenario: Failed + When I add 4 + Then I must have 13 diff --git a/tests/Fixtures/JunitFormat/two_suites.php b/tests/Fixtures/JunitFormat/two_suites.php new file mode 100644 index 000000000..c521f12ff --- /dev/null +++ b/tests/Fixtures/JunitFormat/two_suites.php @@ -0,0 +1,28 @@ +withProfile((new Profile('default')) + ->withSuite((new Suite('small_kid')) + ->withPaths( + 'features/multiple_suites_1.feature', + 'features/multiple_suites_2.feature' + ) + ->withFilter( + new RoleFilter('small kid') + ) + ) + ->withSuite((new Suite('old_man')) + ->withPaths( + 'features/multiple_suites_1.feature', + 'features/multiple_suites_2.feature' + ) + ->withFilter( + new RoleFilter('old man') + ) + ) + ); From 2189968dae9ac96b314176d58dd5129cf32354d3 Mon Sep 17 00:00:00 2001 From: Carlos Granados Date: Wed, 29 Jan 2025 19:38:19 +0100 Subject: [PATCH 542/567] Allow unicode characters in table transformations --- ...itions_transformations_annotations.feature | 63 ++++++++++++++++--- .../ColumnBasedTableTransformation.php | 2 +- .../RowBasedTableTransformation.php | 2 +- .../Transformation/TableRowTransformation.php | 2 +- 4 files changed, 57 insertions(+), 12 deletions(-) diff --git a/features/definitions_transformations_annotations.feature b/features/definitions_transformations_annotations.feature index f528c9118..9d00ca82b 100644 --- a/features/definitions_transformations_annotations.feature +++ b/features/definitions_transformations_annotations.feature @@ -48,6 +48,15 @@ Feature: Step Arguments Transformations Annotations return new User($username, $age); } + /** @Transform table:логин,возраст */ + public function createUserFromTableInRussian(TableNode $table) { + $hash = $table->getHash(); + $username = $hash[0]['логин']; + $age = $hash[0]['возраст']; + + return new User($username, $age); + } + /** @Transform rowtable:username,age */ public function createUserFromRowTable(TableNode $table) { $hash = $table->getRowsHash(); @@ -57,11 +66,25 @@ Feature: Step Arguments Transformations Annotations return new User($username, $age); } + /** @Transform rowtable:логин,возраст */ + public function createUserFromRowTableInRussian(TableNode $table) { + $hash = $table->getRowsHash(); + $username = $hash['логин']; + $age = $hash['возраст']; + + return new User($username, $age); + } + /** @Transform row:username */ public function createUserNamesFromTable($tableRow) { return $tableRow['username']; } + /** @Transform row:логин */ + public function createUserNamesFromTableInRussian($tableRow) { + return $tableRow['логин']; + } + /** @Transform table:%username@,age# */ public function createUserFromTableWithSymbol(TableNode $table) { $hash = $table->getHash(); @@ -184,6 +207,13 @@ Feature: Step Arguments Transformations Annotations Then Username must be "vasiljev" And Age must be 30 + Scenario: + Given I am user: + | логин | возраст | + | vasiljev | 30 | + Then Username must be "vasiljev" + And Age must be 30 + Scenario: Given I am user: | %username@ | age# | @@ -194,10 +224,10 @@ Feature: Step Arguments Transformations Annotations When I run "behat -f progress --no-colors" Then it should pass with: """ - ...... + ............ - 3 scenarios (3 passed) - 9 steps (9 passed) + 4 scenarios (4 passed) + 12 steps (12 passed) """ Scenario: Row Table Arguments Transformations @@ -218,6 +248,13 @@ Feature: Step Arguments Transformations Annotations Then Username must be "vasiljev" And Age must be 30 + Scenario: + Given I am user: + | логин | vasiljev | + | возраст | 30 | + Then Username must be "vasiljev" + And Age must be 30 + Scenario: Given I am user: | --username | rajesh | @@ -228,10 +265,10 @@ Feature: Step Arguments Transformations Annotations When I run "behat -f progress --no-colors" Then it should pass with: """ - ...... + ............ - 3 scenarios (3 passed) - 9 steps (9 passed) + 4 scenarios (4 passed) + 12 steps (12 passed) """ Scenario: Table Row Arguments Transformations @@ -253,14 +290,22 @@ Feature: Step Arguments Transformations Annotations Then the Usernames must be: | $username | | rajesh | + + Scenario: + Given I am user: + | username | age | + | ever.zet | 22 | + Then the Usernames must be: + | логин | + | ever.zet | """ When I run "behat -f progress --no-colors" Then it should pass with: """ - .... + ...... - 2 scenarios (2 passed) - 4 steps (4 passed) + 3 scenarios (3 passed) + 6 steps (6 passed) """ Scenario: Whole table transformation diff --git a/src/Behat/Behat/Transformation/Transformation/ColumnBasedTableTransformation.php b/src/Behat/Behat/Transformation/Transformation/ColumnBasedTableTransformation.php index eda2ff2a4..42501cdc7 100644 --- a/src/Behat/Behat/Transformation/Transformation/ColumnBasedTableTransformation.php +++ b/src/Behat/Behat/Transformation/Transformation/ColumnBasedTableTransformation.php @@ -25,7 +25,7 @@ */ final class ColumnBasedTableTransformation extends RuntimeCallee implements SimpleArgumentTransformation { - public const PATTERN_REGEX = '/^table\:(?:\*|[[:print:]]+)$/'; + public const PATTERN_REGEX = '/^table\:(?:\*|[[:print:]]+)$/u'; /** * @var string diff --git a/src/Behat/Behat/Transformation/Transformation/RowBasedTableTransformation.php b/src/Behat/Behat/Transformation/Transformation/RowBasedTableTransformation.php index aeb277b8d..db38462d8 100644 --- a/src/Behat/Behat/Transformation/Transformation/RowBasedTableTransformation.php +++ b/src/Behat/Behat/Transformation/Transformation/RowBasedTableTransformation.php @@ -26,7 +26,7 @@ */ final class RowBasedTableTransformation extends RuntimeCallee implements SimpleArgumentTransformation { - public const PATTERN_REGEX = '/^rowtable\:[[:print:]]+$/'; + public const PATTERN_REGEX = '/^rowtable\:[[:print:]]+$/u'; /** * @var string diff --git a/src/Behat/Behat/Transformation/Transformation/TableRowTransformation.php b/src/Behat/Behat/Transformation/Transformation/TableRowTransformation.php index 37143d262..ddce0cb9c 100644 --- a/src/Behat/Behat/Transformation/Transformation/TableRowTransformation.php +++ b/src/Behat/Behat/Transformation/Transformation/TableRowTransformation.php @@ -25,7 +25,7 @@ */ final class TableRowTransformation extends RuntimeCallee implements SimpleArgumentTransformation { - public const PATTERN_REGEX = '/^row\:[[:print:]]+$/'; + public const PATTERN_REGEX = '/^row\:[[:print:]]+$/u'; /** * @var string From 5c0b4d84fe05eb91a2a4c49eecbe387beea45c60 Mon Sep 17 00:00:00 2001 From: Carlos Granados Date: Tue, 21 Jan 2025 21:52:30 +0100 Subject: [PATCH 543/567] Initial PHP CS Fixer configuration --- .gitignore | 1 + .php-cs-fixer.dist.php | 12 ++++++++++++ composer.json | 6 +++++- 3 files changed, 18 insertions(+), 1 deletion(-) create mode 100644 .php-cs-fixer.dist.php diff --git a/.gitignore b/.gitignore index 91507e81e..fce15ae58 100644 --- a/.gitignore +++ b/.gitignore @@ -6,3 +6,4 @@ vendor composer.lock .phpunit.result.cache phpstan.neon +.php-cs-fixer.cache diff --git a/.php-cs-fixer.dist.php b/.php-cs-fixer.dist.php new file mode 100644 index 000000000..7b43ff870 --- /dev/null +++ b/.php-cs-fixer.dist.php @@ -0,0 +1,12 @@ +in(__DIR__) +; + +return (new PhpCsFixer\Config()) + ->setParallelConfig(PhpCsFixer\Runner\Parallel\ParallelConfigFactory::detect()) + ->setRules([ + '@PSR1' => true, + ]) + ->setFinder($finder); diff --git a/composer.json b/composer.json index 3f367adea..883014b00 100644 --- a/composer.json +++ b/composer.json @@ -30,6 +30,7 @@ }, "require-dev": { + "friendsofphp/php-cs-fixer": "^3.68", "phpstan/phpstan": "^2.0", "phpunit/phpunit": "^9.6", "sebastian/diff": "^4.0", @@ -66,6 +67,7 @@ "scripts": { "all-tests": [ + "@cs", "@behat-progress", "@phpunit", "@phpstan" @@ -73,7 +75,9 @@ "behat": "LANG=C bin/behat --rerun", "behat-progress": "LANG=C bin/behat --format=progress", "phpstan": "phpstan", - "phpunit": "phpunit" + "phpunit": "phpunit", + "cs": "php-cs-fixer fix --dry-run --verbose --diff", + "cs-fix": "php-cs-fixer fix" }, "bin": ["bin/behat"] From 2b85b5c1a94c21946ac179ec93dfc08d050f3991 Mon Sep 17 00:00:00 2001 From: Carlos Granados Date: Wed, 22 Jan 2025 10:03:32 +0100 Subject: [PATCH 544/567] Apply PSR2 rules related to spacing --- .php-cs-fixer.dist.php | 29 +++++++++++++++++++ .../Context/CustomSnippetAcceptingContext.php | 4 +-- .../Cli/StopOnFailureController.php | 2 +- .../Tester/EventDispatchingOutlineTester.php | 2 +- .../Tester/TickingStepTester.php | 4 +-- .../HelperContainer/ArgumentAutowirer.php | 3 +- .../Behat/Output/Statistics/Statistics.php | 1 - .../Argument/MixedArgumentOrganiser.php | 14 ++++----- .../Event/ExerciseCompleted.php | 1 - .../Tester/EventDispatchingSuiteTester.php | 4 +-- .../Output/Printer/JUnitOutputPrinter.php | 2 +- .../Tester/Handler/StopOnFailureHandler.php | 1 - .../Argument/MixedArgumentOrganiserTest.php | 10 +++---- .../TestworkEventDispatcherTest.php | 4 +-- 14 files changed, 52 insertions(+), 29 deletions(-) diff --git a/.php-cs-fixer.dist.php b/.php-cs-fixer.dist.php index 7b43ff870..88b627122 100644 --- a/.php-cs-fixer.dist.php +++ b/.php-cs-fixer.dist.php @@ -8,5 +8,34 @@ ->setParallelConfig(PhpCsFixer\Runner\Parallel\ParallelConfigFactory::detect()) ->setRules([ '@PSR1' => true, + 'blank_line_after_namespace' => true, +// 'braces_position' => true, +// 'class_definition' => true, +// 'constant_case' => true, +// 'control_structure_braces' => true, +// 'control_structure_continuation_position' => true, +// 'elseif' => true, +// 'function_declaration' => true, +// 'indentation_type' => true, +// 'line_ending' => true, +// 'lowercase_keywords' => true, +// 'method_argument_space' => ['attribute_placement' => 'ignore', 'on_multiline' => 'ensure_fully_multiline'], +// 'no_break_comment' => true, +// 'no_closing_tag' => true, +// 'no_multiple_statements_per_line' => true, + 'no_space_around_double_colon' => true, + 'no_spaces_after_function_name' => true, + 'no_trailing_whitespace' => true, + 'no_trailing_whitespace_in_comment' => true, +// 'single_blank_line_at_eof' => true, +// 'single_class_element_per_statement' => ['elements' => ['property']], +// 'single_import_per_statement' => true, + 'single_line_after_imports' => true, + 'single_space_around_construct' => ['constructs_followed_by_a_single_space' => ['abstract', 'as', 'case', 'catch', 'class', 'do', 'else', 'elseif', 'final', 'for', 'foreach', 'function', 'if', 'interface', 'namespace', 'private', 'protected', 'public', 'static', 'switch', 'trait', 'try', 'use_lambda', 'while'], 'constructs_preceded_by_a_single_space' => ['as', 'else', 'elseif', 'use_lambda']], + 'spaces_inside_parentheses' => true, +// 'statement_indentation' => true, +// 'switch_case_semicolon_to_colon' => true, + 'switch_case_space' => true, +// 'visibility_required' => ['elements' => ['method', 'property']] ]) ->setFinder($finder); diff --git a/src/Behat/Behat/Context/CustomSnippetAcceptingContext.php b/src/Behat/Behat/Context/CustomSnippetAcceptingContext.php index 5090d304b..9cb7e03d5 100644 --- a/src/Behat/Behat/Context/CustomSnippetAcceptingContext.php +++ b/src/Behat/Behat/Context/CustomSnippetAcceptingContext.php @@ -24,8 +24,8 @@ interface CustomSnippetAcceptingContext extends SnippetAcceptingContext { /** - * Returns type of the snippets that this context accepts. - * + * Returns type of the snippets that this context accepts. + * * Behat implements a couple of types by default: "regex" and "turnip" * * @return string diff --git a/src/Behat/Behat/EventDispatcher/Cli/StopOnFailureController.php b/src/Behat/Behat/EventDispatcher/Cli/StopOnFailureController.php index be1e40c15..148507301 100644 --- a/src/Behat/Behat/EventDispatcher/Cli/StopOnFailureController.php +++ b/src/Behat/Behat/EventDispatcher/Cli/StopOnFailureController.php @@ -32,7 +32,7 @@ /** * Stops tests on first scenario failure. - * + * * TODO this should be moved in the Behat\Testwork\Tester\Cli namespace * * @author Konstantin Kudryashov diff --git a/src/Behat/Behat/EventDispatcher/Tester/EventDispatchingOutlineTester.php b/src/Behat/Behat/EventDispatcher/Tester/EventDispatchingOutlineTester.php index 132f584fb..985e25ab0 100644 --- a/src/Behat/Behat/EventDispatcher/Tester/EventDispatchingOutlineTester.php +++ b/src/Behat/Behat/EventDispatcher/Tester/EventDispatchingOutlineTester.php @@ -83,7 +83,7 @@ public function tearDown(Environment $env, FeatureNode $feature, OutlineNode $ou { $event = new BeforeOutlineTeardown($env, $feature, $outline, $result); - $this->eventDispatcher->dispatch( $event,$event::BEFORE_TEARDOWN); + $this->eventDispatcher->dispatch($event,$event::BEFORE_TEARDOWN); $teardown = $this->baseTester->tearDown($env, $feature, $outline, $skip, $result); diff --git a/src/Behat/Behat/EventDispatcher/Tester/TickingStepTester.php b/src/Behat/Behat/EventDispatcher/Tester/TickingStepTester.php index dcbdf4c24..8a481f3d0 100644 --- a/src/Behat/Behat/EventDispatcher/Tester/TickingStepTester.php +++ b/src/Behat/Behat/EventDispatcher/Tester/TickingStepTester.php @@ -21,10 +21,10 @@ * to handle an interupt (on PHP7) * * @see Behat\Testwork\EventDispatcher\Cli\SigintController - * + * * @deprecated Since the way signals are handled changed to use pcntl_signal_dispatch * this class is no longer needed. - * + * * @todo Remove this class in the next major version * * @author Peter Mitchell diff --git a/src/Behat/Behat/HelperContainer/ArgumentAutowirer.php b/src/Behat/Behat/HelperContainer/ArgumentAutowirer.php index 0fbbe210c..ed523bb33 100644 --- a/src/Behat/Behat/HelperContainer/ArgumentAutowirer.php +++ b/src/Behat/Behat/HelperContainer/ArgumentAutowirer.php @@ -97,8 +97,7 @@ private function getClassFromParameter(ReflectionParameter $parameter) : ?string if ($typeString == 'self') { return $parameter->getDeclaringClass()->getName(); - } - elseif ($typeString == 'parent') { + } elseif ($typeString == 'parent') { return $parameter->getDeclaringClass()->getParentClass()->getName(); } diff --git a/src/Behat/Behat/Output/Statistics/Statistics.php b/src/Behat/Behat/Output/Statistics/Statistics.php index 24903b94d..5a1fbeed9 100644 --- a/src/Behat/Behat/Output/Statistics/Statistics.php +++ b/src/Behat/Behat/Output/Statistics/Statistics.php @@ -15,7 +15,6 @@ use Behat\Testwork\Counter\Timer; use Behat\Testwork\Tester\Result\TestResult; - /** * Collects and provided exercise statistics. * diff --git a/src/Behat/Testwork/Argument/MixedArgumentOrganiser.php b/src/Behat/Testwork/Argument/MixedArgumentOrganiser.php index a51510e54..3ecd1db5e 100644 --- a/src/Behat/Testwork/Argument/MixedArgumentOrganiser.php +++ b/src/Behat/Testwork/Argument/MixedArgumentOrganiser.php @@ -136,8 +136,8 @@ private function isParameterTypehintedInArgumentList(array $parameters, $value) */ private function isValueMatchesTypehintedParameter($value, ReflectionParameter $parameter) : bool { - foreach($this->getReflectionClassesFromParameter($parameter) as $typehintRefl) { - if($typehintRefl->isInstance($value)) { + foreach ($this->getReflectionClassesFromParameter($parameter) as $typehintRefl) { + if ($typehintRefl->isInstance($value)) { return true; } } @@ -221,7 +221,7 @@ private function prepareTypehintedArguments(array $parameters, array $typehinted private function filterApplicableTypehintedParameters(array $parameters) : array { return array_filter($parameters, - function($parameter, $num) { + function ($parameter, $num) { return !$this->isArgumentDefined($num) && $this->getReflectionClassesFromParameter($parameter); }, @@ -245,11 +245,9 @@ private function getReflectionClassesFromParameter(\ReflectionParameter $paramet if ($type instanceof ReflectionNamedType) { $types = [$type]; - } - elseif ($type instanceof ReflectionUnionType) { + } elseif ($type instanceof ReflectionUnionType) { $types = $type->getTypes(); - } - else { + } else { $types = []; } @@ -319,7 +317,7 @@ public function matchParameterToCandidateUsingPredicate( $predicate ) { foreach ($candidates as $candidateIndex => $candidate) { - foreach($this->getReflectionClassesFromParameter($parameter) as $class) { + foreach ($this->getReflectionClassesFromParameter($parameter) as $class) { if ($predicate($class, $candidate)) { $num = $parameter->getPosition(); diff --git a/src/Behat/Testwork/EventDispatcher/Event/ExerciseCompleted.php b/src/Behat/Testwork/EventDispatcher/Event/ExerciseCompleted.php index 9927c006d..38a0c8893 100644 --- a/src/Behat/Testwork/EventDispatcher/Event/ExerciseCompleted.php +++ b/src/Behat/Testwork/EventDispatcher/Event/ExerciseCompleted.php @@ -13,7 +13,6 @@ use Behat\Testwork\Event\Event; use Behat\Testwork\Specification\SpecificationIterator; - /** * Represents an exercise event. * diff --git a/src/Behat/Testwork/EventDispatcher/Tester/EventDispatchingSuiteTester.php b/src/Behat/Testwork/EventDispatcher/Tester/EventDispatchingSuiteTester.php index d47645977..98f0f4c1a 100644 --- a/src/Behat/Testwork/EventDispatcher/Tester/EventDispatchingSuiteTester.php +++ b/src/Behat/Testwork/EventDispatcher/Tester/EventDispatchingSuiteTester.php @@ -75,13 +75,13 @@ public function test(Environment $env, SpecificationIterator $iterator, $skip = public function tearDown(Environment $env, SpecificationIterator $iterator, $skip, TestResult $result) { $event = new BeforeSuiteTeardown($env, $iterator, $result); - $this->eventDispatcher->dispatch( $event, $event::BEFORE_TEARDOWN); + $this->eventDispatcher->dispatch($event, $event::BEFORE_TEARDOWN); $teardown = $this->baseTester->tearDown($env, $iterator, $skip, $result); $event = new AfterSuiteTested($env, $iterator, $result, $teardown); - $this->eventDispatcher->dispatch( $event, $event::AFTER); + $this->eventDispatcher->dispatch($event, $event::AFTER); return $teardown; } diff --git a/src/Behat/Testwork/Output/Printer/JUnitOutputPrinter.php b/src/Behat/Testwork/Output/Printer/JUnitOutputPrinter.php index 81e094def..550925beb 100644 --- a/src/Behat/Testwork/Output/Printer/JUnitOutputPrinter.php +++ b/src/Behat/Testwork/Output/Printer/JUnitOutputPrinter.php @@ -145,7 +145,7 @@ public function setFileName($fileName, $extension = 'xml') */ public function flush() { - if($this->domDocument instanceof \DOMDocument){ + if ($this->domDocument instanceof \DOMDocument){ try { $this->getWritingStream()->write( $this->domDocument->saveXML(null, LIBXML_NOEMPTYTAG), diff --git a/src/Behat/Testwork/Tester/Handler/StopOnFailureHandler.php b/src/Behat/Testwork/Tester/Handler/StopOnFailureHandler.php index b875b46e1..64d939441 100644 --- a/src/Behat/Testwork/Tester/Handler/StopOnFailureHandler.php +++ b/src/Behat/Testwork/Tester/Handler/StopOnFailureHandler.php @@ -10,7 +10,6 @@ namespace Behat\Testwork\Tester\Handler; - use Behat\Behat\EventDispatcher\Event\AfterScenarioTested; use Behat\Behat\EventDispatcher\Event\ExampleTested; use Behat\Behat\EventDispatcher\Event\ScenarioTested; diff --git a/tests/Behat/Tests/Testwork/Argument/MixedArgumentOrganiserTest.php b/tests/Behat/Tests/Testwork/Argument/MixedArgumentOrganiserTest.php index 7408d0e44..edc68a12d 100644 --- a/tests/Behat/Tests/Testwork/Argument/MixedArgumentOrganiserTest.php +++ b/tests/Behat/Tests/Testwork/Argument/MixedArgumentOrganiserTest.php @@ -18,7 +18,7 @@ protected function setUp() : void public function testThatItOrganisesNothingIfNoArgs(): void { $r = new ReflectionFunction( - static function(\DateTimeInterface $d) {} + static function (\DateTimeInterface $d) {} ); $args = []; @@ -30,7 +30,7 @@ static function(\DateTimeInterface $d) {} public function testThatItMatchesArgsByPosition(): void { $r = new ReflectionFunction( - static function($x, $y) {} + static function ($x, $y) {} ); $args = [ 1, @@ -46,7 +46,7 @@ static function($x, $y) {} public function testThatItMatchesArgsByName(): void { $r = new ReflectionFunction( - static function($date) {} + static function ($date) {} ); $args = [ 'date' => $date = new \DateTime(), @@ -61,7 +61,7 @@ static function($date) {} public function testThatItMatchesArgsByType(): void { $r = new ReflectionFunction( - static function(\DateTimeInterface $d) {} + static function (\DateTimeInterface $d) {} ); $args = [ 'x' => $date = new \DateTime(), @@ -76,7 +76,7 @@ static function(\DateTimeInterface $d) {} public function testThatItMatchesArgsByNameOverType(): void { $r = new ReflectionFunction( - static function(\DateTimeInterface $a, $date) {} + static function (\DateTimeInterface $a, $date) {} ); $args = [ 'date' => $date = new \DateTime(), diff --git a/tests/Behat/Tests/Testwork/EventDispatcher/TestworkEventDispatcherTest.php b/tests/Behat/Tests/Testwork/EventDispatcher/TestworkEventDispatcherTest.php index 4abf24910..b575313ec 100644 --- a/tests/Behat/Tests/Testwork/EventDispatcher/TestworkEventDispatcherTest.php +++ b/tests/Behat/Tests/Testwork/EventDispatcher/TestworkEventDispatcherTest.php @@ -8,8 +8,8 @@ * file that was distributed with this source code. */ -namespace Behat\Tests\Testwork\EventDispatcher; - +namespace Behat\Tests\Testwork\EventDispatcher; + use Behat\Testwork\EventDispatcher\TestworkEventDispatcher; use PHPUnit\Framework\TestCase; use Symfony\Contracts\EventDispatcher\Event; From ab71677a60a77a8e14c194babbeabfa2003219f3 Mon Sep 17 00:00:00 2001 From: Carlos Granados Date: Wed, 22 Jan 2025 10:23:24 +0100 Subject: [PATCH 545/567] Fixes method argument spacing, including making sure that multiline argument lists are fully multiline --- .php-cs-fixer.dist.php | 2 +- features/bootstrap/FeatureContext.php | 26 ++++++++++++------- .../Context/Cli/ContextSnippetsController.php | 8 ++++-- .../Handler/ContextEnvironmentHandler.php | 3 ++- .../Reader/ContextReaderCachedPerContext.php | 3 ++- .../Reader/ContextReaderCachedPerSuite.php | 3 ++- .../Suite/Setup/SuiteWithContextsSetup.php | 3 ++- .../Cli/AvailableDefinitionsController.php | 5 +++- .../Exception/RedundantStepException.php | 5 +++- .../ConsoleDefinitionInformationPrinter.php | 12 ++++++--- .../Printer/ConsoleDefinitionListPrinter.php | 3 ++- .../Cli/StopOnFailureController.php | 5 +++- .../Tester/EventDispatchingOutlineTester.php | 2 +- .../Behat/Gherkin/Cli/FilterController.php | 16 +++++++++--- .../Behat/Gherkin/Cli/SyntaxController.php | 4 ++- .../Locator/FilesystemFeatureLocator.php | 3 ++- .../Suite/Setup/SuiteWithPathsSetup.php | 3 ++- .../Call/Filter/ServicesResolver.php | 6 +++-- .../HelperContainerExtension.php | 3 ++- .../Hook/ServiceContainer/HookExtension.php | 8 ++++-- .../Behat/Output/Node/Printer/ListPrinter.php | 9 ++++--- .../Pretty/PrettyExampleRowPrinter.php | 4 ++- .../Printer/Pretty/PrettySetupPrinter.php | 8 ++++-- .../Pretty/PrettySkippedStepPrinter.php | 4 ++- .../Node/Printer/Pretty/PrettyStepPrinter.php | 4 ++- .../Printer/Progress/ProgressStepPrinter.php | 3 ++- .../Formatter/JUnitFormatterFactory.php | 7 +++-- .../Formatter/PrettyFormatterFactory.php | 10 ++++--- .../Formatter/ProgressFormatterFactory.php | 4 ++- .../Behat/Snippet/Cli/SnippetsController.php | 8 ++++-- .../Behat/Tester/Cli/RerunController.php | 10 +++++-- .../ServiceContainer/TesterExtension.php | 8 ++++-- .../ReturnTypeTransformation.php | 3 ++- .../Argument/MixedArgumentOrganiser.php | 3 ++- src/Behat/Testwork/Cli/Application.php | 8 ++++-- .../ServiceContainer/ExceptionExtension.php | 3 ++- .../Testwork/Ordering/Cli/OrderController.php | 5 +++- .../Testwork/Output/Cli/OutputController.php | 18 +++++++++---- .../ServiceContainer/ContainerLoader.php | 3 ++- .../Suite/Cli/InitializationController.php | 5 +++- .../Testwork/Suite/Cli/SuiteController.php | 9 +++++-- .../Tester/Cli/ExerciseController.php | 12 ++++++--- .../Testwork/Tester/Cli/StrictController.php | 5 +++- .../Translator/Cli/LanguageController.php | 5 +++- .../ServiceContainer/TranslatorExtension.php | 12 ++++++--- tests/Fixtures/JunitFormat/behat.php | 21 ++++++++++----- tests/Fixtures/JunitFormat/two_suites.php | 9 ++++--- 47 files changed, 231 insertions(+), 92 deletions(-) diff --git a/.php-cs-fixer.dist.php b/.php-cs-fixer.dist.php index 88b627122..f49d93fa9 100644 --- a/.php-cs-fixer.dist.php +++ b/.php-cs-fixer.dist.php @@ -19,7 +19,7 @@ // 'indentation_type' => true, // 'line_ending' => true, // 'lowercase_keywords' => true, -// 'method_argument_space' => ['attribute_placement' => 'ignore', 'on_multiline' => 'ensure_fully_multiline'], + 'method_argument_space' => ['attribute_placement' => 'ignore', 'on_multiline' => 'ensure_fully_multiline'], // 'no_break_comment' => true, // 'no_closing_tag' => true, // 'no_multiple_statements_per_line' => true, diff --git a/features/bootstrap/FeatureContext.php b/features/bootstrap/FeatureContext.php index 23eb9c860..d36539b28 100644 --- a/features/bootstrap/FeatureContext.php +++ b/features/bootstrap/FeatureContext.php @@ -436,26 +436,34 @@ private function getExpectedOutput(PyStringNode $expectedText) // windows path fix if ('/' !== DIRECTORY_SEPARATOR) { $text = preg_replace_callback( - '/[ "]features\/[^\n "]+/', function ($matches) { + '/[ "]features\/[^\n "]+/', + function ($matches) { return str_replace('/', DIRECTORY_SEPARATOR, $matches[0]); - }, $text + }, + $text ); $text = preg_replace_callback( - '/\features\/[^\<]+/', function ($matches) { + '/\features\/[^\<]+/', + function ($matches) { return str_replace('/', DIRECTORY_SEPARATOR, $matches[0]); - }, $text + }, + $text ); $text = preg_replace_callback( - '/\+[fd] [^ ]+/', function ($matches) { + '/\+[fd] [^ ]+/', + function ($matches) { return str_replace('/', DIRECTORY_SEPARATOR, $matches[0]); - }, $text + }, + $text ); // error stacktrace $text = preg_replace_callback( - '/#\d+ [^:]+:/', function ($matches) { + '/#\d+ [^:]+:/', + function ($matches) { return str_replace('/', DIRECTORY_SEPARATOR, $matches[0]); - }, $text + }, + $text ); } @@ -534,7 +542,7 @@ private function getOutput() $output = str_replace('Notice: Undefined index: ', 'Notice: Undefined offset: ', $output); // replace error messages that changed in PHP8 - $output = str_replace('Warning: Undefined array key','Notice: Undefined offset:', $output); + $output = str_replace('Warning: Undefined array key', 'Notice: Undefined offset:', $output); $output = preg_replace('/Class "([^"]+)" not found/', 'Class \'$1\' not found', $output); return trim(preg_replace("/ +$/m", '', $output)); diff --git a/src/Behat/Behat/Context/Cli/ContextSnippetsController.php b/src/Behat/Behat/Context/Cli/ContextSnippetsController.php index 5d6708088..a6f929c3e 100644 --- a/src/Behat/Behat/Context/Cli/ContextSnippetsController.php +++ b/src/Behat/Behat/Context/Cli/ContextSnippetsController.php @@ -59,11 +59,15 @@ public function configure(SymfonyCommand $command) { $command ->addOption( - '--snippets-for', null, InputOption::VALUE_OPTIONAL, + '--snippets-for', + null, + InputOption::VALUE_OPTIONAL, "Specifies which context class to generate snippets for." ) ->addOption( - '--snippets-type', null, InputOption::VALUE_REQUIRED, + '--snippets-type', + null, + InputOption::VALUE_REQUIRED, "Specifies which type of snippets (turnip, regex) to generate." ); } diff --git a/src/Behat/Behat/Context/Environment/Handler/ContextEnvironmentHandler.php b/src/Behat/Behat/Context/Environment/Handler/ContextEnvironmentHandler.php index 8a710d069..8f21c62e8 100644 --- a/src/Behat/Behat/Context/Environment/Handler/ContextEnvironmentHandler.php +++ b/src/Behat/Behat/Context/Environment/Handler/ContextEnvironmentHandler.php @@ -164,7 +164,8 @@ private function getSuiteContexts(Suite $suite) { if (!is_array($suite->getSetting('contexts'))) { throw new SuiteConfigurationException( - sprintf('`contexts` setting of the "%s" suite is expected to be an array, %s given.', + sprintf( + '`contexts` setting of the "%s" suite is expected to be an array, %s given.', $suite->getName(), gettype($suite->getSetting('contexts')) ), diff --git a/src/Behat/Behat/Context/Reader/ContextReaderCachedPerContext.php b/src/Behat/Behat/Context/Reader/ContextReaderCachedPerContext.php index 8a51662e2..8ea483c42 100644 --- a/src/Behat/Behat/Context/Reader/ContextReaderCachedPerContext.php +++ b/src/Behat/Behat/Context/Reader/ContextReaderCachedPerContext.php @@ -48,7 +48,8 @@ public function readContextCallees(ContextEnvironment $environment, $contextClas } return $this->cachedCallees[$contextClass] = $this->childReader->readContextCallees( - $environment, $contextClass + $environment, + $contextClass ); } } diff --git a/src/Behat/Behat/Context/Reader/ContextReaderCachedPerSuite.php b/src/Behat/Behat/Context/Reader/ContextReaderCachedPerSuite.php index 4a8bfd5c6..31e6c71ac 100644 --- a/src/Behat/Behat/Context/Reader/ContextReaderCachedPerSuite.php +++ b/src/Behat/Behat/Context/Reader/ContextReaderCachedPerSuite.php @@ -50,7 +50,8 @@ public function readContextCallees(ContextEnvironment $environment, $contextClas } return $this->cachedCallees[$key] = $this->childReader->readContextCallees( - $environment, $contextClass + $environment, + $contextClass ); } diff --git a/src/Behat/Behat/Context/Suite/Setup/SuiteWithContextsSetup.php b/src/Behat/Behat/Context/Suite/Setup/SuiteWithContextsSetup.php index 1273e3e1c..e590dee56 100644 --- a/src/Behat/Behat/Context/Suite/Setup/SuiteWithContextsSetup.php +++ b/src/Behat/Behat/Context/Suite/Setup/SuiteWithContextsSetup.php @@ -118,7 +118,8 @@ private function getSuiteContexts(Suite $suite) if (!is_array($contexts)) { throw new SuiteConfigurationException( - sprintf('`contexts` setting of the "%s" suite is expected to be an array, `%s` given.', + sprintf( + '`contexts` setting of the "%s" suite is expected to be an array, `%s` given.', $suite->getName(), gettype($contexts) ), diff --git a/src/Behat/Behat/Definition/Cli/AvailableDefinitionsController.php b/src/Behat/Behat/Definition/Cli/AvailableDefinitionsController.php index eaa22d400..92817fc23 100644 --- a/src/Behat/Behat/Definition/Cli/AvailableDefinitionsController.php +++ b/src/Behat/Behat/Definition/Cli/AvailableDefinitionsController.php @@ -70,7 +70,10 @@ public function __construct( */ public function configure(Command $command) { - $command->addOption('--definitions', '-d', InputOption::VALUE_REQUIRED, + $command->addOption( + '--definitions', + '-d', + InputOption::VALUE_REQUIRED, "Print all available step definitions:" . PHP_EOL . "- use to just list definition expressions." . PHP_EOL . "- use to show definitions with extended info." . PHP_EOL . diff --git a/src/Behat/Behat/Definition/Exception/RedundantStepException.php b/src/Behat/Behat/Definition/Exception/RedundantStepException.php index 8a47c5e2e..9d4e65fe6 100644 --- a/src/Behat/Behat/Definition/Exception/RedundantStepException.php +++ b/src/Behat/Behat/Definition/Exception/RedundantStepException.php @@ -33,7 +33,10 @@ public function __construct(Definition $step2, Definition $step1) { $message = sprintf( "Step \"%s\" is already defined in %s\n\n%s\n%s", - $step2->getPattern(), $step1->getPath(), $step1->getPath(), $step2->getPath() + $step2->getPattern(), + $step1->getPath(), + $step1->getPath(), + $step2->getPath() ); parent::__construct($message); diff --git a/src/Behat/Behat/Definition/Printer/ConsoleDefinitionInformationPrinter.php b/src/Behat/Behat/Definition/Printer/ConsoleDefinitionInformationPrinter.php index d690982ee..e04609952 100644 --- a/src/Behat/Behat/Definition/Printer/ConsoleDefinitionInformationPrinter.php +++ b/src/Behat/Behat/Definition/Printer/ConsoleDefinitionInformationPrinter.php @@ -76,7 +76,8 @@ private function extractHeader(Suite $suite, Definition $definition) $pattern = $definition->getPattern(); $lines = array(); $lines[] = strtr( - '{suite} ', array( + '{suite} ', + array( '{suite}' => $suite->getName(), '{type}' => $this->getDefinitionType($definition), '{regex}' => $pattern, @@ -102,7 +103,8 @@ private function extractDescription(Suite $suite, Definition $definition) if ($description = $definition->getDescription()) { foreach (explode("\n", $description) as $descriptionLine) { $lines[] = strtr( - '{space} {description}', array( + '{space} {description}', + array( '{space}' => str_pad('', mb_strlen($suite->getName(), 'utf8') + 1), '{description}' => $descriptionLine ) @@ -125,7 +127,8 @@ private function extractFooter(Suite $suite, Definition $definition) { $lines = array(); $lines[] = strtr( - '{space} at `{path}`', array( + '{space} at `{path}`', + array( '{space}' => str_pad('', mb_strlen($suite->getName(), 'utf8') + 1), '{path}' => $definition->getPath() ) @@ -133,7 +136,8 @@ private function extractFooter(Suite $suite, Definition $definition) if ($this->isVerbose()) { $lines[] = strtr( - '{space} on `{filepath}[{start}:{end}]`', array( + '{space} on `{filepath}[{start}:{end}]`', + array( '{space}' => str_pad('', mb_strlen($suite->getName(), 'utf8') + 1), '{filepath}' => $definition->getReflection()->getFileName(), '{start}' => $definition->getReflection()->getStartLine(), diff --git a/src/Behat/Behat/Definition/Printer/ConsoleDefinitionListPrinter.php b/src/Behat/Behat/Definition/Printer/ConsoleDefinitionListPrinter.php index d155d9449..250cc839d 100644 --- a/src/Behat/Behat/Definition/Printer/ConsoleDefinitionListPrinter.php +++ b/src/Behat/Behat/Definition/Printer/ConsoleDefinitionListPrinter.php @@ -30,7 +30,8 @@ public function printDefinitions(Suite $suite, $definitions) $definition = $this->translateDefinition($suite, $definition); $output[] = strtr( - '{suite} ', array( + '{suite} ', + array( '{suite}' => $suite->getName(), '{type}' => $this->getDefinitionType($definition, true), '{regex}' => $definition->getPattern(), diff --git a/src/Behat/Behat/EventDispatcher/Cli/StopOnFailureController.php b/src/Behat/Behat/EventDispatcher/Cli/StopOnFailureController.php index 148507301..9e325ec81 100644 --- a/src/Behat/Behat/EventDispatcher/Cli/StopOnFailureController.php +++ b/src/Behat/Behat/EventDispatcher/Cli/StopOnFailureController.php @@ -68,7 +68,10 @@ public function setStopOnFailureHandler(StopOnFailureHandler $stopOnFailureHandl */ public function configure(Command $command) { - $command->addOption('--stop-on-failure', null, InputOption::VALUE_NONE, + $command->addOption( + '--stop-on-failure', + null, + InputOption::VALUE_NONE, 'Stop processing on first failed scenario.' ); } diff --git a/src/Behat/Behat/EventDispatcher/Tester/EventDispatchingOutlineTester.php b/src/Behat/Behat/EventDispatcher/Tester/EventDispatchingOutlineTester.php index 985e25ab0..1e11d0bd6 100644 --- a/src/Behat/Behat/EventDispatcher/Tester/EventDispatchingOutlineTester.php +++ b/src/Behat/Behat/EventDispatcher/Tester/EventDispatchingOutlineTester.php @@ -83,7 +83,7 @@ public function tearDown(Environment $env, FeatureNode $feature, OutlineNode $ou { $event = new BeforeOutlineTeardown($env, $feature, $outline, $result); - $this->eventDispatcher->dispatch($event,$event::BEFORE_TEARDOWN); + $this->eventDispatcher->dispatch($event, $event::BEFORE_TEARDOWN); $teardown = $this->baseTester->tearDown($env, $feature, $outline, $skip, $result); diff --git a/src/Behat/Behat/Gherkin/Cli/FilterController.php b/src/Behat/Behat/Gherkin/Cli/FilterController.php index 8fb3de84e..8a829fdbc 100644 --- a/src/Behat/Behat/Gherkin/Cli/FilterController.php +++ b/src/Behat/Behat/Gherkin/Cli/FilterController.php @@ -52,22 +52,30 @@ public function configure(Command $command) { $command ->addOption( - '--name', null, InputOption::VALUE_REQUIRED | InputOption::VALUE_IS_ARRAY, + '--name', + null, + InputOption::VALUE_REQUIRED | InputOption::VALUE_IS_ARRAY, "Only execute the feature elements which match part" . PHP_EOL . "of the given name or regex." ) ->addOption( - '--tags', null, InputOption::VALUE_REQUIRED | InputOption::VALUE_IS_ARRAY, + '--tags', + null, + InputOption::VALUE_REQUIRED | InputOption::VALUE_IS_ARRAY, "Only execute the features or scenarios with tags" . PHP_EOL . "matching tag filter expression." ) ->addOption( - '--role', null, InputOption::VALUE_REQUIRED, + '--role', + null, + InputOption::VALUE_REQUIRED, "Only execute the features with actor role matching" . PHP_EOL . "a wildcard." ) ->addOption( - '--narrative', null, InputOption::VALUE_REQUIRED, + '--narrative', + null, + InputOption::VALUE_REQUIRED, "Only execute the features with actor description" . PHP_EOL . "matching a regex." ) diff --git a/src/Behat/Behat/Gherkin/Cli/SyntaxController.php b/src/Behat/Behat/Gherkin/Cli/SyntaxController.php index 62acc12a6..8abbc5e05 100644 --- a/src/Behat/Behat/Gherkin/Cli/SyntaxController.php +++ b/src/Behat/Behat/Gherkin/Cli/SyntaxController.php @@ -57,7 +57,9 @@ public function configure(Command $command) { $command ->addOption( - '--story-syntax', null, InputOption::VALUE_NONE, + '--story-syntax', + null, + InputOption::VALUE_NONE, "Print example." . PHP_EOL . "Use to see specific language." ); diff --git a/src/Behat/Behat/Gherkin/Specification/Locator/FilesystemFeatureLocator.php b/src/Behat/Behat/Gherkin/Specification/Locator/FilesystemFeatureLocator.php index 8f7b67363..bd73b26a0 100644 --- a/src/Behat/Behat/Gherkin/Specification/Locator/FilesystemFeatureLocator.php +++ b/src/Behat/Behat/Gherkin/Specification/Locator/FilesystemFeatureLocator.php @@ -104,7 +104,8 @@ private function getSuitePaths(Suite $suite) { if (!is_array($suite->getSetting('paths'))) { throw new SuiteConfigurationException( - sprintf('`paths` setting of the "%s" suite is expected to be an array, %s given.', + sprintf( + '`paths` setting of the "%s" suite is expected to be an array, %s given.', $suite->getName(), gettype($suite->getSetting('paths')) ), diff --git a/src/Behat/Behat/Gherkin/Suite/Setup/SuiteWithPathsSetup.php b/src/Behat/Behat/Gherkin/Suite/Setup/SuiteWithPathsSetup.php index ff507f372..1b415a2da 100644 --- a/src/Behat/Behat/Gherkin/Suite/Setup/SuiteWithPathsSetup.php +++ b/src/Behat/Behat/Gherkin/Suite/Setup/SuiteWithPathsSetup.php @@ -102,7 +102,8 @@ private function locatePath($path) private function isAbsolutePath($file) { if ($file[0] == '/' || $file[0] == '\\' - || (strlen($file) > 3 && ctype_alpha($file[0]) + || ( + strlen($file) > 3 && ctype_alpha($file[0]) && $file[1] == ':' && ($file[2] == '\\' || $file[2] == '/') ) diff --git a/src/Behat/Behat/HelperContainer/Call/Filter/ServicesResolver.php b/src/Behat/Behat/HelperContainer/Call/Filter/ServicesResolver.php index 4fcfed4ed..4226e3430 100644 --- a/src/Behat/Behat/HelperContainer/Call/Filter/ServicesResolver.php +++ b/src/Behat/Behat/HelperContainer/Call/Filter/ServicesResolver.php @@ -134,7 +134,8 @@ private function repackageCallWithNewArguments(Call $call, array $newArguments) sprintf( 'ServicesResolver can not filter `%s` call.', get_class($call) - ), $call + ), + $call ); } @@ -181,7 +182,8 @@ private function repackageTransformationCall(TransformationCall $call, array $ne sprintf( 'Something is wrong in callee associated with `%s` call.', get_class($call) - ), $call + ), + $call ); } diff --git a/src/Behat/Behat/HelperContainer/ServiceContainer/HelperContainerExtension.php b/src/Behat/Behat/HelperContainer/ServiceContainer/HelperContainerExtension.php index 8357dae06..e7fe83a00 100644 --- a/src/Behat/Behat/HelperContainer/ServiceContainer/HelperContainerExtension.php +++ b/src/Behat/Behat/HelperContainer/ServiceContainer/HelperContainerExtension.php @@ -98,7 +98,8 @@ public function process(ContainerBuilder $container) foreach ($references as $reference) { if ($container->getDefinition((string) $reference)->isShared()) { throw new WrongServicesConfigurationException(sprintf( - 'Container services must not be configured as shared, but `@%s` is.', $reference + 'Container services must not be configured as shared, but `@%s` is.', + $reference )); } } diff --git a/src/Behat/Behat/Hook/ServiceContainer/HookExtension.php b/src/Behat/Behat/Hook/ServiceContainer/HookExtension.php index 97742c392..368c321c2 100644 --- a/src/Behat/Behat/Hook/ServiceContainer/HookExtension.php +++ b/src/Behat/Behat/Hook/ServiceContainer/HookExtension.php @@ -52,7 +52,9 @@ protected function loadHookableTesters(ContainerBuilder $container) $definition->addTag(TesterExtension::SPECIFICATION_TESTER_WRAPPER_TAG, array('priority' => 9999)); $container->setDefinition(TesterExtension::SPECIFICATION_TESTER_WRAPPER_TAG . '.hookable', $definition); - $definition = new Definition('Behat\Behat\Hook\Tester\HookableScenarioTester', array( + $definition = new Definition( + 'Behat\Behat\Hook\Tester\HookableScenarioTester', + array( new Reference(TesterExtension::SCENARIO_TESTER_ID), new Reference(self::DISPATCHER_ID) ) @@ -60,7 +62,9 @@ protected function loadHookableTesters(ContainerBuilder $container) $definition->addTag(TesterExtension::SCENARIO_TESTER_WRAPPER_TAG, array('priority' => 9999)); $container->setDefinition(TesterExtension::SCENARIO_TESTER_WRAPPER_TAG . '.hookable', $definition); - $definition = new Definition('Behat\Behat\Hook\Tester\HookableScenarioTester', array( + $definition = new Definition( + 'Behat\Behat\Hook\Tester\HookableScenarioTester', + array( new Reference(TesterExtension::EXAMPLE_TESTER_ID), new Reference(self::DISPATCHER_ID) ) diff --git a/src/Behat/Behat/Output/Node/Printer/ListPrinter.php b/src/Behat/Behat/Output/Node/Printer/ListPrinter.php index 6156ef55f..39e93ef10 100644 --- a/src/Behat/Behat/Output/Node/Printer/ListPrinter.php +++ b/src/Behat/Behat/Output/Node/Printer/ListPrinter.php @@ -204,7 +204,8 @@ private function printHookStat(OutputPrinter $printer, HookStat $hookStat, strin { $location = $this->getLocationFromScope($hookStat->getScope()); $printer->writeln( - sprintf(' {+%s}%s{-%s}%s {+comment}# %s{-comment}', + sprintf( + ' {+%s}%s{-%s}%s {+comment}# %s{-comment}', $style, $hookStat->getName(), $style, @@ -242,7 +243,8 @@ private function printStepStat( $maxLength = max(mb_strlen($stat->getScenarioText(), 'utf8'), mb_strlen($stat->getStepText(), 'utf8') + 2) + 1; $printer->writeln( - sprintf('%03d {+%s}%s{-%s}%s{+comment}# %s{-comment}', + sprintf( + '%03d {+%s}%s{-%s}%s{+comment}# %s{-comment}', $number, $style, $stat->getScenarioText(), @@ -253,7 +255,8 @@ private function printStepStat( ); $printer->writeln( - sprintf(' {+%s}%s{-%s}%s{+comment}# %s{-comment}', + sprintf( + ' {+%s}%s{-%s}%s{+comment}# %s{-comment}', $style, $stat->getStepText(), $style, diff --git a/src/Behat/Behat/Output/Node/Printer/Pretty/PrettyExampleRowPrinter.php b/src/Behat/Behat/Output/Node/Printer/Pretty/PrettyExampleRowPrinter.php index bf32202d5..6295bbcf5 100644 --- a/src/Behat/Behat/Output/Node/Printer/Pretty/PrettyExampleRowPrinter.php +++ b/src/Behat/Behat/Output/Node/Printer/Pretty/PrettyExampleRowPrinter.php @@ -181,7 +181,9 @@ private function printStepStdOut(OutputPrinter $printer, StepResult $result) $pad = function ($line) use ($indentedText) { return sprintf( - '%s│ {+stdout}%s{-stdout}', $indentedText, $line + '%s│ {+stdout}%s{-stdout}', + $indentedText, + $line ); }; diff --git a/src/Behat/Behat/Output/Node/Printer/Pretty/PrettySetupPrinter.php b/src/Behat/Behat/Output/Node/Printer/Pretty/PrettySetupPrinter.php index def94cc5d..5fc51719d 100644 --- a/src/Behat/Behat/Output/Node/Printer/Pretty/PrettySetupPrinter.php +++ b/src/Behat/Behat/Output/Node/Printer/Pretty/PrettySetupPrinter.php @@ -181,7 +181,9 @@ private function printHookCallStdOut(OutputPrinter $printer, CallResult $callRes $pad = function ($line) use ($indentText) { return sprintf( - '%s│ {+stdout}%s{-stdout}', $indentText, $line + '%s│ {+stdout}%s{-stdout}', + $indentText, + $line ); }; @@ -204,7 +206,9 @@ private function printHookCallException(OutputPrinter $printer, CallResult $call $pad = function ($l) use ($indentText) { return sprintf( - '%s╳ {+exception}%s{-exception}', $indentText, $l + '%s╳ {+exception}%s{-exception}', + $indentText, + $l ); }; diff --git a/src/Behat/Behat/Output/Node/Printer/Pretty/PrettySkippedStepPrinter.php b/src/Behat/Behat/Output/Node/Printer/Pretty/PrettySkippedStepPrinter.php index 49eb53dc1..b77c856ff 100644 --- a/src/Behat/Behat/Output/Node/Printer/Pretty/PrettySkippedStepPrinter.php +++ b/src/Behat/Behat/Output/Node/Printer/Pretty/PrettySkippedStepPrinter.php @@ -101,7 +101,9 @@ private function printText(OutputPrinter $printer, $stepType, $stepText, StepRes if ($result instanceof DefinedStepResult && $result->getStepDefinition()) { $definition = $result->getStepDefinition(); $stepText = $this->textPainter->paintText( - $stepText, $definition, new IntegerTestResult(TestResult::SKIPPED) + $stepText, + $definition, + new IntegerTestResult(TestResult::SKIPPED) ); } diff --git a/src/Behat/Behat/Output/Node/Printer/Pretty/PrettyStepPrinter.php b/src/Behat/Behat/Output/Node/Printer/Pretty/PrettyStepPrinter.php index 3766b40fd..f69000061 100644 --- a/src/Behat/Behat/Output/Node/Printer/Pretty/PrettyStepPrinter.php +++ b/src/Behat/Behat/Output/Node/Printer/Pretty/PrettyStepPrinter.php @@ -156,7 +156,9 @@ private function printStdOut(OutputPrinter $printer, StepResult $result) $pad = function ($line) use ($indentedText) { return sprintf( - '%s│ {+stdout}%s{-stdout}', $indentedText, $line + '%s│ {+stdout}%s{-stdout}', + $indentedText, + $line ); }; diff --git a/src/Behat/Behat/Output/Node/Printer/Progress/ProgressStepPrinter.php b/src/Behat/Behat/Output/Node/Printer/Progress/ProgressStepPrinter.php index 1bb7970f1..42192e607 100644 --- a/src/Behat/Behat/Output/Node/Printer/Progress/ProgressStepPrinter.php +++ b/src/Behat/Behat/Output/Node/Printer/Progress/ProgressStepPrinter.php @@ -106,7 +106,8 @@ private function printStdOut(OutputPrinter $printer, StepResult $result): void $callResult = $result->getCallResult(); $pad = function ($line) { return sprintf( - ' | {+stdout}%s{-stdout}', $line + ' | {+stdout}%s{-stdout}', + $line ); }; diff --git a/src/Behat/Behat/Output/ServiceContainer/Formatter/JUnitFormatterFactory.php b/src/Behat/Behat/Output/ServiceContainer/Formatter/JUnitFormatterFactory.php index ffd7934d8..66aaac217 100644 --- a/src/Behat/Behat/Output/ServiceContainer/Formatter/JUnitFormatterFactory.php +++ b/src/Behat/Behat/Output/ServiceContainer/Formatter/JUnitFormatterFactory.php @@ -91,7 +91,8 @@ private function loadCorePrinters(ContainerBuilder $container) $container->setDefinition('output.node.printer.junit.step', $definition); $definition = new Definition( - 'Behat\Behat\Output\Node\Printer\JUnit\JUnitSetupPrinter', array( + 'Behat\Behat\Output\Node\Printer\JUnit\JUnitSetupPrinter', + array( new Reference(ExceptionExtension::PRESENTER_ID), ) ); @@ -106,7 +107,9 @@ private function loadCorePrinters(ContainerBuilder $container) private function loadRootNodeListener(ContainerBuilder $container) { - $definition = new Definition('Behat\Behat\Output\Node\EventListener\JUnit\JUnitOutlineStoreListener', array( + $definition = new Definition( + 'Behat\Behat\Output\Node\EventListener\JUnit\JUnitOutlineStoreListener', + array( new Reference('output.node.printer.junit.suite') ) ); diff --git a/src/Behat/Behat/Output/ServiceContainer/Formatter/PrettyFormatterFactory.php b/src/Behat/Behat/Output/ServiceContainer/Formatter/PrettyFormatterFactory.php index 96fcd5995..318ec0b59 100644 --- a/src/Behat/Behat/Output/ServiceContainer/Formatter/PrettyFormatterFactory.php +++ b/src/Behat/Behat/Output/ServiceContainer/Formatter/PrettyFormatterFactory.php @@ -176,7 +176,9 @@ protected function loadFormatter(ContainerBuilder $container) 'Prints the feature as is.', PrettyFormatter::defaults(), $this->createOutputPrinterDefinition(), - new Definition('Behat\Testwork\Output\Node\EventListener\ChainEventListener', array( + new Definition( + 'Behat\Testwork\Output\Node\EventListener\ChainEventListener', + array( array( $this->rearrangeBackgroundEvents( new Reference(self::ROOT_LISTENER_ID) @@ -433,7 +435,8 @@ protected function rearrangeBackgroundEvents($listener) */ protected function proxySiblingEvents($beforeEventName, $afterEventName, array $listeners) { - return new Definition('Behat\Behat\Output\Node\EventListener\Flow\FireOnlySiblingsListener', + return new Definition( + 'Behat\Behat\Output\Node\EventListener\Flow\FireOnlySiblingsListener', array( $beforeEventName, $afterEventName, @@ -452,7 +455,8 @@ protected function proxySiblingEvents($beforeEventName, $afterEventName, array $ */ protected function proxyEventsIfParameterIsSet($name, $value, Definition $listener) { - return new Definition('Behat\Testwork\Output\Node\EventListener\Flow\FireOnlyIfFormatterParameterListener', + return new Definition( + 'Behat\Testwork\Output\Node\EventListener\Flow\FireOnlyIfFormatterParameterListener', array($name, $value, $listener) ); } diff --git a/src/Behat/Behat/Output/ServiceContainer/Formatter/ProgressFormatterFactory.php b/src/Behat/Behat/Output/ServiceContainer/Formatter/ProgressFormatterFactory.php index c2c0ea2e5..ee769d5de 100644 --- a/src/Behat/Behat/Output/ServiceContainer/Formatter/ProgressFormatterFactory.php +++ b/src/Behat/Behat/Output/ServiceContainer/Formatter/ProgressFormatterFactory.php @@ -144,7 +144,9 @@ protected function loadFormatter(ContainerBuilder $container) 'Prints one character per step.', ProgressFormatter::defaults(), $this->createOutputPrinterDefinition(), - new Definition('Behat\Testwork\Output\Node\EventListener\ChainEventListener', array( + new Definition( + 'Behat\Testwork\Output\Node\EventListener\ChainEventListener', + array( array( new Reference(self::ROOT_LISTENER_ID), new Definition('Behat\Behat\Output\Node\EventListener\Statistics\StatisticsListener', array( diff --git a/src/Behat/Behat/Snippet/Cli/SnippetsController.php b/src/Behat/Behat/Snippet/Cli/SnippetsController.php index ce84e68bf..36842c40d 100644 --- a/src/Behat/Behat/Snippet/Cli/SnippetsController.php +++ b/src/Behat/Behat/Snippet/Cli/SnippetsController.php @@ -81,11 +81,15 @@ public function configure(Command $command) { $command ->addOption( - '--append-snippets', null, InputOption::VALUE_NONE, + '--append-snippets', + null, + InputOption::VALUE_NONE, "Appends snippets for undefined steps into main context." ) ->addOption( - '--no-snippets', null, InputOption::VALUE_NONE, + '--no-snippets', + null, + InputOption::VALUE_NONE, "Do not print snippets for undefined steps after stats." ); } diff --git a/src/Behat/Behat/Tester/Cli/RerunController.php b/src/Behat/Behat/Tester/Cli/RerunController.php index 7951ebd4d..5b29dfa23 100644 --- a/src/Behat/Behat/Tester/Cli/RerunController.php +++ b/src/Behat/Behat/Tester/Cli/RerunController.php @@ -66,10 +66,16 @@ public function __construct( */ public function configure(Command $command) { - $command->addOption('--rerun', null, InputOption::VALUE_NONE, + $command->addOption( + '--rerun', + null, + InputOption::VALUE_NONE, 'Re-run scenarios that failed during last execution, or run everything if there were no failures.' ); - $command->addOption('--rerun-only', null, InputOption::VALUE_NONE, + $command->addOption( + '--rerun-only', + null, + InputOption::VALUE_NONE, 'Re-run scenarios that failed during last execution, or exit if there were no failures.' ); } diff --git a/src/Behat/Behat/Tester/ServiceContainer/TesterExtension.php b/src/Behat/Behat/Tester/ServiceContainer/TesterExtension.php index 0dd89db1f..d0e0a2cdb 100644 --- a/src/Behat/Behat/Tester/ServiceContainer/TesterExtension.php +++ b/src/Behat/Behat/Tester/ServiceContainer/TesterExtension.php @@ -148,7 +148,9 @@ protected function loadScenarioTester(ContainerBuilder $container) $container->setDefinition(self::SCENARIO_TESTER_ID, $definition); // Proper isolation for scenarios - $definition = new Definition('Behat\Behat\Tester\Runtime\IsolatingScenarioTester', array( + $definition = new Definition( + 'Behat\Behat\Tester\Runtime\IsolatingScenarioTester', + array( new Reference(self::SCENARIO_TESTER_ID), new Reference(EnvironmentExtension::MANAGER_ID) ) @@ -191,7 +193,9 @@ protected function loadExampleTester(ContainerBuilder $container) $container->setDefinition(self::EXAMPLE_TESTER_ID, $definition); // Proper isolation for examples - $definition = new Definition('Behat\Behat\Tester\Runtime\IsolatingScenarioTester', array( + $definition = new Definition( + 'Behat\Behat\Tester\Runtime\IsolatingScenarioTester', + array( new Reference(self::EXAMPLE_TESTER_ID), new Reference(EnvironmentExtension::MANAGER_ID) ) diff --git a/src/Behat/Behat/Transformation/Transformation/ReturnTypeTransformation.php b/src/Behat/Behat/Transformation/Transformation/ReturnTypeTransformation.php index 11d275fff..1b21f17a4 100644 --- a/src/Behat/Behat/Transformation/Transformation/ReturnTypeTransformation.php +++ b/src/Behat/Behat/Transformation/Transformation/ReturnTypeTransformation.php @@ -148,7 +148,8 @@ static private function getReturnClass(ReflectionFunctionAbstract $reflection) private function getParameterClassNameByIndex(DefinitionCall $definitionCall, $argumentIndex) { $parameters = array_filter( - array_filter($this->getCallParameters($definitionCall), + array_filter( + $this->getCallParameters($definitionCall), $this->hasIndex($argumentIndex) ), $this->getClassReflection() diff --git a/src/Behat/Testwork/Argument/MixedArgumentOrganiser.php b/src/Behat/Testwork/Argument/MixedArgumentOrganiser.php index 3ecd1db5e..df92dee51 100644 --- a/src/Behat/Testwork/Argument/MixedArgumentOrganiser.php +++ b/src/Behat/Testwork/Argument/MixedArgumentOrganiser.php @@ -220,7 +220,8 @@ private function prepareTypehintedArguments(array $parameters, array $typehinted */ private function filterApplicableTypehintedParameters(array $parameters) : array { - return array_filter($parameters, + return array_filter( + $parameters, function ($parameter, $num) { return !$this->isArgumentDefined($num) && $this->getReflectionClassesFromParameter($parameter); diff --git a/src/Behat/Testwork/Cli/Application.php b/src/Behat/Testwork/Cli/Application.php index 669cc5b8b..04968fe4c 100644 --- a/src/Behat/Testwork/Cli/Application.php +++ b/src/Behat/Testwork/Cli/Application.php @@ -70,7 +70,9 @@ public function getDefaultInputDefinition(): InputDefinition new InputOption('--profile', '-p', InputOption::VALUE_REQUIRED, 'Specify config profile to use.'), new InputOption('--config', '-c', InputOption::VALUE_REQUIRED, 'Specify config file to use.'), new InputOption( - '--verbose', '-v', InputOption::VALUE_OPTIONAL, + '--verbose', + '-v', + InputOption::VALUE_OPTIONAL, 'Increase verbosity of exceptions.' . PHP_EOL . 'Use -vv or --verbose=2 to display backtraces in addition to exceptions.' ), @@ -80,7 +82,9 @@ public function getDefaultInputDefinition(): InputDefinition new InputOption('--version', '-V', InputOption::VALUE_NONE, 'Display version.'), new InputOption('--no-interaction', '-n', InputOption::VALUE_NONE, 'Do not ask any interactive question.'), new InputOption( - '--colors', null, InputOption::VALUE_NONE, + '--colors', + null, + InputOption::VALUE_NONE, 'Force ANSI color in the output. By default color support is' . PHP_EOL . 'guessed based on your platform and the output if not specified.' ), diff --git a/src/Behat/Testwork/Exception/ServiceContainer/ExceptionExtension.php b/src/Behat/Testwork/Exception/ServiceContainer/ExceptionExtension.php index 4086df591..29e9d6386 100644 --- a/src/Behat/Testwork/Exception/ServiceContainer/ExceptionExtension.php +++ b/src/Behat/Testwork/Exception/ServiceContainer/ExceptionExtension.php @@ -77,7 +77,8 @@ public function configure(ArrayNodeDefinition $builder) ->children() ->scalarNode('verbosity') ->info('Output verbosity') - ->example(sprintf('%d, %d, %d, %d', + ->example(sprintf( + '%d, %d, %d, %d', OutputPrinter::VERBOSITY_NORMAL, OutputPrinter::VERBOSITY_VERBOSE, OutputPrinter::VERBOSITY_VERY_VERBOSE, diff --git a/src/Behat/Testwork/Ordering/Cli/OrderController.php b/src/Behat/Testwork/Ordering/Cli/OrderController.php index 2c6978b61..63f0dc5de 100644 --- a/src/Behat/Testwork/Ordering/Cli/OrderController.php +++ b/src/Behat/Testwork/Ordering/Cli/OrderController.php @@ -51,7 +51,10 @@ public function __construct(EventDispatcherInterface $eventDispatcher, OrderedEx */ public function configure(SymfonyCommand $command) { - $command->addOption('--order', null, InputOption::VALUE_REQUIRED, + $command->addOption( + '--order', + null, + InputOption::VALUE_REQUIRED, 'Set an order in which to execute the specifications (this will result in slower feedback).' ); } diff --git a/src/Behat/Testwork/Output/Cli/OutputController.php b/src/Behat/Testwork/Output/Cli/OutputController.php index 89137ac2e..5e6774305 100644 --- a/src/Behat/Testwork/Output/Cli/OutputController.php +++ b/src/Behat/Testwork/Output/Cli/OutputController.php @@ -47,19 +47,25 @@ public function configure(Command $command) { $command ->addOption( - '--format', '-f', InputOption::VALUE_REQUIRED | InputOption::VALUE_IS_ARRAY, + '--format', + '-f', + InputOption::VALUE_REQUIRED | InputOption::VALUE_IS_ARRAY, 'How to format tests output. is default.' . PHP_EOL . 'Available formats are:' . PHP_EOL . $this->getFormatterDescriptions() . 'You can use multiple formats at the same time.' ) ->addOption( - '--out', '-o', InputOption::VALUE_REQUIRED | InputOption::VALUE_IS_ARRAY, + '--out', + '-o', + InputOption::VALUE_REQUIRED | InputOption::VALUE_IS_ARRAY, 'Write format output to a file/directory instead of' . PHP_EOL . 'STDOUT . You can also provide different' . PHP_EOL . 'outputs to multiple formats. This option is mandatory for the junit formatter.' ) ->addOption( - '--format-settings', null, InputOption::VALUE_REQUIRED | InputOption::VALUE_IS_ARRAY, + '--format-settings', + null, + InputOption::VALUE_REQUIRED | InputOption::VALUE_IS_ARRAY, 'Set formatters parameters using json object.' . PHP_EOL . 'Keys are parameter names, values are values.' ); @@ -199,7 +205,8 @@ private function isStandardOutput($outputId) private function isAbsolutePath($file) { if ($file[0] == '/' || $file[0] == '\\' - || (strlen($file) > 3 && ctype_alpha($file[0]) + || ( + strlen($file) > 3 && ctype_alpha($file[0]) && $file[1] == ':' && ($file[2] == '\\' || $file[2] == '/') ) @@ -226,7 +233,8 @@ function (Formatter $formatter) { $comment .= $formatter->getDescription(); return $comment; - }, $this->manager->getFormatters() + }, + $this->manager->getFormatters() ) ) . PHP_EOL; } diff --git a/src/Behat/Testwork/ServiceContainer/ContainerLoader.php b/src/Behat/Testwork/ServiceContainer/ContainerLoader.php index 0c7b7f241..3df054375 100644 --- a/src/Behat/Testwork/ServiceContainer/ContainerLoader.php +++ b/src/Behat/Testwork/ServiceContainer/ContainerLoader.php @@ -148,7 +148,8 @@ private function loadExtensions(ContainerBuilder $container, array $config) foreach ($config as $extensionConfigKey => $extensionConfig) { if (null === $extension = $this->extensionManager->getExtension($extensionConfigKey)) { throw new ExtensionException( - sprintf('None of the activated extensions use `%s` config section.', $extensionConfigKey), $extensionConfigKey + sprintf('None of the activated extensions use `%s` config section.', $extensionConfigKey), + $extensionConfigKey ); } diff --git a/src/Behat/Testwork/Suite/Cli/InitializationController.php b/src/Behat/Testwork/Suite/Cli/InitializationController.php index dc8ac0ce6..6fbe68ad9 100644 --- a/src/Behat/Testwork/Suite/Cli/InitializationController.php +++ b/src/Behat/Testwork/Suite/Cli/InitializationController.php @@ -51,7 +51,10 @@ public function __construct(SuiteRepository $repository, SuiteBootstrapper $boot */ public function configure(Command $command) { - $command->addOption('--init', null, InputOption::VALUE_NONE, + $command->addOption( + '--init', + null, + InputOption::VALUE_NONE, 'Initialize all registered test suites.' ); } diff --git a/src/Behat/Testwork/Suite/Cli/SuiteController.php b/src/Behat/Testwork/Suite/Cli/SuiteController.php index a46c3f228..458ae4e43 100644 --- a/src/Behat/Testwork/Suite/Cli/SuiteController.php +++ b/src/Behat/Testwork/Suite/Cli/SuiteController.php @@ -51,7 +51,10 @@ public function __construct(SuiteRegistry $registry, array $suiteConfigurations) */ public function configure(Command $command) { - $command->addOption('--suite', '-s', InputOption::VALUE_REQUIRED, + $command->addOption( + '--suite', + '-s', + InputOption::VALUE_REQUIRED, 'Only execute a specific suite.' ); } @@ -73,7 +76,9 @@ public function execute(InputInterface $input, OutputInterface $output) } $this->registry->registerSuiteConfiguration( - $name, $config['type'], $config['settings'] + $name, + $config['type'], + $config['settings'] ); } return null; diff --git a/src/Behat/Testwork/Tester/Cli/ExerciseController.php b/src/Behat/Testwork/Tester/Cli/ExerciseController.php index 031387647..84dddb108 100644 --- a/src/Behat/Testwork/Tester/Cli/ExerciseController.php +++ b/src/Behat/Testwork/Tester/Cli/ExerciseController.php @@ -87,14 +87,20 @@ public function configure(Command $command) $locatorsExamples = implode(PHP_EOL, array_map( function ($locator) { return '- ' . $locator; - }, $this->specificationFinder->getExampleLocators() + }, + $this->specificationFinder->getExampleLocators() )); $command - ->addArgument('paths', InputArgument::OPTIONAL, + ->addArgument( + 'paths', + InputArgument::OPTIONAL, 'Optional path(s) to execute. Could be:' . PHP_EOL . $locatorsExamples ) - ->addOption('--dry-run', null, InputOption::VALUE_NONE, + ->addOption( + '--dry-run', + null, + InputOption::VALUE_NONE, 'Invokes formatters without executing the tests and hooks.' ); } diff --git a/src/Behat/Testwork/Tester/Cli/StrictController.php b/src/Behat/Testwork/Tester/Cli/StrictController.php index ebd2d3b5d..d7853defa 100644 --- a/src/Behat/Testwork/Tester/Cli/StrictController.php +++ b/src/Behat/Testwork/Tester/Cli/StrictController.php @@ -48,7 +48,10 @@ public function __construct(ResultInterpreter $resultInterpreter, $strict = fals public function configure(Command $command) { - $command->addOption('--strict', null, InputOption::VALUE_NONE, + $command->addOption( + '--strict', + null, + InputOption::VALUE_NONE, 'Passes only if all tests are explicitly passing.' ); } diff --git a/src/Behat/Testwork/Translator/Cli/LanguageController.php b/src/Behat/Testwork/Translator/Cli/LanguageController.php index c7b826e57..73c6e5e8a 100644 --- a/src/Behat/Testwork/Translator/Cli/LanguageController.php +++ b/src/Behat/Testwork/Translator/Cli/LanguageController.php @@ -44,7 +44,10 @@ public function __construct(Translator $translator) */ public function configure(Command $command) { - $command->addOption('--lang', null, InputOption::VALUE_REQUIRED, + $command->addOption( + '--lang', + null, + InputOption::VALUE_REQUIRED, 'Print output in particular language.' ); } diff --git a/src/Behat/Testwork/Translator/ServiceContainer/TranslatorExtension.php b/src/Behat/Testwork/Translator/ServiceContainer/TranslatorExtension.php index 2037cb9e5..a1379802e 100644 --- a/src/Behat/Testwork/Translator/ServiceContainer/TranslatorExtension.php +++ b/src/Behat/Testwork/Translator/ServiceContainer/TranslatorExtension.php @@ -98,25 +98,29 @@ private function loadTranslator(ContainerBuilder $container, $locale, $fallbackL $definition->addMethodCall('setFallbackLocales', array(array($fallbackLocale))); $definition->addMethodCall( - 'addLoader', array( + 'addLoader', + array( 'xliff', new Definition('Symfony\Component\Translation\Loader\XliffFileLoader') ) ); $definition->addMethodCall( - 'addLoader', array( + 'addLoader', + array( 'yaml', new Definition('Symfony\Component\Translation\Loader\YamlFileLoader') ) ); $definition->addMethodCall( - 'addLoader', array( + 'addLoader', + array( 'php', new Definition('Symfony\Component\Translation\Loader\PhpFileLoader') ) ); $definition->addMethodCall( - 'addLoader', array( + 'addLoader', + array( 'array', new Definition('Symfony\Component\Translation\Loader\ArrayLoader') ) diff --git a/tests/Fixtures/JunitFormat/behat.php b/tests/Fixtures/JunitFormat/behat.php index c74eaa034..48d13f1c2 100644 --- a/tests/Fixtures/JunitFormat/behat.php +++ b/tests/Fixtures/JunitFormat/behat.php @@ -5,34 +5,41 @@ use Behat\Config\Suite; return (new Config()) - ->withProfile((new Profile('default')) - ->withSuite((new Suite('single_feature')) + ->withProfile( + (new Profile('default')) + ->withSuite( + (new Suite('single_feature')) ->withPaths( 'features/single_feature.feature' ) ) - ->withSuite((new Suite('multiple_features')) + ->withSuite( + (new Suite('multiple_features')) ->withPaths( 'features/multiple_features_1.feature', 'features/multiple_features_2.feature' ) ) - ->withSuite((new Suite('multiline_titles')) + ->withSuite( + (new Suite('multiline_titles')) ->withPaths( 'features/multiline_titles.feature' ) ) - ->withSuite((new Suite('skipped_test_cases')) + ->withSuite( + (new Suite('skipped_test_cases')) ->withPaths( 'features/skipped_test_cases.feature' ) ) - ->withSuite((new Suite('stop_on_failure')) + ->withSuite( + (new Suite('stop_on_failure')) ->withPaths( 'features/stop_on_failure.feature' ) ) - ->withSuite((new Suite('abort_on_php_error')) + ->withSuite( + (new Suite('abort_on_php_error')) ->withPaths( 'features/abort_on_php_error.feature' ) diff --git a/tests/Fixtures/JunitFormat/two_suites.php b/tests/Fixtures/JunitFormat/two_suites.php index c521f12ff..33e8f6c57 100644 --- a/tests/Fixtures/JunitFormat/two_suites.php +++ b/tests/Fixtures/JunitFormat/two_suites.php @@ -6,8 +6,10 @@ use Behat\Config\Suite; return (new Config()) - ->withProfile((new Profile('default')) - ->withSuite((new Suite('small_kid')) + ->withProfile( + (new Profile('default')) + ->withSuite( + (new Suite('small_kid')) ->withPaths( 'features/multiple_suites_1.feature', 'features/multiple_suites_2.feature' @@ -16,7 +18,8 @@ new RoleFilter('small kid') ) ) - ->withSuite((new Suite('old_man')) + ->withSuite( + (new Suite('old_man')) ->withPaths( 'features/multiple_suites_1.feature', 'features/multiple_suites_2.feature' From a947e21cd9b95e1f8077f7b690f9fa79254f25e7 Mon Sep 17 00:00:00 2001 From: Carlos Granados --definitions l--definitions i|{type}{regex}|{type}{regex}|||||||{type}{regex}|{type}{regex}*.feature--langpretty(output_path) Date: Wed, 22 Jan 2025 10:26:39 +0100 Subject: [PATCH 546/567] Fix line endings and empty line at EOF --- .php-cs-fixer.dist.php | 6 +- .../Tester/Handler/StopOnFailureHandler.php | 2 +- .../TestworkEventDispatcherTest.php | 208 +++++++++--------- 3 files changed, 108 insertions(+), 108 deletions(-) diff --git a/.php-cs-fixer.dist.php b/.php-cs-fixer.dist.php index f49d93fa9..58e7db3ea 100644 --- a/.php-cs-fixer.dist.php +++ b/.php-cs-fixer.dist.php @@ -17,17 +17,17 @@ // 'elseif' => true, // 'function_declaration' => true, // 'indentation_type' => true, -// 'line_ending' => true, + 'line_ending' => true, // 'lowercase_keywords' => true, 'method_argument_space' => ['attribute_placement' => 'ignore', 'on_multiline' => 'ensure_fully_multiline'], // 'no_break_comment' => true, -// 'no_closing_tag' => true, + 'no_closing_tag' => true, // 'no_multiple_statements_per_line' => true, 'no_space_around_double_colon' => true, 'no_spaces_after_function_name' => true, 'no_trailing_whitespace' => true, 'no_trailing_whitespace_in_comment' => true, -// 'single_blank_line_at_eof' => true, + 'single_blank_line_at_eof' => true, // 'single_class_element_per_statement' => ['elements' => ['property']], // 'single_import_per_statement' => true, 'single_line_after_imports' => true, diff --git a/src/Behat/Testwork/Tester/Handler/StopOnFailureHandler.php b/src/Behat/Testwork/Tester/Handler/StopOnFailureHandler.php index 64d939441..a228fa48d 100644 --- a/src/Behat/Testwork/Tester/Handler/StopOnFailureHandler.php +++ b/src/Behat/Testwork/Tester/Handler/StopOnFailureHandler.php @@ -52,4 +52,4 @@ public function exitOnFailure(AfterScenarioTested $event) exit(1); } -} \ No newline at end of file +} diff --git a/tests/Behat/Tests/Testwork/EventDispatcher/TestworkEventDispatcherTest.php b/tests/Behat/Tests/Testwork/EventDispatcher/TestworkEventDispatcherTest.php index b575313ec..4b5815fb9 100644 --- a/tests/Behat/Tests/Testwork/EventDispatcher/TestworkEventDispatcherTest.php +++ b/tests/Behat/Tests/Testwork/EventDispatcher/TestworkEventDispatcherTest.php @@ -1,106 +1,106 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + namespace Behat\Tests\Testwork\EventDispatcher; -use Behat\Testwork\EventDispatcher\TestworkEventDispatcher; -use PHPUnit\Framework\TestCase; -use Symfony\Contracts\EventDispatcher\Event; - -class TestworkEventDispatcherTest extends TestCase -{ - public function testDispatchLegacyCall(): void - { - $dispatcher = new TestworkEventDispatcher(); - $event = new class extends Event {}; - $eventName = 'TEST_EVENT'; - $listener = $this->createListenerSpy(); - - $dispatcher->addListener($eventName, $listener); - $dispatcher->dispatch($event, $eventName); - - $this->assertCount(1, $listener->receivedEvents); - $this->assertEquals($event, $listener->receivedEvents[0]); - } - - public function testDispatchCurrentCall(): void - { - $dispatcher = new TestworkEventDispatcher(); - $event = new class extends Event {}; - $listener = $this->createListenerSpy(); - - $dispatcher->addListener(get_class($event), $listener); - $dispatcher->dispatch($event); - - $this->assertCount(1, $listener->receivedEvents); - $this->assertEquals($event, $listener->receivedEvents[0]); - } - - public function testSetNameOnEvent(): void - { - $dispatcher = new TestworkEventDispatcher(); - $event = new class extends Event { - public $name; - public function setName($name): void - { - $this->name = $name; - } - }; - $eventName = 'TEST_EVENT'; - $listener = $this->createListenerSpy(); - - $dispatcher->addListener($eventName, $listener); - $dispatcher->dispatch($event, $eventName); - - $this->assertCount(1, $listener->receivedEvents); - $this->assertEquals($eventName, $event->name); - } - - public function testBeforeAllListener(): void - { - $dispatcher = new TestworkEventDispatcher(); - $event = new class extends Event {}; - $listener = $this->createListenerSpy(); - - $dispatcher->addListener(TestworkEventDispatcher::BEFORE_ALL_EVENTS, $listener); - $dispatcher->dispatch($event); - - $this->assertCount(1, $listener->receivedEvents); - $this->assertEquals($event, $listener->receivedEvents[0]); - } - - public function testAfterAllListener(): void - { - $dispatcher = new TestworkEventDispatcher(); - $event = new class extends Event {}; - $listener = $this->createListenerSpy(); - - $dispatcher->addListener(TestworkEventDispatcher::AFTER_ALL_EVENTS, $listener); - $dispatcher->dispatch($event); - - $this->assertCount(1, $listener->receivedEvents); - $this->assertEquals($event, $listener->receivedEvents[0]); - } - - /** - * @return callable - */ - public function createListenerSpy() - { - return new class() { - public $receivedEvents = []; - - public function __invoke(Event $event) - { - $this->receivedEvents[] = $event; - } - }; - } -} +use Behat\Testwork\EventDispatcher\TestworkEventDispatcher; +use PHPUnit\Framework\TestCase; +use Symfony\Contracts\EventDispatcher\Event; + +class TestworkEventDispatcherTest extends TestCase +{ + public function testDispatchLegacyCall(): void + { + $dispatcher = new TestworkEventDispatcher(); + $event = new class extends Event {}; + $eventName = 'TEST_EVENT'; + $listener = $this->createListenerSpy(); + + $dispatcher->addListener($eventName, $listener); + $dispatcher->dispatch($event, $eventName); + + $this->assertCount(1, $listener->receivedEvents); + $this->assertEquals($event, $listener->receivedEvents[0]); + } + + public function testDispatchCurrentCall(): void + { + $dispatcher = new TestworkEventDispatcher(); + $event = new class extends Event {}; + $listener = $this->createListenerSpy(); + + $dispatcher->addListener(get_class($event), $listener); + $dispatcher->dispatch($event); + + $this->assertCount(1, $listener->receivedEvents); + $this->assertEquals($event, $listener->receivedEvents[0]); + } + + public function testSetNameOnEvent(): void + { + $dispatcher = new TestworkEventDispatcher(); + $event = new class extends Event { + public $name; + public function setName($name): void + { + $this->name = $name; + } + }; + $eventName = 'TEST_EVENT'; + $listener = $this->createListenerSpy(); + + $dispatcher->addListener($eventName, $listener); + $dispatcher->dispatch($event, $eventName); + + $this->assertCount(1, $listener->receivedEvents); + $this->assertEquals($eventName, $event->name); + } + + public function testBeforeAllListener(): void + { + $dispatcher = new TestworkEventDispatcher(); + $event = new class extends Event {}; + $listener = $this->createListenerSpy(); + + $dispatcher->addListener(TestworkEventDispatcher::BEFORE_ALL_EVENTS, $listener); + $dispatcher->dispatch($event); + + $this->assertCount(1, $listener->receivedEvents); + $this->assertEquals($event, $listener->receivedEvents[0]); + } + + public function testAfterAllListener(): void + { + $dispatcher = new TestworkEventDispatcher(); + $event = new class extends Event {}; + $listener = $this->createListenerSpy(); + + $dispatcher->addListener(TestworkEventDispatcher::AFTER_ALL_EVENTS, $listener); + $dispatcher->dispatch($event); + + $this->assertCount(1, $listener->receivedEvents); + $this->assertEquals($event, $listener->receivedEvents[0]); + } + + /** + * @return callable + */ + public function createListenerSpy() + { + return new class() { + public $receivedEvents = []; + + public function __invoke(Event $event) + { + $this->receivedEvents[] = $event; + } + }; + } +} From ba740b59cff1f5aa8f5e4eed8577b986b8b6b1d3 Mon Sep 17 00:00:00 2001 From: Carlos Granados Date: Wed, 22 Jan 2025 10:31:47 +0100 Subject: [PATCH 547/567] Fix braces position --- .php-cs-fixer.dist.php | 12 ++++++------ features/bootstrap/FeatureContext.php | 2 +- .../ReturnTypeTransformation.php | 6 ++---- .../Exception/InvalidOrderException.php | 3 ++- .../Output/Printer/JUnitOutputPrinter.php | 4 ++-- .../Argument/MixedArgumentOrganiserTest.php | 2 +- .../features/bootstrap/FeatureContext.php | 18 ++++++++++++------ 7 files changed, 26 insertions(+), 21 deletions(-) diff --git a/.php-cs-fixer.dist.php b/.php-cs-fixer.dist.php index 58e7db3ea..edbe6c042 100644 --- a/.php-cs-fixer.dist.php +++ b/.php-cs-fixer.dist.php @@ -9,13 +9,13 @@ ->setRules([ '@PSR1' => true, 'blank_line_after_namespace' => true, -// 'braces_position' => true, -// 'class_definition' => true, + 'braces_position' => true, + 'class_definition' => true, // 'constant_case' => true, -// 'control_structure_braces' => true, -// 'control_structure_continuation_position' => true, -// 'elseif' => true, -// 'function_declaration' => true, + 'control_structure_braces' => true, + 'control_structure_continuation_position' => true, + 'elseif' => true, + 'function_declaration' => true, // 'indentation_type' => true, 'line_ending' => true, // 'lowercase_keywords' => true, diff --git a/features/bootstrap/FeatureContext.php b/features/bootstrap/FeatureContext.php index d36539b28..e0ccba7e1 100644 --- a/features/bootstrap/FeatureContext.php +++ b/features/bootstrap/FeatureContext.php @@ -209,7 +209,7 @@ public function iSetTheWorkingDirectoryToTheFixturesFolder($dir): void if (!is_dir($dir)) { throw new RuntimeException(sprintf('The directory "%s" does not exist', $dir)); } - $this->workingDir = $dir; ; + $this->workingDir = $dir; $this->workingDirChanged = true; } diff --git a/src/Behat/Behat/Transformation/Transformation/ReturnTypeTransformation.php b/src/Behat/Behat/Transformation/Transformation/ReturnTypeTransformation.php index 1b21f17a4..7d14a0331 100644 --- a/src/Behat/Behat/Transformation/Transformation/ReturnTypeTransformation.php +++ b/src/Behat/Behat/Transformation/Transformation/ReturnTypeTransformation.php @@ -221,15 +221,13 @@ private function hasPosition($index) */ private function getClassReflection() : closure { - return function (ReflectionParameter $parameter) : ?ReflectionClass - { + return function (ReflectionParameter $parameter) : ?ReflectionClass { $t = $parameter->getType(); if ($t instanceof ReflectionNamedType) { try { return new ReflectionClass($t->getName()); - } - catch (ReflectionException $t) { + } catch (ReflectionException $t) { return null; } } diff --git a/src/Behat/Testwork/Ordering/Exception/InvalidOrderException.php b/src/Behat/Testwork/Ordering/Exception/InvalidOrderException.php index 8d9cd32a7..e1da3741e 100644 --- a/src/Behat/Testwork/Ordering/Exception/InvalidOrderException.php +++ b/src/Behat/Testwork/Ordering/Exception/InvalidOrderException.php @@ -19,4 +19,5 @@ * @author Ciaran McNulty */ final class InvalidOrderException extends RuntimeException implements TestworkException -{} +{ +} diff --git a/src/Behat/Testwork/Output/Printer/JUnitOutputPrinter.php b/src/Behat/Testwork/Output/Printer/JUnitOutputPrinter.php index 550925beb..ed0101a8f 100644 --- a/src/Behat/Testwork/Output/Printer/JUnitOutputPrinter.php +++ b/src/Behat/Testwork/Output/Printer/JUnitOutputPrinter.php @@ -118,7 +118,7 @@ public function addTestcaseChild($nodeName, array $nodeAttributes = array(), $no private function addAttributesToNode(\DOMElement $node, array $attributes) { - foreach ($attributes as $name => $value){ + foreach ($attributes as $name => $value) { $node->setAttribute($name, $value ?? ''); } } @@ -145,7 +145,7 @@ public function setFileName($fileName, $extension = 'xml') */ public function flush() { - if ($this->domDocument instanceof \DOMDocument){ + if ($this->domDocument instanceof \DOMDocument) { try { $this->getWritingStream()->write( $this->domDocument->saveXML(null, LIBXML_NOEMPTYTAG), diff --git a/tests/Behat/Tests/Testwork/Argument/MixedArgumentOrganiserTest.php b/tests/Behat/Tests/Testwork/Argument/MixedArgumentOrganiserTest.php index edc68a12d..e571da373 100644 --- a/tests/Behat/Tests/Testwork/Argument/MixedArgumentOrganiserTest.php +++ b/tests/Behat/Tests/Testwork/Argument/MixedArgumentOrganiserTest.php @@ -59,7 +59,7 @@ static function ($date) {} } public function testThatItMatchesArgsByType(): void - { + { $r = new ReflectionFunction( static function (\DateTimeInterface $d) {} ); diff --git a/tests/Fixtures/JunitFormat/features/bootstrap/FeatureContext.php b/tests/Fixtures/JunitFormat/features/bootstrap/FeatureContext.php index a4c8b33ec..bcd26b937 100644 --- a/tests/Fixtures/JunitFormat/features/bootstrap/FeatureContext.php +++ b/tests/Fixtures/JunitFormat/features/bootstrap/FeatureContext.php @@ -12,32 +12,38 @@ class FeatureContext implements Context private $value; #[Given('/I have entered (\d+)/')] - public function iHaveEntered($num) { + public function iHaveEntered($num) + { $this->value = $num; } #[When('/I add (\d+)/')] - public function iAdd($num) { + public function iAdd($num) + { $this->value += $num; } #[When('/^Something not done yet$/')] - public function somethingNotDoneYet() { + public function somethingNotDoneYet() + { throw new PendingException(); } #[Then('/I must have (\d+)/')] - public function iMustHave($num) { + public function iMustHave($num) + { PHPUnit\Framework\Assert::assertEquals($num, $this->value); } #[BeforeScenario('@setup-error')] - public function setup() { + public function setup() + { throw new Exception('This scenario has a failed setup'); } #[When('/^I have a PHP error$/')] - public function iHaveAPHPError() { + public function iHaveAPHPError() + { $foo = new class extends Context {}; } } From ba52edd29e43302f4a4254626fd27af8f92dbf32 Mon Sep 17 00:00:00 2001 From: Carlos Granados Date: Wed, 22 Jan 2025 10:32:56 +0100 Subject: [PATCH 548/567] Fix indentation --- .php-cs-fixer.dist.php | 4 ++-- .../Autoloader/ServiceContainer/AutoloaderExtension.php | 2 +- src/Behat/Testwork/Ordering/Cli/OrderController.php | 2 +- .../Testwork/Output/ServiceContainer/OutputExtension.php | 2 +- src/Behat/Testwork/Suite/ServiceContainer/SuiteExtension.php | 2 +- .../Tests/Testwork/Argument/MixedArgumentOrganiserTest.php | 4 ++-- 6 files changed, 8 insertions(+), 8 deletions(-) diff --git a/.php-cs-fixer.dist.php b/.php-cs-fixer.dist.php index edbe6c042..7b2f4206d 100644 --- a/.php-cs-fixer.dist.php +++ b/.php-cs-fixer.dist.php @@ -16,7 +16,7 @@ 'control_structure_continuation_position' => true, 'elseif' => true, 'function_declaration' => true, -// 'indentation_type' => true, + 'indentation_type' => true, 'line_ending' => true, // 'lowercase_keywords' => true, 'method_argument_space' => ['attribute_placement' => 'ignore', 'on_multiline' => 'ensure_fully_multiline'], @@ -33,7 +33,7 @@ 'single_line_after_imports' => true, 'single_space_around_construct' => ['constructs_followed_by_a_single_space' => ['abstract', 'as', 'case', 'catch', 'class', 'do', 'else', 'elseif', 'final', 'for', 'foreach', 'function', 'if', 'interface', 'namespace', 'private', 'protected', 'public', 'static', 'switch', 'trait', 'try', 'use_lambda', 'while'], 'constructs_preceded_by_a_single_space' => ['as', 'else', 'elseif', 'use_lambda']], 'spaces_inside_parentheses' => true, -// 'statement_indentation' => true, + 'statement_indentation' => true, // 'switch_case_semicolon_to_colon' => true, 'switch_case_space' => true, // 'visibility_required' => ['elements' => ['method', 'property']] diff --git a/src/Behat/Testwork/Autoloader/ServiceContainer/AutoloaderExtension.php b/src/Behat/Testwork/Autoloader/ServiceContainer/AutoloaderExtension.php index 7b2cd7ddf..c8cfeec8c 100644 --- a/src/Behat/Testwork/Autoloader/ServiceContainer/AutoloaderExtension.php +++ b/src/Behat/Testwork/Autoloader/ServiceContainer/AutoloaderExtension.php @@ -78,7 +78,7 @@ public function configure(ArrayNodeDefinition $builder) ->treatTrueLike($this->defaultPaths) ->treatNullLike(array()) ->treatFalseLike(array()) - ; + ; assert($builder instanceof ArrayNodeDefinition); $builder ->prototype('scalar')->end() diff --git a/src/Behat/Testwork/Ordering/Cli/OrderController.php b/src/Behat/Testwork/Ordering/Cli/OrderController.php index 63f0dc5de..a3a3765ff 100644 --- a/src/Behat/Testwork/Ordering/Cli/OrderController.php +++ b/src/Behat/Testwork/Ordering/Cli/OrderController.php @@ -76,7 +76,7 @@ public function execute(InputInterface $input, OutputInterface $output) } if (!array_key_exists($orderer, $this->orderers)) { - throw new InvalidOrderException(sprintf("Order option '%s' was not recognised", $orderer)); + throw new InvalidOrderException(sprintf("Order option '%s' was not recognised", $orderer)); } $this->exercise->setOrderer($this->orderers[$orderer]); diff --git a/src/Behat/Testwork/Output/ServiceContainer/OutputExtension.php b/src/Behat/Testwork/Output/ServiceContainer/OutputExtension.php index b624ed24b..7cfd06eb3 100644 --- a/src/Behat/Testwork/Output/ServiceContainer/OutputExtension.php +++ b/src/Behat/Testwork/Output/ServiceContainer/OutputExtension.php @@ -107,7 +107,7 @@ public function configure(ArrayNodeDefinition $builder) return array_merge($a, array('enabled' => true)); }) ->end() - ; + ; assert($builder instanceof ArrayNodeDefinition); $builder ->useAttributeAsKey('name') diff --git a/src/Behat/Testwork/Suite/ServiceContainer/SuiteExtension.php b/src/Behat/Testwork/Suite/ServiceContainer/SuiteExtension.php index c8ec896d9..1492973bf 100644 --- a/src/Behat/Testwork/Suite/ServiceContainer/SuiteExtension.php +++ b/src/Behat/Testwork/Suite/ServiceContainer/SuiteExtension.php @@ -102,7 +102,7 @@ public function configure(ArrayNodeDefinition $builder) return $suite; }) ->end() - ; + ; assert($builder instanceof ArrayNodeDefinition); $childrenBuilder = $builder ->normalizeKeys(false) diff --git a/tests/Behat/Tests/Testwork/Argument/MixedArgumentOrganiserTest.php b/tests/Behat/Tests/Testwork/Argument/MixedArgumentOrganiserTest.php index e571da373..93fd9282a 100644 --- a/tests/Behat/Tests/Testwork/Argument/MixedArgumentOrganiserTest.php +++ b/tests/Behat/Tests/Testwork/Argument/MixedArgumentOrganiserTest.php @@ -58,8 +58,8 @@ static function ($date) {} $this->assertSame(['date' => $date], $organised); } - public function testThatItMatchesArgsByType(): void - { + public function testThatItMatchesArgsByType(): void + { $r = new ReflectionFunction( static function (\DateTimeInterface $d) {} ); From 40e62bde42a457ebee38e08f92784fdb68719fc5 Mon Sep 17 00:00:00 2001 From: Carlos Granados Date: Wed, 22 Jan 2025 10:36:19 +0100 Subject: [PATCH 549/567] Fix visibility declarations --- .php-cs-fixer.dist.php | 2 +- .../Behat/Transformation/SimpleArgumentTransformation.php | 2 +- .../Transformation/ColumnBasedTableTransformation.php | 2 +- .../Transformation/ReturnTypeTransformation.php | 4 ++-- .../Transformation/RowBasedTableTransformation.php | 2 +- .../Transformation/Transformation/TableRowTransformation.php | 2 +- .../Transformation/TokenNameAndReturnTypeTransformation.php | 2 +- .../Transformation/Transformation/TokenNameTransformation.php | 2 +- 8 files changed, 9 insertions(+), 9 deletions(-) diff --git a/.php-cs-fixer.dist.php b/.php-cs-fixer.dist.php index 7b2f4206d..7fdb489ec 100644 --- a/.php-cs-fixer.dist.php +++ b/.php-cs-fixer.dist.php @@ -36,6 +36,6 @@ 'statement_indentation' => true, // 'switch_case_semicolon_to_colon' => true, 'switch_case_space' => true, -// 'visibility_required' => ['elements' => ['method', 'property']] + 'visibility_required' => ['elements' => ['method', 'property']] ]) ->setFinder($finder); diff --git a/src/Behat/Behat/Transformation/SimpleArgumentTransformation.php b/src/Behat/Behat/Transformation/SimpleArgumentTransformation.php index d11c4ff19..182b7b815 100644 --- a/src/Behat/Behat/Transformation/SimpleArgumentTransformation.php +++ b/src/Behat/Behat/Transformation/SimpleArgumentTransformation.php @@ -29,7 +29,7 @@ interface SimpleArgumentTransformation extends Transformation * * @return bool */ - static public function supportsPatternAndMethod($pattern, ReflectionMethod $method); + public static function supportsPatternAndMethod($pattern, ReflectionMethod $method); /** * Returns transformation priority. diff --git a/src/Behat/Behat/Transformation/Transformation/ColumnBasedTableTransformation.php b/src/Behat/Behat/Transformation/Transformation/ColumnBasedTableTransformation.php index 42501cdc7..83ec9dc9b 100644 --- a/src/Behat/Behat/Transformation/Transformation/ColumnBasedTableTransformation.php +++ b/src/Behat/Behat/Transformation/Transformation/ColumnBasedTableTransformation.php @@ -35,7 +35,7 @@ final class ColumnBasedTableTransformation extends RuntimeCallee implements Simp /** * {@inheritdoc} */ - static public function supportsPatternAndMethod($pattern, ReflectionMethod $method) + public static function supportsPatternAndMethod($pattern, ReflectionMethod $method) { return 1 === preg_match(self::PATTERN_REGEX, $pattern); } diff --git a/src/Behat/Behat/Transformation/Transformation/ReturnTypeTransformation.php b/src/Behat/Behat/Transformation/Transformation/ReturnTypeTransformation.php index 7d14a0331..bc9497907 100644 --- a/src/Behat/Behat/Transformation/Transformation/ReturnTypeTransformation.php +++ b/src/Behat/Behat/Transformation/Transformation/ReturnTypeTransformation.php @@ -34,7 +34,7 @@ final class ReturnTypeTransformation extends RuntimeCallee implements SimpleArgu /** * {@inheritdoc} */ - static public function supportsPatternAndMethod($pattern, ReflectionMethod $method) + public static function supportsPatternAndMethod($pattern, ReflectionMethod $method) { $returnClass = self::getReturnClass($method); @@ -125,7 +125,7 @@ public function __toString() * * @return null|string */ - static private function getReturnClass(ReflectionFunctionAbstract $reflection) + private static function getReturnClass(ReflectionFunctionAbstract $reflection) { $type = $reflection->getReturnType(); diff --git a/src/Behat/Behat/Transformation/Transformation/RowBasedTableTransformation.php b/src/Behat/Behat/Transformation/Transformation/RowBasedTableTransformation.php index db38462d8..da9032d42 100644 --- a/src/Behat/Behat/Transformation/Transformation/RowBasedTableTransformation.php +++ b/src/Behat/Behat/Transformation/Transformation/RowBasedTableTransformation.php @@ -36,7 +36,7 @@ final class RowBasedTableTransformation extends RuntimeCallee implements SimpleA /** * {@inheritdoc} */ - static public function supportsPatternAndMethod($pattern, ReflectionMethod $method) + public static function supportsPatternAndMethod($pattern, ReflectionMethod $method) { return 1 === preg_match(self::PATTERN_REGEX, $pattern); } diff --git a/src/Behat/Behat/Transformation/Transformation/TableRowTransformation.php b/src/Behat/Behat/Transformation/Transformation/TableRowTransformation.php index ddce0cb9c..f03462046 100644 --- a/src/Behat/Behat/Transformation/Transformation/TableRowTransformation.php +++ b/src/Behat/Behat/Transformation/Transformation/TableRowTransformation.php @@ -35,7 +35,7 @@ final class TableRowTransformation extends RuntimeCallee implements SimpleArgume /** * {@inheritdoc} */ - static public function supportsPatternAndMethod($pattern, ReflectionMethod $method) + public static function supportsPatternAndMethod($pattern, ReflectionMethod $method) { return 1 === preg_match(self::PATTERN_REGEX, $pattern); } diff --git a/src/Behat/Behat/Transformation/Transformation/TokenNameAndReturnTypeTransformation.php b/src/Behat/Behat/Transformation/Transformation/TokenNameAndReturnTypeTransformation.php index c0086213a..287a5b52e 100644 --- a/src/Behat/Behat/Transformation/Transformation/TokenNameAndReturnTypeTransformation.php +++ b/src/Behat/Behat/Transformation/Transformation/TokenNameAndReturnTypeTransformation.php @@ -36,7 +36,7 @@ final class TokenNameAndReturnTypeTransformation extends RuntimeCallee implement /** * {@inheritdoc} */ - static public function supportsPatternAndMethod($pattern, ReflectionMethod $method) + public static function supportsPatternAndMethod($pattern, ReflectionMethod $method) { return TokenNameTransformation::supportsPatternAndMethod($pattern, $method) && ReturnTypeTransformation::supportsPatternAndMethod('', $method); diff --git a/src/Behat/Behat/Transformation/Transformation/TokenNameTransformation.php b/src/Behat/Behat/Transformation/Transformation/TokenNameTransformation.php index 807ffdf67..91348fc4e 100644 --- a/src/Behat/Behat/Transformation/Transformation/TokenNameTransformation.php +++ b/src/Behat/Behat/Transformation/Transformation/TokenNameTransformation.php @@ -35,7 +35,7 @@ final class TokenNameTransformation extends RuntimeCallee implements SimpleArgum /** * {@inheritdoc} */ - static public function supportsPatternAndMethod($pattern, ReflectionMethod $method) + public static function supportsPatternAndMethod($pattern, ReflectionMethod $method) { return 1 === preg_match(self::PATTERN_REGEX, $pattern); } From 5c1222579b3017d622e5034c8e491f6c922a2668 Mon Sep 17 00:00:00 2001 From: Carlos Granados Date: Wed, 22 Jan 2025 10:41:49 +0100 Subject: [PATCH 550/567] Full PSR2 configuration and run checker in CI --- .github/workflows/build.yml | 19 +++++++++++++++++++ .php-cs-fixer.dist.php | 31 +------------------------------ 2 files changed, 20 insertions(+), 30 deletions(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 280e892ce..44a9a2e56 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -112,6 +112,25 @@ jobs: - name: Run PHPStan run: ./vendor/bin/phpstan + coding-standard: + name: Coding standards + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + + - name: Setup PHP + uses: shivammathur/setup-php@v2 + with: + php-version: "8.1" + ini-values: "zend.exception_ignore_args=Off" + coverage: none + + - name: Install dependencies + run: composer update + + - name: Run PHP CS Fixer + run: ./vendor/bin/php-cs-fixer fix --dry-run --verbose --diff + build-phar: name: Build PHAR file runs-on: ubuntu-latest diff --git a/.php-cs-fixer.dist.php b/.php-cs-fixer.dist.php index 7fdb489ec..04a0e5839 100644 --- a/.php-cs-fixer.dist.php +++ b/.php-cs-fixer.dist.php @@ -7,35 +7,6 @@ return (new PhpCsFixer\Config()) ->setParallelConfig(PhpCsFixer\Runner\Parallel\ParallelConfigFactory::detect()) ->setRules([ - '@PSR1' => true, - 'blank_line_after_namespace' => true, - 'braces_position' => true, - 'class_definition' => true, -// 'constant_case' => true, - 'control_structure_braces' => true, - 'control_structure_continuation_position' => true, - 'elseif' => true, - 'function_declaration' => true, - 'indentation_type' => true, - 'line_ending' => true, -// 'lowercase_keywords' => true, - 'method_argument_space' => ['attribute_placement' => 'ignore', 'on_multiline' => 'ensure_fully_multiline'], -// 'no_break_comment' => true, - 'no_closing_tag' => true, -// 'no_multiple_statements_per_line' => true, - 'no_space_around_double_colon' => true, - 'no_spaces_after_function_name' => true, - 'no_trailing_whitespace' => true, - 'no_trailing_whitespace_in_comment' => true, - 'single_blank_line_at_eof' => true, -// 'single_class_element_per_statement' => ['elements' => ['property']], -// 'single_import_per_statement' => true, - 'single_line_after_imports' => true, - 'single_space_around_construct' => ['constructs_followed_by_a_single_space' => ['abstract', 'as', 'case', 'catch', 'class', 'do', 'else', 'elseif', 'final', 'for', 'foreach', 'function', 'if', 'interface', 'namespace', 'private', 'protected', 'public', 'static', 'switch', 'trait', 'try', 'use_lambda', 'while'], 'constructs_preceded_by_a_single_space' => ['as', 'else', 'elseif', 'use_lambda']], - 'spaces_inside_parentheses' => true, - 'statement_indentation' => true, -// 'switch_case_semicolon_to_colon' => true, - 'switch_case_space' => true, - 'visibility_required' => ['elements' => ['method', 'property']] + '@PSR2' => true, ]) ->setFinder($finder); From c85ceef036517cf7871cb27455cc5aa7c58a459a Mon Sep 17 00:00:00 2001 From: Carlos Granados Date: Fri, 31 Jan 2025 14:40:20 +0100 Subject: [PATCH 551/567] Add git blame ignore file --- .git-blame-ignore-revs | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 .git-blame-ignore-revs diff --git a/.git-blame-ignore-revs b/.git-blame-ignore-revs new file mode 100644 index 000000000..47ad016e8 --- /dev/null +++ b/.git-blame-ignore-revs @@ -0,0 +1,25 @@ +# Git 2.23+ allows ignoring commits from git-blame, useful to not display large automated commits. +# +# This file is a list of such commits, that you most probably are not interested in. +# To make this work for your local setup, you need to run the following command: +# +# $ git config blame.ignoreRevsFile .git-blame-ignore-revs +# +# A few rules for changing this file: +# - Commits are in chronological order - oldest on top. Therefore new commits should be added in the end. +# - The purpose is specifically for large commits - avoid adding commits with a very small impact, even if related +# to automated code style formatting. +# - Each commit should be preceded with a comment detailing the purpose of the commit. + +# PHP-CS-Fixer - Apply PSR2 rules related to spacing +2b85b5c1a94c21946ac179ec93dfc08d050f3991 +# PHP-CS-Fixer - Fixes method argument spacing, including making sure that multiline argument lists are fully multiline +ab71677a60a77a8e14c194babbeabfa2003219f3 +# PHP-CS-Fixer - Fix line endings and empty line at EOF +a947e21cd9b95e1f8077f7b690f9fa79254f25e7 +# PHP-CS-Fixer - Fix braces position +ba740b59cff1f5aa8f5e4eed8577b986b8b6b1d3 +# PHP-CS-Fixer - Fix indentation +ba52edd29e43302f4a4254626fd27af8f92dbf32 +# PHP-CS-Fixer - Fix visibility declarations +40e62bde42a457ebee38e08f92784fdb68719fc5 From d07f230901efff92bf6c6dfc269e3056b4dacc2f Mon Sep 17 00:00:00 2001 From: Carlos Granados Date: Mon, 27 Jan 2025 20:04:05 +0100 Subject: [PATCH 552/567] Add option to print unused definitions --- features/unused_definitions.feature | 41 +++++++++ i18n.php | 18 ++++ .../Definition/Call/RuntimeDefinition.php | 12 +++ .../Cli/UnusedDefinitionsController.php | 91 +++++++++++++++++++ .../ConsoleDefinitionInformationPrinter.php | 64 ++++++++----- .../Printer/ConsoleDefinitionPrinter.php | 10 +- .../ServiceContainer/DefinitionExtension.php | 18 ++-- .../Translator/DefinitionTranslator.php | 5 + .../Tester/Runtime/RuntimeStepTester.php | 6 ++ tests/Fixtures/UnusedDefinitions/behat.php | 19 ++++ .../features/bootstrap/FeatureContext.php | 39 ++++++++ .../features/first_feature.feature | 8 ++ .../features/second_feature.feature | 5 + 13 files changed, 305 insertions(+), 31 deletions(-) create mode 100644 features/unused_definitions.feature create mode 100644 src/Behat/Behat/Definition/Cli/UnusedDefinitionsController.php create mode 100644 tests/Fixtures/UnusedDefinitions/behat.php create mode 100644 tests/Fixtures/UnusedDefinitions/features/bootstrap/FeatureContext.php create mode 100644 tests/Fixtures/UnusedDefinitions/features/first_feature.feature create mode 100644 tests/Fixtures/UnusedDefinitions/features/second_feature.feature diff --git a/features/unused_definitions.feature b/features/unused_definitions.feature new file mode 100644 index 000000000..dd098a40d --- /dev/null +++ b/features/unused_definitions.feature @@ -0,0 +1,41 @@ +Feature: Unused definitions + In order to remove unused code + As a feature developer + I need to be able to generate a list of unused definitions + + Background: + Given I set the working directory to the "UnusedDefinitions" fixtures folder + And I provide the following options for all behat invocations: + | option | value | + | --no-colors | | + | --format | progress | + + Scenario: Print unused definitions for a single suite + When I run behat with the following additional options: + | option | value | + | --suite | first_suite | + | --print-unused-definitions | | + Then it should pass with: + """ + --- 2 unused definitions: + + [Then|*] I call a step used in the second feature + `FeatureContext::stepUsedInSecondFeature()` + + [Then|*] I call a step not used in any feature + This is a step that is never used and should be removed + `FeatureContext::stepNotUsedInAnyFeature()` + """ + + Scenario: Print unused definitions for two suites + When I run behat with the following additional options: + | option | value | + | --print-unused-definitions | | + Then it should pass with: + """ + --- 1 unused definition: + + [Then|*] I call a step not used in any feature + This is a step that is never used and should be removed + `FeatureContext::stepNotUsedInAnyFeature()` + """ diff --git a/i18n.php b/i18n.php index 4dda4786d..b36fe695e 100644 --- a/i18n.php +++ b/i18n.php @@ -17,6 +17,7 @@ 'pending_count' => '[1,Inf] %count% pending', 'undefined_count' => '[1,Inf] %count% undefined', 'skipped_count' => '[1,Inf] %count% skipped', + 'unused_definitions' => '{0} No unused definitions|{1} 1 unused definition:|]1,Inf] %count% unused definitions:', ), 'bg' => array( 'snippet_context_choice' => 'В сет ', @@ -36,6 +37,7 @@ 'pending_count' => '[1,Inf] %count% изчакващи', 'undefined_count' => '[1,Inf] %count% неопределени', 'skipped_count' => '[1,Inf] %count% пропуснати', + 'unused_definitions' => '{0} Няма неизползвани дефиниции|{1} 1 неизползвана дефиниция:|]1,Inf] %count% неизползвани дефиниции:', ), 'cs' => array( 'snippet_proposal_title' => '', @@ -53,6 +55,7 @@ 'pending_count' => '{1} %count% čeká|{2,3,4} %count% čekají|]4,Inf] %count% čeká', 'undefined_count' => '{1} %count% nedefinován|{2,3,4} %count% nedefinovány|]4,Inf] %count% nedefinováno', 'skipped_count' => '{1} %count% přeskočen|{2,3,4} %count% přeskočeny|]4,Inf] %count% přeskočeno', + 'unused_definitions' => '{0} Žádné nepoužité definice|{1} 1 nepoužitá definice:|]1,Inf] %count% nepoužitých definic:', ), 'de' => array( 'snippet_proposal_title' => '', @@ -70,6 +73,7 @@ 'pending_count' => '[1,Inf] %count% ausstehend', 'undefined_count' => '[1,Inf] %count% nicht definiert', 'skipped_count' => '[1,Inf] %count% übersprungen', + 'unused_definitions' => '{0} Keine unbenutzten Definitionen|{1} 1 unbenutzte Definition:|]1,Inf] %count% unbenutzte Definitionen:', ), 'es' => array( 'snippet_proposal_title' => '', @@ -87,6 +91,7 @@ 'pending_count' => '[1,Inf] %count% pendientes', 'undefined_count' => '[1,Inf] %count% por definir', 'skipped_count' => '[1,Inf] %count% saltadas', + 'unused_definitions' => '{0} No hay definiciones sin usar|{1} 1 definición sin usar:|]1,Inf] %count% definiciones sin usar:', ), 'fr' => array( 'snippet_proposal_title' => '', @@ -104,6 +109,7 @@ 'pending_count' => '[1,Inf] %count% en attente', 'undefined_count' => '[1,Inf] %count% indéfinis', 'skipped_count' => '[1,Inf] %count% ignorés', + 'unused_definitions' => '{0} Aucune définition inutilisée|{1} 1 définition inutilisée:|]1,Inf] %count% définitions inutilisées:', ), 'hu' => array( 'snippet_context_choice' => '', @@ -123,6 +129,7 @@ 'pending_count' => '[1,Inf] %count% elintézendő', 'undefined_count' => '[1,Inf] %count% meghatározatlan', 'skipped_count' => '[1,Inf] %count% kihagyott', + 'unused_definitions' => '{0} Nincsenek nem használt definíciók|{1} nem használt definíció:|]1,Inf] %count% nem használt definíciók:', ), 'it' => array( 'snippet_proposal_title' => '', @@ -140,6 +147,7 @@ 'pending_count' => '[1,Inf] %count% in sospeso', 'undefined_count' => '{1} 1 non definito|]1,Inf] %count% non definiti', 'skipped_count' => '{1} 1 ignorato|]1,Inf] %count% ignorati', + 'unused_definitions' => '{0} Nessuna definizione inutilizzata|{1} 1 definizione inutilizzata:|]1,Inf] %count% definizioni inutilizzate:', ), 'ja' => array( 'snippet_proposal_title' => '', @@ -158,6 +166,7 @@ 'pending_count' => '[1,Inf] %count% 個保留', 'undefined_count' => '[1,Inf] %count% 個未定義', 'skipped_count' => '[1,Inf] %count% 個スキップ', + 'unused_definitions' => '{0} 未使用の定義はありません|{1} 未使用の定義が1つあります:|]1,Inf] 未使用の定義が %count% 個あります:', ), 'ko' => array( 'snippet_proposal_title' => ' ', @@ -176,6 +185,7 @@ 'pending_count' => '[1,Inf] %count% 준비중', 'undefined_count' => '[1,Inf] %count% 정의되지 않았습니다.', 'skipped_count' => '[1,Inf] %count% 건너뜀', + 'unused_definitions' => '{0} 사용하지 않은 정의가 없습니다|{1} 사용하지 않은 정의가 1개 있습니다:|]1,Inf] 사용하지 않은 정의가 %count%개 있습니다:', ), 'nl' => array( 'snippet_proposal_title' => '', @@ -193,6 +203,7 @@ 'pending_count' => '[1,Inf] %count% wachtende', 'undefined_count' => '[1,Inf] %count% niet gedefinieerd', 'skipped_count' => '[1,Inf] %count% overgeslagen', + 'unused_definitions' => '{0} Geen ongebruikte definities|{1} 1 ongebruikte definitie:|]1,Inf] %count% ongebruikte definities:', ), 'no' => array( 'snippet_proposal_title' => '', @@ -210,6 +221,7 @@ 'pending_count' => '[1,Inf] %count% ikke implementert', 'undefined_count' => '[1,Inf] %count% ikke definert', 'skipped_count' => '[1,Inf] %count% hoppet over', + 'unused_definitions' => '{0} Ingen ubrukte definisjoner|{1} 1 ubrukt definisjon:|]1,Inf] %count% ubrukte definisjoner:', ), 'pl' => array( 'snippet_proposal_title' => '', @@ -227,6 +239,7 @@ 'pending_count' => '{1} %count% oczekujący|{2,3,4,22,23,24,32,33,34,42,43,44} %count% oczekujące|]4,Inf] %count% oczekujących', 'undefined_count' => '{1} %count% niezdefiniowany|{2,3,4,22,23,24,32,33,34,42,43,44} %count% niezdefiniowane|]4,Inf] %count% niezdefiniowanych', 'skipped_count' => '{1} %count% pominięty|{2,3,4,22,23,24,32,33,34,42,43,44} %count% pominięte|]4,Inf] %count% pominiętych', + 'unused_definitions' => '{0} Brak nieużytych definicji|{1} 1 nieużyta definicja:|]1,Inf] %count% nieużytych definicji:', ), 'pt' => array( 'snippet_proposal_title' => '', @@ -244,6 +257,7 @@ 'pending_count' => '[1,Inf] %count% por definir', 'undefined_count' => '{1} indefinido|]1,Inf] %count% indefinidos', 'skipped_count' => '{1} omitido|]1,Inf] %count% omitidos', + 'unused_definitions' => '{0} Nenhuma definição não utilizada|{1} 1 definição não utilizada:|]1,Inf] %count% definições não utilizadas:', ), 'pt-BR' => array( 'snippet_proposal_title' => '', @@ -261,6 +275,7 @@ 'pending_count' => '[1,Inf] %count% pendente', 'undefined_count' => '[1,Inf] %count% indefinido', 'skipped_count' => '[1,Inf] %count% pulado', + 'unused_definitions' => '{0} Nenhuma definição não utilizada|{1} 1 definição não utilizada:|]1,Inf] %count% definições não utilizadas:', ), 'ro' => array( 'snippet_proposal_title' => '', @@ -279,6 +294,7 @@ 'pending_count' => '[1,Inf] %count% in așteptare', 'undefined_count' => '[1,Inf] %count% fara implementare', 'skipped_count' => '{1} %count% omis|]1,Inf] %count% omiși', + 'unused_definitions' => '{0} Nu există definiții neutilizate|{1} 1 definiție neutilizată:|]1,Inf] %count% definiții neutilizate:', ), 'ru' => array( 'snippet_proposal_title' => ' ', @@ -297,6 +313,7 @@ 'pending_count' => '[1,Inf] %count% в ожидании', 'undefined_count' => '{1,21,31} %count% не определен|]1,Inf] %count% не определено', 'skipped_count' => '{1,21,31} %count% пропущен|]1,Inf] %count% пропущено', + 'unused_definitions' => '{0} Нет неиспользованных определений|{1} 1 неиспользованное определение:|]1,Inf] %count% неиспользованных определений:', ), 'zh' => array( 'snippet_context_choice' => '', @@ -315,5 +332,6 @@ 'pending_count' => '[1,Inf] %count% 个待实现方法', 'undefined_count' => '[1,Inf] %count% 个未定义', 'skipped_count' => '[1,Inf] %count% 个跳过', + 'unused_definitions' => '{0} 没有未使用的定义|{1} 1 个未使用的定义:|]1,Inf] %count% 个未使用的定义:', ), ); diff --git a/src/Behat/Behat/Definition/Call/RuntimeDefinition.php b/src/Behat/Behat/Definition/Call/RuntimeDefinition.php index 4c2c4946a..c13560f70 100644 --- a/src/Behat/Behat/Definition/Call/RuntimeDefinition.php +++ b/src/Behat/Behat/Definition/Call/RuntimeDefinition.php @@ -29,6 +29,8 @@ abstract class RuntimeDefinition extends RuntimeCallee implements Definition */ private $pattern; + private bool $used = false; + /** * Initializes definition. * @@ -68,4 +70,14 @@ public function __toString() { return $this->getType() . ' ' . $this->getPattern(); } + + public function markAsUsed(): void + { + $this->used = true; + } + + public function hasBeenUsed(): bool + { + return $this->used; + } } diff --git a/src/Behat/Behat/Definition/Cli/UnusedDefinitionsController.php b/src/Behat/Behat/Definition/Cli/UnusedDefinitionsController.php new file mode 100644 index 000000000..ce6d983d2 --- /dev/null +++ b/src/Behat/Behat/Definition/Cli/UnusedDefinitionsController.php @@ -0,0 +1,91 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Behat\Behat\Definition\Cli; + +use Behat\Behat\Definition\Call\RuntimeDefinition; +use Behat\Behat\Definition\DefinitionRepository; +use Behat\Behat\Definition\Printer\ConsoleDefinitionInformationPrinter; +use Behat\Testwork\Cli\Controller; +use Behat\Testwork\EventDispatcher\Event\AfterSuiteTested; +use Behat\Testwork\EventDispatcher\Event\ExerciseCompleted; +use Behat\Testwork\EventDispatcher\Event\SuiteTested; +use Symfony\Component\Console\Command\Command; +use Symfony\Component\Console\Input\InputInterface; +use Symfony\Component\Console\Input\InputOption; +use Symfony\Component\Console\Output\OutputInterface; +use Symfony\Component\EventDispatcher\EventDispatcherInterface; + +/** + * Prints unused definitions + * + * @author Konstantin Kudryashov има недекларирани стъпки. Изберете в кой Context да бъдат създадени:%count% obsahuje chybné kroky. Definujte je za použití následujícího kódu:%count% hat fehlende Schritte. Definiere diese mit den folgenden Snippets:%count%A le faltan pasos. Defínelos con estos pasos:%count% a des étapes manquantes. Définissez-les avec les modèles suivants :%count% sorozat meghatározatlan lépéseket tartalmaz. Válaszd ki a környezetet kódrészlet készítéséhez:%count% ha dei passaggi mancanti. Definiscili con questi snippet:%count% のステップが見つかりません。 次のスニペットで定義できます:%count%%count% 정의가 되지 않았습니다. 스니펫을 생성할 컨텍스트를 선택하십시오:Ontbrekende stappen in . Definieer ze met de volgende fragmenten:%count% mangler steg. Definer dem med disse snuttene:%count% zawiera brakujące kroki. Utwórz je korzystając z tych fragmentów kodu:%count% contém definições em falta. Defina-as com estes exemplos:%count% possue etapas faltando. Defina elas com esse(s) trecho(s) de código:%count% are pași lipsa. Puteți implementa pașii cu ajutorul acestor fragmente de cod:%count%%count%не содержит необходимых определений. Вы можете добавить их используя шаблоны: 有新的场景步骤, 请选择要生成代码片段的ContextClass:%count% + */ +final class UnusedDefinitionsController implements Controller +{ + /** + * @var array + */ + private array $definitionUsage = []; + + public function __construct( + private DefinitionRepository $definitionRepository, + private EventDispatcherInterface $eventDispatcher, + private ConsoleDefinitionInformationPrinter $printer, + ) { + } + + public function configure(Command $command): void + { + $command + ->addOption( + '--print-unused-definitions', null, InputOption::VALUE_NONE, + "Reports definitions that were never used." + ) + ; + } + + public function execute(InputInterface $input, OutputInterface $output): ?int + { + if ($input->getOption('print-unused-definitions')) { + $this->eventDispatcher->addListener(SuiteTested::AFTER, array($this, 'registerDefinitionUsages'), -999); + $this->eventDispatcher->addListener(ExerciseCompleted::AFTER, array($this, 'printUnusedDefinitions'), -999); + } + return null; + } + + public function registerDefinitionUsages(AfterSuiteTested $event): void + { + $environmentDefinitions = $this->definitionRepository->getEnvironmentDefinitions($event->getEnvironment()); + foreach ($environmentDefinitions as $definition) { + if ($definition instanceof RuntimeDefinition) { + $path = $definition->getPath(); + if (!isset($this->definitionUsage[$path])) { + $this->definitionUsage[$path] = [ + 'definition' => $definition, + 'used' => $definition->hasBeenUsed(), + ]; + } elseif ($definition->hasBeenUsed()) { + $this->definitionUsage[$path]['used'] = true; + } + } + } + } + + public function printUnusedDefinitions(): void + { + $unusedDefinitions = array_filter($this->definitionUsage, function ($definition) { + return $definition['used'] === false; + }); + $unusedDefinitions = array_column($unusedDefinitions, 'definition'); + + $this->printer->printUnusedDefinitions($unusedDefinitions); + } +} diff --git a/src/Behat/Behat/Definition/Printer/ConsoleDefinitionInformationPrinter.php b/src/Behat/Behat/Definition/Printer/ConsoleDefinitionInformationPrinter.php index e04609952..9b3572bb5 100644 --- a/src/Behat/Behat/Definition/Printer/ConsoleDefinitionInformationPrinter.php +++ b/src/Behat/Behat/Definition/Printer/ConsoleDefinitionInformationPrinter.php @@ -39,12 +39,37 @@ public function setSearchCriterion($criterion) * {@inheritdoc} */ public function printDefinitions(Suite $suite, $definitions) + { + $this->printDefinitionsWithOptionalSuite($definitions, $suite); + } + + /** + * @param Definition[] $definitions + */ + public function printUnusedDefinitions(array $definitions): void + { + $unusedDefinitionsText = $this->translateInfoText( + 'unused_definitions', + ['%count%' => count($definitions)] + ); + $this->write('--- ' . $unusedDefinitionsText, true); + if (count($definitions) !== 0) { + $this->printDefinitionsWithOptionalSuite($definitions); + } + } + + /** + * @param Definition[] $definitions + */ + private function printDefinitionsWithOptionalSuite(array $definitions, ?Suite $suite = null): void { $search = $this->searchCriterion; $output = array(); foreach ($definitions as $definition) { - $definition = $this->translateDefinition($suite, $definition); + if ($suite) { + $definition = $this->translateDefinition($suite, $definition); + } $pattern = $definition->getPattern(); if (null !== $search && false === mb_strpos($pattern, $search, 0, 'utf8')) { @@ -66,19 +91,17 @@ public function printDefinitions(Suite $suite, $definitions) /** * Extracts the formatted header from the definition. * - * @param Suite $suite - * @param Definition $definition - * * @return string[] */ - private function extractHeader(Suite $suite, Definition $definition) + private function extractHeader(?Suite $suite, Definition $definition): array { $pattern = $definition->getPattern(); $lines = array(); + $indent = $suite ? '{suite} ' : ''; $lines[] = strtr( - '{suite} ', + $indent . ' ', array( - '{suite}' => $suite->getName(), + '{suite}' => $suite ? $suite->getName() : '', '{type}' => $this->getDefinitionType($definition), '{regex}' => $pattern, ) @@ -90,22 +113,18 @@ private function extractHeader(Suite $suite, Definition $definition) /** * Extracts the formatted description from the definition. * - * @param Suite $suite - * @param Definition $definition - * * @return string[] */ - private function extractDescription(Suite $suite, Definition $definition) + private function extractDescription(?Suite $suite, Definition $definition): array { - $definition = $this->translateDefinition($suite, $definition); - $lines = array(); if ($description = $definition->getDescription()) { + $indent = $suite ? '{space} ' : ''; foreach (explode("\n", $description) as $descriptionLine) { $lines[] = strtr( - '{space} {description}', + $indent . '{description}', array( - '{space}' => str_pad('', mb_strlen($suite->getName(), 'utf8') + 1), + '{space}' => $suite ? str_pad('', mb_strlen($suite->getName(), 'utf8') + 1) : '', '{description}' => $descriptionLine ) ); @@ -118,27 +137,26 @@ private function extractDescription(Suite $suite, Definition $definition) /** * Extracts the formatted footer from the definition. * - * @param Suite $suite - * @param Definition $definition - * * @return string[] */ - private function extractFooter(Suite $suite, Definition $definition) + private function extractFooter(?Suite $suite, Definition $definition): array { $lines = array(); + $indent = $suite ? '{space} at ' : ''; $lines[] = strtr( - '{space} at `{path}`', + $indent . '`{path}`', array( - '{space}' => str_pad('', mb_strlen($suite->getName(), 'utf8') + 1), + '{space}' => $suite ? str_pad('', mb_strlen($suite->getName(), 'utf8') + 1) : '', '{path}' => $definition->getPath() ) ); if ($this->isVerbose()) { + $indent = $suite ? '{space} on ' : ''; $lines[] = strtr( - '{space} on `{filepath}[{start}:{end}]`', + $indent . '`{filepath}[{start}:{end}]`', array( - '{space}' => str_pad('', mb_strlen($suite->getName(), 'utf8') + 1), + '{space}' => $suite ? str_pad('', mb_strlen($suite->getName(), 'utf8') + 1) : '', '{filepath}' => $definition->getReflection()->getFileName(), '{start}' => $definition->getReflection()->getStartLine(), '{end}' => $definition->getReflection()->getEndLine() diff --git a/src/Behat/Behat/Definition/Printer/ConsoleDefinitionPrinter.php b/src/Behat/Behat/Definition/Printer/ConsoleDefinitionPrinter.php index f4a0fc4d3..95b0cead8 100644 --- a/src/Behat/Behat/Definition/Printer/ConsoleDefinitionPrinter.php +++ b/src/Behat/Behat/Definition/Printer/ConsoleDefinitionPrinter.php @@ -67,8 +67,11 @@ public function __construct( * * @param string $text */ - final protected function write($text) + final protected function write($text, bool $addEmptyLine = false) { + if ($addEmptyLine) { + $this->output->writeln(''); + } $this->output->writeln($text); $this->output->writeln(''); } @@ -101,6 +104,11 @@ final protected function translateDefinition(Suite $suite, Definition $definitio return $this->translator->translateDefinition($suite, $definition); } + final protected function translateInfoText(string $infoText, array $parameters): string + { + return $this->translator->translateInfoText($infoText, $parameters); + } + /** * Returns whether verbosity is verbose (-v). * diff --git a/src/Behat/Behat/Definition/ServiceContainer/DefinitionExtension.php b/src/Behat/Behat/Definition/ServiceContainer/DefinitionExtension.php index 8a947a8e6..6a3005d72 100644 --- a/src/Behat/Behat/Definition/ServiceContainer/DefinitionExtension.php +++ b/src/Behat/Behat/Definition/ServiceContainer/DefinitionExtension.php @@ -15,6 +15,7 @@ use Behat\Behat\Gherkin\ServiceContainer\GherkinExtension; use Behat\Testwork\Cli\ServiceContainer\CliExtension; use Behat\Testwork\Environment\ServiceContainer\EnvironmentExtension; +use Behat\Testwork\EventDispatcher\ServiceContainer\EventDispatcherExtension; use Behat\Testwork\ServiceContainer\Extension; use Behat\Testwork\ServiceContainer\ExtensionManager; use Behat\Testwork\ServiceContainer\ServiceProcessor; @@ -100,7 +101,7 @@ public function load(ContainerBuilder $container, array $config) $this->loadAnnotationReader($container); $this->loadAttributeReader($container); $this->loadDefinitionPrinters($container); - $this->loadController($container); + $this->loadControllers($container); $this->loadDocblockHelper($container); } @@ -258,12 +259,7 @@ private function loadDefinitionPrinters(ContainerBuilder $container) $container->setDefinition($this->getListPrinterId(), $definition); } - /** - * Loads definition controller. - * - * @param ContainerBuilder $container - */ - private function loadController(ContainerBuilder $container) + private function loadControllers(ContainerBuilder $container) { $definition = new Definition('Behat\Behat\Definition\Cli\AvailableDefinitionsController', array( new Reference(SuiteExtension::REGISTRY_ID), @@ -273,6 +269,14 @@ private function loadController(ContainerBuilder $container) )); $definition->addTag(CliExtension::CONTROLLER_TAG, array('priority' => 500)); $container->setDefinition(CliExtension::CONTROLLER_TAG . '.available_definitions', $definition); + + $definition = new Definition('Behat\Behat\Definition\Cli\UnusedDefinitionsController', array( + new Reference(self::REPOSITORY_ID), + new Reference(EventDispatcherExtension::DISPATCHER_ID), + new Reference($this->getInformationPrinterId()) + )); + $definition->addTag(CliExtension::CONTROLLER_TAG, array('priority' => 300)); + $container->setDefinition(CliExtension::CONTROLLER_TAG . '.unused_definitions', $definition); } /** diff --git a/src/Behat/Behat/Definition/Translator/DefinitionTranslator.php b/src/Behat/Behat/Definition/Translator/DefinitionTranslator.php index 105d61c50..f997e4029 100644 --- a/src/Behat/Behat/Definition/Translator/DefinitionTranslator.php +++ b/src/Behat/Behat/Definition/Translator/DefinitionTranslator.php @@ -57,6 +57,11 @@ public function translateDefinition(Suite $suite, Definition $definition, $langu return $definition; } + public function translateInfoText(string $infoText, array $parameters): string + { + return $this->translator->trans($infoText, $parameters, 'output'); + } + public function getLocale() { return $this->translator->getLocale(); diff --git a/src/Behat/Behat/Tester/Runtime/RuntimeStepTester.php b/src/Behat/Behat/Tester/Runtime/RuntimeStepTester.php index 46959f6de..2de56aea9 100644 --- a/src/Behat/Behat/Tester/Runtime/RuntimeStepTester.php +++ b/src/Behat/Behat/Tester/Runtime/RuntimeStepTester.php @@ -11,6 +11,7 @@ namespace Behat\Behat\Tester\Runtime; use Behat\Behat\Definition\Call\DefinitionCall; +use Behat\Behat\Definition\Call\RuntimeDefinition; use Behat\Behat\Definition\DefinitionFinder; use Behat\Behat\Definition\Exception\SearchException; use Behat\Behat\Definition\SearchResult; @@ -117,6 +118,11 @@ private function testDefinition(Environment $env, FeatureNode $feature, StepNode return new UndefinedStepResult(); } + $definition = $search->getMatchedDefinition(); + if ($definition instanceof RuntimeDefinition) { + $definition->markAsUsed(); + } + if ($skip) { return new SkippedStepResult($search); } diff --git a/tests/Fixtures/UnusedDefinitions/behat.php b/tests/Fixtures/UnusedDefinitions/behat.php new file mode 100644 index 000000000..ef1b3a5d3 --- /dev/null +++ b/tests/Fixtures/UnusedDefinitions/behat.php @@ -0,0 +1,19 @@ +withProfile((new Profile('default')) + ->withSuite((new Suite('first_suite')) + ->withPaths( + 'features/first_feature.feature' + ) + ) + ->withSuite((new Suite('second_suite')) + ->withPaths( + 'features/second_feature.feature', + ) + ) + ); diff --git a/tests/Fixtures/UnusedDefinitions/features/bootstrap/FeatureContext.php b/tests/Fixtures/UnusedDefinitions/features/bootstrap/FeatureContext.php new file mode 100644 index 000000000..36fbd1d81 --- /dev/null +++ b/tests/Fixtures/UnusedDefinitions/features/bootstrap/FeatureContext.php @@ -0,0 +1,39 @@ + Date: Thu, 6 Feb 2025 19:24:09 +0100 Subject: [PATCH 553/567] Small changes after PR review --- .../Behat/Definition/Cli/UnusedDefinitionsController.php | 4 +--- .../Behat/Definition/Printer/ConsoleDefinitionPrinter.php | 4 ++-- src/Behat/Behat/Tester/Runtime/RuntimeStepTester.php | 2 ++ 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/src/Behat/Behat/Definition/Cli/UnusedDefinitionsController.php b/src/Behat/Behat/Definition/Cli/UnusedDefinitionsController.php index ce6d983d2..f40437dcc 100644 --- a/src/Behat/Behat/Definition/Cli/UnusedDefinitionsController.php +++ b/src/Behat/Behat/Definition/Cli/UnusedDefinitionsController.php @@ -81,9 +81,7 @@ public function registerDefinitionUsages(AfterSuiteTested $event): void public function printUnusedDefinitions(): void { - $unusedDefinitions = array_filter($this->definitionUsage, function ($definition) { - return $definition['used'] === false; - }); + $unusedDefinitions = array_filter($this->definitionUsage, fn ($definition) => $definition['used'] === false); $unusedDefinitions = array_column($unusedDefinitions, 'definition'); $this->printer->printUnusedDefinitions($unusedDefinitions); diff --git a/src/Behat/Behat/Definition/Printer/ConsoleDefinitionPrinter.php b/src/Behat/Behat/Definition/Printer/ConsoleDefinitionPrinter.php index 95b0cead8..840795865 100644 --- a/src/Behat/Behat/Definition/Printer/ConsoleDefinitionPrinter.php +++ b/src/Behat/Behat/Definition/Printer/ConsoleDefinitionPrinter.php @@ -67,9 +67,9 @@ public function __construct( * * @param string $text */ - final protected function write($text, bool $addEmptyLine = false) + final protected function write($text, bool $lineBreakBefore = false) { - if ($addEmptyLine) { + if ($lineBreakBefore) { $this->output->writeln(''); } $this->output->writeln($text); diff --git a/src/Behat/Behat/Tester/Runtime/RuntimeStepTester.php b/src/Behat/Behat/Tester/Runtime/RuntimeStepTester.php index 2de56aea9..ddd60b14b 100644 --- a/src/Behat/Behat/Tester/Runtime/RuntimeStepTester.php +++ b/src/Behat/Behat/Tester/Runtime/RuntimeStepTester.php @@ -118,6 +118,8 @@ private function testDefinition(Environment $env, FeatureNode $feature, StepNode return new UndefinedStepResult(); } + // If a definition has been found, we mark it as used even if it may be skipped, + // as we want to count skipped definitions as used $definition = $search->getMatchedDefinition(); if ($definition instanceof RuntimeDefinition) { $definition->markAsUsed(); From 7d550cbf4bd5a092ab0bccf1df919e8e5f4f38ab Mon Sep 17 00:00:00 2001 From: Carlos Granados ||{type}{regex}{type}{regex}|||||| Date: Thu, 6 Feb 2025 19:42:43 +0100 Subject: [PATCH 554/567] Fix Coding Standard --- .../Cli/UnusedDefinitionsController.php | 4 +++- tests/Fixtures/UnusedDefinitions/behat.php | 9 ++++++--- .../features/bootstrap/FeatureContext.php | 18 ++++++++++++------ 3 files changed, 21 insertions(+), 10 deletions(-) diff --git a/src/Behat/Behat/Definition/Cli/UnusedDefinitionsController.php b/src/Behat/Behat/Definition/Cli/UnusedDefinitionsController.php index f40437dcc..77823094a 100644 --- a/src/Behat/Behat/Definition/Cli/UnusedDefinitionsController.php +++ b/src/Behat/Behat/Definition/Cli/UnusedDefinitionsController.php @@ -46,7 +46,9 @@ public function configure(Command $command): void { $command ->addOption( - '--print-unused-definitions', null, InputOption::VALUE_NONE, + '--print-unused-definitions', + null, + InputOption::VALUE_NONE, "Reports definitions that were never used." ) ; diff --git a/tests/Fixtures/UnusedDefinitions/behat.php b/tests/Fixtures/UnusedDefinitions/behat.php index ef1b3a5d3..8e925be15 100644 --- a/tests/Fixtures/UnusedDefinitions/behat.php +++ b/tests/Fixtures/UnusedDefinitions/behat.php @@ -5,13 +5,16 @@ use Behat\Config\Suite; return (new Config()) - ->withProfile((new Profile('default')) - ->withSuite((new Suite('first_suite')) + ->withProfile( + (new Profile('default')) + ->withSuite( + (new Suite('first_suite')) ->withPaths( 'features/first_feature.feature' ) ) - ->withSuite((new Suite('second_suite')) + ->withSuite( + (new Suite('second_suite')) ->withPaths( 'features/second_feature.feature', ) diff --git a/tests/Fixtures/UnusedDefinitions/features/bootstrap/FeatureContext.php b/tests/Fixtures/UnusedDefinitions/features/bootstrap/FeatureContext.php index 36fbd1d81..1b8c2f767 100644 --- a/tests/Fixtures/UnusedDefinitions/features/bootstrap/FeatureContext.php +++ b/tests/Fixtures/UnusedDefinitions/features/bootstrap/FeatureContext.php @@ -10,30 +10,36 @@ class FeatureContext implements Context { #[Given('I call a step used in the first feature')] - public function stepUsedInFirstFeature(): void { + public function stepUsedInFirstFeature(): void + { } #[When('I call a step used in both features')] - public function stepUsedInBothFeatures(): void { + public function stepUsedInBothFeatures(): void + { } #[When('I call a pending step')] - public function pendingStep(): void { + public function pendingStep(): void + { throw new PendingException(); } #[When('I call a skipped step')] - public function skippedStep(): void { + public function skippedStep(): void + { } #[Then('I call a step used in the second feature')] - public function stepUsedInSecondFeature(): void { + public function stepUsedInSecondFeature(): void + { } /** * This is a step that is never used and should be removed */ #[Then('I call a step not used in any feature')] - public function stepNotUsedInAnyFeature(): void { + public function stepNotUsedInAnyFeature(): void + { } } From a79ffc8e76250a16c1ecc0f09c535b829cb74235 Mon Sep 17 00:00:00 2001 From: Carlos Granados Date: Thu, 6 Feb 2025 19:49:14 +0100 Subject: [PATCH 555/567] Add option in yaml and php config --- features/unused_definitions.feature | 26 +++++++++++++++++++ .../Cli/UnusedDefinitionsController.php | 4 +++ .../ServiceContainer/DefinitionExtension.php | 13 +++++++--- src/Behat/Config/Profile.php | 7 +++++ tests/Fixtures/UnusedDefinitions/behat.php | 9 ++++++- .../UnusedDefinitions/unused_definitions.yaml | 3 +++ 6 files changed, 58 insertions(+), 4 deletions(-) create mode 100644 tests/Fixtures/UnusedDefinitions/unused_definitions.yaml diff --git a/features/unused_definitions.feature b/features/unused_definitions.feature index dd098a40d..5ceb46288 100644 --- a/features/unused_definitions.feature +++ b/features/unused_definitions.feature @@ -39,3 +39,29 @@ Feature: Unused definitions This is a step that is never used and should be removed `FeatureContext::stepNotUsedInAnyFeature()` """ + + Scenario: Print unused definitions from yaml config + When I run behat with the following additional options: + | option | value | + | --config | unused_definitions.yaml | + Then it should pass with: + """ + --- 1 unused definition: + + [Then|*] I call a step not used in any feature + This is a step that is never used and should be removed + `FeatureContext::stepNotUsedInAnyFeature()` + """ + + Scenario: Print unused definitions from PHP config + When I run behat with the following additional options: + | option | value | + | --profile | unused_definitions | + Then it should pass with: + """ + --- 1 unused definition: + + [Then|*] I call a step not used in any feature + This is a step that is never used and should be removed + `FeatureContext::stepNotUsedInAnyFeature()` + """ diff --git a/src/Behat/Behat/Definition/Cli/UnusedDefinitionsController.php b/src/Behat/Behat/Definition/Cli/UnusedDefinitionsController.php index 77823094a..c3810ef51 100644 --- a/src/Behat/Behat/Definition/Cli/UnusedDefinitionsController.php +++ b/src/Behat/Behat/Definition/Cli/UnusedDefinitionsController.php @@ -39,6 +39,7 @@ public function __construct( private DefinitionRepository $definitionRepository, private EventDispatcherInterface $eventDispatcher, private ConsoleDefinitionInformationPrinter $printer, + private bool $printUnusedDefinitions ) { } @@ -57,6 +58,9 @@ public function configure(Command $command): void public function execute(InputInterface $input, OutputInterface $output): ?int { if ($input->getOption('print-unused-definitions')) { + $this->printUnusedDefinitions = true; + } + if ($this->printUnusedDefinitions) { $this->eventDispatcher->addListener(SuiteTested::AFTER, array($this, 'registerDefinitionUsages'), -999); $this->eventDispatcher->addListener(ExerciseCompleted::AFTER, array($this, 'printUnusedDefinitions'), -999); } diff --git a/src/Behat/Behat/Definition/ServiceContainer/DefinitionExtension.php b/src/Behat/Behat/Definition/ServiceContainer/DefinitionExtension.php index 6a3005d72..705947d62 100644 --- a/src/Behat/Behat/Definition/ServiceContainer/DefinitionExtension.php +++ b/src/Behat/Behat/Definition/ServiceContainer/DefinitionExtension.php @@ -84,6 +84,12 @@ public function initialize(ExtensionManager $extensionManager) */ public function configure(ArrayNodeDefinition $builder) { + $builder + ->addDefaultsIfNotSet() + ->children() + ->scalarNode('print_unused_definitions') + ->defaultFalse() + ; } /** @@ -101,7 +107,7 @@ public function load(ContainerBuilder $container, array $config) $this->loadAnnotationReader($container); $this->loadAttributeReader($container); $this->loadDefinitionPrinters($container); - $this->loadControllers($container); + $this->loadControllers($container, $config['print_unused_definitions']); $this->loadDocblockHelper($container); } @@ -259,7 +265,7 @@ private function loadDefinitionPrinters(ContainerBuilder $container) $container->setDefinition($this->getListPrinterId(), $definition); } - private function loadControllers(ContainerBuilder $container) + private function loadControllers(ContainerBuilder $container, bool $printUnusedDefinitions): void { $definition = new Definition('Behat\Behat\Definition\Cli\AvailableDefinitionsController', array( new Reference(SuiteExtension::REGISTRY_ID), @@ -273,7 +279,8 @@ private function loadControllers(ContainerBuilder $container) $definition = new Definition('Behat\Behat\Definition\Cli\UnusedDefinitionsController', array( new Reference(self::REPOSITORY_ID), new Reference(EventDispatcherExtension::DISPATCHER_ID), - new Reference($this->getInformationPrinterId()) + new Reference($this->getInformationPrinterId()), + $printUnusedDefinitions )); $definition->addTag(CliExtension::CONTROLLER_TAG, array('priority' => 300)); $container->setDefinition(CliExtension::CONTROLLER_TAG . '.unused_definitions', $definition); diff --git a/src/Behat/Config/Profile.php b/src/Behat/Config/Profile.php index 70664c090..d01bd38a9 100644 --- a/src/Behat/Config/Profile.php +++ b/src/Behat/Config/Profile.php @@ -68,6 +68,13 @@ public function disableFormatter(string $name): self return $this; } + public function withPrintUnusedDefinitions(bool $printUnusedDefinitions = true): self + { + $this->settings['definitions']['print_unused_definitions'] = $printUnusedDefinitions; + + return $this; + } + public function toArray(): array { return $this->settings; diff --git a/tests/Fixtures/UnusedDefinitions/behat.php b/tests/Fixtures/UnusedDefinitions/behat.php index 8e925be15..d72db48ed 100644 --- a/tests/Fixtures/UnusedDefinitions/behat.php +++ b/tests/Fixtures/UnusedDefinitions/behat.php @@ -19,4 +19,11 @@ 'features/second_feature.feature', ) ) - ); + ) + ->withProfile( + (new Profile('unused_definitions')) + ->withPrintUnusedDefinitions() + ) +; + +; diff --git a/tests/Fixtures/UnusedDefinitions/unused_definitions.yaml b/tests/Fixtures/UnusedDefinitions/unused_definitions.yaml new file mode 100644 index 000000000..ab26e3548 --- /dev/null +++ b/tests/Fixtures/UnusedDefinitions/unused_definitions.yaml @@ -0,0 +1,3 @@ +default: + definitions: + print_unused_definitions: true From e06965f553a9a1f7d47493f417bb49e34e96e853 Mon Sep 17 00:00:00 2001 From: Carlos Granados Date: Thu, 23 Jan 2025 21:38:04 +0100 Subject: [PATCH 556/567] chore: refactor Transformation tests into new test format with Fixtures --- ...itions_transformations_annotations.feature | 708 ++---------------- ...nitions_transformations_attributes.feature | 176 +---- tests/Fixtures/Transformations/behat.php | 149 ++++ .../ByTypeAndByNameAnnotationsContext.php | 48 ++ .../bootstrap/ByTypeAnnotationsContext.php | 38 + .../ByTypeUnionAnnotationsContext.php | 19 + ...rmationsInOneFunctionAttributesContext.php | 14 + .../MultipleTypesAnnotationsContext.php | 58 ++ ...rdinalTransformationAnnotationsContext.php | 24 + .../ScalarTypeAnnotationsContext.php | 23 + .../SimpleTransformationAttributesContext.php | 18 + .../TransformationAnnotationsContext.php | 98 +++ ...tionWithoutParametersAttributesContext.php | 13 + .../features/bootstrap/User.php | 20 + .../bootstrap/UserAnnotationsContext.php | 47 ++ .../bootstrap/UserAttributesContext.php | 35 + .../WholeTableAnnotationsContext.php | 25 + ..._and_by_name_object_transformation.feature | 9 + .../by_type_object_transformation.feature | 9 + .../by_type_union_transformation.feature | 7 + ...le_transformations_in_one_function.feature | 13 + .../named_argument_transformation.feature | 11 + .../ordinal_argument_transformation.feature | 19 + .../row_table_argument_transformation.feature | 31 + .../scalar_type_transformation.feature | 6 + ...imple_step_argument_transformation.feature | 14 + ..._transformation_without_parameters.feature | 7 + .../table_argument_transformation.feature | 31 + .../table_row_argument_transformation.feature | 27 + .../transform_different_types.feature | 14 + ...code_named_argument_transformation.feature | 11 + ...hole_table_argument_transformation.feature | 10 + 32 files changed, 922 insertions(+), 810 deletions(-) create mode 100644 tests/Fixtures/Transformations/behat.php create mode 100644 tests/Fixtures/Transformations/features/bootstrap/ByTypeAndByNameAnnotationsContext.php create mode 100644 tests/Fixtures/Transformations/features/bootstrap/ByTypeAnnotationsContext.php create mode 100644 tests/Fixtures/Transformations/features/bootstrap/ByTypeUnionAnnotationsContext.php create mode 100644 tests/Fixtures/Transformations/features/bootstrap/MultipleTransformationsInOneFunctionAttributesContext.php create mode 100644 tests/Fixtures/Transformations/features/bootstrap/MultipleTypesAnnotationsContext.php create mode 100644 tests/Fixtures/Transformations/features/bootstrap/OrdinalTransformationAnnotationsContext.php create mode 100644 tests/Fixtures/Transformations/features/bootstrap/ScalarTypeAnnotationsContext.php create mode 100644 tests/Fixtures/Transformations/features/bootstrap/SimpleTransformationAttributesContext.php create mode 100644 tests/Fixtures/Transformations/features/bootstrap/TransformationAnnotationsContext.php create mode 100644 tests/Fixtures/Transformations/features/bootstrap/TransformationWithoutParametersAttributesContext.php create mode 100644 tests/Fixtures/Transformations/features/bootstrap/User.php create mode 100644 tests/Fixtures/Transformations/features/bootstrap/UserAnnotationsContext.php create mode 100644 tests/Fixtures/Transformations/features/bootstrap/UserAttributesContext.php create mode 100644 tests/Fixtures/Transformations/features/bootstrap/WholeTableAnnotationsContext.php create mode 100644 tests/Fixtures/Transformations/features/by_type_and_by_name_object_transformation.feature create mode 100644 tests/Fixtures/Transformations/features/by_type_object_transformation.feature create mode 100644 tests/Fixtures/Transformations/features/by_type_union_transformation.feature create mode 100644 tests/Fixtures/Transformations/features/multiple_transformations_in_one_function.feature create mode 100644 tests/Fixtures/Transformations/features/named_argument_transformation.feature create mode 100644 tests/Fixtures/Transformations/features/ordinal_argument_transformation.feature create mode 100644 tests/Fixtures/Transformations/features/row_table_argument_transformation.feature create mode 100644 tests/Fixtures/Transformations/features/scalar_type_transformation.feature create mode 100644 tests/Fixtures/Transformations/features/simple_step_argument_transformation.feature create mode 100644 tests/Fixtures/Transformations/features/step_argument_transformation_without_parameters.feature create mode 100644 tests/Fixtures/Transformations/features/table_argument_transformation.feature create mode 100644 tests/Fixtures/Transformations/features/table_row_argument_transformation.feature create mode 100644 tests/Fixtures/Transformations/features/transform_different_types.feature create mode 100644 tests/Fixtures/Transformations/features/unicode_named_argument_transformation.feature create mode 100644 tests/Fixtures/Transformations/features/whole_table_argument_transformation.feature diff --git a/features/definitions_transformations_annotations.feature b/features/definitions_transformations_annotations.feature index 9d00ca82b..56861284a 100644 --- a/features/definitions_transformations_annotations.feature +++ b/features/definitions_transformations_annotations.feature @@ -4,183 +4,17 @@ Feature: Step Arguments Transformations Annotations I need to use transformation functions using annotations Background: - Given a file named "features/bootstrap/User.php" with: - """ - username = $username; - $this->age = $age; - } - - public function getUsername() { return $this->username; } - public function getAge() { return $this->age; } - } - """ - And a file named "features/bootstrap/FeatureContext.php" with: - """ - getHash(); - $username = $hash[0]['username']; - $age = $hash[0]['age']; - - return new User($username, $age); - } - - /** @Transform table:логин,возраст */ - public function createUserFromTableInRussian(TableNode $table) { - $hash = $table->getHash(); - $username = $hash[0]['логин']; - $age = $hash[0]['возраст']; - - return new User($username, $age); - } - - /** @Transform rowtable:username,age */ - public function createUserFromRowTable(TableNode $table) { - $hash = $table->getRowsHash(); - $username = $hash['username']; - $age = $hash['age']; - - return new User($username, $age); - } - - /** @Transform rowtable:логин,возраст */ - public function createUserFromRowTableInRussian(TableNode $table) { - $hash = $table->getRowsHash(); - $username = $hash['логин']; - $age = $hash['возраст']; - - return new User($username, $age); - } - - /** @Transform row:username */ - public function createUserNamesFromTable($tableRow) { - return $tableRow['username']; - } - - /** @Transform row:логин */ - public function createUserNamesFromTableInRussian($tableRow) { - return $tableRow['логин']; - } - - /** @Transform table:%username@,age# */ - public function createUserFromTableWithSymbol(TableNode $table) { - $hash = $table->getHash(); - $username = $hash[0]['%username@']; - $age = $hash[0]['age#']; - - return new User($username, $age); - } - - /** @Transform rowtable:--username,age */ - public function createUserFromRowTableWithSymbol(TableNode $table) { - $hash = $table->getRowsHash(); - $username = $hash['--username']; - $age = $hash['age']; - - return new User($username, $age); - } - - /** @Transform row:$username */ - public function createUserNamesFromTableWithSymbol($tableRow) { - return $tableRow['$username']; - } - - /** @Transform /^\d+$/ */ - public function castToNumber($number) { - return intval($number); - } - - /** @Transform :user */ - public function castToUser($username) { - return new User($username); - } - - /** - * @Transform /^(yes|no)$/ - */ - public function castEinenOrKeinenToBoolean($expected) { - return 'yes' === $expected; - } - - /** - * @Given /I am (".*" user)/ - * @Given I am user: - * @Given I am :user - */ - public function iAmUser(User $user) { - $this->user = $user; - } - - /** - * @Then /Username must be "([^"]+)"/ - */ - public function usernameMustBe($username) { - PHPUnit\Framework\Assert::assertEquals($username, $this->user->getUsername()); - } - - /** - * @Then /Age must be (\d+)/ - */ - public function ageMustBe($age) { - PHPUnit\Framework\Assert::assertEquals($age, $this->user->getAge()); - PHPUnit\Framework\Assert::assertIsInt($age); - } - - /** - * @Then the Usernames must be: - */ - public function usernamesMustBe(array $usernames) { - PHPUnit\Framework\Assert::assertEquals($usernames[0], $this->user->getUsername()); - } - - /** - * @Then /^the boolean (no) should be transformed to false$/ - */ - public function theBooleanShouldBeTransformed($boolean) { - PHPUnit\Framework\Assert::assertSame(false, $boolean); - } - } - """ + Given I set the working directory to the "Transformations" fixtures folder + And I provide the following options for all behat invocations: + | option | value | + | --no-colors | | + | --format | progress | + | --profile | annotations | Scenario: Simple Arguments Transformations - Given a file named "features/step_arguments.feature" with: - """ - Feature: Step Arguments - Scenario: - Given I am "everzet" user - Then Username must be "everzet" - And Age must be 20 - And the boolean no should be transformed to false - - Scenario: - Given I am "antono - 29" user - Then Username must be "antono" - And Age must be 29 - """ - When I run "behat -f progress --no-colors" + When I run behat with the following additional options: + | option | value | + | --suite | simple_step_argument_transformation | Then it should pass with: """ ....... @@ -190,163 +24,45 @@ Feature: Step Arguments Transformations Annotations """ Scenario: Table Arguments Transformations - Given a file named "features/table_arguments.feature" with: - """ - Feature: Step Arguments - Scenario: - Given I am user: - | username | age | - | ever.zet | 22 | - Then Username must be "ever.zet" - And Age must be 22 - - Scenario: - Given I am user: - | username | age | - | vasiljev | 30 | - Then Username must be "vasiljev" - And Age must be 30 - - Scenario: - Given I am user: - | логин | возраст | - | vasiljev | 30 | - Then Username must be "vasiljev" - And Age must be 30 - - Scenario: - Given I am user: - | %username@ | age# | - | rajesh | 35 | - Then Username must be "rajesh" - And Age must be 35 - """ - When I run "behat -f progress --no-colors" + When I run behat with the following additional options: + | option | value | + | --suite | table_argument_transformation | Then it should pass with: """ - ............ + ...... - 4 scenarios (4 passed) - 12 steps (12 passed) + 3 scenarios (3 passed) + 9 steps (9 passed) """ Scenario: Row Table Arguments Transformations - Given a file named "features/row_table_arguments.feature" with: - """ - Feature: Step Arguments - Scenario: - Given I am user: - | username | ever.zet | - | age | 22 | - Then Username must be "ever.zet" - And Age must be 22 - - Scenario: - Given I am user: - | username | vasiljev | - | age | 30 | - Then Username must be "vasiljev" - And Age must be 30 - - Scenario: - Given I am user: - | логин | vasiljev | - | возраст | 30 | - Then Username must be "vasiljev" - And Age must be 30 - - Scenario: - Given I am user: - | --username | rajesh | - | age | 35 | - Then Username must be "rajesh" - And Age must be 35 - """ - When I run "behat -f progress --no-colors" + When I run behat with the following additional options: + | option | value | + | --suite | row_table_argument_transformation | Then it should pass with: """ - ............ + ...... - 4 scenarios (4 passed) - 12 steps (12 passed) + 3 scenarios (3 passed) + 9 steps (9 passed) """ Scenario: Table Row Arguments Transformations - Given a file named "features/table_row_arguments.feature" with: - """ - Feature: Step Arguments - Scenario: - Given I am user: - | username | age | - | ever.zet | 22 | - Then the Usernames must be: - | username | - | ever.zet | - - Scenario: - Given I am user: - | %username@ | age# | - | rajesh | 35 | - Then the Usernames must be: - | $username | - | rajesh | - - Scenario: - Given I am user: - | username | age | - | ever.zet | 22 | - Then the Usernames must be: - | логин | - | ever.zet | - """ - When I run "behat -f progress --no-colors" + When I run behat with the following additional options: + | option | value | + | --suite | table_row_argument_transformation | Then it should pass with: """ - ...... + .... - 3 scenarios (3 passed) - 6 steps (6 passed) + 2 scenarios (2 passed) + 4 steps (4 passed) """ Scenario: Whole table transformation - Given a file named "features/bootstrap/FeatureContext.php" with: - """ - getHash(); - } - - /** @Given data: */ - public function givenData(array $data) { - $this->data = $data; - } - - /** @Then the :field should be :value */ - public function theFieldShouldBe($field, $value) { - PHPUnit\Framework\Assert::assertSame($value, $this->data[0][$field]); - } - } - """ - And a file named "features/table.feature" with: - """ - Feature: - Scenario: - Given data: - | username | age | - | ever.zet | 22 | - Then the "username" should be "ever.zet" - And the "age" should be 22 - """ - When I run "behat -f progress --no-colors" + When I run behat with the following additional options: + | option | value | + | --suite | whole_table_argument_transformation | Then it should pass with: """ ... @@ -356,18 +72,9 @@ Feature: Step Arguments Transformations Annotations """ Scenario: Named Arguments Transformations - Given a file named "features/step_arguments.feature" with: - """ - Feature: Step Arguments - Scenario: - Given I am "everzet" - Then Username must be "everzet" - - Scenario: - Given I am "antono" - Then Username must be "antono" - """ - When I run "behat -f progress --no-colors" + When I run behat with the following additional options: + | option | value | + | --suite | named_argument_transformation | Then it should pass with: """ .... @@ -377,86 +84,9 @@ Feature: Step Arguments Transformations Annotations """ Scenario: Transforming different types - Given a file named "features/to_null.feature" with: - """ - Feature: I should be able to transform values into different types for testing - - Scenario Outline: Converting different types - Given I have the value "" - Then it should be of type "" - - Examples: - | value | type | - | "soeuhtou" | string | - | 34 | integer | - | null | NULL | - | 2 workdays ago | DateTime | - """ - And a file named "features/bootstrap/FeatureContext.php" with: - """ - value); - } - - /** - * @Transform /^".*"$/ - */ - public function transformString($string) - { - return strval($string); - } - - /** - * @Transform :number workdays ago - */ - public function transformDate($number) - { - return new \DateTime("-$number days"); - } - - /** - * @Transform /^\d+$/ - */ - public function transformInt($int) - { - return intval($int); - } - - /** - * @Transform /^null/ - */ - public function transformNull($null) - { - return null; - } - - /** - * @Given I have the value ":value" - */ - public function iHaveTheValue($value) - { - $this->value = $value; - } - - /** - * @Then it should be of type :type - */ - public function itShouldBeOfType($type) - { - if (gettype($this->value) != $type && get_class($this->value) != $type) { - throw new Exception("Expected " . $type . ", got " . gettype($this->value) . " (value: " . var_export($this->value, true) . ")"); - } - } - } - """ - When I run "behat -f progress --no-colors" + When I run behat with the following additional options: + | option | value | + | --suite | transform_different_types | Then it should pass with: """ ........ @@ -466,65 +96,9 @@ Feature: Step Arguments Transformations Annotations """ Scenario: By-type object transformations - Given a file named "features/my.feature" with: - """ - Feature: - Scenario: - Given I am "everzet" - And he is "sroze" - Then I should be a user named "everzet" - And he should be a user named "sroze" - """ - And a file named "features/bootstrap/FeatureContext.php" with: - """ - name = $name; } - static public function named($name) { return new static($name); } - } - class FeatureContext implements Behat\Behat\Context\Context - { - private $I; - private $he; - - /** @Transform */ - public function userFromName($name) : User { - return User::named($name); - } - - /** @Given I am :user */ - public function iAm(User $user) { - $this->I = $user; - } - - /** @Given /^he is \"([^\"]+)\"$/ */ - public function heIs(User $user) { - $this->he = $user; - } - - /** @Then I should be a user named :name */ - public function iShouldHaveName($name) { - if ('User' !== get_class($this->I)) { - throw new Exception("User expected, {gettype($this->I)} given"); - } - if ($name !== $this->I->name) { - throw new Exception("Actual name is {$this->I->name}"); - } - } - - /** @Then he should be a user named :name */ - public function heShouldHaveName($name) { - if ('User' !== get_class($this->he)) { - throw new Exception("User expected, {gettype($this->he)} given"); - } - if ($name !== $this->he->name) { - throw new Exception("Actual name is {$this->he->name}"); - } - } - } - """ - When I run "behat -f progress --no-colors" + When I run behat with the following additional options: + | option | value | + | --suite | by_type_object_transformation | Then it should pass with: """ .... @@ -534,75 +108,9 @@ Feature: Step Arguments Transformations Annotations """ Scenario: By-type and by-name object transformations - Given a file named "features/my.feature" with: - """ - Feature: - Scenario: - Given I am "everzet" - And she is "lunivore" - Then I should be a user named "everzet" - And she should be an admin named "admin: lunivore" - """ - And a file named "features/bootstrap/FeatureContext.php" with: - """ - name = $name; } - static public function named($name) { return new static($name); } - } - class FeatureContext implements Behat\Behat\Context\Context - { - private $I; - private $she; - - /** @Transform */ - public function userFromName($name) : User { - return User::named($name); - } - - /** @Transform :admin */ - public function adminFromName($name) : User { - return User::named('admin: ' . $name); - } - - /** @Transform :admin */ - public function adminString($name) { - return 'admin'; - } - - /** @Given I am :user */ - public function iAm(User $user) { - $this->I = $user; - } - - /** @Given she is :admin */ - public function sheIs(User $admin) { - $this->she = $admin; - } - - /** @Then I should be a user named :name */ - public function iShouldHaveName($name) { - if ('User' !== get_class($this->I)) { - throw new Exception("User expected, {gettype($this->I)} given"); - } - if ($name !== $this->I->name) { - throw new Exception("Actual name is {$this->I->name}"); - } - } - - /** @Then she should be an admin named :name */ - public function sheShouldHaveName($name) { - if ('User' !== get_class($this->she)) { - throw new Exception("User expected, {gettype($this->she)} given"); - } - if ($name !== $this->she->name) { - throw new Exception("Actual name is {$this->she->name}"); - } - } - } - """ - When I run "behat -f progress --no-colors" + When I run behat with the following additional options: + | option | value | + | --suite | by_type_and_by_name_object_transformation | Then it should pass with: """ .... @@ -612,18 +120,9 @@ Feature: Step Arguments Transformations Annotations """ Scenario: Unicode Named Arguments Transformations - Given a file named "features/step_arguments_unicode.feature" with: - """ - Feature: Step Arguments - Scenario: - Given I am боб - Then Username must be "боб" - - Scenario: - Given I am "элис" - Then Username must be "элис" - """ - When I run "behat -f progress --no-colors" + When I run behat with the following additional options: + | option | value | + | --suite | unicode_named_argument_transformation | Then it should pass with: """ .... @@ -633,50 +132,9 @@ Feature: Step Arguments Transformations Annotations """ Scenario: Ordinal Arguments without quotes Transformations - Given a file named "features/bootstrap/FeatureContext.php" with: - """ - index = $index; - } - - /** @Then the index should be :value */ - public function theIndexShouldBe($value) { - PHPUnit\Framework\Assert::assertSame($value, $this->index); - } - } - """ - And a file named "features/ordinal_arguments.feature" with: - """ - Feature: Ordinal Step Arguments - Scenario: - Given I pick the 1st thing - Then the index should be "1" - Scenario: - Given I pick the "1st" thing - Then the index should be "1" - Scenario: - Given I pick the 27th thing - Then the index should be "27" - Scenario: - Given I pick the 5 thing - Then the index should be "5" - """ - When I run "behat -f progress --no-colors" + When I run behat with the following additional options: + | option | value | + | --suite | ordinal_argument_transformation | Then it should pass with: """ ........ @@ -686,72 +144,16 @@ Feature: Step Arguments Transformations Annotations """ Scenario: By-type transformations don't trigger from union types - Given a file named "features/union-transforms.feature" with: - """ - Feature: - Scenario: - Given I am "everzet" - And she is "lunivore" - """ - And a file named "features/bootstrap/FeatureContext.php" with: - """ - I = $user; - } - } - """ - When I run "behat -f progress --no-colors" + When I run behat with the following additional options: + | option | value | + | --suite | by_type_union_transformation | Then it should fail with: """ - string given + must be of type User, string given """ Scenario: Return type transformations don't cause issues with scalar type hints (regression) - Given a file named "features/scalar-transforms.feature" with: - """ - Feature: - - Scenario: - Then "string" should be passed - """ - And a file named "features/bootstrap/FeatureContext.php" with: - """ - username; } - public function getAge(): int { return $this->age; } - } - """ - - Scenario: Simple Arguments Transformations - Given a file named "features/bootstrap/FeatureContext.php" with: - """ - user = $user; - } - - #[Then('/Username must be "([^"]+)"/')] - public function usernameMustBe(string $username): void { - Assert::assertEquals($username, $this->user->getUsername()); - } - - #[Then('/Age must be (\d+)/')] - public function ageMustBe(string $age): void { - Assert::assertEquals($age, $this->user->getAge()); - } - } - """ - And a file named "features/step_arguments.feature" with: - """ - Feature: Step Arguments - Scenario: - Given I am "everzet" user - Then Username must be "everzet" - And Age must be 20 - - Scenario: - Given I am "antono - 29" user - Then Username must be "antono" - And Age must be 29 - """ - When I run "behat -f progress --no-colors" + Given I set the working directory to the "Transformations" fixtures folder + And I provide the following options for all behat invocations: + | option | value | + | --no-colors | | + | --format | progress | + | --profile | attributes | + + Scenario: Simple Argument Transformations + When I run behat with the following additional options: + | option | value | + | --suite | simple_step_argument_transformation | Then it should pass with: """ - ...... + ....... 2 scenarios (2 passed) - 6 steps (6 passed) + 7 steps (7 passed) """ Scenario: Transformation without parameters - Given a file named "features/bootstrap/FeatureContext.php" with: - """ - user = $user; - } - - #[Then('I should be a user named :name')] - public function iShouldBeAUserNamed(string $username): void { - Assert::assertEquals($username, $this->user->getUserName()); - } - } - """ - And a file named "features/my.feature" with: - """ - Feature: - Scenario: - Given I am "everzet" - Then I should be a user named "everzet" - """ - When I run "behat -f progress --no-colors" + When I run behat with the following additional options: + | option | value | + | --suite | step_argument_transformation_without_parameters | Then it should pass with: """ .. @@ -126,57 +36,9 @@ Feature: Step Arguments Transformations with Attributes """ Scenario: Multiple Transformations in one function - Given a file named "features/bootstrap/FeatureContext.php" with: - """ - user = $user; - } - - #[Then('/Username must be "([^"]+)"/')] - public function usernameMustBe(string $username): void { - Assert::assertEquals($username, $this->user->getUsername()); - } - - #[Then('/Age must be (\d+)/')] - public function ageMustBe(string $age): void { - Assert::assertEquals($age, $this->user->getAge()); - } - } - """ - And a file named "features/step_arguments.feature" with: - """ - Feature: Step Arguments - Scenario: - Given I am everzet - Then Username must be "everzet" - And Age must be 20 - - Scenario: - Given I am "antono - 29" user - Then Username must be "antono" - And Age must be 29 - """ - When I run "behat -f progress --no-colors" + When I run behat with the following additional options: + | option | value | + | --suite | multiple_transformations_in_one_function | Then it should pass with: """ ...... diff --git a/tests/Fixtures/Transformations/behat.php b/tests/Fixtures/Transformations/behat.php new file mode 100644 index 000000000..c5c92f647 --- /dev/null +++ b/tests/Fixtures/Transformations/behat.php @@ -0,0 +1,149 @@ +withProfile((new Profile('attributes')) + ->withSuite((new Suite('simple_step_argument_transformation')) + ->withPaths( + 'features/simple_step_argument_transformation.feature' + ) + ->withContexts( + 'SimpleTransformationAttributesContext', + 'UserAttributesContext' + ) + ) + ->withSuite((new Suite('step_argument_transformation_without_parameters')) + ->withPaths( + 'features/step_argument_transformation_without_parameters.feature' + ) + ->withContexts( + 'TransformationWithoutParametersAttributesContext', + 'UserAttributesContext' + ) + ) + ->withSuite((new Suite('multiple_transformations_in_one_function')) + ->withPaths( + 'features/multiple_transformations_in_one_function.feature' + ) + ->withContexts( + 'MultipleTransformationsInOneFunctionAttributesContext', + 'UserAttributesContext' + ) + ) + ) + ->withProfile((new Profile('annotations')) + ->withSuite((new Suite('simple_step_argument_transformation')) + ->withPaths( + 'features/simple_step_argument_transformation.feature' + ) + ->withContexts( + 'TransformationAnnotationsContext', + 'UserAnnotationsContext' + ) + ) + ->withSuite((new Suite('table_argument_transformation')) + ->withPaths( + 'features/table_argument_transformation.feature' + ) + ->withContexts( + 'TransformationAnnotationsContext', + 'UserAnnotationsContext' + ) + ) + ->withSuite((new Suite('row_table_argument_transformation')) + ->withPaths( + 'features/row_table_argument_transformation.feature' + ) + ->withContexts( + 'TransformationAnnotationsContext', + 'UserAnnotationsContext' + ) + ) + ->withSuite((new Suite('table_row_argument_transformation')) + ->withPaths( + 'features/table_row_argument_transformation.feature' + ) + ->withContexts( + 'TransformationAnnotationsContext', + 'UserAnnotationsContext' + ) + ) + ->withSuite((new Suite('whole_table_argument_transformation')) + ->withPaths( + 'features/whole_table_argument_transformation.feature' + ) + ->withContexts( + 'WholeTableAnnotationsContext' + ) + ) + ->withSuite((new Suite('named_argument_transformation')) + ->withPaths( + 'features/named_argument_transformation.feature' + ) + ->withContexts( + 'TransformationAnnotationsContext', + 'UserAnnotationsContext' + ) + ) + ->withSuite((new Suite('transform_different_types')) + ->withPaths( + 'features/transform_different_types.feature' + ) + ->withContexts( + 'MultipleTypesAnnotationsContext' + ) + ) + ->withSuite((new Suite('by_type_object_transformation')) + ->withPaths( + 'features/by_type_object_transformation.feature' + ) + ->withContexts( + 'ByTypeAnnotationsContext' + ) + ) + ->withSuite((new Suite('by_type_and_by_name_object_transformation')) + ->withPaths( + 'features/by_type_and_by_name_object_transformation.feature' + ) + ->withContexts( + 'ByTypeAndByNameAnnotationsContext' + ) + ) + ->withSuite((new Suite('unicode_named_argument_transformation')) + ->withPaths( + 'features/unicode_named_argument_transformation.feature' + ) + ->withContexts( + 'TransformationAnnotationsContext', + 'UserAnnotationsContext' + ) + ) + ->withSuite((new Suite('ordinal_argument_transformation')) + ->withPaths( + 'features/ordinal_argument_transformation.feature' + ) + ->withContexts( + 'OrdinalTransformationAnnotationsContext' + ) + ) + ->withSuite((new Suite('by_type_union_transformation')) + ->withPaths( + 'features/by_type_union_transformation.feature' + ) + ->withContexts( + 'ByTypeUnionAnnotationsContext' + ) + ) + ->withSuite((new Suite('scalar_type_transformation')) + ->withPaths( + 'features/scalar_type_transformation.feature' + ) + ->withContexts( + 'ScalarTypeAnnotationsContext' + ) + ) + ) +; diff --git a/tests/Fixtures/Transformations/features/bootstrap/ByTypeAndByNameAnnotationsContext.php b/tests/Fixtures/Transformations/features/bootstrap/ByTypeAndByNameAnnotationsContext.php new file mode 100644 index 000000000..acc0fcd43 --- /dev/null +++ b/tests/Fixtures/Transformations/features/bootstrap/ByTypeAndByNameAnnotationsContext.php @@ -0,0 +1,48 @@ +I = $user; + } + + /** @Given she is :admin */ + public function sheIs(User $admin): void { + $this->she = $admin; + } + + /** @Then I should be a user named :name */ + public function iShouldHaveName(string $name): void { + if ($name !== $this->I->getUsername()) { + throw new Exception("My actual name is {$this->I->getUsername()}"); + } + } + + /** @Then she should be an admin named :name */ + public function sheShouldHaveName(string $name): void { + if ($name !== $this->she->getUsername()) { + throw new Exception("Her actual name is {$this->she->getUsername()}"); + } + } +} diff --git a/tests/Fixtures/Transformations/features/bootstrap/ByTypeAnnotationsContext.php b/tests/Fixtures/Transformations/features/bootstrap/ByTypeAnnotationsContext.php new file mode 100644 index 000000000..df5f3cf54 --- /dev/null +++ b/tests/Fixtures/Transformations/features/bootstrap/ByTypeAnnotationsContext.php @@ -0,0 +1,38 @@ +I = $user; + } + + /** @Given /^he is \"([^\"]+)\"$/ */ + public function heIs(User $user): void { + $this->he = $user; + } + + /** @Then I should be a user named :name */ + public function iShouldHaveName(string $name): void { + if ($name !== $this->I->getUsername()) { + throw new Exception("My actual name is {$this->I->getUsername()}"); + } + } + + /** @Then he should be a user named :name */ + public function heShouldHaveName(string $name): void { + if ($name !== $this->he->getUsername()) { + throw new Exception("His actual name is {$this->he->getUsername()}"); + } + } +} diff --git a/tests/Fixtures/Transformations/features/bootstrap/ByTypeUnionAnnotationsContext.php b/tests/Fixtures/Transformations/features/bootstrap/ByTypeUnionAnnotationsContext.php new file mode 100644 index 000000000..f0869f933 --- /dev/null +++ b/tests/Fixtures/Transformations/features/bootstrap/ByTypeUnionAnnotationsContext.php @@ -0,0 +1,19 @@ +value = $value; + } + + /** + * @Then it should be of type :type + */ + public function itShouldBeOfType(string $type) + { + if (gettype($this->value) != $type && get_class($this->value) != $type) { + throw new Exception("Expected " . $type . ", got " . gettype($this->value) . " (value: " . var_export($this->value, true) . ")"); + } + } +} diff --git a/tests/Fixtures/Transformations/features/bootstrap/OrdinalTransformationAnnotationsContext.php b/tests/Fixtures/Transformations/features/bootstrap/OrdinalTransformationAnnotationsContext.php new file mode 100644 index 000000000..6468677cc --- /dev/null +++ b/tests/Fixtures/Transformations/features/bootstrap/OrdinalTransformationAnnotationsContext.php @@ -0,0 +1,24 @@ +index = $index; + } + + /** @Then the index should be :value */ + public function theIndexShouldBe($value): void { + Assert::assertSame($value, $this->index); + } +} diff --git a/tests/Fixtures/Transformations/features/bootstrap/ScalarTypeAnnotationsContext.php b/tests/Fixtures/Transformations/features/bootstrap/ScalarTypeAnnotationsContext.php new file mode 100644 index 000000000..4082289e8 --- /dev/null +++ b/tests/Fixtures/Transformations/features/bootstrap/ScalarTypeAnnotationsContext.php @@ -0,0 +1,23 @@ +getHash(); + $username = $hash[0]['username']; + $age = $hash[0]['age']; + + return new User($username, $age); + } + + /** @Transform table:%username@,age# */ + public function createUserFromTableWithSymbol(TableNode $table): User { + $hash = $table->getHash(); + $username = $hash[0]['%username@']; + $age = $hash[0]['age#']; + + return new User($username, $age); + } + + /** @Transform table:логин,возраст */ + public function createUserFromTableInRussian(TableNode $table) { + $hash = $table->getHash(); + $username = $hash[0]['логин']; + $age = $hash[0]['возраст']; + + return new User($username, $age); + } + + /** @Transform rowtable:username,age */ + public function createUserFromRowTable(TableNode $table): User { + $hash = $table->getRowsHash(); + $username = $hash['username']; + $age = $hash['age']; + + return new User($username, $age); + } + + /** @Transform rowtable:--username,age */ + public function createUserFromRowTableWithSymbol(TableNode $table): User { + $hash = $table->getRowsHash(); + $username = $hash['--username']; + $age = $hash['age']; + + return new User($username, $age); + } + + /** @Transform rowtable:логин,возраст */ + public function createUserFromRowTableInRussian(TableNode $table) { + $hash = $table->getRowsHash(); + $username = $hash['логин']; + $age = $hash['возраст']; + + return new User($username, $age); + } + + /** @Transform row:username */ + public function createUserNamesFromTable(array $tableRow): string { + return $tableRow['username']; + } + + /** @Transform row:$username */ + public function createUserNamesFromTableWithSymbol(array $tableRow): string { + return $tableRow['$username']; + } + + /** @Transform row:логин */ + public function createUserNamesFromTableInRussian($tableRow) { + return $tableRow['логин']; + } + + /** @Transform /^\d+$/ */ + public function castToNumber(string $number): int { + return intval($number); + } + + /** @Transform :user */ + public function castToUser(string $username): User { + return new User($username); + } + + /** + * @Transform /^(yes|no)$/ + */ + public function castYesOrNoToBoolean(string $expected): bool { + return 'yes' === $expected; + } +} diff --git a/tests/Fixtures/Transformations/features/bootstrap/TransformationWithoutParametersAttributesContext.php b/tests/Fixtures/Transformations/features/bootstrap/TransformationWithoutParametersAttributesContext.php new file mode 100644 index 000000000..d2f103ed1 --- /dev/null +++ b/tests/Fixtures/Transformations/features/bootstrap/TransformationWithoutParametersAttributesContext.php @@ -0,0 +1,13 @@ +username; + } + + public function getAge(): int + { + return $this->age; + } +} diff --git a/tests/Fixtures/Transformations/features/bootstrap/UserAnnotationsContext.php b/tests/Fixtures/Transformations/features/bootstrap/UserAnnotationsContext.php new file mode 100644 index 000000000..2bbe024f8 --- /dev/null +++ b/tests/Fixtures/Transformations/features/bootstrap/UserAnnotationsContext.php @@ -0,0 +1,47 @@ +user = $user; + } + + /** + * @Then /Username must be "([^"]+)"/ + */ + public function usernameMustBe(string $username): void { + Assert::assertEquals($username, $this->user->getUsername()); + } + + /** + * @Then /Age must be (\d+)/ + */ + public function ageMustBe(int $age): void { + Assert::assertEquals($age, $this->user->getAge()); + Assert::assertIsInt($age); + } + + /** + * @Then the Usernames must be: + */ + public function usernamesMustBe(array $usernames): void { + Assert::assertEquals($usernames[0], $this->user->getUsername()); + } + + /** + * @Then /^the boolean (no) should be transformed to false$/ + */ + public function theBooleanShouldBeTransformed(bool $boolean): void { + Assert::assertSame(false, $boolean); + } +} diff --git a/tests/Fixtures/Transformations/features/bootstrap/UserAttributesContext.php b/tests/Fixtures/Transformations/features/bootstrap/UserAttributesContext.php new file mode 100644 index 000000000..838a201b7 --- /dev/null +++ b/tests/Fixtures/Transformations/features/bootstrap/UserAttributesContext.php @@ -0,0 +1,35 @@ +user = $user; + } + + #[Then('/Username must be "([^"]+)"/')] + public function usernameMustBe(string $username): void + { + Assert::assertEquals($username, $this->user->getUsername()); + } + + #[Then('/Age must be (\d+)/')] + public function ageMustBe(string $age): void + { + Assert::assertEquals($age, $this->user->getAge()); + } + + #[Then('/^the boolean (no) should be transformed to false$/')] + public function theBooleanShouldBeTransformed(bool $boolean): void { + Assert::assertSame(false, $boolean); + } +} diff --git a/tests/Fixtures/Transformations/features/bootstrap/WholeTableAnnotationsContext.php b/tests/Fixtures/Transformations/features/bootstrap/WholeTableAnnotationsContext.php new file mode 100644 index 000000000..4b9a9dbd5 --- /dev/null +++ b/tests/Fixtures/Transformations/features/bootstrap/WholeTableAnnotationsContext.php @@ -0,0 +1,25 @@ +getHash(); + } + + /** @Given data: */ + public function givenData(array $data): void { + $this->data = $data; + } + + /** @Then the :field should be :value */ + public function theFieldShouldBe(string $field, string $value): void { + Assert::assertSame($value, $this->data[0][$field]); + } +} diff --git a/tests/Fixtures/Transformations/features/by_type_and_by_name_object_transformation.feature b/tests/Fixtures/Transformations/features/by_type_and_by_name_object_transformation.feature new file mode 100644 index 000000000..bfdcf13ac --- /dev/null +++ b/tests/Fixtures/Transformations/features/by_type_and_by_name_object_transformation.feature @@ -0,0 +1,9 @@ +Feature: By type and by name object transformation + As a feature developer + I want to be able to transform arguments into Users by type and by name + + Scenario: + Given I am "everzet" + And she is "lunivore" + Then I should be a user named "everzet" + And she should be an admin named "admin: lunivore" diff --git a/tests/Fixtures/Transformations/features/by_type_object_transformation.feature b/tests/Fixtures/Transformations/features/by_type_object_transformation.feature new file mode 100644 index 000000000..a3a351510 --- /dev/null +++ b/tests/Fixtures/Transformations/features/by_type_object_transformation.feature @@ -0,0 +1,9 @@ +Feature: By type object transformation + As a feature developer + I want to be able to transform arguments into Users by type + + Scenario: + Given I am "everzet" + And he is "sroze" + Then I should be a user named "everzet" + And he should be a user named "sroze" diff --git a/tests/Fixtures/Transformations/features/by_type_union_transformation.feature b/tests/Fixtures/Transformations/features/by_type_union_transformation.feature new file mode 100644 index 000000000..f0ce08b78 --- /dev/null +++ b/tests/Fixtures/Transformations/features/by_type_union_transformation.feature @@ -0,0 +1,7 @@ +Feature: By type union transformation + As a feature developer + I can't transform transform arguments into a union type + + Scenario: + Given I am "nobody" + And she is "lunivore" diff --git a/tests/Fixtures/Transformations/features/multiple_transformations_in_one_function.feature b/tests/Fixtures/Transformations/features/multiple_transformations_in_one_function.feature new file mode 100644 index 000000000..188f37ffc --- /dev/null +++ b/tests/Fixtures/Transformations/features/multiple_transformations_in_one_function.feature @@ -0,0 +1,13 @@ +Feature: multiple transformations in one function + As a feature developer + I want to be able to transform step arguments with a function that has multiple transformations + + Scenario: + Given I am everzet + Then Username must be "everzet" + And Age must be 20 + + Scenario: + Given I am "antono - 29" user + Then Username must be "antono" + And Age must be 29 diff --git a/tests/Fixtures/Transformations/features/named_argument_transformation.feature b/tests/Fixtures/Transformations/features/named_argument_transformation.feature new file mode 100644 index 000000000..f1d0a3e49 --- /dev/null +++ b/tests/Fixtures/Transformations/features/named_argument_transformation.feature @@ -0,0 +1,11 @@ +Feature: Named argument transformation + As a feature developer + I want to be able to transform named arguments into Users + + Scenario: + Given I am "everzet" + Then Username must be "everzet" + + Scenario: + Given I am "antono" + Then Username must be "antono" diff --git a/tests/Fixtures/Transformations/features/ordinal_argument_transformation.feature b/tests/Fixtures/Transformations/features/ordinal_argument_transformation.feature new file mode 100644 index 000000000..ccfb97d74 --- /dev/null +++ b/tests/Fixtures/Transformations/features/ordinal_argument_transformation.feature @@ -0,0 +1,19 @@ +Feature: Ordinal argument transformation + As a feature developer + I want to be able to transform ordinal arguments with and without quotes + + Scenario: + Given I pick the 1st thing + Then the index should be "1" + + Scenario: + Given I pick the "1st" thing + Then the index should be "1" + + Scenario: + Given I pick the 27th thing + Then the index should be "27" + + Scenario: + Given I pick the 5 thing + Then the index should be "5" diff --git a/tests/Fixtures/Transformations/features/row_table_argument_transformation.feature b/tests/Fixtures/Transformations/features/row_table_argument_transformation.feature new file mode 100644 index 000000000..49f162e41 --- /dev/null +++ b/tests/Fixtures/Transformations/features/row_table_argument_transformation.feature @@ -0,0 +1,31 @@ +Feature: Row table argument transformation + As a feature developer + I want to be able to transform table arguments where the data is in rows into Users + + Scenario: + Given I am user: + | username | ever.zet | + | age | 22 | + Then Username must be "ever.zet" + And Age must be 22 + + Scenario: + Given I am user: + | username | vasiljev | + | age | 30 | + Then Username must be "vasiljev" + And Age must be 30 + + Scenario: + Given I am user: + | --username | rajesh | + | age | 35 | + Then Username must be "rajesh" + And Age must be 35 + + Scenario: + Given I am user: + | логин | vasiljev | + | возраст | 30 | + Then Username must be "vasiljev" + And Age must be 30 diff --git a/tests/Fixtures/Transformations/features/scalar_type_transformation.feature b/tests/Fixtures/Transformations/features/scalar_type_transformation.feature new file mode 100644 index 000000000..c80d96cda --- /dev/null +++ b/tests/Fixtures/Transformations/features/scalar_type_transformation.feature @@ -0,0 +1,6 @@ +Feature: Scalar type transformation + As a feature developer + Transformations should not apply to scalar type hints + + Scenario: + Then "string" should be passed diff --git a/tests/Fixtures/Transformations/features/simple_step_argument_transformation.feature b/tests/Fixtures/Transformations/features/simple_step_argument_transformation.feature new file mode 100644 index 000000000..3e3f48ccc --- /dev/null +++ b/tests/Fixtures/Transformations/features/simple_step_argument_transformation.feature @@ -0,0 +1,14 @@ +Feature: Simple step argument transformation + As a feature developer + I want to be able to transform step arguments into Users + + Scenario: + Given I am "everzet" user + Then Username must be "everzet" + And Age must be 20 + And the boolean no should be transformed to false + + Scenario: + Given I am "antono - 29" user + Then Username must be "antono" + And Age must be 29 diff --git a/tests/Fixtures/Transformations/features/step_argument_transformation_without_parameters.feature b/tests/Fixtures/Transformations/features/step_argument_transformation_without_parameters.feature new file mode 100644 index 000000000..16a2f9ee2 --- /dev/null +++ b/tests/Fixtures/Transformations/features/step_argument_transformation_without_parameters.feature @@ -0,0 +1,7 @@ +Feature: Step argument transformation without parameters + As a feature developer + I want to be able to transform step arguments without parameters into Users + + Scenario: + Given I am "everzet" + Then Username must be "everzet" diff --git a/tests/Fixtures/Transformations/features/table_argument_transformation.feature b/tests/Fixtures/Transformations/features/table_argument_transformation.feature new file mode 100644 index 000000000..f94159aa4 --- /dev/null +++ b/tests/Fixtures/Transformations/features/table_argument_transformation.feature @@ -0,0 +1,31 @@ +Feature: Table argument transformation + As a feature developer + I want to be able to transform table arguments into Users + + Scenario: + Given I am user: + | username | age | + | ever.zet | 22 | + Then Username must be "ever.zet" + And Age must be 22 + + Scenario: + Given I am user: + | username | age | + | vasiljev | 30 | + Then Username must be "vasiljev" + And Age must be 30 + + Scenario: + Given I am user: + | %username@ | age# | + | rajesh | 35 | + Then Username must be "rajesh" + And Age must be 35 + + Scenario: + Given I am user: + | логин | возраст | + | vasiljev | 30 | + Then Username must be "vasiljev" + And Age must be 30 diff --git a/tests/Fixtures/Transformations/features/table_row_argument_transformation.feature b/tests/Fixtures/Transformations/features/table_row_argument_transformation.feature new file mode 100644 index 000000000..c451c4229 --- /dev/null +++ b/tests/Fixtures/Transformations/features/table_row_argument_transformation.feature @@ -0,0 +1,27 @@ +Feature: Table row argument transformation + As a feature developer + I want to be able to transform table rows + + Scenario: + Given I am user: + | username | age | + | ever.zet | 22 | + Then the Usernames must be: + | username | + | ever.zet | + + Scenario: + Given I am user: + | %username@ | age# | + | rajesh | 35 | + Then the Usernames must be: + | $username | + | rajesh | + + Scenario: + Given I am user: + | username | age | + | ever.zet | 22 | + Then the Usernames must be: + | логин | + | ever.zet | diff --git a/tests/Fixtures/Transformations/features/transform_different_types.feature b/tests/Fixtures/Transformations/features/transform_different_types.feature new file mode 100644 index 000000000..66de5be66 --- /dev/null +++ b/tests/Fixtures/Transformations/features/transform_different_types.feature @@ -0,0 +1,14 @@ +Feature: Transform different types + As a feature developer + I want to be able to transform strings into different types + + Scenario Outline: Converting different types + Given I have the value "" + Then it should be of type "" + + Examples: + | value | type | + | "soeuhtou" | string | + | 34 | integer | + | null | NULL | + | 2 workdays ago | DateTime | diff --git a/tests/Fixtures/Transformations/features/unicode_named_argument_transformation.feature b/tests/Fixtures/Transformations/features/unicode_named_argument_transformation.feature new file mode 100644 index 000000000..c02868344 --- /dev/null +++ b/tests/Fixtures/Transformations/features/unicode_named_argument_transformation.feature @@ -0,0 +1,11 @@ +Feature: Unicode named argument transformation + As a feature developer + I want to be able to transform named arguments which use Unicode into Users + + Scenario: + Given I am боб + Then Username must be "боб" + + Scenario: + Given I am "элис" + Then Username must be "элис" diff --git a/tests/Fixtures/Transformations/features/whole_table_argument_transformation.feature b/tests/Fixtures/Transformations/features/whole_table_argument_transformation.feature new file mode 100644 index 000000000..d902eff83 --- /dev/null +++ b/tests/Fixtures/Transformations/features/whole_table_argument_transformation.feature @@ -0,0 +1,10 @@ +Feature: Whole table argument transformation + As a feature developer + I want to be able to transform whole tables + + Scenario: + Given data: + | username | age | + | ever.zet | 22 | + Then the "username" should be "ever.zet" + And the "age" should be 22 From fbda84cdf35864a97ee79a43a01b1183ed970a84 Mon Sep 17 00:00:00 2001 From: Carlos Granados Date: Fri, 24 Jan 2025 11:22:34 +0100 Subject: [PATCH 557/567] feat: add table column transformer --- ...itions_transformations_annotations.feature | 30 ++-- .../Factory/TransformationCalleeFactory.php | 2 + .../TableColumnTransformation.php | 136 ++++++++++++++++++ tests/Fixtures/Transformations/behat.php | 9 ++ .../TransformationAnnotationsContext.php | 20 +++ .../features/bootstrap/User.php | 5 + .../bootstrap/UserAnnotationsContext.php | 41 ++++++ ...ble_column_argument_transformation.feature | 30 ++++ 8 files changed, 264 insertions(+), 9 deletions(-) create mode 100644 src/Behat/Behat/Transformation/Transformation/TableColumnTransformation.php create mode 100644 tests/Fixtures/Transformations/features/table_column_argument_transformation.feature diff --git a/features/definitions_transformations_annotations.feature b/features/definitions_transformations_annotations.feature index 56861284a..fee23ade1 100644 --- a/features/definitions_transformations_annotations.feature +++ b/features/definitions_transformations_annotations.feature @@ -29,10 +29,10 @@ Feature: Step Arguments Transformations Annotations | --suite | table_argument_transformation | Then it should pass with: """ - ...... + ............ - 3 scenarios (3 passed) - 9 steps (9 passed) + 4 scenarios (4 passed) + 12 steps (12 passed) """ Scenario: Row Table Arguments Transformations @@ -41,10 +41,10 @@ Feature: Step Arguments Transformations Annotations | --suite | row_table_argument_transformation | Then it should pass with: """ - ...... + ............ - 3 scenarios (3 passed) - 9 steps (9 passed) + 4 scenarios (4 passed) + 12 steps (12 passed) """ Scenario: Table Row Arguments Transformations @@ -53,10 +53,22 @@ Feature: Step Arguments Transformations Annotations | --suite | table_row_argument_transformation | Then it should pass with: """ - .... + ...... - 2 scenarios (2 passed) - 4 steps (4 passed) + 3 scenarios (3 passed) + 6 steps (6 passed) + """ + + Scenario: Table Column Arguments Transformations + When I run behat with the following additional options: + | option | value | + | --suite | table_column_argument_transformation | + Then it should pass with: + """ + ........... + + 4 scenarios (4 passed) + 11 steps (11 passed) """ Scenario: Whole table transformation diff --git a/src/Behat/Behat/Transformation/Context/Factory/TransformationCalleeFactory.php b/src/Behat/Behat/Transformation/Context/Factory/TransformationCalleeFactory.php index 7e16ffe30..dc668fe83 100644 --- a/src/Behat/Behat/Transformation/Context/Factory/TransformationCalleeFactory.php +++ b/src/Behat/Behat/Transformation/Context/Factory/TransformationCalleeFactory.php @@ -16,6 +16,7 @@ use Behat\Behat\Transformation\Transformation\PatternTransformation; use Behat\Behat\Transformation\Transformation\ReturnTypeTransformation; use Behat\Behat\Transformation\Transformation\RowBasedTableTransformation; +use Behat\Behat\Transformation\Transformation\TableColumnTransformation; use Behat\Behat\Transformation\Transformation\TableRowTransformation; use Behat\Behat\Transformation\Transformation\TokenNameAndReturnTypeTransformation; use Behat\Behat\Transformation\Transformation\TokenNameTransformation; @@ -54,6 +55,7 @@ private static function simpleTransformations() RowBasedTableTransformation::class, ColumnBasedTableTransformation::class, TableRowTransformation::class, + TableColumnTransformation::class, TokenNameAndReturnTypeTransformation::class, ReturnTypeTransformation::class, TokenNameTransformation::class diff --git a/src/Behat/Behat/Transformation/Transformation/TableColumnTransformation.php b/src/Behat/Behat/Transformation/Transformation/TableColumnTransformation.php new file mode 100644 index 000000000..1fcba7496 --- /dev/null +++ b/src/Behat/Behat/Transformation/Transformation/TableColumnTransformation.php @@ -0,0 +1,136 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Behat\Behat\Transformation\Transformation; + +use Behat\Behat\Definition\Call\DefinitionCall; +use Behat\Behat\Transformation\Call\TransformationCall; +use Behat\Behat\Transformation\SimpleArgumentTransformation; +use Behat\Gherkin\Node\TableNode; +use Behat\Testwork\Call\CallCenter; +use Behat\Testwork\Call\RuntimeCallee; +use ReflectionMethod; + +final class TableColumnTransformation extends RuntimeCallee implements SimpleArgumentTransformation +{ + public const PATTERN_REGEX = '/^column\:[[:print:]]+$/u'; + + private string $pattern; + + static public function supportsPatternAndMethod($pattern, ReflectionMethod $method): bool + { + return 1 === preg_match(self::PATTERN_REGEX, $pattern); + } + + public function __construct(string $pattern, callable|array $callable, ?string $description = null) + { + $this->pattern = $pattern; + + parent::__construct($callable, $description); + } + + public function supportsDefinitionAndArgument( + DefinitionCall $definitionCall, + $argumentIndex, + $argumentArgumentValue + ): bool { + if (!$argumentArgumentValue instanceof TableNode && !is_array($argumentArgumentValue)) { + return false; + }; + + if (!str_starts_with($this->pattern, 'column:')) { + return false; + } + $columnNames = explode(',', substr($this->pattern, 7)); + + if ($argumentArgumentValue instanceof TableNode) { + $tableHeadings = $argumentArgumentValue->getRow(0); + foreach ($columnNames as $columnName) { + if (in_array($columnName, $tableHeadings, true)) { + return true; + } + return false; + } + } + foreach ($argumentArgumentValue as $row) { + $rowHasColumn = false; + foreach ($columnNames as $columnName) { + if (isset($row[$columnName])) { + $rowHasColumn = true; + } + } + if (!$rowHasColumn) { + return false; + } + } + return true; + } + + /** + * @param TableNode|array $argumentValue + */ + public function transformArgument( + CallCenter $callCenter, + DefinitionCall $definitionCall, + $argumentIndex, + $argumentValue + ): array + { + $columnNames = explode(',', substr($this->pattern, 7)); + $rows = []; + foreach ($argumentValue as $row) { + foreach ($columnNames as $columnName) { + if (isset($row[$columnName])) { + $call = new TransformationCall( + $definitionCall->getEnvironment(), + $definitionCall->getCallee(), + $this, + [$row[$columnName]] + ); + + $result = $callCenter->makeCall($call); + + if ($result->hasException()) { + throw $result->getException(); + } + + $row[$columnName] = $result->getReturn(); + } + } + $rows[] = $row; + } + + return $rows; + } + + /** + * {@inheritdoc} + */ + public function getPriority() + { + return 30; + } + + /** + * {@inheritdoc} + */ + public function getPattern() + { + return $this->pattern; + } + + /** + * {@inheritdoc} + */ + public function __toString() + { + return 'TableColumnTransform ' . $this->pattern; + } +} diff --git a/tests/Fixtures/Transformations/behat.php b/tests/Fixtures/Transformations/behat.php index c5c92f647..38bafc7bc 100644 --- a/tests/Fixtures/Transformations/behat.php +++ b/tests/Fixtures/Transformations/behat.php @@ -71,6 +71,15 @@ 'UserAnnotationsContext' ) ) + ->withSuite((new Suite('table_column_argument_transformation')) + ->withPaths( + 'features/table_column_argument_transformation.feature' + ) + ->withContexts( + 'TransformationAnnotationsContext', + 'UserAnnotationsContext' + ) + ) ->withSuite((new Suite('whole_table_argument_transformation')) ->withPaths( 'features/whole_table_argument_transformation.feature' diff --git a/tests/Fixtures/Transformations/features/bootstrap/TransformationAnnotationsContext.php b/tests/Fixtures/Transformations/features/bootstrap/TransformationAnnotationsContext.php index 2ef195915..8045f3fa1 100644 --- a/tests/Fixtures/Transformations/features/bootstrap/TransformationAnnotationsContext.php +++ b/tests/Fixtures/Transformations/features/bootstrap/TransformationAnnotationsContext.php @@ -79,6 +79,26 @@ public function createUserNamesFromTableInRussian($tableRow) { return $tableRow['логин']; } + /** @Transform column:user,other user */ + public function convertUsernameToUserInColumn(string $name): User { + return new User($name); + } + + /** @Transform column:логин */ + public function convertUsernameInRussianToUserInColumn(string $name): User { + return new User($name); + } + + /** @Transform column:username */ + public function convertUsernameToUserWithUsernameHeading(string $name): User { + throw new Exception('This should not be called'); + } + + /** @Transform column:hex age */ + public function convertHexAgeToAge(string $hexAge): int { + return hexdec($hexAge); + } + /** @Transform /^\d+$/ */ public function castToNumber(string $number): int { return intval($number); diff --git a/tests/Fixtures/Transformations/features/bootstrap/User.php b/tests/Fixtures/Transformations/features/bootstrap/User.php index 037d15031..2095e1a1e 100644 --- a/tests/Fixtures/Transformations/features/bootstrap/User.php +++ b/tests/Fixtures/Transformations/features/bootstrap/User.php @@ -13,6 +13,11 @@ public function getUsername(): string return $this->username; } + public function setAge(int $age): void + { + $this->age = $age; + } + public function getAge(): int { return $this->age; diff --git a/tests/Fixtures/Transformations/features/bootstrap/UserAnnotationsContext.php b/tests/Fixtures/Transformations/features/bootstrap/UserAnnotationsContext.php index 2bbe024f8..df3cb628d 100644 --- a/tests/Fixtures/Transformations/features/bootstrap/UserAnnotationsContext.php +++ b/tests/Fixtures/Transformations/features/bootstrap/UserAnnotationsContext.php @@ -7,6 +7,8 @@ class UserAnnotationsContext implements Context { private User $user; + private int $totalAge; + /** * @Given /I am (".*" user)/ * @Given I am user: @@ -16,6 +18,38 @@ public function iAmUser(User $user): void { $this->user = $user; } + /** + * @Given I am a user with this age: + */ + public function iAmAUserWithAge(array $data): void { + $this->user = $data[0]['user']; + $this->user->setAge($data[0]['age']); + } + + /** + * @Given I am a Russian user with this age: + */ + public function iAmARussianUserWithAgeIn(array $data): void { + $this->user = $data[0]['логин']; + $this->user->setAge($data[0]['age']); + } + + /** + * @Given I am a user with this hex age: + */ + public function iAmAUserWithHexAge(array $data): void { + $this->user = $data[0]['user']; + $this->user->setAge($data[0]['hex age']); + } + + /** + * @Given I have two users and I add their ages + */ + public function addTwoUsersAges(array $data): void { + $this->totalAge = $data[0]['user']->getAge(); + $this->totalAge += $data[0]['other user']->getAge(); + } + /** * @Then /Username must be "([^"]+)"/ */ @@ -31,6 +65,13 @@ public function ageMustBe(int $age): void { Assert::assertIsInt($age); } + /** + * @Then /total age must be (\d+)/ + */ + public function totalAgeMustBe(int $age): void { + Assert::assertEquals($age, $this->totalAge); + } + /** * @Then the Usernames must be: */ diff --git a/tests/Fixtures/Transformations/features/table_column_argument_transformation.feature b/tests/Fixtures/Transformations/features/table_column_argument_transformation.feature new file mode 100644 index 000000000..28be184e2 --- /dev/null +++ b/tests/Fixtures/Transformations/features/table_column_argument_transformation.feature @@ -0,0 +1,30 @@ +Feature: Table column argument transformation + As a feature developer + I want to be able to transform table columns + + Scenario: + Given I am a user with this age: + | user | age | + | ever.zet | 33 | + Then Username must be "ever.zet" + And Age must be 33 + + Scenario: + Given I have two users and I add their ages + | user | other user | + | ever.zet | roland | + Then total age must be 40 + + Scenario: + Given I am a user with this hex age: + | user | hex age | + | ever.zet | 0x1A | + Then Username must be "ever.zet" + And Age must be 26 + + Scenario: + Given I am a Russian user with this age: + | логин | age | + | ever.zet | 33 | + Then Username must be "ever.zet" + And Age must be 33 From f2859ba123087cdbba764cf566039d5ee53d539b Mon Sep 17 00:00:00 2001 From: Carlos Granados Date: Thu, 6 Feb 2025 20:09:17 +0100 Subject: [PATCH 558/567] Fix coding standard --- .../TableColumnTransformation.php | 5 +- tests/Fixtures/Transformations/behat.php | 57 ++++++++++++------- .../ByTypeAndByNameAnnotationsContext.php | 21 ++++--- .../bootstrap/ByTypeAnnotationsContext.php | 15 +++-- .../ByTypeUnionAnnotationsContext.php | 3 +- ...rdinalTransformationAnnotationsContext.php | 9 ++- .../SimpleTransformationAttributesContext.php | 3 +- .../TransformationAnnotationsContext.php | 51 +++++++++++------ .../bootstrap/UserAnnotationsContext.php | 30 ++++++---- .../bootstrap/UserAttributesContext.php | 3 +- .../WholeTableAnnotationsContext.php | 9 ++- 11 files changed, 136 insertions(+), 70 deletions(-) diff --git a/src/Behat/Behat/Transformation/Transformation/TableColumnTransformation.php b/src/Behat/Behat/Transformation/Transformation/TableColumnTransformation.php index 1fcba7496..dae001608 100644 --- a/src/Behat/Behat/Transformation/Transformation/TableColumnTransformation.php +++ b/src/Behat/Behat/Transformation/Transformation/TableColumnTransformation.php @@ -24,7 +24,7 @@ final class TableColumnTransformation extends RuntimeCallee implements SimpleArg private string $pattern; - static public function supportsPatternAndMethod($pattern, ReflectionMethod $method): bool + public static function supportsPatternAndMethod($pattern, ReflectionMethod $method): bool { return 1 === preg_match(self::PATTERN_REGEX, $pattern); } @@ -81,8 +81,7 @@ public function transformArgument( DefinitionCall $definitionCall, $argumentIndex, $argumentValue - ): array - { + ): array { $columnNames = explode(',', substr($this->pattern, 7)); $rows = []; foreach ($argumentValue as $row) { diff --git a/tests/Fixtures/Transformations/behat.php b/tests/Fixtures/Transformations/behat.php index 38bafc7bc..5b64b5197 100644 --- a/tests/Fixtures/Transformations/behat.php +++ b/tests/Fixtures/Transformations/behat.php @@ -5,8 +5,10 @@ use Behat\Config\Suite; return (new Config()) - ->withProfile((new Profile('attributes')) - ->withSuite((new Suite('simple_step_argument_transformation')) + ->withProfile( + (new Profile('attributes')) + ->withSuite( + (new Suite('simple_step_argument_transformation')) ->withPaths( 'features/simple_step_argument_transformation.feature' ) @@ -15,7 +17,8 @@ 'UserAttributesContext' ) ) - ->withSuite((new Suite('step_argument_transformation_without_parameters')) + ->withSuite( + (new Suite('step_argument_transformation_without_parameters')) ->withPaths( 'features/step_argument_transformation_without_parameters.feature' ) @@ -24,7 +27,8 @@ 'UserAttributesContext' ) ) - ->withSuite((new Suite('multiple_transformations_in_one_function')) + ->withSuite( + (new Suite('multiple_transformations_in_one_function')) ->withPaths( 'features/multiple_transformations_in_one_function.feature' ) @@ -34,8 +38,10 @@ ) ) ) - ->withProfile((new Profile('annotations')) - ->withSuite((new Suite('simple_step_argument_transformation')) + ->withProfile( + (new Profile('annotations')) + ->withSuite( + (new Suite('simple_step_argument_transformation')) ->withPaths( 'features/simple_step_argument_transformation.feature' ) @@ -44,7 +50,8 @@ 'UserAnnotationsContext' ) ) - ->withSuite((new Suite('table_argument_transformation')) + ->withSuite( + (new Suite('table_argument_transformation')) ->withPaths( 'features/table_argument_transformation.feature' ) @@ -53,7 +60,8 @@ 'UserAnnotationsContext' ) ) - ->withSuite((new Suite('row_table_argument_transformation')) + ->withSuite( + (new Suite('row_table_argument_transformation')) ->withPaths( 'features/row_table_argument_transformation.feature' ) @@ -62,7 +70,8 @@ 'UserAnnotationsContext' ) ) - ->withSuite((new Suite('table_row_argument_transformation')) + ->withSuite( + (new Suite('table_row_argument_transformation')) ->withPaths( 'features/table_row_argument_transformation.feature' ) @@ -71,7 +80,8 @@ 'UserAnnotationsContext' ) ) - ->withSuite((new Suite('table_column_argument_transformation')) + ->withSuite( + (new Suite('table_column_argument_transformation')) ->withPaths( 'features/table_column_argument_transformation.feature' ) @@ -80,7 +90,8 @@ 'UserAnnotationsContext' ) ) - ->withSuite((new Suite('whole_table_argument_transformation')) + ->withSuite( + (new Suite('whole_table_argument_transformation')) ->withPaths( 'features/whole_table_argument_transformation.feature' ) @@ -88,7 +99,8 @@ 'WholeTableAnnotationsContext' ) ) - ->withSuite((new Suite('named_argument_transformation')) + ->withSuite( + (new Suite('named_argument_transformation')) ->withPaths( 'features/named_argument_transformation.feature' ) @@ -97,7 +109,8 @@ 'UserAnnotationsContext' ) ) - ->withSuite((new Suite('transform_different_types')) + ->withSuite( + (new Suite('transform_different_types')) ->withPaths( 'features/transform_different_types.feature' ) @@ -105,7 +118,8 @@ 'MultipleTypesAnnotationsContext' ) ) - ->withSuite((new Suite('by_type_object_transformation')) + ->withSuite( + (new Suite('by_type_object_transformation')) ->withPaths( 'features/by_type_object_transformation.feature' ) @@ -113,7 +127,8 @@ 'ByTypeAnnotationsContext' ) ) - ->withSuite((new Suite('by_type_and_by_name_object_transformation')) + ->withSuite( + (new Suite('by_type_and_by_name_object_transformation')) ->withPaths( 'features/by_type_and_by_name_object_transformation.feature' ) @@ -121,7 +136,8 @@ 'ByTypeAndByNameAnnotationsContext' ) ) - ->withSuite((new Suite('unicode_named_argument_transformation')) + ->withSuite( + (new Suite('unicode_named_argument_transformation')) ->withPaths( 'features/unicode_named_argument_transformation.feature' ) @@ -130,7 +146,8 @@ 'UserAnnotationsContext' ) ) - ->withSuite((new Suite('ordinal_argument_transformation')) + ->withSuite( + (new Suite('ordinal_argument_transformation')) ->withPaths( 'features/ordinal_argument_transformation.feature' ) @@ -138,7 +155,8 @@ 'OrdinalTransformationAnnotationsContext' ) ) - ->withSuite((new Suite('by_type_union_transformation')) + ->withSuite( + (new Suite('by_type_union_transformation')) ->withPaths( 'features/by_type_union_transformation.feature' ) @@ -146,7 +164,8 @@ 'ByTypeUnionAnnotationsContext' ) ) - ->withSuite((new Suite('scalar_type_transformation')) + ->withSuite( + (new Suite('scalar_type_transformation')) ->withPaths( 'features/scalar_type_transformation.feature' ) diff --git a/tests/Fixtures/Transformations/features/bootstrap/ByTypeAndByNameAnnotationsContext.php b/tests/Fixtures/Transformations/features/bootstrap/ByTypeAndByNameAnnotationsContext.php index acc0fcd43..bcadacb99 100644 --- a/tests/Fixtures/Transformations/features/bootstrap/ByTypeAndByNameAnnotationsContext.php +++ b/tests/Fixtures/Transformations/features/bootstrap/ByTypeAndByNameAnnotationsContext.php @@ -8,39 +8,46 @@ class ByTypeAndByNameAnnotationsContext implements Context private User $she; /** @Transform */ - public function userFromName(string $name) : User { + public function userFromName(string $name) : User + { return new User($name); } /** @Transform :admin */ - public function adminFromName(string $name) : User { + public function adminFromName(string $name) : User + { return new User('admin: ' . $name); } /** @Transform :admin */ - public function adminString(): string { + public function adminString(): string + { return 'admin'; } /** @Given I am :user */ - public function iAm(User $user): void { + public function iAm(User $user): void + { $this->I = $user; } /** @Given she is :admin */ - public function sheIs(User $admin): void { + public function sheIs(User $admin): void + { $this->she = $admin; } /** @Then I should be a user named :name */ - public function iShouldHaveName(string $name): void { + public function iShouldHaveName(string $name): void + { if ($name !== $this->I->getUsername()) { throw new Exception("My actual name is {$this->I->getUsername()}"); } } /** @Then she should be an admin named :name */ - public function sheShouldHaveName(string $name): void { + public function sheShouldHaveName(string $name): void + { if ($name !== $this->she->getUsername()) { throw new Exception("Her actual name is {$this->she->getUsername()}"); } diff --git a/tests/Fixtures/Transformations/features/bootstrap/ByTypeAnnotationsContext.php b/tests/Fixtures/Transformations/features/bootstrap/ByTypeAnnotationsContext.php index df5f3cf54..25f4b1f2f 100644 --- a/tests/Fixtures/Transformations/features/bootstrap/ByTypeAnnotationsContext.php +++ b/tests/Fixtures/Transformations/features/bootstrap/ByTypeAnnotationsContext.php @@ -8,29 +8,34 @@ class ByTypeAnnotationsContext implements Context private User $he; /** @Transform */ - public function userFromName(string $name) : User { + public function userFromName(string $name) : User + { return new User($name); } /** @Given I am :user */ - public function iAm(User $user): void { + public function iAm(User $user): void + { $this->I = $user; } /** @Given /^he is \"([^\"]+)\"$/ */ - public function heIs(User $user): void { + public function heIs(User $user): void + { $this->he = $user; } /** @Then I should be a user named :name */ - public function iShouldHaveName(string $name): void { + public function iShouldHaveName(string $name): void + { if ($name !== $this->I->getUsername()) { throw new Exception("My actual name is {$this->I->getUsername()}"); } } /** @Then he should be a user named :name */ - public function heShouldHaveName(string $name): void { + public function heShouldHaveName(string $name): void + { if ($name !== $this->he->getUsername()) { throw new Exception("His actual name is {$this->he->getUsername()}"); } diff --git a/tests/Fixtures/Transformations/features/bootstrap/ByTypeUnionAnnotationsContext.php b/tests/Fixtures/Transformations/features/bootstrap/ByTypeUnionAnnotationsContext.php index f0869f933..7352bdaa3 100644 --- a/tests/Fixtures/Transformations/features/bootstrap/ByTypeUnionAnnotationsContext.php +++ b/tests/Fixtures/Transformations/features/bootstrap/ByTypeUnionAnnotationsContext.php @@ -14,6 +14,7 @@ public function userFromName(string $name): User|int * @Given I am :user * @Given she is :user */ - public function iAm(User $user): void { + public function iAm(User $user): void + { } } diff --git a/tests/Fixtures/Transformations/features/bootstrap/OrdinalTransformationAnnotationsContext.php b/tests/Fixtures/Transformations/features/bootstrap/OrdinalTransformationAnnotationsContext.php index 6468677cc..34bca0e41 100644 --- a/tests/Fixtures/Transformations/features/bootstrap/OrdinalTransformationAnnotationsContext.php +++ b/tests/Fixtures/Transformations/features/bootstrap/OrdinalTransformationAnnotationsContext.php @@ -8,17 +8,20 @@ class OrdinalTransformationAnnotationsContext implements Context private int $index; /** @Transform /^(0|[1-9]\d*)(?:st|nd|rd|th)?$/ */ - public function castToInt(string $number): int { + public function castToInt(string $number): int + { return intval($number); } /** @Given I pick the :index thing */ - public function iPickThing(int $index): void { + public function iPickThing(int $index): void + { $this->index = $index; } /** @Then the index should be :value */ - public function theIndexShouldBe($value): void { + public function theIndexShouldBe($value): void + { Assert::assertSame($value, $this->index); } } diff --git a/tests/Fixtures/Transformations/features/bootstrap/SimpleTransformationAttributesContext.php b/tests/Fixtures/Transformations/features/bootstrap/SimpleTransformationAttributesContext.php index c797ad4a6..d491682a5 100644 --- a/tests/Fixtures/Transformations/features/bootstrap/SimpleTransformationAttributesContext.php +++ b/tests/Fixtures/Transformations/features/bootstrap/SimpleTransformationAttributesContext.php @@ -12,7 +12,8 @@ public function createUserFromUsername(string $username, int $age = 20): User } #[Transform('/^(yes|no)$/')] - public function castYesOrNoToBoolean($expected): bool { + public function castYesOrNoToBoolean($expected): bool + { return 'yes' === $expected; } } diff --git a/tests/Fixtures/Transformations/features/bootstrap/TransformationAnnotationsContext.php b/tests/Fixtures/Transformations/features/bootstrap/TransformationAnnotationsContext.php index 8045f3fa1..159d64916 100644 --- a/tests/Fixtures/Transformations/features/bootstrap/TransformationAnnotationsContext.php +++ b/tests/Fixtures/Transformations/features/bootstrap/TransformationAnnotationsContext.php @@ -6,12 +6,14 @@ class TransformationAnnotationsContext implements Context { /** @Transform /"([^\ "]+)(?: - (\d+))?" user/ */ - public function createUserFromUsername(string $username, int $age = 20): User { + public function createUserFromUsername(string $username, int $age = 20): User + { return new User($username, $age); } /** @Transform table:username,age */ - public function createUserFromTable(TableNode $table): User { + public function createUserFromTable(TableNode $table): User + { $hash = $table->getHash(); $username = $hash[0]['username']; $age = $hash[0]['age']; @@ -20,7 +22,8 @@ public function createUserFromTable(TableNode $table): User { } /** @Transform table:%username@,age# */ - public function createUserFromTableWithSymbol(TableNode $table): User { + public function createUserFromTableWithSymbol(TableNode $table): User + { $hash = $table->getHash(); $username = $hash[0]['%username@']; $age = $hash[0]['age#']; @@ -29,7 +32,8 @@ public function createUserFromTableWithSymbol(TableNode $table): User { } /** @Transform table:логин,возраст */ - public function createUserFromTableInRussian(TableNode $table) { + public function createUserFromTableInRussian(TableNode $table) + { $hash = $table->getHash(); $username = $hash[0]['логин']; $age = $hash[0]['возраст']; @@ -38,7 +42,8 @@ public function createUserFromTableInRussian(TableNode $table) { } /** @Transform rowtable:username,age */ - public function createUserFromRowTable(TableNode $table): User { + public function createUserFromRowTable(TableNode $table): User + { $hash = $table->getRowsHash(); $username = $hash['username']; $age = $hash['age']; @@ -47,7 +52,8 @@ public function createUserFromRowTable(TableNode $table): User { } /** @Transform rowtable:--username,age */ - public function createUserFromRowTableWithSymbol(TableNode $table): User { + public function createUserFromRowTableWithSymbol(TableNode $table): User + { $hash = $table->getRowsHash(); $username = $hash['--username']; $age = $hash['age']; @@ -56,7 +62,8 @@ public function createUserFromRowTableWithSymbol(TableNode $table): User { } /** @Transform rowtable:логин,возраст */ - public function createUserFromRowTableInRussian(TableNode $table) { + public function createUserFromRowTableInRussian(TableNode $table) + { $hash = $table->getRowsHash(); $username = $hash['логин']; $age = $hash['возраст']; @@ -65,54 +72,64 @@ public function createUserFromRowTableInRussian(TableNode $table) { } /** @Transform row:username */ - public function createUserNamesFromTable(array $tableRow): string { + public function createUserNamesFromTable(array $tableRow): string + { return $tableRow['username']; } /** @Transform row:$username */ - public function createUserNamesFromTableWithSymbol(array $tableRow): string { + public function createUserNamesFromTableWithSymbol(array $tableRow): string + { return $tableRow['$username']; } /** @Transform row:логин */ - public function createUserNamesFromTableInRussian($tableRow) { + public function createUserNamesFromTableInRussian($tableRow) + { return $tableRow['логин']; } /** @Transform column:user,other user */ - public function convertUsernameToUserInColumn(string $name): User { + public function convertUsernameToUserInColumn(string $name): User + { return new User($name); } /** @Transform column:логин */ - public function convertUsernameInRussianToUserInColumn(string $name): User { + public function convertUsernameInRussianToUserInColumn(string $name): User + { return new User($name); } /** @Transform column:username */ - public function convertUsernameToUserWithUsernameHeading(string $name): User { + public function convertUsernameToUserWithUsernameHeading(string $name): User + { throw new Exception('This should not be called'); } /** @Transform column:hex age */ - public function convertHexAgeToAge(string $hexAge): int { + public function convertHexAgeToAge(string $hexAge): int + { return hexdec($hexAge); } /** @Transform /^\d+$/ */ - public function castToNumber(string $number): int { + public function castToNumber(string $number): int + { return intval($number); } /** @Transform :user */ - public function castToUser(string $username): User { + public function castToUser(string $username): User + { return new User($username); } /** * @Transform /^(yes|no)$/ */ - public function castYesOrNoToBoolean(string $expected): bool { + public function castYesOrNoToBoolean(string $expected): bool + { return 'yes' === $expected; } } diff --git a/tests/Fixtures/Transformations/features/bootstrap/UserAnnotationsContext.php b/tests/Fixtures/Transformations/features/bootstrap/UserAnnotationsContext.php index df3cb628d..c2e2fb4aa 100644 --- a/tests/Fixtures/Transformations/features/bootstrap/UserAnnotationsContext.php +++ b/tests/Fixtures/Transformations/features/bootstrap/UserAnnotationsContext.php @@ -14,14 +14,16 @@ class UserAnnotationsContext implements Context * @Given I am user: * @Given I am :user */ - public function iAmUser(User $user): void { + public function iAmUser(User $user): void + { $this->user = $user; } /** * @Given I am a user with this age: */ - public function iAmAUserWithAge(array $data): void { + public function iAmAUserWithAge(array $data): void + { $this->user = $data[0]['user']; $this->user->setAge($data[0]['age']); } @@ -29,7 +31,8 @@ public function iAmAUserWithAge(array $data): void { /** * @Given I am a Russian user with this age: */ - public function iAmARussianUserWithAgeIn(array $data): void { + public function iAmARussianUserWithAgeIn(array $data): void + { $this->user = $data[0]['логин']; $this->user->setAge($data[0]['age']); } @@ -37,7 +40,8 @@ public function iAmARussianUserWithAgeIn(array $data): void { /** * @Given I am a user with this hex age: */ - public function iAmAUserWithHexAge(array $data): void { + public function iAmAUserWithHexAge(array $data): void + { $this->user = $data[0]['user']; $this->user->setAge($data[0]['hex age']); } @@ -45,7 +49,8 @@ public function iAmAUserWithHexAge(array $data): void { /** * @Given I have two users and I add their ages */ - public function addTwoUsersAges(array $data): void { + public function addTwoUsersAges(array $data): void + { $this->totalAge = $data[0]['user']->getAge(); $this->totalAge += $data[0]['other user']->getAge(); } @@ -53,14 +58,16 @@ public function addTwoUsersAges(array $data): void { /** * @Then /Username must be "([^"]+)"/ */ - public function usernameMustBe(string $username): void { + public function usernameMustBe(string $username): void + { Assert::assertEquals($username, $this->user->getUsername()); } /** * @Then /Age must be (\d+)/ */ - public function ageMustBe(int $age): void { + public function ageMustBe(int $age): void + { Assert::assertEquals($age, $this->user->getAge()); Assert::assertIsInt($age); } @@ -68,21 +75,24 @@ public function ageMustBe(int $age): void { /** * @Then /total age must be (\d+)/ */ - public function totalAgeMustBe(int $age): void { + public function totalAgeMustBe(int $age): void + { Assert::assertEquals($age, $this->totalAge); } /** * @Then the Usernames must be: */ - public function usernamesMustBe(array $usernames): void { + public function usernamesMustBe(array $usernames): void + { Assert::assertEquals($usernames[0], $this->user->getUsername()); } /** * @Then /^the boolean (no) should be transformed to false$/ */ - public function theBooleanShouldBeTransformed(bool $boolean): void { + public function theBooleanShouldBeTransformed(bool $boolean): void + { Assert::assertSame(false, $boolean); } } diff --git a/tests/Fixtures/Transformations/features/bootstrap/UserAttributesContext.php b/tests/Fixtures/Transformations/features/bootstrap/UserAttributesContext.php index 838a201b7..6bd7747c2 100644 --- a/tests/Fixtures/Transformations/features/bootstrap/UserAttributesContext.php +++ b/tests/Fixtures/Transformations/features/bootstrap/UserAttributesContext.php @@ -29,7 +29,8 @@ public function ageMustBe(string $age): void } #[Then('/^the boolean (no) should be transformed to false$/')] - public function theBooleanShouldBeTransformed(bool $boolean): void { + public function theBooleanShouldBeTransformed(bool $boolean): void + { Assert::assertSame(false, $boolean); } } diff --git a/tests/Fixtures/Transformations/features/bootstrap/WholeTableAnnotationsContext.php b/tests/Fixtures/Transformations/features/bootstrap/WholeTableAnnotationsContext.php index 4b9a9dbd5..edc7beefe 100644 --- a/tests/Fixtures/Transformations/features/bootstrap/WholeTableAnnotationsContext.php +++ b/tests/Fixtures/Transformations/features/bootstrap/WholeTableAnnotationsContext.php @@ -9,17 +9,20 @@ class WholeTableAnnotationsContext implements Context private array $data; /** @Transform table:* */ - public function transformTable(TableNode $table): array { + public function transformTable(TableNode $table): array + { return $table->getHash(); } /** @Given data: */ - public function givenData(array $data): void { + public function givenData(array $data): void + { $this->data = $data; } /** @Then the :field should be :value */ - public function theFieldShouldBe(string $field, string $value): void { + public function theFieldShouldBe(string $field, string $value): void + { Assert::assertSame($value, $this->data[0][$field]); } } From 4d63e26cd1109d28f8b3aa464d0ec89598e713d0 Mon Sep 17 00:00:00 2001 From: Carlos Granados Date: Fri, 7 Feb 2025 10:55:55 +0100 Subject: [PATCH 559/567] Changes after PR review --- ...itions_transformations_annotations.feature | 12 ----- ...nitions_transformations_attributes.feature | 13 +++++ .../TableColumnTransformation.php | 13 +++-- tests/Fixtures/Transformations/behat.php | 38 +++++++------- .../bootstrap/ColumnTransformationContext.php | 31 +++++++++++ .../TransformationAnnotationsContext.php | 24 --------- .../bootstrap/UserAttributesContext.php | 36 ------------- ...AnnotationsContext.php => UserContext.php} | 51 ++++++------------- 8 files changed, 85 insertions(+), 133 deletions(-) create mode 100644 tests/Fixtures/Transformations/features/bootstrap/ColumnTransformationContext.php delete mode 100644 tests/Fixtures/Transformations/features/bootstrap/UserAttributesContext.php rename tests/Fixtures/Transformations/features/bootstrap/{UserAnnotationsContext.php => UserContext.php} (65%) diff --git a/features/definitions_transformations_annotations.feature b/features/definitions_transformations_annotations.feature index fee23ade1..b1c42c43c 100644 --- a/features/definitions_transformations_annotations.feature +++ b/features/definitions_transformations_annotations.feature @@ -59,18 +59,6 @@ Feature: Step Arguments Transformations Annotations 6 steps (6 passed) """ - Scenario: Table Column Arguments Transformations - When I run behat with the following additional options: - | option | value | - | --suite | table_column_argument_transformation | - Then it should pass with: - """ - ........... - - 4 scenarios (4 passed) - 11 steps (11 passed) - """ - Scenario: Whole table transformation When I run behat with the following additional options: | option | value | diff --git a/features/definitions_transformations_attributes.feature b/features/definitions_transformations_attributes.feature index 2053e4bfc..f4946fe51 100644 --- a/features/definitions_transformations_attributes.feature +++ b/features/definitions_transformations_attributes.feature @@ -46,3 +46,16 @@ Feature: Step Arguments Transformations with Attributes 2 scenarios (2 passed) 6 steps (6 passed) """ + + Scenario: Table Column Arguments Transformations + When I run behat with the following additional options: + | option | value | + | --suite | table_column_argument_transformation | + Then it should pass with: + """ + ........... + + 4 scenarios (4 passed) + 11 steps (11 passed) + """ + diff --git a/src/Behat/Behat/Transformation/Transformation/TableColumnTransformation.php b/src/Behat/Behat/Transformation/Transformation/TableColumnTransformation.php index dae001608..ecf5bfa06 100644 --- a/src/Behat/Behat/Transformation/Transformation/TableColumnTransformation.php +++ b/src/Behat/Behat/Transformation/Transformation/TableColumnTransformation.php @@ -41,6 +41,9 @@ public function supportsDefinitionAndArgument( $argumentIndex, $argumentArgumentValue ): bool { + // The argument passed initially will be a TableNode but if a column transformation + // has already been applied then this will have been transformed into an array already, + // so we need to accept both possibilities if (!$argumentArgumentValue instanceof TableNode && !is_array($argumentArgumentValue)) { return false; }; @@ -52,12 +55,7 @@ public function supportsDefinitionAndArgument( if ($argumentArgumentValue instanceof TableNode) { $tableHeadings = $argumentArgumentValue->getRow(0); - foreach ($columnNames as $columnName) { - if (in_array($columnName, $tableHeadings, true)) { - return true; - } - return false; - } + return array_intersect($columnNames, $tableHeadings) !== []; } foreach ($argumentArgumentValue as $row) { $rowHasColumn = false; @@ -110,7 +108,8 @@ public function transformArgument( } /** - * {@inheritdoc} + * The priority of this transformer needs to be less that the priority of the other table transformers because + * we want to be able to transform whole tables or whole rows before we attempt to transform any column */ public function getPriority() { diff --git a/tests/Fixtures/Transformations/behat.php b/tests/Fixtures/Transformations/behat.php index 5b64b5197..ae0d755ac 100644 --- a/tests/Fixtures/Transformations/behat.php +++ b/tests/Fixtures/Transformations/behat.php @@ -14,7 +14,7 @@ ) ->withContexts( 'SimpleTransformationAttributesContext', - 'UserAttributesContext' + 'UserContext' ) ) ->withSuite( @@ -24,7 +24,7 @@ ) ->withContexts( 'TransformationWithoutParametersAttributesContext', - 'UserAttributesContext' + 'UserContext' ) ) ->withSuite( @@ -34,9 +34,19 @@ ) ->withContexts( 'MultipleTransformationsInOneFunctionAttributesContext', - 'UserAttributesContext' + 'UserContext' ) ) + ->withSuite( + (new Suite('table_column_argument_transformation')) + ->withPaths( + 'features/table_column_argument_transformation.feature' + ) + ->withContexts( + 'ColumnTransformationContext', + 'UserContext' + ) + ) ) ->withProfile( (new Profile('annotations')) @@ -47,7 +57,7 @@ ) ->withContexts( 'TransformationAnnotationsContext', - 'UserAnnotationsContext' + 'UserContext' ) ) ->withSuite( @@ -57,7 +67,7 @@ ) ->withContexts( 'TransformationAnnotationsContext', - 'UserAnnotationsContext' + 'UserContext' ) ) ->withSuite( @@ -67,7 +77,7 @@ ) ->withContexts( 'TransformationAnnotationsContext', - 'UserAnnotationsContext' + 'UserContext' ) ) ->withSuite( @@ -77,17 +87,7 @@ ) ->withContexts( 'TransformationAnnotationsContext', - 'UserAnnotationsContext' - ) - ) - ->withSuite( - (new Suite('table_column_argument_transformation')) - ->withPaths( - 'features/table_column_argument_transformation.feature' - ) - ->withContexts( - 'TransformationAnnotationsContext', - 'UserAnnotationsContext' + 'UserContext' ) ) ->withSuite( @@ -106,7 +106,7 @@ ) ->withContexts( 'TransformationAnnotationsContext', - 'UserAnnotationsContext' + 'UserContext' ) ) ->withSuite( @@ -143,7 +143,7 @@ ) ->withContexts( 'TransformationAnnotationsContext', - 'UserAnnotationsContext' + 'UserContext' ) ) ->withSuite( diff --git a/tests/Fixtures/Transformations/features/bootstrap/ColumnTransformationContext.php b/tests/Fixtures/Transformations/features/bootstrap/ColumnTransformationContext.php new file mode 100644 index 000000000..3aa251422 --- /dev/null +++ b/tests/Fixtures/Transformations/features/bootstrap/ColumnTransformationContext.php @@ -0,0 +1,31 @@ +user = $user; - } - - #[Then('/Username must be "([^"]+)"/')] - public function usernameMustBe(string $username): void - { - Assert::assertEquals($username, $this->user->getUsername()); - } - - #[Then('/Age must be (\d+)/')] - public function ageMustBe(string $age): void - { - Assert::assertEquals($age, $this->user->getAge()); - } - - #[Then('/^the boolean (no) should be transformed to false$/')] - public function theBooleanShouldBeTransformed(bool $boolean): void - { - Assert::assertSame(false, $boolean); - } -} diff --git a/tests/Fixtures/Transformations/features/bootstrap/UserAnnotationsContext.php b/tests/Fixtures/Transformations/features/bootstrap/UserContext.php similarity index 65% rename from tests/Fixtures/Transformations/features/bootstrap/UserAnnotationsContext.php rename to tests/Fixtures/Transformations/features/bootstrap/UserContext.php index c2e2fb4aa..e147204ba 100644 --- a/tests/Fixtures/Transformations/features/bootstrap/UserAnnotationsContext.php +++ b/tests/Fixtures/Transformations/features/bootstrap/UserContext.php @@ -1,96 +1,77 @@ user = $user; } - /** - * @Given I am a user with this age: - */ + #[Given('I am a user with this age:')] public function iAmAUserWithAge(array $data): void { $this->user = $data[0]['user']; $this->user->setAge($data[0]['age']); } - /** - * @Given I am a Russian user with this age: - */ + #[Given('I am a Russian user with this age:')] public function iAmARussianUserWithAgeIn(array $data): void { $this->user = $data[0]['логин']; $this->user->setAge($data[0]['age']); } - /** - * @Given I am a user with this hex age: - */ + #[Given('I am a user with this hex age:')] public function iAmAUserWithHexAge(array $data): void { $this->user = $data[0]['user']; $this->user->setAge($data[0]['hex age']); } - /** - * @Given I have two users and I add their ages - */ + #[Given('I have two users and I add their ages')] public function addTwoUsersAges(array $data): void { $this->totalAge = $data[0]['user']->getAge(); $this->totalAge += $data[0]['other user']->getAge(); } - /** - * @Then /Username must be "([^"]+)"/ - */ + #[Then('/Username must be "([^"]+)"/')] public function usernameMustBe(string $username): void { Assert::assertEquals($username, $this->user->getUsername()); } - /** - * @Then /Age must be (\d+)/ - */ - public function ageMustBe(int $age): void + #[Then('/Age must be (\d+)/')] + public function ageMustBe(string $age): void { Assert::assertEquals($age, $this->user->getAge()); - Assert::assertIsInt($age); } - /** - * @Then /total age must be (\d+)/ - */ + #[Then('/total age must be (\d+)/')] public function totalAgeMustBe(int $age): void { Assert::assertEquals($age, $this->totalAge); } - /** - * @Then the Usernames must be: - */ + #[Then('the Usernames must be:')] public function usernamesMustBe(array $usernames): void { Assert::assertEquals($usernames[0], $this->user->getUsername()); } - /** - * @Then /^the boolean (no) should be transformed to false$/ - */ + #[Then('/^the boolean (no) should be transformed to false$/')] public function theBooleanShouldBeTransformed(bool $boolean): void { Assert::assertSame(false, $boolean); From ddc7da38b9bfd993f61ea80c2f841812393cd71c Mon Sep 17 00:00:00 2001 From: Carlos Granados Date: Fri, 7 Feb 2025 16:57:03 +0100 Subject: [PATCH 560/567] fix: add some fixes to the print unused definitions feature --- features/unused_definitions.feature | 15 +++++++++++++ .../Definition/Call/RuntimeDefinition.php | 6 +++++ .../Cli/UnusedDefinitionsController.php | 4 ++-- .../ConsoleDefinitionInformationPrinter.php | 5 +---- .../Printer/UnusedDefinitionPrinter.php | 21 ++++++++++++++++++ .../Translator/TranslatedDefinition.php | 5 +++++ .../Tester/Runtime/RuntimeStepTester.php | 7 +++++- tests/Fixtures/UnusedDefinitions/behat.php | 14 ++++++++++-- .../TranslatedDefinitionsContext.php | 22 +++++++++++++++++++ .../features/bootstrap/i18n/ru.xliff | 15 +++++++++++++ .../features/translated_definitions.feature | 5 +++++ 11 files changed, 110 insertions(+), 9 deletions(-) create mode 100644 src/Behat/Behat/Definition/Printer/UnusedDefinitionPrinter.php create mode 100644 tests/Fixtures/UnusedDefinitions/features/bootstrap/TranslatedDefinitionsContext.php create mode 100644 tests/Fixtures/UnusedDefinitions/features/bootstrap/i18n/ru.xliff create mode 100644 tests/Fixtures/UnusedDefinitions/features/translated_definitions.feature diff --git a/features/unused_definitions.feature b/features/unused_definitions.feature index 5ceb46288..ad6ff1558 100644 --- a/features/unused_definitions.feature +++ b/features/unused_definitions.feature @@ -65,3 +65,18 @@ Feature: Unused definitions This is a step that is never used and should be removed `FeatureContext::stepNotUsedInAnyFeature()` """ + + Scenario: Print unused definitions when using translated definitions + When I run behat with the following additional options: + | option | value | + | --profile | translated_definitions | + | --suite | translated_definitions | + | --print-unused-definitions | | + Then it should pass with: + """ + --- 1 unused definition: + + [Given|*] /^I have clicked "+"$/ + `TranslatedDefinitionsContext::iHaveClickedPlus()` + """ + diff --git a/src/Behat/Behat/Definition/Call/RuntimeDefinition.php b/src/Behat/Behat/Definition/Call/RuntimeDefinition.php index c13560f70..e4aba6213 100644 --- a/src/Behat/Behat/Definition/Call/RuntimeDefinition.php +++ b/src/Behat/Behat/Definition/Call/RuntimeDefinition.php @@ -71,11 +71,17 @@ public function __toString() return $this->getType() . ' ' . $this->getPattern(); } + /** + * @internal + */ public function markAsUsed(): void { $this->used = true; } + /** + * @internal + */ public function hasBeenUsed(): bool { return $this->used; diff --git a/src/Behat/Behat/Definition/Cli/UnusedDefinitionsController.php b/src/Behat/Behat/Definition/Cli/UnusedDefinitionsController.php index c3810ef51..f222fed6d 100644 --- a/src/Behat/Behat/Definition/Cli/UnusedDefinitionsController.php +++ b/src/Behat/Behat/Definition/Cli/UnusedDefinitionsController.php @@ -12,7 +12,7 @@ use Behat\Behat\Definition\Call\RuntimeDefinition; use Behat\Behat\Definition\DefinitionRepository; -use Behat\Behat\Definition\Printer\ConsoleDefinitionInformationPrinter; +use Behat\Behat\Definition\Printer\UnusedDefinitionPrinter; use Behat\Testwork\Cli\Controller; use Behat\Testwork\EventDispatcher\Event\AfterSuiteTested; use Behat\Testwork\EventDispatcher\Event\ExerciseCompleted; @@ -38,7 +38,7 @@ final class UnusedDefinitionsController implements Controller public function __construct( private DefinitionRepository $definitionRepository, private EventDispatcherInterface $eventDispatcher, - private ConsoleDefinitionInformationPrinter $printer, + private UnusedDefinitionPrinter $printer, private bool $printUnusedDefinitions ) { } diff --git a/src/Behat/Behat/Definition/Printer/ConsoleDefinitionInformationPrinter.php b/src/Behat/Behat/Definition/Printer/ConsoleDefinitionInformationPrinter.php index 9b3572bb5..d0936f01d 100644 --- a/src/Behat/Behat/Definition/Printer/ConsoleDefinitionInformationPrinter.php +++ b/src/Behat/Behat/Definition/Printer/ConsoleDefinitionInformationPrinter.php @@ -18,7 +18,7 @@ * * @author Konstantin Kudryashov */ -final class ConsoleDefinitionInformationPrinter extends ConsoleDefinitionPrinter +final class ConsoleDefinitionInformationPrinter extends ConsoleDefinitionPrinter implements UnusedDefinitionPrinter { /** * @var null|string @@ -43,9 +43,6 @@ public function printDefinitions(Suite $suite, $definitions) $this->printDefinitionsWithOptionalSuite($definitions, $suite); } - /** - * @param Definition[] $definitions - */ public function printUnusedDefinitions(array $definitions): void { $unusedDefinitionsText = $this->translateInfoText( diff --git a/src/Behat/Behat/Definition/Printer/UnusedDefinitionPrinter.php b/src/Behat/Behat/Definition/Printer/UnusedDefinitionPrinter.php new file mode 100644 index 000000000..a8ad2600d --- /dev/null +++ b/src/Behat/Behat/Definition/Printer/UnusedDefinitionPrinter.php @@ -0,0 +1,21 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Behat\Behat\Definition\Printer; + +use Behat\Behat\Definition\Definition; + +interface UnusedDefinitionPrinter +{ + /** + * @param Definition[] $definitions + */ + public function printUnusedDefinitions(array $definitions): void; +} diff --git a/src/Behat/Behat/Definition/Translator/TranslatedDefinition.php b/src/Behat/Behat/Definition/Translator/TranslatedDefinition.php index 69813facb..c7bf0ba3e 100644 --- a/src/Behat/Behat/Definition/Translator/TranslatedDefinition.php +++ b/src/Behat/Behat/Definition/Translator/TranslatedDefinition.php @@ -130,6 +130,11 @@ public function getReflection() return $this->definition->getReflection(); } + public function getOriginalDefinition(): Definition + { + return $this->definition; + } + /** * {@inheritdoc} */ diff --git a/src/Behat/Behat/Tester/Runtime/RuntimeStepTester.php b/src/Behat/Behat/Tester/Runtime/RuntimeStepTester.php index ddd60b14b..0dfb94ff1 100644 --- a/src/Behat/Behat/Tester/Runtime/RuntimeStepTester.php +++ b/src/Behat/Behat/Tester/Runtime/RuntimeStepTester.php @@ -15,6 +15,7 @@ use Behat\Behat\Definition\DefinitionFinder; use Behat\Behat\Definition\Exception\SearchException; use Behat\Behat\Definition\SearchResult; +use Behat\Behat\Definition\Translator\TranslatedDefinition; use Behat\Behat\Tester\Result\ExecutedStepResult; use Behat\Behat\Tester\Result\FailedStepSearchResult; use Behat\Behat\Tester\Result\SkippedStepResult; @@ -118,9 +119,13 @@ private function testDefinition(Environment $env, FeatureNode $feature, StepNode return new UndefinedStepResult(); } + $definition = $search->getMatchedDefinition(); + // If the definition found is a translated definition, we need to mark the original definition + if ($definition instanceof TranslatedDefinition) { + $definition = $definition->getOriginalDefinition(); + } // If a definition has been found, we mark it as used even if it may be skipped, // as we want to count skipped definitions as used - $definition = $search->getMatchedDefinition(); if ($definition instanceof RuntimeDefinition) { $definition->markAsUsed(); } diff --git a/tests/Fixtures/UnusedDefinitions/behat.php b/tests/Fixtures/UnusedDefinitions/behat.php index d72db48ed..16dd17de8 100644 --- a/tests/Fixtures/UnusedDefinitions/behat.php +++ b/tests/Fixtures/UnusedDefinitions/behat.php @@ -20,10 +20,20 @@ ) ) ) + ->withProfile( + (new Profile('translated_definitions')) + ->withSuite( + (new Suite('translated_definitions')) + ->withPaths( + 'features/translated_definitions.feature' + ) + ->withContexts( + 'TranslatedDefinitionsContext', + ) + ) + ) ->withProfile( (new Profile('unused_definitions')) ->withPrintUnusedDefinitions() ) ; - -; diff --git a/tests/Fixtures/UnusedDefinitions/features/bootstrap/TranslatedDefinitionsContext.php b/tests/Fixtures/UnusedDefinitions/features/bootstrap/TranslatedDefinitionsContext.php new file mode 100644 index 000000000..d50d2b1ac --- /dev/null +++ b/tests/Fixtures/UnusedDefinitions/features/bootstrap/TranslatedDefinitionsContext.php @@ -0,0 +1,22 @@ + + +
+ + + + + + diff --git a/tests/Fixtures/UnusedDefinitions/features/translated_definitions.feature b/tests/Fixtures/UnusedDefinitions/features/translated_definitions.feature new file mode 100644 index 000000000..6270b59d9 --- /dev/null +++ b/tests/Fixtures/UnusedDefinitions/features/translated_definitions.feature @@ -0,0 +1,5 @@ +# language: ru +Функция: Базовая калькуляция + + Сценарий: + Допустим Я набрал число 10 на калькуляторе From 2c95bef0557362d4ec71c7b32abc2f13019b9e55 Mon Sep 17 00:00:00 2001 From: acoulton
+ /^I have entered (\d+) into calculator$/ + + /^Я набрал число (\d+) на калькуляторе$/ + /^I have clicked "+"$/ + + /^Я нажал "([^"]*)"$/ Date: Thu, 13 Feb 2025 08:39:41 +0000 Subject: [PATCH 561/567] Add changelog for 3.19.0 release --- CHANGELOG.md | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 15ed76996..853610750 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,34 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](http://keepachangelog.com/) and this project adheres to [Semantic Versioning](http://semver.org/). +## [3.19.0] - 2025-02-13 + +### Changed + +* Remove internal wrappers for PSR Container interfaces - may affect projects using container-interop/container-interop + < 1.2.0 (released in 2017, package now deprecated and unsupported by behat since 2021). + By @acoulton in [#1584](https://github.com/Behat/Behat/pull/1584) +* Remove legacy Symfony event dispatchers - these were internal wrappers to support symfony <5 and >=5, both now + redundant. By @carlos-granados in [#1585](https://github.com/Behat/Behat/pull/1585) + +### Added + +* Add option to print unused definitions by @carlos-granados in [#1594](https://github.com/Behat/Behat/pull/1594) and + [#1597](https://github.com/Behat/Behat/pull/1597) +* Support transforming named column(s) in any table by @carlos-granados in [#1593](https://github.com/Behat/Behat/pull/1593) + +### Fixed + +* Allow unicode characters in table transformations by @carlos-granados in [#1595](https://github.com/Behat/Behat/pull/1595) + +### Internal + +* Use real files instead of generated files in local tests by @carlos-granados in [#1544](https://github.com/Behat/Behat/pull/1544) +* Adopt PHP CS Fixer and apply PSR2 styles by @carlos-granados in [#1592](https://github.com/Behat/Behat/pull/1592) +* Migrate from Psalm to PHPStan and improve internal type safety by @carlos-granados in [#1583](https://github.com/Behat/Behat/pull/1583), + [#1589](https://github.com/Behat/Behat/pull/1589) and [#1590](https://github.com/Behat/Behat/pull/1590) and by + @stof in [#1591](https://github.com/Behat/Behat/pull/1591) + ## [3.18.1] - 2025-01-10 ### Fixed @@ -1175,6 +1203,8 @@ and this project adheres to [Semantic Versioning](http://semver.org/). ### Changed * Initial release +[3.19.0]: https://github.com/Behat/Behat/compare/v3.18.1...v3.19.0 +[3.18.1]: https://github.com/Behat/Behat/compare/v3.18.0...v3.18.1 [3.18.0]: https://github.com/Behat/Behat/compare/v3.17.0...v3.18.0 [3.17.0]: https://github.com/Behat/Behat/compare/v3.16.0...v3.17.0 [3.16.0]: https://github.com/Behat/Behat/compare/v3.15.0...v3.16.0 From 90fa446e782f14afe3c7a47b58934eff537f6e94 Mon Sep 17 00:00:00 2001 From: Carlos Granados Date: Fri, 31 Jan 2025 15:58:18 +0100 Subject: [PATCH 562/567] PSR-12 spacing --- .php-cs-fixer.dist.php | 88 +++++++++++++++++++ .../UninitializedContextEnvironment.php | 2 +- .../ServiceContainer/ContextExtension.php | 2 +- .../ServiceContainer/DefinitionExtension.php | 2 +- .../ServiceContainer/GherkinExtension.php | 2 +- .../HelperContainer/ArgumentAutowirer.php | 2 +- .../HelperContainerExtension.php | 2 +- .../Formatter/PrettyFormatterFactory.php | 2 +- .../Formatter/ProgressFormatterFactory.php | 2 +- .../ServiceContainer/SnippetExtension.php | 2 +- .../ServiceContainer/TesterExtension.php | 2 +- .../ReturnTypeTransformation.php | 4 +- .../Argument/MixedArgumentOrganiser.php | 4 +- .../Call/Handler/RuntimeCallHandler.php | 2 +- .../Call/ServiceContainer/CallExtension.php | 2 +- src/Behat/Testwork/Cli/Application.php | 2 +- .../ServiceContainer/EnvironmentExtension.php | 2 +- .../EventDispatcherExtension.php | 2 +- .../ServiceContainer/ExceptionExtension.php | 2 +- .../Printer/Factory/ConsoleOutputFactory.php | 2 +- .../ServiceContainer/OutputExtension.php | 2 +- .../ServiceContainer/ContainerLoader.php | 4 +- .../SpecificationExtension.php | 2 +- .../Suite/ServiceContainer/SuiteExtension.php | 2 +- .../ServiceContainer/TesterExtension.php | 2 +- .../Argument/MixedArgumentOrganiserTest.php | 2 +- .../ByTypeAndByNameAnnotationsContext.php | 4 +- .../bootstrap/ByTypeAnnotationsContext.php | 2 +- 28 files changed, 119 insertions(+), 31 deletions(-) diff --git a/.php-cs-fixer.dist.php b/.php-cs-fixer.dist.php index 04a0e5839..4f820a912 100644 --- a/.php-cs-fixer.dist.php +++ b/.php-cs-fixer.dist.php @@ -8,5 +8,93 @@ ->setParallelConfig(PhpCsFixer\Runner\Parallel\ParallelConfigFactory::detect()) ->setRules([ '@PSR2' => true, + 'binary_operator_spaces' => [ + 'default' => 'at_least_single_space', + ], +// 'blank_line_after_opening_tag' => true, +// 'blank_line_between_import_groups' => true, +// 'blank_lines_before_namespace' => true, +// 'braces_position' => [ +// 'allow_single_line_empty_anonymous_classes' => true, +// ], +// 'class_definition' => [ +// 'inline_constructor_arguments' => false, // handled by method_argument_space fixer +// 'space_before_parenthesis' => true, // defined in PSR12 ¶8. Anonymous Classes +// ], +// 'compact_nullable_type_declaration' => true, +// 'declare_equal_normalize' => true, +// 'lowercase_cast' => true, +// 'lowercase_static_reference' => true, +// 'new_with_parentheses' => true, +// 'no_blank_lines_after_class_opening' => true, +// 'no_extra_blank_lines' => [ +// 'tokens' => [ +// 'use', // defined in PSR12 ¶3. Declare Statements, Namespace, and Import Statements +// ], +// ], +// 'no_leading_import_slash' => true, +// 'no_whitespace_in_blank_line' => true, +// 'ordered_class_elements' => [ +// 'order' => [ +// 'use_trait', +// ], +// ], +// 'ordered_imports' => [ +// 'imports_order' => [ +// 'class', +// 'function', +// 'const', +// ], +// 'sort_algorithm' => 'none', +// ], + 'return_type_declaration' => true, +// 'short_scalar_cast' => true, +// 'single_import_per_statement' => ['group_to_single_imports' => false], + 'single_space_around_construct' => [ + 'constructs_followed_by_a_single_space' => [ + 'abstract', + 'as', + 'case', + 'catch', + 'class', + 'const_import', + 'do', + 'else', + 'elseif', + 'final', + 'finally', + 'for', + 'foreach', + 'function', + 'function_import', + 'if', + 'insteadof', + 'interface', + 'namespace', + 'new', + 'private', + 'protected', + 'public', + 'static', + 'switch', + 'trait', + 'try', + 'use', + 'use_lambda', + 'while', + ], + 'constructs_preceded_by_a_single_space' => [ + 'as', + 'else', + 'elseif', + 'use_lambda', + ], + ], +// 'single_trait_insert_per_statement' => true, + 'ternary_operator_spaces' => true, + 'unary_operator_spaces' => [ + 'only_dec_inc' => true, + ], +// 'visibility_required' => true, ]) ->setFinder($finder); diff --git a/src/Behat/Behat/Context/Environment/UninitializedContextEnvironment.php b/src/Behat/Behat/Context/Environment/UninitializedContextEnvironment.php index d36593b3d..2059592c1 100644 --- a/src/Behat/Behat/Context/Environment/UninitializedContextEnvironment.php +++ b/src/Behat/Behat/Context/Environment/UninitializedContextEnvironment.php @@ -57,7 +57,7 @@ public function registerContextClass($contextClass, ?array $arguments = null) ), $contextClass); } - $this->contextClasses[$contextClass] = $arguments ? : array(); + $this->contextClasses[$contextClass] = $arguments ?: array(); } /** diff --git a/src/Behat/Behat/Context/ServiceContainer/ContextExtension.php b/src/Behat/Behat/Context/ServiceContainer/ContextExtension.php index 1e21bbb25..1680173f1 100644 --- a/src/Behat/Behat/Context/ServiceContainer/ContextExtension.php +++ b/src/Behat/Behat/Context/ServiceContainer/ContextExtension.php @@ -73,7 +73,7 @@ final class ContextExtension implements Extension */ public function __construct(?ServiceProcessor $processor = null) { - $this->processor = $processor ? : new ServiceProcessor(); + $this->processor = $processor ?: new ServiceProcessor(); } /** diff --git a/src/Behat/Behat/Definition/ServiceContainer/DefinitionExtension.php b/src/Behat/Behat/Definition/ServiceContainer/DefinitionExtension.php index 705947d62..e50f062a6 100644 --- a/src/Behat/Behat/Definition/ServiceContainer/DefinitionExtension.php +++ b/src/Behat/Behat/Definition/ServiceContainer/DefinitionExtension.php @@ -61,7 +61,7 @@ final class DefinitionExtension implements Extension */ public function __construct(?ServiceProcessor $processor = null) { - $this->processor = $processor ? : new ServiceProcessor(); + $this->processor = $processor ?: new ServiceProcessor(); } /** diff --git a/src/Behat/Behat/Gherkin/ServiceContainer/GherkinExtension.php b/src/Behat/Behat/Gherkin/ServiceContainer/GherkinExtension.php index 3699248f0..7625b910b 100644 --- a/src/Behat/Behat/Gherkin/ServiceContainer/GherkinExtension.php +++ b/src/Behat/Behat/Gherkin/ServiceContainer/GherkinExtension.php @@ -56,7 +56,7 @@ final class GherkinExtension implements Extension */ public function __construct(?ServiceProcessor $processor = null) { - $this->processor = $processor ? : new ServiceProcessor(); + $this->processor = $processor ?: new ServiceProcessor(); } /** diff --git a/src/Behat/Behat/HelperContainer/ArgumentAutowirer.php b/src/Behat/Behat/HelperContainer/ArgumentAutowirer.php index ed523bb33..9c81e13c2 100644 --- a/src/Behat/Behat/HelperContainer/ArgumentAutowirer.php +++ b/src/Behat/Behat/HelperContainer/ArgumentAutowirer.php @@ -86,7 +86,7 @@ private function isArgumentWireable(array $arguments, $index, ReflectionParamete return (bool) $this->getClassFromParameter($parameter); } - private function getClassFromParameter(ReflectionParameter $parameter) : ?string + private function getClassFromParameter(ReflectionParameter $parameter): ?string { if (!($type = $parameter->getType()) || !($type instanceof ReflectionNamedType)) { return null; diff --git a/src/Behat/Behat/HelperContainer/ServiceContainer/HelperContainerExtension.php b/src/Behat/Behat/HelperContainer/ServiceContainer/HelperContainerExtension.php index e7fe83a00..f00780503 100644 --- a/src/Behat/Behat/HelperContainer/ServiceContainer/HelperContainerExtension.php +++ b/src/Behat/Behat/HelperContainer/ServiceContainer/HelperContainerExtension.php @@ -47,7 +47,7 @@ final class HelperContainerExtension implements Extension */ public function __construct(?ServiceProcessor $processor = null) { - $this->processor = $processor ? : new ServiceProcessor(); + $this->processor = $processor ?: new ServiceProcessor(); } /** diff --git a/src/Behat/Behat/Output/ServiceContainer/Formatter/PrettyFormatterFactory.php b/src/Behat/Behat/Output/ServiceContainer/Formatter/PrettyFormatterFactory.php index 318ec0b59..d6618d39a 100644 --- a/src/Behat/Behat/Output/ServiceContainer/Formatter/PrettyFormatterFactory.php +++ b/src/Behat/Behat/Output/ServiceContainer/Formatter/PrettyFormatterFactory.php @@ -54,7 +54,7 @@ class PrettyFormatterFactory implements FormatterFactory */ public function __construct(?ServiceProcessor $processor = null) { - $this->processor = $processor ? : new ServiceProcessor(); + $this->processor = $processor ?: new ServiceProcessor(); } /** diff --git a/src/Behat/Behat/Output/ServiceContainer/Formatter/ProgressFormatterFactory.php b/src/Behat/Behat/Output/ServiceContainer/Formatter/ProgressFormatterFactory.php index ee769d5de..736d8eb87 100644 --- a/src/Behat/Behat/Output/ServiceContainer/Formatter/ProgressFormatterFactory.php +++ b/src/Behat/Behat/Output/ServiceContainer/Formatter/ProgressFormatterFactory.php @@ -50,7 +50,7 @@ class ProgressFormatterFactory implements FormatterFactory */ public function __construct(?ServiceProcessor $processor = null) { - $this->processor = $processor ? : new ServiceProcessor(); + $this->processor = $processor ?: new ServiceProcessor(); } /** diff --git a/src/Behat/Behat/Snippet/ServiceContainer/SnippetExtension.php b/src/Behat/Behat/Snippet/ServiceContainer/SnippetExtension.php index 8d2855edb..d90cecc61 100644 --- a/src/Behat/Behat/Snippet/ServiceContainer/SnippetExtension.php +++ b/src/Behat/Behat/Snippet/ServiceContainer/SnippetExtension.php @@ -52,7 +52,7 @@ class SnippetExtension implements Extension */ public function __construct(?ServiceProcessor $processor = null) { - $this->processor = $processor ? : new ServiceProcessor(); + $this->processor = $processor ?: new ServiceProcessor(); } /** diff --git a/src/Behat/Behat/Tester/ServiceContainer/TesterExtension.php b/src/Behat/Behat/Tester/ServiceContainer/TesterExtension.php index d0e0a2cdb..8bce66a69 100644 --- a/src/Behat/Behat/Tester/ServiceContainer/TesterExtension.php +++ b/src/Behat/Behat/Tester/ServiceContainer/TesterExtension.php @@ -60,7 +60,7 @@ class TesterExtension extends BaseExtension */ public function __construct(?ServiceProcessor $processor = null) { - $this->processor = $processor ? : new ServiceProcessor(); + $this->processor = $processor ?: new ServiceProcessor(); parent::__construct($this->processor); } diff --git a/src/Behat/Behat/Transformation/Transformation/ReturnTypeTransformation.php b/src/Behat/Behat/Transformation/Transformation/ReturnTypeTransformation.php index bc9497907..79145cc28 100644 --- a/src/Behat/Behat/Transformation/Transformation/ReturnTypeTransformation.php +++ b/src/Behat/Behat/Transformation/Transformation/ReturnTypeTransformation.php @@ -219,9 +219,9 @@ private function hasPosition($index) * * @return Closure */ - private function getClassReflection() : closure + private function getClassReflection(): closure { - return function (ReflectionParameter $parameter) : ?ReflectionClass { + return function (ReflectionParameter $parameter): ?ReflectionClass { $t = $parameter->getType(); if ($t instanceof ReflectionNamedType) { diff --git a/src/Behat/Testwork/Argument/MixedArgumentOrganiser.php b/src/Behat/Testwork/Argument/MixedArgumentOrganiser.php index df92dee51..5cd5b96c3 100644 --- a/src/Behat/Testwork/Argument/MixedArgumentOrganiser.php +++ b/src/Behat/Testwork/Argument/MixedArgumentOrganiser.php @@ -134,7 +134,7 @@ private function isParameterTypehintedInArgumentList(array $parameters, $value) /** * Checks if value matches typehint of provided parameter. */ - private function isValueMatchesTypehintedParameter($value, ReflectionParameter $parameter) : bool + private function isValueMatchesTypehintedParameter($value, ReflectionParameter $parameter): bool { foreach ($this->getReflectionClassesFromParameter($parameter) as $typehintRefl) { if ($typehintRefl->isInstance($value)) { @@ -218,7 +218,7 @@ private function prepareTypehintedArguments(array $parameters, array $typehinted * @param ReflectionParameter[] $parameters Constructor Arguments * @return ReflectionParameter[] Filtered $parameters */ - private function filterApplicableTypehintedParameters(array $parameters) : array + private function filterApplicableTypehintedParameters(array $parameters): array { return array_filter( $parameters, diff --git a/src/Behat/Testwork/Call/Handler/RuntimeCallHandler.php b/src/Behat/Testwork/Call/Handler/RuntimeCallHandler.php index 9f51cd06c..36d593d9c 100644 --- a/src/Behat/Testwork/Call/Handler/RuntimeCallHandler.php +++ b/src/Behat/Testwork/Call/Handler/RuntimeCallHandler.php @@ -134,7 +134,7 @@ private function getBufferedStdOut() */ private function startErrorAndOutputBuffering(Call $call) { - $errorReporting = $call->getErrorReportingLevel() ? : $this->errorReportingLevel; + $errorReporting = $call->getErrorReportingLevel() ?: $this->errorReportingLevel; set_error_handler(array($this, 'handleError'), $errorReporting); $this->obStarted = ob_start(); } diff --git a/src/Behat/Testwork/Call/ServiceContainer/CallExtension.php b/src/Behat/Testwork/Call/ServiceContainer/CallExtension.php index e7aa9f9f4..2f1301285 100644 --- a/src/Behat/Testwork/Call/ServiceContainer/CallExtension.php +++ b/src/Behat/Testwork/Call/ServiceContainer/CallExtension.php @@ -49,7 +49,7 @@ final class CallExtension implements Extension */ public function __construct(?ServiceProcessor $processor = null) { - $this->processor = $processor ? : new ServiceProcessor(); + $this->processor = $processor ?: new ServiceProcessor(); } /** diff --git a/src/Behat/Testwork/Cli/Application.php b/src/Behat/Testwork/Cli/Application.php index 04968fe4c..32b1ad6bc 100644 --- a/src/Behat/Testwork/Cli/Application.php +++ b/src/Behat/Testwork/Cli/Application.php @@ -159,7 +159,7 @@ protected function getDefaultCommands(): array */ private function loadConfiguration(InputInterface $input) { - $profile = $input->getParameterOption(array('--profile', '-p')) ? : 'default'; + $profile = $input->getParameterOption(array('--profile', '-p')) ?: 'default'; return $this->configurationLoader->loadConfiguration($profile); } diff --git a/src/Behat/Testwork/Environment/ServiceContainer/EnvironmentExtension.php b/src/Behat/Testwork/Environment/ServiceContainer/EnvironmentExtension.php index 23c67cc30..efcb8a5d9 100644 --- a/src/Behat/Testwork/Environment/ServiceContainer/EnvironmentExtension.php +++ b/src/Behat/Testwork/Environment/ServiceContainer/EnvironmentExtension.php @@ -49,7 +49,7 @@ final class EnvironmentExtension implements Extension */ public function __construct(?ServiceProcessor $processor = null) { - $this->processor = $processor ? : new ServiceProcessor(); + $this->processor = $processor ?: new ServiceProcessor(); } /** diff --git a/src/Behat/Testwork/EventDispatcher/ServiceContainer/EventDispatcherExtension.php b/src/Behat/Testwork/EventDispatcher/ServiceContainer/EventDispatcherExtension.php index 782247ff6..da56f7409 100644 --- a/src/Behat/Testwork/EventDispatcher/ServiceContainer/EventDispatcherExtension.php +++ b/src/Behat/Testwork/EventDispatcher/ServiceContainer/EventDispatcherExtension.php @@ -49,7 +49,7 @@ class EventDispatcherExtension implements Extension */ public function __construct(?ServiceProcessor $processor = null) { - $this->processor = $processor ? : new ServiceProcessor(); + $this->processor = $processor ?: new ServiceProcessor(); } /** diff --git a/src/Behat/Testwork/Exception/ServiceContainer/ExceptionExtension.php b/src/Behat/Testwork/Exception/ServiceContainer/ExceptionExtension.php index 29e9d6386..44fcd12be 100644 --- a/src/Behat/Testwork/Exception/ServiceContainer/ExceptionExtension.php +++ b/src/Behat/Testwork/Exception/ServiceContainer/ExceptionExtension.php @@ -49,7 +49,7 @@ final class ExceptionExtension implements Extension */ public function __construct(?ServiceProcessor $processor = null) { - $this->processor = $processor ? : new ServiceProcessor(); + $this->processor = $processor ?: new ServiceProcessor(); } /** diff --git a/src/Behat/Testwork/Output/Printer/Factory/ConsoleOutputFactory.php b/src/Behat/Testwork/Output/Printer/Factory/ConsoleOutputFactory.php index e1d22ee18..b29bee684 100644 --- a/src/Behat/Testwork/Output/Printer/Factory/ConsoleOutputFactory.php +++ b/src/Behat/Testwork/Output/Printer/Factory/ConsoleOutputFactory.php @@ -79,7 +79,7 @@ protected function createOutputStream() */ public function createOutput($stream = null) { - $stream = $stream ? : $this->createOutputStream(); + $stream = $stream ?: $this->createOutputStream(); $format = $this->createOutputFormatter(); // set user-defined styles diff --git a/src/Behat/Testwork/Output/ServiceContainer/OutputExtension.php b/src/Behat/Testwork/Output/ServiceContainer/OutputExtension.php index 7cfd06eb3..8dc0d7557 100644 --- a/src/Behat/Testwork/Output/ServiceContainer/OutputExtension.php +++ b/src/Behat/Testwork/Output/ServiceContainer/OutputExtension.php @@ -62,7 +62,7 @@ public function __construct($defaultFormatter, array $formatterFactories, ?Servi { $this->defaultFormatter = $defaultFormatter; $this->factories = $formatterFactories; - $this->processor = $processor ? : new ServiceProcessor(); + $this->processor = $processor ?: new ServiceProcessor(); } /** diff --git a/src/Behat/Testwork/ServiceContainer/ContainerLoader.php b/src/Behat/Testwork/ServiceContainer/ContainerLoader.php index 3df054375..680164c45 100644 --- a/src/Behat/Testwork/ServiceContainer/ContainerLoader.php +++ b/src/Behat/Testwork/ServiceContainer/ContainerLoader.php @@ -49,8 +49,8 @@ public function __construct( ?Processor $processor = null ) { $this->extensionManager = $extensionManager; - $this->configuration = $configuration ? : new ConfigurationTree(); - $this->processor = $processor ? : new Processor(); + $this->configuration = $configuration ?: new ConfigurationTree(); + $this->processor = $processor ?: new Processor(); } /** diff --git a/src/Behat/Testwork/Specification/ServiceContainer/SpecificationExtension.php b/src/Behat/Testwork/Specification/ServiceContainer/SpecificationExtension.php index 4154f80ed..4901ab3c2 100644 --- a/src/Behat/Testwork/Specification/ServiceContainer/SpecificationExtension.php +++ b/src/Behat/Testwork/Specification/ServiceContainer/SpecificationExtension.php @@ -46,7 +46,7 @@ final class SpecificationExtension implements Extension */ public function __construct(?ServiceProcessor $processor = null) { - $this->processor = $processor ? : new ServiceProcessor(); + $this->processor = $processor ?: new ServiceProcessor(); } /** diff --git a/src/Behat/Testwork/Suite/ServiceContainer/SuiteExtension.php b/src/Behat/Testwork/Suite/ServiceContainer/SuiteExtension.php index 1492973bf..af8ccd0c7 100644 --- a/src/Behat/Testwork/Suite/ServiceContainer/SuiteExtension.php +++ b/src/Behat/Testwork/Suite/ServiceContainer/SuiteExtension.php @@ -50,7 +50,7 @@ final class SuiteExtension implements Extension */ public function __construct(?ServiceProcessor $processor = null) { - $this->processor = $processor ? : new ServiceProcessor(); + $this->processor = $processor ?: new ServiceProcessor(); } /** diff --git a/src/Behat/Testwork/Tester/ServiceContainer/TesterExtension.php b/src/Behat/Testwork/Tester/ServiceContainer/TesterExtension.php index 172ffa561..a8424912a 100644 --- a/src/Behat/Testwork/Tester/ServiceContainer/TesterExtension.php +++ b/src/Behat/Testwork/Tester/ServiceContainer/TesterExtension.php @@ -59,7 +59,7 @@ abstract class TesterExtension implements Extension */ public function __construct(?ServiceProcessor $processor = null) { - $this->processor = $processor ? : new ServiceProcessor(); + $this->processor = $processor ?: new ServiceProcessor(); } /** diff --git a/tests/Behat/Tests/Testwork/Argument/MixedArgumentOrganiserTest.php b/tests/Behat/Tests/Testwork/Argument/MixedArgumentOrganiserTest.php index 93fd9282a..ce64b418d 100644 --- a/tests/Behat/Tests/Testwork/Argument/MixedArgumentOrganiserTest.php +++ b/tests/Behat/Tests/Testwork/Argument/MixedArgumentOrganiserTest.php @@ -10,7 +10,7 @@ final class MixedArgumentOrganiserTest extends TestCase { private $organiser; - protected function setUp() : void + protected function setUp(): void { $this->organiser = new MixedArgumentOrganiser(); } diff --git a/tests/Fixtures/Transformations/features/bootstrap/ByTypeAndByNameAnnotationsContext.php b/tests/Fixtures/Transformations/features/bootstrap/ByTypeAndByNameAnnotationsContext.php index bcadacb99..b953ba623 100644 --- a/tests/Fixtures/Transformations/features/bootstrap/ByTypeAndByNameAnnotationsContext.php +++ b/tests/Fixtures/Transformations/features/bootstrap/ByTypeAndByNameAnnotationsContext.php @@ -8,13 +8,13 @@ class ByTypeAndByNameAnnotationsContext implements Context private User $she; /** @Transform */ - public function userFromName(string $name) : User + public function userFromName(string $name): User { return new User($name); } /** @Transform :admin */ - public function adminFromName(string $name) : User + public function adminFromName(string $name): User { return new User('admin: ' . $name); } diff --git a/tests/Fixtures/Transformations/features/bootstrap/ByTypeAnnotationsContext.php b/tests/Fixtures/Transformations/features/bootstrap/ByTypeAnnotationsContext.php index 25f4b1f2f..722e6e641 100644 --- a/tests/Fixtures/Transformations/features/bootstrap/ByTypeAnnotationsContext.php +++ b/tests/Fixtures/Transformations/features/bootstrap/ByTypeAnnotationsContext.php @@ -8,7 +8,7 @@ class ByTypeAnnotationsContext implements Context private User $he; /** @Transform */ - public function userFromName(string $name) : User + public function userFromName(string $name): User { return new User($name); } From 4ee4d6e9d81598fe48f2e0a6b2755648aa241cb9 Mon Sep 17 00:00:00 2001 From: Carlos Granados Date: Fri, 31 Jan 2025 16:02:19 +0100 Subject: [PATCH 563/567] PSR-12 blank lines --- .php-cs-fixer.dist.php | 20 +++++++++---------- i18n.php | 4 +++- .../JUnit/JUnitDurationListener.php | 1 + .../JUnit/JUnitOutlineStoreListener.php | 1 - .../Node/Printer/JUnit/JUnitSetupPrinter.php | 2 +- .../Behat/Tester/Result/SkippedStepResult.php | 2 +- .../ReturnTypeTransformation.php | 1 - src/Behat/Config/Config.php | 1 + .../Testwork/Tester/Cli/StrictController.php | 2 +- .../Tester/Handler/StopOnFailureHandler.php | 2 +- .../ServiceContainer/TesterExtension.php | 4 ++-- .../features/bootstrap/FeatureContext.php | 1 - 12 files changed, 21 insertions(+), 20 deletions(-) diff --git a/.php-cs-fixer.dist.php b/.php-cs-fixer.dist.php index 4f820a912..9e1e52899 100644 --- a/.php-cs-fixer.dist.php +++ b/.php-cs-fixer.dist.php @@ -11,9 +11,9 @@ 'binary_operator_spaces' => [ 'default' => 'at_least_single_space', ], -// 'blank_line_after_opening_tag' => true, -// 'blank_line_between_import_groups' => true, -// 'blank_lines_before_namespace' => true, + 'blank_line_after_opening_tag' => true, + 'blank_line_between_import_groups' => true, + 'blank_lines_before_namespace' => true, // 'braces_position' => [ // 'allow_single_line_empty_anonymous_classes' => true, // ], @@ -26,14 +26,14 @@ // 'lowercase_cast' => true, // 'lowercase_static_reference' => true, // 'new_with_parentheses' => true, -// 'no_blank_lines_after_class_opening' => true, -// 'no_extra_blank_lines' => [ -// 'tokens' => [ -// 'use', // defined in PSR12 ¶3. Declare Statements, Namespace, and Import Statements -// ], -// ], + 'no_blank_lines_after_class_opening' => true, + 'no_extra_blank_lines' => [ + 'tokens' => [ + 'use', // defined in PSR12 ¶3. Declare Statements, Namespace, and Import Statements + ], + ], // 'no_leading_import_slash' => true, -// 'no_whitespace_in_blank_line' => true, + 'no_whitespace_in_blank_line' => true, // 'ordered_class_elements' => [ // 'order' => [ // 'use_trait', diff --git a/i18n.php b/i18n.php index b36fe695e..6e70a5ebf 100644 --- a/i18n.php +++ b/i18n.php @@ -1,4 +1,6 @@ - array( 'snippet_context_choice' => '', 'snippet_proposal_title' => '', diff --git a/src/Behat/Behat/Output/Node/EventListener/JUnit/JUnitDurationListener.php b/src/Behat/Behat/Output/Node/EventListener/JUnit/JUnitDurationListener.php index d8ca7c951..426fe897f 100644 --- a/src/Behat/Behat/Output/Node/EventListener/JUnit/JUnitDurationListener.php +++ b/src/Behat/Behat/Output/Node/EventListener/JUnit/JUnitDurationListener.php @@ -1,4 +1,5 @@ searchResult = $searchResult; } - + /** * Returns definition search result. * diff --git a/src/Behat/Behat/Transformation/Transformation/ReturnTypeTransformation.php b/src/Behat/Behat/Transformation/Transformation/ReturnTypeTransformation.php index 79145cc28..c5f7c9b86 100644 --- a/src/Behat/Behat/Transformation/Transformation/ReturnTypeTransformation.php +++ b/src/Behat/Behat/Transformation/Transformation/ReturnTypeTransformation.php @@ -30,7 +30,6 @@ */ final class ReturnTypeTransformation extends RuntimeCallee implements SimpleArgumentTransformation { - /** * {@inheritdoc} */ diff --git a/src/Behat/Config/Config.php b/src/Behat/Config/Config.php index c29f9f922..4bd3bbe5b 100644 --- a/src/Behat/Config/Config.php +++ b/src/Behat/Config/Config.php @@ -5,6 +5,7 @@ namespace Behat\Config; use Behat\Testwork\ServiceContainer\Exception\ConfigurationLoadingException; + use function is_string; final class Config implements ConfigInterface diff --git a/src/Behat/Testwork/Tester/Cli/StrictController.php b/src/Behat/Testwork/Tester/Cli/StrictController.php index d7853defa..53a6069d7 100644 --- a/src/Behat/Testwork/Tester/Cli/StrictController.php +++ b/src/Behat/Testwork/Tester/Cli/StrictController.php @@ -33,7 +33,7 @@ final class StrictController implements Controller * @var bool */ private $strict; - + /** * Initializes controller. * diff --git a/src/Behat/Testwork/Tester/Handler/StopOnFailureHandler.php b/src/Behat/Testwork/Tester/Handler/StopOnFailureHandler.php index a228fa48d..113939475 100644 --- a/src/Behat/Testwork/Tester/Handler/StopOnFailureHandler.php +++ b/src/Behat/Testwork/Tester/Handler/StopOnFailureHandler.php @@ -31,7 +31,7 @@ public function __construct( ) { } - + public function registerListeners() { $this->eventDispatcher->addListener(ScenarioTested::AFTER, array($this, 'exitOnFailure'), -100); diff --git a/src/Behat/Testwork/Tester/ServiceContainer/TesterExtension.php b/src/Behat/Testwork/Tester/ServiceContainer/TesterExtension.php index a8424912a..a80d1b721 100644 --- a/src/Behat/Testwork/Tester/ServiceContainer/TesterExtension.php +++ b/src/Behat/Testwork/Tester/ServiceContainer/TesterExtension.php @@ -145,8 +145,8 @@ protected function loadExerciseController(ContainerBuilder $container, $skip = f $definition->addTag(CliExtension::CONTROLLER_TAG, array('priority' => 0)); $container->setDefinition(CliExtension::CONTROLLER_TAG . '.exercise', $definition); } - - + + /** * Loads stop on failure handler. */ diff --git a/tests/Fixtures/UnusedDefinitions/features/bootstrap/FeatureContext.php b/tests/Fixtures/UnusedDefinitions/features/bootstrap/FeatureContext.php index 1b8c2f767..eb428cf48 100644 --- a/tests/Fixtures/UnusedDefinitions/features/bootstrap/FeatureContext.php +++ b/tests/Fixtures/UnusedDefinitions/features/bootstrap/FeatureContext.php @@ -8,7 +8,6 @@ class FeatureContext implements Context { - #[Given('I call a step used in the first feature')] public function stepUsedInFirstFeature(): void { From efb86c8d82cdf25017a1adfdbddf7c286e49c0c8 Mon Sep 17 00:00:00 2001 From: Carlos Granados suite has undefined steps. Please choose the context to generate snippets:%count% has missing steps. Define them with these snippets:%count% Date: Fri, 31 Jan 2025 16:09:30 +0100 Subject: [PATCH 564/567] PSR-12 Other miscellaneous changes --- .php-cs-fixer.dist.php | 14 +++++++------- .../EventDispatcher/Tester/TickingStepTester.php | 2 +- .../Argument/ServicesResolverFactory.php | 2 +- .../Testwork/ServiceContainer/ExtensionManager.php | 4 ++-- .../TestworkEventDispatcherTest.php | 12 ++++++------ .../features/bootstrap/FeatureContext.php | 2 +- 6 files changed, 18 insertions(+), 18 deletions(-) diff --git a/.php-cs-fixer.dist.php b/.php-cs-fixer.dist.php index 9e1e52899..c9738a260 100644 --- a/.php-cs-fixer.dist.php +++ b/.php-cs-fixer.dist.php @@ -17,22 +17,22 @@ // 'braces_position' => [ // 'allow_single_line_empty_anonymous_classes' => true, // ], -// 'class_definition' => [ -// 'inline_constructor_arguments' => false, // handled by method_argument_space fixer -// 'space_before_parenthesis' => true, // defined in PSR12 ¶8. Anonymous Classes -// ], + 'class_definition' => [ + 'inline_constructor_arguments' => false, // handled by method_argument_space fixer + 'space_before_parenthesis' => true, // defined in PSR12 ¶8. Anonymous Classes + ], // 'compact_nullable_type_declaration' => true, -// 'declare_equal_normalize' => true, + 'declare_equal_normalize' => true, // 'lowercase_cast' => true, // 'lowercase_static_reference' => true, -// 'new_with_parentheses' => true, + 'new_with_parentheses' => true, 'no_blank_lines_after_class_opening' => true, 'no_extra_blank_lines' => [ 'tokens' => [ 'use', // defined in PSR12 ¶3. Declare Statements, Namespace, and Import Statements ], ], -// 'no_leading_import_slash' => true, + 'no_leading_import_slash' => true, 'no_whitespace_in_blank_line' => true, // 'ordered_class_elements' => [ // 'order' => [ diff --git a/src/Behat/Behat/EventDispatcher/Tester/TickingStepTester.php b/src/Behat/Behat/EventDispatcher/Tester/TickingStepTester.php index 8a481f3d0..a8b27c5d4 100644 --- a/src/Behat/Behat/EventDispatcher/Tester/TickingStepTester.php +++ b/src/Behat/Behat/EventDispatcher/Tester/TickingStepTester.php @@ -59,7 +59,7 @@ public function setUp(Environment $env, FeatureNode $feature, StepNode $step, $s */ public function test(Environment $env, FeatureNode $feature, StepNode $step, $skip) { - declare(ticks = 1); + declare(ticks=1); return $this->baseTester->test($env, $feature, $step, $skip); } diff --git a/src/Behat/Behat/HelperContainer/Argument/ServicesResolverFactory.php b/src/Behat/Behat/HelperContainer/Argument/ServicesResolverFactory.php index 7389e28b6..8ea9770f2 100644 --- a/src/Behat/Behat/HelperContainer/Argument/ServicesResolverFactory.php +++ b/src/Behat/Behat/HelperContainer/Argument/ServicesResolverFactory.php @@ -186,7 +186,7 @@ private function createContainerFromClassSpec($classSpec) return call_user_func($constructor); } - return new $constructor[0]; + return new $constructor[0](); } /** diff --git a/src/Behat/Testwork/ServiceContainer/ExtensionManager.php b/src/Behat/Testwork/ServiceContainer/ExtensionManager.php index 4388be21f..a2b97220b 100644 --- a/src/Behat/Testwork/ServiceContainer/ExtensionManager.php +++ b/src/Behat/Testwork/ServiceContainer/ExtensionManager.php @@ -168,11 +168,11 @@ private function initialize(string $locator): Extension private function instantiateExtension(string $locator): mixed { if (class_exists($class = $locator)) { - return new $class; + return new $class(); } if (class_exists($class = $this->getFullExtensionClass($locator))) { - return new $class; + return new $class(); } if (file_exists($locator)) { diff --git a/tests/Behat/Tests/Testwork/EventDispatcher/TestworkEventDispatcherTest.php b/tests/Behat/Tests/Testwork/EventDispatcher/TestworkEventDispatcherTest.php index 4b5815fb9..fd36e9b65 100644 --- a/tests/Behat/Tests/Testwork/EventDispatcher/TestworkEventDispatcherTest.php +++ b/tests/Behat/Tests/Testwork/EventDispatcher/TestworkEventDispatcherTest.php @@ -19,7 +19,7 @@ class TestworkEventDispatcherTest extends TestCase public function testDispatchLegacyCall(): void { $dispatcher = new TestworkEventDispatcher(); - $event = new class extends Event {}; + $event = new class () extends Event {}; $eventName = 'TEST_EVENT'; $listener = $this->createListenerSpy(); @@ -33,7 +33,7 @@ public function testDispatchLegacyCall(): void public function testDispatchCurrentCall(): void { $dispatcher = new TestworkEventDispatcher(); - $event = new class extends Event {}; + $event = new class () extends Event {}; $listener = $this->createListenerSpy(); $dispatcher->addListener(get_class($event), $listener); @@ -46,7 +46,7 @@ public function testDispatchCurrentCall(): void public function testSetNameOnEvent(): void { $dispatcher = new TestworkEventDispatcher(); - $event = new class extends Event { + $event = new class () extends Event { public $name; public function setName($name): void { @@ -66,7 +66,7 @@ public function setName($name): void public function testBeforeAllListener(): void { $dispatcher = new TestworkEventDispatcher(); - $event = new class extends Event {}; + $event = new class () extends Event {}; $listener = $this->createListenerSpy(); $dispatcher->addListener(TestworkEventDispatcher::BEFORE_ALL_EVENTS, $listener); @@ -79,7 +79,7 @@ public function testBeforeAllListener(): void public function testAfterAllListener(): void { $dispatcher = new TestworkEventDispatcher(); - $event = new class extends Event {}; + $event = new class () extends Event {}; $listener = $this->createListenerSpy(); $dispatcher->addListener(TestworkEventDispatcher::AFTER_ALL_EVENTS, $listener); @@ -94,7 +94,7 @@ public function testAfterAllListener(): void */ public function createListenerSpy() { - return new class() { + return new class () { public $receivedEvents = []; public function __invoke(Event $event) diff --git a/tests/Fixtures/JunitFormat/features/bootstrap/FeatureContext.php b/tests/Fixtures/JunitFormat/features/bootstrap/FeatureContext.php index bcd26b937..fb8dc599d 100644 --- a/tests/Fixtures/JunitFormat/features/bootstrap/FeatureContext.php +++ b/tests/Fixtures/JunitFormat/features/bootstrap/FeatureContext.php @@ -44,6 +44,6 @@ public function setup() #[When('/^I have a PHP error$/')] public function iHaveAPHPError() { - $foo = new class extends Context {}; + $foo = new class () extends Context {}; } } From 0ff21b586ee3c7853a986642fc9b60a70493999c Mon Sep 17 00:00:00 2001 From: Carlos Granados Date: Fri, 31 Jan 2025 16:11:12 +0100 Subject: [PATCH 565/567] Full PSR-12 configuration --- .php-cs-fixer.dist.php | 90 +----------------------------------------- 1 file changed, 1 insertion(+), 89 deletions(-) diff --git a/.php-cs-fixer.dist.php b/.php-cs-fixer.dist.php index c9738a260..9e71ff70f 100644 --- a/.php-cs-fixer.dist.php +++ b/.php-cs-fixer.dist.php @@ -7,94 +7,6 @@ return (new PhpCsFixer\Config()) ->setParallelConfig(PhpCsFixer\Runner\Parallel\ParallelConfigFactory::detect()) ->setRules([ - '@PSR2' => true, - 'binary_operator_spaces' => [ - 'default' => 'at_least_single_space', - ], - 'blank_line_after_opening_tag' => true, - 'blank_line_between_import_groups' => true, - 'blank_lines_before_namespace' => true, -// 'braces_position' => [ -// 'allow_single_line_empty_anonymous_classes' => true, -// ], - 'class_definition' => [ - 'inline_constructor_arguments' => false, // handled by method_argument_space fixer - 'space_before_parenthesis' => true, // defined in PSR12 ¶8. Anonymous Classes - ], -// 'compact_nullable_type_declaration' => true, - 'declare_equal_normalize' => true, -// 'lowercase_cast' => true, -// 'lowercase_static_reference' => true, - 'new_with_parentheses' => true, - 'no_blank_lines_after_class_opening' => true, - 'no_extra_blank_lines' => [ - 'tokens' => [ - 'use', // defined in PSR12 ¶3. Declare Statements, Namespace, and Import Statements - ], - ], - 'no_leading_import_slash' => true, - 'no_whitespace_in_blank_line' => true, -// 'ordered_class_elements' => [ -// 'order' => [ -// 'use_trait', -// ], -// ], -// 'ordered_imports' => [ -// 'imports_order' => [ -// 'class', -// 'function', -// 'const', -// ], -// 'sort_algorithm' => 'none', -// ], - 'return_type_declaration' => true, -// 'short_scalar_cast' => true, -// 'single_import_per_statement' => ['group_to_single_imports' => false], - 'single_space_around_construct' => [ - 'constructs_followed_by_a_single_space' => [ - 'abstract', - 'as', - 'case', - 'catch', - 'class', - 'const_import', - 'do', - 'else', - 'elseif', - 'final', - 'finally', - 'for', - 'foreach', - 'function', - 'function_import', - 'if', - 'insteadof', - 'interface', - 'namespace', - 'new', - 'private', - 'protected', - 'public', - 'static', - 'switch', - 'trait', - 'try', - 'use', - 'use_lambda', - 'while', - ], - 'constructs_preceded_by_a_single_space' => [ - 'as', - 'else', - 'elseif', - 'use_lambda', - ], - ], -// 'single_trait_insert_per_statement' => true, - 'ternary_operator_spaces' => true, - 'unary_operator_spaces' => [ - 'only_dec_inc' => true, - ], -// 'visibility_required' => true, + '@PSR12' => true, ]) ->setFinder($finder); From 2bf0b81a92cfdf02b2b9753f409a1bd121ea0516 Mon Sep 17 00:00:00 2001 From: Carlos Granados Date: Fri, 14 Feb 2025 09:22:25 +0100 Subject: [PATCH 566/567] Update git blame ignore file --- .git-blame-ignore-revs | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/.git-blame-ignore-revs b/.git-blame-ignore-revs index 47ad016e8..624ed1cbf 100644 --- a/.git-blame-ignore-revs +++ b/.git-blame-ignore-revs @@ -23,3 +23,9 @@ ba740b59cff1f5aa8f5e4eed8577b986b8b6b1d3 ba52edd29e43302f4a4254626fd27af8f92dbf32 # PHP-CS-Fixer - Fix visibility declarations 40e62bde42a457ebee38e08f92784fdb68719fc5 +# PHP-CS-Fixer - PSR12 spacing +90fa446e782f14afe3c7a47b58934eff537f6e94 +# PHP-CS-Fixer - PSR12 blank lines +4ee4d6e9d81598fe48f2e0a6b2755648aa241cb9 +# PHP-CS-Fixer - PSR12 other miscellaneous changes +efb86c8d82cdf25017a1adfdbddf7c286e49c0c8 From 230c0f58cc5412f3fbd068b48336594ec7c38060 Mon Sep 17 00:00:00 2001 From: Carlos Granados Date: Thu, 27 Feb 2025 13:18:51 +0100 Subject: [PATCH 567/567] chore: remove dependency on file location in Gherkin package --- composer.json | 2 +- .../ServiceContainer/GherkinExtension.php | 21 +++---------------- 2 files changed, 4 insertions(+), 19 deletions(-) diff --git a/composer.json b/composer.json index 883014b00..b69b5c26e 100644 --- a/composer.json +++ b/composer.json @@ -16,7 +16,7 @@ "require": { "php": "8.1.* || 8.2.* || 8.3.* || 8.4.* ", "ext-mbstring": "*", - "behat/gherkin": "^4.10.0", + "behat/gherkin": "^4.12.0", "behat/transliterator": "^1.5", "composer-runtime-api": "^2.2", "composer/xdebug-handler": "^3.0", diff --git a/src/Behat/Behat/Gherkin/ServiceContainer/GherkinExtension.php b/src/Behat/Behat/Gherkin/ServiceContainer/GherkinExtension.php index 7625b910b..6ce919b72 100644 --- a/src/Behat/Behat/Gherkin/ServiceContainer/GherkinExtension.php +++ b/src/Behat/Behat/Gherkin/ServiceContainer/GherkinExtension.php @@ -10,6 +10,7 @@ namespace Behat\Behat\Gherkin\ServiceContainer; +use Behat\Gherkin\Keywords\CachedArrayKeywords; use Behat\Testwork\Cli\ServiceContainer\CliExtension; use Behat\Testwork\Filesystem\ServiceContainer\FilesystemExtension; use Behat\Testwork\ServiceContainer\Exception\ExtensionException; @@ -136,8 +137,6 @@ public function process(ContainerBuilder $container) */ private function loadParameters(ContainerBuilder $container) { - $container->setParameter('gherkin.paths.lib', $this->getLibPath()); - $container->setParameter('gherkin.paths.i18n', '%gherkin.paths.lib%/i18n.php'); $container->setParameter( 'suite.generic.default_settings', array( @@ -147,19 +146,6 @@ private function loadParameters(ContainerBuilder $container) ); } - /** - * Returns gherkin library path. - * - * @return string - */ - private function getLibPath() - { - $reflection = new ReflectionClass('Behat\Gherkin\Gherkin'); - $libPath = rtrim(dirname($reflection->getFilename()) . '/../../../', DIRECTORY_SEPARATOR); - - return $libPath; - } - /** * Loads gherkin service. * @@ -178,9 +164,8 @@ private function loadGherkin(ContainerBuilder $container) */ private function loadKeywords(ContainerBuilder $container) { - $definition = new Definition('Behat\Gherkin\Keywords\CachedArrayKeywords', array( - '%gherkin.paths.i18n%' - )); + $definition = new Definition(CachedArrayKeywords::class); + $definition->setFactory([CachedArrayKeywords::class, 'withDefaultKeywords']); $container->setDefinition(self::KEYWORDS_ID, $definition); $definition = new Definition('Behat\Gherkin\Keywords\KeywordsDumper', array(