github.com/openshift-online/ocm-sdk-go@v0.1.473/testing/templates.go (about)

     1  /*
     2  Copyright (c) 2019 Red Hat, Inc.
     3  
     4  Licensed under the Apache License, Version 2.0 (the "License");
     5  you may not use this file except in compliance with the License.
     6  You may obtain a copy of the License at
     7  
     8    http://www.apache.org/licenses/LICENSE-2.0
     9  
    10  Unless required by applicable law or agreed to in writing, software
    11  distributed under the License is distributed on an "AS IS" BASIS,
    12  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13  See the License for the specific language governing permissions and
    14  limitations under the License.
    15  */
    16  
    17  package testing
    18  
    19  import (
    20  	"bytes"
    21  	"regexp"
    22  	"text/template"
    23  
    24  	"github.com/onsi/gomega/types"
    25  
    26  	. "github.com/onsi/gomega" // nolint
    27  )
    28  
    29  // EvaluateTemplate generates a string from the given templlate source and name value pairs. For
    30  // example the following code:
    31  //
    32  //	EvaluateTemplate(
    33  //		`{
    34  //			"access_token": "{{ .AccessToken }}"
    35  //			"refresh_token": "{{ .RefreshToken }}"
    36  //		}`,
    37  //		"AccessToken", "myaccesstoken",
    38  //		"RefreshToken", "myrefreshtoken",
    39  //	)
    40  //
    41  // Will generate the following string:
    42  //
    43  //	{
    44  //		"access_token": "myaccesstoken"
    45  //		"access_token": "myrefreshtoken"
    46  //	}
    47  //
    48  // To simplify embeding of the templates in Go source the function also removes the leading tabs
    49  // from the generated text.
    50  func EvaluateTemplate(source string, args ...interface{}) string {
    51  	// Check that there is an even number of args, and that the first of each pair is a string:
    52  	count := len(args)
    53  	Expect(count%2).To(
    54  		Equal(0),
    55  		"Template '%s' should have an even number of arguments, but it has %d",
    56  		source, count,
    57  	)
    58  	for i := 0; i < count; i = i + 2 {
    59  		name := args[i]
    60  		_, ok := name.(string)
    61  		Expect(ok).To(
    62  			BeTrue(),
    63  			"Argument %d of template '%s' is a key, so it should be a string, "+
    64  				"but its type is %T",
    65  			i, source, name,
    66  		)
    67  	}
    68  
    69  	// Put the variables in the map that will be passed as the data object for the execution of
    70  	// the template:
    71  	data := make(map[string]interface{})
    72  	for i := 0; i < count; i = i + 2 {
    73  		name := args[i].(string)
    74  		value := args[i+1]
    75  		data[name] = value
    76  	}
    77  
    78  	// Parse the template:
    79  	tmpl, err := template.New("").Parse(source)
    80  	Expect(err).ToNot(
    81  		HaveOccurred(),
    82  		"Can't parse template '%s': %v",
    83  		source, err,
    84  	)
    85  
    86  	// Execute the template:
    87  	buffer := new(bytes.Buffer)
    88  	err = tmpl.Execute(buffer, data)
    89  	Expect(err).ToNot(
    90  		HaveOccurred(),
    91  		"Can't execute template '%s': %v",
    92  		source, err,
    93  	)
    94  	result := buffer.String()
    95  
    96  	// Remove the leading tabs:
    97  	result = RemoveLeadingTabs(result)
    98  
    99  	return result
   100  }
   101  
   102  // MatchJSONTemplate succeeds if actual is a string or stringer of JSON that matches the result of
   103  // evaluating the given template with the given arguments.
   104  func MatchJSONTemplate(template string, args ...interface{}) types.GomegaMatcher {
   105  	return MatchJSON(EvaluateTemplate(template, args...))
   106  }
   107  
   108  // RemoveLeadingTabs removes the leading tabs from the lines of the given string.
   109  func RemoveLeadingTabs(s string) string {
   110  	return leadingTabsRE.ReplaceAllString(s, "")
   111  }
   112  
   113  // leadingTabsRE is the regular expression used to remove leading tabs from strings generated with
   114  // the EvaluateTemplate function.
   115  var leadingTabsRE = regexp.MustCompile(`(?m)^\t*`)