testing submit button with selenium webDriver - selenium

My html form contains multipl html tags such <form>
My html file: myFile.html
<body>
<div class="globalContainer">
<div class="test1" id="formM" width="848" height="720" method="post" name="devis" onreset="return vider();">
<div class="content-1" id="cadreGlob">
<div id="contentForm">
<div class="preview">
<div class="left_col">
<fieldset id="haut">
<label class="labelForm" id="labelPriorite">label1:</label>
<select id="selectPrio">
<option value="labT">subLabel11</option>
<option value="labP">subLabel12</option>
</select><p></p>
<form enctype="multipart/form-data" method="post">
<label class="labelForm" id="labelFile1">label2:</label>
<input id="upload1" type="file" name="file[]" />
</form>
</fieldset>
</div>
<div class="right_col">
<fieldset id="haut">
<form name="page">
<label class="labelForm" for="cb" id="labelPopulation">lebel3:</label>
<input type="checkbox" id="cb" name="cb" checked="checked" onclick="valid();showPop();" /><br />
<label class="labelForm" for="ta" id="labelMessage2">label4:</label>
<textarea disabled="true" id="ta" name="ta" cols="22" rows="9"></textarea>
<label class="labelForm" id="labelFile2" >label5:</label>
<input id="upload2" type="file" name="valider" id="butonParc" disabled="disabled"/>
</form>
</fieldset>
</div>
<div class="left_col">
<p></p>
<fieldset id="bas">
<label class="labelForm" id="labelServiceOp">label6:</label>
<select id="selectServOp">
<option value="def">subLabel61</option>
<option value="sec">subLabel62</option>
</select><p></p>
</fieldset>
</div>
<div class="right_col">
<p></p>
<fieldset id="bas">
<label class="labelForm" id="labelAdressage" >label7:</label>
<select name="ToutePopD" id="ToutePopD">
<option value="toujours">subLabel71</option>
<option value="parfois">subLabl72</option>
</select>
<select name="ToutePopA" id="ToutePopA">
<option value="toujours">subLabl73</option>
<option value="parfois">subLabel74</option>
</select>
</fieldset>
</div>
<div class="right_col"><p></p>
<form action="submit.html" id="sub" name="formValid">
<input type="submit" id="validation" value="validate" name="submit" />
</form> <p></p>
<script>
function vider()
{
document.getElementById("formM").value = "";
return false;
};
</script>
<input type="reset" id="cancel" value="Cancel"name="reset" />
</div>
</div>
</div>
</div>
</div>
</div>
</body>
My first problem
when i execute this command
...
...
this.driver.findElement(By.id("validation")).click();
...
...
My test is not switch to the url : submit.html
My submit.html
<body>
<h2><center>Form validation with Succee</center></h2>
</body>
My second problem:
When i execute the following code, i have an error : Unable to locate element : {"method":"id","selector":"sub"}
public class SeleniumTest {
private WebDriver driver;
private String baseUrl;
private boolean acceptNextAlert = true;
private final StringBuffer verificationErrors = new StringBuffer();
#Before
public void setUp() throws Exception {
final Properties properties = System.getProperties();
this.baseUrl = properties.getProperty("base.url", "myIp:8080/project");
}
#Test
public void firefoxTest() throws Exception {
this.driver = new FirefoxDriver();
testSelenium();
verifyValidation(this.baseUrl +"submit.html");
}
private void testSelenium() throws Exception {
this.driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
this.driver.get(this.baseUrl + "myFile.html");
new Select(this.driver.findElement(By.id("formM")).findElement(By.xpath("//fieldset[#id='haut']/select[1]"))).selectByVisibleText("subLabel11");
this.driver.findElement(By.id("upload1")).sendKeys("myUrl\\myFile.txt");
this.driver.findElement(By.id("validation")).click();
}
private void verifyValidation(String urlValidation) {
String submit =
this.driver.findElement(By.id("sub")).getAttribute("action");
if (submit == urlValidation) {assertEquals("url problem : ", submit, urlValidation);
}
#After
public void tearDown() throws Exception {
this.driver.quit();
final String verificationErrorString = this.verificationErrors.toString();
if (!"".equals(verificationErrorString)) {
fail(verificationErrorString);
}
}
private boolean isElementPresent(final By by) {
try {
this.driver.findElement(by);
return true;
} catch (final NoSuchElementException e) {
return false;
}
}
private String closeAlertAndGetItsText() {
try {
final Alert alert = this.driver.switchTo().alert();
final String alertText = alert.getText();
if (this.acceptNextAlert) {
alert.accept();
} else {
alert.dismiss();
}
return alertText;
} finally {
this.acceptNextAlert = true;
}
}
}
I don't know why WebDriver can not find my id ! ?
Thanks for help !

For your 2nd issue,
it comes into my mind, when there is no submit.html file on your server, page
not found displays. Then, on that page, there is no "id" element -> you get
NoSuchElement Exception throws
There are 4 issues in your scripts
1 - Your xpath //fieldset[#id='haut']/select[0] is not correct, xpath starts from [1]
2 - There is no label "subLabel11", only "subLabl11" exists
3 - this.driver.findElement(By.id("sub")).getAttribute("action"); will return *full-url* (In this case myIp:8080/project/submit.html
4 - if (submit == urlValidation) will always return False since they are 2 objects in different memory location.
Suggest you change it to if (submit.equals(urlValidation))
Beside these above notes, I run your script well on my machine and there is no issue. Here's my script:
new Select(browser.getBrowserCore().findElement(By.id("formM")).findElement(By.xpath("//fieldset[#id='haut']/select"))).selectByVisibleText("subLabl11");
browser.getBrowserCore().findElement(By.id("upload1")).sendKeys("myUrl\\myFile.txt");
browser.getBrowserCore().findElement(By.id("validation")).click();
String submit =
browser.getBrowserCore().findElement(By.id("sub")).getAttribute("action");
System.out.println("submit: "+ submit);
if (!submit.equals("submit.html")) {
System.out.println("comparator: FALSE");
};
Here's the test result
2014-07-21 18:13:44 [main]-[INFO] Started Browser
2014-07-21 18:13:44 [main]-[INFO] Pause 500 ms
2014-07-21 18:13:45 [main]-[INFO] Opened url: http://myIP:8305/
submit: http://myIP:8305/submit.html
comparator: FALSE
2014-07-21 18:13:51 [main]-[INFO] Pause 500 ms
2014-07-21 18:13:51 [main]-[INFO] Quitted Browser
PASSED: stackOverFlowTest
===============================================
Default test
Tests run: 1, Failures: 0, Skips: 0
===============================================

For your first question, the below code work fine with me.
public static void main(String[] args)
{
WebDriver driver=new FirefoxDriver();
driver.get("Your URL");
WebElement validate=driver.findElement(By.id("validation"));
validate.click();
driver.close();
}
Following is the code for your 2nd question:
public static void main(String[] args)
{
WebDriver driver=new FirefoxDriver();
driver.get("Your URL");
WebElement element=driver.findElement(By.id("selectPrio"));
Select sel=new Select(element);
sel.selectByVisibleText("subLabel12");
driver.close();
}

Thank you all for tracks you give me.
I finally succeeded to solve my problem
For my first problem:
I had a mistake in the URL of my page submit.html
For my second problem:
when I execute the command: this.driver.findElement this.driver.findElement(By.id("validation")).click();
the page myFile.html where there is my id "sub" is not supported by the driver but submit.html
And then I made the switch back to my original page myfile.html and I have no error.
Thank you again!

Related

Show Post submit popup message in ASP.Net Core Razor page without controller

I have an ASP.Net Core Razor web application without controllers.
I have a form in my cshtml page and on Post/Submit I am calling an external API, which returns a success message or an error message. I want to show this message in my page as a popup.
I tried multiple things but failed. Here is my code.
In my "Index.cshtml"
<div class="col-lg-4 col-md-6 footer-newsletter">
<h4>Our Newsletter</h4>
<p>Subscribe to our news letter</p>
<form action="" method="post">
<input type="email" asp-for="SubscriptionEmail" placeholder="Email Address"/>
<input type="submit" value="Subscribe" asp-page-handler="NewsSubscription" />
</form>
</div>
In my Index.cshtml.cs
[BindProperty]
public string SubscriptionEmail { get; set; }
public string ActionResultMessageText { get; set; }
public string ActionResultErrorMessageText { get; set; }
public async void OnPostNewsSubscription()
{
try
{
this.ActionResultMessageText = string.Empty;
this.ActionResultErrorMessageText = string.Empty;
using (HttpClient _httpClient = _httpClientFactory.CreateClient("PortalBasicHttpClient"))
{
if (!string.IsNullOrEmpty(SubscriptionEmail))
{
HttpRequestMessage _Request = new(HttpMethod.Post, _httpClient.BaseAddress + "Api/SaveSubscriptionEmail/" + SubscriptionEmail);
HttpResponseMessage _Response = await _httpClient.SendAsync(_Request);
if (_Response.IsSuccessStatusCode)
{
this.ActionResultMessageText = _Response.Content.ReadAsStringAsync().Result.ToString();
}
else
{
this.ActionResultMessageText = _Response.Content.ReadAsStringAsync().Result.ToString();
}
}
}
}
catch (Exception ex)
{
_logger.LogError(ex, ex.Message);
this.ActionResultMessageText = string.Empty;
this.ActionResultErrorMessageText = ex.Message;
}
}
My code behind is working fine, but not sure how to grace fully show this in the razor page using bootstrap.
looking forward for some guidance.
I tried using modal popup, but the text was not updated in the label I used in the modal popup and the pop-up disappeared with in few seconds, even though there was a "ok" button.
I also tried to use the java script method as mentioned in the following link https://www.aspsnippets.com/Articles/ASPNet-Core-Razor-Pages-Display-JavaScript-Alert-Message-Box.aspx
I will be great help if someone can help with a sample code.
Please debug your code and be sure the two properties actually contain the value you want.
The following working demo I just hard coded the two properties value for easy testing in the backend:
Index.cshtml
#page
#model IndexModel
<div class="col-lg-4 col-md-6 footer-newsletter">
<h4>Our Newsletter</h4>
<p>Subscribe to our news letter</p>
<form action="" method="post">
<input type="email" asp-for="SubscriptionEmail" placeholder="Email Address" />
<input type="submit" value="Subscribe" asp-page-handler="NewsSubscription" />
</form>
</div>
#if (Model.ActionResultMessageText == string.Empty)
{
<script type="text/javascript">
window.onload = function () {
alert("#Model.ActionResultErrorMessageText");
};
</script>
}
Index.cshtml.cs
public class IndexModel : PageModel
{
private readonly ILogger<IndexModel> _logger;
public IndexModel(ILogger<IndexModel> logger)
{
_logger = logger;
}
[BindProperty]
public string SubscriptionEmail { get; set; }
public string ActionResultMessageText { get; set; }
public string ActionResultErrorMessageText { get; set; }
public void OnGet()
{
}
public async void OnPostNewsSubscription()
{
this.ActionResultMessageText = string.Empty;
this.ActionResultErrorMessageText = "error";
}
}
Result:
If you want to use Bootstrap modal popup, change your page like below:
#page
#model IndexModel
<div class="col-lg-4 col-md-6 footer-newsletter">
<h4>Our Newsletter</h4>
<p>Subscribe to our news letter</p>
<form action="" method="post">
<input type="email" asp-for="SubscriptionEmail" placeholder="Email Address" />
<input type="submit" value="Subscribe" asp-page-handler="NewsSubscription" />
</form>
</div>
<div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h1 class="modal-title fs-5" id="exampleModalLabel">Modal title</h1>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
#Model.ActionResultErrorMessageText
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>
#if (Model.ActionResultMessageText == string.Empty)
{
<script type="text/javascript">
window.onload = function () {
$("#exampleModal").modal("show")
};
</script>
}
Result:

Trouble with Request.Form inside .cshtml

Trying to create a page that will have a drop down selector with three image names and when an image name is selected and you hit submit it will then display that image on the page.
I found an example of this here(Seems to be outdated): https://learn.microsoft.com/en-us/aspnet/web-pages/overview/ui-layouts-and-themes/9-working-with-images
has: if(Request["photoChoice"] != null)
Read somewhere that the correction is Request.Form
#{ var imagePath = "";
if (Request.Form["photoChoice"] != null)
{
imagePath = #"images\" + Request.Form["photoChoice"];
}
}
<form method="post" action="">
<div>
I want to see:
<select name="photoChoice">
<option value="Photo1.jpg">Photo 1</option>
<option value="Photo2.jpg">Photo 2</option>
<option value="Photo3.jpg">Photo 3</option>
</select>
<input type="submit" value="Submit" />
</div>
<div style="padding:10px;">
#if (imagePath != "")
{
<img src="#imagePath" alt="Sample Image" width="300" />
}
</div>
</form>
The first error I was having was:
" Operator '!=' is ambiguous on operands of type 'StringValues' and 'null' "
adding (object) at the start of the Request there in the if statement
#{ var imagePath = "";
if ((object)Request.Form["photoChoice"] != null)
{
imagePath = #"images\" + Request.Form["photoChoice"];
}
Now I am getting another error "InvalidOperationException: Incorrect Content-Type" when I try to compile the site. It does refer to the If line of code
The link you refer to is used in asp.net, not in core.
The main reason for the error is that you put the request.Form in the
wrong place. Your current requirements should put the code
into the OnPost method in the code behind.
There are many ways to implement this function in the core, but they need to be triggered in the post method in the code behind.
Please refer to this.
The simplest way is to bind fields in the code behind. Please refer to the following for details.
Page.cs:
public class ShowImagesModel : PageModel
{
[BindProperty]
public string imagePath { get; set; }
[BindProperty]
public string photoChoice { get; set; }
public void OnGet()
{
imagePath = "";
}
public void OnPost()
{
if (!string.IsNullOrEmpty(photoChoice))
{
imagePath = #"images\" + photoChoice;
}
}
}
View:
#page
#model WebApplication1_razor_page.ShowImagesModel
#{
ViewData["Title"] = "ShowImages";
Layout = "~/Pages/Shared/_Layout.cshtml";
}
<h1>ShowImages</h1>
<form method="post" action="">
<div>
I want to see:
<select asp-for="photoChoice" >
<option value="Photo1.jpg">Photo 1</option>
<option value="Photo2.jpg">Photo 2</option>
<option value="Photo3.jpg">Photo 3</option>
</select>
<input type="submit" value="Submit" />
</div>
<div style="padding:10px;">
#if (Model.imagePath != "")
{
<img src="#Model.imagePath" alt="Sample Image" width="300" />
}
</div>
</form>
Here is the result:

Getting access denied after a successfull authentication Spring Security with JDBC

After a successful authentication i get redirected to a access denied page.
WebSecurityContext
#Configuration
#EnableWebSecurity
public class WebSecurityContext extends WebSecurityConfigurerAdapter {
#Autowired
private UserDetailsService userDetailsService;
#Autowired
public void configAuthentication(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/admin/login").permitAll()
.antMatchers("/admin/**").hasAnyRole("ROLE_ADMIN", "ROLE_CONTRIBUTOR","ROLE_ROOT")
.and()
.formLogin().loginPage("/admin/login")
.failureUrl("/admin/login/error")
.successHandler(new SuccessfulAuthHandler())
.loginProcessingUrl("/admin/login")
.defaultSuccessUrl("/admin")
.usernameParameter("username")
.passwordParameter("password")
.and()
.logout().logoutSuccessUrl("/admin/login/logout");
}
#Bean(name = "passwordencoder")
public BCryptPasswordEncoder passwordEncoder(){
return new BCryptPasswordEncoder(10);
}
SuccessHandler
#Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
Authentication authentication) throws IOException {
final HttpSession currentSession = request.getSession();
final User user = userService.findByUsername(authentication.getName());
final List<Object> jObj = new ArrayList<>();
final List<Institution> institutions = institutionService.findAllByUserID(user.getId());
for(Institution i : institutions){
Map<String, Object> m = new HashMap<>();
m.put("name", i.getName());
m.put("id", i.getId());
jObj.add(m);
}
currentSession.setAttribute("userInInstitution", jObj);
currentSession.setAttribute("currentUser", user);
String servlet = "";
if(user.getRole() == ConstantsCommon.USER_ROLE_ADMIN){
servlet = DashBoardController.URL;
currentSession.setAttribute("dashboardServlet", servlet);
}else{
servlet = DashBoardController.URL;
currentSession.setAttribute("dashboardServlet", servlet);
}
if(jObj.size() > 1){
currentSession.setAttribute("institution",institutions.get(0));
}else{
currentSession.setAttribute("institution",institutions.get(0));
}
RedirectStrategy r = new DefaultRedirectStrategy();
r.sendRedirect(request,response, servlet);
}
Login HTML
<div class="container">
<div class="row">
<div class="col-md-12">
<div class="pr-wrap">
<div class="pass-reset">
<label>
Enter the email you signed up with</label>
<input type="email" placeholder="Email" />
<input type="submit" value="Submit" class="pass-reset-submit btn btn-success btn-sm" />
</div>
</div>
<div class="wrap">
<p class="form-title">Sign In</p>
<form class="login" name="loginForm" method='POST'>
<input type="hidden" th:name="${_csrf.parameterName}" th:value="${_csrf.token}"/>
<input type="text" name="username" placeholder="Username"/>
<input type="password" name="password" placeholder="Password"/>
<input type="submit" name="submit" value="Sign In" class="btn btn-success btn-sm" />
<div class="remember-forgot">
<div th:if="${error}" class="alert alert-danger notificationMsg" role="alert">
<span th:text="${error}"></span>
</div>
<div th:if="${msg}" class="alert alert-success notificationMsg" role="alert">
<span th:text="${msg}"></span>
</div>
<!--<div class=" forgot-pass-content">-->
<!--Forgot Password-->
<!--</div>-->
</div>
</form>
</div>
</div>
</div>
What am I doing wrong here ?????? The user im logging in with has the role "ROLE_ADMIN". One thing i have also noticed is that my success handler doesn't even get triggered which suggest that mu authentication isn't successful but that can't be right because the password and username are 100% correct.

choosing between 2 actions in one controller with single view by checkbox

I got 2 actions in my controller, I want to choose which action to execute by checkbox in my razor view.
here is my controller:
public ActionResult Person(string searchString)
{
var person = from p in db.Persons
select p;
if (!String.IsNullOrEmpty(searchString))
{
person = person.Where(oo => oo.Name.ToUpper() == searchString);
}
return View(person);
}
public ActionResult Job(string jobString)
{
var jobs = from j in db.Jobs
select j;
if (!String.IsNullOrEmpty(jobString))
{
jobs = jobs.Where(oo => oo.Name.ToUpper() == jobString);
}
return View(jobs);
}
when I check a case I would like to execute the query search for this specific case
here is my view:
<div>
<form method="POST">
<div>
<input type="checkbox" name="Person" value="Person" style="margin-left: 54px"/>Person
</div>
<div class="Job">
<input type="checkbox" name="Job" value="Job" />Job
</div>
#using (Html.BeginForm())
{
<p>
<input type="text" name="SearchString" style="margin-left: 90px;" />
<input type="submit" value="Search" />
</p>
}
</form>
Post to a single action method, then call one of your existing methods depending on the value of the checkbox.
public ActionResult Search(bool isJobSearch, string searchString)
{
if (isJobSearch)
{
return Job(searchString);
}
else
{
return Person(searchString);
}
}
private ActionResult Person(string searchString)
{
// As your example
}
private ActionResult Job(string jobString)
{
// As your example
}
I am just correcting your html
Your html contains two form tags. I am not sure about the usage of form with in form tags. html.beginform will create internally another form tag when gets executed.So better one form tag will contain all elements to make a post.
#using (Html.BeginForm("Search","Home"))
{
<div>
<input type="checkbox" name="Person" value="Person" style="margin-left: 54px"/>Person
</div>
<div class="Job">
<input type="checkbox" name="Job" value="Job" />Job
</div>
<p>
<input type="text" name="SearchString" style="margin-left: 90px;" />
<input type="submit" value="Search" />
</p>
}
}
in controller
public ActionResult Search(FormCollection form)
{
//do some condition based on your needs
if(form["SearchString"]=="Job")
return RedirectToAction("Job");
else
return RedirectToAction("Person");
}
public ActionResult Person()
{
}
public ActionResult Job()
{
}

Not able to click or select the value

I am stuck with the below scenario, trying to click or select the value from the field.
There are 2 fields "Type of Test" which is a dropdown, after selecting the value from dropdown "Body Part" field gets active.
Trying to select the value from "Body Part", but not able to click or select the value from the field.
I have exported the script from Selenium IDE, please let me know where to correct.
public class test {
private WebDriver driver;
private String baseUrl;
#Before
public void setUp() throws Exception {
driver = new FirefoxDriver();
baseUrl = "https://nyrp.opendr.com/search/client-search/pid/VFZSRk5FNVJQVDA9?script=javascript&badge=1";
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}
#Test
public void test() throws Exception {
driver.get(baseUrl + "search/client-search/pid/VFZSRk5FNVJQVDA9?script=javascript&badge=1");
driver.findElement(By.id("typeoftest_1")).click();
new Select(driver.findElement(By.id("typeoftest_1"))).selectByVisibleText("MRA");
Thread.sleep(500);
for (int second = 0;; second++) {
if (second >= 60) fail("timeout");
try { if (isElementPresent(By.id("bodypart_1"))) break; } catch (Exception e) {}
Thread.sleep(1000);
}
driver.findElement(By.id("bodypart_1")).click();
driver.findElement(By.cssSelector("#bodyPartList_1 > li > div.mailval.")).click();
driver.findElement(By.cssSelector("a.search")).click();
}
private boolean isElementPresent(By id) {
// TODO Auto-generated method stub
return false;
}
}
Following is the HTML CODE for "Body Part" field:
<div id="bodypart_box_1">
<div style="position:absolute;left:185px;z-index: 20">
<ul class="parent">
<li>
<div id="main" class="mailval">events=Object { click=[1]}handle=function()
<input id="bodypart_1" class="bodypart" type="text" onfocus="if($(this).hasClass('disabled')){$(this).blur();}" readonly="readonly" value="Select One" name="bodypart_1" title="">
<input id="actualBodypart_1" type="hidden" value="" name="actualBodypart_1">
</div>
<ul id="bodyPartList_1" class="top sub bodyPartList" style="display: none;">olddisplay="none"
<li>
<div class="mailval " title="Head" originaltitle="Head">Head</div>events=Object { click=[1], mouseover=[1]}handle=function()
</li>
<li>
<div class="mailval " title="Neck" originaltitle="Neck">Neck</div>events=Object { click=[1], mouseover=[1]}handle=function()
</li>
<li>
<div class="mailval " title="Pelvis" originaltitle="Pelvis">Pelvis</div>events=Object { click=[1], mouseover=[1]}handle=function()
</li>
</ul>
</li>
</ul>
<div style="clear:both"></div>
</div>