Skip to content

Commit

Permalink
Refactored test runner. Tests can have static time.
Browse files Browse the repository at this point in the history
  • Loading branch information
codeape2 committed Nov 21, 2016
1 parent 04e88af commit e50be6d
Show file tree
Hide file tree
Showing 9 changed files with 179 additions and 24 deletions.
20 changes: 19 additions & 1 deletion UnitTests/DirectoryCreator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,25 @@ public DirectoryCreator(string directoryName = null)
public void AddFile(string filename, string content)
{
Directory.CreateDirectory(Path.Combine(_directoryName, Path.GetDirectoryName(filename)));
File.WriteAllText(Path.Combine(_directoryName, filename), content);
var filepath = Path.Combine(_directoryName, filename);
if (File.Exists(filepath))
{
throw new ArgumentException($"File {filepath} exists");
}
File.WriteAllText(filepath, content);
}

public void DeleteFile(string filename)
{
var filepath = Path.Combine(_directoryName, filename);
if (File.Exists(filepath))
{
File.Delete(filepath);
}
else
{
throw new FileNotFoundException(filepath);
}
}

public string DirectoryName => _directoryName;
Expand Down
12 changes: 12 additions & 0 deletions UnitTests/IntegrationTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,12 @@ public void KnownConfigurationsTestOK()
CheckConfigdirectory(directory);
}
}

[Fact]
public void ShowResponseWorksAsExpected()
{
CheckOutput("examples/example1", 0);
}

public void CheckConfigdirectory(string directory)
{
Expand All @@ -60,5 +66,11 @@ public void CheckConfigdirectory(string directory)
Assert.True(result.OK, $"Test case {result.TestCase.Name}, message '{result.Message}'");
}
}

public void CheckOutput(string directory, int index)
{
var testRunner = new TestRunner(EndpointCollectionReader.ReadFromDirectory(directory));
testRunner.ShowResponse(index);
}
}
}
10 changes: 8 additions & 2 deletions UnitTests/TestDynamicResponse.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@

namespace UnitTests
{
public class TestDynamicResponse
public class TestDynamicResponse
{
static public string Eval(string code, RequestInfo requestInfo = null)
{
Expand All @@ -18,14 +18,20 @@ static public string Eval(string code, RequestInfo requestInfo = null)
requestInfo = new RequestInfo();
}
return new LiteralDynamicResponseCreator(code).GetBody(requestInfo);
//return DynamicResponseCreatorBase.Evaluate(code, requestInfo);
}

[Fact]
public void CanExecuteCode()
{
Assert.Equal("42", Eval("(40+2).ToString()"));
}

[Fact]
public void GetNowWorks()
{
Assert.Equal("System.DateTime", Eval("GetNow().GetType().ToString()"));
}

[Fact]
public void CompilationErrorsAreThrown()
{
Expand Down
41 changes: 38 additions & 3 deletions UnitTests/TestTestCommand.cs
Original file line number Diff line number Diff line change
Expand Up @@ -56,12 +56,17 @@ public static class TESTCOMMAND_CONSTANTS
'name': '/foo/ request works',
'requestpath': '/foo/',
'requestbody': 'file:example.txt',
'expectedresponsebody': 'file:example.txt',
'expectedresponsebody': 'file:example.txt'
},
{
'name': 'Getnow works',
'requestpath': '/getnow/',
'expectedrequestmatcher': 'Any request',
'expectedresponsebody': '2015-01-01 12:01:31'
}
]
";

}

public class TestTestCommandWithoutTestsuite : IDisposable
Expand Down Expand Up @@ -104,11 +109,15 @@ public TestTestCommand()
dc.AddFile("endpoint1\\content.txt", "FOOBARBOOBAR");
dc.AddFile("tests\\tests.json", TESTCOMMAND_CONSTANTS.TESTS);
dc.AddFile("tests\\example.txt", "FOOBARBOOBAR");
dc.AddFile("tests\\now.txt", "2015-01-01 12:01:31");
dc.AddFile("getnow\\endpoint.json", "{'name': 'GetNow', 'pathregex': '/getnow/', 'responses': [{'match': {}, 'response': {'script':'getnow.csscript'}}]}");
dc.AddFile("getnow\\getnow.csscript", "GetNow().ToString(\"yyyy-MM-dd HH:mm:ss\")");
}

public void Dispose()
{
dc.Dispose();
RequestInfo.SetDynamicNow();
}

[Fact]
Expand All @@ -122,7 +131,7 @@ public void DetectsTestSuite()
public void CanReadTestsFromJSONFile()
{
var endpointTestDefinition = EndpointTestDefinition.ReadFromDirectory(dc.DirectoryName);
Assert.Equal(3, endpointTestDefinition.Tests.Count());
Assert.Equal(4, endpointTestDefinition.Tests.Count());
var test = endpointTestDefinition.Tests.ElementAt(0);
Assert.Equal("/foo/ request works", test.Name);
Assert.Equal("/foo/", test.RequestPath);
Expand All @@ -146,6 +155,32 @@ async public void RequestBodyCanBeUnspecified()
Assert.True(result.OK, result.Message);
}

[Fact]
public void TestsHaveConstantGetNow()
{
var testRunner = new TestRunner(EndpointCollectionReader.ReadFromDirectory(dc.DirectoryName));
var result = testRunner.ExecuteTestAndOutputResult(3);
Assert.True(result.OK, result.ResultAsString);
}

[Fact]
public void TestsCanHaveDynamicNow()
{
dc.DeleteFile("tests\\now.txt");
var testRunner = new TestRunner(EndpointCollectionReader.ReadFromDirectory(dc.DirectoryName));
var result = testRunner.ExecuteTestAndOutputResult(3);
Assert.True(result.Error, result.ResultAsString);
Assert.Null(result.Exception);
}

[Fact]
public void SetStaticGetNow()
{
RequestInfo.SetStaticNow(new DateTime(2015, 6, 7, 8, 9, 10));
Assert.Equal("2015-06-07 08:09:10", TestDynamicResponse.Eval("GetNow().ToString(\"yyyy-MM-dd HH:mm:ss\")"));
}


[Fact]
public void RequestBodyCanBeReadFromFile()
{
Expand Down
12 changes: 12 additions & 0 deletions netmockery/EndpointTestDefinition.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@

namespace netmockery
{
//TODO: Merge with TestRunner?
public class EndpointTestDefinition
{
private NetmockeryTestCase[] testcases;
Expand All @@ -24,7 +25,18 @@ static public bool HasTestSuite(string directory)

static private string tests_directory(string directory) => Path.Combine(directory, "tests");

public void SetStaticTimeIfConfigured(string directory)
{
if (File.Exists(now_txt_filename(directory)))
{
var contents = File.ReadAllText(now_txt_filename(directory));
var datetime = DateTime.ParseExact(contents, "yyyy-MM-dd HH:mm:ss", null);
RequestInfo.SetStaticNow(datetime);
}
}

static private string tests_json_filename(string directory) => Path.Combine(tests_directory(directory), "tests.json");
static private string now_txt_filename(string directory) => Path.Combine(tests_directory(directory), "now.txt");

public static EndpointTestDefinition ReadFromDirectory(string directory)
{
Expand Down
2 changes: 1 addition & 1 deletion netmockery/NetmockeryTestCase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -182,7 +182,7 @@ async public Task<Tuple<string, string>> GetResponseAsync(EndpointCollection end
if (matcher_and_creator != null)
{
var responseCreator = matcher_and_creator.Item2;
var responseBodyBytes = await responseCreator.CreateResponseAsync(new TestCaseHttpRequest(RequestPath, QueryString), Encoding.UTF8.GetBytes(RequestBody), new TestCaseHttpResponse(), endpoint.Directory);
var responseBodyBytes = await responseCreator.CreateResponseAsync(new TestCaseHttpRequest(RequestPath, QueryString), Encoding.UTF8.GetBytes(RequestBody ?? ""), new TestCaseHttpResponse(), endpoint.Directory);
return Tuple.Create(Encoding.UTF8.GetString(responseBodyBytes), (string)null);
}
else
Expand Down
24 changes: 7 additions & 17 deletions netmockery/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -120,34 +120,24 @@ public static void Test(string[] commandArgs)
{
if (EndpointTestDefinition.HasTestSuite(EndpointCollection.SourceDirectory))
{
var testDefinitions = EndpointTestDefinition.ReadFromDirectory(EndpointCollection.SourceDirectory);

var testRunner = new TestRunner(EndpointCollection);
var only = getSwitchValue(commandArgs, "--only");
if (only != null)
{
var index = int.Parse(only);
var testCase = testDefinitions.Tests.ElementAt(index);

if (containsSwitch(commandArgs, "--showResponse"))
{
var response = testCase.GetResponseAsync(EndpointCollection).Result;
if (response.Item2 != null)
{
Error.WriteLine($"ERROR: {response.Item2}");
}
else
{
WriteLine(response.Item1);
}
testRunner.ShowResponse(index);
}
else
{
ExecuteTestAndOutputResult(index, testCase);
testRunner.ExecuteTestAndOutputResult(index);
}

return;
}
TestAll(testDefinitions);
else
{
testRunner.TestAll();
}
}
else
{
Expand Down
14 changes: 14 additions & 0 deletions netmockery/ResponseCreator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,20 @@ public class RequestInfo
public string RequestBody;
public IHeaderDictionary Headers;
public string EndpointDirectory;

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

private static DateTime _now = DateTime.MinValue;

public static void SetStaticNow(DateTime now)
{
_now = now;
}

public static void SetDynamicNow()
{
_now = DateTime.MinValue;
}
}

public class BodyReplacement
Expand Down
68 changes: 68 additions & 0 deletions netmockery/TestRunner.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using static System.Console;

namespace netmockery
{
public class TestRunner
{
private EndpointTestDefinition endpointTestDefinition;
private EndpointCollection endpointCollection;

public TestRunner(EndpointCollection endpointCollection)
{
this.endpointCollection = endpointCollection;
Debug.Assert(EndpointTestDefinition.HasTestSuite(endpointCollection.SourceDirectory));
endpointTestDefinition = EndpointTestDefinition.ReadFromDirectory(endpointCollection.SourceDirectory);

endpointTestDefinition.SetStaticTimeIfConfigured(endpointCollection.SourceDirectory);
}

public void TestAll()
{
var errors = 0;
var index = 0;
foreach (var test in endpointTestDefinition.Tests)
{
var result = ExecuteTestAndOutputResult(index++, test);
if (result.Error)
{
errors++;
}
}
WriteLine();
WriteLine($"Total: {endpointTestDefinition.Tests.Count()} Errors: {errors}");
}

public NetmockeryTestCaseResult ExecuteTestAndOutputResult(int index)
{
return ExecuteTestAndOutputResult(index, endpointTestDefinition.Tests.ElementAt(index));
}

public NetmockeryTestCaseResult ExecuteTestAndOutputResult(int index, NetmockeryTestCase test)
{
Write($"{index.ToString().PadLeft(3)} {test.Name.PadRight(60)}");
var result = test.ExecuteAsync(endpointCollection).Result;
WriteLine(result.ResultAsString);
return result;
}

public void ShowResponse(int index)
{
var testCase = endpointTestDefinition.Tests.ElementAt(index);
var response = testCase.GetResponseAsync(endpointCollection).Result;
if (response.Item2 != null)
{
Error.WriteLine($"ERROR: {response.Item2}");
}
else
{
WriteLine(response.Item1);
}
}

}
}

0 comments on commit e50be6d

Please sign in to comment.