github.com/terramate-io/tf@v0.0.0-20230830114523-fce866b4dfcd/command/arguments/show_test.go (about)

     1  // Copyright (c) HashiCorp, Inc.
     2  // SPDX-License-Identifier: MPL-2.0
     3  
     4  package arguments
     5  
     6  import (
     7  	"reflect"
     8  	"testing"
     9  
    10  	"github.com/davecgh/go-spew/spew"
    11  	"github.com/terramate-io/tf/tfdiags"
    12  )
    13  
    14  func TestParseShow_valid(t *testing.T) {
    15  	testCases := map[string]struct {
    16  		args []string
    17  		want *Show
    18  	}{
    19  		"defaults": {
    20  			nil,
    21  			&Show{
    22  				Path:     "",
    23  				ViewType: ViewHuman,
    24  			},
    25  		},
    26  		"json": {
    27  			[]string{"-json"},
    28  			&Show{
    29  				Path:     "",
    30  				ViewType: ViewJSON,
    31  			},
    32  		},
    33  		"path": {
    34  			[]string{"-json", "foo"},
    35  			&Show{
    36  				Path:     "foo",
    37  				ViewType: ViewJSON,
    38  			},
    39  		},
    40  	}
    41  
    42  	for name, tc := range testCases {
    43  		t.Run(name, func(t *testing.T) {
    44  			got, diags := ParseShow(tc.args)
    45  			if len(diags) > 0 {
    46  				t.Fatalf("unexpected diags: %v", diags)
    47  			}
    48  			if *got != *tc.want {
    49  				t.Fatalf("unexpected result\n got: %#v\nwant: %#v", got, tc.want)
    50  			}
    51  		})
    52  	}
    53  }
    54  
    55  func TestParseShow_invalid(t *testing.T) {
    56  	testCases := map[string]struct {
    57  		args      []string
    58  		want      *Show
    59  		wantDiags tfdiags.Diagnostics
    60  	}{
    61  		"unknown flag": {
    62  			[]string{"-boop"},
    63  			&Show{
    64  				Path:     "",
    65  				ViewType: ViewHuman,
    66  			},
    67  			tfdiags.Diagnostics{
    68  				tfdiags.Sourceless(
    69  					tfdiags.Error,
    70  					"Failed to parse command-line flags",
    71  					"flag provided but not defined: -boop",
    72  				),
    73  			},
    74  		},
    75  		"too many arguments": {
    76  			[]string{"-json", "bar", "baz"},
    77  			&Show{
    78  				Path:     "bar",
    79  				ViewType: ViewJSON,
    80  			},
    81  			tfdiags.Diagnostics{
    82  				tfdiags.Sourceless(
    83  					tfdiags.Error,
    84  					"Too many command line arguments",
    85  					"Expected at most one positional argument.",
    86  				),
    87  			},
    88  		},
    89  	}
    90  
    91  	for name, tc := range testCases {
    92  		t.Run(name, func(t *testing.T) {
    93  			got, gotDiags := ParseShow(tc.args)
    94  			if *got != *tc.want {
    95  				t.Fatalf("unexpected result\n got: %#v\nwant: %#v", got, tc.want)
    96  			}
    97  			if !reflect.DeepEqual(gotDiags, tc.wantDiags) {
    98  				t.Errorf("wrong result\ngot: %s\nwant: %s", spew.Sdump(gotDiags), spew.Sdump(tc.wantDiags))
    99  			}
   100  		})
   101  	}
   102  }