Jul 3, 2011

python unittest

unittest

鼓励在写重要的功能函数之前先写 unittest,好处

  • Before writing code, writing unit tests forces you to detail your requirements in a useful fashion.
  • While writing code, unit tests keep you from over-coding. When all the test cases pass, the function is complete.
  • When refactoring code, they can help prove that the new version behaves the same way as the old version.
  • When maintaining code, having tests will help you cover your ass when someone comes screaming that your latest change broke their old code. (“But sir, all the unit tests passed when I checked it in...”)
  • When writing code in a team, having a comprehensive test suite dramatically decreases the chances that your code will break someone else’s code, because you can run their unit tests first. (I’ve seen this sort of thing in code sprints. A team breaks up the assignment, everybody takes the specs for their task, writes unit tests for it, then shares their unit tests with the rest of the team. That way, nobody goes off too far into developing code that doesn’t play well with others.)
做法

  1. 继承 TestCase 类
  2. 在测试开始之前会执行 setUp,做一些初始化工作
  3. 每一个 testcase 以 test_ 开头
  4. assertTrue, assertEqual, assertRaises
  5. unittest.main()


import random
import unittest

class TestSequenceFunctions(unittest.TestCase):

    def setUp(self):
        self.seq = range(10)

    def test_shuffle(self):
        # make sure the shuffled sequence does not lose any elements
        random.shuffle(self.seq)
        self.seq.sort()
        self.assertEqual(self.seq, range(10))

        # should raise an exception for an immutable sequence
        self.assertRaises(TypeError, random.shuffle, (1,2,3))

    def test_choice(self):
        element = random.choice(self.seq)
        self.assertTrue(element in self.seq)

    def test_sample(self):
        with self.assertRaises(ValueError):
            random.sample(self.seq, 20)
        for element in random.sample(self.seq, 5):
            self.assertTrue(element in self.seq)

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

0 comments: