class ContactPersonalTest

You are here

Tests the personal contact form.

Namespace

Drupal\contact\Tests

Hierarchy

Expanded class hierarchy of ContactPersonalTest

Members

Contains filters are case sensitive
Namesort descending Modifiers Type Description
ContactPersonalTest::$admin_user private property A user with some administrative permissions.
ContactPersonalTest::$contact_user private property A user without any permissions.
ContactPersonalTest::$modules public static property Modules to enable.
ContactPersonalTest::$web_user private property A user with 'access user contact forms' permission.
ContactPersonalTest::getInfo public static function Provides meta information about this test case, such as test name. Overrides TestBase::getInfo
ContactPersonalTest::setUp function Sets up a Drupal site for running functional and integration tests. Overrides WebTestBase::setUp
ContactPersonalTest::submitPersonalContact protected function Fills out a user's personal contact form and submits it.
ContactPersonalTest::testPersonalContactAccess function Tests access to the personal contact form.
ContactPersonalTest::testPersonalContactFlood function Tests the personal contact form flood protection.
ContactPersonalTest::testSendPersonalContactMessage function Tests that mails for contact messages are correctly sent.
TestBase::$assertions protected property Assertions thrown in that test case.
TestBase::$configImporter protected property The config importer that can used in a test.
TestBase::$container protected property The dependency injection container used in the test.
TestBase::$databasePrefix protected property The database prefix of this test run.
TestBase::$dieOnFail public property Whether to die in case any test assertion fails.
TestBase::$originalFileDirectory protected property The original file directory, before it was changed for testing purposes.
TestBase::$originalPrefix protected property The original database prefix when running inside Simpletest.
TestBase::$originalSettings protected property The settings array.
TestBase::$public_files_directory protected property The public file directory for the test environment.
TestBase::$randomGenerator protected property The random generator.
TestBase::$results public property Current results of this test case.
TestBase::$siteDirectory protected property The site directory of this test run.
TestBase::$skipClasses protected property This class is skipped when looking for the source of an assertion.
TestBase::$testId protected property The test run ID.
TestBase::$timeLimit protected property Time limit for the test.
TestBase::$verbose public property TRUE if verbose debugging is enabled.
TestBase::$verboseClassName protected property Safe class name for use in verbose output filenames.
TestBase::$verboseDirectory protected property Directory where verbose output files are put.
TestBase::$verboseDirectoryUrl protected property URL to the verbose output file directory.
TestBase::$verboseId protected property Incrementing identifier for verbose output filenames.
TestBase::assert protected function Internal helper: stores the assert.
TestBase::assertEqual protected function Check to see if two values are equal.
TestBase::assertFalse protected function Check to see if a value is false.
TestBase::assertIdentical protected function Check to see if two values are identical.
TestBase::assertIdenticalObject protected function Checks to see if two objects are identical.
TestBase::assertNoErrorsLogged protected function Asserts that no errors have been logged to the PHP error.log thus far.
TestBase::assertNotEqual protected function Check to see if two values are not equal.
TestBase::assertNotIdentical protected function Check to see if two values are not identical.
TestBase::assertNotNull protected function Check to see if a value is not NULL.
TestBase::assertNull protected function Check to see if a value is NULL.
TestBase::assertTrue protected function Check to see if a value is not false.
TestBase::beforePrepareEnvironment protected function Act on global state information before the environment is altered for a test.
TestBase::changeDatabasePrefix private function Changes the database connection to the prefixed one.
TestBase::checkRequirements protected function Checks the matching requirements for Test.
TestBase::configImporter public function Returns a ConfigImporter object to import test importing of configuration.
TestBase::copyConfig public function Copies configuration objects from source storage to target storage.
TestBase::deleteAssert public static function Delete an assertion record by message ID.
TestBase::error protected function Fire an error assertion.
TestBase::errorHandler public function Handle errors during test runs.
TestBase::exceptionHandler protected function Handle exceptions.
TestBase::fail protected function Fire an assertion that is always negative.
TestBase::filePreDeleteCallback public static function Ensures test files are deletable within file_unmanaged_delete_recursive().
TestBase::generatePermutations public static function Converts a list of possible parameters into a stack of permutations.
TestBase::getAssertionCall protected function Cycles through backtrace until the first non-assertion method is found.
TestBase::getDatabaseConnection public static function Returns the database connection to the site running Simpletest.
TestBase::getRandomGenerator protected function Gets the random generator for the utility methods.
TestBase::insertAssert public static function Store an assertion from outside the testing context.
TestBase::pass protected function Fire an assertion that is always positive.
TestBase::prepareDatabasePrefix private function Generates a database prefix for running tests.
TestBase::prepareEnvironment private function Prepares the current environment for running the test.
TestBase::randomName public function Generates a unique random string containing letters and numbers.
TestBase::randomObject public function Generates a random PHP object.
TestBase::randomString public function Generates a unique random string of ASCII characters of codes 32 to 126.
TestBase::randomStringValidate public function Callback for random string validation.
TestBase::restoreEnvironment private function Cleans up the test environment and restores the original environment.
TestBase::run public function Run all tests in this class.
TestBase::settingsSet protected function Changes in memory settings.
TestBase::verbose protected function Logs verbose message in a text file.
WebTestBase::$additionalCurlOptions protected property Additional cURL options.
WebTestBase::$configDirectories protected property The config directories used in this test.
WebTestBase::$content protected property The content of the page currently loaded in the internal browser.
WebTestBase::$cookieFile protected property The current cookie file used by cURL.
WebTestBase::$curlCookies protected property Cookies to set on curl requests.
WebTestBase::$curlHandle protected property The handle of the current cURL connection.
WebTestBase::$customTranslations protected property An array of custom translations suitable for drupal_rewrite_settings().
WebTestBase::$drupalSettings protected property The value of drupalSettings for the currently-loaded page.
WebTestBase::$dumpHeaders protected property Indicates that headers should be dumped if verbose output is enabled.
WebTestBase::$elements protected property The parsed version of the page.
WebTestBase::$generatedTestFiles protected property Whether the files were copied to the test files directory.
WebTestBase::$headers protected property The headers of the page currently loaded in the internal browser.
WebTestBase::$httpauth_credentials protected property HTTP authentication credentials (<username>:<password>).
WebTestBase::$httpauth_method protected property HTTP authentication method.
WebTestBase::$kernel protected property The kernel used in this test. Overrides TestBase::$kernel
WebTestBase::$loggedInUser protected property The current user logged in using the internal browser.
WebTestBase::$maximumRedirects protected property The maximum number of redirects to follow when handling responses.
WebTestBase::$originalShutdownCallbacks protected property The original shutdown handlers array, before it was cleaned for testing.
WebTestBase::$originalUser protected property The original user, before it was changed to a clean uid = 1 for testing.
WebTestBase::$plainTextContent protected property The plain-text content of the currently-loaded page.
WebTestBase::$profile protected property The profile to install as a basis for testing.
WebTestBase::$redirect_count protected property The number of redirects followed during the handling of a request.
WebTestBase::$session_id protected property The current session ID, if available.
WebTestBase::$session_name protected property The current session name, if available.
WebTestBase::$url protected property The URL currently loaded in the internal browser.
WebTestBase::addCustomTranslations protected function Queues custom translations to be written to settings.php.
WebTestBase::assertBlockAppears protected function Checks to see whether a block appears on the page.
WebTestBase::assertField protected function Asserts that a field exists with the given name or id.
WebTestBase::assertFieldById protected function Asserts that a field exists with the given id and value.
WebTestBase::assertFieldByName protected function Asserts that a field exists with the given name and value.
WebTestBase::assertFieldByXPath protected function Asserts that a field exists in the current page by the given XPath.
WebTestBase::assertFieldChecked protected function Asserts that a checkbox field in the current page is checked.
WebTestBase::assertLink protected function Passes if a link with the specified label is found.
WebTestBase::assertLinkByHref protected function Passes if a link containing a given href (part) is found.
WebTestBase::assertMail protected function Asserts that the most recently sent e-mail message has the given value.
WebTestBase::assertMailPattern protected function Asserts that the most recently sent e-mail message has the pattern in it.
WebTestBase::assertMailString protected function Asserts that the most recently sent e-mail message has the string in it.
WebTestBase::assertNoBlockAppears protected function Checks to see whether a block does not appears on the page.
WebTestBase::assertNoDuplicateIds protected function Asserts that each HTML ID is used for just a single element.
WebTestBase::assertNoField protected function Asserts that a field does not exist with the given name or id.
WebTestBase::assertNoFieldById protected function Asserts that a field does not exist with the given id and value.
WebTestBase::assertNoFieldByName protected function Asserts that a field does not exist with the given name and value.
WebTestBase::assertNoFieldByXPath protected function Asserts that a field does not exist in the current page by the given XPath.
WebTestBase::assertNoFieldChecked protected function Asserts that a checkbox field in the current page is not checked.
WebTestBase::assertNoLink protected function Passes if a link with the specified label is not found.
WebTestBase::assertNoLinkByHref protected function Passes if a link containing a given href (part) is not found.
WebTestBase::assertNoOption protected function Asserts that a select option in the current page does not exist.
WebTestBase::assertNoOptionSelected protected function Asserts that a select option in the current page is not checked.
WebTestBase::assertNoPattern protected function Triggers a pass if the perl regex pattern is not found in raw content.
WebTestBase::assertNoRaw protected function Passes if the raw text is NOT found on the loaded page, fail otherwise.
WebTestBase::assertNoResponse protected function Asserts the page did not return the specified response code.
WebTestBase::assertNoText protected function Passes if the text is NOT found on the text version of the page.
WebTestBase::assertNoTitle protected function Pass if the page title is not the given string.
WebTestBase::assertNoUniqueText protected function Passes if the text is found MORE THAN ONCE on the text version of the page.
WebTestBase::assertOption protected function Asserts that a select option in the current page exists.
WebTestBase::assertOptionSelected protected function Asserts that a select option in the current page is checked.
WebTestBase::assertPattern protected function Triggers a pass if the Perl regex pattern is found in the raw content.
WebTestBase::assertRaw protected function Passes if the raw text IS found on the loaded page, fail otherwise.
WebTestBase::assertResponse protected function Asserts the page responds with the specified response code.
WebTestBase::assertText protected function Passes if the text IS found on the text version of the page.
WebTestBase::assertTextHelper protected function Helper for assertText and assertNoText.
WebTestBase::assertThemeOutput protected function Asserts themed output.
WebTestBase::assertTitle protected function Pass if the page title is the given string.
WebTestBase::assertUniqueText protected function Passes if the text is found ONLY ONCE on the text version of the page.
WebTestBase::assertUniqueTextHelper protected function Helper for assertUniqueText and assertNoUniqueText.
WebTestBase::assertUrl protected function Passes if the internal browser's URL matches the given path.
WebTestBase::buildXPathQuery protected function Builds an XPath query.
WebTestBase::checkForMetaRefresh protected function Checks for meta refresh tag and if found call drupalGet() recursively.
WebTestBase::checkPermissions protected function Check to make sure that the array of permissions are valid.
WebTestBase::clickLink protected function Follows a link by name.
WebTestBase::constructFieldXpath protected function Helper: Constructs an XPath for the given set of attributes and value.
WebTestBase::cronRun protected function Runs cron in the Drupal installed by Simpletest.
WebTestBase::curlClose protected function Close the cURL handler and unset the handler.
WebTestBase::curlExec protected function Initializes and executes a cURL request.
WebTestBase::curlHeaderCallback protected function Reads headers and registers errors received from the tested site.
WebTestBase::curlInitialize protected function Initializes the cURL connection.
WebTestBase::drupalCompareFiles protected function Compare two files based on size and file name.
WebTestBase::drupalCreateContentType protected function Creates a custom content type based on default settings.
WebTestBase::drupalCreateNode protected function Creates a node based on default settings.
WebTestBase::drupalCreateRole protected function Creates a role with specified permissions.
WebTestBase::drupalCreateUser protected function Create a user with a given set of permissions.
WebTestBase::drupalGet protected function Retrieves a Drupal path or an absolute path.
WebTestBase::drupalGetAJAX protected function Requests a Drupal path in drupal_ajax format and JSON-decodes the response.
WebTestBase::drupalGetContent protected function Gets the current raw HTML of requested page.
WebTestBase::drupalGetHeader protected function Gets the value of an HTTP response header.
WebTestBase::drupalGetHeaders protected function Gets the HTTP response headers of the requested page.
WebTestBase::drupalGetJSON protected function Retrieves a Drupal path or an absolute path and JSON decode the result.
WebTestBase::drupalGetMails protected function Gets an array containing all e-mails sent during this test case.
WebTestBase::drupalGetNodeByTitle function Get a node from the database based on its title.
WebTestBase::drupalGetSettings protected function Gets the value of drupalSettings for the currently-loaded page.
WebTestBase::drupalGetTestFiles protected function Gets a list files that can be used in tests.
WebTestBase::drupalGetToken protected function Generate a token for the currently logged in user.
WebTestBase::drupalHead protected function Retrieves only the headers for a Drupal path or an absolute path.
WebTestBase::drupalLogin protected function Log in a user with the internal browser.
WebTestBase::drupalLogout protected function Logs a user out of the internal browser and confirms.
WebTestBase::drupalPlaceBlock protected function Creates a block instance based on default settings.
WebTestBase::drupalPost protected function Perform a POST HTTP request.
WebTestBase::drupalPostAjaxForm protected function Executes an Ajax form submission.
WebTestBase::drupalPostForm protected function Executes a form submission.
WebTestBase::drupalProcessAjaxResponse protected function Processes an AJAX response into current content.
WebTestBase::drupalSetContent protected function Sets the raw HTML content.
WebTestBase::drupalSetSettings protected function Sets the value of drupalSettings for the currently-loaded page.
WebTestBase::drupalUserIsLoggedIn protected function Returns whether a given user account is logged in.
WebTestBase::findBlockInstance protected function Find a block instance on the page.
WebTestBase::getAbsoluteUrl protected function Takes a path and returns an absolute path.
WebTestBase::getAjaxPageStatePostData protected function Get the Ajax page state from drupalSettings and prepare it for POSTing.
WebTestBase::getAllOptions protected function Get all option elements, including nested options, in a select.
WebTestBase::getSelectedItem protected function Get the selected value from a select field.
WebTestBase::getUrl protected function Get the current URL from the cURL handler.
WebTestBase::handleForm protected function Handles form input related to drupalPostForm().
WebTestBase::installParameters protected function Returns the parameters that will be used when Simpletest installs Drupal.
WebTestBase::isInChildSite protected function Returns whether the test is being executed from within a test site.
WebTestBase::parse protected function Parse content returned from curlExec using DOM and SimpleXML.
WebTestBase::prepareRequestForGenerator protected function Creates a mock request and sets it on the generator.
WebTestBase::rebuildContainer protected function Overrides \Drupal\simpletest\TestBase::rebuildContainer(). Overrides TestBase::rebuildContainer
WebTestBase::refreshVariables protected function Refreshes in-memory configuration and state information.
WebTestBase::resetAll protected function Resets all data structures after having enabled new modules.
WebTestBase::serializePostValues protected function Serialize POST HTTP request values.
WebTestBase::tearDown protected function Cleans up after testing. Overrides TestBase::tearDown
WebTestBase::translatePostValues protected function Transforms a nested array into a flat array suitable for WebTestBase::drupalPostForm().
WebTestBase::verboseEmail protected function Outputs to verbose the most recent $count emails sent.
WebTestBase::writeCustomTranslations protected function Writes custom translations to the test site's settings.php.
WebTestBase::writeSettings protected function Rewrites the settings.php file of the test site.
WebTestBase::xpath protected function Performs an xpath search on the contents of the internal browser.
WebTestBase::__construct function Constructor for \Drupal\simpletest\WebTestBase. Overrides TestBase::__construct

File

core/modules/contact/lib/Drupal/contact/Tests/ContactPersonalTest.php, line 16
Definition of Drupal\contact\Tests\ContactPersonalTest.

View source
class ContactPersonalTest extends WebTestBase {

  /**
   * Modules to enable.
   *
   * @var array
   */
  public static $modules = array('contact', 'dblog');

  /**
   * A user with some administrative permissions.
   *
   * @var object
   */
  private $admin_user;

  /**
   * A user with 'access user contact forms' permission.
   *
   * @var object
   */
  private $web_user;

  /**
   * A user without any permissions.
   *
   * @var object
   */
  private $contact_user;

  public static function getInfo() {
    return array(
      'name' => 'Personal contact form',
      'description' => 'Tests personal contact form functionality.',
      'group' => 'Contact',
    );
  }

  function setUp() {
    parent::setUp();

    // Create an admin user.
    $this->admin_user = $this->drupalCreateUser(array('administer contact forms', 'administer users', 'administer account settings', 'access site reports'));

    // Create some normal users with their contact forms enabled by default.
    \Drupal::config('contact.settings')->set('user_default_enabled', 1)->save();
    $this->web_user = $this->drupalCreateUser(array('access user contact forms'));
    $this->contact_user = $this->drupalCreateUser();
  }

  /**
   * Tests that mails for contact messages are correctly sent.
   */
  function testSendPersonalContactMessage() {
    $this->drupalLogin($this->web_user);

    $message = $this->submitPersonalContact($this->contact_user);
    $mails = $this->drupalGetMails();
    $this->assertEqual(1, count($mails));
    $mail = $mails[0];
    $this->assertEqual($mail['to'], $this->contact_user->getEmail());
    $this->assertEqual($mail['from'], \Drupal::config('system.site')->get('mail'));
    $this->assertEqual($mail['reply-to'], $this->web_user->getEmail());
    $this->assertEqual($mail['key'], 'user_mail');
    $variables = array(
      '!site-name' => \Drupal::config('system.site')->get('name'),
      '!subject' => $message['subject'],
      '!recipient-name' => $this->contact_user->getUsername(),
    );
    $this->assertEqual($mail['subject'], t('[!site-name] !subject', $variables), 'Subject is in sent message.');
    $this->assertTrue(strpos($mail['body'], t('Hello !recipient-name,', $variables)) !== FALSE, 'Recipient name is in sent message.');
    $this->assertTrue(strpos($mail['body'], $this->web_user->getUsername()) !== FALSE, 'Sender name is in sent message.');
    $this->assertTrue(strpos($mail['body'], $message['message']) !== FALSE, 'Message body is in sent message.');

    // Check there was no problems raised during sending.
    $this->drupalLogout();
    $this->drupalLogin($this->admin_user);
    // Verify that the correct watchdog message has been logged.
    $this->drupalGet('/admin/reports/dblog');
    $placeholders = array(
      '@sender_name' => $this->web_user->username,
      '@sender_email' => $this->web_user->getEmail(),
      '@recipient_name' => $this->contact_user->getUsername(),
    );
    $this->assertText(String::format('@sender_name (@sender_email) sent @recipient_name an e-mail.', $placeholders));
  }

  /**
   * Tests access to the personal contact form.
   */
  function testPersonalContactAccess() {
    // Test allowed access to admin user's contact form.
    $this->drupalLogin($this->web_user);
    $this->drupalGet('user/' . $this->admin_user->id() . '/contact');
    $this->assertResponse(200);
    // Check the page title is properly displayed.
    $this->assertRaw(t('Contact @username', array('@username' => $this->admin_user->getUsername())));

    // Test denied access to admin user's own contact form.
    $this->drupalLogout();
    $this->drupalLogin($this->admin_user);
    $this->drupalGet('user/' . $this->admin_user->id() . '/contact');
    $this->assertResponse(403);

    // Test allowed access to user with contact form enabled.
    $this->drupalLogin($this->web_user);
    $this->drupalGet('user/' . $this->contact_user->id() . '/contact');
    $this->assertResponse(200);

    // Test denied access to the user's own contact form.
    $this->drupalGet('user/' . $this->web_user->id() . '/contact');
    $this->assertResponse(403);

    // Test always denied access to the anonymous user contact form.
    $this->drupalGet('user/0/contact');
    $this->assertResponse(403);

    // Test that anonymous users can access the contact form.
    $this->drupalLogout();
    user_role_grant_permissions(DRUPAL_ANONYMOUS_RID, array('access user contact forms'));
    $this->drupalGet('user/' . $this->contact_user->id() . '/contact');
    $this->assertResponse(200);

    // Test that anonymous users can access admin user's contact form.
    $this->drupalGet('user/' . $this->admin_user->id() . '/contact');
    $this->assertResponse(200);

    // Revoke the personal contact permission for the anonymous user.
    user_role_revoke_permissions(DRUPAL_ANONYMOUS_RID, array('access user contact forms'));
    $this->drupalGet('user/' . $this->contact_user->id() . '/contact');
    $this->assertResponse(403);
    $this->drupalGet('user/' . $this->admin_user->id() . '/contact');
    $this->assertResponse(403);

    // Disable the personal contact form.
    $this->drupalLogin($this->admin_user);
    $edit = array('contact_default_status' => FALSE);
    $this->drupalPostForm('admin/config/people/accounts', $edit, t('Save configuration'));
    $this->assertText(t('The configuration options have been saved.'), 'Setting successfully saved.');
    $this->drupalLogout();

    // Re-create our contacted user with personal contact forms disabled by
    // default.
    $this->contact_user = $this->drupalCreateUser();

    // Test denied access to a user with contact form disabled.
    $this->drupalLogin($this->web_user);
    $this->drupalGet('user/' . $this->contact_user->id() . '/contact');
    $this->assertResponse(403);

    // Test allowed access for admin user to a user with contact form disabled.
    $this->drupalLogin($this->admin_user);
    $this->drupalGet('user/' . $this->contact_user->id() . '/contact');
    $this->assertResponse(200);

    // Re-create our contacted user as a blocked user.
    $this->contact_user = $this->drupalCreateUser();
    $this->contact_user->block();
    $this->contact_user->save();

    // Test that blocked users can still be contacted by admin.
    $this->drupalGet('user/' . $this->contact_user->id() . '/contact');
    $this->assertResponse(200);

    // Test that blocked users cannot be contacted by non-admins.
    $this->drupalLogin($this->web_user);
    $this->drupalGet('user/' . $this->contact_user->id() . '/contact');
    $this->assertResponse(403);

    // Test enabling and disabling the contact page through the user profile
    // form.
    $this->drupalGet('user/' . $this->web_user->id() . '/edit');
    $this->assertNoFieldChecked('edit-contact--2');
    $this->assertFalse(\Drupal::service('user.data')->get('contact', $this->web_user->id(), 'enabled'), 'Personal contact form disabled');
    $this->drupalPostForm(NULL, array('contact' => TRUE), t('Save'));
    $this->assertFieldChecked('edit-contact--2');
    $this->assertTrue(\Drupal::service('user.data')->get('contact', $this->web_user->id(), 'enabled'), 'Personal contact form enabled');
  }

  /**
   * Tests the personal contact form flood protection.
   */
  function testPersonalContactFlood() {
    $flood_limit = 3;
    \Drupal::config('contact.settings')->set('flood.limit', $flood_limit)->save();

    // Clear flood table in preparation for flood test and allow other checks to complete.
    db_delete('flood')->execute();
    $num_records_flood = db_query("SELECT COUNT(*) FROM {flood}")->fetchField();
    $this->assertIdentical($num_records_flood, '0', 'Flood table emptied.');

    $this->drupalLogin($this->web_user);

    // Submit contact form with correct values and check flood interval.
    for ($i = 0; $i < $flood_limit; $i++) {
      $this->submitPersonalContact($this->contact_user);
      $this->assertText(t('Your message has been sent.'), 'Message sent.');
    }

    // Submit contact form one over limit.
    $this->drupalGet('user/' . $this->contact_user->id() . '/contact');
    $this->assertRaw(t('You cannot send more than %number messages in @interval. Try again later.', array('%number' => $flood_limit, '@interval' => format_interval(\Drupal::config('contact.settings')->get('flood.interval')))), 'Normal user denied access to flooded contact form.');

    // Test that the admin user can still access the contact form even though
    // the flood limit was reached.
    $this->drupalLogin($this->admin_user);
    $this->assertNoText('Try again later.', 'Admin user not denied access to flooded contact form.');
  }

  /**
   * Fills out a user's personal contact form and submits it.
   *
   * @param $account
   *   A user object of the user being contacted.
   * @param $message
   *   (optional) An array with the form fields being used. Defaults to an empty
   *   array.
   */
  protected function submitPersonalContact($account, array $message = array()) {
    $message += array(
      'subject' => $this->randomName(16),
      'message' => $this->randomName(64),
    );
    $this->drupalPostForm('user/' . $account->id() . '/contact', $message, t('Send message'));
    return $message;
  }
}