github.com/jaylevin/jenkins-library@v1.230.4/pkg/log/fatalHook_test.go (about)

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