@@ -115,6 +115,51 @@ 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+ // Insert two entries whose combined size exactly matches the cache
134+ // capacity and check that Size reflects the summed weight.
135+ _ , err := c .Put (1 , & sizeable {value : 1 , size : 2 })
136+ require .NoError (t , err )
137+ _ , err = c .Put (2 , & sizeable {value : 2 , size : 3 })
138+ require .NoError (t , err )
139+ assertSize (5 )
140+
141+ // Insert a third entry that forces the LRU element (key 1) out so the
142+ // cache can stay within its capacity budget.
143+ _ , err = c .Put (3 , & sizeable {value : 3 , size : 2 })
144+ require .NoError (t , err )
145+ assertSize (5 )
146+ _ , err = c .Get (1 )
147+ require .ErrorIs (t , err , cache .ErrElementNotFound )
148+
149+ // Replacing an existing element with a smaller version should shrink
150+ // the overall Size accounting accordingly.
151+ _ , err = c .Put (2 , & sizeable {value : 20 , size : 1 })
152+ require .NoError (t , err )
153+ assertSize (3 )
154+
155+ // Deleting an item should subtract its contribution and return the
156+ // removed value to the caller.
157+ val , ok := c .LoadAndDelete (3 )
158+ require .True (t , ok )
159+ require .Equal (t , 3 , val .value )
160+ assertSize (1 )
161+ }
162+
118163// TestCacheFailsInsertionSizeBiggerCapacity tests that the cache fails the
119164// put operation when the element's size is bigger than it's capacity.
120165func TestCacheFailsInsertionSizeBiggerCapacity (t * testing.T ) {
0 commit comments