92 lines
2.5 KiB
Go
92 lines
2.5 KiB
Go
package server
|
|
|
|
import (
|
|
"bytes"
|
|
"errors"
|
|
"fmt"
|
|
"os"
|
|
"testing"
|
|
"time"
|
|
|
|
"git.ctrlz.es/mgdelacroix/birthdaybot/model"
|
|
"github.com/stretchr/testify/require"
|
|
)
|
|
|
|
func TestNotify(t *testing.T) {
|
|
th := SetupTestHelper(t)
|
|
defer th.TearDown()
|
|
t.Run("should correctly use the notification services to notify", func(t *testing.T) {
|
|
birthday := th.srv.birthdays[0]
|
|
th.mockNotificationService.
|
|
EXPECT().
|
|
Notify(birthday, nil).
|
|
Return(nil).
|
|
Times(1)
|
|
|
|
err := th.srv.Notify(birthday)
|
|
require.NoError(t, err)
|
|
})
|
|
|
|
t.Run("should return an error if a service fails", func(t *testing.T) {
|
|
mockErr := errors.New("failed to notify")
|
|
birthday := th.srv.birthdays[0]
|
|
th.mockNotificationService.
|
|
EXPECT().
|
|
Notify(birthday, nil).
|
|
Return(mockErr).
|
|
Times(1)
|
|
|
|
err := th.srv.Notify(birthday)
|
|
require.ErrorIs(t, err, mockErr)
|
|
})
|
|
}
|
|
|
|
func TestTemplate(t *testing.T) {
|
|
t.Run("template should work with birthday data", func(t *testing.T) {
|
|
// create a template file and populate it
|
|
f, err := os.CreateTemp("", "birthdaybot-config-")
|
|
require.NoError(t, err)
|
|
_, werr := fmt.Fprint(f, "My name is {{.Name}}")
|
|
require.NoError(t, werr)
|
|
require.NoError(t, f.Close())
|
|
|
|
// create a test config and set the template
|
|
config := testConfig(t)
|
|
config.Birthdays.Template = f.Name()
|
|
|
|
// create the test helper with the custom config
|
|
th := SetupTestHelper(t, WithConfig(config))
|
|
defer th.TearDown()
|
|
|
|
birthday := &model.Birthday{Name: "Jane Doe"}
|
|
expectedString := "My name is Jane Doe"
|
|
|
|
var stringBuffer bytes.Buffer
|
|
require.NoError(t, th.srv.tmpl.Execute(&stringBuffer, birthday))
|
|
require.Equal(t, expectedString, stringBuffer.String())
|
|
})
|
|
|
|
t.Run("template should work with custom functions", func(t *testing.T) {
|
|
// create a template file and populate it
|
|
f, err := os.CreateTemp("", "birthdaybot-config-")
|
|
require.NoError(t, err)
|
|
_, werr := fmt.Fprint(f, "I'm getting {{getYearsOld .YearOfBirth}} years old")
|
|
require.NoError(t, werr)
|
|
require.NoError(t, f.Close())
|
|
|
|
// create a test config and set the template
|
|
config := testConfig(t)
|
|
config.Birthdays.Template = f.Name()
|
|
|
|
// create the test helper with the custom config
|
|
th := SetupTestHelper(t, WithConfig(config))
|
|
defer th.TearDown()
|
|
|
|
birthday := &model.Birthday{YearOfBirth: 1980}
|
|
expectedString := fmt.Sprintf("I'm getting %d years old", time.Now().Year()-birthday.YearOfBirth)
|
|
|
|
var stringBuffer bytes.Buffer
|
|
require.NoError(t, th.srv.tmpl.Execute(&stringBuffer, birthday))
|
|
require.Equal(t, expectedString, stringBuffer.String())
|
|
})
|
|
}
|