github.com/masterhung0112/hk_server/v5@v5.0.0-20220302090640-ec71aef15e1c/shared/i18n/i18n_test.go (about)

     1  // Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
     2  // See LICENSE.txt for license information.
     3  
     4  package i18n
     5  
     6  import (
     7  	"testing"
     8  
     9  	"github.com/mattermost/go-i18n/i18n/bundle"
    10  	"github.com/mattermost/go-i18n/i18n/language"
    11  	"github.com/mattermost/go-i18n/i18n/translation"
    12  	"github.com/stretchr/testify/assert"
    13  )
    14  
    15  var htmlTestTranslationBundle *bundle.Bundle
    16  
    17  func init() {
    18  	htmlTestTranslationBundle = bundle.New()
    19  	fooBold, _ := translation.NewTranslation(map[string]interface{}{
    20  		"id":          "foo.bold",
    21  		"translation": "<p>[[{{ .Foo }}]]</p>",
    22  	})
    23  	htmlTestTranslationBundle.AddTranslation(&language.Language{Tag: "en"}, fooBold)
    24  }
    25  
    26  func TestTranslateAsHTML(t *testing.T) {
    27  	assert.EqualValues(t, "<p><strong>&lt;i&gt;foo&lt;/i&gt;</strong></p>", TranslateAsHTML(TranslateFunc(htmlTestTranslationBundle.MustTfunc("en")), "foo.bold", map[string]interface{}{
    28  		"Foo": "<i>foo</i>",
    29  	}))
    30  }
    31  
    32  func TestEscapeForHTML(t *testing.T) {
    33  	stringForPointer := "<b>abc</b>"
    34  	for name, tc := range map[string]struct {
    35  		In       interface{}
    36  		Expected interface{}
    37  	}{
    38  		"NoHTML": {
    39  			In:       "abc",
    40  			Expected: "abc",
    41  		},
    42  		"String": {
    43  			In:       "<b>abc</b>",
    44  			Expected: "&lt;b&gt;abc&lt;/b&gt;",
    45  		},
    46  		"StringPointer": {
    47  			In:       &stringForPointer,
    48  			Expected: "&lt;b&gt;abc&lt;/b&gt;",
    49  		},
    50  		"Map": {
    51  			In: map[string]interface{}{
    52  				"abc": "abc",
    53  				"123": "<b>123</b>",
    54  			},
    55  			Expected: map[string]interface{}{
    56  				"abc": "abc",
    57  				"123": "&lt;b&gt;123&lt;/b&gt;",
    58  			},
    59  		},
    60  		"Unsupported": {
    61  			In:       struct{ string }{"<b>abc</b>"},
    62  			Expected: "",
    63  		},
    64  	} {
    65  		t.Run(name, func(t *testing.T) {
    66  			assert.Equal(t, tc.Expected, escapeForHTML(tc.In))
    67  		})
    68  	}
    69  }