github.com/hernad/nomad@v1.6.112/nomad/structs/errors_test.go (about)

     1  // Copyright (c) HashiCorp, Inc.
     2  // SPDX-License-Identifier: MPL-2.0
     3  
     4  package structs
     5  
     6  import (
     7  	"errors"
     8  	"testing"
     9  
    10  	"github.com/hernad/nomad/ci"
    11  	"github.com/stretchr/testify/assert"
    12  )
    13  
    14  func TestRPCCodedErrors(t *testing.T) {
    15  	ci.Parallel(t)
    16  
    17  	cases := []struct {
    18  		err     error
    19  		code    int
    20  		message string
    21  	}{
    22  		{
    23  			NewErrRPCCoded(400, "a test message,here"),
    24  			400,
    25  			"a test message,here",
    26  		},
    27  		{
    28  			NewErrRPCCodedf(500, "a test message,here %s %s", "and,here%s", "second"),
    29  			500,
    30  			"a test message,here and,here%s second",
    31  		},
    32  	}
    33  
    34  	for _, c := range cases {
    35  		t.Run(c.err.Error(), func(t *testing.T) {
    36  			code, msg, ok := CodeFromRPCCodedErr(c.err)
    37  			assert.True(t, ok)
    38  			assert.Equal(t, c.code, code)
    39  			assert.Equal(t, c.message, msg)
    40  		})
    41  	}
    42  
    43  	negativeCases := []string{
    44  		"random error",
    45  		errRPCCodedErrorPrefix,
    46  		errRPCCodedErrorPrefix + "123",
    47  		errRPCCodedErrorPrefix + "qwer,asdf",
    48  	}
    49  	for _, c := range negativeCases {
    50  		t.Run(c, func(t *testing.T) {
    51  			_, _, ok := CodeFromRPCCodedErr(errors.New(c))
    52  			assert.False(t, ok)
    53  		})
    54  	}
    55  }