Module Development

Uploading Files and Submitting AJAX Forms with SimpleTest for Drupal 7

Check your version

This tutorial covers a topic in Drupal 7 which may or may not be the version you're using. We're keeping this tutorial online as a courtesy to users of Drupal 7, but we consider it archived.

Alternate resources

Sprout Video

One element of interacting with a web application that we haven't looked at yet is uploading files. How does the DrupalWebTestCase browser attach a file to the the image field when filling out an article form? In this lesson we'll look at the helpers that DrupalWebTestCase has for handling file interactions including how to use the sample files provided in core, attaching files to a file upload input element, and submitting a form with files attached. In order to demonstrate this we'll be writing a test that creates a new article node with an image attached by filling out the article node creation form and submitting it.

You can get a list of the dummy/test files that come with SimpleTest using the DrupalWebTestCase::drupalGetTestFiles() method. Whenever possible I recommend making use of the provided files.


$files = $this->drupalGetTestFiles('image');
$this->verbose(print_r($files, TRUE));

You'll need to tell SimpleTest what type of files you're interested in, and it'll then return an array of the available files of that type. Valid types are: 'binary', 'html', 'image', 'javascript', 'php', 'sql', 'text'. Check out the DrupalWebTestCase::drupalGetTestFiles documentation for more information.

Once you've got the list of files you can attach files to a form element using DrupalWebTestCase::drupalPost() by specifying the full path to the file as the value for the file or image field in the $data array.


$images = $this->drupalGetTestFiles('image');
$image_realpath = drupal_realpath($images[0]->uri);

$edit = array(
  'title' => 'Test Article With Image',
  'files[field_image_und_0]' => $image_realpath,
);

If SimpleTest doesn't contain a suitable file you can use your own by including the file with your module, and then using the full path to that file in your tests.


$custom_file = drupal_get_path('module', 'helloworld') . '/tests/test.csv';
$realpath = drupal_realpath($custom_file);

This lesson also covers the use of DrupalWebTestCase::drupalPostAJAX(), which allows for the simulation of an AJAX request using the SimpleTest browser. The primary difference between it and the drupalPost method is you need to specify the name of the element that triggers the AJAX request.


$this->drupalPostAJAX('node/add/article', $edit, 'field_image_und_0_upload_button');

Documentation about SimpleTest file uploads

DrupalWebTestCase::drupalGetTestFiles()