This repository has been archived by the owner on Mar 31, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathexec_test.go
112 lines (97 loc) · 2.21 KB
/
exec_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
//go:build !windows
// +build !windows
package well
import (
"bytes"
"context"
"encoding/json"
"testing"
"time"
"unicode/utf8"
"github.com/cybozu-go/log"
)
func TestUTF8StringFromBytes(t *testing.T) {
t.Parallel()
str := "世\xc5\x33\x34"
if utf8.ValidString(str) {
t.Error(str + " should be invalid")
}
vstr := UTF8StringFromBytes([]byte(str))
if !utf8.ValidString(vstr) {
t.Error(vstr + ` should be valid`)
}
}
func TestLogCmd(t *testing.T) {
ctx := context.Background()
ctx = WithRequestID(ctx, testUUID)
logger := log.NewLogger()
logger.SetFormatter(log.JSONFormat{})
buf := new(bytes.Buffer)
logger.SetOutput(buf)
cmd := CommandContext(ctx, "true", "1", "2")
cmd.Severity = log.LvDebug
cmd.Logger = logger
err := cmd.Run()
if err != nil {
t.Fatal(err)
}
if len(buf.Bytes()) > 0 {
t.Error(`log should not be recorded`)
}
cmd = CommandContext(ctx, "true", "1", "2")
cmd.Severity = log.LvInfo
cmd.Logger = logger
err = cmd.Run()
if err != nil {
t.Fatal(err)
}
var execlog ExecLog
err = json.Unmarshal(buf.Bytes(), &execlog)
if err != nil {
t.Fatal(err)
}
if time.Since(execlog.LoggedAt) > time.Minute {
t.Error(time.Since(execlog.LoggedAt) > time.Minute)
}
if execlog.Severity != "info" {
t.Error(`execlog.Severity != "info"`)
}
if execlog.Type != "exec" {
t.Error(`execlog.Type != "exec"`)
}
if execlog.Args[1] != "1" {
t.Error(`execlog.Args[1] != "1"`)
}
if execlog.RequestID != testUUID {
t.Error(`execlog.RequestID != testUUID`)
}
}
func TestLogCmdError(t *testing.T) {
ctx := context.Background()
logger := log.NewLogger()
logger.SetFormatter(log.JSONFormat{})
buf := new(bytes.Buffer)
logger.SetOutput(buf)
cmd := CommandContext(ctx, "/bin/sh", "-c", "echo hoge fuga 1>&2; exit 3")
cmd.Severity = log.LvDebug
cmd.Logger = logger
err := cmd.Run()
if err == nil {
t.Fatal("the command should fail")
}
var execlog ExecLog
err = json.Unmarshal(buf.Bytes(), &execlog)
if err != nil {
t.Fatal(err)
}
if execlog.Severity != "error" {
t.Error(`execlog.Severity != "error"`)
}
if execlog.Type != "exec" {
t.Error(`execlog.Type != "exec"`)
}
t.Log(execlog.Error)
if execlog.Stderr != "hoge fuga\n" {
t.Error(`execlog.Stderr != "hoge fuga\n"`)
}
}