-
Notifications
You must be signed in to change notification settings - Fork 23
/
Copy pathContractTest.cs
249 lines (206 loc) · 9.35 KB
/
ContractTest.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
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
using Meadow.Contract;
using Meadow.Core.EthTypes;
using Meadow.Core.Utils;
using Meadow.CoverageReport;
using Meadow.JsonRpc.Client;
using Meadow.JsonRpc.Types.Debugging;
using Meadow.TestNode;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Net;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
namespace Meadow.UnitTestTemplate
{
[MeadowTestClass]
public abstract class ContractTest
{
#region Fields
private ulong? _baseSnapshotID;
private static Semaphore _sequentialExecutionSemaphore = new Semaphore(1, 1);
#endregion
#region Properties
internal InternalTestState InternalTestState
{
get
{
return TestContext.GetInternalTestState();
}
set
{
TestContext?.SetInternalTestState(value);
}
}
public TestContext TestContext { get; set; }
public TestServices TestServices { get; private set; }
public Address[] Accounts => TestServices.Accounts;
public IJsonRpcClient RpcClient => TestServices.TestNodeClient;
public TestNodeServer TestNodeServer => TestServices.TestNodeServer;
public MeadowAsserter Assert { get; } = MeadowAsserter.Instance;
public CollectionAsserter CollectionAssert { get; } = new CollectionAsserter();
#endregion
#region Functions
/// <summary>
/// Virtual method which is run before every test is executed. Can be overriden to
/// deploy contracts before a test automatically, or etc.
/// </summary>
/// <returns></returns>
protected virtual Task BeforeEach() => Task.CompletedTask;
[TestInitialize]
public async Task OnTestInitialize()
{
try
{
// With parallel tests, all code should execute in pairs (main vs. external for every test)
// so we need to ensure sequential execution to avoid issues with other tests running and trying
// to snapshot, execute, restore on the external node, ending up with a race condition.
// In general, if we are executing on an external node, to avoid race conditions with other threads, we lock.
if (Global.ExternalNodeTestServices != null)
{
_sequentialExecutionSemaphore.WaitOne();
}
// If we only want to use the external node, set the external node override.
if (Global.OnlyUseExternalNode.GetValueOrDefault())
{
InternalTestState.InExternalNodeContext = true;
}
// Determine if we're using an external testing service or one of the built in ones.
if (InternalTestState.InExternalNodeContext)
{
// Using an external node for testing.
TestServices = Global.ExternalNodeTestServices;
}
else
{
// Using a built in node from our pool for testing.
TestServices = await Global.TestServicesPool.Get();
}
// We set the test start recording time initially in case we hit an exception while processing the underlying code.
InternalTestState.StartTime = DateTimeOffset.UtcNow;
// Create a snapshot to revert to when test is completed.
if (!_baseSnapshotID.HasValue)
{
_baseSnapshotID = await TestServices.TestNodeClient.Snapshot();
}
// Determine what message to log
if (InternalTestState.InExternalNodeContext)
{
LogDebug($"Using external node at host name \"{Global.ExternalNodeHost.Host}\" on port \"{Global.ExternalNodeHost.Port}\", snapshot: {_baseSnapshotID}");
}
else
{
LogDebug($"Using built-in local test node on port {TestNodeServer.RpcServer.ServerPort}, snapshot: {_baseSnapshotID}");
}
// Execute our pre-test method
await BeforeEach();
// Set our initialization as successful
InternalTestState.InitializationSuccess = true;
// If we haven't hit an exception, then we refresh start recording time from this point (the end of our test initialization).
InternalTestState.StartTime = DateTimeOffset.UtcNow;
}
catch (Exception ex)
{
Log($"Exception in {nameof(ContractTest)}.{nameof(OnTestInitialize)}: " + ex.ToString());
throw;
}
}
[TestCleanup]
public async Task OnTestCleanup()
{
try
{
// Obtain our end time.
InternalTestState.EndTime = DateTime.Now;
// If we're testing a built in node, we'll want to be collecting relevant coverage information.
if (!InternalTestState.InExternalNodeContext)
{
// Get all coverage map data from the node.
var coverageMapData = await RpcClient.GetAllCoverageMaps();
// Clear coverage for the next unit test that uses this node.
await RpcClient.ClearCoverage();
if (!TestContext.Properties.ContainsKey(nameof(SkipCoverageAttribute)))
{
// Match coverage contract addresses with deployed contracts that the client keeps track of.
var contractInstances = GeneratedSolcData.Default.MatchCoverageData(coverageMapData);
// Store the coverage data for the report generation at end of tests.
Global.CoverageMaps.Add(contractInstances);
}
}
// Revert the node chain for the next unit test to start with a clean slate.
await TestServices.TestNodeClient.Revert(_baseSnapshotID.Value);
// Calculate our time elapsed.
var testDuration = (InternalTestState.EndTime - InternalTestState.StartTime);
// Log the duration to the console.
LogDebug($"{TestContext.CurrentTestOutcome.ToString()} - {Math.Round(testDuration.TotalMilliseconds)} ms");
// If the built in node, we'll want to be collecting relevant testing data.
if (!InternalTestState.InExternalNodeContext)
{
// Initialize our test outcome/results.
var testOutcome = new UnitTestResult
{
Namespace = TestContext.FullyQualifiedTestClassName,
TestName = InternalTestState.CustomDisplayName ?? TestContext.TestName,
Passed = TestContext.CurrentTestOutcome == UnitTestOutcome.Passed,
Duration = testDuration
};
// Add the test to our global testing result test output.
Global.UnitTestResults.Add(testOutcome);
// As this is our built in node, we put the test services back in the pool.
await Global.TestServicesPool.PutAsync(TestServices);
}
// Blank out the local test services after the test has completed.
TestServices = null;
// If we are running an external node, we'll want to make tests run sequentially.
if (Global.ExternalNodeTestServices != null)
{
_sequentialExecutionSemaphore.Release();
}
}
catch (Exception ex)
{
throw new Exception("Critical exeption: Cleanup failed in ContractTest - " + ex.Message, ex);
}
finally
{
// Reset test state so its not reused in another test.
InternalTestState = null;
}
}
/// <summary>
/// Temporarily disable the contract size limit during the execution of the provided callback.
/// </summary>
public async Task DisableContractSizeLimit(Func<Task> executionCallback)
{
await RpcClient.SetContractSizeCheckDisabled(true);
try
{
await executionCallback();
}
finally
{
await RpcClient.SetContractSizeCheckDisabled(false);
}
}
/// <summary>
/// Log a message to the console/debug output with a standardized format.
/// </summary>
/// <param name="msg">The message to log.</param>
public void Log(object msg)
{
var msgStr = msg.ToString();
TestContext.WriteLine(msgStr);
var globalMsg = $"[{TestContext.FullyQualifiedTestClassName}] {msgStr}";
Console.WriteLine(globalMsg);
Debug.WriteLine(globalMsg);
}
[Conditional("DEBUG_UNITTESTS")]
public void LogDebug(object msg)
{
Log(msg);
}
#endregion
}
}