【py code every day】2023-02-10 2nd

第十一章学习时,竟然意外发现本书已经做了第三版的更新。尤其是本章几乎完全更新了
第二版用的是unittest,但第三版用了pytest
而且更新了使用vs code的整体性
好机会,正好本章做个区分学习

In this chapter you’ll learn to test your code using tools in Python’s
unittest module.(2nd)

In this chapter, you’ll learn to test your code using pytest. The pytest
library is a collection of tools that will help you write your first tests quickly
and simply, while supporting your tests as they grow in complexity along
with your projects.(3rd)

为了测试下述两个代码的正误

#test.py
def get_formatted_name(first,last):
    #生成整洁的姓名
    full_name = f"{first} {last}"
    return full_name.title()

#homework.py
from test 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(f"\tNeatly formatted name: {formatted_name}.")

使用unittest

import unittest
from test import get_formatted_name

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

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

结论如下:

X:\Python\Python38\python.exe X:\python_work\test_name_function.py 
.
----------------------------------------------------------------------
Ran 1 test in 0.000s

OK

Process finished with exit code 0

首先,导入模块unittest和要测试的函数get_formatted_name(),创建一个名为 NamesTestCase的类,用户包含一系列针对get_formatted_name()的单元测试。这个Name的类可以随意取名,必须继承unittest.TestCase类
NamesTestCase只含一个方法,用户测试get_formatted_name的一个方面,其方法为test_first_last_name,测试姓和名是否被正常格式化
本例中,实参‘janis’和‘joplin’调用get_formatted_name,并将结果赋给变量formatted_name
接下来,使用unittest类最有用的功能之一:断言 方法
an assert method,断言核实 结果与期望的结果是否一致。
在此,使用assertEqual()来期望 formatted_name 的值与 ‘Janis Joplin’

self.assertEqual(formatted_name, 'Janis Joplin')

意思是:“将formatted_name 的值与字符串’Janis Joplin’比较。如果它们相等,那么万事大吉;如果它们不相等,就告诉我一声!”

接下来,if的代码块检查特殊变量__name__,这个变量是在程序执行时设置

if name == ‘main’: unittest.main()的意思就是:
当程序自己运行时,则调用当前程序中名字以“test”开头的函数
当程序被调用运行时,则不运行程序中名字以“test”开头的函数

这个变量是在程序执行时设置的。如果这个文件作为主程序执行,变量__name__ 将
被设置为’main’ 。在这里,调用unittest.main() 来运行
测试用例。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值