eintopf.info@v0.13.16/service/oqueue/queue_test.go (about)

     1  // Copyright (C) 2022 The Eintopf authors
     2  //
     3  // This program is free software: you can redistribute it and/or modify
     4  // it under the terms of the GNU Affero General Public License as
     5  // published by the Free Software Foundation, either version 3 of the
     6  // License, or (at your option) any later version.
     7  //
     8  // This program is distributed in the hope that it will be useful,
     9  // but WITHOUT ANY WARRANTY; without even the implied warranty of
    10  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    11  // GNU Affero General Public License for more details.
    12  //
    13  // You should have received a copy of the GNU Affero General Public License
    14  // along with this program.  If not, see <https://www.gnu.org/licenses/>.
    15  
    16  package oqueue_test
    17  
    18  import (
    19  	"sync"
    20  	"testing"
    21  	"time"
    22  
    23  	"eintopf.info/service/oqueue"
    24  )
    25  
    26  type testOperation struct{}
    27  
    28  func (t testOperation) UserID() string { return "" }
    29  
    30  func TestOqueueWaitsOnClose(t *testing.T) {
    31  	queue := oqueue.NewQueue()
    32  
    33  	counter := 0
    34  	m := sync.Mutex{}
    35  	queue.AddSubscriber(func(op oqueue.Operation) error {
    36  		time.Sleep(time.Millisecond * 100)
    37  		m.Lock()
    38  		counter++
    39  		m.Unlock()
    40  		return nil
    41  	}, 2)
    42  
    43  	queue.AddOperation(testOperation{})
    44  	queue.AddOperation(testOperation{})
    45  	queue.AddOperation(testOperation{})
    46  
    47  	queue.Close()
    48  	if counter != 3 {
    49  		t.Errorf("all operations should be consumed and processed. only got %d", counter)
    50  	}
    51  }
    52  
    53  func TestMultipleSubscribers(t *testing.T) {
    54  	queue := oqueue.NewQueue()
    55  
    56  	counter := 0
    57  	m := sync.Mutex{}
    58  	queue.AddSubscriber(func(op oqueue.Operation) error {
    59  		m.Lock()
    60  		counter++
    61  		m.Unlock()
    62  		return nil
    63  	}, 2)
    64  	queue.AddSubscriber(func(op oqueue.Operation) error {
    65  		m.Lock()
    66  		counter++
    67  		m.Unlock()
    68  		return nil
    69  	}, 2)
    70  
    71  	queue.AddOperation(testOperation{})
    72  	queue.AddOperation(testOperation{})
    73  	queue.AddOperation(testOperation{})
    74  
    75  	queue.Close()
    76  	if counter != 6 {
    77  		t.Errorf("all operations should be consumed and processed twice. only got %d", counter)
    78  	}
    79  }