unittest练习题
1.用unittest.TestSuite结合untitest.TextTestRunner执行如下测试用例
测试digital函数是否正确,函数定义如下
def digital(str1):
sum = 0
for n in str1:
if n >= “0” and n <= “9”:
sum += 1
return sum
digital函数说明:
参数str1为任意一个字符串;
函数返回值为参数str1中包含的数字个数;
如 参数str1的值为”sdfsdfsdf12”, 函数返回值为2;
如 参数str1的值为”hello”,函数返回值为0;
有一个函数叫digital,返回参数中数字的个数
比如参数如果为abc123,返回3,参数为abc,返回0
以参数“hello 123”和“1a3b”,“你好”来测试digital函数是否正确
思路:先从TestCase继承一个子类,然后子类中实现一个方法,就是一个测试用例
就是一个方法,用参数技术,提供三个元组
[(“hello123”,3),(“1a2b”,2),(“你好”)]
- 代码实现:
import unittest
from parameterized import parameterized
def digital(str1):
sum = 0
for n in str1:
if n >= "0" and n <= "9":
sum += 1
return sum
class MyTest(unittest.TestCase):
@parameterized.expand([("hello123",3),("1a2b",2),("你好",0)])
def test_001(self,a,b):
num1 = digital(a)
self.assertEqual(num1,b)