On Tue, Jan 04, 2022 at 05:01:41PM +0000, Amit via Digitalmars-d-learn wrote: > Hi! > > I wrote a text parser that takes a File argument and parses that > file's contents. Now I would like to write a unit-test for that > parser. I need a File (or a general IO interface) that reads from an > in-memory buffer, similar to python's `StringIO` or go's > `strings.Reader`. > > How can I achieve that? > > Example of what I have in mind: > > ```d > unittest { > string fakeContents = "foo\nbar\nbaz"; > File f = createFileFromString(fakeContents); > assert(myParse(f) == MyParsedObject(...)); > } > ```
It's very easy, just have your text parser take File as a template argument, defaulted to std.file.File, that your unittest(s) can override with a custom type containing the needed methods. For example: auto myParser(File = std.stdio.File)(File input) { ... // read input as usual } unittest { struct FakeFile { string contents = "..."; void[] rawRead(void[] buf) { ... // simulate a file read here } ... // add whatever other File methods you might need here } FakeFile f; auto output = myParser(f); ... } void main() { auto input = File("...", "r"); auto output = myParser(input); // `File` defaults to std.stdio.File ... } T -- "A man's wife has more power over him than the state has." -- Ralph Emerson