class ViewKernelTestBase

Defines a base class for Views unit testing.

Use this test class for unit tests of Views functionality. If a test requires the full web test environment provided by WebTestBase, extend ViewTestBase instead.

Hierarchy

Expanded class hierarchy of ViewKernelTestBase

Deprecated

in drupal:8.0.0 and is removed from drupal:9.0.0. Use \Drupal\Tests\views\Kernel\ViewsKernelTestBase instead.

See also

\Drupal\Tests\views\Kernel\ViewsKernelTestBase

1 file declares its use of ViewKernelTestBase
PluginKernelTestBase.php in core/modules/views/src/Tests/Plugin/PluginKernelTestBase.php

File

core/modules/views/src/Tests/ViewKernelTestBase.php, line 23

Namespace

Drupal\views\Tests
View source
abstract class ViewKernelTestBase extends KernelTestBase {
    use ViewResultAssertionTrait;
    
    /**
     * Modules to enable.
     *
     * @var array
     */
    public static $modules = [
        'system',
        'views',
        'views_test_config',
        'views_test_data',
        'user',
    ];
    
    /**
     * {@inheritdoc}
     *
     * @param bool $import_test_views
     *   Should the views specified on the test class be imported. If you need
     *   to setup some additional stuff, like fields, you need to call false and
     *   then call createTestViews for your own.
     */
    protected function setUp($import_test_views = TRUE) {
        parent::setUp();
        $this->installSchema('system', [
            'sequences',
        ]);
        $this->setUpFixtures();
        if ($import_test_views) {
            ViewTestData::createTestViews(get_class($this), [
                'views_test_config',
            ]);
        }
    }
    
    /**
     * Sets up the configuration and schema of views and views_test_data modules.
     *
     * Because the schema of views_test_data.module is dependent on the test
     * using it, it cannot be enabled normally.
     */
    protected function setUpFixtures() {
        // First install the system module. Many Views have Page displays have menu
        // links, and for those to work, the system menus must already be present.
        $this->installConfig([
            'system',
        ]);
        // Define the schema and views data variable before enabling the test module.
        \Drupal::state()->set('views_test_data_schema', $this->schemaDefinition());
        \Drupal::state()->set('views_test_data_views_data', $this->viewsData());
        $this->installConfig([
            'views',
            'views_test_config',
            'views_test_data',
        ]);
        foreach ($this->schemaDefinition() as $table => $schema) {
            $this->installSchema('views_test_data', $table);
        }
        \Drupal::service('router.builder')->rebuild();
        // Load the test dataset.
        $data_set = $this->dataSet();
        $query = Database::getConnection()->insert('views_test_data')
            ->fields(array_keys($data_set[0]));
        foreach ($data_set as $record) {
            $query->values($record);
        }
        $query->execute();
    }
    
    /**
     * Orders a nested array containing a result set based on a given column.
     *
     * @param array $result_set
     *   An array of rows from a result set, with each row as an associative
     *   array keyed by column name.
     * @param string $column
     *   The column name by which to sort the result set.
     * @param bool $reverse
     *   (optional) Boolean indicating whether to sort the result set in reverse
     *   order. Defaults to FALSE.
     *
     * @return array
     *   The sorted result set.
     */
    protected function orderResultSet($result_set, $column, $reverse = FALSE) {
        $order = $reverse ? -1 : 1;
        usort($result_set, function ($a, $b) use ($column, $order) {
            if ($a[$column] == $b[$column]) {
                return 0;
            }
            return $order * ($a[$column] < $b[$column] ? -1 : 1);
        });
        return $result_set;
    }
    
    /**
     * Executes a view with debugging.
     *
     * @param \Drupal\views\ViewExecutable $view
     *   The view object.
     * @param array $args
     *   (optional) An array of the view arguments to use for the view.
     */
    protected function executeView($view, array $args = []) {
        $view->setDisplay();
        $view->preExecute($args);
        $view->execute();
        $verbose_message = '<pre>Executed view: ' . (string) $view->build_info['query'] . '</pre>';
        if ($view->build_info['query'] instanceof SelectInterface) {
            $verbose_message .= '<pre>Arguments: ' . print_r($view->build_info['query']
                ->getArguments(), TRUE) . '</pre>';
        }
        $this->verbose($verbose_message);
    }
    
    /**
     * Returns the schema definition.
     *
     * @internal
     */
    protected function schemaDefinition() {
        return ViewTestData::schemaDefinition();
    }
    
    /**
     * Returns the views data definition.
     */
    protected function viewsData() {
        return ViewTestData::viewsData();
    }
    
    /**
     * Returns a very simple test dataset.
     */
    protected function dataSet() {
        return ViewTestData::dataSet();
    }

}

Members

Title Sort descending Deprecated Modifiers Object type Summary Overriden Title Overrides
AssertHelperTrait::castSafeStrings protected static function Casts MarkupInterface objects into strings.
ConfigTestTrait::configImporter protected function Returns a ConfigImporter object to import test configuration.
ConfigTestTrait::copyConfig protected function Copies configuration objects from source storage to target storage.
GeneratePermutationsTrait::generatePermutations public static function Converts a list of possible parameters into a stack of permutations.
KernelTestBase::$configDirectories protected property The configuration directories for this test run.
KernelTestBase::$keyValueFactory protected property A KeyValueMemoryFactory instance to use when building the container.
KernelTestBase::$moduleFiles private property
KernelTestBase::$streamWrappers protected property Array of registered stream wrappers.
KernelTestBase::$themeFiles private property
KernelTestBase::beforePrepareEnvironment protected function Act on global state information before the environment is altered for a test. Overrides TestBase::beforePrepareEnvironment
KernelTestBase::containerBuild public function Sets up the base service container for this test.
KernelTestBase::defaultLanguageData protected function Provides the data for setting the default language on the container.
KernelTestBase::disableModules protected function Disables modules for this test.
KernelTestBase::enableModules protected function Enables modules for this test.
KernelTestBase::installConfig protected function Installs default configuration for a given list of modules.
KernelTestBase::installEntitySchema protected function Installs the storage schema for a specific entity type.
KernelTestBase::installSchema protected function Installs a specific table from a module schema definition.
KernelTestBase::prepareConfigDirectories protected function Create and set new configuration directories.
KernelTestBase::registerStreamWrapper protected function Registers a stream wrapper for this test.
KernelTestBase::render protected function Renders a render array.
KernelTestBase::tearDown protected function Performs cleanup tasks after each individual test method has been run. Overrides TestBase::tearDown 1
KernelTestBase::__construct public function Constructor for Test. Overrides TestBase::__construct
RandomGeneratorTrait::$randomGenerator protected property The random generator.
RandomGeneratorTrait::getRandomGenerator protected function Gets the random generator for the utility methods.
RandomGeneratorTrait::randomMachineName protected function Generates a unique random string containing letters and numbers. 1
RandomGeneratorTrait::randomObject public function Generates a random PHP object.
RandomGeneratorTrait::randomString public function Generates a pseudo-random string of ASCII characters of codes 32 to 126.
RandomGeneratorTrait::randomStringValidate public function Callback for random string validation.
StorageCopyTrait::replaceStorageContents protected static function Copy the configuration from one storage to another and remove stale items.
TestBase::$assertions protected property Assertions thrown in that test case.
TestBase::$configImporter protected property The config importer that can used in a 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::$httpAuthCredentials protected property HTTP authentication credentials (&lt;username&gt;:&lt;password&gt;).
TestBase::$httpAuthMethod protected property HTTP authentication method (specified as a CURLAUTH_* constant).
TestBase::$originalConf protected property The original configuration (variables), if available.
TestBase::$originalConfig protected property The original configuration (variables).
TestBase::$originalConfigDirectories protected property The original configuration directories.
TestBase::$originalContainer protected property The original container.
TestBase::$originalFileDirectory protected property The original file directory, before it was changed for testing purposes.
TestBase::$originalLanguage protected property The original language.
TestBase::$originalPrefix protected property The original database prefix when running inside Simpletest.
TestBase::$originalSessionName protected property The name of the session cookie of the test-runner.
TestBase::$originalSettings protected property The settings array.
TestBase::$originalShutdownCallbacks protected property The original array of shutdown function callbacks. 1
TestBase::$originalUser protected property The original user, before testing began. 1
TestBase::$results public property Current results of this test case.
TestBase::$skipClasses protected property This class is skipped when looking for the source of an assertion.
TestBase::$timeLimit protected property Time limit for the test.
TestBase::$translationFilesDirectory protected property The translation file directory for the test environment.
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::assertErrorLogged protected function Asserts that a specific error has been logged to the PHP error log.
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::checkRequirements protected function Checks the matching requirements for Test. 1
TestBase::checkTestHierarchyMismatch public function Fail the test if it belongs to a PHPUnit-based framework.
TestBase::config protected function Configuration accessor for tests. Returns non-overridden configuration.
TestBase::deleteAssert public static function Delete an assertion record by message ID.
TestBase::error protected function Fire an error assertion. 1
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.
TestBase::getAssertionCall protected function Cycles through backtrace until the first non-assertion method is found.
TestBase::getDatabasePrefix public function Gets the database prefix.
TestBase::getTempFilesDirectory public function Gets the temporary files directory.
TestBase::insertAssert Deprecated public static function Store an assertion from outside the testing context. 1
TestBase::pass protected function Fire an assertion that is always positive.
TestBase::prepareDatabasePrefix private function Generates a database prefix for running tests. Overrides TestSetupTrait::prepareDatabasePrefix
TestBase::prepareEnvironment private function Prepares the current environment for running the test.
TestBase::restoreEnvironment private function Cleans up the test environment and restores the original environment.
TestBase::run public function Run all tests in this class. 2
TestBase::settingsSet protected function Changes in memory settings.
TestBase::storeAssertion protected function Helper method to store an assertion record in the configured database. 1
TestBase::verbose protected function Logs a verbose message in a text file.
TestSetupTrait::$configSchemaCheckerExclusions protected static property An array of config object names that are excluded from schema checking.
TestSetupTrait::$container protected property The dependency injection container used in the test.
TestSetupTrait::$kernel protected property The DrupalKernel instance used in the test.
TestSetupTrait::$originalSite protected property The site directory of the original parent site.
TestSetupTrait::$privateFilesDirectory protected property The private file directory for the test environment.
TestSetupTrait::$publicFilesDirectory protected property The public file directory for the test environment.
TestSetupTrait::$siteDirectory protected property The site directory of this test run.
TestSetupTrait::$strictConfigSchema protected property Set to TRUE to strict check all configuration saved. 2
TestSetupTrait::$tempFilesDirectory protected property The temporary file directory for the test environment.
TestSetupTrait::$testId protected property The test run ID.
TestSetupTrait::changeDatabasePrefix protected function Changes the database connection to the prefixed one.
TestSetupTrait::getConfigSchemaExclusions protected function Gets the config schema exclusions for this test.
TestSetupTrait::getDatabaseConnection public static function Returns the database connection to the site running Simpletest.
ViewKernelTestBase::$modules public static property Modules to enable. Overrides KernelTestBase::$modules
ViewKernelTestBase::dataSet protected function Returns a very simple test dataset.
ViewKernelTestBase::executeView protected function Executes a view with debugging.
ViewKernelTestBase::orderResultSet protected function Orders a nested array containing a result set based on a given column.
ViewKernelTestBase::schemaDefinition protected function Returns the schema definition.
ViewKernelTestBase::setUp protected function Overrides KernelTestBase::setUp
ViewKernelTestBase::setUpFixtures protected function Sets up the configuration and schema of views and views_test_data modules.
ViewKernelTestBase::viewsData protected function Returns the views data definition.
ViewResultAssertionTrait::assertIdenticalResultset protected function Verifies that a result set returned by a View matches expected values.
ViewResultAssertionTrait::assertIdenticalResultsetHelper protected function Performs View result assertions.
ViewResultAssertionTrait::assertNotIdenticalResultset protected function Verifies that a result set returned by a View differs from certain values.

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.