|
| 1 | +using System; |
| 2 | +using System.Collections.Generic; |
| 3 | +using System.Linq; |
| 4 | +using System.Text.RegularExpressions; |
| 5 | +using Microsoft.AspNetCore.Http; |
| 6 | +using Microsoft.AspNetCore.Http.Extensions; |
| 7 | + |
| 8 | +namespace TestUtilities |
| 9 | +{ |
| 10 | + public class Rule |
| 11 | + { |
| 12 | + public IList<Func<HttpRequest, bool>> Predictions { get; set; } |
| 13 | + public Action<HttpResponse> Action { get; set; } |
| 14 | + public RuleSet RuleSet { get; set; } |
| 15 | + |
| 16 | + public Rule(RuleSet ruleSet) |
| 17 | + { |
| 18 | + RuleSet = ruleSet; |
| 19 | + Predictions = new List<Func<HttpRequest, bool>>(); |
| 20 | + } |
| 21 | + |
| 22 | + public bool IsValid() |
| 23 | + { |
| 24 | + return Action != null; |
| 25 | + } |
| 26 | + |
| 27 | + public Rule AddRule() |
| 28 | + { |
| 29 | + if (Action == null) |
| 30 | + { |
| 31 | + throw new InvalidOperationException("Previous rule not completed"); |
| 32 | + } |
| 33 | + return RuleSet.AddRule(); |
| 34 | + } |
| 35 | + |
| 36 | + public Rule WhenGet() |
| 37 | + { |
| 38 | + Predictions.Add((request) => |
| 39 | + { |
| 40 | + return request.Method == "GET"; |
| 41 | + }); |
| 42 | + return this; |
| 43 | + } |
| 44 | + |
| 45 | + public Rule WhenUrlMatch(string pattern) |
| 46 | + { |
| 47 | + Predictions.Add((request) => |
| 48 | + { |
| 49 | + var actualUrl = UriHelper.GetDisplayUrl(request); |
| 50 | + return Regex.IsMatch(actualUrl, pattern); |
| 51 | + }); |
| 52 | + return this; |
| 53 | + } |
| 54 | + |
| 55 | + public Rule WhenHeaderMatch(string key, string value) |
| 56 | + { |
| 57 | + Predictions.Add((request) => |
| 58 | + { |
| 59 | + if (!request.Headers.TryGetValue(key, out var actual)) |
| 60 | + { |
| 61 | + return false; |
| 62 | + } |
| 63 | + return actual.Contains(value); |
| 64 | + }); |
| 65 | + return this; |
| 66 | + } |
| 67 | + |
| 68 | + public Rule WhenAuthorizationMatch(string token) |
| 69 | + { |
| 70 | + return WhenHeaderMatch("Authorization", token); |
| 71 | + } |
| 72 | + |
| 73 | + public Rule SetBadRequest(string message = "Bad Request") |
| 74 | + { |
| 75 | + Action = async response => |
| 76 | + { |
| 77 | + response.StatusCode = 400; |
| 78 | + await response.WriteAsync(message); |
| 79 | + }; |
| 80 | + return this; |
| 81 | + } |
| 82 | + |
| 83 | + public Rule SetOkResponse(string output) |
| 84 | + { |
| 85 | + Action = async response => |
| 86 | + { |
| 87 | + await response.WriteAsync(output); |
| 88 | + }; |
| 89 | + return this; |
| 90 | + } |
| 91 | + } |
| 92 | +} |
0 commit comments