gpt4 book ai didi

php - vfsstream 路径和真实路径

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:41:26 26 4
gpt4 key购买 nike

我正在尝试使用 vfsStream 对文件系统交互进行单元测试,但很快就遇到了一个主要障碍。被测代码执行的验证检查之一是在提供的输入路径上执行 realpath() 以测试它是实际路径而不是废话。但是,realpath 在 vfsstream 路径上总是失败。

以下代码演示了任何特定类之外的问题。

$content    = "It rubs the lotion on its skin or else it gets the hose again";
$url = vfsStream::url ('test/text.txt');
file_put_contents ($url, $content);
var_dump ($url);
var_dump (realpath ($url));
var_dump (file_get_contents ($url));

输出如下:

string(27) "vfs://FileClassMap/text.txt"
bool(false)
string(61) "It rubs the lotion on its skin or else it gets the hose again"

显然 vfsStream 创建了文件并将给定的内容写入其中,但我无法使用 realpath 验证它的路径是否正确。由于在实际代码中使用了 realpath,我需要一种解决此问题的方法。

我真的不认为删除 realpath 是一个明智的方法,因为它在代码中执行一个重要的功能,并且删除一个重要的检查只是为了使代码可测试似乎是一个非常糟糕的解决方案。我也可以在测试周围放置一个 if 以使其可以出于测试目的而禁用它,但我再次认为这也不是一个好主意。此外,我不希望在代码中可能调用 realpath () 的每个点都执行此操作。第三种选择是为文件系统单元测试设置一个 RAM 磁盘,但这也不理想。你必须自己清理(这是 vfsstream 应该帮助你避免需要的东西)并且实际如何做会因操作系统而异,因此单元测试将不再与操作系统无关。

那么有没有办法以实际与 realpath 一起使用的格式获取 vfsstream 路径?

为了完整起见,以下是我尝试实际测试的类的代码片段。

if (($fullPath = realpath ($unvalidatedPath))
&& (is_file ($fullPath))
&& (is_writable ($fullPath))) {

对以下内容的重构(根据潜在的解决方案 2)允许我使用 vfsStream 进行测试,但我认为这在生产中可能会出现问题:

// If we can get a canonical path then do so (realpath can fail on URLs, stream wrappers, etc)
$fullPath = realpath ($unvalidatedPath);
if (false === $fullPath) {
$fullPath = $unvalidatedPath;
}

if ((is_file ($fullPath))
&& (is_writable ($fullPath))) {

最佳答案

如果您使用命名空间,您只能在测试类中覆盖 realpath 函数。我总是在我的 vfsStream 测试用例中使用规范路径,因为我不想测试 realpath() 函数本身。

namespace my\namespace;

/**
* Override realpath() in current namespace for testing
*
* @param string $path the file path
*
* @return string
*/
function realpath($path)
{
return $path;
}

这里描述的很好:http://www.schmengler-se.de/en/2011/03/php-mocking-built-in-functions-like-time-in-unit-tests/

关于php - vfsstream 路径和真实路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22365519/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com