[笔记]Selenium Testing Tools Cookbook_Chapter11

Chapter 11 Behavior-Driven Development

Using Behave and Selenium WebDriver in Python

install Behave using the following command:

pip install behave

folder stucture:

searchresult -- environment.py
             |
             -- features -- searchresult.feature
             |
             -- steps -- searchresult_steps.py

searchresult.feature:

Feature: User Search Key Words
    As a user,
    I want to search some words,
    and then get the amount of results

Scenario: Search abc
    Given the user is on Home Page
    When he enters abc as key words
    Then ensure the amount of results is 42029

Scenario: Search apple
    Given the user is on Home Page
    When he enters apple as key words
    Then ensure the amount of results is 55493

searchresult_steps.py:

from behave import *
from selenium import webdriver

@given('the user is on Home Page')
def step_user_is_on_home_page(context):
    #context.driver = webdriver.Firefox(executable_path='/usr/local/bin/geckodriver')
    #context.driver.implicitly_wait(30)
    #context.driver.maximize_window()
    context.driver.get("https://www.jianshu.com")

@when('he enters {words} as key words')
def step_he_enters_key_words(context,words):
    context.driver.find_element_by_name('q').send_keys(words)
    context.driver.find_element_by_class_name('search-btn').click()

@then('ensure the amount of results is {amount}')
def step_ensure_amount_of_result(context,amount):
    context.driver.switch_to.window(context.driver.window_handles[1])
    actual_amount = context.driver.find_element_by_class_name('result').text[0:5]
    print(str(actual_amount))
    print(str(amount))
    assert actual_amount == amount

environment.py:

from selenium import webdriver

def before_scenario(context,scenario):
    context.driver = webdriver.Firefox(executable_path='/usr/local/bin/geckodriver')
    context.driver.implicitly_wait(30)
    context.driver.maximize_window()

def after_scenario(context,scenario):
    context.driver.quit()

Run command:

behave

Special Instruction -- environment.py:

run before and after every step

before_step(context,step)
after_step(context,step)

run before and after every scenario

before_scenario(context,scenario)
after_scenario(context,scenario)

run before and after every feature

before_feature(context,feature)
after_feature(context,feature)

run before and after a section tagged with the given name

before_tag(context,tag)
after_tag(context,tag)

run before and after the whole shooting match

before_all(context)
after_all(context)

你可能感兴趣的:([笔记]Selenium Testing Tools Cookbook_Chapter11)