...
1
2
3 package sockets
4
5 import (
6 "fmt"
7 "net"
8 "os"
9 "syscall"
10 "testing"
11 )
12
13 func runTest(t *testing.T, path string, l net.Listener, echoStr string) {
14 go func() {
15 for {
16 conn, err := l.Accept()
17 if err != nil {
18 return
19 }
20 _, _ = conn.Write([]byte(echoStr))
21 _ = conn.Close()
22 }
23 }()
24
25 conn, err := net.Dial("unix", path)
26 if err != nil {
27 t.Fatal(err)
28 }
29
30 buf := make([]byte, 5)
31 if _, err := conn.Read(buf); err != nil {
32 t.Fatal(err)
33 } else if string(buf) != echoStr {
34 t.Fatal(fmt.Errorf("msg may lost"))
35 }
36 }
37
38
39 func TestNewUnixSocket(t *testing.T) {
40 if os.Getuid() != 0 {
41 t.Skip("requires root")
42 }
43 gid := os.Getgid()
44 path := "/tmp/test.sock"
45 echoStr := "hello"
46 l, err := NewUnixSocket(path, gid)
47 if err != nil {
48 t.Fatal(err)
49 }
50 defer l.Close()
51 runTest(t, path, l, echoStr)
52 }
53
54 func TestUnixSocketWithOpts(t *testing.T) {
55 uid, gid := os.Getuid(), os.Getgid()
56 perms := os.FileMode(0o660)
57 path := "/tmp/test.sock"
58 echoStr := "hello"
59 l, err := NewUnixSocketWithOpts(path, WithChown(uid, gid), WithChmod(perms))
60 if err != nil {
61 t.Fatal(err)
62 }
63 defer l.Close()
64 p, err := os.Stat(path)
65 if err != nil {
66 t.Fatal(err)
67 }
68 if p.Mode().Perm() != perms {
69 t.Fatalf("unexpected file permissions: expected: %#o, got: %#o", perms, p.Mode().Perm())
70 }
71 if stat, ok := p.Sys().(*syscall.Stat_t); ok {
72 if stat.Uid != uint32(uid) || stat.Gid != uint32(gid) {
73 t.Fatalf("unexpected file ownership: expected: %d:%d, got: %d:%d", uid, gid, stat.Uid, stat.Gid)
74 }
75 }
76 runTest(t, path, l, echoStr)
77 }
78
View as plain text