1
1
package cli
2
2
3
3
import (
4
+ "os"
4
5
"strings"
5
6
"testing"
6
7
7
8
"github.com/coder/serpent"
8
9
)
9
10
11
+ func ensureSudo (t * testing.T ) {
12
+ t .Helper ()
13
+ if os .Getgid () != 0 {
14
+ t .Fatal ("test requires root priviledges" )
15
+ }
16
+ }
17
+
10
18
// MockPTY provides a simple mock for PTY-like testing
11
19
// This is a simplified version inspired by coder/coder's ptytest.
12
20
type MockPTY struct {
@@ -38,6 +46,30 @@ func (m *MockPTY) Clear() {
38
46
m .stderr = strings.Builder {}
39
47
}
40
48
49
+ func (m * MockPTY ) ExpectMatch (content string ) {
50
+ if ! strings .Contains (m .stdout .String (), content ) {
51
+ m .t .Fatalf ("expected \" %s\" , got: %s" , content , m .stdout .String ())
52
+ }
53
+ }
54
+
55
+ func (m * MockPTY ) ExpectError (content string ) {
56
+ if ! strings .Contains (m .stderr .String (), content ) {
57
+ m .t .Fatalf ("expected error with \" %s\" , got: %s" , content , m .stderr .String ())
58
+ }
59
+ }
60
+
61
+ func (m * MockPTY ) RequireError () {
62
+ if m .stderr .String () == "" {
63
+ m .t .Fatal ("expected error" )
64
+ }
65
+ }
66
+
67
+ func (m * MockPTY ) RequireNoError () {
68
+ if m .stderr .String () != "" {
69
+ m .t .Fatalf ("expected nothing in stderr, but got: %s" , m .stderr .String ())
70
+ }
71
+ }
72
+
41
73
func TestPtySetupWorks (t * testing.T ) {
42
74
cmd := NewCommand ()
43
75
inv := cmd .Invoke ("--help" )
@@ -49,13 +81,13 @@ func TestPtySetupWorks(t *testing.T) {
49
81
t .Fatalf ("could not run with simple --help arg: %v" , err )
50
82
}
51
83
52
- // TODO: A snapshot test setup is usually a good idea for CLI messages like this
53
- if ! strings .Contains (pty .Stdout (), "Monitor and restrict HTTP/HTTPS requests from processes" ) {
54
- t .Fatalf ("expected help to display summary, got: %s" , pty .Stdout ())
55
- }
84
+ pty .RequireNoError ()
85
+ pty .ExpectMatch ("Monitor and restrict HTTP/HTTPS requests from processes" )
56
86
}
57
87
58
88
func TestCurlGithub (t * testing.T ) {
89
+ ensureSudo (t )
90
+
59
91
cmd := NewCommand ()
60
92
inv := cmd .Invoke ("--allow" , "\" github.com\" " , "--" , "curl" , "https://github.com" )
61
93
@@ -65,4 +97,7 @@ func TestCurlGithub(t *testing.T) {
65
97
if err := inv .Run (); err != nil {
66
98
t .Fatalf ("error curling github: %v" , err )
67
99
}
100
+
101
+ pty .RequireNoError ()
102
+ pty .ExpectMatch ("" )
68
103
}
0 commit comments