testify icon indicating copy to clipboard operation
testify copied to clipboard

assert.Len: avoid printing the value of very large objects

Open brackendawson opened this issue 3 months ago • 2 comments

From #1235 by @Inuart

Description

When testing the Len of very large objects, the error message can appear very long or just not appear at all. Having a "printing length limit" helps in keeping the console clean and ensures the message should have %d item(s), but has %d appears and can be read.

Proposed solution

A failed Len assertion will print the type of the object instead of its value if the actual length of the object is greater than 100 items. 100 is an arbitrary value and I'm open to changing it.

Use case

In my tests some slices have thousands of items and I find myself avoiding

assert.Len(t, items, expectedItems)

in favour of

assert.True(t, len(items) == expectedItems, "expected %d items to be set", expectedItems)

just because the console gets filled with thousands of values that take all available space and are thus not useful for debugging.

In very large slices no message appears, leaving an empty error behind.

brackendawson avatar Sep 19 '25 12:09 brackendawson

Rather than limiting Len to printing 100 elements, we can significantly reduce the limit used by assert.truncatingFormat, this will prevent very very long output on all assertions which risk doing so, not just Len.

Those we need/want to see the very very long output can do so using testing.T.Logf.

brackendawson avatar Sep 19 '25 12:09 brackendawson

Tangential: Assert.ElementsMatch is also unbounded and can print large objects.

tscales avatar Sep 25 '25 14:09 tscales