Learn Selenium Automation Testing

Breaking

Sunday, 26 August 2018

When to use LinkedList over ArrayList

03:35:00 0
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.

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

03:27:00 0
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

03:17:00 0
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

03:09:00 0
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")

How to get the number of Elements in a list in Python

03:03:00 0
How to get the number of Elements in a list in Python
How to get the number of Elements in a list in Python,The len() function can be used with a lot of types in Python - both built-in types and library types.


Below is the code




items = []

items.append("apple")

items.append("orange")

items.append("banana")

len(items)


Output : 3


Everything in Python is an object, including lists. All objects have a header of some sort in the C implementation.

Lists and other similar builtin objects with a "size" in Python, in particular, have an attribute called ob_size, where the number of elements in the object is cached. So checking the number of objects in a list is very fast.


OR

You can use below code also

>>> len([1,2,3])
3


OR


>>> l = slist(range(10))
>>> l.length
10
>>> print l
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]


OR


items = []
items.append("apple")
items.append("orange")
items.append("banana")

print items.__len__()

Get HTML Source of WebElement in Selenium Webdriver using Python

02:51:00 0
Get HTML Source of WebElement in Selenium Webdriver using Python
Get HTML Source of WebElement in Selenium Webdriver using Python,in this lesson you will get complete selenium python code to print or get html source of webelement with the help of innerHtml attribute to get source of the content of the element or outerHtml for source with the current element.

Below is the code:


element.get_attribute('innerHTML')


import unittest
from selenium import webdriver
from selenium.webdriver.common.keys import Keys

class PythonOrgSearch(unittest.TestCase):

    def setUp(self):
        self.driver = webdriver.Firefox()

    def test_search_in_python_org(self):
        driver = self.driver
        driver.get("http://www.python.org")
        elem = driver.find_element_by_xpath("//*")
source_code = elem.get_attribute("outerHTML")


    def tearDown(self):
        self.driver.close()

if __name__ == "__main__":
    unittest.main()


If you want to save it to a file,use below code.


f = open('c:/htmlfile.html', 'w')
f.write(source_code.encode('utf-8'))
f.close()

Print Google Search results using Selenium in Python

02:36:00 0
Print Google Search results using Selenium in Python
Print Google Search results using Selenium in Python,below is the sample class which we can use to execute the code, you just need to change the path to webdriver as per your computer drive path. It was made for PhantomJS ,You can download it HERE., if you want to use Chrome just use 

"self.driver = webdriver.Chrome(path)".


Below is code example:


from urllib.parse import quote_plus
from selenium import webdriver


class Browser:

    def __init__(self, path, initiate=True, implicit_wait_time = 10, explicit_wait_time = 2):
        self.path = path
        if initiate:
            self.start()
        return

    def start(self):
        self.driver = webdriver.Chrome(path)
        self.driver.implicitly_wait(self.implicit_wait_time)
        return

    def end(self):
        self.driver.quit()
        return

    def go_to_url(self, url, wait_time = None):
        if wait_time is None:
            wait_time = self.explicit_wait_time
        self.driver.get(url)
        print('[*] Fetching results from: {}'.format(url))
        time.sleep(wait_time)
        return

    def get_search_url(self, query, page_num=0, per_page=10, lang='en'):
        query = quote_plus(query)
        url = 'https://www.google.hr/search?q={}&num={}&start={}&nl={}'.format(query, per_page, page_num*per_page, lang)
        return url

    def scrape(self):
        #xpath migth change in future
        links = self.driver.find_elements_by_xpath("//h3[@class='r']/a[@href]") # searches for all links insede h3 tags with class "r"
        results = []
        for link in links:
            d = {'url': link.get_attribute('href'),
                 'title': link.text}
            results.append(d)
        return results

    def search(self, query, page_num=0, per_page=10, lang='en', wait_time = None):
        if wait_time is None:
            wait_time = self.explicit_wait_time
        url = self.get_search_url(query, page_num, per_page, lang)
        self.go_to_url(url, wait_time)
        results = self.scrape()
        return results


path = '<YOUR PATH TO PHANTOMJS>/phantomjs-2.1.1-windows/bin/phantomjs.exe'## SET YOU PATH TO phantomjs
br = Browser(path)
results = br.search('site:facebook.com inurl:login')
for r in results:
    print(r)

br.end()

Saturday, 25 August 2018

How to send attachments in jenkins emails

06:25:00 0
How to send attachments in jenkins emails
How to send attachments in Jenkins emails or Configure Jenkins to send an attachment in email using Editable Email Notification plugin in Jenkins to attach a file with the email.
With the help of Ant pattern we can send attachment in Jenkins Email.Please follow my example to send and attachment in Jenkins email.

Gmail SMTP  configurations

Enter Admin Email address as your gmail address
Default user e-mail suffix - @gmail.com
smtp.gmail.com
465
UTF-8
Use SSL Authentication
Enter gmail id
Enter password
Test Email by click on Test Email Configuration

Under Jenkins Job

Select Post Build Action as Editable Email Notifications
Under Attachment enter this format,suppose you want to get png files from Screenshot folder then
follow this format

**/Screenshot/Register.png

Suppose you want to send all png files in email then follow below format

**/Screenshot/*.png


How to configure Jenkins to send an attachment in email,
Jenkins Email-ext (Editable Email Notifications)
How to configure Jenkins to send a file as Email attachment
Jenkins pipeline email attachment
attach file from work space Jenkins


Sunday, 6 May 2018

What is the default port number used by hub in Selenium?

03:17:00 1
What is the default port number used by hub in Selenium?
What is the default port number used by hub in Selenium,While working with Selenium Grid,we require to configure Selenium Hub to connect to different machines and it will have default port number.

What is the default port number used by hub in Selenium?

What is the default port number used by hub in Selenium?

a. 4444
b. 2222
c. 3434
d. 2290

ANSWER : 4444

Thursday, 3 May 2018

Difference Between Assertion and Verification in Selenium

19:41:00 1
Difference Between Assertion and Verification in Selenium
In this Difference Between Assertion and Verification in Selenium post you will learn exact difference and when to use assert and verify command in selenium scripts,Selenium Verify command will not stop Test execution of Test cases if verification Test fails.

It will log an error/defect and continue with Test Cases execution of remaining  test cases. We use Selenium verify commands in Selenium IDE when you still want to proceed with Test execution of test case even if expected output is not matched for a test steps.  

Difference Between Assertion and Verification in Selenium


Selenium Assertion command will stop Test execution of Test cases if verification point fails. It will log an error/defect and will not continue with Test Cases execution of remaining Test case scripts. We can use assertions in Test scenarios where there is no point to continue further Test Execution if expected result is not matching with actual test results. 

It is very simple. You can Use assertions when you want to stop Test case execution , if expected Test results is not matched with actual test results and you can use verification points when you still want to continue test script execution of a test cases if expected test results is not matched with actual test results.

Trending Posts:

Handle Authentication using Selenium