test: write into a temp file and read from its fd

This test creates a new temp file and writes some bytes into it.
It then opens a new file for the file descriptor of the temp file and
tries to read some bytes out of it.
Этот коммит содержится в:
ZauberNerd 2022-03-04 20:49:37 +00:00 коммит произвёл Ron Evans
родитель e295770363
коммит 6f31712b7d

Просмотреть файл

@ -4,7 +4,9 @@
package os_test package os_test
import ( import (
"io"
. "os" . "os"
"runtime"
"testing" "testing"
) )
@ -86,3 +88,29 @@ func TestStandardFd(t *testing.T) {
t.Errorf("Stderr.Fd() = %d, want 2", fd) t.Errorf("Stderr.Fd() = %d, want 2", fd)
} }
} }
func TestFd(t *testing.T) {
if runtime.GOOS == "windows" {
t.Log("TODO: TestFd fails on Windows, skipping")
return
}
f := newFile("TestFd.txt", t)
defer Remove(f.Name())
defer f.Close()
const data = "hello, world\n"
io.WriteString(f, data)
fd := NewFile(f.Fd(), "as-fd")
defer fd.Close()
b := make([]byte, 5)
n, err := fd.ReadAt(b, 0)
if n != 5 && err != nil {
t.Errorf("Failed to read 5 bytes from file descriptor: %v", err)
}
if string(b) != data[:5] {
t.Errorf("File descriptor contents not equal to file contents.")
}
}