You are here

abstract class BotchaBaseWebTestCase in BOTCHA Spam Prevention 6.3

Same name and namespace in other branches
  1. 6 botcha.test \BotchaBaseWebTestCase
  2. 6.2 botcha.test \BotchaBaseWebTestCase
  3. 7 botcha.test \BotchaBaseWebTestCase
  4. 7.2 botcha.test \BotchaBaseWebTestCase
  5. 7.3 tests/botcha.simpletest.test \BotchaBaseWebTestCase

Base class for BOTCHA tests.

Provides common setup stuff and various helper functions

Hierarchy

Expanded class hierarchy of BotchaBaseWebTestCase

File

tests/botcha.simpletest.test, line 34
Simpletest-tests for BOTCHA module.

View source
abstract class BotchaBaseWebTestCase extends DrupalWebTestCase {

  /**
   * @var Botcha
   */
  protected $application;

  /**
   * User with various administrative permissions.
   * @var Drupal user
   */
  protected $admin_user;

  /**
   * Normal visitor with limited permissions
   * @var Drupal user;
   */
  protected $normal_user;
  public function setUp() {

    // Backward compatibility together with support of new way of passing modules parameter.
    // @link DrupalWebTestCase::setUp() @endlink
    $modules = func_get_args();
    if (isset($modules[0]) && is_array($modules[0])) {
      $modules = $modules[0];
    }
    parent::setUp(array_merge($modules, array(
      'comment',
      'autoload',
      'moopapi',
      'dbtng',
    )));

    // @todo Abstract it.
    // @todo Keep an eye on the issue, that will make it unnecessary.
    // @see http://drupal.org/node/1843018
    dbtng_boot();
    drupal_install_modules(array(
      'botcha',
    ));
    $this
      ->resetAll();

    // Fill in the application.
    $this->application = ComponentFactory::get('Botcha', Component::TYPE_CONTROLLER, Component::ID_APPLICATION);

    // Create a normal user.
    $permissions = array(
      'access comments',
      'post comments',
      // @todo Abstract it.
      'post comments without approval',
      //'skip comment approval',
      'access content',
      'create page content',
      'edit own page content',
    );
    $this->normal_user = $this
      ->drupalCreateUser($permissions);

    // Create an admin user.
    $permissions[] = 'administer BOTCHA settings';
    $permissions[] = 'skip BOTCHA';
    $permissions[] = 'administer permissions';
    $permissions[] = 'administer content types';

    // It is for admin test case.
    $permissions[] = 'access site reports';
    $this->admin_user = $this
      ->drupalCreateUser($permissions);

    // Put comments on page nodes on a separate page (default in D7: below post).
    variable_set('comment_form_location_page', COMMENT_FORM_SEPARATE_PAGE);
  }

  /**
   * Assert that the response is accepted:
   * no "unknown CSID" message, no "CSID reuse attack detection" message,
   * no "wrong answer" message.
   */
  protected function assertBotchaResponseAccepted() {

    // There should be no error message about unknown BOTCHA session ID.
    $this
      ->assertNoText(t(BOTCHA_UNKNOWN_CSID_ERROR_MESSAGE), 'BOTCHA response should be accepted (known CSID).', 'BOTCHA');

    // There should be no error message about CSID reuse attack.
    $this
      ->assertNoText(t(BOTCHA_SESSION_REUSE_ATTACK_ERROR_MESSAGE), 'BOTCHA response should be accepted (no BOTCHA session reuse attack detection).', 'BOTCHA');

    // There should be no error message about wrong response.

    //$this->assertNoText(t(BOTCHA_NO_JS_ERROR_MESSAGE),

    //  'BOTCHA response should be accepted (JS enabled).',
    //  'BOTCHA');
  }

  /**
   * Assert that there is a BOTCHA on the form or not.
   * @param bool $presence whether there should be a BOTCHA or not.
   */
  protected function assertBotchaPresence($presence) {
    if ($presence) {
      $this
        ->assertText('If you\'re a human, don\'t change the following field', 'There should be a BOTCHA on the form.', 'BOTCHA');
    }
    else {
      $this
        ->assertNoText('If you\'re a human, don\'t change the following field', 'There should be no BOTCHA on the form.', 'BOTCHA');
    }
  }

  /**
   * Helper function to create a node with comments enabled.
   *
   * @return
   *   Created node object.
   */
  protected function createNodeWithCommentsEnabled($type = 'page') {
    $node_settings = array(
      'type' => $type,
      // @todo Abstract it.
      'comment' => COMMENT_NODE_READ_WRITE,
    );
    $node = $this
      ->drupalCreateNode($node_settings);
    return $node;
  }

  /**
   * Helper function to get form values array from comment form
   */
  protected function getCommentFormValuesFromForm() {

    // Submit the form using the displayed values.
    // @todo Abstract it.

    //$langcode = LANGUAGE_NONE;
    $displayed = array();
    foreach (array(
      'subject' => "//input[@id='edit-subject']/@value",
      // @todo Abstract it.
      'comment' => "//textarea[@id='edit-comment-body-{$langcode}-0-value']",
      //"comment_body[$langcode][0][value]" => "//textarea[@id='edit-comment-body-$langcode-0-value']",
      'botcha_response' => "//input[@id='edit-botcha-response']/@value",
    ) as $field => $path) {
      $value = current($this
        ->xpath($path));
      if (!empty($value)) {
        $displayed[$field] = (string) $value;
      }
    }
    return $displayed;
  }

  /**
   * Helper function to generate a default form values array for comment forms
   */

  // "= NULL" is for backward compatibility.
  protected function setCommentFormValues($should_pass = NULL) {

    // @todo Abstract it.

    //$langcode = LANGUAGE_NONE;
    $edit = array(
      'subject' => 'comment_subject ' . $this
        ->randomName(32),
      // @todo Abstract it.
      'comment' => 'comment_body ' . $this
        ->randomName(256),
    );
    return $edit;
  }

  /**
   * Helper function to generate a default form values array for node forms
   */

  // "= NULL" is for backward compatibility.
  protected function setNodeFormValues($should_pass = NULL) {

    // @todo Abstract it.
    $langcode = 'und';

    //$langcode = LANGUAGE_NONE;
    $edit = array(
      'title' => 'node_title ' . $this
        ->randomName(32),
      "body[{$langcode}][0][value]" => 'node_body ' . $this
        ->randomName(256),
    );
    return $edit;
  }

  /**
   * Get the form_build_id from the current form in the browser.
   */
  protected function getFormBuildIdFromForm($form = NULL) {

    // Form a xpath query string.
    $xpath = '//';
    if (!empty($form)) {

      // Specially to transform user_login to user-login.
      // @todo getFormBuildIdFromForm ?Is there a better way to do it?
      $form_filtered = str_replace('_', '-', $form);

      // If form parameter is set we are looking for forms like it. It is useful
      // when we have multiple forms on one page.
      $xpath .= "form[contains(@id, '{$form_filtered}')]/div/";
    }
    $xpath .= "input[@name='form_build_id']/@value";

    // Force conversion to string.

    //$form_build_id = (string) current($this->xpath("//input[@name='form_build_id']/@value"));
    $form_build_id = (string) current($this
      ->xpath($xpath));
    return $form_build_id;
  }

  /**
   * Helper function to allow comment posting for anonymous users.
   */
  protected function allowCommentPostingForAnonymousVisitors() {

    // Log in as admin.
    $this
      ->drupalLogin($this->admin_user);

    // Post user permissions form
    $edit = array(
      '1[access comments]' => TRUE,
      '1[post comments]' => TRUE,
      // @todo Abstract it.
      '1[post comments without approval]' => TRUE,
    );

    // @todo Abstract it.
    $this
      ->drupalPost('admin/user/permissions', $edit, 'Save permissions');

    //$this->drupalPost('admin/people/permissions', $edit, 'Save permissions');
    $this
      ->assertText('The changes have been saved.');

    // Log admin out
    $this
      ->drupalLogout();
  }

  //-----------------------------------

  /**
   * Get an array of our expectations to cycle through: should we test that this
   * form fails or successfully submitted or both?
   */
  public function getExpectations() {
    return array(
      TRUE,
    );
  }

  /**
   * Get the list of names of the buttons that are available for this concrete
   * form. Used as "modes" for behavior testing. Later we check that the real
   * behavior after clicking this button matches our suspections.
   */
  function getButtonsByForm($form) {
    $buttons = array();
    switch ($form) {
      case 'user_login':
        $buttons[] = t('Log in');
        break;
      case 'node':
      case 'comment':
      default:
        $buttons[] = t('Preview');
        $buttons[] = t('Save');
        break;
    }
    return $buttons;
  }

  /**
   * Helper function to generate a default form values array for any form.
   */
  protected function setFormValues($form, $should_pass = TRUE, &$parameters = array()) {
    $edit = array();
    switch ($form) {

      // These ones for testing FormUI.
      case 'addForm':
        $this
          ->debug("Entered %method %case", array(
          '%method' => __METHOD__,
          '%case' => $form,
        ));
        $edit['botcha_form_id'] = drupal_strtolower($this
          ->randomName(32));
        $parameters['botcha_form_id'] = $edit['botcha_form_id'];
        $edit["botcha_form_recipebook"] = $parameters['rbid'];
        break;
      case 'editForm':
        $this
          ->debug("Entered %method %case", array(
          '%method' => __METHOD__,
          '%case' => $form,
        ));

        // Fill in enabled.
        $edit['botcha_enabled'] = $parameters['botcha_enabled'];

        // Fill in recipe book.
        $edit["botcha_form_recipebook"] = $parameters['rbid'];
        break;
      case 'deleteForm':
        $this
          ->debug("Entered %method %case", array(
          '%method' => __METHOD__,
          '%case' => $form,
        ));

        // Nothing to do.
        break;

      // These ones for testing RecipebookUI.
      case 'addRecipebook':
        $this
          ->debug("Entered %method %case", array(
          '%method' => __METHOD__,
          '%case' => $form,
        ));
        $edit['id'] = drupal_strtolower($this
          ->randomName(32));
        $edit['title'] = $this
          ->randomName(32);
        $edit['description'] = $this
          ->randomName(255);
        $edit['recipes[timegate]'] = 'timegate';
        break;
      case 'editRecipebook':
        $this
          ->debug("Entered %method %case", array(
          '%method' => __METHOD__,
          '%case' => $form,
        ));
        $edit['title'] = $this
          ->randomName(32);
        $edit['description'] = $this
          ->randomName(255);
        $edit['recipes[timegate]'] = 'timegate';
        break;
      case 'deleteRecipebook':
        $this
          ->debug("Entered %method %case", array(
          '%method' => __METHOD__,
          '%case' => $form,
        ));

        // @todo BotchaBaseWebTestCase setFormValues Case deleteRecipebook real logic.
        break;

      // And these ones for testing form submission.
      case 'node':
        $this
          ->debug("Entered %method %case", array(
          '%method' => __METHOD__,
          '%case' => $form,
        ));
        $edit = $this
          ->setNodeFormValues($should_pass);
        break;
      case 'user_login':
        $this
          ->debug("Entered %method %case", array(
          '%method' => __METHOD__,
          '%case' => $form,
        ));
        $edit = $this
          ->setUserLoginFormValues($should_pass);
        break;
      case 'comment':
      default:
        $this
          ->debug("Entered %method %case", array(
          '%method' => __METHOD__,
          '%case' => $form,
        ));
        $edit = $this
          ->setCommentFormValues($should_pass);
        break;
    }
    return $edit;
  }

  /**
   * Helper function to generate a default form values array for comment forms
   */
  protected function setUserLoginFormValues($should_pass) {
    $edit = array(
      'name' => $this->normal_user->name,
      'pass' => $this->normal_user->pass_raw,
    );
    return $edit;
  }
  function checkPreConditions($form, $should_pass, $button) {
    switch ($form) {
      case 'comment':

        // Check that comment form is enabled.
        // @todo Abstract it.
        $this
          ->assertTrue(variable_get("botcha_enabled_comment_form", 0), "BOTCHA protection for comment_form must be enabled", 'BOTCHA');

        //$this->assertTrue(variable_get("botcha_enabled_comment_node_page_form", 0), "BOTCHA protection for comment_node_page_form must be enabled", 'BOTCHA');
        break;
    }
  }

  /**
   * Get one of predefined forms.
   * Used to unify the process of testing.
   */
  function getForm($form, &$parameters = array()) {
    $form_controller = $this->application
      ->getController(Botcha::CONTROLLER_TYPE_FORM);
    $recipe_controller = $this->application
      ->getController(Botcha::CONTROLLER_TYPE_RECIPE);
    $recipebook_controller = $this->application
      ->getController(Botcha::CONTROLLER_TYPE_RECIPEBOOK);

    // @todo Refactor all these switches with classes.
    switch ($form) {

      // These ones for testing FormUI.
      case 'addForm':
        $this
          ->debug("Entered %method %case", array(
          '%method' => __METHOD__,
          '%case' => $form,
        ));
        $this
          ->drupalGet(Botcha::ADMIN_PATH . '/form/add');
        foreach (array(
          'botcha_form_id',
          'botcha_enabled',
          'botcha_form_recipebook',
        ) as $field) {
          $this
            ->assertField($field, "There should be a {$field} field on the form", 'BOTCHA');
        }
        break;
      case 'editForm':
        $this
          ->debug("Entered %method %case", array(
          '%method' => __METHOD__,
          '%case' => $form,
        ));
        $form_id = drupal_strtolower($this
          ->randomName(12));

        // Pass this newly created form to other methods.
        $parameters['botcha_form_id'] = $form_id;

        // Random enabled state generation.
        // Converting to boolean is a workaround for drupalPost which interprets 0 as TRUE else.
        $enabled = (bool) rand(0, 1);
        $parameters['botcha_enabled'] = $enabled;

        // The form should be already binded to some (let's say default) recipe book.
        $rbid = 'default';
        $botcha_form = $form_controller
          ->getForm($form_id, TRUE)
          ->setEnabled($enabled)
          ->setRecipebook($rbid);
        $form_controller
          ->save($botcha_form);

        // Assert form existence.
        $this
          ->assertTrue(!$form_controller
          ->getForm($parameters['botcha_form_id'], FALSE) instanceof BotchaFormNone, "Form {$parameters['botcha_form_id']} exists", 'BOTCHA');

        // Assert recipe book of the form.
        $recipebook_id = $form_controller
          ->getForm($parameters['botcha_form_id'], FALSE)
          ->getRecipebook();
        $this
          ->assertEqual($rbid, $recipebook_id, "BOTCHA form has recipe book {$recipebook_id} (should have {$rbid})", 'BOTCHA');

        // Assert enabled or not.
        $this
          ->assertEqual($enabled, $botcha_form
          ->isEnabled(), 'BOTCHA form has correct state', 'BOTCHA');
        $this
          ->drupalGet(Botcha::ADMIN_PATH . "/form/{$form_id}");
        foreach (array(
          'botcha_form_id',
          'botcha_enabled',
          'botcha_form_recipebook',
        ) as $field) {
          $this
            ->assertField($field, "There should be a {$field} field on the form", 'BOTCHA');
        }

        // @todo Check that id field is disabled.
        break;
      case 'deleteForm':
        $this
          ->debug("Entered %method %case", array(
          '%method' => __METHOD__,
          '%case' => $form,
        ));
        $form_id = drupal_strtolower($this
          ->randomName(12));

        // Pass this newly created form to other methods.
        $parameters['botcha_form_id'] = $form_id;

        // The form should be already binded to some (let's say default) recipe book.
        $botcha_form = $form_controller
          ->getForm($form_id, TRUE)
          ->setRecipebook('default');
        $form_controller
          ->save($botcha_form);
        $this
          ->drupalGet(Botcha::ADMIN_PATH . "/form/{$form_id}/delete");
        break;

      // These ones for testing RecipebookUI.
      case 'addRecipebook':
        $this
          ->debug("Entered %method %case", array(
          '%method' => __METHOD__,
          '%case' => $form,
        ));
        $this
          ->drupalGet(Botcha::ADMIN_PATH . '/recipebook/add');

        // @todo Implement recipes checking.
        foreach (array(
          'id',
          'title',
          'description',
        ) as $field) {
          $this
            ->assertField($field, "There should be a {$field} field on the form", 'BOTCHA');
        }
        break;
      case 'editRecipebook':
        $this
          ->debug("Entered %method %case", array(
          '%method' => __METHOD__,
          '%case' => $form,
        ));
        $id = drupal_strtolower($this
          ->randomName(12));

        // Save this id to the parameters.
        $parameters['id'] = $id;
        $title = $this
          ->randomName(12);
        $description = $this
          ->randomString(255);

        // We need some recipes already set to test unsetting.
        $recipe_id = 'honeypot';
        $recipebook = $recipebook_controller
          ->getRecipebook($id, TRUE)
          ->setTitle($title)
          ->setDescription($description)
          ->setRecipe($recipe_id);
        $recipebook_controller
          ->save($recipebook);
        $this
          ->drupalGet(Botcha::ADMIN_PATH . "/recipebook/{$id}");

        // @todo Implement recipes appearance checking.
        foreach (array(
          'id',
          'title',
          'description',
        ) as $field) {
          $this
            ->assertField($field, "There should be a {$field} field on the form", 'BOTCHA');
        }
        break;
      case 'deleteRecipebook':
        $this
          ->debug("Entered %method %case", array(
          '%method' => __METHOD__,
          '%case' => $form,
        ));

        // @todo Case deleteRecipebook real logic.
        break;

      // And these ones are for testing form submissions.
      case 'node':
        $this
          ->debug("Entered %method %case", array(
          '%method' => __METHOD__,
          '%case' => $form,
        ));
        $this
          ->drupalGet('node/add/page');
        $this
          ->assertBotchaPresence(TRUE);
        break;
      case 'user_login':
        $this
          ->debug("Entered %method %case", array(
          '%method' => __METHOD__,
          '%case' => $form,
        ));
        $this
          ->drupalGet('user');
        $this
          ->assertBotchaPresence(TRUE);
        break;
      case 'comment':
      default:
        $this
          ->debug("Entered %method %case", array(
          '%method' => __METHOD__,
          '%case' => $form,
        ));

        // Create node to post comment to.
        $node = $this
          ->createNodeWithCommentsEnabled();
        $this
          ->drupalGet("comment/reply/{$node->nid}");
        $this
          ->assertBotchaPresence(TRUE);

        // Make sure comments on pages can be saved directly without preview.
        // @todo Abstract it.
        variable_set('comment_preview_page', COMMENT_PREVIEW_OPTIONAL);

        //variable_set('comment_preview_page', DRUPAL_OPTIONAL);
        break;
    }
  }

  /**
   * Post one of predefined forms.
   * Used to unify the process of testing.
   */
  function postForm($form, $edit, $button = NULL, &$parameters = array()) {
    switch ($form) {

      // These ones for testing Form UI.
      case 'addForm':
        $this
          ->debug("Entered %method %case", array(
          '%method' => __METHOD__,
          '%case' => $form,
        ));
        $button = $button ? $button : t('Add');
        $this
          ->drupalPost(NULL, $edit, $button);
        break;
      case 'editForm':
        $this
          ->debug("Entered %method %case", array(
          '%method' => __METHOD__,
          '%case' => $form,
        ));
        $button = $button ? $button : t('Save');
        $this
          ->drupalPost(NULL, $edit, $button);
        break;
      case 'deleteForm':
        $this
          ->debug("Entered %method %case", array(
          '%method' => __METHOD__,
          '%case' => $form,
        ));
        $button = $button ? $button : t('Delete');
        $this
          ->drupalPost(NULL, $edit, $button);
        break;

      // These ones for testing Recipebook UI.
      case 'addRecipebook':
        $this
          ->debug("Entered %method %case", array(
          '%method' => __METHOD__,
          '%case' => $form,
        ));
        $button = $button ? $button : t('Add');
        $this
          ->drupalPost(NULL, $edit, $button);
        break;
      case 'editRecipebook':
        $this
          ->debug("Entered %method %case", array(
          '%method' => __METHOD__,
          '%case' => $form,
        ));
        $button = $button ? $button : t('Save');
        $this
          ->drupalPost(NULL, $edit, $button);
        break;
      case 'deleteRecipebook':
        $this
          ->debug("Entered %method %case", array(
          '%method' => __METHOD__,
          '%case' => $form,
        ));

        // @todo Case deleteRecipebook.
        break;

      // And these ones are for testing form submissions.
      case 'node':
        $this
          ->debug("Entered %method %case", array(
          '%method' => __METHOD__,
          '%case' => $form,
        ));
        $button = $button ? $button : t('Save');
        $this
          ->drupalPost(NULL, $edit, $button);
        break;
      case 'user_login':
        $this
          ->debug("Entered %method %case", array(
          '%method' => __METHOD__,
          '%case' => $form,
        ));
        $button = $button ? $button : t('Log in');
        $this
          ->drupalPost(NULL, $edit, $button);
        break;
      case 'comment':
      default:
        $this
          ->debug("Entered %method %case", array(
          '%method' => __METHOD__,
          '%case' => $form,
        ));

        // Make sure comments on pages can be saved directly without preview.
        // @todo Abstract it.
        variable_set('comment_preview_page', COMMENT_PREVIEW_OPTIONAL);

        //variable_set('comment_preview_page', DRUPAL_OPTIONAL);
        $button = $button ? $button : t('Save');
        $this
          ->drupalPost(NULL, $edit, $button);
        break;
    }
  }

  /**
   * Check whether our suspections are real.
   */
  public function assertFormSubmission($form, $edit, $should_pass = TRUE, $button = NULL, &$parameters = array()) {
    $form_controller = $this->application
      ->getController(Botcha::CONTROLLER_TYPE_FORM);
    $recipe_controller = $this->application
      ->getController(Botcha::CONTROLLER_TYPE_RECIPE);
    $recipebook_controller = $this->application
      ->getController(Botcha::CONTROLLER_TYPE_RECIPEBOOK);

    // @todo Refactor all these switches with classes.
    switch ($form) {

      // These ones for testing Form UI.
      case 'addForm':
        $this
          ->debug("Entered %method %case", array(
          '%method' => __METHOD__,
          '%case' => $form,
        ));

        // Make sure that the message appeared.

        //$this->assertText(t('Added BOTCHA form %form_id.', array('%form_id' => $parameters['botcha_form_id'])), 'BOTCHA form successfully added : Message displayed', 'BOTCHA');
        $this
          ->assertText("Added BOTCHA form {$parameters['botcha_form_id']}.", 'BOTCHA form successfully added : Message displayed', 'BOTCHA');

        // Ensure that the form was created.
        $this
          ->assertTrue(!$form_controller
          ->getForm($parameters['botcha_form_id'], FALSE) instanceof BotchaFormNone, 'BOTCHA form successfully added : Form saved to DB', 'BOTCHA');

        // Assert recipe book of the form.
        $recipebook_id = $form_controller
          ->getForm($parameters['botcha_form_id'], FALSE)
          ->getRecipebook();
        $this
          ->assertEqual($parameters['rbid'], $recipebook_id, "BOTCHA form successfully added : Recipe book {$parameters['rbid']} saved correctly as {$recipebook_id}", 'BOTCHA');
        break;
      case 'editForm':
        $this
          ->debug("Entered %method %case", array(
          '%method' => __METHOD__,
          '%case' => $form,
        ));

        // Make sure that the message appeared.
        $this
          ->assertText("Saved BOTCHA form settings for {$parameters['botcha_form_id']}.", 'BOTCHA form successfully saved : Message displayed', 'BOTCHA');

        // @todo ?Why we need to call getForm with $create = TRUE? What's wrong?
        $botcha_form = $form_controller
          ->getForm($parameters['botcha_form_id'], TRUE);

        // Assert recipe book of the form.
        $recipebook_id = $botcha_form
          ->getRecipebook();

        // Ensure recipe book.
        $this
          ->assertEqual($parameters['rbid'], $recipebook_id, "BOTCHA form successfully saved : Recipe book {$parameters['rbid']} saved correctly as {$recipebook_id}", 'BOTCHA');

        // Ensure enabled.
        $this
          ->assertEqual($parameters['botcha_enabled'], $botcha_form
          ->isEnabled(), 'BOTCHA form was successfully turned on/off', 'BOTCHA');
        break;
      case 'deleteForm':
        $this
          ->debug("Entered %method %case", array(
          '%method' => __METHOD__,
          '%case' => $form,
        ));
        $form_id = $parameters['botcha_form_id'];

        // Make sure that the message appeared.
        $this
          ->assertText("Deleted BOTCHA protection for form {$form_id}.", 'BOTCHA form successfully deleted : Message displayed', 'BOTCHA');

        // Ensure that the form was deleted.
        $this
          ->assertTrue($form_controller
          ->getForm($form_id, FALSE) instanceof BotchaFormNone, 'BOTCHA form successfully deleted', 'BOTCHA');
        break;

      // These ones for testing Recipebook UI.
      case 'addRecipebook':
        $this
          ->debug("Entered %method %case", array(
          '%method' => __METHOD__,
          '%case' => $form,
        ));
        $this
          ->assertTrue($recipebook = $recipebook_controller
          ->getRecipebook($edit['id'], FALSE), "Recipe book {$edit['id']} should exist", 'BOTCHA');
        foreach (array(
          'id',
          'title',
          'description',
        ) as $field) {
          $this
            ->assertEqual($recipebook->{$field}, $edit[$field], "Recipe book {$edit['id']} should have {$field} equal {$edit[$field]} (in fact it has {$recipebook->{$field}})", 'BOTCHA');
        }
        break;
      case 'editRecipebook':
        $this
          ->debug("Entered %method %case", array(
          '%method' => __METHOD__,
          '%case' => $form,
        ));
        $recipebook = $recipebook_controller
          ->getRecipebook($parameters['id'], FALSE);
        foreach (array(
          'title',
          'description',
        ) as $field) {
          $this
            ->assertEqual($recipebook->{$field}, $edit[$field], "Recipe book {$parameters['id']} should have {$field} equal {$edit[$field]} (in fact it has {$recipebook->{$field}})", 'BOTCHA');
        }

        // @todo Add recipes assertion.
        break;
      case 'deleteRecipebook':
        $this
          ->debug("Entered %method %case", array(
          '%method' => __METHOD__,
          '%case' => $form,
        ));

        // @todo Case deleteRecipebook.
        break;

      // And these ones are for testing form submissions.
      case 'node':
        $this
          ->debug("Entered %method %case", array(
          '%method' => __METHOD__,
          '%case' => $form,
        ));
        $this
          ->assertNodeFormSubmission($edit, $should_pass, $button);
        break;
      case 'user_login':
        $this
          ->debug("Entered %method %case", array(
          '%method' => __METHOD__,
          '%case' => $form,
        ));
        $this
          ->assertUserLoginFormSubmission($edit, $should_pass, $button);
        break;
      case 'comment':
      default:
        $this
          ->debug("Entered %method %case", array(
          '%method' => __METHOD__,
          '%case' => $form,
        ));
        $this
          ->assertCommentFormSubmission($edit, $should_pass, $button);
        break;
    }
  }

  /**
   * Assert function for testing if comment posting works as it should.
   *
   * Creates node with comment writing enabled, tries to post comment
   * with given BOTCHA response (caller should enable the desired
   * challenge on page node comment forms) and checks if the result is as expected.
   *
   * @param $node existing node to post comments to (if NULL, will be created)
   * @param $should_pass boolean describing if the posting should pass or should be blocked
   * @param $message message to prefix to nested asserts
   * @param $button name of button to click (t('Save') by default)
   */
  protected function assertCommentFormSubmission($edit, $should_pass, $button) {

    // Assertion itself.
    switch ($should_pass) {
      case FALSE:

        // Check for error message.
        $this
          ->assertText(BOTCHA_WRONG_RESPONSE_ERROR_MESSAGE, 'Comment submission should be blocked.', 'BOTCHA');

        // Check that there is still BOTCHA after failed submit.
        $this
          ->assertBotchaPresence(TRUE);

        //$this->assertNoText($edit['subject'], 'Comment should not show up on node page.', 'BOTCHA');

        // !!? Do we need to check message body?

        //$this->assertNoText($comment_body, $message . ' Comment should not show up on node page.', 'BOTCHA');
        break;
      case TRUE:
      default:
        switch ($button) {
          case t('Preview'):

            // Check that there is still BOTCHA after preview.
            $this
              ->assertBotchaPresence(TRUE);
            break;
          case t('Save'):
          default:

            // There should be no error message.
            $this
              ->assertBotchaResponseAccepted();
            $this
              ->assertText($edit['subject'], 'Comment should show up on node page.', 'BOTCHA');

            // !!? Do we need to check message body?

            //$this->assertText($edit['comment_body'], $message . ' Comment should show up on node page.', 'BOTCHA');
            break;
        }
        break;
    }
  }

  /**
   * Assert submission of node form, check whether it works how it should.
   *
   * @param type $edit
   * @param type $should_pass
   */
  protected function assertNodeFormSubmission($edit, $should_pass, $button) {

    // @todo assertNodeFormSubmission real logic
  }

  /**
   * Assert submission of user login form, check whether it works how it should.
   *
   * @param type $edit
   * @param type $should_pass
   */
  protected function assertUserLoginFormSubmission($edit, $should_pass, $button) {
    switch ($should_pass) {
      case FALSE:

        // Check for error message.
        $this
          ->assertText(BOTCHA_WRONG_RESPONSE_ERROR_MESSAGE, 'BOTCHA should block user login form', 'BOTCHA');

        // And make sure that user is not logged in:
        // check for name and password fields on ?q=user.
        $this
          ->drupalGet('user');
        $this
          ->assertField('name', t('Username field found.'), 'BOTCHA');
        $this
          ->assertField('pass', t('Password field found.'), 'BOTCHA');
        break;
      case TRUE:
      default:

        // If log in was successful, log out to continue testing.
        $this
          ->drupalLogout();
        break;
    }
  }

  /**
   * Used to print debug message on the test result screen.
   * @param string $message_template
   * @param array $substitutions
   */
  protected function debug($message_template, $substitutions = array()) {
    return $this
      ->pass(t($message_template, $substitutions), 'BOTCHA');
  }

}

Members

Namesort descending Modifiers Type Description Overrides
BotchaBaseWebTestCase::$admin_user protected property User with various administrative permissions.
BotchaBaseWebTestCase::$application protected property
BotchaBaseWebTestCase::$normal_user protected property Normal visitor with limited permissions
BotchaBaseWebTestCase::allowCommentPostingForAnonymousVisitors protected function Helper function to allow comment posting for anonymous users.
BotchaBaseWebTestCase::assertBotchaPresence protected function Assert that there is a BOTCHA on the form or not. 3
BotchaBaseWebTestCase::assertBotchaResponseAccepted protected function Assert that the response is accepted: no "unknown CSID" message, no "CSID reuse attack detection" message, no "wrong answer" message.
BotchaBaseWebTestCase::assertCommentFormSubmission protected function Assert function for testing if comment posting works as it should.
BotchaBaseWebTestCase::assertFormSubmission public function Check whether our suspections are real. 2
BotchaBaseWebTestCase::assertNodeFormSubmission protected function Assert submission of node form, check whether it works how it should.
BotchaBaseWebTestCase::assertUserLoginFormSubmission protected function Assert submission of user login form, check whether it works how it should.
BotchaBaseWebTestCase::checkPreConditions function
BotchaBaseWebTestCase::createNodeWithCommentsEnabled protected function Helper function to create a node with comments enabled.
BotchaBaseWebTestCase::debug protected function Used to print debug message on the test result screen.
BotchaBaseWebTestCase::getButtonsByForm function Get the list of names of the buttons that are available for this concrete form. Used as "modes" for behavior testing. Later we check that the real behavior after clicking this button matches our suspections.
BotchaBaseWebTestCase::getCommentFormValuesFromForm protected function Helper function to get form values array from comment form
BotchaBaseWebTestCase::getExpectations public function Get an array of our expectations to cycle through: should we test that this form fails or successfully submitted or both? 5
BotchaBaseWebTestCase::getForm function Get one of predefined forms. Used to unify the process of testing.
BotchaBaseWebTestCase::getFormBuildIdFromForm protected function Get the form_build_id from the current form in the browser.
BotchaBaseWebTestCase::postForm function Post one of predefined forms. Used to unify the process of testing.
BotchaBaseWebTestCase::setCommentFormValues protected function
BotchaBaseWebTestCase::setFormValues protected function Helper function to generate a default form values array for any form. 5
BotchaBaseWebTestCase::setNodeFormValues protected function
BotchaBaseWebTestCase::setUp public function Generates a random database prefix, runs the install scripts on the prefixed database and enable the specified modules. After installation many caches are flushed and the internal browser is setup so that the page requests will run on the new prefix.… Overrides DrupalWebTestCase::setUp 2
BotchaBaseWebTestCase::setUserLoginFormValues protected function Helper function to generate a default form values array for comment forms
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::$originalPrefix protected property The original database prefix, before it was changed for testing purposes.
DrupalTestCase::$results public property Current results of this test case.
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::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.
DrupalTestCase::errorHandler public function Handle errors during test runs.
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::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 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::$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::$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.
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 does not exist in the current page by the given 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::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::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::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 Internal helper function; Create a role with specified permissions.
DrupalWebTestCase::drupalCreateUser protected function Create a user with a given set of permissions. The permissions correspond to the names given on the privileges page.
DrupalWebTestCase::drupalGet protected function Retrieves a Drupal path or an absolute path.
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::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::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::parse protected function Parse content returned from curlExec using DOM and SimpleXML.
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.
DrupalWebTestCase::resetAll protected function Reset all data structures after having enabled new modules.
DrupalWebTestCase::tearDown protected function Delete created files and temporary files directory, delete the tables created by setUp(), and reset the database prefix.
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