-
Notifications
You must be signed in to change notification settings - Fork 1.9k
/
TestWrappedBase.cs
119 lines (99 loc) · 3.99 KB
/
TestWrappedBase.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
using cs_testcommon;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using VLD;
namespace cs_leaktest
{
public class TestWrappedBase
{
[DllImport("kernel32", SetLastError = true, CharSet = CharSet.Ansi)]
static extern IntPtr LoadLibrary([MarshalAs(UnmanagedType.LPStr)]string lpFileName);
[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool FreeLibrary(IntPtr hModule);
/// <summary>
/// Implement custom StackTrace so one can easily click in Test Explorer
/// </summary>
internal class CustomException : Exception
{
private readonly string stackTrace;
internal CustomException(string message, string stackTrace) : base(message)
{
this.stackTrace = stackTrace;
}
public override string StackTrace
{
get
{
return this.stackTrace;
}
}
}
public TestContext TestContext { get; set; }
private object lockObject = new object();
protected void Run(string type, string method)
{
lock (lockObject)
{
using (var vld = new VisualLeakDetector())
{
try
{
// vowpalwabbit\x64\Debug\cs_leaktest.dll
var basePath = Path.GetDirectoryName(typeof(VisualLeakDetector).Assembly.Location);
var handle = LoadLibrary(basePath + @"\\VowpalWabbitCore.dll");
var appDomain = AppDomain.CreateDomain("Test1");
try
{
ITestRunner test1 = (ITestRunner)appDomain.CreateInstanceFromAndUnwrap(basePath + @"\\cs_unittest.dll", "cs_unittest.TestRunner");
Environment.CurrentDirectory = basePath + @"\..\..\..\test";
var result = test1.Run(type, method);
if (result != null)
{
// check for exception marker
var index = result.IndexOf("#-#-#-#-#-#-#");
if (index == -1)
{
Assert.Fail(result);
}
throw new CustomException(result.Substring(0, index), result.Substring(index + 13));
}
}
finally
{
AppDomain.Unload(appDomain);
}
try
{
FreeLibrary(handle);
FreeLibrary(handle);
vld.ReportLeaks();
var message = string.Concat(vld.Messages.Select(t => t.Item2));
var blocks = message.Split(new[] { "---------- Block " }, StringSplitOptions.None)
.Where(block => Regex.IsMatch(block, "^\\d+ at"))
.ToList();
Assert.AreEqual(0, blocks.Count, string.Join("\n", blocks));
}
finally
{
LoadLibrary(basePath + @"\VowpalWabbitCore.dll");
}
}
finally
{
vld.MarkAllLeaksAsReported();
}
}
}
}
}
}