As a little programmer in my programming field, I am currently working as team lead in an entrepreneurial team. The technology stack involves Android, Python, Java and Go, which is also the main technology stack of our team. Contact: [email protected]

Maybe you’ve heard of Test Driven Development, but are you following this rule? In fact, when I write code, I rarely write unit tests first and then business function logic. I’m also going to learn how to write unit tests in Python.

0x00 unittest

The UnitTest unit testing framework in Python is similar to other languages such as JUnit. It supports test automation, configuration sharing, and shutdown code testing.

Suppose I have a mysum module in my project directory that calculates the sum of the numbers in the list. There is also a test_mysum.py file for writing unit tests.

Myproject / │ ├ ─ ─ mysum / │ └ ─ ─ just set py └ ─ ─ unittests └ ─ ─ test_mysum. PyCopy the code

Open the __init__.py file in the mysum module.

Add the following methods

def sum(args):
    total = 0
    for arg in args:
        total += arg
    return total
Copy the code

Open test_mysum.py and write the unit test

import unittest

from mysum import sum

class TestSum(unittest.TestCase):
    def test_list_int(self):
        """Testing the sum of a list of integers"""
        data = [1, 2, 3]
        result = sum(data)
        self.assertEqual(result, 6)


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

Copy the code

The mysum test case class is implemented by inheriting unitTest. TestCase. The test method test_list_int starts with test. In this method, you define a list of integers, execute the sum method, and determine if the result is as expected.

Finally, call unittest.main() to execute the test case

Ran 1 test in0.001 s OKCopy the code

If I add another method

def test_list_sum(self):
    data = [1.3.4]

    result = sum(data)
    self.assertEqual(result, 6)
Copy the code

Information similar to the following is displayed

6 != 8

Expected :8
Actual   :6
Copy the code

From this output, we can see that the expected value does not match the actual value, so if our test case is fine, we need to look at the implementation logic of Mysum.

A test case process can be summarized from this example:

  1. Build input data
  2. Execute the module to be tested and obtain the execution results
  3. Modify the code based on the results compared to the expected results

0x01 setup/tearDown

When writing unit tests, you can also override the setup and tearDown methods of the parent class to do some processing before and at the end of executing the test logic. For example, you can initialize test data in the setup method and do some cleanup in the tearDown method.

import unittest

class TestBasic(unittest.TestCase):
    def setUp(self):
        Load test data
        self.app = App(database='fixtures/test_basic.json')

    def test_customer_count(self):
        self.assertEqual(len(self.app.customers), 100)

    def test_existence_of_customer(self):
        customer = self.app.get_customer(id=10)
        self.assertEqual(customer.name, "Org XYZ")
        self.assertEqual(customer.address, "10 Red Road, Reading")
    
    def tearDown(self):
        self.app.releaseDB()
Copy the code

Setup and tearDown are executed once per test execution.

0x02 pytest

Pytest is a third-party testing framework that does not need to inherit a class and can use native Assert statements to test assertions of results.

It’s also very simple to use

Install first through PIP

➜ pip install pytest
Copy the code

We write a separate tests folder to create the test case file test_Pytest.py. Note: The PyTest file must be separated from the UnitTests file above, otherwise ModuleNotFoundError will appear. I’ve stepped in the hole here.

The file structure I’m using here for pyTest unit tests is

Tests │ └ ─ ─ test_func. PyCopy the code

The content of test_func.py is

Import the module we want to test
from mysum import sum


def test_answer():
    data = [1, 2, 3]

    assert sum(data) == 5

Copy the code

The test method starts with test

Then run it on the command line

➜ python -m pytest tests/test_func.py 
Copy the code

ModuleNotFoundError: No module named ‘mysum’

The result is as follows

tests/test_func.py F                                                                                                                                                                          [100%]

======================================================= FAILURES ==============================================
_______________________________________________________ test_answer ___________________________________________

    def test_answer():
        data = [1, 2, 3]
    
>       assert sum(data) == 5
E       assert 6 == 5
E        +  where 6 = sum([1, 2, 3])

tests/test_func.py:11: AssertionError
=======================================================1 failed in0.03 seconds = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =Copy the code

Due to the 6! =5, the unit test indicates where the error occurred.

0x03 To sum up

Testing code is very important to writing code, and writing unit tests is also a good habit. This article is just an appetizer. To write robust code, start by writing unit tests.

0x04 Learning Materials

  • Docs.python.org/3/library/u… Unit testing framework
  • Realpython.com/python-test… Getting Started With Testing in Python
  • Docs.python-guide.org/writing/tes… Testing Your Code