edge/pkg/module/fetch/module_test.go

86 lines
1.8 KiB
Go
Raw Permalink Normal View History

2023-04-02 17:59:33 +02:00
package fetch
import (
"context"
"net/url"
2023-11-28 16:35:49 +01:00
"os"
2023-04-02 17:59:33 +02:00
"testing"
"time"
2023-04-02 17:59:33 +02:00
"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()
2023-11-28 16:35:49 +01:00
if testing.Verbose() {
logger.SetLevel(slog.LevelDebug)
}
2023-04-02 17:59:33 +02:00
bus := memory.NewBus()
server := app.NewServer(
module.ContextModuleFactory(),
module.ConsoleModuleFactory(),
ModuleFactory(bus),
)
2023-11-28 16:35:49 +01:00
path := "testdata/fetch.js"
data, err := os.ReadFile(path)
2023-04-02 17:59:33 +02:00
if err != nil {
t.Fatalf("%+v", errors.WithStack(err))
}
2023-11-28 16:35:49 +01:00
ctx := context.Background()
if err := server.Start(ctx, path, string(data)); err != nil {
2023-04-02 17:59:33 +02:00
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()
2023-04-02 17:59:33 +02:00
remoteAddr := "127.0.0.1"
url, _ := url.Parse("http://example.com")
2023-11-28 16:35:49 +01:00
reply, err := bus.Request(ctx, NewFetchRequestEnvelope(ctx, remoteAddr, url))
2023-04-02 17:59:33 +02:00
if err != nil {
t.Fatalf("%+v", errors.WithStack(err))
}
2023-11-28 16:35:49 +01:00
response, ok := reply.Message().(*FetchResponse)
2023-04-02 17:59:33 +02:00
if !ok {
2023-11-28 16:35:49 +01:00
t.Fatalf("unexpected reply message type '%T'", reply.Message())
2023-04-02 17:59:33 +02:00
}
2023-11-28 16:35:49 +01:00
if e, g := true, response.Allow; e != g {
2023-04-02 17:59:33 +02:00
t.Errorf("reply.Allow: expected '%v', got '%v'", e, g)
}
url, _ = url.Parse("https://google.com")
2023-11-28 16:35:49 +01:00
reply, err = bus.Request(ctx, NewFetchRequestEnvelope(ctx, remoteAddr, url))
2023-04-02 17:59:33 +02:00
if err != nil {
t.Fatalf("%+v", errors.WithStack(err))
}
2023-11-28 16:35:49 +01:00
response, ok = reply.Message().(*FetchResponse)
2023-04-02 17:59:33 +02:00
if !ok {
2023-11-28 16:35:49 +01:00
t.Fatalf("unexpected reply message type '%T'", reply.Message())
2023-04-02 17:59:33 +02:00
}
2023-11-28 16:35:49 +01:00
if e, g := false, response.Allow; e != g {
2023-04-02 17:59:33 +02:00
t.Errorf("reply.Allow: expected '%v', got '%v'", e, g)
}
}