Chris@0: root = dirname(dirname(substr(__DIR__, 0, -strlen(__NAMESPACE__)))); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Initializes Mink sessions. Chris@0: */ Chris@0: protected function initMink() { Chris@0: $driver = $this->getDefaultDriverInstance(); Chris@0: Chris@0: if ($driver instanceof GoutteDriver) { Chris@0: // Turn off curl timeout. Having a timeout is not a problem in a normal Chris@0: // test running, but it is a problem when debugging. Also, disable SSL Chris@0: // peer verification so that testing under HTTPS always works. Chris@0: /** @var \GuzzleHttp\Client $client */ Chris@0: $client = $this->container->get('http_client_factory')->fromOptions([ Chris@0: 'timeout' => NULL, Chris@0: 'verify' => FALSE, Chris@0: ]); Chris@0: Chris@0: // Inject a Guzzle middleware to generate debug output for every request Chris@0: // performed in the test. Chris@0: $handler_stack = $client->getConfig('handler'); Chris@0: $handler_stack->push($this->getResponseLogHandler()); Chris@0: Chris@0: $driver->getClient()->setClient($client); Chris@0: } Chris@0: Chris@0: $selectors_handler = new SelectorsHandler([ Chris@17: 'hidden_field_selector' => new HiddenFieldSelector(), Chris@0: ]); Chris@0: $session = new Session($driver, $selectors_handler); Chris@0: $this->mink = new Mink(); Chris@0: $this->mink->registerSession('default', $session); Chris@0: $this->mink->setDefaultSessionName('default'); Chris@0: $this->registerSessions(); Chris@0: Chris@16: $this->initFrontPage(); Chris@16: Chris@17: // Copies cookies from the current environment, for example, XDEBUG_SESSION Chris@17: // in order to support Xdebug. Chris@17: // @see BrowserTestBase::initFrontPage() Chris@17: $cookies = $this->extractCookiesFromRequest(\Drupal::request()); Chris@17: foreach ($cookies as $cookie_name => $values) { Chris@17: foreach ($values as $value) { Chris@17: $session->setCookie($cookie_name, $value); Chris@17: } Chris@17: } Chris@17: Chris@16: return $session; Chris@16: } Chris@16: Chris@16: /** Chris@16: * Visits the front page when initializing Mink. Chris@16: * Chris@16: * According to the W3C WebDriver specification a cookie can only be set if Chris@16: * the cookie domain is equal to the domain of the active document. When the Chris@16: * browser starts up the active document is not our domain but 'about:blank' Chris@16: * or similar. To be able to set our User-Agent and Xdebug cookies at the Chris@16: * start of the test we now do a request to the front page so the active Chris@16: * document matches the domain. Chris@16: * Chris@16: * @see https://w3c.github.io/webdriver/webdriver-spec.html#add-cookie Chris@16: * @see https://www.w3.org/Bugs/Public/show_bug.cgi?id=20975 Chris@16: */ Chris@16: protected function initFrontPage() { Chris@0: $session = $this->getSession(); Chris@0: $session->visit($this->baseUrl); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Gets an instance of the default Mink driver. Chris@0: * Chris@0: * @return Behat\Mink\Driver\DriverInterface Chris@0: * Instance of default Mink driver. Chris@0: * Chris@0: * @throws \InvalidArgumentException Chris@0: * When provided default Mink driver class can't be instantiated. Chris@0: */ Chris@0: protected function getDefaultDriverInstance() { Chris@14: // Get default driver params from environment if available. Chris@14: if ($arg_json = $this->getMinkDriverArgs()) { Chris@12: $this->minkDefaultDriverArgs = json_decode($arg_json, TRUE); Chris@0: } Chris@0: Chris@14: // Get and check default driver class from environment if available. Chris@0: if ($minkDriverClass = getenv('MINK_DRIVER_CLASS')) { Chris@0: if (class_exists($minkDriverClass)) { Chris@0: $this->minkDefaultDriverClass = $minkDriverClass; Chris@0: } Chris@0: else { Chris@0: throw new \InvalidArgumentException("Can't instantiate provided $minkDriverClass class by environment as default driver class."); Chris@0: } Chris@0: } Chris@0: Chris@0: if (is_array($this->minkDefaultDriverArgs)) { Chris@0: // Use ReflectionClass to instantiate class with received params. Chris@0: $reflector = new \ReflectionClass($this->minkDefaultDriverClass); Chris@0: $driver = $reflector->newInstanceArgs($this->minkDefaultDriverArgs); Chris@0: } Chris@0: else { Chris@0: $driver = new $this->minkDefaultDriverClass(); Chris@0: } Chris@0: return $driver; Chris@0: } Chris@0: Chris@0: /** Chris@14: * Get the Mink driver args from an environment variable, if it is set. Can Chris@14: * be overridden in a derived class so it is possible to use a different Chris@14: * value for a subset of tests, e.g. the JavaScript tests. Chris@14: * Chris@14: * @return string|false Chris@14: * The JSON-encoded argument string. False if it is not set. Chris@14: */ Chris@14: protected function getMinkDriverArgs() { Chris@14: return getenv('MINK_DRIVER_ARGS'); Chris@14: } Chris@14: Chris@14: /** Chris@0: * Provides a Guzzle middleware handler to log every response received. Chris@0: * Chris@0: * @return callable Chris@0: * The callable handler that will do the logging. Chris@0: */ Chris@0: protected function getResponseLogHandler() { Chris@0: return function (callable $handler) { Chris@0: return function (RequestInterface $request, array $options) use ($handler) { Chris@0: return $handler($request, $options) Chris@0: ->then(function (ResponseInterface $response) use ($request) { Chris@0: if ($this->htmlOutputEnabled) { Chris@0: Chris@0: $caller = $this->getTestMethodCaller(); Chris@0: $html_output = 'Called from ' . $caller['function'] . ' line ' . $caller['line']; Chris@0: $html_output .= '
' . $request->getMethod() . ' request to: ' . $request->getUri(); Chris@0: Chris@0: // On redirect responses (status code starting with '3') we need Chris@0: // to remove the meta tag that would do a browser refresh. We Chris@0: // don't want to redirect developers away when they look at the Chris@0: // debug output file in their browser. Chris@0: $body = $response->getBody(); Chris@0: $status_code = (string) $response->getStatusCode(); Chris@0: if ($status_code[0] === '3') { Chris@0: $body = preg_replace('##', '', $body, 1); Chris@0: } Chris@0: $html_output .= '
' . $body; Chris@0: $html_output .= $this->formatHtmlOutputHeaders($response->getHeaders()); Chris@0: Chris@0: $this->htmlOutput($html_output); Chris@0: } Chris@0: return $response; Chris@0: }); Chris@0: }; Chris@0: }; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Registers additional Mink sessions. Chris@0: * Chris@0: * Tests wishing to use a different driver or change the default driver should Chris@0: * override this method. Chris@0: * Chris@0: * @code Chris@0: * // Register a new session that uses the MinkPonyDriver. Chris@0: * $pony = new MinkPonyDriver(); Chris@0: * $session = new Session($pony); Chris@0: * $this->mink->registerSession('pony', $session); Chris@0: * @endcode Chris@0: */ Chris@0: protected function registerSessions() {} Chris@0: Chris@0: /** Chris@0: * {@inheritdoc} Chris@0: */ Chris@0: protected function setUp() { Chris@12: // Installing Drupal creates 1000s of objects. Garbage collection of these Chris@12: // objects is expensive. This appears to be causing random segmentation Chris@12: // faults in PHP 5.x due to https://bugs.php.net/bug.php?id=72286. Once Chris@12: // Drupal is installed is rebuilt, garbage collection is re-enabled. Chris@12: $disable_gc = version_compare(PHP_VERSION, '7', '<') && gc_enabled(); Chris@12: if ($disable_gc) { Chris@12: gc_collect_cycles(); Chris@12: gc_disable(); Chris@12: } Chris@0: parent::setUp(); Chris@0: Chris@0: $this->setupBaseUrl(); Chris@0: Chris@0: // Install Drupal test site. Chris@0: $this->prepareEnvironment(); Chris@0: $this->installDrupal(); Chris@0: Chris@0: // Setup Mink. Chris@17: $this->initMink(); Chris@0: Chris@0: // Set up the browser test output file. Chris@0: $this->initBrowserOutputFile(); Chris@12: // If garbage collection was disabled prior to rebuilding container, Chris@12: // re-enable it. Chris@12: if ($disable_gc) { Chris@12: gc_enable(); Chris@12: } Chris@14: Chris@14: // Ensure that the test is not marked as risky because of no assertions. In Chris@14: // PHPUnit 6 tests that only make assertions using $this->assertSession() Chris@14: // can be marked as risky. Chris@14: $this->addToAssertionCount(1); Chris@0: } Chris@0: Chris@0: /** Chris@18: * Ensures test files are deletable. Chris@0: * Chris@0: * Some tests chmod generated files to be read only. During Chris@0: * BrowserTestBase::cleanupEnvironment() and other cleanup operations, Chris@0: * these files need to get deleted too. Chris@0: * Chris@0: * @param string $path Chris@0: * The file path. Chris@18: * Chris@18: * @see \Drupal\Core\File\FileSystemInterface::deleteRecursive() Chris@0: */ Chris@0: public static function filePreDeleteCallback($path) { Chris@0: // When the webserver runs with the same system user as phpunit, we can Chris@0: // make read-only files writable again. If not, chmod will fail while the Chris@0: // file deletion still works if file permissions have been configured Chris@0: // correctly. Thus, we ignore any problems while running chmod. Chris@0: @chmod($path, 0700); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Clean up the Simpletest environment. Chris@0: */ Chris@0: protected function cleanupEnvironment() { Chris@0: // Remove all prefixed tables. Chris@0: $original_connection_info = Database::getConnectionInfo('simpletest_original_default'); Chris@0: $original_prefix = $original_connection_info['default']['prefix']['default']; Chris@0: $test_connection_info = Database::getConnectionInfo('default'); Chris@0: $test_prefix = $test_connection_info['default']['prefix']['default']; Chris@0: if ($original_prefix != $test_prefix) { Chris@0: $tables = Database::getConnection()->schema()->findTables('%'); Chris@0: foreach ($tables as $table) { Chris@0: if (Database::getConnection()->schema()->dropTable($table)) { Chris@0: unset($tables[$table]); Chris@0: } Chris@0: } Chris@0: } Chris@0: Chris@0: // Delete test site directory. Chris@18: \Drupal::service('file_system')->deleteRecursive($this->siteDirectory, [$this, 'filePreDeleteCallback']); Chris@0: } Chris@0: Chris@0: /** Chris@0: * {@inheritdoc} Chris@0: */ Chris@0: protected function tearDown() { Chris@0: parent::tearDown(); Chris@0: Chris@0: // Destroy the testing kernel. Chris@0: if (isset($this->kernel)) { Chris@0: $this->cleanupEnvironment(); Chris@0: $this->kernel->shutdown(); Chris@0: } Chris@0: Chris@0: // Ensure that internal logged in variable is reset. Chris@0: $this->loggedInUser = FALSE; Chris@0: Chris@0: if ($this->mink) { Chris@0: $this->mink->stopSessions(); Chris@0: } Chris@0: Chris@0: // Restore original shutdown callbacks. Chris@0: if (function_exists('drupal_register_shutdown_function')) { Chris@0: $callbacks = &drupal_register_shutdown_function(); Chris@0: $callbacks = $this->originalShutdownCallbacks; Chris@0: } Chris@0: } Chris@0: Chris@0: /** Chris@0: * Returns Mink session. Chris@0: * Chris@0: * @param string $name Chris@0: * (optional) Name of the session. Defaults to the active session. Chris@0: * Chris@0: * @return \Behat\Mink\Session Chris@0: * The active Mink session object. Chris@0: */ Chris@0: public function getSession($name = NULL) { Chris@0: return $this->mink->getSession($name); Chris@0: } Chris@0: Chris@0: /** Chris@17: * Get session cookies from current session. Chris@17: * Chris@17: * @return \GuzzleHttp\Cookie\CookieJar Chris@17: * A cookie jar with the current session. Chris@17: */ Chris@17: protected function getSessionCookies() { Chris@17: $domain = parse_url($this->getUrl(), PHP_URL_HOST); Chris@17: $session_id = $this->getSession()->getCookie($this->getSessionName()); Chris@17: $cookies = CookieJar::fromArray([$this->getSessionName() => $session_id], $domain); Chris@17: Chris@17: return $cookies; Chris@17: } Chris@17: Chris@17: /** Chris@16: * Obtain the HTTP client for the system under test. Chris@16: * Chris@16: * Use this method for arbitrary HTTP requests to the site under test. For Chris@16: * most tests, you should not get the HTTP client and instead use navigation Chris@16: * methods such as drupalGet() and clickLink() in order to benefit from Chris@16: * assertions. Chris@16: * Chris@16: * Subclasses which substitute a different Mink driver should override this Chris@16: * method and provide a Guzzle client if the Mink driver provides one. Chris@16: * Chris@16: * @return \GuzzleHttp\ClientInterface Chris@16: * The client with BrowserTestBase configuration. Chris@16: * Chris@16: * @throws \RuntimeException Chris@16: * If the Mink driver does not support a Guzzle HTTP client, throw an Chris@16: * exception. Chris@16: */ Chris@16: protected function getHttpClient() { Chris@16: /* @var $mink_driver \Behat\Mink\Driver\DriverInterface */ Chris@16: $mink_driver = $this->getSession()->getDriver(); Chris@16: if ($mink_driver instanceof GoutteDriver) { Chris@16: return $mink_driver->getClient()->getClient(); Chris@16: } Chris@16: throw new \RuntimeException('The Mink client type ' . get_class($mink_driver) . ' does not support getHttpClient().'); Chris@16: } Chris@16: Chris@16: /** Chris@0: * Helper function to get the options of select field. Chris@0: * Chris@0: * @param \Behat\Mink\Element\NodeElement|string $select Chris@0: * Name, ID, or Label of select field to assert. Chris@0: * @param \Behat\Mink\Element\Element $container Chris@0: * (optional) Container element to check against. Defaults to current page. Chris@0: * Chris@0: * @return array Chris@0: * Associative array of option keys and values. Chris@0: */ Chris@0: protected function getOptions($select, Element $container = NULL) { Chris@0: if (is_string($select)) { Chris@0: $select = $this->assertSession()->selectExists($select, $container); Chris@0: } Chris@0: $options = []; Chris@0: /* @var \Behat\Mink\Element\NodeElement $option */ Chris@0: foreach ($select->findAll('xpath', '//option') as $option) { Chris@0: $label = $option->getText(); Chris@0: $value = $option->getAttribute('value') ?: $label; Chris@0: $options[$value] = $label; Chris@0: } Chris@0: return $options; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Installs Drupal into the Simpletest site. Chris@0: */ Chris@0: public function installDrupal() { Chris@0: $this->initUserSession(); Chris@0: $this->prepareSettings(); Chris@0: $this->doInstall(); Chris@0: $this->initSettings(); Chris@0: $container = $this->initKernel(\Drupal::request()); Chris@0: $this->initConfig($container); Chris@0: $this->installModulesFromClassProperty($container); Chris@0: $this->rebuildAll(); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Prevents serializing any properties. Chris@0: * Chris@0: * Browser tests are run in a separate process. To do this PHPUnit creates a Chris@0: * script to run the test. If it fails, the test result object will contain a Chris@0: * stack trace which includes the test object. It will attempt to serialize Chris@0: * it. Returning an empty array prevents it from serializing anything it Chris@0: * should not. Chris@0: * Chris@0: * @return array Chris@0: * An empty array. Chris@0: * Chris@0: * @see vendor/phpunit/phpunit/src/Util/PHP/Template/TestCaseMethod.tpl.dist Chris@0: */ Chris@0: public function __sleep() { Chris@0: return []; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Translates a CSS expression to its XPath equivalent. Chris@0: * Chris@0: * The search is relative to the root element (HTML tag normally) of the page. Chris@0: * Chris@0: * @param string $selector Chris@0: * CSS selector to use in the search. Chris@0: * @param bool $html Chris@0: * (optional) Enables HTML support. Disable it for XML documents. Chris@0: * @param string $prefix Chris@0: * (optional) The prefix for the XPath expression. Chris@0: * Chris@0: * @return string Chris@0: * The equivalent XPath of a CSS expression. Chris@0: */ Chris@0: protected function cssSelectToXpath($selector, $html = TRUE, $prefix = 'descendant-or-self::') { Chris@0: return (new CssSelectorConverter($html))->toXPath($selector, $prefix); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Performs an xpath search on the contents of the internal browser. Chris@0: * Chris@0: * The search is relative to the root element (HTML tag normally) of the page. Chris@0: * Chris@0: * @param string $xpath Chris@0: * The xpath string to use in the search. Chris@0: * @param array $arguments Chris@0: * An array of arguments with keys in the form ':name' matching the Chris@0: * placeholders in the query. The values may be either strings or numeric Chris@0: * values. Chris@0: * Chris@0: * @return \Behat\Mink\Element\NodeElement[] Chris@0: * The list of elements matching the xpath expression. Chris@0: */ Chris@0: protected function xpath($xpath, array $arguments = []) { Chris@0: $xpath = $this->assertSession()->buildXPathQuery($xpath, $arguments); Chris@0: return $this->getSession()->getPage()->findAll('xpath', $xpath); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Configuration accessor for tests. Returns non-overridden configuration. Chris@0: * Chris@0: * @param string $name Chris@0: * Configuration name. Chris@0: * Chris@0: * @return \Drupal\Core\Config\Config Chris@0: * The configuration object with original configuration data. Chris@0: */ Chris@0: protected function config($name) { Chris@0: return $this->container->get('config.factory')->getEditable($name); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Returns all response headers. Chris@0: * Chris@0: * @return array Chris@0: * The HTTP headers values. Chris@0: * Chris@0: * @deprecated Scheduled for removal in Drupal 9.0.0. Chris@0: * Use $this->getSession()->getResponseHeaders() instead. Chris@0: */ Chris@0: protected function drupalGetHeaders() { Chris@0: return $this->getSession()->getResponseHeaders(); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Gets the value of an HTTP response header. Chris@0: * Chris@0: * If multiple requests were required to retrieve the page, only the headers Chris@0: * from the last request will be checked by default. Chris@0: * Chris@0: * @param string $name Chris@0: * The name of the header to retrieve. Names are case-insensitive (see RFC Chris@0: * 2616 section 4.2). Chris@0: * Chris@0: * @return string|null Chris@0: * The HTTP header value or NULL if not found. Chris@0: */ Chris@0: protected function drupalGetHeader($name) { Chris@0: return $this->getSession()->getResponseHeader($name); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Gets the JavaScript drupalSettings variable for the currently-loaded page. Chris@0: * Chris@0: * @return array Chris@0: * The JSON decoded drupalSettings value from the current page. Chris@0: */ Chris@0: protected function getDrupalSettings() { Chris@17: $html = $this->getSession()->getPage()->getContent(); Chris@0: if (preg_match('@@', $html, $matches)) { Chris@0: return Json::decode($matches[1]); Chris@0: } Chris@0: return []; Chris@0: } Chris@0: Chris@0: /** Chris@0: * {@inheritdoc} Chris@0: */ Chris@0: public static function assertEquals($expected, $actual, $message = '', $delta = 0.0, $maxDepth = 10, $canonicalize = FALSE, $ignoreCase = FALSE) { Chris@0: // Cast objects implementing MarkupInterface to string instead of Chris@0: // relying on PHP casting them to string depending on what they are being Chris@0: // comparing with. Chris@0: $expected = static::castSafeStrings($expected); Chris@0: $actual = static::castSafeStrings($actual); Chris@0: parent::assertEquals($expected, $actual, $message, $delta, $maxDepth, $canonicalize, $ignoreCase); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Retrieves the current calling line in the class under test. Chris@0: * Chris@0: * @return array Chris@0: * An associative array with keys 'file', 'line' and 'function'. Chris@0: */ Chris@0: protected function getTestMethodCaller() { Chris@0: $backtrace = debug_backtrace(); Chris@0: // Find the test class that has the test method. Chris@0: while ($caller = Error::getLastCaller($backtrace)) { Chris@0: if (isset($caller['class']) && $caller['class'] === get_class($this)) { Chris@0: break; Chris@0: } Chris@0: // If the test method is implemented by a test class's parent then the Chris@0: // class name of $this will not be part of the backtrace. Chris@0: // In that case we process the backtrace until the caller is not a Chris@0: // subclass of $this and return the previous caller. Chris@0: if (isset($last_caller) && (!isset($caller['class']) || !is_subclass_of($this, $caller['class']))) { Chris@0: // Return the last caller since that has to be the test class. Chris@0: $caller = $last_caller; Chris@0: break; Chris@0: } Chris@0: // Otherwise we have not reached our test class yet: save the last caller Chris@0: // and remove an element from to backtrace to process the next call. Chris@0: $last_caller = $caller; Chris@0: array_shift($backtrace); Chris@0: } Chris@0: Chris@0: return $caller; Chris@0: } Chris@0: Chris@0: /** Chris@16: * Transforms a nested array into a flat array suitable for drupalPostForm(). Chris@16: * Chris@16: * @param array $values Chris@16: * A multi-dimensional form values array to convert. Chris@16: * Chris@16: * @return array Chris@16: * The flattened $edit array suitable for BrowserTestBase::drupalPostForm(). Chris@16: */ Chris@16: protected function translatePostValues(array $values) { Chris@16: $edit = []; Chris@16: // The easiest and most straightforward way to translate values suitable for Chris@16: // BrowserTestBase::drupalPostForm() is to actually build the POST data Chris@16: // string and convert the resulting key/value pairs back into a flat array. Chris@16: $query = http_build_query($values); Chris@16: foreach (explode('&', $query) as $item) { Chris@16: list($key, $value) = explode('=', $item); Chris@16: $edit[urldecode($key)] = urldecode($value); Chris@16: } Chris@16: return $edit; Chris@16: } Chris@16: Chris@0: }