Automation QA Testing Course Content

10 Powerful Command-Line Options of Common Linux Commands

 10 Powerful Command-Line Options of Common Linux Commands

1. cp -p (preserves timestamp)

You have definitely used the cp command to copy files or directories but do you know how to preserve timestamps while copying files or directories? Well, I didn't, at least until a few months ago. The cp - p command will preserve the timestamp when you copy a file. It's very useful, particularly for taking backup while changing files. The timestamp of the backed file is very important for troubleshooting etc.

$ cp - p $file


2. mkdir -p (create directory structure)

I am sure you have used the mkdir command to create directories and sometimes you might have been frustrated also while creating a complex directory structure one by one. You could have saved a lot of your time there if you knew the mkdir -p option which copies parent directories if it doesn't exist.

For example, when you copy a file /app/config/app.properties then it will create those directories automatically if they don't exist.

$ mkdir - p

3. scp -i (file copy without password using identity file)

This is another useful Linux option of a very common command like SCP which I discovered very late. The SCP command is used to securely copy files and directories from one host to another host. 

When you copy files using SCP, it asks for your username and password but if you are doing using script, you better want to do a password-less SCP and that's where scp -i helps. It can use an identity file to copy files from the remote host rather than using your current username. 

The Identity file contains ssh keys which are required to login to the remote host and copy files.

$ scp -i /home/appuser/.ssh/id_rsa_app 
        datauser@host:/app/data/outbound/stocks.xml


Here the identity file: id_rsa_app contains the private/public key for "datauser". The beauty of this option is that it won't ask for a password if you run this command

4. grep -c  (count number of matches)

Many times we are interested in knowing whether the file contains a matching word or not and the grep command just tells you that, but sometimes you also want to know how many times that particular keyword appears in files? I mean, could of the matching keyword. 

That's where grep -c helps. It will tell you the count of the matching keyword.

It's very useful to find details like how many times a user has logged in or how many files he has downloaded, or how many instruments you have received from upstream, and so on. For example,

$ grep -c "keyword" app.log

will print how many times "keyword" has appeared in the app.log file.


5. find -mtime (search files by modified time)

The find command is one of the most powerful commands in Linux and I have spent considerable time learning many useful find command options to improve my productivity. You can find all of them in my earlier post about 10 examples of find command in Linux. 

One of them is -mtime which is a shortcut for modified time and can be used to search files that have been modified recently like in hours or days. This is very useful while troubleshooting to check if anyone touched any important files. For example

$ find -mtime -3

will print the files that have been modified in less than 3 days or in the last three days. You can also search for more than 3 days like using +3 day


6. cd - (takes you to the previous directory)

We all have used cd but do you know how to go to the previous directory quickly? Well, that's what "cd -" do. It takes you to the previous directory. Yes, even without any option cd command is powerful. To be honest, I was lucky to know this item a little be earlier and since then I have been using it almost on a daily basis.

$ cd /home/test1/
$ cd /opt/bin/
$ cd -
/home/test1/


7. pwd -P (shows the actual path for soft linked directory)

This is again one of those basic Linux commands you will learn in your first Linux class but how many of you know this option? Let me ask you another way, how do you find the actual path of a folder which is linked? Well, that's where pwd-P helps. 

Just pwd will tell you the current folder with the path you followed, which could be linked also but pwd -P will tell you the actual folder location as shown in the following example:

$ pwd
/com/unicorn/app/current
$ pwd -P
/com/unicorn/app/1.0.23

8. tail -f (seeing live updates on a file)

This is another useful option for one of the most common Linux commands. If you haven't come across the tail, it is used to see the content of the file from the bottom, and the tail -f lets you see the live updates. This option is particularly useful to see if your log file is moving and what is logged at the moment.

$ tail -f app.log

9. netstat -p (print process id  of the process for connections)

This is one of the powerful Linux networking commands generally used to find the process which is listening on a particular port, but do you know how to print the process id which is listening on a port? Well, that's where netstat -p helps. It prints the process id and name of the program to which each socket belongs. This is useful because you now also kill the process if you don't want to.

$ netstat -nap | grep LISTEN

10. The for loop ( good for automation of repeated tasks)

This is not exactly a Linux command but a basic bash shell construct which allows you to automate some task. For example, if you have your application running on 5 production host and you want to check if they have enough space or not. Instead of going to each host using ssh and checking manually, which would take around 10 to 15 minutes, you can just run this shell script and get this done in seconds.

$ for h in host1, host2, host3, host4, host5; 
do ssh "${h}" "df -h /app/logs"; 
done



How to handle browser level notification using Selenium Webdriver

 

I am Automating some test cases using Selenium Webdriver and core Java,in chrome browser for one test case on clicking button I am getting browser level notification 'Show notifications with options Allow and Block'. I want to select Allow option. Can anyone know how to handle this kind of notifications using Selenium webdriver. please refer following snapshot for more details


For Old Chrome Version (<50):

//Create a instance of ChromeOptions class
ChromeOptions options = new ChromeOptions();

//Add chrome switch to disable notification - "**--disable-notifications**"
options.addArguments("--disable-notifications");

//Set path for driver exe 
System.setProperty("webdriver.chrome.driver","path/to/driver/exe");

//Pass ChromeOptions instance to ChromeDriver Constructor
WebDriver driver =new ChromeDriver(options);

For New Chrome Version (>50):

//Create a map to store  preferences 
Map<String, Object> prefs = new HashMap<String, Object>();

//add key and value to map as follow to switch off browser notification
//Pass the argument 1 to allow and 2 to block
prefs.put("profile.default_content_setting_values.notifications", 2);

//Create an instance of ChromeOptions 
ChromeOptions options = new ChromeOptions();

// set ExperimentalOption - prefs 
options.setExperimentalOption("prefs", prefs);

//Now Pass ChromeOptions instance to ChromeDriver Constructor to initialize chrome driver which will switch off this browser notification on the chrome browser
WebDriver driver = new ChromeDriver(options);

For Firefox :

    WebDriver driver ;
    FirefoxProfile profile = new FirefoxProfile();
    profile.setPreference("permissions.default.desktop-notification", 1);
    DesiredCapabilities capabilities=DesiredCapabilities.firefox();
    capabilities.setCapability(FirefoxDriver.PROFILE, profile);
    driver = new FirefoxDriver(capabilities);
    driver.get("http://google.com");


Java Interview Coding Challenge


 Problem #1

Consider the Following Problem:

  Write a short program that prints each number from 1 to 100 on a new line.

            For each multiple of 3, print "Fizz" instead of the number.

           For each multiple of 5, print "Buzz" instead of the number.

           For numbers which are multiple of both 3 and 5, print "FizzBuzz" instead of the number.


Solution:

public static void printFizzBuzz(int n) {

for(int i=1;i<=n;i++) {

if((i%3==0) && (i%5==0)) {

System.out.println("FizzBuzz");

}else if(i%3==0) {

System.out.println("Fizz");

}else if(i%5==0) {

System.out.println("Buzz");

}else {

System.out.println(i);

}

}

}

---------------------------------------------------------------------------------------------------------

Problem #2

Given an array of integers, return indices of the two numbers such that they add up to a specific target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

Example:

      Given nums = [2,7,11,15], target = 9,

                Because nums[0] + nums[1] = 2 + 7 =9,

                return [0,1] 

Solution:

public class GetTwoSum{

protected static int[] getTwoSum(int[] numbers, int target) {

//create a Map

Map<Integer, Integer>visitedNumbers = new HashMap<>();

for(int i = 0; i < numbers.length; i++) {

int delta = target - numbers[i];

if(visitedNumbers.containsKey(delta)) {

return new int[] {i, visitedNumbers.get(delta) };

}

visitedNumbers.put(numbers[i], i);

}

return new int[] {-1, -1};

}

public static void main(String[] args) {

printFizzBuzz(100);


int[] numbers = new int[] {2,3,7,4,8};

int target = 6;

int[] result = getTwoSum(numbers, target);

System.out.println(result[0] +" "+result[1]);

}


}

===============================================================

Problem # 3

               ReverseString


public class Ch03ReverseString {


public static void main(String[] args) {

String str = "Hello World!";

System.out.println(reverseWithStringBuilder(str));

System.out.println(reverseManually(str));


}


private static String reverseManually(String str) {

// Create object fir StringBuilder

StringBuilder sb = new StringBuilder();

for(int i = str.length() - 1; i >= 0; i--) {

sb.append(str.charAt(i));

}

return sb.toString();

}


private static String reverseWithStringBuilder(String str) {

return new StringBuilder(str)

.reverse()

.toString();

}


}

----------------------------------------------------------------------------------------------------------------------

Problem #4

        Implement a Stack in java


public class Stack {


private int array[];

private int top;

private int capacity;

Stack(int capacity){

this.array=new int[capacity];

this.capacity=capacity;

this.top=-1;

}

public void push(int item) {

if(isFull()) {

throw new RuntimeException("Stack is full");

}

array[++top]=item;

}

public boolean isFull() {

return top == capacity - 1;

}



/**

* Pop will return top item and remove from the stack and update the stack

* @return

*/

public int pop() {

if(isEmpty()) {

throw new RuntimeException("Stack is empty");

}

return array[top--];

}

/**

* peek will return the top item and wont remvoe the item from stack

* @return

*/

public int peek() {

if(isEmpty()) {

throw new RuntimeException("Stack is empty");

}

return array[top];

}



public boolean isEmpty() {

return top==-1;

}

}

-------------------------------------------------------------------------------------------------------------------

Problem # 5

      Reverse an Integer

public class ReverseInteger {


public int reverse(int input) {

int reversed=0;

while(input!=0) {

reversed = reversed*10 + input % 10;

input /=10;

if(reversed > Integer.MAX_VALUE || reversed < Integer.MIN_VALUE) {

return 0;

}

}

return reversed;

}

public static void main(String[] args) {

System.out.println(new ReverseInteger().reverse(123));


}


}

-------------------------------------------------------------------------------------------------------------

Problem #6

     Convert from Integer to Roman numeral

    I -->1

  II -->2

 III -->3

IV -->4

V -->5

VI -->6

X -->10

L -50

C- 100

D -500

M -1000

public class IntegerToRoman {


public static String intToRoman(int num) {

String[] thousands = new String[]{"","M","MM","MMM"};

String[] hundreds = {"","C","CC","CCC","CD","D","DC","DCC","DCCC","CM"};

String[] tens = {"","X","XX","XXX","XL","L","LX","LXX","LXXX","XC"};

String[] units = {"","I","II","III","IV","V","VI","VII","VIII","IX"};

return thousands[num / 1000] +

hundreds[(num%1000)/100] +

tens[(num % 100) / 10] +

units[num % 10];

}

public static void main(String[] args) {

System.out.println(intToRoman(124));


}

-----------------------------------------------------------------------------------------------------------------------

Problem # 7

 Convert Roman numeral to Integer

public int romanToInt(String s) {

Map<Character,Integer>map = new HashMap();

map.put('I', 1);

map.put('V', 5);

map.put('X', 10);

map.put('L', 50);

map.put('C', 100);

map.put('D', 500);

map.put('M', 1000);

int result = 0;

for(int i=0;i<s.length();i++) {

if(i>0 && map.get(s.charAt(i)) >map.get(s.charAt(i-1))){

result += map.get(s.charAt(i)) - 2 *map.get(s.charAt(i-1));

} else {

result +=map.get(s.charAt(i));

}

}

return result;

}

=================================================================

Problem # 8

Longest Palindrome Substring

public class LongestPalindromeSubstring {

 int resultStart;

 int resultLength;

public String longestPalindrome(String s) {

int strLength = s.length();

if(strLength < 2) {

return s;

}

for(int start = 0; start < strLength -1; start++) {

expandRange(s,start,start);

expandRange(s,start,start + 1);

}

return s.substring(resultStart,resultStart + resultLength);

}

private void expandRange(String str, int begin, int end) {

while(begin >= 0 && end < str.length() && str.charAt(begin) == str.charAt(end)) {

begin--;

end++;

}

if(resultLength < end -begin -1) {

resultStart = begin +1;

resultLength = end - begin -1;

}

}

}

----------------------------------------------------------------------------------------------------------------------

Problem # 9:

    Detect Capital

    Given a word, you need to judge whether the usage of capitals in it is right or not.

 Right Usage:

  1. All letters in this word are capitals
  2. All letters in this word are not capitals
  3. Only the first letter in this word is capital   
  • Example:
  • All caps : "USA"     
  •     

public class DetectCapital {

/**
* Approach 1 : The "clever" solution
* Count the number of uppercase letters
* if it is zero or length of string, return true
* if it is not 1, return false
* if it is 1 and the first letter is uppercase, return true
* Time Complexity -- O(N)
* can we do better?
* Disadvantage:
* Quit at the first wrong character
*  valid --AAAAA
*  Valid : aaaa
*  valid : Aaaaa
* @param word
* @return 
*/
public static boolean detectCapitalUse(String word) {
int numberOfCapitals = 0;
for(int i = 0; i < word.length(); i++) {
if(Character.isUpperCase(word.charAt(i))) {
numberOfCapitals++;
}
}
if(numberOfCapitals == word.length() || numberOfCapitals == 0) return true;
return numberOfCapitals == 1 && Character.isUpperCase(word.charAt(0));
}
/**
* Approach 2:
*
*/
public static boolean detectCapitalUse2(String word) {
//Case 1 : All Capitals
int n = word.length();
if(Character.isUpperCase(word.charAt(0)) && Character.isUpperCase(word.charAt(1))) {
for(int i = 2; i< n; i++) {
if(Character.isLowerCase(word.charAt(i))) {
return false;
}
}
}else {
for(int i = 1; i<n;i ++) {
if(Character.isUpperCase(word.charAt(i))) {
return false;
}
}
}
return true;
}
/**
* Approach using LAMBDA 
* Time Complexity - O(N)
* @param args
*/
public boolean detectCapitalUse3(String word) {
if(word.length() <= 1) return true;
Predicate<Character> correctCase = Character::isLowerCase;
if(Character.isUpperCase(word.charAt(0)) && Character.isUpperCase(word.charAt(1))) {
correctCase = Character::isUpperCase;
}
for(int i = 1; i < word.length(); i++) {
if(!correctCase.test(word.charAt(i))) return false;
}
return true;
}

SOAPUI TOOL

 1. What is SoapUI

2. Why to use SoapUI 3. How to Download and Install SoapUI 4. Difference between SoapUI Open Source and Paid versions What is SoapUI ------------------------ API Testing Tool For manual and automation testing of SOAP and REST APIs SOAP UI is the leading open source cross-platform API Testing tool • SOAPUI allows testers to execute automated functional, regression, compliance, and load tests on different Web API. • SOAPUI supports all the standard protocols and technologies to test all kinds of API's. • SOAPUI interface is simple that enables both technical and non-technical users to use seamlessly. Why to use SoapUI ------------------------------ 1. To create quick and efficient API tests 2. To create API functional, performance and security tests 3. To create API Testing automation framework
4. Supported Protocols/Technologies Step 1 : Download SoapUI from - https://www.soapui.org/downloads/late... Step 2:Installing SoapUI on Windows











Create a SOAP Project, Test Suite, Test Case 1. Create a SOAP API Project 2. Add WSDL 3. Create Test Suite - Test Cases 4. Add Assertions 5. Run Test Step - Test Case - Test Suite 6. Run in sequence and in parallel 7. Create API Documentation • WSDL: • https://www.dataaccess.com/webservicesserver/NumberConversion.wso?WSDL • https://www.dataaccess.com/webservicesserver/TextCasing.wso?WSDL • https://footballpool.dataaccess.eu/info.wso?WSDL • http://webservices.oorsprong.org/websamples.countryinfo/CountryInfoService.wso?wsdl

Create a Rest Project, Rest Request, Test case with Parameters 1. Create a REST Project 2. Add a REST request 3. Add request parameters 4. Create a Test Case 5. Add assertions 6. Run and Validate Rest API’s https://restcountries.eu/rest/v2/all

Order of Execution:


Difference between valueOf and parseInt method in Java

Both valueOf and parseInt methods are used to convert String to Integer in Java, but there are subtle difference between them

If you look code of parseInt() and valueOf() method from java.lang.Integer class, you will find that actual job of converting String to integer is done by parseInt() method, valueOf() just provide caching of frequently used Integer objects, Here is code snippet from valueOf() method which makes things clear:
ublic static Integer valueOf(String s) throws NumberFormatException {
        return Integer.valueOf(parseInt(s, 10));
}

This method first calls parseInt() method, in order to convert String to primitive int, and then creates Integer object from that value. You can see it internally maintains an Integer cache. If primitive int is within range of cache, it returns Integer object from pool, otherwise it create a new object.
public static Integer valueOf(int i) {
        if(i >= -128 && i <= IntegerCache.high)
            return IntegerCache.cache[i + 128];
        else
            return new Integer(i);
}

There is always confusion, whether to use parseInt() or valueOf() for converting String to primitive int and java.lang.Integer, I would suggest use parseInt() if you need primitive int and use valueOf() if you need java.lang.Integer objects. Since immutable objects are safe to be pooled and reusing them only reduces load on garbage collector, it's better to use valueOf() if you need Integer object



Java OOPS - Constructor/Inheritance


Constructor in java is a special type of method that is used to initialize the object.
Java constructor is invoked at the time of object creation. It constructs the values i.e.
provides data for the object that is why it is known as constructor.

Rules for creating java constructor

There are basically two rules defined for the constructor.
1.   Constructor name must be same as its class name
2.   Constructor must have no explicit return type
3.   A Java constructor cannot be abstract, static, final, and synchronized

Types of java constructors

There are two types of constructors:
1.   Default constructor (no-arg constructor)
2.   Parameterized constructor
java constructor

Java Default Constructor

A constructor that have no parameter is known as default constructor.

Syntax of default constructor:

1.   Accessmodifier  <class_name>(){l+s}  

NOTE:  If there is no constructor in a class, compiler automatically creates a default

constructor.

If a class has default constructor, while creating object for the class no need to
provide any parameter values.
Classname refvar=new classname();

Q) What is the purpose of default constructor?

Default constructor provides the default values to the object like 0, null etc. depending on
 the type.

Java parameterized constructor

A constructor that have parameters is known as parameterized constructor.
2.   Accessmodifier  <class_name>(datatype p1,datatype p2,…){l+s}  

Why use parameterized constructor?

Parameterized constructor is used to provide different values to the distinct objects
If a class has parameterized constructor, while creating object for the class need to provide
 parameter values.
Classname refvar=new classname(p1value,p2value,p3 value);

Constructor Overloading in Java

Constructor overloading is a technique in Java in which a class can have any
number of  constructors that differ in parameter lists and datatype.The compiler differentiates
 these constructors by taking into account the number of parameters in the list and their
 type.

Difference between constructor and method in java

There are many differences between constructors and methods. They are given below.
Java Constructor
Java Method
Constructor is used to initialize the state of an object.
Method is used to expose behaviour of an object.
Constructor must not have return type.
Method must have return type.
Constructor is invoked implicitly.
Method is invoked explicitly.
The java compiler provides a default constructor if you don't have any constructor.
Method is not provided by compiler in any case.
Constructor name must be same as the class name.
Method name may or may
 not be same as class name.

Quiz On Constructor:
1)public class Test{

void Test{
System.out.println("Like ThisVideo");
}

public static void main(String[] args){
new Test();
}


}
1)Like ThisVideo
ii)No Output
iii)Exception will be thrown
iv)compilation issue
2)