package server import ( "fmt" "io/ioutil" "os" "testing" "git.ctrlz.es/mgdelacroix/birthdaybot/client" "git.ctrlz.es/mgdelacroix/birthdaybot/model" "git.ctrlz.es/mgdelacroix/birthdaybot/notification" notification_mocks "git.ctrlz.es/mgdelacroix/birthdaybot/notification/mocks" server_mocks "git.ctrlz.es/mgdelacroix/birthdaybot/server/mocks" "github.com/charmbracelet/log" "github.com/golang/mock/gomock" "github.com/stretchr/testify/require" ) type TestHelper struct { t *testing.T ctrl *gomock.Controller mockNotificationService *notification_mocks.MockNotificationService mockWorker *server_mocks.MockWorker srv *Server client *client.Client } func testConfig(t *testing.T) *model.Config { f, err := ioutil.TempFile("", "birthdaybot-") require.NoError(t, err) require.NoError(t, f.Close()) require.NoError(t, os.Remove(f.Name())) return &model.Config{ Web: &model.WebConfig{Enabled: true, Port: 0}, Birthdays: &model.BirthdaysConfig{File: f.Name()}, } } func SetupTestHelper(t *testing.T, opts ...Option) *TestHelper { th := &TestHelper{t: t} th.ctrl = gomock.NewController(t) th.mockNotificationService = notification_mocks.NewMockNotificationService(th.ctrl) notificationServices := []notification.NotificationService{th.mockNotificationService} th.mockWorker = server_mocks.NewMockWorker(th.ctrl) workers := []Worker{th.mockWorker} th.mockWorker.EXPECT().Start().Times(1) th.mockWorker.EXPECT().Stop().Times(1) birthdays := []*model.Birthday{ { Name: "John", Email: "john@doe.com", Phone: "1234", YearOfBirth: 2022, MonthOfBirth: 1, DayOfBirth: 1, }, } serverOpts := append([]Option{ WithConfig(testConfig(t)), WithLogger(log.New(os.Stderr)), WithBirthdays(birthdays), WithNotificationServices(notificationServices), WithWorkers(workers), }, opts...) var err error th.srv, err = New(serverOpts...) require.NoError(t, err) th.srv.Start() client, err := client.New(client.WithURL(fmt.Sprintf("http://127.0.0.1:%d", th.srv.WebServer.Port()))) require.NoError(t, err) th.client = client return th } func (th *TestHelper) TearDown() { th.srv.Stop() th.ctrl.Finish() }