Files
trivy/internal/app_test.go
Teppei Fukuda ac5f313129 feat(db): store metadata as a file (#464)
* refactor: wrap errors

* feat(db): add the metadata file

* test(db): re-generate mocks

* fix(app): read metadata from the file in showVersion

* fix: open the database after downloading it

* fix(operation): use UpdateMetadata

* chore(mod): update dependency

* test(integration): fix tests

* fix(conf): rename TRIVY_NONSSL to TRIVY_NON_SSL
2020-04-15 16:07:42 +03:00

109 lines
2.3 KiB
Go

package internal
import (
"bytes"
"io/ioutil"
"os"
"path/filepath"
"testing"
"time"
"github.com/stretchr/testify/require"
dbFile "github.com/aquasecurity/trivy/pkg/db"
"github.com/spf13/afero"
"github.com/aquasecurity/trivy-db/pkg/db"
"github.com/stretchr/testify/assert"
)
func Test_showVersion(t *testing.T) {
type args struct {
cacheDir string
outputFormat string
version string
}
tests := []struct {
name string
args args
createDB bool
expectedOutput string
}{
{
name: "happy path, table output",
args: args{
outputFormat: "table",
version: "v1.2.3",
},
expectedOutput: `Version: v1.2.3
Vulnerability DB:
Type: Light
Version: 42
UpdatedAt: 2020-03-16 23:40:20 +0000 UTC
NextUpdate: 2020-03-16 23:57:00 +0000 UTC
`,
createDB: true,
},
{
name: "happy path, JSON output",
args: args{
outputFormat: "json",
version: "1.2.3",
},
expectedOutput: `{"Version":"1.2.3","VulnerabilityDB":{"Version":42,"Type":1,"NextUpdate":"2020-03-16T23:57:00Z","UpdatedAt":"2020-03-16T23:40:20Z"}}
`,
createDB: true,
},
{
name: "sad path, no DB is available",
args: args{
outputFormat: "json",
version: "1.2.3",
},
expectedOutput: `{"Version":"1.2.3"}
`,
},
{
name: "sad path, bogus cache dir",
args: args{
outputFormat: "json",
version: "1.2.3",
cacheDir: "/foo/bar/bogus",
},
expectedOutput: `{"Version":"1.2.3"}
`,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
var cacheDir string
switch {
case tt.args.cacheDir != "":
cacheDir = tt.args.cacheDir
default:
cacheDir, _ = ioutil.TempDir("", "Test_showVersion-*")
defer os.RemoveAll(cacheDir)
}
if tt.createDB {
m := dbFile.NewMetadata(afero.NewOsFs(), cacheDir)
err := os.MkdirAll(filepath.Join(cacheDir, "db"), os.ModePerm)
require.NoError(t, err)
err = m.Store(db.Metadata{
Version: 42,
Type: 1,
NextUpdate: time.Unix(1584403020, 0),
UpdatedAt: time.Unix(1584402020, 0),
})
require.NoError(t, err)
}
fw := new(bytes.Buffer)
showVersion(cacheDir, tt.args.outputFormat, tt.args.version, fw)
assert.Equal(t, tt.expectedOutput, fw.String(), tt.name)
})
}
}