Selenium 并发执行测试

1、多线程执行测试用例

这里以百度搜索为例,通过不同的浏览器来启动不同的线程。

from threading import Thread
from selenium import webdriver
from time import ctime,sleep

#测试用例
def test_baidu(browser,search):
    print('start: {0}'.format(ctime()))
    print('browser: {0}'.format(browser))
    if browser == "ie":
        driver =  webdriver.IE()
    elif browser == "chrome":
        driver = webdriver.Chrome()
    elif browser == "ff":
        driver = webdriver.Firefox()
    else:
        print("browser参数有误,只能为 ie、ff、chrome")

    driver.get("http://www.baidu.com")
    driver.find_element_by_id("kw").send_keys(search)
    driver.find_element_by_id("su").click()
    sleep(2)
    driver.quit()

if __name__=="__main__":
    lists = {'chrome':'C++','ie':'JAVA','ff':'python'}
    threads = []
    files = range(len(lists))

    #创建线程
    for browser,search in lists.items():
        t = Thread(target=test_baidu,args=(browser,search))
        threads.append(t)
    #启动线程
    for t in files:
        threads[t].start()
    for t in files:
        threads[t].join()

2、多进程执行测试用例

from multiprocessing import Pool
from selenium import webdriver
from time import sleep

#测试用例
def test_baidu(browser,search):
if browser == "ie":
driver = webdriver.Ie()
elif browser == "chrome":
driver = webdriver.Chrome()
elif browser == "ff":
driver = webdriver.Firefox()
else:
print("browser参数有误,只能为 ie、ff、chrome")

driver.get("http://www.baidu.com")
driver.find_element_by_id("kw").send_keys(search)
driver.find_element_by_id("su").click()
sleep(2)
driver.quit()

if __name__=="__main__":
lists = {'chrome':'C++','ie':'JAVA','ff':'python'}
p = Pool(3)

#创建进程
for browser,search in lists.items():
p.apply_async(test_baidu,args=(browser,search))

p.close()
p.join()

3、多线程分布式执行测试用例

Selenium Grid本身不提供并发执行用例,只是提供多系统、多浏览器执行环境,鉴于并发执行需要用到多线程技术结合Grid来实现分布式并发执行测试用例。

from threading import Thread
from selenium import webdriver
from time import sleep

#测试用例
def test_baidu(host,browser):
    dc = {'browserName':browser}
    driver = webdriver.Remote(command_executor=host,
                              desired_capabilities=dc)
    driver.get("http://www.baidu.com")
    driver.find_element_by_id("kw").send_keys('test')
    driver.find_element_by_id("su").click()
    sleep(2)
    driver.quit()

if __name__=="__main__":
    #启动参数(指定运行主机与浏览器)
    lists = {'http://10.1.29.21:5555/wd/hub':'chrome',
             'http://192.168.17.171:6666/wd/hub': 'internet explorer',
             'http://10.1.29.21:5557/wd/hub': 'firefox'}
    threads = []
    files = range(len(lists))

    #创建线程
    for host,browser in lists.items():
        t = Thread(target=test_baidu,args=(host,browser))
        threads.append(t)
    #启动线程
    for t in files:
        threads[t].start()
    for t in files:
        threads[t].join()

 

posted @ 2020-10-27 19:46  Water_you  阅读(1066)  评论(0编辑  收藏  举报