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