|
| 1 | +package io.qameta.allure.selenide; |
| 2 | + |
| 3 | +import com.codeborne.selenide.WebDriverRunner; |
| 4 | +import com.codeborne.selenide.logevents.LogEvent; |
| 5 | +import com.codeborne.selenide.logevents.LogEventListener; |
| 6 | +import io.qameta.allure.Allure; |
| 7 | +import io.qameta.allure.AllureLifecycle; |
| 8 | +import io.qameta.allure.model.Status; |
| 9 | +import io.qameta.allure.model.StatusDetails; |
| 10 | +import io.qameta.allure.model.StepResult; |
| 11 | +import io.qameta.allure.util.ResultsUtils; |
| 12 | +import org.openqa.selenium.OutputType; |
| 13 | +import org.openqa.selenium.TakesScreenshot; |
| 14 | + |
| 15 | +import java.nio.charset.StandardCharsets; |
| 16 | +import java.util.UUID; |
| 17 | + |
| 18 | +/** |
| 19 | + * @author Artem Eroshenko. |
| 20 | + */ |
| 21 | +public class AllureSelenide implements LogEventListener { |
| 22 | + |
| 23 | + private final AllureLifecycle lifecycle; |
| 24 | + |
| 25 | + public AllureSelenide() { |
| 26 | + this(Allure.getLifecycle()); |
| 27 | + } |
| 28 | + |
| 29 | + public AllureSelenide(final AllureLifecycle lifecycle) { |
| 30 | + this.lifecycle = lifecycle; |
| 31 | + } |
| 32 | + |
| 33 | + @Override |
| 34 | + public void onEvent(final LogEvent event) { |
| 35 | + lifecycle.getCurrentTestCase().ifPresent(uuid -> { |
| 36 | + final String stepUUID = UUID.randomUUID().toString(); |
| 37 | + lifecycle.startStep(stepUUID, new StepResult() |
| 38 | + .withName(event.toString()) |
| 39 | + .withStatus(Status.PASSED)); |
| 40 | + |
| 41 | + lifecycle.updateStep(stepResult -> stepResult.setStart(stepResult.getStart() - event.getDuration())); |
| 42 | + |
| 43 | + if (LogEvent.EventStatus.FAIL.equals(event.getStatus())) { |
| 44 | + lifecycle.addAttachment("Screenshot", "image/png", "png", getScreenshotBytes()); |
| 45 | + lifecycle.addAttachment("Page source", "text/html", "html", getPageSourceBytes()); |
| 46 | + lifecycle.updateStep(stepResult -> { |
| 47 | + final StatusDetails details = ResultsUtils.getStatusDetails(event.getError()) |
| 48 | + .orElse(new StatusDetails()); |
| 49 | + stepResult.setStatus(Status.FAILED); |
| 50 | + stepResult.setStatusDetails(details); |
| 51 | + }); |
| 52 | + } |
| 53 | + lifecycle.stopStep(stepUUID); |
| 54 | + }); |
| 55 | + } |
| 56 | + |
| 57 | + |
| 58 | + private static byte[] getScreenshotBytes() { |
| 59 | + return ((TakesScreenshot) WebDriverRunner.getWebDriver()).getScreenshotAs(OutputType.BYTES); |
| 60 | + } |
| 61 | + |
| 62 | + private static byte[] getPageSourceBytes() { |
| 63 | + return WebDriverRunner.getWebDriver().getPageSource().getBytes(StandardCharsets.UTF_8); |
| 64 | + } |
| 65 | + |
| 66 | +} |
0 commit comments