class ModuleTest

Hierarchy

Expanded class hierarchy of ModuleTest

File

drupal/core/modules/views/lib/Drupal/views/Tests/ModuleTest.php, line 16
Definition of Drupal\views\Tests\ModuleTest.

Namespace

Drupal\views\Tests
View source
class ModuleTest extends ViewUnitTestBase {

  /**
   * Views used by this test.
   *
   * @var array
   */
  public static $testViews = array(
    'test_view_status',
  );

  /**
   * Stores the last triggered error, for example via debug().
   *
   * @var string
   *
   * @see \Drupal\views\Tests\ModuleTest::errorHandler()
   */
  protected $lastErrorMessage;
  public static function getInfo() {
    return array(
      'name' => 'Views Module tests',
      'description' => 'Tests some basic functions of views.module.',
      'group' => 'Views',
    );
  }

  /**
   * Tests the views_get_handler method.
   *
   * @see views_get_handler()
   */
  public function testViewsGetHandler() {
    $types = array(
      'field',
      'area',
      'filter',
    );
    foreach ($types as $type) {
      $item = array(
        'table' => $this
          ->randomName(),
        'field' => $this
          ->randomName(),
      );
      $handler = views_get_handler($item, $type);
      $this
        ->assertEqual('Drupal\\views\\Plugin\\views\\' . $type . '\\Broken', get_class($handler), t('Make sure that a broken handler of type: @type are created', array(
        '@type' => $type,
      )));
    }
    $views_data = $this
      ->viewsData();
    $test_tables = array(
      'views_test_data' => array(
        'id',
        'name',
      ),
    );
    foreach ($test_tables as $table => $fields) {
      foreach ($fields as $field) {
        $data = $views_data[$table][$field];
        $item = array(
          'table' => $table,
          'field' => $field,
        );
        foreach ($data as $id => $field_data) {
          if (!in_array($id, array(
            'title',
            'help',
          ))) {
            $handler = views_get_handler($item, $id);
            $this
              ->assertInstanceHandler($handler, $table, $field, $id);
          }
        }
      }
    }

    // Test the override handler feature.
    $item = array(
      'table' => 'views_test_data',
      'field' => 'job',
    );
    $handler = views_get_handler($item, 'filter', 'standard');
    $this
      ->assertTrue($handler instanceof Standard);

    // @todo Reinstate these tests when the debug() in views_get_handler() is
    //   restored.
    return;

    // Test non-existent tables/fields.
    set_error_handler(array(
      $this,
      'customErrorHandler',
    ));
    $item = array(
      'table' => 'views_test_data',
      'field' => 'field_invalid',
    );
    views_get_handler($item, 'field');
    $this
      ->assertTrue(strpos($this->lastErrorMessage, format_string("Missing handler: @table @field @type", array(
      '@table' => 'views_test_data',
      '@field' => 'field_invalid',
      '@type' => 'field',
    ))) !== FALSE, 'An invalid field name throws a debug message.');
    unset($this->lastErrorMessage);
    $item = array(
      'table' => 'table_invalid',
      'field' => 'id',
    );
    views_get_handler($item, 'filter');
    $this
      ->assertEqual(strpos($this->lastErrorMessage, format_string("Missing handler: @table @field @type", array(
      '@table' => 'table_invalid',
      '@field' => 'id',
      '@type' => 'filter',
    ))) !== FALSE, 'An invalid table name throws a debug message.');
    unset($this->lastErrorMessage);
    $item = array(
      'table' => 'table_invalid',
      'field' => 'id',
      'optional' => FALSE,
    );
    views_get_handler($item, 'filter');
    $this
      ->assertEqual(strpos($this->lastErrorMessage, format_string("Missing handler: @table @field @type", array(
      '@table' => 'table_invalid',
      '@field' => 'id',
      '@type' => 'filter',
    ))) !== FALSE, 'An invalid table name throws a debug message.');
    unset($this->lastErrorMessage);
    $item = array(
      'table' => 'table_invalid',
      'field' => 'id',
      'optional' => TRUE,
    );
    views_get_handler($item, 'filter');
    $this
      ->assertFalse($this->lastErrorMessage, "An optional handler does not throw a debug message.");
    unset($this->lastErrorMessage);
    restore_error_handler();
  }

  /**
   * Defines an error handler which is used in the test.
   *
   * @param int $error_level
   *   The level of the error raised.
   * @param string $message
   *   The error message.
   * @param string $filename
   *   The filename that the error was raised in.
   * @param int $line
   *   The line number the error was raised at.
   * @param array $context
   *   An array that points to the active symbol table at the point the error
   *   occurred.
   *
   * Because this is registered in set_error_handler(), it has to be public.
   * @see set_error_handler()
   */
  public function customErrorHandler($error_level, $message, $filename, $line, $context) {
    $this->lastErrorMessage = $message;
  }

  /**
   * Tests the load wrapper/helper functions.
   */
  public function testLoadFunctions() {
    $this
      ->enableModules(array(
      'node',
    ));
    $controller = $this->container
      ->get('plugin.manager.entity')
      ->getStorageController('view');

    // Test views_view_is_enabled/disabled.
    $load = $controller
      ->load(array(
      'archive',
    ));
    $archive = reset($load);
    $this
      ->assertTrue(views_view_is_disabled($archive), 'views_view_is_disabled works as expected.');

    // Enable the view and check this.
    $archive
      ->enable();
    $this
      ->assertTrue(views_view_is_enabled($archive), ' views_view_is_enabled works as expected.');

    // We can store this now, as we have enabled/disabled above.
    $all_views = $controller
      ->load();

    // Test views_get_all_views().
    $this
      ->assertIdentical(array_keys($all_views), array_keys(views_get_all_views()), 'views_get_all_views works as expected.');

    // Test views_get_enabled_views().
    $expected_enabled = array_filter($all_views, function ($view) {
      return views_view_is_enabled($view);
    });
    $this
      ->assertIdentical(array_keys($expected_enabled), array_keys(views_get_enabled_views()), 'Expected enabled views returned.');

    // Test views_get_disabled_views().
    $expected_disabled = array_filter($all_views, function ($view) {
      return views_view_is_disabled($view);
    });
    $this
      ->assertIdentical(array_keys($expected_disabled), array_keys(views_get_disabled_views()), 'Expected disabled views returned.');

    // Test views_get_views_as_options().
    // Test the $views_only parameter.
    $this
      ->assertIdentical(array_keys($all_views), array_keys(views_get_views_as_options(TRUE)), 'Expected option keys for all views were returned.');
    $expected_options = array();
    foreach ($all_views as $id => $view) {
      $expected_options[$id] = $view
        ->label();
    }
    $this
      ->assertIdentical($expected_options, views_get_views_as_options(TRUE), 'Expected options array was returned.');

    // Test the default.
    $this
      ->assertIdentical($this
      ->formatViewOptions($all_views), views_get_views_as_options(), 'Expected options array for all views was returned.');

    // Test enabled views.
    $this
      ->assertIdentical($this
      ->formatViewOptions($expected_enabled), views_get_views_as_options(FALSE, 'enabled'), 'Expected enabled options array was returned.');

    // Test disabled views.
    $this
      ->assertIdentical($this
      ->formatViewOptions($expected_disabled), views_get_views_as_options(FALSE, 'disabled'), 'Expected disabled options array was returned.');

    // Test the sort parameter.
    $all_views_sorted = $all_views;
    ksort($all_views_sorted);
    $this
      ->assertIdentical(array_keys($all_views_sorted), array_keys(views_get_views_as_options(TRUE, 'all', NULL, FALSE, TRUE)), 'All view id keys returned in expected sort order');

    // Test $exclude_view parameter.
    $this
      ->assertFalse(array_key_exists('archive', views_get_views_as_options(TRUE, 'all', 'archive')), 'View excluded from options based on name');
    $this
      ->assertFalse(array_key_exists('archive:default', views_get_views_as_options(FALSE, 'all', 'archive:default')), 'View display excluded from options based on name');
    $this
      ->assertFalse(array_key_exists('archive', views_get_views_as_options(TRUE, 'all', $archive
      ->get('executable'))), 'View excluded from options based on object');

    // Test the $opt_group parameter.
    $expected_opt_groups = array();
    foreach ($all_views as $id => $view) {
      foreach ($view
        ->get('display') as $display_id => $display) {
        $expected_opt_groups[$view
          ->id()][$view
          ->id() . ':' . $display['id']] = t('@view : @display', array(
          '@view' => $view
            ->id(),
          '@display' => $display['id'],
        ));
      }
    }
    $this
      ->assertIdentical($expected_opt_groups, views_get_views_as_options(FALSE, 'all', NULL, TRUE), 'Expected option array for an option group returned.');
  }

  /**
   * Tests view enable and disable procedural wrapper functions.
   */
  function testStatusFunctions() {
    $view = views_get_view('test_view_status')->storage;
    $this
      ->assertFalse($view
      ->status(), 'The view status is disabled.');
    views_enable_view($view);
    $this
      ->assertTrue($view
      ->status(), 'A view has been enabled.');
    $this
      ->assertEqual($view
      ->status(), views_view_is_enabled($view), 'views_view_is_enabled is correct.');
    views_disable_view($view);
    $this
      ->assertFalse($view
      ->status(), 'A view has been disabled.');
    $this
      ->assertEqual(!$view
      ->status(), views_view_is_disabled($view), 'views_view_is_disabled is correct.');
  }

  /**
   * Tests the views_fetch_plugin_names() function.
   */
  public function testViewsFetchPluginNames() {

    // All style plugins should be returned, as we have not specified a type.
    $plugins = views_fetch_plugin_names('style');
    $definitions = Views::pluginManager('style')
      ->getDefinitions();
    $expected = array();
    foreach ($definitions as $id => $definition) {
      $expected[$id] = $definition['title'];
    }
    asort($expected);
    $this
      ->assertIdentical(array_keys($plugins), array_keys($expected));

    // Test using the 'test' style plugin type only returns the test_style and
    // mapping_test plugins.
    $plugins = views_fetch_plugin_names('style', 'test');
    $this
      ->assertIdentical(array_keys($plugins), array(
      'mapping_test',
      'test_style',
    ));

    // Test a non existent style plugin type returns no plugins.
    $plugins = views_fetch_plugin_names('style', $this
      ->randomString());
    $this
      ->assertIdentical($plugins, array());
  }

  /**
   * Helper to return an expected views option array.
   *
   * @param array $views
   *   An array of Drupal\views\Plugin\Core\Entity\View objects for which to
   *   create an options array.
   *
   * @return array
   *   A formatted options array that matches the expected output.
   */
  protected function formatViewOptions(array $views = array()) {
    $expected_options = array();
    foreach ($views as $id => $view) {
      foreach ($view
        ->get('display') as $display_id => $display) {
        $expected_options[$view
          ->id() . ':' . $display['id']] = t('View: @view - Display: @display', array(
          '@view' => $view
            ->id(),
          '@display' => $display['id'],
        ));
      }
    }
    return $expected_options;
  }

  /**
   * Ensure that a certain handler is a instance of a certain table/field.
   */
  function assertInstanceHandler($handler, $table, $field, $id) {
    $table_data = Views::viewsData()
      ->get($table);
    $field_data = $table_data[$field][$id];
    $this
      ->assertEqual($field_data['id'], $handler
      ->getPluginId());
  }

}

Members

Namesort descending Modifiers Type Description Overrides
DrupalUnitTestBase::$keyValueFactory protected property A KeyValueMemoryFactory instance to use when building the container.
DrupalUnitTestBase::$moduleFiles private property
DrupalUnitTestBase::$themeData private property
DrupalUnitTestBase::$themeFiles private property
DrupalUnitTestBase::containerBuild public function Sets up the base service container for this test. 1
DrupalUnitTestBase::disableModules protected function Disables modules for this test.
DrupalUnitTestBase::enableModules protected function Enables modules for this test.
DrupalUnitTestBase::installConfig protected function Installs default configuration for a given list of modules.
DrupalUnitTestBase::installSchema protected function Installs a specific table from a module schema definition.
DrupalUnitTestBase::tearDown protected function Deletes created files, database tables, and reverts all environment changes. Overrides TestBase::tearDown 2
DrupalUnitTestBase::__construct function Overrides \Drupal\simpletest\UnitTestBase::__construct(). Overrides UnitTestBase::__construct
ModuleTest::$lastErrorMessage protected property Stores the last triggered error, for example via debug().
ModuleTest::$testViews public static property Views used by this test.
ModuleTest::assertInstanceHandler function Ensure that a certain handler is a instance of a certain table/field.
ModuleTest::customErrorHandler public function Defines an error handler which is used in the test.
ModuleTest::formatViewOptions protected function Helper to return an expected views option array.
ModuleTest::getInfo public static function
ModuleTest::testLoadFunctions public function Tests the load wrapper/helper functions.
ModuleTest::testStatusFunctions function Tests view enable and disable procedural wrapper functions.
ModuleTest::testViewsFetchPluginNames public function Tests the views_fetch_plugin_names() function.
ModuleTest::testViewsGetHandler public function Tests the views_get_handler method.
TestBase::$assertions protected property Assertions thrown in that test case.
TestBase::$configImporter protected property The config importer that can used in a test. 1
TestBase::$container protected property The dependency injection container used in the test. 1
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::$results public property Current results of this test case.
TestBase::$setup protected property Flag to indicate whether the test has been set up.
TestBase::$setupDatabasePrefix protected property
TestBase::$setupEnvironment protected property
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 protected 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 (an empty string, 0, NULL, or 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::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 (not an empty string, 0, NULL, or FALSE).
TestBase::changeDatabasePrefix protected function Changes the database connection to the prefixed one.
TestBase::checkRequirements protected function Checks the matching requirements for Test. 4
TestBase::configImporter public function Returns a ConfigImporter object to import test importing of configuration. 1
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. 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 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::insertAssert public static function Store an assertion from outside the testing context.
TestBase::pass protected function Fire an assertion that is always positive.
TestBase::prepareConfigDirectories protected function Create and set new configuration directories. 1
TestBase::prepareDatabasePrefix protected function Generates a database prefix for running tests.
TestBase::prepareEnvironment protected function Prepares the current environment for running the test.
TestBase::randomName public static function Generates a random string containing letters and numbers.
TestBase::randomObject public static function Generates a random PHP object.
TestBase::randomString public static function Generates a random string of ASCII characters of codes 32 to 126.
TestBase::rebuildContainer protected function Rebuild drupal_container(). 1
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.
UnitTestBase::$configDirectories protected property
ViewUnitTestBase::$modules public static property Modules to enable. Overrides DrupalUnitTestBase::$modules 21
ViewUnitTestBase::assertIdenticalResultset protected function Verifies that a result set returned by a View matches expected values.
ViewUnitTestBase::assertIdenticalResultsetHelper protected function Performs View result assertions.
ViewUnitTestBase::assertNotIdenticalResultset protected function Verifies that a result set returned by a View differs from certain values.
ViewUnitTestBase::dataSet protected function Returns a very simple test dataset. 7
ViewUnitTestBase::executeView protected function Executes a view with debugging.
ViewUnitTestBase::orderResultSet protected function Orders a nested array containing a result set based on a given column.
ViewUnitTestBase::schemaDefinition protected function Returns the schema definition. 4
ViewUnitTestBase::setUp protected function Sets up Drupal unit test environment. Overrides DrupalUnitTestBase::setUp 20
ViewUnitTestBase::setUpFixtures protected function Sets up the configuration and schema of views and views_test_data modules. 2
ViewUnitTestBase::viewsData protected function Returns the views data definition. 19