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
    ...
}
posted @   zjh6  阅读(10)  评论(0编辑  收藏  举报  
相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现
点击右上角即可分享
微信分享提示