Skip to content

proposal: testing: Error Cases Helper #41494

@artasparks

Description

@artasparks

I would like to propose adding a helper method to the standard library (in the testing pkg, probably) for testing whether an error contains a substring in the context of unit-testing. It's pattern I use frequently, and tend to copy around between libraries.

When testing whether or not an error is expected based on an expected substring, there are four cases to check. {err, no err} X {expErr, no expErr}. This is a helper to check all four cases.

Generally, I use such a helper in table tests:

...
		{
			desc: "Point out of range",
			in: &Point{x: 100, y: 200},
			expErrSubstr: "out of range x or y",
		},
...
	for _, tc := range testCases {
		t.Run(tc.desc, func(t *testing.T) {
			out, err := New(tc.in.x, tc.in.y).Convert()
			cerr := errcheck.CheckCases(err, tc.expErrSubstr)
			if cerr != nil {
				t.Error(cerr)
				return
			}
			if err != nil {
				// Error is non-nil, but expected. Can't do any more assertions. 
				return
			}
			// More assertions here.

Here's the sort of method method I end up writing:

func CheckCases(err error, expErrSubstr string) error {
	if err == nil && expErrSubstr != "" {
		return fmt.Errorf("got no error but expected error containing %q", expErrSubstr)
	} else if err != nil && expErrSubstr == "" {
		return fmt.Errorf("got error %q but expected no error", err.Error())
	} else if err != nil && !strings.Contains(err.Error(), expErrSubstr) {
		return fmt.Errorf("got error %q but expected it to contain %q", err.Error(), expErrSubstr)
	}
	return nil
}

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions