Python自动化测试系列[v1.0.0][多线程应用]

Python多线程应用于自动化测试

将多线程在测试巧妙地应用,确实会带来很多好处,并且这是充分利用机器资源执行高效率测试很好的方式

# -*- coding: utf-8 -*-
import threading
from time import ctime
import time
from selenium import webdriver


def test_search(browser, word):
    print("Start search at: %s\n" % ctime())
    print("Browser is: %s\n" % browser)
    if browser == 'ie':
        browser_driver = webdriver.Ie()
    elif browser == 'chrome':
        browser_driver = webdriver.Chrome()
    elif browser != 'ie' and browser != 'chrome':
        print("browser 参数非'ie 或 chrome'启动Fiefox")
        browser_driver = webdriver.Firefox()

    browser_driver.get("http://www.baidu.com")
    browser_driver.find_element_by_id("kw").send_keys(word)
    browser_driver.find_element_by_id("su").click()
    time.sleep(3)
    browser_driver.quit()


if __name__ == '__main__':
    dicts = {'chrome':'__davieyang__','ie':'davieyang','davieyang':'davieyang__'}
    threads = []
    for browser, word in dicts.items():
        t = threading.Thread(target = test_search, args=(browser, word))
        threads.append(t)
    for t in range(len(dicts)):
        threads[t].start()
    for t in range(len(dicts)):
        threads[t].join()
# -*- coding: utf-8 -*-
from selenium import webdriver
from time import sleep
from time import ctime
import multiprocessing


def start_browser(browser, time):
    if browser == "chrome":
        print("starting chrome browser now! %s" % ctime())  # 控制台打印当前时间 
        chrome_driver = webdriver.Chrome()
        chrome_driver.get("http://www.baidu.com")
        sleep(time)
        chrome_driver.quit()
    elif browser == "firefox":
        print("starting firefox browser now! %s" % ctime())  # 控制台打印当前时间
        fire_driver = webdriver.Firefox()
        fire_driver.get("http://www.baidu.com")
        sleep(time)
        fire_driver.quit()
    else: 
        print("starting ie browser now! %s" %ctime())  # 控制台打印当前时间
        ie_driver = webdriver.Ie()
        ie_driver.get("http://www.baidu.com")
        sleep(time)
        ie_driver.quit()


#  定义字典参数        
browser_dict = {"chrome": 3, "firefox": 4}
#  定义空List用于存储进程
start_browser_processing = []
#  循环字典Key-Value,创建进程并加入到List中
for browser, time in browser_dict.items():
    processing_browser = multiprocessing.Process(target = start_browser, args = (browser, time))
    start_browser_processing.append(processing_browser)

if __name__ == '__main__':
    for processing_browser in range(len(browser_dict)):
        start_browser_processing[processing_browser].start()
    for processing_browser in range(len(browser_dict)):
        start_browser_processing[processing_browser].join()
    print(u"全部结束 %s" % ctime())

你可能感兴趣的:(Python自动化测试系列[v1.0.0][多线程应用])