github.com/pf-qiu/concourse/v6@v6.7.3-0.20201207032516-1f455d73275f/atc/api/accessor/teams_cacher_test.go (about)

     1  package accessor_test
     2  
     3  import (
     4  	"time"
     5  
     6  	"code.cloudfoundry.org/lager"
     7  	"github.com/pf-qiu/concourse/v6/atc/api/accessor"
     8  	"github.com/pf-qiu/concourse/v6/atc/api/accessor/accessorfakes"
     9  
    10  	"github.com/pf-qiu/concourse/v6/atc/db"
    11  	"github.com/pf-qiu/concourse/v6/atc/db/dbfakes"
    12  	. "github.com/onsi/ginkgo"
    13  	. "github.com/onsi/gomega"
    14  )
    15  
    16  var _ = Describe("TeamsCacher", func() {
    17  	var (
    18  		fakeNotifications *accessorfakes.FakeNotifications
    19  		fakeTeamFactory   *dbfakes.FakeTeamFactory
    20  		fetchedTeams      []db.Team
    21  		fakeTeam          *dbfakes.FakeTeam
    22  
    23  		teamFetcher accessor.TeamFetcher
    24  		notifier    chan bool
    25  		teams       []db.Team
    26  		err         error
    27  	)
    28  
    29  	BeforeEach(func() {
    30  		fakeTeam = new(dbfakes.FakeTeam)
    31  		teams = []db.Team{fakeTeam}
    32  
    33  		notifier = make(chan bool, 1)
    34  		fakeNotifications = new(accessorfakes.FakeNotifications)
    35  		fakeNotifications.ListenReturns(notifier, nil)
    36  		fakeTeamFactory = new(dbfakes.FakeTeamFactory)
    37  		fakeTeamFactory.GetTeamsReturns(teams, nil)
    38  	})
    39  
    40  	JustBeforeEach(func() {
    41  		teamFetcher = accessor.NewTeamsCacher(lager.NewLogger("test"), fakeNotifications, fakeTeamFactory, time.Minute, time.Minute)
    42  		fetchedTeams, err = teamFetcher.GetTeams()
    43  		Expect(err).NotTo(HaveOccurred())
    44  	})
    45  
    46  	Context("when there is no cache found", func() {
    47  		It("fetch teams from DB once", func() {
    48  			Expect(fakeTeamFactory.GetTeamsCallCount()).To(Equal(1))
    49  			Expect(fetchedTeams).To(Equal(teams))
    50  		})
    51  	})
    52  
    53  	Context("when there is cache found", func() {
    54  		JustBeforeEach(func() {
    55  			fetchedTeams, err = teamFetcher.GetTeams()
    56  			Expect(err).NotTo(HaveOccurred())
    57  		})
    58  
    59  		It("does not fetch teams from DB again but read it from cache", func() {
    60  			Expect(fakeTeamFactory.GetTeamsCallCount()).To(Equal(1))
    61  			Expect(fetchedTeams).To(Equal(teams))
    62  		})
    63  	})
    64  
    65  	Context("when it receives a notification", func() {
    66  		JustBeforeEach(func() {
    67  			notifier <- true
    68  			time.Sleep(time.Second)
    69  		})
    70  
    71  		It("fetch teams again from DB since cache is deleted", func() {
    72  			fetchedTeams, err = teamFetcher.GetTeams()
    73  			Eventually(fakeTeamFactory.GetTeamsCallCount()).Should(Equal(2))
    74  		})
    75  	})
    76  })