How to config std.testing.FailingAllocator?

I do not actually need help here. Just posting this into Help for those who may need this later since I cannot find any posts on this.

std.testing.FailingAllocator is a bit weird to use so here is an example from what I devised after 2 hours of reading documentation and an old blog on it. here is a general template you can follow to use it:

const std = @import("std");
test "failing allocation test" {
    var failing_allocator = std.testing.FailingAllocator.init(std.testing.allocator, .{.fail_index = x}); 
//x = any number of allocations you want to pass before the failure
//useful to test a failure part way through execution
    const allocator = failing_allocator.allocator();
//calling allocator method to pass to functions
    const function_call_value = failing_function(allocator, random_arguement);
    try std.testing.expect(failing_return_value_of_function);
}

A more real example from my own code :

test "allocator failure test" {
    var entries:usize = 0;
    var fasta:?[]parse.Fasta = undefined;
    var failing_allocator = std.testing.FailingAllocator.init(std.testing.allocator, .{.fail_index = 4});
    const allocator = failing_allocator.allocator();
    fasta = parse.read_fasta(allocator, &entries);
//below is only needed if the failing_index value is greater than the needed number of allocations
    defer { 
        if (fasta) |valid_value| {
            parse.deinit(valid_value, entries, allocator);
            allocator.free(valid_value);
        }
    }
    try std.testing.expect(fasta == null);
}

The read_fasta function pulls the entire file into heap memory (needed for certain genomic analysis) which can be very memory hungry for a 20 year old computer running Windows Vista. So built into the function are several allocs and reallocs that could fail. So if they do fail the goal is to return null without any memory leaks. There are several points of memory allocation in the function, so it is important to make sure none of them forget to free already allocated memory before returning to main.
Hope someone else finds this helpful later on.

You might be interested in std.testing.checkAllAllocationFailures, which uses FailingAllocator internally:

(side note: it’d probably be nicer to return error.OutOfMemory instead of null on allocation failure; doing so will also make it much easier to use checkAllAllocationFailures)

1 Like

You are probably right for testing purposes. The goal for the final program is to not crash on the user and at this time I feel more comfortable handling optionals than error unions.

Thanks for the extra resources!