Python编程从入门到实践笔记——测试代码(一篇足够)

版权声明:本文为博主原创文章,非商用转载请保持署名-注明出处。 https://blog.csdn.net/adan_journal_of_data/article/details/77937477

11 测试代码

  编写函数或类时,还可为其编写测试。通过测试,可确定代码面对各种输入都能够按要求的那样工作。在程序中添加新代码时,你也可以对其进行测试,确认它们不会破坏程序既有的行为。
  在本章中,你将学习如何使用Python模块unittest中的工具来测试代码。你将学习编写测试用例,核实一系列输入都将得到预期的输出。你将看到测试通过了是什么样子,测试未通过又是什么样子,还将知道测试未通过如何有助于改进代码。你将学习如何测试函数和类,并将知道该为项目编写多少个测试。

"""11.1 测试函数"""
"""
下面是一个简单的函数,它接受名和姓并返回整洁的姓名:
"""
"""name_function.py"""

def get_formatted_name(first, last): 
    """Generate a neatly formatted full name.""" 
    full_name = first + ' ' + last 
    return full_name.title() 
  
  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
"""
为核实get_formatted_name()像期望的那样工作,我们来编写一个
使用这个函数的程序。程序names.py让用户输入名和姓,并显示整洁的全名: 
"""
"""names.py"""

from name_function import get_formatted_name

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

    last = raw_input("Please give me a last name: ")
    if last == 'q':
        break

    formatted_name = get_formatted_name(first, last)
    print("\tNeatly formatted name: " + formatted_name + '.')

  
  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
Enter 'q' at any time to quit.

Please give me a first name: janis
Please give me a last name: joplin
    Neatly formatted name: Janis Joplin.

Please give me a first name: bob
Please give me a last name: dylan
    Neatly formatted name: Bob Dylan.

Please give me a first name: q

  
  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

  从上述输出可知,合并得到的姓名正确无误。现在假设我们要修改get_formatted_name(),使其还能够处理中间名。这样做时,我们要确保不破坏这个函数处理只有名和姓的姓名的方式。为此,我们可以在每次修改get_formatted_name()后都进行测试:运行程序names.py,并输入像Janis Joplin这样的姓名,但这太烦琐了。
  所幸Python提供了一种自动测试函数输出的高效方式。倘若我们对get_formatted_name()进行自动测试,就能始终信心满满,确信给这个函数提供我们测试过的姓名时,它都能正确地工作。

11.1.1 单元测试和测试用例

  Python标准库中的模块unittest提供了代码测试工具。
  单元测试用于核实函数的某个方面没有问题;测试用例是一组单元测试,这些单元测试一起核实函数在各种情形下的行为都符合要求。
  良好的测试用例考虑到了函数可能收到的各种输入,包含针对所有这些情形的测试。全覆盖式测试用例包含一整套单元测试,涵盖了各种可能的函数使用方式。对于大型项目,要实现全覆盖可能很难。通常,最初只要针对代码的重要行为编写测试即可,等项目被广泛使用时再考虑全覆盖。

11.1.2 可通过的测试

  要为函数编写测试用例,可先导入模块unittest以及要测试的函数,再创建一个继承unittest.TestCase的类,并编写一系列方法(需要以test或Test开头)对函数行为的不同方面进行测试。 下面是一个只包含一个方法的测试用例,它检查函数get_formatted_name()在给定名和姓时能否正确地工作:

"""test_name_function.py"""

import unittest
#from name_function import get_formatted_name

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

class NamesTestCase(unittest.TestCase):  # 这个类必须继承unittest.TestCase类
    """测试name_function.py"""   

    def test_first_last_name(self):
        formatted_name = get_formatted_name('janis', 'joplin')

        # ①
        self.assertEqual(formatted_name, 'Janis Joplin')

if __name__ == '__main__':  
#    unittest.main()
    unittest.main(argv=['first-arg-is-ignored'], exit=False)
  
  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
.

Janis Joplin



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

OK

  
  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

①处,我们使用了unittest类最有用的功能之一:一个断言方法。断言方法用来核实得到的结果是否与期望的结果一致。

  在这里,我们期望formatted_name的值为"Janis Joplin"。为检查是否确实如此,我们调用unittest的方法assertEqual(),并向它传递formatted_name"Janis Joplin"进行比较。代码行unittest.main()让Python运行这个文件中的测试。

说明:

  书中原代码在本地可以运行,但是在jupyter notebook中运行报错”AttributeError: ‘module’ object has no attribute”,看到Stack Overflow上的问答,参考修改后可以在jupyter notebook中运行。

unittest.main(argv=['first-arg-is-ignored'], exit=False)

unittest.main(argv=['ignored', '-v'], exit=False)

1.1.3 不能通过的测试

  修改get_formatted_name(),使其能够处理中间名,但这样做时,故意让这个函数无法正确地处理像Janis Joplin这样只有名和姓的姓名。

  下面是函数get_formatted_name()的新版本,它要求通过一个实参指定中间名:

"""name_function.py"""
def get_formatted_name(first, middle, last): 
    """生成整洁的姓名""" 
    full_name = first + ' ' + middle + ' ' + last 
    return full_name.title() 
  
  
  • 1
  • 2
  • 3
  • 4
  • 5

  运行程序test_name_function.py

"""test_name_function.py"""

import unittest
#from name_function import get_formatted_name

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

class NamesTestCase(unittest.TestCase):  # 这个类必须继承unittest.TestCase类
    """测试name_function.py"""   

    def test_first_last_name(self):
        formatted_name = get_formatted_name('janis', 'joplin')

        self.assertEqual(formatted_name, 'Janis Joplin')

if __name__ == '__main__':  
#    unittest.main()
    unittest.main(argv=['first-arg-is-ignored'], exit=False)
  
  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21

E

ERROR: test_first_last_name (main.NamesTestCase)

Traceback (most recent call last):
File “<ipython-input-22-c6f1d3890843>”, line 15, in test_first_last_name
formatted_name = get_formatted_name(‘janis’, ‘joplin’)
TypeError: get_formatted_name() takes exactly 3 arguments (2 given)


Ran 1 test in 0.041s

FAILED (errors=1)

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

11.1.4 测试未通过时怎么办

  测试未通过时怎么办呢?如果你检查的条件没错,测试通过了意味着函数的行为是对的,而测试未通过意味着你编写的新代码有错。因此,测试未通过时,不要修改测试,而应修复导致测试不能通过的代码:检查刚对函数所做的修改,找出导致函数行为不符合预期的修改。
  在这个示例中,get_formatted_name()以前只需要两个实参——名和姓,但现在它要求提供名、中间名和姓。就这里而言,最佳的选择是让中间名变为可选的。这样做后,使用类似于Janis Joplin的姓名 进 行 测 试 时 , 测 试 就 会 通 过 了 , 同 时 这 个 函 数 还 能 接 受 中 间 名 。 下 面 来 修 改get_formatted_name(),将中间名设置为可选的,然后再次运行这个测试用例。如果通过了,我们接着确认这个函数能够妥善地处理中间名。

  将中间名设置为可选的,可在函数定义中将形参middle移到形参列表末尾,并将其默认值指定为一个空字符串。我们还要添加一个if测试,以便根据是否提供了中间名相应地创建姓名:

"""name_function.py"""

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

  
  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

  再次运行test_name_function.py:

"""test_name_function.py"""

import unittest
from name_function import get_formatted_name

class NamesTestCase(unittest.TestCase):  # 这个类必须继承unittest.TestCase类
    """测试name_function.py"""   

    def test_first_last_name(self):
        formatted_name = get_formatted_name('janis', 'joplin')
        print formatted_name
        self.assertEqual(formatted_name, 'Janis Joplin')

if __name__ == '__main__':  
#    unittest.main()
    unittest.main(argv=['first-arg-is-ignored'], exit=False)
  
  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
.

Janis Joplin



----------------------------------------------------------------------
Ran 1 test in 0.003s

OK

  
  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

11.1.5 添加新测试

  确定get_formatted_name()又能正确地处理简单的姓名后,我们再编写一个测试,用于测试包含中间名的姓名。为此,我们在NamesTestCase类中再添加一个方法:

"""test_name_function.py"""

import unittest
from name_function import get_formatted_name

class NamesTestCase(unittest.TestCase):  # 这个类必须继承unittest.TestCase类
    """测试name_function.py"""   

    def test_first_last_name(self):
        formatted_name = get_formatted_name('janis', 'joplin')
        print formatted_name
        self.assertEqual(formatted_name, 'Janis Joplin')

    def test_first_last_middle_name(self):
        formatted_name = get_formatted_name(
            'wolfgang', 'mozart', 'amadeus')
        self.assertEqual(formatted_name, 'Wolfgang Amadeus Mozart')

if __name__ == '__main__':  
#    unittest.main()
    unittest.main(argv=['first-arg-is-ignored'], exit=False)
  
  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
...

Janis Joplin



----------------------------------------------------------------------
Ran 3 tests in 0.007s

OK

  
  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

  我们将这个方法命名为test_first_last_middle_name()。方法名必须以test_打头,这样它才会在我们运行test_name_function.py时自动运行。这个方法名清楚地指出了它测试的是get_formatted_name()的哪个行为,这样,如果该测试未通过,我们就会马上知道受影响的是哪种类型的姓名。在TestCase类中使用很长的方法名是可以的;这些方法的名称必须是描述性的,这才能让你明白测试未通过时的输出;这些方法由Python自动调用,你根本不用编写调用它们的代码。
  为测试函数get_formatted_name(),我们使用名、姓和中间名调用它,再使用assertEqual()检查返回的姓名是否与预期的姓名(名、中间名和姓)一致。

习题11-1 城市和国家

  编写一个函数,它接受两个形参:一个城市名和一个国家名。这个函数返回一个格式为 City, Country 的字符串,如 Santiago, Chile 。将这个函数存储在一个名为 city_functions.py 的模块中。
  创建一个名为 test_cities.py 的程序,对刚编写的函数进行测试(别忘了,你需要导入模块 unittest 以及要测试的函数)。编写一个名为 test_city_country()的方法,核实使用类似于 ‘santiago’ 和 ‘chile’ 这样的值来调用前述函数时,得到的字符串是正确的。
运行 test_cities.py,确认测试 test_city_country()通过了。

"test_cities.py"

import unittest
from  city_functions import city_country

class CityCountryTest(unittest.TestCase):

    def test_city_country(self):
        formatted_string = city_country('santiago', 'chile')
        self.assertEqual(formatted_string, 'Santiago, Chile')

if __name__ == '__main__':
    unittest.main(argv=['first-arg-is-ignored'], exit=False)
  
  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
...

Janis Joplin



----------------------------------------------------------------------
Ran 3 tests in 0.007s

OK

  
  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

习题11–2 人口数量

  修改前面的函数,使其包含第三个必不可少的形参 population,并返回一个格式为 City, Country – population xxx 的字符串,如 Santiago, Chile – population 5000000。运行 test_cities.py,确认测试 test_city_country()未通过。
  修改上述函数,将形参population 设置为可选的。再次运行 test_cities.py,确认测试 test_city_country()又通过了。
  再编写一个名为 test_city_country_population()的测试,核实可以使用类似于 ‘santiago’、’chile’ 和 ‘population=5000000’ 这样的值来调用这个函数。再次运行test_cities.py,确认测试 test_city_country_population()通过了。

"test_cities.py"
"加一个形参population"

import unittest
from  city_functions import city_country

class CityCountryTest(unittest.TestCase):

    def test_city_country(self):
        formatted_string = city_country('santiago', 'chile')
        self.assertEqual(formatted_string, 'Santiago, Chile')

if __name__ == '__main__':
    unittest.main(argv=['first-arg-is-ignored'], exit=False)
  
  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14

ERROR: test_city_country (main.CityCountryTest)

Traceback (most recent call last):
File “<ipython-input-1-40099b039d57>”, line 9, in test_city_country
formatted_string = city_country(‘santiago’, ‘chile’)
TypeError: city_country() takes exactly 3 arguments (2 given)


Ran 1 test in 0.002s

FAILED (errors=1)

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

"test_cities.py"
"形参可选"

import unittest
from  city_functions import city_country

class CityCountryTest(unittest.TestCase):

    def test_city_country(self):
        formatted_string = city_country('santiago', 'chile')
        self.assertEqual(formatted_string, 'Santiago, Chile')

if __name__ == '__main__':
    unittest.main(argv=['first_arg-is-ignored'], exit=False)
  
  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14

.

Ran 1 test in 0.002s

OK

  • 1
  • 2
  • 3
  • 4
  • 5

"test_cities.py"
"测试人口"

import unittest
from  city_functions import city_country

class CityCountryTest(unittest.TestCase):

    def test_city_country(self):
        formatted_string = city_country('santiago', 'chile')
        self.assertEqual(formatted_string, 'Santiago, Chile')

    def test_city_country_population(self):
        formatted_string = city_country('santiago', 'chile', 5000000)
        self.assertEqual(formatted_string, 'Santiago, Chile - population 5000000')

if __name__ == '__main__':
    unittest.main(argv=['first-arg-is-ignored'], exit=False)
  
  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18

Ran 2 tests in 0.005s

OK

  • 1
  • 2
  • 3
  • 4
  • 5

11.2 测试类

11.2.1 各种断言方法

  Python在unittest.TestCase类中提供了很多断言方法。表中描述了6个常用的断言方法。使用这些方法可核实返回的值等于或不等于预期的值、返回的值为TrueFalse、返回的值在列表中或不在列表中。你只能在继承unittest.TestCase的类中使用这些方法。

方法 用途
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  一个要测试的类 """

"""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

  
  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
"""编写一个使用AnonymousSurvey类的程序"""

"""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:
    response = raw_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()

  
  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
What language did you first learn to speak?
Enter 'q' at any time to quit.

Language: English
Language: Spanish
Language: English
Language: Mandarin
Language: q

Thank you to everyone who participated in the survey!
Survey results:
- English
- Spanish
- English
- Mandarin

  
  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
"""11.2.3  测试 AnonymousSurvey 类 """

import unittest
from survey import AnonymousSurvey

class TestAnonymousSurvey(unittest.TestCase):
    """Tests for the class AnonymousSurvey."""


    def test_store_single_response(self):
        """Test that a single response is stored properly."""
        question = "What language did you first learn to speak?"
        my_survey = AnonymousSurvey(question) 
        my_survey.store_response('English') 

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


if __name__ == '__main__':           
    unittest.main(argv=['first-arg-is-ignored'], exit=False)


  
  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22

.

Ran 1 test in 0.001s

OK

  • 1
  • 2
  • 3
  • 4
  • 5

  这很好,但只能收集一个答案的调查用途不大。下面来核实用户提供三个答案时,它们也将被妥善地存储。为此,我们在TestAnonymousSurvey中再添加一个方法:

import unittest
from survey import AnonymousSurvey

class TestAnonymousSurvey(unittest.TestCase):
    """Tests for the class AnonymousSurvey."""


    def test_store_single_response(self):
        """Test that a single response is stored properly."""
        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):
        """Test that three individual responses are stored properly."""
        question = "What language did you first learn to speak?"
        my_survey = AnonymousSurvey(question) 
        responses = ['English', 'Spanish', 'Mandarin'] 
        for response in responses: 
            my_survey.store_response(response) 

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



if __name__ == '__main__':           
    unittest.main(argv=['first-arg-is-ignored'], exit=False)


  
  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32

Ran 2 tests in 0.004s

OK

  • 1
  • 2
  • 3
  • 4
  • 5

  效果很好,但这些测试有些重复的地方。下面使用unittest的另一项功能来提高它们的效率。

11.2.4 方法 setUp()

  在前面的test_survey.py中,我们在每个测试方法中都创建了一个 AnonymousSurvey 实例,并在每个方法中都创建了答案。unittest.TestCase 类包含方法 setUp() ,让我们只需创建这些对象一次,并在每个测试方法中使用它们。如果你在 TestCase 类中包含了方法 setUp() ,Python将先运行它,再运行各个以test_打头的方法。这样,在你编写的每个测试方法中都可使用在方法 setUp() 中创建的对象了。
  下面使用setUp()来创建一个调查对象和一组答案,供方法test_store_single_response()test_store_three_responses()使用:

import unittest
from survey import AnonymousSurvey

class TestAnonymousSurvey(unittest.TestCase):
    """Tests for the class AnonymousSurvey."""

    def setUp(self):
        """
        Create a survey and a set of responses for use in all test methods.
        """
        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):
        """Test that a single response is stored properly."""
        self.my_survey.store_response(self.responses[0])
        self.assertIn(self.responses[0], self.my_survey.responses)


    def test_store_three_responses(self):
        """Test that three individual responses are stored properly."""
        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(argv=['first-arg-is-ignored'], exit=False)

  
  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32

Ran 2 tests in 0.003s

OK

  • 1
  • 2
  • 3
  • 4
  • 5

  方法setUp()做了两件事情:创建一个调查对象;创建一个答案列表。存储这两样东西的变量名包含前缀self(即存储在属性中),因此可在这个类的任何地方使用。这让两个测试方法都更简单,因为它们都不用创建调查对象和答案。方法test_store_single_response()核 实 self.responses 中 的 第 一 个 答 案 ——self.responses[0]—— 被 妥 善 地 存 储 , 而 方 法test_store_three_response()核实self.responses中的全部三个答案都被妥善地存储。
  再次运行test_survey.py时,这两个测试也都通过了。如果要扩展AnonymousSurvey,使其允许每位用户输入多个答案,这些测试将很有用。修改代码以接受多个答案后,可运行这些测试,确认存储单个答案或一系列答案的行为未受影响。
  测试自己编写的类时,方法setUp()让测试方法编写起来更容易:可在setUp()方法中创建一系列实例并设置它们的属性,再在测试方法中直接使用这些实例。相比于在每个测试方法中都创建实例并设置其属性,这要容易得多。

注意
  运行测试用例时,每完成一个单元测试,Python都打印一个字符:测试通过时打印一个句点;测试引发错误时打印一个E;测试导致断言失败时打印一个F。这就是你运行测试用例时,在输出的第一行中看到的句点和字符数量各不相同的原因。如果测试用例包含很多单元测试,需要运行很长时间,就可通过观察这些结果来获悉有多少个测试通过了。

11-3 雇员:
  编写一个名为 Employee 的类,其方法__init__()接受名、姓和年薪,并将它们都存储在属性中。编写一个名为give_raise()的方法,它默认将年薪增加 5000美元,但也能够接受其他的年薪增加量。
  为 Employee 编写一个测试用例,其中包含两个测试方法:test_give_default_raise()test_give_custom_raise()。使用方法 setUp(),以免在每个测试方法中都创建新的雇员实例。运行这个测试用例,确认两个测试都通过了。

class Employee():
    def __init__(self,last_name, first_name, salary=10000 ):
        self.last_name = last_name
        self.first_name = first_name
        self.salary = salary

    def give_raise(self,added=5000):
        self.salary += added
        return added
  
  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
import unittest
from EmployeeFile import Employee

class TestEmployeeRaise(unittest.TestCase):

    def setUp(self):
        self.test1 = Employee('Tom', 'Smith')
        self.test2 = Employee('Tom', 'Smith',3000)


    def test_give_default_raise(self):
        self.salary1 = self.test1.give_raise()
        self.assertEqual(str(self.salary1), '5000')


    def test_give_custom_raise(self):
        self.salary2 = self.test2.give_raise(3000)
        self.assertEqual(str(self.salary2), '3000')


if __name__ == '__main__':
    unittest.main(argv=['first-arg-is-ignored'], exit=False)

  
  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23

Ran 2 tests in 0.003s

OK

  • 1
  • 2
  • 3
  • 4
  • 5

11.3 小结

  测试是很多初学者都不熟悉的主题。作为初学者,并非必须为你尝试的所有项目编写测试;但参与工作量较大的项目时,你应对自己编写的函数和类的重要行为进行测试。这样你就能够更加确定自己所做的工作不会破坏项目的其他部分,你就能够随心所欲地改进既有代码了。如果不小心破坏了原来的功能,你马上就会知道,从而能够轻松地修复问题。相比于等到不满意的用户报告bug后再采取措施,在测试未通过时采取措施要容易得多。
  如果你在项目中包含了初步测试,其他程序员将更敬佩你,他们将能够更得心应手地尝试使用你编写的代码,也更愿意与你合作开发项目。如果你要跟其他程序员开发的项目共享代码,就必须证明你编写的代码通过了既有测试,通常还需要为你添加的新行为编写测试。
  请通过多开展测试来熟悉代码测试过程。对于自己编写的函数和类,请编写针对其重要行为的测试,但在项目早期,不要试图去编写全覆盖的测试用例,除非有充分的理由这样做。

版权声明:本文为博主原创文章,非商用转载请保持署名-注明出处。 https://blog.csdn.net/adan_journal_of_data/article/details/77937477

11 测试代码

猜你喜欢

转载自blog.csdn.net/u014116780/article/details/83743874
今日推荐