// Copyright 2024 Matthew Rich . All rights reserved. package context; import ( "testing" "log" "gitea.rosskeen.house/rosskeen.house/machine" "feudal/message" "feudal/interrogator" "feudal/tests" "feudal/tests/ponger" "feudal/feudal" ) type testWorker struct { context interface{} } func (w *testWorker) Receive(m message.Envelope) { switch m.Body().(type) { case string: m.Sender().Send(m) case *machine.EventMessage: log.Printf("event: %s on %s", m.Body(), w.context.(feudal.Context).Address()) default: log.Fatal("unexpected message") } } func (w *testWorker) Address() string { return w.context.(*Abstract).id.Address() } func (w *testWorker) SetContext(c interface{}) { w.context = c } func setupTestWorker() feudal.WorkerRouter { return New("test", nil, &testWorker{}) } func TestNew(t *testing.T) { w := New("test", nil, &testWorker{}) defer w.Stop() r := tests.SendTestMessage(w, "test message") tests.AssertMessageValue(r, "test message") } func TestWorkerType(t *testing.T) { nw := setupTestWorker() defer nw.Stop() ty := nw.Type() if ty != "testWorker" { t.Errorf("Type() returned incorrect type %s", ty) } } func TestWorkerStop(t *testing.T) { nw := setupTestWorker() defer nw.Stop() } func TestWorkerStateInitial(t *testing.T) { nw := setupTestWorker() defer nw.Stop() if nw.State() != "initialized" { t.Errorf("Invalid state") } } func TestWorkerStateStarted(t *testing.T) { i := interrogator.NewBuffered(10) nw := setupTestWorker() nw.(feudal.Context).Subscribers("lifecycle").Add("test", i) defer nw.Stop() _ = <- i _ = <- i if ! nw.(*Abstract).isStarted() { t.Errorf("worker failed to transition to started state") } } func TestWorkerWhenceParentState(t *testing.T) { nw := setupTestWorker() nw.Stop() p1 := nw.(feudal.Context).WorkerWhence(ponger.PongerFactory(), "p1") if p1 != nil { t.Errorf("Created worker from invalid state") } } func TestWorkerWhence(t *testing.T) { i := interrogator.NewBuffered(10) nw := setupTestWorker() nw.(feudal.Context).Subscribers("lifecycle").Add("test", i) enter_start_nw := <- i log.Printf("%s", enter_start_nw.(*message.AbstractEnvelope)) exit_start_nw := <- i log.Printf("%s", exit_start_nw.(*message.AbstractEnvelope)) ip := interrogator.NewBuffered(10) p1 := nw.(feudal.Context).WorkerWhence(ponger.PongerFactory(), "p1") p1.(feudal.Context).Subscribers("lifecycle").Add("testip", ip) sp1 := <- ip log.Printf("%s %s", sp1.Sender().Address(), sp1.(*message.AbstractEnvelope)) p2 := p1.(feudal.Context).WorkerWhence(ponger.PongerFactory(), "p2") if nw.State() == "started" && p1.State() == "started" && p2.State() == "started" { } }