Error io qameta allure allurelifecycle could not add attachment no test is running

I'm submitting a ... bug report What is the current behavior? 2018-12-19 12:12:06 ERROR AllureLifecycle:563 - Could not add attachment: no test is running 2018-12-19 12:12:08 ERROR AllureLifecy...

@Fanch-

I’m submitting a …

  • bug report

What is the current behavior?


2018-12-19 12:12:06 ERROR AllureLifecycle:563 - Could not add attachment: no test is running
2018-12-19 12:12:08 ERROR AllureLifecycle:414 - Could not start step: no test case running
2018-12-19 12:12:08 ERROR AllureLifecycle:470 - Could not update step: step with uuid 9cb0199b-f0db-45cc-97f9-2e2cc396633a not found
2018-12-19 12:12:08 ERROR AllureLifecycle:504 - Could not stop step: step with uuid 9cb0199b-f0db-45cc-97f9-2e2cc396633a not found

Using maven command to launch the tests, I have not this issue, but using intelliJ run/debug conf (for local tests) I have the previous logs.

So the console output is flooded by AllureLifecycle logs

What is the expected behavior?

With an allure previous version (2.7.0), we didn’t have it.

Please tell us about your environment:

Allure version 2.8.1
Test framework junit@4.12
aspectj version 1.8.10

Other information

    <allure.version>2.8.1</allure.version>
    <aspectj.version>1.8.10</aspectj.version>
    <maven-surefire-plugin.version>2.20.1</maven-surefire-plugin.version>
    <plugin-listener>io.qameta.allure.junit4.AllureJunit4</plugin-listener>

    <dependency>
        <groupId>io.qameta.allure</groupId>
        <artifactId>allure-junit4</artifactId>
        <version>${allure.version}</version>
    </dependency>
    <dependency>
        <groupId>org.aspectj</groupId>
        <artifactId>aspectjweaver</artifactId>
        <version>${aspectj.version}</version>
    </dependency>
</dependencies>

<build>
    <plugins>
        <plugin>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.1</version>
            <configuration>
                <source>1.8</source>
                <target>1.8</target>
                <encoding>UTF-8</encoding>
            </configuration>
        </plugin>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-checkstyle-plugin</artifactId>
            <version>2.17</version>
            <configuration>
                <configLocation>google_checks.xml</configLocation>
                <includeTestSourceDirectory>true</includeTestSourceDirectory>
            </configuration>
        </plugin>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-surefire-plugin</artifactId>
            <version>${maven-surefire-plugin.version}</version>
            <configuration>
                <systemPropertyVariables>
                    <allure.link.mylink.pattern>https://testrail-url?/cases/view/{}</allure.link.mylink.pattern>
                    <allure.link.issue.pattern>https://jira-url/{}</allure.link.issue.pattern>
                    <allure.link.tms.pattern>https://to.define/{}</allure.link.tms.pattern>
                    <allure.results.directory>${project.build.directory}/allure-results</allure.results.directory>
                </systemPropertyVariables>
                <argLine>
                    -javaagent:"${settings.localRepository}/org/aspectj/aspectjweaver/${aspectj.version}/aspectjweaver-${aspectj.version}.jar"
                </argLine>
                <properties>
                    <property>
                        <name>listener</name>
                        <value>
                            ${plugin-listener}
                        </value>
                    </property>
                </properties>
            </configuration>
        </plugin>
    </plugins>
</build>

@baev

This logs means that you are trying to add steps and attachments when no test running (eg in set up/tear down methods that is not supported by allure-junit4 integration by now)

In order versions has no logging for such cases.

@Fanch-

I mean it works using maven command line, it’s when I launch a test with intelliJ that I get the error.

spectacle s30553

Every steps during my test (so not linked to set up/tear down — Before/After) are throwing AllureLifecycle errors (everything works fine with mvn).

I guess with maven commandline, the plugin phase is correctly interpreted, the listener also, and with the IDE there is something wrong. The strange thing is that the attachments are still generated.

The behavior might be the same as before, logs in addition, it’s just for local purpose have something to not show them could be great, otherwise we will still stay in 2.7.0 forever :(

@baev

@Fanch- am I right that you have the same behaviour as in 2.7.0 but additional error logging is present?

The problem is that IDEA ignores maven-surefire configuration, so when you run tests using IDE Allure have no information about test start/stop event, and that causes the warnings.

Attachments are generated because Allure can store the file you are trying to attach, but it can’t find current execution context (AllureLifecycle stores information about current running tests in thread local storage) to add the link to the stored file.

Actually I think that having logs is a good idea — thats is a signal for you that something is wrong (like in this case, you have no listener configured when run your tests via IDE).

The problem is only exists for JUnit 4 projects since JUnit team decided to not add SPI support for listeners in 4.x versions (I even create a pull request with that change few years ago junit-team/junit4#1122)

Also there is no possibility to configure listener for JUnit 4 in IDEA run build configuration (like for TestNG tests)

Possible workarounds

  • You can disable logging for AllureLifecycle class in your logger config (exact configuration depends on slf4j implementation you are using). After that the behaviour should be the same as in 2.7.0
  • You can try to use allure-junit4-aspect module. This module is designed exactly for cases when you have no possibility to configure listener for JUnit 4. It uses aspects, so you need to configure AspectJ in your IDEA run build configuration (by adding aspectj-weaver agent to jvm args or using aspectj-compiler)
  • try to use junit-vintage to run JUnit 4 tests and allure-junit-platform integration instead of allure-junit4

@Fanch-

@baev Thank you for your answer.

With 2.7.0 I have just the logging errors when a step param is malformed, which is cool I agree 2018-12-20 11:54:50 ERROR NamingUtils:54 - Could not find parameter

But I haven’t the following errors during test :


2018-12-19 12:12:06 ERROR AllureLifecycle:563 - Could not add attachment: no test is running
2018-12-19 12:12:08 ERROR AllureLifecycle:414 - Could not start step: no test case running
2018-12-19 12:12:08 ERROR AllureLifecycle:470 - Could not update step: step with uuid 9cb0199b-f0db-45cc-97f9-2e2cc396633a not found

from 2.8.0

We have about 100 steps per test, which log a lot of errors.

But your answer is fine for me, we would have to use junit5 for allure 2.8.0 👍 to avoid IDEA limitation.

@romainlouvet

@Fanch- just add log4j.logger.io.qameta.allure.AllureLifecycle = OFF in your log4j.properties
bisous

@ogulcanarbc

allure-junit-platform 2.13.0 working but 2.17.1 v not working this case, why?

<properties>
    <java.compiler>14</java.compiler>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.target>14</maven.compiler.target>
    <maven.compiler.source>14</maven.compiler.source>
    <maven.compiler.version>3.8.1</maven.compiler.version>
    <maven-surefire-plugin.version>3.0.0-M3</maven-surefire-plugin.version>
    <maven-compiler-plugin.version>3.8.1</maven-compiler-plugin.version>
    <kafka.client.version>2.2.14.RELEASE</kafka.client.version>
    <junit.jupiter.version>5.7.2</junit.jupiter.version>
    <junit.platform.version>1.8.1</junit.platform.version>
    <aspectj.version>1.9.6</aspectj.version>
    <allure.version>2.17.1</allure.version>
    <allure-maven.version>2.10.0</allure-maven.version>
    <allure.cmd.download.url>
        https://repo.maven.apache.org/maven2/io/qameta/allure/allure-commandline
    </allure.cmd.download.url>
    <log4j2.version>2.15.0</log4j2.version>
</properties>

@dzikuf

@Fanch- just add log4j.logger.io.qameta.allure.AllureLifecycle = OFF in your log4j.properties bisous

@romainlouvet in log4j2 this row does`t work. How to do in log4j2?

@david-m-globant

for testng, this solve the title problem

<!-- required by Allure.addAttachment -->
<dependency>
	<groupId>io.qameta.allure</groupId>
	<artifactId>allure-plugin-api</artifactId>
	<version>${allure.version}</version>
</dependency>
<!-- required by Allure web view -->
<dependency>
	<groupId>io.qameta.allure</groupId>
	<artifactId>allure-testng</artifactId>
	<version>${allure.version}</version>
</dependency>

I’m submitting a …

— [X] bug report

  • feature request
  • support request => Please do not submit support request here, see note at the top of this template.

What is the current behavior?

Issue description:

  • I’m implementing the IInvokedMethodListener for TestNG
  • Inside it I have Overridden the afterInvocation method
  • I use this to create a log for the current test method Reporter.getOutput(testResult)
  • Then I try to attach this log file using this code
    Allure.addAttachment(attachmentDescription, "text/plain", attachmentContent, ".txt");
  • This works as expected for all @Test methods, but it doesn’t work for configuration methods like @BeforeMethod and @AfterMethod
  • This error is shown in the console [main] ERROR io.qameta.allure.AllureLifecycle - Could not add attachment: no test is running

Debugging Information

Upon debugging this issue I traced it to this method
String io.qameta.allure.AllureLifecycle.prepareAttachment(String name, String type, String fileExtension)

Apparently threadContext.getCurrent(); is returning empty instead of returning the UUID of the current configuration method.

This behavior is shown if I’m running any test, but if I’m debugging it becomes intermittent, and sometimes works as expected!!!

What is the expected behavior?

The attachment should be added successfully, and this error should not happen.

What is the motivation / use case for changing the behavior?

This impacts reporting attachments for any configuration method.

Please tell us about your environment:

| Test framework | testng@7.0.0 |
| Allure integration | allure-testng@2.13.1 |
| AspectJ Weaver | aspectjweaver | 1.9.5 |
| Java run-time environment | JDK | 13 |
| IDE | Eclipse | Build id: 20191212-1212 |

Other information

  • I couldn’t downgrade to acpectj 1.8.0 because it’s not working with JDK 13
  • Tried using a different listener ‘IConfigurationListener’ but the same issue persisted

Не могу сформировать Allure отчет в своем автотесте.

Запускаю выполнение автотеста с помощью junit: при выполнении не создается папка allure-results и получаю следующие ошибки:

10:18:53.917 [main] ERROR io.qameta.allure.AllureLifecycle - Could not start step: no test case running
10:18:54.316 [main] ERROR io.qameta.allure.AllureLifecycle - Could not update step: no step running
10:18:54.316 [main] ERROR io.qameta.allure.AllureLifecycle - Could not stop step: no step running
10:18:54.317 [main] ERROR io.qameta.allure.AllureLifecycle - Could not start step: no test case running
10:18:54.387 [main] ERROR io.qameta.allure.AllureLifecycle - Could not update step: no step running
10:18:54.387 [main] ERROR io.qameta.allure.AllureLifecycle - Could not stop step: no step running

При запуске с помощью maven, получаю следующий ворнинг:

[ERROR] Directory C:gitetc_testtargetallure-results not found.
[WARNING] Allure report was skipped because there is no results directories found.

Если я создаю папку allure-results вручную, то при исполнении mvn удалит ее и вернет тот же самый ворнинг.

Мой pom.xml:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>ru.mos</groupId>
    <artifactId>etc_test</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <aspectj.version>1.8.10</aspectj.version>
    </properties>

    <dependencies>
        <!-- https://mvnrepository.com/artifact/junit/junit -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13</version>
            <scope>test</scope>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.junit.jupiter/junit-jupiter-api -->
        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter-api</artifactId>
            <version>5.7.0-RC1</version>
            <scope>test</scope>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.junit.jupiter/junit-jupiter-engine -->
        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter-engine</artifactId>
            <version>5.7.0-RC1</version>
            <scope>test</scope>
        </dependency>

        <!-- https://mvnrepository.com/artifact/io.github.bonigarcia/webdrivermanager -->
        <dependency>
            <groupId>io.github.bonigarcia</groupId>
            <artifactId>webdrivermanager</artifactId>
            <version>3.8.0</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.seleniumhq.selenium/selenium-java -->
        <dependency>
            <groupId>org.seleniumhq.selenium</groupId>
            <artifactId>selenium-java</artifactId>
            <version>3.141.59</version>
        </dependency>

        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-classic</artifactId>
            <version>1.1.1</version>
        </dependency>
        <dependency>
            <groupId>io.qameta.allure</groupId>
            <artifactId>allure-junit5</artifactId>
            <version>2.13.1</version>
            <scope>test</scope>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.apache.maven.plugins/maven-surefire-plugin -->
        <dependency>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-surefire-plugin</artifactId>
            <version>3.0.0-M5</version>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <version>2.22.2</version>
                <configuration>
                    <useSystemClassLoader>false</useSystemClassLoader>
                    <argLine>
                        -javaagent:"${settings.localRepository}/org/aspectj/aspectjweaver/1.8.10/aspectjweaver-1.8.10.jar"
                    </argLine>
                    <properties>
                        <property>
                            <name>listener</name>
                            <value>io.qameta.allure.junit5.AllureJunit5</value>
                        </property>
                    </properties>
                    <systemProperties>
                        <property>
                            <name>allure.results.directory</name>
                            <value>${project.build.directory}/allure-results</value>
                        </property>
                    </systemProperties>
                </configuration>
                <dependencies>
                    <dependency>
                        <groupId>org.aspectj</groupId>
                        <artifactId>aspectjweaver</artifactId>
                        <version>1.8.10</version>
                    </dependency>
                </dependencies>
            </plugin>
            <plugin>
                <groupId>io.qameta.allure</groupId>
                <artifactId>allure-maven</artifactId>
                <version>2.10.0</version>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.8.0</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

Структура теста:
TestCase5986:

package ru.mos;

import io.qameta.allure.*;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

import java.util.concurrent.TimeUnit;

public class TestCase5986 {
    public static LoginPage loginPage;
    public static MainPage mainPage;
    public static WblPage wblPage;
    public static WebDriver driver;

    @BeforeClass
    public static void setup() {
        System.setProperty("webdriver.chrome.driver", ConfProperties.getProperty("chromedriver"));
        driver = new ChromeDriver();
        loginPage = new LoginPage(driver);
        mainPage = new MainPage(driver);
        wblPage = new WblPage(driver);
        driver.manage().window().maximize();
        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
        driver.get(ConfProperties.getProperty("loginpage"));
    }

    @Epic("Тестирование стенда ETC)
    @Feature(value = "CASE-5986")
    @Severity(SeverityLevel.CRITICAL)
    @Description("Позитивный тест формы логирования в системе")
    @Story (value = "Авторизация с корректным логином")

    @Test
    public void LoginTest() {
        loginPage.inputLogin(ConfProperties.getProperty("login"), ConfProperties.getProperty("password"));
        loginPage.clickSubmitBtn();
        /*mainPage.waybillListClick();
        wblPage.createBtnClick();
        wblPage.carSelect();
        wblPage.createMission();
        wblPage.techOpIdSelect();
        wblPage.facilityIdSelect();
        wblPage.routeIdSelect();
        wblPage.missionSubmitClick();
        wblPage.refillAddRow1();
        wblPage.oneFuelTankContSelect();
        wblPage.depDateFieldInput();
        wblPage.arrivalDateFieldInput();
        wblPage.newDepDate();
        assert wblPage.checkErrorMsg();*/
    }

        @AfterClass
        public static void driverClose () {
        driver.close();

    }

}

loginPage:

package ru.mos;

import io.qameta.allure.Step;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;

public class LoginPage {
    public WebDriver driver;

    public LoginPage(WebDriver driver) {
        PageFactory.initElements(driver, this);
        this.driver = driver;
    }

    @FindBy(id = "login")
    public WebElement loginFld;
    @FindBy(id = "password")
    public WebElement passwordFld;
    @FindBy(id = "submit")
    public WebElement submitBtn;

    @Step("Ввод логина {login} и пароля {password}")
    public void inputLogin(String login, String password) {
        loginFld.sendKeys(login);
        passwordFld.sendKeys(password);

    }
    
    @Step ("Подтверждение авторизации")
    public void clickSubmitBtn() {
        submitBtn.click();
    }

}

У меня два предположения:

  1. чего-то не хватает в pom.xml;
  2. некорректное использование аннотаций.

UPD:
При выполнении команды allure:serve формируется пустой отчет:
Пустой allure-отчет

UPD2: Лог Maven при выполнении кейса:

C:jdk1.8.0_161binjava.exe -Dmaven.multiModuleProjectDirectory=C:gitTestNGAllure_test "-Dmaven.home=C:UsersTinkovAYAppDataLocalJetBrainsIntelliJ IDEA Community Edition 2020.2pluginsmavenlibmaven3" "-Dclassworlds.conf=C:UsersTinkovAYAppDataLocalJetBrainsIntelliJ IDEA Community Edition 2020.2pluginsmavenlibmaven3binm2.conf" "-Dmaven.ext.class.path=C:UsersTinkovAYAppDataLocalJetBrainsIntelliJ IDEA Community Edition 2020.2pluginsmavenlibmaven-event-listener.jar" "-javaagent:C:UsersTinkovAYAppDataLocalJetBrainsIntelliJ IDEA Community Edition 2020.2libidea_rt.jar=52132:C:UsersTinkovAYAppDataLocalJetBrainsIntelliJ IDEA Community Edition 2020.2bin" -Dfile.encoding=UTF-8 -classpath "C:UsersTinkovAYAppDataLocalJetBrainsIntelliJ IDEA Community Edition 2020.2pluginsmavenlibmaven3bootplexus-classworlds-2.6.0.jar;C:UsersTinkovAYAppDataLocalJetBrainsIntelliJ IDEA Community Edition 2020.2pluginsmavenlibmaven3bootplexus-classworlds.license" org.codehaus.classworlds.Launcher -Didea.version=2020.2.1 clean test -Dsuite=src/test/resources/testng.xml.xml -Dversion=83.0 allure:serve
[INFO] Scanning for projects...
[INFO] 
[INFO] ----------------------< ru.dit:TestNGAllure_test >----------------------
[INFO] Building TestNGAllure_test 1.0-SNAPSHOT
[INFO] --------------------------------[ jar ]---------------------------------
[INFO] 
[INFO] --- maven-clean-plugin:2.5:clean (default-clean) @ TestNGAllure_test ---
[INFO] Deleting C:gitTestNGAllure_testtarget
[INFO] 
[INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ TestNGAllure_test ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] Copying 0 resource
[INFO] 
[INFO] --- maven-compiler-plugin:3.8.0:compile (default-compile) @ TestNGAllure_test ---
[INFO] Nothing to compile - all classes are up to date
[INFO] 
[INFO] --- maven-resources-plugin:2.6:testResources (default-testResources) @ TestNGAllure_test ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] Copying 1 resource
[INFO] 
[INFO] --- maven-compiler-plugin:3.8.0:testCompile (default-testCompile) @ TestNGAllure_test ---
[INFO] Changes detected - recompiling the module!
[INFO] Compiling 5 source files to C:gitTestNGAllure_testtargettest-classes
[INFO] 
[INFO] --- maven-surefire-plugin:2.20:test (default-test) @ TestNGAllure_test ---
[INFO] 
[INFO] -------------------------------------------------------
[INFO]  T E S T S
[INFO] -------------------------------------------------------
[INFO] Running TestSuite
[INFO] Tests run: 0, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 7.034 s - in TestSuite
[INFO] 
[INFO] Results:
[INFO] 
[INFO] Tests run: 0, Failures: 0, Errors: 0, Skipped: 0
[INFO] 
[INFO] 
[INFO] --- allure-maven:2.10.0:serve (default-cli) @ TestNGAllure_test ---
[INFO] Allure installation directory C:gitTestNGAllure_test/.allure
[INFO] Try to finding out allure 2.8.1
[INFO] Generate Allure report (serve) with version 2.8.1
[INFO] Generate Allure report to C:gitTestNGAllure_testtargetsite/allure-maven-plugin
[INFO] Found results directory C:gitTestNGAllure_testtargetallure-results
[INFO] Can't find information about categories.
[INFO] Generate report to C:gitTestNGAllure_testtargetsiteallure-maven-plugin
Generating report to temp directory...
Report successfully generated to C:UsersTinkovAYAppDataLocalTemp6365362014998145974allure-report
Starting web server...
2020-08-26 15:35:45.363:INFO::main: Logging initialized @2065ms to org.eclipse.jetty.util.log.StdErrLog
Server started at <http://10.159.209.98:52175/>. Press <Ctrl+C> to exit

Структура проекта

введите сюда описание изображения

и еще куча таких моментов

Stanislav Mischenko

@krigan

вот теперь как раз буду искать утечку, т.к. ни ретраев, ни датапровайдеров нет

Vladimir-edu

@Vladimir-edu

Всем привет! Столкнулся с проблемой [main] ERROR io.qameta.allure.AllureLifecycle — Could not start step: no test case running. Идея какая есть отдельный тестовый класс №1 для проверки работы терминала. В нем все размечено для аллюра — все работает. Все ОК. Тепрь у меня есть другой тестовый класс №2 который проверяет некие плюшки для активного терминала. Когда я пытаюсь вызвать методы проверки активности терминала (из класса №1) внутри методов класса№2 — то все норм. НО как только я пытаюсь перенести эти вызовы внутри класса2 в метод с аннотацией Before (junit4) , что бы не прописывать вызов внутри каждого метода, то получаю [main] ERROR io.qameta.allure.AllureLifecycle — Could not start step: no test case running.

потому что аллюр не умеет фикстуры для junit4

то есть все степы из before — не знают, куда себя девать, о чем и пишут в лог

Vladimir-edu

@Vladimir-edu

@baev А как-нть это можно обойти? Или придется все то что лежало в бефо распихивать в каждый метод — это же куча лишних строк кода выходит

красиво не будет, к сожалению

Vladimir-edu

@Vladimir-edu

И в будущем изменений в данном направлении не предвидится?

у Junit4 нет способа узнать о фикстурах без добавления кастомного раннера

Vladimir-edu

@Vladimir-edu

Жаль, спасибо.

формально можно сделать, например, на аспектах. Но мне совсем не хочется тратить на это время. Но может когда-нибудь появится

я бы лучше для junit5 запилил поддержку фикстур

Vladimir-edu

@Vladimir-edu

@baev Ладно я закостылилил клон метода без Аллюровского обвеса со step и прочее. Причем если тест падает по причине Ассерта сработавшего на уровне бефо — то в отчет эта инфа никак не попадает. А вот это уже действительно неприятно :((( т.е. либо мне затаскивать ассерт в каждый метод (что не смертельно, но неприятно) И вот с этим уже наверно надо что-то делать так как не всегда фикстуры являются примитивными данными.

Vladimir-edu

@Vladimir-edu

Т.е. тест падает в консоли [ERROR] Tests run: 1, Failures: 1, Errors: 0, Skipped: 0, Time elapsed: 2.8 s <<< FAILURE!. Но в аллюр отчет эта инфа не попадает. (нет никакого упоминания об упавшем тесте(тестах)) Так как тест класс со всеми его методами свалился на уровне бефо. ИМХО это надо править

Добрый вечер GUYS. Подскажите для MSTest есть ли плагин для аллура? или самому писатть обработчики?

@pulversss trx вроде аллюр умеет без адаптера

:warning: для тех, кто был на митапе нашем, и заинтересовался — пишите мне в личку :warning:

Stanislav Mischenko

@krigan

а для тех кто не был по географическим соображениям, но очень хочет заинтересоваться — где бы узнать чекак…

Обещали видео «через 2-3 недели», ЕМНИП

@baev , а что писать тебе в личку?)

@Asdwarf хочу на тнт аллюр сервер ))

Писать приветы, я собираю фидбек

Добрый день! Такой вопрос — есть ли возможность скрыть все пункты меню за исключением Overview и Behaviors, по возможности, без ковыряния в исходниках? Для некоторых больших манагеров это дофига сложно.

AlexP

@AlexanderPoleschuk

ниасилили?

сложно не щелкать в ненужные менюшки?)))

если очень хочется, то можно форкнуть и отключить ненужные штуки, это не очень сложно

ocherniavskyi

@ocherniavskyi-lohika-tix

@baev а видос с митапа будет? а то очень интересно

Через .allure/allure-2.7.0/config удалось скрыть разве что Packages

Всем привет! Тут такой вопрос — можно ли, к примеру, поскрывать все пункты меню в репорте, оставив только Overview и Behaviors? Для каких-то больших манагеров это сложнааа и они этого не хотят..

ocherniavskyi

@ocherniavskyi-lohika-tix

@baev а видосы с митапа будут, а то очень интересно

это один из епиков для следующего большого релиза — сделать возможность конфигурировать вообще все

будет, через пару-тройку недель

без ковыряния кода сложно будет

Блин, что с чатиком. То сообщения упорно не отсылаются, то приходит вся пачка..)

@baev , спасибо! Ждём с нетерпением

AlexP

@AlexanderPoleschuk

gitter штормит. у меня теперь текст сообщения, которое я набираю какой-то здоровый. а текст сообщений в чате мельче стал

Stanislav Mischenko

@krigan

всем ку! можно ли поменять на лету имя теста для репорта?

Привет всем!
Подскажите, пожалуйста, как можно добавить логи с тестов к аллюр отчету? Ипользую groovy, spock, wslite (for https requests). Добавил в проект allure-attachments. Но в отчетах только прошел/непрошел ли тест и данные по параметризированым тестам.
Спасибо!

@krigan для JVM: Allure.getLifecycle().updateTestResult(tr -> tr.setName(«new name»))

вызывать в рамках метода надо

@Luceafarul надо добавить interceptor для клинта, который делает запросы

и в нем можно на каждый запрос что-то создать)

Stanislav Mischenko

@krigan

@baev , спасибо, как раз нашел это сейчас, должно подойти

@krigan смотри в целом, как в Allure классе апи сделано

Recommend Projects

  • React photo

    React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo

    Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo

    Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo

    TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo

    Django

    The Web framework for perfectionists with deadlines.

  • Laravel photo

    Laravel

    A PHP framework for web artisans

  • D3 photo

    D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Visualization

    Some thing interesting about visualization, use data art

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo

    Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo

    Microsoft

    Open source projects and samples from Microsoft.

  • Google photo

    Google

    Google ❤️ Open Source for everyone.

  • Alibaba photo

    Alibaba

    Alibaba Open Source for everyone

  • D3 photo

    D3

    Data-Driven Documents codes.

  • Tencent photo

    Tencent

    China tencent open source team.

Describe the bug
The allure reports do not contain attachments added in BeforeAllCallback/AfterAllCallback

To Reproduce
Run the following code with junit 5:

import io.qameta.allure.Allure;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.AfterAllCallback;
import org.junit.jupiter.api.extension.AfterEachCallback;
import org.junit.jupiter.api.extension.AfterTestExecutionCallback;
import org.junit.jupiter.api.extension.BeforeAllCallback;
import org.junit.jupiter.api.extension.BeforeEachCallback;
import org.junit.jupiter.api.extension.BeforeTestExecutionCallback;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.jupiter.api.extension.ExtensionContext;

@ExtendWith({AllureIssueExtension.class})
public class AllureIssueTest {

    @BeforeAll
    static void beforeAll() {
        Allure.addAttachment("static beforeAll in test class", "something");
    }

    @BeforeEach
    void beforeEach() {
        Allure.addAttachment("beforeEach in test class", "something");
    }

    @Test
    void someTest() {
        Allure.addAttachment("someTest in test class", "something");
    }

    @AfterEach
    void afterEach() {
        Allure.addAttachment("afterEach in test class", "something");
    }

    @AfterAll
    static void afterAll() {
        Allure.addAttachment("static afterAll in test class", "something");
    }
}

class AllureIssueExtension implements BeforeAllCallback, BeforeEachCallback, BeforeTestExecutionCallback,
    AfterTestExecutionCallback, AfterEachCallback, AfterAllCallback {

    @Override
    public void beforeAll(final ExtensionContext context) {
        Allure.addAttachment("BeforeAllCallback in AllureIssueExtension", "something");
    }

    @Override
    public void beforeEach(final ExtensionContext context) {
        Allure.addAttachment("BeforeEachCallback in AllureIssueExtension", "something");
    }

    @Override
    public void beforeTestExecution(final ExtensionContext context) {
        Allure.addAttachment("BeforeTestExecutionCallback in AllureIssueExtension", "something");
    }

    @Override
    public void afterTestExecution(final ExtensionContext context) {
        Allure.addAttachment("AfterTestExecutionCallback in AllureIssueExtension", "something");
    }

    @Override
    public void afterEach(final ExtensionContext context) {
        Allure.addAttachment("AfterEachCallback in AllureIssueExtension", "something");
    }

    @Override
    public void afterAll(final ExtensionContext context) {
        Allure.addAttachment("AfterAllCallback in AllureIssueExtension", "something");
    }
}

Expected behavior
There should be 11 attachments in the allure report.

Actual behavior
The attachments made in BeforeAllCallback and AfterAllCallback are missing:

Screenshots
image

Additinal context
It seems that the allure lifecycle is not started when the extensions are working. Here are the logs produced during BeforeAllCallback and AfterAllCallback work:

[ForkJoinPool-1-worker-3] ERROR AllureLifecycle - Could not add attachment: no test is running

. Примечание: для вопросов поддержки используйте Stackoverflow или Gitter ..

В случае возникновения проблем с плагином Allure Jenkins используйте следующий репозиторий
. чтобы создать проблему: https://github.com/jenkinsci/allure-plugin/issues
.
. Убедитесь, что у вас есть четкое название проблемы. Название должно начинаться с заглавной буквы.
. буква и точка в конце предложения не требуются. Пример удачных названий задач:
.
. — Отчет сломан в IE11
. — Добавить возможность отключить плагины по умолчанию
. — Поддержка эмодзи в описаниях тестов
)

Я отправляю …

  • [x] отчет об ошибке
  • [] запрос функции
  • [] запрос на поддержку => Пожалуйста, не отправляйте сюда запрос на поддержку, см. примечание вверху этого шаблона.

Каково текущее поведение?

Использование allure-cucumber-jvm-3 со скриншотами после каждого шага и частое получение прикрепленных снимков экрана (подозрение на проблему состояния гонки). Чтобы получить скриншоты после каждого шага, используя собственный класс:

public class AllureScreenshotPublisher implements Formatter {
private final AllureLifecycle allureLifecycle;

public AllureScreenshotPublisher() {
    this.allureLifecycle = Allure.getLifecycle();
}

<strong i="26">@Override</strong>
public void setEventPublisher(EventPublisher publisher) {
    publisher.registerHandlerFor(TestStepFinished.class, this::handleTestStepFinished);
}

private void handleTestStepFinished(final TestStepFinished event) {
    byte[] screenShot = ((TakesScreenshot) DriverManager.getDriver()).getScreenshotAs(OutputType.BYTES);
    allureLifecycle.addAttachment(LocalDateTime.now().format(DateTimeFormatter.ofPattern("dd-MMM-yy_hh:mm:ss")), "image/png", "png", screenShot);
}
}

а затем определите это как плагин для каждого бегуна:

@CucumberOptions(
glue = {"*.stepdefs"},
features = {"target/parallel/features/[CUCABLE:FEATURE].feature"},
plugin = {"*.allure.AllureScreenshotPublisher",
"io.qameta.allure.cucumber3jvm.AllureCucumber3Jvm"}
)

public class [CUCABLE:RUNNER] extends AbstractTestNGCucumberTests {

}

Есть идеи, почему это не удается примерно в 5-10% случаев?

С использованием:

io.qameta.allure
очарование-огурец3-jvm
2.7.0

и Selenium 3.141.59 (если поможет :))

Все 26 Комментарий

@ jsa34 гарантирует ли CucumberJVM порядок выполнения форматеров?

Также вы можете использовать StepLifecycleListener#beforeStepStop для добавления снимков экрана, это должно помочь.

PS StepLifecycleListener настраивается через Java SPI

Привет —

Следуя вашему совету, я изменил реализацию следующим образом:

Пользовательский класс для создания скриншотов после каждого шага:

public class AllureScreenshotPublisher implements StepLifecycleListener {
    private final AllureLifecycle allureLifecycle;

    public AllureScreenshotPublisher() {
        this.allureLifecycle = Allure.getLifecycle();
    }

    <strong i="8">@Override</strong>
    public void beforeStepStop(final StepResult result) {
        byte[] screenShot = ((TakesScreenshot) DriverManager.getDriver()).getScreenshotAs(OutputType.BYTES);
        allureLifecycle.addAttachment(LocalDateTime.now().format(DateTimeFormatter.ofPattern("dd-MMM-yy_hh:mm:ss")), "image/png", "png", screenShot);
    }

}

Я удалил плагин из классов бегунов:

@CucumberOptions(
glue = {"*.stepdefs"},
features = {"target/parallel/features/[CUCABLE:FEATURE].feature"},
plugin = {"io.qameta.allure.cucumber3jvm.AllureCucumber3Jvm"}
)

public class [CUCABLE:RUNNER] extends AbstractTestNGCucumberTests {

}

И поместите в src / resources / META-INF / services файл с именем _io.qameta.allure.listener.StepLifecycleListener_ с содержимым:

*****.allure.AllureScreenshotPublisher
(Заглушено родительское местоположение, но это местоположение правильное в проекте.

Теперь, когда я бегу, у меня вообще не делается скриншотов. Я что-то упускаю?

@ jsa34 только что проверил, у меня работает. Не могли бы вы проверить, что StepLifecycleListener загружается и выполняется?

PS Единственная проблема, которую я знаю до сих пор, заключается в том, что люди случайно создают каталог META-INF.services вместо вложенных каталогов при использовании IDEA, потому что он выглядит идентично

Вы были абсолютно правы — META-INF.services не является META-INF / services. Теперь в конце каждого шага вызываются скриншоты, но они не прикрепляются к шагам отчета. Мне пришлось добавить инициализирующий Allure.getLifecycle () в базовый тестовый класс, поскольку я больше не вызываю плагин, и иначе жизненный цикл не вызывается.

Я вижу все вложения в каталоге allure-results, но ничего не вижу в каталоге вложений созданного отчета allure.

(Обновленный класс бегуна:

import io.qameta.allure.Allure;

import cucumber.api.CucumberOptions;
import cucumber.api.testng.AbstractTestNGCucumberTests;

@CucumberOptions(
        glue = {"*****.stepdefs"},
        features = {"target/parallel/features/[CUCABLE:FEATURE].feature"},
        plugin = {"io.qameta.allure.cucumber3jvm.AllureCucumber3Jvm"}
        )

public class [CUCABLE:RUNNER] extends AbstractTestNGCucumberTests {

    public [CUCABLE:RUNNER]() {
        Allure.getLifecycle();
    }

}

Подсказка @ jsa34 : вместо этого вы можете использовать методы Allure.addAttachment , которые должны помочь избавиться от дополнительных вызовов Allure.getLifecycle() в конструкторе. Или удалите кеширование allureLifecycle из AllureScreenshotPublisher (вызовите Allure.getLifecycle().addAttachment(...) внутри метода beforeStepStop напрямую)

Я выполнил ваше предложение и получил те же результаты:

  1. Класс бегуна:
@CucumberOptions(
        glue = {"*****.stepdefs"},
        features = {"target/parallel/features/[CUCABLE:FEATURE].feature"},
        plugin = {"io.qameta.allure.cucumber3jvm.AllureCucumber3Jvm"}
        )

public class [CUCABLE:RUNNER] extends AbstractTestNGCucumberTests {
}
public class AllureScreenshotPublisher implements StepLifecycleListener {
    <strong i="12">@Override</strong>
    public void beforeStepStop(StepResult result) {
        byte[] screenShot = ((TakesScreenshot) DriverManager.getDriver()).getScreenshotAs(OutputType.BYTES);
        Allure.getLifecycle().addAttachment(LocalDateTime.now().format(DateTimeFormatter.ofPattern("dd-MMM-yy_hh:mm:ss")), "image/png", "png", screenShot);
    }
  1. Поместите в src / resources / META-INF / services файл с именем io.qameta.allure.listener.StepLifecycleListener с содержимым:
    * .allure.AllureScreenshotPublisher

РЕЗУЛЬТАТ:
И после тестового запуска я могу видеть все вложения в / target / allure-results, но когда Дженкинс создает отчет после тестового запуска, / allure-report / data / attachments / пуст.

Кстати, спасибо за помощь! Очень признателен — я просто в растерянности :(

какую версию cucumberjvm вы используете? Я думаю 4+?

Это может быть связано с параллельным запуском. Попробуйте обновить версию allure-cucumber3jvm до 2.8.1, попробуйте отключить параллельную конфигурацию и посмотрите, поможет ли это.

Я использую:

        <dependency>
            <groupId>io.qameta.allure</groupId>
            <artifactId>allure-cucumber3-jvm</artifactId>
            <version>2.8.1</version>
        </dependency>

        <dependency>
            <groupId>io.cucumber</groupId>
            <artifactId>cucumber-java</artifactId>
            <version>3.0.2</version>
        </dependency>

        <dependency>
            <groupId>io.cucumber</groupId>
            <artifactId>cucumber-core</artifactId>
            <version>3.0.2</version>
        </dependency>

А для отчетности в POM у меня есть:

    <reporting>
        <excludeDefaults>true</excludeDefaults>
        <plugins>
            <plugin>
                <groupId>io.qameta.allure</groupId>
                <artifactId>allure-maven</artifactId>
                <version>2.9</version>
                <configuration>
                    <reportVersion>2.8.1</reportVersion>
                    <allureDownloadUrl>
                        https://repo.maven.apache.org/maven2/io/qameta/allure/allure-commandline/%s/allure-commandline-%s.zip
                    </allureDownloadUrl>
                </configuration>
            </plugin>
        </plugins>
    </reporting>

больше нет идей. Не могли бы вы создать образец проекта для воспроизведения проблемы (в виде проекта Github с инструкциями, какие команды вы используете для запуска тестов / создания отчета). Нет необходимости настраивать браузеры и т. Д., Вы можете просто прикрепить строки

Конечно — я займусь этим :) Очень признателен за вашу помощь!

Привет,

Приносим извинения за задержку — только что вернулся из рождественских праздников.

Я загрузил образец проекта, который был запрошен:
Образец проекта

Дайте мне знать, если вам понадобится дополнительная информация.

Большое спасибо

PS — Я добавил кое-что в класс «AllureScreenshotPublisher», чтобы сделать его более понятным в журналах для отладки.

Всем привет,
Я хотел бы добавить, что я столкнулся с той же проблемой с allure-cucumber3jvm (2.8.1). После некоторого расследования я думаю, что проблема может быть из-за неправильной работы метода AllureLifecycle # stopStep (final String uuid) (он вызывается в последней строке метода AllureCucumber3Jvm#handlePickleStep ; если код для прикрепления снимков экрана вызывается до его вызова, все работает как положено).

@ jsa34 с учетом моих выводов выше, вы можете попробовать следующий обходной путь вместо использования beforeStepStop :

    <strong i="13">@Override</strong>
    public void afterStepUpdate(StepResult result) {
        if (result.getStatus() != PASSED && result.getStatus() != SKIPPED) {
            byte[] screenShot = ((TakesScreenshot) DriverManager.getDriver()).getScreenshotAs(OutputType.BYTES);
            Allure.getLifecycle().addAttachment(LocalDateTime.now().format(DateTimeFormatter.ofPattern("dd-MMM-yy_hh:mm:ss")), "image/png", "png", screenShot);
        }
    }

Привет!

Спасибо за отзыв, @scormaq !

Я попробовал ваше предложение, и похоже, что вы правы — afterStepUpdate успешно прикрепляет скриншоты.

Название метода beforeStepStop звучит так, как будто оно должно позволять добавлять снимки экрана, потому что вызов метода не должен останавливать шаг, так что, возможно, это ошибка?

Я собираюсь переопределить метод afterStepUpdate на данный момент, пока не услышу иное.

Большое спасибо!

Ага — итак, сейчас использую:

<strong i="6">@Override</strong>
    public void afterStepUpdate(StepResult result) {
            byte[] screenShot = ((TakesScreenshot) DriverManager.getDriver()).getScreenshotAs(OutputType.BYTES);
            Allure.getLifecycle().addAttachment(LocalDateTime.now().format(DateTimeFormatter.ofPattern("dd-MMM-yy_hh:mm:ss")), "image/png", "png", screenShot);
    }

Кажется, что это нормально для одного теста, но когда я запустил набор параллельно (25 потоков) вскоре после запуска, все 25 потоков начали регистрацию:


04 Jan 2019 14:53:51,330 ERROR [TestNG-test=Surefire test-15] AllureLifecycle:563 - Could not add attachment: no test is running

После того, как эти тесты в потоках очистятся и начнется следующий тест, это больше не будет проблемой, но те 25 тестов, которые были в потоках в то время, когда они были обнаружены в журналах, не имели прикрепленных снимков экрана. Не знаете, почему это происходит? Недостаточно памяти для JVM? Кажется странным, что это влияет на ВСЕ потоки на время теста, пока не будет выбран новый, и вскоре после того, как потоки будут запущены.

После тестирования еще немного:

threadCount = 1 … Счастлив :)
threadCount> 1 … Как описано выше

Я обновил проект, о котором упоминал ранее, с помощью примера:

Образец проекта

Теперь у него есть 2 тестовых примера.

Однако это не вызывает ошибок «Нет теста», которые мой проект, над которым я работаю, в журнале, но он не прикрепляет снимки экрана к одному из тестов после создания отчета.

Чтобы запустить его, используйте цели maven:


clean
install
site
-Dbrowser.name=ChromeRemote
-Dselenium.grid.url=http://GRIDLOCATION:4444/wd/hub
-DthreadCount=2

@ jsa34 вы используете какой-то сторонний механизм для параллельного запуска тестов Cucumber-JVM, я думаю, что это может быть корнем вашей проблемы. Cucumber-JVM предыдущей версии 4.x не может запускать тесты изначально параллельно, так же как и его привлекательный адаптер AllureCucumber3Jvm .

Вам нужно либо выяснить, как правильно интегрировать Allure в этот механизм, либо дождаться выпуска AllureCucumber4Jvm и переработать свой подход к распараллеливанию с помощью собственного механизма Cucumber-JVM.

В любом случае, на мой взгляд, проблема не в самом адаптере Allure. Единственная загадочная часть здесь для меня заключается в том, почему метод beforeStepStop() не работает должным образом в сочетании с AllureCucumber3Jvm . : мышление:

Спасибо за отзыв, @scormaq

Я не думаю, что проблема заключается в плагине Cucable — он просто генерирует файлы тестовых исполнителей, которые являются стандартными исполнителями классов TestNG в каталоге / target. Помощник по сборке указывает на каталог тестовых ресурсов, чтобы выбрать эти классы бегунов _IT.java из каталога / target, а не из каталогов проекта.

По сути, TestNG использует стандартные классы бегунов, расположенные в каталоге / target — он работал без проблем на allure v1 — стал проблемой только с обновлением v2.

Я постараюсь сделать более минимальный тестовый пример, чтобы исключить эту возможность, поскольку я, возможно, пропустил что-то, связанное с этим …

Я обновил проект, чтобы удалить плагин Cucable и помощник по сборке, как описано выше, и по-прежнему получаю те же проблемы …

image

image

Все еще пытаюсь отладить это и не знаю, где возникают проблемы …
Даже с явными классами бегунов для каждого теста, когда TestNG забирает _IT.classes, я получаю эти недостающие скриншоты … Как в моем основном проекте с ~ 300 тестами (примерно 20% отказов), так и в примере проекта: https: / /github.com/jsa34/selenium-java-allure-framework

Какие-либо предложения?

Мне не удалось заставить плагин Cucumber 3 и cucumberjvm3 allure работать нормально, поэтому я попробовал предложенный переход на Cucumber 4 с нативным распараллеливанием, и все хорошо — я обновлю упомянутый проект, чтобы отразить это, но я все еще не мудрее относительно того, почему C-JVM3 не работает — особенно при вызове метода beforeStepStop (). Я использую метод afterStepUpdate () сейчас

Не уверен насчет C-JVM3, я переключился с JVM1 на 4, и теперь, используя Cucumber, Maven, TestNG, Selenide и т. Д., Тоже были проблемы со скриншотами, пробовал то, что вы предлагали здесь, но безуспешно, помогло то, что
SelenideLogger.addListener («AllureSelenide», новый AllureSelenide (). Screenshots (true) .savePageSource (true));

в конструкторе по умолчанию для бегунов

Все еще пытаюсь отладить это и не знаю, где возникают проблемы …
Даже с явными классами бегунов для каждого теста, когда TestNG забирает _IT.classes, я получаю эти недостающие скриншоты … Как в моем основном проекте с ~ 300 тестами (примерно 20% отказов), так и в примере проекта: https: / /github.com/jsa34/selenium-java-allure-framework

Какие-либо предложения?

Есть ли шанс, что вы сможете поделиться демо-проектом? Пытаюсь добавить скриншоты с allure на огурце jvm4 с testng.

Привет, я выпустил фреймворк как проект с открытым исходным кодом, который мы используем внутри компании.
Мы исправили эту проблему, изменив этап отправки снимков экрана на метод afterStepUpdate.

Проект находится здесь: (документация требует доработки!)
https://gitlab.developers.cam.ac.uk/jsa34/selenium-java-framework

Надеюсь это поможет!

Я взял решение, упомянутое выше:

<strong i="7">@Override</strong>
    public void afterStepUpdate(StepResult result) {
            byte[] screenShot = ((TakesScreenshot) DriverManager.getDriver()).getScreenshotAs(OutputType.BYTES);
            Allure.getLifecycle().addAttachment(LocalDateTime.now().format(DateTimeFormatter.ofPattern("dd-MMM-yy_hh:mm:ss")), "image/png", "png", screenShot);
    }

У меня это отлично работает, даже с множеством тестов и множеством потоков.

Была ли эта страница полезной?

0 / 5 — 0 рейтинги

Best Java code snippets using io.qameta.allure.AllureLifecycle (Showing top 20 results out of 315)








public static void step(final String name, final Status status) {
  final String uuid = UUID.randomUUID().toString();
  getLifecycle().startStep(uuid, new StepResult().setName(name).setStatus(status));
  getLifecycle().stopStep(uuid);
}
@Override
public void testStarted(final Description description) {
  final String uuid = testCases.get();
  final TestResult result = createTestResult(uuid, description);
  getLifecycle().scheduleTestCase(result);
  getLifecycle().startTestCase(uuid);
}
@AfterReturning(pointcut = "anyMethod() && withStepAnnotation()")
public void stepStop() {
  getLifecycle().updateStep(s -> s.setStatus(Status.PASSED));
  getLifecycle().stopStep();
}








public void addAttachment(final String name, final String type,
             final String fileExtension, final InputStream stream) {
  writeAttachment(prepareAttachment(name, type, fileExtension), stream);
}
@Override
public void endOfScenarioLifeCycle(final Scenario scenario) {
  final StepUtils stepUtils = new StepUtils(currentFeature, currentScenario);
  synchronized (gherkinSteps) {
    while (gherkinSteps.peek() != null) {
      stepUtils.fireCanceledStep(gherkinSteps.remove());
    }
  }
  final String scenarioUuid = scenarioUuids.remove(scenario);
  lifecycle.stopTestCase(scenarioUuid);
  lifecycle.writeTestCase(scenarioUuid);
}
  final Status status = ResultsUtils.getStatus(result.getError())
      .orElse(Status.FAILED);
  lifecycle.updateStep(stepResult -> stepResult.setStatus(Status.FAILED));
  lifecycle.updateTestCase(scenarioUuid, scenarioResult ->
      scenarioResult.setStatus(status)
          .setStatusDetails(statusDetails));
  lifecycle.stopStep();
  break;
case PENDING:
  lifecycle.updateStep(stepResult -> stepResult.setStatus(Status.SKIPPED));
  lifecycle.updateTestCase(scenarioUuid, scenarioResult ->
      scenarioResult.setStatus(Status.SKIPPED)
          .setStatusDetails(statusDetails));
  lifecycle.stopStep();
  break;
case SKIPPED:
  lifecycle.updateStep(stepResult -> stepResult.setStatus(Status.SKIPPED));
  lifecycle.stopStep();
  break;
case PASSED:
  lifecycle.updateStep(stepResult -> stepResult.setStatus(Status.PASSED));
  lifecycle.stopStep();
  lifecycle.updateTestCase(scenarioUuid, scenarioResult ->
      scenarioResult.setStatus(Status.PASSED)
          .setStatusDetails(statusDetails));
@Override
public void onEvent(final LogEvent event) {
  lifecycle.getCurrentTestCase().ifPresent(uuid -> {
    final String stepUUID = UUID.randomUUID().toString();
    lifecycle.startStep(stepUUID, new StepResult()
        .setName(event.toString())
        .setStatus(Status.PASSED));
    lifecycle.updateStep(stepResult -> stepResult.setStart(stepResult.getStart() - event.getDuration()));
    if (LogEvent.EventStatus.FAIL.equals(event.getStatus())) {
      if (saveScreenshots) {
        lifecycle.addAttachment("Screenshot", "image/png", "png", getScreenshotBytes());
      }
      if (savePageHtml) {
        lifecycle.addAttachment("Page source", "text/html", "html", getPageSourceBytes());
      }
      lifecycle.updateStep(stepResult -> {
        final StatusDetails details = ResultsUtils.getStatusDetails(event.getError())
            .orElse(new StatusDetails());
        stepResult.setStatus(ResultsUtils.getStatus(event.getError()).orElse(Status.BROKEN));
        stepResult.setStatusDetails(details);
      });
    }
    lifecycle.stopStep(stepUUID);
  });
}
  protected void fireFixtureStep(final Match match, final Result result, final boolean isBefore) {
    final String uuid = md5(match.getLocation());
    final StepResult stepResult = new StepResult()
        .setName(match.getLocation())
        .setStatus(Status.fromValue(result.getStatus()))
        .setStart(System.currentTimeMillis() - result.getDuration())
        .setStop(System.currentTimeMillis());
    if (FAILED.equals(result.getStatus())) {
      final StatusDetails statusDetails = ResultsUtils.getStatusDetails(result.getError()).get();
      stepResult.setStatusDetails(statusDetails);
      if (isBefore) {
        final TagParser tagParser = new TagParser(feature, scenario);
        statusDetails
            .setMessage("Before is failed: " + result.getError().getLocalizedMessage())
            .setFlaky(tagParser.isFlaky())
            .setMuted(tagParser.isMuted())
            .setKnown(tagParser.isKnown());
        lifecycle.updateTestCase(scenario.getId(), scenarioResult ->
            scenarioResult.setStatus(Status.SKIPPED)
                .setStatusDetails(statusDetails));
      }
    }
    lifecycle.startStep(scenario.getId(), uuid, stepResult);
    lifecycle.stopStep(uuid);
  }
}
@Override
public void testFinished(final Description description) {
  final String uuid = testCases.get();
  testCases.remove();
  getLifecycle().updateTestCase(uuid, testResult -> {
    if (Objects.isNull(testResult.getStatus())) {
      testResult.setStatus(Status.PASSED);
    }
  });
  getLifecycle().stopTestCase(uuid);
  getLifecycle().writeTestCase(uuid);
}






public static <T> T step(final ThrowableContextRunnable<T, StepContext> runnable) {
  final String uuid = UUID.randomUUID().toString();
  getLifecycle().startStep(uuid, new StepResult().setName("step"));
  try {
    final T result = runnable.run(new DefaultStepContext(uuid));
    getLifecycle().updateStep(uuid, step -> step.setStatus(Status.PASSED));
    return result;
  } catch (Throwable throwable) {
    getLifecycle().updateStep(s -> s
        .setStatus(getStatus(throwable).orElse(Status.BROKEN))
        .setStatusDetails(getStatusDetails(throwable).orElse(null)));
    ExceptionUtils.sneakyThrow(throwable);
    return null;
  } finally {
    getLifecycle().stopStep(uuid);
  }
}







public void startStep(final String uuid, final StepResult result) {
  final Optional<String> current = threadContext.getCurrent();
  if (!current.isPresent()) {
    LOGGER.error("Could not start step: no test case running");
    return;
  }
  final String parentUuid = current.get();
  startStep(parentUuid, uuid, result);
}
@Override
public void testIgnored(final Description description) {
  final String uuid = testCases.get();
  testCases.remove();
  final TestResult result = createTestResult(uuid, description);
  result.setStatus(Status.SKIPPED);
  result.setStatusDetails(getIgnoredMessage(description));
  result.setStart(System.currentTimeMillis());
  getLifecycle().scheduleTestCase(result);
  getLifecycle().stopTestCase(uuid);
  getLifecycle().writeTestCase(uuid);
}





public void updateTestCase(final Consumer<TestResult> update) {
  final Optional<String> root = threadContext.getRoot();
  if (!root.isPresent()) {
    LOGGER.error("Could not update test case: no test case running");
    return;
  }
  final String uuid = root.get();
  updateTestCase(uuid, update);
}
  public static void stepFinish() {
    getLifecycle().stopStep(STEP_UUID_STACK.get().removeFirst());
  }
}





public void updateStep(final Consumer<StepResult> update) {
  final Optional<String> current = threadContext.getCurrent();
  if (!current.isPresent()) {
    LOGGER.error("Could not update step: no step running");
    return;
  }
  final String uuid = current.get();
  updateStep(uuid, update);
}






public void scheduleTestCase(final String containerUuid, final TestResult result) {
  storage.getContainer(containerUuid).ifPresent(container -> {
    synchronized (storage) {
      container.getChildren().add(result.getUuid());
    }
  });
  scheduleTestCase(result);
}
  private void handlePickleStep(final TestStepFinished event) {
    final StatusDetails statusDetails;
    if (event.result.getStatus() == Result.Type.UNDEFINED) {
      statusDetails =
          getStatusDetails(new PendingException("TODO: implement me"))
              .orElse(new StatusDetails());
      lifecycle.updateTestCase(getTestCaseUuid(currentTestCase), scenarioResult ->
          scenarioResult
              .setStatus(translateTestCaseStatus(event.result))
              .setStatusDetails(statusDetails));
    } else {
      statusDetails =
          getStatusDetails(event.result.getError())
              .orElse(new StatusDetails());
    }

    final TagParser tagParser = new TagParser(currentFeature, currentTestCase);
    statusDetails
        .setFlaky(tagParser.isFlaky())
        .setMuted(tagParser.isMuted())
        .setKnown(tagParser.isKnown());

    lifecycle.updateStep(getStepUuid(event.testStep), stepResult ->
        stepResult.setStatus(translateTestCaseStatus(event.result)));
    lifecycle.stopStep(getStepUuid(event.testStep));
  }
}
protected void fireCanceledStep(final Step unimplementedStep) {
  final StepResult stepResult = new StepResult();
  stepResult.setName(unimplementedStep.getName())
      .setStart(System.currentTimeMillis())
      .setStop(System.currentTimeMillis())
      .setStatus(Status.SKIPPED)
      .setStatusDetails(new StatusDetails().setMessage("Unimplemented step"));
  lifecycle.startStep(scenario.getId(), getStepUuid(unimplementedStep), stepResult);
  lifecycle.stopStep(getStepUuid(unimplementedStep));
  final StatusDetails statusDetails = new StatusDetails();
  final TagParser tagParser = new TagParser(feature, scenario);
  statusDetails
      .setFlaky(tagParser.isFlaky())
      .setMuted(tagParser.isMuted())
      .setKnown(tagParser.isKnown());
  lifecycle.updateTestCase(scenario.getId(), scenarioResult ->
      scenarioResult.setStatus(Status.SKIPPED)
          .setStatusDetails(statusDetails
              .setMessage("Unimplemented steps were found")));
}
private void handleTestCaseFinished(final TestCaseFinished event) {
  final String uuid = getTestCaseUuid(event.testCase);
  lifecycle.updateTestCase(
      uuid,
      testResult -> testResult.setStatus(translateTestCaseStatus(event.result))
  );
  final Optional<StatusDetails> details = getStatusDetails(event.result.getError());
  details.ifPresent(statusDetails -> lifecycle.updateTestCase(
      uuid,
      testResult -> testResult.setStatusDetails(statusDetails)
  ));
  lifecycle.stopTestCase(uuid);
  lifecycle.writeTestCase(uuid);
}
public static CompletableFuture<InputStream> addStreamAttachmentAsync(
    final String name, final String type, final String fileExtension, final Supplier<InputStream> body) {
  final String source = lifecycle.prepareAttachment(name, type, fileExtension);
  return supplyAsync(body).whenComplete((result, ex) -> lifecycle.writeAttachment(source, result));
}

Понравилась статья? Поделить с друзьями:
  • Error invoking spell
  • Error invoking method при запуске javafx
  • Error invoking method перевод
  • Error invoking method jlss exe
  • Error invoking method failed to launch jvm