github.com/google/go-safeweb@v0.0.0-20231219055052-64d8cfc90fbb/safehttp/plugins/htmlinject/embed_1_16_test.go (about)

     1  // Copyright 2020 Google LLC
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //	https://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  //go:build go1.16
    16  // +build go1.16
    17  
    18  package htmlinject
    19  
    20  import (
    21  	"embed"
    22  	"io/ioutil"
    23  	"path/filepath"
    24  	"strings"
    25  	"testing"
    26  
    27  	safetemplate "github.com/google/safehtml/template"
    28  )
    29  
    30  //go:embed testdata
    31  var embedTestdata embed.FS
    32  
    33  func TestLoadGlobEmbed(t *testing.T) {
    34  	tpl, err := LoadGlobEmbed(nil, LoadConfig{}, safetemplate.TrustedSourceFromConstant("testdata/*.tpl"), embedTestdata)
    35  
    36  	// Test that whatever we provide is clonable or injection won't be possible.
    37  	tpl, err = tpl.Clone()
    38  	if err != nil {
    39  		t.Fatalf("Clone loaded template: got err %q", err)
    40  	}
    41  	tpl = tpl.Funcs(map[string]interface{}{
    42  		XSRFTokensDefaultFuncName: func() string { return "{{" + XSRFTokensDefaultFuncName + "}}" },
    43  		CSPNoncesDefaultFuncName:  func() string { return "{{" + CSPNoncesDefaultFuncName + "}}" },
    44  	})
    45  	if got, want := len(tpl.Templates()), 2; got != want {
    46  		t.Fatalf("Loaded templates: got %d want %d %s", got, want, tpl.DefinedTemplates())
    47  	}
    48  	for _, inner := range tpl.Templates() {
    49  		t.Run(inner.Name(), func(t *testing.T) {
    50  			var sb strings.Builder
    51  			err := tpl.ExecuteTemplate(&sb, inner.Name(), nil)
    52  			if err != nil {
    53  				t.Fatalf("Executing: %v", err)
    54  			}
    55  			stripExt := strings.TrimSuffix(inner.Name(), filepath.Ext(inner.Name()))
    56  			b, err := ioutil.ReadFile("testdata/" + stripExt + ".want")
    57  			if err != nil {
    58  				t.Fatalf("Reading '.want' file: %v", err)
    59  			}
    60  			if got, want := sb.String(), string(b); got != want {
    61  				t.Errorf("got: %v, want: %v", got, want)
    62  			}
    63  		})
    64  	}
    65  }