@@ -252,3 +252,63 @@ func TestToolSnapKeysSorted(t *testing.T) {
252252 assert .Greater (t , mmmIndex , aaaIndex , "mmm should come after aaa" )
253253 assert .Greater (t , zzzIndex , mmmIndex , "zzz should come after mmm" )
254254}
255+
256+ func TestStructFieldOrderingSortedAlphabetically (t * testing.T ) {
257+ withIsolatedWorkingDir (t )
258+
259+ // Given a struct with fields defined in non-alphabetical order
260+ // This test ensures that struct field order doesn't affect the JSON output
261+ type toolWithNonAlphabeticalFields struct {
262+ ZField string `json:"zField"` // Should appear last in JSON
263+ AField string `json:"aField"` // Should appear first in JSON
264+ MField string `json:"mField"` // Should appear in the middle
265+ }
266+
267+ tool := toolWithNonAlphabeticalFields {
268+ ZField : "z value" ,
269+ AField : "a value" ,
270+ MField : "m value" ,
271+ }
272+
273+ // When we write the snapshot
274+ t .Setenv ("UPDATE_TOOLSNAPS" , "true" )
275+ err := Test ("struct_field_order" , tool )
276+ require .NoError (t , err )
277+
278+ // Then the snapshot file should have alphabetically sorted keys despite struct field order
279+ snapJSON , err := os .ReadFile ("__toolsnaps__/struct_field_order.snap" )
280+ require .NoError (t , err )
281+
282+ snapStr := string (snapJSON )
283+
284+ // Find the positions of each field in the JSON string
285+ aFieldIndex := - 1
286+ mFieldIndex := - 1
287+ zFieldIndex := - 1
288+ for i := 0 ; i < len (snapStr )- 7 ; i ++ {
289+ switch snapStr [i : i + 6 ] {
290+ case "aField" :
291+ aFieldIndex = i
292+ case "mField" :
293+ mFieldIndex = i
294+ case "zField" :
295+ zFieldIndex = i
296+ }
297+ }
298+
299+ // Verify alphabetical ordering in the JSON output
300+ require .NotEqual (t , - 1 , aFieldIndex , "aField should be present" )
301+ require .NotEqual (t , - 1 , mFieldIndex , "mField should be present" )
302+ require .NotEqual (t , - 1 , zFieldIndex , "zField should be present" )
303+ assert .Less (t , aFieldIndex , mFieldIndex , "aField should appear before mField" )
304+ assert .Less (t , mFieldIndex , zFieldIndex , "mField should appear before zField" )
305+
306+ // Also verify idempotency - running the test again should produce identical output
307+ err = Test ("struct_field_order" , tool )
308+ require .NoError (t , err )
309+
310+ snapJSON2 , err := os .ReadFile ("__toolsnaps__/struct_field_order.snap" )
311+ require .NoError (t , err )
312+
313+ assert .Equal (t , string (snapJSON ), string (snapJSON2 ), "Multiple runs should produce identical output" )
314+ }
0 commit comments