介紹feature, py文件和之間關系:
example01.feature文件包括5行: Feature行: 介紹這個feature用來干什么的; Scenario行:介紹這個scenario用來干什么的;Given: 一般數據的初始化在這里執行;When:執行操作;Then:驗證結果。
example01.py文件包括@given, @when, @then. 具體步驟實現在每一個對應的步驟里面實現。
接下來我們使用selenium來啟動firefox瀏覽器,做一些頁面上的操作和驗證。 --可以使用exclipse或者Notepad++工具來寫代碼
一、新建文件夾example02,在文件夾里面新建example02.feature文件:
#../feature/example02/example02.feature
Feature:Search behave results in baidu
Scenario: Search behave results in baidu
Given Access baidu website
When Input behave characters
Then There are more than 1 results displaying
二、在example02文件夾里面新建steps文件夾,然后創建example02.py文件:
# This Python file uses the following encoding: utf-8 #../feature/example02/steps/example02.py
from selenium import webdriver
import time
import sys
@Given('Access baidu website')
def step_impl(context):
reload(sys)
sys.setdefaultencoding('utf-8') #設置python的編碼方式為utf-8,它默認的是ACSII, 否則會報UnicodeDecodeError
context.driver = webdriver.Firefox()
context.driver.get("http://www.baidu.com")
@when('Input behave characters') def step_impl(context):
context.ele_input = context.driver.find_element_by_xpath("//input[@id = 'kw']")
context.ele_input.send_keys("behave")
context.ele_btn = context.driver.find_element_by_xpath("//input[@id = 'su']")
context.ele_btn.click() time.sleep(10)
@Then('There are more than 1 results displaying') def step_impl(context):
context.ele_results = context.driver.find_element_by_css_selector("div.nums")
context.expected_results = '相關結果'
if context.expected_results in context.ele_results.text:
assert True
else:
assert False
三、打開cmd,cd到example02.feature所在的路徑,然后輸入behave, 結果運行正常:
你會發現第一次我運行失敗,原因是沒有設置python的默認編碼方式。
問題解決:
- 當使用中文字符的時候,會出現 SyntaxError: Non-ASCII character '/xe6' 錯誤,這個時候,在python語句的第一行加上 # This Python file uses the following encoding: utf-8 或者 #encoding: utf-8 即可以解決這個問題。以下為參考網址:
http://blog.csdn.net/mayflowers/article/details/1568852
https://www.python.org/dev/peps/pep-0263/
- 出現 UnicodeDecodeError: 'ascii' codec can't decode byte 0xe7 in position 0: ordinal not in range(128):加入以下代碼進去,即可以解決問題。
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
如果轉載此篇文章,請標明轉載處來自T先生,謝謝!