AI-translated. Read the original in Korean
Python Testing
This document provides methods and guidelines for testing Python code, including recommended libraries and how to use them. These are recommendations: projects may adopt or propose other approaches. Even then, we encourage consistency within each project.
Unit Tests
This guide uses Python’s built-in unittest library to write unit tests. You can use pytest to make testing more efficient. For basic unit-testing guidelines, see Testing Principles.
Test Layout
Create a tests directory at the project root and place test files inside it. This layout separates application code from test code. You can also place tests alongside application code. Choose a layout that suits your project, using Choosing a test layout / import rules to inform the decision.
Writing Tests
Create a test class using unittest.TestCase. Use its assertion methods to check the state you want to verify.
import unittest
from unittest.mock import Mock
from actual.package import some_method
class TestClass(unittest.TestCase):
def test_some_method(self):
target = some_method()
self.assertIsNotNone(target)
self.assertEqual(target.value, 42)
Setup and Teardown
Use unittest.TestCase.setUp to perform any preparation needed before each test, such as initializing the object under test or dependency objects reused across tests.
import unittest
from unittest.mock import Mock
from actual.package.repo import Repo
class TestRepo(unittest.TestCase):
def setUp(self):
self.target = Target()
def test_target_method(self):
return_value = self.target.do_something()
self.assertTrue(return_value)
You can also use unittest.TestCase.tearDown to reset changes made during a test. For example, if a test must use a database, remove the data it creates in tearDown.
Mocking Dependencies
Mock the dependencies of the object under test. Make sure test results do not vary with the implementations of those dependencies.
repo.py
class Repo:
def __init__(self, cache_data_source: DataSource, remote_data_source: DataSource):
self.cache_data_source = cache_data_source
self.remote_data_source = remote_data_source
# ...
test_repo.py
import unittest
from unittest.mock import Mock
from actual.package.repo import Repo
class TestRepo(unittest.TestCase):
def test_some_method(self):
cache_data_source = Mock()
remote_data_source = Mock()
repo = Repo(cache_data_source, remote_data_source)
# ...
Test Fixtures
You can prepare the resources needed for tests in advance.
TBD
Related guides
All guidesGo Testing
This document provides Go testing methods and guidelines, including recommended libraries and how to use them. These are recommendations only; projects are free to adopt or propose…
Testing Principles
Well-designed tests help us build products faster and more reliably. This document provides the basic principles and guidelines for writing tests. Seven Testing Principles For a de…