Skip to content

Instantly share code, notes, and snippets.

@benfoster
Created February 14, 2014 21:14
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save benfoster/9009407 to your computer and use it in GitHub Desktop.
Save benfoster/9009407 to your computer and use it in GitHub Desktop.
Simple pipeline example
using NUnit.Framework;
namespace PipelineDemo
{
public abstract class Handler<T>
{
protected Handler<T> next;
public void SetInnerHandler(Handler<T> handler)
{
if (next == null)
{
next = handler;
}
else
{
next.SetInnerHandler(handler);
}
}
public abstract void Invoke(T input);
}
public class Pipeline<T>
{
private Handler<T> outer;
public Pipeline<T> Use(Handler<T> handler)
{
if (outer == null)
{
outer = handler;
}
else
{
outer.SetInnerHandler(handler);
}
return this;
}
public void Execute(T input)
{
outer.Invoke(input);
}
}
public class Context
{
public string RequestUri { get; set; }
public int Response { get; set; }
}
public class AuthHandler : Handler<Context>
{
public override void Invoke(Context context)
{
if (context.RequestUri == "/admin")
{
context.Response = 403;
}
else
{
next.Invoke(context);
}
}
}
public class DefaultHandler : Handler<Context>
{
public override void Invoke(Context input)
{
input.Response = 200;
}
}
[TestFixture]
public class PipelineTests
{
Pipeline<Context> pipeline;
Context context;
[SetUp]
public void SetUp()
{
pipeline = new Pipeline<Context>()
.Use(new AuthHandler())
.Use(new DefaultHandler());
context = new Context();
}
[Test]
public void Requests_to_admin_returns_403()
{
context.RequestUri = "/admin";
pipeline.Execute(context);
Assert.AreEqual(403, context.Response);
}
[Test]
public void Requests_to_root_returns_200()
{
context.RequestUri = "/";
pipeline.Execute(context);
Assert.AreEqual(200, context.Response);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment