d单元测试不同文件类
原文
Paul Backus
:
最简单方法是让解析器带输入区间
模板参数,而不是File
,然后,传入各种(文件,内存缓冲,即时生成数据类
等)数据源.如下面的从输入区间
解析整.
import std.range;
int parseInteger(Input)(Input input)
if (isInputRange!Input && is(typeof(input.front - '0') : int))
{
import std.ascii: isDigit;
import std.exception: enforce;
int result = 0;
bool success = false;
while (!input.empty && input.front.isDigit)
{
success = true;
result *= 10;
result += input.front - '0';
input.popFront;
}
enforce(success, "输入不包含整");
return result;
}
unittest
{
import std.ascii: isDigit;
import std.algorithm: filter;
import std.exception: assertThrown;
// 可用串
assert(parseInteger("123") == 123);
assert(parseInteger("123 hello") == 123);
// 可用任意区间类型
assert(parseInteger("321".retro) == 123);
assert(parseInteger("a1b2c3".filter!isDigit) == 123);
// 失败示例.
assertThrown!Exception(parseInteger("hello"));
assertThrown!Exception(parseInteger(""));
}
ali:
interface Storage {//实现open, close, writeln, seek, 等接口.
// ...
}
//两个子类.
class FileStorage : Storage {
// ...
}
class InMemoryStorage : Storage {
ubyte[] buffer;
// ...
}
是随机访问区间
,因为内部有自引用偏移
.
H. S. Teoh
:
很容易,只需要让File
作为模板参数,并默认为std.file.File
,这样,单元测试
可用包含方法的类
来替换它.
auto myParser(File = std.stdio.File)(File input) {
... // 往常一样读输入
}
unittest {
struct FakeFile {//假文件
string contents = "...";
void[] rawRead(void[] buf) {
... // 模拟读文件
}
... // 加需要文件方法
}
FakeFile f;
auto output = myParser(f);//测试.
...
}
void main() {
auto input = File("...", "r");
auto output = myParser(input); //`File`默认为std.stdio.File
...
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现