get.porter.sh/porter@v1.3.0/pkg/exec/schema_test.go (about)

     1  package exec
     2  
     3  import (
     4  	"fmt"
     5  	"os"
     6  	"testing"
     7  
     8  	"github.com/ghodss/yaml" // We are not using go-yaml because of serialization problems with jsonschema, don't use this library elsewhere
     9  	"github.com/stretchr/testify/assert"
    10  	"github.com/stretchr/testify/require"
    11  	"github.com/xeipuuv/gojsonschema"
    12  )
    13  
    14  func TestMixin_PrintSchema(t *testing.T) {
    15  	m := NewTestMixin(t)
    16  
    17  	m.PrintSchema()
    18  	gotSchema := m.TestConfig.TestContext.GetOutput()
    19  
    20  	wantSchema, err := os.ReadFile("schema/exec.json")
    21  	require.NoError(t, err)
    22  
    23  	assert.Equal(t, string(wantSchema), gotSchema)
    24  }
    25  
    26  func TestMixin_ValidateSchema(t *testing.T) {
    27  	m := NewTestMixin(t)
    28  
    29  	// Load the mixin schema
    30  	schemaLoader := gojsonschema.NewStringLoader(m.GetSchema())
    31  
    32  	testcases := []struct {
    33  		name      string
    34  		file      string
    35  		wantError string
    36  	}{
    37  		{"install", "testdata/install-input.yaml", ""},
    38  		{"upgrade", "testdata/upgrade-input.yaml", ""},
    39  		{"invoke", "testdata/invoke-input.yaml", ""},
    40  		{"uninstall", "testdata/uninstall-input.yaml", ""},
    41  		{"invalid command", "testdata/invalid-args-input.yaml", "Additional property args is not allowed"},
    42  		{"invalid type", "testdata/install-invalid-type-input.yaml", "Invalid type"},
    43  	}
    44  
    45  	for _, tc := range testcases {
    46  		t.Run(tc.name, func(t *testing.T) {
    47  			// Read the mixin input as a go dump
    48  			mixinInputB, err := os.ReadFile(tc.file)
    49  			require.NoError(t, err)
    50  			mixinInputMap := make(map[string]interface{})
    51  			err = yaml.Unmarshal(mixinInputB, &mixinInputMap)
    52  			require.NoError(t, err)
    53  			mixinInputLoader := gojsonschema.NewGoLoader(mixinInputMap)
    54  
    55  			// Validate the manifest against the schema
    56  			result, err := gojsonschema.Validate(schemaLoader, mixinInputLoader)
    57  			require.NoError(t, err)
    58  
    59  			if tc.wantError == "" {
    60  				assert.True(t, result.Valid(), "expected the input to be valid")
    61  				assert.Empty(t, result.Errors(), "expected the validation errors to be empty")
    62  			} else {
    63  				assert.False(t, result.Valid(), "expected the input to be invalid")
    64  				assert.Contains(t, fmt.Sprintf("%v", result.Errors()), tc.wantError, "expected validation errors")
    65  			}
    66  		})
    67  	}
    68  }