We're long overdue for a "D is awesome" post
Steven Schveighoffer
schveiguy at gmail.com
Wed May 31 00:47:27 UTC 2023
On 5/30/23 5:42 PM, H. S. Teoh wrote:
> So here's one.
>
> Today, I was writing some code that iterates over a data structure and
> writes output to bunch of different files. It looks something like this:
>
> void genSplitHtml(Data data, ...) {
> auto outputTemplate = File("template.html", "r");
> foreach (...) {
> auto filename = generateFilename(...);
> auto sink = File(filename, "w").lockingTextWriter;
> ...
> while (line; outputTemplate.byLine) {
> if (line.canFind("MAGIC_TOKEN")) {
> generateOutput(...);
> } else {
> sink.put(line);
> }
> }
> }
> }
>
> Since the whole point of this function was to write output to different
> files (with automatically determined names), I wanted to write a
> unittest that tests whether it creates the correct files with the
> correct contents. But I didn't want unittests to touch the actual
> filesystem either -- didn't want to have to clean up the mess during
> development where the code might sometimes break and leave detritus
> behind in a temporary directory, or interact badly with other unittests
> running in parallel, etc..
All of iopipe is 100% unittestable, because all strings are treated as
input pipes.
Roughly speaking, if this were iopipe, I would do it like:
```d
// returns an iopipe with the translated data
auto genSplitHtml(Input)(Input inputPipe, Data data, ...)
{
...
}
// and then you can call it like:
File("template.html", "r").genSplitHtml(data).writeTo(File(filename,
"w")).process();
// in unittest
auto result = "contents of template".genSplitHtml(data);
result.process(); // oof, would be nice if I could do this in one line
assert(result.window == expectedData);
```
I need to work on it more, that `writeTo` function is not there yet
(https://github.com/schveiguy/iopipe/issues/39) and the file opening
stuff isn't as solid as I'd like.
> D not only r0x0rs, D boulders!!
Indeed it does!
-Steve
More information about the Digitalmars-d
mailing list