Devlico.Us
CodeBetter.Com
RSS 2.0 via Feedburner
           Do you Twitter? Follow us @devlicious

Casey Charlton - Insane World

Hang the code, and hang the rules. They're more like guidelines anyway

April 2008 - Posts

  • Switching to a Different User Inside a Unit Test

    Update: Re-published from old blog 

    I found a need yesterday to test some code in particular security contexts. After some (as always) prompt guidance from the altdotnet mailing list, I had the (as it turns out) all too simple solution. xUnit includes an attribute for this, but as I'm using NUnit and just wanted a clean way to do this without writing an extension, I figured I would just play around with it a bit.

    One quick bit of refactoring later, and we have a class to handle this for us:

     1:  public class SecurityContextSwitcher : IDisposable
     2:  {
     3:  private readonly IPrincipal originalPrincipal;
     4:  
     5:  public SecurityContextSwitcher(string username, string[] roles)
     6:  {
     7:  originalPrincipal = Thread.CurrentPrincipal;
     8:  var identity = new GenericIdentity(username);
     9:  var principal = new GenericPrincipal(identity, roles);
     10:  Thread.CurrentPrincipal = principal;
     11:  }
     12:  
     13:  public void Dispose()
     14:  {
     15:  Thread.CurrentPrincipal = originalPrincipal;
     16:  }
     17:  }

    This class allows us to test quite simply with the following syntax:

     1:  [Test]
     2:  public void Handler_will_allow_access_to_anyone_who_is_in_Users_role()
     3:  {
     4:  using (new SecurityContextSwitcher("Test", new[] {"Users"}))
     5:  {
     6:  var request = new GetRequest {Id = new Guid()};
     7:  handlerUnderTest.Handle(request);
     8:  }
     9:  }
     10:  
     11:  [PrincipalPermissionAttribute(SecurityAction.Demand, Role = "Users")]
     12:  public override void Handle(GetRequest message)
     13:  {
     14:  ...
     15:  }
  • Windsor Container Registration of Generic Component via C# Code

    Update: Re-published from old blog 

    I've done it before, but my mind went totally blank yesterday ... due to some typically quick responses from the Castle Users Google Group ... here is the code to do it for future generations to avoid my same silly mistakes ...

     1: WindsorContainer container = new WindsorContainer();
     2: Type eventBrokerServiceType = typeof (IEventBroker<>);
     3: Type brokerType = typeof (EventBroker<>);
     4: container.AddComponent("key", eventBrokerServiceType, brokerType);
     5: IEventBroker<EventArgs> eventBroker = 
     6:  container.Resolve<IEventBroker<EventArgs>>();
     7: Assert.IsNotNull(eventBroker);
More Posts

Our Sponsors

Red-Gate!