Python教程

Python之使用unittest模块测试

本文主要是介绍Python之使用unittest模块测试,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

1

#测试
def get_formatted_name_two(first, last, middle=''):
     """生成整洁的姓名"""
     full_name = f"{first} {middle} {last}"
     return full_name

def get_formatted_name_one(first, last):
     """生成整洁的姓名"""
     full_name = f"{first} {last}"
     return full_name

#改进版
def get_formatted_name_three(first, last, middle=''):
    """生成整洁的姓名"""
    if middle:
        full_name = f"{first} {middle} {last}"
    else:
        full_name = f"{first} {last}"
    return full_name.title()

2

#division为上面代码的模块名(文件名)
from division import get_formatted_name_one
from division import get_formatted_name_two

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

    formatted_name_one = get_formatted_name_one(first, last)
    print(f"\tNeatly formatted name: {formatted_name_one}")   

    formatted_name_two = get_formatted_name_two(first, last, middle='')
    print(f"\tNeatly formatted name: {formatted_name_two}")   

3

#为函数编写测试用例
#可先导入模块unittest和要测试的函数,解释器将在导入的同时执行它。
#再创建一个继承unittest.TestCase的类,并编写一系列方法函数行为的不同方面进行测试
#下面代码检查函数get_formatted_name()在给定名和姓时能否正确工作。
#unittest模块中的断言方法
#assertEqual(a,b)  核实 a == b
#assertNotEqual(a,b)  核实 a != b
#assertTure(x)  核实 x 为 True
#assertFlase(x)  核实 x 为 False
#assertIn(item, list)  核实 item 在 list 中
#assertNotIn(item, list)  核实 item 不在 list 中
import unittest
from division import get_formatted_name_two
from division import get_formatted_name_one
from division import get_formatted_name_three

#用于包含一系列针对get_formatted_name()的单元测试
class NameTestCase(unittest.TestCase):
    """测试division.py"""
    def test_first_last_name(self):
        """能够正确地处理像Janis Joplin这样的姓名吗?"""
        formatted_name_one = get_formatted_name_one('Janis', 'Joplin')
        formatted_name_tow = get_formatted_name_two('Janis', 'Joplin')
        formatted_name_three = get_formatted_name_three('Janis', 'Joplin')
        #unittest类的功能之一:断言方法
        #断言方法:核实得到的结果是否与期望的结果一致。
        self.assertEqual(formatted_name_one, 'Janis Joplin')
        #注意这里名字之间有默认的值,即middle=''。
        self.assertEqual(formatted_name_tow, 'Janis  Joplin')
        self.assertEqual(formatted_name_three, 'Janis Joplin')
  
    #添加新测试
    def test_first_last_middle_name(self):
        """能够正确地处理像Wolfgang Amadeus Mozart这样的姓名吗?"""
        formatted_name_three = get_formatted_name_three(
            'Wolfgang', 'Mozart', 'Amadeus')
        self.assertEqual(formatted_name_three, 'Wolfgang Amadeus Mozart')

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

4

#测试类,与函数相似
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(f"-{response}")

5

#为证明AnonymousSurvey类能正确工作,编写一个使用它的程序
from datetime import MAXYEAR
from alien_invasion import 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_response(response)

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

6

#对AnonymousSurvey类的行为的一个方面进行测试
import unittest
from alien_invasion 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('qq')
        self.assertIn('qq', my_survey.responses)

    def test_store_three_response(self):
        """测试三个答案会被妥善的存储"""
        question = "What language did you first learn to speak?"
        my_survey = AnonymousSurvey(question)
        responses = ['q', 'b', 'c']
        for response in responses:
            my_survey.store_response(response)

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

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

7 基于方法setUp()

#funittest.TestCase类包含的方法setUp()
#不用每次测试都创建实例
import unittest
from alien_invasion import AnonymousSurvey

class TestAnonymousSurvey:
    """针对AnonymousSurvey类的测试"""

    def setUp(self):
        """创建一个调查对象和一组答案,供使用的测试方法使用"""
        question = "What language did you first learn to speak?"
        self.my_survey = AnonymousSurvey(question)
        self.responses = ['q', 'b', 'c']

    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_response(self):
        """测试三个答案会被妥善的存储"""
        for response in self.responses:
            self.my_survey.store_response(response)

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

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

这篇关于Python之使用unittest模块测试的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!