Why am I getting Timeout error in the assertion step - jasmine

I first tried this
let url = await pa.getPageURL("Employees");
console.log("URL "+url);
Then I tried this. Both are throwing time out error but printing the correct url.
it('should be able to open Employees page',async () => {
loginPg.login();
pa.getPageURL("Employees").then(function(url){
console.log("URL "+url);
expect(url).toContain("employees");
})
})
async getPageURL(pageName){
this.menu.click()
let url = element(by.xpath('//span[contains(.,"'+pageName+'")]')).click().then(function(){
return browser.getCurrentUrl();
})
return url;
}
I'm writing a test where it clicks on a page link from the menu and assert the url. It works fine and click the link and goes to the correct page.
I have also verified that the console.log is correctly printing the url in the above code. But it fails everytime with Timeout error.
Error: Timeout - Async callback was not invoked within timeout specified by jasmine.DEFAULT_TIMEOUT_INTERVAL.
at ontimeout (timers.js:475:11)
at tryOnTimeout (timers.js:310:5)
What am I missing here? All my other tests work fine. Please help!

Try using a return keyword before your expect.
And also make sure to check DEFAULT_TIMEOUT_INTERVAL it will be 5 secs by default. Try changing it to 10 secs. So,That time is sufficient for logging in and then proceeding with actual expect.

Related

Blazor Server Side - Error: WebSocket closed with status code: 1006 () after 15 seconds

I have a Blazor Server Side app that throws a "Error: WebSocket closed with status code: 1006 () " on the clients side after 15 seconds while waiting for a sql query to complete.
The sql query populates a report so it sometimes takes up to 30 sec to generate.
I need to either increase the 15 sec timeout or keep the connection alive long enough for the query to complete.
Does anyone know how I can extend the timeout or keep the page alive long enough for the query to complete ?
Edit:
Adding :
endpoints.MapBlazorHub(opts => opts.WebSockets.CloseTimeout = new TimeSpan(1, 1, 1) );
to the start.cs seems to increase the time out to 30sec.
Unfortunately this doesn't seem to be enough off a timeout and changing the TimeSpan value any higher does not seem to increase the timeout further.
Thanks
I managed to "fix" this issue by doing a few things.
First I added
endpoints.MapBlazorHub(opts => opts.WebSockets.CloseTimeout = new TimeSpan(1, 1, 1));
to
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
in the
Startup.cs
This didn't completely work, it just increased the timeout from 15 sec to 30sec.
After playing around a bit, I updated the project from .net5 to .net 6 and updated all my nuget packages.
This seemed to help the most as the report now populates faster (under 30sec).
If I try to generate too large a report that takes over 30sec I now end up with a new error:
Error: Connection disconnected with error 'Error: Server timeout elapsed without receiving a message from the server.'.
If i keep refreshing the page the large reports does seem to eventually load.
For now the above fix helps me with my initial report issue.
If anyone has a real solution to this please let me know.
Edit(12/12/2022):
Finally seem to have a fix for this.
In _Host.cshtml
I added the following inside the "body" tag...
<body>
<script src="_framework/blazor.server.js" autostart="false"></script>
<script>
Blazor.start({
configureSignalR: function (builder) {
let c = builder.build();
c.serverTimeoutInMilliseconds = 3000000;
c.keepAliveIntervalInMilliseconds = 1500000;
builder.build = () => {
return c;
};
}
});
</script>
</body>
This, coupled with the "endpoints" update seems to have solved my issue correctly.
You can try:
WebSocket ws;
protected override async Task OnAfterRenderAsync(bool firstRender)
{
if (firstRender)
{
ws = new WebSocket(new WebAssemblyHttpMessageHandler());
ws.SetReceiveTimeout(TimeSpan.FromSeconds(30));
await ws.ConnectAsync(new Uri("ws://localhost:5000/mywebsocket"));
}
}

connect ETIMEDOUT 137.116.128.188:443 for bot FRAMEWORK, can be extended

So I have a request that is expected to run for at least 1 min. before it will give a response
To help aid user on not doing anything while my request is still running, I set some sendTyping activities:
For censoring production codes work sensitive information
, this is generally how my code looks like:
var queryDone = "No";
var xmlData = '';
let soappy = soapQuery("123", "456", "789","getInfo");
soappy.then(function (res) {
queryDone = 'Yes';
xmlData = res;
console.log(xmlData);
}, function (err) {
queryDone = 'Timeout';
})
while (queryDone == 'No') {
await step.context.sendActivity({ type: 'typing' });
}
where soapQuery() is a function that sends and returns the POST request which looks like this:
return new Promise(function (resolve, reject) {
request.post(options, function (error, response, body) {
if (!error && response.statusCode == 200) {
resolve(body);
}
else {
reject(error);
}
})
})
Problem comes because of this 1 minute response, (it's not really negotiable as the server requires at least 1 min to process it, due to large number of data and validation of my request).
Though after 1 minute, the console does print the response, sadly even before this, the bot already time out.
Any suggestion how to fix this, or extend time out of the bot?
I need the sendtyping activity so that user understands that the request is not yet done. And again, it really takes 1 minute before my request responds.
Thank you!
So, the reason that this happens is that HTTP requests work a little bit differently in the Bot Framework than you might expect. Here's how it works:
So basically, what's happening in your scenario is:
User sends HTTP POST
Bot calls your soapQuery
Bot starts sending Typing Indicators
soapQuery completes
Bot finally sends an HTTP Response to the HTTP POST from step #1, after the request has already timed out, which happens after 15 seconds
To fix this, I would:
Use showTypingMiddleware to send the typing indicator continuously and automatically until the bot sends another message (this gets rid of your blocking while loop)
Once soapQuery finishes, the bot will have lost context for the conversation, so your soappy.then() function will need to send a proactive message. To do so, you'll need to save a reference to the conversation prior to calling soappy(), and then within the then() function, you'll need to use that conversationReference to send the proactive message to the user.
Note, however, that the bot in the sample I linked above calls the proactive message after receiving a request on the api/notify endpoint. Yours doesn't need to do that. It just needs to send the proactive message using similar code. Here's some more documentation on Proactive Messages

WaitUntil not waiting / Get HTML on WaitForSelectorAsync

Having two problems that I would appreciate some advise on. Have used puppeteer in the past in node, but for some reason, running into a problem on the sharp version.
Basically I'm crawling a webpage with a WaitUntil set to WaitUntilNavigation.Networkidle0, the longest wait period. In my node code, this runs and loads my website correctly, but in the C# version, I get the page without angular loaded. From the best I can tell it is not waiting and returning the initial Load state. Below is my code.
if (BROWSER == null)
{
await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultRevision);
BROWSER = await Puppeteer.LaunchAsync(new LaunchOptions
{
Headless = true,
Args = new string[] { "--no-sandbox", "--disable-accelerated-2d-canvas", "--disable-gpu", "--proxy-server='direct://'", "--proxy-bypass-list=*" }
});
}
if (page == null)
{
page = await BROWSER.NewPageAsync();
await page.SetUserAgentAsync("PScraper-SiteCrawler");
await page.SetViewportAsync(new ViewPortOptions() { Width = 1024, Height = 842 });
var response = await page.GoToAsync(url, new NavigationOptions() { Referer = "PScraper-SiteCrawler", Timeout = timeoutMilliseconds, WaitUntil = new[] { WaitUntilNavigation.Networkidle0 } });
}
Timeout is set to 30 seconds, or 30,000 milliseconds. I then get the html of the page doing
await reponse.TextAsync()
My second question is unrelated, but likely simpler to solve. One route I was considering was using the page.WaitForSelectorAsync() method. This appears to wait until the content I'm looking for is loaded, but I haven't been able to figure out how to get the entire html of the page after this is done from the ElementHandle return.
Would appreciate some help here, tried a couple routes and haven't been able to figure out whats causing the difference between the node and C# code.
Solved my problem. The issue was how I was getting the html of the page.
I was using...
await reponse.TextAsync()
Apparently, this gets me only the initial response. When I changed my html get to the following line of code everything worked as expected.
await page.GetContentAsync()

RestSharp - when a test runs for the first time, it fails. When I debug, it passes. what's going on?

Pretty basic test:
[TestClass]
public class ApiClientTest
{
private RestClient _client;
[TestInitialize()]
public virtual void TestInitialize()
{
_client = new RestClient("http://localhost:24144");
_client.CookieContainer = new System.Net.CookieContainer();
}
[TestMethod]
public void ApiClientTestCRUD()
{
// 1. Log out twice. Verify Unauthorized.
var response = LogOut();
response = LogOut();
Assert.AreEqual(response.StatusCode, HttpStatusCode.Unauthorized);
// Error here:
Result Message: Assert.AreEqual failed. Expected:<0>.
Actual:< Unauthorized >.
I get <0>, which isn't even something that my WebAPI returns.
I think the issue is with my use of RestSharp, because if I debug one time it passes, and then subsequent runs pass. Any clue what's going on?
To be clear - this occurs when I open up my solution and attempt to run the test for the first time. I can fix it by debugging once, watching it pass, and then running without debugging as much as I want. I can reproduce this by closing VS and opening up the solution again - and running the test without debugging first.
Here's the LogOut method in my WebAPI:
[Authorize]
public HttpResponseMessage LogOut()
{
try
{
if (User.Identity.IsAuthenticated)
{
WebSecurity.Logout();
return Request.CreateResponse(HttpStatusCode.OK, "logged out successfully.");
}
return Request.CreateResponse(HttpStatusCode.Conflict, "already done.");
}
catch (Exception e)
{
return Request.CreateResponse(HttpStatusCode.InternalServerError, e);
}
}
UPDATE:
I ended up running the tests with Trace.WriteLine:
// 1. Log out twice. Verify Unauthorized.
Trace.WriteLine("ENTERING FIRST LOGOUT");
var response = LogOut();
Trace.WriteLine("Content: " + response.Content);
Trace.WriteLine("ErrorMessage: " + response.ErrorMessage);
Trace.WriteLine("ResponseStatus: " + response.ResponseStatus);
Trace.WriteLine("StatusCode: " + response.StatusCode);
Trace.WriteLine("StatusDescription: " + response.StatusDescription);
response = LogOut();
Trace.WriteLine("COMPLETED LOGOUTS");
Assert.AreEqual(response.StatusCode, HttpStatusCode.Unauthorized);
And I found the following:
ENTERING FIRST LOGOUT
Content:
ErrorMessage: Unable to connect to the remote server
ResponseStatus: Error
StatusCode: 0
StatusDescription:
COMPLETED LOGOUTS
My solution has a test project with this RestSharp test, and a WebAPI project that's supposed to be accepting these requests. If I debug, the RestClient connects. If not, it times out. Any tips?
When debugging is not possible to solve the problem go to the old fashion way.
Add Trace.WriteLine (or even append text to a C:\temp.txt file).
Write some string before every return in the LogOut method, then try writing some more information (if it's the last return then write the Exception message, if it's the second return write the Identity information.
Hope this helps.
How are you hosting the server? I see this that you're using port 24144. Maybe in debug mode you're running the express IIS Web Server and that's the port, but in non-debug mode it's not?

servicestack - caching a service response using redis

I have a servicestack service which when called via the browser (restful) Url ex:http://localhost:1616/myproducts, it works fine.
The service method has RedisCaching enabled. So first time it hits the data repository and caches it for subsequent use.
My problem is when I try calling it from a c# client via Soap12ServiceClient. It returns the below error:
Error in line 1 position 183. Expecting element '<target response>'
from namespace 'http://schemas.datacontract.org/2004/07/<target namespace>'..
Encountered 'Element' with name 'base64Binary',
namespace 'http://schemas.microsoft.com/2003/10/Serialization/'.
Below is my Client code:
var endpointURI = "http://mydevelopmentapi.serverhostingservices.com:1616/";
using (IServiceClient client = new Soap12ServiceClient(endpointURI))
{
var request = new ProductRequest { Param1 = "xy23432"};
client.Send<ProductResponse>(request);
}
It seems that the soapwsdl used is giving the problem, but I appear to have used the defaults as generated by servicestack..
Any help will be much appreciated.
Update
I was able over come this error by changing the cache code at the service end:
Code that returned error at client end:
return RequestContext.ToOptimizedResultUsingCache(this.CacheClient, cacheKey,
() =>
new ProductResponse(){CreateDate = DateTime.UtcNow,
products = new productRepository().Getproducts(request)
});
Code that works now:
var result = this.CacheClient.Get<ProductResponse>(cacheKey);
if (result == null)
{
this.CacheClient.Set<ProductResponse>(cacheKey, productResult);
result = productResult;
}
return result;
But I am still curious to know why the first method (RequestContext.ToOptimizedResultUsingCache) returned error at c# client?
But I am still curious to know why the first method (RequestContext.ToOptimizedResultUsingCache) returned error at c# client?
From what I can tell, the ToOptimizedResultUsingCache is trying to pull a specific format (xml, html, json, etc) out of the cache based on the RequestContext's ResponseContentType (see code here and here). When using the Soap12ServiceClient the ResponseContentType is text/html (not sure if this is correct/intentional within ServiceStack). So what ToOptimizedResultUsingCache is pulling out of the cache is a string of html. The html string is being returned to the Soap12ServiceClient and causing an exception.
By pulling directly out of the cache you are bypassing ToOptimizedResultUsingCache's 'format check' and returning something the Soap12ServiceClient can handle.
** If you are using Redis and creating your key with UrnId.Create method you should see a key like urn:ProductResponse:{yourkey}.html
Thanks for your response paaschpa.
I revisited the code and I was able to fix it. Since your response gave me the direction, I have accepted your answer. Below is my fix.
I moved the return statement from RequestContext to the response DTO.
Code which throws error when used via c# client (code was returning entire requestcontext):
return RequestContext.ToOptimizedResultUsingCache(this.CacheClient, cacheKey,
() =>
new ProductResponse(){CreateDate = DateTime.UtcNow,
products = new productRepository().Getproducts(request)
});
Fixed Code (return moved to response DTO):
RequestContext.ToOptimizedResultUsingCache(this.CacheClient, cacheKey,
() => {
return new ProductResponse(){CreateDate = DateTime.UtcNow,
products = new productRepository().Getproducts(request)
}
});

Resources