github.com/ouraigua/jenkins-library@v0.0.0-20231028010029-fbeaf2f3aa9b/pkg/log/errors_test.go (about)

     1  //go:build unit
     2  // +build unit
     3  
     4  package log
     5  
     6  import (
     7  	"encoding/json"
     8  	"fmt"
     9  	"github.com/sirupsen/logrus"
    10  	"github.com/stretchr/testify/assert"
    11  	"testing"
    12  )
    13  
    14  func TestSetErrorCategory(t *testing.T) {
    15  	SetErrorCategory(ErrorCustom)
    16  	assert.Equal(t, errorCategory, ErrorCustom)
    17  	assert.Equal(t, "custom", fmt.Sprint(errorCategory))
    18  }
    19  
    20  func TestGetErrorCategory(t *testing.T) {
    21  	errorCategory = ErrorCompliance
    22  	assert.Equal(t, GetErrorCategory(), errorCategory)
    23  }
    24  
    25  func TestSetFatalErrorDetail(t *testing.T) {
    26  	sampleError := logrus.Fields{"Message": "Error happened"}
    27  	errDetails, _ := json.Marshal(&sampleError)
    28  
    29  	tests := []struct {
    30  		name       string
    31  		error      []byte
    32  		want       []byte
    33  		errPresent bool
    34  	}{
    35  		{
    36  			name:       "set fatal error",
    37  			error:      errDetails,
    38  			want:       errDetails,
    39  			errPresent: false,
    40  		},
    41  		{
    42  			name:       "set fatal error - override",
    43  			error:      errDetails,
    44  			want:       errDetails,
    45  			errPresent: true,
    46  		},
    47  	}
    48  	for _, tt := range tests {
    49  		t.Run(tt.name, func(t *testing.T) {
    50  			if tt.errPresent {
    51  				SetFatalErrorDetail(tt.error)
    52  			}
    53  			SetFatalErrorDetail(tt.error)
    54  			assert.Equalf(t, tt.want, fatalError, "GetFatalErrorDetail()")
    55  			fatalError = nil // reset error
    56  		})
    57  	}
    58  }
    59  
    60  func TestGetFatalErrorDetail(t *testing.T) {
    61  	sampleError := logrus.Fields{"Message": "Error happened"}
    62  	errDetails, _ := json.Marshal(&sampleError)
    63  
    64  	tests := []struct {
    65  		name       string
    66  		errDetails []byte
    67  		want       string
    68  	}{
    69  		{
    70  			name:       "returns fatal error",
    71  			errDetails: errDetails,
    72  			want:       "{\"Message\":\"Error happened\"}",
    73  		},
    74  		{
    75  			name:       "no fatal error set - returns empty",
    76  			errDetails: nil,
    77  			want:       "",
    78  		},
    79  	}
    80  	for _, tt := range tests {
    81  		t.Run(tt.name, func(t *testing.T) {
    82  			if tt.errDetails != nil {
    83  				SetFatalErrorDetail(tt.errDetails)
    84  			}
    85  			str := ""
    86  			data := []byte(str)
    87  			fmt.Println(data)
    88  			fatalErrorDetail := string(GetFatalErrorDetail())
    89  			assert.Equalf(t, tt.want, fatalErrorDetail, "GetFatalErrorDetail()")
    90  			fatalError = nil // resets fatal error
    91  		})
    92  	}
    93  }