Unit testing with unittest or pytest

Unit testing with unittest or pytest

Unit software testing in the Python programming language is a user-defined Python program-based software source code testing technique or method in which multiple individual portion elements of a Python program source code—such as program-defined functions, methods, or small classes—are tested or analyzed at multiple levels, allowing for easy verification of their proper order within existing Python software source code.

Unit testing with unittest or pytest

In Python programming, there are two popular tools for unit testing.

  • unittest – This is a built-in software testing framework tool or platform for the Python programming language.
  • pytest – This is also a popular third-party Python software source code testing framework tool, widely used for its basic syntax and powerful testing features.

What is unit testing in Python programming?

Here, let’s say we have a Python-based user-defined function that adds two numbers to an existing program.

def total(p, q):

return p + q

Here, we expect:

total(4, 8) → 12

Here, a Python-based unit test automatically checks.

Python Program Function

Unit Test

Supposed Result = Actual Program Result?

SUCESS / FAIL

Source code unit testing in Python programs helps identify issues or errors immediately, and makes it easier to replace or modify program source code safely.

Why is unit testing important in Python?

Unit testing has the following advantages:

  • Quickly detecting software or program errors.
  • This application program can detect bugs before software is deployed.
  • Easy program software debugging.
  • If a Python program fails a software test, it can help developers identify which part of the program or software source code line is causing the problem.
  • This improves the quality of your program source code.
  • Python unit testing encourages software developers to create small, properly organized functions.
  • Easy Python allows secure modifications to software source code.
  • When modifications are made to existing Python program source code, these tests can help you find out if any problems have occurred with the functionality of a previously working program.
  • Easy software testing helps with program automation.
  • Once software tests are written, they can be run repeatedly without manually checking each result.

Testing with Unit Tests in Python.

UnitTest comes bundled with the Python tester, so you don’t usually need to manually install it separately. You can import it into Python like this:

import unittest

Let’s say we have a Python program source code file named calculation.py.

def plus(p, q):

return p + q

def minus(p, q):

return p – q

Here, we can create a Python program test file named:

test_calculation.py

Writing a UnitTest test in Python.

import unittest

from calculation import plus minus

class TestCalculation(unittest.TestCase):

def test_plus(self):

self.assertEqual(plus(3, 5), 8)

def test_minus(self):

self.assertEqual(minus(9, 4), 5)

if __name__ == “__main__”:

unittest.main()

Here in this example.

  • TestCalculation is a user-defined test class.
  • test_plus() plus() tests a plus function value.
  • test_minus() minus() tests a minus function value.
  • assertEqual() checks whether two values ​​are equal.
  • unittest.main() runs a test.

Running unittest in Python.

From the terminal on your computer, run python -m unittest test_calculation.py

If everything in this program is properly defined, you will see the correct output of your program displayed, indicating that the test parameters passed.

For example…

..

——————————————————————————

Run 2 tests in 0.001s

OK

Each. This displays a successful test.

Common unittest Assertions in python

Assertion functionUnittest assertion’s purpose with python
Assertequal(p, q) functionHere we use this function to checks whether p == q equal or not condition
Assertnotequal(p, q) functionHere we use this function to checks whether p != q is not equal to condition
Asserttrue(p) functionHere we use this function to checks whether p is true value statement
Assertfalse(p) functionHere we use this function to checks whether p is false value statement
Assertisnone(p) functionHere we use this function to checks whether p is none or not value
Assertin(p, q) functionHere we use this function to checks whether p is contained in q value statement
Assertraises()functionHere we use this function to checks whether code raises an expected exception or not

Example of unittest in Python.

import unittest

class TestExample(unittest.TestCase):

def test_values(self):

self.assertEqual(3, 3)

self.assertNotEqual(4, 7)

self.assertTrue(9 > 4)

self.assertIn(“Javascript”, [“Javascript”, “Matlab”])

if __name__ == “__main__”:

unittest.main()

Exception Testing in Python.

Unit tests in Python programs can also check whether a user-defined function displays errors in the proper order. Let’s say,

def division(p, q):

if q == 0:

raise ValueError(“Cannot divide by zero value”)

return p / q

The test here could be.

import unittest

class TestDivision(unittest.TestCase):

def test_division_by_zero(self):

with self.assertRaises(ValueError):

division (30, 0)

if __name__ == “__main__”:

unittest.main()

This verifies in the current program that dividing by zero raises any expected exceptions.

The setUp() and tearDown() functions in Python testing.

In Python software testing, unittest provides a method concept that can be used to prepare and clean up test resources.

setUp()

It is run before a test in every Python program.

tearDown()

It is run after a test in every Python program.

Example of the setUp() and tearDown() functions.

import unittest

class TestCalculation(unittest.TestCase):

def setUp(self):

self.p = 5

self.q = 3

def test_plus(self):

self.assertEqual(self.p + self.q, 8)

def test_minus(self):

self.assertEqual(self.p – self.q, 2)

def tearDown(self):

pass

if __name__ == “__main__”:

unittest.main()

This is used in Python when Python users need common setup or cleanup for tests.

Testing with pytest in Python programming.

pytest is a popular third-party Python testing tool or library framework for the Python programming language. Unlike UnitTest, it is not included built-in to Python by default.

Install pytest in Python like this.

pip install pytest

or

python -m pip install pytest

Write a test using pytest tests in Python programming.

We apply this using the same plus() function in Python programming.

def plus(p, q):

return p + q

This can be very handy in your test.

from calculation import plus

def test_plus():

assert plus(3, 7 ) == 10

Note here that we don’t need to create a test class or use self.assertEqual().

You can apply this directly using the assert statement in Python.

Running pytest in Python.

If your test file name here is calculation.

test_calculation.py

run:

pytest

or:

python -m pytest

This displays a successful Python program run test, indicating that the test passed.

Performing multiple case tests with Python pytest.

In the Python programming language, pytest’s job is to check or test a feature’s parameterization.

For example.

import pytest

@pytest.mark.parametrize(

“p, q, assume”,

[

(7, 2, 4),

(3, 9, 8),

(-2, 7, 2),

(0, 0, 0)

]

)

def test_plus(p, q, assume):

assert p + q == assume

Here, in this program, the same test function is run with multiple different inputs.

Testing exceptions with Python pytest.

pytest provides a function called pytest.raises().

import pytest

def division(p, q):

if q == 0:

raise ValueError(“Cannot divide by zero value”)

return p / q

def test_division_by_zero():

with pytest.raises(ValueError):

division(20, 0)

This checks in your program whether the expected exception is generated or not.

Fixture feature in pytest.

A fixture provides reusable setup data or resources for tests.

Example of a Fixture feature.

import pytest

@pytest.fixture

def integers():

return [9, 7, 8, 4, 3, 2]

def test_integers(integers):

assert len(integers) == 5

assert 4 in integers

Here, in this example, integers is a fixture that provides data to the test. Fixtures are particularly useful in Python for:

  • Setting up databases
  • Creating temporary files
  • Checking test data
  • Creating reusable objects
  • Creating and clearing resources

Main difference between unittest vs pytest in python

Each featureUnittest testing frameworkPytest testing framework
Included with pythonUnittest included built-in in python library, you can just use it when you needPytest is third party module, we need to add it manually in python
Installation requiredIt’s a built-in module you no need to install separate unittest in python libraryPytest is third party library test module, you need to install with pip python command
Test syntax or methodPython unittest test framework is more structured syntax to followPytest python framework is generally simpler syntax
Test classes availablePython unittest test framework commonly used for testing purposePytest python framework often unnecessary
Assertions methodPython unittest test framework allow self.assertequal() etc.Pytest python framework support python assert
Fixtures conceptSetup() / teardown() and other mechanismsPytest python framework provides powerful fixture system
Parameterized tests allowPython unittest test supported, but more verbose usePytest python framework very convenient during use
Plugins supportPython unittest test plugins support available, you can use them when needPytest python framework large plugin ecosystem supported
Best use forPython unittest test standard-library testing and structured suites for use casePytest python framework concise, flexible, feature-rich testing

Structure of a project with examples in Python.

A simple project in a Python program might look something like this.

testproject/

├── calculation.py

└── tests/

└── test_calculation.py

calculation.py

def plus(p, q):

return p + q

def plural(p, q):

return p * q

test_calculation.py

Using pytest in Python.

from calculation import plus, multiply

def test_plus():

assert plus(4, 7) == 11

def test_multiply():

assert multiply(3, 5) == 15

run.

pytest

In a Python program, this structure holds the application code, and tests are organized differently.

Unit testing vs. manual testing in Python.

Manual testing

A programmer runs the program application manually and checks the program output.

First, run the program.

Enter user input.

Check the output result.

Decide whether the result is correct.

Unit testing in Python.

These tests automatically check expected behavior in Python program source code.

Run a Python test

Test user input

Compare expected/actual results

Pass or fail

Automated tests in Python programs are especially used when an application itself becomes large-scale.

Best practices for unit testing in Python programming.

Test only one program behavior at a time in the Python programming language.

And every Python program you test should have a clear, detailed purpose.

Use descriptive test names when testing.

For example.

def test_division_by_zero_raises_error():

A better choice is:

def testone():

Create a normal and edge-case test in Python.

For example, testone:

Positive number

Negative number

Zero

Empty input

Very large value

Invalid input

How to keep tests independent in Python.

In this case, one test should not depend on another test running first.

Create tests in Python and run them repeatedly.

Whenever there is a major update or modification to a Python program’s source code, you should run that test.

Which of the two, unittest or pytest, should a Python user learn for testing their software source code?

Both unittest and pytest are useful concepts in Python software source code testing.

You can choose unittest if.

  • If Python users want to use Python’s built-in testing framework.
  • If Python users are reading standard Python libraries.
  • If Python users prefer a class-based testing structure.

You can choose pytest if.

  • If Python users need small source test code.
  • If Python users need powerful fixture features.
  • If Python users need easy parameterized test runs.
  • If Python users are working on modern Python software source code projects.

For beginner Python users, writing tests with pytest is easier, while learning unittest in detail is more beneficial, as it is an element or part of Python’s standard library.

Conclusion of Unit Testing with unittest or pytest in Python.

Unit testing in the Python programming language helps users verify that different elements of a Python program are working in the proper order.

There are two essential testing methods in Python programs.

unittest method

built-in Python

structured and class-based

and

pytest

third-party Python-supported framework

A simple and flexible testing method in Python.

A simple unittest test in the Python programming language looks like this.

import unittest

class TestSolution(unittest.TestCase):

def test_plus(self):

self.assertEqual(1 + 7, 8)

if __name__ == “__main__”:

unittest.main()

A simple pytest test in Python looks like this.

def test_plus():

assert 1 + 7 == 8

Python Testing in a Nutshell.

Unit testing in the Python programming language automatically checks or analyzes small portions of a program, allowing immediate detection of any errors in the existing program and modification of the program source code with greater trust authority.

Leave a Reply