Discuss Behave ”; Previous Next Behave is a Behavior driven development (BDD) tool in Python language. This tutorial shall provide you with a detailed knowledge on Behave and its different terminologies. Print Page Previous Next Advertisements ”;
Category: behave
Behave – Retry Mechanism
Behave – Retry Mechanism ”; Previous Next We can rerun failed Scenarios in the feature file in Behave. This is taken care with the help of the formatters. All the available formatters in Behave can be seen with the command given below − behave –f help You can see the following screen after using the command − The rerun formatter is used to capture the failing scenario and output it in a separate file. Let us take an example, where we have 1 failed feature. Then capture the failed feature in another feature file with the command − behave –f rerun –o failed_features.feature You can see the following − The failed_features.feature file gets generated within the project. It contains the feature file name Payment1.feature where we have a failure. To re-trigger only failed Scenario, we have to run the command stated below − behave @failed_features.feature You will see the following screen − Print Page Previous Next Advertisements ”;
Behave – Reports
Behave – Reports ”; Previous Next Report generation is one of the most important steps towards the test automation framework. At the end of the execution, we cannot rely on the console output rather we should have a detailed report. It should have the information on the count of tests that passed, failed, skipped, feature and scenario breakdown. Behave does not produce an in-built report but it can output in multiple formats and we can utilize the third-party tools to generate a report. All the available formatters in Behave are displayed with the command − behave –format help When you use the command, the following screen will appear on your computer − Some of the common Behave reports are − Allure Report. Output JSON Report. JUnit Report JUnit Report Let us execute a test having two feature files with the below test results − Project folder structure for the above test will be as follows − Step 1 − Execute the command To create a JUnit report, run the command given below − behave –junit Step 2 − Report folder generation A folder called as the reports gets generated within the project, having the name TESTS-<feature file name>.xml. Here, Payment and Payment1 are the names of the feature files. Step 3 − Report generation to a specific folder To generate the reports to a specific folder, say my_reports. We have to run the below mentioned command − behave –junit –junit-directory my_reports A folder called the my_reports gets generated within the project which contains the reports. JSON Report We can create the Behave JSON report. The JSON is actually a formatter. Let us execute a test having two feature files with the below test results − Project folder structure for the above test is as follows − Step 1 − Execute the command To create a JSON output in console, run the command − behave -f json The following screen will appear − Step 2 − Output in readable format To create a JSON output in a more readable format, run the following command − behave -f json.pretty Some portion of the output captured in the below image − Step 3 − Report generation to a specific folder To generate the reports to a specific folder say, my_reports.json, we have to run the following command − behave –f json.pretty –o my_reports.json The following image represents the screen that will appear on your computer. A folder called the my_reports.json gets generated within the project, having details of all the features which are executed. Allure Report To generate Allure reports in Behave, first we have to install Allure in the system. For installation from the command line in Linux, run the following commands one after the other − sudo apt-add-repository ppa:qameta/allure sudo apt-get update sudo apt-get install allure For Mac users, installation is done with the Homebrew with the following command − brew install allure For Windows, Allure is installed from the Scoop installer. Run the below command to download and install Scoop and finally, execute it in the PowerShell − scoop install allure To update Allure distribution installations from Scoop, run the below command from the installation directory of Scoop − bincheckver.ps1 allure -u Finally, run the command given below − scoop update allure After Allure has been installed, we have to get the Allure-Behave integration plugin for Python. For this, run the following command − pip install allure-behave To verify if Allure has been installed successfully, run the command stated below − allure Let us execute a test having two feature files with the below test results − Project folder structure for the above test is as follows − Step 1 − Report generation to a specific folder To generate the reports to a specific folder, say my_allure, we have to run the following command − behave -f allure_behave.formatter:AllureFormatter –o my_allure You will get the screen as shown below − A folder called the my_allure gets generated within the project, having files with .json extension. Step 2 − Start the web server To start the web server, run the command given below − allure serve my_allure Here, the my_allure is the directory which contains the allure json files. Simultaneously, a browser gets opened, with the Allure report as shown below − We can also click on individual features and find their breakdowns, as shown below − Print Page Previous Next Advertisements ”;
Behave – Quick Guide
Behave – Quick Guide ”; Previous Next Behave – Introduction Behave is a tool used for Behaviour driven development (BDD) in Python programming language. In an Agile development framework, BDD creates a culture where testers, developers, business analysts, and other stakeholders of the project can contribute towards the software development. In short, both technical and non-technical individuals have a role to play towards the overall project. Behave has tests developed in plain text with the implementation logic in Python. The BDD format begins with the description of the characteristics of the software similar to a story. It then continues with the development and carries out the following tasks − Developing a failing test case for characteristics. Implement the logic for a test to pass. Code refactor to fulfil the project guidelines. There are numerous libraries for BDD like the Mocha which supports JavaScript, Cucumber which supports Java/Ruby, and Behave which supports Python, and so on. In this tutorial, we shall discuss in detail about Behave. Let us see a basic structure of a BDD. It mainly consists of the feature file, the step definition file, and so on. Feature File The feature file in Behave can be as follows − Feature − Verify book name added in Library. Scenario − Verify Book name. Given − Book details. Then − Verify book name. Corresponding step definition file Following is the corresponding definition file in Behave tool − from behave import * @given(”Book details”) def impl_bk(context): print(”Book details entered”) @then(”Verify book name”) def impl_bk(context): print(”Verify book name”) Output The output obtained after running the feature file is as follows − The output shows the Feature and Scenario names, along with the test results, and the duration of the respective test execution. Behave – Installation Behave installation can be done by the following ways − With pip For Behave installation, we should have pip – the package installer for the Python language installed in our system. The pip is installed by default, if the Python version is greater than 2(upto 2.7.9). To install pip, run the below mentioned command − pip install pip To install pip with Behave, run the command given below − pip install behave The following screen will appear on your computer − We can update an existing version of Behave with the following command − pip install –U behave We can also use the easy_install for the Behave installation. To install Setuptools, run the below mentioned command− pip install setuptools Now, for the Behave installation, run the command stated below: easy_install behave We can update an existing version of behave with the command given below: easy_install –U behave With Source Distribution Post unpacking of the source distribution of Behave, type the new generated directory ”behave-<version>” and execute the below mentioned command − python setup.py install With Git Repository We should first have the pip installed in the system. Later on, to install the latest version of Behave with Git repository, run the below mentioned command − pip install git+https://github.com/behave/behave If we use the PyCharm Editor for writing the Behave code, we should have the Professional version of PyCharm along with the Gherkin plugin installed with it. Behave – Command Line Behave has a collection of command line arguments and it can also be outlined from the configuration files. The values set in the configuration files are used automatically, however, it can be overruled by the command line arguments. Command Line Arguments Let us discuss some of the command line arguments − –c, –no-color Impair the usage of the ANSI color escapes. –color – Utilise the ANSI color escapes. This is an in-built characteristic and can overrule a setting in the configuration file. –d, –dry-run Summons the formatter without running the steps. -D, –define Declares the customised information for the config.userdata dictionary. –e, –exclude Pattern Exclude feature files which are identical to a pattern of regular expression from the execution. –i, –include Pattern Include feature files which are identical to a pattern of regular expression during the execution. –no-junit Omit JUnit reports as output. –junit Add JUnit reports as output. When JUnit is turned on, every stdout and stderr will be a part of the junit report. (Irrespective of the -capture/-no-capture options). –f, –format Define a formatter. If omitted, the in-built formatter is utilised. The –format-help command shall display all the available formats. -steps-catalog Displays a catalogue of all the existing step definitions. –k, –no-skipped Exclude skipped steps from printing in console. no-snippets Exclude snippets from printing in console for the steps, which are still not implemented. –snippets Include snippets, while printing in console for the steps which are still not implemented. This is an in-built characteristic and can overrule a configuration file setting. –m, –no-multiline Exclude multiple lines tables and strings under steps. –multiline Include multiple lines tables and strings under steps. This is an in-built characteristic and can overrule a configuration file setting. –n, –name Include the feature elements, which are identical to the specified name in the run. If the option is provided multiple times, it shall match with all the names. –no-capture Exclude stdout from capturing. –capture Include stdout. This is an in-built characteristic
Behave – Hooks
Behave – Hooks ”; Previous Next Behave setup and teardown functions are implemented in a file called the environment.py which is within the same directory that contains the steps folder. The setup functions include – browser open, database connection, configurations, and so on. The teardown functions include browser closure, database connection termination, reversing changes, and so on. The environment.py file contains the following functions − before_feature(context, feature) − Executes prior every feature. before_scenario(context, scenario) − Executes prior every scenario. before_step(context, step) − Executes prior every step. before_tag(context, tag) − Executes prior every tag. before_all(context) − Executes prior everything. after_feature(context, feature) − Executes post every feature. after_scenario(context, scenario) − Executes post every scenario. after_step(context, step) − Executes post every step. after_tag(context, tag) − Executes post every tag. after_all(context) − Executes post everything. The above functions are used as hooks in Behave. Project structure should be as follows − Feature File with hooks (Payment.feature) The feature file with hooks for Payment.feature is as follows − Feature − Payment Process Scenario − Verify transactions Given user makes a payment of 100 INR And user makes a payment of 10 Dollar Feature File with hooks (Payment1.feature) Given below is the feature file with hooks for Payment1.feature − Feature − Administration Process Scenario − Verify admin transactions Given user is on admin screen Corresponding step Implementation File The step implementation file is as follows − from behave import * from parse_type import TypeBuilder parse_amt = TypeBuilder.make_choice([“100”, “10”]) register_type(Amt=parse_amt) parse_curr = TypeBuilder.make_choice([“INR”, “Dollar”]) register_type(Curn=parse_curr) @given(“user makes a payment of {n:Amt} {t:Curn}”) def step_payment(context, n, t): pass @given(”user is on admin screen”) def step_admin(context): pass Step 4 − Hooks in environment.py file The hooks in environment.py file are as follows: # before all def before_all(context): print(”Before all executed”) # before every scenario def before_scenario(scenario, context): print(”Before scenario executed”) # after every feature def after_feature(scenario, context): print(”After feature executed”) # after all def after_all(context): print(”After all executed”) Output The output obtained after running the feature files is as follows − Print Page Previous Next Advertisements ”;
Behave – Debugging
Behave – Debugging ”; Previous Next Behave scripts can be debugged by dry running the test steps. The dry run helps to go over all the test steps without actually running it. It helps to determine the un-defined steps in the step definition file. It verifies if there are any missing import statements, syntax errors, and so on. All these issues get detected in a quick time by dry run. If we are doing mass updates or any configuration changes, dry running helps to detect any errors in a short time. If we would have to run an entire suite for debugging, that would be time consuming. In Behave, we can do a debug by dry run with the help of the below mentioned command − behave –no-capture –dry-run You will get the screen as shown below − The output shows 3 untested which shows the count of the test steps. Let us dry run feature files having unimplemented steps, as shown below − The output clearly defines the un-defined steps in the step definition file obtained by dry run. Print Page Previous Next Advertisements ”;
Behave – Data Types
Behave – Data Types ”; Previous Next There are two types of Data Types in Behave, which are Predefined and User-defined. Let us first understand what are the predefined data types. Pre-defined Data types Behave utilises the parse module for the parsing parameters in the step definitions. Let us explore some of the parse types that have support for step definitions and do not need be registered like user-defined data types. w (of str type) − Underscore & letters. W (of str type) − Underscore & non-letters. s (of str type) − Whitespace. S (of str type) − Non – Whitespace. d (of int type) − Digits. D (of str type) − Non – Digits. n (of int type) − Numbers having thousands separators. % (of float type) − Percentage. (translated to value/100.0) f (of float type) − Fixed − point numbers. e (of float type) − Floating − point numbers along with exponent. g (of float type) − Number format. b (of int type) − Numbers in binary. (of int type) − Numbers in octal. x (of int type) − Numbers in hexadecimal. ti (of datetime type) − Time in ISO 8601 date/time format. te (of datetime type) − Time in RFC 2822 email data/time format. tg (of datetime type) − Time in Global data/time format. ta (of datetime type) − Time in US data/time format. tc (of datetime type) − ctime() data/time format. th (of datetime type) − Time in HTTP log data/time format. tt (of time type) In the step implementation, we shall pass the parameter: data type enclosed in “{}”. Feature File with % data type The feature file with % data type is as follows − Feature − Payment Process Scenario Outline: Credit card transaction Given user is on credit card payment screen When user makes a payment of “<p>” percent of total Examples: Amounts | p | |80% | |90% | Corresponding Step Implementation File The file is as follows − from behave import * @given(”user is on credit card payment screen”) def credit_card_pay(context): print(”User is on credit card payment screen”) #passing parameter in % datatype enclosed in {} @when(”user makes a payment of “{p:%}” percent of total”) def step_impl(context, p): print(”Number is: ”) print(p) Output The output is obtained after running the feature file and the command used is behave –no-capture -f plain. The continued output is as follows − The output shows 0.8 and 0.9 which is obtained from the % data type to represent 80% and 90% values passed from the feature file. User-defined Data types Behave also has the user-defined data types. The method register_type is used to register a user defined type that can be parsed for any type conversion at the time of matching the step. Feature File The feature file for feature titled payment process is as follows − Feature − Payment Process Scenario Outline: Credit card transaction Given user is on credit card payment screen When user makes a payment of “<amount>” of total Examples: Amounts |amount | |75 | |85 | In the step implementation, we shall pass the parameter: user-defined datatype enclosed in “{}”. The method register_type is used to register a user defined type that can be parsed for any type conversion at the time of matching the step. Corresponding Step Implementation File The file is as follows − from behave import * from behave import register_type #convert parsed text to float def parse_percent(t): return float(t) #register user-defined type register_type(Float=parse_percent) @given(”user is on credit card payment screen”) def credit_card_pay(context): print(”User is on credit card payment screen”) @when(”user makes a payment of “{amount:Float}” of total”) def step_impl(context, amount): print(”Number is: ”) print(amount) Output The output is obtained after running the feature file and the command used is behave –no-capture -f plain. The continued output is as follows − The output shows 75.0 and 85.0 which have been converted to float values (with the help of user-defined conversion). These parameters are passed as the integer types from the feature file. Print Page Previous Next Advertisements ”;
Behave – Multi-Methods
Behave – Multi-Methods ”; Previous Next There are maybe steps in the feature file having almost similar phrases. For instance, Given user makes payment of 100 INR And user makes payment of 10 Dollar Here, we can have different step definitions to differentiate the INR and Dollar. For this, we can use the multi-method approach, where it is mandatory to have varied regular expressions for the dissimilar data types. Feature File (almost similar steps) Consider the feature file as given below − Feature − Multi-Methods Scenario − Purchase Given User is on shop When user purchases 3 shirts And user purchases 4 pants In the step implementation file, TypeBuilder.make_choice function evaluates a regular expression pattern for the provided choices. The method register_type is used to register a user defined type that can be parsed for any type conversion at the time of matching the step. Also, we shall pass the parameter: user-defined datatype enclosed in “{}”. Corresponding Step Implementation File The step implementation file is as follows − from behave import * from behave import register_type from parse_type import TypeBuilder parse_dress = TypeBuilder.make_choice([“shirts”, “t-shirts”]) #register user-defined datatype register_type(Dress=parse_dress) parse_pant = TypeBuilder.make_choice([“pants”, “gowns”]) #register user-defined datatype register_type(Pant=parse_pant) @given(“User is on shop”) def step_user_shop(context): pass # multiple methods being used . @when(u”user purchases {count:n} {d:Dress}”) def step_dress(context, count, d): print(“User purchased: “) print(d) print(“Count is:”) print(count) @when(u”user purchases {count:n} {p:Pant}”) def step_pant(context, count, p): print(“User purchased: “) print(p) print(“Count is:”) print(count) Output The output obtained after running the feature file is given below and the command used is behave –no-capture -f plain. The output shows the purchase items and their counts. These two values have been passed with almost similar steps (but dissimilar data types) in the feature file. In step implementation, we have used multiple methods to obtain the values. Print Page Previous Next Advertisements ”;
Behave – Tags
Behave – Tags ”; Previous Next A section of a feature file can be tagged so that the Behave is capable of verifying only a certain section of the feature file. A Scenario, Feature, Scenario Outline can only be tagged. Also, a tag which is used for a feature shall be inherited by all its Scenarios and the Scenario Outlines. Tags are placed before a Scenario or a Feature that we want to tag. We can also have multiple tags which are separated by spaces within a line. A tag begins with @ and is followed by the tag name. Feature File with tags (Payment.feature) The feature file with tags is as follows − @high Feature − Payment Process @creditpayment Scenario − Credit card transaction Given user is on credit card payment screen Then user should be able to complete credit card payment @debitpayment Scenario − Debit card transaction Given user is on debit card payment screen Then user should be able to complete debit card payment Tags help to manage the test execution by excluding/including the specific scenarios or features depending on the tag. In the above example, to run a specific scenario with tag creditpayment, we have to run the below mentioned command − behave payment.feature –tags=creditpayment To run the feature with tag high and execute all the Scenarios, we have to run the following command − behave payment.feature –tags=high If run the command stated below, it means that the command shall execute the Scenarios which are tagged with creditpayment or debitpayment. behave payment.feature –tags= creditpayment, debitpayment If run the command given below, it means that the command shall execute both the Scenarios which are tagged with creditpayment and debitpayment. behave payment.feature –tags= creditpayment –tags=debitpayment If run the command mentioned below, it means that the command shall not execute the Scenario which is tagged with creditpayment. behave payment.feature –tags= ~ creditpayment Hence, the Feature File with tags(Payment.feature) will now be as follows − @high Feature − Payment Process @creditpayment @payment Scenario − Credit card transaction Given user is on credit card payment screen @debitpayment @payment Scenario − Debit card transaction Given user is on debit card payment screen Scenario − Cheque transaction Given user is on cheque payment screen Corresponding Step Implementation File The file is as follows − from behave import * @given(”user is on credit card payment screen”) def credit_card_pay(context): print(”User is on credit card payment screen”) @given(”user is on debit card payment screen”) def debit_card_pay(context): print(”user is on debit card payment screen”) @given(”user is on cheque payment screen”) def cheque_pay(context): print(”user is on cheque payment screen”) Output The output obtained after running the feature file is mentioned below. Here, we have used the command behave –no-capture Payment.feature –tags=payment. The output shows two scenarios passed, as there are two Scenarios in the features file having Scenario tag with payment. When we use the command behave –no-capture Payment.feature –tags=~creditpayment, the output is as follows − The output shows two scenarios passed, as there are two Scenarios in the features file not having Scenario tag with creditpayment. When we use the command behave –no-capture Payment.feature –tags=high, the output is given below − The output shows three scenarios passed, as there are three Scenarios in the features file not having features tagged with high. Use the command behave –no-capture Payment.feature –tags=payment,creditpayment to get the below mentioned output − The output shows two scenarios passed, as there are two Scenarios in the features file not having Scenario tagged with payment or creditpayment. Print Page Previous Next Advertisements ”;
Behave – Runner Script
Behave – Runner Script ”; Previous Next We can run a Behave test, by running the command line arguments, or we can create a runner script. This script gives the provision of running the test and generating the corresponding report. We can do a re-try and execute the failed test. Also, before executing the entire suite, the runner script is capable of making an application programming interface (API) call and ensuring that there are no issues with the API. Steps for Runner Script Follow the steps given below to create and execute a runner script successfully in Behave. Step 1 − Create a runner script (runner.py) within the features folder. The following screen will appear on your computer − Step 2 − Runner Script Implementation to run tests The runner script can be implemented to run the tests by using the below mentioned code − import subprocess if __name__ == ”__main__”: #command line args along with error capture on failure with check true s = subprocess.run(”behave –no-capture”,shell=True, check=True) Step 3 − Execute the runner script Execute runner.py file with command python3 runner.py (if Python version is 3). The following screen will appear on your computer: Step 4 − Parametrise runner script by passing command line arguments. The runner script implementation to run tests can be done as follows − import argparse import subprocess if __name__ == ”__main__”: p = argparse.ArgumentParser() #–testdir command line argument added p.add_argument(”–testdir”, required=False, help=”File path”) a = p.parse_args() testdir = a.testdir #complete command c= f”behave –no-capture {testdir}” s = subprocess.run(c, shell=True, check=True) Step 5 − Execute the runner script Execute runner.py file with command python3 runner.py –testdir=features. Print Page Previous Next Advertisements ”;