Files
backend_fiesta/models/flexibleInt_test.go
2026-09-02 16:01:24 +05:30

89 lines
2.5 KiB
Go

package models
import (
"encoding/json"
"testing"
)
/*
A strict type on one field rejects the whole request.
Fiber's BodyParser stops at the first field it cannot convert and returns 400
"Invalid request body" — so `"primaryaddress": true` from a checkbox threw away
the address, the street and the pincode with it. The shopper saw no error worth
acting on and then had no address to choose at checkout.
Measured 2026-09-02 against the running backend: three plausible payloads for
one address form, three 400s.
*/
func readInt(t *testing.T, body string) (FlexibleInt, error) {
t.Helper()
var v struct {
N FlexibleInt `json:"n"`
}
err := json.Unmarshal([]byte(`{"n":`+body+`}`), &v)
return v.N, err
}
func mustRead(t *testing.T, body string, want FlexibleInt) {
t.Helper()
got, err := readInt(t, body)
if err != nil {
t.Fatalf("%s: %v", body, err)
}
if got != want {
t.Errorf("%s -> %d, want %d", body, got, want)
}
}
func TestACheckboxIsANumber(t *testing.T) {
// "Set as my default address" sends a boolean.
mustRead(t, "true", 1)
mustRead(t, "false", 0)
}
func TestATextInputIsANumber(t *testing.T) {
mustRead(t, `"1"`, 1)
mustRead(t, `"0"`, 0)
}
func TestAWordIsReadByMeaning(t *testing.T) {
mustRead(t, `"Active"`, 1)
mustRead(t, `"active"`, 1)
mustRead(t, `"Inactive"`, 0)
}
func TestAnUntouchedFieldIsZeroNotAnError(t *testing.T) {
mustRead(t, `""`, 0)
mustRead(t, "null", 0)
}
func TestAClientWithNoIntegerTypeStillWorks(t *testing.T) {
// JavaScript has one number type, so 1 can arrive as 1.0.
mustRead(t, "1.0", 1)
}
func TestAWordItCannotReadIsRefusedRatherThanGuessed(t *testing.T) {
// Storing 0 for something unrecognised would record a choice the shopper
// never made. Better to fail loudly than to invent an answer.
if _, err := readInt(t, `"maybe"`); err == nil {
t.Error(`"maybe" was silently accepted`)
}
}
func TestLatitudeSurvivesBothShapes(t *testing.T) {
// A map picker sends a number; a text field sends a string. Both are the
// same place, and rejecting either loses the whole address.
var withNumber, withString Customerlocations
if err := json.Unmarshal([]byte(`{"latitude":11.0168}`), &withNumber); err != nil {
t.Fatalf("number latitude: %v", err)
}
if err := json.Unmarshal([]byte(`{"latitude":"11.0168"}`), &withString); err != nil {
t.Fatalf("string latitude: %v", err)
}
if withNumber.Latitude != withString.Latitude {
t.Errorf("%q from a number, %q from a string", withNumber.Latitude, withString.Latitude)
}
}