versionedmap_test.go 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. package csync
  2. import (
  3. "testing"
  4. "github.com/stretchr/testify/require"
  5. )
  6. func TestVersionedMap_Set(t *testing.T) {
  7. t.Parallel()
  8. vm := NewVersionedMap[string, int]()
  9. require.Equal(t, uint64(0), vm.Version())
  10. vm.Set("key1", 42)
  11. require.Equal(t, uint64(1), vm.Version())
  12. value, ok := vm.Get("key1")
  13. require.True(t, ok)
  14. require.Equal(t, 42, value)
  15. }
  16. func TestVersionedMap_Del(t *testing.T) {
  17. t.Parallel()
  18. vm := NewVersionedMap[string, int]()
  19. vm.Set("key1", 42)
  20. initialVersion := vm.Version()
  21. vm.Del("key1")
  22. require.Equal(t, initialVersion+1, vm.Version())
  23. _, ok := vm.Get("key1")
  24. require.False(t, ok)
  25. }
  26. func TestVersionedMap_VersionIncrement(t *testing.T) {
  27. t.Parallel()
  28. vm := NewVersionedMap[string, int]()
  29. initialVersion := vm.Version()
  30. // Setting a value should increment the version
  31. vm.Set("key1", 42)
  32. require.Equal(t, initialVersion+1, vm.Version())
  33. // Deleting a value should increment the version
  34. vm.Del("key1")
  35. require.Equal(t, initialVersion+2, vm.Version())
  36. // Deleting a non-existent key should still increment the version
  37. vm.Del("nonexistent")
  38. require.Equal(t, initialVersion+3, vm.Version())
  39. }
  40. func TestVersionedMap_ConcurrentAccess(t *testing.T) {
  41. t.Parallel()
  42. vm := NewVersionedMap[int, int]()
  43. const numGoroutines = 100
  44. const numOperations = 100
  45. // Initial version
  46. initialVersion := vm.Version()
  47. // Perform concurrent Set and Del operations
  48. for i := range numGoroutines {
  49. go func(id int) {
  50. for j := range numOperations {
  51. key := id*numOperations + j
  52. vm.Set(key, key*2)
  53. vm.Del(key)
  54. }
  55. }(i)
  56. }
  57. // Wait for operations to complete by checking the version
  58. // This is a simplified check - in a real test you might want to use sync.WaitGroup
  59. expectedMinVersion := initialVersion + uint64(numGoroutines*numOperations*2)
  60. // Allow some time for operations to complete
  61. for vm.Version() < expectedMinVersion {
  62. // Busy wait - in a real test you'd use proper synchronization
  63. }
  64. // Final version should be at least the expected minimum
  65. require.GreaterOrEqual(t, vm.Version(), expectedMinVersion)
  66. require.Equal(t, 0, vm.Len())
  67. }