public static void Example_SimplePostUsingParameters() { // To prevent Log from output messages to Console we catch them and tell Log to not output to console. Log.LogOutputDelegate = LogDelegate; Log.LogToConsole = false; // Ensure Repository has been cleared - incase any examples have changed anything... Repository.ClearRepositoryAll(); HTTPBased httpRequest = new HTTPBased(); try { HTTPBased.ItemList response = httpRequest.HttpPOST("postman-echo.com", "/post", null, "content-type: text/plain\r\naccept: */*\r\nhost: postman-echo.com\r\naccept-encoding: identity\r\nconnection: close\r\n", "Hello"); OutputDetails("Example of a simple HTTP POST", httpRequest, response, $"Domain postman-echo.com exists and just echo's the post request in the JSON. So we", "expect the response to contain our requests body in the JSON 'data' field", "", $"Note how the header line 'Content-Length: 5' has been automatically added in the.", "request header."); } catch (Exception ex) { Console.WriteLine("Exception: " + ex.Message); } }
public static void Example_InvalidResourcePath() { // Set a non-existant domain. postman-echo.com exists but not the path /not/here string url = "postman-echo.com/not/here";; // To prevent Log from output messages to Console we catch them and tell Log to not output to console. Log.LogOutputDelegate = LogDelegate; Log.LogToConsole = false; // Ensure Repository has been cleared - incase any examples have changed anything... Repository.ClearRepositoryAll(); // Instantiate HTTPBased and set the domain and resoure path of the URL. HTTPBased httpRequest = new HTTPBased(); httpRequest.Domain = url.Split('/')[0]; httpRequest.ResourcePath = "/" + url.Split('/')[1]; // Setup the HTTP Header items. Header should be well-formed so we use the HTTPBased.ItemList to set the items as that will be well-formed. // NOTE. We have NOT set the Connection: close" and so HTTPBased.ItemList headerItems = new HTTPBased.ItemList(); headerItems.Add("accept", "*/*"); headerItems.Add("host", httpRequest.Domain); headerItems.Add("accept-encoding", "identity"); headerItems.Add("connection", "close"); httpRequest.SetHeaderStringFromItemList(headerItems); // Perform HTTP Post. Use TryHttpPOST as we are expecting an error. In a Test script, using the Try... would be preferential anyway incase a defect is touched and // the POST fails badly. If an HTTP POST endpoint ouside the test domain is being used (IE. A Mock) then standard HttpPOST could be used. HTTPBased.ItemList response; bool result = httpRequest.TryHttpPOST(out response); OutputDetails("Example of an invalid resource path", result, httpRequest, response, "We try to access a non-existant resource and so the HTTP server responds with a 404 error"); }
public void WhenITryToPostTheHTMLToTheDomain(string httpTransactionType) { HTTPBased http = new HTTPBased(); HTTPBased.ItemList response = new HTTPBased.ItemList(); switch (httpTransactionType.ToLower()) { case "post": this.context["Response"] = http.HttpPOST( this.context.Keys.Any(key => key == "Domain") ? (string)this.context["Domain"] : null, this.context.Keys.Any(key => key == "ResourcePath") ? (string)this.context["ResourcePath"] : null, this.context.Keys.Any(key => key == "Query") ? (string)this.context["Query"] : null, this.context.Keys.Any(key => key == "Header") ? (string)this.context["Header"] : null, this.context.Keys.Any(key => key == "Payload") ? (string)this.context["Payload"] : null); break; case "get": this.context["Response"] = http.HttpGET( this.context.Keys.Any(key => key == "Domain") ? (string)this.context["Domain"] : null, this.context.Keys.Any(key => key == "ResourcePath") ? (string)this.context["ResourcePath"] : null, this.context.Keys.Any(key => key == "Query") ? (string)this.context["Query"] : null, this.context.Keys.Any(key => key == "Header") ? (string)this.context["Header"] : null, this.context.Keys.Any(key => key == "Payload") ? (string)this.context["Payload"] : null); break; default: throw new ArgumentException($"Only supporting POST and GET. Got [{httpTransactionType}]", "httpTransactionType"); } this.context["TryException"] = http.TryException; }
private static void OutputDetails(string heading, HTTPBased httpRequest, HTTPBased.ItemList response, params string[] details) { // Get the response body string body = response?["Body"] ?? "Body not Set"; // Finally, give the details of the call. Console.WriteLine(heading); if (details.Length > 0) { Console.WriteLine(" - "); } foreach (string detailItem in details) { Console.WriteLine(" - " + detailItem); } Console.WriteLine(" - "); Console.WriteLine(" - REQUEST:-"); Console.WriteLine($" - HTTP POST to " + httpRequest.ActualURL); Console.Write(" - HTTP Payload - "); foreach (string payLoadLine in httpRequest.ActualPayload.Split("\r\n")) { Console.Write(payLoadLine + "\r\n - "); } Console.WriteLine(""); Console.WriteLine(" - RESPONSE:- "); Console.Write(" - "); foreach (string payLoadLine in httpRequest.ActualRawResponse.Split("\r\n")) { Console.Write(payLoadLine + "\r\n - "); } }
public void ThenTheHTTPBodyContains(string expectedBodyPart) { HTTPBased.ItemList result = (HTTPBased.ItemList) this.context["Response"]; string actualBody = result.ContainsKey("Body") ? result["Body"].Trim().ToLower() : null; Assert.IsTrue(actualBody.ToLower().Replace(" ", string.Empty).Contains(expectedBodyPart.ToLower().Replace(" ", string.Empty)), $"Body of HTTP response contains expected text. Actual [{actualBody}], Expected [{expectedBodyPart}]"); }
public void ThenIGetAnHTTPResponseBack(int expectedResponseCode) { HTTPBased.ItemList result = (HTTPBased.ItemList) this.context["Response"]; Assert.IsTrue(result.ContainsKey("StatusCode"), "Response has a Status Code"); Assert.AreEqual(expectedResponseCode.ToString(), result["StatusCode"]); }
public void GivenIBuildAValidMinimalHTTPHeaderAsListClosingTheConnectionAfterTheResponse() { HTTPBased.ItemList headerItems = new HTTPBased.ItemList(); headerItems.Add("Content-Type", "text/xml"); headerItems.Add("Host", (string)this.context["Domain"]); headerItems.Add("Accept-Encoding", "identity"); headerItems.Add("Connection", "close"); this.context["Header"] = headerItems; }
public static void Example_AcceptSSLCertificateUsingCustomDelegate() { // We use the Postman example website for this as the server is well setup for examples. string url = "postman-echo.com/post"; // To prevent Log from output messages to Console we catch them and tell Log to not output to console. Log.LogOutputDelegate = LogDelegate; Log.LogToConsole = false; // Ensure Repository has been cleared - incase any examples have changed anything... Repository.ClearRepositoryAll(); // Instantiate HTTPBased and set the domain and resoure path of the URL. HTTPBased httpRequest = new HTTPBased(); httpRequest.HTTPMethod = HTTPBased.HTTPMethods.Post; httpRequest.Domain = url.Split('/')[0]; httpRequest.ResourcePath = "/" + url.Split('/')[1]; httpRequest.CertificateValidationCallback = AcceptHTTPSCertificate; // This tells HTTPBased to use the AcceptHTTPSCertificate method to make certificate acceptance decision. // Setup the HTTP Header items. Header should be well-formed so we use the HTTPBased.ItemList to set the items as that will be well-formed. // NOTE. We have NOT set the Connection: close" and so HTTPBased.ItemList headerItems = new HTTPBased.ItemList(); headerItems.Add("accept", "*/*"); headerItems.Add("content-type", "text/plain"); headerItems.Add("host", httpRequest.Domain); headerItems.Add("accept-encoding", "identity"); headerItems.Add("connection", "close"); httpRequest.SetHeaderStringFromItemList(headerItems); httpRequest.UseSSL = true; httpRequest.Body = "Hello"; try { HTTPBased.ItemList response = httpRequest.Http(); OutputDetails("Example of a simple HTTP POST", httpRequest, response, "Property .UseSSL is set true and .CertificateValidationCallback is set", "to 'AcceptHTTPSCertificate' method. Method receives callback with", "certificate details:-", $"{serverCertificate})", "which we just accept in this case. A test may want to validate the certificate", "or just log the details etc..."); } catch (Exception ex) { Console.WriteLine("Exception: " + ex.Message); } }
public static void Example_HTTPSPostAutoAcceptSSLCertificate() { // We use the Postman example website for this as the server is well setup for examples. string url = "postman-echo.com/post"; // To prevent Log from output messages to Console we catch them and tell Log to not output to console. Log.LogOutputDelegate = LogDelegate; Log.LogToConsole = false; // Ensure Repository has been cleared - incase any examples have changed anything... Repository.ClearRepositoryAll(); // Tell NonGUI test library to accept the Server Certificate in an SSL (HTTPS) call Repository.ItemLocal["TeamControlium.NonGUI", "SSL_AcceptServerCertificate"] = true; // Instantiate HTTPBased and set the domain and resoure path of the URL. HTTPBased httpRequest = new HTTPBased(); httpRequest.HTTPMethod = HTTPBased.HTTPMethods.Post; httpRequest.Domain = url.Split('/')[0]; httpRequest.ResourcePath = "/" + url.Split('/')[1]; // Setup the HTTP Header items. Header should be well-formed so we use the HTTPBased.ItemList to set the items as that will be well-formed. // NOTE. We have NOT set the Connection: close" and so HTTPBased.ItemList headerItems = new HTTPBased.ItemList(); headerItems.Add("accept", "*/*"); headerItems.Add("content-type", "text/plain"); headerItems.Add("host", httpRequest.Domain); headerItems.Add("accept-encoding", "identity"); headerItems.Add("connection", "close"); httpRequest.SetHeaderStringFromItemList(headerItems); httpRequest.UseSSL = true; httpRequest.Body = "Hello"; try { HTTPBased.ItemList response = httpRequest.Http(); OutputDetails("Example of a simple HTTP POST", httpRequest, response, $"Domain {httpRequest.Domain} exists and just echo's the post request so we", "expect the response to contain our requests body in the JSON 'data' field", "", $"Note how the header line 'Content-Length: {httpRequest.Body.Length}' has been", "automatically added to the Request header by HTTPBased."); } catch (Exception ex) { Console.WriteLine("Exception: " + ex.Message); } }
public static void Example_SimpleGetUsingProperties() { // Set an existant domain and resource path. string url = "postman-echo.com/get"; // To prevent Log from output messages to Console we catch them and tell Log to not output to console. Log.LogOutputDelegate = LogDelegate; Log.LogToConsole = false; // Ensure Repository has been cleared - incase any examples have changed anything... Repository.ClearRepositoryAll(); // Instantiate HTTPBased and set the domain and resoure path of the URL. // So this loads httpRequest.Domain with postman-echo.com // and httpRequest.ResourcePath with /post HTTPBased httpRequest = new HTTPBased(); httpRequest.HTTPMethod = HTTPBased.HTTPMethods.Get; httpRequest.Domain = url.Split('/')[0]; httpRequest.ResourcePath = "/" + url.Split('/')[1]; HTTPBased.ItemList queryArguments = new HTTPBased.ItemList(); queryArguments.Add("foo", "bar"); queryArguments.Add("alpha", "7"); httpRequest.SetQueryStringFromItemList(queryArguments); // Setup the HTTP Header items. We could use a list and call SetHeaderStringFromItemList. But for sake of example we will build the string // ourselves. httpRequest.HeaderString = $"content-type: text/plain\r\naccept: */*\r\nhost: {httpRequest.Domain}\r\naccept-encoding: identity\r\nconnection: close\r\n"; // Perform HTTP Post. Use TryHttpPOST as we are expecting an error. In a Test script, using the Try... would be preferential anyway incase a defect is touched and // the POST fails badly. If an HTTP POST endpoint ouside the test domain is being used (IE. A Mock) then standard HttpPOST could be used. try { HTTPBased.ItemList response = httpRequest.Http(); OutputDetails("Example of a simple HTTP GET", httpRequest, response, $"Domain {httpRequest.Domain} exists and just echo's the get request. So we", "expect the response to contain our requests arguments (foo=bar and alpha=7) in the", "JSON 'args' field", "", $"Note how the header line 'Content-Length: {httpRequest.Body.Length}' has been", "automatically added to the Request header by HTTPBased."); } catch (Exception ex) { Console.WriteLine("Exception: " + ex.Message); } }
public static void Example_RejectSSLCertificate() { // We use the Postman example website for this as the server is well setup for examples. string url = "postman-echo.com/post"; // To prevent Log from output messages to Console we catch them and tell Log to not output to console. Log.LogOutputDelegate = LogDelegate; Log.LogToConsole = false; // Ensure Repository has been cleared - incase any examples have changed anything... Repository.ClearRepositoryAll(); // Tell NonGUI test library to reject the Server Certificate in an SSL (HTTPS) call Repository.ItemLocal["TeamControlium.NonGUI", "SSL_AcceptServerCertificate"] = false; // Set to true to prove that the example would work if true. // Instantiate HTTPBased and set the domain and resoure path of the URL. HTTPBased httpRequest = new HTTPBased(); httpRequest.Domain = url.Split('/')[0]; httpRequest.ResourcePath = "/" + url.Split('/')[1]; // Setup the HTTP Header items. Header should be well-formed so we use the HTTPBased.ItemList to set the items as that will be well-formed. // NOTE. We have NOT set the Connection: close" and so HTTPBased.ItemList headerItems = new HTTPBased.ItemList(); headerItems.Add("accept", "*/*"); headerItems.Add("host", httpRequest.Domain); headerItems.Add("accept-encoding", "identity"); headerItems.Add("connection", "close"); httpRequest.SetHeaderStringFromItemList(headerItems); httpRequest.UseSSL = true; // Perform HTTP Post. Use TryHttpPOST as we are expecting an error. In a Test script, using the Try... would be preferential anyway incase a defect is touched and // the POST fails badly. If an HTTP POST endpoint ouside the test domain is being used (IE. A Mock) then standard HttpPOST could be used. HTTPBased.ItemList response; bool result = httpRequest.TryHttpPOST(out response); OutputDetails("Example of forcing an HTTPS request to fail due to rejected certificate", result, httpRequest, response, "We have set UseSSL to true (which tells NonGUI to use HTTPS rather tha HTTP. But we have also set the", "repository item SSL_AcceptServerCertificate (Is category TeamControlium.NonGUI settings) to false. This", "forces NonGUI to reject the server certificate and so causes the exception."); }
public static void Example_RejectSSLCertificateUsingCustomDelegate() { // We use the Postman example website for this as the server is well setup for examples. string url = "postman-echo.com/post"; // To prevent Log from output messages to Console we catch them and tell Log to not output to console. Log.LogOutputDelegate = LogDelegate; Log.LogToConsole = false; // Ensure Repository has been cleared - incase any examples have changed anything... Repository.ClearRepositoryAll(); // Instantiate HTTPBased and set the domain and resoure path of the URL. HTTPBased httpRequest = new HTTPBased(); httpRequest.Domain = url.Split('/')[0]; httpRequest.ResourcePath = "/" + url.Split('/')[1]; // Setup the HTTP Header items. Header should be well-formed so we use the HTTPBased.ItemList to set the items as that will be well-formed. // NOTE. We have NOT set the Connection: close" and so HTTPBased.ItemList headerItems = new HTTPBased.ItemList(); headerItems.Add("accept", "*/*"); headerItems.Add("host", httpRequest.Domain); headerItems.Add("accept-encoding", "identity"); headerItems.Add("connection", "close"); httpRequest.SetHeaderStringFromItemList(headerItems); httpRequest.UseSSL = true; httpRequest.CertificateValidationCallback = RejectHTTPSCertificate; // Comment out this line to see that the Server certificate gets accepted. // Perform HTTP Post. Use TryHttpPOST as we are expecting an error. In a Test script, using the Try... would be preferential anyway incase a defect is touched and // the POST fails badly. If an HTTP POST endpoint ouside the test domain is being used (IE. A Mock) then standard HttpPOST could be used. HTTPBased.ItemList response; bool result = httpRequest.TryHttpPOST(out response); OutputDetails("Example of using the SSL Certificate validation override to reject an SSL certificate", result, httpRequest, response, "We have set UseSSL to true (which tells NonGUI to use HTTPS rather tha HTTP) and we have set", "CertificateValidationCallback to our own certificate validation method (RejectHTTPSCertificate) which", "forces the certificate to be rejected; hence the exception. In testing, we could use the callback", "to actually inspect and verify the certificate as part of testing if we so wished."); }
public static void Example_BadlyFormedHTTPHeaderBySetting() { // We use the Postman example website for this as the server is well setup for examples. string url = "postman-echo.com/post"; // To prevent Log from output messages to Console we catch them and tell Log to not output to console. Log.LogOutputDelegate = LogDelegate; Log.LogToConsole = false; // Ensure Repository has been cleared - incase any examples have changed anything... Repository.ClearRepositoryAll(); // Tell NonGUI test library to use a ';' between HTTP Header item keys and values Repository.ItemLocal["TeamControlium.NonGUI", "HTTPHeader_ItemDelimiter"] = ";"; // Instantiate HTTPBased and set the domain and resoure path of the URL. HTTPBased httpRequest = new HTTPBased(); httpRequest.Domain = url.Split('/')[0]; httpRequest.ResourcePath = "/" + url.Split('/')[1]; // Setup the HTTP Header items. Header should be well-formed so we use the HTTPBased.ItemList to set the items as that will be well-formed. // NOTE. We have left out the Host item. This is mandatory in HTTP and so we will get a fail. HTTPBased.ItemList headerItems = new HTTPBased.ItemList(); headerItems.Add("accept", "*/*"); headerItems.Add("host", httpRequest.Domain); headerItems.Add("accept-encoding", "identity"); headerItems.Add("connection", "close"); httpRequest.SetHeaderStringFromItemList(headerItems); // Perform HTTP Post. Use TryHttpPOST as we are expecting an error. In a Test script, using the Try... would be preferential anyway incase a defect is touched and // the POST fails badly. If an HTTP POST endpoint ouside the test domain is being used (IE. A Mock) then standard HttpPOST could be used. HTTPBased.ItemList response; bool result = httpRequest.TryHttpPOST(out response); OutputDetails("Example of a badly formed HTTP Header in an HTTP POST", result, httpRequest, response, "We set local Repository item HTTPHeader_ItemDelimiter (In the TeamControlium.NonGUI", "settings category) to a semi-colon (;). And so as the header is now malformed we see", "the request succeeds but the HTTP Response is a 400 (Bad Request)"); }
public void WhenITryAnHTTPRequestWithContent_Length(string httpTransactionType, string addContentLength) { HTTPBased http = new HTTPBased(); HTTPBased.ItemList response = new HTTPBased.ItemList(); switch (httpTransactionType.ToLower()) { case "post": this.context["HTTPRequestSuccess"] = http.TryHttp( HTTPBased.HTTPMethods.Post, this.context.Keys.Any(key => key == "Domain") ? (string)this.context["Domain"] : null, this.context.Keys.Any(key => key == "ResourcePath") ? (string)this.context["ResourcePath"] : null, this.context.Keys.Any(key => key == "Query") ? (string)this.context["Query"] : null, this.context.Keys.Any(key => key == "Header") ? (string)this.context["Header"] : null, this.context.Keys.Any(key => key == "Payload") ? (string)this.context["Payload"] : null, out response, addContentLength.Trim().ToLower() == "added" ? true : false); this.context["Response"] = response; break; case "get": this.context["HTTPRequestSuccess"] = http.TryHttp( HTTPBased.HTTPMethods.Get, this.context.Keys.Any(key => key == "Domain") ? (string)this.context["Domain"] : null, this.context.Keys.Any(key => key == "ResourcePath") ? (string)this.context["ResourcePath"] : null, this.context.Keys.Any(key => key == "Query") ? (string)this.context["Query"] : null, this.context.Keys.Any(key => key == "Header") ? (string)this.context["Header"] : null, this.context.Keys.Any(key => key == "Payload") ? (string)this.context["Payload"] : null, out response, addContentLength.Trim().ToLower() == "added" ? true : false); this.context["Response"] = response; break; default: throw new ArgumentException($"Only supporting POST and GET. Got [{httpTransactionType}]", "httpTransactionType"); } this.context["TryException"] = http.TryException; }
public static void Example_ConnectionTimeout() { // We use the Postman example website for this as the server is well setup for examples. string url = "postman-echo.com/post"; // To prevent Log from output messages to Console we catch them and tell Log to not output to console. Log.LogOutputDelegate = LogDelegate; Log.LogToConsole = false; // Ensure Repository has been cleared - incase any examples have changed anything... Repository.ClearRepositoryAll(); // Instantiate HTTPBased and set the domain and resoure path of the URL. HTTPBased httpRequest = new HTTPBased(); httpRequest.Domain = url.Split('/')[0]; httpRequest.ResourcePath = "/" + url.Split('/')[1]; // Setup the HTTP Header items. Header should be well-formed so we use the HTTPBased.ItemList to set the items as that will be well-formed. // NOTE. We have NOT set the Connection: close" and so HTTPBased.ItemList headerItems = new HTTPBased.ItemList(); headerItems.Add("accept", "*/*"); headerItems.Add("host", httpRequest.Domain); headerItems.Add("accept-encoding", "identity"); //headerItems.Add("connection", "close"); // Unconnect this line to see the POST succeed httpRequest.SetHeaderStringFromItemList(headerItems); // Perform HTTP Post. Use TryHttpPOST as we are expecting an error. In a Test script, using the Try... would be preferential anyway incase a defect is touched and // the POST fails badly. If an HTTP POST endpoint ouside the test domain is being used (IE. A Mock) then standard HttpPOST could be used. HTTPBased.ItemList response; bool result = httpRequest.TryHttpPOST(out response); OutputDetails("Example of a Connection Timeout occuring on an HTTP Post", result, httpRequest, response, "We have not added a 'Connection: close' header item and so HTTP default is 'keep-alive.", "As HTTPBased does not handle Async connections a timeout occures"); }
private static void OutputDetails(string heading, bool result, HTTPBased httpRequest, HTTPBased.ItemList response, params string[] details) { // We are expecting this to fail, so get the Exception message. string exceptionMessage = httpRequest.TryException?.Message ?? "No Exception was thrown!"; // Get the response body if there is one... string body = response?["Body"] ?? "Body not Set"; // Finally, give the details of the call. Console.WriteLine(heading); if (details.Length > 0) { Console.WriteLine(" - "); } foreach (string detailItem in details) { Console.WriteLine(" - " + detailItem); } Console.WriteLine(" - "); Console.WriteLine(" - REQUEST:-"); Console.WriteLine($" - HTTP POST to http{(httpRequest.UseSSL?"s":string.Empty)}://" + httpRequest.Domain + "/" + httpRequest.ResourcePath); Console.WriteLine(" - HTTP Header - " + httpRequest.HeaderString.Replace("\r\n", "\\r\\n")); Console.WriteLine(" - "); Console.WriteLine(" - RESPONSE:-"); Console.WriteLine(" - Request " + (result ? "Succeeded" : "Failed. An exception will have been thrown")); Console.WriteLine(" - " + (response == null ? "There was no response!" : $"Response was {response["StatusCode"] ?? "StatusCode Not set"} ({response["StatusText"] ?? "StatusText Not set"}) and body was {(string.IsNullOrEmpty(body) ? "Empty" : body)}")); Console.WriteLine(" - Exception message: " + exceptionMessage); Console.WriteLine(" - \r\n============================================================================================"); }