package httpblock import ( "context" "net/http" "net/http/httptest" "testing" "git.smesh.lol/nostrino/pkg/crypto/chainhash" ) // TestABlockComesBackFromTheService: one GET by hash returns the bytes. func TestABlockComesBackFromTheService(t *testing.T) { hash := chainhash.HashH([]byte("block")) server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.URL.Path != "/block/btc/"+hash.String() { http.NotFound(w, r) return } _, _ = w.Write([]byte{1, 2, 3, 4}) })) defer server.Close() source, err := New(Config{BaseURL: server.URL, Chain: "btc"}) if err != nil { t.Fatal(err) } raw, err := source(context.Background(), hash) if err != nil { t.Fatal(err) } if len(raw) != 4 || raw[0] != 1 { t.Fatalf("block came back as %v", raw) } } // TestAMissIsNilNotAnError: a 404 means the cache does not hold it, and the tunnel answers. func TestAMissIsNilNotAnError(t *testing.T) { server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { http.NotFound(w, nil) })) defer server.Close() source, err := New(Config{BaseURL: server.URL, Chain: "blake"}) if err != nil { t.Fatal(err) } raw, err := source(context.Background(), chainhash.HashH([]byte("missing"))) if err != nil { t.Fatalf("a miss was reported as an error: %v", err) } if raw != nil { t.Fatalf("a miss returned %d bytes", len(raw)) } } // TestAServerFaultIsAnError: a service that answers 500 is broken, and that is worth a line. func TestAServerFaultIsAnError(t *testing.T) { server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { http.Error(w, "boom", http.StatusInternalServerError) })) defer server.Close() source, err := New(Config{BaseURL: server.URL, Chain: "btc"}) if err != nil { t.Fatal(err) } if _, err := source(context.Background(), chainhash.HashH([]byte("x"))); err == nil { t.Fatal("a 500 from the service was treated as a miss") } } // TestABaseURLThatIsNotHTTPIsRefused: the source is configured, not discovered, so a typo is // caught where it is made. func TestABaseURLThatIsNotHTTPIsRefused(t *testing.T) { if _, err := New(Config{BaseURL: "ftp://example", Chain: "btc"}); err == nil { t.Fatal("a non-http base URL was accepted") } if _, err := New(Config{BaseURL: "http://example", Chain: ""}); err == nil { t.Fatal("a source with no chain was accepted") } }