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));
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->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');