Add tests for ImageToCache/Daemon that they prevent multiple downloads.

pull/11223/head
Andriy Dzikh 2021-04-28 13:49:33 -07:00
parent dba9076cc3
commit 458d1d5102
2 changed files with 64 additions and 2 deletions

View File

@ -130,3 +130,61 @@ func TestPreloadDownloadPreventsMultipleDownload(t *testing.T) {
t.Errorf("Wrong number of downloads occurred. Actual: %v, Expected: 1", tlog.downloads)
}
}
func TestImageToCache(t *testing.T) {
EnableMock(true)
defer EnableMock(false)
tlog := &mockLogger{downloads: 0, t: t}
klog.SetLogger(tlog)
defer klog.SetLogger(nil)
checkImageExistsInCache = func(img string) bool { return tlog.downloads > 0 }
var group sync.WaitGroup
group.Add(2)
dlCall := func() {
if err := ImageToCache("testimg"); err != nil {
t.Errorf("Failed to download preload: %+v", err)
}
group.Done()
}
go dlCall()
go dlCall()
group.Wait()
if tlog.downloads != 1 {
t.Errorf("Wrong number of downloads occurred. Actual: %v, Expected: 1", tlog.downloads)
}
}
func TestImageToDaemon(t *testing.T) {
EnableMock(true)
defer EnableMock(false)
tlog := &mockLogger{downloads: 0, t: t}
klog.SetLogger(tlog)
defer klog.SetLogger(nil)
checkImageExistsInCache = func(img string) bool { return tlog.downloads > 0 }
var group sync.WaitGroup
group.Add(2)
dlCall := func() {
if err := ImageToCache("testimg"); err != nil {
t.Errorf("Failed to download preload: %+v", err)
}
group.Done()
}
go dlCall()
go dlCall()
group.Wait()
if tlog.downloads != 1 {
t.Errorf("Wrong number of downloads occurred. Actual: %v, Expected: 1", tlog.downloads)
}
}

View File

@ -60,6 +60,8 @@ func ImageExistsInCache(img string) bool {
return false
}
var checkImageExistsInCache = ImageExistsInCache
// ImageExistsInDaemon if img exist in local docker daemon
func ImageExistsInDaemon(img string) bool {
// Check if image exists locally
@ -75,9 +77,11 @@ func ImageExistsInDaemon(img string) bool {
return false
}
var checkImageExistsInDaemon = ImageExistsInDaemon
// ImageToCache writes img to the local cache directory
func ImageToCache(img string) error {
if ImageExistsInCache(img) {
if checkImageExistsInCache(img) {
klog.Infof("%s exists in cache, skipping pull", img)
return nil
}
@ -154,7 +158,7 @@ func ImageToCache(img string) error {
// ImageToDaemon writes img to the local docker daemon
func ImageToDaemon(img string) error {
if ImageExistsInDaemon(img) {
if checkImageExistsInDaemon(img) {
klog.Infof("%s exists in daemon, skipping pull", img)
return nil
}