python 单元测试

import unittest
  
  class InequalityTest(unittest.TestCase):

     def testEqual(self):
         self.assertNotEqual(1, 3-2)

     def testNotEqual(self):
         self.assertEqual(2, 3-2)

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

执行结果如下:
Hund@vm-env:/junhui/Knowledge/Learn_Python/py_tests$ python py-add-simple.py
FF
======================================================================
FAIL: testEqual (__main__.InequalityTest)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "py-add-simple.py", line 11, in testEqual
    self.assertNotEqual(1, 3-2)
AssertionError: 1 == 1

======================================================================
FAIL: testNotEqual (__main__.InequalityTest)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "py-add-simple.py", line 14, in testNotEqual
    self.assertEqual(2, 3-2)
AssertionError: 2 != 1

----------------------------------------------------------------------
Ran 2 tests in 0.000s

FAILED (failures=2)

从上面的结果可以看出testcase 的执行顺序是按字母排序的,那么我想先执行testNotEqual 这个测试用例该怎么办呢?经过查看unittest 的文档我找到了如下解决方案,可以把main 中修改为下面的suite 格式:
if __name__ == '__main__':
    suite = unittest.TestSuite()
    suite.addTest(InequalityTest("testNotEqual"))
    suite.addTest(InequalityTest("testEqual"))
    runner = unittest.TextTestRunner()
    runner.run(suite)

1. unittest module包含了编写运行unittest的功能,自定义的test class都要集成unitest.TestCase类,test method要以test开头,运行顺序根据test method的名字排序,特殊方法:

① setup():每个测试函数运行前运行
② teardown():每个测试函数运行完后执行
③ setUpClass():必须使用@classmethod 装饰器,所有test运行前运行一次

④ tearDownClass():必须使用@classmethod装饰器,所有test运行完后运行一次


ython内部自带了一个单元测试的模块,pyUnit也就是我们说的:unittest

先介绍下unittest的基本使用方法:

1.import unittest
2.定义一个继承自unittest.TestCase的测试用例类
3.定义setUp和tearDown,在每个测试用例前后做一些辅助工作。
4.定义测试用例,名字以test开头。
5.一个测试用例应该只测试一个方面,测试目的和测试内容应很明确。主要是调用assertEqual、assertRaises等断言方法判断程序执行结果和预期值是否相符。
6.调用unittest.main()启动测试
7.如果测试未通过,会输出相应的错误提示。如果测试全部通过则不显示任何东西,这时可以添加-v参数显示详细信息。

下面是unittest模块的常用方法:
assertEqual(a, b)     a == b      
assertNotEqual(a, b)     a != b      
assertTrue(x)     bool(x) is True      
assertFalse(x)     bool(x) is False      
assertIs(a, b)     a is b     2.7
assertIsNot(a, b)     a is not b     2.7
assertIsNone(x)     x is None     2.7
assertIsNotNone(x)     x is not None     2.7
assertIn(a, b)     a in b     2.7
assertNotIn(a, b)     a not in b     2.7
assertIsInstance(a, b)     isinstance(a, b)     2.7
assertNotIsInstance(a, b)     not isinstance(a, b)     2.7

下面看具体的代码应用:

首先写了一个简单应用:

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_error( self ):
          element = random . choice( self . seq)
          self . assertTrue( element not in self . seq)


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

下面是写了一个简单的应用,测试下面4个网址返回的状态码是否是200。

import unittest
import urllib

class TestUrlHttpcode( unittest . TestCase ):
    def setUp( self ):
        urlinfo = [ 'http://www.baidu.com' , 'http://www.163.com' , 'http://www.sohu.com' , 'http://www.cnpythoner.com' ]
        self . checkurl = urlinfo

    def test_ok( self ):
        for m in self . checkurl :
            httpcode = urllib . urlopen( m) . getcode()
            self . assertEqual( httpcode , 200)

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

如果有的网址打不开,返回404的话,测试则会报错

 如果有的网址打不开,返回404的话,测试则会报错

  ERROR: test_ok (__main__.TestUrlHttpcode)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "jay.py", line 12, in test_ok
    httpcode = urllib.urlopen(m).getcode()
  File "/usr/lib/python2.7/urllib.py", line 86, in urlopen
    return opener.open(url)
  File "/usr/lib/python2.7/urllib.py", line 207, in open
    return getattr(self, name)(url)
  File "/usr/lib/python2.7/urllib.py", line 462, in open_file
    return self.open_local_file(url)
  File "/usr/lib/python2.7/urllib.py", line 476, in open_local_file
    raise IOError(e.errno, e.strerror, e.filename)
IOError: [Errno 2] No such file or directory: 'fewfe.com'

----------------------------------------------------------------------
Ran 1 test in 1.425s

FAILED (errors=1)
 

也有其他的unittest方法,用于执行更具体的检查,如:

Method     Checks that     New in
assertAlmostEqual(a, b)     round(a-b, 7) == 0      
assertNotAlmostEqual(a, b)     round(a-b, 7) != 0      
assertGreater(a, b)     a > b     2.7
assertGreaterEqual(a, b)     a >= b     2.7
assertLess(a, b)     a < b     2.7
assertLessEqual(a, b)     a <= b     2.7
assertRegexpMatches(s, re)     regex.search(s)     2.7
assertNotRegexpMatches(s, re)     not regex.search(s)     2.7
assertItemsEqual(a, b)     sorted(a) == sorted(b) and works with unhashable objs     2.7
assertDictContainsSubset(a, b)     all the key/value pairs in a exist in b     2.7
assertMultiLineEqual(a, b)     strings     2.7
assertSequenceEqual(a, b)     sequences     2.7
assertListEqual(a, b)     lists     2.7
assertTupleEqual(a, b)     tuples     2.7
assertSetEqual(a, b)     sets or frozensets     2.7
assertDictEqual(a, b)     dicts     2.7
assertMultiLineEqual(a, b)     strings     2.7
assertSequenceEqual(a, b)     sequences     2.7
assertListEqual(a, b)     lists     2.7
assertTupleEqual(a, b)     tuples     2.7
assertSetEqual(a, b)     sets or frozensets     2.7
assertDictEqual(a, b)     dicts     2.7

你可以用unittest模块的更多方法来做自己的单元测试。


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值