How to Call a Python Script with Arguments from Java class

 In this post you will learn How to Call a Python Script with Arguments from Java class , pass arguments using ProcessBuilder class, using process builder class we can execute python file and provide multiple arguments in string format.

How to Call a Python Script with Arguments from Java class

To run ProcessBuilder class will use Process interface with start method.

Using sys library we can save arguments into String array in python file and get arguments into python file with the help of index based like sys.argv[0],sys.argv[1] and sys.argv[2].

You can get python script lines using Bufferedreader class using process.getinputstream() method .


Java ProcessBuilder not able to run Python script

Using ProcessBuilder to execute a python script with arguments

Run external python file with arguments from Java

Selenium Java Cucumber BDD Framework from Scratch

Selenium Java Cucumber BDD Framework from Scratch,Cucumber supports Behavior Driven Development (BDD) ,Cucumber reads executable plain text specifications which is written in Gherkin language in the form of Given, Then, And, But etc keywords.

Step Definitions connects Gherkin steps to programming the code and try to execute the step definitions as mentioned in Feature Files.

Cucumber Selenium Framework from Scratch helps to create Selenium framework using Maven project ,user able to create Feature files based on scenarios. Able to run selenium test scripts with test runner class.

Selenium Cucumber project gives you flavors of 

1.Set Up maven dependency

2.Write User acceptance test cases.

3.Able to create Junit reports

4.Able to map Step definitions to Cucumber glue

5.User can run multiple feature files from runner class.



How to Make a POST Request with Rest Assured?

In previous post you've learned Rest API Testing using Rest Assured and in this below post you will learn How to Make a POST Request with Rest Assured library.In this below code uses requestSpecBuilder to make a post request. Parameter descriptions are listed below.

restAPIURL – URL of the Rest API
APIBody – Body of the Rest API. Example: {"key1":"value1","key2":"value2"}
setContentType() – Pass the "application/json", "application/xml" or "text/html" etc. headers to setContenType() method.
Authentication credentials – Pass the username and password to the basic() method or if there is no authentication leave them blank basic("","")

How to Make a POST Request with Rest Assured


public class RestAssured {


 @Test
 public void httpPostMethodTest() throws JSONException, InterruptedException {

  //Rest API's URL
  String restAPIUrl = "http://{RestAPIURL}";

  //API Body
  String apiBody = "{\"key1\":\"value1\",\"key2\":\"value2\",\"key3\":\"value3\"}";

  // Building request by using requestSpecBuilder
  RequestSpecBuilder builder = new RequestSpecBuilder();

  //Set API's Body
  builder.setBody(apiBody);

  //Setting content type as application/json
  builder.setContentType("application/json; charset=UTF-8");

  RequestSpecification requestSpec = builder.build();

  //Making post request with authentication or leave blank if you don't have credentials like: basic("","")
  Response response = given().authentication().preemptive().basic({
    username
   }, {
    password
   })
   .spec(requestSpec).when().post(restAPIUrl);

  JSONObject JSONResponseBody = new JSONObject(response.body().asString());

  //Get the desired value of a parameter
  String result = JSONResponseBody.getString({
   key
  });

  //Check the Result
  Assert.assertEquals(result, "{expectedValue}");

 }
}

REST API testing using Rest Assured

In this REST API testing using Rest Assured post, You will learn what is API and API testing, what is the little difference between SOAP and REST services, and how to test REST APIs using Rest Assured Library.


Rest API Testing using Rest Assured with Examples


What is API?


API full form is Application Programming Interface. It comprises of a set of functions that can be accessed and executed by another software systems. It is an interface between different systems and establishes interaction with systems and data exchange process.

What is API Testing?


In the modern development world, many web applications are designed based on three-tier architecture model. Those are:

1) Presentation Tier – Occupies the top level and displays information related to services available on a website ,User Interface (UI)
2) Application Tier – Also called Middle Tier or Logic Tier ,Business logic is written in this tier which is pulled from Presentation tier. It is also called Business Tier. (API)
3) Data Tier – Here information about database and data is stored and retrieved from a Database. (DB)

REST vs SOAP

REST (Representational State Transfer)


REST is an architectural style that uses simple HTTP calls for inter-machine communication. REST does not contain an additional messaging layer and focuses on design rules for creating stateless services. A client can access the resource using the unique URI and a representation of the resource is returned. With each new resource representation, the client is said to transfer state. While accessing RESTful resources with HTTP protocol, the URL of the resource serves as the resource identifier and GET, PUT, DELETE, POST and HEAD are the standard HTTP operations to be performed on that resource.

SOAP (Simple Object Access Protocol)


SOAP relies heavily on XML, and together with schema, defines a very strongly typed messaging framework. Every operation the service provides is explicitly defined, along with the XML structure of the request and response for that operation. Each input parameter is similarly defined and bound to a type: for example, an integer, a string, or some other complex object. All of this is codified in the WSDL – Web Service Description (or Definition, in later versions) Language. The WSDL is often explained as a contract between the provider and the consumer of the service. SOAP uses different transport protocols, such as HTTP and SMTP. The standard protocol HTTP makes it easier for SOAP model to tunnel across firewalls and proxies without any modifications to the SOAP protocol.

Trending Posts:



REST API Testing Using Rest Assured

What is Rest Assured?

In order to test REST APIs, I found REST Assured library so useful. It is developed by JayWay Company and it is a really powerful catalyzer for automated testing of REST-services. REST-assured provides a lot of nice features, such as DSL-like syntax, XPath-Validation, Specification Reuse, easy file uploads and with those features we will handle automated API testing much easier.

Rest Assured has a gherkin type syntax which is shown in below code. If you are a fan of BDD (Behavior Driven Development).

Rest Assured Example:

public class RestAssured{

@Test
public void appRestTest() {
given()
.contentType(ContentType.JSON)
.pathParam("name", "suresh")
.when()
.get("/restapipath/{name}")
.then()
.statusCode(200)
.body("firstName", equalTo("Suresh"))
.body("Lastname", equalTo("Narayana"));
}
}

Also, we can get JSON response as a string and send it to the JsonPath class and we can use its methods to write flexible structured tests.

public class RestAssured{

@Test
public void appJsonPathTest() {
Response res = get("/RestAPiservice/customer");
assertEquals(200, res.getStatusCode());
String json = res.asString();
JsonPath jp = new JsonPath(json);
assertEquals("rajesh@gmail.com, jp.get("email"));
assertEquals("suresh", jp.get("firstName"));
assertEquals("Narayana", jp.get("LastName"));
}
}


Sikuli Guide For Beginners – Integrate Sikuli With Selenium Webdriver

Sikuli Guide For Beginners – Integrate Sikuli With Selenium Web driver,In this present article, you will learn Sikuli Graphical User Interface Automation Tool in-detail and how to integrate Sikuli tool with Selenium webdriver.

Sikuli Guide for Beginners - Integrate Sikuli with Selenium WebDriver



What is Sikuli Tool:

Sikuli is a Graphical User Interface open source Automation Tool. Using Sikuli Automation tool you could automate whatever we see on the computer screen. It is basically uses image recognition
technology to identify and control GUI elements on desktop. you all know that using Selenium can't automate windows/desktop objects. Integrating Sikuli with Selenium allows us to
overcome this issue. Using Sikuli tool with Selenium webdriver, we could automate windows/desktop objects,Sikuli can automate both Web and Windows based applications.
Most of testers are using Auto-IT tool to upload or download files in Selenium scripting but using Sikuli we can do it very easily.


Advantages of Sikuli Tool:


It is an open source tool for automation.
Easily to integrate sikuli with selenium.
Can automate Desktop / Windows application.
Easily automate Flash objects – Flash Testing.
It can be used on any platform such as Windows/Linux/Mac/Mobile.

Sample program to login to Remote Desktop:


public void normalTest() throws FindFailed {
ImagePath.setBundlePath("D:/Practicle/SikuliProject/src/test/resources/images/");

Screen s = new Screen();
s.type("r",Key.WIN);
System.out.println("Run window is open");
s.type("mstsc");
System.out.println("Run window entered mstsc");
s.click("ok.png");
System.out.println("Click on OK button");
s.wait("remote.png");
System.out.println("Wait for Remote desktop window appers");
s.type("ipaddress");
System.out.println("Remote Desktop entered ipaddress");
s.click("connect.png");
System.out.println("Remote Desktop clicks Connect button");
s.exists("windowsSecurity.png");
s.type("passsword");
System.out.println("Entered password in Windows Security");
s.wait("wok.png");
s.click("wok.png");
System.out.println("OK button is pressed in Windows Security");
s.exists("remoteWind.png");

}

}

How to send extent reports in email with screenshots

How to send extent reports in email with screenshots,While working with Extent Reports,we are able to take the screenshots ,able to attach into Extent html Reports,but while sending those reports in email screenshots not displays.

I've figured how to display screenshots in Extent Reports,if html file location is changed from one folder to another folder with the simple trick as per Extent Reports site directions.

How to send extent reports in email with screenshots





When to use LinkedList over ArrayList

When to use LinkedList over ArrayList,LinkedList and ArrayList are two different implementations of the List interface. LinkedList implements it with a doubly-linked list. ArrayList implements it with a dynamically re-sizing array.

As with standard linked list and array operations, the various methods will have different algorithmic run times.

When to use Linked List over Arrary List


For LinkedList<E>

get(int index) is O(n) (with n/4 steps on average)
add(E element) is O(1)
add(int index, E element) is O(n) (with n/4 steps on average), but O(1) when index = 0 <--- main benefit of LinkedList<E>
remove(int index) is O(n) (with n/4 steps on average)
Iterator.remove() is O(1). <--- main benefit of LinkedList<E>
ListIterator.add(E element) is O(1) This is one of the main benefits of LinkedList<E>

Note: Many of the operations need n/4 steps on average, constant number of steps in the best case (e.g. index = 0), and n/2 steps in worst case (middle of list)

For ArrayList<E>

get(int index) is O(1) <--- main benefit of ArrayList<E>
add(E element) is O(1) amortized, but O(n) worst-case since the array must be resized and copied
add(int index, E element) is O(n) (with n/2 steps on average)
remove(int index) is O(n) (with n/2 steps on average)
Iterator.remove() is O(n) (with n/2 steps on average)
ListIterator.add(E element) is O(n) (with n/2 steps on average)

Note: Many of the operations need n/2 steps on average, constant number of steps in the best case (end of list), n steps in the worst case (start of list)

LinkedList<E> allows for constant-time insertions or removals using iterators, but only sequential access of elements. In other words, you can walk the list forwards or backwards, but finding a position in the list takes time proportional to the size of the list. Java doc says "operations that index into the list will traverse the list from the beginning or the end, whichever is closer", so those methods are O(n) (n/4 steps) on average, though O(1) for index = 0.

ArrayList<E>, on the other hand, allow fast random read access, so you can grab any element in constant time. But adding or removing from anywhere but the end requires shifting all the latter elements over, either to make an opening or fill the gap. Also, if you add more elements than the capacity of the underlying array, a new array (1.5 times the size) is allocated, and the old array is copied to the new one, so adding to an ArrayList is O(n) in the worst case but constant on average.

So depending on the operations you intend to do, you should choose the implementations accordingly. Iterating over either kind of List is practically equally cheap. (Iterating over an ArrayList is technically faster, but unless you're doing something really performance-sensitive, you shouldn't worry about this -- they're both constants.)

The main benefits of using a LinkedList arise when you re-use existing iterators to insert and remove elements. These operations can then be done in O(1) by changing the list locally only. In an array list, the remainder of the array needs to be moved (i.e. copied). On the other side, seeking in a  LinkedList means following the links in O(n) (n/2 steps) for worst case, whereas in an ArrayList the desired position can be computed mathematically and accessed in O(1).

Another benefit of using a LinkedList arise when you add or remove from the head of the list, since those operations are O(1), while they are O(n) for ArrayList. Note that ArrayDeque may be a good alternative to LinkedList for adding and removing from the head, but it is not a List.

Also, if you have large lists, keep in mind that memory usage is also different. Each element of a LinkedList has more overhead since pointers to the next and previous elements are also stored. ArrayLists don't have this overhead. However, ArrayLists take up as much memory as is allocated for the capacity, regardless of whether elements have actually been added.

The default initial capacity of an ArrayList is pretty small . But since the underlying implementation is an array, the array must be resized if you add a lot of elements. To avoid the high cost of resizing when you know you're going to add a lot of elements, construct the ArrayList with a higher initial capacity.

Create arraylist from array

Create Arraylist from array,In some of the interviews may or may not ask this question but it is tricky question in Java,here i've given simple code to creating arraylist from array,below is the simple code.

Java array is an object the contains elements of similar data type. It is a data structure where we store similar elements. We can store only fixed set of elements in a java array.

Array in java is index based, first element of the array is stored at 0 index.

a[] array={33,3,4,5};

Code to convert into ArrayList:

ArraryList<> arrayList = new ArrayList<>(Arrays.asList(array))


ArrayList<> arrayList=new ArrayList<>(Arrays.asList(array))

AN OTHER EXAMPLES

List<Element> arraylist = Arrays.asList(new Element(1), new Element(2), new Element(3));

How to check if a list is empty in java

How to check if a list is empty in java,in case list is empty in ArraryList() then code should provide prompt or log messages in console in order to verify list is empty or having any data in list.Below is the sample code to verify List is empty or not.

Sample Code:


import java.util.*;
import javax.swing.JOptionPane;

public class ArrayListEmpty 
{
    public static void main(String[] args) 
    {
        List<Integer> numbers = new ArrayList<Integer>();
        int number;
        do {
            number = Integer.parseInt(JOptionPane.showInputDialog("Enter a number)"));
            numbers.add(number);
        } while (number != -1);
        giveList(numbers);
    }

    public static void giveList(List<Integer> numbers)
    {
        if (numbers.isEmpty())
            JOptionPane.showMessageDialog(null, "List is empty");
        else
            JOptionPane.showMessageDialog(null, "List is not empty");
    }
}

How to check if a list is empty in python

How to check if a list is empty,in this topic you will learn verifying list is empty or not in python language with the help of simple code.

Below is the code:

a=[];

I'm checking a is empty or not using for loop as below

if not a:
  print("List is empty")


OR


 a = []
 try:
  print(a[-1])
 except IndexError:
  print("List is empty")