Generate and pass API token to subsequent request in JMETER

Step 1: Open JMeter -> Add Thread Group to the Test Plan -> Add Http request sampler

Step 2: Select HTTP Request sampler and change the name if you wish to.

Step 3: In the Basic tab Enter following information:

Protocol – http/https

Server Name or IP – Enter server name/IP to generate the token. e.g abc.amazoncognito.com

HTTP Request – POST

Path: Enter the query parameter to generate the token. eg. oauth2/token

Step 4: In the parameter tab enter the following information:

Name: grant_type Value: client_credentials

Name: client_id Value: Enter client ID

Name: client_secret Value: Enter client secret

Step 5: Add Post Processor JSON Extractor in the Thread group.

Step 6: Enter following information:

Names of created variables: accessToken

JSON Path expression: access_token

Step 7: Add BeanShell Assertion in the thread group and add following code in the script section.

${__setProperty(bearerTokenforanotherThread, ${accessToken})};

Step 8: Add another thread group to add request which will be using the token generated in above steps.

Step 9: Add BeanShell PreProcessor in the Thread to store the token value and add following code in script section of BeanShell PreProcessor

String bearerToken = ${__property(bearerTokenforanotherThread)}.

Step 10: Add HttpRequest in the thread group and enter following information.

Protocol: http/https

Server Name or IP: Name or IP of API server

HTTP Request: GET/POST/PUT/DELETE

Path: URI Path of the request

Step 11: Select http request -> right click ->Add->config element->HTTP Header Manager
Step 12: Add following code in http header manager:
Name: Authorization
Value: Bearer ${__property(bearerTokenforanotherThread)

Step 13: Run the plan. Token should be generated and pass to the subsequent request in next thread group.

JAVA program to add top two maximum number of an Array.

Below program i have written to add top two max number of an Array:

package com.company;

public class ArrayDemo {


public int addAge(int [] age){

int largest = age[0];
int secondlargest = age[0];

for (int i=1;i<age.length;i++){

if ( age[i] > largest ){
secondlargest = largest;
largest = age[i];
}
if (age[i] < largest && age[i] > secondlargest){
secondlargest = age[i];
}

}


System.out.println("largest number is = " +largest);

System.out.println("Second largest number is = " +secondlargest);
int total = largest + secondlargest;
return total;
}


public static void main (String[] args){

int [] age = {12,88,13,4,15,25,5,49,87};

ArrayDemo arrayAddition = new ArrayDemo();

int total = arrayAddition.addAge(age);

System.out.println(total);


}
}

Selenium – For loop to navigate to the web element list and verify list item.

Step 1: Store item of the list in a List using findElements

List<WebElement> searchResultlist = Driver.driver.findElements(By.xpath("//span[@class='document-name']"));

Step 2: Use for loop to traverse in the list and verify the text using IF condition.
To make sure input by the user and text from the application are in same case, convert both the strings in UPPER case and match.

for (WebElement resultList : searchResultlist){
     System.out.println(resultList.getText());
     if (resultList.getText().toUpperCase().contains(DocumentNumber.toUpperCase())){
         resultList.click();
         break;
    }
}

How to set JAVA Path in Linux machine

Run below command to install JAVA

yum install java-1.8*

Once the installation is completed, run below command to check JAVA Version.

java -version

Above command should give you the following result.

openjdk version "1.8.0_232"
OpenJDK Runtime Environment (build 1.8.0_232-b09)
OpenJDK 64-Bit Server VM (build 25.232-b09, mixed mode)

Run below command to find the JAVA path.

find /usr/lib/jvm/java-1.8* | head -n 3

Above command should give you the following results.

/usr/lib/jvm/java-1.8.0
/usr/lib/jvm/java-1.8.0-openjdk
/usr/lib/jvm/java-1.8.0-openjdk-1.8.0.232.b09-0.el7_7.x86_64

Use last path from above result to update the bash profile.

To update the bash profile run below command.

vi .bash_profile

Update bash_profile as below.

JAVA_HOME = /usr/lib/jvm/java-1.8.0-openjdk-1.8.0.232.b09-0.el7_7.x86_64
PATH=$PATH:$JAVA_HOME:$HOME/.local/bin:$HOME/bin

Save and Exit the bash_profile.

Refresh the bash profile using the below command.

source ~/.bash_profile

After refresh, run the following command to verify the JAVA path.

echo $JAVA_HOME

Output of the above command should be:

/usr/lib/jvm/java-1.8.0-openjdk-1.8.0.232.b09-0.el7_7.x86_64

How to solve login fail issue in JMETER Script

After recording the script in JMETER, if we run the script without making any changes, login fails.

To solve this problem, please follow below steps.

After recording, select login page to see the http request.

In http request, under parameter table, nonce appears at the top of the table with some random values as shown in image below.

Delete “nonce” from the table and run the script again.

Login successful !!

Web application Performance Testing using Jmeter

  • Go to bin folder of apache-jmeter
  • Launch jmeter by clicking jmeter.bat
  • In Jmeter, Go to File -> Templates
  • Select Recording from the Select Template drop down.
  • Click Create and enter application url in hostToRecord text box.
  • Click Create. It will create the performance test plan.
  • To start the recording, select “HTTP(S) Test Script Recorder”
  • After clicking the start button, Root CA certificate will be generated.
  • This certificate is valid only for 7 days. Start the browser and import the certificate.
  • Go to IE->Internet Options->Contet->Certificates-Import
  • Once the certificate imported successfully, change the IE LAN settings to localhost with the port mentioned in JMeter recorder global settings.
  • Once the above setting is done. Enter the application url in IE and start recording the performance scenario.
  • Once the recording completed, this is how the Jmeter will look.
  • Add summary report and aggregate report in the plan to get the performance results.
  • Right click on Test Plan -> Add -> Listener -> Summary Report/Aggregate Report
  • Performance Test Plan is ready to run.
  • Select Thread Group. Change the Thread number as per the requirement and click green button to start the performance testing.
  • Once the execution finished, summary and aggregate report will be generated.

Lambda expression in Selenium

How to use JAVA Lambda expression to select the value from drop down in selenium.

Let say you have a list and want to select a value from it.

<ul class = 'list'> 
 <li data-value="value1" class="option selection focus">Value1</li>
 <li data-value="value2" class="option selection focus">Value2</li> 
  <li data-value="value3" class="option selection focus">Value3</li> 
 <li data-value="value4" class="option selection focus">Value4</li> 

Below code can select the value from drop down as per the parameter passed in the method  

Public void selectValueFromDropDown(String SearchValue)
WebElement element = Driver.driver.findElements(By.xpath("//ul[@class='list']//li")).stream().
 filter(e-> e.getText().equalsIgnoreCase(SearchValue)).findFirst().get();
         element.click();

CloudFormation template for EC2 and Security Group creation

Below template can be used to create EC2 instance and associate Security Group with the EC2 instance which enables SSH.

AWSTemplateFormatVersion : 2010-09-09
Description: Template to create an EC2 instance and enable SSH access to the instance
Parameters:
KeyName:
Description: Name of an existing EC2 KeyPair to enable SSH access to the instance
Type: 'AWS::EC2::KeyPair::KeyName'
ConstraintDescription: Provide the name of an existing SSH key pair Resources:
MyEC2Instance:
Type: 'AWS::EC2::Instance'
Properties:
InstanceType: t2.micro
ImageId: ami-0f2176987ee50226e
SecurityGroups:
- !Ref InstanceSecurityGroup
KeyName: !Ref KeyName
Tags:
- Key: Name
Value: My First CF Instance
InstanceSecurityGroup:
Type: 'AWS::EC2::SecurityGroup'
Properties:
GroupDescription: Enable SSH access via port 22
SecurityGroupIngress:
IpProtocol: tcp
FromPort: 22
ToPort: 22
CidrIp: 0.0.0.0/0
Outputs:
InstanceID:
Description: The Instance ID
Value: !Ref MyEC2Instance

Save above file with .yml extension.

The only thing we need to change in the above template is ImageId: ami-0f2176987ee50226e .

Image IDs are based on the region. Login to your AWS account Go to your EC2 and Click Launch Instance. Copy Image ID as shown in image below and past it in the template.

Template is ready to create the stack.

In AWS console, Go to Services -> Manage & Governance -> CloudFormation

Click “Create New Stack” button.

Choose file from your location and Click Next

Enter Stack name and Select key pair from the drop down and click Next.

In the option page, Click Next

In the Review page, Click Create

Stack creation started.

Once the process completed. Go to EC2 page. You will see instance created with Security Group.

Docker certificate signed error

$ docker ps

error during connect: Get https://192.168.99.100:2376/v1.37/containers/json: x509: certificate signed by unknown authority

Above error appears a lot in docker if any changes made in the settings. Or sometimes if system is restarted.

How to resolve this error?

I executed below steps to solve this error:

Go to your docker toolbox folder and run the below command.

@S500719W10N MINGW64 /c/Program Files/Docker Toolbox

$ docker-machine regenerate-certs default

Regenerate TLS machine certs?  Warning: this is irreversible. (y/n): y

Regenerating TLS certificates

Regenerating local certificates

…..

After running the above command problem should be resolved. In case if problem still not resolved, then follow the below steps:

Use SSH to login to virtual machine:

$ docker-machine ssh default
docker@default:~$ sudo vi /var/lib/boot2docker/profile
Add a NO_PROXY setting
# replace with your oproxy environment settings
export “HTTP_PROXY=http://PROXY:PORT”
export “HTTPS_PROXY=http://PROXY:PORT”
# you can add more no_proxy with your environment.
export “NO_PROXY=192.168.99.,.local,169.254/16,.example.com,192.168.59.

Restart docker
docker@default:~$ sudo /etc/init.d/docker restart
docker@default:~$ exit

$ docker-machine regenerate-certs default

Regenerate TLS machine certs?  Warning: this is irreversible. (y/n): y

Regenerating TLS certificates

Waiting for SSH to be available…

Detecting the provisioner…

Copying certs to the local machine directory…

Copying certs to the remote machine…

Setting Docker configuration on the remote daemon…

$ docker-machine restart default

Restarting “default”…

(default) Check network to re-create if needed…

(default) Windows might ask for the permission to configure a dhcp server. Sometimes, such confirmation window is minimized in the taskbar.

(default) Waiting for an IP…

Waiting for SSH to be available…

Detecting the provisioner…

Restarted machines may have new IP addresses. You may need to re-run the `docker-machine env` command.

$ eval $(docker-machine env default)

$ docker-machine ls

NAME      ACTIVE   DRIVER       STATE     URL                         SWARM   DOCKER     ERRORS

default   *        virtualbox   Running   tcp://192.168.99.101:2376           v18.09.6

Problem solved !!