Behave – Discussion

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 ”;

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 – Step Parameters

Behave – Step Parameters ”; Previous Next We can have parameters within the step names. These parameters can be taken care of by the regular expressions or by the default or extended parser with the help of the use_step_matcher method. behave.use_step_matcher(name) Modify the parameter matcher in parsing the step text. There are multiple in-built parsers present in Behave, as explained below − parse − It gives an easy parser that restores regular expression for the step parameters with plain syntax. For example, {parameter: type}. It allows type conversion with type converters. cfparse − It has the Cardinality Field (CF) support. By default, it generates the missing type converters for connected cardinality (if type converter for cardinality equal to one is given). It can support the below parse expressions − {values:Type+} – Cardinality=1..N, many {values:Type*} – Cardinality=0..N, many0 {values:Type?} – Cardinality=0..1, optional It allows type conversion with type converters. re − It utilises the complete regular expressions to parse the clause. We have to take the help of the named groups (? P<name>…) to declare variables obtained from the text and then feed it to the step (). We can have our customised matcher along with new data types with the help of the register_type method. behave.register_type(w) Registers a user defined type for parsing during type conversion at the time of step matching. class behave.matchers.Matcher(func, pattern ,step_type=None) It extracts the parameters out of step names. pattern − The pattern matching associated with the step function. func − The step function is the pattern is associated with. check_match(step) − To match with the step name provided. describe(schema=None) − Give description in form of text of the function or matcher object. regex_pattern: Yields the utilised textual regex expression. class behave.model_core.Argument(start, end, original, value, name=Name) An argument for a step name in the feature file obtained with step decorator parameters. The attributes are as follows − original − The original text which is matched in the name of the step. value − The value of the argument which is type converted. name − The argument name. The value is set to None, if the parameter is not given. start − The starting index of the argument in step name. end − The ending index of the argument in step name. class behave.matchers.Match(func, arguments=None) A step in the feature file which is parameter-matched and obtained with step decorator parameters. The attributes are as follows − func − The step function which is applicable to the given match. arguments − The argument list the instances having the matched parameter obtained from the name of the step. Print Page Previous Next Advertisements ”;

Behave – Optional Part

Behave – Optional Part ”; Previous Next There are maybe steps in the feature file having almost similar phrases. Behave has the parsing ability so that one step definition can cover these steps. The method use_step_parser is used for this and we have to pass the parser type as a parameter to that method. For extended parse matchers, we have to pass the parameter cfparse. It has the Cardinality Field (CF) support. By default, it generates the missing type converters for connected cardinality (if type converter for cardinality equal to one is given). It can support the below parse expressions − {values:Type+} – Cardinality=1..N, many {values:Type*} – Cardinality=0..N, many0 {values:Type?} – Cardinality=0..1, optional Feature File (almost similar steps) The feature file with almost similar steps is as follows − Feature − Payment Process Scenario − Check Debit transactions Given user is on “debit” screen Scenario − Check Credit transactions Given user is on “credit” screen 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 step implementation file is given below − from behave import * import parse #define parse type use_step_matcher(“cfparse”) # for whitespace characters @parse.with_pattern(r”xs+”) def parse_string(s): #type converter for “x” succeeded by single/multiple spaces return s.strip() #register user-defined datatype register_type(x_=parse_string) #optional part :x_? cardinality field in parse expression @given(”user is on {:x_?}{payment} screen”) def step_payment(context, x_, payment): print(“Payment type: “) print(payment) 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 debit and credit. These two values have been passed with almost similar steps in the feature file. In step implementation, we have parsed both the steps with cardinality fields within parse expression. Print Page Previous Next Advertisements ”;

Behave – Step Functions

Behave – Step Functions ”; Previous Next Step functions are created in the Python files which exist within the steps directory. Every Python file (having extension as .py) inside that directory gets imported to get the step implementations. Once the feature files get triggered for execution, the implementation files get loaded. The step functions are associated with the step decorators. The step implementations must begin with the import, by using the command mentioned below − from behave import * This will import multiple decorators described in Behave to help us to locate our step functions. The decorators like the given, when, then, and so on accepts one string argument. For example, consider the code given herewith − @given(”user is on admin screen”) def step_impl(context): pass The above code shall match the Given step of the below feature file, which is as follows − Feature − Admin Module Scenario − Admin verification Given user is on admin screen The steps starting with And/But in the feature file are renamed to their earlier step keyword. For example, consider the feature file given below − Feature − Admin Module Scenario − Admin verification Given user is on admin screen And user is on history screen Then user should be able to see admin name But user should not able to check history The And step shall be renamed to the Given step and the But step shall be renamed to the earlier step keyword. All these are handled internally. If there are more than one And/But steps consecutively, they would inherit the keyword of non And or But keyword. The step function having the step decorator shall have a minimum one parameter. The first parameter is known as the context variable. Other parameters come from step parameters (if required). For example, refer the step function as per the step parameter. @given(”user is on admin screen”) def step_impl(context): pass Project Structure The project structure for the feature is as follows − Print Page Previous Next Advertisements ”;

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 ”;