Check if "Please enter an email address" message appears - selenium

Given a simple page:
<form>
<input type="email">
<button>click</button>
</form>
If I enter anything in text field that is not e-mail and click the button, Please enter an email address message appears.
Is there a way to to check if the message appears using Selenium or Watir? As far as I see, nothing new appears in browser DOM.
Since the page is using e-mail check that is built in feature of a browser, does it even make sense to check that error message appears? It is at the same level as checking if browser scroll bar works. We are no longer checking the web application, but the platform (browser).
An earlier related question here on SO is: How do I test error conditions in HTML5 pages with cucumber?

I'd agree that this is starting to get close to 'testing the browser', otoh if your code depends on that browser feature, then the site needs to produce the proper html(5) code so that the browser knows you want that level of validation, and that is something you can validate.
Some good background on this at art of the web
The browser side validation is triggered by the combination of the specific input type (which you could check via watir's .type method) and the new required attribute (which might be tricker to check) Given this I think I actually see a pretty good cause here for a new feature in Watir. I'm thinking we could use a .required? method which should be supported for all input elements which support the new 'required' attribute, and would return true if that 'required' attribute is present.
So at the moment what you could do is if you know you are running on an HTML5 browser that supports this feature, you could both check that the input type is 'email' and also that the 'required' attribute is there. (I don't offhand have an idea for how to do that, but perhaps someone else can suggest a way).
The other thing to be sure of would be to provide an invalid value, and make sure that the form will not allow itself to be submitted. e.g. is the validation enforced, or merely advisory. (and don't forget to check the server side by submitting invalid data anyway using something like curl or httparty, since a hostile user could easily bypass any inbrowser validation and submit that form with bogus or even 'hostile' values designed to cause a buffer overflow or injection attack. No site should depend exclusively on client side validation.)
The other thing to consider of course is what if the user is on a browser that does NOT support that particular validation feature, what does the page do then? I'd presume some kind of client side javascript and a message that is displayed.
In that case it really depends on the way in which the message is made to 'appear'. In the app I am testing, messages of that sort happen to be in a handy divs with unique classes which are controlled by css to normally be hidden, and then set to displayed when the client side JS detects the need to display a message for the user. So of course I have tests for stuff like that. Here's an example of one for someone agreeing to our terms and conditions. (Note: we use Cucumber, and the Test-Factory gem to do page objects and data objects)
Lets start with the message, and what right-click.examine-element reveals
The scenario on the grower_selfregister.feature file looks like this
Scenario: self registering grower is required to agree to terms and conditions
Given I am a unregistered grower visiting www.climate.com
When I try to self-register without agreeing to the terms and conditions
Then I am informed that Acceptance of the terms and conditions is required
And I remain on the register page
The critical Cucumber steps are:
When /^I try to self-register without agreeing to the terms and conditions$/ do
#my_user.self_register(:agree_to_terms => FALSE)
end
Then /^I am informed that Acceptance of the terms and conditions is required$/ do
on Register do |page|
page.agree_to_terms_required_message.should be_visible
end
end
Then /^I remain on the register page$/ do
  on Register do |page|
    #ToDo change this to checking the page title (or have the page object do it) once we get titles
    page.url.should == "#{$test_site}/preso/register.html"
  end
end
The relevant portions of the register.rb page object are
class Register < BasePage
#bunch of other element definitions removed for brevity
element(:agree_to_terms_required_message) {|b|b.div(:class => "terms-error")}
end
Does that help provide an example?
Note: it could easily be argued that the second validation (staying on the page) is redundant since I'm unlikely to see the message if I'm not still on the page. But it adds clarity to the expected user experience described in the scenario Also, it could be very important if the implemntation where to change, for example if it was decided to use something like an javascript alert, then it may well be important to validate that once dismissed (something the "I see the message" step would likely do) the user did not proceed into the site anyway.

You could try like this
JavascriptExecutor js = (JavascriptExecutor) driver;
driver.findElement(By.cssSelector("input[type='email']")).sendKeys("asd");
Object s=js.executeScript("return document.getElementById(\"a\").validity.valid");
System.out.println(s);
driver.findElement(By.cssSelector("input[type='email']")).sendKeys("asd#gmail.com");
s=js.executeScript("return document.getElementById(\"a\").validity.valid");
System.out.println(s);
Output for above line is
false
true
So based on that you can conclude that whether the given value is valid or not.
Below javascript logic will return true/false based on the validity of the field
document.getElementById(\"a\").validity.valid
P.s : I assume input tag has id "a"

I haven't found a way to check for the actual error message. However, you can check that the input field is invalid after entering a non-email, using the :invalid CSS pseudo-selector.
WebElement invalidInput = driver.findElement(By.cssSelector("input:invalid"));
assertThat(invalidInput.isDisplayed(), is(true));

Related

Best way to automate a page and check if it is loaded correctly

I am looking to verify if this page loads correctly - http://www2.hm.com/en_ca/women.html
These are the things I think it would be best to verify if the page is loaded correctly, please let me know if I am missing anything
1) Verify all the links on this page works?
2) Verify if the menu on the top is loaded correctly, Do I need to verify the menu names?
3) Check if the classes are loaded properly?
4) get/post request status 200 and other ajax calls?
As per your question a seperate test to check if the page is loaded correctly will be a complete overhead because the Client (i.e. the Web Browser) will never return the Execution Control back to the WebDriver instance until and unless 'document.readyState' is equal to "complete". Once this condition is fulfilled Selenium performs the next line of code.
You can find a detailed discussion on this topic in Selenium IE WebDriver only works while debugging
Next as you want to Verify if all the links on this page works or not , you can write a function() and invoke the function() whereever required.
Moving on to next question, there is no necessity to Verify if the menu on the top is loaded correctly or not as you can't test each and every aspect of each and every WebElement present on a WebPage. The best approach would be to verify and validate the attributes of only those elements with whom we need to interact.
Again Checking if the classes are loaded properly will be a overhead as JVM takes care of it in the best possible way.
Finally, to validate get/post request status 200 you have to write Tests as per your requirement.

dojo load js script and then execute it

I am trying to load a template with xhr and then append it to the page in some div.
the problem is that the page loads the script but doesn't execute it.
the only solution I got is to add some flags in the page (say: "Splitter"), before the splitter, I put the js code, and after the splitter I add the html code, and when getting the template by ajax, I split it. here is an example:
the data I request by ajax is:
//js code:
work_types = <?php echo $work_types; ?>; //json data
<!-- Splitter -->
html code:
<div id="work_types_container"></div>
so the callback returns 'data' which I simply split and exeute like this:
data = data.split("<!-- Splitter -->");
dojo.query("#some_div").append(data[1]); //html part
eval(data[0]); //js part
Although this works for me, but it doesn't seem so professional!
is there another way in dojo to make it work?
If you're using Dojo, it might be worth to look at the dojox/layout/ContentPane module (reference guide). It's quite similar to the dijit/layout/ContentPane variant but with one special extension, that it allows executing the JavaScript on that page (using eval()).
So if you don't want to do all that work by yourself, you could do something like:
<div data-dojo-type="dojox/layout/ContentPane" data-dojo-props="href: myXhrUrl, executeScripts: true"></div>
If you're concerned about it being a DojoX module (DojoX will disappear in Dojo 2.0), the module is labeled as maintained, so it has a higher chance of being integrated in dijit in later versions.
As an anwer to your eval() safety question (in comments). Well, it's allowed of course, else they wouldn't have such a function called eval(). But indeed, it's less secure, the reason for this is that the client in fact trusts the server and executes everything the server sends to the client.
Normally, there are no problems unless the server sends malicious content (this could be due to an issue on your server or man in the middle attacks) which will be executed and thus, causing an XSS vulnerability.
In the ideal world the server only sends data and the client interpretes this data and renders it by himself. In this design, the client only trusts data from the server, so no malicious logic can be executed (so there will be no XSS vulnerability).
It's unlikely that it will happen and the ideal world solution is not even possible in many cases since the initial page request (loading your webpage) is in fact a similar scenario where the client executes whatever the server sends.
Web application security is not about being 100% safe (it's impossible), but it's to try to create as less as possible open doors that can be used by hackers. It's up to you what you consider safe and to verify if the "ideal world" solution is possible in this specific scenario (it might not be, or it might take too much time compared to the other solution).

Validations using simple_form: validated object lost after hitting create

We have a form created by several controllers's new actions, which we reuse via render :new in the create action to display validation error messages. I believe this is the way to go for simple_form and validations. Correct me, if I'm wrong here.
We also have a general language switching mechanic, that redirects to the current_url, with a different locale.
The problem:
After a failed validation and the second rendering of the new form, the language selection throws an error (which would be very misleading to post here). The problem is that the create action expects the validated object, which our language selection does not pass to the current url again.
How would you tackle this problem?
We could try to teach our language switcher about "create" and have it send another post request with the same params, but this seems awful. There would have to be a lot of logic in our little helper and where would we store the objects (at least one kind of them is not persisted at all)?
Someone mentioned (ab-)using a flash message to recreate the object, but it's a huge form with up to 50 validations and this get's uglier with size, I guess.
Storing the object in the session in these cases and have the helper post the object again, if it exists might work. I like this one the most, but it's far from feeling right as well.
We could try to have simple_form use the "new" action instead of just rendering "new", but this seems really bad.
We could disable language switching for create actions altogether, with an alert saying this one step has to be finished in the chosen language.
Do you have any opinions, other suggestions? I'd be very grateful.
Thanks,
Andy
So we changed the language helper to send the same post request again, if it is on a page created by a POST. It ended up looking like this. Not a lot of code added:
def language_link(language)
url_options = { locale: language }
if request.request_method == 'POST'
link_to(language, url_for(params.merge(url_options)), method: :post)
else
link_to(language, url_for(url_options))
end
end
We were carefully making sure we don't end up sending valid data a second time. Creating a second payment, or a second order would be quite bad here for example. We need to keep this in mind in the future as well, when we're creating new post routes accessible on a part of our application where language is changeable. That's the main problem here.
It does not consider PUT requests now because we don't have any edit/update functionality on the part of the app where language is selectable.
We can live with this version in our code. So I post this as an answer. But I'd still be happy to see a better (less dangerous) version, our any thoughts on this at all.
Cheers,
Andy

Java Server Side Error message validation without actually submitting an application

I am trying to create a testing application to validate server side error messages. Right now our framework is such that each time a incorrect value is entered in a field and the submit button is clicked and on submission, the error message displayed on the page is captured.
Is there anyway I can bypass this technique, such that the validation happens only in the server side and is passed back to the client side, without having to reload the page each time.
Any other ideas would be much appreciated. Please try to ignore the lameness of the question :( I'm just starting off and wanted to try something new to reduce the time taken to capture the error messages.
Thanks a lot..!!
Use AJAX, Luke!
There are a lot of options to do this. You may use jQuery.ajax for sending your form data to some validation servlet. Or you may use JSF for it. It largely depends on your framework and/or architecture of your application.

How can I pass data to the success callback of an ExtJS-based AJAX file upload?

So, I've read a lot about using ExtJS's fileuploadfield to submit a form via an IFRAME. I understand that I'm supposed to reply with a JSON object indicating success or failure; fine. What I want to know is, how can I get more information back to the calling code? I don't want to simple send a file and say "yup, that worked fine" -- I want to submit a document, act on it, and return a result.
Say I have the user upload an XML document -- I might want to do a lookup or conversion based on it and update the contents of a form on my page accordingly. Is this even possible? I'd strongly prefer to avoid involving Flash or embedded applets if at all possible. If need be, I could even restrict this behavior to HTML5-compliant browsers...
I honestly thought I wasn't seeing the response I sent, but it was a server-side error. My success callback is now firing, with the full text of my server's response available as f.responseText (where f is the first argument to the success callback). My mistake!