shithub: hugo

Download patch

ref: 4dcb63c2f65608e443aaf99c16019cd1757ee49e
parent: 0a8583a4510de749dbc69de9b00eceaedfc0c9c4
author: Bjørn Erik Pedersen <[email protected]>
date: Sun Feb 7 10:15:27 EST 2016

tpl: Add highlight test

--- a/tpl/template_funcs.go
+++ b/tpl/template_funcs.go
@@ -1132,15 +1132,14 @@
 }
 
 // highlight returns an HTML string with syntax highlighting applied.
-func highlight(in interface{}, lang, opts string) template.HTML {
-	var str string
-	av := reflect.ValueOf(in)
-	switch av.Kind() {
-	case reflect.String:
-		str = av.String()
+func highlight(in interface{}, lang, opts string) (template.HTML, error) {
+	str, err := cast.ToStringE(in)
+
+	if err != nil {
+		return "", err
 	}
 
-	return template.HTML(helpers.Highlight(html.UnescapeString(str), lang, opts))
+	return template.HTML(helpers.Highlight(html.UnescapeString(str), lang, opts)), nil
 }
 
 var markdownTrimPrefix = []byte("<p>")
--- a/tpl/template_funcs_test.go
+++ b/tpl/template_funcs_test.go
@@ -25,6 +25,7 @@
 	"path"
 	"reflect"
 	"runtime"
+	"strings"
 	"testing"
 	"time"
 )
@@ -1530,6 +1531,26 @@
 		if err == nil {
 			t.Errorf("Chomp should fail")
 		}
+	}
+}
+
+func TestHighlight(t *testing.T) {
+	code := "func boo() {}"
+	highlighted, err := highlight(code, "go", "")
+
+	if err != nil {
+		t.Fatal("Highlight returned error:", err)
+	}
+
+	// this depends on a Pygments installation, but will always contain the function name.
+	if !strings.Contains(string(highlighted), "boo") {
+		t.Errorf("Highlight mismatch,  got %v", highlighted)
+	}
+
+	_, err = highlight(t, "go", "")
+
+	if err == nil {
+		t.Error("Expected highlight error")
 	}
 }