Updated to Drupal 8.5. Core Media not yet in use.
[yaffs-website] / web / core / tests / Drupal / FunctionalJavascriptTests / JavascriptTestBase.php
1 <?php
2
3 namespace Drupal\FunctionalJavascriptTests;
4
5 use Drupal\Tests\BrowserTestBase;
6 use Zumba\GastonJS\Exception\DeadClient;
7 use Zumba\Mink\Driver\PhantomJSDriver;
8
9 /**
10  * Runs a browser test using a driver that supports Javascript.
11  *
12  * Base class for testing browser interaction implemented in JavaScript.
13  */
14 abstract class JavascriptTestBase extends BrowserTestBase {
15
16   /**
17    * {@inheritdoc}
18    *
19    * To use a webdriver based approach, please use DrupalSelenium2Driver::class.
20    * We will switch the default later.
21    */
22   protected $minkDefaultDriverClass = PhantomJSDriver::class;
23
24   /**
25    * {@inheritdoc}
26    */
27   protected function initMink() {
28     if ($this->minkDefaultDriverClass === DrupalSelenium2Driver::class) {
29       $this->minkDefaultDriverArgs = ['chrome', NULL, 'http://localhost:4444/'];
30     }
31     elseif ($this->minkDefaultDriverClass === PhantomJSDriver::class) {
32       // Set up the template cache used by the PhantomJS mink driver.
33       $path = $this->tempFilesDirectory . DIRECTORY_SEPARATOR . 'browsertestbase-templatecache';
34       $this->minkDefaultDriverArgs = [
35         'http://127.0.0.1:8510',
36         $path,
37       ];
38       if (!file_exists($path)) {
39         mkdir($path);
40       }
41     }
42
43     try {
44       return parent::initMink();
45     }
46     catch (DeadClient $e) {
47       $this->markTestSkipped('PhantomJS is either not installed or not running. Start it via phantomjs --ssl-protocol=any --ignore-ssl-errors=true vendor/jcalderonzumba/gastonjs/src/Client/main.js 8510 1024 768&');
48     }
49     catch (\Exception $e) {
50       $this->markTestSkipped('An unexpected error occurred while starting Mink: ' . $e->getMessage());
51     }
52   }
53
54   /**
55    * {@inheritdoc}
56    */
57   protected function tearDown() {
58     if ($this->mink) {
59       // Wait for all requests to finish. It is possible that an AJAX request is
60       // still on-going.
61       $result = $this->getSession()->wait(5000, '(typeof(jQuery)=="undefined" || (0 === jQuery.active && 0 === jQuery(\':animated\').length))');
62       if (!$result) {
63         // If the wait is unsuccessful, there may still be an AJAX request in
64         // progress. If we tear down now, then this AJAX request may fail with
65         // missing database tables, because tear down will have removed them.
66         // Rather than allow it to fail, throw an explicit exception now
67         // explaining what the problem is.
68         throw new \RuntimeException('Unfinished AJAX requests while tearing down a test');
69       }
70     }
71     parent::tearDown();
72   }
73
74   /**
75     * {@inheritdoc}
76     */
77   protected function getMinkDriverArgs() {
78     if ($this->minkDefaultDriverClass === DrupalSelenium2Driver::class) {
79       return getenv('MINK_DRIVER_ARGS_WEBDRIVER') ?: getenv('MINK_DRIVER_ARGS_PHANTOMJS') ?: parent::getMinkDriverArgs();
80     }
81     elseif ($this->minkDefaultDriverClass === PhantomJSDriver::class) {
82       return getenv('MINK_DRIVER_ARGS_PHANTOMJS') ?: parent::getMinkDriverArgs();
83     }
84     return parent::getMinkDriverArgs();
85   }
86
87   /**
88    * Asserts that the element with the given CSS selector is visible.
89    *
90    * @param string $css_selector
91    *   The CSS selector identifying the element to check.
92    * @param string $message
93    *   Optional message to show alongside the assertion.
94    *
95    * @deprecated in Drupal 8.1.x, will be removed before Drupal 8.3.x. Use
96    *   \Behat\Mink\Element\NodeElement::isVisible() instead.
97    */
98   protected function assertElementVisible($css_selector, $message = '') {
99     $this->assertTrue($this->getSession()->getDriver()->isVisible($this->cssSelectToXpath($css_selector)), $message);
100   }
101
102   /**
103    * Asserts that the element with the given CSS selector is not visible.
104    *
105    * @param string $css_selector
106    *   The CSS selector identifying the element to check.
107    * @param string $message
108    *   Optional message to show alongside the assertion.
109    *
110    * @deprecated in Drupal 8.1.x, will be removed before Drupal 8.3.x. Use
111    *   \Behat\Mink\Element\NodeElement::isVisible() instead.
112    */
113   protected function assertElementNotVisible($css_selector, $message = '') {
114     $this->assertFalse($this->getSession()->getDriver()->isVisible($this->cssSelectToXpath($css_selector)), $message);
115   }
116
117   /**
118    * Waits for the given time or until the given JS condition becomes TRUE.
119    *
120    * @param string $condition
121    *   JS condition to wait until it becomes TRUE.
122    * @param int $timeout
123    *   (Optional) Timeout in milliseconds, defaults to 10000.
124    * @param string $message
125    *   (optional) A message to display with the assertion. If left blank, a
126    *   default message will be displayed.
127    *
128    * @throws \PHPUnit_Framework_AssertionFailedError
129    *
130    * @see \Behat\Mink\Driver\DriverInterface::evaluateScript()
131    */
132   protected function assertJsCondition($condition, $timeout = 10000, $message = '') {
133     $message = $message ?: "Javascript condition met:\n" . $condition;
134     $result = $this->getSession()->getDriver()->wait($timeout, $condition);
135     $this->assertTrue($result, $message);
136   }
137
138   /**
139    * Creates a screenshot.
140    *
141    * @param string $filename
142    *   The file name of the resulting screenshot. If using the default phantomjs
143    *   driver then this should be a JPG filename.
144    * @param bool $set_background_color
145    *   (optional) By default this method will set the background color to white.
146    *   Set to FALSE to override this behaviour.
147    *
148    * @throws \Behat\Mink\Exception\UnsupportedDriverActionException
149    *   When operation not supported by the driver.
150    * @throws \Behat\Mink\Exception\DriverException
151    *   When the operation cannot be done.
152    */
153   protected function createScreenshot($filename, $set_background_color = TRUE) {
154     $session = $this->getSession();
155     if ($set_background_color) {
156       $session->executeScript("document.body.style.backgroundColor = 'white';");
157     }
158     $image = $session->getScreenshot();
159     file_put_contents($filename, $image);
160   }
161
162   /**
163    * {@inheritdoc}
164    */
165   public function assertSession($name = NULL) {
166     return new WebDriverWebAssert($this->getSession($name), $this->baseUrl);
167   }
168
169   /**
170    * Gets the current Drupal javascript settings and parses into an array.
171    *
172    * Unlike BrowserTestBase::getDrupalSettings(), this implementation reads the
173    * current values of drupalSettings, capturing all changes made via javascript
174    * after the page was loaded.
175    *
176    * @return array
177    *   The Drupal javascript settings array.
178    *
179    * @see \Drupal\Tests\BrowserTestBase::getDrupalSettings()
180    */
181   protected function getDrupalSettings() {
182     $script = <<<EndOfScript
183 (function () {
184   if (typeof drupalSettings !== 'undefined') {
185     return drupalSettings;
186   }
187 })();
188 EndOfScript;
189
190     return $this->getSession()->evaluateScript($script) ?: [];
191   }
192
193   /**
194    * {@inheritdoc}
195    */
196   protected function getHtmlOutputHeaders() {
197     // The webdriver API does not support fetching headers.
198     return '';
199   }
200
201 }