Automation Testing Archives | Talent500 blog https://talent500.com/blog/category/automation-testing/ Fri, 20 Jun 2025 10:48:11 +0000 en-US hourly 1 https://wordpress.org/?v=6.7.1 https://talent500.com/blog/wp-content/uploads/sites/42/2025/01/favicon.ico Automation Testing Archives | Talent500 blog https://talent500.com/blog/category/automation-testing/ 32 32 How to Streamline Test Data Management with Amazon S3 in Test Automation https://talent500.com/blog/data-management-with-amazon-s3/ https://talent500.com/blog/data-management-with-amazon-s3/#respond Mon, 27 Nov 2023 11:44:03 +0000 https://talent500.com/blog/?p=39228 In the realm of test automation, the efficient management of test data stands as a cornerstone for assuring the dependability […]

The post How to Streamline Test Data Management with Amazon S3 in Test Automation appeared first on Talent500 blog.

]]>
In the realm of test automation, the efficient management of test data stands as a cornerstone for assuring the dependability and reproducibility of test scripts. It is imperative to underscore that test data occupies a central role in the triumph of a test automation solution. The precision and accessibility of test data wield a profound influence on the trustworthiness and efficiency of your automated tests.

Storing and efficiently managing extensive test data in a secure and scalable manner can indeed pose a significant challenge, but Amazon S3 (Simple Storage Service) offers a scalable & reliable solution. In this article, we will explore how to streamline test data management with Amazon S3 along with example code.

Before we discuss the steps, let’s try to understand the problem statement with existing Test Data Management.

Challenges with Existing Test Data Storage

Now, let’s explore the difficulties through a real-world scenario evaluation: “Managing Test Data for E-commerce Website Testing”

Scenario

Imagine yourself employed as an automation engineer at a well-known e-commerce website, where your team carries the responsibility of upholding the platform’s quality. The website consistently experiences updates and enhancements, highlighting the significance of comprehensive testing within the development procedure.

Challenges

In the beginning, your team stored test data using a traditional local storage server and shared folders, which brought about a range of challenges: 

Scalability: With the website’s expansion, the test data volume quickly surpassed the local server’s storage limits. 

Data Consistency: Every testing environment had its unique data set, making it tricky to maintain consistency across various testing phases (e.g., development, staging, and production). 

Data Access: Collaborative efforts were hindered as remote teams struggled to access and share data promptly. 

Version Control: Juggling different versions of test data and keeping tabs on changes became more error-prone. 

We can now tackle these challenges by integrating the Amazon S3 storage service into our test automation framework. Amazon S3 provides practically limitless storage space, allowing our team to handle large datasets without worrying about storage limitations. By using S3, we’ve set up a central repository for all our test data, ensuring that all teams work with the same dataset, no matter where they are located. First, let’s gain a better understanding of the Amazon S3 Service.

What is Amazon S3?

Amazon Simple Storage Service (Amazon S3) stands as a prominent cloud storage solution from Amazon Web Services (AWS). Its primary purpose is secure data storage and retrieval via the internet, offering remarkable scalability and dependability. Within Amazon S3, data is structured into “buckets,” where an array of data types can find their home. Whether it’s documents, images, videos, or application backups, Amazon S3 accommodates them. These data are represented as objects within the buckets, and each individual object can reach an impressive size of up to 5 terabytes.

By adopting Amazon S3 for test data management, your team overcame the challenges they faced with traditional storage methods. The centralised, scalable, and versioned data storage solution not only streamlined the testing process but also contributed to the overall quality of the e-commerce website by ensuring consistent and reliable test data across all testing environments.Apart form test data management, many teams also prefer to store the Test Reports & Artefacts in the S3 storage for ease of tracking and management. 

Steps to integrate Amazon S3 

Prerequisites:

  • Knowledge of Selenium WebDriver with Java
  • Amazon Web Services (AWS) account

Step 1: Setting Up Amazon S3

First, you need to create an Amazon S3 bucket to store your test data. Follow these steps:

  1. Log in to your AWS account.
  2. Open the AWS Management Console.
  3. Navigate to the S3 service. In the Search box type “S3” and the S3 storage service should be visible as shown in the below screenshot:
  4. Click “Create bucket” and follow the instructions to configure your bucket. The Create Bucket button should be in Orange and towards the left side of the page.

Important points while creating a bucket

When you create a bucket, you choose the bucket name and the AWS Region. Bucket names must be globally unique and follow bucket naming rules. After you create a bucket, you can’t change the bucket name or Region. Bucket ownership is not transferable. When you create a bucket, you can configure bucket properties and permissions. By default, S3 Block Public Access is turned on to prevent public access to your bucket.Apply the bucket owner enforced setting for Object Ownership to disable ACLs and take ownership of every object in your bucket, simplifying access management for your data. After you disable ACLs, access control for your data is based on policies.

Also refer the official document for more details : https://docs.aws.amazon.com/AmazonS3/latest/userguide/create-bucket-overview.html?icmpid=docs_s3_hp_create_bucket_page 

Step 2: Uploading Test Data to Amazon S3

You can use the AWS SDK for Java to upload test data to your S3 bucket. Here’s an example of how to do this:

import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3Client;
import com.amazonaws.services.s3.model.PutObjectRequest;
import java.io.File;

public class S3TestDataManager {
    private static final String accessKey = "YOUR_ACCESS_KEY";
    private static final String secretKey = "YOUR_SECRET_KEY";
    private static final String bucketName = "your-s3-bucket-name";

    public void uploadFileToS3(String filePath, String s3Key) {
        BasicAWSCredentials credentials = new BasicAWSCredentials(accessKey, secretKey);
        AmazonS3 s3Client = new AmazonS3Client(credentials);

        File file = new File(filePath);
        s3Client.putObject(new PutObjectRequest(bucketName, s3Key, file));
    }
}

Replace “YOUR_ACCESS_KEY”, “YOUR_SECRET_KEY”, and “your-s3-bucket-name” with your AWS access key, secret key, and S3 bucket name.

Step 3: Downloading Test Data from Amazon S3

To download test data from Amazon S3 in your Selenium test script, you can use the AWS SDK for Java as well. Here’s an example of how to do this:

import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3Client;
import com.amazonaws.services.s3.model.S3Object;
import com.amazonaws.services.s3.model.GetObjectRequest;
import java.io.File;

public class S3TestDataReader {
    private static final String accessKey = "YOUR_ACCESS_KEY";
    private static final String secretKey = "YOUR_SECRET_KEY";
    private static final String bucketName = "your-s3-bucket-name";

    public void downloadFileFromS3(String s3Key, String localFilePath) {
        BasicAWSCredentials credentials = new BasicAWSCredentials(accessKey, secretKey);
        AmazonS3 s3Client = new AmazonS3Client(credentials);

        S3Object s3Object = s3Client.getObject(new GetObjectRequest(bucketName, s3Key));
        File localFile = new File(localFilePath);

        s3Object.getObjectContent().transferTo(new FileOutputStream(localFile));
    }
}

This code will download the file specified by s3Key from your S3 bucket and save it to the localFilePath.

Step 4: Using Amazon S3 in Selenium Test Automation

Now that you have set up test data management with Amazon S3, you can seamlessly integrate it into your Selenium test automation scripts. Here’s an example of how to use test data stored in Amazon S3:

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class AmazonS3Test {
    public static void main(String[] args) {
        String s3Key = "path/to/test-data.txt";
        String localFilePath = "downloaded-test-data.txt";

        S3TestDataReader dataReader = new S3TestDataReader();
        dataReader.downloadFileFromS3(s3Key, localFilePath);

        // Your Selenium test script can now use the downloaded test data
        WebDriver driver = new ChromeDriver();
        // Your test automation logic here

        driver.quit();
    }
}

By following these steps, you can streamline test data management in your Selenium test automation using Amazon S3. Storing your test data in the cloud provides scalability, reliability, and accessibility for your automated tests. This approach can enhance your test data management and make your test scripts more robust.

Benefits of Using Amazon S3 for Test Automation?

In the context of test automation, using Amazon S3 as a central repository for your test data offers several compelling advantages:

  • Scalability: Amazon S3 is built to scale, making it an ideal choice for storing test data, which can grow over time. You can seamlessly accommodate increased data storage needs without worrying about infrastructure scaling or capacity planning.
  • Accessibility: Test data stored in Amazon S3 can be accessed from anywhere with an internet connection. This accessibility is especially useful for distributed teams or for running tests in different geographic locations.
  • Reliability: Amazon S3 is designed to be highly reliable, with built-in redundancy and data durability. Your test data is protected against data loss, ensuring your test scripts always have access to the required data.
  • Cost-Efficiency: Amazon S3 offers a cost-effective pay-as-you-go pricing model, which means you only pay for the storage you use. This can significantly reduce the overall cost of your test automation infrastructure.
  • Security: Amazon S3 provides various security features, such as access control lists (ACLs), bucket policies, and server-side encryption. You can control who has access to your test data and ensure it remains confidential and secure.
  • Integration: Amazon S3 seamlessly integrates with other AWS services and a wide range of programming languages, including Java. This allows you to easily incorporate it into your test automation framework, making it straightforward to upload, download, and manage test data.
  • Versioning and Metadata: Amazon S3 allows you to version your data and add custom metadata to objects. This feature can be useful when managing different versions of test data and tracking relevant information.
  • Backup and Recovery: Storing your test data in Amazon S3 provides a built-in backup solution. You can recover data in case of accidental deletion or data corruption, ensuring the integrity of your test assets.

Conclusion

In conclusion, Amazon S3 is an excellent choice for test automation because it offers a secure, scalable, and cost-effective way to manage your test data. By leveraging the capabilities of Amazon S3, you can streamline your test data management processes, improve the reliability of your test automation framework, and ensure that your tests have access to the necessary data, no matter where or when they are executed.

The post How to Streamline Test Data Management with Amazon S3 in Test Automation appeared first on Talent500 blog.

]]>
https://talent500.com/blog/data-management-with-amazon-s3/feed/ 0
Performance Testing Strategies: Load and Stress Testing Your Code https://talent500.com/blog/performance-testing-strategies/ https://talent500.com/blog/performance-testing-strategies/#respond Wed, 18 Oct 2023 09:43:00 +0000 https://talent500.com/blog/?p=39026 In the rapidly evolving landscape of software development, performance testing has become an integral part of the development lifecycle. Ensuring […]

The post Performance Testing Strategies: Load and Stress Testing Your Code appeared first on Talent500 blog.

]]>
In the rapidly evolving landscape of software development, performance testing has become an integral part of the development lifecycle. Ensuring that your application can handle the anticipated user load without compromising on performance or stability is paramount. Load and stress testing are two crucial methodologies that allow developers to assess how their code performs under varying conditions. This blog will dive deep into the concepts of load testing and stress testing. We will also explore comprehensive strategies to execute these methods effectively, and illustrate the process.

What is Load Testing?

Load testing involves subjecting your application to varying levels of user activity, allowing you to evaluate its performance under different loads. The primary objective is to identify potential performance bottlenecks, ascertain the application’s maximum capacity, and ensure that it can cater to the expected user base without experiencing significant degradation in performance or system crashes. Here’s an example.

Load Testing with Apache JMeter

java

import org.apache.jmeter.protocol.http.sampler.HTTPSamplerProxy;

import org.apache.jmeter.testelement.TestPlan;

import org.apache.jmeter.threads.ThreadGroup;

import org.apache.jmeter.util.JMeterUtils;

 

public class LoadTestExample {

    public static void main(String[] args) {

        JMeterUtils.setJMeterHome(“path_to_jmeter_folder”);

        

        TestPlan testPlan = new TestPlan(“Load Test Plan”);

        

        ThreadGroup threadGroup = new ThreadGroup();

        threadGroup.setNumThreads(100);

        threadGroup.setRampUp(10); // Gradual increase of users over 10 seconds

        

        HTTPSamplerProxy httpSampler = new HTTPSamplerProxy();

        httpSampler.setDomain(“your_app_domain.com”);

        httpSampler.setPath(“/endpoint”);

        

        threadGroup.addTestElement(httpSampler);

        testPlan.addTestElement(threadGroup);

        

        testPlan.run();

    }

}

Load testing provides insight into how your application’s performance changes under different workloads. It allows you to measure various performance metrics, such as response time, throughput, and server resource utilization. By analyzing these metrics, you can pinpoint performance bottlenecks, whether they’re related to code inefficiencies, database queries, or external service integrations.

Here’s one more example

Load Testing with Gatling

scala

 

import io.gatling.core.Predef._

import io.gatling.http.Predef._

class LoadTestGatlingExample extends Simulation {

    val httpConf = http.baseUrl(“http://your_app_domain.com”)

    val scn = scenario(“Load Test Scenario”)

        .exec(http(“request_1”).get(“/endpoint”))

    setUp(

        scn.inject(

            rampUsersPerSec(1) to 100 during (10 seconds), // Increase from 1 to 100 users in 10 seconds

            constantUsersPerSec(100) during (30 seconds) // Maintain 100 users for 30 seconds

        )

    ).protocols(httpConf)

}

What is Stress Testing?

Stress testing takes the assessment one step further to load testing by subjecting your application to an intense workload well beyond its expected capacity. The primary objective here is not just to determine the breaking point, but also to observe how your application behaves under extreme conditions, and whether it is capable of recovering gracefully instead of crashing outright. 

Let us illustrate with an example 

Stress Testing with Artillery

yaml

config:

  target: ‘http://your_app_domain.com’

  phases:

    – duration: 300

      arrivalRate: 50

scenarios:

  – flow:

      – get:

          url: ‘/endpoint’

The above Artillery code simulates a stress test scenario by gradually increasing the arrival rate of users over a duration of 300 seconds. This enables you to observe your application’s performance as it’s subjected to a growing influx of users. The arrivalRate parameter controls how many new users are introduced to the system per second.

Let us have a look at one more example.

Stress Testing with JUnit and Apache HttpClient

java

import org.apache.http.client.methods.HttpGet;

import org.apache.http.impl.client.CloseableHttpClient;

import org.apache.http.impl.client.HttpClients;

import org.junit.Test;

import java.io.IOException;

public class StressTestHttpClient {

    @Test

    public void stressTestEndpoint() throws IOException {

        CloseableHttpClient httpClient = HttpClients.createDefault();

        HttpGet httpGet = new HttpGet(“http://your_app_domain.com/endpoint”);

        

        for (int i = 0; i < 1000; i++) {

            httpClient.execute(httpGet);

        }

        

        httpClient.close();

    }

}

In this above example, a simple stress test is performed using JUnit and Apache HttpClient. It sends 1000 HTTP requests to the specified endpoint, simulating a sudden influx of requests to assess how well your application handles high stress levels.

Strategies for Effective Load and Stress Testing

When it comes to performance testing (both load testing and stress testing), here are a few strategies that can help.

Identify Key Scenarios

Before conducting any testing, you must identify the critical user scenarios that are representative of real-world interactions with your application. Focus on high-traffic areas and frequently used features.

Realistic Data and Usage

To achieve accurate results, utilize realistic data and emulate genuine user behavior patterns. This approach ensures that you uncover performance bottlenecks that might not be evident with synthetic data.

Gradual Ramp-Up

In load testing, it’s advisable to gradually increase the user load over time, also known as ramping up. This approach closely resembles how actual user traffic grows, allowing you to observe how the system responds to incremental load increases.

Spike Testing

Stress testing should include sudden spikes in user activity. These spikes simulate unexpected traffic surges and help you understand how your application recovers from such events. This is a crucial aspect of ensuring resilience.

Monitor and Analyze Metrics

Constantly monitor key performance metrics, such as response time, throughput, and error rates. Collecting and analyzing this data allows you to identify patterns, trends, and potential areas for improvement within your application.

Scalability Testing

To assess the scalability of your application, it’s essential to increase the load across various components, such as databases and APIs. This ensures that all parts of your system can handle increased demand without compromising performance.

Failover and Recovery Testing

Beyond performance, it’s vital to test your application’s ability to handle failures gracefully. Ensure that your application can seamlessly switch to backup systems and recover without significant disruption.

Conclusion

Load and stress testing are fundamental pillars of performance testing, helping developers deliver robust, high-performing applications. By implementing effective strategies and employing the right tools, you can identify bottlenecks, optimize performance, and create a reliable user experience. 

As your application evolves, it’s essential to continuously refine your testing approach to maintain the high standards of performance that your users expect. Performance testing is an ongoing process, and investing time in it early in the development cycle can save you from potential headaches in the long run. By combining effective load and stress testing methodologies, you can confidently release software that meets user expectations and withstands the challenges of the digital landscape.

The post Performance Testing Strategies: Load and Stress Testing Your Code appeared first on Talent500 blog.

]]>
https://talent500.com/blog/performance-testing-strategies/feed/ 0
Testing Workflows with Allure: Transforming Testing Workflows with Powerful Reporting https://talent500.com/blog/testing-workflows-with-allure/ https://talent500.com/blog/testing-workflows-with-allure/#respond Tue, 17 Oct 2023 09:17:52 +0000 https://talent500.com/blog/?p=38969 Allure Report is the utility that processes test results collected by a compatible test framework and produces an HTML report. […]

The post Testing Workflows with Allure: Transforming Testing Workflows with Powerful Reporting appeared first on Talent500 blog.

]]>
Allure Report is the utility that processes test results collected by a compatible test framework and produces an HTML report. Allure Report is indeed a powerful open-source tool designed to generate clear and concise test execution reports. It provides a detailed and visually appealing representation of test results, making it easier for teams to understand the test outcomes and identify issues.

Cypress is a popular JavaScript testing framework that is known for its ease of use and fast execution speed.Integration of Allure with Cypress can be used  to generate comprehensive and visually appealing reports of the test cases. Allure reports include detailed information about each test case, including its status, duration, steps, and screenshots.

About Allure Report?

Allure is an open-source framework designed for creating interactive and comprehensive test reports. It is commonly used in software testing to generate detailed and visually appealing reports for test execution results.

Allure provides a clear and concise way to represent test outcomes, making it easier for both technical and non-technical stakeholders to understand the test results.Allure reports allows everyone participating in the development process to extract maximum useful information from everyday execution of tests.

Why Allure Reports?

An open-source framework designed to create test execution reports that are clear to everyone in the team. From the dev/qa perspective Allure reports shorten common defect life cycle: test failures can be divided on bugs and broken tests, also logs, steps, fixtures, attachments, timings, history and integrations with TMS and bug-tracking systems can be configured, so the responsible developers and testers will have all information at hand.

Reasons why you use Allure reports

Below are some key reason why you choose Allure Reports

Clear Visualization:

  • Allure creates dynamic reports with eye-catching graphs, charts, and other graphical features.
  • Test results are provided in a way that is easy for stakeholders of both technical and non-technical backgrounds to understand.

Detailed Test Steps:

  • Each test step in Allure is well described, including the input data, anticipated findings, and actual results.
  • The clarity of test execution can be improved by including screenshots and logs related to each stage.

History and Trends:

  • You may compare current results with previous runs using Allure’s historical test execution data storage feature.
  • Teams may monitor the development of testing efforts over time by analysing historical patterns.

Automated Reports:

  • Allure reports may be created automatically as an integral part of Continuous Integration (CI) pipelines, ensuring that the most recent reports are accessible during each test run.
  • The reporting process is made simpler by integration with CI platforms, which also provide the development team with real-time feedback.

Support for Multiple Languages and Frameworks:

  • Programming languages supported by Allure include Java, Python, Ruby, and JavaScript.
  • It easily integrates with well-known testing frameworks like JUnit, TestNG, NUnit, and others.

Set-up Cypress

Installing Cypress

Below are the steps to install Cypress. However, you can go through this blog to get started with Cypress testing.

Step 1: Create a folder and Generate package.json.

  1. Create a project, naming it ‘talent500_Allure-Cypress’
  2. Use the npm init command to create a package.json file.

Step 2: Run the below command to install Cypress.

  1. In the project folder, run > npm install – save-dev cypress@11.2.0
  2. You can Cypress version 11.2.0 is reflected in package.json

 

Set-up Allure Reports

Step 1: Allure Installation

Enter the below commands in your command line to install allure

Using yarn: 

yarn add -D@shelex/cypress-allure-plugin 

Or

Using npm: 

npm i -D @shelex/cypress-allure-plugin 

npm install –save-dev mocha-allure-reporter allure-commandline

Step 2: Cypress Config File

Update Cypress Config File with below code under file  ‘cypress.config.js’

/// <reference types=“@shelex/cypress-allure-plugin” />

const { defineConfig } = require(“cypress”);

const allureWriter = require(“@shelex/cypress-allure-plugin/writer”);

module.exports = defineConfig({

e2e: {

setupNodeEvents(on, config) {

allureWriter(on, config);

return config;

}

}

});

Here’s a breakdown of what this above configuration file is doing:

  • <reference types=”@shelex/cypress-allure-plugin” /> : This line is a reference directive for TypeScript, indicating that the TypeScript compiler should include type definitions from the @shelex/cypress-allure-plugin package.
  • const { defineConfig } = require(“cypress”): Importing the defineConfig function from the Cypress package.
  • const allureWriter = require(“@shelex/cypress-allure-plugin/writer”):
  • Importing the allureWriter function from the @shelex/cypress-allure-plugin/writer module. This function is likely used to set up Allure reporting.
  • module.exports = defineConfig({ /* … */ }): Exporting a Cypress configuration object. Inside this object, you have an e2e property, which seems to be setting up a custom Node.js event called setupNodeEvents. This event likely hooks into Cypress’ test execution process.
  • setupNodeEvents(on, config) { /* … */ }: This is where you configure the setupNodeEvents event. The allureWriter function is passed the on and config objects. You’re using this event to set up the Allure reporting with Cypress.
  • allureWriter(on, config): This line invokes the allureWriter function, passing the on and config objects. The specifics of what this function does are determined by the @shelex/cypress-allure-plugin package. It’s likely responsible for integrating Allure reporting into your Cypress tests.
  • return config: Finally, the modified config object is returned. This ensures that any changes made within the setupNodeEvents function are applied to the overall Cypress configuration.

Step 3: Update index.js

Then register the command of allure plugin under the path cypress/support/index.js file

import ‘@shelex/cypress-allure-plugin’;

Step 4: Update package.json with below Script

{

“name”: “talent500_allure-cypress”,

“version”: “1.0.0”,

“description”: “”,

“main”: “index.js”,

“scripts”: {

“clean:folders”: “rm -R -f allure-report/* && rm -R -f allure-results/*”,

“cy:run-test”: “cypress run –env allure=true”,

“generate-allure:report”: “allure generate allure-results –clean -o allure-report && allure open allure-report”,

“tests”: “npm run clean:folders && npm run cy:run-test && npm run generate-allure:report”

},

“author”: “Kailash Pathak”,

“license”: “ISC”,

“devDependencies”: {

“@shelex/cypress-allure-plugin”: “^2.40.0”,

“allure-commandline”: “^2.24.1”,

“cypress”: “^11.2.0”,

“mocha-allure-reporter”: “^1.4.0”

}

}

Walkthrough of package.json file

Here’s a breakdown of the key information in this file:

  • Name: ‘talent500_allure-cypress’ – This is the name of your project or package.
  • Version: 1.0.0 – This indicates the version of your project. Versions are typically in the format of major.minor.patch.
  • Description: (empty) – A brief description of your project could be placed here.
  • Main: index.js – This specifies the entry point of your application (the main JavaScript file).
  • Scripts:
    • clean:folders: This script removes the contents of allure-report and allure-results folders.
    • cy:run-test: This script runs enable allure integration enabled.
    • generate-allure:report: This script generates an Allure report using the results from the tests.
    • tests: This is a custom script that runs in sequence: cleaning folders, running tests, and generating the Allure report.
  • Author: Kailash Pathak – The author of the project.
  • License: ISC – The type of license for your project. ISC is a permissive open source license similar to the MIT License.
  • DevDependencies: Inside this section we have placed all devDependenciesi.e Cypress (^11.2.0), Allure plugin for Cypress (^2.40.0), Allure commandline tool (^2.24.1), and Mocha Allure reporter (^1.4.0).

Step 2: Create Test Case

Let’s create a test case for 

  1. Open the URL https://talent500.com/auth/signin
  2. Enter Email  and Password
  3. Verify User should be logged in by verifying the text “PROFILE”
  4. Logout from the Application
  5. Verify text “Opportunities Favor The Bold” after logout

/// <reference types=“cypress” />

describe(“https://talent500.com/ , Login & Logout “, () => {

it(“Logs in successfully and verifies links in header”, () => {

cy.visit(“https://talent500.com/auth/signin”);

cy.get(‘[name=”email”]’).focus();

cy.get(‘[name=”email”]’).type(“applitoolsautomation@yopmail.com”);

cy.get(‘[name=”password”]’).focus();

cy.get(‘[name=”password”]’).type(“Test@123”);

cy.get(‘[type=”submit”]’).eq(1).click({ force: true });

cy.contains(“PROFILE”).should(“be.visible”);

cy.get(‘img[alt=”DropDown Button”]’).click({ force: true });

cy.contains(“Logout”).click();

cy.contains(“Opportunities favor the bold”).should(“be.visible”);

});

});

Step 3: Execute the test case

Lets run the command 

npm run tests

npm run tests

As we run the test case using the command  ‘npm run tests’ . You can see the below command start executing in terminal

“npm run clean:folders && npm run cy:run-test && npm run generate-allure:report”

Commands are run in below sequence

  1. First command ‘npm run clean:folders’ will clean the folders (allure:report,allure:results ) if already created
  2. Second command ‘npm run cy:run-test’ run the test cases from e2e folders
  3. Third command ‘npm run generate-allure:report’ will generate the allure report

In below screenshot you can see one test case found for execution and test case execution is started 

In below screenshot you can see test  cases are executed successfully 

FInally you can see see below command run and generate the allure report 

‘allure generate allure-results –clean -o allure-report && allure open allure-report’


Step 4: Fail Scenario 

Add some more test cases and failed some of the test cases. In the below screenshot you can see I have added one more test case and initially  both test cases are passing

Fail Case :

Let’s fail one of the test cases to see how the report looks when test cases fail. In the below report you can see in the First test case we have a total of 3 test cases. Among 3 test cade 1 test case is failing and 2 test case are passing


Wrapping up

Integrating Allure with Cypress elevates the quality of test reporting by generating comprehensive, visually appealing summaries of test cases.  Allure reports provide a thorough analysis of each test, including crucial information like status, execution time, specific actions taken throughout the test, and supplemental screenshots. This degree of detail gives stakeholders and testers a thorough understanding.

By leveraging this integration, development teams gain valuable insights into the performance and reliability of their applications, fostering continuous improvement and ensuring the delivery of high-quality software products

The post Testing Workflows with Allure: Transforming Testing Workflows with Powerful Reporting appeared first on Talent500 blog.

]]>
https://talent500.com/blog/testing-workflows-with-allure/feed/ 0
Implementing Unit Testing: Boosting Code Reliability and Maintainability https://talent500.com/blog/implementing-unit-testing/ https://talent500.com/blog/implementing-unit-testing/#respond Fri, 13 Oct 2023 09:07:41 +0000 https://talent500.com/blog/?p=38872 In the ever-evolving world of software development, delivering high-quality code that stands the test of time is a non-negotiable requirement. […]

The post Implementing Unit Testing: Boosting Code Reliability and Maintainability appeared first on Talent500 blog.

]]>
In the ever-evolving world of software development, delivering high-quality code that stands the test of time is a non-negotiable requirement. One of the most powerful tools in a developer’s arsenal for achieving this goal is unit testing. This practice involves testing individual components, or units, of code in isolation to ensure their correctness. In this blog, we will talk about the importance of unit testing, its numerous benefits, and provide practical examples to help you implement unit testing effectively in your projects. Let us get started.

The Importance of Unit Testing

Unit testing serves as the foundation for creating robust and dependable software applications. By breaking down your code into manageable units, you can meticulously test each piece in isolation. This approach offers several key advantages:

Early Bug Detection: Unit tests help identify bugs at the earliest stages of development, making it easier and more cost-effective to fix issues.

Code Quality Enhancement: Writing unit tests encourages developers to think critically about various use cases, leading to cleaner and more maintainable code.

Confidence in Refactoring: With unit tests in place, you can confidently refactor or modify your code without the fear of introducing new bugs.

Documentation: Well-written unit tests serve as living documentation, describing how different components of your code should function.

Regression Prevention: Regularly running unit tests guards against regressions, ensuring that new code changes don’t inadvertently break existing functionality.

Setting Up the Testing Environment

To start with unit testing, you need to establish the right testing environment. This involves selecting a suitable testing framework based on your programming language. 

For instance, if you’re working with Python, the built-in unittest framework or the third-party library pytest are excellent choices. Java developers often turn to JUnit.

Once you’ve chosen a framework, integrate it into your project and structure your codebase to include a dedicated folder for tests.

Let us dive into the practical side of unit testing by creating a simple Python function and writing a corresponding unit test.

Imagine you have a MathOperations module with a function that calculates the sum of two numbers.

python

# math_operations.py

def add(a, b):

    return a + b

Now, let’s write a unit test for this function using the unittest framework

python

# test_math_operations.py

import unittest

from math_operations import add

class TestMathOperations(unittest.TestCase):

    def test_add(self):

        result = add(2, 3)

        self.assertEqual(result, 5)

if __name__ == ‘__main__’:

    unittest.main()

In this example, the TestMathOperations class inherits from unittest.TestCase and contains a test method named test_add. 

Within this method, we call the add function with the arguments 2 and 3, and then use the assertEqual method to check if the result is equal to 5.

Testing Strategies and Best Practices

Writing effective unit tests involves adopting certain strategies and best practices.

Test One Thing at a Time: Each test should focus on verifying a single aspect of a component’s behavior. This keeps tests concise and easier to understand.

Use Descriptive Test Names: Choose descriptive names for your test methods that clearly indicate what is being tested.

Employ Assertions: Assertions are the backbone of unit tests. Use them to compare the expected output with the actual output.

Explore Edge Cases: Ensure your tests cover edge cases and boundary conditions to confirm your code behaves as expected in various scenarios.

Isolate Tests: Prevent test interference by ensuring that each test is independent and doesn’t rely on the state left by other tests.

Handling Dependencies with Mocking and Stubbing

When testing components that interact with external dependencies, such as databases or APIs, you often need to isolate those dependencies. This is where mocking and stubbing come into play.

Mocking

Mocking involves creating mock objects that simulate the behavior of dependencies without the overhead of actual implementation. For instance, when testing a database query, you can use a mock database connection to control the responses.

Stubbing

Stubbing is a subset of mocking, where you define specific behaviors for certain method calls. When testing code that sends network requests, you can stub the response to avoid actual network interactions.

Let’s consider an example where you’re testing a function that sends an HTTP request:

python

# my_module.py

import requests

def fetch_data(url):

    response = requests.get(url)

    return response.text

To test this function without making actual network requests, you can use a library like responses to stub the HTTP response:

python

# test_my_module.py

import unittest

import responses

from my_module import fetch_data

class TestMyModule(unittest.TestCase):

    @responses.activate

    def test_fetch_data(self):

        url = ‘http://example.com/data’

        responses.add(responses.GET, url, body=’Mocked response’)

        result = fetch_data(url)

        self.assertEqual(result, ‘Mocked response’)

if __name__ == ‘__main__’:

    unittest.main()

In this example, the responses library is used to stub the HTTP response, allowing you to control the behavior of the external dependency during testing.

Code Coverage Analysis

While writing unit tests is essential, it is equally important to assess the coverage of your tests. It involves calculating how much of your code is exercised by the tests. Tools like coverage for Python can help you measure code coverage and identify areas that need more testing.

However, achieving 100% code coverage doesn’t guarantee bug-free code, but it does provide a strong indication of your tests’ thoroughness.

Test-Driven Development (TDD)

Test-Driven Development (TDD) is a software development methodology that emphasizes writing tests before writing the actual code. The TDD process typically involves three steps:

  • Writing a failing test
  • Writing the minimum code necessary to pass the test
  • Refactoring the code for clarity and maintainability.

Let’s walk through an example of TDD using the Fibonacci sequence:

Write the Failing Test

python

# test_fibonacci.py

import unittest

from fibonacci import get_fibonacci

class TestFibonacci(unittest.TestCase):

    def test_get_fibonacci(self):

        result = get_fibonacci(5)

        self.assertEqual(result, [0, 1, 1, 2, 3])

Write the Minimum Code to Pass

python

# fibonacci.py

def get_fibonacci(n):

    fibonacci_sequence = [0, 1]

    for i in range(2, n):

        next_number = fibonacci_sequence[i – 1] + fibonacci_sequence[i – 2]

        fibonacci_sequence.append(next_number)

    return fibonacci_sequence

Refactor for Clarity and Maintainability

python

# fibonacci.py (refactored)

def get_fibonacci(n):

    fibonacci_sequence = [0, 1]

    while len(fibonacci_sequence) < n:

        next_number = fibonacci_sequence[-1] + fibonacci_sequence[-2]

        fibonacci_sequence.append(next_number)

    return fibonacci_sequence

In this example, test driven developemnt guided the development process, resulting in code that is tested and maintains the expected behavior.

Continuous Improvement and Maintenance

Unit testing is an ongoing effort that requires regular maintenance. As your codebase evolves, update your tests to accommodate changes and new features. Remove or modify tests that are no longer relevant.

It is imperative for you to regularly review your tests to ensure they remain effective and relevant. A test suite that doesn’t evolve with your application can become a liability rather than an asset.

Conclusion

In the dynamic world of software development, unit testing stands as a pillar of excellence. By embracing unit testing, you create a safety net that catches bugs, facilitates refactoring, and boosts code quality. The benefits of unit testing extend beyond mere error detection; they empower you to build applications that are reliable, maintainable, and adaptable.

Unit testing is a journey, not a destination. As you continue to refine your testing strategies, explore advanced techniques, and contribute to the ever-growing knowledge base of software testing, you solidify your position as a proficient and quality-conscious developer.

So, whether you’re a seasoned developer or just starting on your coding journey, make unit testing an integral part of your development process. With every passing line of code and every successful test, you’re enhancing your skills and contributing to a software landscape built on the foundation of quality.

The post Implementing Unit Testing: Boosting Code Reliability and Maintainability appeared first on Talent500 blog.

]]>
https://talent500.com/blog/implementing-unit-testing/feed/ 0
How to Automate SOAP API using Rest Assured with real-time examples ? https://talent500.com/blog/how-to-automate-soap-api/ https://talent500.com/blog/how-to-automate-soap-api/#respond Fri, 13 Oct 2023 08:58:40 +0000 https://talent500.com/blog/?p=38869 Introduction SOAP (Simple Object Access Protocol) is a protocol used for exchanging structured information in the implementation of web services. […]

The post How to Automate SOAP API using Rest Assured with real-time examples ? appeared first on Talent500 blog.

]]>
Introduction

SOAP (Simple Object Access Protocol) is a protocol used for exchanging structured information in the implementation of web services. It employs XML for message format definition and depends on transport protocols like HTTP, SMTP, TCP, or others for message transmission.

Discover the robust capabilities of Rest Assured, a potent Java library that streamlines SOAP web service testing. Follow our detailed guide and practical examples to automate SOAP API tests efficiently. Enhance your testing efficiency and guarantee the dependability of your web services through this comprehensive tutorial. Initiate your journey today and optimise your API automation workflow with Rest Assured.

In this blog post, we will explore the distinctions between REST and SOAP, followed by a comprehensive guide on automating SOAP APIs using Rest Assured.

REST vs SOAP

CharacteristicSOAP (Simple Object Access Protocol)REST (Representational State Transfer)
ProtocolProtocol-based, usually over HTTP, SMTP, or others.Architectural style using HTTP primarily.
StandardsStrict standards and specifications.Flexible and not bound to strict standards.
Message FormatXML is the standard message format, but it can also use JSON.Supports various formats, including XML, JSON, and more.
VerbosityTypically verbose due to XML.Lightweight and less verbose, often using JSON.
CommunicationSupports request-response and request-only patterns.Supports multiple communication methods, including CRUD.
Error HandlingWell-defined error handling using fault messages.Typically relies on HTTP status codes for error handling.
State ManagementSupports stateful communication using WS-Security, WS-ReliableMessaging, etc.Stateless, each request is independent.
SecurityBuilt-in security through WS-Security, often complex.Relies on underlying protocols (HTTPS) and additional measures.
PerformanceCan be slower due to XML parsing and verbosity.Generally faster due to simplicity and lightweight nature.
CachingLimited caching options.Supports caching through HTTP headers.
ScalabilityScalability can be a challenge in some cases.Easier to scale due to statelessness and simplicity.
UsageOften used in enterprise-level applications and services.Widely used in web services, APIs, and web applications.

SOAP Example

<SOAP-ENV:Envelope xmlns:SOAP-ENV=”http://www.w3.org/2003/05/soap-envelope” xmlns:ns1=”http://example.com”>

  <SOAP-ENV:Header/>

  <SOAP-ENV:Body>

    <ns1:GetUser>

      <ns1:UserID>123</ns1:UserID>

    </ns1:GetUser>

  </SOAP-ENV:Body>

</SOAP-ENV:Envelope>

REST Example (HTTP GET request)

GET /users/123 HTTP/1.1

Host: api.example.com

How to automate SOAP APIs using Rest Assured with real-time examples 

Rest Assured is a powerful Java library that simplifies API testing for SOAP web services. By adhering to our detailed instructions and hands-on examples, you can effectively streamline the automation of your SOAP API tests. Boost your testing productivity and ensure the reliability of your web services with this comprehensive tutorial. Get started today and

streamline your API automation process with Rest Assured.

To achieve SOAP API automation using RestAssured, you must establish project dependencies, configure the testing environment, and craft test scripts. The following is an illustrative example of this process:

Step 1: Set up the Project 

Set up the Project Create a new Java project in your favourite IDE and add the required dependencies. In this example, we’ll use Maven for dependency management. Add the dependencies mentioned in the below to your pom.xml file:

<dependencies>
    <dependency>
        <groupId>io.rest-assured</groupId>
        <artifactId>rest-assured</artifactId>
        <version>4.3.3</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.testng</groupId>
        <artifactId>testng</artifactId>
        <version>7.4.0</version>
        <scope>test</scope>
    </dependency>
</dependencies>

Step 2: Configure the Test Environment

Configure the Test Environment Create a new Java class for your test and configure the base URI for the SOAP API:

import io.restassured.RestAssured;
import org.testng.annotations.BeforeClass;

public class SoapAPITest {
    @BeforeClass
    public void setUp() {
        RestAssured.baseURI = “https://example.com/soap-api”; // Replace with your SOAP API URL
    }
}

Step 3: Write Test Scripts

Now you can start writing test scripts to interact with the SOAP API using RestAssured. Below is an example of how to make a SOAP request and validate the response:

import io.restassured.response.Response;
import org.testng.annotations.Test;

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

public class SoapAPITest extends BaseTest {
    @Test
    public void testSoapRequest() {
        String soapRequest = “<soapenv:Envelope xmlns:soapenv=\”http://schemas.xmlsoap.org/soap/envelope/\” “ +
                            “xmlns:web=\”http://www.example.com/webservice\”>” +
                            “<soapenv:Header/>” +
                            “<soapenv:Body>” +
                            “<web:YourSoapRequest>” +
                            “<web:Parameter1>Value1</web:Parameter1>” +
                            “<web:Parameter2>Value2</web:Parameter2>” +
                            “</web:YourSoapRequest>” +
                            “</soapenv:Body>” +
                            “</soapenv:Envelope>”;

        Response response = given()
                .contentType(“text/xml”)
                .body(soapRequest)
            .when()
                .post(“/your-soap-endpoint”) // Replace with your SOAP endpoint
            .then()
                .statusCode(200)
                .body(“Envelope.Body.YourSoapResponse”, equalTo(“ExpectedValue”)) // Replace with your expected value
                .extract().response();

        // Print the SOAP response
        System.out.println(response.getBody().asString());
    }
}

Note: In the above example, you need to replace the placeholders (e.g., https://example.com/soap-api, /your-soap-endpoint, Value1, Value2, ExpectedValue) with your actual SOAP API URL, endpoint, request parameters, and expected values.

With the above setup and test script, you can now run your RestAssured tests to automate SOAP API testing efficiently.

Real time API example with SOAP

To make SOAP API (http://www.dneonline.com/calculator.asmx?WSDL) automation using Rest Assured is easier, you should use the Rest Assured library along with the SAAJ (SOAP with Attachments API for Java) library. 

Rest Assured doesn’t have direct support for handling SOAP, so we’ll use SAAJ to handle the SOAP request and response. Below is a Java code example that shows how to do an ‘Add’ operation using Rest Assured and SAAJ:

import org.testng.annotations.Test;
import io.restassured.RestAssured;
import static io.restassured.module.jsv.JsonSchemaValidator.*;

import javax.xml.soap.MessageFactory;
import javax.xml.soap.SOAPBody;
import javax.xml.soap.SOAPConnection;
import javax.xml.soap.SOAPConnectionFactory;
import javax.xml.soap.SOAPElement;
import javax.xml.soap.SOAPEnvelope;
import javax.xml.soap.SOAPMessage;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import java.io.StringReader;

public class SoapApiTest {

    @Test
    public void testAddOperation() {
        String soapRequestBody = “<soapenv:Envelope xmlns:soapenv=\”http://schemas.xmlsoap.org/soap/envelope/\” xmlns:tem=\”http://tempuri.org/\”>\n”
                + ”   <soapenv:Header/>\n”
                + ”   <soapenv:Body>\n”
                + ”      <tem:Add>\n”
                + ”         <tem:intA>10</tem:intA>\n”
                + ”         <tem:intB>20</tem:intB>\n”
                + ”      </tem:Add>\n”
                + ”   </soapenv:Body>\n”
                + “</soapenv:Envelope>”;

        // Send the SOAP request using SAAJ and Rest Assured
        SOAPConnectionFactory soapConnectionFactory;
        SOAPConnection soapConnection = null;
        try {
            soapConnectionFactory = SOAPConnectionFactory.newInstance();
            soapConnection = soapConnectionFactory.createConnection();
            SOAPMessage soapRequest = MessageFactory.newInstance().createMessage(null,
                    new StringReader(soapRequestBody));
            SOAPMessage soapResponse = soapConnection.call(soapRequest, “http://www.dneonline.com/calculator.asmx”);

            // Extract the response body from the SOAP response
            TransformerFactory transformerFactory = TransformerFactory.newInstance();
            Transformer transformer = transformerFactory.newTransformer();
            SOAPBody responseBody = soapResponse.getSOAPBody();
            StreamSource source = new StreamSource(responseBody.extractContentAsDocument());
            StreamResult result = new StreamResult(System.out);
            transformer.transform(source, result);

            // Add your assertions here for validating the response
            // For example, you can use Rest Assured to validate the JSON response
            RestAssured.given().contentType(“application/json”).body(result.getWriter().toString())
                    .when().post(“/your-validation-endpoint”)
                    .then().assertThat().body(matchesJsonSchemaInClasspath(“your-json-schema.json”));

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (soapConnection != null) {
                try {
                    soapConnection.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

This code sends the SOAP request to the “Add” operation of the SOAP API, extracts the SOAP response, and then you can use Rest Assured to validate the JSON response against a JSON schema.

Conclusion

In conclusion, this tutorial has provided valuable insights into automating SOAP APIs using Rest Assured, backed by real-time examples. By following the steps outlined here, you can streamline your API testing process, ensuring efficiency and reliability. Rest Assured capabilities make it a valuable asset for testers in the quest for robust web service testing. Embrace these techniques to bolster your testing proficiency and deliver higher quality APIs. Start automating with confidence today.

Keep in mind that Rest Assured is primarily designed for RESTful API testing, so using it for SOAP APIs requires a bit of additional work with SAAJ. For pure SOAP testing, you may consider using dedicated SOAP testing libraries like Apache CXF or Spring WS. 

The post How to Automate SOAP API using Rest Assured with real-time examples ? appeared first on Talent500 blog.

]]>
https://talent500.com/blog/how-to-automate-soap-api/feed/ 0
Mastering Different Types of Authentication in Rest Assured https://talent500.com/blog/mastering-different-types-of-authentication/ https://talent500.com/blog/mastering-different-types-of-authentication/#respond Tue, 05 Sep 2023 04:25:18 +0000 https://talent500.com/blog/?p=38484 Within the domain of API automation, safeguarding communication channels against unauthorised access is of great importance. This safeguarding is accomplished […]

The post Mastering Different Types of Authentication in Rest Assured appeared first on Talent500 blog.

]]>
Within the domain of API automation, safeguarding communication channels against unauthorised access is of great importance. This safeguarding is accomplished through the use of authentication and authorization. These concepts form the bedrock upon which secure API interactions are built.

In this blog, we’ll embark on a journey to understand authentication and authorization, and further explore their seamless implementation using Rest Assured. Rest Assured streamlines the automation of authentication processes within API testing. Whether it’s sending Basic Authentication headers, handling OAuth2 token exchange, or incorporating API keys, Rest Assured simplifies the inclusion of these authentication mechanisms into your test scripts. By integrating authentication into your automated tests, you ensure that your APIs’ security is not compromised during the testing process.

We will take examples of code using Rest Assured as it is the most used API automation library in the QA world.

Authentication vs. Authorization: Understanding the Basics

Authentication means verifying the identity of a user or application attempting to access an API. It basically tries to answer the question, “Who are you?” .

Common authentication methods include Basic Auth, Digest Auth,  OAUTH, API keys, Bearer tokens, and more. Proper authentication ensures that only legitimate users gain entry.

Authorization usually happens after authentication and is the process of granting or denying access based on a user’s or application’s permissions. It basically answers the question, “What are you allowed to do?”.

Authorization prevents unauthorised users from accessing sensitive data or performing restricted actions. For instance, attempting to access t500_prod_administrative data using regular user credentials would result in an unauthorised status.

HTTP Status Codes 401 and 403

When dealing with authentication and authorization, you’ll often encounter two HTTP status codes: 401 Unauthorised and 403 Forbidden.

  • 401 Unauthorised: This code signifies that the client lacks valid authentication credentials. In other words, the client needs to provide valid credentials to proceed. 
  • 403 Forbidden: The 403 code indicates that the client’s authentication credentials are valid, but they don’t have the necessary permissions to access the requested resource. It’s a firm denial of access.

Different Authentication Methods in Rest Assured

In the realm of API automation with Rest Assured, the variety of authentication methods available to you ensures that you can precisely simulate diverse security scenarios. One pivotal distinction lies in understanding OAuth vs. OAuth2 – two authorization protocols that have transformed how applications access resources on behalf of users.

1. Basic Authentication: 

Basic Authentication, a straightforward method employed in web apps and APIs, entails sending credentials (username and password) with every request to validate the requester’s identity. This approach, widely supported and easy to implement, is often used to secure resources. It’s preferred when simplicity and efficiency are paramount.

Response resp = given()
    .auth()
    .basic("username", "password")
    .when().get("https://api.example.com/resource");

Through .auth().basic(“username”, “password”), Rest Assured configures the request with your credentials.

2. Pre-emptive Authentication

Pre-emptive Authentication is an authentication strategy employed in HTTP clients to proactively send authentication credentials with the initial request, rather than waiting for the server to respond with a 401 Unauthorized status code.

In the context of Rest Assured and other HTTP client libraries, pre-emptive authentication means sending authentication credentials in the very first request, even before receiving any response from the server. This can be especially useful when dealing with APIs that require authentication for every request and do not challenge with a 401 status code.

Response resp1 = given()
    .auth()
    .preemptive().basic("username", "password")
    .when().get("https://api.example.com/resource");

By using .preemptive() before .basic(), Rest Assured takes the initiative in including the credentials.

3. Digest Authentication

Digest Authentication is an authentication mechanism used in HTTP to enhance the security of Basic Authentication. It addresses some of the security vulnerabilities present in Basic Authentication, such as the transmission of credentials in plain text, by using a more secure approach. Digest Authentication challenges the client with a server-generated nonce (a unique token) and requires the client to respond with a hashed value of the nonce, username, password, and other request-specific information.

Response resp2 = given()
    .auth()
    .digest("username", "password")
    .when().get("https://api.example.com/resource");

Through .digest(“username”, “password”), Digest Authentication is configured.

4. OAuth2 Authentication: 

OAuth2 (Open Authorization 2.0) is a widely used authorization framework that allows applications to obtain limited access to user accounts on behalf of a third-party application. It’s commonly used to enable secure and controlled access to APIs and resources without exposing the user’s credentials.

OAuth2 involves various roles, including the resource owner (user), client application (third-party app), authorization server (handles authentication and issues access tokens), and resource server (holds the protected resources). The process revolves around obtaining an access token, which serves as a temporary authorization token that allows the client application to access specific resources on behalf of the user.

Response resp3 = given()
    .auth()
    .oauth2("access_token")
    .when().get("https://api.example.com/resource");

With .oauth2(“access_token”), Rest Assured automatically integrates the token into the request.

5. OAuth Authentication

OAuth1, often referred to simply as OAuth, is an earlier version of the OAuth protocol that focuses on granting third-party applications limited access to user resources on various online services. It’s designed to enable secure access to resources without the need for sharing the user’s actual credentials (username and password) with the third-party application.

OAuth1 authentication involves three main parties: the user (resource owner), the client application (consumer), and the resource server (service provider). 

Response resp4 = given()
    .auth()
    .oauth("consumerKey", "consumerSecret", "accessToken", "secretToken")
    .when().get("https://api.example.com/resource");

Through .oauth(), you provide the required credentials.

OAuth1 vs OAuth2: A Closer Look

In the realm of securing APIs and enabling controlled access to user resources, OAuth1 and OAuth2 stand as prominent players. While they share the same fundamental purpose, these two protocols diverge in their approaches and mechanisms. Let’s delve into their differences and understand how they shape the landscape of authorization.

OAuth1 Example

OAuth1, the predecessor to OAuth2, revolves around the concept of allowing third-party applications to access user resources. One of its distinguishing features is its utilisation of signatures to authenticate requests. This involves generating a signature that encapsulates various parameters, effectively vouching for the integrity of the request.

For instance, when a third-party application seeks access to a user’s resources, it crafts a signature that encompasses elements like the HTTP method, request URI, and credentials. This signature serves as a cryptographic seal, ensuring that the request remains unaltered and genuine.

OAuth2 Example

In contrast to its predecessor, OAuth2 boasts a more streamlined and user-centric approach. Rather than delving into the intricacies of signature generation, OAuth2 emphasises token-based authentication. This approach prioritises both security and user-friendliness.

Imagine a scenario where a user wishes to grant an application access to their resources. OAuth2 orchestrates a dance between three main players: the user, the application, and the authorization server. Through this dance, the application receives an access token—a short-lived, cryptic key. This token, akin to a digital permission slip, grants the application limited access to the user’s resources without revealing sensitive credentials.

Conclusion

In conclusion, authentication and authorization are vital elements in the API automation landscape. They secure your API interactions and ensure that only authorised users access specific resources. With Rest Assured, you can seamlessly integrate various authentication methods, enabling you to create robust and secure automation scripts. So, whether you’re using Basic Auth, OAuth, or any other method, Rest Assured empowers you to automate authentication and authorization in your API tests with ease.

The post Mastering Different Types of Authentication in Rest Assured appeared first on Talent500 blog.

]]>
https://talent500.com/blog/mastering-different-types-of-authentication/feed/ 0
Revolutionizing Mobile Automation with AI https://talent500.com/blog/revolutionizing-mobile-automation-with-ai/ https://talent500.com/blog/revolutionizing-mobile-automation-with-ai/#respond Wed, 19 Jul 2023 01:57:00 +0000 https://talent500.com/blog/?p=38080 In the present world, there are apps for every mobile device and purpose, and feedback is an integral part of […]

The post Revolutionizing Mobile Automation with AI appeared first on Talent500 blog.

]]>
In the present world, there are apps for every mobile device and purpose, and feedback is an integral part of their improvement process. With the emerging technology and demand for faster releases, it is quite important to make sure that the mobile apps need to be tested thoroughly before it is released to the customers. Due to this reason mobile automation testing has become indispensable to ensure the quality and functionality of mobile applications.

Among all the mobile automation tools available in the market, Appium has established its dominance, capturing a significant market share of 35% among organisations. While Selenium continues to reign in web automation, Appium emerges as the preferred choice for mobile automation. In this context, we will explore the transformative potential of AI-driven automation with Appium, showcasing how it can revolutionise the mobile testing landscape by integrating with ChatGPT.

With the integration of Artificial Intelligence (AI), mobile automation testing has witnessed a remarkable advancement in terms of efficiency and precision. In this blog post, we will discuss the Role of AI and where we can use AI to improve mobile automation efficiency.

The Role of AI in Mobile Automation

Mobile automation testing is incredibly important in today’s digital world because we rely heavily on mobile applications. These apps are crucial for business success, so it’s essential to make sure they work well. However, testing them manually takes a lot of time, can have mistakes, and is difficult because there are so many different mobile devices.

The challenges encountered in mobile automation testing arise from various factors, including the wide range of devices, operating systems, and screen sizes. Ensuring compatibility and consistent performance across this fragmented landscape demands extensive testing efforts and effective management of test scripts. Moreover, the dynamic nature of mobile apps, with frequent updates and evolving user behaviours, adds complexity to testing endeavours.

In this context, the role of AI in mobile automation testing takes centre stage, as the famous saying goes, “With great challenges come great opportunities.” AI-powered techniques hold the potential to revolutionise the testing process, bringing efficiency, accuracy, and enhanced test coverage. 

By harnessing the power of AI in mobile automation testing, organisations can tread the path of success, as another famous quote states, “Fortune favours the prepared mind.” AI-driven approaches offer invaluable insights, aiding in uncovering hidden defects, optimising test coverage, and enhancing the overall quality of mobile applications. It is no wonder that AI is heralded as the “game-changer” in the realm of mobile automation testing, offering new avenues for improvement and advancement.

How AI can be used to improve mobile automation 

To showcase how AI can enhance mobile automation code, let’s explore the following AI-driven improvements. As AI is relatively new, it’s important to prioritise security checks before sharing any sensitive project data.

Adaptive Element Identification

AI can be used to dynamically identify elements based on their visual features rather than just using hardcoded element locators (such as IDs). We can train the system to recognise and locate objects based on their visual appearance by applying image recognition algorithms and AI models. This method of adaptive element identification guarantees more reliable test scripts that are less likely to malfunction as a result of UI changes.

Test Data Generation

The efficient and accurate development of various data sets is made possible by AI, which is essential for test data generation. Libraries like PySynthetic, AutoFixture, and Faker offer AI-powered tools for building thorough and realistic test data. These libraries use AI algorithms to produce data that includes edge cases and boundary conditions and covers a range of scenarios. Organisations can increase test coverage, optimise testing procedures, and raise the calibre of their software by automating the generation of test data.

Develop Test Scripts with AI

The creation of mobile automation test scripts has been transformed by generative AI, which provides previously unheard-of efficiency and accuracy. We can now use the power of AI to take advantage of the capabilities of natural language processing to create test scripts from scratch. We may get ready-to-use test scripts that are catered to our particular needs by giving prompts or instructions to the generative AI model, like “Create a mobile automation test script for login functionality.” This method significantly reduces time and effort, allowing testers to concentrate more on examining test results and locating important flaws.

Efficient Wait Times

AI can assess the response timings of various elements or activities during test runs rather than employing predefined wait timers. This analysis allows the system to optimise test execution by dynamically adjusting wait times. The execution of tests can be sped up with adaptive wait times without sacrificing reliability.

How to integrate ChatGPT with Appium Automation

In this section, we will explore the necessary steps to incorporate ChatGPT into Appium automation. It is important to ensure that you include the API key during the API credentials setup.

1. Import the necessary dependencies

To begin, we import the required dependencies that include Appium and OpenAI GPT3 libraries.

2. Set up the OpenAI API credentials

In this step, we set up the credentials required to access the OpenAI API. The OpenAI API credentials are configured to establish the necessary authentication for API access.

3. Set up the Selenium WebDriver for Appium automation

We configure the Selenium WebDriver to enable Appium automation for seamless testing. The Selenium WebDriver is set up to facilitate Appium automation, ensuring a smooth testing experience.

4. Define the conversation with ChatGPT

In this stage, we define the conversation structure that will be used for interaction with ChatGPT.

5. Iterate over the conversation and interact with ChatGPT

In this code snippet, we iterate over each message in the conversation and interact with ChatGPT. We use the gpt3.completePrompt() method to send each message to ChatGPT and receive a response. Based on ChatGPT’s response, we perform specific actions. If the response indicates to enter a value, we extract the value and enter it into the designated input field. If the response suggests clicking, we locate the relevant button and perform a click action. Finally, we print ChatGPT’s response to observe the generated output.

for (String message : conversation) {
    // Interact with ChatGPT
    String response = gpt3.completePrompt(message);

    // Perform actions based on ChatGPT’s response
    if (response.contains(“Enter”)) {
        String[] parts = response.split(“Enter”);
        String value = parts[1].trim();
        MobileElement element = driver.findElementById(“input_field_id”);
        element.sendKeys(value);
    } else if (response.contains(“Click”)) {
        MobileElement element = driver.findElementById(“button_id”);
        element.click();
    }

    // Print ChatGPT’s response
    System.out.println(“ChatGPT: “ + response);
}

6. Close the app and quit the driver

Here we will just close the app and quit the driver.

driver.closeApp();
driver.quit();

In this example, we configure the OpenAI API credentials and set up the Selenium WebDriver for Appium automation. We define a conversation with ChatGPT and interact with it using the gpt3.completePrompt() method, and retrieve the response. Based on the response, we perform actions in the app such as entering text or clicking buttons. 

Finally, we print the response, close the app, and quit the driver. Remember to customise the placeholder values with your own API key, device information, and application details.

Conclusion 

In conclusion, the integration of AI in mobile automation testing brings significant advantages, empowering testers to enhance coding standards, improve test coverage, and optimise the testing process. With AI-powered tools and techniques, such as the integration of AI with Appium, testers can achieve higher efficiency, accuracy, and effectiveness in their mobile automation efforts. By harnessing the power of AI, organisations can deliver robust and high-quality mobile applications. Embracing AI in mobile automation testing is no longer a luxury but a necessity for staying competitive in the rapidly evolving mobile app market.

By leveraging AI-driven mobile automation, testers can benefit from enhanced test reliability, reduced maintenance efforts, and improved overall efficiency in their testing processes. These capabilities contribute to delivering high-quality mobile applications while effectively managing the challenges posed by the dynamic nature of mobile environments.

 

The post Revolutionizing Mobile Automation with AI appeared first on Talent500 blog.

]]>
https://talent500.com/blog/revolutionizing-mobile-automation-with-ai/feed/ 0
API Testing With Cypress https://talent500.com/blog/api-testing-with-cypress/ https://talent500.com/blog/api-testing-with-cypress/#respond Tue, 18 Jul 2023 10:11:53 +0000 https://talent500.com/blog/?p=38000 Is it possible to test everything using a single tool?.  Seems like a dream but I would say it is […]

The post API Testing With Cypress appeared first on Talent500 blog.

]]>
Is it possible to test everything using a single tool?.  Seems like a dream but I would say it is almost possible with Cypress, a JavaScript frontend testing framework. Cypress is primarily designed for end-to-end testing of web applications, which includes both the frontend user interface (UI) and the backend API interactions.

With Cypress, you can write tests that cover the entire application flow, from interacting with the UI elements to making API requests and validating the responses. This makes Cypress a versatile tool that allows you to test the integration between the UI and the API.

In this tutorial, I will guide you through how we can use cypress for API testing.

Categories of API Testing

API testing is a type of software testing that focuses on verifying and validating the functionality, reliability, performance, and security of application programming interfaces (APIs). APIs enable communication and data exchange between different software systems, allowing them to interact and share information.

API testing involves testing the various aspects of an API, including its endpoints, input/output data, error handling, and integration with other systems. It ensures that the API behaves as expected, follows the defined specifications, and meets the requirements of the applications or services that rely on it.

APIs can be categorised into different types, including: 

  • Web APIs: These are APIs exposed by web services over HTTP or HTTPS protocols. They are often used for data exchange in a client-server architecture. 
  • REST APIs: Representational State Transfer (REST) APIs are a type of web API that follows a set of architectural principles. They use HTTP methods like GET, POST, PUT, DELETE to perform operations on resources. 
  • SOAP APIs: Simple Object Access Protocol (SOAP) APIs use XML-based messages over protocols like HTTP, SMTP, or others for communication. They are typically used in enterprise applications. 
  • GraphQL APIs: GraphQL is a query language for APIs that allows clients to request and retrieve specific data they need, reducing over-fetching or under-fetching of data.

Tools available for REST API testing

There are several tools available for API testing, each with its own set of features and capabilities. Here are some popular tools for API testing:

  1. Cypress: Cypress is a JavaScript-based end-to-end testing framework with a focus on web applications. While it excels in UI testing, it can also be used for API testing using its cy.request() command
  2. Playwright: Playwright provides a JavaScript API for making HTTP requests, enabling you to send API requests, handle responses, and perform assertions. Playwright’s multi-browser support and cross-platform compatibility make it a versatile choice for API testing in a web context.
  3. Postman: Postman is a widely used API testing tool that provides a user-friendly interface for designing, testing, and documenting APIs. It allows you to send requests, set headers, handle authentication, and validate responses. Postman also supports test automation and offers features like test collections, environments, and reporting.
  4. RestAssured: RestAssured is a Java library specifically designed for API testing. It provides a fluent and expressive syntax for writing tests and assertions. RestAssured simplifies the handling of request and response specifications, authentication, and validation of response data.
  5. Karate: Karate is an open-source API testing tool built on top of Cucumber and Gatling. It provides a unified framework for API testing, mocking, and performance testing. Karate uses a simple syntax that combines test case definition, request specification, and assertions in a single feature file.
  6. SoapUI: SoapUI is a specialised tool for testing SOAP and REST APIs. It supports WSDL and Swagger specifications, allowing you to import API definitions and generate tests automatically. SoapUI offers features like test case creation, assertions, security testing, and performance testing.

Why Cypress for REST API testing?

Cypress is primarily known as a frontend testing framework, but it can also be used effectively for API testing.

Here are some reasons why Cypress can be a good choice for API testing:

  1. Easy setup and integration: Cypress provides a seamless and straightforward setup process, allowing you to start writing API tests quickly. It is built specifically for JavaScript frontend developers, so if you are already familiar with JavaScript, getting started with Cypress for API testing is relatively easy.
  2. Unified testing framework: Cypress allows you to use a single testing framework for both frontend and API testing. This can be advantageous as it reduces the need to learn and manage multiple testing tools.
  3. Integration with frontend tests: If you are already using Cypress for frontend testing, using it for API testing as well can provide better integration and consistency across your test suite. You can combine API tests with frontend tests to cover end-to-end scenarios and ensure smooth interactions between the UI and the API.
  4. Built-in assertions and helpful API: Cypress offers a comprehensive set of built-in assertions and a user-friendly API for making API requests and performing assertions on the responses. This makes it easy to validate API responses, assert on status codes, response data, headers, and more.
  5. Test Data and Mocking: Cypress provides mechanisms for managing test data and mocking API responses. You can use fixtures to load test data from external files, create custom Cypress commands to encapsulate API-related logic, and use tools like cy.route() or cy.intercept() to stub or intercept network requests and simulate specific API responses

How Cypress executes API test cases internally:

Below a detailed explanation of how Cypress executes API test cases internally. Cypress uses Node.js as an engine to make HTTP requests to the API server.API server responds to the request, and Cypress receives the response through Node.js and can perform assertions or other actions based on the response data.

Below are the steps for how API test cases are executed in Cypress

Test Initialization:

  • When you run API test cases in Cypress, it initializes the test execution environment.
  • Cypress loads its core library, plugins, and other dependencies required for API testing.

Test File Execution:

  • Cypress reads the API test file(s) specified in the test runner.
  • It parses the test file(s) to identify the API test cases written using Cypress’s API syntax.
  • Cypress organizes the test cases and their associated commands for execution.
  • Cypress launches a browser instance (headless or interactive) using its browser automation capabilities.
  • The test cases and their commands are executed within this browser instance.

Command Execution and Interception:

  • Cypress intercepts API requests made by the test cases using its command interception mechanism.
  • When a cy.request() command is encountered, Cypress intercepts the request before it reaches the actual server.

Request Simulation and Response Capturing:

  • Cypress simulates the intercepted request internally, generating a simulated request object with all the relevant details.
  • It captures the response, including the status code, headers, and response body.

Response Validation and Assertions:

  • After capturing the response, Cypress compares it against the expected values defined in the test case.
  • Cypress provides built-in assertion methods (should(), expect(), etc.) to validate different aspects of the response.

Test Reporting:

  • During the test execution, Cypress collects information about the executed commands
  • The test report is displayed within the Cypress Test Runner interface, providing visibility into the test results and facilitating troubleshooting.

What is cy.request()?

Cypress leverages the cy.request() command to send HTTP requests to the API server.The cy.request() is a command provided by Cypress, that allows you to send HTTP requests and interact with APIs directly within your test cases

Here are the different variations of the cy.request() command in Cypress:

cy.request(url) : This variation sends a GET request to the specified URL.

cy.request(url, body): This variation sends a POST request to the specified URL with the provided request body

cy.request(method, url): This variation allows you to specify the HTTP method (e.g., GET, POST, PUT, DELETE) along with the URL

cy.request(method, url, body): This variation sends a request with the specified HTTP method, URL, and request body.

cy.request(options) : This variation allows you to pass an options object with detailed configuration for the request

API Methods

GET, POST, PUT, and DELETE are the four most common HTTP methods used in REST APIs. They correspond to the CRUD (create, read, update, delete) operations on resources.

  • GET: Used to retrieve data or read a resource from the server.
  • POST: Used to create a new resource on the server.
  • PUT: The PUT method is used to update or replace an existing resource on the server
  • DELETE: The DELETE method is used to delete a specified resource on the server.

Some some commonly used HTTP response codes in REST 

  • 200: OK – The request was successful, and the server returned the requested data.
  • 201: Created – The request was successful, and a new resource was created as a result (typically in response to a POST request). The response will include the URL to access the newly created resource in the Location header.
  • 204: No Content – The request was successful, but the response does not contain any content (typically in response to a DELETE request).
  • 304: Not Modified – The requested resource has not been modified since the last request. This is commonly used in response to a GET request with conditional headers.
  • 400: Bad Request – The request was malformed or could not be understood by the server. This could be due to missing or invalid parameters, incorrect JSON format, etc.
  • 401: Unauthorized – The request requires user authentication. The user must provide valid credentials (such as a valid token or username/password) to access the resource.
  • 403: Forbidden – The authenticated user is not allowed to access the requested resource. This could be due to insufficient permissions.
  • 404: Not Found – The requested resource could not be found on the server.
  • 422: Unprocessable Entity – The server understands the request, but the provided data violates some validation rules (e.g., missing required fields or invalid field values).
  • 500: Internal Server Error – An unexpected error occurred on the server, indicating a problem with the server’s configuration or code.

Some example of different API Methods

Pre-requisites:

  • Install Node.js from Node.js
  • Install Cypress
  • We will be using Go Rest APIs for demo purpose

Let’s take some example to automate the API endpoint using Cypress.

POST Method 

POST method is used to send data to a server to create/update a resource.

it('POST API Automation Using GoRest API', () => {

const user = {

name: 'John Doe',

email: "johndoe123"+randomNumber+"@example.com",

gender: 'male',

status: 'active',

};

cy.request({

method: 'POST',

url: 'https://gorest.co.in/public/v1/users',

headers: {

Authorization: 'Bearer <Enter token here >,

},

body: user,

}).then((response) => {

userId=response.body.data.id

expect(response.status).to.equal(201);

expect(response.body.data.name).to.equal(user.name);

expect(response.body.data.email).to.equal(user.email);

});

});

Here’s a breakdown of the code:

  1. The code defines a test case using the ‘it’ function. The test case name is not provided in the snippet.
  2. The ‘user’ object is defined with properties such as name, email, gender, and status. The ‘email’ property seems to include a random number concatenated to a base email address.
  3. The ‘cy.request’ function is used to send a POST request to the specified URL:
  4. The ‘Authorization’ header is included in the request, but the token value is missing. You would need to replace ‘<Enter token here >’ with the actual authorization token for the request to work correctly.
  5. The ‘body’ property of the request is set to the user object, which contains the data for creating a new user.
  6. The ‘then’ method is used to handle the response from the API request.
  7. Inside the response handler, the userId variable is assigned the value of the newly created user’s ID from the response body.
  8. Assertion statements are used to verify the response status, name, and email of the created user.

NOTE : Bearer token can be generated from this link https://gorest.co.in/my-account/access-tokens

GET Method 

In the GET method The cy.request function is used to send a GET request to the specified URL: ‘https://gorest.co.in/public/v1/users/${userId}‘. The ${userId} is a placeholder that likely refers to the user ID obtained from a previous API call.

it('GET API Automation Using GoRest API', () => {

cy.request({

method: 'GET',

url: 'https://gorest.co.in/public/v1'+`/users/${userId}`,

headers: {

Authorization: 'Bearer <Enter token here>,

},

}).then((response) => {

expect(response.status).to.equal(200);

expect(response.body.data.name).to.equal('John Doe');

expect(response.body.data.gender).to.equal('male');

});

});

PUT Method 

PUT method used to update the existing data. The cy.request function is used to send a PUT request to the specified URL: ‘https://gorest.co.in/public/v1/users/${userId}‘. The ${userId} is a placeholder that likely refers to the user ID obtained from a previous API call.

it('PUT API Automation Using GoRest API', () => {

const user = {

name: 'Time Cook',

email: "TimCook123"+randomNumber+"@example.com",

gender: 'male',

status: 'active',

};

cy.request({

method: 'PUT',

url: 'https://gorest.co.in/public/v1'+`/users/${userId}`,

headers: {

Authorization: 'Bearer <Enter token here>,

},

body: user,

}).then((response) => {

expect(response.status).to.equal(200);

expect(response.body.data.name).to.equal(user.name);

expect(response.body.data.email).to.equal(user.email);

});

});

DELETE Method 

Delete method is used to delete the created record. In below code you can see we have used (${userId} which we want to delete and user ID obtained from a previous API cal

it('DELETE API Automation Using GoRest API', () => {

cy.request({

method: 'DELETE',

url: 'https://gorest.co.in/public/v1'+`/users/${userId}`,

headers: {

Authorization: 'Bearer <Enter token here>,

},

}).then((response) => {

expect(response.status).to.equal(204);

});

});

Execution Report of test cases

Run the command ’yarn cypress open’  test cases to start executing in cypress runner.

Below the execution report, all API endpoints are executed successfully. 

Execution report of POST and GET method.

Execution report of PUT and DELETE method

Wrapping up

API testing with Cypress offers a powerful and efficient way to validate the functionality, performance, and reliability of your API endpoints. By adopting Cypress for API testing, you can enhance the quality of your applications and deliver a seamless experience to your users.

 

The post API Testing With Cypress appeared first on Talent500 blog.

]]>
https://talent500.com/blog/api-testing-with-cypress/feed/ 0
Cypress vs Playwright With Pros and Cons https://talent500.com/blog/cypress-vs-playwright-with-pros-and-cons/ https://talent500.com/blog/cypress-vs-playwright-with-pros-and-cons/#comments Mon, 03 Jul 2023 10:49:52 +0000 https://talent500.com/blog/?p=37358 Choosing the right testing tool for your project can be a challenging decision, especially when there are multiple options available. […]

The post Cypress vs Playwright With Pros and Cons appeared first on Talent500 blog.

]]>
Choosing the right testing tool for your project can be a challenging decision, especially when there are multiple options available. Both Cypress and Playwright are popular testing tools, but they have some differences in their features and capabilities. 

Cypress is a popular tool that has been in the market for a while and has gained a significant user base. It offers an easy-to-use testing framework with a simple syntax that allows developers to write tests quickly. Additionally, Cypress offers a built-in dashboard that facilitates troubleshooting and problem diagnosis.  

Microsoft’s Playwright, on the other hand, is a very recent open-source test automation framework. It aims to automate web application testing across a variety of browsers and operating systems (including Windows, macOS, and Linux), including Chromium, Firefox, and Safari.

While both tools aim to achieve similar goals, they differ in various aspects, including their approach, architecture, and features. By weighing the pros and cons of each tool, you can make an informed decision and choose the tool that fits your requirements.

This blog will teach you about the pros and cons of each tool which will help you in tool selection.

Looking at the npm trends for both Cypress and Playwright can give us some insights into their popularity and adoption rates.

 

What is Cypress?

Cypress is an open-source framework for web application end-to-end testing. It enables developers / tested to write automated tests that simulate user interactions with their web applications and verify the application’s behaviour and functionality.

Cypress Architecture

The majority of tests in different automation technologies, like Selenium, run outside of the browser and carry out remote commands over the network. Cypress sets itself apart from others by conducting tests inside the browser where your applications are executing. There is no need for driver binaries because Cypress tests are executed on the live browser

The screenshot below demonstrates how tests are run within the browser, which speeds up test execution and eliminates network latency.

Behind the scenes, Cypress runs a Node.js server that communicates with the browser via a WebSocket. This communication channel allows the two processes to synchronise and perform tasks on each other’s behalf.

WebSocket communication between the Node.js server and the browser is a critical part of the Cypress architecture. It enables Cypress to provide a seamless testing experience by running tests directly in the browser and providing real-time feedback to the user.

Some of the Advantages of using Cypress (Key Features)

  1. Fast and reliable testing: Cypress provides fast and reliable testing due to its unique architecture that runs tests directly in the browser. It eliminates the need for additional drivers or plugins and provides real-time feedback on test execution. 
  2. Easy setup and installation: Cypress is easy to set up and install, and it comes with a user-friendly dashboard that makes it easy to write, manage, and run tests. 
  3. Automatic waiting and retrying: Cypress automatically waits for elements to load and retry commands when needed, which helps to reduce flaky tests and improve test reliability.
  4. Real-time reloading: Cypress provides real-time reloading of tests and application code, which makes it easy to develop and debug tests.
  5. Interactive debugging: Cypress provides an interactive debugger that allows developers to debug tests in real-time and quickly identify and fix issues.
  6. Supports modern web technologies: Cypress has built-in support for modern web technologies like React, Vue, Angular, and TypeScript, and integrates well with popular testing frameworks and libraries like Mocha, Chai, and Jest.
  7. Cross-browser testing: Cypress supports cross-browser testing, which allows developers to test their applications on different browsers and platforms.

Disadvantages of Cypress (Limitations)

Cypress has many advantages, there are also some limitations to consider:

  1. No support for mobile testing: Cypress does not support mobile testing out of the box. You can use a third-party plugin to add mobile testing capabilities, but it is not as comprehensive as testing on a physical device.
  2. Language support: Support for multiple programming languages is available with automation tools like Selenium and Playwright, but Cypress is only compatible with JavaScript/TypeScript.
  3. MultiTab Testing: Cypress runs tests inside a single browser instance, it does not support multi-tab testing out-of-the-box.
  4. iframe Support: In Cypress, iFrame Support is verified limited and does not work often
  5. Tab Key Support: Cypress does not support Tab key, you need to use a plugin for it. 
  6. XPath Support: Cypress does not support a locator by XPath,you need to use a plugin for it. 
  7. File Upload/Download: Cypress does not support upload/download fields directly, you need to install a plugin to upload/download the file.

What is Playwright?

Playwright is an open-source automation library for testing web applications. It was developed by Microsoft and supports multiple programming languages including JavaScript, Python, C# and Java. Playwright provides a high-level API for interacting with web browsers including Chromium, Firefox, and WebKit, allowing developers to simulate user interactions such as clicking buttons, filling out forms, and navigating pages.

Playwright Architecture

Playwright uses a single WebSocket connection between the client and server to communicate all the commands and responses. When you trigger a test, your test code is executed on the client side, and the commands you write are converted into JSON format and sent to the Playwright server using the WebSocket protocol.

Once the connection is established, the commands are transmitted to the Playwright server, which then executes them on the browser instance. The server then sends the response back to the client in JSON format through the WebSocket connection. This process continues until all the commands in your test are executed.

Some of the Advantages of using Playwright (Key Features)

  1. Cross-browser support: Playwright supports the automation of web browsers across multiple platforms, including Chrome, Firefox, Safari, WebKit and Edge.
  2. Multiple contexts: Playwright allows you to create multiple browser contexts with different user agents, cookies, and caches. This feature is useful for testing web applications with multiple users.
  3. Easy setup: Playwright provides an easy-to-use setup process that allows developers to quickly get started with automating browser interactions.
  4. Multiple programming languages: Several programming languages, including Java, JavaScript, TypeScript, Python, and C#are supported by Playwright.
  5. Automatic waiting: Playwright automatically waits for page loads, element visibility, and other conditions, ensuring that tests run smoothly and reliably.
  6. Integrated screenshots and video recording: Playwright’s ability to capture screenshots and videos of test execution makes it simpler to troubleshoot and examine test failures.
  7. Codegen: Allows you to generate tests by recording user interactions with a website or web application. With Playwright Codegen, you can create automated tests quickly and easily, without writing code manually.
  8. Playwright inspector: Allows you to inspect web pages and generate selectors for elements on the page

Disadvantages of Playwright (Limitations)

  1. Limited community support: Playwright is still a relatively new framework, and as such, it has a smaller community and ecosystem compared to more established frameworks like Selenium or Cypress. This can make it more difficult to find support, plugins, or examples online.
  2. Mobile Device Testing: Instead of using actual mobile devices, Playwright enables mobile testing via device emulation.

Cypress vs Playwright Compare Table

Let’s see a Comparison between Cypress vs Playwright

Cypress Playwright
Browser Support Cypress supports Chromium-based browsers, including Chrome, Edge, and Safari.  Playwright supports Chrome, Firefox, WebKit-based browsers like Safari, Edge (Chromium-based)
Programming Language Cypress supports JavaScript and TypeScript Playwright supports Java, TypeScript, JavaScript, Python,C#,Ruby.
Framework Support Supports, Jest/Jasmine, Mocha and Cucumber Mocha,Jest/Jasmine, AVA,Cucumber and Vitest
Community Support Cypress has Active and large community Playwright has a smaller but growing community.
Open Source Yes, open-source and free to use Yes, open-source and free to use
Integration with CI/CD Supports most of the popular CI/CD tools e.g like CircleCI, TravisCI, and Jenkins,TeamCity Supports most of the popular CI/CD tools e.g  like CircleCI, TravisCI, and Jenkins
Mobile device testing Not support Mobile device testing Not support Mobile device testing
Parallel test execution Supported with Cypress Dashboard or third-party tools Supported with built-in parallelism
Test recording Support Test recording with Cypress Studio Support Test recording
Headless testing Supported Supported

Wrapping up

Both Cypress and Playwright are powerful tools for cross-browser testing, and they each have certain advantages and disadvantages. Decision to choose between Cypress and Playwright depends on your specific testing needs and requirements. Both tools offer powerful capabilities, and it is up to the testing team to decide which tool is best suited to their project and skill set. Regardless of which tool you choose, both Cypress and Playwright are excellent choices for cross-browser testing and can help improve the quality of your web application.

The post Cypress vs Playwright With Pros and Cons appeared first on Talent500 blog.

]]>
https://talent500.com/blog/cypress-vs-playwright-with-pros-and-cons/feed/ 1
How to Perform Web Service Testing: The Definitive Guide https://talent500.com/blog/how-to-perform-web-service-testing-the-definitive-guide/ https://talent500.com/blog/how-to-perform-web-service-testing-the-definitive-guide/#respond Tue, 27 Jun 2023 08:07:00 +0000 https://talent500.com/blog/?p=37611 As more organisations migrate online, the demand for powerful and trustworthy web services rises. So how can you be certain […]

The post How to Perform Web Service Testing: The Definitive Guide appeared first on Talent500 blog.

]]>
As more organisations migrate online, the demand for powerful and trustworthy web services rises. So how can you be certain that your online service is up to scratch? Testing Web Services is critical.

This tutorial sets out a method to testing web services, whether you’re a developer developing web services for the first time or an experienced tester. Let’s get the Blog started!

What is a Web Service?

Web Services are client-server applications or components. Web services may also be thought of as ways of communication between two devices over the network. There are two kinds of online services: SOAP and REST

While web services testing might be time-consuming, it is well worth the effort to keep your site running smoothly.

Here’s How to Create a Web Service

Today we’ll build a small service with only one method that combines two integers.
1. Before you start, make sure you have the following setup:

Microsoft’s Internet Information Services (IIS) is up and running on your machine
The latest.Net Framework SDK is installed
Create a directory under your C:\Inetpub\www.root named WebServices (wwroot image)

  • Next, copy and paste the following code into Notepad.:

  • Following that, we import two namespaces, System and System. Web.Services.
  • Following that, we build our class DEMOAddNumbers and add our function AddThis, which receives two integer inputs — x and y. Lastly, we add the values and return an integer value mySum, which comprises the total of the arguments supplied.
  • Put the file in your wwwroot/WebServices directory as DEMOAddNumbers.asmx. In case you’re wondering, the file extension for ASP.NET is asmx.

How to Create a web.config File

Also had to add a web.config file to C:\Inetpub\wwwroot directory to get this to work on the machine. Copy the following into notepad:

You need to name the file as web.config and save it under C:\Inetpub\wwwroot

 Verify That the Web Service Works

Next, open your browser and put the following address:

http://localhost/WebServices/DEMOAddNumbers.asmx/AddThis?x=40&y=2

The page should now return the value of 42

All About the WSDL

We’ll now examine what WSDL is and how it works. A WSDL is an XML document that specifies a web service’s methods, method arguments, namespace, and handling URL. When an HTTP-GET request is made to a.asmx file, WSDLs and other document formats are created automatically.

For example, navigate to:

http://localhost/WebServices/DemoAddNumbers.asmx

This should display an HTML page that describes the methods of the DEMOAddNumbers web service as well as some more information.

Clicking on the AddThis method link from this page will take you to another HTML page where you may test the service’s functionality.

let’s take a look at the actual WSDL.

Looking at a WSDL

Enter the following URL into your browser to access our web service:

http://localhost/Webservice/DEMOAddNumbers.asmx?WSDL

Our web service’s WSDL (DEMOAddNumbers) should be shown. Again, we didn’t do anything unique to generate the WSDL; it was generated for us automatically.

As can be seen, a WSDL document is just an XML document that contains information about a web service.

The four main sections of a WSDL

  1. Element types – These are the data types that web services employ.

Take note of how the WSDL information corresponds to the code of our web services.

  1. Message element – This section covers the web service’s messages and defines the data parts of an operation
  2. Binding element – This section defines the web service’s communication protocols:
  3. PortType element – The fourth element, portType, is widely regarded as the most significant since it specifies the web services and all of the activities that may be done, as well as all of the service messages.

The portType element defines DEMOAddNumbersSoap, DEMOAddNumbersHttpGet, and DEMOAddNumbersSoapPost as the names of the ports, and “AddThis” as the name of the action in the preceding section.

Additionally, the ports are a Request-Response action, which means that our web service may accept a request and respond with a response. For example:

Request a request called AddThisHttpGetIn

wsdl:input message=”tns:AddThisHttpGetIn”

Return a response called AddThisHttpGetIn

wsdl:output message=”tns:AddThisHttpGetOut”

Then, using a test tool, examine the process of submitting and receiving a request from a web service.

Web Service Testing Response and Requests

Let’s look at a web service’s request and response now that we have a functional web service and a simple WSDL.

Then, load the WSDL into your preferred testing tool. SOAPUI will be used.

  1. Click on ‘File\New soupUI project’ in SoapUI. 
  2. In the New soapUI project, enter the Project Name: AddNums
  3. For Initial WSDL/WADL enter:

http://localhost/Webservice/DEMOAddNumbers.asmx?WSDL

  1. SoapUI needs to import the “AddThis” method under the below projects AddNums\DEMOAddNumbersSOAP. 
  2. Double-clicking on the AddThis ‘Request 1’ will show the following:

*Remember — the WSDL should include all the info needed to interact with a web service. That’s why soapUi was able to read in the WSDL and automatically generate a request with the correct inputs for you.

 Web Service Request/Response

The most common type of web service is our DEMOAddNumbers, in which a requester submits a request to the service and then waits.

The request is subsequently processed and a response is sent by the service.

What does SOAP have to do with Web Services?

SOAP, an XML-based standard for dealing with Web Services, basically gives information to the request over HTTP. SOAP is an abbreviation for Simple Object Access Protocol. Looking at our request, we can notice soap components like SOAP Envelope, Header, and Body.

This is the content of a typical SOAP XML message.

SOAP Faults

A SoapFault should occur if we send invalid data in the request for a Negative Test. As a result, if we transmit. We should have a soap backFault:

As we can see, the SOAP XML is identical to our prior answer, except it now includes a Fault element. A Fault element contains mistakes as well as status information.

 Conclusion

Web Service Testing ensures that all of the Application Programming Interfaces (APIs) offered by your application work as planned. They are comparable to unit tests in that they test particular portions of code as opposed to user interface components.


Web services tests, on the other hand, will often need to be built for each of the available versions of the API so that when a new version of a product is released, you can regression test the newest version of the API as well as all prior versions. This guarantees that legacy clients that are still utilising an older version of the API do not need to make any adjustments.

 

The post How to Perform Web Service Testing: The Definitive Guide appeared first on Talent500 blog.

]]>
https://talent500.com/blog/how-to-perform-web-service-testing-the-definitive-guide/feed/ 0
How To Build Selenium Tests Faster With Ranorex Webtestit https://talent500.com/blog/how-to-build-selenium-tests-faster-with-ranorex-webtestit/ https://talent500.com/blog/how-to-build-selenium-tests-faster-with-ranorex-webtestit/#respond Tue, 27 Jun 2023 07:33:07 +0000 https://talent500.com/blog/?p=37582  When it comes to a project like test automation, you should prioritise test creation before configuration and setup. You should […]

The post How To Build Selenium Tests Faster With Ranorex Webtestit appeared first on Talent500 blog.

]]>
 When it comes to a project like test automation, you should prioritise test creation before configuration and setup. You should avoid wasting time on repeated boilerplate code or resolving failing tests.

Why should you use Ranorex Webtestit?

Selenium Webdriver has become the most popular solution for web test automation. It is open-source, runs on major desktops, and supports the most popular programming languages. Unfortunately, it is time-consuming to set up and takes particular Selenium skills to master.

One of the initial steps in the setup process is to choose an IDE. You may utilise the Selenium WebDriver with a variety of IDEs, including Eclipse, IntelliJ, and NetBeans. Even the ancient Selenium IDE, which reached its end of life in 2017, has been revived.

We now have a new option, Ranorex Webtestit. This is an IDE for creating Selenium (or Protractor) UI tests for websites and web apps using Java or Typescript.

But, Ranorex Webtestit is much more than an IDE. It is a comprehensive web testing toolkit that minimises the time and effort required to set up and maintain a Selenium Webdriver test environment.

Quickly start setting up your test environment with Ranorex Webtestit:

Selenium WebDriver Vs Ranorex WebTestit Quick Setup:

Here is a quick comparison of the time taken to complete a basic setup for Selenium WebDriver and Ranorex WebTestit.

Selenium WebDriver (approx 2 hours to 2 days, depending on your experience)

Ranorex WebTestit (approx 15 minutes)

Ranorex Webtestit contains technologies that assist save time in automating web tests, such as the automatic creation of locators for web components, conditional execution logic, built-in test reporting, and much more, in addition to making setup considerably faster.

Set Up And Run A Sample Test

Download and install the free trial of Ranorex Webtestit to follow along with the below walkthrough steps

You’ll create a username and password, which will get you access to the Ranorex Webtestit user forum: https://discourse.webtestit.com/, which is an excellent location to receive support or communicate with the Ranorex team.

Step 1: Run Ranorex Webtestit and sign in. The Start screen will be shown.

Step 2: Select download sample project.

Step 3: Choose Java – Demoshop before clicking Download and Open. This sample project is for a fictitious web store, and it can be found here: http://demoshop.webtestit.com/

Step 4: The Ranorex Webtestit project view is displayed. The project window with the project tree may be seen on the left.

There are numerous Page Object files in the project tree. Each will represent a significant piece of a web page (not necessarily an entire web page). Utilizing a Page Object model removes the UI definition from your test code, making it easier to maintain and less likely to break your tests.

Step 5: Two test examples, TC1 and TC2, are shown in the page objects below. The first test case involves adding products to a cart and then checking out. The second test scenario validates the “quick checkout” procedure.

Step 6: The “Get Started” window can be located in the bottom left corner of Ranorex Webtestit.

Step 7:Open and click Add endpoint in the Execution panel.

Step 8: Choose the Local endpoint. “Local Chrome,” we’ll call it. Then choose Google Chrome browser after setting the Platform to Desktop. Next, select the Save endpoint option.

Step 9: The new endpoint is now visible in the Execution panel, and you can begin running the test suite.

Step 10: Click the Execute all test files button. Because this is your first test with Ranorex Webtestit, there may be various dependencies to load.

Subsequent test executions will not need to repeat this initial download, making them quicker. The progress may be tracked in the Log panel, which is located right below the Execution panel.

Step 11: Finally, the test run finishes. Now, Click on Show Report.

Step 12: The test run report shows the duration of the test, the number of test failures (if any), the number of test suites and test cases executed, and much more. To check the duration of each test case run, click the down arrow next to the TestSuite(Desktop) item.

Begin to Build Your Web Test

Thus far, you’ve seen a sample test run on your desktop; now, let’s look at the method for creating your test.

Step 1: Select New Project. Here a create new project dialogue box will appear.

Step 2: Provide a project name, choose a programming language, and then click Save. Ranorex Webtestit “scaffolds” your project with Maven, Apache’s build automation tool, and the widely used TestNG testing framework if you choose Java. The Project workspace then displays.

Step 3: Ranorex Webtestit may display a warning that it is no longer linked to Ranorex Selocity. If you haven’t already, Install the Ranorex Velocity add-on to Chrome DevTools.

Next, just launch Chrome, right-click on any site element, and select Inspect. Click Ranorex Selocity in the DevTools window, then Connect.

Step 4: Back to Ranorex Webtestit. Choose the New Page Object file. In the Project tree, a file called “newpofile.java” will emerge. Let’s rename this “mainPO.java”.

Step 5: Now, launch Chrome and navigate to your web application. Selection actions by right-clicking in the search box.

For the search box web element, you’ll see a list of possible selectors. Just copy and paste the desired one into your new Page Object file.

Step 6: When you return to Ranorex Webtestit, you’ll see a new element in the Elements panel. If the element’s name isn’t meaningful, you can change it. The name has been changed to “Search box” in the example below. Now press the Close button.

Step 7: Then, add the new element to your page object before using it in a test. Drag the element into the page object and then select an action, such as Clicking on the element or Typing into the element. Ranorex Webtestit will generate the necessary code for you.

Step 8: You may now begin coding your test. On the Project window, right-click on the tests folder and select Create => Test file. Ranorex Webtestit generates a new test file with boilerplate code for you. You may run your tests by calling the actions in the Page Object.

Step 9: After your test is finished, add an endpoint like in the Demoshop example above, and then run it.

Ranorex Webtestit is compatible with Windows, Mac, and Linux. Via the command line interface, it connects with applications such as TFS, Jenkins, Jira, Git, TestRail, and TravisCI.

Conclusion

If you use (or are considering using) Selenium WebDriver, you should certainly look at Ranorex Webtestit. It will then save you time by setting up your test project for you.

It will save you time with each web test you create by automatically applying the Page Object model, reducing boilerplate code, generating web element locators, and much more.

 

 

 

 

 

The post How To Build Selenium Tests Faster With Ranorex Webtestit appeared first on Talent500 blog.

]]>
https://talent500.com/blog/how-to-build-selenium-tests-faster-with-ranorex-webtestit/feed/ 0
Automate Browser Testing With LambdaTest https://talent500.com/blog/automate-browser-testing-with-lambdatest/ https://talent500.com/blog/automate-browser-testing-with-lambdatest/#respond Tue, 27 Jun 2023 07:29:39 +0000 https://talent500.com/blog/?p=37662 While transferring tests from a local Selenium Grid to a cloud-based Selenium Grid and assessing technologies to speed Selenium Testing, […]

The post Automate Browser Testing With LambdaTest appeared first on Talent500 blog.

]]>
While transferring tests from a local Selenium Grid to a cloud-based Selenium Grid and assessing technologies to speed Selenium Testing, automation engineers are constantly concerned about the scope of the changes. This worry is alleviated by LambdaTest, which requires just “infrastructural modifications” in the source code. The concurrency calculator in LambdaTest is an excellent starting point for calculating the number of concurrent sessions required to provide the ‘best’ test coverage.

LambdaTest is a platform that is used to speed up cross-browser testing operations. It works with a variety of browsers, browser versions, and desktop computers, as well as mobile devices for Appium testing. It is really simple to create an account on LambdaTest, after which you must build the necessary browser and platform capabilities using the LambdaTest Capabilities Generator.

 

Automation test results are available in LambdaTest’s Automation Dashboard. An overall test summary, exceptions encountered, console logs, network activity, and overall test information are all included in each test execution. The Automation Dashboard also includes a video clip of the testing procedure.

To execute the Test, below are the pre-requisites:

  • Account on LambdaTest
  • Java Development Kit (1.6 or higher)
  • Selenium Jars
  • TestNG Jars

To create a Maven project in IntelliJ IDEA, follow these steps:

Step 1: Go to File->New Project->Maven. 

Step 2: Select the Project SDK. The JDK is already installed on your machine.

Step 3: As shown in the below image, put the required Artifact coordinates.

Step 4: Once the project is created, we will make a .class file named GoogleSearchTest in the package named org.selenium4. The below image shows how the project structure will look after the creation of the file:

Step 5: Insert the necessary project dependencies in pom.xml

FileName – 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>org.example</groupId>

<artifactId>org.selenium4.CrossBrowserTest</artifactId>

<version>1.0-SNAPSHOT</version>

 <properties>

               <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>

</properties>

 <dependencies>

              <!– https://mvnrepository.com/artifact/com.github.lambdatest/lambdatest-tunnel-binary –>

              <dependency>

                       <groupId>org.testng</groupId>

                       <artifactId>testng</artifactId>

                       <version>6.9.10</version>

                       <scope>test</scope>

              </dependency>

              <dependency>

                       <groupId>org.seleniumhq.selenium</groupId>

                       <artifactId>selenium-java</artifactId>

                       <version>4.0.0-alpha-6</version>

              </dependency>

              <dependency>

                       <groupId>org.seleniumhq.selenium</groupId>

                       <artifactId>selenium-chrome-driver</artifactId>

                       <version>4.0.0-alpha-6</version>

               </dependency>

               <dependency>

                       <groupId>io.github.bonigarcia</groupId>

                       <artifactId>webdrivermanager</artifactId>

                       <version>4.1.0</version>

                </dependency>

               <!– https://mvnrepository.com/artifact/org.slf4j/slf4j-nop –>

               <dependency>

                        <groupId>org.slf4j</groupId>

                        <artifactId>slf4j-nop</artifactId>

                        <version>1.7.28</version>

                        <scope>test</scope>

                </dependency>

               <!– https://mvnrepository.com/artifact/junit/junit –>

               <dependency>

                        <groupId>junit</groupId>

                        <artifactId>junit</artifactId>

                        <version>4.13</version>

                        <scope>test</scope>

                </dependency>

                <dependency>

                         <groupId>com.github.lambdatest</groupId>

                         <artifactId>lambdatest-tunnel-binary</artifactId>

                         <version>1.0.4</version>

                 </dependency>

 </dependencies>

 <build>

       <defaultGoal>install</defaultGoal>

       <plugins>

             <plugin>

                    <artifactId>maven-compiler-plugin</artifactId>

                    <version>3.0</version>

                    <configuration>

                          <source>1.8</source>

                          <target>1.8</target>

                    </configuration>

              </plugin>

              <plugin>

                    <groupId>org.apache.maven.plugins</groupId>

                    <artifactId>maven-surefire-plugin</artifactId>

                    <version>2.12.4</version>

                    <configuration>

                          <suiteXmlFiles>

                                 <!– TestNG suite XML files –>

                                 <suiteXmlFile>testng.xml</suiteXmlFile>

                          </suiteXmlFiles>

                     </configuration>

              </plugin>

              <plugin>

                      <groupId>org.apache.maven.plugins</groupId>

                      <artifactId>maven-surefire-report-plugin</artifactId>

                      <version>3.0.0-M5</version>

              </plugin>

         </plugins>

    </build>

</project>

Step 6: Insert the code below into GoogleSearchTest.java.
FileName – GoogleSearchTest.java

package org.selenium4;

import org.junit.Assert;

import org.openqa.selenium.By;

import org.openqa.selenium.JavascriptExecutor;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.WebElement;

import org.openqa.selenium.remote.DesiredCapabilities;

import org.openqa.selenium.remote.RemoteWebDriver;

import org.testng.IExecutionListener;

import org.testng.annotations.AfterTest;

import org.testng.annotations.BeforeTest;

import org.testng.annotations.Parameters;

import org.testng.annotations.Test;

import java.net.MalformedURLException;

import java.net.URL;

public class GoogleSearchTest implements IExecutionListener {

        String URL = “https://www.google.com/”;

        String search_string = “Talent500”;

        WebDriver driver = null;

        WebElement search_box;

        String exp_title = “Talent 500”;

        public static String status = “passed”;

        // Update the username and access-key values with your fetched username and access key

        String username = “user-name”;

        String access_key = “access-key”;

        // You can also store them in your System variables and fetch them from there using below command

       // String username = System.getenv(“LT_USERNAME”);

       // String authkey = System.getenv(“LT_ACCESS_KEY”);

       @Override

      public void onExecutionStart() {

               System.out.println(“onExecutionStart”);

      }

      @BeforeTest

     @Parameters(value={“browser”,”version”,”platform”, “resolution”})

      public void testSetUp(String browser, String version, String platform, String resolution) throws Exception {

            DesiredCapabilities capabilities = new DesiredCapabilities();

            capabilities.setCapability(“build”, “Google Search – Talent500 using LambdaTest”);

            capabilities.setCapability(“name”, “Google Search – Talent500 using LambdaTest”);

            capabilities.setCapability(“platform”, platform);

            capabilities.setCapability(“browserName”, browser);

            capabilities.setCapability(“version”,version);

            capabilities.setCapability(“tunnel”,false);

            capabilities.setCapability(“network”,true);

            capabilities.setCapability(“console”,true);

            capabilities.setCapability(“visual”,true);

            try {

                 driver = new RemoteWebDriver(new URL(“http://” + username + “:” + access_key + “@hub.lambdatest.com/wd/hub”), capabilities);

             } catch (MalformedURLException e) {

                    System.out.println(“Invalid grid URL”);

             }

            System.out.println(“Started session”);

     }

    @Test

    public void test_Selenium4_GoogleSearch() throws InterruptedException {

           driver.navigate().to(URL);

           driver.manage().window().maximize();

           try {

                   /* Enter the search term in the Google Search Box */

                  search_box = driver.findElement(By.xpath(“//input[@name=’q’]”));

                  search_box.sendKeys(search_string);

                  search_box.submit();

                  /* driver.manage().timeouts().implicitlyWait(3, TimeUnit.SECONDS); */

                  /* Not a good programming practice, added for demonstration */

                  Thread.sleep(3000);

                  /* Click on the first result which will open up the LambdaTest homepage */

                  WebElement lt_link = driver.findElement(By.xpath(“//span[.=’Talent 500 …’]”));

                  lt_link.click();

                  /* driver.manage().timeouts().implicitlyWait(3, TimeUnit.SECONDS); */

                  /* Not a good programming practice, added for demonstration */

                  Thread.sleep(5000);

                  String curr_window_title = driver.getTitle();

                  Assert.assertEquals(curr_window_title, exp_title);

           } catch (Exception e) {

                   System.out.println(e.getMessage());

            }

     }

    @AfterTest

    public void tearDown() {

        if (driver != null) {

             ((JavascriptExecutor) driver).executeScript(“lambda-status=” + status);

             driver.quit();

        }

    }

    @Override

        public void onExecutionFinish() {

               System.out.println(“onExecutionFinish”);

    }

}

Step 7: Because we are utilising the TestNG framework, we utilise testng.xml to organise the tests. We used the same method to create test suites and tests.

The browser and operating system combinations against which we must execute a Google search for ‘talent500’ are specified in testng.xml.

FileName – testng.xml

<?xml version=”1.0″ encoding=”UTF-8″?>

<!DOCTYPE suite SYSTEM “http://testng.org/testng-1.0.dtd”>

<suite name=”Jenkins Maven Integration Tests” thread-count=”5″ parallel=”tests”>

<!– Add the location where the project is stored in your machine –>

<listeners>

         <listener class-name=”org.selenium4.GoogleSearchTest”/>

</listeners>

<test name=”Google Search Test – 1″>

        <parameter name=”browser” value=”Chrome”/>

        <parameter name=”version” value=”latest”/>

        <parameter name=”platform” value=”Windows 10″/>

        <parameter name=”resolution” value=”1600×1200″/>

        <classes>

              <class name=”org.selenium4.GoogleSearchTest”/>

        </classes>

</test>

 <test name=”Google Search Test – 2″>

        <parameter name=”browser” value=”MicrosoftEdge”/>

        <parameter name=”version” value=”84.0″/>

        <parameter name=”platform” value=”Windows 10″/>

        <parameter name=”resolution” value=”1920×1080″/>

        <classes>

               <class name=”org.selenium4.GoogleSearchTest”/>

        </classes>

</test>

 <test name=”Google Search Test – 3″>

       <parameter name=”browser” value=”Chrome”/>

       <parameter name=”version” value=”latest”/>

       <parameter name=”platform” value=”macOS Mojave”/>

       <parameter name=”resolution” value=”2048×1536″/>

       <classes>

             <class name=”org.selenium4.GoogleSearchTest”/>

       </classes>

</test>

 <test name=”Google Search Test – 4″>

       <parameter name=”browser” value=”Firefox”/>

       <parameter name=”version” value=”latest”/>

       <parameter name=”platform” value=”OS X Mavericks”/>

       <parameter name=”resolution” value=”2560×1440″/>

       <classes>

              <class name=”org.selenium4.GoogleSearchTest”/>

       </classes>

</test>

</suite>

In testng.xml, the Thread Count is set to ‘5’. This implies that we can only run a maximum of 5 tests on the Selenium Grid at the same time. It is crucial to remember, however, that the number of concurrent sessions on LambdaTest is determined by the plan chosen.

Step 8: The LambdaTest capabilities generator is used to produce the browser capabilities. While defining the browser capabilities, we must pick ‘Java’ as the language. The “visual” field of browser capabilities is set to “Yes” since we want to record the whole test execution.

Because the tests will be run on a distant Grid, we must utilise Remote Selenium WebDriver instead of the local Selenium WebDriver. The LambdaTest Selenium Grid is accessed via a login and access-key combination (accessible in the LambdaTest profile area).

driver = new RemoteWebDriver(new URL(“http://” + username + “:” + access_key + “@hub.lambdatest.com/wd/hub”), capabilities);

…………………………..

…………………………..

…………………………..

driver.navigate().to(URL);

driver.manage().window().maximize();

With everything in place, we are ready to run the tests on the Selenium Grid. To run the tests, right-click on testng.xml and select “Run…testng.xml,” as shown below.

To examine the execution status of a test on LambdaTest, navigate to the Automation Dashboard and pick the test(s) whose status you wish to monitor. Because our plan enables ‘5’ concurrent sessions, all 5 test scenarios are conducted in parallel on the LambdaTest Selenium Grid.

We could upgrade our LambdaTest account so the test team members can run more concurrent sessions on the LambdaTest Selenium Grid.

Step 10:Choose the test and examine the logs, exceptions, and so on to verify the activities taken throughout the test. You may also watch the “execution video” to see how the test execution went.

The following is the final execution snapshot from IntelliJ IDEA and LambdaTest, which confirms that the tests were successfully executed:

We have just shown how the benefits of Parallel Testing in Selenium may be expanded by shifting the test execution to a cloud-based Selenium Grid by LambdaTest. As a developer, you have the option of leveraging the benefits by using the programming language and test automation framework offered by LambdaTest.

Manual Testing With LambdaTest

Here are different methods for performing manual cross-browser testing using LambdaTest:

#1) Real-Time Browser Testing

Real-time testing on LambdaTest, as the name implies, is useful for testing your website or web app across many browsers, operating systems, and device emulators.

Along with major browsers like Chrome, Firefox, and Microsoft Edge, you may also test on browsers like Internet Explorer, Opera, Yandex, and others.

Get started with LambdaTest real-time testing,

Step 1: Go to LambdaTest real-time test and select the configuration on which you wish to perform testing. 

Step 2: Select the device type (like mobile or desktop), browsers (like Firefox, Internet Explorer, Chrome, etc.), display resolution and browser version.

Step 3: When running a real-time test, you may change the test setup, save screenshots to the gallery, record a video of the test, and more.

#2) Visual User Interface (UI) Testing

Visual bugs may be a huge turn-off for an online product’s clients or audience. There is a chance that the UI may appear good on a few browser and OS combinations but will look out of place on others. Responsive design testing is also an important aspect of visual UI testing since it allows you to evaluate the responsiveness of the UI on various platforms, browsers, and screen sizes.

LambdaTest may be used to test the following sorts of visual user interfaces:

  1. a) Screenshot Testing

It allows you to record screenshots for a variety of browsers and devices. To execute the test, input the test URL and pick the test setup as in real-time testing. You may also test your website with old browsers such as Internet Explorer.

You will also receive an email notification after the screenshots have been created, allowing you to save the screenshots for future use.

b) Responsive Testing

Responsive Testing on LambdaTest is excellent for determining the responsiveness of the UI across various devices and viewports. The responsiveness may be tested in Landscape and Portrait modes.

If you can’t locate the DeviceName in the ‘device list,’ you may add a custom viewport size on which to run responsive testing. If you encounter a problem with the responsiveness of your website, mark it as a bug so that your team members are aware of the problem.

There is an opportunity to designate a specific location as a Bug and provide comments so that the developers are aware of the problem right away.

Conclusion

If the goal is to test the code against a large number of browser and operating system combinations, test execution on a local Selenium Grid might become difficult. To avoid the expenditures associated with Selenium Grid’s ongoing maintenance and upgrade, adopting a cloud-based Selenium Grid is a more viable and cost-effective choice.

LambdaTest offers a cloud-based Selenium Grid that is scalable and secure, and it supports a wide range of programming languages and test automation frameworks. QA automation engineers may use LambdaTest to test their code against 2,000+ browser, platform, and device permutations.

Besides scalability and performance, LambdaTest’s great customer service, expanding LambdaTest community, and in-depth technical LambdaTest blogs help you expedite your testing efforts.

 

The post Automate Browser Testing With LambdaTest appeared first on Talent500 blog.

]]>
https://talent500.com/blog/automate-browser-testing-with-lambdatest/feed/ 0