package webread import ( "bytes" "context" "encoding/json" "net" "net/http" "net/netip" "os" "strings" "testing" ) func TestMainWritesTheBundle(t *testing.T) { mux := http.NewServeMux() mux.HandleFunc("/", func(w http.ResponseWriter, _ *http.Request) { w.Write([]byte("hello")) }) r := newRig(t, mux) r.host("shop.example.com", public1) raw, _ := json.Marshal(plan(t, "https://shop.example.com/")) dir := t.TempDir() var stderr bytes.Buffer limited := false if code := mainWith([]string{dir}, bytes.NewReader(raw), &stderr, r.d, func() error { limited = true; return nil }); code != 0 { t.Fatalf("exit %d: %s", code, stderr.String()) } if !limited { t.Fatal("limits not applied") } b, err := ReadBundle(dir) if err != nil || len(b.Files) != 1 || string(b.Files[0].Data) != "hello" { t.Fatalf("bundle %+v %v", b, err) } } func TestMainRefusesBadInput(t *testing.T) { ok, _ := json.Marshal(plan(t, "https://shop.example.com/")) for name, c := range map[string]struct { args []string input string }{ "no outdir": {nil, string(ok)}, "two outdirs": {[]string{t.TempDir(), t.TempDir()}, string(ok)}, "not json": {[]string{t.TempDir()}, "{"}, "unknown field": {[]string{t.TempDir()}, strings.Replace(string(ok), `{"sources"`, `{"extra":1,"sources"`, 1)}, "trailing": {[]string{t.TempDir()}, string(ok) + "{}"}, "too large": {[]string{t.TempDir()}, strings.Repeat(" ", MaxPlanBytes+1)}, "bad source": {[]string{t.TempDir()}, `{"sources":[{"id":"s1","url":{"scheme":"https","host":"127.0.0.1","port":443,"path":"/"},"origin":"paul"}]}`}, } { var stderr bytes.Buffer d := defaults() d.lookup = func(context.Context, string) ([]netip.Addr, error) { t.Errorf("%s: looked up", name) return nil, net.ErrClosed } if code := mainWith(c.args, strings.NewReader(c.input), &stderr, d, func() error { return nil }); code == 0 { t.Errorf("%s: exit 0", name) } if len(c.args) == 1 { if names, _ := os.ReadDir(c.args[0]); len(names) != 0 { t.Errorf("%s: wrote %v", name, names) } } } } func TestLocalAddressesKeepsGlobalUnicast(t *testing.T) { var in []net.Addr for _, s := range []string{"127.0.0.1/8", "::1/128", "fe80::1/64", "169.254.3.4/16", "192.168.1.5/24", "151.101.1.1/32", "2a01:4f8::5/64", "224.0.0.1/4", "151.101.1.1/24"} { ip, n, _ := net.ParseCIDR(s) n.IP = ip in = append(in, n) } got, err := localAddresses(func() ([]net.Addr, error) { return in, nil }) if err != nil { t.Fatal(err) } var s []string for _, a := range got { s = append(s, a.String()) } if strings.Join(s, " ") != "151.101.1.1 192.168.1.5 2a01:4f8::5" { t.Fatalf("got %v", s) } if _, err := localAddresses(func() ([]net.Addr, error) { return nil, net.ErrClosed }); err == nil { t.Fatal("an unreadable interface list is not an empty one") } // The real host's list reads, and holds no loopback. real, err := LocalAddresses() if err != nil { t.Fatal(err) } for _, a := range real { if a.IsLoopback() || a.IsLinkLocalUnicast() { t.Fatalf("LocalAddresses gave %s", a) } } }