Skip to content

Commit d4bc06c

Browse files
committed
Add ObjectPool tests
1 parent 9dcdf8d commit d4bc06c

1 file changed

Lines changed: 101 additions & 0 deletions

File tree

Lines changed: 101 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,101 @@
1+
namespace Source.Common.Tests;
2+
3+
public class ObjectPoolTests
4+
{
5+
sealed class TestPoolable : IPoolableObject
6+
{
7+
public int InitCalls;
8+
public int ResetCalls;
9+
public int InUse;
10+
public bool HandedOutTwice;
11+
12+
public void Init() {
13+
InitCalls++;
14+
if (Interlocked.Exchange(ref InUse, 1) != 0)
15+
HandedOutTwice = true;
16+
}
17+
18+
public void Reset() {
19+
ResetCalls++;
20+
Interlocked.Exchange(ref InUse, 0);
21+
}
22+
}
23+
24+
[Fact]
25+
public void AllocInitsAndFreeResets() {
26+
ObjectPool<TestPoolable> pool = new();
27+
28+
TestPoolable obj = pool.Alloc();
29+
Assert.Equal(1, obj.InitCalls);
30+
Assert.Equal(0, obj.ResetCalls);
31+
32+
pool.Free(obj);
33+
Assert.Equal(1, obj.ResetCalls);
34+
}
35+
36+
[Fact]
37+
public void FreedInstanceIsReused() {
38+
ObjectPool<TestPoolable> pool = new();
39+
40+
TestPoolable first = pool.Alloc();
41+
pool.Free(first);
42+
TestPoolable second = pool.Alloc();
43+
44+
Assert.Same(first, second);
45+
Assert.Equal(2, second.InitCalls);
46+
}
47+
48+
[Fact]
49+
public void LiveInstancesAreDistinct() {
50+
ObjectPool<TestPoolable> pool = new();
51+
52+
TestPoolable a = pool.Alloc();
53+
TestPoolable b = pool.Alloc();
54+
55+
Assert.NotSame(a, b);
56+
}
57+
58+
[Fact]
59+
public void CountTracksOutstandingInstances() {
60+
ObjectPool<TestPoolable> pool = new();
61+
62+
TestPoolable a = pool.Alloc();
63+
TestPoolable b = pool.Alloc();
64+
Assert.Equal(2, pool.Count());
65+
66+
pool.Free(a);
67+
Assert.Equal(1, pool.Count());
68+
69+
pool.Free(b);
70+
Assert.Equal(0, pool.Count());
71+
}
72+
73+
[Fact]
74+
public void FreeNullIsIgnored() {
75+
ObjectPool<TestPoolable> pool = new();
76+
77+
pool.Free(null);
78+
79+
Assert.Equal(0, pool.Count());
80+
}
81+
82+
[Fact]
83+
public void ConcurrentUseNeverHandsOutAnInstanceTwice() {
84+
ObjectPool<TestPoolable> pool = new();
85+
const int threads = 8;
86+
const int iterations = 20000;
87+
bool handedOutTwice = false;
88+
89+
Parallel.For(0, threads, _ => {
90+
for (int i = 0; i < iterations; i++) {
91+
TestPoolable obj = pool.Alloc();
92+
if (obj.HandedOutTwice)
93+
Volatile.Write(ref handedOutTwice, true);
94+
pool.Free(obj);
95+
}
96+
});
97+
98+
Assert.False(handedOutTwice);
99+
Assert.Equal(0, pool.Count());
100+
}
101+
}

0 commit comments

Comments
 (0)