On 5/28/2013 9:47 PM, Russel Winder wrote:
Looks like I am out of luck then. :-(

Not at all.

The context is writing a small program that can be a filter or operate
on files: actually it is the wc program. So it needs to work with opened
files and stdin. That is fine (sort of). The issue comes when writing
unit tests for the code: unit tests should not touch the file system, so
I need a memory buffer backed std.stdio.File for the tests. A mock file
in a sense.As noted earlier Go, Python, all JVM languages have such
things, and it really needs to be part of D. If there really is nothing
like this, I should add a JIRA issue and see if I can create a pull
request later in the summer.

Coincidentally, I wrote a wc program a year ago:
-------------------------
import std.stdio, std.file, std.string, std.array, std.algorithm, std.typecons;
import lazysplit;

alias Tuple!(int, "lines", int, "words", int, "chars") Lwc;

void main(string[] args) {
    writeln("   lines   words   bytes file");

    auto total = args[1 .. args.length].wctotal();

    if (args.length > 2)
        writefln("--------------------------------------\n%8s%8s%8s total",
            total[0..3]);
}

auto wctotal(R)(R args) {
    Lwc total;
    foreach (arg; args) {
        auto t = arg.File().byLine(KeepTerminator.yes).wc();

        writefln("%8s%8s%8s %s", t[0..3], arg);

        foreach(i, v; t)
            total[i] += v;
    }
    return total;
}

auto wc(R)(R r) {
    Lwc t;
    foreach (line; r) {
        t.lines += 1;
        t.words += line.lazySplit().count();
        t.chars += line.length;
    }
    return t;
}
--------------------------------------

Just replace "arg.File().byLine(KeepTerminator.yes)" with a string filled with your mocked data.

Reply via email to