File-like option where the "file contents" comes from a string?
Paul Backus
snarwin at gmail.com
Thu Nov 28 19:38:48 UTC 2024
On Wednesday, 27 November 2024 at 01:12:23 UTC, Andy Valencia
wrote:
> Again and again for testing I run into how nice it would be to
> have an open "File" which has its contents set by the unit test
> code:
>
>> auto f = StringFile("my test data...", "r");
>
> I've searched high and low without discovering something which
> would fit the bill.
On Linux, you could use [`fmemopen`][1] to get a `FILE*` pointing
to an in-memory buffer, and [`File.wrapFile`][2] to convert that
into a D `File` object. Keep in mind if you do this that you will
have to manually `fclose` the `FILE*` when you're done with it.
Another possibility is to change your function so that it takes a
[range][3] as its input instead of a `File`. Then, you can pass a
`string` for testing, and something like
`File.byLine(Yes.keepTerminator).joiner` when you want to read
from an actual file. The downside of this approach is that you
will either have to make your function a template, or use
[std.range.interfaces][4] and wrap the inputs with
`inputRangeObject`.
[1]:
https://www.gnu.org/software/libc/manual/html_node/String-Streams.html#index-fmemopen
[2]: https://dlang.org/phobos/std_stdio.html#.File.wrapFile
[3]: https://dlang.org/phobos/std_range.html
[4]: https://dlang.org/phobos/std_range_interfaces.html
More information about the Digitalmars-d-learn
mailing list