func TestShortcodeYoutube(t *testing.T) {
	for i, this := range []struct {
		in, expected string
	}{
		{
			`{{< youtube w7Ft2ymGmfc >}}`,
			"(?s)^\n<div style=\".*?\">.*?<iframe src=\"//www.youtube.com/embed/w7Ft2ymGmfc\" style=\".*?\" allowfullscreen frameborder=\"0\">.*?</iframe>.*?</div>\n$",
		},
		// set class
		{
			`{{< youtube w7Ft2ymGmfc video>}}`,
			"(?s)^\n<div class=\"video\">.*?<iframe src=\"//www.youtube.com/embed/w7Ft2ymGmfc\" allowfullscreen frameborder=\"0\">.*?</iframe>.*?</div>\n$",
		},
		// set class and autoplay (using named params)
		{
			`{{< youtube id="w7Ft2ymGmfc" class="video" autoplay="true" >}}`,
			"(?s)^\n<div class=\"video\">.*?<iframe src=\"//www.youtube.com/embed/w7Ft2ymGmfc\\?autoplay=1\".*?allowfullscreen frameborder=\"0\">.*?</iframe>.*?</div>$",
		},
	} {
		templ := tpl.New()
		p, _ := pageFromString(simplePage, "simple.md")
		output, err := HandleShortcodes(this.in, p, templ)

		matched, err := regexp.MatchString(this.expected, output)

		if err != nil {
			t.Fatalf("[%d] Regexp error", i)
		}

		if !matched {
			t.Errorf("[%d] unexpected rendering, got %s\n", i, output)
		}
	}
}
Example #2
0
func TestHighlight(t *testing.T) {
	viper.Reset()
	defer viper.Reset()

	if !helpers.HasPygments() {
		t.Skip("Skip test as Pygments is not installed")
	}
	viper.Set("PygmentsStyle", "bw")
	viper.Set("PygmentsUseClasses", false)

	templ := tpl.New()

	code := `
{{< highlight java >}}
void do();
{{< /highlight >}}`

	p, _ := pageFromString(simplePage, "simple.md")
	output, err := HandleShortcodes(code, p, templ)

	if err != nil {
		t.Fatal("Handle shortcode error", err)
	}
	matched, err := regexp.MatchString("(?s)^\n<div class=\"highlight\" style=\"background: #ffffff\"><pre style=\"line-height: 125%\">.*?void</span> do().*?</pre></div>\n$", output)

	if err != nil {
		t.Fatal("Regexp error", err)
	}

	if !matched {
		t.Error("Hightlight mismatch, got\n", output)
	}
}
Example #3
0
func TestShortcodeGoFuzzReports(t *testing.T) {
	tem := tpl.New()

	tem.AddInternalShortcode("sc.html", `foo`)
	p, _ := pageFromString(SIMPLE_PAGE, "simple.md")

	for i, this := range []struct {
		data      string
		expectErr bool
	}{
		{"{{</*/", true},
	} {
		output, err := HandleShortcodes(this.data, p, tem)

		if this.expectErr && err == nil {
			t.Errorf("[%d] should have errored", i)
		}

		if !this.expectErr && err != nil {
			t.Errorf("[%d] should not have errored: %s", i, err)
		}

		if !this.expectErr && err == nil && len(output) == 0 {
			t.Errorf("[%d] empty result", i)
		}
	}

}
func TestShortcodeVimeo(t *testing.T) {
	for i, this := range []struct {
		in, expected string
	}{
		{
			`{{< vimeo 146022717 >}}`,
			"(?s)^\n<div style=\".*?\">.*?<iframe src=\"//player.vimeo.com/video/146022717\" style=\".*?\" webkitallowfullscreen mozallowfullscreen allowfullscreen>.*?</iframe>.*?</div>\n$",
		},
		// set class
		{
			`{{< vimeo 146022717 video >}}`,
			"(?s)^\n<div class=\"video\">.*?<iframe src=\"//player.vimeo.com/video/146022717\" webkitallowfullscreen mozallowfullscreen allowfullscreen>.*?</iframe>.*?</div>\n$",
		},
		// set class (using named params)
		{
			`{{< vimeo id="146022717" class="video" >}}`,
			"(?s)^<div class=\"video\">.*?<iframe src=\"//player.vimeo.com/video/146022717\" webkitallowfullscreen mozallowfullscreen allowfullscreen>.*?</iframe>.*?</div>$",
		},
	} {
		templ := tpl.New()
		p, _ := pageFromString(simplePage, "simple.md")
		output, err := HandleShortcodes(this.in, p, templ)

		matched, err := regexp.MatchString(this.expected, output)

		if err != nil {
			t.Fatalf("[%d] Regexp error", i)
		}

		if !matched {
			t.Errorf("[%d] unexpected rendering, got %s\n", i, output)
		}
	}
}
Example #5
0
func templatePrep(s *Site) {
	s.Tmpl = tpl.New()
	s.Tmpl.LoadTemplates(s.absLayoutDir())
	if s.hasTheme() {
		s.Tmpl.LoadTemplatesWithPrefix(s.absThemeDir()+"/layouts", "theme")
	}
}
func doTestShortcodeCrossrefs(t *testing.T, relative bool) {
	var refShortcode string
	var expectedBase string

	if relative {
		refShortcode = "relref"
		expectedBase = "/bar"
	} else {
		refShortcode = "ref"
		expectedBase = baseURL
	}

	path := filepath.FromSlash("blog/post.md")
	in := fmt.Sprintf(`{{< %s "%s" >}}`, refShortcode, path)
	expected := fmt.Sprintf(`%s/simple/url/`, expectedBase)

	templ := tpl.New()
	p, _ := pageFromString(simplePageWithURL, path)
	p.Node.Site = &SiteInfo{
		Pages:   &(Pages{p}),
		BaseURL: template.URL(helpers.SanitizeURLKeepTrailingSlash(baseURL)),
	}

	output, err := HandleShortcodes(in, p, templ)

	if err != nil {
		t.Fatal("Handle shortcode error", err)
	}

	if output != expected {
		t.Errorf("Got\n%q\nExpected\n%q", output, expected)
	}
}
func TestShortcodeTweet(t *testing.T) {
	if testing.Short() {
		t.Skip("skipping Twitter test in short mode.")
	}

	for i, this := range []struct {
		in, expected string
	}{
		{
			`{{< tweet 666616452582129664 >}}`,
			"(?s)^<blockquote class=\"twitter-tweet\"><p lang=\"en\" dir=\"ltr\">Hugo 0.15 will have 30%\\+ faster render times thanks to this commit <a href=\"https://t.co/FfzhM8bNhT\">https://t.co/FfzhM8bNhT</a>  <a href=\"https://twitter.com/hashtag/gohugo\\?src=hash\">#gohugo</a> <a href=\"https://twitter.com/hashtag/golang\\?src=hash\">#golang</a> <a href=\"https://t.co/ITbMNU2BUf\">https://t.co/ITbMNU2BUf</a></p>&mdash; Steve Francia \\(@spf13\\) <a href=\"https://twitter.com/spf13/status/666616452582129664\">November 17, 2015</a></blockquote>.*?<script async src=\"//platform.twitter.com/widgets.js\" charset=\"utf-8\"></script>$",
		},
	} {
		templ := tpl.New()
		p, _ := pageFromString(simplePage, "simple.md")
		cacheFileID := viper.GetString("CacheDir") + url.QueryEscape("https://api.twitter.com/1/statuses/oembed.json?id=666616452582129664")
		defer os.Remove(cacheFileID)
		output, err := HandleShortcodes(this.in, p, templ)

		matched, err := regexp.MatchString(this.expected, output)

		if err != nil {
			t.Fatalf("[%d] Regexp error", i)
		}

		if !matched {
			t.Errorf("[%d] Hightlight mismatch, got %s\n", i, output)
		}
	}
}
func TestShortcodeGist(t *testing.T) {
	for i, this := range []struct {
		in, expected string
	}{
		{
			`{{< gist spf13 7896402 >}}`,
			"(?s)^<script src=\"//gist.github.com/spf13/7896402.js\"></script>$",
		},
		{
			`{{< gist spf13 7896402 "img.html" >}}`,
			"(?s)^<script src=\"//gist.github.com/spf13/7896402.js\\?file=img.html\"></script>$",
		},
	} {
		templ := tpl.New()
		p, _ := pageFromString(simplePage, "simple.md")
		output, err := HandleShortcodes(this.in, p, templ)

		matched, err := regexp.MatchString(this.expected, output)

		if err != nil {
			t.Fatalf("[%d] Regexp error", i)
		}

		if !matched {
			t.Errorf("[%d] unexpected rendering, got %s\n", i, output)
		}
	}
}
Example #9
0
func TestInnerSC(t *testing.T) {
	tem := tpl.New()
	tem.AddInternalShortcode("inside.html", `<div{{with .Get "class"}} class="{{.}}"{{end}}>{{ .Inner }}</div>`)

	CheckShortCodeMatch(t, `{{< inside class="aspen" >}}`, `<div class="aspen"></div>`, tem)
	CheckShortCodeMatch(t, `{{< inside class="aspen" >}}More Here{{< /inside >}}`, "<div class=\"aspen\">More Here</div>", tem)
	CheckShortCodeMatch(t, `{{< inside >}}More Here{{< /inside >}}`, "<div>More Here</div>", tem)
}
Example #10
0
func TestNestedSC(t *testing.T) {
	tem := tpl.New()
	tem.AddInternalShortcode("scn1.html", `<div>Outer, inner is {{ .Inner }}</div>`)
	tem.AddInternalShortcode("scn2.html", `<div>SC2</div>`)

	CheckShortCodeMatch(t, `{{% scn1 %}}{{% scn2 %}}{{% /scn1 %}}`, "<div>Outer, inner is <div>SC2</div>\n</div>", tem)

	CheckShortCodeMatch(t, `{{< scn1 >}}{{% scn2 %}}{{< /scn1 >}}`, "<div>Outer, inner is <div>SC2</div></div>", tem)
}
Example #11
0
func TestParentShortcode(t *testing.T) {
	tem := tpl.New()
	tem.AddInternalShortcode("r1.html", `1: {{ .Get "pr1" }} {{ .Inner }}`)
	tem.AddInternalShortcode("r2.html", `2: {{ .Parent.Get "pr1" }}{{ .Get "pr2" }} {{ .Inner }}`)
	tem.AddInternalShortcode("r3.html", `3: {{ .Parent.Parent.Get "pr1" }}{{ .Parent.Get "pr2" }}{{ .Get "pr3" }} {{ .Inner }}`)

	CheckShortCodeMatch(t, `{{< r1 pr1="p1" >}}1: {{< r2 pr2="p2" >}}2: {{< r3 pr3="p3" >}}{{< /r3 >}}{{< /r2 >}}{{< /r1 >}}`,
		"1: p1 1: 2: p1p2 2: 3: p1p2p3 ", tem)

}
Example #12
0
// Issue #2294
func TestNestedNamedMissingParam(t *testing.T) {
	tem := tpl.New()
	tem.AddInternalShortcode("acc.html", `<div class="acc">{{ .Inner }}</div>`)
	tem.AddInternalShortcode("div.html", `<div {{with .Get "class"}} class="{{ . }}"{{ end }}>{{ .Inner }}</div>`)
	tem.AddInternalShortcode("div2.html", `<div {{with .Get 0}} class="{{ . }}"{{ end }}>{{ .Inner }}</div>`)

	CheckShortCodeMatch(t,
		`{{% acc %}}{{% div %}}d1{{% /div %}}{{% div2 %}}d2{{% /div2 %}}{{% /acc %}}`,
		"<div class=\"acc\"><div >d1</div><div >d2</div>\n</div>", tem)
}
Example #13
0
func TestPositionalParamSC(t *testing.T) {
	tem := tpl.New()
	tem.AddInternalShortcode("video.html", `Playing Video {{ .Get 0 }}`)

	CheckShortCodeMatch(t, "{{< video 47238zzb >}}", "Playing Video 47238zzb", tem)
	CheckShortCodeMatch(t, "{{< video 47238zzb 132 >}}", "Playing Video 47238zzb", tem)
	CheckShortCodeMatch(t, "{{<video 47238zzb>}}", "Playing Video 47238zzb", tem)
	CheckShortCodeMatch(t, "{{<video 47238zzb    >}}", "Playing Video 47238zzb", tem)
	CheckShortCodeMatch(t, "{{<   video   47238zzb    >}}", "Playing Video 47238zzb", tem)
}
Example #14
0
func TestInnerSCWithMarkdown(t *testing.T) {
	tem := tpl.New()
	tem.AddInternalShortcode("inside.html", `<div{{with .Get "class"}} class="{{.}}"{{end}}>{{ .Inner }}</div>`)

	CheckShortCodeMatch(t, `{{% inside %}}
# More Here

[link](http://spf13.com) and text

{{% /inside %}}`, "<div><h1 id=\"more-here:bec3ed8ba720b9073ab75abcf3ba5d97\">More Here</h1>\n\n<p><a href=\"http://spf13.com\">link</a> and text</p>\n</div>", tem)
}
Example #15
0
func TestNamedParamSC(t *testing.T) {
	tem := tpl.New()
	tem.AddInternalShortcode("img.html", `<img{{ with .Get "src" }} src="{{.}}"{{end}}{{with .Get "class"}} class="{{.}}"{{end}}>`)

	CheckShortCodeMatch(t, `{{< img src="one" >}}`, `<img src="one">`, tem)
	CheckShortCodeMatch(t, `{{< img class="aspen" >}}`, `<img class="aspen">`, tem)
	CheckShortCodeMatch(t, `{{< img src= "one" >}}`, `<img src="one">`, tem)
	CheckShortCodeMatch(t, `{{< img src ="one" >}}`, `<img src="one">`, tem)
	CheckShortCodeMatch(t, `{{< img src = "one" >}}`, `<img src="one">`, tem)
	CheckShortCodeMatch(t, `{{< img src = "one" class = "aspen grove" >}}`, `<img src="one" class="aspen grove">`, tem)
}
Example #16
0
func TestIsNamedParamsSC(t *testing.T) {
	tem := tpl.New()
	tem.AddInternalShortcode("byposition.html", `<div id="{{ .Get 0 }}">`)
	tem.AddInternalShortcode("byname.html", `<div id="{{ .Get "id" }}">`)
	tem.AddInternalShortcode("ifnamedparams.html", `<div id="{{ if .IsNamedParams }}{{ .Get "id" }}{{ else }}{{ .Get 0 }}{{end}}">`)

	CheckShortCodeMatch(t, `{{< ifnamedparams id="name" >}}`, `<div id="name">`, tem)
	CheckShortCodeMatch(t, `{{< ifnamedparams position >}}`, `<div id="position">`, tem)
	CheckShortCodeMatch(t, `{{< byname id="name" >}}`, `<div id="name">`, tem)
	CheckShortCodeMatch(t, `{{< byname position >}}`, `<div id="error: cannot access positional params by string name">`, tem)
	CheckShortCodeMatch(t, `{{< byposition position >}}`, `<div id="position">`, tem)
	CheckShortCodeMatch(t, `{{< byposition id="name" >}}`, `<div id="error: cannot access named params by position">`, tem)
}
Example #17
0
func TestNestedComplexSC(t *testing.T) {
	tem := tpl.New()
	tem.AddInternalShortcode("row.html", `-row-{{ .Inner}}-rowStop-`)
	tem.AddInternalShortcode("column.html", `-col-{{.Inner    }}-colStop-`)
	tem.AddInternalShortcode("aside.html", `-aside-{{    .Inner  }}-asideStop-`)

	CheckShortCodeMatch(t, `{{< row >}}1-s{{% column %}}2-**s**{{< aside >}}3-**s**{{< /aside >}}4-s{{% /column %}}5-s{{< /row >}}6-s`,
		"-row-1-s-col-2-<strong>s</strong>-aside-3-<strong>s</strong>-asideStop-4-s-colStop-5-s-rowStop-6-s", tem)

	// turn around the markup flag
	CheckShortCodeMatch(t, `{{% row %}}1-s{{< column >}}2-**s**{{% aside %}}3-**s**{{% /aside %}}4-s{{< /column >}}5-s{{% /row %}}6-s`,
		"-row-1-s-col-2-<strong>s</strong>-aside-3-<strong>s</strong>-asideStop-4-s-colStop-5-s-rowStop-6-s", tem)
}
Example #18
0
func TestHighlight(t *testing.T) {
	if !helpers.HasPygments() {
		t.Skip("Skip test as Pygments is not installed")
	}
	defer viper.Set("PygmentsStyle", viper.Get("PygmentsStyle"))
	viper.Set("PygmentsStyle", "bw")

	tem := tpl.New()

	code := `
{{< highlight java >}}
void do();
{{< /highlight >}}`
	CheckShortCodeMatch(t, code, "\n<div class=\"highlight\" style=\"background: #ffffff\"><pre style=\"line-height: 125%\"><span style=\"font-weight: bold\">void</span> do();\n</pre></div>\n", tem)
}
func TestShortcodeHighlight(t *testing.T) {
	viper.Reset()
	defer viper.Reset()

	if !helpers.HasPygments() {
		t.Skip("Skip test as Pygments is not installed")
	}
	viper.Set("PygmentsStyle", "bw")
	viper.Set("PygmentsUseClasses", false)

	for i, this := range []struct {
		in, expected string
	}{
		{`
{{< highlight java >}}
void do();
{{< /highlight >}}`,
			"(?s)^\n<div class=\"highlight\" style=\"background: #ffffff\"><pre style=\"line-height: 125%\">.*?void</span> do().*?</pre></div>\n$",
		},
		{`
{{< highlight java "style=friendly" >}}
void do();
{{< /highlight >}}`,
			"(?s)^\n<div class=\"highlight\" style=\"background: #f0f0f0\"><pre style=\"line-height: 125%\">.*?void</span>.*?do</span>.*?().*?</pre></div>\n$",
		},
	} {
		templ := tpl.New()
		p, _ := pageFromString(simplePage, "simple.md")
		output, err := HandleShortcodes(this.in, p, templ)

		if err != nil {
			t.Fatalf("[%d] Handle shortcode error", i)
		}

		matched, err := regexp.MatchString(this.expected, output)

		if err != nil {
			t.Fatalf("[%d] Regexp error", i)
		}

		if !matched {
			t.Errorf("[%d] Hightlight mismatch, got %s\n", i, output)
		}
	}
}
func TestShortcodeTweet(t *testing.T) {
	for i, this := range []struct {
		in, resp, expected string
	}{
		{
			`{{< tweet 666616452582129664 >}}`,
			`{"url":"https:\/\/twitter.com\/spf13\/status\/666616452582129664","author_name":"Steve Francia","author_url":"https:\/\/twitter.com\/spf13","html":"\u003Cblockquote class=\"twitter-tweet\"\u003E\u003Cp lang=\"en\" dir=\"ltr\"\u003EHugo 0.15 will have 30%+ faster render times thanks to this commit \u003Ca href=\"https:\/\/t.co\/FfzhM8bNhT\"\u003Ehttps:\/\/t.co\/FfzhM8bNhT\u003C\/a\u003E  \u003Ca href=\"https:\/\/twitter.com\/hashtag\/gohugo?src=hash\"\u003E#gohugo\u003C\/a\u003E \u003Ca href=\"https:\/\/twitter.com\/hashtag\/golang?src=hash\"\u003E#golang\u003C\/a\u003E \u003Ca href=\"https:\/\/t.co\/ITbMNU2BUf\"\u003Ehttps:\/\/t.co\/ITbMNU2BUf\u003C\/a\u003E\u003C\/p\u003E&mdash; Steve Francia (@spf13) \u003Ca href=\"https:\/\/twitter.com\/spf13\/status\/666616452582129664\"\u003ENovember 17, 2015\u003C\/a\u003E\u003C\/blockquote\u003E\n\u003Cscript async src=\"\/\/platform.twitter.com\/widgets.js\" charset=\"utf-8\"\u003E\u003C\/script\u003E","width":550,"height":null,"type":"rich","cache_age":"3153600000","provider_name":"Twitter","provider_url":"https:\/\/twitter.com","version":"1.0"}`,
			`(?s)^<blockquote class="twitter-tweet"><p lang="en" dir="ltr">Hugo 0.15 will have 30%. faster render times thanks to this commit <a href="https://t.co/FfzhM8bNhT">https://t.co/FfzhM8bNhT</a>  <a href="https://twitter.com/hashtag/gohugo.src=hash">#gohugo</a> <a href="https://twitter.com/hashtag/golang.src=hash">#golang</a> <a href="https://t.co/ITbMNU2BUf">https://t.co/ITbMNU2BUf</a></p>&mdash; Steve Francia .@spf13. <a href="https://twitter.com/spf13/status/666616452582129664">November 17, 2015</a></blockquote>.*?<script async src="//platform.twitter.com/widgets.js" charset="utf-8"></script>$`,
		},
	} {
		// overload getJSON to return mock API response from Twitter
		tweetFuncMap := template.FuncMap{
			"getJSON": func(urlParts ...string) interface{} {
				var v interface{}
				err := json.Unmarshal([]byte(this.resp), &v)
				if err != nil {
					t.Fatalf("[%d] unexpected error in json.Unmarshal: %s", i, err)
					return err
				}
				return v
			},
		}

		templ := tpl.New()
		templ.Lookup("").Funcs(tweetFuncMap)

		p, _ := pageFromString(simplePage, "simple.md")
		cacheFileID := viper.GetString("CacheDir") + url.QueryEscape("https://api.twitter.com/1/statuses/oembed.json?id=666616452582129664")
		defer os.Remove(cacheFileID)
		output, err := HandleShortcodes(this.in, p, templ)

		matched, err := regexp.MatchString(this.expected, output)

		if err != nil {
			t.Fatalf("[%d] Regexp error", i)
		}

		if !matched {
			t.Errorf("[%d] unexpected rendering, got %s\n", i, output)
		}
	}
}
Example #21
0
func TestInnerSCWithAndWithoutMarkdown(t *testing.T) {
	tem := tpl.New()
	tem.AddInternalShortcode("inside.html", `<div{{with .Get "class"}} class="{{.}}"{{end}}>{{ .Inner }}</div>`)

	CheckShortCodeMatch(t, `{{% inside %}}
# More Here

[link](http://spf13.com) and text

{{% /inside %}}

And then:

{{< inside >}}
# More Here

This is **plain** text.

{{< /inside >}}
`, "<div><h1 id=\"more-here\">More Here</h1>\n\n<p><a href=\"http://spf13.com\">link</a> and text</p>\n</div>\n\nAnd then:\n\n<div>\n# More Here\n\nThis is **plain** text.\n\n</div>\n", tem)
}
func TestShortcodeFigure(t *testing.T) {
	for i, this := range []struct {
		in, expected string
	}{
		{
			`{{< figure src="/img/hugo-logo.png" >}}`,
			"(?s)^\n<figure >.*?<img src=\"/img/hugo-logo.png\" />.*?</figure>\n$",
		},
		{
			// set alt
			`{{< figure src="/img/hugo-logo.png" alt="Hugo logo" >}}`,
			"(?s)^\n<figure >.*?<img src=\"/img/hugo-logo.png\" alt=\"Hugo logo\" />.*?</figure>\n$",
		},
		// set title
		{
			`{{< figure src="/img/hugo-logo.png" title="Hugo logo" >}}`,
			"(?s)^\n<figure >.*?<img src=\"/img/hugo-logo.png\" />.*?<figcaption>.*?<h4>Hugo logo</h4>.*?</figcaption>.*?</figure>\n$",
		},
		// set attr and attrlink
		{
			`{{< figure src="/img/hugo-logo.png" attr="Hugo logo" attrlink="/img/hugo-logo.png" >}}`,
			"(?s)^\n<figure >.*?<img src=\"/img/hugo-logo.png\" />.*?<figcaption>.*?<p>.*?<a href=\"/img/hugo-logo.png\">.*?Hugo logo.*?</a>.*?</p>.*?</figcaption>.*?</figure>\n$",
		},
	} {
		templ := tpl.New()
		p, _ := pageFromString(simplePage, "simple.md")
		output, err := HandleShortcodes(this.in, p, templ)

		matched, err := regexp.MatchString(this.expected, output)

		if err != nil {
			t.Fatalf("[%d] Regexp error", i)
		}

		if !matched {
			t.Errorf("[%d] unexpected rendering, got %s\n", i, output)
		}
	}
}
Example #23
0
func (h *HAProxyGenerator) config(services []*types.Service) string {
	globalConfig, err := readExistingFile(h.c.TemplatePath)
	if err != nil {
		log.ErrorLog.Error("Unable to read config template. Stopping proxy config generator: %s", err)
		return ""
	}

	var out bytes.Buffer

	tpl, err := tpl.New().New("proxy").Parse(globalConfig)
	if err != nil {
		log.ErrorLog.Error("%s", err)
		return ""
	}

	err = tpl.Execute(&out, services)
	if err != nil {
		log.ErrorLog.Error("%s", err)
		return ""
	}

	return removeEmptyLines(out.String()) + "\n"
}
func TestShortcodeSpeakerdeck(t *testing.T) {
	for i, this := range []struct {
		in, expected string
	}{
		{
			`{{< speakerdeck 4e8126e72d853c0060001f97 >}}`,
			"(?s)^<script async class='speakerdeck-embed' data-id='4e8126e72d853c0060001f97'.*?>.*?</script>$",
		},
	} {
		templ := tpl.New()
		p, _ := pageFromString(simplePage, "simple.md")
		output, err := HandleShortcodes(this.in, p, templ)

		matched, err := regexp.MatchString(this.expected, output)

		if err != nil {
			t.Fatalf("[%d] Regexp error", i)
		}

		if !matched {
			t.Errorf("[%d] unexpected rendering, got %s\n", i, output)
		}
	}
}
Example #25
0
// Issue #929
func TestHyphenatedSC(t *testing.T) {
	tem := tpl.New()
	tem.AddInternalShortcode("hyphenated-video.html", `Playing Video {{ .Get 0 }}`)

	CheckShortCodeMatch(t, "{{< hyphenated-video 47238zzb >}}", "Playing Video 47238zzb", tem)
}
Example #26
0
func TestEmbeddedSC(t *testing.T) {
	tem := tpl.New()
	CheckShortCodeMatch(t, "{{% test %}}", "This is a simple Test", tem)
	CheckShortCodeMatch(t, `{{% figure src="/found/here" class="bananas orange" %}}`, "\n<figure class=\"bananas orange\">\n    \n        <img src=\"/found/here\" />\n    \n    \n</figure>\n", tem)
	CheckShortCodeMatch(t, `{{% figure src="/found/here" class="bananas orange" caption="This is a caption" %}}`, "\n<figure class=\"bananas orange\">\n    \n        <img src=\"/found/here\" alt=\"This is a caption\" />\n    \n    \n    <figcaption>\n        <p>\n        This is a caption\n        \n            \n        \n        </p> \n    </figcaption>\n    \n</figure>\n", tem)
}
Example #27
0
func TestFigureImgWidth(t *testing.T) {
	tem := tpl.New()
	CheckShortCodeMatch(t, `{{% figure src="/found/here" class="bananas orange" alt="apple" width="100px" %}}`, "\n<figure class=\"bananas orange\">\n    \n        <img src=\"/found/here\" alt=\"apple\" width=\"100px\" />\n    \n    \n</figure>\n", tem)
}
Example #28
0
func TestPositionalParamIndexOutOfBounds(t *testing.T) {
	tem := tpl.New()
	tem.AddInternalShortcode("video.html", `Playing Video {{ .Get 1 }}`)
	CheckShortCodeMatch(t, "{{< video 47238zzb >}}", "Playing Video error: index out of range for positional param at position 1", tem)
}
Example #29
0
func TestExtractShortcodes(t *testing.T) {
	for i, this := range []struct {
		name             string
		input            string
		expectShortCodes string
		expect           interface{}
		expectErrorMsg   string
	}{
		{"text", "Some text.", "map[]", "Some text.", ""},
		{"invalid right delim", "{{< tag }}", "", false, "simple:4:.*unrecognized character.*}"},
		{"invalid close", "\n{{< /tag >}}", "", false, "simple:5:.*got closing shortcode, but none is open"},
		{"invalid close2", "\n\n{{< tag >}}{{< /anotherTag >}}", "", false, "simple:6: closing tag for shortcode 'anotherTag' does not match start tag"},
		{"unterminated quote 1", `{{< figure src="im caption="S" >}}`, "", false, "simple:4:.got pos.*"},
		{"unterminated quote 1", `{{< figure src="im" caption="S >}}`, "", false, "simple:4:.*unterm.*}"},
		{"one shortcode, no markup", "{{< tag >}}", "", testScPlaceholderRegexp, ""},
		{"one shortcode, markup", "{{% tag %}}", "", testScPlaceholderRegexp, ""},
		{"one pos param", "{{% tag param1 %}}", `tag([\"param1\"], true){[]}"]`, testScPlaceholderRegexp, ""},
		{"two pos params", "{{< tag param1 param2>}}", `tag([\"param1\" \"param2\"], false){[]}"]`, testScPlaceholderRegexp, ""},
		{"one named param", `{{% tag param1="value" %}}`, `tag([\"param1:value\"], true){[]}`, testScPlaceholderRegexp, ""},
		{"two named params", `{{< tag param1="value1" param2="value2" >}}`, `tag([\"param1:value1\" \"param2:value2\"], false){[]}"]`,
			testScPlaceholderRegexp, ""},
		{"inner", `Some text. {{< inner >}}Inner Content{{< / inner >}}. Some more text.`, `inner([], false){[Inner Content]}`,
			fmt.Sprintf("Some text. %s. Some more text.", testScPlaceholderRegexp), ""},
		// issue #934
		{"inner self-closing", `Some text. {{< inner />}}. Some more text.`, `inner([], false){[]}`,
			fmt.Sprintf("Some text. %s. Some more text.", testScPlaceholderRegexp), ""},
		{"close, but not inner", "{{< tag >}}foo{{< /tag >}}", "", false, "Shortcode 'tag' in page 'simple.md' has no .Inner.*"},
		{"nested inner", `Inner->{{< inner >}}Inner Content->{{% inner2 param1 %}}inner2txt{{% /inner2 %}}Inner close->{{< / inner >}}<-done`,
			`inner([], false){[Inner Content-> inner2([\"param1\"], true){[inner2txt]} Inner close->]}`,
			fmt.Sprintf("Inner->%s<-done", testScPlaceholderRegexp), ""},
		{"nested, nested inner", `Inner->{{< inner >}}inner2->{{% inner2 param1 %}}inner2txt->inner3{{< inner3>}}inner3txt{{</ inner3 >}}{{% /inner2 %}}final close->{{< / inner >}}<-done`,
			`inner([], false){[inner2-> inner2([\"param1\"], true){[inner2txt->inner3 inner3(%!q(<nil>), false){[inner3txt]}]} final close->`,
			fmt.Sprintf("Inner->%s<-done", testScPlaceholderRegexp), ""},
		{"two inner", `Some text. {{% inner %}}First **Inner** Content{{% / inner %}} {{< inner >}}Inner **Content**{{< / inner >}}. Some more text.`,
			`map["{@{@HUGOSHORTCODE-1@}@}:inner([], true){[First **Inner** Content]}" "{@{@HUGOSHORTCODE-2@}@}:inner([], false){[Inner **Content**]}"]`,
			fmt.Sprintf("Some text. %s %s. Some more text.", testScPlaceholderRegexp, testScPlaceholderRegexp), ""},
		{"closed without content", `Some text. {{< inner param1 >}}{{< / inner >}}. Some more text.`, `inner([\"param1\"], false){[]}`,
			fmt.Sprintf("Some text. %s. Some more text.", testScPlaceholderRegexp), ""},
		{"two shortcodes", "{{< sc1 >}}{{< sc2 >}}",
			`map["{@{@HUGOSHORTCODE-1@}@}:sc1([], false){[]}" "{@{@HUGOSHORTCODE-2@}@}:sc2([], false){[]}"]`,
			testScPlaceholderRegexp + testScPlaceholderRegexp, ""},
		{"mix of shortcodes", `Hello {{< sc1 >}}world{{% sc2 p2="2"%}}. And that's it.`,
			`map["{@{@HUGOSHORTCODE-1@}@}:sc1([], false){[]}" "{@{@HUGOSHORTCODE-2@}@}:sc2([\"p2:2\"]`,
			fmt.Sprintf("Hello %sworld%s. And that's it.", testScPlaceholderRegexp, testScPlaceholderRegexp), ""},
		{"mix with inner", `Hello {{< sc1 >}}world{{% inner p2="2"%}}Inner{{%/ inner %}}. And that's it.`,
			`map["{@{@HUGOSHORTCODE-1@}@}:sc1([], false){[]}" "{@{@HUGOSHORTCODE-2@}@}:inner([\"p2:2\"], true){[Inner]}"]`,
			fmt.Sprintf("Hello %sworld%s. And that's it.", testScPlaceholderRegexp, testScPlaceholderRegexp), ""},
	} {

		p, _ := pageFromString(SIMPLE_PAGE, "simple.md")
		tem := tpl.New()
		tem.AddInternalShortcode("tag.html", `tag`)
		tem.AddInternalShortcode("sc1.html", `sc1`)
		tem.AddInternalShortcode("sc2.html", `sc2`)
		tem.AddInternalShortcode("inner.html", `{{with .Inner }}{{ . }}{{ end }}`)
		tem.AddInternalShortcode("inner2.html", `{{.Inner}}`)
		tem.AddInternalShortcode("inner3.html", `{{.Inner}}`)

		content, shortCodes, err := extractShortcodes(this.input, p, tem)

		if b, ok := this.expect.(bool); ok && !b {
			if err == nil {
				t.Fatalf("[%d] %s: ExtractShortcodes didn't return an expected error", i, this.name)
			} else {
				r, _ := regexp.Compile(this.expectErrorMsg)
				if !r.MatchString(err.Error()) {
					t.Fatalf("[%d] %s: ExtractShortcodes didn't return an expected error message, got %s but expected %s",
						i, this.name, err.Error(), this.expectErrorMsg)
				}
			}
			continue
		} else {
			if err != nil {
				t.Fatalf("[%d] %s: failed: %q", i, this.name, err)
			}
		}

		var expected string
		av := reflect.ValueOf(this.expect)
		switch av.Kind() {
		case reflect.String:
			expected = av.String()
		}

		r, err := regexp.Compile(expected)

		if err != nil {
			t.Fatalf("[%d] %s: Failed to compile regexp %q: %q", i, this.name, expected, err)
		}

		if strings.Count(content, shortcodePlaceholderPrefix) != len(shortCodes) {
			t.Fatalf("[%d] %s: Not enough placeholders, found %d", i, this.name, len(shortCodes))
		}

		if !r.MatchString(content) {
			t.Fatalf("[%d] %s: Shortcode extract didn't match. got %q but expected %q", i, this.name, content, expected)
		}

		for placeHolder, sc := range shortCodes {
			if !strings.Contains(content, placeHolder) {
				t.Fatalf("[%d] %s: Output does not contain placeholder %q", i, this.name, placeHolder)
			}

			if sc.params == nil {
				t.Fatalf("[%d] %s: Params is nil for shortcode '%s'", i, this.name, sc.name)
			}
		}

		if this.expectShortCodes != "" {
			shortCodesAsStr := fmt.Sprintf("map%q", collectAndSortShortcodes(shortCodes))
			if !strings.Contains(shortCodesAsStr, this.expectShortCodes) {
				t.Fatalf("[%d] %s: Short codes not as expected, got %s but expected %s", i, this.name, shortCodesAsStr, this.expectShortCodes)
			}
		}
	}
}
Example #30
0
func TestNonSC(t *testing.T) {
	tem := tpl.New()
	// notice the syntax diff from 0.12, now comment delims must be added
	CheckShortCodeMatch(t, "{{%/* movie 47238zzb */%}}", "{{% movie 47238zzb %}}", tem)
}