Selenium入门04

接上一节,说一下Grid的用法

1、启动hub

set JAVA_HOME=C:\NeoLanguages\Java\JDK\jdk_x86_1.8.0_77
set PATH=%JAVA_HOME%\bin;%PATH%;C:\NeoTest\TestSelenium\trunk\bin\x86\;
set webdriver.gecko.driver=C:\NeoTest\TestSelenium\trunk\bin\x86\geckodriver.exe

java -jar ../lib/selenium-server-standalone-3.3.1.jar -role hub -hubConfig hubConfig.json -debug true

pause

hubConfig.json

{
  "port": 4444,
  "newSessionWaitTimeout": -1,
  "servlets" : [],
  "withoutServlets": [],
  "custom": {},
  "capabilityMatcher": "org.openqa.grid.internal.utils.DefaultCapabilityMatcher",
  "throwOnCapabilityNotPresent": true,
  "cleanUpCycle": 5000,
  "role": "hub",
  "debug": false,
  "browserTimeout": 0,
  "timeout": 1800
}

2、启动node

set JAVA_HOME=C:\NeoLanguages\Java\JDK\jdk_x86_1.8.0_77
set PATH=%JAVA_HOME%\bin;%PATH%;C:\NeoTest\TestSelenium\trunk\bin\x86\;
set webdriver.gecko.driver=C:\NeoTest\TestSelenium\trunk\bin\x86\geckodriver.exe

java -jar ../lib/selenium-server-standalone-3.3.1.jar -role node -nodeConfig node01Config.json -debug true

pause

node01Config.json

{
 "capabilities":
  [
    {
      "browserName": "firefox",
      "maxInstances": 5,
      "seleniumProtocol": "WebDriver"
    }
  ],
  "proxy": "org.openqa.grid.selenium.proxy.DefaultRemoteProxy",
  "maxSession": 5,
  "port": 5555,
  "register": true,
  "registerCycle": 5000,
  "hub": "http://192.168.130.178:4444",
  "nodeStatusCheckTimeout": 5000,
  "nodePolling": 5000,
  "role": "node",
  "unregisterIfStillDownAfter": 60000,
  "downPollingLimit": 2,
  "debug": false,
  "servlets" : [],
  "withoutServlets": [],
  "custom": {}
}

3、可以在hub中看到注册情况
http://localhost:4444/grid/console
这个地方一定要注意,每个node上的浏览器及操作系统信息,向hub发送指令时,必须符合该信息

4、运行脚本
TestHelloWorldHub.py

# !C:\Languages\Python\Python27\python.exe
# -*- coding: utf-8 -*-
'''
Created on 2016-10-22
@author: Hansen
HelloWorld sample for NeoSelenium
'''

from NeoSelenium import initEngine
from NeoSelenium import deInitEngine
from NeoSelenium import initEngineHub

#一个简单的查询测试
def neohope_search_test():
    try:
        #myEngine = initEngine('ie32')
        #myEngine = initEngine('ie64')
        #myEngine = initEngine('chrome')
        #myEngine = initEngine('ff32')
        #myEngine = initEngine('ff64')
        #myEngine = initEngineRemote()
	myEngine = initEngineHub()

        base_url = "https://www.neohope.com"
        myEngine.get(base_url + "/")
        myEngine.find_element_by_name("s").clear()
        myEngine.find_element_by_name("s").send_keys("Metabase")
        myEngine.find_element_by_css_selector("button.search-submit").click()
        myEngine.implicitly_wait(1000)
        #print(myEngine.find_elements_by_xpath("//div[@id='content']/article"))
        queryResultLenght = len(myEngine.find_elements_by_xpath("//div[@id='content']/article"))
        #print(queryResultLenght)
        #应该是1但现在是10
        assert queryResultLenght==1
    finally:
        #deInitEngine(myEngine)
        print("test end")

#start here
neohope_search_test()

NeoSelenium.py

#!C:\Languages\Python\Python27\python.exe
# -*- coding: utf-8 -*-
'''
Created on 2017-04-07
@author: Hansen
NeoSelenium
'''

import os
from selenium import webdriver
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities

NPath = None
x86Path = "C:\NeoTest\TestSelenium\\trunk\\bin\\x86;"
x64Path = "C:\NeoTest\TestSelenium\\trunk\\bin\\x64;"

'''
selenium remote engine init
'''
def initEngineRemote():
    engine = webdriver.Remote(command_executor="http://192.168.130.178:4444/wd/hub", desired_capabilities=DesiredCapabilities.FIREFOX)
    return engine

'''
selenium remote engine init
'''
def initEngineHub():
    engine = webdriver.Remote(command_executor="http://192.168.130.178:5555/wd/hub", desired_capabilities={
        "browserName": "firefox",
        "platform": "VISTA"
    })
    return engine   

'''
selenium engine deInit
'''
def deInitEngine(engine):
    engine.close()
    engine.quit()


Selenium入门03

接上一节,说一下如何进行远程测试

1、下载selenium-server-standalone的jar包
http://www.seleniumhq.org/download/

2、运行selenium-server-standalone

set JAVA_HOME=C:\NeoLanguages\Java\JDK\jdk_x86_1.8.0_77
set PATH=%JAVA_HOME%\bin;%PATH%;C:\NeoTest\TestSelenium\trunk\bin\x86\;
set webdriver.gecko.driver=C:\NeoTest\TestSelenium\trunk\bin\x86\geckodriver.exe

java -jar ../lib/selenium-server-standalone-3.3.1.jar -role standalone

pause

3、远程测试脚本
TestHelloWorldRemote.py

# !C:\Languages\Python\Python27\python.exe
# -*- coding: utf-8 -*-
'''
Created on 2016-10-22
@author: Hansen
HelloWorld sample for NeoSelenium
'''

from NeoSelenium import deInitEngine
from NeoSelenium import initEngineRemote

#一个简单的查询测试
def neohope_search_test():
    try:
        #myEngine = initEngine('ie32')
        #myEngine = initEngine('ie64')
        #myEngine = initEngine('chrome')
        #myEngine = initEngine('ff32')
        #myEngine = initEngine('ff64')
	myEngine = initEngineRemote()

        base_url = "https://www.neohope.com"
        myEngine.get(base_url + "/")
        myEngine.find_element_by_name("s").clear()
        myEngine.find_element_by_name("s").send_keys("Metabase")
        myEngine.find_element_by_css_selector("button.search-submit").click()
	myEngine.implicitly_wait(1000)
	#print(myEngine.find_elements_by_xpath("//div[@id='content']/article"))
	queryResultLenght = len(myEngine.find_elements_by_xpath("//div[@id='content']/article"))
	#print(queryResultLenght)
	#应该是1但现在是10
        assert queryResultLenght==1
    finally:
        #deInitEngine(myEngine)
	print("test end")

#start here
neohope_search_test()

NeoSelenium.py

#!C:\Languages\Python\Python27\python.exe
# -*- coding: utf-8 -*-
'''
Created on 2017-04-07
@author: Hansen
NeoSelenium
'''

import os
from selenium import webdriver
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities

NPath = None
x86Path = "C:\NeoTest\TestSelenium\\trunk\\bin\\x86;"
x64Path = "C:\NeoTest\TestSelenium\\trunk\\bin\\x64;"

'''
selenium remote engine init
'''
def initEngineRemote():
    engine = webdriver.Remote(command_executor="http://192.168.130.178:4444/wd/hub", desired_capabilities=DesiredCapabilities.FIREFOX)
    return engine

'''
selenium engine deInit
'''
def deInitEngine(engine):
    engine.close()
    engine.quit()

Selenium入门02

下面就说一下如何用Python进行自动化测试咯

1、安装语言包

pip install selenium

2、在selenium网站下载对应浏览器的driver
http://www.seleniumhq.org/download/

3、改一下我写的这个文件,将driver路径改成正确的路径
NeoSelenium.py

#!C:\Languages\Python\Python27\python.exe
# -*- coding: utf-8 -*-
'''
Created on 2017-04-07
@author: Hansen
NeoSelenium
'''

import os
from selenium import webdriver
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities

NPath = None
x86Path = "C:\NeoTest\TestSelenium\\trunk\\bin\\x86;"
x64Path = "C:\NeoTest\TestSelenium\\trunk\\bin\\x64;"

def initIE32():
    global x86Path
    global NPath
    os.environ["PATH"] = x86Path+NPath
    #print(os.environ["PATH"])
    engine = webdriver.Ie()
    return engine

def initIE64():
    global x64Path
    global NPath
    os.environ["PATH"] = x64Path+NPath
    #print(os.environ["PATH"])
    engine = webdriver.Ie()
    return engine

def initChrome32():
    global x86Path
    global NPath
    os.environ["PATH"] = x86Path+NPath
    engine = webdriver.Chrome()
    return engine

def initFirfox32():
    global x86Path
    global NPath
    os.environ["PATH"] = x86Path+NPath
    #print(os.environ["PATH"])
    engine = webdriver.Firefox()
    return engine

def initFirfox64():
    global x64Path
    global NPath
    os.environ["PATH"] = x64Path+NPath
    #print(os.environ["PATH"])
    engine = webdriver.Firefox()
    return engine

'''
selenium engine init
'''
def initEngine(engineType):
    global NPath
    if(NPath is None):
        NPath = os.environ["PATH"]
    if(cmp('IE32',engineType.upper())==0):
        return initIE32()
    elif(cmp('IE64',engineType.upper())==0):
        return initIE64()
    elif(cmp('CHROME',engineType.upper())==0 or cmp('CHROME32',engineType.upper())==0):
        return initChrome32()
    elif(cmp('FIREFOX',engineType.upper()) or cmp('FIREFOX32',engineType.upper()) or cmp('FF',engineType.upper())==0 or cmp('FF32',engineType.upper())==0):
        return initFirfox32()
    elif(cmp('FIREFOX64',engineType.upper()) or cmp('FF64',engineType.upper())==0):
        return initFirfox64()
    else:
        print("engin type: "+engineType.upper()+" not supported!")
        return None

'''
selenium remote engine init
'''
def initEngineRemote():
    engine = webdriver.Remote(command_executor="http://localhost:4444/wd/hub", desired_capabilities=DesiredCapabilities.FIREFOX)
    return engine
    

'''
selenium engine deInit
'''
def deInitEngine(engine):
    engine.close()
    engine.quit()

4、第一个自动化测试脚本
TestHelloWorld.py

# !C:\Languages\Python\Python27\python.exe
# -*- coding: utf-8 -*-
'''
Created on 2016-10-22
@author: Hansen
HelloWorld sample for NeoSelenium
'''

from NeoSelenium import initEngine
from NeoSelenium import deInitEngine

#一个简单的查询测试
def neohope_search_test():
    try:
        #myEngine = initEngine('ie32')
        #myEngine = initEngine('ie64')
        #myEngine = initEngine('chrome')
        myEngine = initEngine('ff32')
        #myEngine = initEngine('ff64')

        base_url = "https://www.neohope.com"
        myEngine.get(base_url + "/")
        myEngine.find_element_by_name("s").clear()
        myEngine.find_element_by_name("s").send_keys("Metabase")
        myEngine.find_element_by_css_selector("button.search-submit").click()
	myEngine.implicitly_wait(1000)
	#print(myEngine.find_elements_by_xpath("//div[@id='content']/article"))
	queryResultLenght = len(myEngine.find_elements_by_xpath("//div[@id='content']/article"))
	#print(queryResultLenght)
	#应该是1但现在是10
        assert queryResultLenght==1
    finally:
        #deInitEngine(myEngine)
	print("test end")

#start here
neohope_search_test()

5、运行脚本

PS:
IE驱动抛出异常解决方案

"Unexpected error launching Internet Explorer. Protected Mode settings are not the same for all zones. Enable Protected Mode must be set to the same value (enabled or disabled) for all zones."

解决方法:

     
打开IE->Internet options->Security->Enable Protected Mode
这个框,在四个域下面要是一致的(要么都勾上,要么都不勾上)

Selenium入门01

1、常用模块介绍

Selenium IDE 是一个FF插件,用于录制测试用例并重新运行。可以保持为html脚本,也可以导出为各种语言的单元测试
Selenium Html Runner 可以直接运行Selenium IDE导出的html脚本
Selenium Standalone Server 有三种运行模式(standalone、hub、node),后两种用于grid
Selenium Remote Control Selenium RC, Selenium1采用代理网站及JS注入的方式,达到操控网页的目的,在Selenium3已经取消支持
Browser Drivers Selenium2为在不修改网页的情况下,达到操控网页的无敌,利用了各种浏览器的API,达到操控浏览器的目的
Remote Web Drivers 远程运行测试(与Selenium Standalone Server或Selenium Standalone Hub进行交互时使用)
Selenium GRID 用于同时对多个操作系统的多种浏览器进行自动化测试(包括一个HUB,和多个NODE)
Language Binding 各种开发语言包

2、Selenium IDE
2.1、FF下载插件并重启
https://addons.mozilla.org/en-US/firefox/addon/selenium-ide/
2.2、录制插件

用FF打开你要测试的网站
打开Selenium IDE
Tools->Selenium IDE
输入BaseURL,点击右侧小红点儿,开始录制
在页面上进行操作(最好不要切换页面)

2.3、保存TestSuit及TestCase

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
  <meta content="text/html; charset=UTF-8" http-equiv="content-type" />
  <title>Test Suite</title>
</head>
<body>
<table id="suiteTable" cellpadding="1" cellspacing="1" border="1" class="selenium"><tbody>
<tr><td><b>Test Suite</b></td></tr>
<tr><td><a href="neohope.case.search.html">neohope_search_testcase001</a></td></tr>
</tbody></table>
</body>
</html>

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head profile="http://selenium-ide.openqa.org/profiles/test-case">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link rel="selenium.base" href="https://www.neohope.com/" />
<title>neohope_search_testcase001</title>
</head>
<body>
<table cellpadding="1" cellspacing="1" border="1">
<thead>
<tr><td rowspan="1" colspan="3">neohope_search_testcase001</td></tr>
</thead><tbody>
<tr>
	<td>open</td>
	<td>/</td>
	<td></td>
</tr>
<tr>
	<td>type</td>
	<td>name=s</td>
	<td>Metabase</td>
</tr>
<tr>
	<td>clickAndWait</td>
	<td>css=button.search-submit</td>
	<td></td>
</tr>
<tr>
	<td>assertXpathCount</td>
	<td>//article</td>
	<td>1</td>
</tr>

</tbody></table>
</body>
</html>

2.4、导出python脚本
Selenium IDE->File->Export Test Case As…->Python2/WebDriver

3、用selenium-html-runner运行
3.1、下载并配置jdk
3.2、下载selenium-html-runner-3.0.1.jar
3.3、在selenium网站下载对应浏览器的driver
http://www.seleniumhq.org/download/
3.4、运行

set JAVA_HOME=C:\NeoLanguages\Java\JDK\jdk_x86_1.8.0_77
set PATH=%JAVA_HOME%\bin;%PATH%;C:\NeoTest\TestSelenium\trunk\bin\x86\;
set webdriver.gecko.driver=C:\NeoTest\TestSelenium\trunk\bin\x86\geckodriver.exe

java -jar ../lib/selenium-html-runner-3.0.1.jar -htmlSuite *firefox "https://www.neohope.com/" "../testcases/neohope.suit" "../testcases/neohope.result"
PAUSE