Behave – Feature Files

Behave – Feature Files ”; Previous Next Behave works with three different file types, as explained earlier. These files are as follows − Feature files which are created by the Business analyst or any project stakeholder and contains behaviour related use cases. Step Implementation file for the scenarios defined in the feature file. Environment Setup files where the pre/post conditions are to be executed prior and post steps, features, scenarios, and so on. A Feature file should be within a folder called as the features. Also, there should be a sub-directory steps within the features directory. The following screen will appear on your computer − Launching Feature file We can launch the feature file with various command line arguments, as explained below − If no information is available, all the feature files within the features directory shall be loaded for the execution in Behave. If the path of the features directory is provided, then it is mandatory to have at least one feature file (with .feature extension) and a sub-directory named steps within the features directory. Also, if the environment.py is present, it should be within the directory that has the steps directory and not within the steps directory. If the path to a feature file is provided, then it instructs Behave to search for it. To get the corresponding steps directory for that feature file, the parent directory is searched. If not found in the current parent directory, then it searches its parents. This shall continue until it reaches the file system root. Also, if the environment.py is present it should be within the directory that has the steps directory and not within the steps directory. Structure of a Feature File A Feature consists of Scenarios. They may/may not contain a description, background, and a group of tags. A structure of a feature file is as follows − Feature File The format of a feature file is as follows − Feature − Verify book name added in Library Scenario − Verify Book name Given Book details Then Verify book name Corresponding Step Implementation File. The corresponding step implementation file looks like the one mentioned below − 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 duration of the test execution. Print Page Previous Next Advertisements ”;

Behave – Gherkin Keywords

Behave – Gherkin Keywords ”; Previous Next Gherkin keywords in Behave are listed below − Features Scenario Steps Background Scenario Outline Text Table Tags Given When Then But And Feature files are written in Gherkin language. It is in plain text and created by non- technical members of the team (business analyst). Feature files can be used for both automation testing and documentation. Line endings finish statements are included in Behave. We can use tabs/spaces for indentation. Majority of lines begin with the keywords like Scenario, Given, Then, and so on. Comments can be added in any location within the file. They start with/without spaces, followed by # symbol along with text. Let us discuss some key Gherkin keywords. Feature A Feature consists of Scenarios. They may/may not contain description, background, and a group of tags. The structure of a feature file is as follows − Feature − Verify book name added in Library Scenario − Verify Book name Given Book details Then Verify book name The name of the feature should have a description for the feature which is being tested. However, a lengthy description is not mandatory and a description is only added to remove ambiguity in the feature name. Background A Background is added to have a group of steps. It is close to a Scenario. We can add a context to the 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 better human readability. A Background can appear only a single time in a feature file and it 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 keyword 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 Scenario A Scenario defines a behaviour of the application that is being tested. It has a title to describe its objective. Its description can be added for better human readability. A Scenario may have multiple steps, which begins with the keywords Given, Then, When, and so on. It is recommended to have a Scenario to check a single characteristic or an expected result. Feature File with Scenario The feature file with Scenario keyword is as follows: Feature − Payment Process Scenario − Credit card transaction Given user is on credit card payment screen Then user should be able to complete credit card payment Scenario Outline A Scenario Outline is used if we have a group of similar criteria and the results to be passed in a Scenario. A Scenario Outline is accompanied with an Examples table and 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 as it eliminates the repeating steps and orders our tests. Feature File with Scenario Outline The feature file with Scenario Outline keyword is as follows − Feature − User information Scenario Outline: Check login functionality Given user enters <email> and <password> Then user should be logged in Example Following is an example of the feature file with Scenario Outline − Examples: Credentials | email | password | | [email protected] | pwd1 | | [email protected] | pwd2 | The same test gets executed with a varied set of parameters. Given A step starting the keyword Given is used to place the system in a familiar circumstance prior to the interaction of the user with the system (similar to a precondition). It is recommended not to describe a user action in the Given step. A Given step can be added for setting the configuration in the database, log in to the application, and so on. Feature File with Given The feature file with Given keyword is as follows − Feature − Payment Process Scenario − Credit card transaction Given user is on credit card payment screen Then user should be able to complete credit card payment When A step starting with the keyword When is used to add the essential task to be performed by the user. With this, there is a user communication with the system that brings about the changes to system’s state or an impact elsewhere. Feature File with When The feature file with When keyword is as follows − Feature − Payment Process Scenario − Credit card transaction Given user is on credit card payment screen When user clicks on the Payment with Credit Card button Then user should be able to complete credit card payment Then A step starting with the keyword Then is used to get the expected results. The results observed (ideally in form of an output – messages, reports, and so on) in this step should be connected to a business scenario and the feature file where

Behave – Command Line

Behave – Command Line ”; Previous Next 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 and can overrule a configuration file setting. –no-capture-stderr Exclude stderr from capturing. –capture-stderr Include stderr. This is an in-built characteristic and can overrule a configuration file setting. –no-logcapture Exclude log from capturing. –logcapture Include log capturing. Every log for a step will be present and available during the failures. This is an in-built characteristic and can overrule a configuration file setting. –logging-level Mention the logging level that shall be captured. The default value is INFO. –logging-format Mention the user-defined format for printing statements. The default value is %(levelname)s:%(name)s:%(message)s. –logging-datefmt Mention the user-defined date and time format for printing statements. –logging-filter Mention if the statements are to be filtered or not. All the statements are captured by default. In case the output is too lengthy, we can utilise the option to filter out the unnecessary output. –logging-clear-handlers Remove all the handlers which are used for logging. –no-summary Exclude summary post the execution. -summary Include summary post the execution. –o, –outfile Write the given file instead of using stdout. –q, –quiet Alias are used for –no-snippets –no-source. –s, –no-source Exclude printing the file and the line of step definition along with steps. –show-source Include printing the file and the line of step definition along with the steps. This is an in-built characteristic and can overrule a configuration file setting. –stage Describes the present stage of the test. The stage name is utilised as the name affix for the environment file, along with the directory for the steps. –stop Terminate executing tests after encountering the first failure. –t, –tags Include the features/scenarios having tags, which are identical to TAG_EXPRESSION in the execution. –T, –no-timings Exclude printing duration of execution for each step. –show-timings Capture the duration taken by each step to complete in seconds in the console. This is an in-built characteristic and can overrule a configuration file setting. –v, –verbose Displays the loaded features and files. –w, –wip Execute the scenarios having the wip tag. Moreover, we have to use the plain formatter and not record the stdout or log output and terminate post first failure. –x, –expand Flatten the table of Scenario Outline in output. –lang Utilise keywords for a language except English. –lang-list Displays all the languages present in –lang. –lang-help Displays all the translations acquired for a single language. –tags-help Display help for tag statements. –version Displays version. junit –directory This is the directory location where the Junit reports are stored. –show-skipped Include skipped steps while printing in console. This is an in-built characteristic and can overrule a configuration file setting. Print Page Previous Next Advertisements ”;

Behave – Step Parameters

Behave – Step Parameters ”; Previous Next We can pass parameters to steps in Behave. Let us see a feature file containing steps having multiple parameters where the varied values have been set. This is helpful in making the automation implementation easier, since the total step definitions is lessened. Feature File Consider an example of feature file as given below − Feature − Schedule Scenario − Verify Day and Night Schedule Given I reach office at “day” shift And I reach office at “night” shift The feature file contains almost the similar steps as in the Given and in the And steps. The only difference is that in the day and night shift timings. Instead of repeating the implementations for almost the similar steps, we can pass parameters to the steps in the step definition file. Please Note − We have kept the day and night parameters in double-quoted text (single-quoted text can also be used) in the feature file. In the step implementation, we shall pass the parameter enclosed in {}. Also, the parameter is passed as one of the arguments to the implementation method. Corresponding Step Implementation File The corresponding step implementation file is as follows − from behave import * @given(”I reach office at “{time}” shift”) def step_implpy(context, time): print(“Shift is: {}”.format(time)) Output The output obtained after running the feature file is as follows and the command used is behave –no-capture -f plain− The output shows Shift is: day and Shift is: night printed. Here, the parameters day and night are passed from the step. Print Page Previous Next Advertisements ”;

Behave – Regular Expressions

Behave – Regular Expressions ”; Previous Next Let us have an overall view of the syntax of regular expressions − Dot (.) − Equivalent to any character. Caret (^) − Equivalent to beginning of string. (^…) Dollar Sign (&dollar;) − Equivalent to end of string. (…&dollar;) | − Expression x| y, matches x or y. − Escape character. . − Matches dot. (.) \ − Matches backslash. () […] − Declares a set of characters. ([A-Za-z]) d − Matches digit. ([0-9]) D − Matches non-digit. s − Matches whitespace character. S − Matches non – whitespace character. w − Matches alphanumeric. W − Matches non-alphanumeric. (…) − Group a pattern of regular expression. number − Matches text of previous group by index. (1) (? P<name>…) − Matches pattern and stores it in the name parameter. (?P=name) − Matches all text which was matched by the previous group name. (?:…) − Matches a pattern, however cannot capture text. (?#…) − Comment (not considered). Narrates details of pattern. In case a character, character set or group needs to repeat multiple times, it is mandatory to provide the cardinality of the pattern of regular expression. ? : Pattern having cardinality 0… 1:not mandatory(question mark) – : Pattern having cardinality 0 or more, 0..( asterisk) + – : Pattern having cardinality 1 or more, 1..(plus) {n}: Matches a pattern for n repetitions. {a ,b}: Matches from a to b for a pattern repetitions. [A-Za-z]+ : Matches multiple alphabetical characters. There are maybe steps in the feature file having almost the 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 regular expression matchers, we have to pass the parameter re. The parameter (? P<name>…) is utilised to obtain parameters from the step definition. Feature File (almost similar steps) The feature file for 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 Corresponding Step Implementation File The step implementation file is as follows − from behave import * #define parser type use_step_matcher(“re”) #regular expression parsing @given(”user is on “(?P<payment>.*)” screen”) def step_impl(context, payment): print(“Screen type: “) print(payment) Output The output obtained after running the feature file is as follows. Here, we have used the command behave –no-capture -f plain. The output shows the debit and credit. These two values have been passed with almost the similar steps in the feature file. In step implementation, we have parsed both the steps with regular expression. Print Page Previous Next Advertisements ”;

Behave – Installation

Behave – Installation ”; Previous Next 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. Print Page Previous Next Advertisements ”;

Behave – Configuration Files

Behave – Configuration Files ”; Previous Next Behave configuration files are known as the .behaverc/behave.ini/setup.cfg/tox.ini(any one and is set as per user choice). The files can be located in the following places − The present working directory. User home directory. For Windows users, in the directory %APPDATA%. The command behave –v, shall display all the configuration details. The configuration files should begin with the keyword [behave] and follow Windows INI style format. For example, [behave] format = plain dry_run = false Types of Parameters Types of configuration parameters in Behave include the following − Text − To assign a text to the configuration setting. Bool − Assigns Boolean value to the configuration setting. The text defines the behaviour (true values include 1, true, yes, and on). The false values include 0, false, no, and off). Sequence<text> − To accept multiple values on new lines. For example, tag expression can be as follows − tags=@a, ~@b @c This is equivalent to the following tag expression − –tags @a, ~@b –tags @c Configuration Parameters Some of the configuration parameters in Behave are explained below − color − bool Utilise ANSI color escapes. This is an in-built characteristic and can overrule a setting in the configuration file. dry_run − bool Calls the formatters without running the steps. userdata_defines − sequence<text> Declares the customised data for the config.userdata dictionary. exclude_re − text Exclude the feature files which are identical to a pattern of regular expression from the execution. include_re − text Include the feature files which are identical to a pattern of regular expression during the execution. junit − bool 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). junit_directory − text This is the directory location where the JUnit reports are stored. default_format − text Declare default formatter. The default value is pretty. format: sequence<text> Define a formatter. If omitted, the in-built formatter is utilised. The –format-help command shall display all the available formats. steps_catalog − bool Displays a catalogue of all the existing step definitions. scenario_outline_annotation_schema: text Mention annotation schema for scenario outline. show_skipped − bool Include the skipped steps while printing in console. This is an in-built characteristic and can overrule a configuration file setting. show_snippets − bool 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. show_multiline − bool Include multiple lines tables and strings under steps. This is an in-built characteristic and can overrule a configuration file setting. name − sequence<text> Include the feature elements which are identical to the specified name in the run. If the option is provided multiple times, it shall match all the specified names. stdout_capture − bool Include stdout. This is an in-built characteristic and can overrule a configuration file setting. stderr_capture − bool Include stderr. This is an in-built characteristic and can overrule a configuration file setting. log_capture − bool Include log capturing. Every log for a step will be present and available during the failures. This is an in-built characteristic and can overrule a configuration file setting. logging_level − text Mention the logging level to be captured. The default value is INFO. logging_format − text Mention user-defined format for printing statements. The default value is %(levelname)s:%(name)s:%(message)s. logging_datefmt − text Mention user-defined date and time format for printing statements. logging_filter − text Mention the statements which are to be filtered. All the statements are captured by default. In case the output is too lengthy, we can utilise the option to filter out the unnecessary output. logging_clear_handlers : bool Remove all the handlers which are used for logging. summary − bool Include a summary post the execution. outfiles − sequence<text> Write the given file instead of using stdout. paths − sequence<text> Mention the default paths of feature files. quiet − bool Alias is used for –no-snippets –no-source. show-source − bool Include printing the file and the line of step definition along with steps. This is an in-built characteristic and can overrule a configuration file setting. stage − text Describes the present stage of the test. The stage name is utilised as the name affix for the environment file along with the directory for steps. stop − bool Terminate executing tests after encountering the first failure. tags − sequence<text> Include the features/scenarios having tags which are identical to TAG_EXPRESSION in the execution. default_tags − text Declare the default tags if they are not given. show_timings − bool Capture the duration taken by each step to complete in seconds in the console. This is an in-built characteristic and can overrule a configuration file setting. verbose − bool Displays the loaded features and files. wip − bool Execute the scenarios having the wip tag. Moreover, we have to use the plain formatter and not record the stdout or log output and terminate post first failure. expand − bool

Behave – Useful Resources

Behave – Useful Resources ”; Previous Next The following resources contain additional information on Behave. Please use them to get more in-depth knowledge on this. Marketing with Facebook Groups and Marketplace 17 Lectures 34 mins Stone River ELearning More Detail Git and GitHub Masterclass – Fasttrack your Journey to Git! 118 Lectures 9 hours Karthikeya T More Detail Print Page Previous Next Advertisements ”;

Behave – Exclude Tests

Behave – Exclude Tests ”; Previous Next We can exclude the executing files by its filename from execution. Suppose, we have more than one feature file within the features folder. The following screen can be seen on the computer − On executing the command behave, the output will be as follows − If we have to only run the feature file Payment.feature and exclude Payment1.feature, we have to pass the command line argument –e or –exclude followed by pattern of the regular expression. On executing the command behave –exclude *1.feature, the output is as follows − The output shows one feature passed along with the Payment.feature file name. Also, Payment1.feature is not included in the run. Print Page Previous Next Advertisements ”;

Behave – Feature Testing Setup

Behave – Feature Testing Setup ”; Previous Next Behave works with three different file types, which are as follows − Feature files which are created by a Business analyst or any project stakeholder and contains behaviour related use cases. Step Implementation file for the scenarios defined in the feature file. Environment Setup files where, the pre/post conditions are to be executed prior and post the steps, features, scenarios, and so on. Feature File A feature file should be within a folder called as the features. Also, there should be a sub-directory steps within the features directory. Launching Feature file We can launch the feature file with various command line arguments. These are explained below − If no information is available, all the feature files within the features directory shall be loaded for execution in Behave. If the path of the features directory is provided, then it is mandatory to have at least one feature file (with .feature extension) and a sub-directory named steps within the features directory. Also, if the environment.py is present, it should be within the directory that has the steps directory and not within the steps directory. If the path to a feature file is provided, then it instructs Behave to search for it. To get the corresponding steps directory for that feature file, the parent directory is searched. If not found in the current parent directory, then it searches its parents. This shall continue until it reaches the file system root. Also, if the environment.py is present, it should be within the directory that has the steps directory and not within the steps directory. Print Page Previous Next Advertisements ”;