github.com/thiagoyeds/go-cloud@v0.26.0/pubsub/pub_test.go (about)

     1  // Copyright 2019 The Go Cloud Development Kit Authors
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     https://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package pubsub_test
    16  
    17  import (
    18  	"context"
    19  	"testing"
    20  	"time"
    21  
    22  	"gocloud.dev/pubsub"
    23  	"gocloud.dev/pubsub/driver"
    24  )
    25  
    26  type funcTopic struct {
    27  	driver.Topic
    28  	sendBatch func(ctx context.Context, ms []*driver.Message) error
    29  	closed    bool
    30  }
    31  
    32  func (t *funcTopic) SendBatch(ctx context.Context, ms []*driver.Message) error {
    33  	return t.sendBatch(ctx, ms)
    34  }
    35  
    36  func (t *funcTopic) IsRetryable(error) bool { return false }
    37  func (t *funcTopic) Close() error {
    38  	t.closed = true
    39  	return nil
    40  }
    41  
    42  func TestTopicShutdownCanBeCanceledEvenWithHangingSend(t *testing.T) {
    43  	dt := &funcTopic{
    44  		sendBatch: func(ctx context.Context, ms []*driver.Message) error {
    45  			<-ctx.Done()
    46  			return ctx.Err()
    47  		},
    48  	}
    49  	topic := pubsub.NewTopic(dt, nil)
    50  
    51  	go func() {
    52  		m := &pubsub.Message{}
    53  		if err := topic.Send(context.Background(), m); err == nil {
    54  			t.Fatal("nil err from Send, expected context cancellation error")
    55  		}
    56  	}()
    57  
    58  	done := make(chan struct{})
    59  	ctx, cancel := context.WithTimeout(context.Background(), time.Millisecond)
    60  	defer cancel()
    61  	go func() {
    62  		topic.Shutdown(ctx)
    63  		close(done)
    64  	}()
    65  
    66  	// Now cancel the context being used by topic.Shutdown.
    67  	cancel()
    68  
    69  	// It shouldn't take too long before topic.Shutdown stops.
    70  	tooLong := 5 * time.Second
    71  	select {
    72  	case <-done:
    73  	case <-time.After(tooLong):
    74  		t.Fatalf("waited too long(%v) for Shutdown(ctx) to run", tooLong)
    75  	}
    76  }
    77  
    78  func TestTopicCloseIsCalled(t *testing.T) {
    79  	ctx := context.Background()
    80  	dt := &funcTopic{}
    81  	topic := pubsub.NewTopic(dt, nil)
    82  	topic.Shutdown(ctx)
    83  	if !dt.closed {
    84  		t.Error("want Topic.Close to have been called")
    85  	}
    86  }