The solution to "Error handling"...
H. S. Teoh
hsteoh at qfbox.info
Fri Jul 10 00:08:00 UTC 2026
On Thu, Jul 09, 2026 at 04:26:03PM -0700, Walter Bright via Digitalmars-d wrote:
> On 7/9/2026 12:32 AM, Robert Collins wrote:
> > Instead of only catching exceptions, we started testing common
> > failure scenarios such as invalid input, missing resources, API
> > timeouts, and permission issues. We also separated user-friendly
> > messages from detailed logs, so users received clear guidance while
> > developers still had enough information to troubleshoot the root
> > cause.
>
> One testing technique that works well is to have input objects,
> processing code, and output objects. One creates "mock" input objects,
> which can be used to generate specific bad input. Then write "mock"
> output objects that, instead of reporting the error, compare the error
> against what the expected error would be.
>
> You can see this in action in the lexer unittests in the dmd compiler.
Mock objects are awesome for unittests. I've taken advantage of D
templates to generate instantiations of functions that use mock objects
instead of real OS syscalls, in order to ensure the logic is sound. For
example:
auto myFunc(File = std.stdio.File)(File input, File output) {
...
}
unittest {
struct MockFile {
// insert stuff to inject errors & various
// conditions
}
MockFile mockInput = ...;
MockFile mockOutput = ...;
auto ret = myFunc(mockInput, mockOutput);
assert(ret == expectedReturn);
... // check of MockFile state is as expected
}
When compiling with -unittest, the mock version of myFunc is
instantiated and gets called by the unittest. When not compiling with
-unittest, only the non-mock version of myFunc is generated, so there's
no template bloat in the release build.
This technique can be used not just for files; with suitable template
parameters I've managed to write unittests for functions that manipulate
the filesystem -- by creating a mock filesystem (with minimal
functionality, just enough to run the desired tests).
T
--
May you live all the days of your life. -- Jonathan Swift
More information about the Digitalmars-d
mailing list