PyTest Framework for Test Automation: Unlocking its potential — Part 1

Google Image

The PyTest framework is a popular choice for test automation in the Python ecosystem. It provides a simple and powerful testing framework for writing and executing test cases efficiently. In this article, we will explore the key features and benefits of PyTest, along with practical examples to demonstrate its usage.

What is PyTest?

Pytest is a software test framework, which means pytest is a command-line tool that automatically finds tests you’ve written, runs the tests, and reports the results.

A robust Python testing tool, pytest can be used for all types and levels of software testing. Pytest can be used by development teams, QA teams, independent testing groups, individuals practicing TDD, and open source projects.

Why to choose Pytest?

Pytest supports unit testing. I started my Python adventure with UI test automation using Selenium. I started to prepare a test automation plan and make some research for what to use. I tried to find the best possible tool to use which gains the most for the test automation project. This is where test automation planning is important to have before starting. It is where I met with Pytest.

Advantages of Pytest:

· Pytest has its own way to detect the test file and test functions automatically, if not mentioned explicitly.

· It allows us to execute a specific part of a test suite and also skip a subset of the entire test suite.

· Pytest can run multiple tests in parallel, so it reduced the execution time of the test suite significantly.

· It has a simple syntax and is easy to learn and start using.

· It is open source and free.

· It has many documentation available and IDE support.

Getting started with Pytest:

Installation:

To follow along here, you will need to have pytest installed. On most systems, you can do this by running the following code at the command line:

Pip install pytest

Writing test functions:

Lets assume we have a simple function to test

def add_numbers(x, y):    return x + y# Now, let's write test functions for the above functiondef test_add_numbers():    # Test case 1: Adding positive numbers    result = add_numbers(2, 3)    assert result == 5, "Addition of positive numbers failed"    # Test case 2: Adding negative numbers    result = add_numbers(-5, -10)    assert result == -15, "Addition of negative numbers failed"test_add_numbers()

In the example above, we have a function add_numbers that takes two arguments and returns their sum. We then define a test function test_add_numbers that contains multiple test cases. Each test case verifies the expected result using the assert statement. If the condition in assert is False, an error message will be displayed.

Running tests:

1. Download the updated webdriver and place it in the specified location where you gonna run your test project.

2. Import the WebDriver and Keys classes from Selenium.

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

The WebDriver class will connect you to a browser’s instance, which we will shortly cover. The Keys class lets you emulate the stroke of keyboard keys, including special keys like “Shift” and “Return”.

3. Next, create an instance of Chrome with the path of the driver that you downloaded through the websites of the respective browser. In this example, we assume that the driver is in the same directory as the Python script that you will execute.

chrome_executable_path = "./Driver/chromedriver.exe"

4. Next, use the .get() method of the driver to load a website. You may also load a local development site as this process is equivalent to opening a window of Chrome on your local machine, typing a URL and hitting Enter. The .get() method not only starts loading a website but also waits for it to render completely before moving on to the next step.

Login_locators = {
'URL':'http://mzs.zsservices.com/',
}

def get_url(self):
url = Login_locators['URL']
return url

driver.get(get_url())

In this example, I have defined the URL value in the file ‘Login_locators’ and getting the respective value by importing the class I used in Login_locators file.

Finding Xpaths:

XML Path or commonly known as XPath, is a query language for XML documents. It is made of path expression governed by some pre-defined conditions. Moreover, XPath can be effectively used to identify and locate almost any element present on a web page. It is quite helpful while working on a dynamic web page where the web element’s unique attributes are not constant. Moreover, it allows us to write XML document navigation flow for locating web elements.

Syntax of Xpath:

XPath = //tag_name[@Attribute_name = “Value of attribute”]
Image by Author

What is HTML/XML DOM?

All the HTML web pages are internally represented as an XML document. Additionally, the XML document has a tree-like structure, where we have different tags and attributes. For example, if we open the Chrome Dev tools section by right-clicking on any page and selecting the “Inspect” option, the HTML structure will look as follows:

Image by Author

It starts with a tag <html> which has two child nodes <head> and <body>. Here <body> again has a child node like <div>, which has its child nodes. Further, you can also see the first <div> tag has an “id” attribute, which has a value “app”. Similarly, the child node of the <div> also has its own set of attributes and values.

One thing that we can notice here is every node that opens is again closed by using forward slash before the tag name, such as the <body> tag is closed using </body>. So, this way, we can see that all the HTML pages are internally represented as an XML document and constitute the XML DOM (Document Object Model).

Different Kinds of XPaths:

Selenium uses two strategies to locate elements using XPaths :

  • Locating a web element using an Absolute XPath.
  • Locating a web element using Relative XPath.

Absolute Path:

Absolute XPath is the direct way of finding the element. Moreover, it starts from the first/root node of the XML/HTML document and goes all the way to the required node following one node at a time.

Example:

'/html/body/app-root/app-team-member/div[2]/div/main/div[3]/app-survey-email/div[1]/fieldset/div[3]/div/div/div[2]/app-mr-task/div/div/div/div/div[1]/div[1]/div[3]/div/input'

Relative Path:

Relative XPath starts from any node inside the HTML DOM; it need not start from the root node. It beings with a double forward slash.

Example:

//input[@id= "ctl00_PageContentPlaceholder_UserNameInput"]

If you have reached this far, thank you for reading this blog, I hope you found it insightful 😃. Give us a follow for more content on technology, productivity, work habits, and more!

--

--