简体   繁体   中英

PHPUnit - testing function which uses realpath()

I have a function that checks if user supplied filename is under the /opt/ directory. It uses realpath so users can't pass in something like '../etc/passwd' for security reasons.

function check_file_path($relative_filename) {
    $abspath = realpath('/opt/' . $relative_filename);
    return ($abspath && strpos($abspath , '/opt/') === 0);
}

Now realpath will return false if the file doesn't exist on the fs. When PHPUnit is running (on dev machine, not on the server), the path does not exist thus we cannot do a positive test.

I've looked into vfsstream but it doesn't play nice with realpath()

org\bovigo\vfs\vfsStream::setup('home');
$file = org\bovigo\vfs\vfsStream::url('home/test.txt');
file_put_contents($file, "The new contents of the file");
$abspath = realpath('vfs://home/test.txt');
// $abspath will be false

Any suggestion to mock a filesystem so that realpath will work?

  1. You can use runkit . It's extension of php.

  2. But if your function calling inside any namespace you can define your own function in that namespace.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM