github.com/hs0210/hashicorp-terraform@v0.11.12-beta1/registry/response/pagination_test.go (about) 1 package response 2 3 import ( 4 "encoding/json" 5 "testing" 6 ) 7 8 func intPtr(i int) *int { 9 return &i 10 } 11 12 func prettyJSON(o interface{}) (string, error) { 13 bytes, err := json.MarshalIndent(o, "", "\t") 14 if err != nil { 15 return "", err 16 } 17 return string(bytes), nil 18 } 19 20 func TestNewPaginationMeta(t *testing.T) { 21 type args struct { 22 offset int 23 limit int 24 hasMore bool 25 currentURL string 26 } 27 tests := []struct { 28 name string 29 args args 30 wantJSON string 31 }{ 32 { 33 name: "first page", 34 args: args{0, 10, true, "http://foo.com/v1/bar"}, 35 wantJSON: `{ 36 "limit": 10, 37 "current_offset": 0, 38 "next_offset": 10, 39 "next_url": "http://foo.com/v1/bar?offset=10" 40 }`, 41 }, 42 { 43 name: "second page", 44 args: args{10, 10, true, "http://foo.com/v1/bar"}, 45 wantJSON: `{ 46 "limit": 10, 47 "current_offset": 10, 48 "next_offset": 20, 49 "prev_offset": 0, 50 "next_url": "http://foo.com/v1/bar?offset=20", 51 "prev_url": "http://foo.com/v1/bar" 52 }`, 53 }, 54 { 55 name: "last page", 56 args: args{40, 10, false, "http://foo.com/v1/bar"}, 57 wantJSON: `{ 58 "limit": 10, 59 "current_offset": 40, 60 "prev_offset": 30, 61 "prev_url": "http://foo.com/v1/bar?offset=30" 62 }`, 63 }, 64 { 65 name: "misaligned start ending exactly on boundary", 66 args: args{32, 10, false, "http://foo.com/v1/bar"}, 67 wantJSON: `{ 68 "limit": 10, 69 "current_offset": 32, 70 "prev_offset": 22, 71 "prev_url": "http://foo.com/v1/bar?offset=22" 72 }`, 73 }, 74 { 75 name: "misaligned start partially through first page", 76 args: args{5, 12, true, "http://foo.com/v1/bar"}, 77 wantJSON: `{ 78 "limit": 12, 79 "current_offset": 5, 80 "next_offset": 17, 81 "prev_offset": 0, 82 "next_url": "http://foo.com/v1/bar?offset=17", 83 "prev_url": "http://foo.com/v1/bar" 84 }`, 85 }, 86 { 87 name: "no current URL", 88 args: args{10, 10, true, ""}, 89 wantJSON: `{ 90 "limit": 10, 91 "current_offset": 10, 92 "next_offset": 20, 93 "prev_offset": 0 94 }`, 95 }, 96 { 97 name: "#58 regression test", 98 args: args{1, 3, true, ""}, 99 wantJSON: `{ 100 "limit": 3, 101 "current_offset": 1, 102 "next_offset": 4, 103 "prev_offset": 0 104 }`, 105 }, 106 } 107 for _, tt := range tests { 108 t.Run(tt.name, func(t *testing.T) { 109 got := NewPaginationMeta(tt.args.offset, tt.args.limit, tt.args.hasMore, 110 tt.args.currentURL) 111 gotJSON, err := prettyJSON(got) 112 if err != nil { 113 t.Fatalf("failed to marshal PaginationMeta to JSON: %s", err) 114 } 115 if gotJSON != tt.wantJSON { 116 // prettyJSON makes debugging easier due to the annoying pointer-to-ints, but it 117 // also implicitly tests JSON marshalling as we can see if it's omitting fields etc. 118 t.Fatalf("NewPaginationMeta() =\n%s\n want:\n%s\n", gotJSON, tt.wantJSON) 119 } 120 }) 121 } 122 }