|
| 1 | +package jsonfieldstest |
| 2 | + |
| 3 | +import ( |
| 4 | + "strings" |
| 5 | + "testing" |
| 6 | + |
| 7 | + "github.com/cli/cli/v2/pkg/cmdutil" |
| 8 | + "github.com/spf13/cobra" |
| 9 | + "github.com/stretchr/testify/assert" |
| 10 | + "github.com/stretchr/testify/require" |
| 11 | +) |
| 12 | + |
| 13 | +func jsonFieldsFor(cmd *cobra.Command) []string { |
| 14 | + // This annotation is added by the `cmdutil.AddJSONFlags` function. |
| 15 | + // |
| 16 | + // This is an extremely janky way to get access to this information but due to the fact we pass |
| 17 | + // around concrete cobra.Command structs, there's no viable way to have typed access to the fields. |
| 18 | + // |
| 19 | + // It's also kind of fragile because it's several hops away from the code that actually validates the usage |
| 20 | + // of these flags, so it's possible for things to get out of sync. |
| 21 | + stringFields, ok := cmd.Annotations["help:json-fields"] |
| 22 | + if !ok { |
| 23 | + return nil |
| 24 | + } |
| 25 | + |
| 26 | + return strings.Split(stringFields, ",") |
| 27 | +} |
| 28 | + |
| 29 | +// NewCmdFunc represents the typical function signature we use for creating commands e.g. `NewCmdView`. |
| 30 | +// |
| 31 | +// It is generic over `T` as each command construction has their own Options type e.g. `ViewOptions` |
| 32 | +type NewCmdFunc[T any] func(f *cmdutil.Factory, runF func(*T) error) *cobra.Command |
| 33 | + |
| 34 | +// ExpectCommandToSupportJSONFields asserts that the provided command supports exactly the provided fields. |
| 35 | +// Ordering of the expected fields is not important. |
| 36 | +// |
| 37 | +// Make sure you are not pointing to the same slice of fields in the test and the implementation. |
| 38 | +// It can be a little tedious to rewrite the fields inline in the test but it's significantly more useful because: |
| 39 | +// - It forces the test author to think about and convey exactly the expected fields for a command |
| 40 | +// - It avoids accidentally adding fields to a command, and the test passing unintentionally |
| 41 | +func ExpectCommandToSupportJSONFields[T any](t *testing.T, fn NewCmdFunc[T], expectedFields []string) { |
| 42 | + t.Helper() |
| 43 | + |
| 44 | + actualFields := jsonFieldsFor(fn(&cmdutil.Factory{}, nil)) |
| 45 | + assert.Equal(t, len(actualFields), len(expectedFields), "expected number of fields to match") |
| 46 | + require.ElementsMatch(t, expectedFields, actualFields) |
| 47 | +} |
0 commit comments