| | 1 | | // Copyright (c) Microsoft Corporation. All rights reserved. |
| | 2 | | // Licensed under the MIT License. |
| | 3 | |
|
| | 4 | | using System; |
| | 5 | | using System.IO; |
| | 6 | | using System.Linq; |
| | 7 | | using System.Runtime.CompilerServices; |
| | 8 | | using System.Security.Cryptography; |
| | 9 | | using System.Text.Json; |
| | 10 | | using System.Threading; |
| | 11 | | using System.Threading.Tasks; |
| | 12 | | using Azure.Core.Pipeline; |
| | 13 | | using Azure.Core.Tests.TestFramework; |
| | 14 | |
|
| | 15 | | namespace Azure.Core.TestFramework |
| | 16 | | { |
| | 17 | | public class TestRecording : IDisposable |
| | 18 | | { |
| | 19 | | private const string RandomSeedVariableKey = "RandomSeed"; |
| | 20 | | private const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; |
| | 21 | | private const string charsLower = "abcdefghijklmnopqrstuvwxyz0123456789"; |
| | 22 | | internal const string DateTimeOffsetNowVariableKey = "DateTimeOffsetNow"; |
| | 23 | |
|
| 9113 | 24 | | public TestRecording(RecordedTestMode mode, string sessionFile, RecordedTestSanitizer sanitizer, RecordMatcher m |
| | 25 | | { |
| 9113 | 26 | | Mode = mode; |
| 9113 | 27 | | _sessionFile = sessionFile; |
| 9113 | 28 | | _sanitizer = sanitizer; |
| 9113 | 29 | | _matcher = matcher; |
| | 30 | |
|
| 9113 | 31 | | switch (Mode) |
| | 32 | | { |
| | 33 | | case RecordedTestMode.Record: |
| 4 | 34 | | _session = new RecordSession(); |
| 4 | 35 | | if (File.Exists(_sessionFile)) |
| | 36 | | { |
| | 37 | | try |
| | 38 | | { |
| 4 | 39 | | _previousSession = Load(); |
| 0 | 40 | | } |
| 4 | 41 | | catch (Exception) |
| | 42 | | { |
| | 43 | | // ignore |
| 4 | 44 | | } |
| | 45 | | } |
| | 46 | | break; |
| | 47 | | case RecordedTestMode.Playback: |
| 9109 | 48 | | _session = Load(); |
| | 49 | | break; |
| | 50 | | } |
| 9113 | 51 | | } |
| | 52 | |
|
| 73974 | 53 | | public RecordedTestMode Mode { get; } |
| | 54 | |
|
| 9113 | 55 | | private readonly AsyncLocal<EntryRecordModel> _disableRecording = new AsyncLocal<EntryRecordModel>(); |
| | 56 | |
|
| | 57 | | private readonly string _sessionFile; |
| | 58 | |
|
| | 59 | | private readonly RecordedTestSanitizer _sanitizer; |
| | 60 | |
|
| | 61 | | private readonly RecordMatcher _matcher; |
| | 62 | |
|
| | 63 | | private readonly RecordSession _session; |
| | 64 | |
|
| | 65 | | private RecordSession _previousSession; |
| | 66 | |
|
| | 67 | | private TestRandom _random; |
| | 68 | |
|
| | 69 | | public TestRandom Random |
| | 70 | | { |
| | 71 | | get |
| | 72 | | { |
| 127120 | 73 | | if (_random == null) |
| | 74 | | { |
| 8369 | 75 | | switch (Mode) |
| | 76 | | { |
| | 77 | | case RecordedTestMode.Live: |
| 0 | 78 | | var csp = new RNGCryptoServiceProvider(); |
| 0 | 79 | | var bytes = new byte[4]; |
| 0 | 80 | | csp.GetBytes(bytes); |
| 0 | 81 | | _random = new TestRandom(Mode, BitConverter.ToInt32(bytes, 0)); |
| 0 | 82 | | break; |
| | 83 | | case RecordedTestMode.Record: |
| | 84 | | // Try get the seed from existing session |
| 2 | 85 | | if (!(_previousSession != null && |
| 2 | 86 | | _previousSession.Variables.TryGetValue(RandomSeedVariableKey, out string seedString) & |
| 2 | 87 | | int.TryParse(seedString, out int seed) |
| 2 | 88 | | )) |
| | 89 | | { |
| 2 | 90 | | _random = new TestRandom(Mode); |
| 2 | 91 | | seed = _random.Next(); |
| | 92 | | } |
| 2 | 93 | | _session.Variables[RandomSeedVariableKey] = seed.ToString(); |
| 2 | 94 | | _random = new TestRandom(Mode, seed); |
| 2 | 95 | | break; |
| | 96 | | case RecordedTestMode.Playback: |
| 8367 | 97 | | if (IsTrack1SessionRecord()) |
| | 98 | | { |
| | 99 | | //random is not really used for track 1 playback, so randomly pick one as seed |
| 0 | 100 | | _random = new TestRandom(Mode, (int)DateTime.UtcNow.Ticks); |
| | 101 | | } |
| | 102 | | else |
| | 103 | | { |
| 8367 | 104 | | _random = new TestRandom(Mode, int.Parse(_session.Variables[RandomSeedVariableKey])); |
| | 105 | | } |
| 8367 | 106 | | break; |
| | 107 | | default: |
| 0 | 108 | | throw new ArgumentOutOfRangeException(); |
| | 109 | | } |
| | 110 | | } |
| 127120 | 111 | | return _random; |
| | 112 | | } |
| | 113 | | } |
| | 114 | |
|
| | 115 | | /// <summary> |
| | 116 | | /// The moment in time that this test is being run. |
| | 117 | | /// </summary> |
| | 118 | | private DateTimeOffset? _now; |
| | 119 | |
|
| | 120 | | /// <summary> |
| | 121 | | /// Gets the moment in time that this test is being run. This is useful |
| | 122 | | /// for any test recordings that capture the current time. |
| | 123 | | /// </summary> |
| | 124 | | public DateTimeOffset Now |
| | 125 | | { |
| | 126 | | get |
| | 127 | | { |
| 3980 | 128 | | if (_now == null) |
| | 129 | | { |
| 1672 | 130 | | switch (Mode) |
| | 131 | | { |
| | 132 | | case RecordedTestMode.Live: |
| 0 | 133 | | _now = DateTimeOffset.Now; |
| 0 | 134 | | break; |
| | 135 | | case RecordedTestMode.Record: |
| | 136 | | // While we can cache DateTimeOffset.Now for playing back tests, |
| | 137 | | // a number of auth mechanisms are time sensitive and will require |
| | 138 | | // values in the present when re-recording |
| 0 | 139 | | _now = DateTimeOffset.Now; |
| 0 | 140 | | _session.Variables[DateTimeOffsetNowVariableKey] = _now.Value.ToString("O"); // Use the "Rou |
| 0 | 141 | | break; |
| | 142 | | case RecordedTestMode.Playback: |
| 1672 | 143 | | _now = DateTimeOffset.Parse(_session.Variables[DateTimeOffsetNowVariableKey]); |
| 1672 | 144 | | break; |
| | 145 | | default: |
| 0 | 146 | | throw new ArgumentOutOfRangeException(); |
| | 147 | | } |
| | 148 | | } |
| 3980 | 149 | | return _now.Value; |
| | 150 | | } |
| | 151 | | } |
| | 152 | |
|
| | 153 | | /// <summary> |
| | 154 | | /// Gets the moment in time that this test is being run in UTC format. |
| | 155 | | /// This is useful for any test recordings that capture the current time. |
| | 156 | | /// </summary> |
| 2124 | 157 | | public DateTimeOffset UtcNow => Now.ToUniversalTime(); |
| | 158 | |
|
| | 159 | | private RecordSession Load() |
| | 160 | | { |
| 9113 | 161 | | using FileStream fileStream = File.OpenRead(_sessionFile); |
| 9113 | 162 | | using JsonDocument jsonDocument = JsonDocument.Parse(fileStream); |
| 9109 | 163 | | return RecordSession.Deserialize(jsonDocument.RootElement); |
| 9109 | 164 | | } |
| | 165 | |
|
| | 166 | | public void Dispose(bool save) |
| | 167 | | { |
| 9113 | 168 | | if (Mode == RecordedTestMode.Record && save) |
| | 169 | | { |
| 4 | 170 | | var directory = Path.GetDirectoryName(_sessionFile); |
| 4 | 171 | | Directory.CreateDirectory(directory); |
| | 172 | |
|
| 4 | 173 | | _session.Sanitize(_sanitizer); |
| 4 | 174 | | if (_session.IsEquivalent(_previousSession, _matcher)) |
| | 175 | | { |
| 0 | 176 | | return; |
| | 177 | | } |
| | 178 | |
|
| 4 | 179 | | using FileStream fileStream = File.Create(_sessionFile); |
| 4 | 180 | | var utf8JsonWriter = new Utf8JsonWriter(fileStream, new JsonWriterOptions() |
| 4 | 181 | | { |
| 4 | 182 | | Indented = true |
| 4 | 183 | | }); |
| 4 | 184 | | _session.Serialize(utf8JsonWriter); |
| 4 | 185 | | utf8JsonWriter.Flush(); |
| | 186 | | } |
| 9113 | 187 | | } |
| | 188 | |
|
| | 189 | | public void Dispose() |
| | 190 | | { |
| 0 | 191 | | Dispose(true); |
| 0 | 192 | | } |
| | 193 | |
|
| | 194 | | public T InstrumentClientOptions<T>(T clientOptions) where T : ClientOptions |
| | 195 | | { |
| 14939 | 196 | | clientOptions.Transport = CreateTransport(clientOptions.Transport); |
| 14939 | 197 | | return clientOptions; |
| | 198 | | } |
| | 199 | |
|
| | 200 | | public HttpPipelineTransport CreateTransport(HttpPipelineTransport currentTransport) |
| | 201 | | { |
| 14941 | 202 | | return Mode switch |
| 14941 | 203 | | { |
| 0 | 204 | | RecordedTestMode.Live => currentTransport, |
| 6 | 205 | | RecordedTestMode.Record => new RecordTransport(_session, currentTransport, entry => _disableRecording.Va |
| 29878 | 206 | | RecordedTestMode.Playback => new PlaybackTransport(_session, _matcher, _sanitizer, Random, |
| 356250 | 207 | | entry => _disableRecording.Value == EntryRecordModel.RecordWithoutRequestBody), |
| 0 | 208 | | _ => throw new ArgumentOutOfRangeException(nameof(Mode), Mode, null), |
| 14941 | 209 | | }; |
| | 210 | | } |
| | 211 | |
|
| | 212 | | public string GenerateId() |
| | 213 | | { |
| 1357 | 214 | | return Random.Next().ToString(); |
| | 215 | | } |
| | 216 | |
|
| | 217 | | public string GenerateAlphaNumericId(string prefix, int? maxLength = null, bool useOnlyLowercase = false) |
| | 218 | | { |
| 656 | 219 | | var stringChars = new char[8]; |
| | 220 | |
|
| 11808 | 221 | | for (int i = 0; i < stringChars.Length; i++) |
| | 222 | | { |
| 5248 | 223 | | if (useOnlyLowercase) |
| | 224 | | { |
| 5120 | 225 | | stringChars[i] = charsLower[Random.Next(charsLower.Length)]; |
| | 226 | | } |
| | 227 | | else |
| | 228 | | { |
| 128 | 229 | | stringChars[i] = chars[Random.Next(chars.Length)]; |
| | 230 | | } |
| | 231 | | } |
| | 232 | |
|
| 656 | 233 | | var finalString = new string(stringChars); |
| 656 | 234 | | if (maxLength.HasValue) |
| | 235 | | { |
| 0 | 236 | | return $"{prefix}{finalString}".Substring(0, maxLength.Value); |
| | 237 | | } |
| | 238 | | else |
| | 239 | | { |
| 656 | 240 | | return $"{prefix}{finalString}"; |
| | 241 | | } |
| | 242 | | } |
| | 243 | |
|
| | 244 | | public string GenerateId(string prefix, int maxLength) |
| | 245 | | { |
| 118 | 246 | | var id = $"{prefix}{Random.Next()}"; |
| 118 | 247 | | return id.Length > maxLength ? id.Substring(0, maxLength): id; |
| | 248 | | } |
| | 249 | |
|
| | 250 | | public string GenerateAssetName(string prefix, [CallerMemberName]string callerMethodName = "testframework_failed |
| | 251 | | { |
| 6280 | 252 | | if (Mode == RecordedTestMode.Playback && IsTrack1SessionRecord()) |
| | 253 | | { |
| 0 | 254 | | return _session.Names[callerMethodName].Dequeue(); |
| | 255 | | } |
| | 256 | | else |
| | 257 | | { |
| 6280 | 258 | | return prefix + Random.Next(9999); |
| | 259 | | } |
| | 260 | | } |
| | 261 | |
|
| | 262 | | public bool IsTrack1SessionRecord() |
| | 263 | | { |
| 14647 | 264 | | return _session.Entries.FirstOrDefault()?.IsTrack1Recording ?? false; |
| | 265 | | } |
| | 266 | |
|
| | 267 | | public string GetVariable(string variableName, string defaultValue) |
| | 268 | | { |
| 15743 | 269 | | switch (Mode) |
| | 270 | | { |
| | 271 | | case RecordedTestMode.Record: |
| 0 | 272 | | _session.Variables[variableName] = defaultValue; |
| 0 | 273 | | return defaultValue; |
| | 274 | | case RecordedTestMode.Live: |
| 0 | 275 | | return defaultValue; |
| | 276 | | case RecordedTestMode.Playback: |
| 15743 | 277 | | _session.Variables.TryGetValue(variableName, out string value); |
| 15743 | 278 | | return value; |
| | 279 | | default: |
| 0 | 280 | | throw new ArgumentOutOfRangeException(); |
| | 281 | | } |
| | 282 | | } |
| | 283 | |
|
| | 284 | | public void SetVariable(string variableName, string value) |
| | 285 | | { |
| 145 | 286 | | switch (Mode) |
| | 287 | | { |
| | 288 | | case RecordedTestMode.Record: |
| 2 | 289 | | _session.Variables[variableName] = value; |
| | 290 | | break; |
| | 291 | | default: |
| | 292 | | break; |
| | 293 | | } |
| 145 | 294 | | } |
| | 295 | |
|
| | 296 | | public void DisableIdReuse() |
| | 297 | | { |
| 8 | 298 | | _previousSession = null; |
| 8 | 299 | | } |
| | 300 | |
|
| | 301 | | public DisableRecordingScope DisableRecording() |
| | 302 | | { |
| 0 | 303 | | return new DisableRecordingScope(this, EntryRecordModel.DontRecord); |
| | 304 | | } |
| | 305 | |
|
| | 306 | | public DisableRecordingScope DisableRequestBodyRecording() |
| | 307 | | { |
| 98 | 308 | | return new DisableRecordingScope(this, EntryRecordModel.RecordWithoutRequestBody); |
| | 309 | | } |
| | 310 | |
|
| | 311 | | public struct DisableRecordingScope : IDisposable |
| | 312 | | { |
| | 313 | | private readonly TestRecording _testRecording; |
| | 314 | |
|
| | 315 | | public DisableRecordingScope(TestRecording testRecording, EntryRecordModel entryRecordModel) |
| | 316 | | { |
| 98 | 317 | | _testRecording = testRecording; |
| 98 | 318 | | _testRecording._disableRecording.Value = entryRecordModel; |
| 98 | 319 | | } |
| | 320 | |
|
| | 321 | | public void Dispose() |
| | 322 | | { |
| 98 | 323 | | _testRecording._disableRecording.Value = EntryRecordModel.Record; |
| 98 | 324 | | } |
| | 325 | | } |
| | 326 | | } |
| | 327 | | } |