### getSetupHook() Example Source: https://github.com/allure-framework/allure-phpunit/blob/main/_autodocs/api-reference/Configuration.md Example demonstrating the usage of a setup hook callable for custom initialization logic. ```php $config = new Config([ 'setupHook' => function (): void { // Initialize custom resources echo "Setting up Allure"; }, ]); $hook = $config->getSetupHook(); if ($hook) { $hook(); // Outputs: "Setting up Allure" ``` -------------------------------- ### Setup Hook Example Source: https://github.com/allure-framework/allure-phpunit/blob/main/_autodocs/ARCHITECTURE.md A closure example for the `setupHook` configuration option, used for initializing resources before the Allure lifecycle starts. ```php 'setupHook' => function (): void { // Initialize resources // Configure logging // Set up test database } ``` -------------------------------- ### Example Usage of Config Source: https://github.com/allure-framework/allure-phpunit/blob/main/_autodocs/api-reference/Configuration.md A comprehensive example demonstrating how to instantiate and use the Config class. ```php use Qameta\Allure\PHPUnit\Internal\Config; use Qameta\Allure\PHPUnit\Setup\ThreadDetectorInterface; $config = new Config([ 'outputDirectory' => 'allure-results', 'linkTemplates' => [ 'tms' => 'https://jira.example.com/browse/%s', ], 'threadDetector' => new class implements ThreadDetectorInterface { public function getThread(): ?string { return null; } public function getHost(): ?string { return gethostname() ?: null; } }, ]); echo $config->getOutputDirectory(); // "allure-results" ``` -------------------------------- ### getOutputDirectory() Example Source: https://github.com/allure-framework/allure-phpunit/blob/main/_autodocs/api-reference/Configuration.md Example demonstrating how to set and retrieve the output directory configuration. ```php $config = new Config([ 'outputDirectory' => 'my-allure-results', ]); echo $config->getOutputDirectory(); // Output: "my-allure-results" ``` -------------------------------- ### getLinkTemplates() Example Source: https://github.com/allure-framework/allure-phpunit/blob/main/_autodocs/api-reference/Configuration.md Example showing how to configure and retrieve link templates for various link types. ```php $config = new Config([ 'linkTemplates' => [ 'tms' => 'https://jira.example.com/browse/%s', 'issue' => new MyIssueTemplate(), ], ]); $templates = $config->getLinkTemplates(); ``` -------------------------------- ### ThreadDetectorInterface getHost() Example Source: https://github.com/allure-framework/allure-phpunit/blob/main/_autodocs/api-reference/Configuration.md Example usage of the getHost() method. ```php $detector = new MyThreadDetector(); echo $detector->getHost(); // "localhost" or actual hostname ``` -------------------------------- ### Integration Example Source: https://github.com/allure-framework/allure-phpunit/blob/main/_autodocs/api-reference/Configuration.md Shows how to load and use the AllureExtension configuration, either from a file or programmatically. ```php use Qameta\Allure\PHPUnit\Internal\Config; use Qameta\Allure\PHPUnit\Setup\ThreadDetectorInterface; // Load from file $data = require 'config/allure.config.php'; $config = new Config($data); // Or create programmatically $config = new Config([ 'outputDirectory' => 'my-results', 'threadDetector' => new class implements ThreadDetectorInterface { public function getThread(): ?string { return $_ENV['TEST_TOKEN'] ?? null; } public function getHost(): ?string { return gethostname() ?: null; } }, ]); // Use in extension $extension = new AllureExtension(); // AllureExtension uses config internally ``` -------------------------------- ### Configuration File Example Source: https://github.com/allure-framework/allure-phpunit/blob/main/_autodocs/api-reference/Configuration.md An example of an Allure PHPUnit configuration file returning an array with optional keys. ```php 'build/allure-results', // Link templates for various link types 'linkTemplates' => [ 'tms' => 'https://jira.example.com/browse/%s', 'issue' => \My\CustomLinkTemplate::class, ], // Custom thread detector for parallel execution 'threadDetector' => \My\ThreadDetector::class, // Setup hook executed before lifecycle starts 'setupHook' => function (): void { // Custom initialization error_log('Allure test suite started'); }, // Lifecycle hooks for test events 'lifecycleHooks' => [ \My\CustomLifecycleHook::class, ], ]; ``` -------------------------------- ### Execute Setup Code Source: https://github.com/allure-framework/allure-phpunit/blob/main/_autodocs/README.md Example of configuring a setup hook to execute custom setup code before tests run. ```php // config/allure.config.php 'setupHook' => function (): void { require_once 'tests/fixtures/bootstrap.php'; TestDatabase::connect(); }, ``` -------------------------------- ### Configuration Array Structure Example Source: https://github.com/allure-framework/allure-phpunit/blob/main/_autodocs/api-reference/Configuration.md An example demonstrating the structure of the configuration array used to instantiate the Config class. ```php $config = new Config([ 'outputDirectory' => 'build/allure-results', 'linkTemplates' => [ 'tms' => 'https://jira.example.com/browse/%s', 'issue' => MyCustomLinkTemplate::class, ], 'setupHook' => function (): void { // Setup code }, 'threadDetector' => MyThreadDetector::class, 'lifecycleHooks' => [ MyLifecycleHook::class, ], ]); ``` -------------------------------- ### Flexible Configuration Values - Direct Instance Source: https://github.com/allure-framework/allure-phpunit/blob/main/_autodocs/api-reference/Configuration.md Example showing how to provide a direct instance for a configuration value. ```php ['linkTemplates' => ['tms' => new MyTemplate()]] ``` -------------------------------- ### getLifecycleHooks() Example Source: https://github.com/allure-framework/allure-phpunit/blob/main/_autodocs/api-reference/Configuration.md Example showing how to configure and retrieve lifecycle hooks for test result monitoring or modification. ```php class MyLifecycleHook implements LifecycleHookInterface { // Implement required interface methods } $config = new Config([ 'lifecycleHooks' => [ new MyLifecycleHook(), ], ]); $hooks = $config->getLifecycleHooks(); ``` -------------------------------- ### ThreadDetectorInterface getThread() Example Source: https://github.com/allure-framework/allure-phpunit/blob/main/_autodocs/api-reference/Configuration.md Example implementation and usage of the getThread() method. ```php // In parallel test execution class MyThreadDetector implements ThreadDetectorInterface { public function getThread(): ?string { return $_ENV['WORKER_ID'] ?? null; } public function getHost(): ?string { return gethostname() ?: null; } } // Usage $detector = new MyThreadDetector(); echo $detector->getThread(); // "worker-1" ``` -------------------------------- ### Flexible Configuration Values - Callable Factory Source: https://github.com/allure-framework/allure-phpunit/blob/main/_autodocs/api-reference/Configuration.md Example showing how to provide a callable factory for a configuration value. ```php ['linkTemplates' => ['tms' => fn () => new MyTemplate()]] // Config calls the function and uses the result ``` -------------------------------- ### Error Handling Example Source: https://github.com/allure-framework/allure-phpunit/blob/main/_autodocs/api-reference/Configuration.md Demonstrates how config validation throws RuntimeException for invalid types. ```php try { $config = new Config([ 'outputDirectory' => 123, // Invalid type ]); $config->getOutputDirectory(); } catch (RuntimeException $e) { echo $e->getMessage(); // Output: Config key "outputDirectory" should contain a string } ``` -------------------------------- ### registerRun() Example Source: https://github.com/allure-framework/allure-phpunit/blob/main/_autodocs/api-reference/AllureAdapter.md Example usage of the registerRun() method. ```php $adapter = AllureAdapter::getInstance(); $runInfo = $adapter->registerRun($testResult, $testInfo); echo "Test Case ID: " . $runInfo->getTestCaseId(); echo "History ID: " . $runInfo->getHistoryId(); echo "Run Index: " . $runInfo->getRunIndex(); ``` -------------------------------- ### Configuration File Example Source: https://github.com/allure-framework/allure-phpunit/blob/main/_autodocs/api-reference/AllureExtension.md Example of an Allure PHP Unit Extension configuration file, showing optional keys for output directory, link templates, thread detector, setup hook, and lifecycle hooks. ```php 'build/allure-results', // Link templates for test links (tms, issue, etc) 'linkTemplates' => [ 'tms' => 'https://example.com/tasks/%s', 'issue' => MyCustomLinkTemplate::class, ], // Custom thread detector for parallel test execution 'threadDetector' => MyThreadDetector::class, // Setup hook called before lifecycle starts 'setupHook' => function (): void { // Custom initialization }, // Lifecycle hooks for test events 'lifecycleHooks' => [ MyLifecycleHook::class, ], ]; ``` -------------------------------- ### Complete Configuration Example Source: https://github.com/allure-framework/allure-phpunit/blob/main/_autodocs/configuration.md A comprehensive example of the Allure PHPUnit configuration array. ```php 'build/allure-results', // Link templates for TMS and issue tracking 'linkTemplates' => [ 'tms' => 'https://jira.example.com/browse/%s', 'issue' => 'https://github.com/example/project/issues/%s', 'requirement' => 'https://requirements.example.com/req/%s', ], // Custom thread detector for parallel execution (Paratest) 'threadDetector' => new class implements ThreadDetectorInterface { public function getThread(): ?string { // Paratest sets TEST_TOKEN environment variable return $_ENV['TEST_TOKEN'] ?? null; } public function getHost(): ?string { return gethostname() ?: null; } }, // Setup hook executed before tests start 'setupHook' => function (): void { // Initialize test environment define('TESTING', true); // Set up test database $pdo = new \PDO('sqlite::memory:'); $pdo->exec(file_get_contents('tests/fixtures/schema.sql')); $GLOBALS['test_db'] = $pdo; // Configure logging \Log::setLevel(\Log::DEBUG); \Log::setOutput('build/test.log'); }, // Lifecycle hooks for test monitoring 'lifecycleHooks' => [ // Hook to capture logs on failure \App\Hooks\LogCapturingHook::class, // Hook to take screenshots on failure \App\Hooks\ScreenshotHook::class, ], ]; ``` -------------------------------- ### Production Configuration Example Source: https://github.com/allure-framework/allure-phpunit/blob/main/_autodocs/configuration.md An example of a production-ready Allure configuration file. ```php '/var/log/allure-results', // Link to production Jira and GitHub 'linkTemplates' => [ 'tms' => 'https://jira.mycompany.com/browse/%s', 'issue' => 'https://github.com/mycompany/myrepo/issues/%s', ], // Multi-host parallel execution 'threadDetector' => \App\ProductionThreadDetector::class, // Production hooks 'lifecycleHooks' => [ \App\Hooks\MetricsReportingHook::class, \App\Hooks\SlackNotificationHook::class, ], ]; ``` -------------------------------- ### Flexible Configuration Values - Nested Callables Source: https://github.com/allure-framework/allure-phpunit/blob/main/_autodocs/api-reference/Configuration.md Example demonstrating support for nested callables in configuration values. ```php // Callable returning callable is supported recursively ['setupHook' => fn () => fn () => doSomething()] ``` -------------------------------- ### getThreadDetector() Example Source: https://github.com/allure-framework/allure-phpunit/blob/main/_autodocs/api-reference/Configuration.md Example illustrating how to provide a custom ThreadDetectorInterface implementation for parallel test execution. ```php class MyThreadDetector implements ThreadDetectorInterface { public function getThread(): ?string { return "worker-1"; } public function getHost(): ?string { return "localhost"; } } $config = new Config([ 'threadDetector' => new MyThreadDetector(), ]); $detector = $config->getThreadDetector(); ``` -------------------------------- ### outputDirectory Examples Source: https://github.com/allure-framework/allure-phpunit/blob/main/_autodocs/configuration.md Various examples demonstrating how to set the 'outputDirectory' configuration option, including relative, absolute, platform-independent, and null values. ```php // Relative path 'outputDirectory' => 'build/allure-results', // Absolute path 'outputDirectory' => '/var/allure-results', // Platform-independent separator (on Windows, DIRECTORY_SEPARATOR becomes \) 'outputDirectory' => 'results' . DIRECTORY_SEPARATOR . 'allure', // Null uses default 'outputDirectory' => null, ``` -------------------------------- ### Flexible Configuration Values - Class Name String Source: https://github.com/allure-framework/allure-phpunit/blob/main/_autodocs/api-reference/Configuration.md Example showing how to provide a class name string for a configuration value, which will be instantiated by Config. ```php ['linkTemplates' => ['tms' => MyTemplate::class]] // Config instantiates: new MyTemplate() ``` -------------------------------- ### getHost() Implementation Source: https://github.com/allure-framework/allure-phpunit/blob/main/_autodocs/api-reference/Configuration.md Demonstrates how getHost() retrieves the system's hostname. ```php public function getHost(): ?string ``` ```php $detector = new DefaultThreadDetector(); echo $detector->getHost(); // "my-machine.local" ``` -------------------------------- ### Example Usage of TestStartInfo Source: https://github.com/allure-framework/allure-phpunit/blob/main/_autodocs/types.md Example demonstrating the creation and usage of TestStartInfo. ```php $startInfo = new TestStartInfo( containerId: 'cont-a1b2c3d4-e5f6-4a5b-8c9d-e0f1a2b3c4d5', testId: 'test-a1b2c3d4-e5f6-4a5b-8c9d-e0f1a2b3c4d5', ); echo $startInfo->getContainerId(); // "cont-a1b2c3d4-e5f6-4a5b-8c9d-e0f1a2b3c4d5" echo $startInfo->getTestId(); // "test-a1b2c3d4-e5f6-4a5b-8c9d-e0f1a2b3c4d5" ``` -------------------------------- ### setupHook - Callable Factory Source: https://github.com/allure-framework/allure-phpunit/blob/main/_autodocs/configuration.md Example of using a callable factory for the setupHook. ```php 'setupHook' => function (): callable { return function (): void { // Setup code }; }, ``` -------------------------------- ### Custom Metrics Hook Implementation Source: https://github.com/allure-framework/allure-phpunit/blob/main/_autodocs/configuration.md An example of a custom lifecycle hook to record test start time. ```php class CustomMetricsHook implements LifecycleHookInterface { public function onBeforeTestStart(TestResult $result): void { // Record test start time $result->setStartTime(microtime(true)); } } return [ 'lifecycleHooks' => [ CustomMetricsHook::class, ], ]; ``` -------------------------------- ### Configuration File Example Source: https://github.com/allure-framework/allure-phpunit/blob/main/_autodocs/README.md Example of the Allure PHPUnit configuration file. ```php 'build/allure-results', 'linkTemplates' => [ 'tms' => 'https://jira.example.com/browse/%s', ], ]; ``` -------------------------------- ### setupHook - Direct Callable Source: https://github.com/allure-framework/allure-phpunit/blob/main/_autodocs/configuration.md Example of using a direct callable (closure) for the setupHook. ```php 'setupHook' => function (): void { // Custom setup code error_log('Allure setup started'); define('TEST_MODE', true); }, ``` -------------------------------- ### setupHook - Static Method as String Source: https://github.com/allure-framework/allure-phpunit/blob/main/_autodocs/configuration.md Example of using a static method as a string for the setupHook. ```php 'setupHook' => 'MySetupClass::setup', ``` -------------------------------- ### Allure Configuration File Example Source: https://github.com/allure-framework/allure-phpunit/blob/main/README.md Example of an Allure configuration file (config/allure.config.php) to customize output directory, link templates, and hooks. ```php 'build/allure-results', 'linkTemplates' => [ // Class or object must implement \Qameta\Allure\Setup\LinkTemplateInterface 'tms' => \My\LinkTemplate::class, ], 'setupHook' => function (): void { // Some actions performed before starting the lifecycle }, // Class or object must implement \Qameta\Allure\PHPUnit\Setup\ThreadDetectorInterface 'threadDetector' => \My\ThreadDetector::class, 'lifecycleHooks' => [ // Class or object must implement one of \Qameta\Allure\Hook\LifecycleHookInterface descendants. \My\LifecycleHook::class, ], ]; ``` -------------------------------- ### linkTemplates - Direct Object Instance Example Source: https://github.com/allure-framework/allure-phpunit/blob/main/_autodocs/configuration.md Example of configuring 'linkTemplates' by providing direct instances of LinkTemplateInterface implementations. ```php 'linkTemplates' => [ 'tms' => new JiraLinkTemplate('https://jira.example.com'), 'issue' => new GitHubLinkTemplate('myorg/myrepo'), ], ``` -------------------------------- ### getTestId() Example Source: https://github.com/allure-framework/allure-phpunit/blob/main/_autodocs/api-reference/AllureAdapter.md Example usage of the getTestId() method. ```php $adapter = AllureAdapter::getInstance(); $testId = $adapter->getTestId($testInfo); ``` -------------------------------- ### linkTemplates - Factory Function Example Source: https://github.com/allure-framework/allure-phpunit/blob/main/_autodocs/configuration.md Example of configuring 'linkTemplates' using factory functions that return LinkTemplateInterface instances. ```php 'linkTemplates' => [ 'tms' => function (): LinkTemplateInterface { return new JiraLinkTemplate(getenv('JIRA_URL')); }, ], ``` -------------------------------- ### Enable Detailed Logging in Setup Hook Source: https://github.com/allure-framework/allure-phpunit/blob/main/_autodocs/ARCHITECTURE.md PHP code snippet to enable detailed error reporting and logging within the setup hook. ```php 'setupHook' => function (): void { error_reporting(E_ALL); ini_set('display_errors', '1'); set_error_handler(function ($errno, $errstr) { error_log("[$errno] $errstr"); }); } ``` -------------------------------- ### setupHook - Invokable Class Source: https://github.com/allure-framework/allure-phpunit/blob/main/_autodocs/configuration.md Example of using an invokable class instance for the setupHook. ```php 'setupHook' => new class { public function __invoke(): void { // Setup code } }, ``` -------------------------------- ### Example Usage of TestInfo and TestRunInfo Source: https://github.com/allure-framework/allure-phpunit/blob/main/_autodocs/types.md Example demonstrating the creation and usage of TestInfo and TestRunInfo objects. ```php $testInfo = new TestInfo( test: 'Tests\UserTest::testCreation', class: 'Tests\UserTest', method: 'testCreation', dataLabel: 'Data set 1', host: 'localhost', thread: '1', ); $runInfo = new TestRunInfo( testInfo: $testInfo, uuid: 'a1b2c3d4-e5f6-4a5b-8c9d-e0f1a2b3c4d5', rerunOf: null, // First run runIndex: 0, testCaseId: 'abc123def456', historyId: 'xyz789uvw012', ); echo $runInfo->getRunIndex(); // 0 echo $runInfo->getTestCaseId(); // "abc123def456" ``` -------------------------------- ### Lifecycle Hooks Example Source: https://github.com/allure-framework/allure-phpunit/blob/main/_autodocs/configuration.md Demonstrates how to define lifecycle hooks in the configuration. ```php 'lifecycleHooks' => [ \My\HookOne::class, new MyHookTwo(), function (): LifecycleHookInterface { return new MyHookThree(); }, ], ``` -------------------------------- ### linkTemplates - Class Name String Example Source: https://github.com/allure-framework/allure-phpunit/blob/main/_autodocs/configuration.md Example of configuring 'linkTemplates' using class names that implement the LinkTemplateInterface. ```php 'linkTemplates' => [ 'tms' => \My\JiraLinkTemplate::class, 'issue' => \My\GitHubIssueLinkTemplate::class, ], ``` -------------------------------- ### Install Allure PHPUnit Source: https://github.com/allure-framework/allure-phpunit/blob/main/_autodocs/README.md Command to install the Allure PHPUnit package using Composer. ```bash composer require --dev allure-framework/allure-phpunit:^3 ``` -------------------------------- ### Display Name Annotation Example Source: https://github.com/allure-framework/allure-phpunit/blob/main/README.md Example demonstrating the use of the #[DisplayName] annotation to provide human-readable titles for test classes and methods. ```php namespace Example\Tests; use PHPUnit\Framework\TestCase; use Qameta\Allure\Attribute\DisplayName; #[DisplayName("Human-readable test class title")] class SomeTest extends TestCase { #[DisplayName("Human-readable test method title")] public function testCaseMethod(): void { //Some implementation here... } } ``` -------------------------------- ### Error Messages Example Source: https://github.com/allure-framework/allure-phpunit/blob/main/_autodocs/configuration.md Examples of error messages generated during configuration validation. ```text RuntimeException: Config key "outputDirectory" should contain a string RuntimeException: Config key "linkTemplates/tms" contains invalid source of LinkTemplateInterface RuntimeException: Config key "threadDetector" contains invalid source of ThreadDetectorInterface RuntimeException: Config key "lifecycleHooks" should contain an array with integer keys only ``` -------------------------------- ### TestInfo Example Usage Source: https://github.com/allure-framework/allure-phpunit/blob/main/_autodocs/types.md Example demonstrating how to instantiate and use the TestInfo class. ```php $info = new TestInfo( test: 'MyApp\Tests\UserTest::testCreation', class: 'MyApp\Tests\UserTest', method: 'testCreation', dataLabel: null, host: 'localhost', thread: '1', ); echo $info->getTest(); // "MyApp\Tests\UserTest::testCreation" echo $info->getFullName(); // "MyApp\Tests\UserTest::testCreation" echo implode('/', $info->getTitlePath()); // "MyApp/Tests/UserTest" ``` -------------------------------- ### getHost() Method Signature Source: https://github.com/allure-framework/allure-phpunit/blob/main/_autodocs/api-reference/Configuration.md The method signature for the getHost() method of ThreadDetectorInterface. ```php public function getHost(): ?string ``` -------------------------------- ### Multiple Lifecycle Hooks Example Source: https://github.com/allure-framework/allure-phpunit/blob/main/_autodocs/configuration.md Shows how to configure multiple lifecycle hooks for different purposes. ```php return [ 'lifecycleHooks' => [ \My\DatabaseHook::class, // Sets up test database \My\LoggingHook::class, // Captures logs \My\ScreenshotHook::class, // Takes screenshots on failure \My\MetricsHook::class, // Records metrics ], ]; ``` -------------------------------- ### linkTemplates - URL String Template Example Source: https://github.com/allure-framework/allure-phpunit/blob/main/_autodocs/configuration.md Example of configuring 'linkTemplates' using URL string templates for 'tms' and 'issue' link types. ```php 'linkTemplates' => [ 'tms' => 'https://jira.example.com/browse/%s', 'issue' => 'https://github.com/myorg/myrepo/issues/%s', ], ``` -------------------------------- ### setInstance() Example Source: https://github.com/allure-framework/allure-phpunit/blob/main/_autodocs/api-reference/AllureAdapter.md Sets a custom AllureAdapter instance, useful for testing and dependency injection. ```php $mockAdapter = new MyMockAllureAdapter(); AllureAdapter::setInstance($mockAdapter); ``` -------------------------------- ### Config Constructor Source: https://github.com/allure-framework/allure-phpunit/blob/main/_autodocs/api-reference/Configuration.md The constructor for the Config class takes an array of configuration data. ```php public function __construct(array $data) ``` -------------------------------- ### reset() Example Source: https://github.com/allure-framework/allure-phpunit/blob/main/_autodocs/api-reference/AllureAdapter.md Used primarily in testing scenarios to clear the singleton state between tests. ```php AllureAdapter::reset(); $freshInstance = AllureAdapter::getInstance(); // Creates new instance ``` -------------------------------- ### Example of registering AllureExtension in phpunit.xml Source: https://github.com/allure-framework/allure-phpunit/blob/main/_autodocs/api-reference/AllureExtension.md This example shows how to register the AllureExtension as a PHPUnit extension in the phpunit.xml configuration file, including passing a custom configuration file path as a parameter. ```xml ``` -------------------------------- ### ConfigInterface Definition Source: https://github.com/allure-framework/allure-phpunit/blob/main/_autodocs/api-reference/Configuration.md Defines all configuration options for Allure PHPUnit integration. ```php interface ConfigInterface { public function getOutputDirectory(): ?string; public function getLinkTemplates(): array; public function getSetupHook(): ?callable; public function getThreadDetector(): ?ThreadDetectorInterface; public function getLifecycleHooks(): array; } ``` -------------------------------- ### getThread() Implementation Source: https://github.com/allure-framework/allure-phpunit/blob/main/_autodocs/api-reference/Configuration.md Demonstrates how getThread() retrieves the TEST_TOKEN environment variable. ```php public function getThread(): ?string ``` ```php // When running with Paratest $_ENV['TEST_TOKEN'] = 'worker-2'; $detector = new DefaultThreadDetector(); echo $detector->getThread(); // "worker-2" ``` -------------------------------- ### Configuration Key Type Mismatches Source: https://github.com/allure-framework/allure-phpunit/blob/main/_autodocs/errors.md Examples demonstrating various configuration key type mismatches and the resulting RuntimeExceptions. ```php // outputDirectory must be string $config = new Config([ 'outputDirectory' => 123, // Integer provided ]); $config->getOutputDirectory(); // RuntimeException: Config key "outputDirectory" should contain a string ``` ```php // setupHook must be callable $config = new Config([ 'setupHook' => 'not a callable', ]); $config->getSetupHook(); // RuntimeException: Config key "setupHook" should contain a callable ``` ```php // linkTemplates must be array $config = new Config([ 'linkTemplates' => 'not an array', ]); $config->getLinkTemplates(); // RuntimeException: Config key "linkTemplates" should contain an array ``` ```php // lifecycleHooks must have integer keys only $config = new Config([ 'lifecycleHooks' => [ 'named_key' => \My\Hook::class, // String key instead of int ], ]); $config->getLifecycleHooks(); // RuntimeException: Config key "lifecycleHooks" should contain an array with integer keys only ``` -------------------------------- ### Environment-Based Configuration Loading Source: https://github.com/allure-framework/allure-phpunit/blob/main/_autodocs/configuration.md Example of loading configuration based on the current environment (e.g., testing, CI). ```php 'build/allure-results', ]; $envConfigs = [ 'testing' => [ 'linkTemplates' => [ 'tms' => 'https://test-jira.example.com/browse/%s', ], ], 'ci' => [ 'outputDirectory' => '/tmp/allure-results', 'linkTemplates' => [ 'tms' => 'https://jira.example.com/browse/%s', ], ], ]; return array_merge($baseConfig, $envConfigs[$env] ?? []); ``` -------------------------------- ### setupHook - Typical Usage Source: https://github.com/allure-framework/allure-phpunit/blob/main/_autodocs/configuration.md A typical usage example for setupHook, demonstrating initialization of test fixtures, database connection, and logging configuration. ```php return [ 'setupHook' => function (): void { // Initialize test fixtures require_once 'tests/fixtures/bootstrap.php'; // Set up test database TestDatabase::connect(); // Configure logging Logger::setLevel(Logger::DEBUG); }, ]; ``` -------------------------------- ### Catching Configuration Errors Source: https://github.com/allure-framework/allure-phpunit/blob/main/_autodocs/errors.md Example of how to catch RuntimeExceptions that may occur during Allure configuration loading. ```php use Qameta\Allure\PHPUnit\AllureExtension; try { // Configuration is loaded during bootstrap // Errors thrown here if config is invalid } catch (RuntimeException $e) { // Handle configuration error error_log("Allure configuration error: " . $e->getMessage()); // Fail gracefully or exit } ``` -------------------------------- ### Config Class Implementation Source: https://github.com/allure-framework/allure-phpunit/blob/main/_autodocs/api-reference/Configuration.md The Config class implements ConfigInterface and loads configuration from an array. ```php final class Config implements ConfigInterface { public function __construct(private readonly array $data) } ``` -------------------------------- ### Example Legacy Syntax Source: https://github.com/allure-framework/allure-phpunit/blob/main/_autodocs/api-reference/TestAttributes.md Illustrates the use of legacy Doctrine annotations for Allure features. ```php use Yandex\Allure\Adapter\Annotation\DisplayName; use Yandex\ Allure\Adapter\Annotation\Description; use Yandex\\Allure\Adapter\Annotation\Severity; /** * @DisplayName("Test description") * @Description("Detailed test description", type = DescriptionType::MARKDOWN) * @Severity(level = SeverityLevel::CRITICAL) */ public function testLegacyAnnotation(): void { // Test code } ``` -------------------------------- ### Configure Output Directory Source: https://github.com/allure-framework/allure-phpunit/blob/main/_autodocs/README.md Example of configuring the output directory for Allure results. ```php // config/allure.config.php return [ 'outputDirectory' => 'build/allure-results', ]; ``` -------------------------------- ### registerStart() Example Source: https://github.com/allure-framework/allure-phpunit/blob/main/_autodocs/api-reference/AllureAdapter.md Called during test preparation to register the test and container IDs. Stores a TestStartInfo object internally indexed by test identifier, which later allows retrieval of container and test IDs. ```php use Qameta\Allure\PHPUnit\AllureAdapter; $adapter = AllureAdapter::getInstance(); $testId = $adapter->registerStart($containerResult, $testResult, $testInfo); ``` -------------------------------- ### threadDetector - Direct Object Instance Source: https://github.com/allure-framework/allure-phpunit/blob/main/_autodocs/configuration.md Example of providing a direct object instance for threadDetector, implementing the ThreadDetectorInterface. ```php 'threadDetector' => new class implements ThreadDetectorInterface { public function getThread(): ?string { return $_ENV['TEST_TOKEN'] ?? null; } public function getHost(): ?string { return gethostname() ?: null; } }, ``` -------------------------------- ### Custom Link Template Implementation Source: https://github.com/allure-framework/allure-phpunit/blob/main/_autodocs/ARCHITECTURE.md Example of implementing the `LinkTemplateInterface` for creating custom link formats. ```php class CustomLinkTemplate implements LinkTemplateInterface { public function create(string $value): Link { // Format link based on value } } ``` -------------------------------- ### TestPreparationStartedSubscriber Source: https://github.com/allure-framework/allure-phpunit/blob/main/_autodocs/api-reference/EventSubscribers.md Handles the test preparation start event - called before test setup methods. ```php final class TestPreparationStartedSubscriber implements PreparationStartedSubscriber { public function __construct(private readonly TestLifecycleInterface $testLifecycle) public function notify(PreparationStarted $event): void } ``` -------------------------------- ### Custom ThreadDetector Implementation Source: https://github.com/allure-framework/allure-phpunit/blob/main/_autodocs/ARCHITECTURE.md Example of implementing the `ThreadDetectorInterface` for custom thread detection logic. ```php class CustomThreadDetector implements ThreadDetectorInterface { public function getThread(): ?string { // Read from environment, config, etc. } public function getHost(): ?string { // Return host/machine identifier } } ``` -------------------------------- ### Example of Annotations Not Loaded Exception Source: https://github.com/allure-framework/allure-phpunit/blob/main/_autodocs/errors.md Demonstrates how the 'LogicException: Annotations not loaded' can occur and be caught, showing the previous ReflectionException. ```php // Test class that cannot be reflected class BrokenTest { // Has syntax error or other reflection issue } // When TestUpdater tries to parse annotations try { $testInfo = new TestInfo( test: 'BrokenTest::testMethod', class: 'BrokenTest', method: 'testMethod', dataLabel: null, host: null, thread: null, ); $testUpdater->setInfo($testResult, $testInfo); } catch (LogicException $e) { echo $e->getMessage(); // LogicException: Annotations not loaded echo $e->getPrevious()?->getMessage(); // Shows the underlying ReflectionException } ``` -------------------------------- ### AllureExtension setupAllure() Method Source: https://github.com/allure-framework/allure-phpunit/blob/main/_autodocs/api-reference/AllureExtension.md Initializes Allure framework components with loaded configuration. ```php private function setupAllure(ConfigInterface $config): void ``` -------------------------------- ### Using .env for Configuration Source: https://github.com/allure-framework/allure-phpunit/blob/main/_autodocs/configuration.md Demonstrates how to load configuration values from a .env file. ```php $env['ALLURE_OUTPUT_DIR'] ?? 'build/allure-results', 'linkTemplates' => [ 'tms' => $env['JIRA_URL'] . '/browse/%s', 'issue' => $env['GITHUB_URL'] . '/issues/%s', ], 'threadDetector' => new class implements ThreadDetectorInterface { public function getThread(): ?string { return getenv('TEST_TOKEN'); } public function getHost(): ?string { return getenv('TEST_HOST'); } }, ]; ``` -------------------------------- ### getContainerId() Example Source: https://github.com/allure-framework/allure-phpunit/blob/main/_autodocs/api-reference/AllureAdapter.md Example usage of the getContainerId() method. ```php $adapter = AllureAdapter::getInstance(); $containerId = $adapter->getContainerId($testInfo); ``` -------------------------------- ### setupHook - Common Pattern: Static Method Source: https://github.com/allure-framework/allure-phpunit/blob/main/_autodocs/configuration.md Common pattern for setupHook using a static method. ```php class AllureSetup { public static function configure(): void { // Setup code } } return [ 'setupHook' => [AllureSetup::class, 'configure'], ]; ``` -------------------------------- ### getInstance() Example Source: https://github.com/allure-framework/allure-phpunit/blob/main/_autodocs/api-reference/AllureAdapter.md Returns the singleton instance, creating it if it doesn't exist. The instance is stored in the private static property $instance. ```php use Qameta\Allure\PHPUnit\AllureAdapter; $adapter = AllureAdapter::getInstance(); ``` -------------------------------- ### setupHook - Common Pattern: Closure with Environment Variables Source: https://github.com/allure-framework/allure-phpunit/blob/main/_autodocs/configuration.md Common pattern for setupHook using a closure that reads environment variables. ```php return [ 'setupHook' => function (): void { $env = getenv('APP_ENV') ?: 'test'; require_once "config/{$env}.php"; }, ]; ``` -------------------------------- ### Container not registered example Source: https://github.com/allure-framework/allure-phpunit/blob/main/_autodocs/errors.md Example illustrating a LogicException when getContainerId() is called for a test that has not been registered via registerStart(). ```php $testInfo = new TestInfo( test: 'Tests\\MyTest::testMethod', class: 'Tests\\MyTest', method: 'testMethod', dataLabel: null, host: null, thread: null, ); $adapter = AllureAdapter::getInstance(); // Container ID not registered yet try { $containerId = $adapter->getContainerId($testInfo); } catch (LogicException $e) { echo $e->getMessage(); // LogicException: Container not registered: Tests\\MyTest::testMethod } // First register the test $adapter->registerStart($containerResult, $testResult, $testInfo); // Now it works $containerId = $adapter->getContainerId($testInfo); // Returns UUID ``` -------------------------------- ### Parameter Attribute Example Source: https://github.com/allure-framework/allure-phpunit/blob/main/_autodocs/api-reference/TestAttributes.md An example showing how to document test inputs and values using the Parameter attribute. ```php #[Parameter("username", "john_doe")] #[Parameter("email", "john@example.com")] public function testUserRegistration(): void { $user = User::register('john_doe', 'john@example.com'); $this->assertNotNull($user->id); } ``` -------------------------------- ### Running Unit Tests Source: https://github.com/allure-framework/allure-phpunit/blob/main/_autodocs/ARCHITECTURE.md Command to execute the unit tests for the Allure adapter. ```bash # Unit tests vendor/bin/phpunit ``` -------------------------------- ### Test not registered example Source: https://github.com/allure-framework/allure-phpunit/blob/main/_autodocs/errors.md Example showing how a LogicException occurs when getTestId() is called for a test that has not been registered via registerStart(). ```php $testInfo = new TestInfo( test: 'Tests\\MyTest::testMethod', class: 'Tests\\MyTest', method: 'testMethod', dataLabel: null, host: null, thread: null, ); $adapter = AllureAdapter::getInstance(); // Test ID not registered yet try { $testId = $adapter->getTestId($testInfo); } catch (LogicException $e) { echo $e->getMessage(); // LogicException: Test not registered: Tests\\MyTest::testMethod } // First register the test $adapter->registerStart($containerResult, $testResult, $testInfo); // Now it works $testId = $adapter->getTestId($testInfo); // Returns UUID ``` -------------------------------- ### Status Determination Example Source: https://github.com/allure-framework/allure-phpunit/blob/main/_autodocs/api-reference/ExceptionDetailsTrait.md An example from TestFailedSubscriber showing how the status detector uses the stored exception to determine the test status. ```php // TestFailedSubscriber example public function notify(Failed $event): void { $lastException = $adapter->getLastException(); $status = $statusDetector->getStatus($lastException); // status could be: // - Status::failed() for assertions // - Status::broken() for unexpected errors // - etc } ``` -------------------------------- ### Link Attribute Example Source: https://github.com/allure-framework/allure-phpunit/blob/main/_autodocs/api-reference/TestAttributes.md An example showcasing the use of Link attributes with specific types like 'tms' and 'issue'. ```php #[Link(type: "tms", name: "PROJ-123")] #[Link(type: "issue", name: "BUG-456")] public function testCreateUser(): void { // Test } ``` -------------------------------- ### setupHook - Common Pattern: Invokable Class Source: https://github.com/allure-framework/allure-phpunit/blob/main/_autodocs/configuration.md Common pattern for setupHook using an invokable class. ```php class AllureBootstrapper { public function __invoke(): void { // Setup code } } return [ 'setupHook' => AllureBootstrapper::class, ]; ``` -------------------------------- ### Custom Exception Handling with Capture Example Source: https://github.com/allure-framework/allure-phpunit/blob/main/_autodocs/api-reference/ExceptionDetailsTrait.md An example showing how to explicitly capture an exception using onNotSuccessfulTest() within a custom try-catch block. ```php use PHPUnit\Framework\TestCase; use Qameta\Allure\PHPUnit\ExceptionDetailsTrait; use Throwable; class ErrorHandlingTest extends TestCase { use ExceptionDetailsTrait; public function testErrorRecovery(): void { try { $this->risky_operation(); } catch (Throwable $e) { // Ensure exception is captured for Allure $this->onNotSuccessfulTest($e); // This will re-throw, failing the test } } private function risky_operation(): void { throw new RuntimeException("Operation failed"); } } ``` -------------------------------- ### Check Configuration Loaded Source: https://github.com/allure-framework/allure-phpunit/blob/main/_autodocs/ARCHITECTURE.md PHP command to output and check the loaded configuration. ```php php -r "var_dump(require 'config/allure.config.php');" ``` -------------------------------- ### Transparent Exception Capture Example Source: https://github.com/allure-framework/allure-phpunit/blob/main/_autodocs/api-reference/ExceptionDetailsTrait.md An example demonstrating how exceptions are automatically captured by the trait during test execution without explicit try-catch blocks. ```php use PHPUnit\Framework\TestCase; use Qameta\Allure\PHPUnit\ExceptionDetailsTrait; class UserApiTest extends TestCase { use ExceptionDetailsTrait; public function testUserCreation(): void { // Exception is automatically captured if thrown $user = User::create(['name' => 'John']); $this->assertNotNull($user->id); } } ``` -------------------------------- ### Initialization Flow Source: https://github.com/allure-framework/allure-phpunit/blob/main/_autodocs/ARCHITECTURE.md This diagram details the initialization process of the Allure PHPUnit adapter, starting from the PHPUnit bootstrap and leading to event subscriber registration. ```text PHPUnit Bootstrap ↓ AllureExtension::bootstrap() ├─→ LoadConfigData() ├─→ Create Config instance ├─→ SetupAllure() │ ├─→ ConfigureOutputDirectory │ ├─→ AddLinkTemplates │ └─→ ExecuteSetupHook │ └─→ RegisterEventSubscribers ├─→ TestPreparationStartedSubscriber ├─→ TestPreparedSubscriber ├─→ TestFinishedSubscriber ├─→ TestPassedSubscriber ├─→ TestFailedSubscriber ├─→ TestErroredSubscriber ├─→ TestSkippedSubscriber ├─→ TestMarkedIncompleteSubscriber ├─→ TestWarningTriggeredSubscriber └─→ TestConsideredRiskySubscriber ``` -------------------------------- ### Example 1: Complete Test Class Source: https://github.com/allure-framework/allure-phpunit/blob/main/_autodocs/api-reference/TestAttributes.md A comprehensive example of using various Allure attributes on a test class and its methods for detailed reporting. ```php use PHPUnit\Framework\TestCase; use Qameta\Allure\Attribute\{ DisplayName, Description, Severity, Feature, Story, Parameter, }; use Qameta\Allure\Allure; #[ DisplayName("User Management Tests"), Description("Comprehensive test suite for user management features"), Feature("User Management"), Feature("Admin Panel"), ] class UserManagementTest extends TestCase { #[ DisplayName("Admin can create new users"), Description("Verify that admin users can create new user accounts"), Severity(Severity::CRITICAL), Feature("Admin Panel"), Story("User Creation"), Parameter("role", "admin"), ] public function testAdminCreateUser(): void { Allure::runStep( #[DisplayName('Create user via admin panel')] function () { // Create user } ); } } ``` -------------------------------- ### Example 2: Parameterized Test Source: https://github.com/allure-framework/allure-phpunit/blob/main/_autodocs/api-reference/TestAttributes.md An example demonstrating the use of Allure attributes with PHPUnit's DataProvider for parameterized tests, including dynamic parameter logging. ```php use PHPUnit\Framework\Attributes\DataProvider; use Qameta\Allure\Attribute\{DisplayName, Parameter}; use Qameta\Allure\Allure; class ValidationTest extends TestCase { #[DataProvider('emailProvider'), DisplayName('Email validation')] public function testEmailValidation(string $email, bool $expected): void { Allure::parameter('email', $email); Allure::parameter('expected', $expected ? 'valid' : 'invalid'); $result = validateEmail($email); $this->assertEquals($expected, $result); } public static function emailProvider(): iterable { return [ 'valid email' => ['user@example.com', true], 'invalid format' => ['not-an-email', false], 'empty string' => ['', false], ]; } } ``` -------------------------------- ### Mixed Usage Example Source: https://github.com/allure-framework/allure-phpunit/blob/main/_autodocs/api-reference/ExceptionDetailsTrait.md Demonstrates how to use the ExceptionDetailsTrait, showing both the recommended trait method and direct adapter access for capturing exceptions. ```php use PHPUnit\Framework\TestCase; use Qameta\Allure\PHPUnit\ExceptionDetailsTrait; use Qameta\Allure\PHPUnit\AllureAdapter; use Throwable; class MixedHandlingTest extends TestCase { use ExceptionDetailsTrait; public function testWithExplicitCapture(): void { try { // Some code that might fail $result = $this->mayFail(); } catch (Throwable $e) { // Option 1: Use trait method (recommended) $this->onNotSuccessfulTest($e); // Option 2: Direct adapter access (less elegant) // AllureAdapter::getInstance()->setLastException($e); // throw $e; } } } ``` -------------------------------- ### ThreadDetectorInterface Definition Source: https://github.com/allure-framework/allure-phpunit/blob/main/_autodocs/api-reference/Configuration.md The interface definition for ThreadDetectorInterface. ```php interface ThreadDetectorInterface { public function getThread(): ?string; public function getHost(): ?string; } ``` -------------------------------- ### resetLastException() Example Source: https://github.com/allure-framework/allure-phpunit/blob/main/_autodocs/api-reference/AllureAdapter.md Clears the exception state before processing a new test. ```php $adapter = AllureAdapter::getInstance(); $adapter->resetLastException(); ``` -------------------------------- ### Using Allure Steps in PHPUnit Source: https://github.com/allure-framework/allure-phpunit/blob/main/README.md Example of how to use `Allure::runStep` to divide a test method into distinct steps, each with a title and optional parameters. This helps in isolating failures and understanding test execution flow. ```php namespace Example\Tests; use PHPUnit\Framework\TestCase; use Qameta\Allure\Allure; use Qameta\Allure\Attribute\Parameter; use Qameta\Allure\Attribute\Title; use Qameta\Allure\StepContextInterface; class SomeTest extends TestCase { public function testCaseMethod(): void { //Some implementation here... $x = Allure::runStep( #[Title('First step')] function (StepContextInterface $step): string { $step->parameter('param1', $someValue); return 'foo'; }, ); Allure::runStep([$this, 'stepTwo']); //Some implementation here... } #[ Title("Second step"), Parameter("param2", "value2"), ] private function stepTwo(): void { //Some implementation here... } } ``` -------------------------------- ### DefaultThreadDetector Class Signature Source: https://github.com/allure-framework/allure-phpunit/blob/main/_autodocs/api-reference/Configuration.md The class signature for the DefaultThreadDetector, implementing ThreadDetectorInterface. ```php final class DefaultThreadDetector implements ThreadDetectorInterface { public function getThread(): ?string public function getHost(): ?string } ``` -------------------------------- ### File Structure Source: https://github.com/allure-framework/allure-phpunit/blob/main/_autodocs/INDEX.md The directory structure of the Allure PHPUnit adapter documentation. ```text output/ ├── README.md ← START HERE ├── INDEX.md ← You are here ├── ARCHITECTURE.md ← System design ├── configuration.md ← Configuration guide ├── types.md ← Data structures ├── errors.md ← Error reference └── api-reference/ ├── AllureExtension.md ├── AllureAdapter.md ├── Configuration.md ├── EventSubscribers.md ├── ExceptionDetailsTrait.md └── TestAttributes.md ``` -------------------------------- ### getThread() Method Signature Source: https://github.com/allure-framework/allure-phpunit/blob/main/_autodocs/api-reference/Configuration.md The method signature for the getThread() method of ThreadDetectorInterface. ```php public function getThread(): ?string ``` -------------------------------- ### Configuration Validation Errors Source: https://github.com/allure-framework/allure-phpunit/blob/main/_autodocs/configuration.md Examples of invalid configuration values that trigger RuntimeExceptions. ```php // Invalid outputDirectory type 'outputDirectory' => 123, // RuntimeException: should contain a string // Invalid linkTemplate type 'linkTemplates' => [ 'tms' => 123, // RuntimeException: invalid source ], // Invalid threadDetector class 'threadDetector' => 'NonExistentClass', // RuntimeException: contains invalid source // Wrong lifecycle hook array format 'lifecycleHooks' => [ 'named_key' => \My\Hook::class, // RuntimeException: must have integer keys ] ``` -------------------------------- ### Typical Usage of outputDirectory Source: https://github.com/allure-framework/allure-phpunit/blob/main/_autodocs/configuration.md A common way to configure the 'outputDirectory' in the Allure PHPUnit configuration file. ```php return [ 'outputDirectory' => 'build/allure-results', ]; ``` -------------------------------- ### Link Template Configuration Source: https://github.com/allure-framework/allure-phpunit/blob/main/_autodocs/api-reference/TestAttributes.md Configuration example for link templates in `config/allure.config.php`. ```php 'linkTemplates' => [ 'tms' => 'https://jira.example.com/browse/%s', 'issue' => 'https://github.com/myorg/myrepo/issues/%s', ] ``` -------------------------------- ### Check Generated Files Source: https://github.com/allure-framework/allure-phpunit/blob/main/_autodocs/ARCHITECTURE.md Bash command to list the generated Allure report files. ```bash ls -la build/allure-results/ ```