Writing simpletests for imagecache_create_url and file_create_url today, I had to change a few of Drupal's persistent variables, namely clean_url and file_downloads. I was kind of frustrated by the need to save the old values, set the values I needed for the test case, run the test, then restore the old variables.
The process itself is a little dangerous in the case you hit runtime fatal errors and the variables never get restored.. Also during the course of the testing all other requests to the same drupal site are affected by this variable change, so there are potential concurrency errors as well.
I was thinking.. wouldn't it be awesome if I could set variables for just the current request... aka just set $conf['variable_name']...
since there have been movements to eliminate globals and I'm just generally scared of them... and I want non-persistant variable_set I though changing variable_set by adding a persistent argument would make testing a little easier and maybe enable some kinds of strange hacker for others...
<?php
function variable_set($name, $value, $persistent = true) {
global $conf;
if ($persistent) {
$serialized_value = serialize($value);
db_query("UPDATE {variable} SET value = '%s' WHERE name = '%s'", $serialized_value, $name);
if (!db_affected_rows()) {
@db_query("INSERT INTO {variable} (name, value) VALUES ('%s', '%s')", $name, $serialized_value);
}
cache_clear_all('variables', 'cache');
}
$conf[$name] = $value;
}
?>
Just an idea since testing seems to be in the air... maybe the problem is already solved elsewhere...
Comments
yep, already there
I believe DrupalTestCase (or some related simpletest class) already provides a non-persistent variable_set(), plus a few other non-persistent setters that are reset when the test is done.
Don't know the name by heart, but I remember webchick's simpletest tutorial to have covered that functionality.
Not a problem in 7.x SimpleTest -> possible backport
The latest version of SimpleTest that was committed to the Drupal core creates a temporary database before each test function and clears it after the test. This alleviates the issue you are having.
I assume you are writing in the 5.x framework. I am not familiar with the installer and if it would be easy to backport this functionality. There are several issues related to back-porting the large number of changes in the 7.x version and I plan to work on them soon so this will definitely be something I will look into.
http://drupal.org/node/241156
http://drupal.org/node/254507
The non-persistent
The non-persistent variable_set works, but it will obviously not revert if the test crashes. That creates problems when writing tests since they inevitably crash while in development. As a temporary solution it works, but I hope to back-port much of the improvements made to 7.x.