I am a beginner in Selenium. I wanted to know how I can verify the URL against the keyword I entered in the search bar.
The search page url is https://catalog-mytest.com/search?
When I entered redcar in the search bar and hit enter, the url becomes https://catalog-mytest.com/search?keywords=redcar
Could you guide me on how to write a piece of code that would verify the URL with the keywords? thank you.
There can be two approaches-
Approach-1:
String url = Driver.getCurrentUrl();
boolean passed = url.contains("your keyword here");
if (passed) {
System.out.println("Test Passed");
} else {
System.out.println("Test Failed");
Assert.fail("This message will be printed in stacktrace if the assertion fails.");
}
This is the simplest way of doing this.
Approach-2:
String keyword = Driver.getCurrentUrl().split("?")[1].split("=")[1];
boolean passed = keyword.equals("your keyword here");
if (passed) {
System.out.println("Test Passed");
} else {
System.out.println("Test Failed");
Assert.fail("This message will be printed in stacktrace if the assertion fails.");
}
This approach can be error prone, if the URL does not always contain
?, = in it then the test can fail with
ArrayIndexOutOfBoundsException
Related
I have written a code to connect to this webpage: compilerjava.net
1) I found the text-area field within that page which accepts the code to compile.
2) I have found the button that compiles the code.
3) I have found the text-area which returns the result of the code.
The issue is, when I call textarea.setText( "something"), it (I think) doesn't actually change the code in the webpage. So when I click on the compile button, it compiles the default code within that page and returns the output of that default code.
I have tried to set focus to textarea, you can see all of those down below.
I called;
1) textArea.focus();
2) textArea.click();
3) I tried using textArea.setAttribute( "name", "code");
I have searched the internet and found various stackoverflow questions close to this problem, neither of them solved my issue and it just seems to work for everyone when they say textArea.setText().
Another interesting fact I should share with you is,
If I call textArea.setText( "...") and then I say;
HtmlTextArea textArea1 = form.getTextAreaByName( "code");
If I call textArea1.getText(), the value of this text will be "...". This should imply that I have actually managed to change the value of the text-area, but when I compile, it compiles the default text in the text-area and not the text that I have set it to.
Any help with this?
P.S: The reason why I put the result of the compilation on a while loop is related to network connection issues. If you try to run this code it might not work on your first try. Also note that the run-time is around 15 seconds, because it gives thousands of warnings which I blocked to print to console.
P.S2: I also looked at this page and none of these worked;
http://www.programcreek.com/java-api-examples/index.php?api=com.gargoylesoftware.htmlunit.html.HtmlTextArea
public class Test {
public static void main(String[] args) {
try {
// Prevents the program to print thousands of warning codes.
java.util.logging.Logger.getLogger("com.gargoylesoftware").setLevel(java.util.logging.Level.OFF);
java.util.logging.Logger.getLogger("org.apache.http").setLevel(java.util.logging.Level.OFF);
// Initializes the web client and yet again stops some warning codes.
WebClient webClient = new WebClient( BrowserVersion.CHROME);
webClient.getOptions().setThrowExceptionOnFailingStatusCode( false);
webClient.getOptions().setThrowExceptionOnScriptError( false);
webClient.getOptions().setJavaScriptEnabled( true);
webClient.getOptions().setCssEnabled( true);
// Gets the html page, which is the online compiler I'm using.
HtmlPage page = webClient.getPage("https://www.compilejava.net/");
// Succesfully finds the form which has the required buttons etc.
List<HtmlForm> forms = page.getForms();
HtmlForm form = forms.get( 0);
// Finds the textarea which will hold the code.
HtmlTextArea textArea = form.getTextAreaByName( "code");
// Finds the textarea which will hold the result of the compilation.
HtmlTextArea resultArea = page.getHtmlElementById( "execsout");
// Finds the compile button.
HtmlButtonInput button = form.getInputByName( "compile");
textArea.click();
textArea.focus();
// Simple code to run.
textArea.setDefaultValue( "public class HelloWorld\n" +
"{\n" +
" // arguments are passed using the text field below this editor\n" +
" public static void main(String[] args)\n" +
" {\n" +
" System.out.print( \"Hello\");\n" +
" }\n" +
"}");
System.out.println( textArea.getText());
// Compiles.
button.click();
// Result of the compilation.
String str = resultArea.getText();
while ( resultArea.getText() == null || resultArea.getText().substring(0, 3).equals( "exe")) {
System.out.print( resultArea.getText());
}
System.out.println();
System.out.println( resultArea.getText());
} catch ( Exception e) {
e.printStackTrace();
}
}
}
a little patience helps here
// Result of the compilation.
while (resultArea.getText() == null || resultArea.getText().startsWith("exe")) {
System.out.println(resultArea.getText());
Thread.sleep(500);
}
System.out.println();
System.out.println(resultArea.getText());
I have made a REST client-server, and everything works more or less fine. Here is the dilemma: I have an option to retrieve user by its username, which works fine when the user actually exists. However, when he doesn't, i get 204 http code, which is fine, since I made a null return. I would like my method to return a plain string to client console when no user is found, say, "No such user found...", but the method return type is User (class) logically, to return a user object when such is found.
Here is the server side:
#GET
#Path("/{uName}")
#Produces({ "application/json", "application/xml"})
public User getUserByUsername(#PathParam("uName") String uName) {
returnAll = usrList.getUsers();
for (User u : returnAll) {
if (u.getUserName().equals(uName))
return u;
}
return null;
}
And here is the relevant part of client:
case 3:
sc.nextLine();
System.out.println("Enter username");
userName = sc.nextLine();
restConnect("http://localhost:8080/rest/user/"
+ userName, "GET");
promptKey();
Changing a method to return a String type would obviously disrupt the code when user is actually found. What can I do to make two type return function? Thanks
EDIT:
When user was found, my method would return the first user in list with get(0) which is wrong. It was a residue of me testing something with the ID's
EDITx2: working client
case 3:
sc.nextLine();
System.out.println("Enter username");
userName = sc.nextLine();
try{
restConnect("http://localhost:8080/rest/user/"
+ URLEncoder.encode(userName, "UTF-8"), "GET");
}
catch(RuntimeException e){
System.out.println("No such user...");
}
promptKey();
Your code should be returning a 4xx error when the user does not exist and the client should have a branch when an error is returned.
Think about how things should work for a client that you did not develop yourself and the definition of the API will probably be more clear.
See http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html for additional result code details.
EDIT: Alex Martelli Gave me a great answer which I changed only slightly in order to get working properly for me
The answer to this problem for me was
public boolean Login2(String usernamein, String passwordin) {
DatastoreService datastore = DatastoreServiceFactory
.getDatastoreService();
Filter usernamefilter = new FilterPredicate("username",
FilterOperator.EQUAL, usernamein);
Query validuserquery = new Query("Users").setFilter(usernamefilter)
.setKeysOnly();
Entity theUser = datastore.prepare(validuserquery).asSingleEntity();
if (theUser == null) {
System.out.println("Username not found");
return false;
}
return true;
}
End of EDIT
Original Post
Okay so I have spent the entire day trying to do this and have tried my best to research it but I can't do it! :(
I feel like there is probably and easy answer but I can't work it out, I feel like I have tried Everything! please please please help D:
I have a Login section of code on its own .jsp page called Index.jsp
String username = "";
String password = "";
try {
if (request.getParameter("usernamein") != null && request.getParameter("passwordin") != null) {
username = (request.getParameter("usernamein"));
password = request.getParameter("passwordin");
if(login.Login2(username, password)){
response.sendRedirect("Race.jsp");
System.out.println("go to next page");
} else {//need username/password
out.println("your username or password is incorrect");
}
}
} catch (Exception e) {
out.println("problem in getting u an p error =" + e);
}
Part way through that code is the line (login.Login2(username, password))
that code calls a method in a class using java use bean thingy
the method it calls is this:
public boolean Login2(String usernamein, String passwordin) {
DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
Filter usernamefilter = new FilterPredicate("username", FilterOperator.EQUAL, usernamein);
Query validuserquery = new Query("Users");
validuserquery.addProjection(new PropertyProjection("username", null));
System.out.println(validuserquery);
List<Entity> list = datastore.prepare(validuserquery).asList(FetchOptions.Builder.withLimit(100));
System.out.println(list);
for (Entity username : list){
System.out.println("username is equal to '"+username+"'");
if(username.equals(usernamein)){
return true;
}else
System.out.println("was not equal");
return false;
}
return false;
}
I'm trying to only go to the next page in the top code if the if statement is true, meaning that the username does exist, eventually I want it to only go to then next page if the username and password are both in the same entity i.e. the combination exists.
I hope you guys understand what i am trying to do and can help me
oh the System.out.println() for the username value outputs this:
username is equal to '<Entity [user("id")/Users(5910974510923776)]:
username = RawValue [value=[B#187c4d7]
>
'
If you need any more info just ask and i'll add it to the post :D ty
You would be best advised to query the datastore for just the username of interest...:
Query validuserquery = new Query("Users").
setFilter(new Query.FilterPredicate("username",
Query.FilterOperator.EQUAL,
usernamein)
).setKeysOnly();
Entity anyentity = datastore.prepare(validuserquery).asSingleEntity();
if(anyentity == null) {
System.out.println("was not equal");
return false;
}
return true;
This assumes there are no entities with duplicated username in your store (though you could deal with that by catching exception PreparedQuery.TooManyResultsException -- if that gets raised, it means you have more than one entity with that username, so that would be a return true case too:-).
The core idea is: getting every user entity and checking their usernames in your application code is really wasteful of resources (quite apart from the bugs in your code in this case) -- use queries to get only the relevant entity or entities, if any!-)
Try searching a bit more next time. It's not that hard, your issue was pretty easy. In any case :
Your query returns a full object, not just properties of your object. You need to do
entity.getProperty("username")
So that you see your property, not the full object.
More info here.
The program checks to see if the email address entered contains a # and a .edu
if it doesn't it needs to go back through the steps, I think I can use a do-while,but I haven't got one to work yet, how would I nest my if-else statements in a do-while? Thanks!
if (UserEmail.contains("#")) {
if (UserEmail.contains(".edu")){
System.out.print("Please create a password: ");
PassWord = kb.nextLine();
System.out.println(UserEmail.replaceAll("#\\S+?\\.edu\\b", ""));
System.out.print("Your password is " + PassWord);
} else {
System.out.print("email is not valid Please, try again.")
} else {
System.out.print("email is not valid Please, try again.");
// at this point it should repeat and ask for the email again
}
}
Define method isValid(String email, String password,... some more params) aand put all your check logic in the method.
Write something like this
while (!isValid(the params)) {
//ask all the credentials
}
to simplify your if-else code consider using
if (UserEmail.contains("#") && UserEmail.contains(".edu")) {
.
.
}
this can be wrappped in a do - while
do {
if (UserEmail.contains("#") && UserEmail.contains(".edu")) {
.
.
break;
}
System.out.print("email is not valid Please, try again.")
}
while (true);
You can simply add something like boolean correctEmail = false before your logic and at the beginning of your if statements, you write while(!correctEmail) {
At the end of your password-creation you set correctEmail to true and you're ready to go.
It is pretty straight forward.
bool trigger = (true/false);
do {
if (...) {
if (...){...}
else if (...) {...}
else {
print out retry statement;
trigger = false;
}
}
}
while (trigger == true);
Don't forget a semicolon at the end.
I use Selenium WebDriver in Eclipse.
I write method to check if title is displayed correctly. Here is the code:
class Check {
String text_to_found;
String reason;
Check (String t, String r) {
text_to_found=t;
reason=r;
}
public void check_title() {
try {
Assert.assertTrue("Title " + text_to_found + " not found", text_to_found.equals(reason));
} catch (AssertionError e) {
System.err.println("title not found: " + e.getMessage());
}
}
I call it with such command:
Check title1 = new Check ("Title", driver.getTitle());
title1.check_title();
First time it works correct. But second (and so on) times, if I call this method (for new opened windows) it says that title is not found, but I know that it is correct. Advise, what is wrong with code?
I just used your code to check the title of google.com. In your code if the title does not match -
Check title1 = new Check ("G3oogle", driver.getTitle());
title1.check_title();
We get the result - title not found: Title G3oogle not found
But if it matches as below -
Check title1 = new Check ("Google", driver.getTitle());
title1.check_title();
You are not printing anything on the console. So if you want print anything to the console if title matches then you can modify your code -
public void check_title() {
if(text_to_found.equals(reason)){
System.out.println("title found: Title "+text_to_found+" found");
}
else{
System.out.println("title not found: Title "+text_to_found+" not found");
}
}