Behave – Enumeration

Behave – Enumeration ”; Previous Next Enumeration is used to map the multiple distinctive string based words to the values. We may require a user-defined data type having the following characteristics − A handful of words must be matched. Pre-defined values prior to the test execution. For the above scenarios, enumeration based on string can be used. Feature File Consider a feature file for the Feature titled payment process, as mentioned below − Feature − Payment Process Scenario − Response When User asks “Is payment done?” Then response is “No” In the step implementation file, TypeBuilder.make_enum function evaluates a regular expression pattern for the provided enumeration of words or strings. 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 enum datatype enclosed in “{}”. Corresponding Step Implementation File The step implementation file for the above Feature is as follows − from behave import * from behave import register_type from parse_type import TypeBuilder # — ENUM: Yields True (for “yes”), False (for “no”) parse_response = TypeBuilder.make_enum({“yes”: True, “no”: False}) register_type(Response=parse_response) @when(”User asks “{q}””) def step_question(context, q): print(“Question is: “) print(q) @then(”response is “{a:Response}””) def step_answer(context, a): print(“Answer is: “) print(a) Output The output obtained after running the feature file is mentioned below. Here, we have used the command behave –no-capture -f plain. The output shows Is payment done? and False. The output False comes from the enumeration data type. 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 – Steps in a Step

Behave – Steps in a Step ”; Previous Next We can substitute multiple steps in a Scenario with one macro step. This helps us not to repeat the same code in the step definition file. A BDD framework has the capability to invoke multiple steps from the step definition. Feature File with Similar Steps The feature file with the similar steps is as follows − Feature − Payment Module Scenario − Verify message after payment Given User is on payment screen When User enters payment details And User completes payment Then User should get success message Scenario − Verify new users can process payment Given User keys in payment info and submits Then success message should get displayed In the feature file, we have two Scenario with similar steps. In Behave, we can execute more than one step in a single step. This can be done with the help of context.execute_steps method in the step implementation file. Corresponding Step Implementation File The corresponding step implementation file for the above mentioned feature file is as follows − from behave import * @given(”User is on payment screen”) def is_on_payment_screen(context): print(”User is on payment screen”) @when(”User enters payment details”) def enters_payment_details(context): print(”When User enters payment details”) @when(”User completes payment”) def completes_payment(context): print(”When User completes payment”) @then(”User should get success message”) def get_success_message(context): print(”Then User should get success message”) @given(”User keys in payment info and submits”) def payment_info_and_submits(context): #passing steps within steps with context.execute_steps context.execute_steps(u””” Given User is on payment screen When User enters payment details And User completes payment “””) @then(”success message should get displayed”) def success_message(context): print(”Then success message should get displayed”) Output The output obtained after running the feature file is given below and the command used is behave –no-capture -f plain. The continued output is as follows − The output shows that the new users of Scenario Verify can process the payment by having the steps executed from the Scenario Verify new users can process payment. Print Page Previous Next Advertisements ”;

Behave – Scenario Outlines

Behave – Scenario Outlines ”; Previous Next A Scenario Outline is used if we have a group of similar criteria and the results are to be passed in a Scenario. A Scenario Outline is accompanied with an Examples table. A Scenario Outline can have multiple Examples tables. The tests get executed once for every row found (after the header row) within the Examples table. The values to be tested are represented by their names enclosed in brackets<>. These names should match with the Examples table header. It helps to reduce the lines of code (eliminates repeating steps) and orders our tests. Feature File The feature file for scenario outline is as follows − Feature − User information Scenario Outline: Check login functionality Given user enters “<name>” and “<password>” Then user should be logged in Examples: Credentials | name | password | | user1 | pwd1 | | user2 | pwd2 | Please Note: We have kept the name and password parameters enclosed in “<>”. These parameters are column headers provided below the Examples section. In the step implementation, we shall pass the parameters enclosed in “{}”. Also, these parameters need to be passed as arguments to the implementation method. Corresponding Step Implementation File The corresponding step implementation file is as follows − from behave import * @given(”user enters “{name}” and “{password}””) def step_implpy(context, name, password): print(“Username for login: {}”.format(name)) print(“Password for login: {}”.format(password)) @then(”user should be logged in”) def step_implpy(context): pass Output The output is obtained after running the feature file and the command used is behave –no-capture -f plain. The output shows Username for login: user1, Password for login: pwd1 and Username for login: user2, Password for login: pwd2 printed. Here, the two data sets were passed from the Examples. Print Page Previous Next Advertisements ”;

Behave – Setup Table

Behave – Setup Table ”; Previous Next A step can have a text and data table associated with it. We can add a data table with a step. It is recommended to have the table data indented and it is mandatory to have an equal column number for each line. A column data should be separated by the | symbol. Feature File with Table (Login.feature) The feature file is as mentioned below − Feature − User Information Scenario − Check login functionality Given Collection of credentials | username |password | | user1 | pwd1 | | user2 | pwd2 | Then user should be logged in A table is accessible to the implementation Python code with the .table attribute within the context variable (passed in the step function). A table is an instance of Table. We can use the set up table to facilitate setting up the test. Python code The python code to access table.(login_module.py) is as follows − class Deprt(object): def __init__(self, username, ms=None): if not ms: ms = [] self.username = username self.ms = ms def m_addition(self, usernane): assert usernane not in self.ms self.ms.append(usernane) class LModel(object): def __init__(self): self.loginusrs = []f self.passwords = {} def usr_addition(self, username, password): assert username not in self.loginusrs if password not in self.passwords: self.passwords[password] = Deprt(password) self.passwords[password].m_addition(username) Corresponding Step Implementation File(step_implg.py) The file is as follows − from behave import * from features.steps.login_module import LModel @given(”Collection of credentials”) def step_impl(context): model = getattr(context, “model”, None) if not model: context.model = LModel() #iterate rows of table for r in context.table: context.model.usr_addition(r[“username”], password=r[“password”]) @then(”user should be logged in”) def step_impl(context): pass Project setup The project set up for the file in Python project is as follows 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 step up table printed. Print Page Previous Next Advertisements ”;

Behave – Background

Behave – Background ”; Previous Next A Background is added to have a group of steps. It is close to a Scenario. We can add a context to multiple Scenarios with Background. It is run prior to every Scenario of a feature, but post the execution of before hooks. Background is generally used for executing preconditions like login Scenarios or database connection, and so on. A Background description can be added for the better human readability. It can appear only for a single time in a feature file and must be declared prior to a Scenario or Scenario Outline. A Background should not be used to create a complex state (only if it cannot be avoided). This segment should be brief and authentic. Also, we should avoid having a large number of scenarios within one feature file. Feature File with Background The feature file with background for the feature titled payment process is as follows − Feature − Payment Process Background: Given launch application Then Input credentials Scenario − Credit card transaction Given user is on credit card payment screen Then user should be able to complete credit card payment Scenario − Debit card transaction Given user is on debit card payment screen Then user should be able to complete debit card payment Corresponding Step Implementation File The file is given below − from behave import * @given(”launch application”) def launch_application(context): print(”launch application”) @then(”Input credentials”) def input_credentials(context): print(”Input credentials”) @given(”user is on credit card payment screen”) def credit_card_pay(context): print(”User is on credit card payment screen”) @then(”user should be able to complete credit card payment”) def credit_card_pay_comp(context): print(”user should be able to complete credit card pay”) @given(”user is on debit card payment screen”) def debit_card_pay(context): print(”User is on debit card payment screen”) @then(”user should be able to complete debit card payment”) def debit_card_pay_comp(context): print(”user should be able to complete debit card payment”) Output The output obtained after running the feature file is mentioned below and the command used here is behave –no-capture -f plain. The continued output is as follows − The output shows the Background steps (Given Launch applications & Then Input Credentials) running twice before each of the Scenarios. Print Page Previous Next Advertisements ”;

Behave – Supported Languages

Behave – Supported Languages ”; Previous Next We have the option to utilise other languages apart from English in the feature file. This is because, the majority of BDD tools have the support for internationalisation. The important fact is that the keywords – Then, When, Given can be described in other native languages like Spanish, French, and so on. In that case, the developer can implement the step definitions in other languages as well. The list of all the languages can be obtained with the command: behave –lang-list. The following screen will appear on your computer after using the command behave –lang-list − Some more languages included in Behave are mentioned below − A feature file can be associated with a particular language. At this time, the BDD framework chooses the keywords for that specific language. The language can be set as default in the configuration file. Behave configuration files can be either, .behaverc or behave.ini files. The value for the parameter lang should be set to da in the configuration file, if we want the language to be to Danish. Configuration file setup The feature file set up for selecting a particular language is given below and the language used as an example is Danish (da). [behave] lang = da Print Page Previous Next Advertisements ”;

Behave – Step Matchers

Behave – Step Matchers ”; Previous Next There are three types of Step Matchers in Behave. They are explained below − ParseMatcher (parse) − Based on the parse module. extended ParseMatcher(cfparse) − Allows cardinality syntax. RegexMatcher (re) − Based on regular expressions for matching patterns. Parse matcher It is the in-built step matcher which has the below mentioned features: Simple to use and comprehend. Predefined and user-defined data types support this matcher. Re-utilises regular expressions with the help of data types. Conceals the complexity of regular expression. extended Parse matcher It extends the Parse Matcher. It has additional features along with the features of Parse matcher. The additional features include − Comprehends the cardinality field syntax. Generates missing type converters for the fields with cardinality field parts. Built on parse-type. Regex matcher It has the below features − Backward compatible to Cucumber. Easier to use compared to a parse matcher. Let us understand the parse matchers in detail. Parse Matchers There are maybe steps in the feature file having almost similar phrases. Behave has the parsing ability. The method use_step_parser is used for this and we have to pass the parser type as a parameter to that method. For parse matchers, we have to pass the parameter parse. It utilises the parse for regular expressions parsing and matching. Feature File (almost Given similar steps) The feature file for the similar steps is as follows − Feature − Payment Process Scenario − Check Debit transactions Given user is on “debit” screen When user makes a payment Scenario − Check Credit transactions Given user is on “credit” screen Corresponding Step Implementation File The step implementation file is as follows − from behave import * #define parser type use_step_matcher(“parse”) @given(”user is on “{p}” screen”) def step_impl(context, p): print(p) @when(”user makes a payment”) def step_pay_complete(context): pass Output The output obtained after running the feature file is mentioned below. Here, we have used the command behave –no-capture -f plain. The output shows debit and credit. These two values have been passed with almost similar Given steps in the feature file. In step implementation, we have parsed both the steps. Print Page Previous Next Advertisements ”;