Unittest中传参过多优化方式(五)

玩技站长
玩技站长
管理员, Keymaster
11052
文章
0
粉丝
软件知识评论363字数 335阅读1分7秒阅读模式

此案例引入unittest数据驱动四 的例子,用例代码如下:

from ddt import ddt, file_data
from base.login_base import keyDemo
from time import sleep
import unittest


@ddt
class CassDemo(unittest.TestCase):
    def setUp(self, ) -> None:
        self.kd = keyDemo('Chrome')
        self.kd.maxwindow()

    def tearDown(self) -> None:
        self.kd.quite()

    @file_data('../data/search.yaml')
    def test_01(self, **kwargs):
        # self.kd = keyDemo('Chrome')
        self.kd.open(kwargs['url'])
        self.kd.input(**kwargs['input'])
        self.kd.click(**kwargs['click'])
        sleep(3)
        # self.kd.quite()


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

底层代码逻辑如下:(引入**kwargs字典的方式,将yaml文件中的input、click中的参数解析)文章源自玩技e族-https://www.playezu.com/26271.html

from selenium import webdriver
from time import sleep


# 基于type生成对应的浏览器对象
def browser(type_):
    try:
        driver = getattr(webdriver, type_)()
    except Exception as e:
        print(e)
        driver = webdriver.Chrome()
    return driver


class keyDemo:

    # driver = webdriver.Chrome()
    # 打开浏览器

    def __init__(self, type_):
        self.driver = browser(type_)

    def open(self, url):
        self.driver.get(url)

    def maxwindow(self):
        self.driver.maximize_window()

    # 定位元素
    def locator(self, name, value):
        return self.driver.find_element(name, value)

    # 输入值
    def input(self, **kwargs):
        self.locator(kwargs['name'], kwargs['value']).send_keys(kwargs['txt'])

    # 点击操作
    def click(self, **kwargs):
        self.locator(kwargs['name'], kwargs['value']).click()

    # 强制等待
    def sleep(self, time_to_wait):
        self.driver.implicitly_wait(time_to_wait)

    # 退出操作
    def quite(self):
        self.driver.quit()

数据源YAML文件如下:文章源自玩技e族-https://www.playezu.com/26271.html

-
  url: https://www.baidu.com
  input:
    name: id
    value: kw
    txt: 玩技e族
  click:
    name: id
    value: su
-
  url: https://www.jd.com
  input:
    name: id
    value: key
    txt: 玩技e族
  click:
    name: xpath
    value: //button[@class="button"]
文章源自玩技e族-https://www.playezu.com/26271.html文章源自玩技e族-https://www.playezu.com/26271.html
 最后更新:2022-8-22
匿名

发表评论

匿名网友
确定

拖动滑块以完成验证