From b20fb7da17d79a51a845ff97755dd4a6978c0296 Mon Sep 17 00:00:00 2001 From: Stefan Martinov Date: Mon, 24 Aug 2020 14:35:19 +0200 Subject: [PATCH] feat: add update request queue test --- repo/loader_test.go | 65 +++++++++++++++++++++++++++++++++++++++++++++ repo/repo.go | 2 +- 2 files changed, 66 insertions(+), 1 deletion(-) create mode 100644 repo/loader_test.go diff --git a/repo/loader_test.go b/repo/loader_test.go new file mode 100644 index 0000000..682034b --- /dev/null +++ b/repo/loader_test.go @@ -0,0 +1,65 @@ +package repo + +import ( + "testing" + "time" + + "github.com/stretchr/testify/assert" +) + +var ( + updateDuration = 5 * time.Millisecond +) + +func TestRepo_tryUpdate(t *testing.T) { + repo := &Repo{ + updateInProgressChannel: make(chan chan updateResponse, 1), + } + + executed := make(chan time.Time, 4) + + // Consumer For Updates + go func() { + for { + res := <-repo.updateInProgressChannel + now := time.Now() + executed <- now + time.Sleep(updateDuration) + res <- updateResponse{now.UnixNano(), nil} + } + }() + + update := func(index int, expectError bool) { + go func() { + _, err := repo.tryUpdate() + assert.Equal(t, expectError, err != nil, "Error in request %d", index) + }() + } + + // First one is being executed + update(0, false) + time.Sleep(1 * time.Millisecond) + assert.Equal(t, 1, len(executed)) + + // Second one is being queued + update(1, false) + time.Sleep(1 * time.Millisecond) + assert.Equal(t, 1, len(executed)) + + // Last one gets "Accepted" + time.Sleep(1 * time.Millisecond) + lastUpdateRequest := time.Now() + update(2, true) + assert.Equal(t, 1, len(executed)) + + <-executed // Dump first execution time + + // Second execution should be done after given sleep time + time.Sleep(updateDuration) + assert.Equal(t, 1, len(executed)) + lastUpdate := <-executed + assert.True(t, lastUpdate.After(lastUpdateRequest)) + + // When all requests are complete, allow queueing up again + update(3, false) +} diff --git a/repo/repo.go b/repo/repo.go index 7bf302b..fec6c4d 100644 --- a/repo/repo.go +++ b/repo/repo.go @@ -62,7 +62,7 @@ func NewRepo(server string, varDir string) *Repo { history: newHistory(varDir), dimensionUpdateChannel: make(chan *repoDimension), dimensionUpdateDoneChannel: make(chan error), - updateInProgressChannel: make(chan chan updateResponse, 0), + updateInProgressChannel: make(chan chan updateResponse, 1), } go repo.updateRoutine()