github.com/linchen2chris/hugo@v0.0.0-20230307053224-cec209389705/transform/livereloadinject/livereloadinject_test.go (about)

     1  // Copyright 2018 The Hugo Authors. All rights reserved.
     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  // http://www.apache.org/licenses/LICENSE-2.0
     7  //
     8  // Unless required by applicable law or agreed to in writing, software
     9  // distributed under the License is distributed on an "AS IS" BASIS,
    10  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    11  // See the License for the specific language governing permissions and
    12  // limitations under the License.
    13  
    14  package livereloadinject
    15  
    16  import (
    17  	"bytes"
    18  	"net/url"
    19  	"strings"
    20  	"testing"
    21  
    22  	qt "github.com/frankban/quicktest"
    23  	"github.com/gohugoio/hugo/transform"
    24  )
    25  
    26  func TestLiveReloadInject(t *testing.T) {
    27  	c := qt.New(t)
    28  
    29  	lrurl, err := url.Parse("http://localhost:1234/subpath")
    30  	if err != nil {
    31  		t.Errorf("Parsing test URL failed")
    32  		return
    33  	}
    34  	expectBase := `<script src="/subpath/livereload.js?mindelay=10&amp;v=2&amp;port=1234&amp;path=subpath/livereload" data-no-instant defer></script>`
    35  	apply := func(s string) string {
    36  		out := new(bytes.Buffer)
    37  		in := strings.NewReader(s)
    38  
    39  		tr := transform.New(New(*lrurl))
    40  		tr.Apply(out, in)
    41  
    42  		return out.String()
    43  	}
    44  
    45  	c.Run("Head lower", func(c *qt.C) {
    46  		c.Assert(apply("<html><head>foo"), qt.Equals, "<html><head>"+expectBase+"foo")
    47  	})
    48  
    49  	c.Run("Head upper", func(c *qt.C) {
    50  		c.Assert(apply("<html><HEAD>foo"), qt.Equals, "<html><HEAD>"+expectBase+"foo")
    51  	})
    52  
    53  	c.Run("Body lower", func(c *qt.C) {
    54  		c.Assert(apply("foo</body>"), qt.Equals, "foo"+expectBase+"</body>")
    55  	})
    56  
    57  	c.Run("Body upper", func(c *qt.C) {
    58  		c.Assert(apply("foo</BODY>"), qt.Equals, "foo"+expectBase+"</BODY>")
    59  	})
    60  
    61  	c.Run("Html upper", func(c *qt.C) {
    62  		c.Assert(apply("<html>foo"), qt.Equals, "<html>"+expectBase+warnScript+"foo")
    63  	})
    64  
    65  	c.Run("Html upper with attr", func(c *qt.C) {
    66  		c.Assert(apply(`<html lang="en">foo`), qt.Equals, `<html lang="en">`+expectBase+warnScript+"foo")
    67  	})
    68  
    69  	c.Run("No match", func(c *qt.C) {
    70  		c.Assert(apply("<h1>No match</h1>"), qt.Equals, "<h1>No match</h1>"+expectBase+warnScript)
    71  	})
    72  }