Skip to content

Commit

Permalink
Various changes: documentation, test --viewResponse
Browse files Browse the repository at this point in the history
  • Loading branch information
codeape2 committed Nov 10, 2016
1 parent ed1b942 commit 38ad2ca
Show file tree
Hide file tree
Showing 9 changed files with 195 additions and 25 deletions.
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
Netmockery is a simple system for simulating network services.

The [documentation](netmockery/documentation.md) is a work in progress.
11 changes: 11 additions & 0 deletions UnitTests/TestTestCommand.cs
Original file line number Diff line number Diff line change
Expand Up @@ -185,6 +185,17 @@ async public void CanCheckExpectedRequestMatcherSuccess()
Assert.True(result.OK);
}

[Fact]
async public void CanGetResultBody()
{
var testcase =
(new JSONTest { name = "checksomething", requestpath = "/foo/", requestbody = "this is a test", expectedrequestmatcher = "Regex 'test'" })
.Validated().CreateTestCase(".");
var result = await testcase.GetResponseAsync(EndpointCollectionReader.ReadFromDirectory(dc.DirectoryName));
Assert.Equal("FOOBARBOOBAR", result.Item1);
Assert.Null(result.Item2);
}

[Fact]
async public void CanCheckExpectedResponseCreatorError()
{
Expand Down
7 changes: 6 additions & 1 deletion netmockery.sln
Original file line number Diff line number Diff line change
@@ -1,12 +1,17 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 14
VisualStudioVersion = 14.0.25123.0
VisualStudioVersion = 14.0.25420.1
MinimumVisualStudioVersion = 10.0.40219.1
Project("{8BB2217D-0F2D-49D1-97BC-3654ED321F3B}") = "netmockery", "netmockery\netmockery.xproj", "{3416FD6A-7658-4BEC-8467-13196D5FD2CA}"
EndProject
Project("{8BB2217D-0F2D-49D1-97BC-3654ED321F3B}") = "UnitTests", "UnitTests\UnitTests.xproj", "{10629440-1E0F-4677-8461-831C5251E96D}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{E789D0E5-31C6-4B48-A2F2-144D8336EAB3}"
ProjectSection(SolutionItems) = preProject
README.md = README.md
EndProjectSection
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Expand Down
11 changes: 9 additions & 2 deletions netmockery/Controllers/DocumentationController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,22 @@
using System.Linq;
using System.Threading.Tasks;
using HeyRed.MarkdownSharp;
using Microsoft.AspNetCore.Hosting;

namespace netmockery.Controllers
{
public class DocumentationController : Controller
{
private IHostingEnvironment _env;

public DocumentationController(IHostingEnvironment env)
{
_env = env;
}

public ActionResult Index()
{
var markdown = new Markdown();
var text = markdown.Transform(System.IO.File.ReadAllText("documentation.md"));
var text = new Markdown().Transform(System.IO.File.ReadAllText(System.IO.Path.Combine(_env.ContentRootPath, "documentation.md")));
return View("DisplayMarkdown", text);
}
}
Expand Down
4 changes: 2 additions & 2 deletions netmockery/JSONReader.cs
Original file line number Diff line number Diff line change
Expand Up @@ -22,10 +22,10 @@ public class JSONTest
public string requestpath;
public string querystring;
public string requestbody;
public string expectedresponsebody;

public string expectedrequestmatcher;
public string expectedresponsecreator;
public string expectedrequestcreator;
public string expectedresponsebody;

public JSONTest Validated()
{
Expand Down
30 changes: 28 additions & 2 deletions netmockery/NetmockeryTestCase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -126,6 +126,10 @@ public bool Evaluate(string requestMatcher, string responseCreator, string respo
return true;
}

private const string ERROR_NOMATCHING_ENDPOINT = "No endpoint matches request path";
private const string ERROR_ENDPOINT_HAS_NO_MATCH = "Endpoint has no match for request";


async public Task<NetmockeryTestCaseResult> ExecuteAsync(EndpointCollection endpointCollection, bool handleErrors=true)
{
Debug.Assert(endpointCollection != null);
Expand All @@ -136,7 +140,7 @@ async public Task<NetmockeryTestCaseResult> ExecuteAsync(EndpointCollection endp
var endpoint = endpointCollection.Resolve(RequestPath);
if (endpoint == null)
{
retval.SetFailure("No endpoint matches request path");
retval.SetFailure(ERROR_NOMATCHING_ENDPOINT);
}
else
{
Expand Down Expand Up @@ -169,7 +173,7 @@ async public Task<NetmockeryTestCaseResult> ExecuteAsync(EndpointCollection endp
}
else
{
retval.SetFailure("Endpoint has not match for request");
retval.SetFailure(ERROR_ENDPOINT_HAS_NO_MATCH);
}
}
}
Expand All @@ -180,6 +184,28 @@ async public Task<NetmockeryTestCaseResult> ExecuteAsync(EndpointCollection endp
}
return retval;
}

async public Task<Tuple<string, string>> GetResponseAsync(EndpointCollection endpointCollection)
{
var endpoint = endpointCollection.Resolve(RequestPath);
if (endpoint == null)
{
return Tuple.Create((string)null, ERROR_NOMATCHING_ENDPOINT);
}
bool singleMatch;
var matcher_and_creator = endpoint.Resolve(new PathString(RequestPath), new QueryString(QueryString), RequestBody, null, out singleMatch);
if (matcher_and_creator != null)
{
var responseCreator = matcher_and_creator.Item2;
var responseBodyBytes = await responseCreator.CreateResponseAsync(new TestCaseHttpRequest(RequestPath), Encoding.UTF8.GetBytes(RequestBody), new TestCaseHttpResponse(), endpoint.Directory);
return Tuple.Create(Encoding.UTF8.GetString(responseBodyBytes), (string)null);
}
else
{
return Tuple.Create((string)null, ERROR_ENDPOINT_HAS_NO_MATCH);
}

}
}

public class NetmockeryTestCaseResult
Expand Down
42 changes: 33 additions & 9 deletions netmockery/Program.cs
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Hosting.WindowsServices;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using static System.Console;

Expand All @@ -18,6 +20,17 @@ public static void ReloadConfig()
{
EndpointCollection = EndpointCollectionReader.ReadFromDirectory(_configdirectory);
}

private static IWebHost CreateWebHost(string contentRoot)
{
return new WebHostBuilder()
.UseKestrel()
.UseContentRoot(contentRoot)
.UseIISIntegration()
.UseStartup<Startup>()
.Build();
}

public static void Main(string[] args)
{
System.Net.ServicePointManager.ServerCertificateValidationCallback =
Expand All @@ -30,15 +43,8 @@ public static void Main(string[] args)

if (args.Length == 1)
{
var host = new WebHostBuilder()
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
.UseIISIntegration()
.UseStartup<Startup>()
.Build();

WriteLine("Admin interface available on /__netmockery");
host.Run();
CreateWebHost(Directory.GetCurrentDirectory()).Run();
}
else
{
Expand Down Expand Up @@ -67,6 +73,11 @@ public static void Main(string[] args)
Test(commandArgs);
break;

case "service":
WriteLine("Running as service");
RunAsService();
break;

default:
Error.WriteLine($"Unknown command {commandName}");
break;
Expand All @@ -79,6 +90,11 @@ public static void Main(string[] args)
}
}

static public void RunAsService()
{
CreateWebHost(AppDomain.CurrentDomain.BaseDirectory).RunAsService();
}

static private string getSwitchValue(string[] commandArgs, string switchName)
{
var index = Array.FindIndex(commandArgs, v => v == switchName);
Expand Down Expand Up @@ -114,7 +130,15 @@ public static void Test(string[] commandArgs)

if (containsSwitch(commandArgs, "--showResponse"))
{
throw new NotImplementedException("TODO");
var response = testCase.GetResponseAsync(EndpointCollection).Result;
if (response.Item2 != null)
{
Error.WriteLine($"ERROR: {response.Item2}");
}
else
{
WriteLine(response.Item1);
}
}
else
{
Expand Down
106 changes: 99 additions & 7 deletions netmockery/documentation.md
Original file line number Diff line number Diff line change
@@ -1,16 +1,108 @@
Directory structure
===================
# Netmockery Documentation

* [Running netmockery](#running)
* [Configuring netmockery](#configuring)
* [Writing tests](#tests)
* [Misc](#misc)

<a name="running"></a>
# Running netmockery

Command line:

netmockery.exe p:\ath\to\endpoint\directory

Netmockery starts and listens on port ``5000``.

## Installing as windows service

To install:

sc create netmockery binPath= "p:\ath\to\netmockery.exe p:\ath\to\endpoint\directory service"

If ``p:\ath\to\netmockery.exe`` or ``p:\ath\to\endpoint\directory`` contains spaces, they must be escaped using ``\"`` . Example:

sc create netmockery binPath= "p:\ath\to\netmockery.exe \"p:\ath\to\endpoint\directory\with space\" service"

Start/stop service:

net start netmockery
net stop netmockery

To uninstall:

sc delete netmockery

<a name="configuring"></a>
# Configuring netmockery

## Directory structure

TODO

## Request matching

Request matching
================
TODO

## Response creation

TODO

<a name="tests"></a>
# Writing tests

Within a endpoint directory, a ``tests`` directory with a ``tests.json`` file defines test cases for the endpoint directory.

Example ``tests.json`` file:

[
{
'name': 'My first test',
'requestpath': '/somepath/',
// optional request parameters:
// querystring
// requestbody

// one or more test expectations:
// expectedrequestmatcher
// expectedresponsecreator
// expectedresponsebody
},
// More test cases
]

Specifying the request:

* ``name``: display name for test (required)
* ``requestpath``: request path (required)
* ``querystring``: request query string
* ``requestbody``: request body

Specifying the expectations:

* ``expectedrequestmatcher``: Display name of request matcher
* ``expectedresponsecreator``: Display name of response creator
* ``expectedresponsebody``: Expected response body contents. If specified as ``file:filename``, the expected response body is read from the specified file.

## Running tests

Command line:

# run all tests
netmockery.exe p:\ath\to\endpoint\directory test

# run single test, numeric parameter N specifies which test (first test is test 0 (zero))
netmockery.exe p:\ath\to\endpoint\directory test --only N

# execute request specified by test N, but display respons (do not check test expectations)
netmockery.exe p:\ath\to\endpoint\directory test --only N --showResponse

<a name="misc"></a>
# Misc

TODO: delay parameter

Response creation
=================
TODO: index.md documentation

TODO
TODO: other commands, dump
6 changes: 4 additions & 2 deletions netmockery/project.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,8 @@
"Newtonsoft.Json": "9.0.1",
"Markdown": "2.1.0",
"Microsoft.AspNetCore.StaticFiles": "1.0.0",
"System.Net.Http": "4.1.0"
"System.Net.Http": "4.1.0",
"Microsoft.AspNetCore.Hosting.WindowsServices": "1.1.0-preview1-final"
},

"tools": {
Expand All @@ -33,7 +34,8 @@
"include": [
"wwwroot",
"web.config",
"Views"
"Views",
"documentation.md"
]
},

Expand Down

0 comments on commit 38ad2ca

Please sign in to comment.