Created
March 4, 2016 15:31
-
-
Save sdurandeu/7b47aa632cc90ee09089 to your computer and use it in GitHub Desktop.
Unit Test: check attributes of controllers
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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