Unit Testing Castle Monorail Filters

I’m really liking the unit test support in the Castle Monorail project. Here’s an example to create a simple test for testing filters.

[TestFixture]
public class AdminAuthorizationFilterTest : BaseControllerTest
{
private Controller _controller;

[SetUp]
public void Setup()
{
_controller = new TestController();
PrepareController(_controller);
}

[Test]
public void Perform_No_User_Expect_False()
{
AdminAuthorizationFilter filter = new AdminAuthorizationFilter();
bool perform = filter.Perform(ExecuteEnum.BeforeAction, Context, _controller);
Assert.That(perform, Is.False);
Assert.That(Response.WasRedirected, Is.True);
}
}

internal class TestController : Controller {}

</p>

Setup is the same as testing a controller, but I needed to create an basic test controller. I attempted to use Rhino Mocks to partial mock the controller, but that disconnected the BaseControllerTest resulting in things like checking the Response object not working. Creating the class is one less line of code anyway.

More on test support here.
And Here.


Testing filters and the using.castleproject.org site

Opps, I guess there’s already some documentation on Testing Filters here. There is a lot of good info on the using.castleproject.org site, I’ll be checking and adding info there.


Storing DateTime objects in Amazon Simple DB

I’m working with the Amazon Simple DB web service. It stores everything in strings as such I needed to store a DateTime in ISO 8601 format for later sorting the strings in correct order. The frameworks has at least three formating strings. Either s or u or o. The s format seems like a good choice as it’s called the sortable format. However it doesn’t store any sub second data or timezone info. The u format is s in universal time, but still lacks the sub second data. Lastly the o format for round trip stores all the DateTime info in ISO 8601 format and should remain sortable as long as all dates are stored in the same time zone. MSDN DateTime format strings{#uww6}

Here’s more good info on storing data as a string in ways that are sortable later and useful Simple DB info.

http://docs.amazonwebservices.com/AmazonSimpleDB/2007-11-07/GettingStartedGuide/{#acr4}
http://docs.amazonwebservices.com/AmazonSimpleDB/2007-11-07/DeveloperGuide/{#gy.7}
http://developer.amazonwebservices.com/connect/entry.jspa?externalID=1231&categoryID=152{#dl7j}
http://developer.amazonwebservices.com/connect/entry.jspa?externalID=1232&categoryID=152{#f-:g}







Castle monorail brail view template

I finally spent two minutes to create a view.brail VS template today. It’s really basic, but at least I won’t end up with a class definition every time I try to add a new view. Below is the zip file, just drop in into My Documents\Visual Studio 2005\Templates\ItemTemplates.

View.zip (5.12 KB)


Updates to AwsS3Library – Bucket contents support

Posted updates and fixes to the AwsS3Library. Added support for AwsBucket Contents to be parsed when getting a bucket.

AwsBucket bucket = _service.Get(new AwsBucket("somebucket"));
foreach (AwsObjectKey awsObjectKey in bucket.AwsObjectKeys)
{
Console.WriteLine("Object Key " + awsObjectKey.Key);
}

</p>


OpenId Authentication In Castle Monorail with ExtremeSwank OpenID Consumer

I spent some time today setting up OpenId in Monorail using ExtremeSwank OpenId consumer library. I went with a view component that can be on every page and a login controller to handle the authenticate and logout functions. This code is mostly a mix of the ExtremeSwank sample code and monorail sample code and probably shouldn’t be used in a production environment.

Anyway, we’ll start with the controller. It has three methods, Index, Authenticate, and Logout. The Index is just an empty action to explain OpenId to those who may not have experience with it. Authenticate takes the OpenId URL provided by the user to authenticate.  We store that in the session and pass to the consumer. Then we call BeginAuth which will process the request as long as the URL is correct. If not I render the Index view.

public void Authenticate(string openIdUrl)
{
try { OpenIDConsumer consumer = new OpenIDConsumer();
consumer.Identity = openIdUrl;
Session[OPENID_LOGIN] = consumer.Identity;
consumer.ReturnURL = Context.UrlReferrer;
consumer.BeginAuth();
}
catch (Exception e)
{
PropertyBag["message"] = "Login attempt failed.";
}
RenderView("Index");
}
ly, I have the Logout method which just removes the OpenIdUser object from the session.<!-- code formatted by http://manoli.net/csharpformat/ -->
public void Logout()
{
Session[OPENID_USEROBJECT] = null;
RedirectToReferrer();
}

Next I have the ViewComponent which checks to see if the user is authenticating, authenticated, or not. I check for the OpenIDUser in the session first, if it finds that, then the user is authenticated. Otherwise, it creates a OpenIdConsumer object which looks at the state of authentication and executes accordingly, rendering either the default URL box or the logout link.

public override void Render()
{
OpenIDUser user = Session[LoginController.OPENID_USEROBJECT] as OpenIDUser;
if (user != null)
{
RenderLoggedIn(user);
}
else { OpenIDConsumer consumer = new OpenIDConsumer();
switch (consumer.RequestedMode)
{
case RequestedMode.IdResolution:
consumer.Identity = (string)Session[LoginController.OPENID_LOGIN];
if (consumer.Validate())
{
user = consumer.RetrieveUser();
Session[LoginController.OPENID_USEROBJECT] = user;
RenderLoggedIn(user);
}
else { RenderLoginFailed(); } break;
case RequestedMode.CancelledByUser:
RenderLoginCancelled();
break;
default:
base.Render();
break;
}
}
}
eded to add the appropriate views, but thats mostly all that's needed for this simple setup. <br><p></p>

How to test a mocked object when that object requires an attribute

Today I needed to unit test a method that checked for and required a specific attribute on the class. I ended up with a fairly simple solution, the decorator pattern. Simply create a decorator for the type that needs the attribute, put the attribute on the decorator. Pass you mocked class to a new instance of the decorator when you pass to the method being tested. I sounds like more work then it is, of course it may not always make sense to go this route. Anyway, here’s the code.



using NUnit.Framework;
using NUnit.Framework.SyntaxHelpers;
using Rhino.Mocks;

namespace MockingClassesWithRequiredAttributes
{
[TestFixture]
public class Class1
{
[Test]
public void Test()
{
MockRepository mocks = new MockRepository();
IRun mockedRun = mocks.DynamicMock<IRun>();
using (mocks.Record())
{
mockedRun.Run();
LastCall.On(mockedRun);
}
using (mocks.Playback())
{
IRequireCategoryAttribute(new MockDecorator(mockedRun));
}
}

static void IRequireCategoryAttribute(IRun run)
{
object[] attributes = run.GetType().GetCustomAttributes(
typeof(System.ComponentModel.CategoryAttribute), false);
Assert.That(attributes.Length, Is.GreaterThan(0));
run.Run();
}
}

[System.ComponentModel.Category]
class MockDecorator : IRun
{
private readonly IRun run;

public MockDecorator(IRun run)
{
run = run;
}

public void Run()
{
_run.Run();
}
}

public interface IRun
{
void Run();
}
}

One downside to this approach is the MockDecorator class that is just for testing. Any other approaches you’ve used?


Brutalist Framework