https://pytest-bdd.readthedocs.io/en/latest/#bdd-library-for-the-py-test-runner
BDD library for the py.test runner
pytest-bdd implements a subset of the Gherkin language to enable automating project requirements testing and to facilitate behavioral driven development.
pytest-bdd實現了Gherkin語言的子集,以實現自動化項目需求測試並促進行為驅動的開發。
Unlike many other BDD tools, it does not require a separate runner and benefits from the power and flexibility of pytest. It enables unifying unit and functional tests, reduces the burden of continuous integration server configuration and allows the reuse of test setups.
與許多其他BDD工具不同,它不需要單獨的運行程序,並且可以從pytest的功能和靈活性中受益。 它可以統一單元測試和功能測試,減輕連續集成服務器配置的負擔,並允許重用測試設置。
Pytest fixtures written for unit tests can be reused for setup and actions mentioned in feature steps with dependency injection. This allows a true BDD just-enough specification of the requirements without maintaining any context object containing the side effects of Gherkin imperative declarations.
為單元測試編寫的Pytest固定裝置可以通過依賴項注入重新用於功能步驟中提到的設置和操作。 這允許對需求進行真正的BDD正當說明,而無需維護任何包含Gherkin命令性聲明的副作用的上下文對象。
Install pytest-bdd
pip install pytest-bdd
Example
Feature: stage 01 This is a test
Scenario: This is a test sample
Given I have a book and its name is learn
And I have finished 20 pages
When I begin to read the 21 page
And I read 10 pages
Then I verify the next time I should read from Page 31
Given 是前置條件, previous condition
when 是進行的操作,steps to do
then 是進行驗證, 期望值
但是並不是一個簡單的方法來進行驗證,尤其在UI自動化的時候,頁面本身能不能點,能不能跳轉,元素在不在,既是進行的操作,本身也是驗證
以下是每一個step,這些方法沒有具體實現,只是進行了打印。
from time import sleep import pytest from pytest_bdd import when, then, parsers from pytest_bdd import scenario, given ############### # STEPS # ############### @given('I have a book and its name is learn') def step_click_my_audience_page(): print('I have a book and its name is learn') @given('I have finished 20 pages') def book_page_i_have_a_book(): print("hello yes i have a book and its name is {}".format("book")) @when('I begin to read the 21 page') def book_i(): print('I begin to read the 21 page') @when('I read 10 pages') def book_2(): print('I read 10 pages') @then('I verify the next time I should read from Page 31') def book333(): print('I verify the next time I should read from Page 31') @given(parsers.cfparse('case {num}')) def book_seq(num): print('Hello there,I am reading book page {}'.format(num))