@@ -21,7 +21,9 @@ import (
21
21
"path/filepath"
22
22
"strings"
23
23
"testing"
24
+ "time"
24
25
26
+ "github.com/bradleyjkemp/cupaloy/v2"
25
27
"github.com/spf13/cobra"
26
28
)
27
29
@@ -282,3 +284,84 @@ func TestArgsRegex(t *testing.T) {
282
284
}
283
285
})
284
286
}
287
+
288
+ // To update snapshots run: UPDATE_SNAPSHOTS=true go test ./...
289
+ func TestGenDocsSnapshots (t * testing.T ) {
290
+ // Test cases
291
+ tests := []struct {
292
+ name string
293
+ cmd * cobra.Command
294
+ options []GenDocsOption
295
+ }{
296
+ {
297
+ name : "default_example" ,
298
+ cmd : & cobra.Command {
299
+ Use : "default_example" ,
300
+ Long : "Testing example output using the default example formatter" ,
301
+ Example : "example --test -v" ,
302
+ },
303
+ options : []GenDocsOption {
304
+ WithCustomTimeGetter (func () time.Time {
305
+ return time .Date (2025 , 3 , 5 , 17 , 0 , 0 , 0 , time .UTC )
306
+ }),
307
+ },
308
+ },
309
+ {
310
+ name : "custom_formatter_example" ,
311
+ cmd : & cobra.Command {
312
+ Use : "custom_example" ,
313
+ Long : "Testing example output using a custom example formatter" ,
314
+ Example : "example --test -v" ,
315
+ },
316
+ options : []GenDocsOption {
317
+ WithCustomTimeGetter (func () time.Time {
318
+ return time .Date (2025 , 3 , 5 , 17 , 0 , 0 , 0 , time .UTC )
319
+ }),
320
+ WithCustomExampleFormatter (func (buf * bytes.Buffer , cmd * cobra.Command ) {
321
+ _ , _ = fmt .Fprintf (buf , "custom example for %s\n " , cmd .Use )
322
+ _ , _ = buf .WriteString (cmd .Example )
323
+ }),
324
+ },
325
+ },
326
+ {
327
+ name : "custom_formatter_surround_default_example" ,
328
+ cmd : & cobra.Command {
329
+ Use : "custom_formatter_surround_default_example" ,
330
+ Long : "Testing example output using a custom example formatter which calls the default formatter" ,
331
+ Example : "example --test -v" ,
332
+ },
333
+ options : []GenDocsOption {
334
+ WithCustomTimeGetter (func () time.Time {
335
+ return time .Date (2025 , 3 , 5 , 17 , 0 , 0 , 0 , time .UTC )
336
+ }),
337
+ WithCustomExampleFormatter (func (buf * bytes.Buffer , cmd * cobra.Command ) {
338
+ _ , _ = buf .WriteString ("-- before example --\n " )
339
+ DefaultExampleFormatter (buf , cmd )
340
+ _ , _ = buf .WriteString ("-- after example --\n " )
341
+ }),
342
+ },
343
+ },
344
+ }
345
+
346
+ // Run tests
347
+ for _ , tt := range tests {
348
+ t .Run (tt .name , func (t * testing.T ) {
349
+ snapshotter := cupaloy .New (cupaloy .SnapshotFileExtension (".txt" ))
350
+ // Create buffer to capture output
351
+ buf := new (bytes.Buffer )
352
+
353
+ // Execute function
354
+ err := GenDocs (tt .cmd , buf , tt .options ... )
355
+ if err != nil {
356
+ t .Fatalf ("GenDocs() error = %v" , err )
357
+ return
358
+ }
359
+
360
+ // Compare with snapshot
361
+ err = snapshotter .SnapshotWithName (tt .name , buf .String ())
362
+ if err != nil {
363
+ t .Errorf ("Snapshot comparison failed: %v" , err )
364
+ }
365
+ })
366
+ }
367
+ }
0 commit comments