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

     1  //go:build unit
     2  // +build unit
     3  
     4  package log
     5  
     6  import (
     7  	"os"
     8  	"path/filepath"
     9  	"testing"
    10  
    11  	"github.com/sirupsen/logrus"
    12  	"github.com/stretchr/testify/assert"
    13  )
    14  
    15  func TestFatalHookLevels(t *testing.T) {
    16  	hook := FatalHook{}
    17  	assert.Equal(t, []logrus.Level{logrus.FatalLevel}, hook.Levels())
    18  }
    19  
    20  func TestFatalHookFire(t *testing.T) {
    21  	workspace := t.TempDir()
    22  
    23  	t.Run("with step name", func(t *testing.T) {
    24  		hook := FatalHook{
    25  			Path:          workspace,
    26  			CorrelationID: "https://build.url",
    27  		}
    28  		entry := logrus.Entry{
    29  			Data: logrus.Fields{
    30  				"category": "testCategory",
    31  				"stepName": "testStep",
    32  			},
    33  			Message: "the error message",
    34  		}
    35  
    36  		err := hook.Fire(&entry)
    37  
    38  		assert.NoError(t, err)
    39  		fileContent, err := os.ReadFile(filepath.Join(workspace, "testStep_errorDetails.json"))
    40  		assert.NoError(t, err)
    41  		assert.NotContains(t, string(fileContent), `"category":"testCategory"`)
    42  		assert.Contains(t, string(fileContent), `"correlationId":"https://build.url"`)
    43  		assert.Contains(t, string(fileContent), `"message":"the error message"`)
    44  	})
    45  
    46  	t.Run("no step name", func(t *testing.T) {
    47  		hook := FatalHook{
    48  			Path:          workspace,
    49  			CorrelationID: "https://build.url",
    50  		}
    51  		entry := logrus.Entry{
    52  			Data: logrus.Fields{
    53  				"category": "testCategory",
    54  			},
    55  			Message: "the error message",
    56  		}
    57  
    58  		err := hook.Fire(&entry)
    59  
    60  		assert.NoError(t, err)
    61  		fileContent, err := os.ReadFile(filepath.Join(workspace, "errorDetails.json"))
    62  		assert.NoError(t, err)
    63  		assert.NotContains(t, string(fileContent), `"category":"testCategory"`)
    64  		assert.Contains(t, string(fileContent), `"correlationId":"https://build.url"`)
    65  		assert.Contains(t, string(fileContent), `"message":"the error message"`)
    66  	})
    67  
    68  	t.Run("file exists", func(t *testing.T) {
    69  		hook := FatalHook{}
    70  		entry := logrus.Entry{
    71  			Message: "the new error message",
    72  		}
    73  
    74  		err := hook.Fire(&entry)
    75  
    76  		assert.NoError(t, err)
    77  		fileContent, err := os.ReadFile(filepath.Join(workspace, "errorDetails.json"))
    78  		assert.NoError(t, err)
    79  
    80  		assert.Contains(t, string(fileContent), `"message":"the error message"`)
    81  	})
    82  }