Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add new unit tests #190

Merged
merged 1 commit into from
Jan 6, 2025
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
68 changes: 68 additions & 0 deletions Tests/NFUnitTestStringBuilder/StringBuilderTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -443,6 +443,74 @@ public void Clear_AtMaxCapacity_CapacityStaysUnchanged()
builder.Clear();
Assert.AreEqual(14, builder.Capacity);
}

[TestMethod]
[DataRow(1)]
[DataRow(10000)]
public void Clear_AppendAndInsertBeforeClearManyTimes_CapacityStaysWithinRange(int times)
{
var builder = new StringBuilder();
var originalCapacity = builder.Capacity;
var s = new string(' ', 10);
int oldLength = 0;
for (int i = 0; i < times; i++)
{
builder.Append(s);
builder.Append(s);
builder.Append(s);
builder.Insert(0, s, 1);
builder.Insert(0, s, 1);
oldLength = builder.Length;

builder.Clear();
}
Assert.IsTrue(builder.Capacity >= 1 && builder.Capacity <= oldLength * 1.2);
}

[TestMethod]
public void Clear_InitialCapacityMuchLargerThanLength_CapacityReducedToInitialCapacity()
{
var builder = new StringBuilder(100);
var initialCapacity = builder.Capacity;
builder.Append(new string('a', 40));
builder.Insert(0, new string('a', 10), 1);
builder.Insert(0, new string('a', 10), 1);
builder.Insert(0, new string('a', 10), 1);
var oldCapacity = builder.Capacity;
var oldLength = builder.Length;
builder.Clear();
Assert.AreNotEqual(oldCapacity, builder.Capacity);
Assert.AreEqual(initialCapacity, builder.Capacity);
Assert.IsFalse(builder.Capacity >= 1 && builder.Capacity <= oldLength * 1.2);

// find max between initial capacity and 1.2 * old length
int maxCapacity = initialCapacity > (int)(oldLength * 1.2) ? initialCapacity : (int)(oldLength * 1.2);

Assert.IsTrue(builder.Capacity >= 1 && builder.Capacity <= maxCapacity);
}

[TestMethod]
public void Clear_StringBuilderHasTwoChunks_OneChunkIsEmpty_ClearReducesCapacity()
{
var sb = new StringBuilder(string.Empty);
int initialCapacity = sb.Capacity;
for (int i = 0; i < initialCapacity; i++)
{
sb.Append('a');
}

sb.Insert(0, new char[] { 'a' }, 0, 1);

while (sb.Length > 1)
{
sb.Remove(1, 1);
}

int oldCapacity = sb.Capacity;
sb.Clear();
Assert.AreEqual(oldCapacity - 1, sb.Capacity);
Assert.AreEqual(initialCapacity, sb.Capacity);
}
}

static class RandomExtension
Expand Down