2020-12-09 15:31:34 +00:00
|
|
|
package middlewares
|
|
|
|
|
|
|
|
import (
|
|
|
|
"errors"
|
|
|
|
"testing"
|
|
|
|
|
2021-12-06 13:29:39 +00:00
|
|
|
"github.com/snyk/driftctl/pkg/resource"
|
2020-12-09 15:31:34 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
var callCounters map[string]int
|
|
|
|
|
|
|
|
type FakeMiddleware struct {
|
|
|
|
Name string
|
|
|
|
Err error
|
|
|
|
}
|
|
|
|
|
2021-08-09 14:03:04 +00:00
|
|
|
func (m FakeMiddleware) Execute(remoteResources, resourcesFromState *[]*resource.Resource) error {
|
2020-12-09 15:31:34 +00:00
|
|
|
callCounters[m.Name]++
|
|
|
|
return m.Err
|
|
|
|
}
|
|
|
|
|
|
|
|
func TestChainMiddleware(t *testing.T) {
|
|
|
|
|
|
|
|
callCounters = make(map[string]int)
|
|
|
|
|
|
|
|
fakeMiddleware1 := FakeMiddleware{
|
|
|
|
Name: "1",
|
|
|
|
}
|
|
|
|
fakeMiddleware2 := FakeMiddleware{
|
|
|
|
Name: "2",
|
|
|
|
}
|
|
|
|
|
|
|
|
middleware := NewChain(fakeMiddleware1, fakeMiddleware2)
|
2021-08-09 14:03:04 +00:00
|
|
|
remoteResources := []*resource.Resource{}
|
|
|
|
stateResources := []*resource.Resource{}
|
2020-12-09 15:31:34 +00:00
|
|
|
err := middleware.Execute(&remoteResources, &stateResources)
|
|
|
|
|
|
|
|
if err != nil {
|
|
|
|
t.Error("A middleware returned an error")
|
|
|
|
}
|
|
|
|
|
|
|
|
if callCounters["1"] != 1 {
|
|
|
|
t.Error("Middleware 1 was not called correctly")
|
|
|
|
}
|
|
|
|
|
|
|
|
if callCounters["2"] != 1 {
|
|
|
|
t.Error("Middleware 2 was not called correctly")
|
|
|
|
}
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
func TestChainMiddlewareErrorShouldStopExecution(t *testing.T) {
|
|
|
|
|
|
|
|
callCounters = make(map[string]int)
|
|
|
|
|
|
|
|
fakeMiddleware1 := FakeMiddleware{
|
|
|
|
Name: "1",
|
|
|
|
Err: errors.New("Test error"),
|
|
|
|
}
|
|
|
|
fakeMiddleware2 := FakeMiddleware{
|
|
|
|
Name: "2",
|
|
|
|
}
|
|
|
|
|
|
|
|
middleware := NewChain(fakeMiddleware1, fakeMiddleware2)
|
2021-08-09 14:03:04 +00:00
|
|
|
remoteResources := []*resource.Resource{}
|
|
|
|
stateResources := []*resource.Resource{}
|
2020-12-09 15:31:34 +00:00
|
|
|
err := middleware.Execute(&remoteResources, &stateResources)
|
|
|
|
|
|
|
|
if err == nil {
|
|
|
|
t.Error("No error were reported")
|
|
|
|
}
|
|
|
|
|
|
|
|
if err.Error() != "Test error" {
|
|
|
|
t.Error("Unknown error reported")
|
|
|
|
}
|
|
|
|
|
|
|
|
if callCounters["1"] != 1 {
|
|
|
|
t.Error("Middleware 1 was not called correctly")
|
|
|
|
}
|
|
|
|
|
|
|
|
if callCounters["2"] != 0 {
|
|
|
|
t.Error("Middleware 2 was called after error happen in middleware 1")
|
|
|
|
}
|
|
|
|
|
|
|
|
}
|