github.com/artisanhe/tools@v1.0.1-0.20210607022958-19a8fef2eb04/mq/agent/agent_test.go (about)

     1  package agent
     2  
     3  import (
     4  	"context"
     5  	"fmt"
     6  	"testing"
     7  	"time"
     8  
     9  	"github.com/davecgh/go-spew/spew"
    10  	"github.com/sirupsen/logrus"
    11  
    12  	"github.com/artisanhe/tools/courier"
    13  	"github.com/artisanhe/tools/mq"
    14  )
    15  
    16  func init() {
    17  	logrus.SetLevel(logrus.DebugLevel)
    18  }
    19  
    20  type DoSomeThing struct {
    21  	Int int
    22  }
    23  
    24  func (op DoSomeThing) Output(ctx context.Context) (interface{}, error) {
    25  	logrus.Println("running: ", op.Int)
    26  	time.Sleep(50 * time.Millisecond)
    27  	if op.Int%2 == 0 {
    28  		return nil, fmt.Errorf("error %d", op.Int)
    29  	}
    30  	return op.Int, nil
    31  }
    32  
    33  func TestAgent(t *testing.T) {
    34  	agent := Agent{
    35  		Host: "redis.staging.g7pay.net",
    36  		Port: 36379,
    37  	}
    38  	agent.MarshalDefaults(&agent)
    39  	agent.Init()
    40  
    41  	agent.RegisterReceiver(func(status *mq.TaskStatus) error {
    42  		logrus.Infoln(
    43  			"received:",
    44  			status.Channel,
    45  			status.Subject,
    46  			status.ID,
    47  			status.Status,
    48  			string(status.Result),
    49  			string(status.Traceback),
    50  		)
    51  		return nil
    52  	})
    53  	agent.StartReceiver()
    54  
    55  	agent.RegisterRoutes(courier.NewRouter(DoSomeThing{}).Route())
    56  	agent.StartWorker()
    57  
    58  	for i := 0; i < 10; i++ {
    59  		subject, data, _ := SubjectAndDataFromValue(&DoSomeThing{
    60  			Int: i,
    61  		})
    62  		task, _ := agent.Publish(agent.Name, subject, data)
    63  		logrus.Infoln(task.ID, string(task.Data))
    64  		if i%4 == 0 {
    65  			agent.Cancel(task.ID)
    66  		}
    67  	}
    68  
    69  	spew.Dump(agent.ListChannel())
    70  
    71  	time.Sleep(5 * time.Second)
    72  }