Drupal testing patterns
Here is an effort at documenting Drupal testing patterns from what's currently used in core tests. The objective is to promote reusability of standardized patterns throughout core and contributed tests.
// Catch - this looks good, but I think we should completely ignore stuff like getContent() which is used once per year and just focus one what 70% of basic tests will use - the API docs etc. are there, and linkable at the end, for everything else.
Browser-related patterns
Fetch a page (GET)
<?php
// Fetch an URL in the internal browser (GET).
$this->drupalGet($url);
?>Known shortcomings:
- There is no documented way to tweak headers
Fetch a page (other methods)
drupalHead() is meant to fetch headers via the HEAD method.
<?php
// Fetch an URL in the internal browser (HEAD).
$this->drupalHead($url);
?>Known shortcomings:
- The sames as
drupalGet()above, - There is no generic way (yet) to get content via other HTTP methods.
Post a form
<?php
$edit = array('name' => $name, 'mail' => $mail);
$this->drupalPost('user/register', $edit, t('Create new account'));
?>Default values defined by the form will be used if not overriden in $edit.
Known shortcomings:
- There is no way to target a specific form on the page (by its
$form_id). - It is not possible to get default values of fields already defined on the page before posting the form.
Post a form: upload a file
From upload.test:
<?php
$edit = array(
'files[upload]' => $filename
);
$this->drupalPost('node/' . $nid . '/edit', $edit, t('Save'));
?>Known shortcomings:
- When you upload a file, it is impossible to have any other field starting with a '@' (cURL shortcoming).
Assert content on a page
<?php
// assertRaw checks for raw HTML in the page the internal browser last fetched.
$this->drupalGet('user/register');
$this->assertRaw('<a href="'. url('user/password') .'">', t('Make sure a link appears to "Request new password" on the user register page.'));
// assertText checks for plain text in the page the internal browser last fetched.
$this->drupalGet('user/register');
$this->assertText(t('Request new password'), t('Make sure the text "Request new password" appears on the user register page.'));
?>Follow a link
<?php
// TODO: find a real life example
$this->clickLink($label, $index = 0);
?>Get the content of the internal browser
<?php
// Get the response content.
$content = $this->getContent();
?>
