0% found this document useful (0 votes)
10 views7 pages

Python Unit Testing Guide

This document discusses unit testing in Python. It explains that unit testing involves testing individual code modules to check for errors. The Python unittest module is used for unit testing and provides assert functions to check conditions. Several examples are given of writing unit test cases using assert statements and the unittest module to test the sum() function. The document also briefly discusses test runners like unittest, nose, and pytest that automate running tests and reporting results.

Uploaded by

AARUSH SABOO
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views7 pages

Python Unit Testing Guide

This document discusses unit testing in Python. It explains that unit testing involves testing individual code modules to check for errors. The Python unittest module is used for unit testing and provides assert functions to check conditions. Several examples are given of writing unit test cases using assert statements and the unittest module to test the sum() function. The document also briefly discusses test runners like unittest, nose, and pytest that automate running tests and reporting results.

Uploaded by

AARUSH SABOO
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

KJSCE/IT/SYBTECH/SEM III/PL1(Python)-

Experiment No. 1

Title: Program on Unit Testing using Python

(A Constituent College of Somaiya Vidyavihar


KJSCE/IT/SYBTECH/SEM III/PL1(Python)-

Batch: Roll No: Experiment No.:2

Aim: Program on implementation of Unit Testing using Python

Resources needed: Python IDE

Theory:

What is Software Testing?

Software Testing involves execution of software/program components using manual to evaluate one or more pro

What is Unit Testing?

is a technique in which particular module is tested to check by developer himself whether there are any errors. Th

What is the Python unittest?

Python provides the unittest module to test the unit of source code. The unittest plays an
essential role when we are writing the huge code, and it provides the facility to check whether
the output is correct or not.

Normally, we print the value and match it with the reference output or check the output
manually.

Python testing framework uses Python's built-in assert() function which tests a particular
condition. If the assertion fails, an AssertionError will be raised. The testing framework will then
identify the test as Failure. Other exceptions are treated as Error.
The following three sets of assertion functions are defined in unittest module −

 Basic Boolean Asserts


 Comparative Asserts

(A Constituent College of Somaiya Vidyavihar


KJSCE/IT/SYBTECH/SEM III/PL1(Python)-

 Asserts for Collections

Basic assert functions evaluate whether the result of an operation is True or False. All the assert
methods accept a msg argument that, if specified, is used as the error message on failure.
You can write both integration tests and unit tests in Python. To write a unit test for the built-in
function sum(), you would check the output of sum() against a known output.

For example, here’s how you check that the sum() of the numbers (1, 2, 3) equals 6:

>>> assert sum([1, 2, 3]) == 6, "Should be 6"

This will not output anything on the REPL because the values are correct.

If the result from sum() is incorrect, this will fail with an AssertionError and the
message "Should be 6". Try an assertion statement again with the wrong values to see
an AssertionError:

>>> assert sum([1, 1, 1]) == 6, "Should be 6"


In the REPL, you are seeing the raised AssertionError because the result of sum() does not
match 6. (most recent call last):
Traceback
File "<stdin>",
Instead of testing line 1, in
on the REPL, you’ll want to put this into a new Python file called test_sum.py
and
<module>
executeAssertionError:
it again: Should

def test_sum():
assert sum([1, 2, 3]) == 6, "Should be 6"

ifname== " main ": test_sum() print("Everything passed")

Now you have written a test case, an assertion, and an entry point (the command line). You can
now execute this at the command line:

(A Constituent College of Somaiya Vidyavihar


KJSCE/IT/SYBTECH/SEM III/PL1(Python)-

$ python
test_sum.py

You can see the successful result, Everything passed.

In Python, sum() accepts any iterable as its first argument. You tested with a list. Now test with a
tuple as well. Create a new file called test_sum_2.py with the following code:

def test_sum():
assert sum([1, 2, 3]) == 6, "Should be 6"

def test_sum_tuple():
assert sum((1, 2, 2)) == 6, "Should be 6"

ifname== " main ": test_sum() test_sum_tuple()


print("Everything passed")

When you execute test_sum_2.py, the script will give an error because the sum() of (1, 2, 2) is 5, not 6. The resul

$ python test_sum_2.py Traceback (most recent call last):


File "test_sum_2.py", line 9, in <module> test_sum_tuple()
File "test_sum_2.py", line 5, in test_sum_tuple assert sum((1, 2, 2)) == 6, "Should be 6"
AssertionError: Should be 6

Here you can see how a mistake in your code gives an error on the console with some
information on where the error was and what the expected result was.

Writing tests in this way is okay for a simple check, but what if more than one fails? This is
where test runners come in. The test runner is a special application designed for running tests,

(A Constituent College of Somaiya Vidyavihar


KJSCE/IT/SYBTECH/SEM III/PL1(Python)-

checking the output, and giving you tools for debugging and diagnosing tests and applications.

Choosing a Test Runner

Python contains many test runners. The most popular build-in Python library is
called unittest. The unittest is portable to the other frameworks. Consider the following three top
most test runners.

 unittest
 nose Or nose2
 pytest

unittest

The unittest is built into the Python standard library since 2.1. The best thing about the unittest, it comes with bot

The code must be written using the classes and functions.


The sequence of distinct assertion methods in the TestCase class apart from the built-in asserts statements.
Let's implement the above example using the unittest case.

Example -

import unittest
class TestingSum([Link]):

def test_sum(self):
[Link](sum([2, 3, 5]), 10, "It should be 10")
def test_sum_tuple(self):
[Link](sum((1, 3, 5)), 10, "It should be 10")

if name == ' main


': [Link]()

Output:

(A Constituent College of Somaiya Vidyavihar


KJSCE/IT/SYBTECH/SEM III/PL1(Python)-

.F
-
FAIL: test_sum_tuple (__main .TestingSum)
--
Traceback (most recent call last):
File "<string>", line 11, in test_sum_tuple
AssertionError: 9 != 10 : It should be 10

Ran 2 tests in 0.001s

FAILED (failures=1)
Traceback (most recent call last):
File "<string>", line 14, in <module>
File "/usr/lib/python3.8/unittest/[Link]", line 101, in init
[Link]()
File "/usr/lib/python3.8/unittest/[Link]", line 273, in runTests
[Link](not [Link]())
SystemExit: True

As we can see in the output, it shows the dot(.) for the successful execution and F for the one
failure.

Activities:

Write a program to add multiple numbers in loop and test it by running minimum 3 test cases

Result: (script and output)

Outcomes:

(A Constituent College of Somaiya Vidyavihar


KJSCE/IT/SYBTECH/SEM III/PL1(Python)-

Questions:

a) Differentiate between Unit Testing and Integration Testing.


b) Differentiate between manual testing and automated testing.

Conclusion: (Conclusion to be based on the objectives and outcomes achieved)

References:
1. Daniel Arbuckle, Learning Python Testing, Packt Publishing, 1st Edition, 2014 Wesly J Chun, Core Pyth
2. Albert Lukaszewsk, MySQL for Python, Packt Publishing, 1st Edition, 2010 Eric Chou, Mastering Pytho
3.
4.
5.

(A Constituent College of Somaiya Vidyavihar

Common questions

Powered by AI

It is crucial to use both manual and automated testing methods because they complement each other in covering different testing requirements. Manual testing allows for exploratory, ad-hoc testing and human judgment, particularly useful for early-stage development and non-repetitive test cases . Automated testing provides speed and accuracy for repetitive and regression testing, reducing human error and increasing efficiency . The key difference lies in the execution: manual testing relies on human intervention, whereas automated testing uses scripts and tools to run test scenarios.

Unit testing focuses on testing individual components or modules of a software to ensure each component functions correctly in isolation . In contrast, integration testing verifies the interoperability and correct interaction between multiple components or systems . Both are necessary because while unit testing ensures each module works individually, integration testing ensures that all parts work together harmoniously to achieve the intended outcomes of the software application.

A script executing test cases may result in an 'F' signifying a failure if the actual outcome of the test does not match the expected result. For example, in the test cases provided, the sum((1, 2, 2)) != 6 but was asserted to be equal, leading to an AssertionError and marking the test as failed . Conversely, a dot (.) indicates successful execution where test conditions met expected results without errors .

Python's unittest module facilitates testing by providing a framework to write test cases using classes and functions, and it supports varied assertions to validate outcomes . Basic assertion types in unittest include Boolean asserts that evaluate whether an operation is True or False, and comparative asserts which compare expected versus actual results . These assertions help in automating and simplifying the testing process by flagging any discrepancies through errors.

Integrating unittest with command-line execution involves creating test cases in Python scripts and executing them directly through the command-line interface, allowing developers to run tests easily without needing a specific IDE . This approach benefits development by facilitating automation, supporting CI/CD pipelines, and enabling batch processing of test suites. It also aids in quick verification of code changes by running tests immediately after modifications, thereby streamlining debugging and enhancing development efficiency.

The role of a test runner is to execute tests and provide outcomes in an organized manner, facilitating error diagnostics and troubleshooting . Popular test runners mentioned in the sources include unittest, nose or nose2, and pytest . These tools automate the testing process and offer robust testing capabilities, making them integral to developing reliable software applications.

The choice of language constructs like lists versus tuples impacts unit test cases in Python by affecting elements like mutability and expected outcomes. In the examples, a test case using a tuple did not pass because the sum of (1, 2, 2) does not match the expected result of 6, whereas tests using lists passed without errors when conditions aligned with expected sums . Understanding the properties of these constructs is crucial for correctly predicting test outcomes and avoiding assertion failures.

In Python's unittest framework, a 'Failure', indicated by an AssertionError, occurs when a test assertion condition fails, meaning the output did not match the expected result . An 'Error' results from exceptions other than AssertionErrors raised during test execution due to code issues or unexpected conditions . The difference helps developers identify not just failed logic conditions but also additional issues that might disrupt the code execution.

The trend towards using frameworks like unittest and pytest elevates software development practices by promoting test-driven development (TDD) and encouraging the integration of testing into the development life cycle. They standardize the way tests are written and executed, enhance automation, and improve code reliability and maintainability through structured testing . These frameworks provide developers with comprehensive tools for writing robust tests, improving code quality perceptions among stakeholders, and aligning software delivery with operational excellence.

Developers relying on static test cases may face challenges like limited test coverage, as static cases might not account for dynamic or unforeseen use scenarios, leading to untested edge cases . This can be mitigated by integrating dynamic test case generation methods, utilizing parameterized tests to cover a broader range of inputs, and continually updating test cases to reflect changes and new features in the software . Encouraging a culture of continuous testing and iteration can also bridge these gaps effectively.

You might also like