Is there a File-like object for unit tests?

Ali Çehreli acehreli at yahoo.com
Tue Jan 4 17:58:41 UTC 2022


On 1/4/22 9:48 AM, Paul Backus wrote:
 > On Tuesday, 4 January 2022 at 17:01:41 UTC, Amit wrote:

 >> 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?

I don't think it exists in the standard library. So, I had to write this 
for work manually. Instead of using File on the interfaces, I created a 
Storage interface that implemented everything I did with a File: open, 
close, writeln, seek, etc.

interface Storage {
   // ...
}

And I had two versions of it:

class FileStorage : Storage {
   // ...
}

class InMemoryStorage : Storage {
   ubyte[] buffer;
   // ...
}

Worked like a charm after fixing a number of bugs. (I wish it were open 
source.)

 > Probably the easiest way to do it is to have your parser take a generic
 > [range][1] as its argument instead of a `File`.

Makes sense but in my case File was everywhere so it felt better to 
abstract it away.

 > For example, here's a function that parses an integer from an input 
range:

In my case, it would have to be a RandomAccessRange because the file 
format had self-references through offsets.

Ali



More information about the Digitalmars-d-learn mailing list