Beispiel #1
0
        public void ShouldReadResourceLine()
        {
            WebSocketHttpRequest request = RequestParser.Parse(ValidRequestArray());

            Assert.AreEqual("GET", request.Method);
            Assert.AreEqual("/demo", request.Path);
        }
        public async Task ParseLogoutRequest_post_binding()
        {
            //ARRANGE
            var form = await SamlPostRequestProviderMock.BuildLogoutRequestPostForm();

            Func <Type, IMetadataHandler> metadataHandlerFactory = t => new MetadataEntitityDescriptorHandler();
            var xmlSerialiser    = new XMLSerialiser();
            var compressor       = new DeflateCompressor();
            var encoder          = new MessageEncoding(compressor);
            var logger           = new LogProviderMock();
            var serialiser       = new RequestSerialiser(xmlSerialiser, encoder, logger) as IRequestSerialiser;
            var certManager      = new CertificateManager(logger);
            var signatureManager = new XmlSignatureManager();
            Func <IEnumerable <RequestValidationRule> > rulesResolver = () => new[] { new SignatureValidRule(logger, certManager, signatureManager) };
            var requestValidator                  = new Federation.Protocols.Request.Validation.RequestValidator(logger, new RuleFactory(rulesResolver));
            var configurationRetrieverMock        = new ConfigurationRetrieverMock();
            var federationPartyContextBuilderMock = new FederationPartyContextBuilderMock();
            var configurationManger               = new ConfigurationManager <MetadataBase>(federationPartyContextBuilderMock, configurationRetrieverMock);
            var requestParser = new RequestParser(metadataHandlerFactory, t => new LogoutRequestParser(serialiser, logger),
                                                  configurationManger, logger, requestValidator);
            var postBindingDecoder = new PostBindingDecoder(logger);
            var message            = await postBindingDecoder.Decode(form.HiddenControls.ToDictionary(k => k.Key, v => v.Value));

            var context = new SamlInboundContext
            {
                Message            = message,
                DescriptorResolver = m => metadataHandlerFactory(typeof(object)).GetIdentityProviderSingleSignOnDescriptor(m).Single().Roles.Single()
            };
            //ACT
            var result = await requestParser.Parse(context);

            //ASSERT
            Assert.IsTrue(result.IsValidated);
            Assert.IsInstanceOf <LogoutRequest>(result.SamlRequest);
        }
        public void GetRequest_ShouldReturnRequest_WithMethodGet()
        {
            // 1. Arrange
            RequestParser parser            = new RequestParser();
            Method        expectedMethod    = Method.Get;
            string        expectedPath      = "jen/dva";
            var           expectedQuery     = QueryCollection.Empty;
            string        expectedBody      = string.Empty;
            string        expectedFetchMode = "navigate";
            string        requestString     = @"GET /jen/dva?param=value1&param=value2 HTTP/1.1
Host: localhost:13000
Connection: keep-alive
Cache-Control: max-age=0
Upgrade-Insecure-Requests: 1
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.132 Safari/537.36
Sec-Fetch-Mode: navigate
Sec-Fetch-User: ?1
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3
Sec-Fetch-Site: none
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.9,mk;q=0.8,sr;q=0.7,hr;q=0.6,bs;q=0.5
Cookie: _ga=GA1.1.405632844.1539592429; x-access-token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJuYW1lIjoiZGpvdmFub3ZAdW5kZXJ0b25lLmNvbSIsImlkIjoxMDAwMDAwMDAwLCJlbWFpbCI6ImRqb3Zhbm92QHVuZGVydG9uZS5jb20iLCJpYXQiOjE1NjYyMTMzMjMsImV4cCI6MTU2NjI5OTcyM30.xt_HboZPPzp_QIQfBaWKNmZC_7zBAS2mZiIAfm0pImE; uid=1000000000
";
            // 2. Act
            Request actual = parser.Parse(requestString);

            // 3. Assert
            Assert.AreEqual(expectedMethod, actual.Method);
            Assert.AreEqual(expectedPath, actual.Path);
            StringAssert.Equals(expectedQuery, actual.Query);
            Assert.AreEqual(expectedBody, actual.Body);
            Assert.AreEqual(expectedFetchMode, actual.Headers.GetHeader("Sec-Fetch-Mode"));
        }
Beispiel #4
0
        public void ShouldReadHeaders()
        {
            WebSocketHttpRequest request = RequestParser.Parse(ValidRequestArray());

            Assert.AreEqual("example.com", request.Headers ["Host"]);
            Assert.AreEqual("Upgrade", request.Headers ["Connection"]);
            Assert.AreEqual("12998 5 Y3 1  .P00", request.Headers ["Sec-WebSocket-Key2"]);
            Assert.AreEqual("http://example.com", request.Headers ["Origin"]);
        }
        public void SendPutTestFail()
        {
            string   input    = $"PUT {hostAddress} HTTP/1.1\n";
            Request  request  = RequestParser.Parse(input);
            IService service  = ServiceFactory.GetService(request.RequestType);
            var      response = service.Send(request);

            Assert.AreEqual("Sending request failed!", response.Result);
        }
Beispiel #6
0
        void ClientConnected(IAsyncResult ar)
        {
            server.BeginAcceptTcpClient(ClientConnected, null);

            TcpClient client;

            try {
                client = server.EndAcceptTcpClient(ar);
            }
            catch (ObjectDisposedException) {
                return;
            }
            catch (Exception e) {
                Logger.Error(this, "Error accepting tcp client", e);
                return;
            }

            HttpClient httpclient = new HttpClient(client);

            do
            {
                try {
                    HttpRequest request = parser.Parse(client.GetStream());
                    if (request == null)
                    {
                        break;
                    }

                    if (request.HasHeader("Connection"))
                    {
                        httpclient.KeepAlive = request.GetHeader("Connection").ToLower() == "keep-alive";
                    }

                    Request?.Invoke(httpclient, request);
                }
                catch (MissingHeaderException) {
                    break;
                }
                catch (IOException) {
                    break;
                }
                catch (Exception e) {
                    Logger.Error(this, "Error parsing request", e);
                    try {
                        httpclient.WriteStatus(500, "Internal Server Error");
                        httpclient.EndHeader();
                        client.Close();
                    }
                    catch (Exception ex) {
                        Logger.Error(this, "Error sending error response", ex);
                    }
                }
            }while(httpclient.KeepAlive && client.Connected);

            client.Close();
        }
Beispiel #7
0
        public void NoHeadersRequestShouldBeNull()
        {
            const string noHeadersNoBodyRequest =
                "GET /zing HTTP/1.1\r\n" +
                "\r\n" +
                "";
            var bytes = RequestArray(noHeadersNoBodyRequest);

            Assert.IsNull(RequestParser.Parse(bytes));
        }
Beispiel #8
0
        public void HeadersShouldBeCaseInsensitive()
        {
            WebSocketHttpRequest request = RequestParser.Parse(ValidRequestArray());

            Assert.IsTrue(request.Headers.ContainsKey("Sec-WebSocket-Protocol"));
            Assert.IsTrue(request.Headers.ContainsKey("sec-websocket-protocol"));
            Assert.IsTrue(request.Headers.ContainsKey("sec-WEBsocket-protoCOL"));
            Assert.IsTrue(request.Headers.ContainsKey("UPGRADE"));
            Assert.IsTrue(request.Headers.ContainsKey("CONNectiON"));
        }
Beispiel #9
0
        private void OnClientConnect(ISocket clientSocket)
        {
            if (clientSocket == null)
            {
                return; // socket closed
            }
            FleckLog.Debug(string.Format("Client connected from {0}:{1}", clientSocket.RemoteIpAddress, clientSocket.RemotePort.ToString()));
            ListenForClients();

            WebSocketConnection connection = null;

            connection = new WebSocketConnection(
                clientSocket,
                _config,
                bytes => RequestParser.Parse(bytes, _scheme),
                r => {
                try {
                    return(HandlerFactory.BuildHandler(
                               r, s => connection.OnMessage(s), connection.Close, b => connection.OnBinary(b),
                               b => connection.OnPing(b), b => connection.OnPong(b)
                               ));
                } catch (WebSocketException) {
                    const string responseMsg = "HTTP/1.1 200 OK\r\n"
                                               + "Date: {0}\r\n"
                                               + "Server: SharpChat\r\n"
                                               + "Content-Length: {1}\r\n"
                                               + "Content-Type: text/html; charset=utf-8\r\n"
                                               + "Connection: close\r\n"
                                               + "\r\n"
                                               + "{2}";
                    string responseBody = File.Exists(@"http-motd.txt") ? File.ReadAllText(@"http-motd.txt") : @"SharpChat";

                    clientSocket.Stream.Write(Encoding.UTF8.GetBytes(string.Format(
                                                                         responseMsg, DateTimeOffset.Now.ToString(@"r"), Encoding.UTF8.GetByteCount(responseBody), responseBody
                                                                         )));
                    clientSocket.Close();
                    return(null);
                }
            },
                s => SubProtocolNegotiator.Negotiate(SupportedSubProtocols, s));

            if (IsSecure)
            {
                FleckLog.Debug("Authenticating Secure Connection");
                clientSocket
                .Authenticate(Certificate,
                              EnabledSslProtocols,
                              connection.StartReceiving,
                              e => FleckLog.Warn("Failed to Authenticate", e));
            }
            else
            {
                connection.StartReceiving();
            }
        }
Beispiel #10
0
        private void saveButton_Click(object sender, EventArgs e)
        {
            Request request = RequestParser.Parse(requestTextBox.Text);

            if (request != null)
            {
                //simulating data source
                requestList.Add(request);
                requestGridView.Rows.Add(request.TypeIcon, request.TargetAddress, request.Id);
            }
        }
        private async void ParseHTTPHeaderButton_Click(object sender, RoutedEventArgs e)
        {
            string header = await MainWindow.inputDialog.ShowAsync(FindResource("label_HTTPHeaderInput") as string, true, TryFindResource("hint_HTTPHeader") as string);

            if (header != null)
            {
                string[] errors = RequestParser.Parse(Item, header);
                await MainWindow.dialog.ShowInfomationAsync(FindResource("label_headerError")
                                                            + Environment.NewLine + string.Join(Environment.NewLine, errors));

                Notify(nameof(Item));
            }
        }
Beispiel #12
0
        public void Parse_ShouldCallGetHttpRequestFactoryMethod_WhenCorrectParamsAreProvided()
        {
            const string input = "1 2 3";

            this._mockedFactory.Setup(f => f.GetHttpRequest("1", "2", "3"));

            var parser = new RequestParser(this._mockedFactory.Object);

            parser.Parse(input);

            this._mockedFactory.Verify(factory => factory.GetHttpRequest("1", "2", "3"),
                                       Times.Once());
        }
        public void SendPostTest()
        {
            string input = $"POST {hostAddress} HTTP/1.1\n" +
                           "Content-Type: application/x-www-form-urlencoded\n" +
                           "Content-Length: 32\n" +
                           "\n" +
                           "deneme=Deneme&deneme%20deneme=DenemeDeneme\n";
            Request  request  = RequestParser.Parse(input);
            IService service  = ServiceFactory.GetService(request.RequestType);
            var      response = service.Send(request);

            Assert.AreEqual("ok\n", response.Result);
        }
Beispiel #14
0
        private async void sendButton_Click(object sender, EventArgs e)
        {
            Request request = RequestParser.Parse(requestTextBox.Text);

            if (request != null)
            {
                IService service  = ServiceFactory.GetService(request.RequestType);
                var      response = await service.Send(request);

                responseTextBox.Text    = response;
                tabControl1.SelectedTab = tabResponse;
            }
        }
Beispiel #15
0
        public void PartialHeaderRequestShouldBeNull()
        {
            const string partialHeaderRequest =
                "GET /demo HTTP/1.1\r\n" +
                "Host: example.com\r\n" +
                "Connection: Upgrade\r\n" +
                "Sec-WebSocket-Key2: 12998 5 Y3 1  .P00\r\n" +
                "Sec-WebSocket-Protocol: sample\r\n" +
                "Upgrade: WebSocket\r\n" +
                "Sec-WebSoc"; //Cut off
            var bytes = RequestArray(partialHeaderRequest);

            Assert.IsNull(RequestParser.Parse(bytes));
        }
Beispiel #16
0
        public void SendGetTestFail()
        {
            string input = "GET http://denemeMetin.com HTTP/1.1\n" +
                           "Host: localhost:8000\n" +
                           "Connection: keep-alive\n" +
                           "Accept: text/html,application/xhtml+xml,application/xml?q=0.9,image/webp,*/*?q=0.8\n" +
                           "UserAgent: Mozilla/5.0 (Windows NT 10.0? WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.109 Safari/537.36\n" +
                           "AcceptEncoding: gzip, deflate\n" +
                           "AcceptLanguage: enUS, en?q=0.8\n";
            Request  request  = RequestParser.Parse(input);
            IService service  = ServiceFactory.GetService(request.RequestType);
            var      response = service.Send(request);

            Assert.AreEqual("Sending request failed!", response.Result);
        }
Beispiel #17
0
        public void FillHeadersTest()
        {
            string input = "GET http://localhost:8000/150m3w91 HTTP/1.1\n" +
                           "Accept-Charset: iso-8859-5, unicode-1-1;q=0.8\n" +
                           "Accept-Encoding: compress, gzip\n" +
                           "Expires: Thu, 01 Dec 1994 16:00:00 GMT\n" +
                           "If-Match: \"xyzzy\"" +
                           "Connection: close\n" +
                           "Content-Language: da\n" +
                           "Content-Length: 3495\n" +
                           "Content-Location: /index.htm\n" +
                           "Content-Range: bytes 21010-47021/47022\n" +
                           "Date: Tue, 15 Nov 1994 08:12:31 GMT\n" +
                           "ETag: \"xyzzy\"\n" +
                           "From: [email protected]\n" +
                           "Host: www.w3.org\n" +
                           "If-Modified-Since: Sat, 29 Oct 1994 19:43:31 GMT\n" +
                           "If-None-Match: \"xyzzy\"\n" +
                           "If-Unmodified-Since: Sat, 29 Oct 1994 19:43:31 GMT\n" +
                           "Last-Modified: Tue, 15 Nov 1994 12:45:26 GMT\n" +
                           "Location: http://www.w3.org/pub/WWW/People.html\n" +
                           "Referer: http://www.w3.org/hypertext/DataSources/Overview.html\n" +
                           "Retry-After: 120\n" +
                           "Server: CERN/3.0 libwww/2.17\n" +
                           "TE: trailers, deflate;q=0.5\n" +
                           "Transfer-Encoding: chunked\n" +
                           "Upgrade: HTTP/2.0, SHTTP/1.3, IRC/6.9, RTA/x11\n" +
                           "User-Agent: CERN-LineMode/2.15 libwww/2.17b3\n" +
                           "Via: 1.0 fred, 1.1 nowhere.com (Apache/1.1)\n" +
                           "Expect: 100-continue\n" +
                           "Warning: 199 Miscellaneous warning\n" +
                           "WWW-Authenticate: Basic\n" +
                           "Pragma: no-cache\n" +
                           "Proxy-Authenticate: Basic\n" +
                           "Proxy-Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==\n" +
                           "Trailer: Max-Forwards\n" +
                           "Vary: *\n" +
                           "Max-Forwards: 10\n" +
                           "Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==\n" +
                           "Cookie: $Version=1; Skin=new;\n" +
                           "Cache-Control: no-cache\n" +
                           "Content-Encoding: gzip";
            Request        request     = RequestParser.Parse(input);
            IService       service     = ServiceFactory.GetService(request.RequestType);
            HttpWebRequest httpRequest = (HttpWebRequest)WebRequest.Create(request.TargetAddress);

            service.FillHeaders(httpRequest, request);
        }
Beispiel #18
0
        public void RunTimeOfParseRequestWithLargeCookie()
        {
            var watch        = new Stopwatch();
            var largeHeaders = LargeHeaders();

            for (int i = 0; i < largeHeaders.Length; i++)
            {
                var header = largeHeaders[i];
                var bytes  = RequestArray(header);
                watch.Reset();
                watch.Start();
                var conn = RequestParser.Parse(bytes);
                watch.Stop();
                Assert.Less(watch.ElapsedMilliseconds, 100);
            }
        }
Beispiel #19
0
        public void RequestParserParseContent()
        {
            string input = "POST http://localhost:8000/1bmyfxm1 HTTP/1.0\n" +
                           "Content-Type: application/x-www-form-urlencoded\n" +
                           "Content-Length: 32\n" +
                           "\n" +
                           "home=Cosby&favorite+flavor=flies\n";
            Request request = RequestParser.Parse(input);

            Assert.AreEqual(SparkHttp.Entity.Type.POST, request.RequestType);
            Assert.AreEqual("http://localhost:8000/1bmyfxm1", request.TargetAddress);
            Assert.AreEqual(HttpVersion.Version10, request.RequestVersion);
            Assert.AreEqual("application/x-www-form-urlencoded", request.Headers["Content-Type"]);
            Assert.AreEqual("32", request.Headers["Content-Length"]);
            Assert.AreEqual("home=Cosby&favorite+flavor=flies", request.Content);
        }
Beispiel #20
0
        public void RunTimeOfParseRequestWithLargeCookie()
        {
            var watch = new Stopwatch();

            for (var i = 0; i < 100; i++)
            {
                var bytes = RequestArray(requestWithLargeCookie);
                watch.Start();
                var parsed = RequestParser.Parse(bytes);
                watch.Stop();

                Assert.IsNotNull(parsed);
                Assert.AreEqual(11, parsed.Headers.Count);
            }

            Assert.Less(watch.Elapsed.TotalSeconds, 50.0 / 1000);
        }
Beispiel #21
0
        public void PartialHeaderRequestShouldNotBeIncluded()
        {
            const string partialHeaderRequest =
                "GET /demo HTTP/1.1\r\n" +
                "Host: example.com\r\n" +
                "Connection: Upgrade\r\n" +
                "Sec-WebSocket-Key2: 12998 5 Y3 1  .P00\r\n" +
                "Sec-WebSocket-Protocol: sample\r\n" +
                "Upgrade: WebSocket\r\n" +
                "Sec-WebSoc"; //Cut off
            var bytes   = RequestArray(partialHeaderRequest);
            var request = RequestParser.Parse(bytes);

            Assert.IsNotNull(request);
            Assert.IsTrue(request.Headers.ContainsKey("Upgrade"));
            Assert.IsFalse(request.Headers.ContainsKey("Sec-WebSoc"));
        }
Beispiel #22
0
        public void ParseTakesInBytesOfARequestWithNoHeadersAndReturnsARequest()
        {
            const string testGetRequestString = "GET / HTTP/1.1\r\n" +
                                                "\r\n";
            var testGetRequestBytes = Encoding.UTF8.GetBytes(testGetRequestString);

            var testRequest = new Request(
                "GET",
                "/",
                "HTTP/1.1"
                );

            var testDataParser = new RequestParser();
            var result         = testDataParser.Parse(testGetRequestBytes);

            Assert.True(result.Equals(testRequest));
        }
Beispiel #23
0
        public void NoBodyRequestShouldNotBeNull()
        {
            const string noBodyRequest =
                "GET /demo HTTP/1.1\r\n" +
                "Host: example.com\r\n" +
                "Connection: Upgrade\r\n" +
                "Sec-WebSocket-Key2: 12998 5 Y3 1  .P00\r\n" +
                "Sec-WebSocket-Protocol: sample\r\n" +
                "Upgrade: WebSocket\r\n" +
                "Sec-WebSocket-Key1: 4 @1  46546xW%0l 1 5\r\n" +
                "Origin: http://example.com\r\n" +
                "\r\n" +
                "";
            var bytes = RequestArray(noBodyRequest);

            Assert.IsNotNull(RequestParser.Parse(bytes));
        }
Beispiel #24
0
        public void RequestParserParseContentJson()
        {
            string input = "PUT http://localhost:8000/1bmyfxm1 HTTP/1.0\n" +
                           "Content-Type: application/x-www-form-urlencoded\n" +
                           "Content-Length: 44\n" +
                           "\n" +
                           "{\n" +
                           "\"home\": \"Cosby\",\n" +
                           "\"favorete flavor\": \"flies\"\n" +
                           "}";
            Request request = RequestParser.Parse(input);

            Assert.AreEqual(SparkHttp.Entity.Type.PUT, request.RequestType);
            Assert.AreEqual("http://localhost:8000/1bmyfxm1", request.TargetAddress);
            Assert.AreEqual(HttpVersion.Version10, request.RequestVersion);
            Assert.AreEqual("application/json", request.Headers["Content-Type"]);
            Assert.AreEqual("44", request.Headers["Content-Length"]);
            Assert.AreEqual("{\"home\": \"Cosby\",\"favorete flavor\": \"flies\"}", request.Content);
        }
Beispiel #25
0
        public static void Main(string[] args)
        {
            // JSON Data
            Request request = new Request()
            {
                ContentType = "json",
                Content     = @"{""name"":""John Doe"",""age"":20}"
            };

            RequestParser requestParser = new RequestParser(request);

            requestParser.Parse();

            // XML Data
            request = new Request()
            {
                ContentType = "xml",
                Content     = @"<PurchaseOrder>
                                <PurchasedGame>
                                    <Name>GTA</Name>
                                </PurchasedGame>
                                <Customer>
                                    <Name>Evander</Name>
                                </Customer>
                            </PurchaseOrder>"
            };

            requestParser = new RequestParser(request);
            requestParser.Parse();

            // Invalid data
            request = new Request()
            {
                ContentType = "string",
                Content     = "test"
            };

            requestParser = new RequestParser(request);
            requestParser.Parse();

            Console.ReadKey();
        }
Beispiel #26
0
        public void EmptyHeaderValuesShouldParse()
        {
            const string emptyCookieRequest =
                "GET /demo HTTP/1.1\r\n" +
                "Host: example.com\r\n" +
                "Connection: Upgrade\r\n" +
                "Sec-WebSocket-Key2: 12998 5 Y3 1  .P00\r\n" +
                "Sec-WebSocket-Protocol: sample\r\n" +
                "Upgrade: WebSocket\r\n" +
                "Sec-WebSocket-Key1: 4 @1  46546xW%0l 1 5\r\n" +
                "Origin: http://example.com\r\n" +
                "Cookie: \r\n" +
                "\r\n" +
                "^n:ds[4U";
            var bytes   = RequestArray(emptyCookieRequest);
            var request = RequestParser.Parse(bytes);

            Assert.IsNotNull(request);
            Assert.AreEqual("", request.Headers ["Cookie"]);
        }
Beispiel #27
0
        public void RequestParserParse()
        {
            string input = "GET https://www.google.com/ HTTP/1.1\n" +
                           "Host: www.google.com\n" +
                           "Connection: keep-alive\n" +
                           "Accept: text/html,application/xhtml+xml,application/xml?q=0.9,image/webp,*/*?q=0.8\n" +
                           "UserAgent: Mozilla/5.0 (Windows NT 10.0? WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.109 Safari/537.36\n" +
                           "AcceptEncoding: gzip, deflate\n" +
                           "AcceptLanguage: enUS, en?q=0.8\n";
            Request request = RequestParser.Parse(input);

            Assert.AreEqual(SparkHttp.Entity.Type.GET, request.RequestType);
            Assert.AreEqual("https://www.google.com/", request.TargetAddress);
            Assert.AreEqual("www.google.com", request.Headers["Host"]);
            Assert.AreEqual("keep-alive", request.Headers["Connection"]);
            Assert.AreEqual("text/html,application/xhtml+xml,application/xml?q=0.9,image/webp,*/*?q=0.8", request.Headers["Accept"]);
            Assert.AreEqual("Mozilla/5.0 (Windows NT 10.0? WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.109 Safari/537.36", request.Headers["UserAgent"]);
            Assert.AreEqual("gzip, deflate", request.Headers["AcceptEncoding"]);
            Assert.AreEqual("enUS, en?q=0.8", request.Headers["AcceptLanguage"]);
        }
        public void PutRequest_ShouldReturnRequest_WithMethodPut()
        {
            // 1. Arrange
            RequestParser parser            = new RequestParser();
            Method        expectedMethod    = Method.Put;
            string        expectedPath      = "sadsadsa/sadsads/sadsad/asdsa";
            string        expectedQuery     = string.Empty;
            string        expectedBody      = @"{
        ""firstName"": ""Wekoslav"",
        ""lastName"": ""Stefanovski""
}";
            string        expectedUserAgent = "PostmanRuntime/7.16.3";
            string        requestString     = @"PUT /sadsadsa/sadsads/sadsad/asdsa HTTP/1.1
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1bmlxdWVfbmFtZSI6Indla29zbGF2IiwiQ291bnRyeSI6Ik1hY2Vkb25pYSIsIm5iZiI6MTU2NzQ1Mzg2MSwiZXhwIjoxNTY3NDU3NDYxLCJpYXQiOjE1Njc0NTM4NjF9.YkAwmtzYGPMWUK1x5deRIu3mEcoRktDLOiZ3U3LVToM
Content-Type: application/json
User-Agent: PostmanRuntime/7.16.3
Accept: */*
Cache-Control: no-cache
Postman-Token: 4c085ee0-a559-486e-a9c6-406823700d7a
Host: localhost:13000
Accept-Encoding: gzip, deflate
Content-Length: 56
Connection: keep-alive

{
        ""firstName"": ""Wekoslav"",
        ""lastName"": ""Stefanovski""
}";
            // 2. Act
            Request actual = parser.Parse(requestString);

            // 3. Assert
            Assert.AreEqual(expectedMethod, actual.Method);
            Assert.AreEqual(expectedPath, actual.Path);
            StringAssert.Equals(expectedQuery, actual.Query);
            Assert.AreEqual(expectedBody, actual.Body);
            Assert.AreEqual(expectedUserAgent, actual.Headers.GetHeader("User-Agent"));
        }
Beispiel #29
0
        public void Parse_ShouldAddHeadersToRequest_WhenCorrectParamsAreProvided()
        {
            const string input = @"GET /Home/LivePageForAjax HTTP/1.1
Host: telerikacademy.com
Referer: http://telerikacademy.com/";

            var mockedRequest = new Mock <IHttpRequest>();

            mockedRequest.Setup(r => r.AddHeader("Host", "telerikacademy.com"));
            mockedRequest.Setup(r => r.AddHeader("Referer", "http://telerikacademy.com/"));
            this._mockedFactory.Setup(f => f.GetHttpRequest("GET", "/Home/LivePageForAjax", "HTTP/1.1"))
            .Returns(() => mockedRequest.Object);

            var parser = new RequestParser(this._mockedFactory.Object);

            parser.Parse(input);

            this._mockedFactory.Verify(factory => factory.GetHttpRequest("GET", "/Home/LivePageForAjax", "HTTP/1.1"),
                                       Times.Once());
            mockedRequest.Verify(r => r.AddHeader("Host", "telerikacademy.com"),
                                 Times.Once());
            mockedRequest.Verify(r => r.AddHeader("Referer", "http://telerikacademy.com/"),
                                 Times.Once());
        }
Beispiel #30
0
        public void ShouldReturnNullForEmptyBytes()
        {
            WebSocketHttpRequest request = RequestParser.Parse(new byte[0]);

            Assert.IsNull(request);
        }