Python unit test example GitHub

Bruce 55 Published: 08/07/2024

Python unit test example GitHub

Here's an example of a Python unit test using the unittest module from the standard library, with explanations and code snippets:

What is Unit Testing?

Unit testing is a software testing method where individual units of source code are tested in isolation. Each unit is typically a function, method or procedure that performs a specific task. The goal of unit testing is to ensure each unit behaves correctly without affecting other parts of the system.

Why Use Unit Testing?

There are several reasons why you should use unit testing:

Early detection of defects: Catch bugs early in the development process when it's easier and less expensive to fix them. Improved code quality: Encourage better coding practices by requiring tests for each new feature or refactored code. Reduced regression testing time: With a comprehensive test suite, you can quickly identify changes that break existing functionality. Enhanced confidence in code changes: Know what changes will affect your application and prioritize them accordingly.

Python Unit Testing with unittest

Here's an example of how to write unit tests using the unittest module:

import unittest

def add_numbers(a, b):

return a + b

class TestAddNumbers(unittest.TestCase):

def test_add_positives(self):

self.assertEqual(add_numbers(2, 3), 5)

def test_add_negative_numbers(self):

self.assertEqual(add_numbers(-2, -3), -5)

def test_add_mixed_signs(self):

self.assertEqual(add_numbers(1, -2), -1)

if name == 'main':

unittest.main()

In this example:

We define a simple add_numbers function that takes two numbers and returns their sum. We create a TestAddNumbers class that inherits from unittest.TestCase. Each method in the test class represents an individual test case. The name of each method should start with "test" to indicate it's a test case. In each test case, we use assertions to verify the expected result matches the actual result returned by add_numbers. Finally, we run the tests using unittest.main().

How to Run Unit Tests

You can run unit tests from the command line or within your IDE:

From the command line: Navigate to the directory containing your test file and run python -m unittest test_module.py (replace test_module.py with your actual test file name). Within an IDE: Most popular IDEs, such as PyCharm, Visual Studio Code, or Spyder, allow you to create a configuration for running unit tests. For example, in PyCharm, you can right-click on the test file and select "Run 'Unittest'".

Conclusion

In this example, we've demonstrated how to write Python unit tests using the unittest module from the standard library. Unit testing helps ensure your code is robust, reliable, and maintainable by catching defects early in the development process. By following best practices for writing unit tests, you can improve the quality of your code and make it easier to debug and refactor in the future.

Additional Tips

Keep tests simple and focused: Each test case should test a single scenario or functionality. Use descriptive names: Name your tests and test classes clearly so they're easy to understand and maintain. Don't over-test: Balance testing coverage with actual development time. Over-testing can lead to burnout and decreased productivity. Integrate tests into CI/CD pipeline: Automate running unit tests as part of your continuous integration and delivery (CI/CD) pipeline to ensure code quality and detect regressions early.

GitHub Link:

[Insert link]

This repository contains the Python unit test example we've discussed. You can explore it to see more details on how to write effective unit tests in Python using the unittest module.

Python unit test example pytest

I'll respond in English as you requested.

Here's an example of a Python unit test using Pytest:

pytest_example.py

import pytest

from your_module import YourClass

@pytest.fixture

def instance():

return YourClass()

def test_your_method(instance):

Act

result = instance.your_method(some_input)

Assert

assert result == expected_output

@pytest.mark.parametrize("input_value, expected_output", [

("test1", "output1"),

("test2", "output2"),

("test3", "output3")

])

def test_your_method_with_parameters(instance, input_value, expected_output):

Act

result = instance.your_method(input_value)

Assert

assert result == expected_output

@pytest.mark.parametrize("input_values, expected_outputs", [

[("test1", "test2"), ["output1", "output2"]],

[("test3", "test4"), ["output3", "output4"]],

])

def test_your_method_with_list_parameters(instance, input_values, expected_outputs):

Act

results = instance.your_method(*input_values)

Assert

assert results == expected_outputs

@pytest.mark.parametrize("invalid_input", [

None,

123,

"this is not a string"

])

def test_your_method_with_invalid_parameters(instance, invalid_input):

with pytest.raises(TypeError):

instance.your_method(invalid_input)

This example demonstrates various ways to write unit tests using Pytest:

Test with a single input: test_your_method tests the method your_method with a single input value. Test with multiple inputs and expected outputs: test_your_method_with_parameters tests the method your_method with multiple input values and their corresponding expected outputs. Test with lists of inputs and expected outputs: test_your_method_with_list_parameters tests the method your_method with lists of input values and their corresponding expected outputs. Test for invalid inputs: test_your_method_with_invalid_parameters tests that the method raises a TypeError when passed an invalid input value (e.g., None, an integer, or a non-string value).

Each test function starts by creating an instance of the class being tested using the @pytest.fixture decorator. The test then calls the method being tested and asserts that the result is as expected using Pytest's built-in assertion mechanisms.

How to run the tests

To run these tests, save this code in a file named pytest_example.py, create a directory named tests containing this file, and then navigate to that directory in your terminal. Run the tests using the following command:

pytest pytest_example.py

This will execute all the test functions and report any failures or errors.

Why use Pytest?

Pytest is a popular testing framework for Python because it:

Provides a lot of flexibility: Pytest allows you to write tests in various styles, including fixtures, parametrize, and more. Has excellent reporting capabilities: Pytest provides detailed reports on test failures and errors, making it easier to diagnose issues. Is highly extensible: Pytest has a large ecosystem of plugins and integrations with other testing tools.

Overall, Pytest is an effective way to write unit tests in Python that can help you ensure your code is robust, reliable, and easy to maintain.