Esempio n. 1
0
        /// <summary>
        /// Initializes a new instance of the <see cref="Request"/> class.
        /// </summary>
        /// <param name="method">The HTTP data transfer method used by the client.</param>
        /// <param name="url">The <see cref="Url"/> of the requested resource</param>
        /// <param name="headers">The headers that was passed in by the client.</param>
        /// <param name="body">The <see cref="Stream"/> that represents the incoming HTTP body.</param>
        /// <param name="ip">The client's IP address</param>
        /// <param name="certificate">The client's certificate when present.</param>
        /// <param name="protocolVersion">The HTTP protocol version.</param>
        public Request(string method,
            Url url,
            RequestStream body = null,
            IDictionary<string, IEnumerable<string>> headers = null,
            string ip = null,
            byte[] certificate = null,
            string protocolVersion = null)
        {
            if (String.IsNullOrEmpty(method))
            {
                throw new ArgumentOutOfRangeException("method");
            }

            if (url == null)
            {
                throw new ArgumentNullException("url");
            }

            if (url.Path == null)
            {
                throw new ArgumentNullException("url.Path");
            }

            if (String.IsNullOrEmpty(url.Scheme))
            {
                throw new ArgumentOutOfRangeException("url.Scheme");
            }

            this.UserHostAddress = ip;

            this.Url = url;

            this.Method = method;

            this.Query = url.Query.AsQueryDictionary();

            this.Body = body ?? RequestStream.FromStream(new MemoryStream());

            this.Headers = new RequestHeaders(headers ?? new Dictionary<string, IEnumerable<string>>());

            this.Session = new NullSessionProvider();

            if (certificate != null && certificate.Length != 0)
            {
                this.ClientCertificate = new X509Certificate2(certificate);
            }

            this.ProtocolVersion = protocolVersion ?? string.Empty;

            if (String.IsNullOrEmpty(this.Url.Path))
            {
                this.Url.Path = "/";
            }

            this.ParseFormData();
            this.RewriteMethod();
        }
        public string ProcessData(RequestStream requestBody)
        {
            var length = int.Parse(requestBody.Length.ToString());
            var bytes = new byte[length];
            requestBody.Read(bytes, 0, length);
            var json = System.Text.Encoding.UTF8.GetString(bytes);
            // Process the status
            var board = JsonConvert.DeserializeObject<BoardStatus>(json);

            if (board.RoundNumber == 0) _commander.Reset();

            _commander.GetBoardStatus(board);

            // Create commands to do
            return JsonConvert.SerializeObject(_commander.GiveCommands());
        }
        public void Handle_WithAPostRequestToPactAndPactDirIsDifferentFromDefault_NewPactFileIsSavedWithInteractionsInTheSpecifiedPath()
        {
            var pactDetails = new PactDetails
            {
                Consumer = new Pacticipant { Name = "Consumer" },
                Provider = new Pacticipant { Name = "Provider" }
            };

            var interactions = new List<ProviderServiceInteraction>
            {
                new ProviderServiceInteraction
                {
                    Description = "My description",
                    Request = new ProviderServiceRequest
                    {
                        Method = HttpVerb.Get,
                        Path = "/test"
                    },
                    Response = new ProviderServiceResponse
                    {
                        Status = (int)HttpStatusCode.NoContent
                    }
                }
            };

            var pactFile = new ProviderServicePactFile
            {
                Provider = pactDetails.Provider,
                Consumer = pactDetails.Consumer,
                Interactions = interactions
            };

            var config = new PactConfig { PactDir = @"C:\temp" };
            var filePath = Path.Combine(config.PactDir, pactDetails.GeneratePactFileName());

            var pactFileJson = JsonConvert.SerializeObject(pactFile, JsonConfig.PactFileSerializerSettings);
            var pactDetailsJson = JsonConvert.SerializeObject(pactDetails, JsonConfig.ApiSerializerSettings);

            var jsonStream = new MemoryStream(Encoding.UTF8.GetBytes(pactDetailsJson));

            var requestStream = new RequestStream(jsonStream, jsonStream.Length, true);
            var context = new NancyContext
            {
                Request = new Request("POST", new Url("http://localhost/pact"), requestStream)
            };

            var handler = GetSubject(config);

            _mockProviderRepository.Interactions.Returns(interactions);

            var response = handler.Handle(context);

            _mockFileSystem.File.Received(1).WriteAllText(filePath, pactFileJson);
        }
        public void Handle_WithAPostRequestToPactAndNoInteractionsHaveBeenRegistered_NewPactFileIsSavedWithNoInteractions()
        {
            var pactDetails = new PactDetails
            {
                Consumer = new Pacticipant { Name = "Consumer" },
                Provider = new Pacticipant { Name = "Provider" }
            };

            var pactFile = new ProviderServicePactFile
            {
                Provider = pactDetails.Provider,
                Consumer = pactDetails.Consumer,
                Interactions = new ProviderServiceInteraction[0]
            };

            var pactFileJson = JsonConvert.SerializeObject(pactFile, JsonConfig.PactFileSerializerSettings);
            var pactDetailsJson = JsonConvert.SerializeObject(pactDetails, JsonConfig.ApiSerializerSettings);

            var jsonStream = new MemoryStream(Encoding.UTF8.GetBytes(pactDetailsJson));

            var requestStream = new RequestStream(jsonStream, jsonStream.Length, true);
            var context = new NancyContext
            {
                Request = new Request("POST", new Url("http://localhost/pact"), requestStream)
            };

            var handler = GetSubject();

            handler.Handle(context);

            _mockFileSystem.File.Received(1).WriteAllText(Path.Combine(Constants.DefaultPactDir, pactDetails.GeneratePactFileName()), pactFileJson);
        }
        public void Handle_WithAPostRequestToPactAndInteractionsHaveBeenRegistered_ReturnsResponseWithPactFileJson()
        {
            var pactDetails = new PactDetails
            {
                Consumer = new Pacticipant { Name = "Consumer" },
                Provider = new Pacticipant { Name = "Provider" }
            };

            var interactions = new List<ProviderServiceInteraction>
            {
                new ProviderServiceInteraction
                {
                    Description = "My description",
                    Request = new ProviderServiceRequest
                    {
                        Method = HttpVerb.Get,
                        Path = "/test"
                    },
                    Response = new ProviderServiceResponse
                    {
                        Status = (int)HttpStatusCode.NoContent
                    }
                }
            };

            var pactFile = new ProviderServicePactFile
            {
                Provider = pactDetails.Provider,
                Consumer = pactDetails.Consumer,
                Interactions = interactions
            };

            var pactFileJson = JsonConvert.SerializeObject(pactFile, JsonConfig.PactFileSerializerSettings);
            var pactDetailsJson = JsonConvert.SerializeObject(pactDetails, JsonConfig.ApiSerializerSettings);

            var jsonStream = new MemoryStream(Encoding.UTF8.GetBytes(pactDetailsJson));

            var requestStream = new RequestStream(jsonStream, jsonStream.Length, true);
            var context = new NancyContext
            {
                Request = new Request("POST", new Url("http://localhost/pact"), requestStream)
            };

            var handler = GetSubject();

            _mockProviderRepository.Interactions.Returns(interactions);

            var response = handler.Handle(context);

            Assert.Equal("application/json", response.Headers["Content-Type"]);
            Assert.Equal(pactFileJson, ReadResponseContent(response.Contents));
        }
        public void Handle_WithAPostRequestToPactAndDirectoryDoesNotExist_DirectoryIsCreatedAndNewPactFileIsSavedWithInteractions()
        {
            var pactDetails = new PactDetails
            {
                Consumer = new Pacticipant { Name = "Consumer" },
                Provider = new Pacticipant { Name = "Provider" }
            };

            var interactions = new List<ProviderServiceInteraction>
            {
                new ProviderServiceInteraction
                {
                    Description = "My description",
                    Request = new ProviderServiceRequest
                    {
                        Method = HttpVerb.Get,
                        Path = "/test"
                    },
                    Response = new ProviderServiceResponse
                    {
                        Status = (int)HttpStatusCode.NoContent
                    }
                }
            };

            var pactFile = new ProviderServicePactFile
            {
                Provider = pactDetails.Provider,
                Consumer = pactDetails.Consumer,
                Interactions = interactions
            };

            var pactFileJson = JsonConvert.SerializeObject(pactFile, JsonConfig.PactFileSerializerSettings);
            var pactDetailsJson = JsonConvert.SerializeObject(pactDetails, JsonConfig.ApiSerializerSettings);

            var jsonStream = new MemoryStream(Encoding.UTF8.GetBytes(pactDetailsJson));

            var requestStream = new RequestStream(jsonStream, jsonStream.Length, true);
            var context = new NancyContext
            {
                Request = new Request("POST", new Url("http://localhost/pact"), requestStream)
            };

            var filePath = Path.Combine(Constants.DefaultPactDir, pactDetails.GeneratePactFileName());

            var handler = GetSubject();

            _mockProviderRepository.Interactions.Returns(interactions);

            var writeAllTextCount = 0;
            _mockFileSystem.File
                .When(x => x.WriteAllText(filePath, pactFileJson))
                .Do(x =>
                {
                    writeAllTextCount++;
                    if (writeAllTextCount == 1)
                    {
                        throw new DirectoryNotFoundException("It doesn't exist");
                    }
                });

            handler.Handle(context);

            _mockFileSystem.File.Received(2).WriteAllText(filePath, pactFileJson);
        }
        public void Handle_WithAPostRequestToInteractions_ReturnsOkResponse()
        {
            var interaction = new ProviderServiceInteraction
            {
                Description = "My description",
                Request = new ProviderServiceRequest
                {
                    Method = HttpVerb.Get,
                    Path = "/test"
                },
                Response = new ProviderServiceResponse
                {
                    Status = (int)HttpStatusCode.NoContent
                }
            };
            var interactionJson = interaction.AsJsonString();

            var jsonStream = new MemoryStream(Encoding.UTF8.GetBytes(interactionJson));

            var requestStream = new RequestStream(jsonStream, jsonStream.Length, true);
            var context = new NancyContext
            {
                Request = new Request("POST", new Url("http://localhost/interactions"), requestStream)
            };

            var handler = GetSubject();

            var response = handler.Handle(context);

            Assert.Equal(HttpStatusCode.OK, response.StatusCode);
        }
        public void Handle_WithAPostRequestToInteractions_AddInteractionIsCalledOnTheMockProviderRepository()
        {
            var interaction = new ProviderServiceInteraction
            {
                Description = "My description",
                Request = new ProviderServiceRequest
                {
                    Method = HttpVerb.Get,
                    Path = "/test"
                },
                Response = new ProviderServiceResponse
                {
                    Status = (int)HttpStatusCode.NoContent
                }
            };
            var interactionJson = interaction.AsJsonString();

            var jsonStream = new MemoryStream(Encoding.UTF8.GetBytes(interactionJson));

            var requestStream = new RequestStream(jsonStream, jsonStream.Length, true);
            var context = new NancyContext
            {
                Request = new Request("POST", new Url("http://localhost/interactions"), requestStream)
            };

            var handler = GetSubject();

            handler.Handle(context);

            _mockProviderRepository.Received(1).AddInteraction(Arg.Is<ProviderServiceInteraction>(x => x.AsJsonString() == interactionJson));
        }
        private Request GetPreCannedRequest(IDictionary<string, IEnumerable<string>> headers = null, string content = null)
        {
            RequestStream requestStream = null;

            if (!String.IsNullOrEmpty(content))
            {
                var contentBytes = Encoding.UTF8.GetBytes(content);
                var stream = new MemoryStream(contentBytes);
                requestStream = new RequestStream(stream, contentBytes.Length, true);
            }

            var url = new Url
            {
                HostName = "localhost",
                Scheme = "http",
                Port = 1234,
                Path = "/events"
            };

            Request request;
            if (requestStream != null)
            {
                request = new Request("GET", url, headers: headers, body: requestStream);
            }
            else
            {
                request = new Request("GET", url, headers: headers);
            }

            return request;
        }
Esempio n. 10
0
 Request CreateRequest(string method, string host, string path, IDictionary<string, IEnumerable<string>> headers, RequestStream body,
                       string scheme, string query = null, string ip = null)
 {
     return new Request(method, new Url {Path = path, Scheme = scheme, HostName = host, Query = query ?? String.Empty}, body, headers, ip);
 }
Esempio n. 11
0
 public Message(RequestStream requestStream)
 {
     Body = Encoding.UTF8.GetString(requestStream.ReadToEnd());
 }
Esempio n. 12
0
 public FakeRequest(string method, string path, IDictionary<string, IEnumerable<string>> headers, RequestStream body, string protocol, string query, string userHostAddress = null)
     : base(method, new Url { Path = path, Query = query, Scheme = protocol }, body, headers, ip: userHostAddress)
 {
 }