github.com/ethersphere/bee/v2@v2.2.0/pkg/util/nbhdutil/neighborhoodsuggestion_test.go (about) 1 // Copyright 2024 The Swarm Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 package nbhdutil_test 6 7 import ( 8 "io" 9 "net/http" 10 "strings" 11 "testing" 12 13 "github.com/ethersphere/bee/v2/pkg/util/nbhdutil" 14 ) 15 16 type mockHttpClient struct { 17 res string 18 } 19 20 func (c *mockHttpClient) Get(_ string) (*http.Response, error) { 21 return &http.Response{ 22 Body: io.NopCloser(strings.NewReader(c.res)), 23 }, nil 24 } 25 26 func Test_FetchNeighborhood(t *testing.T) { 27 t.Parallel() 28 29 tests := []struct { 30 name string 31 neighborhood string 32 suggester string 33 httpRes string 34 wantNeighborhood string 35 wantError bool 36 }{ 37 { 38 name: "no suggester", 39 suggester: "", 40 wantNeighborhood: "", 41 wantError: false, 42 }, 43 { 44 name: "invalid suggester url", 45 suggester: "abc", 46 wantNeighborhood: "", 47 wantError: true, 48 }, 49 { 50 name: "missing neighborhood in res", 51 suggester: "http://test.com", 52 wantNeighborhood: "", 53 wantError: false, 54 httpRes: `{"abc":"abc"}`, 55 }, 56 { 57 name: "invalid neighborhood", 58 suggester: "http://test.com", 59 wantNeighborhood: "", 60 wantError: true, 61 httpRes: `{"neighborhood":"abc"}`, 62 }, 63 { 64 name: "valid neighborhood", 65 suggester: "http://test.com", 66 wantNeighborhood: "11011101000", 67 wantError: false, 68 httpRes: `{"neighborhood":"11011101000"}`, 69 }, 70 } 71 72 for _, test := range tests { 73 t.Run(test.name, func(t *testing.T) { 74 neighborhood, err := nbhdutil.FetchNeighborhood(&mockHttpClient{res: test.httpRes}, test.suggester) 75 if test.wantNeighborhood != neighborhood { 76 t.Fatalf("invalid neighborhood. want %s, got %s", test.wantNeighborhood, neighborhood) 77 } 78 if test.wantError && err == nil { 79 t.Fatalf("expected error. got no error") 80 } 81 if !test.wantError && err != nil { 82 t.Fatalf("expected no error. got %v", err) 83 } 84 }) 85 } 86 }