You are here

class QuickEditLoadingTest in Quick Edit 7

Tests loading of Quick Edit and lazy-loading of in-place editors.

Hierarchy

Expanded class hierarchy of QuickEditLoadingTest

File

./quickedit.test, line 11
Tests loading of Quick Edit and lazy-loading of in-place editors.

View source
class QuickEditLoadingTest extends DrupalWebTestCase {

  /**
   * The installation profile to use with this test class.
   *
   * @var string
   */
  protected $profile = 'testing';
  public static function getInfo() {
    return array(
      'name' => 'In-place editing loading',
      'description' => 'Tests loading of in-place editing functionality and lazy loading of its in-place editors.',
      'group' => 'Quick Edit',
    );
  }
  protected function setUp() {

    // Block module is necessary for regions to show up, and hence for
    // hook_page_build() to be able to #attach something in Drupal 7.
    parent::setUp(array(
      'block',
      'contextual',
      'quickedit',
      'filter',
      'node',
    ));

    // Bartik theme alters comment links, so use a different theme.
    theme_enable(array(
      'bartik',
    ));
    variable_set('theme_default', 'bartik');

    // Create a text format.
    $filtered_html_format = new stdClass();
    $filtered_html_format->format = 'filtered_html';
    $filtered_html_format->name = 'Filtered HTML';
    $filtered_html_format->filters = array();
    filter_format_save($filtered_html_format);

    // Create a node type.
    $this
      ->drupalCreateContentType(array(
      'type' => 'article',
      'name' => 'Article',
    ));

    // Create one node of the above node type using the above text format.
    $this
      ->drupalCreateNode(array(
      'type' => 'article',
      'title' => '<script>alert("EVIL!")</script>',
      'body' => array(
        LANGUAGE_NONE => array(
          0 => array(
            'value' => '<p>How are you?</p>',
            'format' => 'filtered_html',
          ),
        ),
      ),
      'log' => $this
        ->randomString(),
      'promote' => 1,
    ));

    // Create 2 users, the only difference being the ability to use in-place
    // editing
    $basic_permissions = array(
      'access content',
      'create article content',
      'edit any article content',
      'use text format filtered_html',
      'access contextual links',
    );
    $this->author_user = $this
      ->drupalCreateUser($basic_permissions);
    $this->editor_user = $this
      ->drupalCreateUser(array_merge($basic_permissions, array(
      'access in-place editing',
    )));
  }

  /**
   * Test the loading of Quick Edit when a user doesn't have access to it.
   */
  public function testUserWithoutPermission() {
    $this
      ->drupalLogin($this->author_user);
    $this
      ->drupalGet('node/1');

    // Library and in-place editors.
    $settings = $this
      ->drupalGetSettings();
    $module_path = drupal_get_path('module', 'quickedit');
    $this
      ->assertFalse(isset($settings['ajaxPageState']['js'][$module_path . '/js/quickedit.js']), 'Quick Edit library not loaded.');
    $this
      ->assertFalse(isset($settings['ajaxPageState']['js'][$module_path . '/quickedit/js/editors/formEditor.js']), "'form' in-place editor not loaded.");

    // HTML annotation does not exist for users without permission to in-place
    // edit.
    $this
      ->assertNoRaw('data-quickedit-entity-id="node/1"');
    $this
      ->assertNoRaw('data-quickedit-field-id="node/1/body/und/full"');

    // Retrieving the metadata should result in an empty 403 response.
    $post = array(
      'fields[0]' => 'node/1/body/und/full',
    );
    $response = $this
      ->drupalPostCustom('quickedit/metadata', 'application/json', $post);

    // @todo: Sadly, Drupal 7 returns HTML when a 403 occurs, no matter what the
    //        Content-Type is. It should be possible to work around this by
    //        moving the access check into the page callback. Question is
    //        whether that's worth the effort.
    // $this->assertIdentical('{}', $response);
    $this
      ->assertResponse(403);

    // Quick Edit's JavaScript would never hit these endpoints if the metadata
    // was empty as above, but we need to make sure that malicious users aren't
    // able to use any of the other endpoints either.
    $post = array(
      'editors[0]' => 'form',
    ) + $this
      ->getAjaxPageStatePostData();
    $response = $this
      ->drupalPostCustom('quickedit/attachments', 'application/vnd.drupal-ajax', $post);
    $commands = drupal_json_decode($response);
    $this
      ->assertIdentical(2, count($commands));
    $this
      ->assertIdentical('settings', $commands[0]['command']);
    $this
      ->assertIdentical('alert', $commands[1]['command']);
    $this
      ->assertIdentical('You are not authorized to access this page.', $commands[1]['text']);
    $this
      ->assertResponse(200);

    // 403 in Drupal 8!
    $post = array(
      'nocssjs' => 'true',
    ) + $this
      ->getAjaxPageStatePostData();
    $response = $this
      ->drupalPostCustom('quickedit/form/' . 'node/1/body/und/full', 'application/vnd.drupal-ajax', $post);
    $commands = drupal_json_decode($response);
    $this
      ->assertIdentical(2, count($commands));
    $this
      ->assertIdentical('settings', $commands[0]['command']);
    $this
      ->assertIdentical('alert', $commands[1]['command']);
    $this
      ->assertIdentical('You are not authorized to access this page.', $commands[1]['text']);
    $this
      ->assertResponse(200);

    // 403 in Drupal 8!
    $edit = array();
    $edit['form_id'] = 'quickedit_field_form';
    $edit['form_token'] = 'xIOzMjuc-PULKsRn_KxFn7xzNk5Bx7XKXLfQfw1qOnA';
    $edit['form_build_id'] = 'form-kVmovBpyX-SJfTT5kY0pjTV35TV-znor--a64dEnMR8';
    $edit['body[0][summary]'] = '';
    $edit['body[0][value]'] = '<p>Malicious content.</p>';
    $edit['body[0][format]'] = 'filtered_html';
    $edit['op'] = t('Save');
    $response = $this
      ->drupalPostCustom('quickedit/form/' . 'node/1/body/und/full', 'application/vnd.drupal-ajax', $edit);
    $commands = drupal_json_decode($response);
    $this
      ->assertIdentical(2, count($commands));
    $this
      ->assertIdentical('settings', $commands[0]['command']);
    $this
      ->assertIdentical('alert', $commands[1]['command']);
    $this
      ->assertIdentical('You are not authorized to access this page.', $commands[1]['text']);
    $this
      ->assertResponse(200);

    // 403 in Drupal 8!
    $post = array(
      'nocssjs' => 'true',
    );
    $response = $this
      ->drupalPostCustom('quickedit/entity/' . 'node/1', 'application/json', $post);
    $commands = drupal_json_decode($response);
    $this
      ->assertIdentical(2, count($commands));
    $this
      ->assertIdentical('settings', $commands[0]['command']);
    $this
      ->assertIdentical('alert', $commands[1]['command']);
    $this
      ->assertIdentical('You are not authorized to access this page.', $commands[1]['text']);
    $this
      ->assertResponse(200);

    // 403 in Drupal 8!
  }

  /**
   * Tests the loading of Quick Edit when a user does have access to it.
   *
   * Also ensures lazy loading of in-place editors works.
   */
  public function testUserWithPermission() {
    $this
      ->drupalLogin($this->editor_user);
    $this
      ->drupalGet('node/1');

    // Library and in-place editors.
    $settings = $this
      ->drupalGetSettings();
    $module_path = drupal_get_path('module', 'quickedit');
    $this
      ->assertTrue(isset($settings['ajaxPageState']['js'][$module_path . '/js/quickedit.js']), 'Quick Edit library loaded.');
    $this
      ->assertFalse(isset($settings['ajaxPageState']['js'][$module_path . '/js/editors/formEditor.js']), "'form' in-place editor not loaded.");

    // HTML annotation must always exist (to not break the render cache).
    $this
      ->assertRaw('data-quickedit-entity-id="node/1"');
    $this
      ->assertRaw('data-quickedit-field-id="node/1/body/und/full"');

    // There should be only one revision so far.
    $revisions = node_revision_list(node_load(1));
    $this
      ->assertIdentical(1, count($revisions), 'The node has only one revision.');
    $original_log = $revisions[1]->log;

    // Retrieving the metadata should result in a 200 JSON response.
    $htmlPageDrupalSettings = $this->drupalSettings;
    $post = array(
      'fields[0]' => 'node/1/body/und/full',
    );
    $response = $this
      ->drupalPostCustom('quickedit/metadata', 'application/json', $post);
    $this
      ->assertResponse(200);
    $expected = array(
      'node/1/body/und/full' => array(
        'label' => 'Body',
        'access' => TRUE,
        'editor' => 'form',
        'aria' => 'Entity node 1, field Body',
      ),
    );
    $this
      ->assertIdentical(drupal_json_decode($response), $expected, 'The metadata HTTP request answers with the correct JSON response.');

    // Restore drupalSettings to build the next requests; simpletest wipes them
    // after a JSON response.
    $this->drupalSettings = $htmlPageDrupalSettings;

    // Retrieving the attachments should result in a 200 response, containing:
    //  1. a settings command with useless metadata: AjaxController is dumb
    //  2. an insert command that loads the required in-place editors
    $post = array(
      'editors[0]' => 'form',
    ) + $this
      ->getAjaxPageStatePostData();
    $response = $this
      ->drupalPostCustom('quickedit/attachments', 'application/vnd.drupal-ajax', $post);
    $ajax_commands = drupal_json_decode($response);
    $this
      ->assertIdentical(2, count($ajax_commands), 'The attachments HTTP request results in two AJAX commands.');

    // First command: settings.
    $this
      ->assertIdentical('settings', $ajax_commands[0]['command'], 'The first AJAX command is a settings command.');

    // Second command: insert libraries into DOM.
    $this
      ->assertIdentical('insert', $ajax_commands[1]['command'], 'The second AJAX command is an append command.');
    $expected = array(
      'command' => 'insert',
      'method' => 'append',
      'selector' => 'body',
      'data' => '<script type="text/javascript" src="' . file_create_url($module_path . '/js/editors/formEditor.js') . '?v=' . VERSION . '"></script>' . "\n",
      'settings' => NULL,
    );
    $this
      ->assertIdentical($expected, $ajax_commands[1], 'The append command contains the expected data.');

    // Retrieving the form for this field should result in a 200 response,
    // containing only an quickeditFieldForm command.
    $post = array(
      'nocssjs' => 'true',
      'reset' => 'true',
    ) + $this
      ->getAjaxPageStatePostData();
    $response = $this
      ->drupalPostCustom('quickedit/form/' . 'node/1/body/und/full', 'application/vnd.drupal-ajax', $post);
    $this
      ->assertResponse(200);
    $ajax_commands = drupal_json_decode($response);
    $this
      ->assertIdentical(1, count($ajax_commands), 'The field form HTTP request results in one AJAX command.');
    $this
      ->assertIdentical('quickeditFieldForm', $ajax_commands[0]['command'], 'The first AJAX command is an editFieldForm command.');
    $this
      ->assertIdentical('<form ', drupal_substr($ajax_commands[0]['data'], 0, 6), 'The quickeditFieldForm command contains a form.');

    // Prepare form values for submission. drupalPostAjaxForm() is not suitable
    // for handling pages with JSON responses, so we need our own solution
    // here.
    $form_tokens_found = preg_match('/\\sname="form_token" value="([^"]+)"/', $ajax_commands[0]['data'], $token_match) && preg_match('/\\sname="form_build_id" value="([^"]+)"/', $ajax_commands[0]['data'], $build_id_match);
    $this
      ->assertTrue($form_tokens_found, 'Form tokens found in output.');
    if ($form_tokens_found) {
      $edit = array(
        'body[und][0][summary]' => '',
        'body[und][0][value]' => '<p>Fine thanks.</p>',
        'body[und][0][format]' => 'filtered_html',
        'op' => t('Save'),
      );
      $post = array(
        'form_id' => 'quickedit_field_form',
        'form_token' => $token_match[1],
        'form_build_id' => $build_id_match[1],
      );
      $post += $edit + $this
        ->getAjaxPageStatePostData();

      // Submit field form and check response. This should store the updated
      // entity in TempStore on the server.
      $response = $this
        ->drupalPostCustom('quickedit/form/' . 'node/1/body/und/full', 'application/vnd.drupal-ajax', $post);
      $this
        ->assertResponse(200);
      $ajax_commands = drupal_json_decode($response);
      $this
        ->assertIdentical(2, count($ajax_commands), 'The field form HTTP request results in two AJAX commands.');
      $this
        ->assertIdentical('settings', $ajax_commands[0]['command'], 'The first AJAX command is a settings command.');
      $this
        ->assertIdentical('quickeditFieldFormSaved', $ajax_commands[1]['command'], 'The second AJAX command is an quickeditFieldFormSaved command.');
      $this
        ->assertTrue(strpos($ajax_commands[1]['data'], 'Fine thanks.'), 'Form value saved and printed back.');
      $this
        ->assertIdentical($ajax_commands[1]['other_view_modes'], array(), 'Field was not rendered in any other view mode.');

      // Ensure the text on the original node did not change yet.
      $this
        ->drupalGet('node/1');
      $this
        ->assertText('How are you?');

      // Save the entity by moving the TempStore values to entity storage.
      $post = array(
        'nocssjs' => 'true',
      );
      $response = $this
        ->drupalPostCustom('quickedit/entity/' . 'node/1', 'application/json', $post);
      $this
        ->assertResponse(200);
      $ajax_commands = drupal_json_decode($response);
      $this
        ->assertIdentical(2, count($ajax_commands), 'The entity submission HTTP request results in two AJAX commands.');
      $this
        ->assertIdentical('settings', $ajax_commands[0]['command'], 'The first AJAX command is a settings command.');
      $this
        ->assertIdentical('quickeditEntitySaved', $ajax_commands[1]['command'], 'The second AJAX command is an quickeditEntitySaved command.');
      $this
        ->assertIdentical($ajax_commands[1]['data']['entity_type'], 'node', 'Saved entity is of type node.');
      $this
        ->assertIdentical($ajax_commands[1]['data']['entity_id'], '1', 'Entity id is 1.');

      // Ensure the text on the original node did change.
      $this
        ->drupalGet('node/1');
      $this
        ->assertText('Fine thanks.');

      // Ensure no new revision was created and the log message is unchanged.
      $revisions = node_revision_list(node_load(1));
      $this
        ->assertIdentical(1, count($revisions), 'The node has only one revision.');
      $this
        ->assertIdentical($original_log, $revisions[1]->log, 'The revision log message is unchanged.');

      // Now configure this node type to create new revisions automatically,
      // then again retrieve the field form, fill it, submit it (so it ends up
      // in TempStore) and then save the entity. Now there should be two
      // revisions.
      variable_set('node_options_article', array(
        'status',
        'revision',
      ));

      // Retrieve field form.
      $post = array(
        'nocssjs' => 'true',
        'reset' => 'true',
      );
      $response = $this
        ->drupalPostCustom('quickedit/form/' . 'node/1/body/und/full', 'application/vnd.drupal-ajax', $post);
      $this
        ->assertResponse(200);
      $ajax_commands = drupal_json_decode($response);
      $this
        ->assertIdentical(1, count($ajax_commands), 'The field form HTTP request results in one AJAX command.');
      $this
        ->assertIdentical('quickeditFieldForm', $ajax_commands[0]['command'], 'The first AJAX command is an quickeditFieldForm command.');
      $this
        ->assertIdentical('<form ', drupal_substr($ajax_commands[0]['data'], 0, 6), 'The quickeditFieldForm command contains a form.');

      // Submit field form.
      preg_match('/\\sname="form_token" value="([^"]+)"/', $ajax_commands[0]['data'], $token_match);
      preg_match('/\\sname="form_build_id" value="([^"]+)"/', $ajax_commands[0]['data'], $build_id_match);
      $edit['body[und][0][value]'] = '<p>kthxbye</p>';
      $post = array(
        'form_id' => 'quickedit_field_form',
        'form_token' => $token_match[1],
        'form_build_id' => $build_id_match[1],
      );
      $post += $edit + $this
        ->getAjaxPageStatePostData();
      $response = $this
        ->drupalPostCustom('quickedit/form/' . 'node/1/body/und/full', 'application/vnd.drupal-ajax', $post);

      // @todo Uncomment the below once https://drupal.org/node/2063303 is fixed.
      // $this->assertIdentical('[]', $response);
      $this
        ->assertResponse(200);
      $ajax_commands = drupal_json_decode($response);
      $this
        ->assertIdentical(2, count($ajax_commands), 'The field form HTTP request results in two AJAX commands.');
      $this
        ->assertIdentical('settings', $ajax_commands[0]['command'], 'The first AJAX command is a settings command.');
      $this
        ->assertIdentical('quickeditFieldFormSaved', $ajax_commands[1]['command'], 'The second AJAX command is an quickeditFieldFormSaved command.');
      $this
        ->assertTrue(strpos($ajax_commands[1]['data'], 'kthxbye'), 'Form value saved and printed back.');

      // Save the entity.
      $post = array(
        'nocssjs' => 'true',
      );
      $response = $this
        ->drupalPostCustom('quickedit/entity/' . 'node/1', 'application/json', $post);

      // @todo Uncomment the below once https://drupal.org/node/2063303 is fixed.
      // $this->assertIdentical('[]', $response);
      $this
        ->assertResponse(200);

      // Test that a revision was created with the correct log message.
      $revisions = node_revision_list(node_load(1));
      $this
        ->assertIdentical(2, count($revisions), 'The node has two revisions.');
      $this
        ->assertIdentical($original_log, $revisions[1]->log, 'The first revision log message is unchanged.');
      $this
        ->assertIdentical('Updated the <em class="placeholder">Body</em> field through in-place editing.', $revisions[2]->log, 'The second revision log message was correctly generated by Edit module.');
    }
  }

  /**
   * Tests the loading of Quick Edit for the title base field.
   */
  public function testTitleBaseField() {
    $this
      ->drupalLogin($this->editor_user);

    // First, ensure quickedit_preprocess_node()'s wrapping of the 'title'
    // template variable does not result in an XSS. We cannot check this on the
    // full node page, because there the 'node' template's 'title' variable is
    // not printed: there, the actual
    $this
      ->drupalGet('');
    $this
      ->assertNoRaw('<script>alert("EVIL!")</script>');

    // Next, try in-place editing the node on its full node page. Also ensure
    // quickedit_preprocess_page()'s wrapping of the 'title' template variable
    // does not result in an XSS.
    $this
      ->drupalGet('node/1');
    $this
      ->assertNoRaw('<script>alert("EVIL!")</script>');

    // Ensure that the full page title is actually in-place editable
    $node = node_load(1);
    $elements = $this
      ->xpath('//h1/div[@data-quickedit-field-id="node/1/title/und/full" and normalize-space(text())=:title]', array(
      ':title' => $node->title,
    ));
    $this
      ->assertTrue(!empty($elements), 'Title with data-quickedit-field-id attribute found.');

    // Retrieving the metadata should result in a 200 JSON response.
    $htmlPageDrupalSettings = $this->drupalSettings;
    $post = array(
      'entities[0]' => 'node/1',
      'fields[0]' => 'node/1/title/und/full',
    );
    $response = $this
      ->drupalPostCustom('quickedit/metadata', 'application/json', $post);
    $this
      ->assertResponse(200);
    $expected = array(
      // The label should be check_plain()'d.
      'node/1' => array(
        'label' => '&lt;script&gt;alert(&quot;EVIL!&quot;)&lt;/script&gt;',
      ),
      'node/1/title/und/full' => array(
        'label' => 'Title',
        'access' => TRUE,
        'editor' => 'plain_text',
        'aria' => 'Entity node 1, field Title',
      ),
    );
    $this
      ->assertIdentical(drupal_json_decode($response), $expected, 'The metadata HTTP request answers with the correct JSON response.');

    // Restore drupalSettings to build the next requests; simpletest wipes them
    // after a JSON response.
    $this->drupalSettings = $htmlPageDrupalSettings;

    // Retrieving the form for this field should result in a 200 response,
    // containing only an quickeditFieldForm command.
    $post = array(
      'nocssjs' => 'true',
      'reset' => 'true',
    ) + $this
      ->getAjaxPageStatePostData();
    $response = $this
      ->drupalPostCustom('quickedit/form/' . 'node/1/title/und/full', 'application/vnd.drupal-ajax', $post);
    $this
      ->assertResponse(200);
    $ajax_commands = drupal_json_decode($response);
    $this
      ->assertIdentical(1, count($ajax_commands), 'The field form HTTP request results in one AJAX command.');
    $this
      ->assertIdentical('quickeditFieldForm', $ajax_commands[0]['command'], 'The first AJAX command is an quickeditFieldForm command.');
    $this
      ->assertIdentical('<form ', drupal_substr($ajax_commands[0]['data'], 0, 6), 'The quickeditFieldForm command contains a form.');

    // Prepare form values for submission. drupalPostAjaxForm() is not suitable
    // for handling pages with JSON responses, so we need our own solution
    // here.
    $form_tokens_found = preg_match('/\\sname="form_token" value="([^"]+)"/', $ajax_commands[0]['data'], $token_match) && preg_match('/\\sname="form_build_id" value="([^"]+)"/', $ajax_commands[0]['data'], $build_id_match);
    $this
      ->assertTrue($form_tokens_found, 'Form tokens found in output.');
    if ($form_tokens_found) {
      $edit = array(
        'title' => 'Obligatory question',
        'op' => t('Save'),
      );
      $post = array(
        'form_id' => 'quickedit_field_form',
        'form_token' => $token_match[1],
        'form_build_id' => $build_id_match[1],
      );
      $post += $edit + $this
        ->getAjaxPageStatePostData();

      // Submit field form and check response. This should store the
      // updated entity in TempStore on the server.
      $response = $this
        ->drupalPostCustom('quickedit/form/' . 'node/1/title/und/full', 'application/vnd.drupal-ajax', $post);
      $this
        ->assertResponse(200);
      $ajax_commands = drupal_json_decode($response);
      $this
        ->assertIdentical(2, count($ajax_commands), 'The field form HTTP request results in two AJAX commands.');
      $this
        ->assertIdentical('settings', $ajax_commands[0]['command'], 'The first AJAX command is a settings command.');
      $this
        ->assertIdentical('quickeditFieldFormSaved', $ajax_commands[1]['command'], 'The second AJAX command is an quickeditFieldFormSaved command.');
      $this
        ->assertTrue(strpos($ajax_commands[1]['data'], 'Obligatory question'), 'Form value saved and printed back.');

      // Ensure the text on the original node did not change yet.
      $this
        ->drupalGet('node/1');
      $this
        ->assertNoText('Obligatory question');

      // Save the entity by moving the TempStore values to entity storage.
      $post = array(
        'nocssjs' => 'true',
      );
      $response = $this
        ->drupalPostCustom('quickedit/entity/' . 'node/1', 'application/json', $post);
      $this
        ->assertResponse(200);
      $ajax_commands = drupal_json_decode($response);
      $this
        ->assertIdentical(2, count($ajax_commands), 'The entity submission HTTP request results in two AJAX commands.');
      $this
        ->assertIdentical('settings', $ajax_commands[0]['command'], 'The first AJAX command is a settings command.');
      $this
        ->assertIdentical('quickeditEntitySaved', $ajax_commands[1]['command'], 'The second AJAX command is an quickeditEntitySaved command.');
      $this
        ->assertIdentical($ajax_commands[1]['data']['entity_type'], 'node', 'Saved entity is of type node.');
      $this
        ->assertIdentical($ajax_commands[1]['data']['entity_id'], '1', 'Entity id is 1.');

      // Ensure the text on the original node did change.
      $this
        ->drupalGet('node/1');
      $this
        ->assertText('Obligatory question');
    }
  }

  /**
   * Tests that Quick Edit doesn't make fields rendered with display options editable.
   */
  public function testDisplayOptions() {
    $node = node_load('1');
    $display_settings = array(
      'label' => 'inline',
    );
    $build = field_view_field('node', $node, 'body', $display_settings);
    $output = drupal_render($build);
    $this
      ->assertFalse(strpos($output, 'data-quickedit-field-id'), 'data-quickedit-field-id attribute not added when rendering field using dynamic display options.');
  }

  /**
   * Tests that Quick Edit works with custom render pipelines.
   */
  public function testCustomPipeline() {
    module_enable(array(
      'quickedit_test',
    ));
    $custom_render_url = 'quickedit/form/node/1/body/und/quickedit_test-custom-render-data';
    $this
      ->drupalLogin($this->editor_user);

    // Request editing to render results with the custom render pipeline.
    $post = array(
      'nocssjs' => 'true',
    ) + $this
      ->getAjaxPageStatePostData();
    $response = $this
      ->drupalPostCustom($custom_render_url, 'application/vnd.drupal-ajax', $post);
    $ajax_commands = drupal_json_decode($response);

    // Prepare form values for submission. drupalPostAJAX() is not suitable for
    // handling pages with JSON responses, so we need our own solution here.
    $form_tokens_found = preg_match('/\\sname="form_token" value="([^"]+)"/', $ajax_commands[0]['data'], $token_match) && preg_match('/\\sname="form_build_id" value="([^"]+)"/', $ajax_commands[0]['data'], $build_id_match);
    $this
      ->assertTrue($form_tokens_found, 'Form tokens found in output.');
    if ($form_tokens_found) {
      $post = array(
        'form_id' => 'quickedit_field_form',
        'form_token' => $token_match[1],
        'form_build_id' => $build_id_match[1],
        'body[und][0][summary]' => '',
        'body[und][0][value]' => '<p>Fine thanks.</p>',
        'body[und][0][format]' => 'filtered_html',
        'op' => t('Save'),
      );

      // Assume there is another field on this page, which doesn't use a custom
      // render pipeline, but the default one, and it uses the "full" view mode.
      $post += array(
        'other_view_modes[]' => 'full',
      );

      // Submit field form and check response. Should render with the custom
      // render pipeline.
      $response = $this
        ->drupalPostCustom($custom_render_url, 'application/vnd.drupal-ajax', $post);
      $this
        ->assertResponse(200);
      $ajax_commands = drupal_json_decode($response);
      $this
        ->assertIdentical(2, count($ajax_commands), 'The field form HTTP request results in two AJAX commands.');
      $this
        ->assertIdentical('settings', $ajax_commands[0]['command'], 'The first AJAX command is a settings command.');
      $this
        ->assertIdentical('quickeditFieldFormSaved', $ajax_commands[1]['command'], 'The second AJAX command is an quickeditFieldFormSaved command.');
      $this
        ->assertTrue(strpos($ajax_commands[1]['data'], 'Fine thanks.'), 'Form value saved and printed back.');
      $this
        ->assertTrue(strpos($ajax_commands[1]['data'], '<div class="quickedit-test-wrapper">') !== FALSE, 'Custom render pipeline used to render the value.');
      $this
        ->assertIdentical(array_keys($ajax_commands[1]['other_view_modes']), array(
        'full',
      ), 'Field was also rendered in the "full" view mode.');
      $this
        ->assertTrue(strpos($ajax_commands[1]['other_view_modes']['full'], 'Fine thanks.'), '"full" version of field contains the form value.');
    }
  }

  /**
   * Tests Quick Edit with concurrent node / Quick Edit use.
   */
  function testConcurrentEdit() {
    $this
      ->drupalLogin($this->editor_user);

    // Retrieving the form for this field should result in a 200 response,
    // containing only an quickeditFieldForm command.
    $post = array(
      'nocssjs' => 'true',
      'reset' => 'true',
    ) + $this
      ->getAjaxPageStatePostData();
    $response = $this
      ->drupalPostCustom('quickedit/form/' . 'node/1/body/und/full', 'application/vnd.drupal-ajax', $post);
    $this
      ->assertResponse(200);
    $ajax_commands = drupal_json_decode($response);

    // Prepare form values for submission. drupalPostAJAX() is not suitable
    // for handling pages with JSON responses, so we need our own solution
    // here.
    $form_tokens_found = preg_match('/\\sname="form_token" value="([^"]+)"/', $ajax_commands[0]['data'], $token_match) && preg_match('/\\sname="form_build_id" value="([^"]+)"/', $ajax_commands[0]['data'], $build_id_match);
    $this
      ->assertTrue($form_tokens_found, 'Form tokens found in output.');
    if ($form_tokens_found) {
      $post = array();
      $post['form_id'] = 'quickedit_field_form';
      $post['form_token'] = $token_match[1];
      $post['form_build_id'] = $build_id_match[1];
      $post['body[und][0][summary]'] = '';
      $post['body[und][0][value]'] = '<p>Fine thanks.</p>';
      $post['body[und][0][format]'] = 'filtered_html';
      $post['op'] = t('Save');

      // Save the node on the regular node edit form.
      $this
        ->drupalPost('node/1/edit', array(), t('Save'));

      // Ensure different save timestamps for field editing.
      sleep(2);

      // Submit field form and check response. Should throw a validation error
      // because the node was changed in the meantime.
      // $response = $this->submitFieldForm('node/1/body/und/full', $edit);
      $response = $this
        ->drupalPostCustom('quickedit/form/' . 'node/1/body/und/full', 'application/vnd.drupal-ajax', $post);
      $this
        ->assertResponse(200);
      $ajax_commands = drupal_json_decode($response);
      $this
        ->assertIdentical(2, count($ajax_commands), 'The field form HTTP request results in two AJAX commands.');
      $this
        ->assertIdentical('settings', $ajax_commands[0]['command'], 'The first AJAX command is a settings command.');
      $this
        ->assertIdentical('quickeditFieldFormValidationErrors', $ajax_commands[1]['command'], 'The second AJAX command is an quickeditFieldFormValidationErrors command.');
      $this
        ->assertTrue(strpos($ajax_commands[1]['data'], t('The copy of the content being edited is outdated. Reload the page to edit an up-to-date version.')), 'Error message returned to user.');
    }
  }

  /**
   * Perform a POST HTTP request in a non-form context.
   *
   * @param string $path
   *   Drupal path where the request should be POSTed to. Will be transformed
   *   into an absolute path automatically.
   * @param string $accept
   *   The value for the "Accept" header. Usually either 'application/json' or
   *   'application/vnd.drupal-ajax'.
   * @param array $post
   *   The POST data. When making a 'application/vnd.drupal-ajax' request, the
   *   Ajax page state data should be included. Use getAjaxPageStatePostData()
   *   for that.
   * @param array $options
   *   (optional) Options to be forwarded to the url generator. The 'absolute'
   *   option will automatically be enabled.
   *
   * @return
   *   The content returned from the call to curl_exec().
   *
   * @see WebTestBase::getAjaxPageStatePostData()
   * @see WebTestBase::curlExec()
   * @see url()
   */
  protected function drupalPostCustom($path, $accept, array $post, $options = array()) {
    return $this
      ->curlExec(array(
      CURLOPT_URL => url($path, $options + array(
        'absolute' => TRUE,
      )),
      CURLOPT_POST => TRUE,
      CURLOPT_POSTFIELDS => $this
        ->serializePostValues($post),
      CURLOPT_HTTPHEADER => array(
        'Accept: ' . $accept,
        'Content-Type: application/x-www-form-urlencoded',
      ),
    ));
  }

  /**
   * Serialize POST HTTP request values.
   *
   * Encode according to application/x-www-form-urlencoded. Both names and
   * values needs to be urlencoded, according to
   * http://www.w3.org/TR/html4/interact/forms.html#h-17.13.4.1
   *
   * @param array $post
   *   The array of values to be POSTed.
   *
   * @return string
   *   The serialized result.
   */
  protected function serializePostValues($post = array()) {
    foreach ($post as $key => $value) {
      $post[$key] = urlencode($key) . '=' . urlencode($value);
    }
    return implode('&', $post);
  }

  /**
   * Get the Ajax page state from drupalSettings and prepare it for POSTing.
   *
   * @return array
   *   The Ajax page state POST data.
   */
  protected function getAjaxPageStatePostData() {
    $post = array();
    $drupal_settings = $this->drupalSettings;
    if (isset($drupal_settings['ajaxPageState'])) {
      $post['ajax_page_state[theme]'] = $drupal_settings['ajaxPageState']['theme'];
      $post['ajax_page_state[theme_token]'] = $drupal_settings['ajaxPageState']['theme_token'];
      foreach ($drupal_settings['ajaxPageState']['css'] as $key => $value) {
        $post["ajax_page_state[css][{$key}]"] = 1;
      }
      foreach ($drupal_settings['ajaxPageState']['js'] as $key => $value) {
        $post["ajax_page_state[js][{$key}]"] = 1;
      }
    }
    return $post;
  }

}

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::$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
QuickEditLoadingTest::$profile protected property The installation profile to use with this test class. Overrides DrupalWebTestCase::$profile
QuickEditLoadingTest::drupalPostCustom protected function Perform a POST HTTP request in a non-form context.
QuickEditLoadingTest::getAjaxPageStatePostData protected function Get the Ajax page state from drupalSettings and prepare it for POSTing.
QuickEditLoadingTest::getInfo public static function
QuickEditLoadingTest::serializePostValues protected function Serialize POST HTTP request values.
QuickEditLoadingTest::setUp protected function Sets up a Drupal site for running functional and integration tests. Overrides DrupalWebTestCase::setUp
QuickEditLoadingTest::testConcurrentEdit function Tests Quick Edit with concurrent node / Quick Edit use.
QuickEditLoadingTest::testCustomPipeline public function Tests that Quick Edit works with custom render pipelines.
QuickEditLoadingTest::testDisplayOptions public function Tests that Quick Edit doesn't make fields rendered with display options editable.
QuickEditLoadingTest::testTitleBaseField public function Tests the loading of Quick Edit for the title base field.
QuickEditLoadingTest::testUserWithoutPermission public function Test the loading of Quick Edit when a user doesn't have access to it.
QuickEditLoadingTest::testUserWithPermission public function Tests the loading of Quick Edit when a user does have access to it.