MDL-48639 behat upload: support absolute paths & better errors
authorTim Hunt <T.J.Hunt@open.ac.uk>
Wed, 17 Dec 2014 16:26:49 +0000 (16:26 +0000)
committerTim Hunt <T.J.Hunt@open.ac.uk>
Fri, 19 Dec 2014 11:58:59 +0000 (11:58 +0000)
In a custom step I needed to be able to upload a file I had previously
saved to $CFG->dataroot/temp, but that was not possible.

Also, the failure was not at all obvious. I have made it throw a clear
exception if the file you are trying to upload does not exist.

repository/upload/tests/behat/behat_repository_upload.php

index d5197fd..366e529 100644 (file)
@@ -98,7 +98,7 @@ class behat_repository_upload extends behat_files {
      * Uploads a file to filemanager
      *
      * @throws ExpectationException Thrown by behat_base::find
-     * @param string $filepath
+     * @param string $filepath Normally a path relative to $CFG->dirroot, but can be an absolute path too.
      * @param string $filemanagerelement
      * @param TableNode $data Data to fill in upload form
      * @param false|string $overwriteaction false if we don't expect that file with the same name already exists,
@@ -130,13 +130,18 @@ class behat_repository_upload extends behat_files {
 
         // Attaching specified file to the node.
         // Replace 'admin/' if it is in start of path with $CFG->admin .
-        $pos = strpos($filepath, 'admin/');
-        if ($pos === 0) {
-            $filepath = $CFG->admin . DIRECTORY_SEPARATOR . substr($filepath, 6);
+        if (substr($filepath, 0, 6) === 'admin/') {
+            $filepath = $CFG->dirroot . DIRECTORY_SEPARATOR . $CFG->admin .
+                    DIRECTORY_SEPARATOR . substr($filepath, 6);
         }
         $filepath = str_replace('/', DIRECTORY_SEPARATOR, $filepath);
-        $fileabsolutepath = $CFG->dirroot . DIRECTORY_SEPARATOR . $filepath;
-        $file->attachFile($fileabsolutepath);
+        if (!is_readable($filepath)) {
+            $filepath = $CFG->dirroot . DIRECTORY_SEPARATOR . $filepath;
+            if (!is_readable($filepath)) {
+                throw new ExpectationException('The file to be uploaded does not exist.', $this->getSession());
+            }
+        }
+        $file->attachFile($filepath);
 
         // Fill the form in Upload window.
         $datahash = $data->getRowsHash();