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
Line 189: Line 189:
<code>
<code>
php admin/tool/behat/cli/init.php --add-core-features-to-theme=clean
php admin/tool/behat/cli/init.php --add-core-features-to-theme=clean
</code>
The first time init runs can be time consuming as it creates a paralell set of tables to core, i.e. bh_user,bh_assign etc. After init the tests can be run with the alternative theme as follows.
<code>
vendor/bin/behat --suite=classic --tags="@enrol_foobar"
vendor/bin/behat --suite=classic --tags="@enrol_foobar"
</code>
</code>

Revision as of 14:52, 28 January 2021

Short version

...or how I got it to work on Ubuntu and some of the problems encountered.

You need a bunch of browsers and terminal windows open to do this.

1. Background

  1. 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 was not tested.
  2. Moodle is version 3.3 and is a fully installed and working version using the 'standard' Ubuntu LAMP stack.

2. Set up Selenium

First, you should have a look at working combinations of OS+Browser+selenium.

  1. Download the Selenium Standalone Server from http://www.seleniumhq.org/download/. It's a single JAR file, put it anywhere handy.
  2. Download the Chrome driver from https://sites.google.com/a/chromium.org/chromedriver/. Ensure you have the right version of the Chrome driver - see Trouble shooting. (Firefox is currently problematic. See Actual_Selenium_with_old_Firefox_47.0.1 if you need to try to make it work.)
  3. Unzip the driver (it's a single file) and copy to /usr/local/bin (should work anywhere on the path)
  4. If not installed already, 'sudo apt install default-jre'
  5. Start Selenium - 'java -jar /path/to/your/selenium/server/selenium-server-standalone-N.NN.N.jar -port 4444'
  6. check it works, access 'localhost:4444/wd/hub/' in your browser and check you can create a new Chrome session.

If running headless or the above doesn't work ("Selenium server is not running" when running the behat tests). Try the following

  1. Run 'Xvfb -ac :99 -screen 0 1280x1024x16 &'
  2. Then immediately, 'export DISPLAY=:99'
  3. The run the Selenium command as above

3. Set up Moodle

  1. Create a new 'dataroot' area for files especially for behat adjusting permissions accordingly.
  2. If not there already, add Section 11 from config-dist.php to your config.php file and review the settings.
  3. $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.
  4. $CFG->behat_dataroot should point to the directory you created above
  5. $CFG->behat_prefix should be fine.
  6. Set up $CFG->behat_profiles to select Chrome as the browser...
    $CFG->behat_profiles = [
        'default' => [
            'browser' => 'chrome',
            'extensions' => [
                'Behat\MinkExtension' => [
                    'selenium2' => [
                        'browser' => 'chrome',
                    ]
                ]
            ]
        ]
    ];

4. Configure Behat for Moodle

  1. Run 'php admin/tool/behat/cli/init.php' (from the root of your Moodle install). This installs all the required software and creates the test version of Moodle.

5. Run Behat tests

  1. Run 'vendor/bin/behat'. If you don't want to run all the tests add '--tags="@something"' where the @something refers to the tags at the top of most feature files. Use comma-separated list like '@some_thing,@some_thing_else' to run tests from multiple areas. See upstream documentation on Gherkin filters for advanced syntax and more complex examples.
  2. 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!)
  3. At the end of each line it shows you the number of steps that have completed so far.
    • If you are doing a full run, then as of November 2020 there are about 63,000 steps, which took around 25 hours to complete on one test machine (when not using the parallel running feature). Moodle HQ manage complete runs in ~5 hours on a well-optmised set-up, with 3 parallel workers.

Prerequisite

Before initializing acceptance test environment for running behat, you should ensure:

  1. Acceptance_testing#Requirements Meet min. system requirements for running tests
  2. Acceptance_testing#Installation Have set min. config variable in config.php for behat
  3. Acceptance_testing#Installation Downloaded composer dependencies

Overview

Acceptance tests (also known as behat), use Selenium server and can be run as:

  1. Single run: In single run, only one behat run is executed. So all features are executed in this single run.
  2. 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:
    • Features are divided between multiple behat runs
    • 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

Before running acceptance tests, environment needs to be initialised for acceptance testing.

Single run

For initialising acceptance tests for single run, above command is sufficient. php admin/tool/behat/cli/init.php

Parallel runs

For initialising acceptance tests for parallel runs, you can use one of the following options

  1. -j=<number> or --parallel=<number> (required) Number of parallel behat run to initialise
  2. -m=<number> or --maxruns=<number> (optional) Max parallel site which should be initialised at one time. If your system is slow, then you can initialise sites in chucks.
  3. --fromrun=<number> (optional) Initialise site to run specified run from. Used for running acceptance tests on different vms
  4. --torun=<number> (optional) Initialise site to run specified run till. Used for running acceptance tests on different vms
  5. -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.
  6. -a=<name> or --add-core-features-to-theme=<name> (optional) Since Moodle 3.2. Use this option to add all core features to specified themes (comma separated list of themes)

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

Step 2: Running acceptance test environment

Single run

Run either of the following commands. For more options vendor/bin/behat --help or http://docs.behat.org/guides/6.cli.html vendor/bin/behat --config /path/to/your/CFG_behat_dataroot/behatrun/behat/behat.yml

You almost always want to limit the number of tests that are run. To run all the tests in one plugin:

vendor/bin/behat --config /path/to/your/CFG_behat_dataroot/behatrun/behat/behat.yml --tags mod_myplugin

To run all the tests in one .feature file:

vendor/bin/behat --config /path/to/your/CFG_behat_dataroot/behatrun/behat/behat.yml /path/to/moodle/mod/myplugin/tests/behat/testsomething.feature

To run a single scenario:

vendor/bin/behat --config /path/to/your/CFG_behat_dataroot/behatrun/behat/behat.yml /path/to/moodle/mod/myplugin/tests/behat/testsomething.feature:40

Here, '40' is the line-number of the feature file where the Scenario starts.

Parallel runs

For running parallel runs, use following command

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

Following optional options are available for custom run:

  1. --feature Only execute specified feature file (Absolute path of feature file).
  2. --suite Features for specified theme will be executed.
  3. --replace Replace args string with run process number, useful for output and reruns.
  4. --fromrun Execute run starting from (Used for parallel runs on different vms)
  5. --torun Execute run till (Used for parallel runs on different vms)
  6. 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"

Example: Initialise and run Behat tests for a custom plugin under a custom theme:

php admin/tool/behat/cli/init.php --parallel=3 --add-core-features-to-theme="mytheme"
php admin/tool/behat/cli/run.php --tags="@tool_myplugin" --suite="mytheme"

Common options for running tests

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

Since Moodle 3.1 option for output is: --format=pretty --out=/path/to/pretty.txt --format=moodle_progress --out=std Before Moodle 3.1 option for output was: --format='moodle_progress,pretty' --out=',/path/to/pretty.txt' 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: (since Moodle 3.1) 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"}'**

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

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

  1. 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)
  2. 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)

You can run behat with any theme installed. To execute behat with specified theme use --suite=[classic | customtheme ] 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 --add-core-features-to-theme={THEME_NAME}, e.g.

php admin/tool/behat/cli/init.php --add-core-features-to-theme=clean The first time init runs can be time consuming as it creates a paralell set of tables to core, i.e. bh_user,bh_assign etc. After init the tests can be run with the alternative theme as follows. vendor/bin/behat --suite=classic --tags="@enrol_foobar"

If there is no --suite= parameter it will fall back to the default boost theme. No = or quotes needed around the theme name.

Make sure that $CFG->theme is not set in your config.php.

Override behat core context for theme suite

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

Blacklist behat context or features to run in theme suite

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. {

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

}

Override core behat selectors

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.

Use php built in web server

You can use php built-in-web server for executing behat runs. To do so:

  1. Open a command line interface and cd /to/your/moodle/dirroot
  2. 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)
  3. Update $CFG->behat_wwwroot = localhost:8000; in config.php

Define custom options 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.

      array (
          '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 = array (
       array ('wd_host' => 'http://127.0.0.1:4444/wd/hub'),
       array ('wd_host' => 'http://127.0.0.1:4445/wd/hub'),
       array ('wd_host' => 'http://127.0.0.1:4446/wd/hub'),
   );

Write new tests and behat methods

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.

Running acceptance tests with different browser

If you follow the steps above, Behat will run with Chrome.

You can get it to run with other browsers. The basic idea is to expand the $CFG->behat_profiles array in config.php to list more browsers.

$CFG->behat_profiles = array(

  'chrome' => array(
      'browser' => 'chrome',
      'tags' => '@javascript',
  )

);

More info about alternative browsers

Start multiple selenium servers

From command line Start selenium servers at different ports (say 4444, 4445, 4446 for 3 parallel runs) 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 & java -jar /path/to/your/selenium/server/selenium-server-standalone-2.NN.N.jar -port 4446

Alternative way of running three Selenium servers in parallel:

$ printf %d\\n {4444..4446} | xargs -n 1 -P 3 java -jar /path/to/your/selenium/server/selenium-server-standalone-2.NN.N.jar -port

Run tests directly in Chrome, with no Selenium

Historically, the tests would talk to a Selenium server, which would then tell the target browser what to do. More and more, the browsers themselves contain such a server and you can talk to them directly, which is faster and easier. Work was done to get this working with Chrome in MDL-58948, but it still needs some further setup to get it working, which is detailed in the bug ticket, and which I'll copy below:

Replace your current behat config with the abve, the api_url is where you'll talk directly to your Chrome browser. $CFG->behat_config = [

   'default' => [
       'extensions' => [
           'DMore\ChromeExtension\Behat\ServiceContainer\ChromeExtension' => [],
           'Behat\MinkExtension'                                          => [
               'browser_name' => 'chrome',
               'base_url'     => $CFG->behat_wwwroot,
               'goutte'       => null,
               'selenium2'    => null,
               'sessions'     => [
                   'javascript' => [
                       'chrome' => [
                           'api_url' => 'http://localhost:9222'
                       ]
                   ]
               ]
           ]
       ]
   ],

];

Use composer to install two more required libraries: composer require --dev dmore/behat-chrome-extension composer require --dev dmore/chrome-mink-driver

If you try to run the tests it will tell you that Chrome isn't running, in a second tab run the following to start Chrome (or chromium-browser on Ubuntu)

chrome --disable-gpu --headless --remote-debugging-address=0.0.0.0 --remote-debugging-port=9222

This is running headless so you won't see any windows pop up as the tests run, though it runs in the other mode too.

Behat should now run as before, but faster.

Run Chrome locally with Behat and Moodle on a remote server

If you have Moodle running on a remote (headless) server, but don't want to install a window manager, you can do the following:

1. Go through all the steps from above

2. Establish an SSH SOCKS5 proxy connection to your server: ssh -D VARIABLE-PORT-A -N -q -C USER@SERVER 3. Forward the port to connect to the DevTools-API of your browser: ssh -R VARIABLE-PORT-B:localhost:VARIABLE-PORT-B USER@SERVER -N -q -C 4. Tell your local Chrome to use custom settings: /path/to/Google\ Chrome [--disable-gpu] --remote-debugging-address=0.0.0.0 --remote-debugging-port=VARIABLE-PORT-B --proxy-server=socks://127.0.0.1:VARIABLE-PORT-A --proxy-bypass-list='<-loopback>'

Or, all in one command: ssh -D VARIABLE-PORT-A -N -q -C -f USER@SERVER && ssh -R VARIABLE-PORT-B:localhost:VARIABLE-PORT-B USER@SERVER -N -q -C -f && /path/to/Google\ Chrome [--disable-gpu] --remote-debugging-address=0.0.0.0 --remote-debugging-port=VARIABLE-PORT-B --proxy-server=socks://127.0.0.1:VARIABLE-PORT-A --proxy-bypass-list='<-loopback>'

Explanation for the SSH settings:

  • VARIABLE-PORT-B & VARIABLE-PORT-A : Choose these as you like. Bear in mind that you will need root rights if the port number is 1023 or lower
  • -N: Tells SSH not to open an actual command prompt
  • -C: Compress all data passed through the tunnel
  • -q: Quiet mode. Causes most warning and diagnostic messages to be suppressed
  • -R: Open a tunnel binding to localhost on the remote machine, going to localhost on the local machine
  • -f: Fork the process into background

Explanation for the Chrome settings:

  • --proxy-bypass-list='<-loopback>' : Tells Chrome to send requests to localhost through the tunnel
  • --proxy-server=socks://127.0.0.1:VARIABLE-PORT-A : To use the SOCKS5 tunnel we just set up
  • --remote-debugging-port=VARIABLE-PORT-B & --remote-debugging-address=0.0.0.0 : To use the SSH tunnel we just set up

Using Docker to start selenium server

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

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: What version do I need?

so the command will be: docker run -d -p4444:4444 selenium/standalone-firefox:2.53.1-beryllium to see all available version click in tags. For firefox you can find at: https://hub.docker.com/r/selenium/standalone-firefox/tags/

Change config.php file

In config.php file you must change the $CFG->behat_wwwroot= to your network card (NIC) ip address, you can't use localhost , 127.0.0.1, ... or selenium docker server will fail

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 could just mean that the browser was not yet ready. You may find that the test works if you run it again. If you get this error frequently, it might be useful to increase the timeout.

It is possible to increase this timeout by adding a line in your config.php. (Requires Moodle versions 3.5 (from 3.5.6), 3.6 (from 3.6.4), or 3.7+.)

$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

  1. Start the Selenium server (in case you want to run tests that involves Javascript)

Disable acceptance test environment

if you want to prevent access to test environment php admin/tool/behat/cli/util.php --disable 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.

Trouble shooting

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.
  • 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

See also