github.com/rclone/rclone@v1.66.1-0.20240517100346-7b89735ae726/lib/kv/internal_test.go (about)

     1  //go:build !plan9 && !js
     2  
     3  package kv
     4  
     5  import (
     6  	"context"
     7  	"fmt"
     8  	"sync"
     9  	"testing"
    10  
    11  	"github.com/stretchr/testify/assert"
    12  	"github.com/stretchr/testify/require"
    13  )
    14  
    15  func TestKvConcurrency(t *testing.T) {
    16  	require.Equal(t, 0, len(dbMap), "no databases can be started initially")
    17  
    18  	const threadNum = 5
    19  	var wg sync.WaitGroup
    20  	ctx := context.Background()
    21  	results := make([]*DB, threadNum)
    22  	wg.Add(threadNum)
    23  	for i := 0; i < threadNum; i++ {
    24  		go func(i int) {
    25  			db, err := Start(ctx, "test", nil)
    26  			require.NoError(t, err)
    27  			require.NotNil(t, db)
    28  			results[i] = db
    29  			wg.Done()
    30  		}(i)
    31  	}
    32  	wg.Wait()
    33  
    34  	// must have a single multi-referenced db
    35  	db := results[0]
    36  	assert.Equal(t, 1, len(dbMap))
    37  	assert.Equal(t, threadNum, db.refs)
    38  	for i := 0; i < threadNum; i++ {
    39  		assert.Equal(t, db, results[i])
    40  	}
    41  
    42  	for i := 0; i < threadNum; i++ {
    43  		assert.Equal(t, 1, len(dbMap))
    44  		err := db.Stop(false)
    45  		assert.NoError(t, err, "unexpected error %v at retry %d", err, i)
    46  	}
    47  
    48  	assert.Equal(t, 0, len(dbMap), "must be closed in the end")
    49  	err := db.Stop(false)
    50  	assert.ErrorIs(t, err, ErrInactive, "missing expected stop indication")
    51  }
    52  
    53  func TestKvExit(t *testing.T) {
    54  	require.Equal(t, 0, len(dbMap), "no databases can be started initially")
    55  	const dbNum = 5
    56  	ctx := context.Background()
    57  	for i := 0; i < dbNum; i++ {
    58  		facility := fmt.Sprintf("test-%d", i)
    59  		for j := 0; j <= i; j++ {
    60  			db, err := Start(ctx, facility, nil)
    61  			require.NoError(t, err)
    62  			require.NotNil(t, db)
    63  		}
    64  	}
    65  	assert.Equal(t, dbNum, len(dbMap))
    66  	Exit()
    67  	assert.Equal(t, 0, len(dbMap))
    68  }