@@ -3354,7 +3354,7 @@ func TestCustomValidationErrorStatus(t *testing.T) {
33543354// })
33553355// }
33563356
3357- func globalHandler (ctx context.Context , input * struct {
3357+ func globalHandler (_ context.Context , input * struct {
33583358 Count int `query:"count"`
33593359}) (* struct { Body int }, error ) {
33603360 return & struct { Body int }{Body : input .Count * 3 / 2 }, nil
@@ -3409,3 +3409,54 @@ func TestGenerateFuncsPanicWithDescriptiveMessage(t *testing.T) {
34093409 })
34103410
34113411}
3412+
3413+ func TestFieldsOptionalByDefault (t * testing.T ) {
3414+ type MyInput struct {
3415+ Body struct {
3416+ Name string `json:"name"`
3417+ Age int `json:"age" required:"true"`
3418+ }
3419+ }
3420+
3421+ // Default behavior.
3422+ {
3423+ config := huma .DefaultConfig ("Test" , "1.0.0" )
3424+ config .FieldsOptionalByDefault = false
3425+ _ , api := humatest .New (t , config )
3426+
3427+ huma .Post (api , "/test" , func (ctx context.Context , input * MyInput ) (* struct {}, error ) {
3428+ return nil , nil
3429+ })
3430+
3431+ // Missing name should fail because it's required by default.
3432+ resp := api .Post ("/test" , map [string ]any {
3433+ "age" : 25 ,
3434+ })
3435+ assert .Equal (t , http .StatusUnprocessableEntity , resp .Code )
3436+ assert .Contains (t , resp .Body .String (), "required property name" )
3437+ }
3438+
3439+ // Mark fields optional by default.
3440+ {
3441+ config := huma .DefaultConfig ("Test" , "1.0.0" )
3442+ config .FieldsOptionalByDefault = true
3443+ _ , api := humatest .New (t , config )
3444+
3445+ huma .Post (api , "/test" , func (ctx context.Context , input * MyInput ) (* struct {}, error ) {
3446+ return nil , nil
3447+ })
3448+
3449+ // Missing name should pass because it's optional by default.
3450+ resp := api .Post ("/test" , map [string ]any {
3451+ "age" : 25 ,
3452+ })
3453+ assert .Equal (t , http .StatusNoContent , resp .Code )
3454+
3455+ // Missing age should still fail because it's explicitly marked as required.
3456+ resp = api .Post ("/test" , map [string ]any {
3457+ "name" : "John" ,
3458+ })
3459+ assert .Equal (t , http .StatusUnprocessableEntity , resp .Code )
3460+ assert .Contains (t , resp .Body .String (), "required property age" )
3461+ }
3462+ }
0 commit comments