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.
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_TestingThe 'unittest' module
|--- __init__.py (to initialize the directory as python package)
|--- app.py (our software)
|--- tests (folder to keep all test files)
|--- __init__.py
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.
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')
if __name__ == '__main__':
unittest.main()
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.000sOK
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.001sFAILED (failures=2)
A few things to note in the above test report are -
Note: For further knowledge you can read the complete documentation of unittest.
The "nose2" moduleThe 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,
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.
nose2 -s DIR_ADD DIR_NAME
nose2 -s DIR_ADD DIR_NAME.TEST_FILE.TEST_CLASS.TEST_NAME
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 itemstests/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.
py.test <filename>
py.test -k "area"
# @pytest.mark.<tag_name>
@pytest.mark.area
def test_file1_area():
sq = app.Square(2)
assert sq.area() == 4,
f"area for side {sq.side} units is {sq.area()}"
py.test -m <tag_name>
pip install pytest-xdist
py.test -n 4
pytest --workers 4
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4