Skip to content

Commit ff6f33d

Browse files
committed
extract limit computing logic into a func and add a test
1 parent b3fb1e6 commit ff6f33d

File tree

2 files changed

+39
-9
lines changed

2 files changed

+39
-9
lines changed

auth/auth_ui/huh.go

Lines changed: 12 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -33,8 +33,8 @@ import (
3333
)
3434

3535
const (
36-
defQRCodeSz = 9000 // default limit for encoded image size, seen values 6174, 8462
37-
maxQRCodeSz = 1<<16 - 1
36+
defQRCodeSz = 9000 // default limit for encoded image size, seen values 6174, 8462
37+
maxQRCodeSz = 1<<16 - 1 // maximum allowed QR code image size.
3838
imgPrefix = "data:image/png;base64,"
3939
)
4040

@@ -267,15 +267,10 @@ func (*Huh) RequestQR(ctx context.Context, _ io.Writer) (string, error) {
267267
3. right-click the QR code image;
268268
4. choose Copy Image.`
269269

270-
// check limQrCodeSz value for sanity
271-
if limQrCodeSz < defQrCodeSz || maxQrCodeSz < limQrCodeSz {
272-
limQrCodeSz = defQrCodeSz
273-
}
274-
275270
var imageData string
276271
q := huh.NewForm(huh.NewGroup(
277272
huh.NewText().
278-
CharLimit(limQrCodeSz).
273+
CharLimit(qrCharLimit()).
279274
Value(&imageData).
280275
Validate(func(s string) error {
281276
if !strings.HasPrefix(s, imgPrefix) {
@@ -292,3 +287,12 @@ func (*Huh) RequestQR(ctx context.Context, _ io.Writer) (string, error) {
292287
}
293288
return imageData, nil
294289
}
290+
291+
// qrCharLimit returns the effective character limit for the QR code input
292+
// field.
293+
func qrCharLimit() int {
294+
if defQRCodeSz <= limQRCodeSz && limQRCodeSz <= maxQRCodeSz {
295+
return limQRCodeSz
296+
}
297+
return defQRCodeSz
298+
}

auth/auth_ui/huh_test.go

Lines changed: 27 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,9 @@
1515

1616
package auth_ui
1717

18-
import "testing"
18+
import (
19+
"testing"
20+
)
1921

2022
func Test_valSixDigits(t *testing.T) {
2123
type args struct {
@@ -60,3 +62,27 @@ func Test_valSixDigits(t *testing.T) {
6062
})
6163
}
6264
}
65+
66+
func Test_qrCharLimit(t *testing.T) {
67+
tests := []struct {
68+
name string
69+
limQRsz int
70+
want int
71+
}{
72+
{"zero", 0, defQRCodeSz},
73+
{"default", defQRCodeSz, defQRCodeSz},
74+
{"between allowed values", (maxQRCodeSz - defQRCodeSz) / 2, (maxQRCodeSz - defQRCodeSz) / 2},
75+
{"over maximum", maxQRCodeSz + 1, defQRCodeSz},
76+
}
77+
for _, tt := range tests {
78+
t.Run(tt.name, func(t *testing.T) {
79+
var old = limQRCodeSz
80+
limQRCodeSz = tt.limQRsz
81+
t.Cleanup(func() { limQRCodeSz = old })
82+
83+
if got := qrCharLimit(); got != tt.want {
84+
t.Errorf("qrCharLimit() = %v, want %v", got, tt.want)
85+
}
86+
})
87+
}
88+
}

0 commit comments

Comments
 (0)