github.com/Synthesix/Sia@v1.3.3-0.20180413141344-f863baeed3ca/persist/log_test.go (about) 1 package persist 2 3 import ( 4 "io/ioutil" 5 "os" 6 "path/filepath" 7 "strings" 8 "testing" 9 10 "github.com/Synthesix/Sia/build" 11 ) 12 13 // TestLogger checks that the basic functions of the file logger work as 14 // designed. 15 func TestLogger(t *testing.T) { 16 // Create a folder for the log file. 17 testdir := build.TempDir(persistDir, t.Name()) 18 err := os.MkdirAll(testdir, 0700) 19 if err != nil { 20 t.Fatal(err) 21 } 22 23 // Create the logger. 24 logFilename := filepath.Join(testdir, "test.log") 25 fl, err := NewFileLogger(logFilename) 26 if err != nil { 27 t.Fatal(err) 28 } 29 30 // Write an example statement, and then close the logger. 31 fl.Println("TEST: this should get written to the logfile") 32 err = fl.Close() 33 if err != nil { 34 t.Fatal(err) 35 } 36 37 // Check that data was written to the log file. There should be three 38 // lines, one for startup, the example line, and one to close the logger. 39 expectedSubstring := []string{"STARTUP", "TEST", "SHUTDOWN", ""} // file ends with a newline 40 fileData, err := ioutil.ReadFile(logFilename) 41 if err != nil { 42 t.Fatal(err) 43 } 44 fileLines := strings.Split(string(fileData), "\n") 45 for i, line := range fileLines { 46 if !strings.Contains(string(line), expectedSubstring[i]) { 47 t.Error("did not find the expected message in the logger") 48 } 49 } 50 if len(fileLines) != 4 { // file ends with a newline 51 t.Error("logger did not create the correct number of lines:", len(fileLines)) 52 } 53 } 54 55 // TestLoggerCritical prints a critical message from the logger. 56 func TestLoggerCritical(t *testing.T) { 57 // Create a folder for the log file. 58 testdir := build.TempDir(persistDir, t.Name()) 59 err := os.MkdirAll(testdir, 0700) 60 if err != nil { 61 t.Fatal(err) 62 } 63 64 // Create the logger. 65 logFilename := filepath.Join(testdir, "test.log") 66 fl, err := NewFileLogger(logFilename) 67 if err != nil { 68 t.Fatal(err) 69 } 70 71 // Write a catch for a panic that should trigger when logger.Critical is 72 // called. 73 defer func() { 74 r := recover() 75 if r == nil { 76 t.Error("critical message was not thrown in a panic") 77 } 78 79 // Close the file logger to clean up the test. 80 err = fl.Close() 81 if err != nil { 82 t.Fatal(err) 83 } 84 }() 85 fl.Critical("a critical message") 86 }