Generate Your Python Tests

转载: http://blog.kevinastone.com/generate-your-tests.html

When testing your application, you’ll often come across the need to test that your application behaves correct across a range of inputs or conditions. Instead of repetitively defining the same test scaffolding, let’s use some meta-programming to build our tests methods from a list of parameters. Nose has support for Generator Tests, but they don’t work with python’s unittest framework. Let’s walk-through how to build our own test generator that does.

Our Test Case

So let’s write a simple application for demonstration. We want to see if our input string is alphabetized.

1
2
def is_alphabetized(value):
return ''.join(sorted(value)) == value

Now let’s write a unit test case to check our implementation:

1
2
3
4
5
6
7
8
import unittest
class IsAlphabetizedTestCase(unittest.TestCase):
def test_is_alphabetized(self):
self.assertTrue(is_alphabetized('abcd'))
def test_is_not_alphabetized(self):
self.assertFalse(is_alphabetized('zyxw'))

参考资料

[1] Python 自动生成测试
[2] Python Mock 测试工具
[3] Python 常见的十个错误
[4] Python单元测试和Mock测试