edge/pkg/module/fetch/module_test.go

86 lines
1.8 KiB
Go

package fetch
import (
"context"
"net/url"
"os"
"testing"
"time"
"cdr.dev/slog"
"forge.cadoles.com/arcad/edge/pkg/app"
"forge.cadoles.com/arcad/edge/pkg/bus/memory"
"forge.cadoles.com/arcad/edge/pkg/module"
"github.com/pkg/errors"
"gitlab.com/wpetit/goweb/logger"
)
func TestFetchModule(t *testing.T) {
t.Parallel()
if testing.Verbose() {
logger.SetLevel(slog.LevelDebug)
}
bus := memory.NewBus()
server := app.NewServer(
module.ContextModuleFactory(),
module.ConsoleModuleFactory(),
ModuleFactory(bus),
)
path := "testdata/fetch.js"
data, err := os.ReadFile(path)
if err != nil {
t.Fatalf("%+v", errors.WithStack(err))
}
ctx := context.Background()
if err := server.Start(ctx, path, string(data)); err != nil {
t.Fatalf("%+v", errors.WithStack(err))
}
defer server.Stop()
// Wait for module to startup
time.Sleep(1 * time.Second)
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
remoteAddr := "127.0.0.1"
url, _ := url.Parse("http://example.com")
reply, err := bus.Request(ctx, NewFetchRequestEnvelope(ctx, remoteAddr, url))
if err != nil {
t.Fatalf("%+v", errors.WithStack(err))
}
response, ok := reply.Message().(*FetchResponse)
if !ok {
t.Fatalf("unexpected reply message type '%T'", reply.Message())
}
if e, g := true, response.Allow; e != g {
t.Errorf("reply.Allow: expected '%v', got '%v'", e, g)
}
url, _ = url.Parse("https://google.com")
reply, err = bus.Request(ctx, NewFetchRequestEnvelope(ctx, remoteAddr, url))
if err != nil {
t.Fatalf("%+v", errors.WithStack(err))
}
response, ok = reply.Message().(*FetchResponse)
if !ok {
t.Fatalf("unexpected reply message type '%T'", reply.Message())
}
if e, g := false, response.Allow; e != g {
t.Errorf("reply.Allow: expected '%v', got '%v'", e, g)
}
}