自動化測試之 ddt 驅動 yaml/yml 文件

1、上篇文章咱們使用了 unittest + ddt 驅動 json 文件作數據驅動測試,本篇文章咱們採用 unittest + ddt 驅動 yaml/yml 文件來實現數據驅動測試,話很少說上源碼。。。json

  • ddt.file_data:裝飾測試方法,參數是文件名。文件能夠是 json 或者 yaml 類型。
    • 注意:若是文件是以 「.yml」或者".yaml" 結尾,ddt 會做爲 yaml 類型處理,其餘文件都會做爲 json 文件處理。  app

    • 若是文件是列表,列表的值會做爲測試用例參數,同時,會做爲測試用例方法名後綴顯示。    函數

    • 若是文件是字典,字典的 key 會做爲測試用例方法的後綴顯示,字典的 value 會做爲測試用例參數。  

2、安裝 yaml 模塊post

  • pip install pyyaml
  • 注意:安裝的包名爲 pyyaml,可是導入的是 yaml
  • yaml 文件能夠經過 open 函數來讀取,而後經過 load() 方法轉換成字典
  • 以下圖實例

import yaml

f = open("ddt_data.yaml", encoding="utf8")
print(yaml.load(f))
f.close()

# 運行結果以下
"""
[{
'url': 'http://cms.duoceshi.cn/xxx/xxxx/xxxxx', 
'method': 'post', 
'header': {'Content-Type': 'application/x-www-form-urlencoded'}, 
'params': {'userAccount': 'admin', 'loginPwd': 123456}
}]
"""
  • 以下圖爲個人數據文件,且文件中數據類型爲字典

import requests
import unittest
from ddt import ddt, file_data

@ddt
class CmsLogin(unittest.TestCase):

    @file_data("ddt_data.yaml")
    def testcase(self, method, url, header, params):
        res = requests.request(method, url, headers=header, data=params)
        print(res.text)

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

# 運行結果以下
"""
Ran 2 tests in 0.215s

..
{"code":"200","msg":"登陸成功!","model":{}}
{"code":"400","msg":"登陸賬號不存在!","model":{}}
----------------------------------------------------------------------
"""
  • 以下圖爲個人數據文件,且文件中數據類型爲列表

import yaml
from ddt import ddt, data, unpack

def get_yml_data(yml_file):
    with open(yml_file, encoding="utf8") as f:
        return yaml.load(f)

@ddt
class CmsLogin(unittest.TestCase):

    @data(*get_yml_data("ddt_data.yml"))
    @unpack
    def testcase(self, name, age):
        print(name + "----" + str(age))

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

# 運行結果以下
"""
Ran 3 tests in 0.000s

...
Evan----19
Lvan----20
Alex----21
"""
相關文章
相關標籤/搜索