예제 #1
0
        public void Should_Be_Flippable()
        {
            var response = new MockRequest(new Lobster()).Get("/?flip=left");

            Assert.AreEqual(200, response.Status);
            Assert.IsTrue(response.Body.ToString().Contains("(,,,(,,(,("));
        }
        public void It_Processes_Requests()
        {
            var response = new MockRequest(new TestApplication()).Get("/");

            Assert.AreEqual(200, response.Status);
            Assert.AreEqual("Bam!", response.Body.ToString());
        }
        public void It_Passes_Form_Post_Data_Into_Action()
        {
            var response = new MockRequest(new TestApplication()).Post("/post",
                                                                         new Dictionary<string, dynamic> { { "input", "testData=horticulture" } });

            Assert.AreEqual("horticulture", response.Body.ToString());
        }
예제 #4
0
        public void Should_Look_Like_A_Lobster()
        {
            var response = new MockRequest(Lobster.LambdaLobster).Get("/");

            Assert.AreEqual(200, response.Status);
            Assert.IsTrue(response.Body.ToString().Contains("(,(,,(,,,("));
            Assert.IsTrue(response.Body.ToString().Contains("?flip"));
        }
예제 #5
0
        public void Should_Return_Error_For_Unsatisfiable_Byte_Range()
        {
            var env = new MockRequest().EnvironmentFor("/cgi/test");
            env["HTTP_RANGE"] = "bytes=1234-5678";
            var response = new MockResponse(new File(_docRoot).Call(env));

            Assert.AreEqual(416, response.Status);
            Assert.AreEqual("bytes */193", response["Content-Range"]);
        }
예제 #6
0
 public void Template_engine_performs_url_replacements_with_virtual_directory()
 {
     var service = new BasicTemplateService();
     var r = new MockRequest(new Uri("http://sandbox.ascendrewards.com/bar/admin/foo"), "/bar");
     var t = new Template { Content = @"This is a <a href=""~/url"">link</a>." };
     var d = new TemplateData {{ "foo", "bar" }};
     var w = service.Render(t.Content, d, r);
     Assert.That(w, Is.EqualTo(@"This is a <a href=""http://sandbox.ascendrewards.com/bar/url"">link</a>."));
 }
예제 #7
0
 public void Init()
 {
     Environment.SetEnvironmentVariable("ViewDirectory", "../../Views/");
     _mRequest = new MockRequest
     {
         Method = "GET",
         Resource = "/",
         HttpVersion = "HTTP/1.1"
     };
     _director = new QuoteFormResponse();
 }
예제 #8
0
        public void Should_Return_Correct_Byte_Range_In_Body()
        {
            var env = new MockRequest().EnvironmentFor("/cgi/test");
            env["HTTP_RANGE"] = "bytes=22-33";
            var response = new MockResponse(new File(_docRoot).Call(env));

            Assert.AreEqual(206, response.Status);
            Assert.AreEqual("12", response["Content-Length"]);
            Assert.AreEqual("bytes 22-33/193", response["Content-Range"]);
            Assert.AreEqual("-*- test -*-", response.Body.ToString());
        }
예제 #9
0
        public void Should_Return_Bodies_That_Respond_To_ToPath()
        {
            var env = new MockRequest().EnvironmentFor("/cgi/test");
            var response = new File(_docRoot).Call(env);

            var path = Path.Combine(_docRoot, "cgi/test");

            Assert.AreEqual(200, response[0]);
            Assert.IsTrue(response[2] is IPathConvertible);
            Assert.AreEqual(path, response[2].ToPath());
        }
예제 #10
0
        public void Should_Catch_Exceptions()
        {
            dynamic res = null;

            var req = new MockRequest(new ShowExceptions(DetachedApplication.Create(
                env => { throw new InvalidOperationException(); })));

            Assert.DoesNotThrow(delegate { res = req.Get("/"); });

            Assert.AreEqual(500, res.Status);

            Assert.IsTrue(res.Body.ToString().Contains("InvalidOperationException"));
            Assert.IsTrue(res.Body.ToString().Contains("ShowExceptions"));
        }
예제 #11
0
        public async Task GetWithLabel()
        {
            var response = new MockResponse(200);

            response.SetContent(SerializationHelpers.Serialize(s_testSetting, SerializeSetting));

            var mockTransport           = new MockTransport(response);
            ConfigurationClient service = CreateTestService(mockTransport);

            ConfigurationSetting setting = await service.GetAsync(s_testSetting.Key, s_testSetting.Label);

            MockRequest request = mockTransport.SingleRequest;

            AssertRequestCommon(request);
            Assert.AreEqual(RequestMethod.Get, request.Method);
            Assert.AreEqual($"https://contoso.appconfig.io/kv/test_key?label=test_label&api-version={s_version}", request.Uri.ToString());
            Assert.AreEqual(s_testSetting, setting);
        }
        public void ShouldReturnListOfRelationshipInstancesWithPayloads()
        {
            //Arrange
            const string gremlinQueryExpected = "foo bar query";
            var          query = new GremlinApiQuery(gremlinQueryExpected, null);

            using (var testHarness = new RestTestHarness
            {
                {
                    MockRequest.PostObjectAsJson("/ext/GremlinPlugin/graphdb/execute_script", query),
                    MockResponse.Json(HttpStatusCode.OK, @"[ {
                          'start' : 'http://127.0.0.1:5118/db/data/node/123',
                          'data' : {
                            'Foo': 'Foo',
                            'Bar': 'Bar'
                          },
                          'self' : 'http://127.0.0.1:5118/db/data/relationship/456',
                          'property' : 'http://127.0.0.1:5118/db/data/relationship/456/properties/{key}',
                          'properties' : 'http://127.0.0.1:5118/db/data/relationship/456/properties',
                          'type' : 'KNOWS',
                          'extensions' : {
                          },
                          'end' : 'http://127.0.0.1:5118/db/data/node/789'
                        } ]")
                }
            })
            {
                var graphClient = (GraphClient)testHarness.CreateAndConnectGraphClient();

                //Act
                var relationships = graphClient
                                    .ExecuteGetAllRelationshipsGremlin <TestPayload>(gremlinQueryExpected, null)
                                    .ToList();

                //Assert
                Assert.AreEqual(1, relationships.Count());
                Assert.AreEqual(456, relationships.ElementAt(0).Reference.Id);
                Assert.AreEqual(123, relationships.ElementAt(0).StartNodeReference.Id);
                Assert.AreEqual(789, relationships.ElementAt(0).EndNodeReference.Id);
                Assert.AreEqual("KNOWS", relationships.ElementAt(0).TypeKey);
                Assert.AreEqual("Foo", relationships.ElementAt(0).Data.Foo);
                Assert.AreEqual("Bar", relationships.ElementAt(0).Data.Bar);
            }
        }
예제 #13
0
        public void ExecuteMultipleStatementInOneRequest()
        {
            var initTransactionRequest = MockRequest.PostJson("/transaction", @"{
                'statements': [{'statement': 'MATCH n\r\nRETURN count(n)', 'resultDataContents':[], 'parameters': {}}, {'statement': 'MATCH t\r\nRETURN count(t)', 'resultDataContents':[], 'parameters': {}}]}");
            var commitRequest          = MockRequest.PostJson("/transaction/1/commit", @"{'statements': []}");

            using (var testHarness = new RestTestHarness
            {
                {
                    initTransactionRequest,
                    MockResponse.Json(201, TransactionRestResponseHelper.GenerateInitTransactionResponse(1), "http://foo/db/data/transaction/1")
                },
                {
                    commitRequest, MockResponse.Json(200, @"{'results':[], 'errors':[] }")
                }
            })
            {
                var client = testHarness.CreateAndConnectTransactionalGraphClient();
                using (var transaction = client.BeginTransaction())
                {
                    // dummy query to generate request
                    var rawClient = client as IRawGraphClient;
                    if (rawClient == null)
                    {
                        Assert.Fail("ITransactionalGraphClient is not IRawGraphClient");
                    }

                    var queries = new List <CypherQuery>()
                    {
                        client.Cypher
                        .Match("n")
                        .Return(n => n.Count())
                        .Query,
                        client.Cypher
                        .Match("t")
                        .Return(t => t.Count())
                        .Query
                    };

                    rawClient.ExecuteMultipleCypherQueriesInTransaction(queries);
                    transaction.Commit();
                }
            }
        }
예제 #14
0
        public void ShouldThrowNeoExceptionWhenBatchCreationStepJobFails()
        {
            var testHarness = new RestTestHarness
            {
                {
                    MockRequest.PostJson("/batch",
                                         @"[{
                          'method': 'POST', 'to' : '/node',
                          'body': {
                            'Foo': 'foo',
                            'TestNode2': { 'Foo': 'foo', 'Bar': 'bar' }
                          },
                          'id': 0
                        }]"
                                         ),
                    MockResponse.Json(HttpStatusCode.OK,
                                      @"[ {
                        'id':0,'location':null,
                        'body': {
                            'message': 'Could not set property ""TestNode2"", unsupported type: {Foo=foo, Bar=bar}',
                            'exception': 'PropertyValueException',
                            'fullname': 'org.neo4j.server.rest.web.PropertyValueException',
                            'stacktrace': [
                               'org.neo4j.server.rest.domain.PropertySettingStrategy.setProperty(PropertySettingStrategy.java:141)',
                               'java.lang.Thread.run(Unknown Source)'
                            ]
                        },
                        'status': 400}]"
                                      )
                }
            };

            var graphClient = testHarness.CreateAndConnectGraphClient();
            var ex          = Assert.Throws <NeoException>(() => graphClient.Create(new NestedTestNode()
            {
                Foo       = "foo",
                TestNode2 = new TestNode2()
                {
                    Bar = "bar", Foo = "foo"
                }
            }));

            ex.Message.Should().Be("PropertyValueException: Could not set property \"TestNode2\", unsupported type: {Foo=foo, Bar=bar}");
        }
        public void ShouldReindexRelationshipWithDateTimeOffsetIndexEntry()
        {
            //Arrange
            var indexEntries = new List <IndexEntry>
            {
                new IndexEntry
                {
                    Name      = "my_relationships",
                    KeyValues = new Dictionary <string, object>
                    {
                        { "BarKey", new DateTimeOffset(1000, new TimeSpan(0)) }
                    },
                }
            };

            using (var testHarness = new RestTestHarness
            {
                {
                    MockRequest.PostObjectAsJson("/index/relationship/my_relationships",
                                                 new
                    {
                        key = "BarKey",
                        value = "1000",
                        uri = "http://foo/db/data/relationship/1234"
                    }),
                    MockResponse.Json(HttpStatusCode.Created,
                                      @"Location: http://foo/db/data/index/relationship/my_relationships/BarKey/someDateValue/1234")
                },
                {
                    MockRequest.Delete("/index/relationship/my_relationships/1234"),
                    MockResponse.Http((int)HttpStatusCode.NoContent)
                }
            })
            {
                var graphClient = testHarness.CreateAndConnectGraphClient();

                //Act
                var relReference = new RelationshipReference(1234);
                graphClient.ReIndex(relReference, indexEntries);

                // Assert
                Assert.Pass("Success.");
            }
        }
예제 #16
0
        public async Task VerifyImdsRequestWithClientIdMockAsync()
        {
            using (new TestEnvVar("MSI_ENDPOINT", null))
                using (new TestEnvVar("MSI_SECRET", null))
                {
                    var response = new MockResponse(200);

                    var expectedToken = "mock-msi-access-token";

                    response.SetContent($"{{ \"access_token\": \"{expectedToken}\", \"expires_on\": \"3600\" }}");

                    var mockTransport = new MockTransport(response);

                    var options = new TokenCredentialOptions()
                    {
                        Transport = mockTransport
                    };

                    var pipeline = CredentialPipeline.GetInstance(options);

                    ManagedIdentityCredential credential = InstrumentClient(new ManagedIdentityCredential(pipeline, new MockManagedIdentityClient(pipeline, "mock-client-id")
                    {
                        ImdsAvailableFunc = _ => true
                    }));

                    AccessToken actualToken = await credential.GetTokenAsync(new TokenRequestContext(MockScopes.Default));

                    Assert.AreEqual(expectedToken, actualToken.Token);

                    MockRequest request = mockTransport.Requests[0];

                    string query = request.Uri.Query;

                    Assert.IsTrue(query.Contains("api-version=2018-02-01"));

                    Assert.IsTrue(query.Contains($"resource={Uri.EscapeDataString(ScopeUtilities.ScopesToResource(MockScopes.Default))}"));

                    Assert.IsTrue(query.Contains($"client_id=mock-client-id"));

                    Assert.IsTrue(request.Headers.TryGetValue("Metadata", out string metadataValue));

                    Assert.AreEqual("true", metadataValue);
                }
        }
        public void ShouldPreserveSlashInRelationshipIndexValue()
        {
            //Arrange
            var indexKeyValues = new Dictionary <string, object>
            {
                { "BarKey", "abc/def" }
            };
            var indexEntries = new List <IndexEntry>
            {
                new IndexEntry
                {
                    Name      = "my_relationships",
                    KeyValues = indexKeyValues,
                }
            };

            using (var testHarness = new RestTestHarness
            {
                {
                    MockRequest.PostObjectAsJson("/index/relationship/my_relationships",
                                                 new
                    {
                        key = "BarKey",
                        value = "abc/def",
                        uri = "http://foo/db/data/relationship/123"
                    }),
                    MockResponse.Json(HttpStatusCode.Created,
                                      @"Location: http://foo/db/data/index/relationship/my_relationships/BarKey/abc-def/1234")
                },
                {
                    MockRequest.Delete("/index/relationship/my_relationships/123"),
                    MockResponse.Http((int)HttpStatusCode.NoContent)
                }
            })
            {
                var graphClient = testHarness.CreateAndConnectGraphClient();

                //Act
                var relReference = new RelationshipReference(123);
                graphClient.ReIndex(relReference, indexEntries);

                // Assert
            }
        }
예제 #18
0
        public void ShouldPreserveSlashInIndexValue()
        {
            //Arrange
            var indexKeyValues = new Dictionary <string, object>
            {
                { "FooKey", "abc/def" }
            };
            var indexEntries = new List <IndexEntry>
            {
                new IndexEntry
                {
                    Name      = "my_nodes",
                    KeyValues = indexKeyValues,
                }
            };

            using (var testHarness = new RestTestHarness
            {
                {
                    MockRequest.PostObjectAsJson("/index/node/my_nodes",
                                                 new
                    {
                        key = "FooKey",
                        value = "abc/def",
                        uri = "http://foo/db/data/node/123"
                    }),
                    MockResponse.Json(HttpStatusCode.Created,
                                      @"Location: http://foo/db/data/index/node/my_nodes/FooKey/abc-def/123")
                },
                {
                    MockRequest.Delete("/index/node/my_nodes/123"),
                    MockResponse.Http((int)HttpStatusCode.NoContent)
                }
            })
            {
                var graphClient = testHarness.CreateAndConnectGraphClient();

                //Act
                graphClient.ReIndex((NodeReference)123, indexEntries);

                // Assert
                Assert.Pass("Success.");
            }
        }
예제 #19
0
 public void ShouldDeleteAllRelationshipsFirst()
 {
     using (var testHarness = new RestTestHarness
     {
         {
             MockRequest.Get("/node/456/relationships/all"),
             MockResponse.Json(HttpStatusCode.OK,
                               @"[
                   { 'self': 'http://foo/db/data/relationship/56',
                     'start': 'http://foo/db/data/node/123',
                     'end': 'http://foo/db/data/node/456',
                     'type': 'KNOWS',
                     'properties': 'http://foo/db/data/relationship/56/properties',
                     'property': 'http://foo/db/data/relationship/56/properties/{key}',
                     'data': { 'date': 1270559208258 }
                   },
                   { 'self': 'http://foo/db/data/relationship/78',
                     'start': 'http://foo/db/data/node/456',
                     'end': 'http://foo/db/data/node/789',
                     'type': 'KNOWS',
                     'properties': 'http://foo/db/data/relationship/78/properties',
                     'property': 'http://foo/db/data/relationship/78/properties/{key}',
                     'data': { 'date': 1270559208258 }
                   }
                 ]")
         },
         {
             MockRequest.Delete("/relationship/56"),
             MockResponse.Http(204)
         },
         {
             MockRequest.Delete("/relationship/78"),
             MockResponse.Http(204)
         },
         {
             MockRequest.Delete("/node/456"),
             MockResponse.Http(204)
         }
     })
     {
         var graphClient = testHarness.CreateAndConnectGraphClient();
         graphClient.Delete(456, DeleteMode.NodeAndRelationships);
     }
 }
        public void RecordMatcherThrowsExceptionsWithDetails()
        {
            var matcher = new RecordMatcher(new RecordedTestSanitizer());

            MockRequest mockRequest = new MockRequest
            {
                Method = RequestMethod.Head
            };

            mockRequest.Uri.Reset(new Uri("http://localhost"));
            mockRequest.Headers.Add("Some-Header", "Random value");
            mockRequest.Headers.Add("Some-Other-Header", "V");

            RecordEntry[] entries = new[]
            {
                new RecordEntry()
                {
                    RequestUri    = "http://remote-host",
                    RequestMethod = RequestMethod.Put,
                    Request       =
                    {
                        Headers =
                        {
                            { "Some-Header",  new[] { "Non-Random value" } },
                            { "Extra-Header", new[] { "Extra-Value"      } }
                        }
                    }
                }
            };

            InvalidOperationException exception = Assert.Throws <InvalidOperationException>(() => matcher.FindMatch(mockRequest, entries));

            Assert.AreEqual(
                "Unable to find a record for the request HEAD http://localhost/" + Environment.NewLine +
                "Method doesn't match, request <HEAD> record <PUT>" + Environment.NewLine +
                "Uri doesn't match:" + Environment.NewLine +
                "    request <http://localhost/>" + Environment.NewLine +
                "    record  <http://remote-host>" + Environment.NewLine +
                "Header differences:" + Environment.NewLine +
                "    <Some-Header> values differ, request <Random value>, record <Non-Random value>" + Environment.NewLine +
                "    <Some-Other-Header> is absent in record, value <V>" + Environment.NewLine +
                "    <Extra-Header> is absent in request, value <Extra-Value>" + Environment.NewLine,
                exception.Message);
        }
예제 #21
0
        public async Task Set()
        {
            var response = new MockResponse(200);

            response.SetContent(SerializationHelpers.Serialize(s_testSetting, SerializeSetting));

            var mockTransport           = new MockTransport(response);
            ConfigurationClient service = CreateTestService(mockTransport);

            ConfigurationSetting setting = await service.SetAsync(s_testSetting);

            MockRequest request = mockTransport.SingleRequest;

            AssertRequestCommon(request);
            Assert.AreEqual(RequestMethod.Put, request.Method);
            Assert.AreEqual("https://contoso.appconfig.io/kv/test_key?label=test_label", request.UriBuilder.ToString());
            AssertContent(SerializationHelpers.Serialize(s_testSetting, SerializeRequestSetting), request);
            Assert.AreEqual(s_testSetting, setting);
        }
        public async Task ShouldBeNeo4jIfNotSet()
        {
            var queryRequest = MockRequest.PostJson("/db/neo4j/tx/commit",
                                                    "{'statements': [{'statement': 'MATCH n\r\nRETURN count(n)', 'resultDataContents':[], 'parameters': {}}]}");

            using (var testHarness = new RestTestHarness(false, "http://foo:7474")
            {
                { queryRequest, EmptyOKResponse }
            })
            {
                var client = await testHarness.CreateAndConnectGraphClient(RestTestHarness.Neo4jVersion.Neo40);

                // dummy query to generate request
                await client.Cypher
                .Match("n")
                .Return(n => n.Count())
                .ExecuteWithoutResultsAsync().ConfigureAwait(false);
            }
        }
예제 #23
0
        public async Task SendsCommandWithCustomHeaders()
        {
            const string queryText = "MATCH n SET n.Value = 'value'";
            const int    expectedMaxExecutionTime = 100;
            const string headerName    = "MyTestHeader";
            const string headerValue   = "myTestHeaderValue";
            var          customHeaders = new NameValueCollection();

            customHeaders.Add(headerName, headerValue);

            var cypherQuery         = new CypherQuery(queryText, new Dictionary <string, object>(), CypherResultMode.Set, CypherResultFormat.DependsOnEnvironment, "neo4j", maxExecutionTime: expectedMaxExecutionTime, customHeaders: customHeaders);
            var transactionApiQuery = new CypherStatementList {
                new CypherTransactionStatement(cypherQuery)
            };

            using (var testHarness = new RestTestHarness
            {
                {
                    MockRequest.Get(""),
                    MockResponse.NeoRoot20()
                },
                {
                    MockRequest.PostObjectAsJson("/transaction/commit", transactionApiQuery),
                    MockResponse.Http((int)HttpStatusCode.OK)
                }
            })
            {
                var httpClient  = testHarness.GenerateHttpClient(testHarness.BaseUri);
                var graphClient = new GraphClient(new Uri(testHarness.BaseUri), httpClient);
                await graphClient.ConnectAsync();

                httpClient.ClearReceivedCalls();
                await((IRawGraphClient)graphClient).ExecuteCypherAsync(cypherQuery);

                var call                   = httpClient.ReceivedCalls().Single();
                var requestMessage         = (HttpRequestMessage)call.GetArguments()[0];
                var maxExecutionTimeHeader = requestMessage.Headers.Single(h => h.Key == "max-execution-time");
                Assert.Equal(expectedMaxExecutionTime.ToString(CultureInfo.InvariantCulture), maxExecutionTimeHeader.Value.Single());
                var customHeader = requestMessage.Headers.Single(h => h.Key == headerName);
                Assert.NotNull(customHeader);
                Assert.Equal(headerValue, customHeader.Value.Single());
            }
        }
        public void ShouldReindexRelationshipWithIndexEntryContainingSpace()
        {
            //Arrange
            var indexEntries = new List <IndexEntry>
            {
                new IndexEntry
                {
                    Name      = "my_relationships",
                    KeyValues = new Dictionary <string, object>
                    {
                        { "BarKey", "the_value with space" }
                    },
                }
            };

            using (var testHarness = new RestTestHarness
            {
                {
                    MockRequest.PostObjectAsJson("/index/relationship/my_relationships",
                                                 new
                    {
                        key = "BarKey",
                        value = "the_value with space",
                        uri = "http://foo/db/data/relationship/1234"
                    }),
                    MockResponse.Json(HttpStatusCode.Created,
                                      @"Location: http://foo/db/data/index/relationship/my_relationships/BarKey/the_value%20with%20space/1234")
                },
                {
                    MockRequest.Delete("/index/relationship/my_relationships/1234"),
                    MockResponse.Http((int)HttpStatusCode.NoContent)
                }
            })
            {
                var graphClient = testHarness.CreateAndConnectGraphClient();

                //Act
                var relReference = new RelationshipReference(1234);
                graphClient.ReIndex(relReference, indexEntries);

                // Assert
            }
        }
 public async Task ThrowsArgumentExceptionOnBadRequest()
 {
     try
     {
         MockResponse response = new MockResponse((int)HttpStatusCode.BadRequest);
         var          request  = new MockRequest()
         {
             Method = RequestMethod.Put
         };
         await _requestResponse.ThrowIfRequestFailedAsync(request, response);
     }
     catch (ArgumentException ex)
     {
         var inner = (RequestFailedException)ex.InnerException;
         Assert.AreEqual((int)HttpStatusCode.BadRequest, inner.Status);
         return;
     }
     Assert.Fail("No exception!");
 }
예제 #26
0
        public async Task DeserializeResultsFromTransaction()
        {
            var initTransactionRequest     = MockRequest.PostJson("/transaction", @"{
                'statements': [{'statement': 'MATCH n\r\nRETURN count(n)', 'resultDataContents':[], 'parameters': {}}]}");
            var deserializationRequest     = MockRequest.PostJson("/transaction/1", @"{
                'statements': [{'statement': 'MATCH n\r\nRETURN count(n)', 'resultDataContents':[], 'parameters': {}}]}");
            var rollbackTransactionRequest = MockRequest.Delete("/transaction/1");

            using (var testHarness = new RestTestHarness
            {
                {
                    initTransactionRequest,
                    MockResponse.Json(201, TransactionRestResponseHelper.GenerateInitTransactionResponse(1), "http://foo/db/data/transaction/1")
                },
                {
                    deserializationRequest,
                    MockResponse.Json(200, @"{'results':[{'columns': ['count(n)'], 'data': [{'row': [0]}]}]}")
                },
                {
                    rollbackTransactionRequest, MockResponse.Json(200, @"{'results':[], 'errors':[] }")
                }
            })
            {
                var client = await testHarness.CreateAndConnectTransactionalGraphClient();

                using (var transaction = client.BeginTransaction())
                {
                    // dummy query to generate request
                    await client.Cypher
                    .Match("n")
                    .Return(n => n.Count())
                    .ExecuteWithoutResultsAsync();

                    // this query will hit the deserializer
                    var count = await client.Cypher
                                .Match("n")
                                .Return(n => n.Count())
                                .ResultsAsync;

                    Assert.Equal(count.First(), 0);
                }
            }
        }
예제 #27
0
            internal static MockRequest FromHttpRequest(Uri uri, HttpListenerRequest request)
            {
                var mockRequest = new MockRequest()
                {
                    Method = request.HttpMethod,
                    Uri    = uri.OriginalString + request.Url.PathAndQuery
                };

                if (request.HasEntityBody)
                {
                    var contentType = GetContentType(request.Headers?.Get("Content-Type"));

                    if (IsTextContent(contentType))
                    {
                        var encoding = GetEncoding(contentType.CharSet);

                        using (var reader = new StreamReader(request.InputStream, encoding))
                        {
                            mockRequest.Content = reader.ReadToEnd();
                        }
                    }
                    else
                    {
                        using (BinaryReader reader = new BinaryReader(request.InputStream))
                        {
                            var bytes = reader.ReadBytes((int)request.ContentLength64);
                            mockRequest.Content = Convert.ToBase64String(bytes);
                        }
                    }
                }

                if (request.Headers != null && request.Headers.Count > 0)
                {
                    mockRequest.Headers = new NameValueCollection(request.Headers);

                    if (request.Headers["Host"] != null)
                    {
                        mockRequest.Headers["Host"] = uri.Authority;
                    }
                }

                return(mockRequest);
            }
예제 #28
0
        public void ShouldReindexNodeWithDateTimeOffsetIndexEntry()
        {
            //Arrange
            var indexEntries = new List <IndexEntry>
            {
                new IndexEntry
                {
                    Name      = "my_nodes",
                    KeyValues = new Dictionary <string, object>
                    {
                        { "FooKey", new DateTimeOffset(1000, new TimeSpan(0)) }
                    },
                }
            };

            using (var testHarness = new RestTestHarness
            {
                {
                    MockRequest.PostObjectAsJson("/index/node/my_nodes",
                                                 new
                    {
                        key = "FooKey",
                        value = "1000",
                        uri = "http://foo/db/data/node/123"
                    }),
                    MockResponse.Json(HttpStatusCode.Created,
                                      @"Location: http://foo/db/data/index/node/my_nodes/FooKey/someDateValue/123")
                },
                {
                    MockRequest.Delete("/index/node/my_nodes/123"),
                    MockResponse.Http((int)HttpStatusCode.NoContent)
                }
            })
            {
                var graphClient = testHarness.CreateAndConnectGraphClient();

                //Act
                graphClient.ReIndex((NodeReference)123, indexEntries);

                // Assert
            }
        }
예제 #29
0
            internal static MockRequest FromHttpRequest(Uri uri, HttpListenerRequest request)
            {
                var mockRequest = new MockRequest()
                {
                    Method = request.HttpMethod,
                    Uri    = uri.OriginalString + request.Url.PathAndQuery
                };

                if (request.HasEntityBody)
                {
                    var contentType = new ContentType(request.Headers?.Get("Content-Type") ?? "text/plain; charset=utf-8");
                    var encoding    = Encoding.GetEncoding(contentType.CharSet ?? "utf-8");

                    using (var stream = request.InputStream)
                        using (var reader = new StreamReader(stream, encoding))
                        {
                            var content = reader.ReadToEnd();

                            try
                            {
                                var jcontent = JToken.Parse(content);
                                mockRequest.Content = JsonConvert.SerializeObject(jcontent);
                            }
                            catch (JsonReaderException)
                            {
                                mockRequest.Content = content;
                            }
                        }
                }

                if (request.Headers != null && request.Headers.Count > 0)
                {
                    mockRequest.Headers = new NameValueCollection(request.Headers);

                    if (request.Headers["Host"] != null)
                    {
                        mockRequest.Headers["Host"] = uri.Authority;
                    }
                }

                return(mockRequest);
            }
        public async Task AuthorizationHeaderFormat()
        {
            var expectedSyntax = $"HMAC-SHA256 Credential={s_credential}&SignedHeaders=date;host;x-ms-content-sha256&Signature=(.+)";

            var response = new MockResponse(200);

            response.SetContent(SerializationHelpers.Serialize(s_testSetting, SerializeSetting));

            var mockTransport           = new MockTransport(response);
            ConfigurationClient service = CreateTestService(mockTransport);

            ConfigurationSetting setting = await service.AddAsync(s_testSetting);

            MockRequest request = mockTransport.SingleRequest;

            AssertRequestCommon(request);
            Assert.True(request.Headers.TryGetValue("Authorization", out var authHeader));

            Assert.True(Regex.IsMatch(authHeader, expectedSyntax));
        }
        public void UserAgentOverrideBenchmark()
        {
            var requestMock = new MockRequest();
            var message     = new HttpMessage(requestMock, new ResponseClassifier());

            if (!string.IsNullOrEmpty(SDKAgentOverride))
            {
                message.SetProperty("SDKUserAgent", SDKAgentOverride);
            }
            if (CustomHeaders.Length > 0)
            {
                foreach (var header in CustomHeaders)
                {
                    requestMock.Headers.Add(HttpHeader.Names.UserAgent, header);
                }
            }
            var policy = new MgmtTelemetryPolicy(message, ClientOptions.Default);

            policy.OnSendingRequest(message);
        }
예제 #32
0
        public void RecordMatcherThrowsExceptionsWhenNoRecordsLeft()
        {
            var matcher = new RecordMatcher(new RecordedTestSanitizer());

            MockRequest mockRequest = new MockRequest();

            mockRequest.Method         = RequestMethod.Head;
            mockRequest.UriBuilder.Uri = new Uri("http://localhost");
            mockRequest.Headers.Add("Some-Header", "Random value");
            mockRequest.Headers.Add("Some-Other-Header", "V");

            RecordEntry[] entries = {};

            InvalidOperationException exception = Assert.Throws <InvalidOperationException>(() => matcher.FindMatch(mockRequest, entries));

            Assert.AreEqual(
                "Unable to find a record for the request HEAD http://localhost/" + Environment.NewLine +
                "No records to match." + Environment.NewLine,
                exception.Message);
        }
        public async Task RequestHasSpecificApiVersion()
        {
            var response = new MockResponse(200);

            response.SetContent(SerializationHelpers.Serialize(s_testSetting, SerializeSetting));

            var mockTransport = new MockTransport(response);
            var options       = new ConfigurationClientOptions(ConfigurationClientOptions.ServiceVersion.V1_0);

            options.Diagnostics.ApplicationId = "test_application";
            options.Transport = mockTransport;

            ConfigurationClient client = CreateClient <ConfigurationClient>(s_connectionString, options);

            ConfigurationSetting setting = await client.AddAsync(s_testSetting);

            MockRequest request = mockTransport.SingleRequest;

            StringAssert.Contains("api-version=1.0", request.UriBuilder.Uri.ToString());
        }
예제 #34
0
        public void GivenSortDirectionOnLastLoginTime_WhenExecuteSortSelector_ThenReturnLastLoginTimeInMinutes()
        {
            MockRequest.Expect(m => m["iSortCol_0"]).Return("3");
            MockRequest.Expect(m => m["sSortDir_0"]).Return("asc");
            UserClientDataTable target = new UserClientDataTable(MockRequest, SecurityConfiguration);
            User user = new User
            {
                LoginEvents = new List <LoginEvent>
                {
                    new LoginEvent {
                        CreateTime = DateTime.Now
                    }
                }
            };
            string expected = ((int)new TimeSpan(user.LastLoginTime.Value.Ticks).TotalMinutes).ToString();

            var actual = target.SortSelector.Compile().Invoke(user);

            Assert.AreEqual(expected, actual);
        }
        public void OnSendingRequest_PutRequest_ShouldIgnore()
        {
            MockRequest request = CreateMockRequest(MockPrimaryUri);

            request.Method = RequestMethod.Put;
            var message = new HttpMessage(
                request,
                new StorageResponseClassifier()
            {
                SecondaryStorageUri = MockSecondaryUri
            });

            var policy = new GeoRedundantReadPolicy(MockSecondaryUri);

            policy.OnSendingRequest(message);

            Assert.AreEqual(MockPrimaryUri.Host, message.Request.Uri.Host);
            Assert.IsFalse(message.TryGetProperty(Constants.GeoRedundantRead.AlternateHostKey, out object val) &&
                           (string)val == MockSecondaryUri.Host);
        }
예제 #36
0
        public async Task DataSourceCredentialEntitySendsSecretDuringCreation(DataSourceCredentialEntity credential, string expectedSubstring)
        {
            MockResponse createResponse = new MockResponse(201);

            createResponse.AddHeader(new HttpHeader("Location", $"https://fakeresource.cognitiveservices.azure.com/metricsadvisor/v1.0/credentials/{FakeGuid}"));

            MockResponse getResponse = new MockResponse(200);

            getResponse.SetContent(DataSourceCredentialEntityResponseContent);

            MockTransport mockTransport = new MockTransport(createResponse, getResponse);
            MetricsAdvisorAdministrationClient adminClient = CreateInstrumentedAdministrationClient(mockTransport);

            await adminClient.CreateDataSourceCredentialAsync(credential);

            MockRequest request = mockTransport.Requests.First();
            string      content = ReadContent(request);

            Assert.That(content, Contains.Substring(expectedSubstring));
        }
예제 #37
0
        public void Should_Not_Squeeze_Slashes()
        {
            var mapping = new KeyValuePair <string, object> [2];

            mapping[0] = GetMapForRootRouteTest("/", "root");
            mapping[1] = GetMapForRootRouteTest("/foo", "foo");

            var mappingDictionary = mapping.ToDictionary(pair => pair.Key, pair => pair.Value);

            var map = new UrlMap(mappingDictionary);

            var mock = new MockRequest(map);

            var res = mock.Get("/http://example.org/bar");

            Assert.AreEqual(200, res.Status);
            Assert.AreEqual("root", res["X-Position"]);
            Assert.AreEqual("/http://example.org/bar", res["X-PathInfo"]);
            Assert.AreEqual(string.Empty, res["X-ScriptName"]);
        }
예제 #38
0
        public void LoadsSingleNullGuidCookieUsingPropertyName()
        {
            var request = new MockRequest();
            var context = new MockContext {
                Request = request
            };

            var runner = new HandlerRunnerBuilder(typeof(SingleNullableGuidCookieHandler), "GET").BuildRunner();
            var target = new SingleNullableGuidCookieHandler();

            try
            {
                runner(target, context);
            }
            catch (ArgumentNullException)
            {
                // Content-type handling is going to throw an exception here.
            }
            Assert.False(target.Test.HasValue);
        }
        public async Task VerifyAppServiceMsiRequestWithClientIdMockAsync()
        {
            using (new TestEnvVar("MSI_ENDPOINT", "https://mock.msi.endpoint/"))
                using (new TestEnvVar("MSI_SECRET", "mock-msi-secret"))
                {
                    var response = new MockResponse(200);

                    var expectedToken = "mock-msi-access-token";

                    response.SetContent($"{{ \"access_token\": \"{expectedToken}\", \"expires_on\": \"{DateTimeOffset.UtcNow.ToString()}\" }}");

                    var mockTransport = new MockTransport(response);

                    var options = new AzureCredentialOptions()
                    {
                        Transport = mockTransport
                    };

                    ManagedIdentityClient client = InstrumentClient(new ManagedIdentityClient(options));

                    AccessToken actualToken = await client.AuthenticateAsync(MockScopes.Default, "mock-client-id");

                    Assert.AreEqual(expectedToken, actualToken.Token);

                    MockRequest request = mockTransport.Requests[0];

                    Assert.IsTrue(request.Uri.ToString().StartsWith("https://mock.msi.endpoint/"));

                    string query = request.Uri.Query;

                    Assert.IsTrue(query.Contains("api-version=2017-09-01"));

                    Assert.IsTrue(query.Contains($"resource={Uri.EscapeDataString(ScopeUtilities.ScopesToResource(MockScopes.Default))}"));

                    Assert.IsTrue(query.Contains($"client_id=mock-client-id"));

                    Assert.IsTrue(request.Headers.TryGetValue("secret", out string actSecretValue));

                    Assert.AreEqual("mock-msi-secret", actSecretValue);
                }
        }
예제 #40
0
        public void ShouldReplaceNodeWithIndexEntries()
        {
            var newData = new TestNode {
                Foo = "foo", Bar = "bar", Baz = "baz"
            };

            using (var testHarness = new RestTestHarness
            {
                {
                    MockRequest.PutObjectAsJson("/node/456/properties", newData),
                    MockResponse.Http((int)HttpStatusCode.NoContent)
                },
                {
                    MockRequest.Delete("/index/node/foo/456"),
                    MockResponse.Http((int)HttpStatusCode.NoContent)
                },
                {
                    MockRequest.PostObjectAsJson("/index/node/foo", new { key = "foo", value = "bar", uri = "http://foo/db/data/node/456" }),
                    MockResponse.Json(HttpStatusCode.Created, "Location: http://foo/db/data/index/node/foo/bar/456")
                }
            })
            {
                var graphClient = testHarness.CreateAndConnectGraphClient();

                // Act
                var pocoReference = new NodeReference <TestNode>(456);
                graphClient.Update(
                    pocoReference,
                    newData,
                    new []
                {
                    new IndexEntry
                    {
                        Name      = "foo",
                        KeyValues = new Dictionary <string, object> {
                            { "foo", "bar" }
                        },
                    }
                });
            }
        }
예제 #41
0
        public void Should_Set_Last_Modified_Header()
        {
            var response = new MockRequest(new File(_docRoot)).Get("/cgi/test");

            var path = Path.Combine(_docRoot, @"cgi\test");
            var fileInfo = new FileInfo(path);

            Assert.AreEqual(200, response.Status);
            Assert.AreEqual(fileInfo.LastWriteTimeUtc.ToHttpDateString(), response["Last-Modified"]);
        }
예제 #42
0
        public void Should_Not_Allow_Directory_Traversal()
        {
            var response = new MockRequest(new File(_docRoot)).Get("/cgi/../test");

            Assert.AreEqual(403, response.Status);
        }
예제 #43
0
        public void Should_Not_Allow_Directory_Traversal_With_Encoded_Periods()
        {
            var response = new MockRequest(new File(_docRoot)).Get("/%2E%2E/README");

            Assert.AreEqual(403, response.Status);
        }
예제 #44
0
        public void Should_Return_404_If_Cannot_Find_File()
        {
            var response = new MockRequest(new File(_docRoot)).Get("/cgi/blubb");

            Assert.AreEqual(404, response.Status);
        }
예제 #45
0
        public void Should_Serve_Files()
        {
            var response = new MockRequest(new File(_docRoot)).Get("/cgi/test");

            Assert.AreEqual(200, response.Status);
        }
예제 #46
0
        public void Should_Serve_Files_With_Url_Encoded_Filenames()
        {
            var response = new MockRequest(new File(_docRoot)).Get("/cgi/%74%65%73%74");

            Assert.AreEqual(200, response.Status);
        }
 public void Reset()
 {
     Request = new MockRequest();
     ConfigureResponseStream(data);
 }
 public void ToAbsoluteUrl_can_handle_tilde_with_root_application_path()
 {
     var r = new MockRequest(new Uri("http://ascendrewards.com/a1/dashboard/files"), "/");
     Assert.That("~/a/b/c".ToAbsoluteUrl(r).ToString(), Is.EqualTo("http://ascendrewards.com/a/b/c"));
 } 
예제 #49
0
        public void Should_Detect_SystemCallErrors()
        {
            var response = new MockRequest(new File(_docRoot)).Get("/cgi");

            Assert.AreEqual(404, response.Status);
        }
 public void ToAbsoluteUrl_can_handle_absolute_https_url()
 {
     var r = new MockRequest(new Uri("http://ascendrewards.com/a1/dashboard/files"), "/a1");
     Assert.That("https://ascendrewards.com/a1/a/b/c".ToAbsoluteUrl(r).ToString(), Is.EqualTo("https://ascendrewards.com/a1/a/b/c"));
 }
        public void It_Passes_Query_String_Data_Into_Action()
        {
            var response = new MockRequest(new TestApplication()).Get("/data?testData=horticulture");

            Assert.AreEqual("horticulture", response.Body.ToString());
        }
        public void It_Passes_Route_Parameters_As_Data()
        {
            var response = new MockRequest(new TestApplication()).Get("/params/test");

            Assert.AreEqual("test", response.Body.ToString());
        }
예제 #53
0
 public MockRequest Mock(Uri uri, string content)
 {
     return responses[uri] = new MockRequest(uri, content);
 }
예제 #54
0
 public void Init()
 {
     _mRequest = new MockRequest() {Method = "Foo", Resource = "Bar"};
     _director = new FourOhFourResponse();
 }
예제 #55
0
 public void TestSetup()
 {
     _request = new MockRequest(ProtectedApp);
 }