abstract class ModuleTestBase

You are here

Helper class for module test cases.

Namespace

Drupal\system\Tests\Module

Hierarchy

Expanded class hierarchy of ModuleTestBase

Members

Contains filters are case sensitive
Namesort descending Modifiers Type Description
ModuleTestBase::$admin_user protected property
ModuleTestBase::$modules public static property Modules to enable.
ModuleTestBase::assertLogMessage function Verify a log entry was entered for a module's status change. Called in the same way of the expected original watchdog() execution.
ModuleTestBase::assertModuleConfig function Asserts that the default configuration of a module has been installed.
ModuleTestBase::assertModules function Assert the list of modules are enabled or disabled.
ModuleTestBase::assertModuleTablesDoNotExist function Assert that none of the tables defined in a module's hook_schema() exist.
ModuleTestBase::assertModuleTablesExist function Assert that all tables defined in a module's hook_schema() exist.
ModuleTestBase::assertNoModuleConfig function Asserts that no configuration exists for a given module.
ModuleTestBase::assertTableCount function Assert there are tables that begin with the specified base table name.
ModuleTestBase::setUp function Sets up a Drupal site for running functional and integration tests. Overrides WebTestBase::setUp
TestBase::$assertions protected property Assertions thrown in that test case.
TestBase::$configImporter protected property The config importer that can used in a test.
TestBase::$container protected property The dependency injection container used in the test.
TestBase::$databasePrefix protected property The database prefix of this test run.
TestBase::$dieOnFail public property Whether to die in case any test assertion fails.
TestBase::$originalFileDirectory protected property The original file directory, before it was changed for testing purposes.
TestBase::$originalPrefix protected property The original database prefix when running inside Simpletest.
TestBase::$originalSettings protected property The settings array.
TestBase::$public_files_directory protected property The public file directory for the test environment.
TestBase::$randomGenerator protected property The random generator.
TestBase::$results public property Current results of this test case.
TestBase::$siteDirectory protected property The site directory of this test run.
TestBase::$skipClasses protected property This class is skipped when looking for the source of an assertion.
TestBase::$testId protected property The test run ID.
TestBase::$timeLimit protected property Time limit for the test.
TestBase::$verbose public property TRUE if verbose debugging is enabled.
TestBase::$verboseClassName protected property Safe class name for use in verbose output filenames.
TestBase::$verboseDirectory protected property Directory where verbose output files are put.
TestBase::$verboseDirectoryUrl protected property URL to the verbose output file directory.
TestBase::$verboseId protected property Incrementing identifier for verbose output filenames.
TestBase::assert protected function Internal helper: stores the assert.
TestBase::assertEqual protected function Check to see if two values are equal.
TestBase::assertFalse protected function Check to see if a value is false.
TestBase::assertIdentical protected function Check to see if two values are identical.
TestBase::assertIdenticalObject protected function Checks to see if two objects are identical.
TestBase::assertNoErrorsLogged protected function Asserts that no errors have been logged to the PHP error.log thus far.
TestBase::assertNotEqual protected function Check to see if two values are not equal.
TestBase::assertNotIdentical protected function Check to see if two values are not identical.
TestBase::assertNotNull protected function Check to see if a value is not NULL.
TestBase::assertNull protected function Check to see if a value is NULL.
TestBase::assertTrue protected function Check to see if a value is not false.
TestBase::beforePrepareEnvironment protected function Act on global state information before the environment is altered for a test.
TestBase::changeDatabasePrefix private function Changes the database connection to the prefixed one.
TestBase::checkRequirements protected function Checks the matching requirements for Test.
TestBase::configImporter public function Returns a ConfigImporter object to import test importing of configuration.
TestBase::copyConfig public function Copies configuration objects from source storage to target storage.
TestBase::deleteAssert public static function Delete an assertion record by message ID.
TestBase::error protected function Fire an error assertion.
TestBase::errorHandler public function Handle errors during test runs.
TestBase::exceptionHandler protected function Handle exceptions.
TestBase::fail protected function Fire an assertion that is always negative.
TestBase::filePreDeleteCallback public static function Ensures test files are deletable within file_unmanaged_delete_recursive().
TestBase::generatePermutations public static function Converts a list of possible parameters into a stack of permutations.
TestBase::getAssertionCall protected function Cycles through backtrace until the first non-assertion method is found.
TestBase::getDatabaseConnection public static function Returns the database connection to the site running Simpletest.
TestBase::getInfo public static function Provides meta information about this test case, such as test name.
TestBase::getRandomGenerator protected function Gets the random generator for the utility methods.
TestBase::insertAssert public static function Store an assertion from outside the testing context.
TestBase::pass protected function Fire an assertion that is always positive.
TestBase::prepareDatabasePrefix private function Generates a database prefix for running tests.
TestBase::prepareEnvironment private function Prepares the current environment for running the test.
TestBase::randomName public function Generates a unique random string containing letters and numbers.
TestBase::randomObject public function Generates a random PHP object.
TestBase::randomString public function Generates a unique random string of ASCII characters of codes 32 to 126.
TestBase::randomStringValidate public function Callback for random string validation.
TestBase::restoreEnvironment private function Cleans up the test environment and restores the original environment.
TestBase::run public function Run all tests in this class.
TestBase::settingsSet protected function Changes in memory settings.
TestBase::verbose protected function Logs verbose message in a text file.
WebTestBase::$additionalCurlOptions protected property Additional cURL options.
WebTestBase::$configDirectories protected property The config directories used in this test.
WebTestBase::$content protected property The content of the page currently loaded in the internal browser.
WebTestBase::$cookieFile protected property The current cookie file used by cURL.
WebTestBase::$curlCookies protected property Cookies to set on curl requests.
WebTestBase::$curlHandle protected property The handle of the current cURL connection.
WebTestBase::$customTranslations protected property An array of custom translations suitable for drupal_rewrite_settings().
WebTestBase::$drupalSettings protected property The value of drupalSettings for the currently-loaded page.
WebTestBase::$dumpHeaders protected property Indicates that headers should be dumped if verbose output is enabled.
WebTestBase::$elements protected property The parsed version of the page.
WebTestBase::$generatedTestFiles protected property Whether the files were copied to the test files directory.
WebTestBase::$headers protected property The headers of the page currently loaded in the internal browser.
WebTestBase::$httpauth_credentials protected property HTTP authentication credentials (<username>:<password>).
WebTestBase::$httpauth_method protected property HTTP authentication method.
WebTestBase::$kernel protected property The kernel used in this test. Overrides TestBase::$kernel
WebTestBase::$loggedInUser protected property The current user logged in using the internal browser.
WebTestBase::$maximumRedirects protected property The maximum number of redirects to follow when handling responses.
WebTestBase::$originalShutdownCallbacks protected property The original shutdown handlers array, before it was cleaned for testing.
WebTestBase::$originalUser protected property The original user, before it was changed to a clean uid = 1 for testing.
WebTestBase::$plainTextContent protected property The plain-text content of the currently-loaded page.
WebTestBase::$profile protected property The profile to install as a basis for testing.
WebTestBase::$redirect_count protected property The number of redirects followed during the handling of a request.
WebTestBase::$session_id protected property The current session ID, if available.
WebTestBase::$session_name protected property The current session name, if available.
WebTestBase::$url protected property The URL currently loaded in the internal browser.
WebTestBase::addCustomTranslations protected function Queues custom translations to be written to settings.php.
WebTestBase::assertBlockAppears protected function Checks to see whether a block appears on the page.
WebTestBase::assertField protected function Asserts that a field exists with the given name or id.
WebTestBase::assertFieldById protected function Asserts that a field exists with the given id and value.
WebTestBase::assertFieldByName protected function Asserts that a field exists with the given name and value.
WebTestBase::assertFieldByXPath protected function Asserts that a field exists in the current page by the given XPath.
WebTestBase::assertFieldChecked protected function Asserts that a checkbox field in the current page is checked.
WebTestBase::assertLink protected function Passes if a link with the specified label is found.
WebTestBase::assertLinkByHref protected function Passes if a link containing a given href (part) is found.
WebTestBase::assertMail protected function Asserts that the most recently sent e-mail message has the given value.
WebTestBase::assertMailPattern protected function Asserts that the most recently sent e-mail message has the pattern in it.
WebTestBase::assertMailString protected function Asserts that the most recently sent e-mail message has the string in it.
WebTestBase::assertNoBlockAppears protected function Checks to see whether a block does not appears on the page.
WebTestBase::assertNoDuplicateIds protected function Asserts that each HTML ID is used for just a single element.
WebTestBase::assertNoField protected function Asserts that a field does not exist with the given name or id.
WebTestBase::assertNoFieldById protected function Asserts that a field does not exist with the given id and value.
WebTestBase::assertNoFieldByName protected function Asserts that a field does not exist with the given name and value.
WebTestBase::assertNoFieldByXPath protected function Asserts that a field does not exist in the current page by the given XPath.
WebTestBase::assertNoFieldChecked protected function Asserts that a checkbox field in the current page is not checked.
WebTestBase::assertNoLink protected function Passes if a link with the specified label is not found.
WebTestBase::assertNoLinkByHref protected function Passes if a link containing a given href (part) is not found.
WebTestBase::assertNoOption protected function Asserts that a select option in the current page does not exist.
WebTestBase::assertNoOptionSelected protected function Asserts that a select option in the current page is not checked.
WebTestBase::assertNoPattern protected function Triggers a pass if the perl regex pattern is not found in raw content.
WebTestBase::assertNoRaw protected function Passes if the raw text is NOT found on the loaded page, fail otherwise.
WebTestBase::assertNoResponse protected function Asserts the page did not return the specified response code.
WebTestBase::assertNoText protected function Passes if the text is NOT found on the text version of the page.
WebTestBase::assertNoTitle protected function Pass if the page title is not the given string.
WebTestBase::assertNoUniqueText protected function Passes if the text is found MORE THAN ONCE on the text version of the page.
WebTestBase::assertOption protected function Asserts that a select option in the current page exists.
WebTestBase::assertOptionSelected protected function Asserts that a select option in the current page is checked.
WebTestBase::assertPattern protected function Triggers a pass if the Perl regex pattern is found in the raw content.
WebTestBase::assertRaw protected function Passes if the raw text IS found on the loaded page, fail otherwise.
WebTestBase::assertResponse protected function Asserts the page responds with the specified response code.
WebTestBase::assertText protected function Passes if the text IS found on the text version of the page.
WebTestBase::assertTextHelper protected function Helper for assertText and assertNoText.
WebTestBase::assertThemeOutput protected function Asserts themed output.
WebTestBase::assertTitle protected function Pass if the page title is the given string.
WebTestBase::assertUniqueText protected function Passes if the text is found ONLY ONCE on the text version of the page.
WebTestBase::assertUniqueTextHelper protected function Helper for assertUniqueText and assertNoUniqueText.
WebTestBase::assertUrl protected function Passes if the internal browser's URL matches the given path.
WebTestBase::buildXPathQuery protected function Builds an XPath query.
WebTestBase::checkForMetaRefresh protected function Checks for meta refresh tag and if found call drupalGet() recursively.
WebTestBase::checkPermissions protected function Check to make sure that the array of permissions are valid.
WebTestBase::clickLink protected function Follows a link by name.
WebTestBase::constructFieldXpath protected function Helper: Constructs an XPath for the given set of attributes and value.
WebTestBase::cronRun protected function Runs cron in the Drupal installed by Simpletest.
WebTestBase::curlClose protected function Close the cURL handler and unset the handler.
WebTestBase::curlExec protected function Initializes and executes a cURL request.
WebTestBase::curlHeaderCallback protected function Reads headers and registers errors received from the tested site.
WebTestBase::curlInitialize protected function Initializes the cURL connection.
WebTestBase::drupalCompareFiles protected function Compare two files based on size and file name.
WebTestBase::drupalCreateContentType protected function Creates a custom content type based on default settings.
WebTestBase::drupalCreateNode protected function Creates a node based on default settings.
WebTestBase::drupalCreateRole protected function Creates a role with specified permissions.
WebTestBase::drupalCreateUser protected function Create a user with a given set of permissions.
WebTestBase::drupalGet protected function Retrieves a Drupal path or an absolute path.
WebTestBase::drupalGetAJAX protected function Requests a Drupal path in drupal_ajax format and JSON-decodes the response.
WebTestBase::drupalGetContent protected function Gets the current raw HTML of requested page.
WebTestBase::drupalGetHeader protected function Gets the value of an HTTP response header.
WebTestBase::drupalGetHeaders protected function Gets the HTTP response headers of the requested page.
WebTestBase::drupalGetJSON protected function Retrieves a Drupal path or an absolute path and JSON decode the result.
WebTestBase::drupalGetMails protected function Gets an array containing all e-mails sent during this test case.
WebTestBase::drupalGetNodeByTitle function Get a node from the database based on its title.
WebTestBase::drupalGetSettings protected function Gets the value of drupalSettings for the currently-loaded page.
WebTestBase::drupalGetTestFiles protected function Gets a list files that can be used in tests.
WebTestBase::drupalGetToken protected function Generate a token for the currently logged in user.
WebTestBase::drupalHead protected function Retrieves only the headers for a Drupal path or an absolute path.
WebTestBase::drupalLogin protected function Log in a user with the internal browser.
WebTestBase::drupalLogout protected function Logs a user out of the internal browser and confirms.
WebTestBase::drupalPlaceBlock protected function Creates a block instance based on default settings.
WebTestBase::drupalPost protected function Perform a POST HTTP request.
WebTestBase::drupalPostAjaxForm protected function Executes an Ajax form submission.
WebTestBase::drupalPostForm protected function Executes a form submission.
WebTestBase::drupalProcessAjaxResponse protected function Processes an AJAX response into current content.
WebTestBase::drupalSetContent protected function Sets the raw HTML content.
WebTestBase::drupalSetSettings protected function Sets the value of drupalSettings for the currently-loaded page.
WebTestBase::drupalUserIsLoggedIn protected function Returns whether a given user account is logged in.
WebTestBase::findBlockInstance protected function Find a block instance on the page.
WebTestBase::getAbsoluteUrl protected function Takes a path and returns an absolute path.
WebTestBase::getAjaxPageStatePostData protected function Get the Ajax page state from drupalSettings and prepare it for POSTing.
WebTestBase::getAllOptions protected function Get all option elements, including nested options, in a select.
WebTestBase::getSelectedItem protected function Get the selected value from a select field.
WebTestBase::getUrl protected function Get the current URL from the cURL handler.
WebTestBase::handleForm protected function Handles form input related to drupalPostForm().
WebTestBase::installParameters protected function Returns the parameters that will be used when Simpletest installs Drupal.
WebTestBase::isInChildSite protected function Returns whether the test is being executed from within a test site.
WebTestBase::parse protected function Parse content returned from curlExec using DOM and SimpleXML.
WebTestBase::prepareRequestForGenerator protected function Creates a mock request and sets it on the generator.
WebTestBase::rebuildContainer protected function Overrides \Drupal\simpletest\TestBase::rebuildContainer(). Overrides TestBase::rebuildContainer
WebTestBase::refreshVariables protected function Refreshes in-memory configuration and state information.
WebTestBase::resetAll protected function Resets all data structures after having enabled new modules.
WebTestBase::serializePostValues protected function Serialize POST HTTP request values.
WebTestBase::tearDown protected function Cleans up after testing. Overrides TestBase::tearDown
WebTestBase::translatePostValues protected function Transforms a nested array into a flat array suitable for WebTestBase::drupalPostForm().
WebTestBase::verboseEmail protected function Outputs to verbose the most recent $count emails sent.
WebTestBase::writeCustomTranslations protected function Writes custom translations to the test site's settings.php.
WebTestBase::writeSettings protected function Rewrites the settings.php file of the test site.
WebTestBase::xpath protected function Performs an xpath search on the contents of the internal browser.
WebTestBase::__construct function Constructor for \Drupal\simpletest\WebTestBase. Overrides TestBase::__construct

File

core/modules/system/lib/Drupal/system/Tests/Module/ModuleTestBase.php, line 18
Definition of Drupal\system\Tests\Module\ModuleTestBase.

View source
abstract class ModuleTestBase extends WebTestBase {

  /**
   * Modules to enable.
   *
   * @var array
   */
  public static $modules = array('system_test');

  protected $admin_user;

  function setUp() {
    parent::setUp();

    $this->admin_user = $this->drupalCreateUser(array('access administration pages', 'administer modules'));
    $this->drupalLogin($this->admin_user);
  }

  /**
   * Assert there are tables that begin with the specified base table name.
   *
   * @param $base_table
   *   Beginning of table name to look for.
   * @param $count
   *   (optional) Whether or not to assert that there are tables that match the
   *   specified base table. Defaults to TRUE.
   */
  function assertTableCount($base_table, $count = TRUE) {
    $tables = db_find_tables(Database::getConnection()->prefixTables('{' . $base_table . '}') . '%');

    if ($count) {
      return $this->assertTrue($tables, format_string('Tables matching "@base_table" found.', array('@base_table' => $base_table)));
    }
    return $this->assertFalse($tables, format_string('Tables matching "@base_table" not found.', array('@base_table' => $base_table)));
  }

  /**
   * Assert that all tables defined in a module's hook_schema() exist.
   *
   * @param $module
   *   The name of the module.
   */
  function assertModuleTablesExist($module) {
    $this->rebuildContainer();
    $tables = array_keys(drupal_get_schema_unprocessed($module));
    $tables_exist = TRUE;
    foreach ($tables as $table) {
      if (!db_table_exists($table)) {
        $tables_exist = FALSE;
      }
    }
    return $this->assertTrue($tables_exist, format_string('All database tables defined by the @module module exist.', array('@module' => $module)));
  }

  /**
   * Assert that none of the tables defined in a module's hook_schema() exist.
   *
   * @param $module
   *   The name of the module.
   */
  function assertModuleTablesDoNotExist($module) {
    $tables = array_keys(drupal_get_schema_unprocessed($module));
    $tables_exist = FALSE;
    foreach ($tables as $table) {
      if (db_table_exists($table)) {
        $tables_exist = TRUE;
      }
    }
    return $this->assertFalse($tables_exist, format_string('None of the database tables defined by the @module module exist.', array('@module' => $module)));
  }

  /**
   * Asserts that the default configuration of a module has been installed.
   *
   * @param string $module
   *   The name of the module.
   *
   * @return bool
   *   TRUE if configuration has been installed, FALSE otherwise.
   */
  function assertModuleConfig($module) {
    $module_config_dir = drupal_get_path('module', $module) . '/' . InstallStorage::CONFIG_INSTALL_DIRECTORY;
    if (!is_dir($module_config_dir)) {
      return;
    }
    $module_file_storage = new FileStorage($module_config_dir);

    // Verify that the module's default config directory is not empty and
    // contains default configuration files (instead of something else).
    $all_names = $module_file_storage->listAll();
    if (empty($all_names)) {
      // Module has an empty config directory. For example it might contain a
      // schema directory.
      return;
    }
    $this->assertTrue($all_names);

    // Look up each default configuration object name in the active
    // configuration, and if it exists, remove it from the stack.
    // Only default config that belongs to $module is guaranteed to exist; any
    // other default config depends on whether other modules are enabled. Thus,
    // list all default config once more, but filtered by $module.
    $names = $module_file_storage->listAll($module . '.');
    foreach ($names as $key => $name) {
      if (\Drupal::config($name)->get()) {
        unset($names[$key]);
      }
    }
    // Verify that all configuration has been installed (which means that $names
    // is empty).
    return $this->assertFalse($names, format_string('All default configuration of @module module found.', array('@module' => $module)));
  }

  /**
   * Asserts that no configuration exists for a given module.
   *
   * @param string $module
   *   The name of the module.
   *
   * @return bool
   *   TRUE if no configuration was found, FALSE otherwise.
   */
  function assertNoModuleConfig($module) {
    $names = \Drupal::configFactory()->listAll($module . '.');
    return $this->assertFalse($names, format_string('No configuration found for @module module.', array('@module' => $module)));
  }

  /**
   * Assert the list of modules are enabled or disabled.
   *
   * @param $modules
   *   Module list to check.
   * @param $enabled
   *   Expected module state.
   */
  function assertModules(array $modules, $enabled) {
    $this->rebuildContainer();
    foreach ($modules as $module) {
      if ($enabled) {
        $message = 'Module "@module" is enabled.';
      }
      else {
        $message = 'Module "@module" is not enabled.';
      }
      $this->assertEqual($this->container->get('module_handler')->moduleExists($module), $enabled, format_string($message, array('@module' => $module)));
    }
  }

  /**
   * Verify a log entry was entered for a module's status change.
   * Called in the same way of the expected original watchdog() execution.
   *
   * @param $type
   *   The category to which this message belongs.
   * @param $message
   *   The message to store in the log. Keep $message translatable
   *   by not concatenating dynamic values into it! Variables in the
   *   message should be added by using placeholder strings alongside
   *   the variables argument to declare the value of the placeholders.
   *   See t() for documentation on how $message and $variables interact.
   * @param $variables
   *   Array of variables to replace in the message on display or
   *   NULL if message is already translated or not possible to
   *   translate.
   * @param $severity
   *   The severity of the message, as per RFC 3164.
   * @param $link
   *   A link to associate with the message.
   */
  function assertLogMessage($type, $message, $variables = array(), $severity = WATCHDOG_NOTICE, $link = '') {
    $count = db_select('watchdog', 'w')->condition('type', $type)->condition('message', $message)->condition('variables', serialize($variables))->condition('severity', $severity)->condition('link', $link)->countQuery()->execute()->fetchField();
    $this->assertTrue($count > 0, format_string('watchdog table contains @count rows for @message', array('@count' => $count, '@message' => format_string($message, $variables))));
  }
}
1 file declares its use of ModuleTestBase
ConfigImportAllTest.php in core/modules/config/lib/Drupal/config/Tests/ConfigImportAllTest.php
Contains \Drupal\config\Tests\ConfigImportAllTest.