import unittest
from ddt import *
def read_phohe():
"""
读取phone.txt文件中的电话号码数据
:return:返回一个手机号列表
"""
li = []
with open("phone.txt", "r", encoding="utf-8") as f:
for line in f.readlines():
li.append(line.strip("\n")) # strip()用于移除字符串头尾指定的字符
return li
@ddt
class TestCase(unittest.TestCase):
@data(*read_phohe())
def test_01(self, phone):
print("手机号为", phone)
# 测试是否能读取电话号码
@unittest.skip
def test_02(self):
li = read_phohe()
print(li)
if __name__ == '__main__':
unittest.main(verbosity=2)
当传的数据是通过变量的方式,如元组2、列表2,变量前需要加上
*
import unittest
from ddt import *
@ddt
class TestDemo1(unittest.TestCase):
@unittest.skip
def test_03(self):
res = read_userdata()
print(res) # [['admin', '123456'], ['sniper', '123456'], ['root', '123456']]
@data(*read_userdata())
@unpack
def test_04(self, username, password):
print(f"账号为:{
username},密码为:{
password}")
if __name__ == '__main__':
unittest.main(verbosity=2)
- 15912345678
- 17612345678
- 18512345678
from ddt import *
import unittest
@ddt
class TestRead(unittest.TestCase):
@file_data("phone.yaml")
def test_01(self, phone):
print("手机号为:", phone)
if __name__ == '__main__':
unittest.main(verbosity=2)
推荐使用这个方法定义数据
)-
username: admin
password: 123456
-
username: sniper
password: 123456
-
username: root
password: 666666
import unittest
from ddt import *
@ddt
class TestCall(unittest.TestCase):
# file_data在处理多个参数传递需求的时候,无法满足需求,就算加上unpack也不能自动解包
# 在yaml数据文件中采用对象的定义方式来定义数据内容
# 数据文件中的key和程序测试方法的入口参数必须同名
@file_data("userdata.yaml")
# @unpack
def test_02(self, username, password):
print("用户登录姓名和密码为:", username, password)
if __name__ == '__main__':
unittest.main(verbosity=2)
-
name: admin
pwd: 123456
-
name: root
pwd: 666666
import unittest
from ddt import *
@ddt
class TestCall(unittest.TestCase):
# 如果key和入口参数不一致
@file_data("userdata2.yaml")
def test_03(self, **userdata): # *传递列表类型可变参数;**传递字典类型可变参数
username = userdata["name"]
password = userdata["pwd"]
print("测试用户登陆流程:", userdata, type(userdata))
print(f"测试用户姓名为:{
username},密码为:{
password}")
if __name__ == '__main__':
unittest.main(verbosity=2)