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


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:  }


About Casey Charlton

A somewhat passionate and opinionated developer, with occassional sparks of wisdom, and occasional useful information. Check out Devlicio.us!

Our Sponsors

Red-Gate!