2016-03-23 2 views
0

У меня есть тест в Cucumber, который использует формат таблицы примеров. Могу ли я получить Огурцы для параллельной работы каждой строки таблицы.Огурцы - работающие параллельные сценарии

Сценарий Outline: e_5_1 Проверьте коды обличая суда на английском языке 2

Given I navigate to the customer portal search screen 
    When I enter DLN, NI and Postcode from row "<user_row>" and access Penalties and disqualifications 
    And click on the endorsement in order to confirm court description from rows "<row1>" to "<row2>" 
Then I Logout 

    Examples: 
    | user_row | row1  | row2  | 
    | 2  | 2  | 51  | 
    | 52  | 52  | 98  | 
    | 99  | 99  | 148  | 
    | 149  | 149  | 198  | 

Обычно, я бы сказал, запустить test.feature для номера строки и она будет перебирать каждую строку по одному за раз, или я мог бы укажите номер строки, в которой сидит строка таблицы.

Могу ли я заставить его одновременно запускать все 4 ряда строк параллельно?

Заранее спасибо

+0

всего несколько комментариев в стиле: сценарий будет читать лучше, если вы не используете идентификаторы, но вместо того, чтобы использовать реальные имена (имеет реализации шага сделать соответствующую Lookups). Шаг «Затем я выхожу» можно разместить на этапе «После» (см. Https://github.com/cucumber/cucumber/wiki/Hooks). –

ответ

1

Вы можете использовать плагин с открытым исходным кодом cucumber-jvm-parallel-plugin который имеет много преимуществ по сравнению с существующими решениями, но его только для Java. Доступен в мавена repository

<dependency> 
    <groupId>com.github.temyers</groupId> 
    <artifactId>cucumber-jvm-parallel-plugin</artifactId> 
    <version>2.2.0</version> 
    </dependency> 
  1. Прежде всего, необходимо добавить эту зависимость и плагин с требуемой конфигурацией в вашем пом файле проекта.

    <dependencies> 
        <dependency> 
        <groupId>com.github.temyers</groupId> 
        <artifactId>cucumber-jvm-parallel-plugin</artifactId> 
        <version>2.2.0</version> 
        </dependency> 
        <dependency> 
         <groupId>net.masterthought</groupId> 
         <artifactId>cucumber-reporting</artifactId> 
         <version>3.3.0</version> 
        </dependency> 
    </dependencies> 
    
    <plugin> 
        <groupId>com.github.temyers</groupId> 
        <artifactId>cucumber-jvm-parallel-plugin</artifactId> 
        <version>2.2.0</version> 
        <executions> 
        <execution> 
        <id>generateRunners</id> 
        <phase>generate-test-sources</phase> 
        <goals> 
         <goal>generateRunners</goal> 
        </goals> 
        <configuration> 
         <!-- Mandatory --> 
         <!-- comma separated list of package names to scan for glue code --> 
         <glue>foo, bar</glue> 
         <outputDirectory>${project.build.directory}/generated-test-sources/cucumber</outputDirectory> 
          <!-- The directory, which must be in the root of the runtime classpath, containing your feature files. --> 
          <featuresDirectory>src/test/resources/features/</featuresDirectory> 
          <!-- Directory where the cucumber report files shall be written --> 
          <cucumberOutputDir>target/cucumber-parallel</cucumberOutputDir> 
          <!-- comma separated list of output formats json,html,rerun.txt --> 
          <format>json</format> 
          <!-- CucumberOptions.strict property --> 
          <strict>true</strict> 
          <!-- CucumberOptions.monochrome property --> 
          <monochrome>true</monochrome> 
          <!-- The tags to run, maps to CucumberOptions.tags property you can pass ANDed tags like "@tag1","@tag2" and ORed tags like "@tag1,@tag2,@tag3" --> 
         <tags></tags> 
         <!-- If set to true, only feature files containing the required tags shall be generated. --> 
         <filterFeaturesByTags>false</filterFeaturesByTags> 
         <!-- Generate TestNG runners instead of default JUnit ones. --> 
         <useTestNG>false</useTestNG> 
         <!-- The naming scheme to use for the generated test classes. One of 'simple' or 'feature-title' --> 
         <namingScheme>simple</namingScheme> 
         <!-- The class naming pattern to use. Only required/used if naming scheme is 'pattern'.--> 
         <namingPattern>Parallel{c}IT</namingPattern> 
         <!-- One of [SCENARIO, FEATURE]. SCENARIO generates one runner per scenario. FEATURE generates a runner per feature. --> 
         <parallelScheme>SCENARIO</parallelScheme> 
         <!-- This is optional, required only if you want to specify a custom template for the generated sources (this is a relative path) --> 
         <customVmTemplate>src/test/resources/cucumber-custom-runner.vm</customVmTemplate> 
         </configuration> 
         </execution> 
        </executions> 
        </plugin> 
    
  2. Теперь добавьте ниже плагин чуть ниже выше плагин, который будет ссылаться на классы бегуна, сгенерированные плагином выше

    <plugin> 
         <groupId>org.apache.maven.plugins</groupId> 
         <artifactId>maven-surefire-plugin</artifactId> 
         <version>2.19</version> 
         <configuration> 
          <forkCount>5</forkCount> 
          <reuseForks>true</reuseForks> 
          <includes> 
           <include>**/*IT.class</include> 
          </includes> 
         </configuration> 
        </plugin> 
    
  3. Выше двух плагинов будет делать магию для испытания огурцов работает параллельно (если вы машина также имеют расширенную аппаратную поддержку).

  4. Строго предоставлено <forkCount>n</forkCount> здесь 'n' прямо пропорционально 1) Расширенная аппаратная поддержка и 2) доступные узлы, то есть зарегистрированные экземпляры браузера в HUB.

  5. Одним из основных и наиболее важных изменений являются вашим класс WebDriver должен быть СОВМЕСТНЫМИ и вы должны не реализовать метод driver.quit(), как закрывание заботиться путем выключения крючка.

    import cucumber.api.Scenario; 
    import cucumber.api.java.After; 
    import cucumber.api.java.Before; 
    import org.openqa.selenium.OutputType; 
    import org.openqa.selenium.WebDriver; 
    import org.openqa.selenium.WebDriverException; 
    import org.openqa.selenium.firefox.FirefoxDriver; 
    import org.openqa.selenium.support.events.EventFiringWebDriver; 
    
    public class SharedDriver extends EventFiringWebDriver { 
        private static WebDriver REAL_DRIVER = null; 
    
    
    
        private static final Thread CLOSE_THREAD = new Thread() { 
         @Override 
         public void run() { 
          REAL_DRIVER.close(); 
         } 
        }; 
    
        static { 
         Runtime.getRuntime().addShutdownHook(CLOSE_THREAD); 
        } 
    
        public SharedDriver() { 
         super(CreateDriver()); 
        } 
    
        public static WebDriver CreateDriver() { 
         WebDriver webDriver; 
         if (REAL_DRIVER == null) 
          webDriver = new FirefoxDriver(); 
         setWebDriver(webDriver); 
         return webDriver; 
        } 
    
        public static void setWebDriver(WebDriver webDriver) { 
         this.REAL_DRIVER = webDriver; 
        } 
    
        public static WebDriver getWebDriver() { 
         return this.REAL_DRIVER; 
        } 
    
        @Override 
        public void close() { 
         if (Thread.currentThread() != CLOSE_THREAD) { 
          throw new UnsupportedOperationException("You shouldn't close this WebDriver. It's shared and will close when the JVM exits."); 
         } 
         super.close(); 
        } 
    
        @Before 
        public void deleteAllCookies() { 
         manage().deleteAllCookies(); 
        } 
    
        @After 
        public void embedScreenshot(Scenario scenario) { 
         try { 
          byte[] screenshot = getScreenshotAs(OutputType.BYTES); 
          scenario.embed(screenshot, "image/png"); 
         } catch (WebDriverException somePlatformsDontSupportScreenshots) { 
          System.err.println(somePlatformsDontSupportScreenshots.getMessage()); 
         } 
        } 
    } 
    
  6. Учитывая вы хотите выполнить более 50 потоков, то есть же нет экземпляров браузера зарегистрированы в HUB, но концентратор умрет, если он не получает достаточное количество памяти поэтому, чтобы избежать этой критической ситуации вы должны начать ступицу -DPOOL_MAX = 512 (или больше), как указано в grid2 documentation.

    Really large (>50 node) Hub installations may need to increase the jetty threads by setting -DPOOL_MAX=512 (or larger) on the java command line.

    java -jar selenium-server-standalone-<version>.jar -role hub -DPOOL_MAX=512