PHP Logo

The other day I ran into an interesting problem. In one of our integration tests we did the following:

$this->assertFalse(is_file($fullPath));

$item->runProcessThatCreatesFileInADifferentProcess();

$this->assertTrue(is_file($fullPath));

The assertTrue() check always failed and everything we did showed that the file existed. In order to get around this we had to use PHP’s clearstatcache() function before the assertTrue() call.

The reason for this can be seen in this section from https://www.php.net/manual/en/function.clearstatcache.php

When you use stat(), lstat(), or any of the other functions listed in the affected functions list (below), PHP caches the information those functions return in order to provide faster performance. However, in certain cases, you may want to clear the cached information. For instance, if the same file is being checked multiple times within a single script, and that file is in danger of being removed or changed during that script’s operation, you may elect to clear the status cache. In these cases, you can use the clearstatcache() function to clear the information that PHP caches about a file.

PHP was caching the result of is_file() and causing the assert to fail. To fix the tests we had to add the following call to clearstatcache().

$this->assertFalse(is_file($fullPath));

$item->runProcessThatCreatesFileInADifferentProcess();

clearstatcache(false, $fullPath);
$this->assertTrue(is_file($fullPath));