Skip to content

Commit b38bc8b

Browse files
committed
add object pool tests
1 parent 727e94f commit b38bc8b

1 file changed

Lines changed: 127 additions & 0 deletions

File tree

Lines changed: 127 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,127 @@
1+
using Backdash.Data;
2+
3+
namespace Backdash.Tests.Specs.Unit.Data;
4+
5+
public class ObjectPoolTests
6+
{
7+
[Fact]
8+
public void ShouldRentAndReturnSameObject()
9+
{
10+
var sut = ObjectPool.Create<TestObj>();
11+
12+
var value = sut.Rent();
13+
sut.Count.Should().Be(0);
14+
15+
sut.Return(value);
16+
sut.Count.Should().Be(1);
17+
18+
var value2 = sut.Rent();
19+
sut.Count.Should().Be(0);
20+
21+
value2.Should().BeSameAs(value);
22+
}
23+
24+
[Fact]
25+
public void ShouldNotReturnSameObjectTwice()
26+
{
27+
var sut = ObjectPool.Create<TestObj>();
28+
var value = sut.Rent();
29+
sut.Count.Should().Be(0);
30+
31+
sut.Return(value);
32+
sut.Return(value);
33+
sut.Count.Should().Be(1);
34+
}
35+
36+
[Fact]
37+
public void ShouldCallCreateAndReturnFunction()
38+
{
39+
ObjectPool<TestObj> sut = new(
40+
() => new()
41+
{
42+
Value = 1,
43+
Returned = false,
44+
},
45+
obj =>
46+
{
47+
obj.Value = 0;
48+
obj.Returned = true;
49+
}
50+
);
51+
52+
var value = sut.Rent();
53+
54+
value.Should().BeEquivalentTo(new
55+
{
56+
Value = 1,
57+
Returned = false,
58+
});
59+
60+
value.Value = 2;
61+
sut.Return(value);
62+
63+
value.Should().BeEquivalentTo(new
64+
{
65+
Value = 0,
66+
Returned = true,
67+
});
68+
}
69+
70+
[Fact]
71+
public void ShouldAddMoreThanCapacity()
72+
{
73+
const int capacity = 5;
74+
var sut = ObjectPool.Create<TestObj>(capacity);
75+
FillPool(sut, capacity * 2);
76+
sut.Count.Should().Be(capacity);
77+
}
78+
79+
[Fact]
80+
public void ShouldClear()
81+
{
82+
var sut = ObjectPool.Create<TestObj>();
83+
FillPool(sut, 5);
84+
85+
sut.Count.Should().Be(5);
86+
sut.Clear();
87+
sut.Count.Should().Be(0);
88+
}
89+
90+
[Fact]
91+
public void ShouldDisposeItems()
92+
{
93+
var sut = ObjectPool.Create<TestObjDisposable>();
94+
TestObjDisposable[] rents =
95+
[
96+
sut.Rent(),
97+
sut.Rent(),
98+
sut.Rent(),
99+
];
100+
101+
foreach (var r in rents)
102+
sut.Return(r);
103+
104+
sut.Count.Should().Be(rents.Length);
105+
sut.Dispose();
106+
rents.Should().AllSatisfy(r => r.Disposed.Should().BeTrue());
107+
}
108+
109+
static void FillPool(ObjectPool<TestObj> sut, int count) =>
110+
Enumerable.Repeat<object?>(null, count)
111+
.Select(_ => sut.Rent())
112+
.ToList()
113+
.ForEach(x => sut.Return(x));
114+
115+
[Serializable]
116+
sealed class TestObj
117+
{
118+
public int Value { get; set; }
119+
public bool Returned { get; set; }
120+
}
121+
122+
sealed class TestObjDisposable : IDisposable
123+
{
124+
public bool Disposed { get; private set; }
125+
public void Dispose() => Disposed = true;
126+
}
127+
}

0 commit comments

Comments
 (0)