Skip to content

Commit 6e84575

Browse files
committed
Refactored test runner. Only supports simpleresponsecreator.
+ Removed static now
1 parent 104fc91 commit 6e84575

File tree

8 files changed

+114
-45
lines changed

8 files changed

+114
-45
lines changed

UnitTests/IntegrationTests.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -61,7 +61,7 @@ public void CheckConfigdirectory(string directory)
6161
foreach (var test in tests.Tests)
6262
{
6363
output.WriteLine(test.Name);
64-
var result = test.ExecuteAsync(endpointCollection).Result;
64+
var result = test.ExecuteAsync(endpointCollection, now: tests.Now).Result;
6565
output.WriteLine(result.ResultAsString);
6666
Assert.True(result.OK, $"Test case {result.TestCase.Name}, message '{result.Message}'");
6767
}

UnitTests/TestDynamicResponse.cs

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,12 +11,16 @@ namespace UnitTests
1111
{
1212
public class TestDynamicResponse
1313
{
14-
static public string Eval(string code, RequestInfo requestInfo = null)
14+
static public string Eval(string code, RequestInfo requestInfo = null, DateTime? now = null)
1515
{
1616
if (requestInfo == null)
1717
{
1818
requestInfo = new RequestInfo();
1919
}
20+
if (now != null)
21+
{
22+
requestInfo.SetStaticNow(now.Value);
23+
}
2024
return new LiteralDynamicResponseCreator(code).GetBody(requestInfo);
2125
}
2226

UnitTests/TestTestCommand.cs

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -123,7 +123,6 @@ public TestTestCommand()
123123
public void Dispose()
124124
{
125125
dc.Dispose();
126-
RequestInfo.SetDynamicNow();
127126
}
128127

129128
[Fact]
@@ -190,8 +189,7 @@ public void TestsCanHaveDynamicNow()
190189
[Fact]
191190
public void SetStaticGetNow()
192191
{
193-
RequestInfo.SetStaticNow(new DateTime(2015, 6, 7, 8, 9, 10));
194-
Assert.Equal("2015-06-07 08:09:10", TestDynamicResponse.Eval("GetNow().ToString(\"yyyy-MM-dd HH:mm:ss\")"));
192+
Assert.Equal("2015-06-07 08:09:10", TestDynamicResponse.Eval("GetNow().ToString(\"yyyy-MM-dd HH:mm:ss\")", now: new DateTime(2015, 6, 7, 8, 9, 10)));
195193
}
196194

197195

netmockery/CommandLineParser.cs

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -19,14 +19,15 @@ static public class CommandLineParser
1919
private const string BOOL_SWITCH_SHOWRESPONSE = "--showResponse";
2020
private const string BOOL_SWITCH_NOTESTMODE = "--notestmode";
2121
private const string BOOL_SWITCH_STOP = "--stop";
22+
private const string BOOL_SWITCH_DIFF = "--diff";
2223

2324
static private string[] VALUE_SWITCHES = new[] { VALUE_SWITCH_URL, VALUE_SWITCH_ONLY };
24-
static private string[] BOOL_SWITCHES = new[] { BOOL_SWITCH_SHOWRESPONSE, BOOL_SWITCH_NOTESTMODE, BOOL_SWITCH_STOP };
25+
static private string[] BOOL_SWITCHES = new[] { BOOL_SWITCH_SHOWRESPONSE, BOOL_SWITCH_NOTESTMODE, BOOL_SWITCH_STOP, BOOL_SWITCH_DIFF };
2526

2627
static private Dictionary<int, string[]> VALID_SWITHCES_BY_COMMAND = new Dictionary<int, string[]> {
2728
{ COMMAND_NORMAL, new[] { VALUE_SWITCH_URL, BOOL_SWITCH_NOTESTMODE } },
2829
{ COMMAND_SERVICE, new[] { VALUE_SWITCH_URL } },
29-
{ COMMAND_TEST, new[] { VALUE_SWITCH_URL, VALUE_SWITCH_ONLY, BOOL_SWITCH_SHOWRESPONSE, BOOL_SWITCH_STOP} },
30+
{ COMMAND_TEST, new[] { VALUE_SWITCH_URL, VALUE_SWITCH_ONLY, BOOL_SWITCH_SHOWRESPONSE, BOOL_SWITCH_STOP, BOOL_SWITCH_DIFF} },
3031
{ COMMAND_DUMP, new string[0] }
3132
};
3233

@@ -143,6 +144,7 @@ static public ParsedCommandLine ParseArguments(string[] args)
143144
ShowResponse = boolValues[BOOL_SWITCH_SHOWRESPONSE],
144145
NoTestMode = boolValues[BOOL_SWITCH_NOTESTMODE],
145146
Stop = boolValues[BOOL_SWITCH_STOP],
147+
Diff = boolValues[BOOL_SWITCH_DIFF]
146148
};
147149
}
148150
}
@@ -167,6 +169,7 @@ public class ParsedCommandLine
167169
public bool ShowResponse;
168170
public bool NoTestMode;
169171
public bool Stop;
172+
public bool Diff;
170173

171174
public bool TestMode => !NoTestMode;
172175
}

netmockery/NetmockeryTestCase.cs

Lines changed: 35 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -176,7 +176,7 @@ async public Task<NetmockeryTestCaseResult> ExecuteAgainstUrlAsync(string url)
176176
private const string ERROR_ENDPOINT_HAS_NO_MATCH = "Endpoint has no match for request";
177177

178178

179-
async public Task<NetmockeryTestCaseResult> ExecuteAsync(EndpointCollection endpointCollection, bool handleErrors=true)
179+
async public Task<NetmockeryTestCaseResult> ExecuteAsync(EndpointCollection endpointCollection, bool handleErrors=true, DateTime? now=null)
180180
{
181181
Debug.Assert(endpointCollection != null);
182182

@@ -204,14 +204,25 @@ async public Task<NetmockeryTestCaseResult> ExecuteAsync(EndpointCollection endp
204204
string responseBody = null;
205205
if (NeedsResponseBody)
206206
{
207-
var httpResponse = new TestCaseHttpResponse();
208-
var responseBodyBytes = await responseCreator.CreateResponseAsync(
209-
new TestCaseHttpRequest(RequestPath, QueryString),
210-
Encoding.UTF8.GetBytes(RequestBody ?? ""),
211-
httpResponse,
212-
endpoint.Directory
213-
);
214-
responseBody = httpResponse.GetWrittenResponseAsString();
207+
var simpleResponseCreator = responseCreator as SimpleResponseCreator;
208+
if (simpleResponseCreator == null)
209+
{
210+
return testResult.SetFailure($"Response creator {responseCreator.ToString()} not supported by test framework");
211+
}
212+
213+
var requestInfo = new RequestInfo
214+
{
215+
EndpointDirectory = endpoint.Directory,
216+
Headers = null,
217+
RequestPath = RequestPath,
218+
QueryString = QueryString,
219+
RequestBody = RequestBody
220+
};
221+
if (now != null)
222+
{
223+
requestInfo.SetStaticNow(now.Value);
224+
}
225+
responseBody = simpleResponseCreator.GetBodyAndExecuteReplacements(requestInfo);
215226
}
216227
string message;
217228
if (Evaluate(matcher_and_creator.RequestMatcher.ToString(), matcher_and_creator.ResponseCreator.ToString(), responseBody, out message))
@@ -240,9 +251,21 @@ async public Task<Tuple<string, string>> GetResponseAsync(EndpointCollection end
240251
var matcher_and_creator = endpoint.Resolve(new PathString(RequestPath), new QueryString(QueryString), RequestBody, null);
241252
if (matcher_and_creator != null)
242253
{
243-
var responseCreator = matcher_and_creator.ResponseCreator;
244-
var responseBodyBytes = await responseCreator.CreateResponseAsync(new TestCaseHttpRequest(RequestPath, QueryString), Encoding.UTF8.GetBytes(RequestBody ?? ""), new TestCaseHttpResponse(), endpoint.Directory);
245-
return Tuple.Create(Encoding.UTF8.GetString(responseBodyBytes), (string)null);
254+
var responseCreator = matcher_and_creator.ResponseCreator as SimpleResponseCreator;
255+
if (responseCreator == null)
256+
{
257+
return Tuple.Create((string)null, $"This response creator is not supported by test framework: {matcher_and_creator.ResponseCreator.ToString()}");
258+
}
259+
260+
var responseBody = responseCreator.GetBodyAndExecuteReplacements(new RequestInfo
261+
{
262+
EndpointDirectory = endpoint.Directory,
263+
Headers = null,
264+
QueryString = QueryString,
265+
RequestBody = RequestBody,
266+
RequestPath = RequestPath
267+
});
268+
return Tuple.Create(responseBody, (string)null);
246269
}
247270
else
248271
{

netmockery/Program.cs

Lines changed: 59 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -100,34 +100,78 @@ static public void RunAsService(ParsedCommandLine commandArgs)
100100

101101
public static void Test(ParsedCommandLine commandArgs, EndpointCollection endpointCollection)
102102
{
103-
if (TestRunner.HasTestSuite(endpointCollection.SourceDirectory))
103+
if (!TestRunner.HasTestSuite(endpointCollection.SourceDirectory))
104104
{
105-
var testRunner = new ConsoleTestRunner(endpointCollection);
106-
if (commandArgs.Url != null)
107-
{
108-
testRunner.Url = commandArgs.Url;
109-
}
110-
if (commandArgs.Only != null)
105+
Error.WriteLine("ERROR: No test suite found");
106+
return;
107+
}
108+
109+
if (commandArgs.Diff && commandArgs.Only == null)
110+
{
111+
Error.WriteLine("ERROR: --diff can only be specified with --only");
112+
return;
113+
}
114+
115+
var testRunner = new ConsoleTestRunner(endpointCollection);
116+
if (commandArgs.Url != null)
117+
{
118+
testRunner.Url = commandArgs.Url;
119+
}
120+
121+
if (commandArgs.Only != null)
122+
{
123+
var index = int.Parse(commandArgs.Only);
124+
if (commandArgs.Diff)
111125
{
112-
var index = int.Parse(commandArgs.Only);
113-
if (commandArgs.ShowResponse)
126+
var testCase = testRunner.Tests.ElementAt(index);
127+
if (testCase.ExpectedResponseBody == null)
114128
{
115-
testRunner.ShowResponse(index);
129+
Error.WriteLine($"ERROR: Test case has no expected response body");
130+
return;
116131
}
117-
else
132+
133+
var responseTuple = testCase.GetResponseAsync(endpointCollection).Result;
134+
if (responseTuple.Item2 != null)
118135
{
119-
testRunner.ExecuteTestAndOutputResult(index);
136+
Error.WriteLine($"ERROR: {responseTuple.Item2}");
137+
return;
120138
}
139+
140+
var expectedFilename = Path.GetTempFileName();
141+
var actualFilename = Path.GetTempFileName();
142+
143+
File.WriteAllText(expectedFilename, testCase.ExpectedResponseBody);
144+
File.WriteAllText(actualFilename, responseTuple.Item1);
145+
146+
StartExternalDiffTool(expectedFilename, actualFilename);
147+
148+
return;
149+
}
150+
if (commandArgs.ShowResponse)
151+
{
152+
testRunner.ShowResponse(index);
121153
}
122154
else
123155
{
124-
testRunner.TestAll(commandArgs.Stop, true);
125-
}
156+
testRunner.ExecuteTestAndOutputResult(index);
157+
}
126158
}
127159
else
128160
{
129-
Error.WriteLine("ERROR: No test suite found");
161+
testRunner.TestAll(commandArgs.Stop, true);
162+
}
163+
}
164+
165+
public static void StartExternalDiffTool(string expectedFilename, string actualFilename)
166+
{
167+
var difftool = Environment.GetEnvironmentVariable("DIFFTOOL");
168+
if (difftool == null)
169+
{
170+
Error.WriteLine("ERROR: No diff tool configured. Set DIFFTOOL environment variable to point to executable.");
171+
return;
130172
}
173+
174+
Process.Start(difftool, $"\"{expectedFilename}\" \"{actualFilename}\"");
131175
}
132176

133177

netmockery/ResponseCreator.cs

Lines changed: 3 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -76,6 +76,8 @@ public interface IResponseCreatorWithFilename
7676

7777
public class RequestInfo
7878
{
79+
private DateTime _now = DateTime.MinValue;
80+
7981
public string RequestPath;
8082
public string QueryString;
8183
public string RequestBody;
@@ -84,17 +86,10 @@ public class RequestInfo
8486

8587
public DateTime GetNow() => _now == DateTime.MinValue ? DateTime.Now : _now;
8688

87-
private static DateTime _now = DateTime.MinValue;
88-
89-
public static void SetStaticNow(DateTime now)
89+
public void SetStaticNow(DateTime now)
9090
{
9191
_now = now;
9292
}
93-
94-
public static void SetDynamicNow()
95-
{
96-
_now = DateTime.MinValue;
97-
}
9893
}
9994

10095
public class BodyReplacement

netmockery/TestRunner.cs

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -13,9 +13,12 @@ public abstract class TestRunner
1313
private IEnumerable<NetmockeryTestCase> testcases;
1414
protected EndpointCollection endpointCollection;
1515
protected HashSet<Tuple<string, int>> responsesCoveredByTests = new HashSet<Tuple<string, int>>();
16+
private DateTime? now;
1617

1718
public string Url { get; set; }
1819

20+
public DateTime? Now => now;
21+
1922
public TestRunner(EndpointCollection endpointCollection)
2023
{
2124
this.endpointCollection = endpointCollection;
@@ -31,8 +34,7 @@ public void SetStaticTimeIfConfigured(string directory)
3134
if (File.Exists(now_txt_filename(directory)))
3235
{
3336
var contents = File.ReadAllText(now_txt_filename(directory));
34-
var datetime = DateTime.ParseExact(contents, "yyyy-MM-dd HH:mm:ss", null);
35-
RequestInfo.SetStaticNow(datetime);
37+
now = DateTime.ParseExact(contents, "yyyy-MM-dd HH:mm:ss", null);
3638
}
3739
}
3840

@@ -102,7 +104,7 @@ public NetmockeryTestCaseResult ExecuteTestAndOutputResult(int index, Netmockery
102104
{
103105
WriteBeginTest(index, test);
104106

105-
var result = Url != null ? test.ExecuteAgainstUrlAsync(Url).Result : test.ExecuteAsync(endpointCollection).Result;
107+
var result = Url != null ? test.ExecuteAgainstUrlAsync(Url).Result : test.ExecuteAsync(endpointCollection, now: now).Result;
106108
WriteResult(result);
107109

108110
responsesCoveredByTests.Add(Tuple.Create(result.EndpointName, result.ResponseIndex));

0 commit comments

Comments
 (0)