Open In App

Automated software testing with Python

Last Updated : 24 May, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Software testing is the process in which a developer ensures that the actual output of the software matches with the desired output by providing some test inputs to the software. Software testing is an important step because if performed properly, it can help the developer to find bugs in the software in very less amount of time. Software testing can be divided into two classes, Manual testing and Automated testing. Automated testing is the execution of your tests using a script instead of a human. In this article, we’ll discuss some of the methods of automated software testing with Python. Let’s write a simple application over which we will perform all the tests. 

Python-based automation testing frameworks like pytest provide a structured and efficient way to write test cases, making test automation more manageable and scalable. When executed on cloud platforms like LambdaTest, these tests gain the advantage of running on diverse browsers and environments, enabling comprehensive cross-browser testing without the need for extensive local infrastructure.

LambdaTest is an AI-powered test orchestration and execution platform that lets developers and testers perform automated software testing using Python. The platform offers an online browser farm of real browsers and operating systems to run Python automated tests at scale on a cloud grid.  Developers and testers can run test suites using popular testing frameworks like Selenium, Playwright, Cypress, Appium, and more.

Python
class Square:
    def __init__(self, side):
        """ creates a square having the given side
        """
        self.side = side

    def area(self):
        """ returns area of the square
        """
        return self.side**2

    def perimeter(self):
        """ returns perimeter of the square
        """
        return 4 * self.side

    def __repr__(self):
        """ declares how a Square object should be printed
        """
        s = 'Square with side = ' + str(self.side) + '\n' + \
        'Area = ' + str(self.area()) + '\n' + \
        'Perimeter = ' + str(self.perimeter())
        return s


if __name__ == '__main__':
    # read input from the user
    side = int(input('enter the side length to create a Square: '))
    
    # create a square with the provided side
    square = Square(side)

    # print the created square
    print(square)

Note: For more information about the function __repr__(), refer this article. Now that we have our software ready, let’s have a look at the directory structure of our project folder and after that, we’ll start testing our software.

---Software_Testing
|--- __init__.py (to initialize the directory as python package)
|--- app.py (our software)
|--- tests (folder to keep all test files)
|--- __init__.py

The ‘unittest’ module

One of the major problems with manual testing is that it requires time and effort. In manual testing, we test the application over some input, if it fails, either we note it down or we debug the application for that particular test input, and then we repeat the process. With unittest, all the test inputs can be provided at once and then you can test your application. In the end, you get a detailed report with all the failed test cases clearly specified, if any. The unittest module has both a built-in testing framework and a test runner. A testing framework is a set of rules which must be followed while writing test cases, while a test runner is a tool which executes these tests with a bunch of settings, and collects the results. Installation: unittest is available at PyPI and can be installed with the following command –

pip install unittest

Use: We write the tests in a Python module (.py). To run our tests, we simply execute the test module using any IDE or terminal. Now, let’s write some tests for our small software discussed above using the unittest module.

  1. Create a file named tests.py in the folder named “tests”.
  2. In tests.py import unittest.
  3. Create a class named TestClass which inherits from the class unittest.TestCase. Rule 1: All the tests are written as the methods of a class, which must inherit from the class unittest.TestCase.
  4. Create a test method as shown below. Rule 2: Name of each and every test method should start with “test” otherwise it’ll be skipped by the test runner. 
Python
        def test_area(self):
            # testing the method Square.area().
            
            sq = Square(2)    # creates a Square of side 2 units.

            # test if the area of the above square is 4 units, 
            # display an error message if it's not.

            self.assertEqual(sq.area(), 4, 
                f'Area is shown {sq.area()} for side = {sq.side} units')
        
  1. Rule 3: We use special assertEqual() statements instead of the built-in assert statements available in Python. The first argument of assertEqual() is the actual output, the second argument is the desired output and the third argument is the error message which would be displayed in case the two values differ from each other (test fails).
  2. To run the tests we just defined, we need to call the method unittest.main(), add the following lines in the “tests.py” module. 
Python
        if __name__ == '__main__':
            unittest.main()
        
  1. Because of these lines, as soon as you run execute the script “test.py”, the function unittest.main() would be called and all the tests will be executed.

Finally the “tests.py” module should resemble the code given below. 

Python
import unittest
from .. import app

class TestSum(unittest.TestCase):

    def test_area(self):
        sq = app.Square(2)

        self.assertEqual(sq.area(), 4, 
            f'Area is shown {sq.area()} rather than 9')

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

Having written our test cases let us now test our application for any bugs. To test your application you simply need to execute the test file “tests.py” using the command prompt or any IDE of your choice. The output should be something like this.

.
----------------------------------------------------------------------
Ran 1 test in 0.000s

OK

In the first line, a .(dot) represents a successful test while an ‘F’ would represent a failed test case. The OK message, in the end, tells us that all the tests were passed successfully. Let’s add a few more tests in “tests.py” and retest our application. 

Python
import unittest
from .. import app

class TestSum(unittest.TestCase):

    def test_area(self):
        sq = app.Square(2)
        self.assertEqual(sq.area(), 4, 
            f'Area is shown {sq.area()} rather than 9')

    def test_area_negative(self):
        sq = app.Square(-3)
        self.assertEqual(sq.area(), -1, 
            f'Area is shown {sq.area()} rather than -1')

    def test_perimeter(self):
        sq = app.Square(5)
        self.assertEqual(sq.perimeter(), 20, 
            f'Perimeter is {sq.perimeter()} rather than 20')

    def test_perimeter_negative(self):
        sq = app.Square(-6)
        self.assertEqual(sq.perimeter(), -1, 
            f'Perimeter is {sq.perimeter()} rather than -1')

if __name__ == '__main__':
    unittest.main()
.F.F
======================================================================
FAIL: test_area_negative (__main__.TestSum)
----------------------------------------------------------------------
Traceback (most recent call last):
File "tests_unittest.py", line 11, in test_area_negative
self.assertEqual(sq.area(), -1, f'Area is shown {sq.area()} rather than -1 for negative side length')
AssertionError: 9 != -1 : Area is shown 9 rather than -1 for negative side length

======================================================================
FAIL: test_perimeter_negative (__main__.TestSum)
----------------------------------------------------------------------
Traceback (most recent call last):
File "tests_unittest.py", line 19, in test_perimeter_negative
self.assertEqual(sq.perimeter(), -1, f'Perimeter is {sq.perimeter()} rather than -1 for negative side length')
AssertionError: -24 != -1 : Perimeter is -24 rather than -1 for negative side length

----------------------------------------------------------------------
Ran 4 tests in 0.001s

FAILED (failures=2)

A few things to note in the above test report are –

  • The first line represents that test 1 and test 3 executed successfully while test 2 and test 4 failed
  • Each failed test case is described in the report, the first line of the description contains the name of the failed test case and the last line contains the error message we defined for that test case.
  • At the end of the report you can see the number of failed tests, if no test fails the report will end with OK

Note: For further knowledge you can read the complete documentation of unittest.

The “nose2” module

The purpose of nose2 is to extend unittest to make testing easier. nose2 is compatible with tests written using the unittest testing framework and can be used as a replacement of the unittest test runner. Installation: nose2 can be installed from PyPI using the command,

pip install nose2

Use: nose2 does not have any testing framework and is merely a test runner which is compatible with the unittest testing framework. Therefore we’ll the run same tests we wrote above (for unittest) using nose2. To run the tests we use the following command in the project source directory (“Software_Testing” in our case),

nose2

In nose2 terminology all the python modules (.py) with name starting from “test” (i.e. test_file.py, test_1.py) are considered as test files. On execution, nose2 will look for all test files in all the sub-directories which lie under one or more of the following categories,

  • which are python packages (contain “__init__.py”).
  • whose name starts with “test” after being lowercased, i.e. TestFiles, tests.
  • which are named either “src” or “lib”.

nose2 first loads all the test files present in the project and then the tests are executed. Thus, with nose2 we get the freedom to split our tests among various test files in different folders and execute them at once, which is very useful when dealing with large number of tests. Let’s now learn about different customisation options provided by nose2 which can help us during the testing process.

  1. Changing the search directory – If we want to change the directory in which nose2 searches for test files, we can do that using the command line arguments -s or –start-dir as,
nose2 -s DIR_ADD DIR_NAME
  1. here, DIR_NAME is the directory in which we want to search for the test files and, DIR_ADD is the address of the parent directory of DIR_NAME relative to the project source directory (i.e. use “./” if test directory is in the project source directory itself). This is extremely useful when you want to test only one feature of your application at a time.
  2. Running specific test cases – Using nose2 we can also run a specific test at a time by using the command line arguments -s and –start-dir as,
nose2 -s DIR_ADD DIR_NAME.TEST_FILE.TEST_CLASS.TEST_NAME
  • TEST_NAME: name of the test method.
  • TEST_CLASS: class in which the test method is defined.
  • TEST_FILE: name of the test file in which the test case is defined i.e. test.py.
  • DIR_NAME: directory in which the test file exists.
  • DIR_ADD: address of the parent directory of DIR_NAME relative to the project source.
  1. Running tests in a single module – nose2 can also be used like unittest by calling the function nose2.main() just like we called unittest.main() in previous examples.

The “pytest” module

pytest is the most popular testing framework for python. Using pytest you can test anything from basic python scripts to databases, APIs and UIs. Though pytest is mainly used for API testing, in this article we’ll cover only the basics of pytest. Installation: You can install pytest from PyPI using the command,

pip install pytest

Use: The pytest test runner is called using the following command in project source,

py.test

Unlike nose2, pytest looks for test files in all the locations inside the project directory. Any file with name starting with “test_” or ending with “_test” is considered a test file in the pytest terminology. Let’s create a file “test_file1.py” in the folder “tests” as our test file. Creating test methods: pytest supports the test methods written in the unittest framework, but the pytest framework provides easier syntax to write tests. See the code below to understand the test method syntax of the pytest framework. 

Python
from .. import app

def test_file1_area():
    sq = app.Square(2)
    assert sq.area() == 4, 
        f"area for side {sq.side} units is {sq.area()}"

def test_file1_perimeter():
    sq = app.Square(-1)
    assert sq.perimeter() == -1, 
        f'perimeter is shown {sq.perimeter()} rather than -1'

Note: similar to unittest, pytest requires all test names to start with “test”. Unlike unittest, pytest uses the default python assert statements which make it further easier to use. Note that, now the “tests” folder contains two files namely, “tests.py” (written in unittest framework) and “test_file1.py” (written in pytest framework). Now let’s run the pytest test runner.

py.test

You’ll get a similar report as obtained by using unittest.

============================= test session starts ==============================
platform linux -- Python 3.6.7, pytest-4.4.1, py-1.8.0, pluggy-0.9.0
rootdir: /home/manthan/articles/Software_testing_in_Python
collected 6 items

tests/test_file1.py .F [ 33%]
tests/test_file2.py .F.F [100%]

=================================== FAILURES ===================================

The percentages on the right side of the report show the percentage of tests that have been completed at that moment, i.e. 2 out of the 6 test cases were completed at the end of the “test_file1.py”. Here are a few more basic customisations that come with pytest.

  1. Running specific test files: To run only a specific test file, use the command,
py.test <filename>
  1. Substring matching: Suppose we want to test only the area() method of our Square class, we can do this using substring matching as follows,
py.test -k "area"
  1. With this command pytest will execute only those tests which have the string “area” in their names, i.e. “test_file1_area()”, “test_area()” etc.
  2. Marking: As a substitute to substring matching, marking is another method using which we can run a specific set of tests. In this method we put a mark on the tests we want to run. Observe the code example given below, 
Python
            # @pytest.mark.&lt;tag_name&gt;
            @pytest.mark.area     
    
            def test_file1_area():
                sq = app.Square(2)
                assert sq.area() == 4, 
                    f&quot;area for side {sq.side} units is {sq.area()}&quot;
            
  1. In the above code example test_file1_area() is marked with tag “area”. All the test methods which have been marked with some tag can be executed by using the command,
py.test -m <tag_name>
  1. Parallel Processing: If you have a large number of tests then pytest can be customised to run these test methods in parallel. For that you need to install pytest-xdist which can be installed using the command,
pip install pytest-xdist
  1. Now you can use the following command to execute your tests faster using multiprocessing,
py.test -n 4
  1. With this command pytest assigns 4 workers to perform the tests in parallel, you can change this number as per your needs. If your tests are thread-safe, you can also use multithreading to speed up the testing process. For that you need to install pytest-parallel (using pip). To run your tests in multithreading use the command,
pytest --workers 4


Previous Article
Next Article

Similar Reads

Automated Browser Testing with Edge and Selenium in Python
Cross-browser testing is mandatory in the software industry. We all know that there are many browsers like Firefox, Chrome, Edge, Opera etc., are available. Rather than writing separate code to each and every browser, it is always a decent approach to go towards automated testing. Let us see how to do that using Selenium for Edge browser in Python.
5 min read
5 Reasons Why QA Wolf ls Above the Rest in Automated Testing
In the software development industry, where speed and quality are king and queen respectively, ensuring exceptional user experiences is paramount. Manual testing, as important as it may be to the overall scheme of things, often proves to be a slow-moving beast, delaying innovation and releases. That's where automated testing solutions like QA Wolf
5 min read
Why Python Is Used For Developing Automated Trading Strategy?
Python is a high-level programming language that is more deployed in machine learning and for automation of trading systems. Python has got exclusive library functions that facilitate ease of coding the algorithmic trading strategies. This article is all about why python programming language is preferred in developing a customized automated trading
5 min read
Automated Certificate generator using Opencv in Python
Prerequisites: Introduction to OpenCV OpenCV is the huge open-source library for computer vision, machine learning, and image processing and now it plays a major role in real-time operation which is very important in today’s systems. By using it, one can process images and videos to identify objects, faces, or even the handwriting of a human. Any e
2 min read
Getting started with Python for Automated Trading
Automated Trading is the terminology given to trade entries and exits that are processed and executed via a computer. Automated trading has certain advantages: Minimizes human intervention: Automated trading systems eliminate emotions during trading. Traders usually have an easier time sticking to the strategy by holding emotions in check. Backtest
3 min read
Automated Trading using Python
Using Python speeds up the trading process, and hence it is also called automated trading/ quantitative trading. The use of Python is credited to its highly functional libraries like TA-Lib, Zipline, Scipy, Pyplot, Matplotlib, NumPy, Pandas etc. Exploring the data at hand is called data analysis. Starting with Python. We will first learn to extract
4 min read
Automated File Organizer using Tkinter in Python
Prerequisites: Tkinter File organization is helpful when you are trying to find a specific one in a pool of files and directories. It seems time-consuming and exhausting to check each file. In cases where the number of files are way too many and you have no idea where to find it exactly, file organization is a saviour. This article discusses how th
2 min read
How to Send Automated Email Messages in Python
In this article, we are going to see how to send automated email messages which involve delivering text messages, essential photos, and important files, among other things. in Python. We'll be using two libraries for this: email, and smtplib, as well as the MIMEMultipart object. This object has multiple subclasses; these subclasses will be used to
6 min read
Automated SSH bot in Python
In this article, we are going to see how we can use Python to Automate some basic SSH processes. What is SSH? SSH stands for Secure Shell or Secure Socket Shell, in simple terms, it is a network communication protocol used to communicate between two computers and share data among them. The main feature of SSH is that the communication between two c
8 min read
Automated Website Scraping using Scrapy
Scrapy is a Python framework for web scraping on a large scale. It provides with the tools we need to extract data from websites efficiently, processes it as we see fit, and store it in the structure and format we prefer. Zyte (formerly Scrapinghub), a web scraping development and services company, currently maintains it. What is a Web Crawler (Web
5 min read
Visual Testing - Software Testing
Visual Testing is also called Visual UI Testing. It validates whether the developed software user interface (UI) is compatible with the user's view. It ensures that the developed web design is correctly following the spaces, sizes, shapes, and positions of UI elements. It also ensures that the elements are working properly with various devices and
10 min read
Software Testing - Unit Testing Tools
Unit Testing is a part of software testing where testing is performed on isolated small parts of the code. The objective of Unit Testing is to isolate small portions of application code that could be individually tested and verified, provided all the isolated code units have been developed in the correct procedure. It is performed by the developmen
8 min read
Cross-Browser Testing Tools - Software Testing
Cross-Browser Testing Tools - Ensuring software compatibility across different web browsers is essential for delivering a consistent user experience. Cross-browser testing tools help developers identify and fix issues by testing how their web applications perform on various browsers and operating systems. These tools streamline the process of detec
14 min read
Mobile Testing Tools - Software Testing
Mobile application testing is an interaction by which application programming produced for handheld cell phones is tried for its usefulness, convenience, and consistency. Mobile applications either come pre-introduced or can be introduced from portable programming dissemination stages. It can be a robotized or manual kind of testing. Table of Conte
11 min read
Accessibility Testing - Software Testing
Accessibility Testing is a critical aspect of software testing aimed at ensuring that applications are usable by people with various disabilities, such as visual, auditory, motor, or cognitive impairments. This testing verifies that the software complies with accessibility standards like WCAG (Web Content Accessibility Guidelines) and is inclusive
14 min read
Load Testing - Software Testing
Load testing is a type of Performance Testing that determines the performance of a system, software product, or software application under real-life-based load conditions. This article focuses on discussing load testing in detail. Table of Content What is Load Testing?Load Testing TechniquesObjectives of Load TestingLoad Testing ProcessMetrics of L
9 min read
Automation Testing - Software Testing
Automated Testing means using special software for tasks that people usually do when checking and testing a software product. Nowadays, many software projects use automation testing from start to end, especially in agile and DevOps methods. This means the engineering team runs tests automatically with the help of software tools . It will help to ke
15+ min read
Performance Testing - Software Testing
Performance Testing is a type of software testing that ensures software applications perform properly under their expected workload. It is a testing technique carried out to determine system performance in terms of sensitivity, reactivity, and stability under a particular workload. Prerequisite - Types of Software Testing Table of Content What is p
12 min read
Test Execution For Software Testing
The term Test Execution tells that the testing for the product or application needs to be executed in order to obtain the expected result. After the development phase, the testing phase will take place where the various levels of testing techniques will be carried out and the creation and execution of test cases will be taken place. The article foc
12 min read
Top Software Testing Companies for QA Outsourcing in 2024
Due to the increase in technologies, software testing companies are growing in demand in the tech industries. These software outsourcing companies are used to improve the performance, security, and functionality of the businesses and help these businesses grow in the tech industries. These companies also benefit from enhancing the quality and relia
7 min read
10 Best Software Testing Tools For QA
Quality Assurance (QA) testing tools are the tools that are used to automate the testing process of software applications. Therefore, QA is designed to make sure that every new software release meets the requirements of the project and provides a good user experience. This article will provide you with a detailed explanation of the 10 Best Software
9 min read
Software Testing Tools
Software Testing tools are the tools that are used for the testing of software. Software testing tools are often used to assure firmness, thoroughness, and performance in testing software products. Unit testing and subsequent integration testing can be performed by software testing tools. These tools are used to fulfill all the requirements of plan
12 min read
What is Software Testing?
Software testing is an important process in the software development lifecycle . It involves verifying and validating that a software application is free of bugs, meets the technical requirements set by its design and development , and satisfies user requirements efficiently and effectively. This process ensures that the application can handle all
11 min read
Python | Exceptional Conditions Testing in Unit Tests
This article aims to write a unit test that cleanly tests if an exception is raised. To test for exceptions, the assertRaises() method is used. Code #1 : Testing that a function raised a ValueError exception import unittest # A simple function to illustrate def parse_int(s): return int(s) class TestConversion(unittest.TestCase): def test_bad_int(se
2 min read
Python | Testing Output to stdout
Testing is a critical part of development as there is no compiler to analyze the code before Python executes it. Given a program that has a method whose output goes to standard Output (sys.stdout). This almost always means that it emits text to the screen. One likes to write a test for the code to prove that, given the proper input, the proper outp
2 min read
Mutation Testing using Mutpy Module in Python
Prerequisite: Mutation Testing Mutpy is a Mutation testing tool in Python that generated mutants and computes a mutation score. It supports standard unittest module, generates YAML/HTML reports and has colorful output. It applies mutation on AST level. Installation: This module does not come built-in with Python. To install it type the below comman
5 min read
Object oriented testing in Python
Prerequisite: Object-Oriented Testing Automated Object-Oriented Testing can be performed in Python using Pytest testing tool. In this article, we perform object-oriented testing by executing test cases for classes. We write a program that has one parent class called Product and three child classes - Snack, Beverage, and Staples. We implement all th
5 min read
How to split data into training and testing in Python without sklearn
Here we will learn how to split a dataset into Train and Test sets in Python without using sklearn. The main concept that will be used here will be slicing. We can use the slicing functionalities to break the data into separate (train and test) parts. If we were to use sklearn this task is very easy but it can be a little tedious in case we are not
2 min read
Python Falcon - API Testing
Python Falcon is a lightweight and fast web framework designed for building RESTful APIs. When it comes to API testing, Falcon provides a straightforward and efficient way to interact with your API endpoints. In this article, we'll explore three simple examples using Python Falcon: a basic API endpoint, form submission, and file upload with display
2 min read
Python Falcon - Testing
Testing is an integral part of software development, ensuring the reliability and functionality of applications. Python Falcon is a lightweight web framework for building APIs rapidly. In this article, we will explore how to test Python Falcon APIs using two popular testing frameworks: unittest and pytest. Each approach offers its advantages, and w
4 min read
Practice Tags :