I am working on updating unit tests for my core library, and came across a scenario regarding filelocks (flock), and wanted to see how others implemented these types of unit tests.
Basically I have a utlity File class which will write contents to a file:
class CoreLib_Api_File_Package
{
public static function write(array $options)
{
...
if (!$file->flock(LOCK_EX)) {
throw new CoreLib_Api_Exception('Unable to obtain lock on file');
}
...
}
}
And my unit test looks like:
public function testWriteException_UnableToSecureLock()
{
$this->touchFile($this->destFileUri);
$file = new SplFileObject($this->destFileUri, CoreLib_Api_File::MODE_WRITE);
$file->flock(LOCK_EX);
CoreLib_Api_File_Package::write(array('fileUri' => $this->destFileUri, 'content' => $this->testContent, 'mode' => CoreLib_Api_File::MODE_WRITE));
}
As you can see from the test code I am putting an explicit lock on $this->destFileUri
before I make the API call to the write()
method. What I would expect is that the exception throw new CoreLib_Api_Exception('Unable to obtain lock on file');
to be thrown. Instead, my unit test just hangs indefinitely.
What would be the proper way to test whether a file has a lock?
Thanks in advance.