Python基础学习_测试_unittest模块

测试代码的目的:确定代码在面对各种输入时能否正常工作

学习目标:1、使用unittest模块测试代码 2、测试函数和类

3、为项目编写多少个测试类 4、知道测试为通过如何有助于改进代码

5、编写测试用例

1.1 测试函数 即我们自己定义的函数

def get_formatted_name(first,last):
    """Generate a neatly formatted full name. """
    full_name = first + ' ' + last
    return full_name

自己写测试代码

from name_function import get_formatted_name

print("Enter 'q' at any time to quit.")
while True:
    first = input("\nPlease give me at first name: ")
    if first == 'q':
        break
    last = input("Please give me a last name: ")
    if last == 'q':
        break
    
    formatted_name = get_formatted_name(first,last)
    print("\tNeatly formatted name: " + formatted_name)

结果:

Enter 'q' at any time to quit.


Please give me at first name: li

Please give me a last name: ming
	Neatly formatted name: li ming


Please give me at first name: liou

Please give me a last name: bei
	Neatly formatted name: liou bei


Please give me at first name: zhang

Please give me a last name: fei
	Neatly formatted name: zhang fei


Please give me at first name: zhao

Please give me a last name: yun
	Neatly formatted name: zhao yun


Please give me at first name: q

1.1.1 单元测试和测试用例

Python标准库中的模块unittest提供代码测试工具

单元测试:核实函数的某个方面是否有无问题

测试用例:是一组单元测试,这些单元测试一起核实函数在各种情形下的行为都符合要求

全覆盖式测试用例:包括一整套单元测试,涵盖了各种可能的函数使用方式。

大型项目的测试:通常,对重要行为编写测试,等项目被广泛使用时再考虑全覆盖。

1.1.2 可通过的测试

编写函数测试用例步骤

1、导入模块unittest以及测试的函数

2、创建一个继承unittest.TestCase的类,

并写一系列方法对函数行为的不同方面进行测试

import unittest
from name_function import get_formatted_name

class NamesTestCase(unittest.TestCase):
    """测试name_function.py"""
    
    def test_first_last_name(self):
        """能够正确地处理像Janis Joplin这样的姓名吗?"""
        formatted_name = get_formatted_name('janis', 'joplin')
        self.assertEqual(formatted_name, 'janis joplin')

unittest.main()

结果:

.
----------------------------------------------------------------------
Ran 1 test in 0.002s

OK
Out[3]: <spydercustomize.IPyTesProgram at 0x19b1f96b5e0>

一个点表示测试通过

总结:1、建立一个测试类,

测试类的名称最好包括test字眼,并且该类必须要继承unittest.TestCase类

2、该类中的方法的名称必须以test开头,

3、要调用合适的unittest模块中的合适方法,这里面调用了assertEqual():

该方法就将我们所创建的函数需要达到的结果与函数实现结果看是否满足我们的要求

原理:将formatted_name与’janis joplin’对比,看是否相等。

1.1.3 不能通过的测试

例子:前面一个例子加一个中间名实参

import unittest 
from name_function11 import get_formatted_name1

class NamesTestCase1(unittest.TestCase):
    """测试name_function.py"""
    
    def test_first_last_name(self):
        """能够正确地处理像Janis Joplin这样的姓名吗?"""
        formatted_name = get_formatted_name1('janis','li', 'joplin')
        self.assertEqual(formatted_name, 'janis li joplin')

unittest.main()

结果:


----------------------------------------------------------------------
Ran 2 tests in 0.004s

FAILED (failures=1)
Out[11]: <spydercustomize.IPyTesProgram at 0x19b1f9fb8e0>

改正:原因出在传递的中间名的实参有多种情况,所以应该把middle改为任意关键字实参

并且放在最后

import unittest 
from name_function111 import get_formatted_name11

class NamesTestCase11(unittest.TestCase):
    """测试name_function.py"""
    
    def test_first_last_name(self):
        """能够正确地处理像Janis Joplin这样的姓名吗?"""
        formatted_name = get_formatted_name11('janis', 'joplin','li')
        self.assertEqual(formatted_name, 'Janis Li Joplin')

unittest.main()

结果:

..
----------------------------------------------------------------------
Ran 2 tests in 0.003s

OK
Out[34]: <spydercustomize.IPyTesProgram at 0x19b1fa27700>

1.2 测试类

方法:

“”"
方法 用途
assertEqual(a,b) 核实a==b
assertNotEqual(a,b) 核实a != b
assertTrue(x) 核实x为True
assertFalse(x) 核实x为False
assertIn(item, list) 核实item在list中
assertNotIn(item, list) 核实item不在list中
“”"

11.2.2 测试的类

类的测试与函数的测试相似-------测试类主要对类的方法进行测试,但是与函数有不同之处

自己编写测试程序

from survey import AnonymousSurvey

定义一个问题,并创建一个表示调查的AnonymousSurvey对象

question = "What language did you first learn to speak?"
my_survey = AnonymousSurvey(question)

显示问题并存储答案

my_survey.show_question()
print("Enter 'q' at any time to quit.\n")
while True:
    response = input("Language: ")
    if response == 'q':
        break
    my_survey.store_responses(response)

显示调查结果

print("\nThank you to everyone who participated in the survey!")
my_survey.show_results()

结果:

What language did you first learn to speak?
Enter 'q' at any time to quit.


Language: English

Language: chinese

Language: English

Language: Franch

Language: q

Thank you to everyone who participated in the survey!
Survey results:
- English
- chinese
- English
- Franch

1.2.3 测试AnonymousSurvey类 即使用Python自带的模块unittest来测试

import unittest
from survey import AnonymousSurvey

class TestAnonymousSurvey(unittest.TestCase):
    """针对AnonymousSurvey类的测试"""
    
    def test_store_single_response(self):
        """测试单个答案会被妥善地存储"""
        question = "What language did you first learn to speak?"
        my_survey = AnonymousSurvey(question)
        my_survey.store_responses('English')
        
        self.assertIn('English', my_survey.responses)

unittest.main()

结果:

...
----------------------------------------------------------------------
Ran 3 tests in 0.005s

OK
Out[36]: <spydercustomize.IPyTesProgram at 0x19b1fa4c1f0>

结果表明测试都通过了

核实三个语言是否都在

import unittest
from survey import AnonymousSurvey

class TestAnonymousSurvey(unittest.TestCase):
    """针对AnonymousSurvey类的测试"""
    
    def test_store_single_response(self):
        """测试单个答案会被妥善地存储"""
        question = "What language did you first learn to speak?"
        my_survey = AnonymousSurvey(question)
        my_survey.store_responses('English')
        
        self.assertIn('English', my_survey.responses)
    
    def test_store_three_responses(self):
        """测试三个答案都会被妥善地存储"""
        question = "What language did you first learn to speak?"
        my_survey = AnonymousSurvey(question)
        responses = ['English','Spanish','Mandarin']
        for response in responses:
            my_survey.store_responses(response)
        
        for response in responses:
            self.assertIn(response, my_survey.responses)

unittest.main()

结果:

....
----------------------------------------------------------------------
Ran 4 tests in 0.006s

OK
Out[37]: <spydercustomize.IPyTesProgram at 0x19b1fa55cd0>

1.2.4 方法setUp()

作用:处理测试中同一个对象,并在测试中使用他们

Python中首先运行setUp(),然后在运行以test开头的方法

import unittest
from survey import AnonymousSurvey

class TestAnonymousSurvey(unittest.TestCase):
    """针对AnonymousSurvey类的测试"""
    
    def setUp(self):
        """
        创建一个调查对象和一组答案,供使用的测试方法使用
        """
        question = "What language did you first learn to speak?"
        self.my_survey = AnonymousSurvey(question)
        self.responses = ["English",'Spanish','Mandarin']


    def test_store_single_response(self):
        """测试单个答案会被妥善地存储"""
        
        self.my_survey.store_responses(self.responses[0])
        self.assertIn(self.responses[0], self.my_survey.responses)
        
        # question = "What language did you first learn to speak?"
        # my_survey = AnonymousSurvey(question)
        # my_survey.store_responses('English')
        # self.assertIn('English', my_survey.responses)
    
    def test_store_three_responses(self):
        """测试三个答案都会被妥善地存储"""
        
        for response in self.responses:
               self.my_survey.store_responses(response)
        
        for response in self.responses:
               self.assertIn(response, self.my_survey.responses)

       # question = "What language did you first learn to speak?"
       # my_survey = AnonymousSurvey(question)
       # responses = ['English','Spanish','Mandarin']
       # for response in responses:
       #     my_survey.store_responses(response)
        
       # for response in responses:
       #     self.assertIn(response, my_survey.responses)
            
   
unittest.main()

结果:

....
----------------------------------------------------------------------
Ran 4 tests in 0.005s

OK
Out[38]: <spydercustomize.IPyTesProgram at 0x19b1f89d670>

总结:

            测试的目的:检验我们编写的代码是否满足功能要求,或者检测我们的代码具有哪些漏洞。
            测试的对象:函数、类
            测试的模块:unittest模块
            测试类创建步骤:
            1、导入模块unittest以及测试的函数
             2、创建一个继承unittest.TestCase的类,
             并写一系列方法对函数行为的不同方面进行测试
            测试类的写法要求:
           1、建立一个测试类测试类的名称最好包括test字眼,并且该类必须要继承unittest.TestCase类
           2、该类中的方法的名称必须以test开头,
           3、要调用合适的unittest模块中的合适方法,这里面调用了assertEqual():

你可能感兴趣的:(python,学习,单元测试)