github.com/opentofu/opentofu@v1.7.1/internal/command/metadata_functions_test.go (about)

     1  // Copyright (c) The OpenTofu Authors
     2  // SPDX-License-Identifier: MPL-2.0
     3  // Copyright (c) 2023 HashiCorp, Inc.
     4  // SPDX-License-Identifier: MPL-2.0
     5  
     6  package command
     7  
     8  import (
     9  	"encoding/json"
    10  	"testing"
    11  
    12  	"github.com/mitchellh/cli"
    13  )
    14  
    15  func TestMetadataFunctions_error(t *testing.T) {
    16  	ui := new(cli.MockUi)
    17  	c := &MetadataFunctionsCommand{
    18  		Meta: Meta{
    19  			Ui: ui,
    20  		},
    21  	}
    22  
    23  	// This test will always error because it's missing the -json flag
    24  	if code := c.Run(nil); code != 1 {
    25  		t.Fatalf("expected error, got:\n%s", ui.OutputWriter.String())
    26  	}
    27  }
    28  
    29  func TestMetadataFunctions_output(t *testing.T) {
    30  	ui := new(cli.MockUi)
    31  	m := Meta{Ui: ui}
    32  	c := &MetadataFunctionsCommand{Meta: m}
    33  
    34  	if code := c.Run([]string{"-json"}); code != 0 {
    35  		t.Fatalf("wrong exit status %d; want 0\nstderr: %s", code, ui.ErrorWriter.String())
    36  	}
    37  
    38  	var got functions
    39  	gotString := ui.OutputWriter.String()
    40  	err := json.Unmarshal([]byte(gotString), &got)
    41  	if err != nil {
    42  		t.Fatal(err)
    43  	}
    44  
    45  	if len(got.Signatures) < 100 {
    46  		t.Fatalf("expected at least 100 function signatures, got %d", len(got.Signatures))
    47  	}
    48  
    49  	// check if one particular stable function is correct
    50  	gotMax, ok := got.Signatures["max"]
    51  	wantMax := "{\"description\":\"`max` takes one or more numbers and returns the greatest number from the set.\",\"return_type\":\"number\",\"variadic_parameter\":{\"name\":\"numbers\",\"type\":\"number\"}}"
    52  	if !ok {
    53  		t.Fatal(`missing function signature for "max"`)
    54  	}
    55  	if string(gotMax) != wantMax {
    56  		t.Fatalf("wrong function signature for \"max\":\ngot: %q\nwant: %q", gotMax, wantMax)
    57  	}
    58  
    59  	stderr := ui.ErrorWriter.String()
    60  	if stderr != "" {
    61  		t.Fatalf("expected empty stderr, got:\n%s", stderr)
    62  	}
    63  
    64  	// test that ignored functions are not part of the json
    65  	for _, v := range ignoredFunctions {
    66  		_, ok := got.Signatures[v]
    67  		if ok {
    68  			t.Fatalf("found ignored function %q inside output", v)
    69  		}
    70  	}
    71  }
    72  
    73  type functions struct {
    74  	FormatVersion string                     `json:"format_version"`
    75  	Signatures    map[string]json.RawMessage `json:"function_signatures,omitempty"`
    76  }