From 131ac823fda6bc6781b182ebed07e5eb34d44aeb Mon Sep 17 00:00:00 2001 From: Ken Hibino Date: Mon, 31 Aug 2020 05:39:45 -0700 Subject: [PATCH] Return error if queue name is empty when enqueueing --- client.go | 20 +++++++++++++++----- client_test.go | 30 ++++++++++++++++++++++++++++++ 2 files changed, 45 insertions(+), 5 deletions(-) diff --git a/client.go b/client.go index 7bbe371..91ee83f 100644 --- a/client.go +++ b/client.go @@ -115,7 +115,11 @@ type option struct { uniqueTTL time.Duration } -func composeOptions(opts ...Option) option { +// composeOptions merges user provided options into the default options +// and returns the composed option. +// It also validates the user provided options and returns an error if any of +// the user provided options fail the validations. +func composeOptions(opts ...Option) (option, error) { res := option{ retry: defaultMaxRetry, queue: base.DefaultQueueName, @@ -127,7 +131,11 @@ func composeOptions(opts ...Option) option { case retryOption: res.retry = int(opt) case queueOption: - res.queue = string(opt) + trimmed := strings.TrimSpace(string(opt)) + if len(trimmed) == 0 { + return option{}, fmt.Errorf("queue name must contain one or more characters") + } + res.queue = trimmed case timeoutOption: res.timeout = time.Duration(opt) case deadlineOption: @@ -138,7 +146,7 @@ func composeOptions(opts ...Option) option { // ignore unexpected option } } - return res + return res, nil } const ( @@ -239,7 +247,10 @@ func (c *Client) enqueueAt(t time.Time, task *Task, opts ...Option) (*Result, er if defaults, ok := c.opts[task.Type]; ok { opts = append(defaults, opts...) } - opt := composeOptions(opts...) + opt, err := composeOptions(opts...) + if err != nil { + return nil, err + } deadline := noDeadline if !opt.deadline.IsZero() { deadline = opt.deadline @@ -266,7 +277,6 @@ func (c *Client) enqueueAt(t time.Time, task *Task, opts ...Option) (*Result, er Timeout: int64(timeout.Seconds()), UniqueKey: uniqueKey, } - var err error now := time.Now() if t.Before(now) || t.Equal(now) { err = c.enqueue(msg, opt.uniqueTTL) diff --git a/client_test.go b/client_test.go index ac37f6e..c4ec428 100644 --- a/client_test.go +++ b/client_test.go @@ -463,6 +463,36 @@ func TestClientEnqueueIn(t *testing.T) { } } +func TestClientEnqueueError(t *testing.T) { + r := setup(t) + client := NewClient(getRedisConnOpt(t)) + + task := NewTask("send_email", map[string]interface{}{"to": "customer@gmail.com", "from": "merchant@example.com"}) + + tests := []struct { + desc string + task *Task + opts []Option + }{ + { + desc: "With empty queue name", + task: task, + opts: []Option{ + Queue(""), + }, + }, + } + + for _, tc := range tests { + h.FlushDB(t, r) + + _, err := client.Enqueue(tc.task, tc.opts...) + if err == nil { + t.Errorf("%s; client.Enqueue(task, opts...) did not return non-nil error", tc.desc) + } + } +} + func TestClientDefaultOptions(t *testing.T) { r := setup(t)