Skip to content

Instantly share code, notes, and snippets.

@sdurandeu
Created March 4, 2016 15:31
Show Gist options
  • Select an option

  • Save sdurandeu/7b47aa632cc90ee09089 to your computer and use it in GitHub Desktop.

Select an option

Save sdurandeu/7b47aa632cc90ee09089 to your computer and use it in GitHub Desktop.
Unit Test: check attributes of controllers
private static readonly string[] IgnoreMethods =
{
"Web.Controllers.CaseStudiesController.CaseStudiesApi",
"Web.Controllers.DocumentationController.DocArticlesApi",
"Web.Controllers.VideosController.AzureFridayResults",
"Web.Controllers.ChannelCalculatorController.PostEstimate",
"Web.Controllers.ChannelCalculatorController.GetExcelExportedFileFromCalculator"
};
[TestMethod]
public void ThenTheActionShouldHaveAnAntiForgeryAttribute()
{
var actions = typeof (MvcApplication).Assembly
.GetExportedTypes()
.Where(x => typeof (Controller).IsAssignableFrom(x))
.SelectMany(x => x.GetMethods())
.Where(
x =>
(typeof (ActionResult)).IsAssignableFrom(x.ReturnType) ||
(typeof (Task<ActionResult>)).IsAssignableFrom(x.ReturnType))
.Where(x => x.GetCustomAttributes<HttpPostAttribute>().Any() &&
!x.GetCustomAttributes<ValidateAntiForgeryTokenAttribute>().Any())
.Select(x => string.Format("{1}.{0}", x.Name, x.DeclaringType.FullName))
.Where(x => IgnoreMethods.All(y => y != x));
if (actions.Any())
{
Assert.Fail("Some post actions do not have an anti-forgery token: " + Environment.NewLine +
string.Join(Environment.NewLine, actions));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment