SuperAPI AI Directory

unittest-writer

Testing & quality

View repository

Updated 10-16 05:00

About this skill

Unittest Writer

Quick Start

Create a basic test case:

import unittest

class TestStringMethods(unittest.TestCase):
    def test_upper(self):
        self.assertEqual('foo'.upper(), 'FOO')

    def test_isupper(self):
        self.assertTrue('FOO'.isupper())
        self.assertFalse('Foo'.isupper())
def test_split(self):
    s = 'hello world'
    self.assertEqual(s.split(), ['hello', 'world'])
    with self.assertRaises(TypeError):
        s.split(2)

if name == 'main': unittest.main()


## Basic Structure

### Test Class

继承 `unittest.TestCase` 创建测试类:

```python
import unittest

class TestMyFunction(unittest.TestCase):
    def test_method_name(self):
        pass

Test Methods

  • Test methods must start with test_ start with
  • Each test method should run independently
  • Use assertion methods to verify results

setUp and tearDown

Prepare the environment before tests and clean up resources after tests:

class TestDatabase(unittest.TestCase):
    def setUp(self):
        self.db = Database()
        self.db.connect()

    def tearDown(self):
        self.db.disconnect()

    def test_query(self):
        result = self.db.query('SELECT * FROM users')
        self.assertIsNotNone(result)

Common Assertions

Equality

self.assertEqual(a, b)           # a == b
self.assertNotEqual(a, b)        # a != b

Boolean

self.assertTrue(x)              # bool(x) is True
self.assertFalse(x)             # bool(x) is False

Comparison

self.assertGreater(a, b)        # a > b
self.assertGreaterEqual(a, b)   # a >= b
self.assertLess(a, b)           # a < b
self.assertLessEqual(a, b)      # a <= b

Membership

self.assertIn(item, container)  # item in container
self.assertNotIn(item, container)

Identity

self.assertIs(a, b)             # a is b
self.assertIsNot(a, b)

None

self.assertIsNone(x)            # x is None
self.assertIsNotNone(x)

Exceptions

with self.assertRaises(ValueError):
    raise ValueError('error message')

with self.assertRaises(TypeError) as cm:
    invalid_operation()
self.assertEqual(str(cm.exception), 'expected message')

Floating Point

self.assertAlmostEqual(a, b, places=7)
self.assertNotAlmostEqual(a, b)

Test Organization

Test Discovery

unittest automatically discovers tests:

python -m unittest discover
python -m unittest discover -s tests -p 'test_*.py'

Test Modules

Organize tests by module:

project/
├── mymodule.py
└── tests/
    ├── __init__.py
    ├── test_mymodule.py
    └── test_other.py

Test Suites

Manually organize a test suite:

def suite():
    suite = unittest.TestSuite()
    suite.addTest(TestStringMethods('test_upper'))
    suite.addTest(TestStringMethods('test_split'))
    return suite

if __name__ == '__main__':
    runner = unittest.TextTestRunner()
    runner.run(suite())

Running Tests

Command Line

# 运行所有测试
python -m unittest

# 运行特定模块
python -m unittest test_module

# 运行特定类
python -m unittest test_module.TestClass

# 运行特定方法
python -m unittest test_module.TestClass.test_method

# 详细输出
python -m unittest -v test_module

# 停止在第一个失败
python -m unittest -f test_module

Within Script

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

Best Practices

  1. One assertion per test: Each test method focuses on one behavior
  2. Descriptive names: Use descriptive test method names
  3. Independent tests: There should be no dependencies between tests
  4. Arrange-Act-Assert: Organize the test code structure
  5. Test edge cases: Test boundary conditions and exceptional cases

Advanced Features

Skipping Tests

@unittest.skip('reason')
def test_feature(self):
    pass

@unittest.skipIf(condition, 'reason')
def test_feature(self):
    pass

@unittest.skipUnless(condition, 'reason')
def test_feature(self):
    pass

Expected Failures

@unittest.expectedFailure
def test_feature(self):
    pass

Test Context Managers

def test_context_manager(self):
    with self.assertLogs('logger', level='INFO') as cm:
        logging.getLogger('logger').info('message')
    self.assertIn('message', cm.output)

Resources

Detailed Assertion Reference

See assertions.md for complete list of all assertion methods with examples.

Test Patterns and Best Practices

See patterns.md for:

  • Testing design patterns
  • Boundary testing strategies
  • Exception testing patterns
  • Mock and fixture usage

Advanced Features

See advanced.md for:

  • Mock objects and patching
  • Test fixtures and setup inheritance
  • Parameterized tests
  • Test coverage integration
  • Custom test runners