Skip to content

Commit

Permalink
Updated extension options to be consistent.
Browse files Browse the repository at this point in the history
  • Loading branch information
AlexSkrypnyk committed Jan 19, 2025
1 parent 328aee8 commit ce9c661
Show file tree
Hide file tree
Showing 15 changed files with 231 additions and 217 deletions.
184 changes: 111 additions & 73 deletions README.md

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion behat.yml
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ default:

DrevOps\BehatScreenshotExtension:
dir: '%paths.base%/.logs/screenshots'
fail: true
on_failed: true
purge: true
info_types:
- url
Expand Down
7 changes: 4 additions & 3 deletions behat.yml.dist
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,13 @@ default:
extensions:
DrevOps\BehatScreenshotExtension:
dir: %paths.base%/screenshots
fail: true
on_failed: true
purge: false
info_types:
- url
- feature
- step
- datetime
filenamePattern: '{datetime:u}.{feature_file}.feature_{step_line}.{ext}'
filenamePatternFailed: '{datetime:u}.{fail_prefix}{feature_file}.feature_{step_line}.{ext}'
failed_prefix: failed_
filename_pattern: '{datetime:u}.{feature_file}.feature_{step_line}.{ext}'
filename_pattern_failed: '{datetime:u}.{failed_prefix}{feature_file}.feature_{step_line}.{ext}'
Original file line number Diff line number Diff line change
Expand Up @@ -25,9 +25,9 @@ class ScreenshotContextInitializer implements ContextInitializer {
*
* @param string $dir
* Screenshot dir.
* @param bool $fail
* Create screenshot on test failure.
* @param string $failPrefix
* @param bool $onFailed
* Create screenshot on failed test.
* @param string $failedPrefix
* File name prefix for a failed test.
* @param bool $purge
* Purge dir before start script.
Expand All @@ -42,8 +42,8 @@ class ScreenshotContextInitializer implements ContextInitializer {
*/
public function __construct(
protected string $dir,
protected bool $fail,
private readonly string $failPrefix,
protected bool $onFailed,
private readonly string $failedPrefix,
protected bool $purge,
protected string $filenamePattern,
protected string $filenamePatternFailed,
Expand All @@ -68,8 +68,8 @@ public function initializeContext(Context $context): void {

$context->setScreenshotParameters(
$dir,
$this->fail,
$this->failPrefix,
$this->onFailed,
$this->failedPrefix,
$this->filenamePattern,
$this->filenamePatternFailed,
$this->infoTypes
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,9 @@ interface ScreenshotAwareContextInterface extends Context {
*
* @param string $dir
* Directory to store screenshots.
* @param bool $fail
* @param bool $on_failed
* Create screenshots on fail.
* @param string $fail_prefix
* @param string $failed_prefix
* File name prefix for a failed test.
* @param string $filename_pattern
* File name pattern.
Expand All @@ -29,7 +29,7 @@ interface ScreenshotAwareContextInterface extends Context {
*
* @return $this
*/
public function setScreenshotParameters(string $dir, bool $fail, string $fail_prefix, string $filename_pattern, string $filename_pattern_failed, array $info_types): static;
public function setScreenshotParameters(string $dir, bool $on_failed, string $failed_prefix, string $filename_pattern, string $filename_pattern_failed, array $info_types): static;

/**
* Save screenshot content into a file.
Expand Down
36 changes: 18 additions & 18 deletions src/DrevOps/BehatScreenshotExtension/Context/ScreenshotContext.php
Original file line number Diff line number Diff line change
Expand Up @@ -19,19 +19,19 @@
class ScreenshotContext extends RawMinkContext implements ScreenshotAwareContextInterface {

/**
* Makes screenshot when fail.
* Screenshot directory path.
*/
protected bool $fail = FALSE;
protected string $dir = '';

/**
* Prefix for failed screenshot files.
* Make screenshots on failed tests.
*/
protected string $failPrefix = '';
protected bool $onFailed = FALSE;

/**
* Screenshot directory name.
* Prefix for failed screenshot files.
*/
protected string $dir = '';
protected string $failedPrefix = '';

/**
* Filename pattern.
Expand Down Expand Up @@ -65,10 +65,10 @@ class ScreenshotContext extends RawMinkContext implements ScreenshotAwareContext
/**
* {@inheritdoc}
*/
public function setScreenshotParameters(string $dir, bool $fail, string $fail_prefix, string $filename_pattern, string $filename_pattern_failed, array $info_types): static {
public function setScreenshotParameters(string $dir, bool $on_failed, string $failed_prefix, string $filename_pattern, string $filename_pattern_failed, array $info_types): static {
$this->dir = $dir;
$this->fail = $fail;
$this->failPrefix = $fail_prefix;
$this->onFailed = $on_failed;
$this->failedPrefix = $failed_prefix;
$this->filenamePattern = $filename_pattern;
$this->filenamePatternFailed = $filename_pattern_failed;
$this->infoTypes = $info_types;
Expand Down Expand Up @@ -135,8 +135,8 @@ public function beforeStepInit(BeforeStepScope $scope): void {
* @AfterStep
*/
public function printLastResponseOnError(AfterStepScope $event): void {
if (!$event->getTestResult()->isPassed() && $this->fail) {
$this->iSaveScreenshot(['is_failure' => TRUE]);
if (!$event->getTestResult()->isPassed() && $this->onFailed) {
$this->iSaveScreenshot(['is_failed' => TRUE]);
}
}

Expand All @@ -148,7 +148,7 @@ public function printLastResponseOnError(AfterStepScope $event): void {
*/
public function iSaveScreenshot(array $options = []): void {
$filename = isset($options['filename']) && is_scalar($options['filename']) ? strval($options['filename']) : NULL;
$is_failure = isset($options['is_failure']) && is_scalar($options['is_failure']) && $options['is_failure'];
$is_failed = isset($options['is_failed']) && is_scalar($options['is_failed']) && $options['is_failed'];

$driver = $this->getSession()->getDriver();
$info = $this->renderInfo();
Expand All @@ -163,7 +163,7 @@ public function iSaveScreenshot(array $options = []): void {
return;
}

$filename_html = $this->makeFileName('html', $filename, $is_failure);
$filename_html = $this->makeFileName('html', $filename, $is_failed);
$this->saveScreenshotContent($filename_html, $content);

// Drivers that do not support making screenshots, including Goutte
Expand All @@ -181,7 +181,7 @@ public function iSaveScreenshot(array $options = []): void {
// @codeCoverageIgnoreEnd
// Re-create the filename with a different extension to group content
// and screenshot files together by name.
$filename_png = $this->makeFileName('png', $filename, $is_failure);
$filename_png = $this->makeFileName('png', $filename, $is_failed);
$this->saveScreenshotContent($filename_png, $content);
}

Expand Down Expand Up @@ -315,16 +315,16 @@ protected function getCurrentTime(): int {
* File extension without dot.
* @param string|null $filename
* Optional file name.
* @param bool $is_failure
* @param bool $is_failed
* Make filename for fail case.
*
* @return string
* Unique file name.
*
* @throws \Exception
*/
protected function makeFileName(string $ext, ?string $filename = NULL, bool $is_failure = FALSE): string {
if ($is_failure) {
protected function makeFileName(string $ext, ?string $filename = NULL, bool $is_failed = FALSE): string {
if ($is_failed) {
$filename = $this->filenamePatternFailed;
}
elseif (empty($filename)) {
Expand Down Expand Up @@ -357,7 +357,7 @@ protected function makeFileName(string $ext, ?string $filename = NULL, bool $is_

$data = [
'ext' => $ext,
'fail_prefix' => $this->failPrefix,
'failed_prefix' => $this->failedPrefix,
'feature_file' => $feature->getFile(),
'step_line' => $step->getLine(),
'step_name' => $step->getText(),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ class BehatScreenshotExtension implements ExtensionInterface {
/**
* Extension configuration ID.
*/
const MOD_ID = 'drevops_screenshot';
const MOD_ID = 'drevops_behat_screenshot';

/**
* {@inheritdoc}
Expand Down Expand Up @@ -57,25 +57,25 @@ public function configure(ArrayNodeDefinition $builder): void {
->cannotBeEmpty()
->defaultValue('%paths.base%/screenshots')
->end()
->scalarNode('fail')
->scalarNode('on_failed')
->cannotBeEmpty()
->defaultValue(TRUE)
->end()
->scalarNode('fail_prefix')
->scalarNode('failed_prefix')
->cannotBeEmpty()
->defaultValue('failed_')
->end()
->scalarNode('purge')
->cannotBeEmpty()
->defaultValue(FALSE)
->end()
->scalarNode('filenamePattern')
->scalarNode('filename_pattern')
->cannotBeEmpty()
->defaultValue('{datetime:U}.{feature_file}.feature_{step_line}.{ext}')
->end()
->scalarNode('filenamePatternFailed')
->scalarNode('filename_pattern_failed')
->cannotBeEmpty()
->defaultValue('{datetime:U}.{fail_prefix}{feature_file}.feature_{step_line}.{ext}')
->defaultValue('{datetime:U}.{failed_prefix}{feature_file}.feature_{step_line}.{ext}')
->end()
->arrayNode('info_types')
->defaultValue([])
Expand All @@ -91,15 +91,15 @@ public function configure(ArrayNodeDefinition $builder): void {
public function load(ContainerBuilder $container, array $config): void {
$definition = new Definition(ScreenshotContextInitializer::class, [
$config['dir'],
$config['fail'],
$config['fail_prefix'],
$config['on_failed'],
$config['failed_prefix'],
$config['purge'],
$config['filenamePattern'],
$config['filenamePatternFailed'],
$config['filename_pattern'],
$config['filename_pattern_failed'],
$config['info_types'],
]);
$definition->addTag(ContextExtension::INITIALIZER_TAG, ['priority' => 0]);
$container->setDefinition('drevops_screenshot.screenshot_context_initializer', $definition);
$container->setDefinition(static::MOD_ID . '.screenshot_context_initializer', $definition);
}

}
14 changes: 9 additions & 5 deletions src/DrevOps/BehatScreenshotExtension/Tokenizer.php
Original file line number Diff line number Diff line change
Expand Up @@ -118,10 +118,14 @@ protected static function extractTokens(array $tokens, array $data): array {
* Token replacement.
*/
protected static function buildTokenReplacement(string $token, string $name, ?string $qualifier = NULL, ?string $format = NULL, array $data = []): string {
$method = 'replace' . ucfirst($name) . 'Token';
$method = 'replace' . str_replace('_', '', ucwords($name, '_')) . 'Token';
if (is_callable([self::class, $method])) {
return self::$method($token, $name, $qualifier, $format, $data);
}

$method = 'replace' . str_replace('_', '', ucwords($name . '_' . $qualifier, '_')) . 'Token';
if (is_callable([self::class, $method])) {
$token = self::$method($token, $name, $qualifier, $format, $data);
return self::$method($token, $name, $qualifier, $format, $data);
}

return $token;
Expand Down Expand Up @@ -230,10 +234,10 @@ protected static function replaceUrlToken(string $token, string $name, ?string $
}

/**
* Replace {fail} token.
* Replace {failed_prefix} token.
*/
protected static function replaceFailToken(string $token, string $name, ?string $qualifier = NULL, ?string $format = NULL, array $data = []): string {
return !empty($data['fail_prefix']) && is_string($data['fail_prefix']) ? $data['fail_prefix'] : $token;
protected static function replaceFailedPrefixToken(string $token, string $name, ?string $qualifier = NULL, ?string $format = NULL, array $data = []): string {
return !empty($data['failed_prefix']) && is_string($data['failed_prefix']) ? $data['failed_prefix'] : $token;
}

}
2 changes: 1 addition & 1 deletion tests/behat/bootstrap/BehatCliContext.php
Original file line number Diff line number Diff line change
Expand Up @@ -396,7 +396,7 @@ private function getExpectedOutput(PyStringNode $expectedText) {
* @param string $success "fail" or "pass"
*/
public function itShouldFail($success) {
if ('fail' === $success) {
if ('on_failed' === $success) {
if (0 === $this->getExitCode()) {
echo 'Actual output:' . PHP_EOL . PHP_EOL . $this->getOutput();
}
Expand Down
4 changes: 2 additions & 2 deletions tests/behat/bootstrap/BehatCliTrait.php
Original file line number Diff line number Diff line change
Expand Up @@ -278,7 +278,7 @@ public function behatCliWriteScreenshotFixture(): void {
* @Then it should fail with an error:
*/
public function behatCliAssertFailWithError(PyStringNode $message): void {
$this->itShouldFail('fail');
$this->itShouldFail('on_failed');
Assert::assertStringContainsString(trim((string) $message), $this->getOutput());
// Enforce \Exception for all assertion exceptions. Non-assertion
// exceptions should be thrown as \RuntimeException.
Expand All @@ -290,7 +290,7 @@ public function behatCliAssertFailWithError(PyStringNode $message): void {
* @Then it should fail with an exception:
*/
public function behatCliAssertFailWithException(PyStringNode $message): void {
$this->itShouldFail('fail');
$this->itShouldFail('on_failed');
Assert::assertStringContainsString(trim((string) $message), $this->getOutput());
// Enforce \RuntimeException for all non-assertion exceptions. Assertion
// exceptions should be thrown as \Exception.
Expand Down
2 changes: 1 addition & 1 deletion tests/behat/features/behatcli.feature
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ Feature: Behat CLI context
selenium2: ~
base_url: http://0.0.0.0:8888
"""
And a file named "tests/behat/fixtures/screenshot.html" with:
And a file named "tests/behat/fixtures/screenshot.html" with:
"""
<!DOCTYPE html>
<html>
Expand Down
Loading

0 comments on commit ce9c661

Please sign in to comment.