From 7e1af7b6439336e2643da21a3bbb1d1a3715b46f Mon Sep 17 00:00:00 2001 From: Edward Surov Date: Wed, 15 Sep 2021 13:43:51 +0300 Subject: [PATCH] prototype of v2 (via #55) --- .gitattributes | 25 + .github/workflows/build.yml | 102 +-- .gitignore | 11 +- README.md | 232 +++--- composer.json | 53 +- phpcs.xml.dist | 15 + phpunit.report.xml | 29 +- phpunit.xml | 15 - phpunit.xml.dist | 17 + psalm.xml.dist | 17 + src/AllureAdapter.php | 151 ++++ src/AllureAdapterInterface.php | 29 + src/AllureExtension.php | 153 ++++ src/ExceptionDetailsTrait.php | 17 + src/Internal/DefaultThreadDetector.php | 39 + src/Internal/TestInfo.php | 75 ++ src/Internal/TestLifecycle.php | 191 +++++ src/Internal/TestLifecycleFactory.php | 25 + .../TestLifecycleFactoryInterface.php | 13 + src/Internal/TestLifecycleInterface.php | 31 + src/Internal/TestRunInfo.php | 52 ++ src/Internal/TestStartInfo.php | 25 + src/Internal/TestUpdater.php | 138 ++++ src/Internal/TestUpdaterInterface.php | 25 + src/Setup/ConfiguratorInterface.php | 26 + src/Setup/DefaultConfigurator.php | 77 ++ src/Setup/ThreadDetectorInterface.php | 13 + src/Yandex/Allure/PhpUnit/AllurePhpUnit.php | 304 -------- .../Allure/Adapter/AllureAdapterTest.php | 179 ----- .../Yandex/Allure/Report/Check/ReportTest.php | 337 -------- .../Allure/Report/Generate/AnnotationTest.php | 71 -- .../Allure/Report/Generate/AttachmentTest.php | 29 - .../Allure/Report/Generate/StepsTest.php | 109 --- .../Annotation/TitleClassLevelLegacyTest.php | 25 + .../Annotation/TitleClassLevelMixedTest.php | 26 + .../Annotation/TitleClassLevelNativeTest.php | 22 + test/report/Generate/Annotation/TitleTest.php | 48 ++ test/report/Generate/AnnotationTest.php | 154 ++++ test/report/Generate/NegativeTest.php | 78 ++ test/report/Generate/RetriesTest.php | 66 ++ test/report/Hook/OnLifecycleErrorHook.php | 20 + test/report/Hook/OnSetupHook.php | 17 + test/unit/AllureAdapterTest.php | 721 ++++++++++++++++++ test/unit/AllureExtensionTest.php | 400 ++++++++++ test/unit/ExceptionDetailsTraitTest.php | 53 ++ .../Internal/DefaultThreadDetectorTest.php | 35 + test/unit/Internal/TestInfoTest.php | 203 +++++ test/unit/Internal/TestRunInfoTest.php | 157 ++++ test/unit/Internal/TestStartInfoTest.php | 27 + test/unit/Setup/DefaultConfiguratorTest.php | 102 +++ test/unit/Setup/OnSetupHook.php | 31 + test/unit/TestConfigurator.php | 68 ++ test/unit/TestConfiguratorInterface.php | 12 + test/unit/TestTestLifecycle.php | 62 ++ 54 files changed, 3722 insertions(+), 1230 deletions(-) create mode 100644 .gitattributes create mode 100644 phpcs.xml.dist delete mode 100644 phpunit.xml create mode 100644 phpunit.xml.dist create mode 100644 psalm.xml.dist create mode 100644 src/AllureAdapter.php create mode 100644 src/AllureAdapterInterface.php create mode 100644 src/AllureExtension.php create mode 100644 src/ExceptionDetailsTrait.php create mode 100644 src/Internal/DefaultThreadDetector.php create mode 100644 src/Internal/TestInfo.php create mode 100644 src/Internal/TestLifecycle.php create mode 100644 src/Internal/TestLifecycleFactory.php create mode 100644 src/Internal/TestLifecycleFactoryInterface.php create mode 100644 src/Internal/TestLifecycleInterface.php create mode 100644 src/Internal/TestRunInfo.php create mode 100644 src/Internal/TestStartInfo.php create mode 100644 src/Internal/TestUpdater.php create mode 100644 src/Internal/TestUpdaterInterface.php create mode 100644 src/Setup/ConfiguratorInterface.php create mode 100644 src/Setup/DefaultConfigurator.php create mode 100644 src/Setup/ThreadDetectorInterface.php delete mode 100644 src/Yandex/Allure/PhpUnit/AllurePhpUnit.php delete mode 100644 test/Yandex/Allure/Adapter/AllureAdapterTest.php delete mode 100644 test/Yandex/Allure/Report/Check/ReportTest.php delete mode 100644 test/Yandex/Allure/Report/Generate/AnnotationTest.php delete mode 100644 test/Yandex/Allure/Report/Generate/AttachmentTest.php delete mode 100644 test/Yandex/Allure/Report/Generate/StepsTest.php create mode 100644 test/report/Generate/Annotation/TitleClassLevelLegacyTest.php create mode 100644 test/report/Generate/Annotation/TitleClassLevelMixedTest.php create mode 100644 test/report/Generate/Annotation/TitleClassLevelNativeTest.php create mode 100644 test/report/Generate/Annotation/TitleTest.php create mode 100644 test/report/Generate/AnnotationTest.php create mode 100644 test/report/Generate/NegativeTest.php create mode 100644 test/report/Generate/RetriesTest.php create mode 100644 test/report/Hook/OnLifecycleErrorHook.php create mode 100644 test/report/Hook/OnSetupHook.php create mode 100644 test/unit/AllureAdapterTest.php create mode 100644 test/unit/AllureExtensionTest.php create mode 100644 test/unit/ExceptionDetailsTraitTest.php create mode 100644 test/unit/Internal/DefaultThreadDetectorTest.php create mode 100644 test/unit/Internal/TestInfoTest.php create mode 100644 test/unit/Internal/TestRunInfoTest.php create mode 100644 test/unit/Internal/TestStartInfoTest.php create mode 100644 test/unit/Setup/DefaultConfiguratorTest.php create mode 100644 test/unit/Setup/OnSetupHook.php create mode 100644 test/unit/TestConfigurator.php create mode 100644 test/unit/TestConfiguratorInterface.php create mode 100644 test/unit/TestTestLifecycle.php diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..b2ea9a7 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,25 @@ +# Define the line ending behavior of the different file extensions +# Set default behavior, in case users don't have core.autocrlf set. +* text text=auto eol=lf + +.php diff=php + +# Declare files that will always have CRLF line endings on checkout. +*.bat eol=crlf + +# Declare files that will always have LF line endings on checkout. +*.pem eol=lf + +# Denote all files that are truly binary and should not be modified. +*.png binary +*.jpg binary +*.gif binary +*.ico binary +*.mo binary +*.pdf binary +*.phar binary +*.woff binary +*.woff2 binary +*.ttf binary +*.otf binary +*.eot binary diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index a9dad6e..d7e8845 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -1,66 +1,66 @@ name: Build on: + workflow_dispatch: pull_request: branches: - '*' push: branches: - - '*' + - 'master' jobs: - build71: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v2.3.4 - - uses: shivammathur/setup-php@v2 - with: - php-version: '7.1.3' - - name: Install - run: composer update - - name: Test - run: composer test - build72: - runs-on: ubuntu-latest + tests: + name: PHP ${{ matrix.php-version }} on ${{ matrix.os }} (${{ matrix.composer-options }}) + runs-on: ${{ matrix.os }} + strategy: + fail-fast: false + matrix: + php-version: + - "8.0" + - "8.1" + os: + - ubuntu-latest + - windows-latest + - macOS-latest + composer-options: + - "" + - "--prefer-lowest" steps: - - uses: actions/checkout@v2.3.4 - - uses: shivammathur/setup-php@v2 - with: - php-version: '7.2' - - name: Install - run: composer update - - name: Test - run: composer test - build73: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v2.3.4 - - uses: shivammathur/setup-php@v2 + - name: Checkout + uses: actions/checkout@v2.3.4 + + - name: Validate composer.json and composer.lock + run: composer validate + + - name: Set up PHP ${{ matrix.php-version }} + uses: shivammathur/setup-php@v2 with: - php-version: '7.3' - - name: Install + php-version: ${{ matrix.php-version }} + extensions: pcntl, posix + coverage: xdebug + ini-values: error_reporting=E_ALL + + - name: Install dependencies run: composer update - - name: Test + --prefer-dist + --no-progress + ${{ matrix.composer-options }} + + - name: Run tests + if: ${{ matrix.os != 'windows-latest' && matrix.php-version != '8.1' }} run: composer test - build74: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v2.3.4 - - uses: shivammathur/setup-php@v2 - with: - php-version: '7.4' - - name: Install - run: composer update - - name: Test + + - name: Run tests (windows) + if: ${{ matrix.os == 'windows-latest' && matrix.php-version != '8.1' }} + run: composer test-windows + + - name: Run tests (experimental) + if: ${{ matrix.os != 'windows-latest' && matrix.php-version == '8.1' }} + continue-on-error: true run: composer test - build80: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v2.3.4 - - uses: shivammathur/setup-php@v2 - with: - php-version: '8.0' - - name: Install - run: composer update - - name: Test - run: composer test \ No newline at end of file + + - name: Run tests (windows, experimental) + if: ${{ matrix.os == 'windows-latest' && matrix.php-version == '8.1' }} + continue-on-error: true + run: composer test-windows diff --git a/.gitignore b/.gitignore index dabbba2..8eace9a 100644 --- a/.gitignore +++ b/.gitignore @@ -1,8 +1,7 @@ -*.iml -.idea -vendor/* -composer.phar -composer.lock -nbproject /build +/vendor/ +/composer.lock +/phpunit.xml +/phpcs.xml +/psalm.xml .phpunit.result.cache diff --git a/README.md b/README.md index 6308fbb..a96b240 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,9 @@ # Allure PHPUnit adapter +[![Latest Stable Version](http://poser.pugx.org/allure-framework/allure-phpunit/v)](https://packagist.org/packages/allure-framework/allure-phpunit) [![Build](https://github.com/allure-framework/allure-phpunit/actions/workflows/build.yml/badge.svg)](https://github.com/allure-framework/allure-phpunit/actions/workflows/build.yml) +[![Total Downloads](http://poser.pugx.org/allure-framework/allure-phpunit/downloads)](https://packagist.org/packages/allure-framework/allure-phpunit) +[![License](http://poser.pugx.org/allure-framework/allure-phpunit/license)](https://packagist.org/packages/allure-framework/allure-phpunit) This an official PHPUnit adapter for Allure Framework - a flexible, lightweight and multi-language framework for writing self-documenting tests. @@ -19,63 +22,95 @@ This an official PHPUnit adapter for Allure Framework - a flexible, lightweight * [Steps](#divide-test-methods-into-steps) ## What is this for? -The main purpose of this adapter is to accumulate information about your tests and write it out to a set of XML files: one for each test class. Then you can use a standalone command line tool or a plugin for popular continuous integration systems to generate an HTML page showing your tests in a good form. +The main purpose of this adapter is to accumulate information about your tests and write it out to a set of JSON files: one for each test class. Then you can use a standalone command line tool or a plugin for popular continuous integration systems to generate an HTML page showing your tests in a good form. ## Example project Example project is located at: https://github.com/allure-framework/allure-phpunit-example ## How to generate report -This adapter only generates XML files containing information about tests. See [wiki section](https://github.com/allure-framework/allure-core/wiki#generating-report) on how to generate report. +This adapter only generates JSON files containing information about tests. See [wiki section](https://docs.qameta.io/allure/#_reporting) on how to generate report. ## Installation && Usage -**Note:** this adapter supports Allure 1.4.x only. +**Note:** this adapter supports Allure 2.x.x only. In order to use this adapter you need to add a new dependency to your **composer.json** file: ``` { "require": { - "php": ">=7.0.0", - "allure-framework/allure-phpunit": "~1.2.0" + "php": "^8", + "allure-framework/allure-phpunit": "^2" } } ``` Then add Allure test listener in **phpunit.xml** file: ```xml - - + + + - build/allure-results - true - - - someCustomAnnotation - - + + build/allure-results + + Qameta\Allure\PHPUnit\Setup\DefaultConfigurator + - - + + ``` -After running PHPUnit tests a new folder will be created (**build/allure-results** in the example above). This folder will contain generated XML files. See [framework help](https://github.com/allure-framework/allure-core/wiki) for details about how to generate report from XML files. By default generated report will only show a limited set of information but you can use cool Allure features by adding a minimum of test code changes. Read next section for details. +After running PHPUnit tests a new folder will be created (**build/allure-results** in the example above). This folder will contain generated JSON files. See [framework help](https://docs.qameta.io/allure/#_reporting) for details about how to generate report from JSON files. By default generated report will only show a limited set of information but you can use cool Allure features by adding a minimum of test code changes. Read next section for details. + +You can also use setup hook to tune or extend Allure lifecycle: +```xml + + + + + + + + + + My\Namespace\OnSetupHook + + + +``` + +And the hook class could look like this: + +```php +addHooks(new MyHook()) + } +} +``` + +In the above example we add some custom hook `MyHook` to Allure lifecycle. ## Main features This adapter comes with a set of PHP annotations and traits allowing to use main Allure features. ### Human-readable test class or test method title -In order to add such title to any test class or [test case](https://github.com/allure-framework/allure-core/wiki/Glossary#test-case) method you need to annotate it with **@Title** annotation: +In order to add such title to any test class or [test case](https://github.com/allure-framework/allure1/wiki/Glossary#test-case) method you need to annotate it with **#[Title]** annotation: ```php namespace Example\Tests; use PHPUnit\Framework\TestCase; -use Yandex\Allure\Adapter\Annotation\Title; +use Qameta\Allure\Attribute\Title; -/** - * @Title("Human-readable test class title") - */ +#[Title("Human-readable test class title")] class SomeTest extends TestCase { - /** - * @Title("Human-readable test method title") - */ - public function testCase() + #[Title("Human-readable test method title")] + public function testCaseMethod(): void { //Some implementation here... } @@ -83,45 +118,38 @@ class SomeTest extends TestCase ``` ### Extended test class or test method description -Similarly you can add detailed description for each test class and [test method](https://github.com/allure-framework/allure-core/wiki/Glossary#test-case). To add such description simply use **@Description** annotation: +Similarly you can add detailed description for each test class and [test method](https://github.com/allure-framework/allure1/wiki/Glossary#test-case). To add such description simply use **#[Description]** annotation: ```php namespace Example\Tests; use PHPUnit\Framework\TestCase; -use Yandex\Allure\Adapter\Annotation\Description; -use Yandex\Allure\Adapter\Model\DescriptionType; +use Qameta\Allure\Attribute\Description; -/** - * @Description("Detailed description for test class") - */ +#[Description("Detailed description for **test** class")] class SomeTest extends TestCase { - /** - * @Description(value = "Detailed description for test class.", type = DescriptionType::HTML) - */ - public function testCase() + #[Description("Detailed description for test class", isHtml: true)] + public function testCaseMethod(): void { //Some implementation here... } } ``` -Description can be added in plain text, HTML or Markdown format - simply assign different **type** value. +Description can be added in Markdown format (which is default one) or in HTML format. For HTML simply pass `true` value for optional `isHtml` argument. ### Set test severity -**@Severity** annotation is used in order to prioritize test methods by severity: +**#[Severity]** annotation is used in order to prioritize test methods by severity: + ```php namespace Example\Tests; use PHPUnit\Framework\TestCase; -use Yandex\Allure\Adapter\Annotation\Severity; -use Yandex\Allure\Adapter\Model\SeverityLevel; +use Qameta\Allure\Attribute\Severity; class SomeTest extends TestCase { - /** - * @Severity(level = SeverityLevel::MINOR) - */ - public function testCase() + #[Severity(Severity::MINOR)] + public function testCaseMethod(): void { //Some implementation here... } @@ -129,47 +157,52 @@ class SomeTest extends TestCase ``` ### Specify test parameters information -In order to add information about test method [parameters](https://github.com/allure-framework/allure-core/wiki/Glossary#parameter) you should use **@Parameter** annotation: +In order to add information about test method [parameters](https://github.com/allure-framework/allure-core/wiki/Glossary#parameter) you should use **#[Parameter]** annotation. You can also use static shortcut if your marameter has dynamic value: + ```php namespace Example\Tests; use PHPUnit\Framework\TestCase; -use Yandex\Allure\Adapter\Annotation\Parameter; -use Yandex\Allure\Adapter\Model\ParameterKind; +use Qameta\Allure\Allure; +use Qameta\Allure\Attribute\Parameter; class SomeTest extends TestCase { - /** - * @Parameter(name = "param1", value = "value1") - * @Parameter(name = "param2", value = "value2", kind = ParameterKind::SYSTEM_PROPERTY) - */ - public function testCase() + #[ + Parameter("param1", "value1"), + Parameter("param2", "value2"), + ] + public function testCaseMethod(): void { //Some implementation here... + Allure::parameter("param3", $someVar); } } ``` ### Map test classes and test methods to features and stories -In some development approaches tests are classified by [stories](https://github.com/allure-framework/allure-core/wiki/Glossary#user-story) and [features](https://github.com/allure-framework/allure-core/wiki/Glossary#feature). If you're using this then you can annotate your test with **@Stories** and **@Features** annotations: +In some development approaches tests are classified by [stories](https://github.com/allure-framework/allure-core/wiki/Glossary#user-story) and [features](https://github.com/allure-framework/allure-core/wiki/Glossary#feature). If you're using this then you can annotate your test with **#[Story]** and **#[Feature]** annotations: ```php namespace Example\Tests; use PHPUnit\Framework\TestCase; -use Yandex\Allure\Adapter\Annotation\Features; -use Yandex\Allure\Adapter\Annotation\Stories; - -/** - * @Stories({"story1", "story2"}) - * @Features({"feature1", "feature2", "feature3"}) - */ +use Qameta\Allure\Attribute\Feature; +use Qameta\Allure\Attribute\Story; + +#[ + Story("story1"), + Story("story2"), + Feature("feature1"), + Feature("feature2"), + Feature("feature3"), +] class SomeTest extends TestCase { - /** - * @Features({"feature2"}) - * @Stories({"story1"}) - */ - public function testCase() + #[ + Story("story3"), + Feature("feature4"), + ] + public function testCaseMethod(): void { //Some implementation here... } @@ -178,82 +211,65 @@ class SomeTest extends TestCase You will then be able to filter tests by specified features and stories in generated Allure report. ### Attach files to report -If you wish to [attach some files](https://github.com/allure-framework/allure-core/wiki/Glossary#attachment) generated during PHPUnit run (screenshots, log files, dumps and so on) to report - then you need to use **AttachmentSupport** trait in your test class: +If you wish to [attach some files](https://github.com/allure-framework/allure-core/wiki/Glossary#attachment) generated during PHPUnit run (screenshots, log files, dumps and so on) to report - then you need to use static shortcuts in your test class: ```php namespace Example\Tests; use PHPUnit\Framework\TestCase; -use Yandex\Allure\Adapter\Support\AttachmentSupport; +use Qameta\Allure\Allure; class SomeTest extends TestCase { - use AttachmentSupport; - - public function testCase() + public function testCaseMethod() { //Some implementation here... - $filePath = $this->outputSomeContentToTemporaryFile(); - $this->addAttachment($filePath, 'Attachment human-readable name', 'text/plain'); + Allure::attachment("Attachment 1", "attachment content", 'text/plain'); + Allure::attachmentFile("Attachment 2", "/path/to/file.png", 'image/png'); //Some implementation here... } - - private function outputSomeContentToTemporaryFile() - { - $tmpPath = tempnam(sys_get_temp_dir(), 'test'); - file_put_contents($tmpPath, 'Some content to be outputted to temporary file.'); - return $tmpPath; - } - } ``` -In order to create an [attachment](https://github.com/allure-framework/allure-core/wiki/Glossary#attachment) simply call **AttachmentSupport::addAttachment()** method. This method accepts attachment type, human-readable name and a string either storing full path to the file we need to attach or file contents. +In order to create an [attachment](https://github.com/allure-framework/allure-core/wiki/Glossary#attachment) simply call **Allure::attachment()** method. This method accepts human-readable name, string content and MIME attachment type. To attach a file, use **Allure::attachmentFile()** method that accepts file name instead of string content. ### Divide test methods into steps -Allure framework also supports very useful feature called [steps](https://github.com/allure-framework/allure-core/wiki/Glossary#test-step). Consider a test method which has complex logic inside and several assertions. When an exception is thrown or one of assertions fails sometimes it's very difficult to determine which one caused the failure. Allure steps allow to divide test method logic into several isolated pieces having independent run statuses such as **passed** or **failed**. This allows to have much more cleaner understanding of what really happens. In order to use steps simply import **StepSupport** trait in your test class: +Allure framework also supports very useful feature called [steps](https://github.com/allure-framework/allure-core/wiki/Glossary#test-step). Consider a test method which has complex logic inside and several assertions. When an exception is thrown or one of assertions fails sometimes it's very difficult to determine which one caused the failure. Allure steps allow dividing test method logic into several isolated pieces having independent run statuses such as **passed** or **failed**. This allows to have much cleaner understanding of what really happens. In order to use steps simply use static shortcuts: + ```php namespace Example\Tests; use PHPUnit\Framework\TestCase; -use Yandex\Allure\Adapter\Support\StepSupport; +use Qameta\Allure\Allure; +use Qameta\Allure\Attribute\Parameter; +use Qameta\Allure\Attribute\Title; +use Qameta\Allure\StepContextInterface; class SomeTest extends TestCase { - use StepSupport; - - public function testCase() + public function testCaseMethod(): void { //Some implementation here... - $this->executeStep("This is step one", function () { - $this->stepOne(); - }); - - $this->executeStep("This is step two", function () { - $this-stepTwo(); - }); - - $this->executeStep("This is step three", function () { - $this->stepThree('someArgument'); - }); - //Some implementation here... - } - - private function stepOne() - { + $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() { //Some implementation here... } - - private function stepThree($argument) - { - //Some implementation here... - } - } ``` The entire test method execution status will depend on every step but information about steps status will be stored separately. diff --git a/composer.json b/composer.json index 3220bbc..9d8149f 100644 --- a/composer.json +++ b/composer.json @@ -9,7 +9,7 @@ "cases", "allure" ], - "description": "Allure PHPUNit integration", + "description": "Allure PHPUnit integration", "homepage": "http://allure.qatools.ru/", "license": "Apache-2.0", "authors": [ @@ -17,6 +17,11 @@ "name": "Ivan Krutov", "email": "vania-pooh@yandex-team.ru", "role": "Developer" + }, + { + "name": "Edward Surov", + "email": "zoohie@gmail.com", + "role": "Developer" } ], "support": { @@ -24,33 +29,59 @@ "source": "https://github.com/allure-framework/allure-phpunit" }, "require": { - "php": ">=7.1", - "allure-framework/allure-php-api": "^1.3", - "phpunit/phpunit": "^7.2 | ^8 | ^9" + "php": "^8", + "allure-framework/allure-php-commons": "dev-main", + "phpunit/phpunit": "^9" }, "require-dev": { "ext-dom": "*", - "mikey179/vfsstream": "^1" + "brianium/paratest": "^6.3.1", + "psalm/plugin-phpunit": "^0.16.1", + "squizlabs/php_codesniffer": "^3.6.0", + "vimeo/psalm": "^4.10" }, "autoload": { - "psr-0": { - "Yandex": "src/" + "psr-4": { + "Qameta\\Allure\\PHPUnit\\": "src/" } }, "autoload-dev": { "psr-0": { "Yandex": "test/" + }, + "psr-4": { + "Qameta\\Allure\\PHPUnit\\Test\\Unit\\": "test/unit/", + "Qameta\\Allure\\PHPUnit\\Test\\Report\\": "test/report/" } }, "scripts": { - "test-unit": "vendor/bin/phpunit", + "test-cs": "vendor/bin/phpcs -sp", + "test-unit": "vendor/bin/phpunit --coverage-text", + "clear-allure-results": "rm -rf ./build/allure-results", "test-report": [ - "vendor/bin/phpunit --configuration=phpunit.report.xml --stderr 2> /dev/null; exit 0", - "vendor/bin/phpunit --testsuite=report" + "@clear-allure-results", + "vendor/bin/paratest --processes=3 --configuration=phpunit.report.xml --testsuite=positive", + "vendor/bin/paratest --processes=3 --configuration=phpunit.report.xml --testsuite=negative; exit 0", + "vendor/bin/paratest --processes=3 --configuration=phpunit.report.xml --testsuite=retries --repeat=3; exit 0" ], + "test-report-windows": [ + "@clear-allure-results", + "vendor/bin/paratest --processes=3 --configuration=phpunit.report.xml --testsuite=positive", + "vendor/bin/paratest --processes=3 --configuration=phpunit.report.xml --testsuite=negative & exit 0", + "vendor/bin/paratest --processes=3 --configuration=phpunit.report.xml --testsuite=retries --repeat=3 & exit 0" + ], + "test-psalm": "vendor/bin/psalm", "test": [ + "@test-cs", + "@test-unit", + "@test-report", + "@test-psalm" + ], + "test-windows": [ + "@test-cs", "@test-unit", - "@test-report" + "@test-report-windows", + "@test-psalm" ] } } diff --git a/phpcs.xml.dist b/phpcs.xml.dist new file mode 100644 index 0000000..227a3bb --- /dev/null +++ b/phpcs.xml.dist @@ -0,0 +1,15 @@ + + + Qameta Coding Standards + + src + test + + + + + + + */test/*Test.php + + diff --git a/phpunit.report.xml b/phpunit.report.xml index 2440841..fdb7b19 100644 --- a/phpunit.report.xml +++ b/phpunit.report.xml @@ -1,20 +1,29 @@ + defaultTestSuite="positive"> - - test/Yandex/Allure/Report/Generate + + test/report/Generate + test/report/Generate/NegativeTest.php + test/report/Generate/RetriesTest.php + + + test/report/Generate/NegativeTest.php + + + test/report/Generate/RetriesTest.php - - + + - build/allure-results - true + + + Qameta\Allure\PHPUnit\Test\Report\Hook\OnSetupHook - - + + diff --git a/phpunit.xml b/phpunit.xml deleted file mode 100644 index fd3cfd2..0000000 --- a/phpunit.xml +++ /dev/null @@ -1,15 +0,0 @@ - - - - - test/Yandex/Allure/Adapter/ - - - test/Yandex/Allure/Report/Check/ - - - diff --git a/phpunit.xml.dist b/phpunit.xml.dist new file mode 100644 index 0000000..4660606 --- /dev/null +++ b/phpunit.xml.dist @@ -0,0 +1,17 @@ + + + + + test/unit/ + + + + + src/ + + + diff --git a/psalm.xml.dist b/psalm.xml.dist new file mode 100644 index 0000000..ab032bb --- /dev/null +++ b/psalm.xml.dist @@ -0,0 +1,17 @@ + + + + + + + + + + + + + diff --git a/src/AllureAdapter.php b/src/AllureAdapter.php new file mode 100644 index 0000000..c9f4c00 --- /dev/null +++ b/src/AllureAdapter.php @@ -0,0 +1,151 @@ + + */ + private array $lastStarts = []; + + /** + * @var array + */ + private array $lastRuns = []; + + private ?Throwable $lastException = null; + + private function __construct() + { + } + + public static function getInstance(): AllureAdapterInterface + { + return self::$instance ??= new self(); + } + + public static function setInstance(AllureAdapterInterface $instance): void + { + self::$instance = $instance; + } + + public static function reset(): void + { + self::$instance = null; + } + + public function resetLastException(): void + { + $this->lastException = null; + } + + public function setLastException(Throwable $e): void + { + $this->lastException = $e; + } + + public function getLastException(): ?Throwable + { + return $this->lastException; + } + + public function registerStart(ContainerResult $containerResult, TestResult $testResult, TestInfo $info): string + { + $this->lastStarts[$info->getTest()] = new TestStartInfo( + containerId: $containerResult->getUuid(), + testId: $testResult->getUuid(), + ); + + return $testResult->getUuid(); + } + + public function getContainerId(TestInfo $info): string + { + $startInfo = $this->lastStarts[$info->getTest()] ?? null; + + return $startInfo?->getContainerId() + ?? throw new LogicException("Container not registered: {$info->getTest()}"); + } + + public function getTestId(TestInfo $info): string + { + $startInfo = $this->lastStarts[$info->getTest()] ?? null; + + return $startInfo?->getTestId() + ?? throw new LogicException("Test not registered: {$info->getTest()}"); + } + + public function registerRun(TestResult $testResult, TestInfo $info): TestRunInfo + { + $testCaseId = $this->buildTestCaseId($testResult, $info); + $historyId = $this->buildHistoryId($testResult, $info, $testCaseId); + + $previousRunInfo = $this->lastRuns[$historyId] ?? null; + $currentRunInfo = new TestRunInfo( + testInfo: $info, + uuid: $testResult->getUuid(), + rerunOf: $previousRunInfo?->getUuid(), + runIndex: 1 + ($previousRunInfo?->getRunIndex() ?? -1), + testCaseId: $testCaseId, + historyId: $historyId, + ); + $this->lastRuns[$historyId] = $currentRunInfo; + + return $currentRunInfo; + } + + /** + * @param TestResult $test + * @return list + */ + private function getIncludedParameters(TestResult $test): array + { + return array_values( + array_filter( + $test->getParameters(), + fn (Parameter $parameter): bool => $parameter->getExcluded() !== true, + ), + ); + } + + private function buildTestCaseId(TestResult $test, TestInfo $info): string + { + $parameterNames = implode( + '::', + array_map( + fn (Parameter $parameter): string => $parameter->getName(), + $this->getIncludedParameters($test), + ), + ); + + return md5("{$info->getName()}::{$parameterNames}"); + } + + private function buildHistoryId(TestResult $test, TestInfo $info, string $testCaseId): string + { + $parameterValues = implode( + '::', + array_map( + fn (Parameter $parameter) => $parameter->getValue() ?? '', + $this->getIncludedParameters($test), + ), + ); + + return md5("{$testCaseId}::{$info->getName()}::{$parameterValues}"); + } +} diff --git a/src/AllureAdapterInterface.php b/src/AllureAdapterInterface.php new file mode 100644 index 0000000..4c48ca7 --- /dev/null +++ b/src/AllureAdapterInterface.php @@ -0,0 +1,29 @@ +createConfigurator( + $configurator ?? DefaultConfigurator::class, + ...$args, + ); + } + $configurator->setupAllure($outputDirectory ?? self::DEFAULT_OUTPUT_DIRECTORY); + $this->testLifecycle = $this->createTestLifecycleInterface($configurator); + } + + private function createConfigurator(string $class, mixed ...$args): ConfiguratorInterface + { + return + class_exists($class) && + is_a($class, ConfiguratorInterface::class, true) + ? new $class(...$args) + : throw new LogicException("Invalid configurator class: {$class}"); + } + + private function createTestLifecycleInterface(ConfiguratorInterface $configurator): TestLifecycleInterface + { + $testLifecycleFactory = $configurator instanceof TestLifecycleFactoryInterface + ? $configurator + : new TestLifecycleFactory(); + + return $testLifecycleFactory->createTestLifecycle($configurator); + } + + public function executeBeforeTest(string $test): void + { + $this + ->testLifecycle + ->switchTo($test) + ->reset() + ->create() + ->updateInfo() + ->start(); + } + + public function executeAfterTest(string $test, float $time): void + { + $this + ->testLifecycle + ->switchTo($test) + ->stop() + ->updateRunInfo() + ->write(); + } + + public function executeAfterTestFailure(string $test, string $message, float $time): void + { + $this + ->testLifecycle + ->switchTo($test) + ->updateDetectedStatus($message, Status::failed()); + } + + public function executeAfterTestError(string $test, string $message, float $time): void + { + $this + ->testLifecycle + ->switchTo($test) + ->updateDetectedStatus($message, Status::failed()); + } + + public function executeAfterIncompleteTest(string $test, string $message, float $time): void + { + $this + ->testLifecycle + ->switchTo($test) + ->updateStatus($message, Status::broken()); + } + + public function executeAfterSkippedTest(string $test, string $message, float $time): void + { + $this + ->testLifecycle + ->switchTo($test) + ->updateStatus($message, Status::skipped()); + } + + public function executeAfterTestWarning(string $test, string $message, float $time): void + { + $this + ->testLifecycle + ->switchTo($test) + ->updateStatus($message, Status::broken()); + } + + public function executeAfterRiskyTest(string $test, string $message, float $time): void + { + $this + ->testLifecycle + ->switchTo($test) + ->updateStatus($message, Status::failed()); + } + + public function executeAfterSuccessfulTest(string $test, float $time): void + { + $this + ->testLifecycle + ->switchTo($test) + ->updateStatus(status: Status::passed()); + } +} diff --git a/src/ExceptionDetailsTrait.php b/src/ExceptionDetailsTrait.php new file mode 100644 index 0000000..7a8323e --- /dev/null +++ b/src/ExceptionDetailsTrait.php @@ -0,0 +1,17 @@ +setLastException($t); + throw $t; + } +} diff --git a/src/Internal/DefaultThreadDetector.php b/src/Internal/DefaultThreadDetector.php new file mode 100644 index 0000000..09e1ac3 --- /dev/null +++ b/src/Internal/DefaultThreadDetector.php @@ -0,0 +1,39 @@ +hostName ??= @gethostname(); + + return false === $this->hostName ? null : $this->hostName; + } +} diff --git a/src/Internal/TestInfo.php b/src/Internal/TestInfo.php new file mode 100644 index 0000000..55def10 --- /dev/null +++ b/src/Internal/TestInfo.php @@ -0,0 +1,75 @@ +test; + } + + /** + * @return class-string|null + */ + public function getClass(): ?string + { + return $this->class; + } + + public function getMethod(): ?string + { + return $this->method; + } + + public function getDataLabel(): ?string + { + return $this->dataLabel; + } + + public function getFullName(): ?string + { + return isset($this->class, $this->method) + ? "{$this->class}::{$this->method}" + : null; + } + + public function getName(): string + { + return $this->getFullName() ?? $this->getTest(); + } + + public function getHost(): ?string + { + return $this->host; + } + + public function getThread(): ?string + { + return $this->thread; + } +} diff --git a/src/Internal/TestLifecycle.php b/src/Internal/TestLifecycle.php new file mode 100644 index 0000000..5ddc7a9 --- /dev/null +++ b/src/Internal/TestLifecycle.php @@ -0,0 +1,191 @@ +resultFactory->createContainer(); + $this->lifecycle->startContainer($containerResult); + + $testResult = $this->resultFactory->createTest(); + $this->lifecycle->scheduleTest($testResult, $containerResult->getUuid()); + + $this->adapter->registerStart($containerResult, $testResult, $this->getCurrentTest()); + + return $this; + } + + public function updateInfo(): self + { + $this->lifecycle->updateTest( + fn (TestResult $testResult) => $this->testUpdater->setInfo($testResult, $this->getCurrentTest()), + $this->adapter->getTestId($this->getCurrentTest()), + ); + + return $this; + } + + public function start(): self + { + $this->lifecycle->startTest( + $this->adapter->getTestId($this->getCurrentTest()), + ); + + return $this; + } + + public function stop(): self + { + $this->lifecycle->stopTest( + $this->adapter->getTestId($this->getCurrentTest()), + ); + $this->lifecycle->stopContainer( + $this->adapter->getContainerId($this->getCurrentTest()), + ); + + return $this; + } + + public function updateRunInfo(): self + { + $this->lifecycle->updateTest( + fn (TestResult $testResult) => $this->testUpdater->setRunInfo( + $testResult, + $this->adapter->registerRun($testResult, $this->getCurrentTest()), + ), + $this->adapter->getTestId($this->getCurrentTest()), + ); + + return $this; + } + + public function write(): self + { + $this->lifecycle->writeTest( + $this->adapter->getTestId($this->getCurrentTest()), + ); + + return $this; + } + + public function updateStatus(?string $message = null, ?Status $status = null): self + { + $this->lifecycle->updateTest( + fn (TestResult $testResult) => $this->testUpdater->setStatus($testResult, $message, $status), + $this->adapter->getTestId($this->getCurrentTest()), + ); + + return $this; + } + + public function updateDetectedStatus(?string $message = null, ?Status $status = null): self + { + $exception = $this->adapter->getLastException(); + if (!isset($exception)) { + return $this->updateStatus($message, $status); + } + + $this->lifecycle->updateTest( + fn (TestResult $testResult) => $this->testUpdater->setDetectedStatus( + $testResult, + $this->statusDetector, + $exception, + ), + $this->adapter->getTestId($this->getCurrentTest()), + ); + + return $this; + } + + public function switchTo(string $test): self + { + $thread = $this->threadDetector->getThread(); + $this->lifecycle->switchThread($thread); + + $this->currentTest = $this->buildTestInfo( + $test, + $this->threadDetector->getHost(), + $thread, + ); + + return $this; + } + + public function reset(): self + { + $this->adapter->resetLastException(); + + return $this; + } + + private function getCurrentTest(): TestInfo + { + return $this->currentTest ?? throw new RuntimeException("Current test is not set"); + } + + private function buildTestInfo(string $test, ?string $host = null, ?string $thread = null): TestInfo + { + $dataLabelMatchResult = preg_match( + '#^([^\s]+)\s+with\s+data\s+set\s+"(.*)"\s+\(.+\)$#', + $test, + $matches, + ); + + /** @var list $matches */ + if (1 === $dataLabelMatchResult) { + $classAndMethod = $matches[1] ?? null; + $dataLabel = $matches[2] ?? '?'; + } else { + $classAndMethod = $test; + $dataLabel = null; + } + + [$class, $method] = isset($classAndMethod) + ? array_pad(explode('::', $classAndMethod, 2), 2, null) + : [null, null]; + + /** @psalm-suppress MixedArgument */ + return new TestInfo( + test: $test, + class: isset($class) && class_exists($class) ? $class : null, + method: $method, + dataLabel: $dataLabel, + host: $host, + thread: $thread, + ); + } +} diff --git a/src/Internal/TestLifecycleFactory.php b/src/Internal/TestLifecycleFactory.php new file mode 100644 index 0000000..131902f --- /dev/null +++ b/src/Internal/TestLifecycleFactory.php @@ -0,0 +1,25 @@ +getAllureLifecycle() ?? Allure::getLifecycle(), + $configurator->getResultFactory() ?? Allure::getResultFactory(), + $configurator->getStatusDetector() ?? Allure::getStatusDetector(), + $configurator->getThreadDetector() ?? new DefaultThreadDetector(), + $configurator->getAllureAdapter() ?? AllureAdapter::getInstance(), + new TestUpdater(), + ); + } +} diff --git a/src/Internal/TestLifecycleFactoryInterface.php b/src/Internal/TestLifecycleFactoryInterface.php new file mode 100644 index 0000000..6c62284 --- /dev/null +++ b/src/Internal/TestLifecycleFactoryInterface.php @@ -0,0 +1,13 @@ +testInfo; + } + + public function getUuid(): string + { + return $this->uuid; + } + + public function getRerunOf(): ?string + { + return $this->rerunOf; + } + + public function getRunIndex(): int + { + return $this->runIndex; + } + + public function getTestCaseId(): string + { + return $this->testCaseId; + } + + public function getHistoryId(): string + { + return $this->historyId; + } +} diff --git a/src/Internal/TestStartInfo.php b/src/Internal/TestStartInfo.php new file mode 100644 index 0000000..41e595d --- /dev/null +++ b/src/Internal/TestStartInfo.php @@ -0,0 +1,25 @@ +containerId; + } + + public function getTestId(): string + { + return $this->testId; + } +} diff --git a/src/Internal/TestUpdater.php b/src/Internal/TestUpdater.php new file mode 100644 index 0000000..1c1622e --- /dev/null +++ b/src/Internal/TestUpdater.php @@ -0,0 +1,138 @@ +parseAnnotations($info); + + $testResult + ->setName($parser->getTitle() ?? $info->getName()) + ->setFullName($info->getFullName()) + ->setDescriptionHtml($parser->getDescriptionHtml()) + ->setDescription($parser->getDescription()) + ->addLabels( + ...$this->createSystemLabels($info), + ...$parser->getLabels(), + ) + ->addParameters( + ...$this->createSystemParameters($info), + ...$parser->getParameters(), + ) + ->addLinks(...$parser->getLinks()); + } + + /** + * @param TestInfo $info + * @return AttributeParser + */ + private function parseAnnotations(TestInfo $info): AttributeParser + { + $class = $info->getClass(); + if (!isset($class)) { + return new AttributeParser([]); + } + + $annotations = []; + $reader = new LegacyAttributeReader( + new DoctrineAnnotationReader(), + new AttributeReader(), + ); + try { + $classRef = new ReflectionClass($class); + $annotations = [ + ...$annotations, + ...$reader->getClassAnnotations($classRef), + ]; + } catch (Throwable $e) { + throw new LogicException("Annotations not loaded", 0, $e); + } + + $method = $info->getMethod(); + if (!isset($method)) { + return new AttributeParser($annotations); + } + + try { + $methodRef = new ReflectionMethod($class, $method); + $annotations = [ + ...$annotations, + ...$reader->getMethodAnnotations($methodRef), + ]; + } catch (Throwable $e) { + throw new LogicException("Annotations not loaded", 0, $e); + } + + return new AttributeParser($annotations); + } + + /** + * @return list