github.com/anacrolix/torrent@v1.61.0/internal/indexed/indexed_test.go (about)

     1  package indexed
     2  
     3  import (
     4  	"cmp"
     5  	"testing"
     6  
     7  	g "github.com/anacrolix/generics"
     8  	"github.com/go-quicktest/qt"
     9  )
    10  
    11  func TestUpdateOrCreate(t *testing.T) {
    12  	var a Map[string, int]
    13  	a.Init(cmp.Compare)
    14  	created := a.UpdateOrCreate("a", func(old int) int {
    15  		return old + 1
    16  	})
    17  	a.OnValueChange(func(key string, old, new g.Option[int]) {
    18  		i, _ := a.Get(key)
    19  		if i == 0 {
    20  			a.Delete(key)
    21  		}
    22  	})
    23  	qt.Assert(t, qt.IsTrue(created))
    24  	v, ok := a.Get("a")
    25  	qt.Assert(t, qt.IsTrue(ok))
    26  	qt.Assert(t, qt.Equals(v, 1))
    27  	created = a.UpdateOrCreate("a", func(old int) int {
    28  		return old + 1
    29  	})
    30  	qt.Assert(t, qt.IsFalse(created))
    31  	v, ok = a.Get("a")
    32  	qt.Assert(t, qt.IsTrue(ok))
    33  	qt.Assert(t, qt.Equals(v, 2))
    34  	created = a.UpdateOrCreate("a", func(old int) int {
    35  		return 0
    36  	})
    37  	qt.Assert(t, qt.IsFalse(created))
    38  	v, ok = a.Get("a")
    39  	qt.Assert(t, qt.IsFalse(ok))
    40  	qt.Assert(t, qt.Equals(v, 0))
    41  }