Skip to content

Commit 0519aef

Browse files
committed
helpers
1 parent f6fd236 commit 0519aef

File tree

1 file changed

+39
-4
lines changed

1 file changed

+39
-4
lines changed

cli/cli_test.go

Lines changed: 39 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,20 @@
11
package cli
22

33
import (
4+
"os"
45
"strings"
56
"testing"
67

78
"github.com/coder/serpent"
89
)
910

11+
func ensureSudo(t *testing.T) {
12+
t.Helper()
13+
if os.Getgid() != 0 {
14+
t.Fatal("test requires root priviledges")
15+
}
16+
}
17+
1018
// MockPTY provides a simple mock for PTY-like testing
1119
// This is a simplified version inspired by coder/coder's ptytest.
1220
type MockPTY struct {
@@ -38,6 +46,30 @@ func (m *MockPTY) Clear() {
3846
m.stderr = strings.Builder{}
3947
}
4048

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+
4173
func TestPtySetupWorks(t *testing.T) {
4274
cmd := NewCommand()
4375
inv := cmd.Invoke("--help")
@@ -49,13 +81,13 @@ func TestPtySetupWorks(t *testing.T) {
4981
t.Fatalf("could not run with simple --help arg: %v", err)
5082
}
5183

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")
5686
}
5787

5888
func TestCurlGithub(t *testing.T) {
89+
ensureSudo(t)
90+
5991
cmd := NewCommand()
6092
inv := cmd.Invoke("--allow", "\"github.com\"", "--", "curl", "https://github.com")
6193

@@ -65,4 +97,7 @@ func TestCurlGithub(t *testing.T) {
6597
if err := inv.Run(); err != nil {
6698
t.Fatalf("error curling github: %v", err)
6799
}
100+
101+
pty.RequireNoError()
102+
pty.ExpectMatch("")
68103
}

0 commit comments

Comments
 (0)