notify_test.go 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. // Copyright 2019 Yunion
  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. // http://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. package notifyclient
  15. import (
  16. "html/template"
  17. "strings"
  18. "testing"
  19. "yunion.io/x/jsonutils"
  20. )
  21. func TestNotifyTemplate(t *testing.T) {
  22. cases := []struct {
  23. template string
  24. data interface{}
  25. want string
  26. }{
  27. {
  28. `云主机{{ .name }}创建成功`,
  29. struct {
  30. Name string
  31. }{
  32. Name: "testsrv-1",
  33. },
  34. `云主机testsrv-1创建成功`,
  35. },
  36. {
  37. `您的云主机{{ .name }}已经创建成功,服务器IP地址为{{ .ips }},{{ if .account }}初始帐号为{{ .account }},{{ end }}{{ if .keypair }}访问密钥为{{ .keypair }},{{ end }}{{ if len .password }}初始密码为{{ .password }},{{ end }}请使用{{ if .windows }}远程桌面连接器(RDC){{ else }}SSH{{ end }}或控制面板控制台访问云主机。`,
  38. struct {
  39. Name string
  40. Ips string
  41. Account string
  42. Keypair string
  43. Password string
  44. Windows bool
  45. }{
  46. Name: "testsrv-1",
  47. Ips: "10.168.222.23",
  48. Account: "root",
  49. Password: "1234567",
  50. Windows: false,
  51. },
  52. `您的云主机testsrv-1已经创建成功,服务器IP地址为10.168.222.23,初始帐号为root,初始密码为1234567,请使用SSH或控制面板控制台访问云主机。`,
  53. },
  54. }
  55. for _, c := range cases {
  56. temp, err := template.New("template").Parse(c.template)
  57. if err != nil {
  58. t.Errorf("parse template %s fail %s", c.template, err)
  59. } else {
  60. strBuild := strings.Builder{}
  61. jsonData := jsonutils.Marshal(c.data)
  62. t.Logf("jsonData: %s", jsonData)
  63. err = temp.Execute(&strBuild, jsonData.Interface())
  64. if err != nil {
  65. t.Errorf("execute template fail %s", err)
  66. } else {
  67. if strBuild.String() != c.want {
  68. t.Errorf("fail: got %s want %s", strBuild.String(), c.want)
  69. }
  70. }
  71. }
  72. }
  73. }