Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Updated extension options to be consistent. #147

Merged
merged 1 commit into from
Jan 19, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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 @@
*
* @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 @@
*/
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 @@

$context->setScreenshotParameters(
$dir,
$this->fail,
$this->failPrefix,
$this->onFailed,
$this->failedPrefix,

Check warning on line 72 in src/DrevOps/BehatScreenshotExtension/Context/Initializer/ScreenshotContextInitializer.php

View check run for this annotation

Codecov / codecov/patch

src/DrevOps/BehatScreenshotExtension/Context/Initializer/ScreenshotContextInitializer.php#L71-L72

Added lines #L71 - L72 were not covered by tests
$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
49 changes: 30 additions & 19 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 @@
/**
* {@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 @@
* @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 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 @@
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 @@
// @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 @@ -279,15 +279,26 @@
protected function compileInfo(): void {
foreach ($this->infoTypes as $type) {
if ($type === 'url') {
$this->appendInfo('Current URL', $this->getSession()->getCurrentUrl());
$current_url = 'not available';
try {
$current_url = $this->getSession()->getCurrentUrl();
}
catch (\Exception) {

Check warning on line 286 in src/DrevOps/BehatScreenshotExtension/Context/ScreenshotContext.php

View check run for this annotation

Codecov / codecov/patch

src/DrevOps/BehatScreenshotExtension/Context/ScreenshotContext.php#L286

Added line #L286 was not covered by tests
// Do nothing.
}

$this->appendInfo('Current URL', $current_url);
}

if ($type === 'feature') {
$this->appendInfo('Feature', (string) $this->getBeforeStepScope()->getFeature()->getTitle());
}

if ($type === 'step') {
$step = $this->getBeforeStepScope()->getStep();
$this->appendInfo('Step', sprintf('%s (line %d)', $step->getText(), $step->getLine()));
}

if ($type === 'datetime') {
$this->appendInfo('Datetime', date('Y-m-d H:i:s'));
}
Expand Down Expand Up @@ -315,16 +326,16 @@
* 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 +368,7 @@

$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/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
4 changes: 2 additions & 2 deletions tests/behat/features/behatcli_trait.feature
Original file line number Diff line number Diff line change
Expand Up @@ -25,12 +25,12 @@ Feature: Behat CLI Trait context
Given scenario steps tagged with "@phpserver":
"""
Given I am on the phpserver test page
And the response status code should be 404
And the response status code should be 400
"""
When I run "behat --no-colors --strict"
Then it should fail with an error:
"""
Current response status code is 200, but 404 expected.
Current response status code is 200, but 400 expected.
"""

Scenario: Test fails with exception
Expand Down
Loading
Loading