Skip to content

Building 70 Projects ranging from beginner to advanced so anyone can — learn from, build upon, use as a reference, or even copy directly. Owned by my cybersecurity company 👇

2.4 KB
Raw Blame
// ©AngelaMos | 2026
// cache_test.go

package vuln

import (
	"path/filepath"
	"testing"
	"time"

	"github.com/CarterPerez-dev/bomber/pkg/types"
	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
)

func TestCachePutGet(t *testing.T) {
	dbPath := filepath.Join(t.TempDir(), "test.db")
	cache, err := NewCache(dbPath, 24*time.Hour)
	require.NoError(t, err)
	defer func() { _ = cache.Close() }()

	matches := []types.VulnMatch{
		{
			Package:       types.Package{PURL: "pkg:golang/[email protected]"},
			Vulnerability: types.Vulnerability{ID: "CVE-2024-1234", Source: "osv"},
		},
	}

	require.NoError(t, cache.Put("pkg:golang/[email protected]", "osv", matches))

	got, ok, err := cache.Get("pkg:golang/[email protected]", "osv")
	require.NoError(t, err)
	assert.True(t, ok)
	assert.Len(t, got, 1)
	assert.Equal(t, "CVE-2024-1234", got[0].Vulnerability.ID)
}

func TestCacheExpiry(t *testing.T) {
	dbPath := filepath.Join(t.TempDir(), "test.db")
	cache, err := NewCache(dbPath, 1*time.Millisecond)
	require.NoError(t, err)
	defer func() { _ = cache.Close() }()

	matches := []types.VulnMatch{
		{
			Package:       types.Package{PURL: "pkg:golang/[email protected]"},
			Vulnerability: types.Vulnerability{ID: "CVE-2024-1234", Source: "osv"},
		},
	}

	require.NoError(t, cache.Put("pkg:golang/[email protected]", "osv", matches))
	time.Sleep(5 * time.Millisecond)

	_, ok, err := cache.Get("pkg:golang/[email protected]", "osv")
	require.NoError(t, err)
	assert.False(t, ok)
}

func TestCacheMiss(t *testing.T) {
	dbPath := filepath.Join(t.TempDir(), "test.db")
	cache, err := NewCache(dbPath, 24*time.Hour)
	require.NoError(t, err)
	defer func() { _ = cache.Close() }()

	_, ok, err := cache.Get("pkg:golang/[email protected]", "osv")
	require.NoError(t, err)
	assert.False(t, ok)
}

func TestCacheOverwrite(t *testing.T) {
	dbPath := filepath.Join(t.TempDir(), "test.db")
	cache, err := NewCache(dbPath, 24*time.Hour)
	require.NoError(t, err)
	defer func() { _ = cache.Close() }()

	old := []types.VulnMatch{
		{Vulnerability: types.Vulnerability{ID: "CVE-OLD"}},
	}
	require.NoError(t, cache.Put("pkg:[email protected]", "osv", old))

	updated := []types.VulnMatch{
		{Vulnerability: types.Vulnerability{ID: "CVE-NEW"}},
	}
	require.NoError(t, cache.Put("pkg:[email protected]", "osv", updated))

	got, ok, err := cache.Get("pkg:[email protected]", "osv")
	require.NoError(t, err)
	assert.True(t, ok)
	assert.Equal(t, "CVE-NEW", got[0].Vulnerability.ID)
}