Selenium3自动化测试——22.使用DDT运行同一测试用例

有时,我们需要使用不同数据对同一测试用例进行检验,这时需要用到DDT。

1)安装

pip install ddt

2)以百度搜索为例,确定DDT的用法

import unittest
from time import sleep
from selenium import webdriver
from ddt import ddt, data, file_data, unpack


@ddt
class TestBaidu(unittest.TestCase):
    @classmethod
    def setUpClass(cls):
        cls.driver = webdriver.Chrome()
        cls.base_url = "https://www.baidu.com"

    def baidu_search(self, search_key):
        self.driver.get(self.base_url)
        self.driver.find_element_by_id("kw").send_keys(search_key)
        self.driver.find_element_by_id("su").click()
        sleep(3)

    # 参数化使用方法一列表
    @data(["case1", "selenium"], ["case2", "ddt"], ["case3", "python"])
    @unpack
    def test_search1(self, case, search_kay):
        print("第一组测试用例:", case)
        self.baidu_search(search_kay)
        self.assertEqual(self.driver.title, search_kay + "_百度搜索")

    # 参数化使用方法二元祖
    @data(("case1", "selenium"), ("case2", "ddt"), ("case3", "python"))
    @unpack
    def test_search2(self, case, search_kay):
        print("第二组测试用例:", case)
        self.baidu_search(search_kay)
        self.assertEqual(self.driver.title, search_kay + "_百度搜索")

    # 参数化使用方法三
    @data({"search_kay": "selenium"}, {"search_kay": "ddt"}, {"search_kay": "python"})
    @unpack
    def test_search3(self, search_kay):
        print("第三组测试用例:", search_kay)
        self.baidu_search(search_kay)
        self.assertEqual(self.driver.title, search_kay + "_百度搜索")

    # 参数化读取JSON文件
    @file_data('ddt_data_file.json')
    def test_search4(self, search_key):
        print("第四组测试用例:", search_key)
        self.baidu_search(search_key)
        self.assertEqual(self.driver.title, search_key + "_百度搜索")

    @classmethod
    def tearDownClass(cls):
        cls.driver.quit()


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

首先,通过@ddt装饰器来进行装饰

其次,DDT提供了不同形式的参数化。对列表,元组,字典,json数据都可以进行参数化。

结果显示:

test_search1_1___case1____selenium__ (__main__.TestBaidu) ... 第一组测试用例: case1
ok
第一组测试用例: case2
test_search1_2___case2____ddt__ (__main__.TestBaidu) ... ok
第一组测试用例: case3
test_search1_3___case3____python__ (__main__.TestBaidu) ... ok
第二组测试用例: case1
test_search2_1___case1____selenium__ (__main__.TestBaidu) ... ok
第二组测试用例: case2
test_search2_2___case2____ddt__ (__main__.TestBaidu) ... 第二组测试用例: case3
ok
test_search2_3___case3____python__ (__main__.TestBaidu) ... ok
第三组测试用例: selenium
test_search3_1 (__main__.TestBaidu) ... ok
第三组测试用例: ddt
test_search3_2 (__main__.TestBaidu) ... ok
第三组测试用例: python
test_search3_3 (__main__.TestBaidu) ... 第四组测试用例: python
ok
test_search4_1_case1 (__main__.TestBaidu)
test_search4_1_case1 ... 第四组测试用例: ddt
ok
test_search4_2_case2 (__main__.TestBaidu)
test_search4_2_case2 ... ok
第四组测试用例: Selenium
test_search4_3_case3 (__main__.TestBaidu)
test_search4_3_case3 ... ok

----------------------------------------------------------------------
Ran 12 tests in 102.513s

OK

Process finished with exit code 0

 

你可能感兴趣的:(Selenium自动化测试)