mirror of
https://github.com/hibiken/asynq.git
synced 2025-09-19 05:17:30 +08:00
Add Use method to better support middlewares with ServeMux
This commit is contained in:
@@ -7,9 +7,12 @@ package asynq
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
"github.com/google/go-cmp/cmp"
|
||||
)
|
||||
|
||||
var called string
|
||||
var called string // identity of the handler that was called.
|
||||
var invoked []string // list of middlewares in the order they were invoked.
|
||||
|
||||
// makeFakeHandler returns a handler that updates the global called variable
|
||||
// to the given identity.
|
||||
@@ -20,6 +23,17 @@ func makeFakeHandler(identity string) Handler {
|
||||
})
|
||||
}
|
||||
|
||||
// makeFakeMiddleware returns a middleware function that appends the given identity
|
||||
//to the global invoked slice.
|
||||
func makeFakeMiddleware(identity string) MiddlewareFunc {
|
||||
return func(next Handler) Handler {
|
||||
return HandlerFunc(func(ctx context.Context, t *Task) error {
|
||||
invoked = append(invoked, identity)
|
||||
return next.ProcessTask(ctx, t)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// A list of pattern, handler pair that is registered with mux.
|
||||
var serveMuxRegister = []struct {
|
||||
pattern string
|
||||
@@ -114,3 +128,43 @@ func TestServeMuxNotFound(t *testing.T) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var middlewareTests = []struct {
|
||||
typename string // task's type name
|
||||
middlewares []string // middlewares to use. They should be called in this order.
|
||||
want string // identifier of the handler that should be called
|
||||
}{
|
||||
{"email:signup", []string{"logging", "expiration"}, "signup email handler"},
|
||||
{"csv:export", []string{}, "csv export handler"},
|
||||
{"email:daily", []string{"expiration", "logging"}, "default email handler"},
|
||||
}
|
||||
|
||||
func TestServeMuxMiddlewares(t *testing.T) {
|
||||
for _, tc := range middlewareTests {
|
||||
mux := NewServeMux()
|
||||
for _, e := range serveMuxRegister {
|
||||
mux.Handle(e.pattern, e.h)
|
||||
}
|
||||
var mws []MiddlewareFunc
|
||||
for _, s := range tc.middlewares {
|
||||
mws = append(mws, makeFakeMiddleware(s))
|
||||
}
|
||||
mux.Use(mws...)
|
||||
|
||||
invoked = []string{} // reset to empty slice
|
||||
called = "" // reset to zero value
|
||||
|
||||
task := NewTask(tc.typename, nil)
|
||||
if err := mux.ProcessTask(context.Background(), task); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if diff := cmp.Diff(invoked, tc.middlewares); diff != "" {
|
||||
t.Errorf("invoked middlewares were %v, want %v", invoked, tc.middlewares)
|
||||
}
|
||||
|
||||
if called != tc.want {
|
||||
t.Errorf("%q handler was called for task %q, want %q to be called", called, task.Type, tc.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
Reference in New Issue
Block a user