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