How to achieve webservice testing automation through programming/coding - c#

I know these questions have been asked many times , I am still looking for an answer that satisfies my question. please have a look at below points what I am looking for:
First thing , How to achieve that through programming. for web automation I am using specflow C#. do i need to create unit tests for the web service testing ? what can be done through programming ? soapUI is ruled out as its already used by manual testers.
Are there any available frameworks for these ?
Please give me links and examples supporting them.
I know its a broad question. but I do need some help from everyone so that I start in the right direction on API testing.

Your absolute first port of call is to understand the web service you are testing. Do you have valid XML you can submit to the web service? If so, store it somewhere and create a step that obtains it from the folder. Use that XML as your test case and iterate through each file in the folder. Each XML file should be different based on what you want the tests to cover.
Generally, web service testing will include logging response times, sending differing flavors of XML as test cases (alter the content of the nodes to cover different triggers), and checking for particular values in your responses.
A very high level and implicit Scenario could look like this (based on something I did once):
Scenario Outline: Submit Requests to Web Service
Given I have XML file '<XML_Case>'
And I submit a 'POST' request
Then I should receive a response from the Web Service
And the response will include a 'ResponseId' in the 'Header' section
And the response will include a 'RequestId' in the 'Body' section
And the 'Complete' node in the 'Body' section will return the value of 'True'
Examples:
|XML_Case |
| C:\TestData\test1.xml |
| C:\TestData\test2.xml |
| etc... |
To drive this, there are many approaches in C#. To start you off, you could check for the XML file and convert it into your XML request via something like this as a step definition:
[Given(#"I have XML file '(.*)'")]
public void GivenIHaveXMLFile(string fileName)
{
//Checks if file exists
if (System.IO.File.Exists(fileName))
{
var requestXml = CreateXMLInstance(fileName);
}
else
{
throw new Exception("No XML file found in specified location");
}
}
The CreateXMLInstance method used in that code would load the XML from the file path and could be like this:
public XmlDocument CreateXmlInstance(string xmlPath)
{
//Loads XML from file path
XmlDocument request = new XmlDocument();
request.Load(xmlPath);
return request;
}
You've essentially created your first few steps and could store the requestXml variable as a field or in Specflow's ScenarioContext for use later when you do the web service calls.
There is obviously a lot more to consider but this might send you in the right direction.

Related

c# HtmlAgilityPack class inside many classes, need to check if class exist

I am working on this for days without a solution.
For example, I have this link: https://www.aliexpress.com/item/32682673712.html
I am trying to check if the Buy now button disable
if I have this line inside the DOM : Buy Now
the problem is that this line inside a class that inside a class and so on...
I know there is an option to get a specific node with HtmlAgilityPack But I didn't succeed
var nodes = doc.DocumentNode.SelectNodes("//div[(#class='next-btn next-large next-btn-primary buynow disable')]/p");
but I don't get anything
I tried to get the entire dom and then search with inside but didn't succeed
var getHtmlWeb = new HtmlWeb();
var document = getHtmlWeb.Load(url);
I just got the html and not the DOM
another thing I tried to do is:
var Driver = new FirefoxDriver();
Driver.Navigate().GoToUrl(url);
string pagesource = Driver.PageSource;
and it did works! but this solution open the browser and I don't want that (I am running over many links)
Please help a frustrated guy :)
thanks.
This is happening because the buynow button is being loaded via JavaScript.
If you open network tab in chrome dev tools, you will notice that the page is making a call to some api to load the product information.
The url with json data for the product looks like this:
https://www.aliexpress.com/aeglodetailweb/api/store/header?itemId=32682673712&categoryId=100007324&sellerAdminSeq=202460364&storeNum=720855&minPrice=4.99&maxPrice=4.99&priceCurrency=USD
You will most probably have to send same headers as chrome is sending for the request in order to load the api endpoint in your app.

Apache SOLR and C# windows application

Am newbie to Apache SOLR 7.4. Am trying to upload XML file to remote server where the SOLR 7.4 is hosted.I need to update the collection with new XML file uploaded to the server. How can I re-index the collection ?
Things I have tried like using Simple Post Tool, CURL command with update etc.
If you're writing a C# application, using SolrNet is the suggested way. To upload a file to Solr Cell (which is what the module that extracts content from most file types is called), you can follow the example given in the manual. To parse the file for content to see how it behaves with the file you've uploaded:
ISolrOperations<Something> solr = ...
using (var file = File.OpenRead(#"test.pdf")) {
var response = solr.Extract(new ExtractParameters(file, "some_document_id") {
ExtractOnly = true,
ExtractFormat = ExtractFormat.Text,
});
Console.WriteLine(response.Content);
}
Set ExtractOnly to false to index the content, and use Fields to set additional field values (i.e. an id field, etc.).

Is there a more efficient way to deal with Amazon Product advertising API on C# ASP.NET (esp MVC 5)?

I have finally got the Amazon product advertising API to work on my MVC 5 site. I am using the "SignedRequestHelper" class that was provided on one of the downloads from the Amazon site. I have actually got a ref to the Amazon API but I do not seem to be using it at all at present.
What I am using so far is (controller):
SignedRequestHelper helper = new SignedRequestHelper("myAWSaccessKeyID",
"mysecretKey", "webservices.amazon.co.uk");
Dictionary<String, String> items = new Dictionary<String, String>();
items.Add("Service", "AWSECommerceService");
items.Add("Operation", "ItemSearch");
items.Add("AWSAccessKeyId", "myAWSaccessKeyID");
items.Add("AssociateTag", "myTag");
items.Add("SearchIndex", SearchIndex);//This is a string value (selectbox)
items.Add("ResponseGroup", "Images,ItemAttributes,OfferFull,Offers,OfferSummary,Reviews");
items.Add("Keywords", keyword);//This is a string value
string requestUrl = helper.Sign(items);
ViewBag.Stuff = requestUrl;//Just so I could see the whole URL!
WebRequest request = HttpWebRequest.Create(requestUrl);
WebResponse response = request.GetResponse();
XmlDocument doc = new XmlDocument();
doc.Load(response.GetResponseStream());
XmlNodeList titleNodes = doc.GetElementsByTagName("Item");
ViewBag.Titles = titleNodes;
You may notice I partially the copied the style of JAVA code from the scratch pad.
From that point on in the view I just deal with each part as it comes. It is kind of messy and horrid and dealing with switches like this:
foreach (System.Xml.XmlNode item in ViewBag.Titles)
{
<h3>Item: #count</h3>
foreach (System.Xml.XmlNode child in item.ChildNodes)
{
switch (child.Name)
{
case "ASIN":
<p>ASIN: #child.InnerText</p>
break;
case "MediumImage":
<img src="#child.ChildNodes[0].InnerText" />
break;
case "ItemAttributes":
foreach (System.Xml.XmlNode child1 in child.ChildNodes)
{
if(child1.Name == "Title")
{
<p>#child1.InnerText</p>
}
}
break;
}
}
count++;
}
It works and I can use the XML document etc. I just need to know if there is a way to change it so that it is actually using the API part that was given as a reference. I would rather use proper tools than do it with raw XML like this. I had such difficulty connecting with the Amazon documentation that I basically just tried to connect in the JAVA style code on Amazon's scratchpad.
You can use the following nuget Nager.AmazonProductAdvertising package.
PM> Install-Package Nager.AmazonProductAdvertising
Example Controller
public ActionResult ProductSearch(string search)
{
var authentication = new AmazonAuthentication();
authentication.AccessKey = "accesskey";
authentication.SecretKey = "secretkey";
var wrapper = new AmazonWrapper(authentication, AmazonEndpoint.DE);
var result = wrapper.Search(search);
return View(result);
}
Example View
#model Nager.AmazonProductAdvertising.Model.AmazonItemResponse
#{
ViewBag.Title = "Search";
}
<table class="table">
<tr>
<th>ASIN</th>
<th>SalesRank</th>
</tr>
#foreach (var item in Model.Items.Item)
{
<tr>
<td>#item.ASIN</td>
<td>#item.SalesRank</td>
</tr>
}
</table>
Take a look to AWS SDK for .Net. Also you can find some guides and how to work with it's APIs.
The AWS SDK for .NET includes the following:
The current version of the AWS SDK for .NET.
All previous major versions of the AWS SDK for .NET.
Sample code that demonstrates how to use the AWS SDK for .NET with several AWS services.
There is a library that is incredibly thorough for dealing with the Amazon Product Advertising API (PAAPI). When you make a request, you can receive a variety of responses, but this library can handle them all! It reads the XML and puts all the information in an object.
I'm working on two MVC 5 sites right now that interact with the PAAPI. I have a separate folder with the files and a couple files I wrote to make requests and process responses by pulling the data I need out of the object created by the library.
I made a C# console app demo, and you can view it here:
https://github.com/zoenberger/AmazonProductAdvertising
I used this for guidance:
https://flyingpies.wordpress.com/2009/08/01/17/
However, I ran into a couple errors:
In some instances, large responses require you to modify the
MaxReceivedMessageSize and is show on the demo.
I ran into an error with the ImageSets[] in the library. May people have and the fix is here.
I believe that I have finally found a way to use the actual Amazon Prod Adv API now. The problem was working out how to sign the request using the latest API (that I had added as a reference). The reference was added in a similar way to the getting started guide even though that was making reference to VS2005. That is obviously 10 years old but I somehow did get it working with a bit of problem solving. I just never got the signing correct so I ended up using that horrid REST bodge (in my original question)!
The post that has helped me now is this one:
amazon product advertising api - item lookup request working example
It is the one marked as the answer. It has only 4 up-votes but it is the best thing I have found. I put all the classes into the controller to test it but I will now have to do it properly using models or extension classes. It worked anyway though.

Using the Azure API, how do I list and add virtual directories to a website?

I am trying to add a Virtual Directory to an Azure Web Site from a WinForms Application using the Azure API. I can enumerate the WebSites on in my webspace, but I cannot find a method that allows me access to the Virtual Directories in the WebSite.
Here is my code:
string certPath = Properties.Settings.Default.AzureCertificatePath;
string certPassword = Properties.Settings.Default.AzureCertificatePassword;
string subscriptionId = Properties.Settings.Default.AzureSubscriptionId;
var cert = new X509Certificate2(certPath, certPassword, X509KeyStorageFlags.MachineKeySet);
var cred = new CertificateCloudCredentials(subscriptionId, cert);
using (var client = new WebSiteManagementClient(cred))
{
var spaces = client.WebSpaces.List();
foreach (var space in spaces)
{
Console.WriteLine("Space: {0}", space.Name);
var sites = client.WebSpaces.ListWebSites(space.Name, new WebSiteListParameters {PropertiesToInclude = { "Name" } }); ***// Where do I find out what properties can be included in this array?***
foreach (var site in sites)
{
***// What goes here to show the virtual directories in this specific website??????***
}
}
}
I found that the Azure web services API does not offer access to the virtual directories/applications on a web app, although the underlying REST API's that it uses does.
Luckily, the management API is open source (I wanted to get the v3.0.0.0 of the website management API, matching what I had NuGet'd, which I found here: https://github.com/Azure/azure-sdk-for-net/commits/master?page=79) so with a little perseverance and messing about with .targets files and NuGet references, you can get the source code of the WebSiteManagement project into your solution instead of the referenced DLL that you likely downloaded from NuGet.
From there, if you go into your client.WebSites.GetConfiguration method, stick a breakpoint in and capture the HTTP response returned - you'll see that in the JSON the VirtualApplications on your website are indeed there.
From there, you can edit your copy of the source code to expose those object structures out, much the same way that other object structures are mapped out of the JSON (e.g. HandlerMappings).
Likewise for updating them, you need to add the VirtualApplications (in the ewact same format) into the Microsoft.WindowsAzure.Management.WebSites.Models.WebSiteUpdateConfigurationParameters, and pass that into client.WebSites.UpdateConfiguration (which you will also need to amend to map your VirtualApplications object structure back into JSON in the same format).
Works great for me doing it this way.
Note/Disclaimer: The GitHub site documentation does mention that much of the source code was autogenerated, and that you shouldn't really go editing that code, instead raise an issue on the project about getting it sorted. I didn't have the time to do this and needed an immediate way of getting it working with my local copy of the code only, so my solution does, as you'll note when you look a the source, involve adding to that auto-gen'd code. It works great, but I should in good conscience point you to the project owner's warnings about tinkering with the auto-gen'd code.

Manipulate umbraco content using a console application

This is a noob question but I'm searching for some time and can't find any useful information.
I need to develop a rotine (console application) that will read and write content into a umbraco site. I've already read that you can do that with web forms and mvc application.
But I need to use umbraco like an external source. I need to do something like we do with Word documents. For example: open the file, read the file, write some things and save it.
I've already installed the API using
PM> Install-Package UmbracoCms -Pre
Some things I've already read:
http://nishantwork.wordpress.com/2012/09/27/umbraco-create-custom-content-node-in-umbraco-by-c/
https://github.com/sitereactor/umbraco-console-example
What is the best to achieve that? I don't know how to do it exactly...
You can create an Umbraco node (document), write to it and save it from a console application. Umbraco is basically a bunch of .Net libraries:
//Get the type you would like to use by its alias and the user who should be the creator of the document
DocumentType dt = DocumentType.GetByAlias("Textpage");
User author = User.GetUser(0);
//create a document with a name, a type, an umbraco user, and the ID of the document's parent page. To create a document at the root of umbraco, use the id -1
Document doc = Document.MakeNew("My new document", dt, author, 1018);
// Get the properties you wish to modify by it's alias and set their value
doc.getProperty("bodyText").Value = "<p>Your body text</p>";
doc.getProperty("articleDate").Value = DateTime.Now;
//after creating the document, prepare it for publishing
doc.Publish(author);
//Tell umbraco to publish the document
umbraco.library.UpdateDocumentCache(doc.Id);
See:
http://our.umbraco.org/wiki/reference/api-cheatsheet/creating-a-document
http://our.umbraco.org/wiki/reference/api-cheatsheet/modifying-document-properties
Just to help anyone with the same issue. I'm find out a web service in umbraco and i'm currently using that (until now for reading information only, but as far as I know we can write infomation also). Altought there's little documentation is easy to use.
But to use that you need to set <webservices enabled="False"> in umbracoSettings.config . This fie is in the folder Config inside umbraco.
We have to set user rights into the webservices node also to allow the user to use the web service
DocumentServiceReference.documentServiceSoapClient client = new DocumentServiceReference.documentServiceSoapClient();
client.WebservicesEnabled();
DocumentServiceReference.ArrayOfDocumentCarrier documents = client.readList(parentId, username, password);
foreach (DocumentServiceReference.documentCarrier doc in documents)
{
DocumentServiceReference.ArrayOfDocumentProperty properties = doc.DocumentProperties;
foreach (DocumentServiceReference.documentProperty property in properties)
{
string key = property.Key;
string value = property.PropertyValue.ToString();
}
}

Categories