python入门学习笔记----第十一章:测试代码

这里写目录标题

    • 11.1 测试函数
      • 11.1.2 可通过的测试
      • 11.1.3 不能通过的测试
      • 11.1.4 测试未通过怎么办
      • 11.1.5 添加新测试
    • 11.2 测试类
      • 11.2.1 各种断言方法
      • 11.2.2 一个要测试的类
      • 11.2.4 方法setUp()





11.1 测试函数

1、编写name_function.py模块

def get_formatted_name(first, last):
    """生成整洁的姓名"""
    full_name = first + ' ' + last
    return full_name.title()

2、在names.py中测试

from name_function import get_formatted_name

print("Enter 'q' at any time to quit.")
while True:
    first = input("\nPlease give me a 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 + '.')

3、输出

Enter 'q' at any time to quit.

Please give me a first name: 胡
Please give me a last name: 猪猪
	Neatly formatted name: 胡 猪猪.

Please give me a first name: 胡
Please give me a last name: q



11.1.2 可通过的测试

先导入模块unittest以及要测试的函数,再创建一个继承unittest.TestCase的类,并编写一系列方法对函数行为的不同方面进行测试。
1、在test_name_function.py中测试name_function.py里面的get-formatted_name()

#导入unittest模块
import unittest
#导入要测试的模块函数
from name_function import get_formatted_name

#创建NameTestCase类,继承unittest.TestCase父类
class NamesTestCase(unittest.TestCase):
    """测试name_function.py"""

    #定义方法
    def test_first_last_name(self):
        """能够正确地处理像Janis Joplin这样的姓名吗?"""
        #创建实例,存储在formatted_name中
        formatted_name = get_formatted_name('janis', 'joplin')
        #断言方法,用来核实得到的结果是否和期望的结果一致
        #两个参数进行比较
        self.assertEqual(formatted_name, "Janis Joplin")

unittest.main()

2、输出
在这里插入图片描述


11.1.3 不能通过的测试

1、修改name_function.py,使其包含中间名
python入门学习笔记----第十一章:测试代码_第1张图片
2、运行test_name_function.py,输出

E
======================================================================
ERROR: test_first_last_name (__main__.NamesTestCase)
能够正确地处理像Janis Joplin这样的姓名吗?
----------------------------------------------------------------------
Traceback (most recent call last):
  File "C:/Users/zdb/PycharmProjects/untitled/temp.py", line 14, in test_first_last_name
    formatted_name = get_formatted_name('janis', 'joplin')
TypeError: get_formatted_name() missing 1 required positional argument: 'last'

----------------------------------------------------------------------
Ran 1 test in 0.001s

FAILED (errors=1)

进程已结束,退出代码1



11.1.4 测试未通过怎么办

测试未通过时,不要修改测试,而应修复导致测试不能通过的代码
1、使中间名变设置成可选的

def get_formatted_name(first, last, middle=''):
    """生成整洁的姓名"""
    if middle:
        full_name = first + ' ' + middle + ' ' + last
    else:
        full_name = first + ' ' + last
    return full_name.title()

2、运行test_name_function.py,输出
在这里插入图片描述


11.1.5 添加新测试

添加一个包含中间名的测试
1、在NamesTestCase类中再添加一个方法:

#导入unittest模块
import unittest
#导入要测试的模块函数
from name_function import get_formatted_name

#创建NameTestCase类,继承unittest.TestCase父类
class NamesTestCase(unittest.TestCase):
    """测试name_function.py"""

    #定义方法
    def test_first_last_name(self):
        """能够正确地处理像Janis Joplin这样的姓名吗?"""
        #创建实例,存储在formatted_name中
        formatted_name = get_formatted_name('janis', 'joplin')
        #断言方法,用来核实得到的结果是否和期望的结果一致
        #两个参数进行比较
        self.assertEqual(formatted_name, "Janis Joplin")

    def test_first_last_middle_name(self):
        """能够正确地处理像Wolfgang Amadeus Mozart这样的姓名吗?"""
        formatted_name = get_formatted_name('wolfgang', 'mozart', 'amadeus')
        self.assertEqual(formatted_name, "Wolfgang Amadeus Mozart")

unittest.main()

2、输出
在这里插入图片描述




11.2 测试类

11.2.1 各种断言方法

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



11.2.2 一个要测试的类

1、创建survey.py

class AnonymousSurvey():
    """收集匿名调查问卷的答案"""

    def __init__(self, question):
        """存储一个问题,并为存储答案做准备"""
        self.question = question
        self.responses = []   #答案设置空列表

    def show_question(self):
        """显示调查问卷"""
        print(self.question)

    def store_response(self, new_response):
        """存储单份调查问卷"""
        self.responses.append(new_response)

    def show_results(self):
        """显示搜集到的所有问卷"""
        print("Survey results:")
        for response in self.responses:
            print('- ' + response)

2、在language_survey.py中测试

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:    #一直循环,直到输入q跳出
    response = input("Language: ")
    if response == 'q':
        break
    my_survey.store_response(response)

#显示调查结果
print("\nThank youto everyone who participated in the survey!")
my_survey.show_results()

3、输出

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

Language: English
Language: python
Language: math
Language: q

Thank youto everyone who participated in the survey!
Survey results:
- English
- python
- math

进程已结束,退出代码0



1、测试survey.py中存储功能

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_response('English')

        self.assertIn('English', my_survey.responses)

unittest.main()

2、输出
在这里插入图片描述


测试三个

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_response('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', 'python', 'C']
        for response in responses:
            my_survey.store_response(response)

        for response in responses:
            self.assertIn(response, my_survey.responses)

unittest.main()

输出
在这里插入图片描述


11.2.4 方法setUp()

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', 'python', 'C']     #创建一个答案列表,存储在属性中,有self

    def test_store_single_response(self):
        """测试单个答案会被妥善地存储"""
        self.my_survey.store_response(self.responses[0])
        self.assertIn(self.responses[0], self.my_survey.responses)

    def test_store_three_responses(self):
        """测试三个答案会被妥善地存储"""
        for response in self.responses:
            self.my_survey.store_response(response)

        for response in self.responses:
            self.assertIn(response, self.my_survey.responses)

unittest.main()

在这里插入图片描述

你可能感兴趣的:(python)