Skip to content

Instantly share code, notes, and snippets.

@sebastianneubert
Created March 31, 2022 06:55
Show Gist options
  • Save sebastianneubert/b8171ce2ac5ed473c0404fe4f96ada9b to your computer and use it in GitHub Desktop.
Save sebastianneubert/b8171ce2ac5ed473c0404fe4f96ada9b to your computer and use it in GitHub Desktop.
Codeception ForceEnvironment Extension
<?php
namespace Tests\Support\Extension;
use Codeception\Event\SuiteEvent;
use Codeception\Event\TestEvent;
use Codeception\Events;
use Codeception\Exception\ExtensionException;
use Codeception\Extension;
use PHPUnit\Framework\SkippedTestError;
/**
* Codeception ForceEnvironment Extension
*
* This extension allows you to force the environment to be set to a specific value. Only tests which
* has the environment set will be executed. Tests without environment set will be skipped. If you forgot to set
* an environment param to codeception, the test suite will be aborted with a hint to set an environment.
*
* # example config in codeception.yml
*
* extensions:
* enabled:
* - Tests\Support\Extension\ForceEnvironment
* config:
* Tests\Support\Extension\ForceEnvironment:
* environments:
* - local
* - staging
* - production
*/
class ForceEnvironment extends Extension
{
private ?string $currentEnvironment = null;
public static array $events = array(
Events::SUITE_BEFORE => 'beforeSuite',
Events::TEST_BEFORE => 'beforeTest',
);
/**
* @throws ExtensionException in case of missing environment parameter or if the environment is not supported
*/
public function beforeSuite(SuiteEvent $e)
{
$allowedEnvs = $this->config['environments'] ?? [];
if (!isset($e->getSettings()['current_environment'])) {
$message = 'Please set an environment with --env=<ENVIRONMENT>.';
if ([] !== $allowedEnvs) {
$message .= ' Allowed environments are: ' . implode(', ', $allowedEnvs);
}
throw new ExtensionException(self::class, $message);
}
$this->currentEnvironment = $e->getSettings()['current_environment'];
if ([] !== $allowedEnvs) {
if (!in_array($this->currentEnvironment, $this->config['environments'])) {
throw new ExtensionException(
self::class,
sprintf("Environment '%s' is not allowed. Allowed environments: %s",
$this->currentEnvironment,
implode(', ', $allowedEnvs)
)
);
}
}
}
/**
* @throws SkippedTestError in case of a test has not the expected environment
*/
public function beforeTest(TestEvent $e)
{
$testEnvs = $e->getTest()->getMetadata()->getEnv();
if (!in_array($this->currentEnvironment, $testEnvs)) {
throw new SkippedTestError(
sprintf('Test "%s" is skipped because it\'s not explicitly content of environment %s',
$e->getTest()->getMetadata()->getCurrent('name'),
implode(', ', $e->getTest()->getMetadata()->getEnv())
)
);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment