You are here

class TermMergeTermMergeWebTestCase in Term Merge 7

Test the functionality of Term Merge module.

Hierarchy

Expanded class hierarchy of TermMergeTermMergeWebTestCase

File

./term_merge.test, line 105
Test the Term Merge module.

View source
class TermMergeTermMergeWebTestCase extends TermMergeWebTestCase {

  /**
   * GetInfo method.
   */
  public static function getInfo() {
    return array(
      'name' => 'Term Merge',
      'description' => 'Ensure that the module Term Merge works correctly.',
      'group' => 'Term Merge',
    );
  }

  /**
   * Test merging two terms.
   */
  public function testTermMerge() {

    // Checking whether parent's relationship is handled as it should.
    // At the same time we make sure 'term_branch_keep' property functions.
    $terms = array(
      'trunk' => FALSE,
      'branch' => FALSE,
      'another_parent' => FALSE,
      'branch_child' => FALSE,
    );
    foreach ($terms as $term_type => $tmp) {
      $url = 'admin/structure/taxonomy/vocabulary/add';
      $name = $this
        ->randomName();
      $edit = array(
        'name' => $name,
      );

      // Putting "branch" to be parent of "branch_child".
      if ($term_type == 'branch_child') {
        $edit['parent[]'] = array(
          $terms['branch']->tid,
          $terms['another_parent']->tid,
        );
      }
      $this
        ->drupalPost($url, $edit, 'Save');
      $terms[$term_type] = $this
        ->getLastTerm($this->vocabulary);
    }

    // Firstly we try to merge without deleting the branch term and make sure
    // branch's children are not reassigned to the trunk term nor the branch
    // term itself is deleted.
    actions_do('term_merge_action', $terms['branch'], array(
      'term_trunk' => $terms['trunk']->tid,
      'merge_fields' => array(),
      'term_branch_keep' => TRUE,
    ));
    $this
      ->drupalGet('taxonomy/term/' . $terms['branch']->tid);
    $this
      ->assertText($terms['branch']->name);
    drupal_static_reset();
    $parents = array();
    foreach (taxonomy_get_parents_all($terms['branch_child']->tid) as $parent) {
      $parents[] = $parent->tid;
    }
    $valid_parents = array(
      $terms['branch_child']->tid,
      $terms['branch']->tid,
      $terms['another_parent']->tid,
    );
    $intersection = array_intersect($parents, $valid_parents);
    $this
      ->assertTrue(count($intersection) == count($valid_parents), 'The parents of children of term branch are not updated if property "term_branch_keep" is set to FALSE.');

    // Now we merge with deletion of branch term, thus the parents of its
    // children have to be updated.
    actions_do('term_merge_action', $terms['branch'], array(
      'term_trunk' => $terms['trunk']->tid,
      'merge_fields' => array(),
      'term_branch_keep' => FALSE,
    ));
    $this
      ->drupalGet('taxonomy/term/' . $terms['branch']->tid);
    $this
      ->assertResponse(404, 'The branch term has been deleted.');
    drupal_static_reset();
    $parents = array();
    foreach (taxonomy_get_parents_all($terms['branch_child']->tid) as $parent) {
      $parents[] = $parent->tid;
    }
    $valid_parents = array(
      $terms['branch_child']->tid,
      $terms['trunk']->tid,
      $terms['another_parent']->tid,
    );
    $intersection = array_intersect($parents, $valid_parents);
    $this
      ->assertTrue(count($intersection) == count($valid_parents), 'The parents of children of term branch are updated if property "term_branch_keep" is set to TRUE.');

    // Now testing 'merge_fields' property. Attaching fields to taxonomy terms.
    $bundle = field_extract_bundle('taxonomy_term', $this->vocabulary);
    $fields_map = array(
      'term_merge_test_single' => 1,
      'term_merge_test_unlimited' => FIELD_CARDINALITY_UNLIMITED,
      'term_merge_do_not_merge' => 10,
      'term_merge_not_unique' => FIELD_CARDINALITY_UNLIMITED,
    );
    foreach ($fields_map as $field_name => $cardinality) {
      $field = array(
        'field_name' => $field_name,
        'cardinality' => $cardinality,
        'locked' => TRUE,
        'type' => 'text',
      );
      field_create_field($field);
      field_create_instance(array(
        'field_name' => $field_name,
        'entity_type' => 'taxonomy_term',
        'bundle' => $bundle,
        'label' => $field_name,
      ));
    }
    $terms = array(
      'trunk' => FALSE,
      'branch' => FALSE,
    );
    foreach ($terms as $term_type => $tmp) {
      $term = (object) array(
        'vid' => $this->vocabulary->vid,
        'name' => $this
          ->randomName(),
      );
      foreach ($fields_map as $field_name => $cardinality) {
        switch ($field_name) {
          case 'term_merge_test_single':
            $term->{$field_name}[LANGUAGE_NONE][0]['value'] = $this
              ->randomName();
            break;
          case 'term_merge_test_unlimited':
          case 'term_merge_do_not_merge':
            $count = rand(1, 3);
            for ($i = 0; $i < $count; $i++) {
              $term->{$field_name}[LANGUAGE_NONE][$i]['value'] = $this
                ->randomName();
            }
            break;
          case 'term_merge_not_unique':
            $term->{$field_name}[LANGUAGE_NONE][0]['value'] = 'term_merge_not_unique_value';
            break;
        }
      }
      taxonomy_term_save($term);
      $terms[$term_type] = $this
        ->getLastTerm($this->vocabulary);
    }

    // Firstly we make sure if 'merge_fields' is disabled, the fields are not
    // merged.
    actions_do('term_merge_action', $terms['branch'], array(
      'term_trunk' => $terms['trunk']->tid,
      'merge_fields' => array(),
      'term_branch_keep' => TRUE,
    ));
    $this
      ->drupalGet('taxonomy/term/' . $terms['trunk']->tid);
    foreach ($fields_map as $field_name => $cardinality) {
      foreach (field_get_items('taxonomy_term', $terms['branch'], $field_name) as $item) {
        if ($field_name != 'term_merge_not_unique') {
          $this
            ->assertNoText($item['value'], 'Values of field ' . $field_name . ' have not been added to the trunk term with disabled "merge_fields" option.');
        }
      }
    }

    // Now we try merging with merging fields. The values of the branch term
    // should be added to the trunk term's values only in where we asked them
    // to be added. Moreover, only unique values are to be kept in each of the
    // merged fields.
    actions_do('term_merge_action', $terms['branch'], array(
      'term_trunk' => $terms['trunk']->tid,
      'merge_fields' => array(
        'term_merge_test_single',
        'term_merge_test_unlimited',
        'term_merge_not_unique',
      ),
      'term_branch_keep' => TRUE,
    ));
    $this
      ->drupalGet('taxonomy/term/' . $terms['trunk']->tid);
    foreach ($fields_map as $field_name => $cardinality) {
      switch ($field_name) {
        case 'term_merge_test_single':
        case 'term_merge_do_not_merge':

          // Make sure if cardinality limit is hit, firstly original trunk term
          // values are stored. And make sure values of fields that are not
          // instructed to be added to trunk term's values are actually not
          // added.
          foreach (field_get_items('taxonomy_term', $terms['branch'], $field_name) as $item) {
            $this
              ->assertNoText($item['value'], 'Values of field ' . $field_name . ' (cardinality ' . $cardinality . ') have not been added to the trunk term with enabled "merge_fields" option.');
          }
          break;
        case 'term_merge_not_unique':

          // Make sure only the unique values in merged field are kept.
          foreach (field_get_items('taxonomy_term', $terms['trunk'], $field_name) as $item) {
            $this
              ->assertUniqueText($item['value'], 'Only unique field values are kept in the trunk term field after merging terms with enabled "merge_fields" option.');
          }
          break;
        case 'term_merge_test_unlimited':

          // Make sure values of fields that are instructed to be added to trunk
          // term's values are actually added.
          foreach (field_get_items('taxonomy_term', $terms['branch'], $field_name) as $item) {
            $this
              ->assertText($item['value'], 'Values of field ' . $field_name . ' (cardinality ' . $cardinality . ') have been added to the trunk term with enabled "merge_fields" option.');
          }
          break;
      }
    }

    // Make sure that all taxonomy term reference fields are updated to point
    // from a branch term to a trunk term in other entities that have taxonomy
    // term reference fields.
    $terms = array(
      'trunk' => FALSE,
      'branch' => FALSE,
    );
    foreach ($terms as $term_type => $tmp) {
      $url = 'admin/structure/taxonomy/vocabulary/add';
      $name = $this
        ->randomName();
      $edit = array(
        'name' => $name,
      );
      $this
        ->drupalPost($url, $edit, 'Save');
      $terms[$term_type] = $this
        ->getLastTerm($this->vocabulary);
    }

    // Firstly we need to create a new content type and assign term reference
    // field to this new content type.
    $this
      ->drupalPost('admin/structure/types/add', array(
      'name' => $this
        ->randomName(),
      'type' => 'term_merge_node',
    ), 'Save content type');
    $this
      ->drupalPost('admin/structure/types/manage/term-merge-node/fields', array(
      'fields[_add_new_field][label]' => 'Term Reference',
      'fields[_add_new_field][field_name]' => 'term_reference',
      'fields[_add_new_field][type]' => 'taxonomy_term_reference',
      'fields[_add_new_field][widget_type]' => 'taxonomy_autocomplete',
    ), 'Save');
    $this
      ->drupalPost(NULL, array(
      'field[settings][allowed_values][0][vocabulary]' => $this->vocabulary->machine_name,
    ), 'Save field settings');
    $this
      ->drupalPost(NULL, array(
      'field[cardinality]' => FIELD_CARDINALITY_UNLIMITED,
    ), 'Save settings');

    // Flushing fields API cache.
    _field_info_collate_fields(TRUE);

    // Creating a new node and settings its term reference field to point to
    // the term branch.
    $title = $this
      ->randomName();
    $this
      ->drupalPost('node/add/term-merge-node', array(
      'title' => $title,
      'field_term_reference[' . LANGUAGE_NONE . ']' => $terms['branch']->name,
    ), 'Save');
    $node = $this
      ->drupalGetNodeByTitle($title, TRUE);
    actions_do('term_merge_action', $terms['branch'], array(
      'term_trunk' => $terms['trunk']->tid,
      'merge_fields' => array(),
      'term_branch_keep' => TRUE,
    ));
    $this
      ->drupalGet('node/' . $node->nid);
    $this
      ->assertText($terms['trunk']->name, 'Taxonomy term reference field gets updated to point from term branch to term trunk after merging terms.');

    // Testing 'Keep only unique' setting for merging. We create a node assigned
    // to both branch and trunk terms, and merge with, and then without 'Keep
    // only unique' setting, asserting each result.
    $terms = array(
      'trunk' => FALSE,
      'branch' => FALSE,
    );
    foreach ($terms as $term_type => $tmp) {
      $url = 'admin/structure/taxonomy/vocabulary/add';
      $name = $this
        ->randomName();
      $edit = array(
        'name' => $name,
      );
      $this
        ->drupalPost($url, $edit, 'Save');
      $terms[$term_type] = $this
        ->getLastTerm($this->vocabulary);
    }
    $title = $this
      ->randomName();
    $this
      ->drupalPost('node/add/term-merge-node', array(
      'title' => $title,
      'field_term_reference[' . LANGUAGE_NONE . ']' => $terms['branch']->name . ', ' . $terms['trunk']->name,
    ), 'Save');
    actions_do('term_merge_action', $terms['branch'], array(
      'term_trunk' => $terms['trunk']->tid,
      'merge_fields' => array(),
      'term_branch_keep' => TRUE,
      'keep_only_unique' => FALSE,
    ));
    $node = $this
      ->drupalGetNodeByTitle($title);
    $is_first_trunk = $node->field_term_reference[LANGUAGE_NONE][0]['tid'] == $terms['trunk']->tid;
    $is_second_trunk = $node->field_term_reference[LANGUAGE_NONE][1]['tid'] == $terms['trunk']->tid;
    $this
      ->assertTrue($is_first_trunk && $is_second_trunk, 'The same terms are kept in term reference field values if "Keep only unique" is off.');

    // We switch roles of 'trunk' and 'branch' now. We have a node with 2 terms,
    // if we merge them into another with "Keep only unique" on we are supposed
    // to have only 1 term after merging.
    actions_do('term_merge_action', $terms['trunk'], array(
      'term_trunk' => $terms['branch']->tid,
      'merge_fields' => array(),
      'term_branch_keep' => TRUE,
      'keep_only_unique' => TRUE,
    ));
    $node = $this
      ->drupalGetNodeByTitle($title, TRUE);
    $is_single = count($node->field_term_reference[LANGUAGE_NONE]) == 1;
    $is_expected_term = $node->field_term_reference[LANGUAGE_NONE][0]['tid'] == $terms['branch']->tid;
    $this
      ->assertTrue($is_single && $is_expected_term, 'Only one term is kept in term reference field values if "Keep only unique" is on.');
  }

  /**
   * Test all cases for potentially "buggy" input.
   *
   * Test the functionality of the action "Term Merge" with various suspicious
   * input arguments, and testing the web UI of the module with suspicious
   * input.
   */
  public function testTermMergeResistance() {
    drupal_static_reset();

    // Trying to merge 2 terms from 2 different vocabularies.
    $this
      ->drupalPost('admin/structure/taxonomy/add', array(
      'name' => $this
        ->randomName(),
      'machine_name' => 'vocabulary2',
    ), 'Save');
    $terms = array(
      'vocabulary' => FALSE,
      'vocabulary2' => FALSE,
    );
    foreach ($terms as $term_type => $tmp) {
      $url = 'admin/structure/taxonomy/' . $term_type . '/add';
      $edit = array(
        'name' => $this
          ->randomName(),
      );
      $this
        ->drupalPost($url, $edit, 'Save');
      $terms[$term_type] = $this
        ->getLastTerm(taxonomy_vocabulary_machine_name_load($term_type));
    }
    actions_do('term_merge_action', $terms['vocabulary'], array(
      'term_trunk' => $terms['vocabulary2']->tid,
      'term_branch_keep' => FALSE,
    ));
    $this
      ->termMergeResistanceAssert($terms, 'Testing merging 2 terms from 2 different vocabularies.');

    // Trying to merge a parent into its child.
    $terms = array(
      'parent' => FALSE,
      'child' => FALSE,
    );
    drupal_static_reset();
    foreach ($terms as $term_type => $tmp) {
      $url = 'admin/structure/taxonomy/' . $this->vocabulary->machine_name . '/add';
      $edit = array(
        'name' => $this
          ->randomName(),
      );
      if ($term_type == 'child') {
        $edit['parent[]'] = array(
          $terms['parent']->tid,
        );
      }
      $this
        ->drupalPost($url, $edit, 'Save');
      $terms[$term_type] = $this
        ->getLastTerm($this->vocabulary);
    }
    actions_do('term_merge_action', $terms['parent'], array(
      'term_trunk' => $terms['child']->tid,
      'term_branch_keep' => FALSE,
    ));
    $this
      ->termMergeResistanceAssert($terms, 'Testing merging a parent into its child.');

    // Trying to merge a term into itself.
    $terms = array(
      'single' => FALSE,
    );
    foreach ($terms as $term_type => $tmp) {
      $url = 'admin/structure/taxonomy/' . $this->vocabulary->machine_name . '/add';
      $name = $this
        ->randomName();
      $edit = array(
        'name' => $name,
      );
      $this
        ->drupalPost($url, $edit, 'Save');
      $terms[$term_type] = $this
        ->getLastTerm($this->vocabulary);
    }
    actions_do('term_merge_action', $terms['single'], array(
      'term_trunk' => $terms['single']->tid,
      'term_branch_keep' => FALSE,
    ));
    $this
      ->termMergeResistanceAssert($terms, 'Testing merging a term into itself.');

    // Making sure the access rights are respected.
    $account = $this
      ->drupalCreateUser(array(
      'merge vocabulary2 terms',
    ));
    $this
      ->drupalLogin($account);
    $this
      ->drupalGet('admin/structure/taxonomy/' . $this->vocabulary->machine_name . '/merge');
    $this
      ->assertResponse(403, 'Per vocabulary term merge permissions are respected in the module - an account cannot merge terms in the vocabulary in which he is not supposed to be able to merge.');
    $this
      ->drupalGet('admin/structure/taxonomy/vocabulary2/merge');
    $this
      ->assertResponse(200, 'Per vocabulary term merge permissions are respected in the module - an account can merge terms in the vocabulary in which he is supposed to be able to merge.');

    // Test the threshold for "select" widget of the trunk term.
    variable_set('term_merge_select_limit', 0);
    $this
      ->drupalGet('admin/structure/taxonomy/vocabulary2/merge');
    $this
      ->assertFieldByXPath('//input[@type="radio"][@name="term_trunk[widget]"][@value="autocomplete"][@checked="checked"]', NULL, 'Threshold for "select" widget of the trunk term is taken into consideration.');
  }

  /**
   * Test all cases of usage of Term Merge Batch.
   */
  public function testTermMergeBatch() {

    // Adding fields with unlimited cardinality to our vocabulary.
    $this
      ->drupalPost('admin/structure/taxonomy/vocabulary/fields', array(
      'fields[_add_new_field][label]' => 'Test Unlimited Text',
      'fields[_add_new_field][field_name]' => 'test_text',
      'fields[_add_new_field][type]' => 'text',
      'fields[_add_new_field][widget_type]' => 'text_textfield',
    ), 'Save');
    $this
      ->drupalPost(NULL, array(), 'Save field settings');
    $this
      ->drupalPost(NULL, array(
      'field[cardinality]' => FIELD_CARDINALITY_UNLIMITED,
    ), 'Save settings');

    // Additionally we need to create a new content type and assign term
    // reference field to this new content type.
    $this
      ->drupalPost('admin/structure/types/add', array(
      'name' => $this
        ->randomName(),
      'type' => 'term_merge_node',
    ), 'Save content type');
    $this
      ->drupalPost('admin/structure/types/manage/term-merge-node/fields', array(
      'fields[_add_new_field][label]' => 'Term Reference',
      'fields[_add_new_field][field_name]' => 'term_reference',
      'fields[_add_new_field][type]' => 'taxonomy_term_reference',
      'fields[_add_new_field][widget_type]' => 'taxonomy_autocomplete',
    ), 'Save');
    $this
      ->drupalPost(NULL, array(
      'field[settings][allowed_values][0][vocabulary]' => $this->vocabulary->machine_name,
    ), 'Save field settings');
    $this
      ->drupalPost(NULL, array(), 'Save settings');

    // Flushing fields API cache.
    _field_info_collate_fields(TRUE);

    // Array of cases for which we test the Term Merge batch.
    $cases = array(
      'taxonomy_vocabulary_tab',
      'taxonomy_term_tab',
      'via_term_trunk_widget_select',
      'via_term_trunk_widget_autocomplete',
      'via_term_trunk_widget_autocomplete_without_tid',
      'merge_fields',
      'do_not_merge_fields',
    );
    foreach ($cases as $case) {

      // Creating a necessary set of terms in the vocabulary.
      drupal_static_reset();
      $terms = array(
        'parent' => FALSE,
        'another_parent' => FALSE,
        'child' => FALSE,
        'term1' => FALSE,
        'term2' => FALSE,
        'term3' => FALSE,
        'term_trunk_parent' => FALSE,
        'term_trunk' => FALSE,
      );
      foreach ($terms as $term_type => $tmp) {
        $url = 'admin/structure/taxonomy/' . $this->vocabulary->machine_name . '/add';
        $edit = array(
          'name' => $term_type . '_' . $this
            ->randomName(),
          'field_test_text[' . LANGUAGE_NONE . '][0][value]' => $term_type,
        );
        switch ($term_type) {
          case 'child':
            $edit['parent[]'] = array(
              $terms['parent']->tid,
              $terms['another_parent']->tid,
            );
            break;
          case 'term_trunk':
            $edit['parent[]'] = array(
              $terms['term_trunk_parent']->tid,
            );
            break;
        }
        $this
          ->drupalPost($url, $edit, 'Save');
        $terms[$term_type] = $this
          ->getLastTerm($this->vocabulary);
      }

      // The initial URL from where the form that kicks off batch is submitted.
      $init_url = '';

      // What widget to use for choosing term trunk.
      $term_trunk_widget = '';

      // Value for term trunk in the format, expected by the widget
      // $term_trunk_widget. Additionally, if any test case requires any extra
      // fields to be submitted, input those fields into this array and they
      // won't be taken out from this array, then it will get merged into $edit,
      // and this way eventually your values will be successfully submitted.
      $term_trunk_edit = array();

      // Setting up controlling vars based on case and doing any specific
      // assertions for each case.
      switch ($case) {
        case 'taxonomy_vocabulary_tab':
          $init_url = 'admin/structure/taxonomy/' . $this->vocabulary->machine_name . '/merge';

          // It doesn't really matter which widget we use, we test widgets
          // throughout in other cases.
          $term_trunk_widget = array_rand(drupal_map_assoc(array(
            'select',
            'autocomplete',
          )));
          break;
        case 'taxonomy_term_tab':
          $init_url = 'taxonomy/term/' . $terms['parent']->tid . '/merge';

          // It doesn't really matter which widget we use, we test widgets
          // throughout in other cases.
          $term_trunk_widget = array_rand(drupal_map_assoc(array(
            'select',
            'autocomplete',
          )));

          // Assert that the term, for which the tab was clicked, is selected as
          // term branch by default.
          $this
            ->drupalGet($init_url);
          $this
            ->assertOptionSelected('edit-term-branch', $terms['parent']->tid, 'Clicking the "Merge Terms" tab from a term view page sets the viewed term as a term branch by default.');
          break;
        case 'via_term_trunk_widget_select':
          $init_url = 'taxonomy/term/' . $terms['parent']->tid . '/merge';
          $term_trunk_widget = 'select';

          // Making sure for the term trunk select the selected term branch are
          // not available, nor their children.
          $this
            ->drupalGet($init_url);
          $matches = array();
          preg_match('#\\<select[^>]+name="term_trunk\\[tid\\]"[^>]*\\>.+?\\</select\\>#si', $this->content, $matches);
          $term_trunk_options = $matches[0];
          $str_pos = strpos($term_trunk_options, $terms['child']->name);
          $this
            ->assertIdentical(FALSE, $str_pos, 'Child is not available as option for term trunk if its parent is chosen among term branches.');
          $str_pos = strpos($term_trunk_options, $terms['parent']->name);
          $this
            ->assertIdentical(FALSE, $str_pos, 'Selected branch term is not available as an option for term trunk.');
          break;
        case 'via_term_trunk_widget_autocomplete':
          $init_url = 'admin/structure/taxonomy/' . $this->vocabulary->machine_name . '/merge';
          $term_trunk_widget = 'autocomplete';

          // Test autocomplete widget menu path to make sure it does reply
          // with valid suggestions.
          $response = $this
            ->drupalGet('term-merge/autocomplete/term-trunk/' . $this->vocabulary->machine_name . '/' . drupal_strtoupper($terms['term_trunk']->name));
          $response = drupal_json_decode($response);
          $autocomplete_key = $terms['term_trunk']->name . ' (' . $terms['term_trunk']->tid . ')';
          $this
            ->assertTrue(isset($response[$autocomplete_key]), 'Autocomplete menu path replies with valid suggestions for term trunk autocomplete widget.');

          // Making sure for the term trunk autocomplete widget doesn't allow to
          // submit any of the selected term branches nor their children.
          $prohibited_terms = array(
            'parent' => 'Merging into the same term is not allowed in autocomplete widget for term trunk.',
            'child' => 'Merging into any of child of selected branch terms is not allowed in autocomplete widget for term trunk.',
          );
          foreach ($prohibited_terms as $term => $assert_message) {
            $term = $terms[$term];
            $this
              ->drupalGet($init_url);
            $this
              ->drupalPostAJAX(NULL, array(
              'term_branch[]' => array(
                $terms['parent']->tid,
              ),
              'term_trunk[widget]' => $term_trunk_widget,
            ), 'term_trunk[widget]');
            $this
              ->drupalPost(NULL, array(
              'term_branch[]' => array(
                $terms['parent']->tid,
              ),
              'term_trunk[widget]' => $term_trunk_widget,
              'term_trunk[tid]' => $term->name . ' (' . $term->tid . ')',
            ), 'Submit');
            $this
              ->assertText('Trunk term cannot be one of the selected branch terms or their children', $assert_message);
          }
          break;
        case 'via_term_trunk_widget_autocomplete_without_tid':
          $init_url = 'admin/structure/taxonomy/' . $this->vocabulary->machine_name . '/merge';
          $term_trunk_widget = 'autocomplete';

          // Making sure for the term trunk autocomplete widget doesn't allow to
          // submit any of the selected term branches nor their children.
          $prohibited_terms = array(
            'parent' => 'Merging into the same term is not allowed in autocomplete widget for term trunk.',
            'child' => 'Merging into any of child of selected branch terms is not allowed in autocomplete widget for term trunk.',
          );
          foreach ($prohibited_terms as $term => $assert_message) {
            $term = $terms[$term];
            $this
              ->drupalGet($init_url);
            $this
              ->drupalPostAJAX(NULL, array(
              'term_branch[]' => array(
                $terms['parent']->tid,
              ),
              'term_trunk[widget]' => $term_trunk_widget,
            ), 'term_trunk[widget]');
            $this
              ->drupalPost(NULL, array(
              'term_branch[]' => array(
                $terms['parent']->tid,
              ),
              'term_trunk[widget]' => $term_trunk_widget,
              'term_trunk[tid]' => $term->name,
            ), 'Submit');
            $this
              ->assertText('Trunk term cannot be one of the selected branch terms or their children', $assert_message);
          }
          break;
        case 'merge_fields':
          $init_url = 'admin/structure/taxonomy/' . $this->vocabulary->machine_name . '/merge';

          // It doesn't really matter which widget we use, we test widgets
          // throughout in other cases.
          $term_trunk_widget = array_rand(drupal_map_assoc(array(
            'select',
            'autocomplete',
          )));

          // We embed extra info related to field values merging into
          // $term_trunk_edit.
          $term_trunk_edit['merge_fields[field_test_text]'] = TRUE;
          break;
        case 'do_not_merge_fields':
          $init_url = 'admin/structure/taxonomy/' . $this->vocabulary->machine_name . '/merge';

          // It doesn't really matter which widget we use, we test widgets
          // throughout in other cases.
          $term_trunk_widget = array_rand(drupal_map_assoc(array(
            'select',
            'autocomplete',
          )));
          break;
      }

      // Creating a new node and setting its term reference field to point to
      // the term branch.
      $title = $this
        ->randomName();
      $this
        ->drupalPost('node/add/term-merge-node', array(
        'title' => $title,
        'field_term_reference[' . LANGUAGE_NONE . ']' => $terms['term1']->name,
      ), 'Save');
      $node = $this
        ->drupalGetNodeByTitle($title, TRUE);

      // Calling the Term Merge form.
      $this
        ->drupalGet($init_url);

      // Choosing term branches.
      $term_branches = array(
        'term1',
        'term2',
        'term3',
      );
      $term_branches_edit = array();
      foreach ($term_branches as $term_type) {
        $term_branches_edit[] = $terms[$term_type]->tid;
      }
      $this
        ->drupalPostAJAX(NULL, array(
        'term_branch[]' => $term_branches_edit,
      ), 'term_branch[]');

      // Choosing the widget for trunk term.
      $this
        ->drupalPostAJAX(NULL, array(
        'term_branch[]' => $term_branches_edit,
        'term_trunk[widget]' => $term_trunk_widget,
      ), 'term_trunk[widget]');

      // Choosing term trunk.
      switch ($term_trunk_widget) {
        case 'select':
          $term_trunk_edit += array(
            'term_trunk[tid]' => $terms['term_trunk']->tid,
          );
          break;
        case 'autocomplete':
          $term_trunk_edit += array(
            'term_trunk[tid]' => $terms['term_trunk']->name . ' (' . $terms['term_trunk']->tid . ')',
          );
          break;
      }

      // Submitting the form.
      $edit = $term_trunk_edit + array(
        'term_branch[]' => $term_branches_edit,
        'term_trunk[widget]' => $term_trunk_widget,
        'term_branch_keep' => FALSE,
        'step' => 2,
      );
      $this
        ->drupalPost(NULL, $edit, 'Submit');
      $this
        ->drupalPost(NULL, array(), 'Confirm');

      // Making sure all the branches are deleted.
      foreach ($term_branches as $term_type) {
        $term = $terms[$term_type];
        $this
          ->drupalGet('taxonomy/term/' . $term->tid);
        $this
          ->assertResponse(404, 'Branch term ' . $term_type . ' has been deleted after merging.');
      }
      $text_assertions = array();
      $term_trunk = $terms['term_trunk'];

      // Adding any extra text assertions on per test-case basis.
      switch ($case) {
        case 'merge_fields':

          // Making sure the term trunk has been merged all the fields from term
          // branches into itself.
          foreach ($term_branches as $term_type) {
            $items = field_get_items('taxonomy_term', $terms[$term_type], 'field_test_text');
            foreach ($items as $delta => $item) {
              $text_assertions[$term_type . ' text field delta#' . $delta . ' has been merged when instructed to merge field values.'] = $item['value'];
            }
          }
          break;
        case 'do_not_merge_fields':

          // We need to assert that no values for field have been merged from
          // branch terms into the values of trunk term.
          $this
            ->drupalGet('taxonomy/term/' . $term_trunk->tid);
          foreach ($term_branches as $term_type) {
            $items = field_get_items('taxonomy_term', $terms[$term_type], 'field_test_text');
            foreach ($items as $delta => $item) {
              $this
                ->assertNoText($item['value'], $term_type . ' text field delta#' . $delta . ' has not been merged when instrcuted not to merge field values.');
            }
          }
          break;
      }
      $this
        ->drupalGet('taxonomy/term/' . $term_trunk->tid);
      foreach ($text_assertions as $k => $v) {
        $this
          ->assertText($v, 'Term trunk has the property ' . $k);
      }

      // Making sure the taxonomy term reference in other entities are updated
      // to point from term branches to the just created term trunk.
      $this
        ->drupalGet('node/' . $node->nid);
      $this
        ->assertText($term_trunk->name, 'Taxonomy term reference fields in other entities are updated to point from term branches to the term trunk.');
    }
  }

  /**
   * Supportive function for the main test "testTermMergeResistance".
   *
   * Assert that each term of the array $terms is available.
   *
   * @param array $terms
   *   Array of taxonomy terms objects
   * @param string $message
   *   Assertion message to be shown on the test results page
   */
  protected function termMergeResistanceAssert($terms, $message) {
    foreach ($terms as $term) {
      $this
        ->drupalGet('taxonomy/term/' . $term->tid);
      $this
        ->assertResponse(200, $message);
    }
  }

}

Members

Namesort descending Modifiers Type Description Overrides
DrupalTestCase::$assertions protected property Assertions thrown in that test case.
DrupalTestCase::$databasePrefix protected property The database prefix of this test run.
DrupalTestCase::$originalFileDirectory protected property The original file directory, before it was changed for testing purposes.
DrupalTestCase::$results public property Current results of this test case.
DrupalTestCase::$setup protected property Flag to indicate whether the test has been set up.
DrupalTestCase::$setupDatabasePrefix protected property
DrupalTestCase::$setupEnvironment protected property
DrupalTestCase::$skipClasses protected property This class is skipped when looking for the source of an assertion.
DrupalTestCase::$testId protected property The test run ID.
DrupalTestCase::$timeLimit protected property Time limit for the test.
DrupalTestCase::$useSetupInstallationCache public property Whether to cache the installation part of the setUp() method.
DrupalTestCase::$useSetupModulesCache public property Whether to cache the modules installation part of the setUp() method.
DrupalTestCase::$verboseDirectoryUrl protected property URL to the verbose output file directory.
DrupalTestCase::assert protected function Internal helper: stores the assert.
DrupalTestCase::assertEqual protected function Check to see if two values are equal.
DrupalTestCase::assertFalse protected function Check to see if a value is false (an empty string, 0, NULL, or FALSE).
DrupalTestCase::assertIdentical protected function Check to see if two values are identical.
DrupalTestCase::assertNotEqual protected function Check to see if two values are not equal.
DrupalTestCase::assertNotIdentical protected function Check to see if two values are not identical.
DrupalTestCase::assertNotNull protected function Check to see if a value is not NULL.
DrupalTestCase::assertNull protected function Check to see if a value is NULL.
DrupalTestCase::assertTrue protected function Check to see if a value is not false (not an empty string, 0, NULL, or FALSE).
DrupalTestCase::deleteAssert public static function Delete an assertion record by message ID.
DrupalTestCase::error protected function Fire an error assertion. 1
DrupalTestCase::errorHandler public function Handle errors during test runs. 1
DrupalTestCase::exceptionHandler protected function Handle exceptions.
DrupalTestCase::fail protected function Fire an assertion that is always negative.
DrupalTestCase::generatePermutations public static function Converts a list of possible parameters into a stack of permutations.
DrupalTestCase::getAssertionCall protected function Cycles through backtrace until the first non-assertion method is found.
DrupalTestCase::getDatabaseConnection public static function Returns the database connection to the site running Simpletest.
DrupalTestCase::insertAssert public static function Store an assertion from outside the testing context.
DrupalTestCase::pass protected function Fire an assertion that is always positive.
DrupalTestCase::randomName public static function Generates a random string containing letters and numbers.
DrupalTestCase::randomString public static function Generates a random string of ASCII characters of codes 32 to 126.
DrupalTestCase::run public function Run all tests in this class.
DrupalTestCase::verbose protected function Logs a verbose message in a text file.
DrupalWebTestCase::$additionalCurlOptions protected property Additional cURL options.
DrupalWebTestCase::$content protected property The content of the page currently loaded in the internal browser.
DrupalWebTestCase::$cookieFile protected property The current cookie file used by cURL.
DrupalWebTestCase::$cookies protected property The cookies of the page currently loaded in the internal browser.
DrupalWebTestCase::$curlHandle protected property The handle of the current cURL connection.
DrupalWebTestCase::$drupalSettings protected property The value of the Drupal.settings JavaScript variable for the page currently loaded in the internal browser.
DrupalWebTestCase::$elements protected property The parsed version of the page.
DrupalWebTestCase::$generatedTestFiles protected property Whether the files were copied to the test files directory.
DrupalWebTestCase::$headers protected property The headers of the page currently loaded in the internal browser.
DrupalWebTestCase::$httpauth_credentials protected property HTTP authentication credentials (<username>:<password>).
DrupalWebTestCase::$httpauth_method protected property HTTP authentication method
DrupalWebTestCase::$loggedInUser protected property The current user logged in using the internal browser.
DrupalWebTestCase::$originalShutdownCallbacks protected property The original shutdown handlers array, before it was cleaned for testing purposes.
DrupalWebTestCase::$originalUser protected property The original user, before it was changed to a clean uid = 1 for testing purposes.
DrupalWebTestCase::$plainTextContent protected property The content of the page currently loaded in the internal browser (plain text version).
DrupalWebTestCase::$profile protected property The profile to install as a basis for testing. 20
DrupalWebTestCase::$redirect_count protected property The number of redirects followed during the handling of a request.
DrupalWebTestCase::$session_id protected property The current session ID, if available.
DrupalWebTestCase::$session_name protected property The current session name, if available.
DrupalWebTestCase::$url protected property The URL currently loaded in the internal browser.
DrupalWebTestCase::assertField protected function Asserts that a field exists with the given name or ID.
DrupalWebTestCase::assertFieldById protected function Asserts that a field exists in the current page with the given ID and value.
DrupalWebTestCase::assertFieldByName protected function Asserts that a field exists in the current page with the given name and value.
DrupalWebTestCase::assertFieldByXPath protected function Asserts that a field exists in the current page by the given XPath.
DrupalWebTestCase::assertFieldChecked protected function Asserts that a checkbox field in the current page is checked.
DrupalWebTestCase::assertLink protected function Pass if a link with the specified label is found, and optional with the specified index.
DrupalWebTestCase::assertLinkByHref protected function Pass if a link containing a given href (part) is found.
DrupalWebTestCase::assertMail protected function Asserts that the most recently sent e-mail message has the given value.
DrupalWebTestCase::assertMailPattern protected function Asserts that the most recently sent e-mail message has the pattern in it.
DrupalWebTestCase::assertMailString protected function Asserts that the most recently sent e-mail message has the string in it.
DrupalWebTestCase::assertNoDuplicateIds protected function Asserts that each HTML ID is used for just a single element.
DrupalWebTestCase::assertNoField protected function Asserts that a field does not exist with the given name or ID.
DrupalWebTestCase::assertNoFieldById protected function Asserts that a field does not exist with the given ID and value.
DrupalWebTestCase::assertNoFieldByName protected function Asserts that a field does not exist with the given name and value.
DrupalWebTestCase::assertNoFieldByXPath protected function Asserts that a field doesn't exist or its value doesn't match, by XPath.
DrupalWebTestCase::assertNoFieldChecked protected function Asserts that a checkbox field in the current page is not checked.
DrupalWebTestCase::assertNoLink protected function Pass if a link with the specified label is not found.
DrupalWebTestCase::assertNoLinkByHref protected function Pass if a link containing a given href (part) is not found.
DrupalWebTestCase::assertNoOptionSelected protected function Asserts that a select option in the current page is not checked.
DrupalWebTestCase::assertNoPattern protected function Will trigger a pass if the perl regex pattern is not present in raw content.
DrupalWebTestCase::assertNoRaw protected function Pass if the raw text is NOT found on the loaded page, fail otherwise. Raw text refers to the raw HTML that the page generated.
DrupalWebTestCase::assertNoResponse protected function Asserts the page did not return the specified response code.
DrupalWebTestCase::assertNoText protected function Pass if the text is NOT found on the text version of the page. The text version is the equivalent of what a user would see when viewing through a web browser. In other words the HTML has been filtered out of the contents.
DrupalWebTestCase::assertNoTitle protected function Pass if the page title is not the given string.
DrupalWebTestCase::assertNoUniqueText protected function Pass if the text is found MORE THAN ONCE on the text version of the page.
DrupalWebTestCase::assertOptionSelected protected function Asserts that a select option in the current page is checked.
DrupalWebTestCase::assertPattern protected function Will trigger a pass if the Perl regex pattern is found in the raw content.
DrupalWebTestCase::assertRaw protected function Pass if the raw text IS found on the loaded page, fail otherwise. Raw text refers to the raw HTML that the page generated.
DrupalWebTestCase::assertResponse protected function Asserts the page responds with the specified response code.
DrupalWebTestCase::assertText protected function Pass if the text IS found on the text version of the page. The text version is the equivalent of what a user would see when viewing through a web browser. In other words the HTML has been filtered out of the contents.
DrupalWebTestCase::assertTextHelper protected function Helper for assertText and assertNoText.
DrupalWebTestCase::assertThemeOutput protected function Asserts themed output.
DrupalWebTestCase::assertTitle protected function Pass if the page title is the given string.
DrupalWebTestCase::assertUniqueText protected function Pass if the text is found ONLY ONCE on the text version of the page.
DrupalWebTestCase::assertUniqueTextHelper protected function Helper for assertUniqueText and assertNoUniqueText.
DrupalWebTestCase::assertUrl protected function Pass if the internal browser's URL matches the given path.
DrupalWebTestCase::buildXPathQuery protected function Builds an XPath query.
DrupalWebTestCase::changeDatabasePrefix protected function Changes the database connection to the prefixed one.
DrupalWebTestCase::checkForMetaRefresh protected function Check for meta refresh tag and if found call drupalGet() recursively. This function looks for the http-equiv attribute to be set to "Refresh" and is case-sensitive.
DrupalWebTestCase::checkPermissions protected function Check to make sure that the array of permissions are valid.
DrupalWebTestCase::clickLink protected function Follows a link by name.
DrupalWebTestCase::constructFieldXpath protected function Helper function: construct an XPath for the given set of attributes and value.
DrupalWebTestCase::copySetupCache protected function Copy the setup cache from/to another table and files directory.
DrupalWebTestCase::cronRun protected function Runs cron in the Drupal installed by Simpletest.
DrupalWebTestCase::curlClose protected function Close the cURL handler and unset the handler.
DrupalWebTestCase::curlExec protected function Initializes and executes a cURL request.
DrupalWebTestCase::curlHeaderCallback protected function Reads headers and registers errors received from the tested site.
DrupalWebTestCase::curlInitialize protected function Initializes the cURL connection.
DrupalWebTestCase::drupalCompareFiles protected function Compare two files based on size and file name.
DrupalWebTestCase::drupalCreateContentType protected function Creates a custom content type based on default settings.
DrupalWebTestCase::drupalCreateNode protected function Creates a node based on default settings.
DrupalWebTestCase::drupalCreateRole protected function Creates a role with specified permissions.
DrupalWebTestCase::drupalCreateUser protected function Create a user with a given set of permissions.
DrupalWebTestCase::drupalGet protected function Retrieves a Drupal path or an absolute path.
DrupalWebTestCase::drupalGetAJAX protected function Retrieve a Drupal path or an absolute path and JSON decode the result.
DrupalWebTestCase::drupalGetContent protected function Gets the current raw HTML of requested page.
DrupalWebTestCase::drupalGetHeader protected function Gets the value of an HTTP response header. If multiple requests were required to retrieve the page, only the headers from the last request will be checked by default. However, if TRUE is passed as the second argument, all requests will be processed…
DrupalWebTestCase::drupalGetHeaders protected function Gets the HTTP response headers of the requested page. Normally we are only interested in the headers returned by the last request. However, if a page is redirected or HTTP authentication is in use, multiple requests will be required to retrieve the…
DrupalWebTestCase::drupalGetMails protected function Gets an array containing all e-mails sent during this test case.
DrupalWebTestCase::drupalGetNodeByTitle function Get a node from the database based on its title.
DrupalWebTestCase::drupalGetSettings protected function Gets the value of the Drupal.settings JavaScript variable for the currently loaded page.
DrupalWebTestCase::drupalGetTestFiles protected function Get a list files that can be used in tests.
DrupalWebTestCase::drupalGetToken protected function Generate a token for the currently logged in user.
DrupalWebTestCase::drupalHead protected function Retrieves only the headers for a Drupal path or an absolute path.
DrupalWebTestCase::drupalLogin protected function Log in a user with the internal browser.
DrupalWebTestCase::drupalLogout protected function
DrupalWebTestCase::drupalPost protected function Execute a POST request on a Drupal page. It will be done as usual POST request with SimpleBrowser.
DrupalWebTestCase::drupalPostAJAX protected function Execute an Ajax submission.
DrupalWebTestCase::drupalSetContent protected function Sets the raw HTML content. This can be useful when a page has been fetched outside of the internal browser and assertions need to be made on the returned page.
DrupalWebTestCase::drupalSetSettings protected function Sets the value of the Drupal.settings JavaScript variable for the currently loaded page.
DrupalWebTestCase::getAbsoluteUrl protected function Takes a path and returns an absolute path.
DrupalWebTestCase::getAllOptions protected function Get all option elements, including nested options, in a select.
DrupalWebTestCase::getSelectedItem protected function Get the selected value from a select field.
DrupalWebTestCase::getSetupCacheKey protected function Returns the cache key used for the setup caching.
DrupalWebTestCase::getUrl protected function Get the current URL from the cURL handler.
DrupalWebTestCase::handleForm protected function Handle form input related to drupalPost(). Ensure that the specified fields exist and attempt to create POST data in the correct manner for the particular field type.
DrupalWebTestCase::loadSetupCache protected function Copies the cached tables and files for a cached installation setup.
DrupalWebTestCase::parse protected function Parse content returned from curlExec using DOM and SimpleXML.
DrupalWebTestCase::preloadRegistry protected function Preload the registry from the testing site.
DrupalWebTestCase::prepareDatabasePrefix protected function Generates a database prefix for running tests.
DrupalWebTestCase::prepareEnvironment protected function Prepares the current environment for running the test.
DrupalWebTestCase::recursiveDirectoryCopy protected function Recursively copy one directory to another.
DrupalWebTestCase::refreshVariables protected function Refresh the in-memory set of variables. Useful after a page request is made that changes a variable in a different thread. 1
DrupalWebTestCase::resetAll protected function Reset all data structures after having enabled new modules.
DrupalWebTestCase::storeSetupCache protected function Store the installation setup to a cache.
DrupalWebTestCase::tearDown protected function Delete created files and temporary files directory, delete the tables created by setUp(), and reset the database prefix. 6
DrupalWebTestCase::verboseEmail protected function Outputs to verbose the most recent $count emails sent.
DrupalWebTestCase::xpath protected function Perform an xpath search on the contents of the internal browser. The search is relative to the root element (HTML tag normally) of the page.
DrupalWebTestCase::__construct function Constructor for DrupalWebTestCase. Overrides DrupalTestCase::__construct 1
TermMergeTermMergeWebTestCase::getInfo public static function GetInfo method.
TermMergeTermMergeWebTestCase::termMergeResistanceAssert protected function Supportive function for the main test "testTermMergeResistance".
TermMergeTermMergeWebTestCase::testTermMerge public function Test merging two terms.
TermMergeTermMergeWebTestCase::testTermMergeBatch public function Test all cases of usage of Term Merge Batch.
TermMergeTermMergeWebTestCase::testTermMergeResistance public function Test all cases for potentially "buggy" input.
TermMergeWebTestCase::$admin protected property Fully loaded Drupal user who has access to all required parts of the website for testing.
TermMergeWebTestCase::$vocabulary protected property Fully loaded Drupal taxonomy vocabulary object on which all tests are run.
TermMergeWebTestCase::getLastTerm protected function Return last inserted term into the specified vocabulary.
TermMergeWebTestCase::normalizeSetUpArguments protected function Normalize the input arguments of ::setUp() method.
TermMergeWebTestCase::setUp public function SetUp method. Overrides DrupalWebTestCase::setUp 4