Пример #1
0
        public async Task TestStopRecordingThrowsOnInvalidSkipValue()
        {
            string targetFile = "recordings/TestStartRecordSimple_nosave.json";
            string additionalEntryModeHeader = "request-body";

            RecordingHandler testRecordingHandler = new RecordingHandler(Directory.GetCurrentDirectory());
            var httpContext = new DefaultHttpContext();
            var body        = "{\"x-recording-file\":\"" + targetFile + "\"}";

            httpContext.Request.Body          = TestHelpers.GenerateStreamRequestBody(body);
            httpContext.Request.ContentLength = body.Length;
            var controller = new Record(testRecordingHandler, _nullLogger)
            {
                ControllerContext = new ControllerContext()
                {
                    HttpContext = httpContext
                }
            };
            await controller.Start();

            var recordingId = httpContext.Response.Headers["x-recording-id"].ToString();

            httpContext.Request.Headers["x-recording-id"] = recordingId;
            httpContext.Request.Headers.Remove("x-recording-file");

            httpContext.Request.Headers["x-recording-skip"] = additionalEntryModeHeader;


            var resultingException = Assert.Throws <HttpException>(
                () => controller.Stop()
                );

            Assert.Equal("When stopping a recording and providing a \"x-recording-skip\" value, only value \"request-response\" is accepted.", resultingException.Message);
            Assert.Equal(HttpStatusCode.BadRequest, resultingException.StatusCode);
        }
Пример #2
0
        public async Task TestAddTransformWithValidUriRegexCondition(string body, string regex)
        {
            var requestBody = body.Replace("CONDITION_REGEX", regex);
            RecordingHandler testRecordingHandler = new RecordingHandler(Directory.GetCurrentDirectory());
            var httpContext = new DefaultHttpContext();

            httpContext.Request.Headers["x-abstraction-identifier"] = "ApiVersionTransform";
            httpContext.Request.Body          = TestHelpers.GenerateStreamRequestBody(requestBody);
            httpContext.Request.ContentLength = httpContext.Request.Body.Length;

            var controller = new Admin(testRecordingHandler, _nullLogger)
            {
                ControllerContext = new ControllerContext()
                {
                    HttpContext = httpContext
                }
            };

            testRecordingHandler.Transforms.Clear();
            await controller.AddTransform();

            var createdTransform = testRecordingHandler.Transforms.First();

            Assert.Single(testRecordingHandler.Transforms);
            Assert.True(createdTransform is ApiVersionTransform);
            Assert.True(createdTransform.Condition != null);
            Assert.True(createdTransform.Condition is ApplyCondition);
            Assert.Equal(regex, createdTransform.Condition.UriRegex);
        }
Пример #3
0
        public async Task TestAddSanitizerThrowsOnMissingRequiredArgument()
        {
            RecordingHandler testRecordingHandler = new RecordingHandler(Directory.GetCurrentDirectory());
            var httpContext = new DefaultHttpContext();

            httpContext.Request.Headers["x-abstraction-identifier"] = "GeneralStringSanitizer";
            httpContext.Request.Body          = TestHelpers.GenerateStreamRequestBody("{\"value\":\"replacementValue\"}");
            httpContext.Request.ContentLength = 33;

            var controller = new Admin(testRecordingHandler, _nullLogger)
            {
                ControllerContext = new ControllerContext()
                {
                    HttpContext = httpContext
                }
            };

            testRecordingHandler.Sanitizers.Clear();

            var assertion = await Assert.ThrowsAsync <HttpException>(
                async() => await controller.AddSanitizer()
                );

            Assert.True(assertion.StatusCode.Equals(HttpStatusCode.BadRequest));
            Assert.Contains("Required parameter key System.String target was not found in the request body.", assertion.Message);
        }
Пример #4
0
        public async Task GenerateInstanceThrowsOnBadBodyFormat()
        {
            RecordingHandler testRecordingHandler = new RecordingHandler(Directory.GetCurrentDirectory());
            var httpContext = new DefaultHttpContext();

            httpContext.Request.Headers["x-abstraction-identifier"] = "UriRegexSanitizer";
            httpContext.Request.Body          = TestHelpers.GenerateStreamRequestBody("{\"value\":\"replacementValue\",\"regex\":[\"a_regex_goes_here_but_this_test_is_after_another_error\"]}");
            httpContext.Request.ContentLength = 199;

            var controller = new Admin(testRecordingHandler, _nullLogger)
            {
                ControllerContext = new ControllerContext()
                {
                    HttpContext = httpContext
                }
            };

            testRecordingHandler.Sanitizers.Clear();

            var assertion = await Assert.ThrowsAsync <HttpException>(
                async() => await controller.AddSanitizer()
                );

            Assert.True(assertion.StatusCode.Equals(HttpStatusCode.BadRequest));
            Assert.Contains("Array parameters are not supported", assertion.Message);
        }
Пример #5
0
        public async Task TestAddHeaderTransform()
        {
            RecordingHandler testRecordingHandler = new RecordingHandler(Directory.GetCurrentDirectory());
            var httpContext = new DefaultHttpContext();

            httpContext.Request.Headers["x-abstraction-identifier"] = "HeaderTransform";
            httpContext.Request.Body = TestHelpers.GenerateStreamRequestBody(
                "{ \"key\": \"Location\", \"value\": \"https://fakeazsdktestaccount.table.core.windows.net/Tables\", \"condition\": { \"uriRegex\": \".*/token\", \"responseHeader\": { \"key\": \"Location\", \"valueRegex\": \".*/value\" } }}");
            httpContext.Request.ContentLength = httpContext.Request.Body.Length;

            var controller = new Admin(testRecordingHandler, _nullLogger)
            {
                ControllerContext = new ControllerContext()
                {
                    HttpContext = httpContext
                }
            };

            testRecordingHandler.Transforms.Clear();
            await controller.AddTransform();

            var result = testRecordingHandler.Transforms.First();

            Assert.True(result is HeaderTransform);
            var key         = (string)typeof(HeaderTransform).GetField("_key", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(result);
            var replacement = (string)typeof(HeaderTransform).GetField("_value", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(result);
            var regex       = result.Condition.ResponseHeader.ValueRegex;

            Assert.Equal("Location", key);
            Assert.Equal("https://fakeazsdktestaccount.table.core.windows.net/Tables", replacement);
            Assert.Equal(".*/value", regex);
            Assert.Equal(".*/token", result.Condition.UriRegex);
        }
Пример #6
0
        public async void TestAddSanitizer()
        {
            // arrange
            RecordingHandler testRecordingHandler = new RecordingHandler(Directory.GetCurrentDirectory());
            var httpContext = new DefaultHttpContext();

            httpContext.Request.Headers["x-abstraction-identifier"] = "HeaderRegexSanitizer";
            httpContext.Request.Body          = TestHelpers.GenerateStreamRequestBody("{ \"key\": \"Location\", \"value\": \"https://fakeazsdktestaccount.table.core.windows.net/Tables\" }");
            httpContext.Request.ContentLength = 92;

            var controller = new Admin(testRecordingHandler, _nullLogger)
            {
                ControllerContext = new ControllerContext()
                {
                    HttpContext = httpContext
                }
            };

            testRecordingHandler.Sanitizers.Clear();
            await controller.AddSanitizer();

            var result = testRecordingHandler.Sanitizers.First();

            Assert.True(result is HeaderRegexSanitizer);
        }
Пример #7
0
        public async void TestAddSanitizerWrongEmptyValue()
        {
            RecordingHandler testRecordingHandler = new RecordingHandler(Directory.GetCurrentDirectory());
            var httpContext = new DefaultHttpContext();

            httpContext.Request.Headers["x-abstraction-identifier"] = "HeaderRegexSanitizer";
            httpContext.Request.Body          = TestHelpers.GenerateStreamRequestBody("{ \"key\": \"\", \"value\": \"https://fakeazsdktestaccount.table.core.windows.net/Tables\" }");
            httpContext.Request.ContentLength = 92;

            var controller = new Admin(testRecordingHandler, _nullLogger)
            {
                ControllerContext = new ControllerContext()
                {
                    HttpContext = httpContext
                }
            };

            testRecordingHandler.Sanitizers.Clear();

            var assertion = await Assert.ThrowsAsync <HttpException>(
                async() => await controller.AddSanitizer()
                );

            assertion.StatusCode.Equals(HttpStatusCode.BadRequest);
        }
Пример #8
0
        private List <ActionDescription> _populateFromHandler(RecordingHandler handler)
        {
            List <ActionDescription> descriptions = new List <ActionDescription>();
            var docXML = GetDocCommentXML();

            descriptions.AddRange(handler.Sanitizers.Select(x => new ActionDescription()
            {
                ActionType         = MetaDataType.Sanitizer,
                Name               = x.GetType().Name,
                ConstructorDetails = GetInstanceDetails(x),
                Description        = GetClassDocComment(x.GetType(), docXML)
            }));

            descriptions.AddRange(handler.Transforms.Select(x => new ActionDescription()
            {
                ActionType         = MetaDataType.Transform,
                Name               = x.GetType().Name,
                ConstructorDetails = GetInstanceDetails(x),
                Description        = GetClassDocComment(x.GetType(), docXML)
            }));

            descriptions.Add(new ActionDescription()
            {
                ActionType         = MetaDataType.Matcher,
                Name               = handler.Matcher.GetType().Name,
                ConstructorDetails = GetInstanceDetails(handler.Matcher),
                Description        = GetClassDocComment(handler.Matcher.GetType(), docXML)
            });

            return(descriptions);
        }
Пример #9
0
        public async Task TestPlaybackSetsRetryAfterToZero()
        {
            RecordingHandler testRecordingHandler = new RecordingHandler(Directory.GetCurrentDirectory());
            var httpContext = new DefaultHttpContext();

            httpContext.Request.Headers["x-recording-file"] = "Test.RecordEntries/response_with_retry_after.json";

            var controller = new Playback(testRecordingHandler)
            {
                ControllerContext = new ControllerContext()
                {
                    HttpContext = httpContext
                }
            };
            await controller.Start();

            var recordingId = httpContext.Response.Headers["x-recording-id"].ToString();

            Assert.NotNull(recordingId);
            Assert.True(testRecordingHandler.PlaybackSessions.ContainsKey(recordingId));
            var          entry    = testRecordingHandler.PlaybackSessions[recordingId].Session.Entries[0];
            HttpRequest  request  = TestHelpers.CreateRequestFromEntry(entry);
            HttpResponse response = new DefaultHttpContext().Response;
            await testRecordingHandler.HandlePlaybackRequest(recordingId, request, response);

            Assert.Equal("0", response.Headers["Retry-After"]);

            // this response did not have the retry-after header initially, so it should not have been added.
            entry    = testRecordingHandler.PlaybackSessions[recordingId].Session.Entries[0];
            request  = TestHelpers.CreateRequestFromEntry(entry);
            response = new DefaultHttpContext().Response;
            await testRecordingHandler.HandlePlaybackRequest(recordingId, request, response);

            Assert.False(response.Headers.ContainsKey("Retry-After"));
        }
Пример #10
0
        public void TestCreateUpstreamRequestIncludesExpectedHeaders(params string[] incomingHeaders)
        {
            var requestContext         = GenerateHttpRequestContext(incomingHeaders);
            var recordingHandler       = new RecordingHandler(Directory.GetCurrentDirectory());
            var upstreamRequestContext = GenerateHttpRequestContext(incomingHeaders);

            var output = recordingHandler.CreateUpstreamRequest(upstreamRequestContext.Request, new byte[] { });

            // iterate across the set we know about and confirm that GenerateUpstreamRequest worked properly!
            var setOfHeaders = GenerateHeaderValuesTuples(incomingHeaders);
            {
                foreach (var headerTuple in setOfHeaders)
                {
                    var inContent  = false;
                    var inStandard = false;

                    try
                    {
                        inContent = output.Headers.Contains(headerTuple.Item1);
                    }
                    catch (Exception) { }

                    try
                    {
                        inStandard = output.Content.Headers.Contains(headerTuple.Item1);
                    }
                    catch (Exception) { }

                    Assert.True(inContent || inStandard);
                }
            }
        }
Пример #11
0
        public void TestRecordMaintainsUpstreamOverrideHostHeader(string upstreamHostHeaderValue)
        {
            var httpContext = new DefaultHttpContext();
            RecordingHandler testRecordingHandler = new RecordingHandler(Directory.GetCurrentDirectory());

            testRecordingHandler.StartRecording("hello.json", httpContext.Response);

            var recordingId = httpContext.Response.Headers["x-recording-id"].ToString();

            httpContext.Request.Body                      = TestHelpers.GenerateStreamRequestBody(String.Empty);
            httpContext.Request.ContentLength             = 0;
            httpContext.Request.Headers["x-recording-id"] = recordingId;
            httpContext.Request.Headers["x-recording-upstream-base-uri"] = "http://example.org";

            if (!String.IsNullOrWhiteSpace(upstreamHostHeaderValue))
            {
                httpContext.Request.Headers["x-recording-upstream-host-header"] = upstreamHostHeaderValue;
            }

            httpContext.Request.Method = "GET";

            var upstreamRequest = testRecordingHandler.CreateUpstreamRequest(httpContext.Request, new byte[] { });

            if (!String.IsNullOrWhiteSpace(upstreamHostHeaderValue))
            {
                Assert.Equal(upstreamHostHeaderValue, upstreamRequest.Headers.Host);
            }
            else
            {
                Assert.Null(upstreamRequest.Headers.Host);
            }
        }
Пример #12
0
        public void TestResetTargetsSessionOnly()
        {
            RecordingHandler testRecordingHandler = new RecordingHandler(Directory.GetCurrentDirectory());
            var httpContext = new DefaultHttpContext();

            testRecordingHandler.StartRecording("recordingings/cool.json", httpContext.Response);
            var recordingId = httpContext.Response.Headers["x-recording-id"].ToString();

            testRecordingHandler.Sanitizers.Clear();
            testRecordingHandler.Sanitizers.Add(new BodyRegexSanitizer("sanitized", ".*"));
            testRecordingHandler.Transforms.Clear();
            testRecordingHandler.AddSanitizerToRecording(recordingId, new GeneralRegexSanitizer("sanitized", ".*"));
            testRecordingHandler.SetDefaultExtensions(recordingId);
            var session = testRecordingHandler.RecordingSessions.First().Value;

            // check that the individual session had reset sanitizers
            Assert.Empty(session.AdditionalSanitizers);

            // stop the recording to clear out the session cache
            testRecordingHandler.StopRecording(recordingId);

            // then verify that the session level is NOT reset.
            Assert.Single(testRecordingHandler.Sanitizers);
            Assert.IsType <BodyRegexSanitizer>(testRecordingHandler.Sanitizers.First());
        }
Пример #13
0
        public void TestAddTransform()
        {
            // arrange
            RecordingHandler testRecordingHandler = new RecordingHandler(Directory.GetCurrentDirectory());
            var httpContext = new DefaultHttpContext();
            var apiVersion  = "2016-03-21";

            httpContext.Request.Headers["x-api-version"]            = apiVersion;
            httpContext.Request.Headers["x-abstraction-identifier"] = "ApiVersionTransform";

            var controller = new Admin(testRecordingHandler)
            {
                ControllerContext = new ControllerContext()
                {
                    HttpContext = httpContext
                }
            };

            testRecordingHandler.Transforms.Clear();

            // act
            controller.AddTransform();

            var result = testRecordingHandler.Transforms.First();

            // assert
            Assert.True(result is ApiVersionTransform);
        }
Пример #14
0
        public async Task TestStopRecordingInMemory(string additionalEntryModeHeader)
        {
            RecordingHandler testRecordingHandler = new RecordingHandler(Directory.GetCurrentDirectory());

            var recordContext    = new DefaultHttpContext();
            var recordController = new Record(testRecordingHandler, _nullLogger)
            {
                ControllerContext = new ControllerContext()
                {
                    HttpContext = recordContext
                }
            };
            await recordController.Start();

            var inMemId = recordContext.Response.Headers["x-recording-id"].ToString();

            recordContext.Request.Headers["x-recording-id"] = new string[] { inMemId };

            if (!string.IsNullOrEmpty(additionalEntryModeHeader))
            {
                recordContext.Request.Headers["x-recording-skip"] = additionalEntryModeHeader;
            }

            recordController.Stop();

            if (string.IsNullOrEmpty(additionalEntryModeHeader))
            {
                Assert.True(testRecordingHandler.InMemorySessions.Count() == 1);
                Assert.NotNull(testRecordingHandler.InMemorySessions[inMemId]);
            }
            else
            {
                Assert.True(testRecordingHandler.InMemorySessions.Count() == 0);
            }
        }
Пример #15
0
        public async Task TestSetCustomMatcherWithQueryOrdering()
        {
            RecordingHandler testRecordingHandler = new RecordingHandler(Directory.GetCurrentDirectory());
            var httpContext = new DefaultHttpContext();

            httpContext.Request.Headers["x-abstraction-identifier"] = "CustomDefaultMatcher";
            httpContext.Request.Body = TestHelpers.GenerateStreamRequestBody("{ \"ignoreQueryOrdering\": true }");

            // content length must be set for the body to be parsed in SetMatcher
            httpContext.Request.ContentLength = httpContext.Request.Body.Length;

            var controller = new Admin(testRecordingHandler, _nullLogger)
            {
                ControllerContext = new ControllerContext()
                {
                    HttpContext = httpContext
                }
            };
            await controller.SetMatcher();

            var matcher = testRecordingHandler.Matcher;

            Assert.True(matcher is CustomDefaultMatcher);

            var queryOrderingValue = (bool)typeof(RecordMatcher).GetField("_ignoreQueryOrdering", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(matcher);

            Assert.True(queryOrderingValue);
        }
Пример #16
0
        public void TestStopRecordingSimple()
        {
            RecordingHandler testRecordingHandler = new RecordingHandler(Directory.GetCurrentDirectory());
            var httpContext = new DefaultHttpContext();
            var targetFile  = "recordings/TestStartRecordSimple.json";

            httpContext.Request.Headers["x-recording-file"] = targetFile;

            var controller = new Record(testRecordingHandler)
            {
                ControllerContext = new ControllerContext()
                {
                    HttpContext = httpContext
                }
            };

            controller.Start();
            var recordingId = httpContext.Response.Headers["x-recording-id"].ToString();

            httpContext.Request.Headers["x-recording-id"] = recordingId;
            httpContext.Request.Headers.Remove("x-recording-file");

            controller.Stop();

            var fullPath = testRecordingHandler.GetRecordingPath(targetFile);

            Assert.True(File.Exists(fullPath));
        }
Пример #17
0
        public async void TestSetMatcherIndividualRecording()
        {
            RecordingHandler testRecordingHandler = new RecordingHandler(Directory.GetCurrentDirectory());
            var httpContext = new DefaultHttpContext();
            await testRecordingHandler.StartPlaybackAsync("Test.RecordEntries/oauth_request_with_variables.json", httpContext.Response);

            var recordingId = httpContext.Response.Headers["x-recording-id"];

            httpContext.Request.Headers["x-recording-id"]           = recordingId;
            httpContext.Request.Headers["x-abstraction-identifier"] = "BodilessMatcher";
            httpContext.Request.Body = TestHelpers.GenerateStreamRequestBody("{}");

            var controller = new Admin(testRecordingHandler, _nullLogger)
            {
                ControllerContext = new ControllerContext()
                {
                    HttpContext = httpContext
                }
            };
            await controller.SetMatcher();

            var result = testRecordingHandler.PlaybackSessions[recordingId].CustomMatcher;

            Assert.True(result is BodilessMatcher);
        }
        public async Task CanApplyHeaderTransform()
        {
            var headerTransform = new HeaderTransform(
                "someNewHeader",
                "value");
            RecordingHandler testRecordingHandler = new RecordingHandler(Directory.GetCurrentDirectory());

            testRecordingHandler.Transforms.Clear();
            testRecordingHandler.Transforms.Add(headerTransform);

            var playbackContext  = new DefaultHttpContext();
            var targetFile       = "Test.RecordEntries/response_with_header_to_transform.json";
            var transformedEntry = TestHelpers.LoadRecordSession(targetFile).Session.Entries[0];

            // start playback
            playbackContext.Request.Headers["x-recording-file"] = targetFile;
            var controller = new Playback(testRecordingHandler)
            {
                ControllerContext = new ControllerContext()
                {
                    HttpContext = playbackContext
                }
            };
            await controller.Start();

            var recordingId = playbackContext.Response.Headers["x-recording-id"].ToString();

            // transform should apply
            HttpRequest  request  = TestHelpers.CreateRequestFromEntry(transformedEntry);
            HttpResponse response = new DefaultHttpContext().Response;
            await testRecordingHandler.HandlePlaybackRequest(recordingId, request, response);

            Assert.Equal("value", response.Headers["someNewHeader"]);
        }
Пример #19
0
        public async void TestAddSanitizerWithOddDefaults()
        {
            // arrange
            RecordingHandler testRecordingHandler = new RecordingHandler(Directory.GetCurrentDirectory());
            var httpContext = new DefaultHttpContext();

            httpContext.Request.Headers["x-abstraction-identifier"] = "BodyKeySanitizer";
            httpContext.Request.Body = TestHelpers.GenerateStreamRequestBody("{ \"jsonPath\": \"$.TableName\" }");
            httpContext.Request.Headers["Content-Length"] = new string[] { "34" };
            httpContext.Request.Headers["Content-Type"]   = new string[] { "application/json" };

            var controller = new Admin(testRecordingHandler, _nullLogger)
            {
                ControllerContext = new ControllerContext()
                {
                    HttpContext = httpContext
                }
            };

            testRecordingHandler.Sanitizers.Clear();
            await controller.AddSanitizer();

            var result = testRecordingHandler.Sanitizers.First();

            Assert.True(result is BodyKeySanitizer);
        }
Пример #20
0
        public async Task TestAddSanitizerWithValidUriRegexCondition(string requestBody, string conditionRegex)
        {
            requestBody = requestBody.Replace("CONDITION_REGEX", conditionRegex);
            RecordingHandler testRecordingHandler = new RecordingHandler(Directory.GetCurrentDirectory());
            var httpContext = new DefaultHttpContext();

            httpContext.Request.Headers["x-abstraction-identifier"] = "GeneralRegexSanitizer";
            httpContext.Request.Body          = TestHelpers.GenerateStreamRequestBody(requestBody);
            httpContext.Request.ContentLength = httpContext.Request.Body.Length;

            var controller = new Admin(testRecordingHandler)
            {
                ControllerContext = new ControllerContext()
                {
                    HttpContext = httpContext
                }
            };

            testRecordingHandler.Sanitizers.Clear();
            await controller.AddSanitizer();

            var createdSanitizer = testRecordingHandler.Sanitizers.First();

            Assert.Single(testRecordingHandler.Sanitizers);
            Assert.True(createdSanitizer is GeneralRegexSanitizer);
            Assert.True(createdSanitizer.Condition != null);
            Assert.True(createdSanitizer.Condition is ApplyCondition);
            Assert.Equal(conditionRegex, createdSanitizer.Condition.UriRegex);
        }
Пример #21
0
        public async void TestAddSanitizerIndividualRecording()
        {
            RecordingHandler testRecordingHandler = new RecordingHandler(Directory.GetCurrentDirectory());
            var httpContext = new DefaultHttpContext();
            await testRecordingHandler.StartPlaybackAsync("Test.RecordEntries/oauth_request_with_variables.json", httpContext.Response);

            var recordingId = httpContext.Response.Headers["x-recording-id"];

            httpContext.Request.Headers["x-recording-id"]           = recordingId;
            httpContext.Request.Headers["x-abstraction-identifier"] = "HeaderRegexSanitizer";
            httpContext.Request.Body          = TestHelpers.GenerateStreamRequestBody("{ \"key\": \"Location\", \"value\": \"https://fakeazsdktestaccount.table.core.windows.net/Tables\" }");
            httpContext.Request.ContentLength = 92;

            var controller = new Admin(testRecordingHandler, _nullLogger)
            {
                ControllerContext = new ControllerContext()
                {
                    HttpContext = httpContext
                }
            };
            await controller.AddSanitizer();

            var result = testRecordingHandler.PlaybackSessions[recordingId].AdditionalSanitizers.First();

            Assert.True(result is HeaderRegexSanitizer);
        }
Пример #22
0
        public async void TestStopPlaybackSimple()
        {
            RecordingHandler testRecordingHandler = new RecordingHandler(Directory.GetCurrentDirectory());
            var httpContext = new DefaultHttpContext();
            var body        = "{\"x-recording-file\":\"Test.RecordEntries/requests_with_continuation.json\"}";

            httpContext.Request.Body          = TestHelpers.GenerateStreamRequestBody(body);
            httpContext.Request.ContentLength = body.Length;

            var controller = new Playback(testRecordingHandler)
            {
                ControllerContext = new ControllerContext()
                {
                    HttpContext = httpContext
                }
            };
            await controller.Start();

            var targetRecordingId = httpContext.Response.Headers["x-recording-id"].ToString();

            httpContext.Request.Headers["x-recording-id"] = new string[] { targetRecordingId };
            controller.Stop();

            Assert.False(testRecordingHandler.PlaybackSessions.ContainsKey(targetRecordingId));
        }
Пример #23
0
        public async Task AddSanitizerThrowsOnAdditionOfBadRegex()
        {
            RecordingHandler testRecordingHandler = new RecordingHandler(Directory.GetCurrentDirectory());
            var httpContext = new DefaultHttpContext();

            httpContext.Request.Headers["x-abstraction-identifier"] = "UriRegexSanitizer";
            httpContext.Request.Body          = TestHelpers.GenerateStreamRequestBody("{\"value\":\"replacementValue\",\"regex\":\"[\"}");
            httpContext.Request.ContentLength = 25;

            var controller = new Admin(testRecordingHandler, _nullLogger)
            {
                ControllerContext = new ControllerContext()
                {
                    HttpContext = httpContext
                }
            };

            testRecordingHandler.Sanitizers.Clear();

            var assertion = await Assert.ThrowsAsync <HttpException>(
                async() => await controller.AddSanitizer()
                );

            Assert.True(assertion.StatusCode.Equals(HttpStatusCode.BadRequest));
            Assert.Contains("Expression of value [ does not successfully compile.", assertion.Message);
        }
Пример #24
0
        public void TestStopRecordingWithVariables()
        {
            var tmpPath          = Path.GetTempPath();
            var startHttpContext = new DefaultHttpContext();
            var pathToRecording  = "recordings/oauth_request_new.json";
            var recordingHandler = new RecordingHandler(tmpPath);
            var dict             = new Dictionary <string, string> {
                { "key1", "valueabc123" },
                { "key2", "value123abc" }
            };
            var endHttpContext = new DefaultHttpContext();

            recordingHandler.StartRecording(pathToRecording, startHttpContext.Response);
            var sessionId = startHttpContext.Response.Headers["x-recording-id"].ToString();

            recordingHandler.StopRecording(sessionId, variables: new SortedDictionary <string, string>(dict));
            var storedVariables = TestHelpers.LoadRecordSession(Path.Combine(tmpPath, pathToRecording)).Session.Variables;

            Assert.Equal(dict.Count, storedVariables.Count);

            foreach (var kvp in dict)
            {
                Assert.Equal(kvp.Value, storedVariables[kvp.Key]);
            }
        }
Пример #25
0
        public async void TestAddTransformIndividualRecording()
        {
            RecordingHandler testRecordingHandler = new RecordingHandler(Directory.GetCurrentDirectory());
            var httpContext = new DefaultHttpContext();
            await testRecordingHandler.StartPlaybackAsync("Test.RecordEntries/oauth_request_with_variables.json", httpContext.Response);

            var recordingId = httpContext.Response.Headers["x-recording-id"];
            var apiVersion  = "2016-03-21";

            httpContext.Request.Headers["x-api-version"]            = apiVersion;
            httpContext.Request.Headers["x-abstraction-identifier"] = "ApiVersionTransform";
            httpContext.Request.Headers["x-recording-id"]           = recordingId;

            var controller = new Admin(testRecordingHandler, _nullLogger)
            {
                ControllerContext = new ControllerContext()
                {
                    HttpContext = httpContext
                }
            };
            await controller.AddTransform();

            var result = testRecordingHandler.PlaybackSessions[recordingId].AdditionalTransforms.First();

            Assert.True(result is ApiVersionTransform);
        }
Пример #26
0
        public async Task TestStartPlaybackWithoutVariables()
        {
            var startHttpContext = new DefaultHttpContext();
            var recordingHandler = new RecordingHandler(Directory.GetCurrentDirectory());

            await recordingHandler.StartPlayback("Test.RecordEntries/oauth_request.json", startHttpContext.Response);
        }
Пример #27
0
        [InlineData("{ \"value\": \"hello_there\", \"condition\": {}}", "At least one trigger regex must be present.")]         // empty condition keys, but defined condition object
        public async Task TestAddTransformWithBadUriRegexCondition(string body, string errorText)
        {
            RecordingHandler testRecordingHandler = new RecordingHandler(Directory.GetCurrentDirectory());
            var httpContext = new DefaultHttpContext();

            httpContext.Request.Headers["x-abstraction-identifier"] = "ApiVersionTransform";
            httpContext.Request.Body          = TestHelpers.GenerateStreamRequestBody(body);
            httpContext.Request.ContentLength = httpContext.Request.Body.Length;

            var controller = new Admin(testRecordingHandler, _nullLogger)
            {
                ControllerContext = new ControllerContext()
                {
                    HttpContext = httpContext
                }
            };

            testRecordingHandler.Transforms.Clear();
            var assertion = await Assert.ThrowsAsync <HttpException>(
                async() => await controller.AddTransform()
                );

            Assert.Equal(HttpStatusCode.BadRequest, assertion.StatusCode);
            Assert.Empty(testRecordingHandler.Transforms);
            Assert.Contains(errorText, assertion.Message);
        }
Пример #28
0
        public async Task TestSetCustomMatcher()
        {
            RecordingHandler testRecordingHandler = new RecordingHandler(Directory.GetCurrentDirectory());
            var httpContext = new DefaultHttpContext();

            httpContext.Request.Headers["x-abstraction-identifier"] = "CustomDefaultMatcher";
            httpContext.Request.Body = TestHelpers.GenerateStreamRequestBody("{ \"excludedHeaders\": \"Content-Type,Content-Length\", \"ignoredHeaders\": \"Connection\", \"compareBodies\": false, \"ignoredQueryParameters\": \"api-version,location\" }");

            // content length must be set for the body to be parsed in SetMatcher
            httpContext.Request.ContentLength = httpContext.Request.Body.Length;

            var controller = new Admin(testRecordingHandler, _nullLogger)
            {
                ControllerContext = new ControllerContext()
                {
                    HttpContext = httpContext
                }
            };
            await controller.SetMatcher();

            var matcher = testRecordingHandler.Matcher;

            Assert.True(matcher is CustomDefaultMatcher);

            var compareBodies = (bool)typeof(RecordMatcher).GetField("_compareBodies", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(matcher);

            Assert.False(compareBodies);

            Assert.Contains("Content-Type", matcher.ExcludeHeaders);
            Assert.Contains("Content-Length", matcher.ExcludeHeaders);
            Assert.Contains("Connection", matcher.IgnoredHeaders);
            Assert.Contains("api-version", matcher.IgnoredQueryParameters);
            Assert.Contains("location", matcher.IgnoredQueryParameters);
        }
Пример #29
0
        public async Task TestAddSanitizerContinuesWithTwoRequiredParams()
        {
            var targetKey    = "Content-Type";
            var targetString = "application/javascript";

            RecordingHandler testRecordingHandler = new RecordingHandler(Directory.GetCurrentDirectory());
            var httpContext = new DefaultHttpContext();

            httpContext.Request.Headers["x-abstraction-identifier"] = "HeaderStringSanitizer";
            httpContext.Request.Body          = TestHelpers.GenerateStreamRequestBody("{\"target\":\"" + targetString + "\", \"key\":\"" + targetKey + "\"}");
            httpContext.Request.ContentLength = 79;

            var controller = new Admin(testRecordingHandler, _nullLogger)
            {
                ControllerContext = new ControllerContext()
                {
                    HttpContext = httpContext
                }
            };

            testRecordingHandler.Sanitizers.Clear();
            await controller.AddSanitizer();

            var addedSanitizer = testRecordingHandler.Sanitizers.First();

            Assert.True(addedSanitizer is HeaderStringSanitizer);

            var actualTargetString = (string)typeof(HeaderStringSanitizer).GetField("_targetValue", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(addedSanitizer);
            var actualTargetKey    = (string)typeof(HeaderStringSanitizer).GetField("_targetKey", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(addedSanitizer);

            Assert.Equal(targetKey, actualTargetKey);
            Assert.Equal(targetString, actualTargetString);
        }
Пример #30
0
        public async Task TestStopRecordingSimple(string targetFile)
        {
            RecordingHandler testRecordingHandler = new RecordingHandler(Directory.GetCurrentDirectory());
            var httpContext = new DefaultHttpContext();
            var body        = "{\"x-recording-file\":\"" + targetFile + "\"}";

            httpContext.Request.Body          = TestHelpers.GenerateStreamRequestBody(body);
            httpContext.Request.ContentLength = body.Length;

            var controller = new Record(testRecordingHandler)
            {
                ControllerContext = new ControllerContext()
                {
                    HttpContext = httpContext
                }
            };
            await controller.Start();

            var recordingId = httpContext.Response.Headers["x-recording-id"].ToString();

            httpContext.Request.Headers["x-recording-id"] = recordingId;
            httpContext.Request.Headers.Remove("x-recording-file");

            controller.Stop();

            var fullPath = testRecordingHandler.GetRecordingPath(targetFile);

            Assert.True(File.Exists(fullPath));
        }