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