关于chromedriver和selenium(webdriver)的调研和修改(二)

      之前在(一)中,主要写的是如何满足当时的需求,来修改chromedriverh和之后的测试。按照之前的思路,我们并不需要使用chromedriver打开浏览器,只是创建session的时候,直接挂到已经启动的浏览器上,当然,这个启动的进程需要打开--remote-debugging-port的参数。由于代码不能公开,所以在(一)里并没有把如何使用的测试代码贴出来。之后自己重新写了一下,代码中不再有和项目相关的东西,可以用来讨论DIY的chromedriver的使用。

     首先需要重新描述一下上下文:我们现在需要对chrome进行GUI测试,这些已经基于msaa进行了封装,chrome的界面是支持的(关于msaachrome的自动化部分,请查询之前写的一些东西);在测试chrome的gui界面的同时,我们也需要测试一下页面的情况,这两个是相互独立的。由于要先启动chrome对其gui进行测试,所以后续需要用chromedriver挂到已经打开的chrome上,而不是启动新的session。因为我们重新对chromedriver进行了改造,init_session的时候禁止它启动chrome,并且定死了一个通信端口,具体的做法见()。

      对已经改造的chromedriver,使用的方法在(一)中已经提到,如下:

1、通过进程启动浏览器——启动命令需要指定port



2、启动chromedriver.exe进行,将port传入



3、通过selenium控制chromedriver.exe进行浏览器的各种操作



可以直接使用selenium操作chromedriver(推荐),也可以直接编写代码操作(不推荐)

      测试的代码,遵照这个思路,把操作gui的Chrome测试实例,和selenium&webdriver融合到了一起,进行操作。由于这里只介绍如何融合在一起,怎么对chrome的gui操作进行封装不具体讨论。详细的测试代码如下:

#!/usr/bin/env python

#coding: utf-8



from selenium.webdriver import *

import unittest

import subprocess

import time



from pychrome import PyChrome

import pylog



CHROME_PATH = r"chrome.exe"

DRIVER_PATH = r"chromedriver.exe" 



PORT_ID = 'myport'



STARTUP_CMD = r'--dom-automation=True --remote-debugging-port=' + PORT_ID



AUTO_INS = False

BR = None

DRIVER = None



TEST_URLS = (

             "http://www.baidu.com", 

             "http://www.163.com", 

             "http://www.youku.com", 

             "http://www.so.com"

             )



def _beforeSetUp():

    subprocess.Popen('taskkill /F /IM chrome.exe').wait()

    time.sleep(1)

    subprocess.Popen(CHROME_PATH + ' ' + STARTUP_CMD).pid

    time.sleep(2)

    subprocess.Popen(DRIVER_PATH).pid

    pass



def _afterTearDown():

        subprocess.Popen('taskkill /F /IM chrome.exe').wait()

        subprocess.Popen('taskkill /F /IM chromedriver.exe').wait()



def timeCount(func):

    def wrapper(*arg,**kwarg):

        pylog.log.info('-----------%s--------------'%func)

        start = time.clock()

        func(*arg,**kwarg)

        end =time.clock()

        pylog.log.info('used: %s seconds', end - start)

    return wrapper



class TestChromedriver(unittest.TestCase):

    @timeCount

    def test_00_SetUp(self):

        global AUTO_INS

        global BR

        global DRIVER

        if not AUTO_INS:

            time.sleep(1) 

            #setup chrome_options for specific path

            Options = ChromeOptions()

            Options.binary_location = CHROME_PATH

            Desiredcapabilities = DesiredCapabilities.CHROME

            #init chrome with option, driver and capability

            DRIVER = Chrome(chrome_options=Options, executable_path = DRIVER_PATH, port = 9515)

            self.assertTrue(DRIVER is not None, "ther's no driver instance")

            

            time.sleep(1)

            #create BR instance to hold gui

            BR = PyChrome()

            BR.open()

            time.sleep(1)

            self.assertTrue(DRIVER is not None, "driver's created")

        pass

    

    @timeCount

    def tearDown(self):

        pass

    

    @timeCount

    def test_01_SessionId(self):

        self.assertTrue(DRIVER.session_id is not None, "there's no session's created")

        pass

    

    @timeCount

    def test_02_WindowHandles(self):

        handles = DRIVER.window_handles

        self.assertTrue(len(handles) >= 0, "no window's handle")

    

    @timeCount

    def test_03_TabsByManual(self):

        self.assertTrue(DRIVER.current_window_handle is not None)

        DRIVER.get("http://www.baidu.com")

        map(lambda x: BR.open_tab(x), TEST_URLS)

        time.sleep(1)

        self.assertTrue(len(DRIVER.window_handles) > len(TEST_URLS), "invalid handles' number")

        pass

    

    @timeCount

    def test_04_SwitchWindows(self):

        handles = DRIVER.window_handles



        def _switch(x):

            try:

                DRIVER.switch_to_window(x)

                DRIVER.get('http://www.baidu.com')

                return True

            except Exception as e:

                return e

            

        _r = map(lambda x: _switch(x), handles)

        self.assertTrue(any(_r))

        pass

    

    @timeCount

    def test_05_NavigateTab(self):

        DRIVER.switch_to_window(DRIVER.window_handles[0])

        _url = DRIVER.current_url

        map(lambda x: DRIVER.get(x), TEST_URLS)

        try:

            map(lambda x: DRIVER.back(), TEST_URLS)

        except:

            pass

        DRIVER.forward()

        self.assertEqual(_url, DRIVER.current_url)

        

        _url = DRIVER.current_url

        try:

            map(lambda x: DRIVER.forward(), TEST_URLS)

        except:

            pass

        

        self.assertNotEqual(_url, DRIVER.current_url)

        pass

    

    @timeCount

    def test_06_JavaScript(self):

        _url = DRIVER.current_url

        

        script = "location.hash='test';return location.hash"

        pylog.log.info(DRIVER.execute_script(script))

        

        self.assertNotEqual(_url, DRIVER.current_url)

    

    @timeCount

    def test_07_Alert(self):

        _error = []

        _alert = None

        

        try:

            DRIVER.execute_script('alert(555)')

        except Exception as e:

            _error.append(str(e))

            

        try:

            _alert = DRIVER.switch_to_alert()

        except Exception as e:

            _error.append(str(e))

            

        if _alert:

            try:

                _alert.accept()

            except Exception as e:

                _error.append(str(e))

    

        self.assertTrue(_error is not None)

        pass

    

    @timeCount

    def test_08_Close(self):

        _handles = DRIVER.window_handles

        DRIVER.close()

        self.assertTrue(len(_handles) > len(DRIVER.window_handles))

    

    @timeCount

    def test_09_Quit(self):

        DRIVER.quit()



if __name__ == '__main__':

        _beforeSetUp()

        try:

            unittest.main()

        finally:

            _afterTearDown()

    

 

代码解释:

timeCount:一个测试执行时间的装饰器

pylog:自定义的日志输入类,用法和log一样

PyChrome:对chrome的GUI的msaa封装

unittest.TestCase:python提供的一个简单的单元测试框架,这里没有做其他的封装,直接使用

其他代码都属于python的基本使用,这里不做过多的解释。

你可能感兴趣的:(webdriver)