As I mentioned in my previous question I'm attempting to write tests for a patch that will, ideally, trigger the creation of a redirect if the URI of a file changes.

My patch uses hook_file_update() which is called whenever file_save() runs.

Currently this chunk of code:

  // Move file to new URI
  $new_uri = 'public://qwerty.png';
  $test_file->uri = $new_uri;

This calls my hook and creates the redirect, but the redirect fails because drupalGet($new_url) returns a 404.

file_save() returns the error, filesize() [function.filesize]: stat failed for public://qwerty.png.

I've tried file_save() on URIs that linked to existing files, which gives an error, I've tried it on not-yet-extant URIs (as above), which gives an error, and I've tried file_move(), which doesn't call hook_file_update().

How can I programmatically change the URI of a file and trigger hook_file_update() inside a test?

  • It's probably just a typo in the question but are you calling drupalGet($new_url) or drupalGet($new_uri) (with an i)? – Clive Jan 23 '13 at 17:47
  • I've tried both. But I know from stepping through with xdebug that the node_save() is failing so neither will ever work. Any by "both" I mean $test_file->uri and the output of file_create_url($test_file->uri) – beth Jan 23 '13 at 17:48
  • 1
    Have you tried invoking the same code outside of the test environment? i.e. with a file that you know definitely exists and can't return a 404? It would help to work out if the problem is within the test environment or the patch logic – Clive Jan 23 '13 at 18:34
  • 1
    BTW this is really interesting, if you're able to upload the full module somewhere I'd be happy to have a play around and see if I can work it out. Can't promise anything but you never know I might get lucky :) – Clive Jan 23 '13 at 18:35
  • I haven't tried it outside of a test (yet) but I have tried it with a file I know exists and doesn't return (on its own) a 404. That creates separate issues with file_save() because it doesn't want to use an already-in-use uri. The earlier question linked in the OP contains the entirety of my modifications to the redirect.module and redirect.test files (one custom function on each), if you want to cut, paste, and try it out. – beth Jan 23 '13 at 18:48

The way I ended up getting around this was:

  1. Upload my file as an unmanaged file at the new URI
  2. $test_file->uri = $new_uri;
  3. file_save($test_file);
  4. file_unmanaged_delete($old_uri);

It didn't like it when I used a URI that was not yet in existence, nor one that was already in use by a managed file, but using one that goes to an unmanaged file seemed to work fine.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.