111 lines
2.4 KiB
Go
111 lines
2.4 KiB
Go
//go:build linux || freebsd
|
||
// +build linux freebsd
|
||
|
||
package gopher
|
||
|
||
import (
|
||
"bufio"
|
||
"context"
|
||
"net"
|
||
"net/url"
|
||
"strconv"
|
||
"strings"
|
||
"testing"
|
||
|
||
"codeberg.org/petrbalvin/goget/internal/core"
|
||
)
|
||
|
||
func TestFormatGopherMenu(t *testing.T) {
|
||
tests := []struct {
|
||
line string
|
||
expected string
|
||
}{
|
||
{"0About\t/about\tgopher.floodgap.com\t70\r\n", "📄 About [/about]"},
|
||
{"1Fun\t/fun\tgopher.floodgap.com\t70\r\n", "📁 Fun [/fun]"},
|
||
{"iWelcome to Gopher\t(null)\t(null)\t0\r\n", "ℹ️ Welcome to Gopher"},
|
||
{"hNews\t/news\tgopher.floodgap.com\t70\r\n", "🌐 News [/news]"},
|
||
}
|
||
|
||
for _, tc := range tests {
|
||
result := formatGopherMenu(tc.line)
|
||
if result != tc.expected {
|
||
t.Errorf("formatGopherMenu(%q) = %q, want %q", tc.line, result, tc.expected)
|
||
}
|
||
}
|
||
}
|
||
|
||
func TestStripGopherMeta(t *testing.T) {
|
||
result := stripGopherMeta("0About\t/about\thost\t70")
|
||
if result != "About" {
|
||
t.Errorf("got %q, want %q", result, "About")
|
||
}
|
||
}
|
||
|
||
func TestGopherIcon(t *testing.T) {
|
||
if i := gopherIcon('0'); i != "📄" {
|
||
t.Errorf("got %q", i)
|
||
}
|
||
if i := gopherIcon('1'); i != "📁" {
|
||
t.Errorf("got %q", i)
|
||
}
|
||
if i := gopherIcon('9'); i != "💾" {
|
||
t.Errorf("got %q", i)
|
||
}
|
||
if i := gopherIcon('h'); i != "🌐" {
|
||
t.Errorf("got %q", i)
|
||
}
|
||
if i := gopherIcon('7'); i != "🔍" {
|
||
t.Errorf("got %q", i)
|
||
}
|
||
}
|
||
|
||
func TestIsTextGopherType(t *testing.T) {
|
||
if !isTextGopherType('0') {
|
||
t.Error("0 should be text")
|
||
}
|
||
if isTextGopherType('9') {
|
||
t.Error("9 should not be text")
|
||
}
|
||
}
|
||
|
||
type stringWriter struct{ sb *strings.Builder }
|
||
|
||
func (w *stringWriter) Write(p []byte) (int, error) { return w.sb.Write(p) }
|
||
|
||
func TestGopherDownloadMock(t *testing.T) {
|
||
listener, err := net.Listen("tcp", "127.0.0.1:0")
|
||
if err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
defer listener.Close()
|
||
|
||
port := listener.Addr().(*net.TCPAddr).Port
|
||
|
||
go func() {
|
||
conn, _ := listener.Accept()
|
||
if conn == nil {
|
||
return
|
||
}
|
||
defer conn.Close()
|
||
reader := bufio.NewReader(conn)
|
||
reader.ReadString('\n') // selector
|
||
conn.Write([]byte("0Hello from gopher\t(null)\t(null)\t0\r\n"))
|
||
conn.Write([]byte(".\r\n"))
|
||
}()
|
||
|
||
proto := NewProtocol()
|
||
u, _ := url.Parse("gopher://127.0.0.1:" + strconv.Itoa(port) + "/")
|
||
|
||
var buf strings.Builder
|
||
_, err = proto.Download(context.Background(), &core.DownloadRequest{
|
||
URL: u,
|
||
Writer: &stringWriter{&buf},
|
||
})
|
||
if err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
if !strings.Contains(buf.String(), "Hello from gopher") {
|
||
t.Errorf("output missing text: %q", buf.String())
|
||
}
|
||
}
|