Подключаемый модуль Cucable не запускает сценарии параллельно - PullRequest
0 голосов
/ 30 мая 2019

Я пытаюсь запустить сценарий параллельно, используя Trivago's Cucable Plugin. Чтобы проверить это, прежде чем реализовать мой проект, я загружаю этот проект.

https://github.com/trivago/cucable-plugin/tree/master/example-project

Я попытался, mvn clean verify, и он создал *IT.java файлы в целевой папке, но я заметил, что они не работают параллельно.

Откуда я знаю? Я добавил сон в каждое утверждение. Максимальный сон составляет 15 секунд, поэтому общая сборка должна составлять приблизительно 16 секунд, но она показывает 30 (сумма всех снов всех сценариев 2 + 5 + 15 + 8) секунд.

cucable.template

import cucumber.api.CucumberOptions;
import org.junit.runner.RunWith;

@RunWith(Cucumber.class)
@CucumberOptions(
        glue = "steps",
        features = {"target/parallel/features/[CUCABLE:FEATURE].feature"},
        plugin = {"json:target/cucumber-report/[CUCABLE:RUNNER].json"}
)
public class [CUCABLE:RUNNER] {
    // [CUCABLE:CUSTOM:comment]
}

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<!--suppress UnresolvedMavenProperty -->
<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>com.trivago.rta</groupId>
    <artifactId>cucable-test-project</artifactId>
    <version>1.5.1</version>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <maven.failsafe.plugin.version>3.0.0-M3</maven.failsafe.plugin.version>
        <maven.build.helper.plugin.version>3.0.0</maven.build.helper.plugin.version>
        <cucumber.version>4.2.6</cucumber.version>
        <maven.compiler.plugin.version>3.7.0</maven.compiler.plugin.version>

        <generated.runner.directory>${project.build.directory}/parallel/runners</generated.runner.directory>
        <generated.feature.directory>${project.build.directory}/parallel/features</generated.feature.directory>
    </properties>

    <dependencies>
        <dependency>
            <groupId>io.cucumber</groupId>
            <artifactId>cucumber-java</artifactId>
            <version>${cucumber.version}</version>
        </dependency>
        <dependency>
            <groupId>io.cucumber</groupId>
            <artifactId>cucumber-junit</artifactId>
            <version>${cucumber.version}</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>com.trivago.rta</groupId>
                <artifactId>cucable-plugin</artifactId>
                <version>${project.version}</version>
                <executions>
                    <execution>
                        <id>generate-test-resources</id>
                        <phase>generate-test-resources</phase>
                        <goals>
                            <goal>parallel</goal>
                        </goals>
                    </execution>
                </executions>
                <configuration>
                    <sourceRunnerTemplateFile>src/test/java/some/template/CucableJavaTemplate.java
                    </sourceRunnerTemplateFile>
                    <sourceFeatures>src/test/resources/features</sourceFeatures>

                    <generatedFeatureDirectory>${generated.feature.directory}</generatedFeatureDirectory>
                    <generatedRunnerDirectory>${generated.runner.directory}</generatedRunnerDirectory>

                </configuration>
            </plugin>
            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>build-helper-maven-plugin</artifactId>
                <version>${maven.build.helper.plugin.version}</version>
                <executions>
                    <execution>
                        <id>add-test-source</id>
                        <phase>generate-test-sources</phase>
                        <goals>
                            <goal>add-test-source</goal>
                        </goals>
                        <configuration>
                            <sources>
                                <source>${generated.runner.directory}</source>
                            </sources>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-failsafe-plugin</artifactId>
                <version>${maven.failsafe.plugin.version}</version>
                <executions>
                    <execution>
                        <id>Run parallel tests</id>
                        <phase>integration-test</phase>
                        <goals>
                            <goal>integration-test</goal>
                        </goals>
                    </execution>
                </executions>
                <configuration>
                    <forkCount>5</forkCount>
                    <testFailureIgnore>true</testFailureIgnore>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>${maven.compiler.plugin.version}</version>
                <configuration>
                    <source>8</source>
                    <target>8</target>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

1 Ответ

1 голос
/ 30 мая 2019

Ключевой момент:

  • Мы не будем смешивать прямые и переходные зависимости, особенно их версии! Это может привести к непредсказуемому исходу.
  • Нам нужно было бы использовать Cucumber-JVM v4.x.x специально для реализации параллельного выполнения без использования cucumber-jvm-parallel или подключаемого модуля cucable
  • Мы рассмотрим v4.2.6 для реализации

Параллельное выполнение огурцов через JUnit

Первый - Обновите POM.xml, указав правильный набор зависимостей io.cucumber.

 <dependency>
    <groupId>io.cucumber</groupId>
    <artifactId>cucumber-junit</artifactId>
    <version>4.2.6</version>
</dependency>

<dependency>
    <groupId>io.cucumber</groupId>
    <artifactId>cucumber-picocontainer</artifactId>
    <version>4.2.6</version>
</dependency>

Указать на заметку - Может быть проблема в том, что все в порядке, но тесты по-прежнему не выполняются параллельно, и это может произойти, если ваш pom.xml имеет прямую / транзитивную зависимость testng. Поскольку testNG заставляет Surefire игнорировать класс-оболочку JUnit. Если у вас была зависимость testng, то удалите зависимость TestNG, или вы можете взять вызов 2, определите 2 выполнения - для TestNG и JUnit и отключите один в соответствии с вашими потребностями.

Второе - Настройка класса Runner в соответствии с вашими требованиями

package com.jacksparrow.automation.suite.runner;

import org.junit.runner.RunWith;
import cucumber.api.CucumberOptions;
import cucumber.api.junit.Cucumber;

@RunWith(Cucumber.class)
@CucumberOptions(features = "classpath:features/functional/",
                     glue = {"com.jacksparrow.automation.steps_definitions.functional" },
                   plugin = { "pretty","json:target/cucumber-json/cucumber.json",
                            "junit:target/cucumber-reports/Cucumber.xml", "html:target/cucumber-reports"},
                   tags = { "@BAMS_Submitted_State_Guest_User" },
                   junit ={ "--step-notifications"},
                   strict = false,
                   dryRun = false,
               monochrome = true)

public class RunCukeTest {
}

Третий - Реализация плагина maven surefire, который фактически запускал бы тесты параллельно

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-surefire-plugin</artifactId>
    <version>3.0.0-M3</version>
    <configuration>
        <parallel>methods</parallel>
        <threadCount>2</threadCount>
        <reuserForks>false</reuserForks>
        <testFailureIgnore>true</testFailureIgnore>
        <includes>
            <include>**/*RunCukeTest.java</include>
        </includes>
    </configuration>
</plugin>

Четвертый - Реализация Hooks.java

import cucumber.api.Scenario;
import cucumber.api.java.Before;
import cucumber.api.java.After;

public class Hooks {

    @Before
    public void setUpScenario(String browser){
        //BaseSteps.getInstance().getBrowserInstantiation(browser); your browser setup method
    }
    @After
    public void afterScenario(Scenario scenario){
    // more code goes here  
    }
   }

Параллельное выполнение огурца через TestNG

Примечание: В приведенной ниже реализации мы будем читать параметр браузера из файла TestNG.xml

Первый - Обновите POM.xml, указав правильный набор зависимостей io.cucumber.

<dependency>
    <groupId>io.cucumber</groupId>
    <artifactId>cucumber-picocontainer</artifactId>
    <version>4.2.6</version>
</dependency>

<dependency>
    <groupId>io.cucumber</groupId>
    <artifactId>cucumber-testng</artifactId>
    <version>4.2.6</version>
</dependency>

Второй - Настроить класс TestNGRunner в соответствии с потребностями фреймворка

package com.jacksparrow.automation.suite.runner;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Parameters;
import com.jacksparrow.automation.steps_definitions.functional.BaseSteps;
import cucumber.api.CucumberOptions;
import cucumber.api.testng.AbstractTestNGCucumberTests;

@CucumberOptions(features = "classpath:features/functional/",
                     glue = {"com.jacksparrow.automation.steps_definitions.functional" },
                   plugin = { "pretty","json:target/cucumber-json/cucumber.json",
                            "junit:target/cucumber-reports/Cucumber.xml", "html:target/cucumber-reports"},
                   tags = { "@BAMS_Submitted_State_Guest_User" },
                   junit ={ "--step-notifications"},
                   strict = false,
                   dryRun = false,
               monochrome = true)

public class RunCukeTest extends Hooks {

} 

Третий - Реализация Hooks.java

import org.testng.annotations.BeforeClass;
import org.testng.annotations.Parameters;
import cucumber.api.testng.AbstractTestNGCucumberTests;

public class Hooks extends AbstractTestNGCucumberTests {

    @Parameters({ "browser" })
    @BeforeTest
    public void setUpScenario(String browser){
        //BaseSteps.getInstance().getBrowserInstantiation(browser); your browser setup method
    }
}

Четвертый - Обновите файл TestNG.xml в / src / test / resources / в соответствии с требованиями класса TestNGRunner и фреймворка.

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="Testng Cucumber Suite" parallel="tests" thread-count="2">
    <test name="SmokeTest">
        <parameter name="browser" value="chrome" />
        <classes>
            <class name="com.cvs.runner.TestSuiteRunner" />
        </classes>
    </test>
</suite>

Пятый - Вы должны быть полностью настроены на запуск пакета автоматизации с использованием TestNG любым из следующих способов

 -    Run TestNG.xml directly from IDE 
 -    From CMD - mvn test -Dsurefire.suiteXmlFiles=src/test/resources/testng.xml
 -    From POM.xml - Using Surefire Plugin

<profiles>
   <profile>
      <id>selenium-tests</id>
      <build>
         <plugins>
            <plugin>
               <groupId>org.apache.maven.plugins</groupId>
               <artifactId>maven-surefire-plugin</artifactId>
               <version>3.0.0-M3</version>
               <configuration>
                  <suiteXmlFiles>
                     <suiteXmlFile>src/test/resources/testng.xml</suiteXmlFile>
                  </suiteXmlFiles>
               </configuration>
            </plugin>     
         </plugins>
      </build>
   </profile>
</profiles>
...