我已经编写了一个与wpa_supplicant对话的小型库。我已经验证了它可以与测试应用程序一起使用,但是我也想添加一个单元测试。我的单元测试无法连接到Unix套接字。我收到错误消息“没有这样的文件或目录”,但同时创建了两个套接字文件。
lib.go
package libwpa
import (
"bytes"
"fmt"
"io/ioutil"
"net"
"os"
"strconv"
"strings"
)
type Conn struct {
uconn *net.UnixConn //Linux specific
localSock *os.File
}
func Connect(usock string) (*Conn, error) {
var (
uc *Conn
err error
)
uc = &Conn{}
if uc.localSock, err = ioutil.TempFile("/tmp", "wpa_supplicant"); err != nil {
return uc, err
}
os.Remove(uc.localSock.Name())
uc.uconn, err = net.DialUnix("unixgram",
&net.UnixAddr{Name: uc.localSock.Name(), Net: "unixgram"},
&net.UnixAddr{Name: usock, Net: "unixgram"})
if err != nil {
return uc, err
}
return uc, nil
}
lib_test.go
package libwpa
import (
"fmt"
"io/ioutil"
"net"
"os"
"testing"
)
func listen(reply chan<- []byte) {
conn, err := net.ListenUnixgram("unixgram", &net.UnixAddr{Name: "/tmp/foobar", Net: "unixgram"})
if err != nil {
fmt.Printf("failed to listen: %v\n", err)
panic(err)
}
defer os.Remove("/tmp/foobar")
f, _ := ioutil.ReadDir("/tmp")
for _, d := range f {
fmt.Printf("%v\n", d.Name())
}
buf := make([]byte, 2048)
n, uaddr, err := conn.ReadFromUnix(buf)
if err != nil {
fmt.Printf("LISTEN: Error: %v\n", err)
} else {
fmt.Printf("LISTEN: received %v bytes from %+v\n", n, uaddr)
fmt.Printf("LISTEN: %v\n", string(buf))
}
conn.Close()
reply <- buf
}
func Test_Connect(t *testing.T) {
reply := make(chan []byte, 2)
go listen(reply)
_, err := Connect("/tmp/foobar")
if err != nil {
t.Fatalf("Failed to connect: %v", err)
}
}
运行它我得到
$ go test
--- FAIL: Test_Connect (0.00s)
lib_test.go:42: Failed to connect: dial unixgram /tmp/wpa_supplicant208023735->/tmp/foobar: connect: no such file or directory
FAIL
exit status 1
FAIL _/home/code/apps/go/src/crown/libwpa 0.006s
$ ls /tmp/{foobar,wpa*}
/tmp/foobar= /tmp/wpa_supplicant923064975=
答案 0 :(得分:0)
我认为您忘了在前面加上“ defer”关键字:
os.Remove(uc.localSock.Name())
在您的lib.go文件中。修复后,您会收到“地址已在使用中”错误。
答案 1 :(得分:0)
我的问题原来是lib_test.go中的争用条件。我有一个goroutine创建我的监听套接字,然后立即从库中调用Connect(),但是监听套接字尚未准备好。添加少量延迟即可解决此问题。
原文:
go listen(reply)
_, err := Connect("/tmp/foobar")
修复:
go listen(reply)
time.Sleep(time.Second * 1)
_, err := Connect("/tmp/foobar")
我知道有更好的长期解决方案,但这至少使我再次陷入困境。