github.com/google/go-safeweb@v0.0.0-20231219055052-64d8cfc90fbb/tests/integration/safehtml/safehtml_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  package safehtml_test
    16  
    17  import (
    18  	"net/http/httptest"
    19  	"testing"
    20  
    21  	"github.com/google/go-safeweb/safehttp"
    22  	"github.com/google/safehtml"
    23  	"github.com/google/safehtml/template"
    24  )
    25  
    26  func TestHandleRequestWrite(t *testing.T) {
    27  	mb := safehttp.NewServeMuxConfig(nil)
    28  	mux := mb.Mux()
    29  
    30  	mux.Handle("/", safehttp.MethodGet, safehttp.HandlerFunc(func(rw safehttp.ResponseWriter, ir *safehttp.IncomingRequest) safehttp.Result {
    31  		return rw.Write(safehtml.HTMLEscaped("<h1>Escaped, so not really a heading</h1>"))
    32  	}))
    33  
    34  	req := httptest.NewRequest(safehttp.MethodGet, "http://foo.com/", nil)
    35  
    36  	rw := httptest.NewRecorder()
    37  
    38  	mux.ServeHTTP(rw, req)
    39  
    40  	body := rw.Body.String()
    41  
    42  	if want := "&lt;h1&gt;Escaped, so not really a heading&lt;/h1&gt;"; body != want {
    43  		t.Errorf("body got: %q want: %q", body, want)
    44  	}
    45  }
    46  
    47  func TestHandleRequestWriteTemplate(t *testing.T) {
    48  	mb := safehttp.NewServeMuxConfig(nil)
    49  	mux := mb.Mux()
    50  
    51  	mux.Handle("/", safehttp.MethodGet, safehttp.HandlerFunc(func(rw safehttp.ResponseWriter, ir *safehttp.IncomingRequest) safehttp.Result {
    52  		return safehttp.ExecuteTemplate(rw, template.Must(template.New("name").Parse("<h1>{{ . }}</h1>")), "This is an actual heading, though.")
    53  	}))
    54  
    55  	req := httptest.NewRequest(safehttp.MethodGet, "http://foo.com/", nil)
    56  
    57  	rw := httptest.NewRecorder()
    58  
    59  	mux.ServeHTTP(rw, req)
    60  
    61  	body := rw.Body.String()
    62  
    63  	if want := "<h1>This is an actual heading, though.</h1>"; body != want {
    64  		t.Errorf("body got: %q want: %q", body, want)
    65  	}
    66  }