-
Notifications
You must be signed in to change notification settings - Fork 31
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Signed-off-by: Daisuke Kanda <[email protected]>
- Loading branch information
Showing
2 changed files
with
101 additions
and
33 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,88 @@ | ||
package log | ||
|
||
import ( | ||
"testing" | ||
|
||
"fmt" | ||
"log/slog" | ||
"bytes" | ||
"encoding/json" | ||
"regexp" | ||
) | ||
|
||
type setupType struct { | ||
logger *RelayLogger | ||
buffer bytes.Buffer | ||
} | ||
|
||
func beforeEach(t *testing.T) *setupType { | ||
var r setupType | ||
|
||
err := InitLoggerWithWriter("debug", "json", &r.buffer) | ||
if err != nil { | ||
t.Fatal(err) | ||
} | ||
|
||
r.logger = GetLogger() | ||
|
||
return &r | ||
} | ||
|
||
type logType struct { | ||
Time string | ||
Level string | ||
Source struct { | ||
Function string | ||
File string | ||
Line int | ||
} | ||
Msg string | ||
Stack string | ||
Error string | ||
} | ||
|
||
func parseResult(setup *setupType, t *testing.T) (string, logType) { | ||
raw := setup.buffer.String() | ||
var parsed logType | ||
|
||
err := json.Unmarshal(setup.buffer.Bytes(), &parsed) | ||
if err != nil { | ||
t.Fatalf("fail to parse log: %v: %s", err, raw) | ||
} | ||
|
||
return raw, parsed | ||
} | ||
|
||
func TestLogLog(t *testing.T) { | ||
setup := beforeEach(t) | ||
|
||
setup.logger.log(slog.LevelInfo, 0, "test") | ||
raw, r := parseResult(setup, t) | ||
|
||
if r.Level != "INFO" { | ||
t.Fatalf("mismatch level: %s", raw) | ||
} | ||
|
||
if m, err := regexp.MatchString(`/log.TestLogLog$`, r.Source.Function); err != nil || !m { | ||
t.Fatalf("mismatch source.function: %v", raw) | ||
} | ||
} | ||
|
||
func TestLogError(t *testing.T) { | ||
setup := beforeEach(t) | ||
|
||
setup.logger.Error("testerr", fmt.Errorf("dummy")) | ||
raw, r := parseResult(setup, t) | ||
|
||
if r.Level != "ERROR" { | ||
t.Fatalf("mismatch level: %s", raw) | ||
} | ||
|
||
if m, err := regexp.MatchString(`/log.TestLogError$`, r.Source.Function); err != nil || !m { | ||
t.Fatalf("mismatch source.function: %v", raw) | ||
} | ||
|
||
if r.Error != "dummy" { | ||
t.Fatalf("mismatch level: %s", raw) | ||
} | ||
} |