一.问题背景
使用行为驱动开发框架Behave做自动化测试时,运行报错
D:\D1\code\AutoTest\python_ui_autotest\SeleniumPython\chapter7>behave
Feature: Register User # features/register.feature:2
As a developer
This is my first bdd project
Scenario: open register website # features/register.feature:7
When I open the register website # features/steps/register_user.py:6
Then I expect that the title is "注册" # None
成功: 已终止进程 "chromedriver.exe",其 PID 为 20012。
Failing scenarios:
features/register.feature:7 open register website
0 features passed, 1 failed, 0 skipped
0 scenarios passed, 1 failed, 0 skipped
1 step passed, 0 failed, 0 skipped, 1 undefined
Took 0m35.519s
You can implement step definitions for undefined steps with these snippets:
@then(u'I expect that the title is "注册"')
def step_impl(context):
raise NotImplementedError(u'STEP: Then I expect that the title is "注册"')
用自然语言描述的场景文件.feature文件:
#coding=utf-8
Feature: Register User
As a developer
This is my first bdd project
Scenario: open register website
When I open the register website
Then I expect that the title is "注册"
环境配置文件environment.py:
#coding=utf-8
from selenium import webdriver
import os
def before_all(context):
option = webdriver.ChromeOptions()
# 防止打印一些无用的日志
option.add_experimental_option("excludeSwitches", ['enable-automation', 'enable-logging'])
context.driver = webdriver.Chrome(chrome_options=option)
def after_all(context):
try:
os.system('taskkill /im chromedriver.exe /F')
except:
print("chrome driver进程不存在")
和.feature文件对应的描述行为的脚本文件register_user.py:
#coding=utf-8
from behave import *
use_step_matcher('re') #表示使用正则表达式
@when("I open the register website")
def method1(context):
context.driver.get("你的网址")
@then("I expect that the title is '([^']*)'") #表示匹配任意字符
def method2(context,expectTitle):
title = context.driver.title
print("expectTitle--->",expectTitle)
assert expectTitle in title
二.问题解决
1.刚开始怀疑是匹配中文的问题,于是
在.feature文件中把匹配关键词变为英文
再次运行还是报这个错:
Failing scenarios:
features/register.feature:7 open register website
0 features passed, 1 failed, 0 skipped
0 scenarios passed, 1 failed, 0 skipped
1 step passed, 0 failed, 0 skipped, 1 undefined
Took 0m19.100s
You can implement step definitions for undefined steps with these snippets:
@then(u'I expect that the title is "By"')
def step_impl(context):
raise NotImplementedError(u'STEP: Then I expect that the title is "By"')
2.由于是用正则表达式匹配,检查正则表达式:
@then("I expect that the title is '([^']*)'") #表示匹配任意字符
()表示分组,[^’] 表示匹配除了’之外的字符,*表示匹配0个或者多个
.feature文件是这样写的:
Then I expect that the title is "注册"
这也就解释了为什么会报 NotImplementedError
把正则表达式修改为:([^"]*)
即
@then('I expect that the title is "([^"]*)"') #表示匹配任意字符
3.再次运行成功了
成功: 已终止进程 "chromedriver.exe",其 PID 为 26656。
1 feature passed, 0 failed, 0 skipped
1 scenario passed, 0 failed, 0 skipped
2 steps passed, 0 failed, 0 skipped, 0 undefined
Took 0m11.026s