mirror of https://github.com/SixLabors/ImageSharp
7 changed files with 177 additions and 27 deletions
@ -0,0 +1,43 @@ |
|||||
|
// Copyright (c) Six Labors.
|
||||
|
// Licensed under the Apache License, Version 2.0.
|
||||
|
|
||||
|
using System; |
||||
|
using System.Diagnostics; |
||||
|
using SixLabors.ImageSharp.Diagnostics; |
||||
|
using Xunit; |
||||
|
|
||||
|
namespace SixLabors.ImageSharp.Tests |
||||
|
{ |
||||
|
public static class MemoryAllocatorValidator |
||||
|
{ |
||||
|
public static IDisposable MonitorAllocations(int max = 0) |
||||
|
{ |
||||
|
MemoryDiagnostics.Current = new(); |
||||
|
return new TestMemoryAllocatorDisposable(max); |
||||
|
} |
||||
|
|
||||
|
public static void ValidateAllocation(int max = 0) |
||||
|
{ |
||||
|
var count = MemoryDiagnostics.TotalUndisposedAllocationCount; |
||||
|
var pass = count <= max; |
||||
|
Assert.True(pass, $"Expected a max of {max} undisposed buffers but found {count}"); |
||||
|
|
||||
|
if (count > 0) |
||||
|
{ |
||||
|
Debug.WriteLine("We should have Zero undisposed memory allocations."); |
||||
|
} |
||||
|
|
||||
|
MemoryDiagnostics.Current = null; |
||||
|
} |
||||
|
|
||||
|
public struct TestMemoryAllocatorDisposable : IDisposable |
||||
|
{ |
||||
|
private readonly int max; |
||||
|
|
||||
|
public TestMemoryAllocatorDisposable(int max) => this.max = max; |
||||
|
|
||||
|
public void Dispose() |
||||
|
=> ValidateAllocation(this.max); |
||||
|
} |
||||
|
} |
||||
|
} |
||||
@ -0,0 +1,36 @@ |
|||||
|
// Copyright (c) Six Labors.
|
||||
|
// Licensed under the Apache License, Version 2.0.
|
||||
|
|
||||
|
using System; |
||||
|
using System.Diagnostics; |
||||
|
using System.Reflection; |
||||
|
using Xunit.Sdk; |
||||
|
|
||||
|
namespace SixLabors.ImageSharp.Tests |
||||
|
{ |
||||
|
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)] |
||||
|
public class ValidateDisposedMemoryAllocationsAttribute : BeforeAfterTestAttribute |
||||
|
{ |
||||
|
private readonly int max = 0; |
||||
|
|
||||
|
public ValidateDisposedMemoryAllocationsAttribute() |
||||
|
: this(0) |
||||
|
{ |
||||
|
} |
||||
|
|
||||
|
public ValidateDisposedMemoryAllocationsAttribute(int max) |
||||
|
{ |
||||
|
this.max = max; |
||||
|
if (max > 0) |
||||
|
{ |
||||
|
Debug.WriteLine("Needs fixing, we shoudl have Zero undisposed memory allocations."); |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
public override void Before(MethodInfo methodUnderTest) |
||||
|
=> MemoryAllocatorValidator.MonitorAllocations(this.max); // the disposable isn't important cause the validate below does the same thing
|
||||
|
|
||||
|
public override void After(MethodInfo methodUnderTest) |
||||
|
=> MemoryAllocatorValidator.ValidateAllocation(this.max); |
||||
|
} |
||||
|
} |
||||
Loading…
Reference in new issue