github.com/safedep/dry@v0.0.0-20241016050132-a15651f0548b/log/zap_test.go (about) 1 package log 2 3 import ( 4 "os" 5 "testing" 6 7 "github.com/stretchr/testify/assert" 8 ) 9 10 func TestNewZapLogger(t *testing.T) { 11 logger, err := newZapLogger("TestSvc", "test") 12 13 assert.Nil(t, err) 14 assert.NotNil(t, logger) 15 16 zapLogger, typeCheck := logger.(*zapLoggerWrapper) 17 assert.True(t, typeCheck) 18 19 assert.NotNil(t, zapLogger.logger) 20 assert.NotNil(t, zapLogger.sugaredLogger) 21 } 22 23 func TestProductionLoggerToFile(t *testing.T) { 24 t.Run("ProductionLoggerToFile", func(t *testing.T) { 25 tmpFile, err := os.CreateTemp("", "test-*.log") 26 assert.NoError(t, err) 27 28 path := tmpFile.Name() 29 tmpFile.Close() 30 31 // Remove the file created by os.CreateTemp 32 os.Remove(path) 33 34 // Make sure the file created by the test is removed 35 defer os.Remove(path) 36 37 t.Setenv(loggerKeyEnvLogFileName, path) 38 t.Setenv(loggerKeyEnvLogLevel, logLevelNameDebug) 39 40 l, err := newZapLogger("TestSvc", "test") 41 assert.NoError(t, err) 42 43 l.Infof("Test info log message") 44 l.Debugf("Test debug log message") 45 46 z, ok := l.(*zapLoggerWrapper) 47 assert.True(t, ok) 48 49 z.logger.Sync() 50 51 assert.FileExists(t, path) 52 53 content, err := os.ReadFile(path) 54 assert.NoError(t, err) 55 56 assert.Contains(t, string(content), "Test info log message") 57 assert.Contains(t, string(content), "Test debug log message") 58 }) 59 }