crowdsec/pkg/cwhub/cwhub_test.go
mmetc ac98256602
Refact pkg/cwhub, cmd/crowdsec-cli (#2557)
- pkg/cwhub: change file layout, rename functions
 - method Item.SubItems
 - cmd/crowdsec-cli: generic code for hub items
 - cscli: removing any type of items in a collection now requires --force
 - tests
2023-10-20 14:32:35 +02:00

154 lines
3.5 KiB
Go

package cwhub
import (
"io"
"net/http"
"os"
"path/filepath"
"strings"
"testing"
log "github.com/sirupsen/logrus"
"github.com/stretchr/testify/require"
"github.com/crowdsecurity/crowdsec/pkg/csconfig"
)
/*
To test :
- Download 'first' hub index
- Update hub index
- Install collection + list content
- Taint existing parser + list
- Upgrade collection
*/
var responseByPath map[string]string
// testHub initializes a temporary hub with an empty json file, optionally updating it
func testHub(t *testing.T, update bool) *Hub {
tmpDir, err := os.MkdirTemp("", "testhub")
require.NoError(t, err)
hubCfg := &csconfig.HubCfg{
HubDir: filepath.Join(tmpDir, "crowdsec", "hub"),
HubIndexFile: filepath.Join(tmpDir, "crowdsec", "hub", ".index.json"),
InstallDir: filepath.Join(tmpDir, "crowdsec"),
InstallDataDir: filepath.Join(tmpDir, "installed-data"),
}
err = os.MkdirAll(hubCfg.HubDir, 0o700)
require.NoError(t, err)
err = os.MkdirAll(hubCfg.InstallDir, 0o700)
require.NoError(t, err)
err = os.MkdirAll(hubCfg.InstallDataDir, 0o700)
require.NoError(t, err)
index, err := os.Create(hubCfg.HubIndexFile)
require.NoError(t, err)
_, err = index.WriteString(`{}`)
require.NoError(t, err)
index.Close()
t.Cleanup(func() {
os.RemoveAll(tmpDir)
})
constructor := InitHub
if update {
constructor = InitHubUpdate
}
hub, err := constructor(hubCfg)
require.NoError(t, err)
return hub
}
// envSetup initializes the temporary hub and mocks the http client
func envSetup(t *testing.T) *Hub {
setResponseByPath()
log.SetLevel(log.DebugLevel)
defaultTransport := http.DefaultClient.Transport
t.Cleanup(func() {
http.DefaultClient.Transport = defaultTransport
})
// Mock the http client
http.DefaultClient.Transport = newMockTransport()
hub := testHub(t, true)
return hub
}
type mockTransport struct{}
func newMockTransport() http.RoundTripper {
return &mockTransport{}
}
// Implement http.RoundTripper
func (t *mockTransport) RoundTrip(req *http.Request) (*http.Response, error) {
// Create mocked http.Response
response := &http.Response{
Header: make(http.Header),
Request: req,
StatusCode: http.StatusOK,
}
response.Header.Set("Content-Type", "application/json")
log.Infof("---> %s", req.URL.Path)
// FAKE PARSER
resp, ok := responseByPath[req.URL.Path]
if !ok {
log.Fatalf("unexpected url :/ %s", req.URL.Path)
}
response.Body = io.NopCloser(strings.NewReader(resp))
return response, nil
}
func fileToStringX(path string) string {
f, err := os.Open(path)
if err != nil {
panic(err)
}
defer f.Close()
data, err := io.ReadAll(f)
if err != nil {
panic(err)
}
return strings.ReplaceAll(string(data), "\r\n", "\n")
}
func setResponseByPath() {
responseByPath = map[string]string{
"/master/parsers/s01-parse/crowdsecurity/foobar_parser.yaml": fileToStringX("./testdata/foobar_parser.yaml"),
"/master/parsers/s01-parse/crowdsecurity/foobar_subparser.yaml": fileToStringX("./testdata/foobar_parser.yaml"),
"/master/collections/crowdsecurity/test_collection.yaml": fileToStringX("./testdata/collection_v1.yaml"),
"/master/.index.json": fileToStringX("./testdata/index1.json"),
"/master/scenarios/crowdsecurity/foobar_scenario.yaml": `filter: true
name: crowdsecurity/foobar_scenario`,
"/master/scenarios/crowdsecurity/barfoo_scenario.yaml": `filter: true
name: crowdsecurity/foobar_scenario`,
"/master/collections/crowdsecurity/foobar_subcollection.yaml": `
blah: blalala
qwe: jejwejejw`,
"/master/collections/crowdsecurity/foobar.yaml": `
blah: blalala
qwe: jejwejejw`,
}
}