#练习1: import random import unittest from TestCalc import TestCalcFunctions class TestSequenceFunctions(unittest.TestCase): def setUp(self): self.seq = range(10) def tearDown(self): pass def test_choice(self): # 从序列seq中随机选取一个元素 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) class TestDictValueFormatFunctions(unittest.TestCase): def setUp(self): self.seq = range(10) def tearDown(self): pass def test_shuffle(self): # 随机打乱原seq的顺序 random.shuffle(self.seq) self.seq.sort() self.assertEqual(self.seq, range(10)) # 验证执行函数时抛出了TypeError异常 self.assertRaises(TypeError, random.shuffle, (1, 2, 3)) if __name__ == '__main__': # 根据给定的测试类,获取其中的所有以“test”开头的测试方法,并返回一个测试套件 suite1 = unittest.TestLoader().loadTestsFromTestCase(TestSequenceFunctions) suite2 = unittest.TestLoader().loadTestsFromTestCase(TestDictValueFormatFunctions) suite3 = unittest.TestLoader().loadTestsFromTestCase(TestCalcFunctions) # 将多个测试类加载到测试套件中 suite = unittest.TestSuite([suite2, suite1,suite3]) #通过调整suit2和suite1的顺序,可以设定执行顺序 # 设置verbosity = 2,可以打印出更详细的执行信息 unittest.TextTestRunner(verbosity = 2).run(suite)
#练习2: #会生成一个test.html文件 import unittest import HTMLTestRunner import math #被测试类 class Calc(object): def add(self, x, y, *d): # 加法计算 result = x + y for i in d: result += i return result def sub(self, x, y, *d): # 减法计算 result = x - y for i in d: result -= i return result #单元测试 class SuiteTestCalc(unittest.TestCase): def setUp(self): self.c = Calc() @unittest.skip("skipping") def test_Sub(self): print "sub" self.assertEqual(self.c.sub(100, 34, 6), 61, u'求差结果错误!') def testAdd(self): print "add" self.assertEqual(self.c.add(1, 32, 56), 89, u'求和结果错误!') class SuiteTestPow(unittest.TestCase): def setUp(self): self.seq = range(10) # @unittest.skipIf() def test_Pow(self): print "Pow" self.assertEqual(pow(6, 3), 216, u'求幂结果错误!') def test_hasattr(self): print "hasattr" # 检测math模块是否存在pow属性 self.assertTrue(hasattr(math, 'pow1'), u"检测的属性不存在!") if __name__ == "__main__": suite1 = unittest.TestLoader().loadTestsFromTestCase(SuiteTestCalc) suite2 = unittest.TestLoader().loadTestsFromTestCase(SuiteTestPow) suite = unittest.TestSuite([suite1, suite2]) #unittest.TextTestRunner(verbosity=2).run(suite) filename = "c:\test.html" # 定义个报告存放路径,支持相对路径。 # 以二进制方式打开文件,准备写 fp = file(filename, 'wb') # 使用HTMLTestRunner配置参数,输出报告路径、报告标题、描述,均可以配 runner = HTMLTestRunner.HTMLTestRunner(stream = fp, title = u'测试报告', description = u'测试报告内容') # 运行测试集合 runner.run(suite)
#练习3: import unittest import random # 被测试类 class MyClass(object): @classmethod def sum(self, a, b): return a + b @classmethod def div(self, a, b): return a / b @classmethod def retrun_None(self): return None # 单元测试类 class MyTest(unittest.TestCase): # assertEqual()方法实例 def test_assertEqual(self): # 断言两数之和的结果 try: a, b = 1, 2 sum = 3 self.assertEqual(a + b, sum, '断言失败,%s + %s != %s' %(a, b, sum)) except AssertionError, e: print e # assertNotEqual()方法实例 def test_assertNotEqual(self): # 断言两数之差的结果 try: a, b = 5, 2 res = 1 self.assertNotEqual(a - b, res, '断言失败,%s - %s != %s' %(a, b, res)) except AssertionError, e: print e # assertTrue()方法实例 def test_assertTrue(self): # 断言表达式的为真 try: self.assertTrue(1 == 1, "表达式为假") except AssertionError, e: print e # assertFalse()方法实例 def test_assertFalse(self): # 断言表达式为假 try: self.assertFalse(3 == 2, "表达式为真") except AssertionError, e: print e # assertIs()方法实例 def test_assertIs(self): # 断言两变量类型属于同一对象 try: a = 12 b = a self.assertIs(a, b, "%s与%s不属于同一对象" %(a, b)) except AssertionError, e: print e # test_assertIsNot()方法实例 def test_assertIsNot(self): # 断言两变量类型不属于同一对象 try: a = 12 b = "test" self.assertIsNot(a, b, "%s与%s属于同一对象" %(a, b)) except AssertionError, e: print e # assertIsNone()方法实例 def test_assertIsNone(self): # 断言表达式结果为None try: result = MyClass.retrun_None() self.assertIsNone(result, "not is None") except AssertionError, e: print e # assertIsNotNone()方法实例 def test_assertIsNotNone(self): # 断言表达式结果不为None try: result = MyClass.sum(2, 5) self.assertIsNotNone(result, "is None") except AssertionError, e: print e # assertIn()方法实例 def test_assertIn(self): # 断言对象B是否包含在对象A中 try: strA = "this is a test" strB = "is" self.assertIn(strA, strB, "%s不包含在%s中" %(strB, strA)) except AssertionError, e: print e # assertNotIn()方法实例 def test_assertNotIn(self): # 断言对象B不包含在对象A中 try: strA = "this is a test" strB = "Selenium" self.assertNotIn(strA, strB, "%s包含在%s中" %(strB, strA)) except AssertionError, e: print e # assertIsInstance()方法实例 def test_assertIsInstance(self): # 测试对象A的类型是否是指定的类型 try: x = MyClass y = object self.assertIsInstance(x, y, "%s的类型不是%s".decode("utf-8") %(x, y)) except AssertionError, e: print e # assertNotIsInstance()方法实例 def test_assertNotIsInstance(self): # 测试对象A的类型不是指定的类型 try: a = 123 b = str self.assertNotIsInstance(a, b, "%s的类型是%s" %(a, b)) except AssertionError, e: print e # assertRaises()方法实例 def test_assertRaises(self): # 测试抛出的指定的异常类型 # assertRaises(exception) with self.assertRaises(ValueError) as cm: random.sample([1,2,3,4,5], "j") # 打印详细的异常信息 #print "===", cm.exception # assertRaises(exception, callable, *args, **kwds) try: self.assertRaises(ZeroDivisionError, MyClass.div, 3, 0) except ZeroDivisionError, e: print e # assertRaisesRegexp()方法实例 def test_assertRaisesRegexp(self): # 测试抛出的指定异常类型,并用正则表达式具体验证 # assertRaisesRegexp(exception, regexp) with self.assertRaisesRegexp(ValueError, 'literal') as ar: int("xyz") # 打印详细的异常信息 #print ar.exception # 打印正则表达式 #print "re:",ar.expected_regexp # assertRaisesRegexp(exception, regexp, callable, *args, **kwds) try: self.assertRaisesRegexp(ValueError, "invalid literal for.*XYZ'$",int,'XYZ') except AssertionError, e: print e if __name__ == '__main__': # 执行单元测试 unittest.main()