log_test.go 2.14 KB
Newer Older
1 2 3 4 5 6 7 8 9
package persist

import (
	"io/ioutil"
	"os"
	"path/filepath"
	"strings"
	"testing"

10
	"gitlab.com/NebulousLabs/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 17 18
	if testing.Short() {
		t.SkipNow()
	}
19
	// Create a folder for the log file.
20
	testdir := build.TempDir(persistDir, t.Name())
21 22 23 24 25 26 27
	err := os.MkdirAll(testdir, 0700)
	if err != nil {
		t.Fatal(err)
	}

	// Create the logger.
	logFilename := filepath.Join(testdir, "test.log")
28
	fl, err := NewFileLogger(logFilename)
29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
	if err != nil {
		t.Fatal(err)
	}

	// Write an example statement, and then close the logger.
	fl.Println("TEST: this should get written to the logfile")
	err = fl.Close()
	if err != nil {
		t.Fatal(err)
	}

	// Check that data was written to the log file. There should be three
	// lines, one for startup, the example line, and one to close the logger.
	expectedSubstring := []string{"STARTUP", "TEST", "SHUTDOWN", ""} // file ends with a newline
	fileData, err := ioutil.ReadFile(logFilename)
	if err != nil {
		t.Fatal(err)
	}
	fileLines := strings.Split(string(fileData), "\n")
	for i, line := range fileLines {
		if !strings.Contains(string(line), expectedSubstring[i]) {
			t.Error("did not find the expected message in the logger")
		}
	}
	if len(fileLines) != 4 { // file ends with a newline
		t.Error("logger did not create the correct number of lines:", len(fileLines))
	}
}
57 58 59 60

// TestLoggerCritical prints a critical message from the logger.
func TestLoggerCritical(t *testing.T) {
	// Create a folder for the log file.
61
	testdir := build.TempDir(persistDir, t.Name())
62 63 64 65 66 67 68
	err := os.MkdirAll(testdir, 0700)
	if err != nil {
		t.Fatal(err)
	}

	// Create the logger.
	logFilename := filepath.Join(testdir, "test.log")
69
	fl, err := NewFileLogger(logFilename)
70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89
	if err != nil {
		t.Fatal(err)
	}

	// Write a catch for a panic that should trigger when logger.Critical is
	// called.
	defer func() {
		r := recover()
		if r == nil {
			t.Error("critical message was not thrown in a panic")
		}

		// Close the file logger to clean up the test.
		err = fl.Close()
		if err != nil {
			t.Fatal(err)
		}
	}()
	fl.Critical("a critical message")
}