Run Serenity Tests in GitLab CI/CD

Last Updated on

HOME

This tutorial explains the process to run the Serenity Tests in the GitLab pipeline. This is a very important step towards achieving CI/CD.

Table of Contents:

What is GitLab CI/CD Workflow?

GitLab automatically enables CI/CD pipelines for new projects. It’s just a matter of adding a new configuration file called .gitlab-ci.yml to your code repository with instructions for GitLab on what to run. So simply create the following basic workflow in your main repository directory and commit it:

The Serenity tests run on a headless browser in the pipeline.

What is a headless browser?

A headless browser is like any other browser but without a Head/GUI (Graphical User Interface).  A headless browser is used to automate the browser without launching the browser. While the tests are running, we could not see the browser, but we can see the test results coming on the console. The tests can run in the GitLab pipeline if the tests run in the headless mode.

Prerequisite:

  1. Serenity – 3.2.3
  2. Serenity Cucumber – 3.2.3
  3. JUnit Jupiter – 5.8.0
  4. JUnit Vintage – 5.8.0
  5. Java 11
  6. Maven – 3.8.1
  7. Selenium – 3.141.59
  8. Maven Compiler Plugin – 3.8.1
  9. Maven Surefire Plugin – 3.0.0-M5
  10. Maven FailSafe Plugin – 3.0.0-M5
  11. GitLab Account

Please refer to this tutorial to get the structure and code of the Serenity Project – Integration of Serenity with Cucumber and JUnit5.

GitLab Section

Step 1 – Create a blank project in GitLab

To know, how to create a blank new project in GitLab, please refer to this tutorial.

Step 2 – Push the project from the local repository to GitLab Repository

To know, how to push the changes in GitLab, please refer to this tutorial.

Step 3 – Create a .gitlab-ci.yml file in the project in GitLab

There are many ways to create a new file in GitLab. One of the ways is to create a file as shown in the below image.

It is a YAML file where you configure specific instructions for GitLab CI/CD. In the .gitlab-ci.yml, we can define:

  • The scripts you want to run.
  • Other configuration files and templates you want to include.
  • Dependencies and caches.
  • The commands you want to run in sequence and those you want to run in parallel.
  • The location to deploy your application to.
  • Whether you want to run the scripts automatically or trigger any of them manually.

image: markhobson/maven-chrome
 
stages:
  - test
 
variables:
  MAVEN_OPTS: "-Dmaven.repo.local=.m2/repository"
 
test:
  stage: test
  allow_failure: true
 
# Run the tests  
  script:
    - echo "Executing BDD scenarios with maven"
    - mvn clean verify
 
# Store artifacts
  artifacts:
    when: always
    name: "Serenity Report"
    paths:
    - target/site/*
    expire_in: 24 h

Image – markhobson/maven-chrome is used in this test. It is a docker image for Java automated UI tests.

This command lets the pipeline continue running subsequent jobs, even if the previous job is failed.

allow_failure: true

The below command is used to execute the tests from Maven in the docker image.

mvn clean verify

The below command means that the artifact should be generated every time the pipeline is run, irrespective of the fact if the job is successful or failed.

artifacts:
    when: always

The below command provides the name of the artifact. If this is not used, then the artifacts file is named artifacts, which becomes artifacts.zip when downloaded.

artifacts:
    name: "Serenity Report"

The below command provides the path of the files that should be present in the artifact.

artifacts:
    paths:
    - target/site/*

Pipeline configuration begins with jobs. Jobs are the most fundamental element of a  .gitlab-ci.yml file.

Jobs are:

  • Defined with constraints stating under what conditions they should be executed.
  • Top-level elements with an arbitrary name and must contain at least the script clause.
  • Not limited in how many can be defined.

Jobs can output an archive of files and directories. This output is known as a job artifact. The expire_in keyword determines how long GitLab keeps the job artifacts. Here, it shows 24 hrs to retain the artifacts.

Step 4 – Run the tests in the GitLab pipeline

Now, when a new change is committed, a pipeline kicks off and it runs all the tests.

Step 5 – Check the status of the pipeline

Once the Status of the pipeline changes to either failed or passed, that means the tests are already executed.

As you can see, the Status is passed, its green colour. This means all the tests present in the test suite are executed and passed. If any test fails in the test suite, the final execution status will be brown. The reason for the brown colour is we have mentioned allow_failure: true.

Below is the execution status report in the GitLab pipeline.

As I have added an artifact also in the .gitalb-ci.yml, which is highlighted in the image. This artifact creates a folder with the name “Serenity_Report” and the reports in this folder come from the path /target/site. This artifact gives us the option to download the reports or browse the report. This report will be available for 24 hours only as mentioned in the gitlab-ci.yml.

Step 6 – Download the report

Once, will click on the download button, it will download “Serenity_Report.zip”. Unzip the folder and it looks like something as shown below:

Example of Index.html

Example of Serenity Summary Report

Congratulations. This tutorial has explained the steps to run Serenity tests in GitLab CI/CD. Happy Learning!!

Run Robot Framework Tests in GitLab CI/CD

Last Updated On

HOME

This tutorial walks you through the process of running Robot Framework tests in GitLab pipelines. This is a very important step in achieving CI/CD. Ideally, tests should be run after each change (minor/major) before the latest change is merged into the master branch. Let’s assume that 100 changes are merged into the master branch a day and tests are run every time before deployment. In this case, there is no QA manually starting 100 tests a day. Now, what should be done to overcome this problem. Now add a test to your GitLab pipeline. Adding a test stage to your pipeline automatically runs the tests when you run the pipeline. 

Table of Contents

  1. What is GitLab CI/CD Workflow?
  2. What is a headless browser?
  3. Prerequisite
  4. Implementation Steps:
    1. Create a new Project
    2. Create 2 new directories in the new project
    3. Create Test Files
    4. Create Resources file for each page
    5. Execute the tests
  5. GitLab Section
    1. Create a blank project in GitLab
    2. Push the project from local repository to Gitlab Repository
    3. Create a .gitlab-ci.yml file in the project in GitLab
    4. Run the tests in the GitLab pipeline
    5. Check the status of the pipeline
    6. Download the report

What is GitLab CI/CD Workflow?

Once the proposed changes are built, then push the commits to a feature branch in a remote repository that’s hosted in GitLab. The push triggers the CI/CD pipeline for your project. Then, GitLab CI/CD runs automated scripts (sequentially or in parallel) to build as well as to test the application. After a successful run of the test scripts, GitLab CI/CD deploys your changes automatically to any environment (DEV/QA/UAT/PROD). But if the test stage is failed in the pipeline, then the deployment is stopped.

To use GitLab CI/CD, we need to keep 2 things in mind:

a) Make sure a runner is available in GitLab to run the jobs. If there is no runner, install GitLab Runner and register a runner for your instance, project, or group.

b) Create a .gitlab-ci.yml file at the root of the repository. This file is where CI/CD jobs are defined.

The Selenium tests run on a headless browser in the pipeline.

What is a headless browser?

A headless browser is like any other browser but without a Head/GUI (Graphical User Interface).  A headless browser is used to automate the browser without launching the browser. While the tests are running, we could not see the browser, but we can see the test results coming on the console.

Prerequisite

  1. Install Python
  2. Install PIP
  3. Install Robot Framework
  4. Install Robot framework Selenium Library
  5. Install PyCharm IDE
  6. GitLab Account

Implementation Steps:

Step 1 – Create a new Project

Step 1.1 – Open PyCharm and create a new project. Go to File and select New Project from the main menu.

Step 1.2 – Choose the project location. Click the Browse button next to the Location field and specify the directory for your project.

Deselect the Create a main.py welcome script checkbox because you will create a new Python file for this tutorial.

Click on the Create Button.

Step 1.3 – A new dialog will appear asking to Open the project using any one of the given options. I have selected New Window as I like to have separate windows for each project.

Below is the image of the new project created in PyCharms.

Step 2 – Create 2 new directories in the new project

Right-Click on the project, select New->Directory, and provide the name as TestCases and Resources

Step 3 – Create Test Files

This directory contains multiple test case files consisting of test steps. 

Right-click on the new directory select New File and provide the name LoginPageTests.robot and ForgetPasswordTests.robot as shown below:

Below is the code for LoginPageTests.robot

*** Settings ***
Documentation       Tests to login to Login Page
Library     SeleniumLibrary
Test Setup      Open the Browser with URL
Test Teardown   Close Browser Session
Resource       ../Resources/GenericResources.robot
Resource       ../Resources/LoginResources.robot
Resource      ../Resources/DashboardResources.robot

*** Test Cases ***

Validate Unsuccessful Login using invalid credentials

    LoginResources.Fill the login form     ${valid_username}       ${invalid_password}
    LoginResources.Verify the error message is correct


Validate Unsuccessful Login for blank username

     LoginResources.Fill the login form     ${blank_username}       ${valid_password}
     LoginResources.Verify the error message is displayed for username


Validate Unsuccessful Login for blank password

     LoginResources.Fill the login form     ${valid_username}       ${blank_password}
     LoginResources.Verify the error message is displayed for password


Validate successful Login

    LoginResources.Fill the login form     ${valid_username}       ${valid_password}
    DashboardResources.Verify Dashboard page opens

Below is the code for ForgetPasswordTests.robot

*** Settings ***
Documentation       Tests to validate Forgot Your Password Page functionality
Library     SeleniumLibrary
Test Setup      Open the Browser with URL
Test Teardown   Close Browser Session
Resource       ../Resources/GenericResources.robot
Resource       ../Resources/LoginResources.robot
Resource      ../Resources/ForgetPasswordResources.robot


*** Test Cases ***

Validate Reset Password Functionality

    LoginResources.Go to Forgot Your Password Page
    ForgetPasswordResources.Verify Forgot Your Password Page opens
    ForgetPasswordResources.Fill the Forgot Password Page
    ForgetPasswordResources.Verify the message

Validate Cancel Functionality

    LoginResources.Go to Forgot Your Password Page
    ForgetPasswordResources.Verify Forgot Your Password Page opens
    ForgetPasswordResources.Cancel the Reset Password
    ForgetPasswordResources.Verify that Login Page is displayed

Step 4 – Create a Resource file for each page

It maintains the files which contain page elements as well as corresponding keywords. 

Right-click on the new directory select New File and provide the name as LoginResources.robot, DashboardResources.robot, GenericResources.robot, and ForgetPasswordResources.robot as shown below:

GenericResources.robot contains the keywords that are common to all the tests, like opening of the browser or closing of the browser.

*** Settings ***
Documentation    A resource file with reusable keywords and variables.
Library     SeleniumLibrary

*** Variables ***
${valid_username}     Admin
${valid_password}       admin123
${invalid_username}     1234
${invalid_password}     45678
${blank_username}
${blank_password}
${url}      https://opensource-demo.orangehrmlive.com/web/index.php/auth/login
${browser_name}      Chrome

*** Keywords ***

Open the Browser with URL
    Open Browser   ${url}    headlesschrome
    Maximize Browser Window
    Set Selenium Implicit Wait    5

Close Browser Session
    Close Browser

Below is the code for LoginResources.robot

*** Settings ***
Documentation        All the page objects and keywords of landing page
Library     SeleniumLibrary

*** Variables ***
${login_error_message}      css:.oxd-alert-content--error
${dashboard_title}       css:.oxd-topbar-header-breadcrumb-module
${missing_username_error_message}    xpath://*[@class='oxd-form']/div[1]/div/span
${missing_password_error_message}   xpath://*[@class='oxd-form']/div[2]/div/span
${forgot_password_link}   xpath://div[@class='orangehrm-login-forgot']/p

*** Keywords ***

Fill the login form
    [Arguments]    ${username}      ${password}
   Input Text    css:input[name=username]   ${username}
   Input Password    css:input[name=password]   ${password}
   Click Button    css:.orangehrm-login-button


Verify the error message is correct
    Element Text Should Be    ${login_error_message}    Invalid credentials


Verify the error message is displayed for username
     Element Text Should Be    ${missing_username_error_message}      Required

Verify the error message is displayed for password
      Element Text Should Be    ${missing_password_error_message}      Required

Go to Forgot Your Password Page
    Click Element      ${forgot_password_link}

Below is the code for DashboardResources.robot

*** Settings ***
Documentation        All the page objects and keywords of Dashboard page
Library     SeleniumLibrary

*** Variables ***
${dashboard_title}       css:.oxd-topbar-header-breadcrumb-module

*** Keywords ***

Verify Dashboard page opens
    Element Text Should Be    ${dashboard_title}      Dashboard

Below is the code for ForgetPasswordResources.robot

*** Settings ***
Documentation       All the page objects and keywords of Forget Password page
Library     SeleniumLibrary

*** Variables ***
${forgot_page_title}       css:.orangehrm-forgot-password-title
${username}     css:.oxd-input--active
${reset_btn}     css:.orangehrm-forgot-password-button--reset
${cancel_btn}    css:.orangehrm-forgot-password-button--cancel
${reset_message}      xpath://div[@class='orangehrm-card-container']/h6
${login_page_title}   xpath://*[@class='orangehrm-login-slot']/h5

*** Keywords ***

Verify Forgot Your Password Page opens
    Element Text Should Be    ${forgot_page_title}      Reset Password

Fill the Forgot Password Page
   Input Text        ${username}     abc@gmail.com
   Click Button    ${reset_btn}

Verify the message
    Element Text Should Be    ${reset_message}      Reset Password link sent successfully

Cancel the Reset Password
    Click Button    ${cancel_btn}

Verify that Login Page is displayed
    Element Text Should Be    ${login_page_title}       Login

All the below-mentioned keywords are derived from SeleniumLibrary. The functionality of keywords mentioned above:

1. Create Webdriver − The keyword creates an instance of Selenium WebDriver.

2. Go To – This keyword navigates the current browser window to the provided url.

3. Maximize Browser Window – This keyword maximizes the current browser window.

4. Set Selenium Implicit Wait – This keyword sets the implicit wait value used by Selenium.

5. Input Text − This keyword is used to type the given text in the specified textbox identified by the locator name:username.

6. Input Password – This keyword is used to type the given text in the specified password identified by the locator name:password.

The difference compared to Input Text is that this keyword does not log the given password on the INFO level.

7. Click button – This keyword is used to click the button identified by the locator. In this case, it is “Login” button.

8. Element Text Should Be – This keyword is used to verify that the current page contains the exact text identified by the locator. Here, we are checking the exact text “Invalid Credentials”.

These keywords are present in SeleniumLibrary. To know more about these keywords, please refer to this document – https://robotframework.org/SeleniumLibrary/SeleniumLibrary.htm.

To run this script, go to the command line and go to directory tests.

Step 5 – Execute the tests

We need the below command to run the Robot Framework script.

robot .

The output of the above program is

GitLab Section

Step 6 – Create a blank project in GitLab

To know, how to create a blank new project in GitLab, please refer to this tutorial.

Step 7 – Push the project from the local repository to the Gitlab Repository

To know, how to push the changes in GitLab, please refer to this tutorial.

Step 8 – Create a .gitlab-ci.yml file in the project in GitLab

There are many ways to create a new file in GitLab. One of the ways is to create a file as shown in the below image.

It is a YAML file where you configure specific instructions for GitLab CI/CD. In the .gitlab-ci.yml, we can define:

  • The scripts you want to run.
  • Other configuration files and templates you want to include.
  • Dependencies and caches.
  • The commands you want to run in sequence and those you want to run in parallel.
  • The location to deploy your application to.
  • Whether you want to run the scripts automatically or trigger any of them manually.

Below is the sample pipeline.

stages:
  - test

image: ppandiyan/robotframework

run-tests:
  stage: test
  script:
    - robot --outputdir testOutput .
  artifacts:
    paths:
      - testOutput
    expire_in: 1 day

Image – ppandiyan/robotframework is used in this test. This docker file contains headlesschrome, headlessfirefox and Python2.7.

This gitlab-ci.yml has only 1 stage – a test that contains the command to run the tests as well as also create an artifact that contains all the surefire reports which can be saved as Test Evidence.

Step 9 – Run the tests in the GitLab pipeline

Now, when a new change is committed, a pipeline kicks off and it runs all the tests.

Step 10 – Check the status of the pipeline

Once the Status of the pipeline changes to either failed or passed that means the tests are already executed.

Let us see the logs of the execution it shows that all the tests are passed here.

As I have added an artifact also in the gitalb-ci.yml, which is highlighted in the image. This artifact creates a folder with the name “testOutput” and the folder contains reports, logs as well as output files. This artifact gives us the option to download the reports or browse the report. This report will be available for 1 day only as mentioned in the gitlab-ci.yml.

Step 11 – Download the report

Once, will click on the download button, it will download “report.zip”. Unzip the folder and it looks like something as shown below:

Example of Report.html

Example of Log.html

Congratulations. This tutorial has explained the steps to run Robot Framework tests in GitLab CI/CD. Happy Learning!!

Jenkins GitLab Integration

HOME

The previous tutorial has explained how to install it onto a Windows 10 system and create a Maven or Gradle project in Jenkins. Jenkins and GitLab are two powerful tools on their own, but what about using them together? In this tutorial, learn about the benefits of a Jenkins GitLab integration and how to set up the integration on your own.

What is GitLab?

GitLab is a web-based Git repository that provides free open and private repositories, issue-following capabilities, and wikis. It is a complete DevOps platform that enables professionals to perform all the tasks in a project—from project planning and source code management to monitoring and security. Additionally, it allows teams to collaborate and build better software.

What is Jenkins?

Jenkins is a well-known open-source tool that aids in the implementation of Continuous Integration (CI) and Continuous Deployment/Continuous Delivery (CD) processes by automating parts of the software development pipeline such as building, testing, and deployment.

Jenkins Version Used – 2.361.2

In this version of Jenkins, Git Plugin is already installed. If the Git Plugin is not installed, then follow the below steps to add Git Plugin in Jenkins.

Step 1: Open your dashboard.

Click on the Manage Jenkins button on your Jenkins dashboard:

Step 2: Select Manage Plugins.

Click on the Manage Jenkins. Choose Manage Plugins.

Step 3:  Add Git Plugin

On the Plugins Page, go to the Available option.

  1. Select the GIT Plugin
  2. Click on Install without restart. The plugin will take a few moments to finish downloading depending on your internet connection, and will be installed automatically.
  3. You can also select the option Download now and Install after the restart button. In which plugin is installed after the restart
  4. You will be shown a “No updates available” message if you already have the Git plugin installed.

In my case, Git Plugin is already installed, so you can’t see it in the Available Plugin.

Step 4: Verify Git Plugin is installed

Once the plugins have been installed,
Go to Manage Jenkins on your Jenkins dashboard. You will see your plugins listed among the rest.

How to Integrate Jenkins With GitLab

Step 1: Create a new project using the Maven project plugin.

  1. Give the Name of the project.
  2. Click on the Maven project. 
  3. Click on the OK button.

In the General section, enter the project description in the Description box.

Click on create new jobs.

Enter the item name, select the job type, and click OK. We shall create a Maven project as an example.

Step 2: Describe the project in the description section

In the General section, enter the project description in the Description box.

Step 3 – Source Code Management section

You will see a Git option under Source Code Management if your Git plugin has been installed in Jenkins.

Enter the Git repository URL to pull the code from GitHub. Enter the credentials to log in to GitLab.

I have already set up the credentials to log in to GitLab. Click on the Add button and select Jenkins.

Add the username and password used to log in to GitLab. Click on the “Add” button.

Note:- Please make sure that Git is installed on your local machine. To install Git on your local machine, go to this tutorial – How to install Git on Windows 10.

Step 4: Build Management

Go to the Build section of the new job.

  1. In the Root POM textbox, enter pom.xml
  2. In the Goals and options section, enter “clean test

Step 5: Select “Publish TestNG Results” from “Post Build Actions

Scroll down to “Post Build Actions” and click on the “Add Post Build Actions” drop-down list. Select “Publish TestNG Results“. 

Enter TestNG XML Report Pattern as “**target/surefire-reports/testng-results.xml” and click on the “Save” button.

We have created a new project Git_Demo” with the configuration to run TestNG Tests and also to generate TestNG Reports after execution using Jenkins.

Step 6: Execute the tests

Let’s execute it now by clicking on the “Build Now” button. 

Right-click on Build Number (here in my case it is #2) and click on Console Output to see the result.

Step 7: View the TestNG Report

Once the execution is completed, we could see a link to view “TestNG Results“.

Click on the TestNG Results. It displays the summary of the tests.

If you want to check the execution history, then click on the shown link.

This way, we could integrate Git in Jenkins.

Congratulations on making it through this tutorial and hope you found it useful! Happy Learning!! Cheers!!

How to run Rest API Tests in GitLab CI/CD

HOME

This tutorial explains the process to run the Rest API Tests in the GitLab pipeline. This is a significant step towards achieving CI/CD. Ideally, the tests need to run after any change (minor/major) before merging the change to the master branch. Suppose there are 100 changes in a day, and any QA won’t want to start the tests manually 100 times in a day. So, now adding tests to the GitLab pipeline comes into the picture. We can add a test stage to the pipeline and the tests will run automatically when the pipeline run, or we can schedule the tests to run automatically every hour or day using GitLab pipeline.

Prerequisite:

  1. Rest Assured – 4.3.3
  2. Java 11
  3. Maven / Gradle
  4. TestNG /JUnit
  5. GitLab account

To use GitLab CI/CD, we need to keep 2 things in mind:-

a) Make sure a runner is available in GitLab to run the jobs. If there is no runner, install GitLab Runner and register a runner for your instance, project, or group.

b) Create a .gitlab-ci.yml file at the root of the repository. This file is where you define your CI/CD jobs.

Step 1 – Create a new Maven Project

Step 2 – Add dependencies to the project

<dependencies>
      
      <dependency>
         <groupId>org.testng</groupId>
         <artifactId>testng</artifactId>
         <version>7.4.0</version>
         <scope>test</scope>
      </dependency>
      
      <dependency>
         <groupId>io.rest-assured</groupId>
         <artifactId>rest-assured</artifactId>
         <version>4.3.3</version>
         <scope>test</scope>
      </dependency>
      
      <dependency>
         <groupId>org.json</groupId>
         <artifactId>json</artifactId>
         <version>20210307</version>
      </dependency>
   </dependencies>
   
<build>
    <plugins>
        
        <!-- Compiler plug-in -->
         <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.5.1</version>
            <configuration>
               <source>11</source>
               <target>11</target>
            </configuration>
         </plugin>

         <!-- Added Surefire Plugin configuration to execute tests -->
         <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-surefire-plugin</artifactId>
            <version>3.0.0-M5</version>
            <configuration>
               <suiteXmlFiles>
                  <suiteXmlFile>testng.xml</suiteXmlFile>
               </suiteXmlFiles>
            </configuration>
         </plugin>
      </plugins>
   </build>
</project>

It is needed to add maven-surefire plugin to run the TestNG tests through command line. To know more about this, please refer to this tutorial.

Step 3 – Create the Test Code to test the Rest API

Here, 2 tests are created. One of the tests gets all the employee data (GET) whereas another test creates an employee (POST).

import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;

import org.json.JSONObject;
import org.testng.annotations.Test;

import io.restassured.http.ContentType;

public class RestAPIDemo {

	@Test(description = "To get the details of employee with id 2", priority = 0)
	public void verifyUser() {

		// Given
		given()
				// When
				.when().get("http://dummy.restapiexample.com/api/v1/employee/2")
				
               // Then
				.then().statusCode(200).statusLine("HTTP/1.1 200 OK")
				
                // To verify booking id at index 2
				.body("data.employee_name", equalTo("Garrett Winters"))
				.body("message", equalTo("Successfully! Record has been fetched."));
	}

	@Test(description = "To create a new employee", priority = 1)
	public void createUser() {

		JSONObject data = new JSONObject();

		// Map<String, String> map = new HashMap<String, String>();

		data.put("employee_name", "APITest");
		data.put("employee_salary", "99999");
		data.put("employee_age", "30");

		// GIVEN
		given().baseUri("http://dummy.restapiexample.com/api").contentType(ContentType.JSON).body(data.toString())

				// WHEN
				.when().post("/v1/create")

				// THEN
				.then().statusCode(200).body("data.employee_name", equalTo("APITest"))
				.body("message", equalTo("Successfully! Record has been added."));

	}
}

Step 4 – Create testng.xml to run the tests through TestNG

Now, let’s create a testng.xml to run the TestNG tests. If JUnit is used instead of TestNG, then this step is not needed.

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "https://testng.org/testng-1.0.dtd">
<suite name="Suite">
  <test name="Test">
    <classes>
      <class name="com.example.RestAssured_TestNG_Demo.RestAPIDemo"/>
    </classes>
  </test> <!-- Test -->
</suite> <!-- Suite -->

Step 5 – Run the tests through the command line

Now, let us execute the tests through the command line. Go to the place where pom.xml of the project is placed and use the below command to run the tests. This step makes sure that all the tests are running as expected.

GitLab Section

Step 6 – Create a blank project in GitLab

Refer to this tutorial to create a new blank project – How to create a new project in GitLab.

Step 7 – Push the project from the local repository to GitLab Repository

Refer to this tutorial to push the changes – How to push new local GIT Repository to GitLab.

Step 8 – Create .gitlab-ci.yml file in the project in GitLab

It is a YAML file where you configure specific instructions for GitLab CI/CD. In the .gitlab-ci.yml, we can define:

  • The scripts you want to run.
  • Other configuration files and templates you want to include.
  • Dependencies and caches.
  • The commands you want to run in sequence and those you want to run in parallel.
  • The location to deploy your application.
  • Whether you want to run the scripts automatically or trigger any of them manually.

image: adoptopenjdk/maven-openjdk11

stages:
  - test

variables:
  MAVEN_OPTS: "-Dmaven.repo.local=.m2/repository"

test:
  stage: test
  allow_failure: true

# Run the tests
  script:
    - mvn $MAVEN_OPTS clean package
    - mvn compile test

# Store artifacts
  artifacts:
    when: always
    name: "report"
    paths:
    - target/surefire-reports/*
    expire_in: 1 h

Step 9 – Run the tests in the GitLab pipeline

Now, when a new change is committed, a pipeline kicks off and it runs all the tests.

Step 10 – Check the status of the pipeline

Once the Status of the pipeline changes to either failed or passed.. that means the tests are already executed. Here, the pipeline is passed with brown colour means that the execution of the test is completed with some failures.

I have added an artifact in the gitalb-ci.yml with the name “report”. This artifact creates a folder with the name “report” and the reports in this folder come from the path /target/surefire-reports. This artifact gives us an option to download the reports or browse the report. This report will be available for 1 hour only as mentioned in the gitlab-ci.yml.

Step 11 – Download the report

Click on the Download button and the report zip file is downloaded. Unzip the folder, and it contains all different types of surefire-reports.

Example of Emailable-Report.html

Example of Index.html

Congratulations. This tutorial has explained the steps to run Selenium tests in GitLab CI/CD. Happy Learning!!

Run Selenium Tests in GitLab CI/CD

Last Updated on

HOME

This tutorial explains the process to run the Selenium Tests in the GitLab pipeline. This is a very important step towards achieving CI/CD. Ideally, the tests need to run after any change (minor/major) before merging the latest change to the master branch. Suppose there are 100 changes merged to the master branch in a day. It is expected to run the tests every time before deployment. In this case, any QA won’t want to start the tests manually 100 times in a day. Now, what should be done to overcome this problem. Now, adding tests to the GitLab pipeline comes into the picture. We can add a test stage to the pipeline and the tests will run automatically when the pipeline run.

Table of Contents

  1. Prerequisite
  2. What is GitLab CI/CD Workflow?
  3. What is a headless browser?
  4. Implementation Steps
    1. Create a new Maven Project
    2. Add the dependencies to the POM.xml
    3. Create the Test Code
    4. Create testng.xml to run the tests
    5. Run the tests through command line
  5. GitLab Section
    1. Create a blank project in GitLab
    2. Push the project from local repository to Gitlab Repository
    3. Create a .gitlab-ci.yml file in the project in GitLab
    4. Run the tests in the GitLab pipeline
    5. Check the status of the pipeline
    6. Download the report

Prerequisite

  1. Selenium
  2. TestNG/JUnit (for Assertions)
  3. Java 11
  4. Maven/ Gradle
  5. GitLab Account

What is GitLab CI/CD Workflow?

Build the proposed changes. Then, push the commits to a feature branch. This branch should be in a remote repository that’s hosted in GitLab. The push triggers the CI/CD pipeline for your project. Then, GitLab CI/CD runs automated scripts (sequentially or in parallel) to build as well as to test the application. After a successful run of the test scripts, GitLab CI/CD deploys your changes automatically to any environment (DEV/QA/UAT/PROD). But if the test stage is failed in the pipeline, then the deployment is stopped.

After the implementation works as expected:

  • Get the code reviewed and approved.
  • Merge the feature branch into the default branch.
    • GitLab CI/CD deploys your changes automatically to a production environment.

To use GitLab CI/CD, we need to keep 2 things in mind:

a) Make sure a runner is available in GitLab to run the jobs. If there is no runner, install GitLab Runner and register a runner for your instance, project, or group.

b) Create a .gitlab-ci.yml file at the root of the repository. This file is where CI/CD jobs are defined.

The Selenium tests run on a headless browser in the pipeline.

What is a headless browser?

A headless browser is like any other browser, but without a Head/GUI (Graphical User Interface).  A headless browser is used to automate the browser without launching the browser. While the tests are running, we cannot see the browser. However, we can see the test results coming on the console.

To explain, I have created 2 Selenium tests and used TestNG for asserting the tests. The tests will run on a headless Chrome browser. One more thing to keep in mind is that when tests run on a headless Chrome browser, the window screen won’t be full screen. So, the screen needs to be maximized explicitly otherwise some of the tests would fail.

Implementation Steps

Step 1 – Create a new Maven Project

Step 2- Add the dependencies to the POM.xml

Add the below-mentioned dependencies that need to add to the project to the pom.xml in Maven Project.

 <dependencies>

        <dependency>
            <groupId>io.github.bonigarcia</groupId>
            <artifactId>webdrivermanager</artifactId>
            <version>5.1.0</version>
        </dependency>

        <dependency>
            <groupId>org.seleniumhq.selenium</groupId>
            <artifactId>selenium-java</artifactId>
            <version>3.141.59</version>
        </dependency>

        <dependency>
            <groupId>org.testng</groupId>
            <artifactId>testng</artifactId>
            <version>7.5</version>
            <scope>test</scope>
        </dependency>
                   
    </dependencies>
    <build>
     <plugins>
     
     <!--  Compiler Plugin -->
    
    <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.8.1</version>
        <configuration>
           <source>11</source>
           <target>11</target>
        </configuration>
    </plugin>
     
      <!--  Plugin used to execute tests -->
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-surefire-plugin</artifactId>
        <version>3.0.0-M5</version>
        <configuration>
          <suiteXmlFiles>
            <suiteXmlFile>testng.xml</suiteXmlFile>
          </suiteXmlFiles>
        </configuration>
      </plugin>
     </plugins>
  </build>
</project>

As explained in one of the previous tutorial, it is needed to add the maven-surefire-plugin to run the TestNG tests through the command line.

Step 3 – Create the Test Code

This is the BaseTest Class. The WebDriver is initialized here. It operates in headless mode and full screen. At the end, the WebDriver is closed.

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;

import io.github.bonigarcia.wdm.WebDriverManager;

public class BaseTest {
	
	WebDriver driver;
	
	@BeforeMethod
	public void beforeTests() {
        WebDriverManager.chromedriver().setup();
        ChromeOptions options=new ChromeOptions();
        options.setHeadless(true);
        options.addArguments("window-size=1920,1200");
        driver=new ChromeDriver(options);
        driver.get("https://opensource-demo.orangehrmlive.com/");
    }

	@AfterMethod
    public void afterTests() {
        driver.quit();
    }

}

There are 2 different pages that need to be tested – LoginPage and ForgetPasswordPage

LoginPage contains the tests to log in to the application. After successful login, the application moves to the next webpage – HomePage. You can see that BaseTest class is extended in both the Test classes.

import org.openqa.selenium.By;
import org.testng.Assert;
import org.testng.annotations.Test;

@Test
public class LoginPage extends BaseTest{
	
	@Test
	public void validCredentials() throws InterruptedException {

	        driver.findElement(By.name("txtUsername")).sendKeys("Admin");	        
	        driver.findElement(By.name("txtPassword")).sendKeys("admin123");
	        driver.findElement(By.id("btnLogin")).click();
	         String newPageText = driver.findElement(By.xpath("//*[@id='content']/div/div[1]/h1")).getText();
	        System.out.println("newPageText :" + newPageText);
	        Assert.assertEquals(newPageText,"Dashboard");

	}

}

ForgetPasswordPage

import org.openqa.selenium.By;
import org.testng.Assert;
import org.testng.annotations.Test;

@Test
public class ForgetPasswordPage extends BaseTest{
	
	@Test
	public void getHeading() {
		
		Thread.sleep(1000);
		driver.findElement(By.xpath("//*[@id='forgotPasswordLink']/a")).click();
		String heading = driver.findElement(By.xpath("//*[@id='content']/div[1]/div[2]/h1")).getText();
		System.out.println("Title : "+ heading );
		Assert.assertEquals(heading, "Forgot Your Password?");
	}
	
}

Step 4 – Create testng.xml to run the tests

Now, let’s create a testng.xml to run the TestNG tests. If JUnit is used instead of TestNG, then this step is not needed.

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "https://testng.org/testng-1.0.dtd">
<suite name="Suite">
  <test name="Test">
    <classes>
      <class name="org.example.DockerDemo.LoginPage"/>
      <class name="org.example.DockerDemo.ForgetPasswordPage"/>
    </classes>
  </test> <!-- Test -->
</suite> <!-- Suite -->

Step 5 – Run the tests through command line

Now, let us execute the tests through the command line. Go to the place where the pom.xml of the project is placed and use the below command to run the tests. This step makes sure that all the tests are running as expected.

mvn compile test

GitLab Section

Step 6 – Create a blank project in GitLab

To know, how to create a blank new project in GitLab, please refer to this tutorial.

Step 7 – Push the project from local repository to Gitlab Repository

To know, how to push the changes in GitLab, please refer to this tutorial.

Step 8 – Create a .gitlab-ci.yml file in the project in GitLab

There are many ways to create a new file in GitLab. One of the ways is to create a file as shown in the below image.

It is a YAML file where you configure specific instructions for GitLab CI/CD. In the .gitlab-ci.yml, we can define:

  • The scripts you want to run.
  • Other configuration files and templates you want to include.
  • Dependencies and caches.
  • The commands you want to run in sequence and those you want to run in parallel.
  • The location to deploy your application to.
  • Whether you want to run the scripts automatically or trigger any of them manually.
image: markhobson/maven-chrome

stages:
  - test

variables:
  MAVEN_OPTS: "-Dmaven.repo.local=.m2/repository"

test:
  stage: test
  allow_failure: true

# Run the tests  
  script:
    - mvn $MAVEN_OPTS clean package
    - mvn compile test

# Store artifacts
  artifacts:
    when: always
    name: "report"
    paths:
    - target/surefire-reports/*
    expire_in: 1 h

Image – markhobson/maven-chrome is used in this test. It is a docker image for Java automated UI tests.

This gitlab-ci.yml has only 1 stage. It is a test stage that contains the command to run the tests. It also creates an artifact that contains all the surefire reports. These reports can be saved as Test Evidence.

Step 9 – Run the tests in the GitLab pipeline

Now, when a new change is committed, a pipeline kicks off and it runs all the tests.

Step 10 – Check the status of the pipeline

Once the Status of the pipeline changes to either failed or passed.. that means the tests are already executed.

As you can see the Status is failed here which means that the execution is completed. Let us see the logs of the execution it shows that out of 2 tests, 1 test passed and 1 test failed. This shows that tests are running successfully in the GitLab pipeline.

As I have added an artifact also in the gitalb-ci.yml, which is highlighted in the image. This artifact creates a folder with the name “report” and the reports in this folder come from the path /target/surefire-reports. This artifact gives us the option to download the reports or browse the report. This report will be available for 1 hour only as mentioned in the gitlab-ci.yml.

Step 11 – Download the report

Once, will click on the download button, it will download “report.zip”. Unzip the folder and it looks like something as shown below:

Example of Emailable-Report.html

Example of Index.html

Congratulations. This tutorial has explained the steps to run Selenium tests in GitLab CI/CD. Happy Learning!!

How to pull changes from Remote Repository to Local Repository – git pull

HOME

The previous tutorial has explained about pushing the changes from Local GIT Repository to Remote GIT Repository. This tutorial explains the process of pulling the changes from Remote Repository to Local GIT Repository. I’ll use GitLab to make the changes.

What is git pull?

The git pull command fetches and downloads content from the remote repository and integrates changes into the local repository. The git pull command is called as the combination of git fetch followed by git merge.

This is my project in GitLab. If, you don’t have any project in GitLab, follow the below steps to create a GIT local Repository and push it to GitLab.

Step 1– To create a new Git local Repository, use git init. The details are mentioned in this tutorial – How to create a new Git Repository – git init Command.

Step 2 – To create a new project in GitLab, refer to this tutorial – How to create a new project in GitLab.

Step 3 – To push your GIT local repository to Gitlab, refer to this tutorial – How to push new local GIT Repository to GitLab.

Step 4 – Let’s add a new file in the Remote Repository directly using GitLab. Follow the steps shown below to add and commit a new .

Step 5 – This is a new file. I have provided name to this file as products.txt. Add the comment as commit message. Click the Commit changes button to commit this change.

Below image shows that new file – products.txt is committed to this project.

Step 6 – Go to the directory where local GIT Repository is saved. Right-click and click on Git Bash Here to open GitBash at that place.

Use the below command to see the list of files present in GIT Local Repository.

ls -a
git log

Type git log to see the list of commits present.

Step 7 – Type git pull command is used to pull the latest changes from Remote GIT Repository to local GIT Repository.

git pull origin master

This command says that pull the content from the “master” branch in the “origin” repo.

As the “git pull” command fetches and merges, we can see the newly added file named “products.txt” in my local repo.

Again use the below commands:

ls -a
git log

This shows that the new file – products.txt which was present in GitLab is now present in Git local Repository means latest change is pulled from GitLab to local Repository.

Congratulation!! We are able to pull the changes from Remote Repository to Local Repository. Happy Learning!!

How to install Git on Windows 10

HOME

This tutorial explains the steps to install Git on Windows 10.

Step 1 – To install Git, go to – Git (git-scm.com). I want to install Git on Windows, so can use highlighted option to install Git.

The latest version here is 2.34.1.

Step 2 – Save the Git.exe file.

Step 3 – Now open the installer you have downloaded and go through the installation process. Unless you know what you are doing, leave all settings to their defaults. Click the Next button.

Step 4 – Select the destination location where GIT will be installed. You can continue with the default location as shown below, or use the installation path suggested by Git. Click the Next button.

Step 5 – In this step, you need to select components to be installed. Apart from the pre-selected options, you may also want to select “Add a Git Bash Profile to Windows Terminal”. This can be useful later on, especially if you plan to use Visual Studio Code or other IDEs that have a built-in terminal window. Click the Next button.

Step 6 Select if you would like to GIT shortcut in the start menu. Click the Next button.

Step 7 – Select the default editor of GIT. I use Notepad++ as the default editor used by GIT.

Click the Next button.

Step 8 – Git hosting tools like GitHub or GitLab already use main as their default branch.

Click the Next button.

Step 9 – Click the Next button.

Step 10 – Click the Next button.

Step 11 – Select SSL/TLS library used by GIT to use for the HTTPS connection. Go with default selection and click the Next button.

Step 12 – Click the Next button.

Step 13 – Click the Next button.

Step 14 – Configure the default behaviour of the git pull command. Click the Next button.

Step 15 – Click the Next button.

Step 16 – Enable file system caching to boost performance, which is the default selection. Click the Next button.

Step 17 – Click the Install button.

Step 18 You will get the below screen after the successful installation of GIT. Click the Finish button. This wizard has also installed a new tool called Git Bash, a terminal alternative for cmd or Powershell.

From Git Bash or terminal of your choice, run the following command:-

git --version

You can also use Windows PowerShell as well.

We are done! Congratulations on making it through this tutorial and hope you found it useful! Happy Learning!!

How to create a new project in GitLab

HOME

In this tutorial, I will explain how we can create a new empty project in GitLab.

Implementation Steps

Step 1 – Login to GitLab using your username and password.

Step 2 – In your dashboard, click the blue New project button. This opens the New project page.

Step 3 – The New project page provides 4 options to select:

  1. Create a blank project.
  2. Create a project using one of the available project templates.
  3. Import a project from a different repository, if enabled on your GitLab instance.
  4. Run CI/CD pipelines for external repositories. 

As I have mentioned earlier, I want to create a new empty project, so I will select open 1 (Create a blank project).

Step 4 – A new page will open. Provide the following information on that page:

  • Project Name – Mention the name of your project in the Project name field – CucumberGradleDemo. You can’t use special characters, but you can use spaces, hyphens, underscores, or even emojis.

  • Project slug – When a name is added, the Project slug auto-populates. The path to your project is in the Project slug field. This is the URL path for your project that the GitLab instance uses. If the Project name is blank, it auto populates when you fill in the Project slug. If you want a different slug, input the project name first, then change the slug after.

  • Project description (optional)  – This field enables you to enter a description for your project’s dashboard, which helps others understand what your project is about. Though it’s not required, it’s a good idea to fill this in.

  • Visibility Level – Select the appropriate Visibility Level for your project.

  • Selecting the Initialize repository with a README option creates a README file so that the Git repository is initialized, has a default branch, and can be cloned.

Select the Create Project button.

Congratulations!!. We have just created a new and empty project in GitLab. Now you can clone this project and start working on it.

How to Export IntelliJ project to GitLab

HOME

What is GitLab?

GitLab is the open DevOps platform, delivered as a single application that spans the entire software development lifecycle. If you’re not using GitLab, your DevOps lifecycle is likely spread across any number of applications. These silos take overhead to integrate, manage, configure, and maintain, slowing down your team and your deployments. Moving to a single application will speed up your workflow and help you deliver better software, faster. To know more about GitLab, click here.

In this article, we will see how to push an existing project to GitLab using Eclipse IDE.

Implementation Steps

Step 1 – Go to Git at the top, select VCS ->VCS Oprations -> Create Git Repository.

This will convert the project to a Git project.

Step 2 – Go to Git option present at the top and then select “Commit” option.

Step 3 – This will show all the files which are uncommitted. Select the files you want to commit and mention a message in the below message box as “New project from IntelliJ to GitLab“. Click on the Commit button.

Step 4 – A window opens where we need to mention the location where the project should be pushed in GitLab.

Click the OK button. It will ask for credentials to the GitLab, provide them.

Step 5 – The below image shows that the latest code is moved to GitLab. Here, the origin branch is used to commit and pushed the changes. If we are using a local branch to commit and push the changes, then we need to create a merge request to merge the code of the new branch to the code of existing origin(master branch).

Congratulations on making it through this tutorial and hope you found it useful! Happy Learning!! Cheers!!

How to Export Eclipse projects to GitLab

HOME

What is GitLab?

GitLab is the open DevOps platform, delivered as a single application that spans the entire software development lifecycle. If you’re not using GitLab, your DevOps lifecycle is likely spread across any number of applications. These silos take overhead to integrate, manage, configure, and maintain, slowing down your team and your deployments. Moving to a single application will speed up your workflow and help you deliver better software, faster. To know more about GitLab, click here.

In this article, we will see how to push an existing project to GitLab using Eclipse IDE.

Implementation Steps

Step 1 – Go to GitLab and select the project which you want to clone. Click on the blue color “Clone” button and then copy the hyperlink as shown in the image. You can either Clone with SSH or Clone with HTTPS.

Step 2 – Open Eclipse IDE and right-click on the project you want to push and go to the Team ->Share project.

Step 3 – It will add the project to the given repository as shown below image. Select the Finish button.

As you can see, the given project is Git Repository. If the project is not GIT Repository, refer to this tutorial – How to create a new Git Repository  to convert the project in GIT Repository.

Step 4 – Again, Right-Click on the project and go to the Team ->commit.

Step 5 – Select the files you want to commit and click green color + sign or Drag and Drop the files from “Unstaged Changes to Staged Changes“.

This is how the stage files looks like as shown below.

Step 6 – Write the commit message in “Commit Message” and click “Commit and Push“.

Step 7 – Fill in the below details in this window and click the “Preview” button.

URI – This is the URL that we have cloned from GitLab in Step 1.
Host – gitlab.com
Repository path – the path of the project in GitLab (This is auto-populated after entering URI)

Authentication
User – Username of GitLab
Password – password of GitLab

Step 8 – A new window will open which provides the detail of the Destination location of the project. Click the “Preview” button.

Step 9 – Push to the new branch of GitLab Repository and click the Push button.

Step 10 – As this is a new project with a master branch, you can see the whole project migrated in GitLab. If we are not using the master branch, but the local branch, then we need to create a merge request to merge the latest changes in the already existing project in GitLab.

Cheers!!Congratulations on making it through this tutorial and hope you found it useful! Happy Learning!!