ValidationRules.cs 2.83 KB
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using Microsoft.VisualStudio.TestTools.WebTesting;
using Microsoft.VisualStudio.TestTools.LoadTesting;
using System.IO;
using System.ComponentModel;
using System.Text.RegularExpressions;

namespace LIL_VSTT_Plugins
{
    /// <summary>
    /// Count Validation
    /// Räknar hur många gånger ett visst reguljärt utryck finns i svaret och validerar detta
    /// </summary>
    [DisplayName("Count Validation")]
    [Description("(C) Copyright 2011 LIGHTS IN LINE AB\r\nValiderar att ett reguljärt utryck finns minst ett visst antal gånger i svaret, eller inte.")]
    public class CountValidation : ValidationRule
    {
        [DisplayName("RegEx"), Description("Regular Expression to match on the response.")]
        public String RegEx { get; set; }

        [DisplayName("Condition"), Description("Valid conditions are =,>,<,>=,<=")]
        [DefaultValue("=")]
        public String myCon { get; set; }

        [DisplayName("Count"), Description("Expected count of occurences")]
        public int Count { get; set; }

        [DisplayName("Pass"), Description("Pass or fail if count matches. True passes if the count matches, False fails if the count matches")]
        [DefaultValue(true)]
        public bool Pass { get; set; }

        public override void Validate(object sender, ValidationEventArgs e)
        {
            MatchCollection matches = System.Text.RegularExpressions.Regex.Matches(
                e.Response.BodyString,
                RegEx,
                RegexOptions.IgnoreCase);
            
            switch (myCon) { 
                case "=":
                    if (matches.Count == Count) { e.IsValid = Pass; e.Message = "Number of matches equal to count. Valid set to " + Pass.ToString(); }
                    break;
                case "<":
                    if (matches.Count < Count) { e.IsValid = Pass; e.Message = "Number of matches less than count. Valid set to " + Pass.ToString(); }
                    break;
                case ">":
                    if (matches.Count > Count) { e.IsValid = Pass; e.Message = "Number of matches higher than count. Valid set to " + Pass.ToString(); }
                    break;
                case "<=":
                    if (matches.Count <= Count) { e.IsValid = Pass; e.Message = "Number of matches less or equal to count. Valid set to " + Pass.ToString(); }
                    break;
                case ">=":
                    if (matches.Count >= Count) { e.IsValid = Pass; e.Message = "Number of matches higher or equal to count. Valid set to " + Pass.ToString(); }
                    break;
                default:
                    e.IsValid = true; e.Message = "Invalid condition specified. Validation will pass.";
                    break;
            }
        }
    }
}