Help us improve
Share bugs, ideas, or general feedback.
From external-gitcode-ascend-skills
Guides creating and optimizing Python unittest test cases with assertions, setUp/tearDown patterns, test discovery, and suites. Use when writing or refactoring unit tests.
npx claudepluginhub ascend-ai-coding/awesome-ascend-skills --plugin migration-ascend-torchnpu-skillsHow this skill is triggered — by the user, by Claude, or both
Slash command
/external-gitcode-ascend-skills:unittest-writerThe summary Claude sees in its skill listing — used to decide when to auto-load this skill
创建基本测试用例:
Creates, writes, and optimizes Python test cases using pytest, including fixtures, parameterized tests, assertions, test organization, and debugging.
Guides Python testing with pytest, TDD, fixtures, mocking, parametrization, and coverage. Useful when writing Python code or reviewing test suites.
Provides test design patterns, coverage strategies (80-100% targets), types (unit/integration/E2E), organization, and best practices for comprehensive test suites. Use for new suites, coverage improvement, or test design.
Share bugs, ideas, or general feedback.
创建基本测试用例:
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()
继承 unittest.TestCase 创建测试类:
import unittest
class TestMyFunction(unittest.TestCase):
def test_method_name(self):
pass
test_ 开头在测试前准备环境,测试后清理资源:
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)
self.assertEqual(a, b) # a == b
self.assertNotEqual(a, b) # a != b
self.assertTrue(x) # bool(x) is True
self.assertFalse(x) # bool(x) is False
self.assertGreater(a, b) # a > b
self.assertGreaterEqual(a, b) # a >= b
self.assertLess(a, b) # a < b
self.assertLessEqual(a, b) # a <= b
self.assertIn(item, container) # item in container
self.assertNotIn(item, container)
self.assertIs(a, b) # a is b
self.assertIsNot(a, b)
self.assertIsNone(x) # x is None
self.assertIsNotNone(x)
with self.assertRaises(ValueError):
raise ValueError('error message')
with self.assertRaises(TypeError) as cm:
invalid_operation()
self.assertEqual(str(cm.exception), 'expected message')
self.assertAlmostEqual(a, b, places=7)
self.assertNotAlmostEqual(a, b)
unittest 自动发现测试:
python -m unittest discover
python -m unittest discover -s tests -p 'test_*.py'
按模块组织测试:
project/
├── mymodule.py
└── tests/
├── __init__.py
├── test_mymodule.py
└── test_other.py
手动组织测试套件:
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())
# 运行所有测试
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
if __name__ == '__main__':
unittest.main()
@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
@unittest.expectedFailure
def test_feature(self):
pass
def test_context_manager(self):
with self.assertLogs('logger', level='INFO') as cm:
logging.getLogger('logger').info('message')
self.assertIn('message', cm.output)
See assertions.md for complete list of all assertion methods with examples.
See patterns.md for:
See advanced.md for: