Hi I am trying to automate AdvancedRestClient extension for Chrome to test webservice.
I am able to start the Extension and send request. But I am not able to get any response.
public class WebServices {
public static void main(String[] args) {
//Start the driver
System.setProperty("webdriver.chrome.driver","$PATH_TO_DRIVER");
ChromeOptions options = new ChromeOptions();
options.addArguments("load-extension=C:/Users/$username/AppData/Local/Google/Chrome/User Data/Default/Extensions/hgmloofddffdnphfgcellkdfbfbjeloo/3.1.7_0");
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability(ChromeOptions.CAPABILITY, options);
ChromeDriver driver = new ChromeDriver(capabilities);
driver.manage().deleteAllCookies();
driver.manage().window().maximize();
//Start the extension
driver.get("chrome-extension://hgmloofddffdnphfgcellkdfbfbjeloo/RestClient.html");
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
//Get the authentication field and set authentication
WebElement authField = driver.findElement(By.xpath("//*[#id='appContainer']/div/div/div/div[4]/div[2]/section[1]/textarea"));
authField.sendKeys("$SET_AUTORIZATION")
//Get the reqestURL field and enter request
WebElement requestField = driver.findElement(By.xpath("//*[#id='appContainer']/div/div/div/div[2]/input"));
requestField.clear();
requestField.sendKeys("$REQUEST");
authField.click();
//Click on send button
WebElement sendButton = driver.findElement(By.xpath("//*[#id='appContainer']/div/div/div/div[7]/div/button[2]"));
sendButton.click();
}
}
The above steps work fine when I do it manually. But script does not generate any response.
Please help.
Automating a browser to test a web service is not the most reliable or efficient way.
You should instantiate a HttpClient in your test instead a Webdriver instance. This will allow you to make REST calls directly and interogate the response in the same way you would assert via WebDriver.
This approach will take milliseconds rather than seconds to run a test. Also, it can run anywhere without the need to install Chrome or Webdriver
Related
I've developing an Angular web application using ASP.Net Core 3.1 for the API.
So far, I've written some integration unit tests using a Custom WebApplicationFactory to create the test server.
All tests use the HttpClient to make GETs and POSTs to the API running under the Custom WebApplicationFactory. Most of these tests initially perform a login to obtain a token to use for subsequent requests.
I'd like to add Two Factor Authentication to the application, but this will inevitably break any tests, as they aren't able to get hold of the six digit code which would be sent via email.
Here is what a test currently looks like, without MFA being implemented.
Is there a way that the test can be given the MFA code so that it can continue to perform tests?
Do I simply need to seed a user that does not have MFA enabled?
I actually want all users to have MFA enabled in production.
Many thanks
using Xunit;
using System.Threading.Tasks;
using MyCompany.ViewModels.Authentication;
using MyCompany.StaffPortal.Tests.Shared;
using StaffPortal;
using Newtonsoft.Json;
using MyCompany.ServiceA.ViewModels;
using System.Collections.Generic;
using System.Net.Http;
namespace MyCompany.Tests.StaffPortal.ServiceA
{
public class ExtensionsControllerTests : TestBase
{
public ExtensionsControllerTests(CustomWebApplicationFactory<Startup> factory) : base(factory)
{
}
[Fact]
public async Task Test_GetExtensions()
{
//This line creates a new "web browser" and uses the login details provided to obtain and set up the token so that we can request information about an account.
HttpClient httpClient = await CreateAuthenticatedHttpClient("abcltd1#MyCompany.com", "test", 1);
//Perform any work and get the information from the API
//Contact the API using the token so check that it works
var getExtensionsResponse = await httpClient.GetAsync("/api/ServiceA/extensions/GetExtensions");
//Check that the response was OK
Assert.True(getExtensionsResponse.StatusCode == System.Net.HttpStatusCode.OK, "GetExtensions did not return an OK result.");
//Get and Convert the Content we received into a List of ServiceAExtensionViewModel, as that is what GetExtensions sends back to the browser.
var getExtensionsResponseContent = await getExtensionsResponse.Content.ReadAsStringAsync();
List<ServiceAExtensionViewModel> extensionList = JsonConvert.DeserializeObject<List<ServiceAExtensionViewModel>>(getExtensionsResponseContent);
//Check the information received matches our expectations
Assert.True(extensionList.Count == 2);
Assert.True(extensionList[0].PropertyA == 123);
Assert.True(extensionList[0].PropertyB == 0161);
Assert.True(extensionList[0].PropertyC == true);
}
}
}
Here is the content's of CreateAuthenticatedHttpClient() for reference.
protected async Task<HttpClient> CreateAuthenticatedHttpClient(string username, string password, int companyAccountId)
{
var httpClient = _factory.CreateClient(
new WebApplicationFactoryClientOptions
{
AllowAutoRedirect = false
});
//Create the Login information to send to the server
var loginInformation = new LoginRequestModel
{
Username = username,
Password = password,
ReturnUrl = ""
};
//Convert it into Json which the server will understand
var validLoginRequestJson = ConvertToJson(loginInformation);
//Send the Json Login information to the server, and put the response we receive into loginResponse
//In the code below, httpClient is like a web browser. You give it the
var loginResponse = await httpClient.PostAsync("/api/authenticate", validLoginRequestJson);
//Check the loginResponse was a CREATED response, which means that the token was made
Assert.True(loginResponse.StatusCode == System.Net.HttpStatusCode.Created, "New Token was not returned.");
//Check the response is identified as being in Json format
Assert.Equal("application/json; charset=utf-8", loginResponse.Content.Headers.ContentType.ToString());
//Next we have to convert the received Json information into whatever we are expecting.
//In this case, we are expecting a AuthenticationResponseViewModel (because that's what the API sends back to the person trying to log in)
//First we get hold of the Content (which is in Json format)
var responseJsonString = await loginResponse.Content.ReadAsStringAsync();
//Second we convert the Json back into a real AuthenticationResponseViewModel
AuthenticationResponseViewModel authenticationResponseViewModel = JsonConvert.DeserializeObject<AuthenticationResponseViewModel>(responseJsonString);
//Now we take the Token from AuthenticationResponseViewModel, and add it into the httpClient so that we can check the Token works.
httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", authenticationResponseViewModel.token);
httpClient.DefaultRequestHeaders.Add("CompanyId", companyAccountId.ToString());
return httpClient;
}
I am quite new to the ringcentral APIs and currently going through all of them.
Currently going through the following reference: https://developers.ringcentral.com/api-reference/SMS/createSMSMessage
Through Java we can use an API to send SMS, but can we receive a SMS using Java.
Can someone help me in getting the documentation/article or any kind of reference where I can get to know the simple way to send and receive the SMS using Java
A sample send SMS example with Java as follows:
import java.io.IOException;
import com.ringcentral.*;
import com.ringcentral.definitions.*;
public class Send_SMS {
String RECIPIENT_NUMBER = "<ENTER PHONE NUMBER>";
String RINGCENTRAL_CLIENTID = "<ENTER CLIENT ID>";
String RINGCENTRAL_CLIENTSECRET = "<ENTER CLIENT SECRET>";
String RINGCENTRAL_USERNAME = "<YOUR ACCOUNT PHONE NUMBER>";
String RINGCENTRAL_PASSWORD = "<YOUR ACCOUNT PASSWORD>";
String RINGCENTRAL_EXTENSION = "<YOUR EXTENSION, PROBABLY ";
public static void main(String[] args) {
var obj = new Send_SMS();
try {
obj.sendSms();
} catch (RestException | IOException e) {
e.printStackTrace();
}
}
public void sendSms() throws RestException, IOException{
RestClient rc = new RestClient(RINGCENTRAL_CLIENTID, RINGCENTRAL_CLIENTSECRET, RINGCENTRAL_SERVER);
rc.authorize(RINGCENTRAL_USERNAME, RINGCENTRAL_EXTENSION, RINGCENTRAL_PASSWORD);
CreateSMSMessage postParameters = new CreateSMSMessage();
postParameters.from = new MessageStoreCallerInfoRequest().phoneNumber(RINGCENTRAL_USERNAME);
postParameters.to = new MessageStoreCallerInfoRequest[]{new MessageStoreCallerInfoRequest().phoneNumber(RECIPIENT_NUMBER)};
postParameters.text = "Hello World from Java";
var response = rc.restapi().account().extension().sms().post(postParameters);
System.out.println("SMS sent. Message status: " + response.messageStatus);
}
}
You can download the java SDK from here: https://github.com/ringcentral/ringcentral-java
and start with documentation here: https://developers.ringcentral.com/guide/messaging/quick-start/java
Once you get the library in your application, you can start compiling it and running it.
Here is a SMS Java quickstart guide: https://developers.ringcentral.com/guide/sms/quick-start/java
Hope this helps!
Here is the official RingCentral Java SDK: https://github.com/ringcentral/ringcentral-java, it is currently 1.0.0-beta9. We are going to release a stable version this month.
Here is a list of all the API calls that you can invoke: https://github.com/ringcentral/ringcentral-java/blob/master/samples.md, including sms sending: https://github.com/ringcentral/ringcentral-java/blob/master/samples.md#create-smsmms-message
For sms receiving, you can use our subscription and notification feature: https://github.com/ringcentral/ringcentral-java#pubnub-subscriptions--notificatioins
So whenever there is new sms, you will be notified, then you can issue api call to get the message.
For technical details, you can always send email to devsupport#ringcentral.com
We are using C/Side on one server to try to call a URL to a PHP script on another server without opening a browser window. We want the script to run as a background process. So far, everything we've tried opens a browser. Any suggestions?
I used HttpClient to do this. But it's not that straight forward in Nav, since you cannot call an asynchronous method and assign its return value to a variable. So I created a wrapper class in c#.
public class NavHttpClient
{
private HttpResponseMessage responseMsg;
public HttpResponseMessage ResponseMsg
{
get { return responseMsg; }
}
public async Task GetAsync(string requestUri)
{
HttpClient client = new HttpClient();
responseMsg = await client.GetAsync(requestUri);
}
}
Then I exported this class in a class library. Now I can use it Nav this way:
NavWebClient : DotNet NavWebClient.NavHttpClient.'NavWebClient, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'
NavWebClient := NavWebClient.NavHttpClient;
NavWebClient.GetAsync('http://localhost').Wait;
IF NavWebClient.ResponseMsg.IsSuccessStatusCode THEN
...
Is this solution suits your needs? Inside there is link to codeunit for Nav 2013 that allows to work with web services in Nav style.
Please ignore the spelling mistake, I cannot copy code so I have typed the whole thing and changed name of controller and method.
WEB API 2
Controller:
// Controller name is Test
public HttpResponseMessage Method1(int param1) // Post method
{
// return string
}
If I create an object of controller in test case then it is working fine. But if I want to test in localhost using following code:
Unit Test:
public void Method1Test()
{
HttpResponseMessage response;
HttpConfiguration config = new HttpConfiguration();
config.Routes.MapHttpRoute("DefaultApi", "api/{controller}/{id}");
HttpServer server = new HttpServer(config);
using(var client = new HttpClient(server))
{
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, "http://localhost:5022/api/test?param1=1");
request.Content = new ObjectContent<int>(param1, new JsonMediaTypeFormatter());
response = client.SendAsync(request, CancellationToken.None).Result;
};
Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
}
Now, my test case is failing. I used the same code in different project and it worked. May be it is the way I am trying to call Post method. Is this the right way to call post method with Int parameter in URL?
In help page, under API column it shows:
POST api/test/param1={param1}
Also I have put some stop point in actual service I am cursor is not stopping at that point. Why?
If I want to call the same service from browser, what URL should I pass? Is it -
http://localhost:5022/api/test?param1=1
Or something else?
I figured it out. Following is the correct unit test method but this has some extra information which I have not provided earlier i.e., passing object as an input for the service.
private void Method1Test(ObjectClass obj)
{
HttpResponseMessage response = null;
HttpConfiguration config = new HttpConfiguration();
config.Routes.MapHttpRoute("DefaultApi", "api/{controller}/{id}");
HttpServer server = new HttpServer(config);
using (var client = new HttpClient(server))
{
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, "http://localhost:5022/api/test/1");
request.Content = new ObjectContent<ObjectClass>(obj, new JsonMediaTypeFormatter());
response = client.SendAsync(request, CancellationToken.None).Result;
};
Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
}
So the correct URL that I was looking for was
http://localhost:5022/api/test/1
Sorry, It took long to post this answer. This method is working like a charm for more then 2 years.
im trying to write a UnitTest for a WebAPI and EF
Im trying to add Data do the database in den TestInitialize, but it didnt work. When i do the same command in a Console Applications, it works.
Is there a different in calling that webapi for tests?
[TestInitialize]
public void CreateEntityObjects()
{
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://localhost:60609/");
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
Department dep1 = new Department() { Id = Guid.NewGuid(), Name = "IT" };
client.PostAsJsonAsync("api/Department", dep1);
}
Edit:
So i still just do the initialize no cleanup (later). I was looking manually if there is some data in the database. But no data, no Error, nothing.
You may try looking at the result property of the request:
var response = client.PostAsJsonAsync("api/Department", dep1).Result;
and then look at what does the server return:
string responseContent = response.Result.Content.ReadAsStringAsync().Result;
Now analyze the responseContent variable to see what possible error message you might have gotten from the server. Also you probably want to self-host your Web API in the unit test before sending an HTTP request to it, otherwise your API might not even be started.