UI Automation - Self Healing Agent - java

I am doing UI automation in Selenium-Java where I am recognising object/element based on XPATH or CSS selector. Due to many unwanted reason - tests are getting failed due to change in XPATH at different environment.
I thought to write a utility script which will identify and auto-generate robust and simple XPaths.
Is there a way - I can make this happen at run time to self heal my existing Selenium-Java automation scripts.

It's not possible to recognize the elements that should get their xpath regenerated without specifying somehow what those elements are.
It's easy for humans to know which one is the "sign up" button, for example, even if its label, style or position changes, since people can use other context clues to guess which button is meant by "the sign up button". Implementing these context clues for a computer would require quite a lot of effort, especially for more obscure type of elements.
I would stick to spending some time and human thought to figure out the most robust locator for each element. (For a sign up button I'd say it's often the value of the href attribute.)
Maybe you could even specify multiple different locators per element. Then implement the search so that the locator that first matches a single element is used and fail only if all specified locators fail. That could decrease the frequency with which a person has to be fixing the tests. Or it could have the opposite effect :)
One more idea: if you can use version control to get the last version that some specific selector still worked, maybe you could try finding the most similar element in the new version and regenerating the xpath for that.

Related

Update the Code if there is any change noticed in the xpath with the new xpath during run time without failing the script

while running the script, when the code finds the xpath is changed.
Is there any way to update the xpath automatically during run time and proceed with the next steps without fail.
John, I think what you're asking is "how do I implement a crystal ball that foresees changes in HTML and auto-adapts to them".
The answer is - you don't, the best realistic way is to talk to developers to implement sensible IDs and classes on every important element and ask them to communicate changes before you run your tests, see them break and wonder what happened.
If your a dev yourself and you try to practice TDD, then:
1) implement a failing test with a dummy Xpath, see it fail
2) implement the UI
3) Update the Xpath in your test, run, see the test pass

Persistent background checking with Selenium

First time poster, long time lurker. I've gotten a lot of great advice to problems from this site, but I haven't found anything here for the topic of this question. Normally I would bug our SME at the office but he's indisposed.
So, we use Selenium Web Driver to do automated tests. I'm working on an application with some mapping and demographics features, so my tests are very function vs. form oriented.
My tests are written such that I have classes/methods that are a part of the puzzle (the site is essentially one workflow where you go from page 1 to page 5 and the same actions need to be performed in steps 2-3, for example, but test A might do something different on page 4 to see the result in page 5. Clear as mud?
Anyways, during manual tests, I can sometimes see an error message pop up on the site (a hidden div that will become visible if it detects an error, but it's usually a very generic/vague error). This error sometimes pops up even if you're able to go through the flow with no other ill-effects. However, I want to capture when these errors happen so I can look for patterns - if this means just logging it to console or failing the test...I can figure that out later.
The immediate problem is having a persistent check in place that will always look for this error during every test. I could create a method and call it in my "action" methods, though this would leave gaps and slow the tests down. Is there any clever way of implementing something like this without slowing the tests down or calling this check every time I do a step in the process? Also, forgive me, I'm still learning Java and the selenium web driver, so if I've said anything stupid, that's why.
Since this message is persistent if it is there, you might try adding a check for it in your test case teardown method. (I would recommend that you reduce the implicit wait time before you do that check, though, otherwise each test will take an extra amount of time waiting for an error message that isn't there.)
Another possible option is to define your own listener on your own test runner and update the testFinished() method to go check for your error message. See this for some ideas.
Since it sounds like the error messages are always in known locations on each page, I would create a method (or methods, depending on how many error message locations there are on a given page) that looks to see if an error exists and then log it before leaving the page. It sounds like you might be using the page object model. If so, you can add these methods to the each relevant page object for easy access.
NOTE: Checking for errors once before you leave the page may not be enough. You may need to check each time you do some action that might cause an error. This is probably not a bad practice anyway because it will help in debugging errors because you will notice an error closer to the time it was triggered, thus narrowing down what caused the error.
If you have the ability, do something like log it as a warning so that it doesn't fail your test but stands out (and is searchable) in your logs.
You seem concerned that checking for all these errors will significantly slow your script. If properly written, it shouldn't add a significant delay. One significant delay you might run into is if you have implicit waits turned on and are checking for elements that don't exist (e.g., unless there's an error). This will cause the implicit wait to be applied each time you search for the missing element and will likely add significant time to the run time. My suggestion is to turn off implicit waits and add explicit waits only where needed. Searching for any element will add some time but 25ms here and there should be negligible in an overall script run.
Have you tried using EventFiringWebDriver?
There is an answer here on what it does:
What is EventFiringWebDriver in selenium?
Newer selenium versions have more types of events present in the interface, which can broaden its use on these types of tests.

Choosing between multiple ways to set GWT element IDs

As far as I can tell, there are two ways to set the IDs for web elements from within GWT. I need to perform Selenium automated testing, and would appreciate insight into the relative advantages of each technique.
Option 1: the generally accepted method
uiObject.ensureDebugId("idForMyElement");
This solution is well documented, and officially supported by google. However it comes with some disadvantages:
My team will have to add lines to every package's gwt.xml file like so:
<inherits name='com.google.gwt.user.Debug' />
Furthermore, the Debug class prepends "gwt-debug" to IDs by default. I realize I can change this behavior, but I don't like adding complexity where I can help it.
Option 2: use a generic setAttribute call
uiObject.getElement().setAttribute("id", "idForMyElement);
This seems cleaner to me- are there any downsides I might be overlooking?
Relevant resources:
How can I set id for GWT widgets in UiBinder?
https://code.google.com/p/google-web-toolkit/issues/detail?id=4176
The first option is better because you can compile out debug ids from your production code, making it smaller.
With the second option ids will be there even when you don't need them anymore.

Selenium 2 : finding web element locators programmatically

I am tired of manually finding locators (id,xpath,css,linkText etc..) for web elements from my web page source. It also consumes more efforts. So, to avoid that I want to write a code that interacts with page source directly and generates locators details (e.g. id="xyz" , xpath ="html/body/table/tr/td/a" etc.)
To achieve this ,I think I can generate ID locator by using split() function of String object. But, what I don't know is how to generate xpaths, css and linkText locators for all page components?
Although I'd generally recommend to construct XPath expressions on your own (as you can better exploit things to mach against like class attributes), probably the most reasonable and convenient automatic way to determine XPath expressions for selenium is to use either Firebug's or Chrome Developer Tool's "Find XPath" feature. They both at least use #id attributes to shorten XPath expressions.
If you want to write some code yourself, eg. for embedding in other tools you use, you might want to have a look at the answers of "PHP XML - Find out the path to a known value" which solves the problem in PHP, or another one with answers for Javascript: "Javascript get XPath of a node".
If you're using any tools not working on the DOM (Selenium/Firebug/Chrome Dev' Tools/JavaScript will do), watch out for the problems I described in "Why does my XPath query (scraping HTML tables) only work in Firebug, but not the application I'm developing?".
There are (at present) no "tools" that do even a marginally decent job of synthesizing reliable and concise xpath or css based locators. I've been writing selenium and HTML/CSS code for nearly the duration of the industry, and the so-called CASE-methods that purport to do this job better than humans produces laughably flawed output more often that it generates useful material. However, I would add a codicil: there is hope.
By taking careful stock of the various XPath and CSS methods (see http://www.w3schools.com/xpath/xpath_axes.asp for some general guidelines) and using only the most minimal locator strings that will pass muster in Firebug, Selenium IDE and other similar plug-ins, one can progress gradually towards a better approach. In general one should (where possible) use only one component from an object's attribute list and avoid using dynamically defined quantities. Best practices would encourage picking class, name or id only if they are "immutable".
Mutability is a tricky issue: simply dragging a cursor over an object or clicking on it may change the class or css characteristics. Sometimes this can be surmounted by using only the "fixed" portion of the offending attribute. For example, a class might initially be 'tabContent', but when the cursor is placed over the corresponding object it might change to 'tabContentMouseOver'. You get the idea. By using an xpath locator string //*[contains(#class,'tabContent')] you stand a better than even chance of hitting the desired object, irrespective of whether it is clicked, highlighted, or even disabled.
The next "trick" I'd encourage you to consider is using the "buddy" principle; many objects (button-like ones in particular) nowadays consist of an image with no dynamic properties wrapped by a div that manages its event-driven behavior. For such situations you might find that //div[#eventproxy='tabObject']/following::img[contains(#src,'tabImage') and text()='Contents'] or something similar will cover all the bases. Contents will vary with your situation of course.
Make vigorous use of the hierarchical axes methods ('following' is one I use quite often), but only where necessary; sometimes '//' will suffice instead.
Penalize yourself for every unnecessary character, and reward yourself for methods which are concise and can weather frequent and severe code changes. Above all, persevere.
In general I avoid using "pure" CSS locators for the following reason -- they were never intended as locators. "Cascading Style Sheets" by their very nature are designed to impact the maximum number of web objects possible, and are very rarely unique to any one piece of content. Web-coders are notorious for changing these on the fly to produce spiffy new effects or restructure content to suit customer demands; why hitch your tests to content that is known to fluctuate? Besides, everything CSS can do (and I do mean EVERYTHING) can also be done inside XPaths if you so choose.
The canard about XPaths being "slower" than CSS methods I believe has been disproved often enough that it should be taken with several tablespoons of salt. Still, if you really feel more comfortable with CSS techniques, go for it! Experience will educate you better than any blurb you find in stackoverflow ever will.

JSP internationalization RTL/LTR

I want to create a web site which can be viewed with two languages, one LTR and one RTL. This means that all content should be shown in either of the two languages.
My framework is Spring, and I'm using Tiles2, but I think this question is not framework specific.
The obvious solution to supporting two languages is having everything doubled (all JSP's, fragments, etc.), and you get the part of the tree which fits the language you chose. But this causes problems when changing the web site (you might forget to update the other JSP's), and is not scalable (try doing this for 5 or 10 languages).
I know I can use properties files to host strings for the different languages, but then my web site would be a huge collection of spring:message tags and will be a lot harder to maintain (what happens if I have a paragraph of 100 lines, does this all go into a single properties line?)
Is there any kind of framework, plugin, other, which solves this problem? Has anyone come across a clever solution to this problem?
I've never realized a complete project, just some tests. I think this problem is not so big as it seems if you follow some simple rules. Here is what I would try to do:
Specify direction with <body dir='ltr/rtl'>. This is preferred versus CSS direction attribute.
Avoid different left/right margins or paddings in all CSS. If you must break this rule, probably you'll need to use two different files (ltr.css and rtl.css) containing all these different elements.
Sometimes you'll need to move some elements from left to right or vice versa. For example, in LTR you want a menu on the left, but in RTL you want it on the right. You can achieve this using CSS, but this sometimes is complicated if you are not an expert and you must test it in all browsers. Another option is to use some IF depending on the case. This last option will fit very well if you use a grid based CSS library, like Bootstrap.
Choose carefully which CSS and JS libraries you'll use. Obviously, pick the ones which offer RTL/LTR support.
Don't worry too much about the images. If you must change one image depending on the language is probably because it has some text in it. So, you must use different images anyway. This is a problem related to i18n, not a text direction issue.
Don't let your customer to be too much fussy about it. I think that with these rules (and maybe some more) you can get a good result. But if your customer starts complaining about one pixel here and another one there, you'll need to complicate all this and probably is not necessary.
About your language properties file. Yes, use them. Always. This is a good practice even when you are only using one language: HTML structure is separated from content, is very easy to correct or translate, some words or sentences are in only one file...
Usually, web frameworks are used to build web applications rather than web sites, and there are quite few long static paragraphs. Most of the content is dynamic and comes from a database. But yes, the usual way of doing is to externalize everything to resource bundles, usually in the form of properties files.
Putting a long paragraph in a properties file doesn't cause much problem, because you can break long paragraphs into multiple lines by ending each line by a backslash:
home.welcomeParagraph=This is a long \
paragraph splitted into several lines \
thanks to backslashes.
RTL and LTR is one of the upper and more difficult i18n problems.
Basically its a Problem of the view-scope of the MVC-Model. This may also includes pictures and emotional differences like the color of the skin of people. In this case you better abadon to the solution HTML+CSS gives you.
In example:
<style type="text/css">
*:lang(ar) { direction:rtl }
*:lang(de) { direction:ltr }
</style>
The best practice is to ask members of the audience-group about what effect the webpages have to them.
I agree to most of solutions provided here. Your problem is more design (architecturally) oriented rather than technical. You need to choose path whether you need to keep this logic of internationalization on server (java) side or in static files.
In case you want to go for java side (preferable solution), you need to keep two properties file and use jstl tags. This minimizes your work in case you want to add another language in future. This is maintainable solution. I have seen applications supporting more than 15 languages and time zones. In fact release process gets pretty easy.
In case you want to go for keeping multiple css and other static files, you will soon find things running out of your hands pretty soon. I dont think this is a maintainable solution.
Said all this, I will leave this choice to the architect of application. He will be able to judge which way to go based upon the nature of application and constraints given to him.
You don't want to use everywhere. That's a pity because it is just the way you should do it. It is a bad practice to keep hard-coded texts in a jsp if you need internationalization.
Furthermore, Most of the modern IDE allows you to go to the variable declaration by doing ctrl+left click (or hovering the key) so that having a lot of variables in your code should not be a problem for maintenance.
First, you must distinguish, for each text element, whether it is a user interface element (e.g. button label) or redactionnal content.
user interface element labels will be stored in properties file that will have to be translated for each supported language (and provide a default value as a fall back)
redactionnal content will be stored in a content management system that you will organize in order to find easily a localized version of your content

Categories