@@ -115,6 +115,55 @@ func TestElementSizeCapacityEvictsEverything(t *testing.T) {
115115 require .Equal (t , four , 4 )
116116}
117117
118+ // TestCacheSizeTracksMutations ensures that Size mirrors the total bytes held
119+ // in the cache as items are inserted, evicted, replaced, and deleted.
120+ func TestCacheSizeTracksMutations (t * testing.T ) {
121+ t .Parallel ()
122+
123+ // Initialize a cache with enough headroom to exercise evictions while
124+ // still keeping multiple entries resident.
125+ c := NewCache [int , * sizeable ](5 )
126+
127+ // assertSize is a helper to reduce boilerplate when checking Size().
128+ assertSize := func (expected uint64 ) {
129+ t .Helper ()
130+ require .Equal (t , expected , c .Size ())
131+ }
132+
133+ // The initial size is 0.
134+ assertSize (0 )
135+
136+ // Insert two entries whose combined size exactly matches the cache
137+ // capacity and check that Size reflects the summed weight.
138+ _ , err := c .Put (1 , & sizeable {value : 1 , size : 2 })
139+ require .NoError (t , err )
140+ assertSize (2 )
141+ _ , err = c .Put (2 , & sizeable {value : 2 , size : 3 })
142+ require .NoError (t , err )
143+ assertSize (5 )
144+
145+ // Insert a third entry that forces the LRU element (key 1) out so the
146+ // cache can stay within its capacity budget.
147+ _ , err = c .Put (3 , & sizeable {value : 3 , size : 2 })
148+ require .NoError (t , err )
149+ assertSize (5 )
150+ _ , err = c .Get (1 )
151+ require .ErrorIs (t , err , cache .ErrElementNotFound )
152+
153+ // Replacing an existing element with a smaller version should shrink
154+ // the overall Size accounting accordingly.
155+ _ , err = c .Put (2 , & sizeable {value : 20 , size : 1 })
156+ require .NoError (t , err )
157+ assertSize (3 )
158+
159+ // Deleting an item should subtract its contribution and return the
160+ // removed value to the caller.
161+ val , ok := c .LoadAndDelete (3 )
162+ require .True (t , ok )
163+ require .Equal (t , 3 , val .value )
164+ assertSize (1 )
165+ }
166+
118167// TestCacheFailsInsertionSizeBiggerCapacity tests that the cache fails the
119168// put operation when the element's size is bigger than it's capacity.
120169func TestCacheFailsInsertionSizeBiggerCapacity (t * testing.T ) {
0 commit comments