From a4b3d8e5246c848a66cc27013e6aeb22d1660da2 Mon Sep 17 00:00:00 2001 From: Smirnov Oleksandr Date: Thu, 3 Oct 2024 22:31:39 +0300 Subject: [PATCH] refactor(mailer): add mutex to testing mailer, to avoid race-conditions (#27) --- internal/mailer/testing_mailer.go | 20 +++++++++++++++++--- 1 file changed, 17 insertions(+), 3 deletions(-) diff --git a/internal/mailer/testing_mailer.go b/internal/mailer/testing_mailer.go index a88b1a3f..433f8fa6 100644 --- a/internal/mailer/testing_mailer.go +++ b/internal/mailer/testing_mailer.go @@ -1,10 +1,15 @@ package mailer -import "context" +import ( + "context" + "sync" +) var _ Mailer = (*TestMailer)(nil) type TestMailer struct { + mu sync.Mutex + emails map[string]string } @@ -12,17 +17,26 @@ type TestMailer struct { // that implementation of Mailer stores all sent email in memory // to get the last email sent to a specific email use GetLastSentEmailToEmail func NewTestMailer() *TestMailer { - return &TestMailer{ + return &TestMailer{ //nolint:exhaustruct emails: make(map[string]string), } } func (t *TestMailer) Send(_ context.Context, to, _, content string) error { + t.mu.Lock() + defer t.mu.Unlock() + t.emails[to] = content + return nil } // GetLastSentEmailToEmail returns the last email sent to a specific email func (t *TestMailer) GetLastSentEmailToEmail(email string) string { - return t.emails[email] + t.mu.Lock() + defer t.mu.Unlock() + + e := t.emails[email] + + return e }