Please bear with me as I am relatively new to Appium. I am writing C# tests in Appium for my Android app. I am stuck finding answers to questions below.
1) How to check if a particular element exists? Is there any boolean property or function returning true or false? The methods driver.GetElementById, driver.GetElementByName etc. throw exceptions if element doesn't exists.
2) Suppose I want to write a test for login. The user enters username and password and hits login button. The requests goes to server and it checks whether username-password pair exists in database. Meanwhile the loading indicator (progress dialog in Android) is shown on screen. How shall make a test suspend it's execution until response comes from server assuming I don't want to use something like Thread.Sleep function?
3) Can I check whether textfield validation is failed on screen? A control with black background and white text is shown below textfield upon validation failure if we set validation for that textfield through setError function. Is there any way to check that validation has failed?
Anticipating answers. Thanks.
For the first 2 questions (This is what I do in java, definitely can be implemented in c#) -
1) Use the polling technique - In a loop check for the element return of the following
#param - By by , int time
driver.findElement(By by);
This must not be null or empty.
If within the threshhold time the element is not present then fail the test.
In appium mode - isVisible() will be same as the above, as an element not visible will not be present.
2) Check for the next activity to be awaited. Use the same polling technique to keep on comparing the current activity with the awaited activity, If the awaited activity does not start within the threshold time then fail the test.
#param int time, String awaitedActivity
1) Get the current activity.
2) Compare with the awaited activity.
3) If same then break the loop.
4) Else sleep for a second and then continue till the time is exhausted.
Related
I am trying to write a very simple mathematical game in C# Console Application. The program will ask a simple mathematical question to the user. The user must respond by typing the answer and then press enter. I used the code
userinput = Convert.ToInt32(Console.Readline());
code to do this. However, I need the user to assign the value of userinput variable in three seconds after the problem is asked. So, I have to start a countdown timer immediately after the problem is asked. If the user does not type the answer and hit enter within three seconds, the program will display the message "timeout for this question" and immediately display the next question. If the user can type the answer and hit enter within three seconds, the program should immediately stop the countdown timer and evaluate the user's answer. I would be very happy if you can help me with that. Thank you very much in advance.
Note: I read the similar threads but they are based on readykey type user inputs. I need a readline type input.
Some pseudocode:
ask the problem;
start the timer;
if (the user types the answer and presses enter within three seconds)
{
evaluate the answer;
go to the next question;
}
else
{
prompt timeout;
go to the next question;
}
Countdown timers are a great way to add an extra touch of challenge and excitement to any game or activity. In this article, we will provide you with a step-by-step guide on how to set up a countdown timer limit to user input with readline in C# Console.
The first step is to import the C# Console namespace. This will give you access to the readline and Console classes, which are required for setting up a countdown timer. To do this, simply place the following code in your project:
using System;
Next, you need to create a method that will be used to set the timer limit. In this example, we are going to use a loop to count down from the user-specified value to zero. To do this, declare a new integer variable called ‘limit’ and set it to the result of the ReadLine() method. This method will prompt the user to enter a value they want to use as a timer limit:
int limit = int.Parse(Console.ReadLine());
Now, you will need to set up the loop for the countdown. This loop will continue running until it reaches zero. Inside the loop, you can use the Console.WriteLine() method to print out current time left for the user. After each iteration, you need to decrease the value of the limit variable by one:
while (limit > 0)
{
Console.WriteLine("Time left: " + limit);
limit--;
}
Finally, you will need to add some code to print out a message when the timer has reached zero. This can be done by using the Console.WriteLine() method again, this time with a message that informs the user that their time has run out:
if (limit == 0)
{
Console.WriteLine("Time's up!");
}
With that, you have successfully created a countdown timer limit to user input with readline in C# Console! This simple script can be used to add a bit of extra challenge and excitement to any game or activity you create.
I have a sequence of Images (IObservable<ImageSource>) that goes through this "pipeline".
Each image is recognized using OCR
If the results have valid values, the are uploaded to a service that can register a set of results at a given time (not concurrently).
If the results have any invalid value, they are presented to the user in order to fix them. After they are fixed, the process continues.
During the process, the UI should stay responsive.
The problem is that I don't know how to handle the case when the user has to interact. I just cannot do this
subscription = images
.Do(source => source.Freeze())
.Select(image => OcrService.Recognize(image))
.Subscribe(ocrResults => Upload(ocrResults));
...because when ocrResults have to be fixed by the user, the flow should be kept on hold until the valid values are accepted (ie. the user could execute a Command clicking a Button)
How do I say: if the results are NOT valid, wait until the user fixes them?
This seems to be a mix of UX, WPF and Rx all wrapped up in one problem. Trying to solve it with only Rx is probably going to send you in to a tail spin. I am sure you could solve it with just Rx, and no more thought about it, but would you want to? Would it be testable, loosely coupled and easy to maintain?
In my understanding of the problem you have to following steps
User Uploads/Selects some images
The system performs OCR on each image
If the OCR tool deems the image source to be valid, the result of the processing is uploaded
If the OCR tool deems the image source to be invalid, the user "fixes" the result and the result is uploaded
But this may be better described as
User Uploads/Selects some images
The system performs OCR on each image
The result of the OCR is placed in a validation queue
While the result is invalid, a user is required to manually update it to a valid state.
The valid result is uploaded
So this to me seem that you need a task/queue based UI so that a User can see invalid OCR results that they need to work on. This also then tells me that if a person is involved, that it should probably be outside of the Rx query.
Step 1 - Perform ORC
subscription = images
.Subscribe(image=>
{
//image.Freeze() --probably should be done by the source sequence
var result = _ocrService.Recognize(image);
_validator.Enqueue(result);
});
Step 2 - Validate Result
//In the Enqueue method, if queue is empty, ProcessHead();
//Else add to queue.
//When Head item is updated, ProcessHead();
//ProcessHead method checks if the head item is valid, and if it is uploads it and remove from queue. Once removed from queue, if(!IsEmpty) {ProcessHead();}
//Display Head of the Queue (and probably queue depth) to user so they can interact with it.
Step 3 - Upload result
Upload(ocrResults)
So here Rx is just a tool in our arsenal, not the one hammer that needs to solve all problems. I have found that with most "Rx" problems that grow in size, that Rx just acts as the entry and exit points for various Queue structures. This allows us to make the queuing in our system explicit instead of implicit (i.e. hidden inside of Rx operators).
I'm assuming your UploadAsync method returns a Task to allow you to wait for it to finished? If so, there are overloads of SelectMany that handle tasks.
images.Select(originalImage => ImageOperations.Resize(originalImage))
.SelectMany(resizedImg => imageUploader.UploadAsync(resizedImg))
.Subscribe();
Assuming you've got an async method which implements the "user fix process":
/* show the image to the user, which fixes it, returns true if fixed, false if should be skipped */
async Task UserFixesTheOcrResults(ocrResults);
Then your observable becomes:
subscription = images
.Do(source => source.Freeze())
.Select(image => OcrService.Recognize(image))
.Select(ocrResults=> {
if (ocrResults.IsValid)
return Observable.Return(ocrResults);
else
return UserFixesTheOcrResults(ocrResults).ToObservable().Select(_ => ocrResults)
})
.Concat()
.Subscribe(ocrResults => Upload(ocrResults));
I wants to apply dynamic wait in ranorex.
To open a webpage I used static wait like this :-
Host.Local.OpenBrowser("http://www.ranorex.com/Documentation/Ranorex/html/M_Ranorex_WebDocument_Navigate_2.htm",
"firefox.exe");
Delay.Seconds(15);
Please provide me a proper solution in details. Waiting for your humble reply.
The easiest way is use the wait for document loaded method. This allows you to set a timeout that is the maximum to wait, but will continue when the element completes it's load. Here is the documentation on it,
http://www.ranorex.com/Documentation/Ranorex/html/M_Ranorex_WebDocument_WaitForDocumentLoaded_1.htm
First of all, you should be more detailed about your issues. Atm you actually don't state any issue and don't even specify the reason for the timeout.
I don't actually see why you would need a timeout there. The next element to be interacted with in your tests will have it's own search timeouts. In my experience I haven't had a need or a reason to have a delay for the browser opening.
If you truelly need a dynamic delay there, here's what you actually should validate.
1) Either select an element that always exists on the webpage when you open the browser or
2) Select the next element to be interacted with and build the delay ontop of either of these 2
Let's say that we have a Input field that we need to add text to after the page has opened. The best idea would be do wait for that element to exists and then continue with the test case.
So, we wait for the element to exist (add the element to the repository):
repo.DomPart.InputElementInfo.WaitForExists(30000);
And then we can continue with the test functionality:
repo.DomPart.InputElement.InnerText = "Test";
What waitForExists does is it waits for 30 seconds (30000 ms) for the element to exists. It it possible to catch an exception from this and add error handleing if the element is not found.
The dynamic functionality has to be added by you. In ranorex at one point you will always run into a timeout. It might be a specified delay, it might be the timeout for a repo element, etc. The "dynamic" functionality is mostly yours to do.
If this is not the answer you were looking for, please speicify the reason for the delay and i'll try to answer your specific issue more accurately.
Let's assume that some action is performed when I click the button on a web-page. Let's say it takes X seconds and during these seconds a div is displayed in the center of the page. When action processing is finished the div is removed and focus goes to element E.
1) I've written a test in Selenium ( C# ):
stopwatch.Restart();
button.Click();
while (driver.FindElementsById(PopupDivId).Count != 0)
{
Thread.Sleep(10);
}
stopwatch.Stop();
2 ) And a test in javascript (inside my page). Simplified code:
OnClick button handler:
console.time('test');
GotFocus handler on textbox (element E):
console.log(document.getElementById('My_PopupDivId')); // just to be sure - it returns null
console.timeEnd('test');
For some reason Selenium measurements are ~2x bigger than direct javascript measurements.
(400ms vs 800ms).
Is this something wrong with my code or it's just Selenium inaccuracy ( does it actually make sense to measure such things as javascript/DOM performance using Selenium?)
John Koerner's comment is right on the money. You are comparing apples and oranges. Here are some factors affecting the difference:
Selenium uses a wire protocol to talk to your browser. It has to take your parameters, marshal them, send them to the browser, wait for a response, unmarshal the return value and give it to your code. That's in addition to whatever DOM operations are performed.
Your Selenium timing include the click operation as part of what is timed, whereas you start your JavaScript timing inside the event handler for the click. Selenium does some housekeeping work when you ask it to click on a button, like for instance check whether it is visible and bring it in to view if it is not visible. Your Selenium timing includes the cost of this, but your JavaScript timing does not.
Your Selenium code is subject to whatever implicit wait value is set. I don't typically use implicit wait but I've just tested it and found that if I ask Selenium for a list of elements, it will wait until the implicit wait has elapsed before telling me there are none.
To get a better idea of how much Selenium is affecting your results, you should try your test with different delays between the appearance of the div and its removal. I really doubt that a case where your JavaScript timing would yield 2 seconds would translate to a 4 second timing in Selenium.
As for using Selenium for performance measurements, I'd say Selenium is a very blunt tool for such task. When I'm worried about code performance in a browser, I skip Selenium and use JavaScript directly. I have used Selenium to get an idea about performance, in the aggregate. For instance, there's been times I reworked some core part of an application and then ran a test suite that uses Selenium and found the time to run the whole test suite significantly improved. However, as I said, this is blunt. We're talking seconds of difference, not milliseconds.
I am creating a live editor in Windows 8.1 App using JavaScript. Almost done with that, but the problem is whenever I run such bad loops or functions then it automatically hangs or exits.
I test it with a loop such as:( It just a example-user may write its loop in its own way..)
for(i=0;i<=50000;i++)
{
for(j=0;j<5000;j++){
$('body').append('hey I am a bug<br>');
}
}
I know that this is a worst condition for any app or browser to handle that kind of loop. So here I want that if user uses such a loop then how I handle it, to produce their output?
Or if its not possible to protect my app for that kind of loop, if it is dangerous to my app so I alert the user that:
Running this snippet may crash the app!
I have an idea to check the code by using regular expressions if code have something like for(i=0;i<=5000;i++) then the above alert will show, how to do a Regex for that?
Also able to include C# as back-end .
Unfortunately, without doing some deep and complex code analysis of the edited code, you'll not be able to fully prevent errant JavaScript that kills your application. You could use, for example, a library that builds an abstract syntax tree from JavaScript and not allow code execution if certain patterns are found. But, the number of patterns that could cause an infinite loop are large, so it would not be simple to find, and it's likely to not be robust enough.
In the for example, you could modify the code to be like this:
for(i=0;!timeout() && i<=50000;i++)
{
for(j=0;!timeout() && j<5000;j++){
$('body').append('hey I am a bug<br>');
}
}
I've "injected" a call to a function you'd write called timeout. In there, it would need to be able to detect whether the loop should be aborted because the script has been running too long.
But, that could have been written with a do-while, so that type of loop would need to be handled.
The example of using jQuery for example in a tight loop, and modifying the DOM means that solutions that trying to isolate the JavaScript into a Web Worker would be complex, as it's not allowed to manipulate the DOM directly. It can only send/receive "string" messages.
If you had used the XAML/C# WebView to host (and build) the JavaScript editor, you could have considered using an event that is raised called WebView.LongRunningScriptDetected. It is raised when a long running script is detected, providing the host the ability to kill the script before the entire application becomes unresponsive and is killed.
Unfortunately, this same event is not available in the x-ms-webview control which is available in a WinJS project.
I've got 2 solutions:
1.
My first solution would be defining a variable
startSeconds=new Date().getSeconds();.
Then, using regex, I'm inserting this piece of code inside the nested loop.
;if(startSecond < new Date().getSeconds())break;
So, what it does is each time the loop runs, it does two things:
Checks if startSecond is less than current seconds new Date().getSeconds();.
For example, startSecond may be 22. new Date().getSeconds() may return 24.Now, the if condition succeeds so it breaks the loop.
Mostly, a non dangerous loop should run for about 2 to 3 seconds
Small loops like for(var i=0;i<30;i++){} will run fully, but big loops will run for 3 to 4 seconds, which is perfectly ok.
My solution uses your own example of 50000*5000, but it doesn't crash!
Live demo:http://jsfiddle.net/nHqUj/4
2.
My second solution would be defining two variables start, max.
Max should be the maximum number of loops that you are willing to run. Example 1000.
Then, using regex, I'm inserting this piece of code inside the nested loop.
;start+=1;if(start>max)break;
So, what it does is each time the loop runs, it does two things:
Increments the value of start by 1.
Checks whether start is greater than the max. If yes, it breaks the loop.
This solution also uses your own example of 50000*5000, but it doesn't crash!
Updated demo:http://jsfiddle.net/nHqUj/3
Regex I'm using:(?:(for|while|do)\s*\([^\{\}]*\))\s*\{([^\{\}]+)\}
One idea, but not sure what is your editor is capable of..
If some how you can understand that this loop may cause problem(like if a loop is more than 200 times then its a issue) and for a loop like that from user if you can change the code to below to provide the output then it will not hang. But frankly not sure if it will work for you.
var j = 0;
var inter = setInterval( function(){
if( j<5000 ){
$('#test').append('hey I am a bug<br>');
++j;
} else {
clearInterval(inter);
}
}, 100 );
Perhaps inject timers around for loops and check time at the first line. Do this for every loop.
Regex: /for\([^{]*\)[\s]*{/
Example:
/for\([^{]*\)[\s]*{/.test("for(var i=0; i<length; i++){");
> true
Now, if you use replace and wrap the for in a grouping you can get the result you want.
var code = "for(var i=0; i<length; i++){",
testRegex = /(?:for\([^{]*\)[\s]*{)/g,
matchReplace = "var timeStarted = new Date().getTime();" +
"$1" +
"if (new Date().getTime() - timeStarted > maxPossibleTime) {" +
"return; // do something here" +
"}";
code.replace(textRegex, matchReplace);
You cannot find what user is trying to do with a simple regex. Lets say, the user writes his code like...
for(i=0;i<=5;i++)
{
for(j=0;j<=5;j++){
if(j>=3){
i = i * 5000;
j = j * 5000;
}
$('body').append('hey I am a bug<br>');
}
}
Then with a simple regex you cannot avoid this. Because the value of i is increased after a time period. So the best way to solve the problem is to have a benchmark. Say, your app hangs after continuos processing of 3 minutes(Assume, until your app hits 3 minutes of processing time, its running fine). Then, whatever the code the user tries to run, you just start a timer before the process and if the process takes more than 2.5 minutes, then you just kill that process in your app and raise a popup to the user saying 'Running this snippet may crash the app!'... By doing this way you dont even need a regex or to verify users code if it is bad...
Try this... Might help... Cheers!!!
Let's assume you are doing this in the window context and not in a worker. Put a function called rocketChair in every single inner loop. This function is simple. It increments a global counter and checks the value against a global ceiling. When the ceiling is reached rocketChair summarily throws "eject from perilous code". At this time you can also save to a global state variable any state you wish to preserve.
Wrap your entire app in a single try catch block and when rocket chair ejects you can save the day like the hero you are.