package nvdmirror import ( "fmt" "os" "net/http" "path/filepath" "testing" ) // serve on given port func serve(port int, ch chan bool) { s := http.Server { Addr: fmt.Sprintf(":%d", port), Handler: http.FileServer(http.Dir("testdata/files")), } go (func() { // block on channel _ = <-ch // shut down server s.Close() })() // start server s.ListenAndServe() } // close server immediately func stopServer(ch chan bool) { ch <- false } func TestSync(t *testing.T) { // port := 8888 ch := make(chan bool) defer stopServer(ch) // spin up local server go serve(port, ch) // create temp dir dir, err := os.MkdirTemp("", "") if err != nil { t.Error(err) return } defer os.RemoveAll(dir) // dir = "testdata/out" // create cache cache, err := NewJsonCache(filepath.Join(dir, "cache.json.gz")) if err != nil { t.Error(err) return } defer cache.Close() // custom sync config // FIXME: stand up custom server for this config := SyncConfig { Cve11BaseUrl: fmt.Sprintf("http://localhost:%d", port), } // sync data t.Run("initial", func(t *testing.T) { if err := Sync(config, &cache, dir); err != nil { t.Error(err) } }) // sync data again (to test caching) t.Run("caching", func(t *testing.T) { if err := Sync(config, &cache, dir); err != nil { t.Error(err) } }) // sync w/ missing dir t.Run("missingDir", func(t *testing.T) { missingDir := filepath.Join(dir, "does/not/exist") if err := Sync(config, &cache, missingDir); err != nil { t.Error(err) } }) // sync w/ bad cache t.Run("failSetCache", func(t *testing.T) { var cache FailSetCache if err := Sync(config, &cache, dir); err == nil { t.Error(err) } }) t.Run("customUserAgent", func(t *testing.T) { // custom sync config // FIXME: stand up custom server for this config := SyncConfig { Cve11BaseUrl: fmt.Sprintf("http://localhost:%d", port), UserAgent: "custom-user-agent/0.0.0", } if err := Sync(config, &cache, dir); err != nil { t.Error(err) } }) t.Run("clientFail", func(t *testing.T) { // custom sync config // FIXME: stand up custom server for this config := SyncConfig { Cve11BaseUrl: "http://localhost:0", } if err := Sync(config, &cache, dir); err != nil { t.Error(err) } }) } func TestBadUrls(t *testing.T) { // create temp dir dir, err := os.MkdirTemp("", "") if err != nil { t.Error(err) return } defer os.RemoveAll(dir) // create cache cache, err := NewJsonCache(filepath.Join(dir, "cache.json.gz")) if err != nil { t.Error(err) return } defer cache.Close() // invalid base URLs failTests := []string { "httsldkfjasldkfjadp:// \\ localhost:0", } for _, test := range(failTests) { t.Run(test, func(t *testing.T) { // custom sync config config := SyncConfig { Cve11BaseUrl: test } // sync data; note: even with an invalid base URL we still expect // this call to succeed; it's just that all of the URLs will be // nonsensical if err := Sync(config, &cache, dir); err != nil { t.Error(err) } }) } }