智一面的面试题提供python的测试题
使用地址:http://www.gtalent.cn/exam/interview?token=99ef9b1b81c34b4e0514325e9bd3be54

TestCase类提供了几种断言方法来检查和报告故障。 下表列出了最常用的方法(有关更多断言方法,请参见下表):
 
Method Checks that
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
assertIsNot(a, b) a is not b
assertIsNone(x) x is None
assertIsNotNone(x) x is not None
assertIn(a, b) a in b
assertNotIn(a, b) a not in b
assertIsInstance(a, b) isinstance(a, b)
assertNotIsInstance(a, b) not isinstance(a, b)
除此之外,也可以使用以下方法检查异常,警告和日志消息的产生:
 
Method
 
Checks that
 
assertRaises(exc, fun, *args, **kwds)
 
fun(*args, **kwds) raises exc
 
assertRaisesRegex(exc, r, fun, *args, **kwds)
 
fun(*args, **kwds) raises exc and the message matches regex r
 
assertWarns(warn, fun, *args, **kwds)
 
fun(*args, **kwds) raises warn
 
assertWarnsRegex(warn, r, fun, *args, **kwds)
 
fun(*args, **kwds) raises warn and the message matches regex r
 
assertLogs(logger, level)
 
The with block logs on logger with minimum level
 
assertRaises(exception, callable, *args, **kwds)
assertRaises(exception, *, msg=None)
测试是否使用还传递给assertRaises()的任何位置或关键字参数调用callable时引发了异常。 如果引发异常,则测试通过;如果引发另一个异常,则测试通过;如果未引发异常,则测试通过。 为了捕获一组异常中的任何一个,可以将包含异常类的元组作为异常传递。
 
assertRaisesRegex(exception, regex, callable, *args, **kwds)
assertRaisesRegex(exception, regex, *, msg=None)
像assertRaises()一样,也测试正则表达式是否与引发的异常的字符串表示形式匹配。 regex可以是正则表达式对象,也可以是包含适合re.search()使用的正则表达式的字符串。
 
assertWarnsRegex(warning, regex, callable, *args, **kwds)
assertWarnsRegex(warning, regex, *, msg=None)
像assertWarns()一样,还测试触发警告消息中的正则表达式是否匹配。 regex可以是正则表达式对象,也可以是包含适合re.search()使用的正则表达式的字符串。
 
还有其他用于执行更具体检查的方法,例如:
 
Method Checks that
assertAlmostEqual(a, b) round(a-b, 7) == 0
assertNotAlmostEqual(a, b) round(a-b, 7) != 0
assertGreater(a, b) a > b
assertGreaterEqual(a, b) a >= b
assertLess(a, b) a < b
assertLessEqual(a, b) a <= b
assertRegex(s, r) r.search(s)
assertNotRegex(s, r) not r.search(s)
assertCountEqual(a, b) a and b have the same elements in the same number, regardless of their order.
下表总结了assertEqual()自动使用的类型特定方法的列表。 请注意,通常不必直接调用这些方法。
 
Method Used to compare
assertMultiLineEqual(a, b) strings
assertSequenceEqual(a, b) sequences
assertListEqual(a, b) lists
assertTupleEqual(a, b) tuples
assertSetEqual(a, b) sets or frozensets
assertDictEqual(a, b) dicts
三、TestRunner:测试运行器
TestRunner 测试运行器默认是使用 TextTestRunner(文本的测试运行器),而对于生成的文本测试结果有时候并不是那么的直观,此时我们便可以选择其他的测试运行器。
 
3.1 使用HTMLTestRunner生成html报告
3.1.1 安装 HTMLTestRunner.py 模块
下载HTMLTestRunner.py :http://tungwaiyip.info/software/HTMLTestRunner.html
 
将HTMLTestRunner.py 放到python安装目录下的 lib目录下。如果不知到python的安装目录可以使用如下命令查看:
 
windows下查看:where python ,如果结果有两个,选择目录中不含 Microsoft 的哪一个。
 
Linux下查看:which python 或 whereis python 。
 
 
3.1.2 修改 HTMLTestRunner.py 模块
官网发布的HTMLTestRunner.py 是基于 python2开发的,我们需要对其进行修改才能在 python3 中正常使用。
 
#第94行
import StringIO 修改为:import io

#第539行
self.outputBuffer = StringIO.StringIO() 修改为:self.outputBuffer = io.StringIO()

#第631行
print >>sys.stderr, '\nTime Elapsed: %s' % (self.stopTime-self.startTime)修改为:print(sys.stderr, '\nTime Elapsed: %s' % (self.stopTime-self.startTime))

#第642行
if not rmap.has_key(cls):修改为:if not cls in rmap:

#第766行
uo = o.decode('latin-1')修改为:uo = o

#第772行
ue = e.decode('latin-1')修改为:ue = e

 

3.1.3 使用 HTMLTestRunner.py 进行单元测试
我们使用TextTestRunner作为测试器进行测试时的代码是这样的。
 
#使用TextTestRuner运行
    unittest.TextTestRunner(suite)

 

 
而我们使用HTMLTestRunner作为测试器进行测试也可以使用同样的方式,只不过我们要先生成一个html文件,一遍在测试结束后向此文件中写入报告。

   
# 使用HTMLTestRunner运行
    # 创建 html 文件
    name = open(os.getcwd()+"/report,"wb")
    # 创建运行器实例
    runner = HTMLTestRunner(stream=name,                       # 输出到文件
                            title="Python自动化测试报告",     # html title
                            description="报告详情如下:")      #  描述
    runner.run(suite)
    # unittest.main(testRunner=runner,testcases=suite)
​

 

 
需要注意的是,使用HTMLTestRunner作为测试运行器时,TestCase中的帮助字符串将会作为生成的html的注释。
在这里插入图片描述
 
四、测试实例,如何测试一个python程序
例如,现在我们有一个 my_math.py 的python程序。

# my_math.py

def fib(n = 0)->int:
    """ 斐波那契数列 """
    a, b = 0, 1
    for i in range(n):
        a, b = b, a+b
    return a

def NarcissisticNumber(left=100, right=999)->list:
    """ 水仙花数 """
    assert(left >= 0 and right <= 999)
    lst = []
    for i in range(left, right+1):
        s = str(i)
        one = int(s[-1])
        ten = int(s[-2])
        hun = int(s[-3])
        if i == one ** 3 + ten ** 3 + hun ** 3:
            lst.append(i)
    return lst

if __name__ == '__main__':
    print("斐波那契数列第10项是:",fib(10))

    print("10 - 1000 的水仙花数有:\n",NarcissisticNumber(100,999))

 

 
在此 my_math 模块中有两个方法,分别为 求斐波那契第n项 与 求范围内的水仙花数 。
 
下面我们要对这两个方法进行测试,只需要新建一个 test_my_math.py 文件,将 unittest 与 my_math 模块引入即可。

import unittest

from 测试.测试实例 import my_math


class MyMathTest(unittest.TestCase):

    def test_fib(self):
        print("测试",my_math.fib.__doc__)
        a, b = 0, 1
        for i in range(0, 50):
            #  输出结果
            # print("斐波那契数列第{0}项是{1}".format(i, my_math.fib(i)))
            self.assertEqual(my_math.fib(i), a, "断言出错..")
            a , b = b , a+b

    def test_NarcissisticNumber(self):
        print("测试",my_math.NarcissisticNumber.__doc__)
        # 三位水仙花数
        lst = [153,370,371,407]
        res = my_math.NarcissisticNumber()
        self.assertEqual(lst, res, "断言出错..")

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

 

 
 
测试结果:在这里插入图片描述
 
我们的python技术交流群:941108876
智一面的面试题提供python的测试题
http://www.gtalent.cn/exam/interview?token=99ef9b1b81c34b4e0514325e9bd3be54