### Install Behave from Source Distribution Source: https://github.com/arqawa/behave/blob/main/docs/install.rst Installs behave by building from its source distribution. After unpacking the source archive, navigate to the behave directory and run the setup script. ```bash python setup.py install ``` -------------------------------- ### Install Behave using easy_install Source: https://github.com/arqawa/behave/blob/main/docs/install.rst Installs or upgrades behave using the easy_install command from setuptools. This method is an alternative to pip. The -U flag is used for upgrading. ```bash easy_install behave ``` ```bash easy_install -U behave ``` -------------------------------- ### Install Behave from GitHub Repository Source: https://github.com/arqawa/behave/blob/main/docs/install.rst Installs the latest development version of behave directly from its GitHub repository using pip. This allows installation of the bleeding-edge version. You can also install a specific tagged version. ```bash pip install git+https://github.com/behave/behave ``` ```bash pip install git+https://github.com/behave/behave@ ``` -------------------------------- ### Behave: Logging Setup in Environment Hooks (Python) Source: https://github.com/arqawa/behave/blob/main/docs/api.rst Provides examples for setting up logging within Behave's 'environment.py' file using the 'setup_logging' configuration. It shows how to configure logging directly via the command line or by referencing an external configuration file. ```python # -- FILE:features/environment.py def before_all(context): # -- SET LOG LEVEL: behave --logging-level=ERROR ... # on behave command-line or in "behave.ini". context.config.setup_logging() # -- ALTERNATIVE: Setup logging with a configuration file. # context.config.setup_logging(configfile="behave_logging.ini") ``` -------------------------------- ### Define and Use Fixtures for Setup and Cleanup in Behave Source: https://context7.com/arqawa/behave/llms.txt This snippet illustrates how to define and use fixtures in Behave for managing setup and cleanup tasks. It shows two fixture examples: one for setting up a Selenium WebDriver instance ('browser_firefox') using a generator function for automatic cleanup, and another for database connections ('database.connection') using context.add_cleanup. The 'before_tag' hook demonstrates how to activate these fixtures based on tags. ```python # -- FILE: features/environment.py from behave import fixture, use_fixture @fixture def browser_firefox(context, timeout=30): """Setup browser fixture with automatic cleanup""" from selenium import webdriver context.browser = webdriver.Firefox() context.browser.implicitly_wait(timeout) yield context.browser context.browser.quit() @fixture(name="database.connection") def database_fixture(context, db_name): """Setup database with explicit cleanup registration""" import sqlite3 context.db = sqlite3.connect(db_name) context.add_cleanup(context.db.close) return context.db def before_tag(context, tag): if tag == "fixture.browser.firefox": use_fixture(browser_firefox, context, timeout=10) elif tag.startswith("fixture.database"): db_name = tag.replace("fixture.database.", "") + ".db" use_fixture(database_fixture, context, db_name) ``` -------------------------------- ### Install Behave using pip Source: https://github.com/arqawa/behave/blob/main/docs/install.rst Installs the latest stable version of behave using the pip package manager. This is the recommended method for most users. To update an existing installation, use the -U flag. ```bash pip install behave ``` ```bash pip install -U behave ``` -------------------------------- ### Splinter Browser Fixture Setup with Behave Source: https://github.com/arqawa/behave/blob/main/docs/practical_tips.rst Sets up a browser fixture using Splinter for front-end testing within Behave. Similar to the Selenium example, this fixture is defined in `environment.py` and provides a browser instance via `context.browser`. It handles browser initialization and quitting. ```python # -- FILE: features/environment.py # CONTAINS: Browser fixture setup and teardown from behave import fixture, use_fixture from splinter.browser import Browser @fixture def splinter_browser(context): context.browser = Browser() yield context.browser context.browser.quit() def before_all(context): use_fixture(splinter_browser, context) ``` -------------------------------- ### Behave Composite Fixture with use_composite_fixture_with Source: https://github.com/arqawa/behave/blob/main/docs/fixtures.rst This example demonstrates an alternative way to create composite fixtures using `use_composite_fixture_with`. This method is more concise as it allows defining multiple fixtures with their parameters in a single call, simplifying the setup and cleanup process. ```python from behave import fixture from behave.fixture import use_composite_fixture_with, fixture_call_params @fixture def composite2(context, *args, **kwargs): the_composite = use_composite_fixture_with(context, [ fixture_call_params(foo, name="foo"), fixture_call_params(bar, name="bar"), ]) return the_composite ``` -------------------------------- ### Conditional Environment Setup Based on Feature Tags Source: https://github.com/arqawa/behave/blob/main/docs/tutorial.rst Shows how to conditionally execute setup logic within Behave's `before_feature` hook based on the presence of specific tags on the feature. This allows for dynamic environment configuration, such as only initializing a browser if the feature is tagged with `@browser`. ```python # -- FILE: features/environment.py # HINT: Reusing some code parts from above. ... def before_feature(context, feature): model.init(environment='test') if 'browser' in feature.tags: # Logic to initialize browser if feature has @browser tag ``` -------------------------------- ### Gherkin Scenario Outline with Examples Source: https://github.com/arqawa/behave/blob/main/docs/tutorial.rst Demonstrates the use of Scenario Outlines in Gherkin to run the same scenario with different sets of data. The in the scenario are replaced by values from the 'Examples' tables, allowing for efficient testing of multiple cases. ```gherkin Scenario Outline: Blenders Given I put in a blender, when I switch the blender on then it should transform into Examples: Amphibians | thing | other thing | | Red Tree Frog | mush | Examples: Consumer Electronics | thing | other thing | | iPhone | toxic waste | | Galaxy Nexus | toxic waste | ``` -------------------------------- ### Python Fixture Definition Example Source: https://github.com/arqawa/behave/blob/main/docs/new_and_noteworthy_v1.2.6.rst Shows how to define a reusable fixture in Python for Behave. This example uses a generator function decorated with `@fixture` to handle setup (e.g., initializing a browser) and cleanup (e.g., shutting down the browser). ```python # -- FILE: behave4my_project/fixtures.py (or in: features/environment.py) from behave import fixture from somewhere.browser.firefox import FirefoxBrowser # -- FIXTURE-VARIANT 1: Use generator-function @fixture def browser_firefox(context, timeout=30, **kwargs): # -- SETUP-FIXTURE PART: context.browser = FirefoxBrowser(timeout, **kwargs) yield context.browser # -- CLEANUP-FIXTURE PART: context.browser.shutdown() ``` -------------------------------- ### Gherkin: Tagged Examples with Active Tags and Userdata Source: https://github.com/arqawa/behave/blob/main/docs/new_and_noteworthy_v1.2.6.rst Illustrates a more advanced usage of tagged examples by combining them with active tags and userdata. Tags like '@use.with_stage=develop' allow dynamic selection of example sets based on environment variables or configuration, making tests more adaptable. ```gherkin # -- FILE: features/tagged_examples2.feature # VARIANT 2: With active tags and userdata. Feature: Scenario Outline: Wow Given an employee "" @use.with_stage=develop Examples: Araxas | name | birthyear | | Alice | 1985 | | Bob | 1975 | @use.with_stage=integration Examples: | name | birthyear | | Charly | 1995 | ``` -------------------------------- ### Shell: Running Examples Using Userdata or Stage Mechanism Source: https://github.com/arqawa/behave/blob/main/docs/new_and_noteworthy_v1.2.6.rst Provides shell commands to select 'Examples' sections in a 'Scenario Outline' using either userdata or a dedicated stage mechanism. This allows runtime configuration to determine which set of example data should be used for testing. ```shell # -- VARIANT 1: Use userdata behave -D stage=integration features/tagged_examples2.feature # -- VARIANT 2: Use stage mechanism behave --stage=integration features/tagged_examples2.feature ``` -------------------------------- ### Behave Step Implementation for Visiting URL with Splinter Source: https://github.com/arqawa/behave/blob/main/docs/practical_tips.rst An example step implementation in Behave that uses the `context.browser` object (assuming it's a Splinter Browser instance) to visit a specified URL. This step complements the Splinter fixture setup in `environment.py`. ```python # -- FILE: features/steps/browser_steps.py from behave import given, when, then @when(u'I visit "{url}"') def step_impl(context, url): context.browser.visit(context.get_url(url)) ``` -------------------------------- ### Behave Composite Fixture with use_fixture Source: https://github.com/arqawa/behave/blob/main/docs/fixtures.rst This example shows how to create a composite fixture using the `use_fixture` function. It ensures that both `foo` and `bar` fixtures are cleaned up, even if errors occur after their setup. This approach requires manually calling each fixture. ```python from behave import fixture @fixture def composite1(context, *args, **kwargs): the_fixture1 = use_fixture(foo, context) the_fixture2 = use_fixture(bar, context) return [the_fixture1, the_fixture2] ``` -------------------------------- ### Setup Web Server and Chrome Browser Fixtures in Behave Source: https://github.com/arqawa/behave/blob/main/docs/tutorial.rst Defines fixtures for setting up a WSGI server and a Selenium Chrome browser. The `wsgi_server` fixture starts a server in a separate thread and shuts it down afterward. The `selenium_browser_chrome` fixture initializes a Chrome WebDriver instance and quits it upon completion. These are commonly used in `environment.py` for test setup. ```python # -- FILE: features/environment.py from behave import fixture, use_fixture from behave4my_project.fixtures import wsgi_server from selenium import webdriver @fixture def selenium_browser_chrome(context): # -- HINT: @behave.fixture is similar to @contextlib.contextmanager context.browser = webdriver.Chrome() yield context.browser # -- CLEANUP-FIXTURE PART: context.browser.quit() def before_all(context): use_fixture(wsgi_server, context, port=8000) use_fixture(selenium_browser_chrome, context) # -- HINT: CLEANUP-FIXTURE is performed after after_all() hook is called. def before_feature(context, feature): model.init(environment='test') ``` ```python # -- FILE: behave4my_project/fixtures.py # ALTERNATIVE: Place fixture in "features/environment.py" (but reuse is harder) from behave import fixture import threading from wsgiref import simple_server from my_application import model from my_application import web_app @fixture def wsgi_server(context, port=8000): context.server = simple_server.WSGIServer(('', port)) context.server.set_app(web_app.main(environment='test')) context.thread = threading.Thread(target=context.server.serve_forever) context.thread.start() yield context.server # -- CLEANUP-FIXTURE PART: context.server.shutdown() context.thread.join() ``` -------------------------------- ### Behave Configuration File Example (INI) Source: https://github.com/arqawa/behave/blob/main/docs/behave.rst Demonstrates the basic structure and format of a Behave configuration file. Configuration files allow for persistent settings that can override command-line arguments or provide default behaviors. ```ini [behave] format=plain logging_clear_handlers=yes logging_filter=-suds ``` -------------------------------- ### Behave Feature File Examples in Gherkin Source: https://context7.com/arqawa/behave/llms.txt Example feature files written in Gherkin syntax, demonstrating basic scenarios, background setup, data tables, multiline text blocks, and scenario outlines with examples. These files define the test cases for behave. ```gherkin # -- FILE: features/example.feature Feature: Showing off behave As a developer I want to use behave for BDD So that I can write maintainable tests Background: Given the system is initialized And the database is clean @smoke @critical Scenario: Run a simple test Given we have behave installed When we implement 5 tests Then behave will test them for us! Scenario: Using tables for test data Given I have the following users: | username | email | role | | alice | alice@example.com | admin | | bob | bob@example.com | user | When I process all users Then each user should be validated Scenario: Using multiline text Given I have the following JSON data: """ { "name": "Test User", "age": 30, "active": true } """ When I parse the JSON Then the data should be valid @fixture.browser.firefox Scenario Outline: Login with different credentials Given I am on the login page When I enter username "" and password "" Then I should see "" Examples: Valid credentials | username | password | result | | alice | secret123 | Welcome | | bob | pass456 | Welcome | Examples: Invalid credentials | username | password | result | | invalid | wrong | Login failed | | "" | "" | Please login | ``` -------------------------------- ### Visual Testing with Selenium using Applitools Source: https://github.com/arqawa/behave/blob/main/docs/practical_tips.rst This snippet demonstrates how to integrate Applitools Eyes for visual testing into a Selenium WebDriver setup. It requires the Applitools SDK and a running Selenium instance. The code typically involves initializing the Eyes SDK, starting a test, capturing screenshots, and comparing them against baseline images. ```java import com.applitools.eyes.*; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; public class SeleniumVisualTest { public static void main(String[] args) { // Set the path to your chromedriver executable System.setProperty("webdriver.chrome.driver", "/path/to/chromedriver"); WebDriver driver = new ChromeDriver(); Eyes eyes = new Eyes(); // Set your Applitools API key eyes.setApiKey("YOUR_APPLITOOLS_API_KEY"); try { // Start the test eyes.open(driver, "My Selenium App", "Login Page Test"); // Navigate to the page driver.get("https://applitools.github.io/demo/TestSG/"); // Perform visual validation eyes.checkWindow("Login Page"); // Close the test eyes.closeAsync(); } catch (Exception e) { e.printStackTrace(); eyes.abortAsync(); } finally { // Quit the driver driver.quit(); } } } ``` -------------------------------- ### Gherkin: Tagged Examples in Scenario Outline Source: https://github.com/arqawa/behave/blob/main/docs/new_and_noteworthy_v1.2.6.rst Demonstrates how to use tags with the 'Examples' section in a 'Scenario Outline' to provide multiple sets of example data. This allows for selective execution based on tags, such as testing stages (development, integration, system). The generated scenarios inherit tags from both the ScenarioOutline and its Examples section. ```gherkin # -- FILE: features/tagged_examples.feature Feature: Scenario Outline: Wow Given an employee "" @develop Examples: Araxas | name | birthyear | | Alice | 1985 | | Bob | 1975 | @integration Examples: | name | birthyear | | Charly | 1995 | ``` -------------------------------- ### Behave Configuration: Sequence Type Example Source: https://github.com/arqawa/behave/blob/main/docs/behave.rst Shows how to define sequence-based configuration parameters, such as tag expressions, within a Behave configuration file. This allows for multi-line definitions of parameters that accept multiple values. ```ini tags=@foo,~@bar @zap ``` -------------------------------- ### Selenium Browser Fixture Setup with Behave Source: https://github.com/arqawa/behave/blob/main/docs/practical_tips.rst Sets up a Firefox browser fixture using Selenium for front-end testing within Behave. The fixture is defined in `environment.py` and makes the browser instance available via `context.browser` for step implementations. It includes setup and teardown logic. ```python # -- FILE: features/environment.py # CONTAINS: Browser fixture setup and teardown from behave import fixture, use_fixture from selenium.webdriver import Firefox @fixture def browser_firefox(context): # -- BEHAVE-FIXTURE: Similar to @contextlib.contextmanager context.browser = Firefox() yield context.browser # -- CLEANUP-FIXTURE PART: context.browser.quit() def before_all(context): use_fixture(browser_firefox, context) # -- NOTE: CLEANUP-FIXTURE is called after after_all() hook. ``` -------------------------------- ### Gherkin Feature File Using a Fixture Source: https://github.com/arqawa/behave/blob/main/docs/new_and_noteworthy_v1.2.6.rst An example Gherkin feature file that demonstrates how to utilize a defined fixture at the scenario level. This simplifies the setup and teardown process for tests that require specific resources or configurations. ```gherkin # -- FILE: features/use_fixture1.feature Feature: Use Fixture on Scenario Level ``` -------------------------------- ### Gherkin Feature File Example Source: https://github.com/arqawa/behave/blob/main/docs/tutorial.rst Demonstrates the basic structure of a Gherkin feature file, including the Feature, Scenario, Given, When, and Then keywords. This format is used to describe system behavior in a human-readable way. ```gherkin Feature: showing off behave Scenario: run a simple test Given we have behave installed When we implement a test Then behave will test it for us! ``` -------------------------------- ### Execute invoke.zip from Python Source: https://github.com/arqawa/behave/blob/main/tasks/_vendor/README.rst Demonstrates how to execute the 'invoke.zip' archive using the Python interpreter. This is useful when the 'invoke' package is not installed system-wide. It shows basic commands like '--help' and '--version'. ```shell python -m tasks/_vendor/invoke.zip --help python -m tasks/_vendor/invoke.zip --version ``` -------------------------------- ### Python - Step Implementation Example Source: https://github.com/arqawa/behave/blob/main/docs/gherkin.rst Provides an example of how behave step definitions are implemented in Python. Steps defined in gherkin files are linked to Python functions, typically located in the 'steps' directory. The function signatures often include arguments for captured values from the step text. ```python from behave import * @given('we are looking at the home page') def step_impl(context): pass @when('I open my eyes') def step_impl(context): pass @then('I see something') def step_impl(context): pass @then('I don't see something else') def step_impl(context): pass ``` -------------------------------- ### Gherkin Feature File Example for Behave Source: https://github.com/arqawa/behave/blob/main/README.rst This Gherkin feature file defines a scenario to demonstrate behave's functionality. It outlines the steps 'Given we have behave installed', 'When we implement 5 tests', and 'Then behave will test them for us!'. ```gherkin # -- FILE: features/example.feature Feature: Showing off behave Scenario: Run a simple test Given we have behave installed When we implement 5 tests Then behave will test them for us! ``` -------------------------------- ### Behave Scenario Outline with Examples Source: https://github.com/arqawa/behave/blob/main/docs/gherkin.rst Shows how to use Scenario Outlines in Behave for parameterized tests. It defines a template scenario with placeholders (, ) that are filled in by the data provided in the Examples table. This reduces redundancy when testing variations of the same scenario. ```gherkin Scenario Outline: Blenders Given I put in a blender, when I switch the blender on then it should transform into Examples: Amphibians | thing | other thing | | a frog | a ‘blended’ frog | | a lime | a ‘blended’ lime | ``` -------------------------------- ### gherkin - Example Data Table Substitution Source: https://github.com/arqawa/behave/blob/main/docs/gherkin.rst Demonstrates how behave uses example data tables in gherkin scenarios for substitution. Values from table rows replace placeholders like '' in steps and step data. This allows running a scenario multiple times with different data. ```gherkin Examples: Consumer Electronics | thing | other thing | | iPhone | toxic waste | | Galaxy Nexus | toxic waste | ``` -------------------------------- ### Accessing Step Data: Text Block Example Source: https://github.com/arqawa/behave/blob/main/docs/tutorial.rst Demonstrates how to associate a multi-line text block with a step and access it via context.text in Python. ```gherkin Scenario: some scenario Given a sample text loaded into the frobulator """ Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. """ When we activate the frobulator Then we will find it similar to English ``` -------------------------------- ### Behave Step Implementation for Visiting URL with Selenium Source: https://github.com/arqawa/behave/blob/main/docs/practical_tips.rst An example step implementation in Behave that uses the `context.browser` object (assuming it's a Selenium WebDriver instance) to navigate to a specified URL. This step is typically used in conjunction with the Selenium fixture setup. ```python # -- FILE: features/steps/browser_steps.py from behave import given, when, then @when(u'I visit "{url}"') def step_impl(context, url): context.browser.get(context.get_url(url)) ``` -------------------------------- ### Shell: Running Gherkin Scenarios with Tags Source: https://github.com/arqawa/behave/blob/main/docs/new_and_noteworthy_v1.2.6.rst Shows how to execute specific 'Examples' sections within a 'Scenario Outline' by using tags. This command filters scenarios to run only those associated with the '@develop' tag, targeting a particular set of example data defined in the feature file. ```shell behave --tags=@develop features/tagged_examples.feature ``` -------------------------------- ### Accessing Step Data: Table Example Source: https://github.com/arqawa/behave/blob/main/docs/tutorial.rst Shows how to associate a data table with a step and access it via context.table in Python. The table is accessed row by row, with dictionary-like access to columns. ```gherkin Scenario: some scenario Given a set of specific users | name | department | | Barry | Beer Cans | | Pudey | Silly Walks | | Two-Lumps | Silly Walks | When we count the number of people in each department Then we will find two people in "Silly Walks" But we will find one person in "Beer Cans" ``` ```python @given('a set of specific users') def step_impl(context): for row in context.table: model.add_user(name=row['name'], department=row['department']) ``` -------------------------------- ### Getting Language Equivalents Source: https://github.com/arqawa/behave/blob/main/docs/gherkin.rst Shows the command to display the Gherkin keyword translations for a specific language. This helps understand the mapping between keywords in different languages and Behave's parsing. ```bash behave --lang-help fr ``` -------------------------------- ### UNIX-like Invoke Script using invoke.zip Source: https://github.com/arqawa/behave/blob/main/tasks/_vendor/README.rst Provides an example of a bash script to run invoke from the bundled 'invoke.zip' archive on UNIX-like systems. It determines the script's directory and then executes the zip file with any provided arguments. ```bash #!/bin/bash # RUN INVOKE: From bundled ZIP file. HERE=$(dirname $0) python ${HERE}/../tasks/_vendor/invoke.zip $* ``` -------------------------------- ### Behave Feature File Structure Example Source: https://github.com/arqawa/behave/blob/main/docs/gherkin.rst Demonstrates the basic structure of a Behave feature file, including Background, Scenarios, and step definitions. This structure is common for defining behavior-driven development tests. ```gherkin Feature: Some reasonably descriptive title for the feature being tested The following description is optional and serves to clarify any potential confusion or scope issue in the feature name. Background: some requirement of this test Given some setup condition And some other setup action Scenario: some scenario Given some condition When some action is taken Then some result is expected. Scenario: some other scenario Given some other condition When some action is taken Then some other result is expected. ``` -------------------------------- ### Behave Scenario Example with Multiple Conditions Source: https://github.com/arqawa/behave/blob/main/docs/gherkin.rst Illustrates a more complex Behave scenario with 'given', 'when', and 'then' steps, including additional 'and' and 'but' conditions to test multiple aspects of a behavior. This is useful for testing intricate state changes. ```gherkin Scenario: Replaced items should be returned to stock Given that a customer buys a blue garment and I have two blue garments in stock but I have no red garments in stock and three black garments in stock. When he returns the garment for a replacement in black, then I should have three blue garments in stock and no red garments in stock, and two black garments in stock. ``` -------------------------------- ### Example JSON Configuration File Source: https://github.com/arqawa/behave/blob/main/docs/new_and_noteworthy_v1.2.5.rst A sample JSON file structure that can be loaded into Behave's userdata. It contains key-value pairs representing configuration settings like browser, server, count, and cleanup status. ```json { "browser": "firefox", "server": "asterix", "count": 42, "cleanup": true } ``` -------------------------------- ### Behave Tag Expression Examples Source: https://github.com/arqawa/behave/blob/main/docs/behave.rst Illustrates how to use tag expressions to filter scenarios for execution. This includes simple tag inclusion, negation, logical OR, and logical AND operations using multiple --tags options. ```bash --tags @dev --tags ~@dev --tags @dev,@wip --tags @foo,~@bar --tags @zap ``` -------------------------------- ### Running Behave with Userdata via Command Line Source: https://github.com/arqawa/behave/blob/main/docs/new_and_noteworthy_v1.2.5.rst Provides examples of how to pass user-specific data directly on the command line when running Behave tests. This allows overriding configuration file settings or providing values ad-hoc. ```sh # -- ADAPT TEST-RUN: With user-specific data settings. # SHELL: behave -D server=obelix features/ behave --define server=obelix features/ ``` -------------------------------- ### gherkin - Basic Step Implementation Source: https://github.com/arqawa/behave/blob/main/docs/gherkin.rst Illustrates the basic structure of gherkin feature files, showing the use of keywords like 'Given', 'When', and 'Then' to define scenarios. This serves as a high-level description of behavior without detailing the underlying implementation. ```gherkin Given a browser client is used to load the URL "http://website.example/website/home.html" ``` ```gherkin Given we are looking at the home page ``` -------------------------------- ### Python Step for SOAP Request and Response Verification Source: https://github.com/arqawa/behave/blob/main/docs/tutorial.rst This Python snippet demonstrates setting up a SOAP client and making a request within a 'given' step, storing the response in 'context.response'. The subsequent 'then' step asserts that the 'ok' field in the response dictionary is equal to 1. This pattern is useful for testing SOAP API interactions. ```python from behave import given, then from hamcrest import eq_ @given('I request a new widget for an account via SOAP') def step_impl(context): client = Client("http://127.0.0.1:8000/soap/") context.response = client.Allocate(customer_first='Firstname', customer_last='Lastname', colour='red') @then('I should receive an OK SOAP response') def step_impl(context): eq_(context.response['ok'], 1) ``` -------------------------------- ### Enable Debug-on-Error in Behave Source: https://github.com/arqawa/behave/blob/main/docs/tutorial.rst This Python code enables the 'debug on error' functionality in behave, which starts the debugger when a step fails. It checks for a user-defined configuration flag `BEHAVE_DEBUG_ON_ERROR` and uses `ipdb.post_mortem` to enter the debugger at the point of failure. This setup is typically done in the `features/environment.py` file. ```python # -- FILE: features/environment.py # USE: behave -D BEHAVE_DEBUG_ON_ERROR (to enable debug-on-error) # USE: behave -D BEHAVE_DEBUG_ON_ERROR=yes (to enable debug-on-error) # USE: behave -D BEHAVE_DEBUG_ON_ERROR=no (to disable debug-on-error) BEHAVE_DEBUG_ON_ERROR = False def setup_debug_on_error(userdata): global BEHAVE_DEBUG_ON_ERROR BEHAVE_DEBUG_ON_ERROR = userdata.getbool("BEHAVE_DEBUG_ON_ERROR") def before_all(context): setup_debug_on_error(context.config.userdata) def after_step(context, step): if BEHAVE_DEBUG_ON_ERROR and step.status == "failed": # -- ENTER DEBUGGER: Zoom in on failure location. # NOTE: Use IPython debugger, same for pdb (basic python debugger). import ipdb ipdb.post_mortem(step.exc_traceback) ``` -------------------------------- ### Executing Steps Programmatically Source: https://github.com/arqawa/behave/blob/main/docs/tutorial.rst Demonstrates how a step implementation can programmatically execute other steps using context.execute_steps. This is useful for code reuse and complex workflows. ```python @when('I do the same thing as before') def step_impl(context): context.execute_steps(''' when I press the big red button and I duck ''') ``` -------------------------------- ### Run Behave Tests with Stages Source: https://github.com/arqawa/behave/blob/main/docs/practical_tips.rst Demonstrates how to use the '--stage' option in Behave to run tests for different layers (e.g., model, UI) using the same feature files. This approach helps in maintaining technology-agnostic feature files. ```bash $ behave --stage=model features/ $ behave --stage=ui features/ # NOTE: Normally used on a subset of features. ``` -------------------------------- ### Gherkin: Original Scenario Outline Example Source: https://github.com/arqawa/behave/blob/main/docs/new_and_noteworthy_v1.2.5.rst This Gherkin code block demonstrates a basic Scenario Outline with two 'Examples' sections. It illustrates how scenarios were previously generated with uniform names and file locations. ```gherkin # -- file:features/xxx.feature Feature: Scenario Outline: Wow # line 2 Given an employee "" Examples: Araxas | name | birthyear | | Alice | 1985 | # line 7 | Bob | 1975 | # line 8 Examples: | name | birthyear | | Charly | 1995 | # line 12 ``` -------------------------------- ### Active Tag Filtering Example (Gherkin) Source: https://github.com/arqawa/behave/blob/main/docs/new_and_noteworthy_v1.2.5.rst Demonstrates how to use active tags in a feature file to specify conditions under which scenarios should run. This example uses the '@use.with_browser' tag to control scenario execution based on the browser type. ```gherkin # -- FILE: features/alice.feature Feature: @use.with_browser=chrome Scenario: Alice (Run only with Browser Chrome) Given I do something ... @use.with_browser=safari Scenario: Bob (Run only with Browser Safari) Given I do something else ... ``` -------------------------------- ### Gherkin: Generated Scenarios with Placeholders Source: https://github.com/arqawa/behave/blob/main/docs/new_and_noteworthy_v1.2.5.rst This Gherkin code shows the resulting scenarios generated from a Scenario Outline that uses placeholders in its name and example group name. Each scenario's name is dynamically generated, reflecting the specific data from each example row. ```gherkin Scenario Outline: Wow Alice-1985 -- @1.1 # features/xxx.feature:7 Given an employee "Alice" Scenario Outline: Wow Bob-1975 -- @1.2 # features/xxx.feature:8 Given an employee "Bob" Scenario Outline: Wow Charly-1995 -- @2.1 Benares-42 # features/xxx.feature:12 Given an employee "Charly" ``` -------------------------------- ### Behave: Access Environment Variables in Steps Source: https://github.com/arqawa/behave/blob/main/examples/env_vars/README.rst This example showcases how to utilize environment variables within behave step implementations. It assumes behave is run with default settings from 'behave.ini'. The environment variable `LOGNAME` is used and checked within the steps. ```gherkin Feature: Test Environment variable concept Scenario: USE ENVIRONMENT-VAR: LOGNAME = xxx (variant 1) When I click on $LOGNAME ... passed USE ENVIRONMENT-VAR: LOGNAME = xxx (variant 2) When I use the environment variable $LOGNAME ... passed ``` -------------------------------- ### Behave Command-Line Options Source: https://github.com/arqawa/behave/blob/main/docs/behave.rst Provides a comprehensive list of command-line options for controlling Behave's test execution and output. These options allow for fine-grained control over which tests are run, how results are displayed, and how Behave behaves during execution. ```bash behave --show-source behave --stage behave --stop behave -t TAG_EXPRESSION behave -T behave --show-timings behave -v behave -w behave -x behave --lang behave --lang-list behave --lang-help behave --tags-help behave --version ``` -------------------------------- ### Shell: Filtering Scenarios by Name using behave CLI Source: https://github.com/arqawa/behave/blob/main/docs/new_and_noteworthy_v1.2.5.rst Demonstrates using the Behave CLI's `--name` option to select scenarios based on their generated names, which include example group identifiers. This allows running all scenarios belonging to a specific 'Examples' group, like 'Araxas'. ```sh $ behave --name=Araxas -f progress3 features/xxx.feature ... # features/xxx.feature Wow -- @1.1 Araxas . Wow -- @1.2 Araxas . $ behave --name='-- @.* Araxas' -f progress3 features/xxx.feature ... # features/xxx.feature Wow -- @1.1 Araxas . Wow -- @1.2 Araxas . ``` -------------------------------- ### Python Async Step Implementation Example Source: https://github.com/arqawa/behave/blob/main/docs/new_and_noteworthy_v1.2.6.rst Demonstrates the implementation of asynchronous steps in Behave using Python. This involves defining step functions that can handle asynchronous operations, likely within an event loop. It requires Python 3.4 or newer. ```python # -- FILE: features/steps/async_steps35.py # -- FILE: features/steps/async_steps34.py ``` ```python # -- FILE: features/steps/async_dispatch_steps.py # REQUIRES: Python 3.4 or newer ``` -------------------------------- ### Gherkin Feature File with Prose Source: https://github.com/arqawa/behave/blob/main/docs/tutorial.rst Illustrates a more detailed Gherkin feature file that includes a narrative explaining the purpose of the feature and the user story. It also demonstrates scenarios with Given, When, and Then steps. ```gherkin Feature: Fight or flight In order to increase the ninja survival rate, As a ninja commander I want my ninjas to decide whether to take on an opponent based on their skill levels Scenario: Weaker opponent Given the ninja has a third level black-belt When attacked by a samurai Then the ninja should engage the opponent Scenario: Stronger opponent Given the ninja has a third level black-belt When attacked by Chuck Norris Then the ninja should run for his life ```