Note:

If you want to create a new page for developers, you should create it on the Moodle Developer Resource site.

Running acceptance test: Difference between revisions

From MoodleDocs
m (Protected "Running acceptance test": Developer Docs Migration ([Edit=Allow only administrators] (indefinite)))
 
(56 intermediate revisions by 21 users not shown)
Line 1: Line 1:
== Short version ==
{{Template:Migrated|newDocId=/general/development/tools/behat/running}}
Moodle uses [https://behat.org Behat], a php framework for automated functional testing, as part of a suite of testing tools.


...or how I got it to work on Ubuntu and some of the problems encountered.  
Behat takes a set of Features, Scenarios, and Steps, and uses these to step through actions and test results using a real web browser. This is possible thanks to a protocol implemented in most modern web browsers called Webdriver.


You need a bunch of browsers and terminal windows open to do this.
This documentation covers how to run Behat tests within Moodle, including requirements, setup, useful tips and tricks, and basic troubleshooting.
== Requirements ==
# Any recent OS with [[Releases|supported version of Moodle]] installed
# A recent browser (We support Firefox, Chrome as standard, but other browsers are possible)
# The WebDriver implementation for your browser
# A recent version of Selenium (Optional, but recommended)
# A recent Java Runtime Environment (Required if using Selenium)
=== Recommended extras ===
Some extra software is also recommended for testing with Behat.
==== Pre-configured browser profiles: moodle-browser-config ====
Available for [[Releases|all supported versions of Moodle]], the [https://github.com/andrewnicols/moodle-browser-config moodle-browser-config] is a recommended inclusion for Behat. This configuration tooling provides a range of standard browser profiles for testing.


==== 1. Background ====
Note: In future, the <tt>moodle-browser-config</tt> tool may be included as composer dependency to Moodle but this is currently not the case.
===== Installation =====
# Check out the moodle-browser-config repository:
    // Change directory to your git root, for example:
    $ cd ~/git
    // Clone the moodle-browser-config repository
    git clone https://github.com/andrewnicols/moodle-browser-config
# Open your Moodle installation's <tt>config.php</tt> in your preferred editor, and require the tool's init.php:
    require_once('/path/to/your/git/dir/moodle-browser-config/init.php');
===== Provided profiles =====
The full list of profiles which are included with <tt>moodle-browser-config</tt> are provided in its [https://github.com/andrewnicols/moodle-browser-config own documentation].


# I am using the desktop version of Ubuntu 17.04 so there are no issues about running this software in headless mode. Running in headless mode is not considered in this section.
The following is a summary of the profiles that most users may be interested in.
# Moodle is version 3.3 and is a fully installed and working version using the 'standard' Ubuntu LAMP stack.


==== 2. Set up Selenium ====
You can also provide your own custom profiles, including for remote services such as Browserstack, and Saucelabs, as
well as for other browsers supporting the W3C Webdriver specification.


# Download the Selenium Standalone Server from [http://www.seleniumhq.org/download/ http://www.seleniumhq.org/download/]. It's a single JAR file, put it anywhere handy.
Please note that <tt>Safari</tt> and <tt>Safaridriver</tt> are not currently supported as they do not meet the W3C WebDriver specification.
# Download the Chrome driver from [https://sites.google.com/a/chromium.org/chromedriver/ https://sites.google.com/a/chromium.org/chromedriver/] (Forget trying to use Firefox, the latest version is not compatible)
{| class="wikitable" border="1"
# Unzip the driver (it's a single file) and copy to /usr/local/bin (should work anywhere on the path)
|-
# If not installed already, '<tt>sudo apt install default-jre</tt>'
! Profile name
# Start Selenium - '<tt>java -jar /path/to/your/selenium/server/selenium-server-standalone-N.NN.N.jar -port 4444</tt>'
! Description
# check it works, access 'localhost:4444/wd/hub/' in your browser and check you can create a new Chrome session.
! Uses Selenium?
! Displays GUI?
|-
| firefox
| Use Firefox via Selenium
| Yes
| Yes
|-
| headlessfirefox
| Use Firefox via Selenium, without displaying the GUI
| Yes
| No
|-
| geckodriver
| Use Firefox with Geckodriver directly
| No
| Yes
|-
| headlessgeckodriver
| Use Firefox with Geckodriver directly, without displaying the GUI
| No
| No
|-
| chrome
| Use Chrome via Selenium
| Yes
| Yes
|-
| headlesschrome
| Use Chrome via Selenium, without displaying the GUI
| Yes
| No
|-
| chromedriver
| Use Chrome with Chromedriver directly
| No
| Yes
|-
| headlesschromedriver
| Use Chrome with Chromedriver directly, without displaying the GUI
| No
| No
|-
| edge
| Use Edge via Selenium
| Yes
| Yes
|-
| headlessedge
| Use Edge via Selenium, without displaying the GUI
| Yes
| No
|-
| edgedriver
| Use Edge with Edgedriver directly
| No
| Yes
|-
| headlessedgedriver
| Use Edge with Edgedriver directly, without displaying the GUI
| No
| No
|}
==== chromedriver-wrapper ====
When using Google Chrome, you must use the correct version of the <tt>chromedriver</tt> browser driver for the version of Chrome that you use.


If running headless or the above doesn't work ("Selenium server is not running). Try the following
Since Google Chrome automatically updates on a regular basis, you will need to regularly upgrade your driver to match the version of Chrome that you are using.
# Run '<tt>Xvfb -ac :99 -screen 0 1280x1024x16 &</tt>'
# Then immediately, '<tt>export DISPLAY=:99</tt>'
# The run the Selenium command as above


==== 3. Set up Moodle ====
To make this easier, a <tt>chromedriver-wrapper</tt> utility has been written. This inspects the version of Chrome that is in your path, and downloads the correct version of <tt>chromedriver</tt> for that version, before starting it.


# Create a new 'dataroot' area for files especially for behat adjusting permissions accordingly.  
Installation instructinos can be found at [https://github.com/andrewnicols/chromedriver-wrapper https://github.com/andrewnicols/chromedriver-wrapper].
# If not there already, add Section 11 from config-dist.php to your config.php file and review the settings.  
== Getting started (basic) ==
# $CFG->behat_wwwroot needs to point to your Moodle site yet be different from the 'normal' wwwroot (e.g. if you used localhost for wwwroot use 127.0.0.1 for the behat_wwwroot). Whatever you choose, make sure it works.
This is a quick walk through to get Behat running for the first time.
# $CFG->behat_dataroot should point to the directory you created above
=== Setting up ===
# $CFG->behat_prefix should be fine.  
There are a number of ways of configuring Behat on Moodle. This is one of the simplest.
# Set up $CFG->behat_profiles to select Chrome as the browser...


    $CFG->behat_profiles = [
These notes assume that you have already installed a supported Java Runtime Environment, and the [[Running_acceptance_test#Pre-configured_browser_profiles:_moodle-browser-config]] tool.
        'default' => [
==== Setting up Selenium ====
            'browser' => 'chrome',
Generally we recommend use of Selenium, though this is not a fixed requirement. You can use the browser's driver implementation directly but this is harder to setup for the first time.
                'extensions' => [
 
                    'Behat\MinkExtension' => [
Selenium is written in Java, and requires a recent version of the JRE to run. Please ensure that you have this installed prior to starting.
                        'selenium2' => [
 
                            'browser' => 'chrome',
Since Moodle 3.9.5 / 3.10.2 / 3.11.0 Moodle will work with any modern version of Selenium. At time of writing that is <tt>3.141.59</tt>, and 4.1.0. '''Note:''' There appears to be an issue with the version 4 jars - particually in 4.1.0 that generates a '''"Could not open connection: Capability value must be set”''' error which appears to be an issue between Selenium and the MInkExtension for JavaScript tests - see https://githubmemory.com/repo/Behat/MinkExtension/activity for more information. The quick work around is to use the earlier version (3.141.59).
                        ]
# Download the Selenium Server (Grid) from [https://www.selenium.dev/downloads/ https://www.selenium.dev/downloads/]. This is a single JAR file, put it anywhere handy.
                    ]
# Start Selenium
                ]
    # Version 3.141.59:
            ]
    $ java -jar selenium-server-standalone-3.141.59.jar
        ];
   
    # Version 4.0.0 and later:
    $ java -jar selenium-server-4.0.0-beta-3.jar standalone
You can optionally specify a number of settings, depending on the version of Selenium that you are using, including the port to run on.
See the help for the version of Selenium that you are using.
==== Setting up your browsers ====
Selenium is just an intelligient wrapper to start, and manage your browser sessions. It doesn't actually include any web browsers itself.
 
Moodle HQ run all behat tests against both Firefox and Chrome multiple times per day. Other combinations, including Microsoft Edge, are also supported.
 
To use Behat, you will need a recent version of your preferred browser, as well as a <tt>driver</tt> for that browser. The driver is responsible for communication between Selenium (or Moodle directly) and the browser.
 
Both the browser, and its driver, must be placed inside your <tt>$PATH</tt> - this may be somewhere like <tt>/usr/bin</tt>, <tt>/usr/local/bin</tt>, or perhaps a user bin directory like <tt>~/bin</tt> which is present in your <tt>$PATH</tt>
===== Chrome =====
You can download Google Chrome from [https://www.google.com.au/chrome https://www.google.com.au/chrome].


==== 4. Configure Behat for Moodle ====
You will need the [https://chromedriver.chromium.org/downloads correct version of the chromedriver] as per the
documentation. Alternatively you can make use of the [[Running_acceptance_test#chromedriver-wrapper|chromedriver-wrapper utility]] noted in the Recommended extras sections.


# Run '<tt>php admin/tool/behat/cli/init.php</tt>' (from the root of your Moodle install). This installs all the required software and creates the test version of Moodle.  
Either the <tt>chromedriver</tt> binary must be in a directory in your <tt>$PATH</tt>, or the <tt>chromedriver-wrapper/bin</tt> folder must be in your <tt>$PATH</tt>.
===== Firefox =====
You can download Mozilla Firefox from [https://www.mozilla.org/en-US/firefox/new/ https://www.mozilla.org/en-US/firefox/new/].


==== 5. Run Behat tests ====
You will need the [https://github.com/mozilla/geckodriver/releases correct version of geckodriver] as per the [https://firefox-source-docs.mozilla.org/testing/geckodriver/Support.html documentation].


# Run '<tt>php admin/tool/behat/cli/run.php</tt>' (if you don't want to run all the tests add '<tt>--tag="@something"</tt>' where the @something refers to the tags at the top of most feature files)
The <tt>geckodriver</tt> binary must be in a directory in your <tt>$PATH</tt>.
# After some initial setup dots should start to go by. It's a while before Selenium is first accessed. On the Linux desktop a new Chrome window appears and the testing process 'remote control' starts (hopefully!)
==== Set up Moodle ====
# Create a new 'dataroot' area for files especially for behat
# Set the following in your Moodle <tt>config.php</tt>:
    $CFG->behat_dataroot = '/path/to/the/dataroot/you/created';
    $CFG->behat_wwwroot = 'http://127.0.0.1/path/to/your/site';
    $CFG->behat_prefix = 'beh_';
# We recommend that you also include the <tt>behat-browser-config</tt> if you have not done so already.
    require_once('/path/to/moodle-browser-config/init.php');
===== Notes about the behat_wwwroot =====
You will need to set the <tt>behat_wwwroot</tt> to your Moodle site, but it ''must'' use a different value to your <tt>$CFG->wwwroot</tt>.


== Prerequisite ==
One common way to do this is to use <tt>127.0.0.1</tt> for behat, but <tt>localhost</tt> for standard use. Alternatively you can add an additional hostname in your <tt>/etc/hosts</tt> file and use this instead.
Before initializing acceptance test environment for running behat, you should ensure:
# [[Acceptance_testing#Requirements Meet min. system requirements for running tests]]
# [[Acceptance_testing#Installation Have set min. config variable in config.php for behat]]
# [[Acceptance_testing#Installation Downloaded composer dependencies]]


== Overview ==
If you use Docker, then you may be able to use <tt>host.docker.internal</tt> where your site is hosted on the docker host
Acceptance tests (also known as behat), use [http://www.seleniumhq.org/download/ Selenium server] and can be run as:
==== Configure Behat for Moodle ====
# '''Single run:''' In single run, only one behat run is executed. So all features are executed in this single run.
After setting your configuration, you can simply initialise behat:
# '''Parallel runs:''' (Since Moodle 3.0) Parallel runs allow dev's to execute multiple behat runs together. This was introduced to get acceptance tests results faster. To achieve this:
    $ php admin/tool/behat/cli/init.php
#* Features are divided between multiple behat runs
This will install all required Composer dependencies, install a new Moodle site, and put configuration in place
#* Symlinks behatrun{x} (x being the run process number), are created pointing to moodle directory, so site for run 1 is accessible via https://localhost/moodle/behatrun1
#* Process number is included as suffix to $CFG->behat_prefix.
#* Process number is suffixed to $CFG->behat_dataroot.


== Step 1: Initialise acceptance test environment ==
When it finishes it will give advice on how to run Behat.
Before running acceptance tests, environment needs to be initialised for acceptance testing.
==== Run Behat tests ====
Before running behat, ensure that your Selenium server is running.


=== Single run ===
The easiest way to run behat, and test that everything works is by simply running it using the command provided when you
For initialising acceptance tests for single run, above command is sufficient.
initialised Behat. If you didn't make a note of it, you can just run the initialisation again.
<code>
    $ php admin/tool/behat/cli/init.php
php admin/tool/behat/cli/init.php
This will give you a command which you can then run. This command will run every behat scenario, which will take a considerable amount of time. This command will look a bit like this:
</code>
    $ vendor/bin/behat --config /Users/nicols/Sites/moodles/sm/moodledata_behat/behatrun/behat/behat.yml
To make this more useful you an combine it with flags, for example to only run certain <tt>tags</tt> or for a specific Behat Feature file, or Scenario.


=== Parallel runs ===
To run all features/scenarios which are tagged with <tt>mod_forum</tt>:
For initialising acceptance tests for parallel runs, you can use one of the following options
    $ vendor/bin/behat --config /Users/nicols/Sites/moodles/sm/moodledata_behat/behatrun/behat/behat.yml --tags=@mod_forum
# '''-j or --parallel''' (required) Number of parallel behat run to initialise
To run one specific feature file:
# '''-m or --maxruns'''  (optional) Max parallel site which should be initialised at one time. If your system is slow, then you can initialise sites in chucks.
    $ vendor/bin/behat --config /Users/nicols/Sites/moodles/sm/moodledata_behat/behatrun/behat/behat.yml `pwd`/mod/forum/tests/behat/private_replies.feature
# '''--fromrun''' (optional) Initialise site to run specified run from. Used for running acceptance tests on different vms
To run one specific scenario within a feature file:
# '''--torun''' (optional) Initialise site to run specified run till. Used for running acceptance tests on different vms
    # To run the Scenario on line 38 of the file:
# '''-o or --optimize-runs''' (optional) This option will split features with specified tags in all parallel runs, so they are executed first when parallel run gets executed.
    $ vendor/bin/behat --config /Users/nicols/Sites/moodles/sm/moodledata_behat/behatrun/behat/behat.yml `pwd`/mod/forum/tests/behat/private_replies.feature:38
# '''-a or --add-core-features-to-theme''' (optional) Since Moodle 3.2. Use this option to add all core features to specified themes (comma separated list of themes)
To run one specific scenario by name:
<code>
    $ vendor/bin/behat --config /Users/nicols/Sites/moodles/sm/moodledata_behat/behatrun/behat/behat.yml --name="As a teacher I can see my own response"
// Below command will initialise moodle to run 2 parallel tests.
See the upstream documentation on Behat, and Gherkin filters for more information.
php admin/tool/behat/cli/init.php --parallel=2
===== Running using a different browser =====
</code>
The default browser in Behat is <tt>Firefox</tt>. To specify a different browser profile, you can add the <tt>--profile</tt> argument. For example, to use Chrome in Headless mode:
    $ vendor/bin/behat --config /Users/nicols/Sites/moodles/sm/moodledata_behat/behatrun/behat/behat.yml --profile=headlesschrome
If you are using the <tt>moodle-browser-config</tt> utility, then you can use any profile listed in [[Running_acceptance_test#Pre-configured_browser_profiles:_moodle-browser-config|moodle-browser-config]]. Otherwise you can write your own browser profile configuration.
=== Advanced testing ===
==== Run tests without Selenium (chromedriver, geckodriver) ====
Historically, Behat required Selenium server, however browsers now make use of their own automation layer. For example, Firefox uses <tt>Geckodriver</tt> and Chrome uses <tt>Chromedriver</tt>. As a result the use of Selenium itself is now optional.


== Step 2: Running acceptance test environment ==
The moodle-browser-config tool includes standard profiles to use these drivers directly and without the use of Selenium.
=== Single run ===
Run either of the following commands. For more options '''vendor/bin/behat --help''' or http://docs.behat.org/guides/6.cli.html
<code>
vendor/bin/behat --config /path/to/your/CFG_behat_dataroot/behatrun/behat/behat.yml
</code>
<code>
php admin/tool/behat/cli/run.php
</code>


=== Parallel runs ===
To use the drivers directly, you must run the driver itself, for example to run <tt>chromedriver</tt>:
For running parallel runs, use following command
    $ chromedriver
<code>
To run <tt>geckodriver</tt>:
php admin/tool/behat/cli/run.php
    $ geckodriver
</code>
Note: geckodriver runs on port 4444 by default. You cannot geckodriver at the same time as selenium.
Following optional options are available for custom run:
# '''--feature''' Only execute specified feature file (Absolute path of feature file).
# '''--suite''' Features for specified theme will be executed.
# '''--replace''' Replace args string with run process number, useful for output and reruns.
# '''--fromrun''' Execute run starting from (Used for parallel runs on different vms)
# '''--torun''' Execute run till (Used for parallel runs on different vms)
# '''-a or --add-core-features-to-theme''' (optional) Since Moodle 3.2. Use this option to add all core features to specified theme's (comma separated list)
# Behat options can be passed for filtering features/scenarios:
#* In case you don't want to run Javascript tests, use the Behat tags option to skip them, '''--tags="~@javascript"'''
#* In case you want to run specific scenario, use the Behat name option to run it, '''--name="Filter user accounts by role and cohort"'''
#* In case you want to run specific feature file, use the Behat feature option to run it, '''--feature="/PATH/TO/MOODLE/admin/tests/behat/filter_users.feature"'''


=== Common options for running tests ===
After starting your preferred browser, you can then run behat and specify an alternative profile, for example:
==== Tests filters ====
    $ vendor/bin/behat --config /Users/nicols/Sites/moodles/sm/moodledata_behat/behatrun/behat/behat.yml --profile=geckodriver
With the '''--tags''' or the '''-name''' Behat options you can filter which tests are going to run or which ones are going to be skipped. There are a few tags that you might be interested in:
==== Headless browsers ====
* '''@javascript''': All the tests that runs in a browser using Javascript; they require Selenium to be running, otherwise an exception will be thrown.
There are a number of reasons that you may prefer to use a headless browser. It can be particularly helpful if you are running the tests on a remote system, for example over SSH, or if you do not want to be interrupted by browsers popping up on your machine.
* '''@_file_upload''': All the tests that involves file uploading or any OS feature that is not 100% part of the browser. They should only be executed when Selenium is running in the same machine where the tests are running.
* '''@_alert''': All the tests that involves Javascript dialogs (alerts, confirms...) are using a feature that is OS-dependant and out of the browser scope, so they should be tag appropriately as not all browsers manage them properly.
* '''@_switch_window''': All the tests that are using the '''I switch to "NAME" window''' step should be tagged as not all browsers manage them properly.
* '''@_switch_iframe''': All the tests that are using the '''I switch to "NAME" window''' steps should be tagged as it is an advanced feature and some browsers may have problems dealing with them
* '''@_cross_browser''': All the tests that should run against multiple combinations of browsers + OS in a regular basis. The features that are sensitive to different combinations of OS and browsers should be tagges as @_cross_browser.
* '''@componentname''': Moodle features uses the [https://docs.moodle.org/dev/Frankenstyle Frankenstyle] component name to tag the features according to the Moodle subsystem they belong to.


==== Output formats ====
The following headless profiles are some of those provided in the moodle-browser-config tool as standard:
Since Moodle 3.1 option for output is:
# <tt>headlessfirefox</tt> Use Firefox via Selenium, without displaying the GUI
<code>
# <tt>headlessgeckodriver</tt> Use Firefox with Geckodriver directly, without displaying the GUI
--format=pretty --out=/path/to/pretty.txt --format=moodle_progress --out=std
# <tt>headlesschrome</tt> Use Chrome via Selenium, without displaying the GUI
</code>
# <tt>headlesschromedriver</tt> Use Chrome with Chromedriver directly, without displaying the GUI
Before Moodle 3.1 option for output was:
These can be provided to the <tt>--profile</tt> argument to behat:
<code>
    $ vendor/bin/behat --config /Users/nicols/Sites/moodles/sm/moodledata_behat/behatrun/behat/behat.yml --profile=headlesschrome
--format='moodle_progress,pretty' --out=',/path/to/pretty.txt'
==== Parallel runs ====
</code>
Out-of-the-box, Moodle will configure Behat to run a single Moodle installation with all tests run in series. This is great for developer use where you are running a single test. or a small suite of tests. However this can be quite slow. A lot of time is spent waiting in Behat for things to happen. This may be for a page to load, for additional content to load, or even explicit waits because some interactions must be deliberately slowed down. As a result, a system running behat will not have a particularly high load most of the time.
Following output formats are supported:
# '''progress''': Prints one character per step.
# '''pretty''': Prints the feature as is.
# '''junit''': Outputs the failures in JUnit compatible files.
# '''moodle_progress''': Prints Moodle branch information and dots for each step.
# '''moodle_list''': List all scenarios.
# '''moodle_stepcount''': List all features with total steps in each feature file. Used for parallel run.
# '''moodle_screenshot''': (since Moodle 3.1) Take screenshot and core dump of each step. With following options you can dump either or both.
## --format-settings '{"formats": "image"}'**: will dump image only
## --format-settings '{"formats": "html"}'**: will dump html only.
## --format-settings '{"formats": "html,image"}'**: will dump both.
## --format-settings '{"formats": "html", "dir_permissions": "0777"}'**
If you want to see the failures immediately (rather than waiting ~3 hours for all the tests to finish) then either use the -v option to output a bit more information, or change the output format using --format. Format 'pretty' ('''-f pretty''') is sufficient for most cases, as it outputs each step outcomes in the command line making easier to see the progress.


== Advance usage ==
If you want to run a large suite of tests then it is possible to take advantage of the relatively low resource consumption by running several behat runners in parallel. This is commonly referred to as a '''Parallel run'''.
=== Rerun failed scenarios ===
With slow systems or parallel run you might see some random failures, to rerun only failed scenarios (to eliminate random failures), use --rerun option
# '''Single run:''' --run="absolute_path_to_empty_file" (Behat will record failed scenarios in this file, and when run again only failed scenarios will be run)
# '''Parallel run:''' --rerun="absolute_path_to_empty_file_{runprocess}.txt --replace="{runprocess}" ({runprocess} will be replaced with the process number for recording fails in the specific run process).
'''Since Moodle 3.1 --rerun option don't accept any value, as it is handled internally by behat'''


=== Running behat with specified theme (Since Moodle 3.2) ===
A parallel run of behat takes the same codebase and creates several installations rather than just a single Moodle installation. The behat Feature files are then grouped and allocated between each of the separate installations.
You can run behat with any theme installed. To execute behat with specified theme use '''--suite={THEME_NAME}''' option, while running behat. By default the features in theme behat folder will be executed for the suite. But if you want to run all core features with the specific theme then initialise acceptance test with -a option. For example, '''-a {THEME_NAME}'''
Also if you want a specific theme for your behat tests, use the $CFG->theme variable to set the theme.


==== Override behat core context for theme suite ====
To support this, each of the parallels runs needs its own:
To override behat step definitions so as to run behat with specified theme, you should create a contexts within '''/theme/{MYTHEME}/tests/behat/''' with prefix behat_theme_{MYTHEME}_ and suffixed with the context being overridden. For example, if you want to override behat_mod_forum context, then you should create a class /theme/{MYTHEME}/tests/behat/mod_forum/behat_theme_{MYTHEME}_behat_mod_forum.php
* <tt>behat_wwwroot</tt>
* <tt>behat_dataroot</tt>
* database
Rather than using an entirely separate database, the same database is actually used, but a different <tt>behat_prefix</tt> is used to prefix the table names in the database differently.
===== Installation =====
The Behat initialisation command is responsible for preparing Moodle to run a standard run. You'll have used this before when installing for a standard run:
    $ php admin/tool/behat/cli/init.php
The same command can be used to prepare Moodle for a parallel run by specifying the <tt>--parallel</tt> or <tt>-j</tt> parameter:
    // Below command will initialise moodle to run 3 parallel tests.
    $ php admin/tool/behat/cli/init.php --parallel=3
This can be combined with the <tt>--add-core-features-to-theme</tt> or <tt>-a</tt> flag to prepare Behat to run with all installed themes.


==== Blacklist behat context or features to run in theme suite ====
A number of advanced options are also available but you are unlikely to need these:
To blacklist contexts/ features to be executed by theme suite you should create a /theme/{MYTHEME}/tests/behat/blacklist.json file with following format. Following will not use step_definitions from  behat_grade and behat_navigation while running theme suite. Also, scenarios in auth/tests/behat/login.feature and grade/tests/behat/grade_hidden_items.feature won't be executed with theme suite.
# <tt>-m=<number></tt> or <tt>--maxruns=<number></tt> Max parallel site which should be initialised at one time. If your system is slow, then you can initialise sites in chucks.
<code>
# <tt>--fromrun=<number></tt> Initialise site to run specified run from. Used for running acceptance tests on different vms
{
# <tt>--torun=<number></tt> Initialise site to run specified run till. Used for running acceptance tests on different vms
  "contexts": [
# <tt>-o</tt> or <tt>--optimize-runs</tt> This option will split features with specified tags in all parallel runs, so they are executed first when parallel run gets executed.
    "behat_grade",
You can view details of all of these using the <tt>--help</tt> flag to <tt>admin/tool/behat/cli/init.php</tt>
    "behat_navigation",
===== Running Parallel tests =====
  ],
You can use the Moodle behat runner to run all tests, including Standard runs. It is an intelligient wrapper around the standard <tt>./vendor/bin/behat</tt> command which specifies the configuration file, and other required features.
  "features": [
    $ php admin/tool/behat/cli/run.php
    "auth/tests/behat/login.feature",
Many of the standard options and parameters that can be passed to <tt>./vendor/bin/behat</tt> can also be passed to the Moodle runner, for example:
    "grade/tests/behat/grade_hidden_items.feature",
# <tt>--tags</tt> Run tests which match the specified tags
  ]
# <tt>--name="Scenario name"</tt> Run a test matching the supplied scenario name
}
# <tt>--feature="/path/to/test.feature"</tt> Run a specific feature file.
</code>
# <tt>--suite</tt> Features for specified theme will be executed.
==== Override core behat selectors ====
The runner also includes a number of custom parameters relating to parallel runs:
To override behat selectors in specific theme, you should create a class behat_theme_{MYTHEME}_behat_selectors in /theme/{MYTHEME}/tests/behat/behat_theme_{MYTHEME}_behat_selectors.php extending behat_selectors.
# <tt>--replace</tt> Replace args string with run process number, useful for output and reruns.
# <tt>--fromrun</tt> Execute run starting from (Used for parallel runs on different vms)
# <tt>--torun</tt> Execute run till (Used for parallel runs on different vms)
The <tt>--replace</tt> feature is particularly useful and can be used to replace a string in the command with the run number. This is useful when specifying output formats, and rerun files as noted below.


=== Use php built in web server ===
You can use php built-in-web server for executing behat runs. To do so:
# Open a command line interface and '''cd /to/your/moodle/dirroot'''
# '''php -S localhost:8000''' (This is the test site URL that moodle uses by default, if you want to use another one you can override it in config.php with $CFG->behat_wwwroot attribute; more info in https://docs.moodle.org/dev/Acceptance_testing#Advanced_usage or config-dist.php)
# Update $CFG->behat_wwwroot = localhost:8000; in config.php


=== Define custom options for parallel runs ===
The following example demonstrates how Behat might be initialised with three parallel runs, to run on all themes:
    $ php admin/tool/behat/cli/init.php --parallel=3 --add-core-features-to-theme
And then to run all tests matching the <tt>@tool_myplugin</tt> tag, against the <tt>classic</tt> theme:
    $ php admin/tool/behat/cli/run.php --tags="@tool_myplugin" --suite="classic"
===== Custom parameters for parallel runs =====
You can set following custom config options for parallel runs via $CFG->behat_parallel_run. It's an array of options where 1st array is for 1st run and so on.
You can set following custom config options for parallel runs via $CFG->behat_parallel_run. It's an array of options where 1st array is for 1st run and so on.
<code>
    $CFG->behat_parallel_run = [
      array (
        [
           'dbtype' => 'mysqli',
           'dbtype' => 'mysqli',
           'dblibrary' => 'native',
           'dblibrary' => 'native',
Line 204: Line 278:
           'behat_wwwroot' => 'http://127.0.0.1/moodle',
           'behat_wwwroot' => 'http://127.0.0.1/moodle',
           'behat_dataroot' => '/home/example/bht_moodledata'
           'behat_dataroot' => '/home/example/bht_moodledata'
       )
       ],
</code>
      // ...
    ],
To set different selenium servers for parallel runs, you can use following. NOTE: Running parallel (headless) runs on different selenium servers avoid random focus failures.
    $CFG->behat_parallel_run = [
        ['wd_host' => 'http://127.0.0.1:4444/wd/hub'],
        ['wd_host' => 'http://127.0.0.1:4445/wd/hub'],
        ['wd_host' => 'http://127.0.0.1:4446/wd/hub'],
    ];
==== Tests filters ====
With the <tt>--tags</tt> or the <tt>-name</tt> Behat options you can filter which tests are going to run or which ones are going to be skipped. There are a few tags that you might be interested in:
* <tt>@javascript</tt>: All the tests that runs in a browser using Javascript; they require Selenium or the browser's own automation layer, as per [[Running acceptance test#Run%20tests%20without%20Selenium%20.28chromedriver.2C%20geckodriver.29|Running acceptance test#Run tests without Selenium .28chromedriver.2C geckodriver.29,]] to be running, otherwise an exception will be thrown.
* <tt>@_file_upload</tt>: All the tests that involves file uploading or any OS feature that is not 100% part of the browser. They should only be executed when Selenium is running in the same machine where the tests are running.
* <tt>@_alert</tt>: All the tests that involves Javascript dialogs (alerts, confirms...) are using a feature that is OS-dependant and out of the browser scope, so they should be tag appropriately as not all browsers manage them properly.
* <tt>@_switch_window</tt>: All the tests that are using the <tt>I switch to "NAME" window</tt> step should be tagged as not all browsers manage them properly.
* <tt>@_switch_iframe</tt>: All the tests that are using the <tt>I switch to "NAME" iframe</tt> steps should be tagged as it is an advanced feature and some browsers may have problems dealing with them
* <tt>@_cross_browser</tt>: All the tests that should run against multiple combinations of browsers + OS in a regular basis. The features that are sensitive to different combinations of OS and browsers should be tagges as @_cross_browser.
* <tt>@componentname</tt>: Moodle features uses the [https://docs.moodle.org/dev/Frankenstyle Frankenstyle] component name to tag the features according to the Moodle subsystem they belong to.
==== Output formats ====
Behat is able to output in a number of different formats, and to different locations as required.
 
This can be achieved by specifying the <tt>--format</tt>, and <tt>--out</tt> parameters when running behat, for example:
    // Run behat, using the 'pretty' format and outputting the value to /tmp/pretty.txt
    $ vendor/bin/behat --config /Users/nicols/Sites/moodles/sm/moodledata_behat/behatrun/behat/behat.yml \
        --format=pretty --out=/tmp/pretty.txt
It is also possible to output to multiple formats simultaneously by repeating the arguments, for example:
 
Since Moodle 3.1 option for output is:
    $ vendor/bin/behat --config /Users/nicols/Sites/moodles/sm/moodledata_behat/behatrun/behat/behat.yml \
        --format=pretty --out=/tmp/pretty.txt \
        --format=moodle_progress --out=std
The following output formats are supported:
# <tt>progress</tt>: Prints one character per step.
# <tt>pretty</tt>: Prints the feature as is.
# <tt>junit</tt>: Outputs the failures in JUnit compatible files.
# <tt>moodle_progress</tt>: Prints Moodle branch information and dots for each step.
# <tt>moodle_list</tt>: List all scenarios.
# <tt>moodle_stepcount</tt>: List all features with total steps in each feature file. Used for parallel run.
# <tt>moodle_screenshot</tt>: Take screenshot and core dump of each step. With following options you can dump either or both.
## <tt>--format-settings '{"formats": "image"}'</tt>: will dump image only
## <tt>--format-settings '{"formats": "html"}'</tt>: will dump html only.
## <tt>--format-settings '{"formats": "html,image"}'</tt>: will dump both.
## <tt>--format-settings '{"formats": "html", "dir_permissions": "0777"}'</tt>
Note: If you want to see the failures immediately (rather than waiting ~3 hours for all the tests to finish) then either use the -v option to output a bit more information, or change the output format using --format. Format 'pretty' ('''-f pretty''') is sufficient for most cases, as it outputs each step outcomes in the command line making easier to see the progress.


To set different selenium servers for parallel runs, you can use following. NOTE: Running parallel (headless) runs on different selenium servers avoid random focus failures.
When working with parallel runs, you may wish to have an output for each run. If you were to specify a standard path for this then each of the parallel runs would overwrite the others file. The <tt>--replace</tt> option allows this to be handled:
<code>
     $ admin/tool/behat/cli/run.php \
     $CFG->behat_parallel_run = array (
        --replace="{runprocess}" \
         array ('wd_host' => 'http://127.0.0.1:4444/wd/hub'),
        --format=pretty --out=/tmp/pretty_{runprocess}.txt \
         array ('wd_host' => 'http://127.0.0.1:4445/wd/hub'),
         --format=moodle_progress --out=std
         array ('wd_host' => 'http://127.0.0.1:4446/wd/hub'),
In this example, the <tt>--replace</tt> argument is provided with a value of <tt>{runprocess}</tt>. Anywhere that <tt>{runprocess}</tt> appears in the command it will be replaced with the run number. The above command will generate a set of commands like:
    );
    $ vendor/bin/behat --config /Users/nicols/Sites/moodles/sm/moodledata_behat/behatrun1/behat/behat.yml \
</code>
         --format=pretty --out=/tmp/pretty_1.txt \
        --format=moodle_progress --out=std
 
    $ vendor/bin/behat --config /Users/nicols/Sites/moodles/sm/moodledata_behat/behatrun2/behat/behat.yml \
        --format=pretty --out=/tmp/pretty_2.txt \
        --format=moodle_progress --out=std
 
    $ vendor/bin/behat --config /Users/nicols/Sites/moodles/sm/moodledata_behat/behatrun3/behat/behat.yml \
         --format=pretty --out=/tmp/pretty_3.txt \
        --format=moodle_progress --out=std
==== Rerun failed scenarios ====
With slow systems or parallel run you may experience see some random failures. These may happen when your system is too slow, when it is too fast, or where a page depends on external dependencies.
 
To help with this it is possible to rerun any failed scenarios using the <tt>--rerun</tt> option to Behat.
 
The following example runs Behat with the rerun option:
    $ vendor/bin/behat --config /Users/nicols/Sites/moodles/sm/moodledata_behat/behatrun/behat/behat.yml \
        --format=pretty --out=/tmp/pretty.txt \
        --format=moodle_progress --out=std \
        --rerun
If any single test fails then the command will return a non-zero exit code. Running the same command again will mean that only failed scenarios are run.


=== Running acceptance tests with different browser ===
For a parallel run it can be called as follows:
By default behat will run with Firefox browser through Selenium. By adding the following code to your config.php you can change the selected browser that is run when behat is invoked.  You will need to run php admin/tool/behat/cli/init.php for changes to take effect. Then use --profile='chrome'.
    $ admin/tool/behat/cli/run.php \
        --replace="{runprocess}" \
        --format=pretty --out=/tmp/pretty_{runprocess}.txt \
        --format=moodle_progress --out=std \
        --rerun
The Moodle behat runner also includes an <tt>--auto-rerun</tt> option which will automatically rerun failed scenarios exactly once.
==== Running behat with specified theme ====
Behat can be run with any installed theme, but it must be initialised with the <tt>-a</tt> or <tt>--add-core-features-to-theme</tt> option first.


<code>
After configuring the theme can be specified using the <tt>--suite</tt> parameter.
$CFG->behat_profiles = array(
  'chrome' => array(
      'browser' => 'chrome',
      'tags' => '@javascript',
  )
);
</code>
[[Acceptance_testing/Browsers|More info about alternative browsers]]


=== Start multiple selenium servers ===
Note: The default theme in Moodle (boost) has the suite name <tt>default</tt>.
From command line Start selenium servers at different ports (say 4444, 4445, 4446 for 3 parallel runs)
    // Initialise Behat for all themes:
<code>
    $ php admin/tool/behat/cli/init.php --add-core-features-to-theme
java -jar /path/to/your/selenium/server/selenium-server-standalone-2.NN.N.jar -port 4444 &
   
java -jar /path/to/your/selenium/server/selenium-server-standalone-2.NN.N.jar -port 4445 &
    // Run Behat against all initalised themes:
java -jar /path/to/your/selenium/server/selenium-server-standalone-2.NN.N.jar -port 4446
    $ vendor/bin/behat --config /Users/nicols/Sites/moodles/sm/moodledata_behat/behatrun/behat/behat.yml
</code>
   
    // Run Behat against just the default theme when all themes were initialised:
    $ vendor/bin/behat --config /Users/nicols/Sites/moodles/sm/moodledata_behat/behatrun/behat/behat.yml --suite=default
   
    // Run Behat against just the 'classic' theme when all themes were initialised:
    $ vendor/bin/behat --config /Users/nicols/Sites/moodles/sm/moodledata_behat/behatrun/behat/behat.yml --suite=classic
==== Using Docker to start selenium server ====
There are a wide range of docker images available which contain a browser with Selenium. You will probably be using the official SeleniumHQ images unless you have a specific reason not to.


=== Using Docker to start selenium server ===
The complete list of available SeleniumHQ images is available at [https://hub.docker.com/u/selenium/ https://hub.docker.com/u/selenium/].
==== What is Docker ====
Docker is a app container,  it's a kind of virtual machine, but only for one app, service,  so you can download
a docker image and run a selenium server without worry in how to configure selenium in your machine, one for chrome, others for firefox, you either don't need to install the browsers in your machine
To install docker follow this link; https://docs.docker.com/engine/installation/


==== Selenium docker images ====
Moodle uses the ''standalone'' version and any recent version with version 3.141.59 or higher is supported.
There is many docker images available,  for many browser, the complete list is in https://hub.docker.com/u/selenium/
for moodle you can use standalone version.
You can download  specific selenium version too,  for example,  for firefox,  moodle recommend selenium 2.53.1, see: [https://docs.moodle.org/dev/Acceptance_testing/Browsers/Working_combinations_of_OS%2BBrowser%2Bselenium What version do I need?]


so  the command will be:
For any test which uploads files, for example when interacting with the filepicker, you must also ensure that the Moodle directory is mounted as on your local filesystem.
<code>
docker run -d -p4444:4444 selenium/standalone-firefox:2.53.1-beryllium
</code>
to see all available version click in tags.  For firefox you can find at: https://hub.docker.com/r/selenium/standalone-firefox/tags/


An example usage is:
    $ docker run -d -p 4444:4444 -v `pwd`:`pwd` selenium/standalone-firefox:latest
==== Change config.php file ====
==== Change config.php file ====
In config.php file you must change the $CFG->behat_wwwrootto your network card (NIC) ip address,  you can't use  
In the Moodle <tt>config.php</tt> file you must change the <tt>$CFG->behat_wwwroot</tt> to an address that can be reached from within the docker image.
localhost , 127.0.0.1, ... or selenium docker server  will fail
 
You cannot use <tt>localhost</tt> or <tt>127.0.0.1</tt> as this will be the IP address of the docker container itself.
 
On some more recent versions of Docker you can use <tt>http://host.docker.internal/</tt>, for example if my site is located at <tt>/sm</tt> on my development machine, I can set the following:
    $CFG->behat_wwwroot = 'http://host.docker.internal/sm';
 
 
==== Manually configuring other browsers =====
If you would prefer not to use the <tt>moodle-browser-config</tt> tool but still wish to specify different browsers then you can do so using the <tt>$CFG->behat_profiles</tt> array. Each key/value pair contains a profile name, and the configuration for that profile. For example:
    $CFG->behat_profiles = [
        'chrome' => [
            'browser' => 'chrome',
            'tags' => '@javascript',
        ],
    ];
[[Acceptance_testing/Browsers|More info about alternative browsers]]
== Troubleshooting ==
=== Increasing timeouts ===
You may see errors such as:
<syntaxhighlight lang="php">
Javascript code and/or AJAX requests are not ready after 10 seconds.
There is a Javascript error or the code is extremely slow.
</syntaxhighlight>
Sometimes this indicates a genuine problem with the code, but if you are using a slow computer, it may just mean that your browser did not finish generating parts of the UI before behat tried was finished.


== NOTE ==
If you find that this happens regularly on different scenarios then you may want to increase the timeout:
# Start the Selenium server (in case you want to run tests that involves Javascript)
    $CFG->behat_increasetimeout = 2;
#* (See http://www.installationpage.com/selenium/how-to-run-selenium-headless-firefox-in-ubuntu/ for running 'headless' Firefox and xvfm in a server environment)
This will increase all the timeouts by a factor of 2; if that isn't sufficient, you could use 3.
#* Open another command line interface and '''java -jar /path/to/your/selenium/server/selenium-server-standalone-2.NN.N.jar'''


=== Trouble shooting ===
Increasing timeouts will make tests run a bit slower (because there are points where Behat waits up to a timeout to make sure something doesn't happen) so don't do this unless you need to.
=== New step definitions or features are not executed ===  
 
Note: This is usually an indicator that your development machine is not well tuned. A better option would be to find out where the bottleneck is. This is usually the database configuration.
 
 
=== New step definitions or features are not executed ===
If you are adding new tests or steps definitions update the tests list
If you are adding new tests or steps definitions update the tests list
<code>
<syntaxhighlight lang="php">
php admin/tool/behat/cli/util.php --enable
php admin/tool/behat/cli/util.php --enable
</code>
</syntaxhighlight>
''' For parallel runs, all options for initialising parallel runs are valid '''
''' For parallel runs, all options for initialising parallel runs are valid '''
=== Tests are failing ===
If you followed all the steps and you receive an unknown weird error probably your browser version is not compatible with the Selenium version you are running. Please refer Working combinations to ensure you have correct [[Acceptance_testing/Browsers#Working_combinations_of_OS.2BBrowser.2Bselenium]] of them to run acceptance test.
=== The tests are failing, and the error message is completely useless ===
For example, it just says "Error writing to database" with no stack trace.


=== Tests are failing ===
Add -vv command-line option to get very verbose output.
If you followed all the steps and you receive an unknown weird error probably your system's Firefox version is not compatible with the Selenium version you are running.  Please refer Working combinations to ensure you have correct [[Acceptance_testing/Browsers#Working_combinations_of_OS.2BBrowser.2Bselenium]] of them to run acceptance test.
=== Errors during setup (before test are launched) ===
Typical errors are:
* Behat requirement not satisfied: http://127.0.0.1/m/stable_master is not available, ensure you specified correct url and that the server is set up and started.
* init.php or util.php complain that "Unknown error 1 This is not a behat test site!".  Delete the behat wwwroot (look in config.php for $CFG->behat_dataroot) and drop the behat DB tables (look in config.php for $CFG->behat_prefix).  Then try again.
* Behat is configured but not enabled on this test site.
In order to fix those errors please check that: the behat_dataroot has correct write permissions and that the $CFG->behat* variables are placed before the lib/setup.php include:
require_once(__DIR__ . '/lib/setup.php');
=== Selenium server is not running ===
==== Chrome specific ====
If you are using chrome, you need to ensure that the driver matches the version of the installed chrome browser – which may change on OS updates/upgrades. Moodle or Selenium will not give the appropriate message – see [https://tracker.moodle.org/browse/MDL-67659/ MDL-67659]. One solution is the one suggested in the issue and use Andrew Nicols’ [https://github.com/andrewnicols/chromedriver-wrapper/  Chromedriver Wrapper] which will ensure you have the appropriate driver before running the tests.


=== Disable acceptance test environment ===
if you want to prevent access to test environment
<code>
php admin/tool/behat/cli/util.php --disable
</code>
'''Note that if you have the HTTP_PROXY environment variable set, which you may have had to do to run composer, then you also need to set NO_PROXY=localhost.'''


== External links ==
== External links ==
Line 286: Line 452:
* Docker environment with Behat preconfigured : https://github.com/tobiga/docker_moodle_environment
* Docker environment with Behat preconfigured : https://github.com/tobiga/docker_moodle_environment


[[Category:Quality Assurance]]
 
== Examples ==
=== Quick setup and testing using moodle-docker ===
This is a quick guide to help locally pass tests for your developments, before submitting them:
# Set up a default Moodle install using [https://github.com/moodlehq/moodle-docker moodle-docker], with the database and Moodle version of your choice. See its README for more details. This will start some docker containers.
# Initialize behat to start testing with this command, from the webserver container: <syntaxhighlight lang="php">php admin/tool/behat/cli/init.php</syntaxhighlight>
# Run the behat test of your choice, from the webserver container. For instance: <syntaxhighlight lang="php">vendor/bin/behat --config /var/www/behatdata/behatrun/behat/behat.yml --tags tool_task</syntaxhighlight>
And you'll see something like:
<syntaxhighlight lang="php">
Moodle 4.0dev (Build: 20210507), 0b47ea0a44a092f9000729ca7b15fff23111538b
Php: 7.3.26, mysqli: 5.7.21, OS: Linux 5.4.0-66-generic x86_64
Run optional tests:
 
Accessibility: No
Server OS "Linux", Browser: "firefox"
Started at 09-05-2021, 06:00
...................................................................... 70
...............................
12 scenarios (12 passed)
101 steps (101 passed)
2m53.27s (47.61Mb)
</syntaxhighlight>
== See also ==
* [[Acceptance testing for the mobile app]]
[[Category:Quality Assurance]][[Category:Behat]]
 
 
== Information to re-home ==
==== Override behat core context for theme suite ====
Note: This documentation needs to be rehomed to a location related to writing Behat tests.
 
To override behat step definitions so as to run behat with specified theme, you should create a contexts within '''/theme/{MYTHEME}/tests/behat/''' with prefix behat_theme_{MYTHEME}_ and suffixed with the context being overridden. For example, if you want to override behat_mod_forum context, then you should create a class /theme/{MYTHEME}/tests/behat/mod_forum/behat_theme_{MYTHEME}_behat_mod_forum.php
==== Disable behat context or features to run in theme suite ====
Note: This documentation needs to be rehomed to a location related to writing Behat tests.
 
To disable specific contexts and features from being executed by a specific theme/suite you can create a <tt>/theme/{MYTHEME}/tests/behat/blacklist.json</tt> file with following format.
<syntaxhighlight lang="php">
{
  "contexts": [
    "behat_grade",
    "behat_navigation",
  ],
  "features": [
    "auth/tests/behat/login.feature",
    "grade/tests/behat/grade_hidden_items.feature",
  ]
}
</syntaxhighlight>
The above will:
# disable the use of step_definitions from <tt>behat_grade</tt> and <tt>behat_navigation</tt> while running theme suite; and
# disable running of scenarios in <tt>auth/tests/behat/login.feature</tt> and <tt>grade/tests/behat/grade_hidden_items.feature</tt>.
==== Override core behat selectors ====
Note: This documentation needs to be rehomed to a location related to writing Behat tests.
 
To override behat selectors in specific theme, you should create a class behat_theme_{MYTHEME}_behat_selectors in /theme/{MYTHEME}/tests/behat/behat_theme_{MYTHEME}_behat_selectors.php extending behat_selectors.
==== Write new tests and behat methods ====
Note: This documentation needs to be rehomed to a location related to writing Behat tests.
 
If you want to write tests for your own integration, you can do so by creating new tests with format .feature. Follow instructions in [[Writing_acceptance_tests|this page]] to write new tests.
 
It is also possible to add new steps the moodle behat integration. In order to do so, you will have to create a new .php class with the prefix '''behat_'''. Copy the format from '''lib\behat\behat_base.php''', but set your class to extend the behat_base class instead of the MinkExtension. You can define new behat steps by declaring functions with the appropriate heading.
 
You will not be able to use these steps and features right away. Check [[Running_acceptance_test#New_step_definitions_or_features_are_not_executed|this section]] for instructions on how to update the behat integration.
 
 
For further information on how to create new steps definitions, check [[Acceptance testing/Custom acceptance steps]].

Latest revision as of 05:59, 8 July 2022

Important:

This content of this page has been updated and migrated to the new Moodle Developer Resources. The information contained on the page should no longer be seen up-to-date.

Why not view this page on the new site and help us to migrate more content to the new site!

Moodle uses Behat, a php framework for automated functional testing, as part of a suite of testing tools.

Behat takes a set of Features, Scenarios, and Steps, and uses these to step through actions and test results using a real web browser. This is possible thanks to a protocol implemented in most modern web browsers called Webdriver.

This documentation covers how to run Behat tests within Moodle, including requirements, setup, useful tips and tricks, and basic troubleshooting.

Requirements

  1. Any recent OS with supported version of Moodle installed
  2. A recent browser (We support Firefox, Chrome as standard, but other browsers are possible)
  3. The WebDriver implementation for your browser
  4. A recent version of Selenium (Optional, but recommended)
  5. A recent Java Runtime Environment (Required if using Selenium)

Recommended extras

Some extra software is also recommended for testing with Behat.

Pre-configured browser profiles: moodle-browser-config

Available for all supported versions of Moodle, the moodle-browser-config is a recommended inclusion for Behat. This configuration tooling provides a range of standard browser profiles for testing.

Note: In future, the moodle-browser-config tool may be included as composer dependency to Moodle but this is currently not the case.

Installation
  1. Check out the moodle-browser-config repository:
   // Change directory to your git root, for example:
   $ cd ~/git
   // Clone the moodle-browser-config repository
   git clone https://github.com/andrewnicols/moodle-browser-config
  1. Open your Moodle installation's config.php in your preferred editor, and require the tool's init.php:
   require_once('/path/to/your/git/dir/moodle-browser-config/init.php');
Provided profiles

The full list of profiles which are included with moodle-browser-config are provided in its own documentation.

The following is a summary of the profiles that most users may be interested in.

You can also provide your own custom profiles, including for remote services such as Browserstack, and Saucelabs, as well as for other browsers supporting the W3C Webdriver specification.

Please note that Safari and Safaridriver are not currently supported as they do not meet the W3C WebDriver specification.

Profile name Description Uses Selenium? Displays GUI?
firefox Use Firefox via Selenium Yes Yes
headlessfirefox Use Firefox via Selenium, without displaying the GUI Yes No
geckodriver Use Firefox with Geckodriver directly No Yes
headlessgeckodriver Use Firefox with Geckodriver directly, without displaying the GUI No No
chrome Use Chrome via Selenium Yes Yes
headlesschrome Use Chrome via Selenium, without displaying the GUI Yes No
chromedriver Use Chrome with Chromedriver directly No Yes
headlesschromedriver Use Chrome with Chromedriver directly, without displaying the GUI No No
edge Use Edge via Selenium Yes Yes
headlessedge Use Edge via Selenium, without displaying the GUI Yes No
edgedriver Use Edge with Edgedriver directly No Yes
headlessedgedriver Use Edge with Edgedriver directly, without displaying the GUI No No

chromedriver-wrapper

When using Google Chrome, you must use the correct version of the chromedriver browser driver for the version of Chrome that you use.

Since Google Chrome automatically updates on a regular basis, you will need to regularly upgrade your driver to match the version of Chrome that you are using.

To make this easier, a chromedriver-wrapper utility has been written. This inspects the version of Chrome that is in your path, and downloads the correct version of chromedriver for that version, before starting it.

Installation instructinos can be found at https://github.com/andrewnicols/chromedriver-wrapper.

Getting started (basic)

This is a quick walk through to get Behat running for the first time.

Setting up

There are a number of ways of configuring Behat on Moodle. This is one of the simplest.

These notes assume that you have already installed a supported Java Runtime Environment, and the Running_acceptance_test#Pre-configured_browser_profiles:_moodle-browser-config tool.

Setting up Selenium

Generally we recommend use of Selenium, though this is not a fixed requirement. You can use the browser's driver implementation directly but this is harder to setup for the first time.

Selenium is written in Java, and requires a recent version of the JRE to run. Please ensure that you have this installed prior to starting.

Since Moodle 3.9.5 / 3.10.2 / 3.11.0 Moodle will work with any modern version of Selenium. At time of writing that is 3.141.59, and 4.1.0. Note: There appears to be an issue with the version 4 jars - particually in 4.1.0 that generates a "Could not open connection: Capability value must be set” error which appears to be an issue between Selenium and the MInkExtension for JavaScript tests - see https://githubmemory.com/repo/Behat/MinkExtension/activity for more information. The quick work around is to use the earlier version (3.141.59).

  1. Download the Selenium Server (Grid) from https://www.selenium.dev/downloads/. This is a single JAR file, put it anywhere handy.
  2. Start Selenium
   # Version 3.141.59:
   $ java -jar selenium-server-standalone-3.141.59.jar
   
   # Version 4.0.0 and later:
   $ java -jar selenium-server-4.0.0-beta-3.jar standalone

You can optionally specify a number of settings, depending on the version of Selenium that you are using, including the port to run on. See the help for the version of Selenium that you are using.

Setting up your browsers

Selenium is just an intelligient wrapper to start, and manage your browser sessions. It doesn't actually include any web browsers itself.

Moodle HQ run all behat tests against both Firefox and Chrome multiple times per day. Other combinations, including Microsoft Edge, are also supported.

To use Behat, you will need a recent version of your preferred browser, as well as a driver for that browser. The driver is responsible for communication between Selenium (or Moodle directly) and the browser.

Both the browser, and its driver, must be placed inside your $PATH - this may be somewhere like /usr/bin, /usr/local/bin, or perhaps a user bin directory like ~/bin which is present in your $PATH

Chrome

You can download Google Chrome from https://www.google.com.au/chrome.

You will need the correct version of the chromedriver as per the documentation. Alternatively you can make use of the chromedriver-wrapper utility noted in the Recommended extras sections.

Either the chromedriver binary must be in a directory in your $PATH, or the chromedriver-wrapper/bin folder must be in your $PATH.

Firefox

You can download Mozilla Firefox from https://www.mozilla.org/en-US/firefox/new/.

You will need the correct version of geckodriver as per the documentation.

The geckodriver binary must be in a directory in your $PATH.

Set up Moodle

  1. Create a new 'dataroot' area for files especially for behat
  2. Set the following in your Moodle config.php:
   $CFG->behat_dataroot = '/path/to/the/dataroot/you/created';
   $CFG->behat_wwwroot = 'http://127.0.0.1/path/to/your/site';
   $CFG->behat_prefix = 'beh_';
  1. We recommend that you also include the behat-browser-config if you have not done so already.
   require_once('/path/to/moodle-browser-config/init.php');
Notes about the behat_wwwroot

You will need to set the behat_wwwroot to your Moodle site, but it must use a different value to your $CFG->wwwroot.

One common way to do this is to use 127.0.0.1 for behat, but localhost for standard use. Alternatively you can add an additional hostname in your /etc/hosts file and use this instead.

If you use Docker, then you may be able to use host.docker.internal where your site is hosted on the docker host

Configure Behat for Moodle

After setting your configuration, you can simply initialise behat:

   $ php admin/tool/behat/cli/init.php

This will install all required Composer dependencies, install a new Moodle site, and put configuration in place

When it finishes it will give advice on how to run Behat.

Run Behat tests

Before running behat, ensure that your Selenium server is running.

The easiest way to run behat, and test that everything works is by simply running it using the command provided when you initialised Behat. If you didn't make a note of it, you can just run the initialisation again.

   $ php admin/tool/behat/cli/init.php

This will give you a command which you can then run. This command will run every behat scenario, which will take a considerable amount of time. This command will look a bit like this:

   $ vendor/bin/behat --config /Users/nicols/Sites/moodles/sm/moodledata_behat/behatrun/behat/behat.yml

To make this more useful you an combine it with flags, for example to only run certain tags or for a specific Behat Feature file, or Scenario.

To run all features/scenarios which are tagged with mod_forum:

   $ vendor/bin/behat --config /Users/nicols/Sites/moodles/sm/moodledata_behat/behatrun/behat/behat.yml --tags=@mod_forum

To run one specific feature file:

   $ vendor/bin/behat --config /Users/nicols/Sites/moodles/sm/moodledata_behat/behatrun/behat/behat.yml `pwd`/mod/forum/tests/behat/private_replies.feature

To run one specific scenario within a feature file:

   # To run the Scenario on line 38 of the file:
   $ vendor/bin/behat --config /Users/nicols/Sites/moodles/sm/moodledata_behat/behatrun/behat/behat.yml `pwd`/mod/forum/tests/behat/private_replies.feature:38

To run one specific scenario by name:

   $ vendor/bin/behat --config /Users/nicols/Sites/moodles/sm/moodledata_behat/behatrun/behat/behat.yml --name="As a teacher I can see my own response"

See the upstream documentation on Behat, and Gherkin filters for more information.

Running using a different browser

The default browser in Behat is Firefox. To specify a different browser profile, you can add the --profile argument. For example, to use Chrome in Headless mode:

   $ vendor/bin/behat --config /Users/nicols/Sites/moodles/sm/moodledata_behat/behatrun/behat/behat.yml --profile=headlesschrome

If you are using the moodle-browser-config utility, then you can use any profile listed in moodle-browser-config. Otherwise you can write your own browser profile configuration.

Advanced testing

Run tests without Selenium (chromedriver, geckodriver)

Historically, Behat required Selenium server, however browsers now make use of their own automation layer. For example, Firefox uses Geckodriver and Chrome uses Chromedriver. As a result the use of Selenium itself is now optional.

The moodle-browser-config tool includes standard profiles to use these drivers directly and without the use of Selenium.

To use the drivers directly, you must run the driver itself, for example to run chromedriver:

   $ chromedriver

To run geckodriver:

   $ geckodriver

Note: geckodriver runs on port 4444 by default. You cannot geckodriver at the same time as selenium.

After starting your preferred browser, you can then run behat and specify an alternative profile, for example:

   $ vendor/bin/behat --config /Users/nicols/Sites/moodles/sm/moodledata_behat/behatrun/behat/behat.yml --profile=geckodriver

Headless browsers

There are a number of reasons that you may prefer to use a headless browser. It can be particularly helpful if you are running the tests on a remote system, for example over SSH, or if you do not want to be interrupted by browsers popping up on your machine.

The following headless profiles are some of those provided in the moodle-browser-config tool as standard:

  1. headlessfirefox Use Firefox via Selenium, without displaying the GUI
  2. headlessgeckodriver Use Firefox with Geckodriver directly, without displaying the GUI
  3. headlesschrome Use Chrome via Selenium, without displaying the GUI
  4. headlesschromedriver Use Chrome with Chromedriver directly, without displaying the GUI

These can be provided to the --profile argument to behat:

   $ vendor/bin/behat --config /Users/nicols/Sites/moodles/sm/moodledata_behat/behatrun/behat/behat.yml --profile=headlesschrome

Parallel runs

Out-of-the-box, Moodle will configure Behat to run a single Moodle installation with all tests run in series. This is great for developer use where you are running a single test. or a small suite of tests. However this can be quite slow. A lot of time is spent waiting in Behat for things to happen. This may be for a page to load, for additional content to load, or even explicit waits because some interactions must be deliberately slowed down. As a result, a system running behat will not have a particularly high load most of the time.

If you want to run a large suite of tests then it is possible to take advantage of the relatively low resource consumption by running several behat runners in parallel. This is commonly referred to as a Parallel run.

A parallel run of behat takes the same codebase and creates several installations rather than just a single Moodle installation. The behat Feature files are then grouped and allocated between each of the separate installations.

To support this, each of the parallels runs needs its own:

  • behat_wwwroot
  • behat_dataroot
  • database

Rather than using an entirely separate database, the same database is actually used, but a different behat_prefix is used to prefix the table names in the database differently.

Installation

The Behat initialisation command is responsible for preparing Moodle to run a standard run. You'll have used this before when installing for a standard run:

   $ php admin/tool/behat/cli/init.php

The same command can be used to prepare Moodle for a parallel run by specifying the --parallel or -j parameter:

   // Below command will initialise moodle to run 3 parallel tests.
   $ php admin/tool/behat/cli/init.php --parallel=3

This can be combined with the --add-core-features-to-theme or -a flag to prepare Behat to run with all installed themes.

A number of advanced options are also available but you are unlikely to need these:

  1. -m=<number> or --maxruns=<number> Max parallel site which should be initialised at one time. If your system is slow, then you can initialise sites in chucks.
  2. --fromrun=<number> Initialise site to run specified run from. Used for running acceptance tests on different vms
  3. --torun=<number> Initialise site to run specified run till. Used for running acceptance tests on different vms
  4. -o or --optimize-runs This option will split features with specified tags in all parallel runs, so they are executed first when parallel run gets executed.

You can view details of all of these using the --help flag to admin/tool/behat/cli/init.php

Running Parallel tests

You can use the Moodle behat runner to run all tests, including Standard runs. It is an intelligient wrapper around the standard ./vendor/bin/behat command which specifies the configuration file, and other required features.

   $ php admin/tool/behat/cli/run.php

Many of the standard options and parameters that can be passed to ./vendor/bin/behat can also be passed to the Moodle runner, for example:

  1. --tags Run tests which match the specified tags
  2. --name="Scenario name" Run a test matching the supplied scenario name
  3. --feature="/path/to/test.feature" Run a specific feature file.
  4. --suite Features for specified theme will be executed.

The runner also includes a number of custom parameters relating to parallel runs:

  1. --replace Replace args string with run process number, useful for output and reruns.
  2. --fromrun Execute run starting from (Used for parallel runs on different vms)
  3. --torun Execute run till (Used for parallel runs on different vms)

The --replace feature is particularly useful and can be used to replace a string in the command with the run number. This is useful when specifying output formats, and rerun files as noted below.


The following example demonstrates how Behat might be initialised with three parallel runs, to run on all themes:

   $ php admin/tool/behat/cli/init.php --parallel=3 --add-core-features-to-theme

And then to run all tests matching the @tool_myplugin tag, against the classic theme:

   $ php admin/tool/behat/cli/run.php --tags="@tool_myplugin" --suite="classic"
Custom parameters for parallel runs

You can set following custom config options for parallel runs via $CFG->behat_parallel_run. It's an array of options where 1st array is for 1st run and so on.

   $CFG->behat_parallel_run = [
       [
          'dbtype' => 'mysqli',
          'dblibrary' => 'native',
          'dbhost' => 'localhost',
          'dbname' => 'moodletest',
          'dbuser' => 'moodle',
          'dbpass' => 'moodle',
          'behat_prefix' => 'mdl_',
          'wd_host' => 'http://127.0.0.1:4444/wd/hub',
          'behat_wwwroot' => 'http://127.0.0.1/moodle',
          'behat_dataroot' => '/home/example/bht_moodledata'
      ],
      // ...
   ],

To set different selenium servers for parallel runs, you can use following. NOTE: Running parallel (headless) runs on different selenium servers avoid random focus failures.

   $CFG->behat_parallel_run = [
       ['wd_host' => 'http://127.0.0.1:4444/wd/hub'],
       ['wd_host' => 'http://127.0.0.1:4445/wd/hub'],
       ['wd_host' => 'http://127.0.0.1:4446/wd/hub'],
   ];

Tests filters

With the --tags or the -name Behat options you can filter which tests are going to run or which ones are going to be skipped. There are a few tags that you might be interested in:

  • @javascript: All the tests that runs in a browser using Javascript; they require Selenium or the browser's own automation layer, as per Running acceptance test#Run tests without Selenium .28chromedriver.2C geckodriver.29, to be running, otherwise an exception will be thrown.
  • @_file_upload: All the tests that involves file uploading or any OS feature that is not 100% part of the browser. They should only be executed when Selenium is running in the same machine where the tests are running.
  • @_alert: All the tests that involves Javascript dialogs (alerts, confirms...) are using a feature that is OS-dependant and out of the browser scope, so they should be tag appropriately as not all browsers manage them properly.
  • @_switch_window: All the tests that are using the I switch to "NAME" window step should be tagged as not all browsers manage them properly.
  • @_switch_iframe: All the tests that are using the I switch to "NAME" iframe steps should be tagged as it is an advanced feature and some browsers may have problems dealing with them
  • @_cross_browser: All the tests that should run against multiple combinations of browsers + OS in a regular basis. The features that are sensitive to different combinations of OS and browsers should be tagges as @_cross_browser.
  • @componentname: Moodle features uses the Frankenstyle component name to tag the features according to the Moodle subsystem they belong to.

Output formats

Behat is able to output in a number of different formats, and to different locations as required.

This can be achieved by specifying the --format, and --out parameters when running behat, for example:

   // Run behat, using the 'pretty' format and outputting the value to /tmp/pretty.txt
   $ vendor/bin/behat --config /Users/nicols/Sites/moodles/sm/moodledata_behat/behatrun/behat/behat.yml \
       --format=pretty --out=/tmp/pretty.txt

It is also possible to output to multiple formats simultaneously by repeating the arguments, for example:

Since Moodle 3.1 option for output is:

   $ vendor/bin/behat --config /Users/nicols/Sites/moodles/sm/moodledata_behat/behatrun/behat/behat.yml \
       --format=pretty --out=/tmp/pretty.txt \
       --format=moodle_progress --out=std

The following output formats are supported:

  1. progress: Prints one character per step.
  2. pretty: Prints the feature as is.
  3. junit: Outputs the failures in JUnit compatible files.
  4. moodle_progress: Prints Moodle branch information and dots for each step.
  5. moodle_list: List all scenarios.
  6. moodle_stepcount: List all features with total steps in each feature file. Used for parallel run.
  7. moodle_screenshot: Take screenshot and core dump of each step. With following options you can dump either or both.
    1. --format-settings '{"formats": "image"}': will dump image only
    2. --format-settings '{"formats": "html"}': will dump html only.
    3. --format-settings '{"formats": "html,image"}': will dump both.
    4. --format-settings '{"formats": "html", "dir_permissions": "0777"}'

Note: If you want to see the failures immediately (rather than waiting ~3 hours for all the tests to finish) then either use the -v option to output a bit more information, or change the output format using --format. Format 'pretty' (-f pretty) is sufficient for most cases, as it outputs each step outcomes in the command line making easier to see the progress.

When working with parallel runs, you may wish to have an output for each run. If you were to specify a standard path for this then each of the parallel runs would overwrite the others file. The --replace option allows this to be handled:

   $ admin/tool/behat/cli/run.php \
       --replace="{runprocess}" \
       --format=pretty --out=/tmp/pretty_{runprocess}.txt \
       --format=moodle_progress --out=std

In this example, the --replace argument is provided with a value of {runprocess}. Anywhere that {runprocess} appears in the command it will be replaced with the run number. The above command will generate a set of commands like:

   $ vendor/bin/behat --config /Users/nicols/Sites/moodles/sm/moodledata_behat/behatrun1/behat/behat.yml \
       --format=pretty --out=/tmp/pretty_1.txt \
       --format=moodle_progress --out=std
   $ vendor/bin/behat --config /Users/nicols/Sites/moodles/sm/moodledata_behat/behatrun2/behat/behat.yml \
       --format=pretty --out=/tmp/pretty_2.txt \
       --format=moodle_progress --out=std
   $ vendor/bin/behat --config /Users/nicols/Sites/moodles/sm/moodledata_behat/behatrun3/behat/behat.yml \
       --format=pretty --out=/tmp/pretty_3.txt \
       --format=moodle_progress --out=std

Rerun failed scenarios

With slow systems or parallel run you may experience see some random failures. These may happen when your system is too slow, when it is too fast, or where a page depends on external dependencies.

To help with this it is possible to rerun any failed scenarios using the --rerun option to Behat.

The following example runs Behat with the rerun option:

   $ vendor/bin/behat --config /Users/nicols/Sites/moodles/sm/moodledata_behat/behatrun/behat/behat.yml \
       --format=pretty --out=/tmp/pretty.txt \
       --format=moodle_progress --out=std \
       --rerun

If any single test fails then the command will return a non-zero exit code. Running the same command again will mean that only failed scenarios are run.

For a parallel run it can be called as follows:

   $ admin/tool/behat/cli/run.php \
       --replace="{runprocess}" \
       --format=pretty --out=/tmp/pretty_{runprocess}.txt \
       --format=moodle_progress --out=std \
       --rerun

The Moodle behat runner also includes an --auto-rerun option which will automatically rerun failed scenarios exactly once.

Running behat with specified theme

Behat can be run with any installed theme, but it must be initialised with the -a or --add-core-features-to-theme option first.

After configuring the theme can be specified using the --suite parameter.

Note: The default theme in Moodle (boost) has the suite name default.

   // Initialise Behat for all themes:
   $ php admin/tool/behat/cli/init.php --add-core-features-to-theme
   
   // Run Behat against all initalised themes:
   $ vendor/bin/behat --config /Users/nicols/Sites/moodles/sm/moodledata_behat/behatrun/behat/behat.yml
   
   // Run Behat against just the default theme when all themes were initialised:
   $ vendor/bin/behat --config /Users/nicols/Sites/moodles/sm/moodledata_behat/behatrun/behat/behat.yml --suite=default
   
   // Run Behat against just the 'classic' theme when all themes were initialised:
   $ vendor/bin/behat --config /Users/nicols/Sites/moodles/sm/moodledata_behat/behatrun/behat/behat.yml --suite=classic

Using Docker to start selenium server

There are a wide range of docker images available which contain a browser with Selenium. You will probably be using the official SeleniumHQ images unless you have a specific reason not to.

The complete list of available SeleniumHQ images is available at https://hub.docker.com/u/selenium/.

Moodle uses the standalone version and any recent version with version 3.141.59 or higher is supported.

For any test which uploads files, for example when interacting with the filepicker, you must also ensure that the Moodle directory is mounted as on your local filesystem.

An example usage is:

   $ docker run -d -p 4444:4444 -v `pwd`:`pwd` selenium/standalone-firefox:latest

Change config.php file

In the Moodle config.php file you must change the $CFG->behat_wwwroot to an address that can be reached from within the docker image.

You cannot use localhost or 127.0.0.1 as this will be the IP address of the docker container itself.

On some more recent versions of Docker you can use http://host.docker.internal/, for example if my site is located at /sm on my development machine, I can set the following:

   $CFG->behat_wwwroot = 'http://host.docker.internal/sm';


Manually configuring other browsers =

If you would prefer not to use the moodle-browser-config tool but still wish to specify different browsers then you can do so using the $CFG->behat_profiles array. Each key/value pair contains a profile name, and the configuration for that profile. For example:

   $CFG->behat_profiles = [
       'chrome' => [
           'browser' => 'chrome',
           'tags' => '@javascript',
       ],
   ];

More info about alternative browsers

Troubleshooting

Increasing timeouts

You may see errors such as:

Javascript code and/or AJAX requests are not ready after 10 seconds.
There is a Javascript error or the code is extremely slow.

Sometimes this indicates a genuine problem with the code, but if you are using a slow computer, it may just mean that your browser did not finish generating parts of the UI before behat tried was finished.

If you find that this happens regularly on different scenarios then you may want to increase the timeout:

   $CFG->behat_increasetimeout = 2;

This will increase all the timeouts by a factor of 2; if that isn't sufficient, you could use 3.

Increasing timeouts will make tests run a bit slower (because there are points where Behat waits up to a timeout to make sure something doesn't happen) so don't do this unless you need to.

Note: This is usually an indicator that your development machine is not well tuned. A better option would be to find out where the bottleneck is. This is usually the database configuration.


New step definitions or features are not executed

If you are adding new tests or steps definitions update the tests list

php admin/tool/behat/cli/util.php --enable

For parallel runs, all options for initialising parallel runs are valid

Tests are failing

If you followed all the steps and you receive an unknown weird error probably your browser version is not compatible with the Selenium version you are running. Please refer Working combinations to ensure you have correct Acceptance_testing/Browsers#Working_combinations_of_OS.2BBrowser.2Bselenium of them to run acceptance test.

The tests are failing, and the error message is completely useless

For example, it just says "Error writing to database" with no stack trace.

Add -vv command-line option to get very verbose output.

Errors during setup (before test are launched)

Typical errors are:

  • Behat requirement not satisfied: http://127.0.0.1/m/stable_master is not available, ensure you specified correct url and that the server is set up and started.
  • init.php or util.php complain that "Unknown error 1 This is not a behat test site!". Delete the behat wwwroot (look in config.php for $CFG->behat_dataroot) and drop the behat DB tables (look in config.php for $CFG->behat_prefix). Then try again.
  • Behat is configured but not enabled on this test site.

In order to fix those errors please check that: the behat_dataroot has correct write permissions and that the $CFG->behat* variables are placed before the lib/setup.php include:

require_once(__DIR__ . '/lib/setup.php');

Selenium server is not running

Chrome specific

If you are using chrome, you need to ensure that the driver matches the version of the installed chrome browser – which may change on OS updates/upgrades. Moodle or Selenium will not give the appropriate message – see [https://tracker.moodle.org/browse/MDL-67659 MDL-67659]. One solution is the one suggested in the issue and use Andrew Nicols’ Chromedriver Wrapper which will ensure you have the appropriate driver before running the tests.


External links


Examples

Quick setup and testing using moodle-docker

This is a quick guide to help locally pass tests for your developments, before submitting them:

  1. Set up a default Moodle install using moodle-docker, with the database and Moodle version of your choice. See its README for more details. This will start some docker containers.
  2. Initialize behat to start testing with this command, from the webserver container:
    php admin/tool/behat/cli/init.php
    
  3. Run the behat test of your choice, from the webserver container. For instance:
    vendor/bin/behat --config /var/www/behatdata/behatrun/behat/behat.yml --tags tool_task
    

And you'll see something like:

Moodle 4.0dev (Build: 20210507), 0b47ea0a44a092f9000729ca7b15fff23111538b
Php: 7.3.26, mysqli: 5.7.21, OS: Linux 5.4.0-66-generic x86_64
Run optional tests:

Accessibility: No
Server OS "Linux", Browser: "firefox"
Started at 09-05-2021, 06:00
...................................................................... 70
...............................
12 scenarios (12 passed)
101 steps (101 passed)
2m53.27s (47.61Mb)

See also


Information to re-home

Override behat core context for theme suite

Note: This documentation needs to be rehomed to a location related to writing Behat tests.

To override behat step definitions so as to run behat with specified theme, you should create a contexts within /theme/{MYTHEME}/tests/behat/ with prefix behat_theme_{MYTHEME}_ and suffixed with the context being overridden. For example, if you want to override behat_mod_forum context, then you should create a class /theme/{MYTHEME}/tests/behat/mod_forum/behat_theme_{MYTHEME}_behat_mod_forum.php

Disable behat context or features to run in theme suite

Note: This documentation needs to be rehomed to a location related to writing Behat tests.

To disable specific contexts and features from being executed by a specific theme/suite you can create a /theme/{MYTHEME}/tests/behat/blacklist.json file with following format.

{
  "contexts": [
    "behat_grade",
    "behat_navigation",
  ],
  "features": [
    "auth/tests/behat/login.feature",
    "grade/tests/behat/grade_hidden_items.feature",
   ]
}

The above will:

  1. disable the use of step_definitions from behat_grade and behat_navigation while running theme suite; and
  2. disable running of scenarios in auth/tests/behat/login.feature and grade/tests/behat/grade_hidden_items.feature.

Override core behat selectors

Note: This documentation needs to be rehomed to a location related to writing Behat tests.

To override behat selectors in specific theme, you should create a class behat_theme_{MYTHEME}_behat_selectors in /theme/{MYTHEME}/tests/behat/behat_theme_{MYTHEME}_behat_selectors.php extending behat_selectors.

Write new tests and behat methods

Note: This documentation needs to be rehomed to a location related to writing Behat tests.

If you want to write tests for your own integration, you can do so by creating new tests with format .feature. Follow instructions in this page to write new tests.

It is also possible to add new steps the moodle behat integration. In order to do so, you will have to create a new .php class with the prefix behat_. Copy the format from lib\behat\behat_base.php, but set your class to extend the behat_base class instead of the MinkExtension. You can define new behat steps by declaring functions with the appropriate heading.

You will not be able to use these steps and features right away. Check this section for instructions on how to update the behat integration.


For further information on how to create new steps definitions, check Acceptance testing/Custom acceptance steps.