5/18/19

API/Webservices Testing using RestAssured (Part 1)




Rest Assured : Is an API designed for automating REST services/Rest API's

Pre-Requisites

Java
Free videos: https://www.youtube.com/watch?v=ms3NggvNW40&list=PLUDwpEzHYYLv9v8aRuNi67vZ81cW2ksze
Eclipse

TestNG : Framework implemented on top of Java used for organizing test cases, test suites.
Free videos: https://www.youtube.com/playlist?list=PLUDwpEzHYYLsWENabqeETzgPLbmwqhM45
Maven

Setup

1) Creating Maven project in Eclipse
2) We need to update pom.xml with required dependencies

- RestAssured  https://mvnrepository.com/artifact/io.rest-assured/rest-assured
- TestNG       https://mvnrepository.com/artifact/org.testng/testng
- Json-simple  https://mvnrepository.com/artifact/com.googlecode.json-simple/json-simple
- apache poi   https://mvnrepository.com/artifact/org.apache.poi/poi
       https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml



Test Case 1) Weather API - Validate status code & Status line

http://restapi.demoqa.com/utilities/weather/city/

Request Type: GET

http://restapi.demoqa.com/utilities/weather/city/Hyderabad

SUCCESS RESPONSE
{
“City”: “Hyderabad”,
“Temperature”: “31.49 Degree celsius”,
“Humidity”: “62 Percent”,
“Weather Description”: “scattered clouds”,
“Wind Speed”: “3.6 Km per hour”,
“Wind Direction degree”: “270 Degree”
}

STATUS CODE : 200
Status Line: HTTP/1.1 200 OK"


Code Snippet

import org.testng.Assert;
import org.testng.annotations.Test;

import io.restassured.RestAssured;
import io.restassured.http.Method;
import io.restassured.response.Response;
import io.restassured.specification.RequestSpecification;

public class TC001_GET_Request {

@Test
void getweatherDetails()
{
//Specify base URI
RestAssured.baseURI="http://restapi.demoqa.com/utilities/weather/city";
//Request object
RequestSpecification httpRequest=RestAssured.given();
//Response object
Response response=httpRequest.request(Method.GET,"/Hyderabad");
//print response in console window
String responseBody=response.getBody().asString();
System.out.println("Response Body is:" +responseBody);
//status code validation
int statusCode=response.getStatusCode();
System.out.println("Status code is: "+statusCode);
Assert.assertEquals(statusCode, 200);
//status line verification
String statusLine=response.getStatusLine();
System.out.println("Status line is:"+statusLine);
Assert.assertEquals(statusLine, "HTTP/1.1 200 OK");
}
}


Test Case 2) Register Customer API

Request Type: POST
http://restapi.demoqa.com/customer/register

BODY

{
   “FirstName” : “value”
   “LastName” : “value”,
   “UserName” : “value”,
   “Password” : “value”,
   “Email”        : “Value”
 }

SUCCESS RESPONSE

{
“SuccessCode”: “OPERATION_SUCCESS”,
“Message”: “Operation completed successfully”
}

STATUS CODE : 201

Code Snippet

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

import io.restassured.RestAssured;
import io.restassured.http.Method;
import io.restassured.response.Response;
import io.restassured.specification.RequestSpecification;

public class TC002_POST_Request {

@Test
void RegistrationSuccessful()
{

//Specify base URI
RestAssured.baseURI="http://restapi.demoqa.com/customer";

//Request object
RequestSpecification httpRequest=RestAssured.given();


//Request paylaod sending along with post request
JSONObject requestParams=new JSONObject();

requestParams.put("FirstName","JohnXYZ");
requestParams.put("LastName","XYZJohn");
requestParams.put("UserName","JohnXYZ");
requestParams.put("Password","JohnXYZxyx");
requestParams.put("Email","JohnXYZ@gmail.com");

httpRequest.header("Content-Type","application/json");

httpRequest.body(requestParams.toJSONString()); // attach above data to the request

//Response object
Response response=httpRequest.request(Method.POST,"/register");


//print response in console window

String responseBody=response.getBody().asString();
System.out.println("Response Body is:" +responseBody);

//status code validation
int statusCode=response.getStatusCode();
System.out.println("Status code is: "+statusCode);
Assert.assertEquals(statusCode, 201);

//success code validation
String successCode=response.jsonPath().get("SuccessCode");
Assert.assertEquals(successCode, "OPERATION_SUCCESS");

}


}

Test Case 3) Google Map API - Validating Headers

https://maps.googleapis.com/maps/api/place/nearbysearch/xml?location=-33.8670522,151.1957362&radius=1500&type=supermarket&key=AIzaSyBjGCE3VpLU4lgTqSTDmHmJ2HoELb4Jy1s

SUCCESS RESPONSE : Returns list of super markets

"Headers:
Content-Encoding →gzip
Content-Type →application/xml; charset=UTF-8
Server →scaffolding on HTTPServer2
"

Code Snippet

import org.testng.Assert;
import org.testng.annotations.Test;

import io.restassured.RestAssured;
import io.restassured.http.Method;
import io.restassured.response.Response;
import io.restassured.specification.RequestSpecification;

public class TC003_GET_Request {

@Test
void googleMapTest()
{

//Specify base URI
RestAssured.baseURI="https://maps.googleapis.com";

//Request object
RequestSpecification httpRequest=RestAssured.given();

//Response object
Response response=httpRequest.request(Method.GET,"/maps/api/place/nearbysearch/xml?location=-33.8670522,151.1957362&radius=1500&type=supermarket&key=AIzaSyBjGCE3VpLU4lgTqSTDmHmJ2HoELb4Jy1s");

//print response in console window
String responseBody=response.getBody().asString();
System.out.println("Response Body is:" +responseBody);

//validating headers
String contentType=response.header("Content-Type");// capture details of Content-Type header
System.out.println("Content Type is:"+contentType);
Assert.assertEquals(contentType, "application/xml; charset=UTF-8");

String contentEncoding=response.header("Content-Encoding");// capture details of Content-Encoding  header
System.out.println("Content Encoding is:"+contentEncoding);
Assert.assertEquals(contentEncoding, "gzip");

}

}




4/9/19

Python Interview Questions and Answers Part-2


29)  Tell me about a few string operations in Python?
Here are the most commonly used text processing methods.

#Creating strings
name = "John" # a string
mychar = 'S' # a character
print(name)
print(mychar)

#you can also use the following syntax to create strings.
name1 = str() # this will create empty string object
name2 = str("newstring") # string object containing 'newstring'
print(name1)
print(name2)

#====Strings are immutable====
str1="welcome"
str2="welcome"

print(id(str1),id(str2))  #57660416 ,57660416

str2=str2+"to python"
print(id(str1),id(str2))  #57660416 ,59955200(changed means immutable)

#==== + and * with string=====
str="welcome"
print(str+" to Python programming") # welcome to Python programming
print(str *3) #welcomewelcomewelcome

#=======Slicing ==============
str="welcome"
print(str[1:3]) #el
print(str[:6])#welcom
print(str[4:])#ome
print(str[1:-1]) #elcom #elimate 1 char from end
print(str[1:-2]) #elco  #eleminate 2 chars from end

#=======String Functions in Python=======
print(len("hello")) #5
print(max("abc")) #c
print(min("abc")) #a

#========in  and not in  operators=====
s1 = "Welcome"
print("come" in s1)# True
print("come" not in s1) #False

#========Strings comparison=======
print("tim" == "tie") #False
print("free" != "freedom") #True
print ("arrow" > "aron") #True
print ("right" >= "left") #True
print ("teeth" < "tee") #False
print ("yellow" <= "fellow") #False
print ("abc" > "") #True

#======Testing strings===========
s = "welcome to python"
print(s.isalnum()) #False
print("Welcome".isalpha()) #True
print("2012".isdigit()) #True
print("first Number".isidentifier())#False
print(s.islower()) #True
print("WELCOME".isupper()) #True
print(" ".isspace()) #True

#======Searching for Substrings========
s = "welcome to python"
print(s.endswith("thon")) #True
print(s.startswith("good")) #False
print(s.find("come")) #3
print(s.find("become")) #-1
print(s.count("o")) #3

#=========Converting Strings==========
s = "String in PYTHON"
s1 = s.capitalize()
print(s1) #String in python

s2 = s.title()
print(s2)#String In Python

s3 = s.lower()
print(s3) #string in python

s4 = s.upper()
print(s4) #STRING IN PYTHON

s5 = s.swapcase()
print(s5) #sTRING IN python

s6 = s.replace("in", "on")
print(s6) #String on PYTHON

print(s) #String in PYTHON

30) How do you create a list which is a reverse version on another list in Python?
Python provides a function called reversed(), which will return a reversed iterator. Then, one can use a list constructor over it to get a list.

Example:
a =[10,20,30,40,50]
print(a)
b = list(reversed(a))#[10, 20, 30, 40, 50]
print(b) #[50, 40, 30, 20, 10]

31) What is a dictionary in Python?
In Python, dictionaries are kind of hash or maps in another language. Dictionary consists of a key and a value. Keys are unique, and values are accessed using keys. Here are a few examples of creating and accessing dictionaries.

Examples:

######Retrieving, modifying and adding elements in the dictionary########
friends = {'tom' : '111-222-333','jerry' : '666-33-111'}
print(friends) #{'tom': '111-222-333', 'jerry': '666-33-111'}

#Retrieving elements from the dictionary
print(friends['tom']) # 111-222-333

#Adding elements into the dictionary
friends['bob'] = '888-999-666'
print(friends) #{'tom': '111-222-333', 'jerry': '666-33-111', 'bob': '888-999-666'}

#Modify elements into the dictionary
friends['bob'] = '888-999-777'
print(friends) #{'tom': '111-222-333', 'jerry': '666-33-111', 'bob': '888-999-777'}

#Delete element from the dictionary
del friends['bob']
print(friends) #{'tom': '111-222-333', 'jerry': '666-33-111'}

32) How do you merge one dictionary with the other?
Python provides an update() method which can be used to merge one dictionary on another.
Example:
a = {'a':1}
b = {'b':2}
a.update(b)
print(a) #{'a': 1, 'b': 2}

33) How to walk through a list in a sorted order without sorting the actual list?
In Python we have function called sorted(), which returns a sorted list without modifying the original list. 

Here is the code:

a=[500,300,400,200,100]
print(a)#[500, 300, 400, 200, 100]
print(sorted(a)) #[100, 200, 300, 400, 500]

34) names = [‘john’, ‘fan’, ‘sam’, ‘megha’, ‘popoye’, ’tom’, ‘jane’, ‘james’,’tony’]
       Write one line of code to get a list of names that start with character ‘j’?
Solution:
names = ['john', 'fan', 'sam', 'megha', 'popoye', 'tom', 'jane', 'james', 'tony']
jnames=[name for name in names if name[0] == 'j']     #One line code to filter names that start with ‘j’
print(jnames)

35) What is a set?
A Set is an unordered collection of unique objects.

36) a = “this is a sample string with many characters”
      Write a Python code to find how many different characters are present in this string?
Solution:
a = "this is a sample string with many characters"
print(len(set(a))) #16

37) Name some standard Python errors you know?
TypeError: Occurs when the expected type doesn’t match with the given type of a variable.
ValueError: When an expected value is not given- if you are expecting 4 elements in a list and you gave 2.
NameError: When trying to access a variable or a function that is not defined.
IOError: When trying to access a file that does not exist. 
IndexError: Accessing an invalid index of a sequence will throw an IndexError.
KeyError: When an invalid key is used to access a value in the dictionary.

38) How Python supports encapsulation with respect to functions?
Python supports inner functions. A function defined inside a function is called an inner function, whose behavior is not hidden. This is how Python supports encapsulation with respect to functions.

39) How do you open an already existing file and add content to it?
In Python, open(,) is used to open a file in different modes. The open function returns a handle to the file, using which one can perform read, write and modify operations.

Example:

    F = open(“simplefile.txt”,”a+”) #Opens the file in append mode
    F.write(“some content”)    #Appends content to the file.
    F.close()    # closes the file.

39) What are the built-in type does python provides?
There are mutable and Immutable types of Pythons built in types. 
Mutable built-in types
List
Sets
Dictionaries
Immutable built-in types
Strings
Tuples
Numbers

40) What is module and package in Python?
In Python, module is the way to structure program. Each Python program file is a module, which imports other modules like objects and attributes.
The folder of Python program is a package of modules. A package can have modules or subfolders.

41) Explain how can you generate random numbers in Python?
To generate random numbers in Python, you need to import command as
import random
print(random.random())
This returns a random floating point number in the range [0,1)

42) How to connect to the Oracle Database using python script?
Using cx_Oracle module.

Example:

import os
import cx_Oracle
# Set folder in which Instant Client is installed in system path
os.environ['PATH'] = 'E:\\app\\OracleHomeUser1\\instantclient_18_3'
# Connect to hr account in Oracle Database 11g Express Edition
con = cx_Oracle.connect("hr", "hr", "localhost:1521/pdborcl")
cur = con.cursor()
query="select * from employees"
cur.execute(query)
for cols in cur:
    print(cols[0],"  ",cols[1],"  ",cols[2])
print("Completed!!!")
cur.close()
con.close()

43) How to connect to the Microsoft Excel and read write data in to excel using python script?

Reading data from Excel:

# import openpyxl module
import openpyxl

# Give the location of the file
path = "C:\SeleniumPractice\data3.xlsx"

workbook = openpyxl.load_workbook(path)
sheet = workbook["Sheet1"]

rows=sheet.max_row
cols=sheet.max_column

print(rows) # print the total number of rows
print(cols) # ptint total number of column

for r in range(1,rows+1):
    for c in range(1,cols+1):
        print(sheet.cell(row=r, column=c).value,end='     ')
    print()

Writing  data into Excel:

# import openpyxl module
import openpyxl

# Give the location of the file
path = "C:\SeleniumPractice\Test2.xlsx"

workbook = openpyxl.load_workbook(path)
sheet= workbook.active

for r in range(1,5):
    for c in range(1,3):
        sheet.cell(row=r, column=c).value = "abcdef" #(or)sheet.cell(row=r, column=c, value='xyz')

workbook.save(path)

44) What is the difference between list and tuples?

LIST
TUPLES
Lists are mutable i.e they can be edited.
Tuples are immutable (tuples are lists which can’t be edited).
Lists are slower than tuples.
Tuples are faster than list.
Syntax: list_1 = [10, ‘Chelsea’, 20]
Syntax: tup_1 = (10, ‘Chelsea’ , 20)

45). Explain Inheritance in Python with an example.
Inheritance allows One class to gain all the members(say attributes and methods) of another class. Inheritance provides code reusability, makes it easier to create and maintain an application. The class from which we are inheriting is called super-class and the class that is inherited is called a derived / child class.

They are different types of inheritance supported by Python:
1. Single Inheritance – where a derived class acquires the members of a single super class.
2. Multi-level inheritance – a derived class d1 in inherited from base class base1, and d2 are inherited from base2.
3. Hierarchical inheritance – from one base class you can inherit any number of child classes
4. Multiple inheritance – a derived class is inherited from more than one base class.

46). How can you randomize the items of a list in place in Python?

Consider the example shown below:

from random import shuffle
x = ['Keep', 'The', 'Blue', 'Flag', 'Flying', 'High']
shuffle(x)
print(x)

47). Write a sorting algorithm for a numerical dataset in Python.
The following code can be used to sort a list in Python:

list = ["1", "4", "0", "6", "9"]
list = [int(i) for i in list]
list.sort()
print (list)

48) How to print current date &  time?
Time module is available.

Example:

import time;
localtime = time.asctime( time.localtime(time.time()) )
print ("Local current time :", localtime)




Python Interview Questions and Answers Part-1




1)  A = 10, 20, 30
In the above assignment operation, what is the data type of ‘A’ that Python appreciates as?

Unlike other languages, Python appreciates ‘A’ as a tuple. When you print ‘A’, the output is (10,20,30). This type of assignment is called “Tuple Packing”.

2)  A = 1,2,3,4
      a,b,c,d = A
In the above assignment operations, what is the value assigned to the variable ‘d’?

4 is the value assigned to d.  This type of assignment is called ‘Tuple Unpacking’.

3) a = 10
     b = 20
Swap these two Variables without using the third temporary variable?

a, b = b, a 

This kind of assignment is called a parallel assignment.

4)  What is a Variable in Python?

When we say Name = ‘john’ in Python, the name is not storing the value ‘john’. But, ‘Name’ acts like a tag to refer to the object ‘john’. The object has types in Python but variables do not, all variables are just tags. All identifiers are variables in Python. Variables never store any data in Python.

5)  a = 10
     b = a
     a = 20
     print b
What is the output?
Output is 10.

6) How do you find the type and identification number of an object in Python?
type() gives the type of the object that variable is pointing to, and id() give the unique identification number of the object that variable is pointing to. Ex:

print(type(b)) #
print(id(b)) #1452987584

7)  a = 0101
    b = 2
    c = a+b

What is the Value of c?


In Python2, any number with leading 0 is interpreted as an octal number. So, variable a points to 65(Equalent in Decimal) then the variable c will be pointing to the value 67 i.e 65+2.In Python3, a=0101  (Doesn’t support syntax)

8) What are the Arithmetic Operators that Python supports?




10)  What are the basic Data Types Supported by Python?
Numeric Data types: int, long, float, NoneType
String: str
Boolean: (True, False)
NoneType: None

11) How do you check whether the two variables are pointing to the same object in Python?
In Python, we have an operation called ‘is’ operator, which returns true if the two variables are pointing to the same object.

Example:
a = "Hello world"
c = a
print(a is c) #Returns true if the two variables are pointing to the same object
print(id(a)) #64450416
print(id(c)) #64450416

12) What is for-else and while-else in Python?
Python provides an interesting way of handling loops by providing a function to write else block in case the loop is not satisfying the condition.

Example :

a = "Hello world"
c = a
print(a is c) #Returns true if the two variables are pointing to the same object
print(id(a)) #64450416
print(id(c)) #64450416

The same is true with while-else too.

13) How do you programmatically know the version of Python you are using?
The version property under sys module will give the version of Python that we are using.
import sysprint(sys.version)

14) How do you find the number of references pointing to a particular object?
The getrefcount() function in the sys module gives the number of references pointing to a particular object including its own reference. 

import sys
x = "JohnShekar"
y = xprint(sys.getrefcount(x))

Here, the object ‘JohnShekar’ is referred by x, y and getrefcount() function itself. So the output is 3. 

15) How do you dispose a variable in Python?
‘del’ is the keyword statement used in Python to delete a reference variable to an object.

import sys
x = "JohnShekar"
y = xprint(sys.getrefcount(x))
del xprint(sys.getrefcount(x)) #NameError: name 'x' is not defined

16) What is the difference between range() and xrange() functions in Python?
range() and xrange() are two functions that could be used to iterate a certain number of times in for loops in Python.
In Python 3, there is no xrange , but the range function behaves like xrange in Python 2.
If you want to write code that will run on both Python 2 and Python 3, you should use range().

Example:
# initializing a with range()
a = range(1, 10000)

# initializing a with xrange()
x = xrange(1, 10000)

print("The return type of range() is : ")
print(type(a))

# testing the type of x
print("The return type of xrange() is : ")
print(type(x))

17) What are the ideal naming conventions in Python?
All variables and functions follow lowercase and underscore naming convention.

Examples: is_prime(), test_var = 10 etc

Constants are all either uppercase or camel case.

Example: MAX_VAL = 50, PI = 3.14

None, True, False are predefined constants follow camel case, etc.

Class names are also treated as constants and follow camel case.

Example:    UserNames

18) What happens in the background when you run a Python file?
When we run a .py file, it undergoes two phases. In the first phase it checks the syntax and in the second phase it compiles to bytecode (.pyc file is generated) using Python virtual machine, loads the bytecode into memory and runs.

19) What is a module in Python?
A module is a .py file in Python in which variables, functions, and classes can be defined. It can also have a runnable code.

20) How do you include a module in your Python file?
The keyword “import” is used to import a module into the current file.

Example: import sys  #here sys is a predefined Python module.

21) How do you reload a Python module?
There is a function called reload() in Python, which takes module name as an argument and reloads the module.

22) What is List in Python?
The List is one of the built-in data structures in Python. Lists are used to store an ordered collection of items, which can be of different type.

Elements in a list are separated by a comma and enclosed in square brackets.

Examples of List are:

    A = [1,2,3,4]
    B = [‘a’,’b’,’c’]
    C = [1,’a’,’2’,’b’]

List in Python is sequence type as it stores ordered collection of objects/items. In Python String and tuple are also sequence types.

23)  When do you choose a list over a tuple?
When there is an immutable ordered list of elements, we choose tuple. Because we cannot add/remove an element from the tuple. On the other hand, we can add elements to a list using append () or extend() or insert(), etc., and delete elements from a list using remove() or pop().

Simple tuples are immutable, and lists are not. Based on these properties one can decide what to choose in their programming context.

24) How do you get the last value in a list or a tuple?
When we pass -1 to the index operator of the list or tuple, it returns the last value. If -2 is passed, it returns the last but one value.

Example:

a = [1,2,3,4] #List
print(a[-1])#4
print(a[-2])#3
b = (1,2,3,4) #Tuple

print(b[-1])#4print(b[-2])#3

25) What is Index Out Of Range Error?
When the value passed to the index operator is greater than the actual size of the tuple or list, Index Out of Range error is thrown by Python.

a = [1,2,3,4] #Listprint(a[5])#IndexError: list index out of range 

26) What is slice notation in Python to access elements in an iterator?
In Python, to access more than one element from a list or a tuple we can use ‘:’ operator. Here is the syntax. Say ‘a’ is list

    a[startindex:EndIndex:Step]

Example:

a = [100,200,300,400,500,600,700,800]

print(a[3:]) # Prints the values from index 3 till the end [400, 500, 600, 700, 800]
print(a[3:6])#Prints the values from index 3 to index 6. [400, 500, 600]
print(a[2::2])#Prints the values from index 2 till the end of the list with step count 2. [300, 500, 700]

The above operations are valid for a tuple too.

27) How do you convert a list of integers to a comma separated string?
List elements can be turned into a string using join function.

a = [1,2,3,4,5,6,7,8]
print(a)

numbers = ','.join(str(i) for i in a)
print(numbers)

28) What is the difference between Python append () and extend () functions?
The extend() function takes an iterable (list or tuple or set) and adds each element of the iterable to the list. Whereas append takes a value and adds to the list as a single object.

Example:

a = [1,2,3,4,5]
b = [6,7,8]
a.extend(b)
print(a)#[1, 2, 3, 4, 5, 6, 7, 8]
c = ['a','b']

a.append(c)
print(a) #[1, 2, 3, 4, 5, 6, 7, 8, ['a', 'b']]






3/30/19

How To Explain Project In Interview Freshers and Experienced

Describe an important project you’ve worked on” is one of the most common questions you can expect in an interview. The purpose of asking this question is to check your project management experience and project management skills.

The other traits that they would like to check are , how you manage or deal with tough situations, your approach towards challenges, skills in leading a project successfully. So, you should answer this question carefully.
The first thing you need to do is prepare for this question in advance. As this is one of the common questions, you should very well be prepared with an effective answer. For it, you need to prepare a list of all your projects and clearly mention all the goals and the roles you have played in completing those projects.
With the help of your answer, your interviewer should get to know about your priority setting, decision making, meeting deadlines, and assigning tasks etc.
Some of the points while preparing the answer are
1. Provide a best suitable example
2. Be clear and specific
3. Your role should be explained clearly
4. Brief them the mistakes to avoid

Project Explanation in Interview for Freshers and Experienced:

There are few things which any interviewer would expect from a project you have done previously irrespective of being a fresher or experienced. They are,
1. The way you solved a problem in the project.
2. Your role in the project.
3. Your imagination or creativeness in the concept of the project.
These are the main things any interviewer would expect from your project. Try to categorize your project into various steps and explain in a very crisp way to make them feel one with your project to win the interview. The various steps to explain a project are,

1. Project Introduction:

This is very important in explaining a project as it overall sets the mood of the interviewer about the project. So try to impress the interviewer with a good heading or you can start by telling the application of your project in the market. Also, try to tell your motivation behind choosing this as your project.

2. Modules description:

There might be various modules for a project. It differs according to the project you choose. Try to break your project into various modules and explain. This will bring clarity to the interviewer about your project.

3. Advantages and the main functionality of your application:

Try to speak about the functionality of your application in a few words and also include their advantages. Sometimes pictorial representations will help for the better understanding. So explain your project with a flowchart, chart diagrams, or any graphs. This will add extra scores to your explanation about your project.

4. Tools, Technologies, and Platform used:

This is also a very important aspect when explaining a project. Tools, Technologies, and platform used will help the interviewer understand better about the working of the project. As well as it will create an impact on how new is your project. Try to explain it very short and be to the point.

5. Personal contribution and your role in the project:

Any interviewer would only focus on how well you have contributed for the project. Try to show your individuality in the project while explaining. It might be small or big, it is how you portray yourself for the project. Don’t try to be too modest by telling it is a team work, because this is an interview for an individual and not for the team.

6. Challenges in the project:

You might had some difficulties and challenges during your project. Explain the interviewer how you had overcome the challenge and also explain about the thought process of yourself to overcome the difficulties.

7. Number of people in the project:

Even though individuality in the project is expected, an interviewer might also check the team work and your compatibility during the project with a team. So try to highlight the teamwork when explaining the project.

8. Amount of time it took for the project:

Amount of time involved in the project will be expected from the interviewer side to know how you manage the time limit when given to you. So explain it in two to three lines about the time limit of your project.

9. Improvements in the future for the present system:

Try to show your involvement in the project. You can also explain the future improvements for the present project. Also, talk about the expectations of you towards the project in future. This in turn will showcase your confidence, and positivity towards the work.

10. Drawbacks:

This has to be handled carefully, as never explain too many drawbacks of your project. And use correct words to explain the drawbacks. Show your positive mental attitude when explaining the negatives of the project. All they want is how much you are capable in handling negatives in the work.

Interview Tips For Experienced Candidates:

There is a lot of difference between a fresher’s experience in explaining a project in their graduation and an experienced person explaining the project. Both are equally important, but expectations differ for the both. For example, from an experienced candidate during the interview, project explanation will decide how capable he is for the job. There are few things which has to be remembered while explaining about the project during the interview.
They are,

1. Explain your overall project:

This explanation totally differs from fresher’s explanation about the project. Give a brief explanation about the project title and also its impact on your previous company. Talk briefly about its importance in your previous organization.

2. Talk about the technology, working, and tools used in previous company:

Try to explain about the overall technology used, working of the project and also explain about the importance of the project in the company. This will help the interviewer gain confidence on your skill set.

3. Overall months or years you worked:

Tell about the time period you worked on the project as it will talk about your commitment towards the project, and also experience you gained throughout the project.

Few points to emphasize:

Some of the points to focus while answering are
  • Specify about the skills and features that needed to complete the project
  • Have a positive mindset
  • Discuss the goals of the project
  • How interesting the project was
  • What made you accept this project

Mistakes You Should Avoid

Some of the mistakes to miss are
  • Be little careful
  • Do not get in detailed project information
  • Never criticize your previous employers
  • Do not drag your answer

3/16/19

Selenium with Python | Oracle Database Connectivity using cx_Oracle | Data Driven Testing

About cx_Oracle

cx_Oracle is a Python extension module that enables access to Oracle Database. It conforms to the Python database API 2.0 specification with a considerable number of additions and a couple of exclusions.


Overview

To use cx_Oracle 7 with Python and Oracle Database you need:

Python 2.7 or 3.5 and higher. Older versions of cx_Oracle may work with older versions of Python.

Oracle client libraries. These can be from the free Oracle Instant Client, or those included in Oracle Database if Python is on the same machine as the database. Oracle client libraries versions 18, 12, and 11.2 are supported on Linux, Windows and macOS. Users have also reported success with other platforms.

An Oracle Database. Oracle’s standard client-server version interoperability allows cx_Oracle to connect to both older and newer databases.

Quick Start cx_Oracle Installation

An installation of Python is needed. Python 2.7 and Python 3.5 and higher are supported by cx_Oracle 7.

Install cx_Oracle from PyPI with:

python -m pip install cx_Oracle --upgrade

Pre-requisites

1) Oracle data base
http://www.oracle.com/webfolder/technetwork/tutorials/obe/db/12c/r1/Windows_DB_Install_OBE/Installing_Oracle_Db12c_Windows.html

2) Oracle instant client
https://www.oracle.com/technetwork/topics/winsoft-085727.html

3) cx_Oracle though command prompt
Command should execute in command prompt: pip install cx-Oracle

4) cx_Oracle in Pycharm
Select project-->File-->Settings-->Project interpreter--> Click on + -->cx_Oracle-->select-->install package.


Database operations using Pyhton(cx_Oracle Module)

1) Connect to database
2) How to execute queries(insert, update, delete)
3) How to select data from database
4) Data driven testing

Connect to database

import cx_Oracle
import os
os.environ['PATH']='E:\\app\\OracleHomeUser1\\instantclient_18_3'

#Establish connection to the database
con=cx_Oracle.connect("hr","hr","localhost/pdborcl")
print("Connected!!!")
con.close()

How to execute queries(insert, update, delete)

import cx_Oracle
import os
os.environ['PATH']='E:\\app\\OracleHomeUser1\\instantclient_18_3'

#Establish connection to the database
con=cx_Oracle.connect("hr","hr","localhost/pdborcl")

cur=con.cursor()

query1="insert into student values(102,'JOHN')"
query2="update student set sname='XYZ' where sid=102"
query3="delete student where sid=102"

cur.execute(query3)

cur.close()
con.commit()
con.close()

print("Completed!!!")


How to select data from database 

import cx_Oracle
import os
os.environ['PATH']='E:\\app\\OracleHomeUser1\\instantclient_18_3'

#Establish connection to the database
con=cx_Oracle.connect("hr","hr","localhost/pdborcl")

cur=con.cursor()

query="select * From employees"

cur.execute(query)

for cols in cur:
    print(cols[0],"     ",cols[1],"     ",cols[2])

cur.close()
con.close()

print("Completed!!!")


Data Driven testing

from selenium import webdriver
import time
import cx_Oracle
import os
os.environ['PATH']='E:\\app\\OracleHomeUser1\\instantclient_18_3'

driver=webdriver.Chrome(executable_path="C:\Drivers\chromedriver_win32\chromedriver.exe")

driver.get("http://newtours.demoaut.com/")
driver.maximize_window()

#Establish connection to the database
con=cx_Oracle.connect("hr","hr","localhost:1521/pdborcl")

cur=con.cursor()
query="select * From users"
cur.execute(query)

for cols in cur:
    driver.find_element_by_name("userName").send_keys(cols[0])
    driver.find_element_by_name("password").send_keys(cols[1])
    driver.find_element_by_name("login").click()
    time.sleep(5)

    # validation started
    if driver.title == "Find a Flight: Mercury Tours:":
        print("Test passed")
    else:
        print("Test failed")
    driver.find_element_by_link_text("Home").click()

cur.close()
con.close()

print("Data Driven test Completed!!!")




3/13/19

Webservices/API Testing FAQ’s Part-3 SoupUI


43.What is SOAPUI & ReadyAPI?
  • SOAPUI is a Webservices/API Testing tool.
  • SOAPUI Pro (Ready API) which is Licensed version of SOAPUI
44. What is WSDL?
  • WSDL stands for Web Service Description Language and is a document written in XML.
  • It uses XML to define the service layer document which consists of origin of the web service, headers, port types, request and response data.
  • This one can provide the information about web methods and web service.
  • It describes:
  • Origin of the web service
  • Header information
  • Port type
  • Input and output messages
45. What is the role of WSDL document in web service testing?
  • Validating web services in only possible with WSDL document because to configure web services in SoapUI, WSDL document is mandatory. If the WSDL document is not valid, SoapUI will throw an exception immediately.
46. What is UDDI?
  • Universal Description, Discovery and Integration- a directory or global repository where all the web services can be found.
  • A new Webservice can also be registered through this.
  • This is also the place where WSDL detailed definitions are found.
47. What is SOAP?
  • Simple Object access protocol that uses XML to interact with web applications.
  • It uses XML based content to communicate between two client machines across any network
48. What would be the message format of SOAP protocol?
  • Generally, all the SOAP-based web services are written by using XML language which uses standard message format that is accepted across the universe. In this format, it is easy to read, identify the errors, avoids interoperability problems etc.
  • Here’s the sample SOAP message format.
49. What are the advantages of SOAP?
  • Since its XML based, it is platform and programming language independent. RPC (Remote procedure calls) are sometimes blocked by firewalls and proxy servers- Soap overcomes that.
50. SoapUI and SoapUI Pro?
  • SoapUI is a web service testing tool and SoapUI Pro is its commercial version.
  • SoapUI can help create functional, security and load testing test suites.
  • SoapUI Pro does all that with advanced drag and drop, Data Driven testing, advanced reporting and coverage analysis.
51.What we can do with the help of SoapUI?
  • SoapUI offers us to perform automation testing which includes functional testing, load testing and Data Driven testing.
  • It also provides in build reporting tool and export test results
  • We assert our services using various types of assertions
52.What hierarchy does SoapUI follow to build a proper testing project?
  • In a SoapUI project, the following order maintained.
  • TestSuite – This is combination of functional tests and logical blocks
  • Testcase – It’s a group that contains several test steps for the specific aspects of the service.
  • Teststep – it contains the set of functional tests
53.What is the basic method to automate web services in SoapUI?
  • Create a project and add the WSDL file
  • Add test suites, Test cases and Test cases- in that order
  • Include custom programming/validation using by adding Groovy steps
  • Call external data sources if using
  • Add assertions if necessary
  • Then RUN.
54. What are SoapUI assertions?
  • Assertions compare the parts/all of the response message to the expected outcome.
55. What are the major types of assertions available in SoapUI?
Assertions are one of the major features in SoapUI.
It offers the following types of assertions.
  • Simple contains
  • Schema compliance
  • Simple not contain
  • Soap Faults
  • Response SLA
  • XPath Match
  • XQuery Match
  • WS security status
  • Script Assertion
  • WS- Addressing Request or Response Assertion
Additionally, Equals assertion is introduced in SoapUI NG Pro version.
56. Explain about XPath Assertion in SoapUI
In SoapUI, XPath assertion is used for asserting the web service response value by specifying the absolute path.
If the absolute path is matched with the response value, then the test case or test suite will be considered as PASS otherwise it will be notified as FAILED.
We can see the results of assertion at bottom of the screen where the Assertion tab will have resultant information.
57. What is Data Driven testing?
Data Driven testing means to store our test data which includes input and expected output in an external data source called Excel / Database / XML file. Later, we need to iterate the data source using respective component.
In SoapUI, Datasource and Datasource Loop test steps are used for performing data driven testing.
58. What are the different types of assertions used in SoapUI?
The following are the different types of assertions:
Contains & Not Contains
XPath match
XQuery match
Schema compliance
Soap Faults
Response SLA
WS security Status
Script Assertion
WS- Addressing Request or Response Assertion
59. What is Groovy script and where can it be used?
Groovy is a scripting language which internally includes all the Java libraries – it helps us to customize and add custom validations to SoapUI tests
60. How to group tests?
The basic Test suite is a way for us to group tests in SoapUI.
When you need a different set of tests, you just have to create a new test suite and create tests as required under it as test cases.
61.How to save the responses received?
The response values can be saved by clicking on the required request and choosing the “Dump file” location in its properties.
62. What are the properties available in SoapUI?
In SoapUI, there are three levels of properties available. They are,
Custom Properties or Project Level Properties:
These properties are added several times based on our needs and they can be utilized at any test suites, test cases or test steps that belong to the current project.
Test Suite Level Properties:
The tester can add his own properties with relevant information under the test suites. These properties are available for the corresponding test suite only.
Test case Level Properties: If the tester needs to store their test data within the test cases they can create their own properties inside the test case. So these properties can be accessed within the respective test cases.
63. What can data sources be used in SoapUI?
Excel Files
CSV Files
ODBC Sources
SQL / ADO Objects