|
| 1 | +/** |
| 2 | + * This file is part of tz. |
| 3 | + * |
| 4 | + * tz is free software: you can redistribute it and/or modify it under |
| 5 | + * the terms of the GNU General Public License as published by the Free |
| 6 | + * Software Foundation, either version 3 of the License, or (at your |
| 7 | + * option) any later version. |
| 8 | + * |
| 9 | + * tz is distributed in the hope that it will be useful, but WITHOUT |
| 10 | + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY |
| 11 | + * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public |
| 12 | + * License for more details. |
| 13 | + * |
| 14 | + * You should have received a copy of the GNU General Public License |
| 15 | + * along with tz. If not, see <https://www.gnu.org/licenses/>. |
| 16 | + **/ |
| 17 | +package main |
| 18 | + |
| 19 | +import ( |
| 20 | + "fmt" |
| 21 | + "os" |
| 22 | + "math/rand" |
| 23 | + "strings" |
| 24 | + "testing" |
| 25 | +) |
| 26 | + |
| 27 | +func TestLogger(t *testing.T) { |
| 28 | + oldDebug := os.Getenv("DEBUG") |
| 29 | + os.Setenv("DEBUG", "1") |
| 30 | + SetupLogger() |
| 31 | + |
| 32 | + logMsg := fmt.Sprintf("Hello world %v!", rand.Int()) |
| 33 | + logger.Printf(logMsg) |
| 34 | + |
| 35 | + out, err := os.ReadFile("debug.log") |
| 36 | + if err != nil { |
| 37 | + t.Errorf("Could not read log file debug.log: %v", err) |
| 38 | + } |
| 39 | + lines := strings.Split(string(out), "\n") |
| 40 | + lastLine := lines[len(lines) - 2] // ignore trailing newline |
| 41 | + if !strings.Contains(lastLine, logMsg) { |
| 42 | + t.Errorf("Missing log line in debug.log: %s", logMsg) |
| 43 | + } |
| 44 | + |
| 45 | + if oldDebug != "1" { |
| 46 | + os.Setenv("DEBUG", oldDebug) |
| 47 | + SetupLogger() |
| 48 | + } |
| 49 | +} |
| 50 | + |
| 51 | +func TestNoLogger(t *testing.T) { |
| 52 | + oldDebug, debugWasSet := os.LookupEnv("DEBUG") |
| 53 | + os.Unsetenv("DEBUG") |
| 54 | + SetupLogger() |
| 55 | + |
| 56 | + logMsg := fmt.Sprintf("Not logged %v!", rand.Int()) |
| 57 | + logger.Print(logMsg) |
| 58 | + |
| 59 | + out, err := os.ReadFile("debug.log") |
| 60 | + if err != nil { |
| 61 | + t.Errorf("Could not read log file debug.log: %v", err) |
| 62 | + } |
| 63 | + if strings.Contains(string(out), logMsg) { |
| 64 | + t.Errorf("Log file debug.log contained forbidden string: %s", logMsg) |
| 65 | + } |
| 66 | + |
| 67 | + if debugWasSet { |
| 68 | + os.Setenv("DEBUG", oldDebug) |
| 69 | + SetupLogger() |
| 70 | + } |
| 71 | +} |
0 commit comments