github.com/decred/politeia@v1.4.0/politeiawww/legacy/user/mailtest.go (about)

     1  // Copyright (c) 2021 The Decred developers
     2  // Use of this source code is governed by an ISC
     3  // license that can be found in the LICENSE file.
     4  
     5  package user
     6  
     7  import (
     8  	"sync"
     9  
    10  	"github.com/google/uuid"
    11  )
    12  
    13  // testMailerDB implements the MailerDB interface that is used for testing
    14  // purposes. It saves and retrieves data in memory to emulate the behaviour
    15  // needed to test the mail package.
    16  type testMailerDB struct {
    17  	sync.RWMutex
    18  
    19  	Histories map[uuid.UUID]EmailHistory
    20  }
    21  
    22  // NewTestMailerDB returns a new testMailerDB. The caller can optionally
    23  // provide a list of email histories to seed the testMailerDB with on
    24  // intialization.
    25  func NewTestMailerDB(histories map[uuid.UUID]EmailHistory) *testMailerDB {
    26  	if histories == nil {
    27  		histories = make(map[uuid.UUID]EmailHistory, 1024)
    28  	}
    29  	return &testMailerDB{
    30  		Histories: histories,
    31  	}
    32  }
    33  
    34  // EmailHistoriesSave implements the save function using the in memory cache
    35  // for testing purposes.
    36  //
    37  // This function satisfies the MailerDB interface.
    38  func (m *testMailerDB) EmailHistoriesSave(histories map[uuid.UUID]EmailHistory) error {
    39  	m.Lock()
    40  	defer m.Unlock()
    41  
    42  	for email, history := range histories {
    43  		m.Histories[email] = history
    44  	}
    45  
    46  	return nil
    47  }
    48  
    49  // EmailHistoriesGet implements the get function for the in memory cache used
    50  // for testing purposes.
    51  //
    52  // This function satisfies the MailerDB interface.
    53  func (m *testMailerDB) EmailHistoriesGet(users []uuid.UUID) (map[uuid.UUID]EmailHistory, error) {
    54  	m.RLock()
    55  	defer m.RUnlock()
    56  
    57  	histories := make(map[uuid.UUID]EmailHistory, len(users))
    58  	for _, userID := range users {
    59  		h, ok := m.Histories[userID]
    60  		if !ok {
    61  			// User email history does not exist, skip adding this
    62  			// entry to the returned user email history map.
    63  			continue
    64  		}
    65  		histories[userID] = h
    66  	}
    67  	return histories, nil
    68  }