1 package org.apache.archiva.web.test.parent;
4 * Licensed to the Apache Software Foundation (ASF) under one
5 * or more contributor license agreements. See the NOTICE file
6 * distributed with this work for additional information
7 * regarding copyright ownership. The ASF licenses this file
8 * to you under the Apache License, Version 2.0 (the
9 * "License"); you may not use this file except in compliance
10 * with the License. You may obtain a copy of the License at
12 * http://www.apache.org/licenses/LICENSE-2.0
14 * Unless required by applicable law or agreed to in writing,
15 * software distributed under the License is distributed on an
16 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
17 * KIND, either express or implied. See the License for the
18 * specific language governing permissions and limitations
22 import org.apache.archiva.web.test.tools.ArchivaSeleniumExecutionRule;
23 import org.apache.archiva.web.test.tools.WebdriverUtility;
24 import org.junit.Assert;
25 import org.junit.Rule;
28 import java.nio.file.Path;
29 import java.text.SimpleDateFormat;
30 import java.util.Date;
31 import java.util.Iterator;
33 import java.util.Map.Entry;
34 import java.util.Properties;
35 import java.util.concurrent.TimeUnit;
36 import java.util.function.Function;
38 import org.openqa.selenium.*;
39 import org.openqa.selenium.htmlunit.HtmlUnitDriver;
40 import org.openqa.selenium.support.ui.ExpectedConditions;
41 import org.openqa.selenium.support.ui.FluentWait;
42 import org.openqa.selenium.support.ui.Select;
43 import org.openqa.selenium.support.ui.WebDriverWait;
44 import org.slf4j.Logger;
45 import org.slf4j.LoggerFactory;
48 * @author <a href="mailto:evenisse@apache.org">Emmanuel Venisse</a>
52 public abstract class AbstractSeleniumTest
54 private final Logger logger = LoggerFactory.getLogger( getClass() );
57 public ArchivaSeleniumExecutionRule archivaSeleniumExecutionRule = new ArchivaSeleniumExecutionRule();
59 public String browser = System.getProperty( "browser" );
61 public String baseUrl =
62 "http://localhost:" + System.getProperty( "tomcat.maven.http.port" ) + "/archiva/index.html?request_lang=en";
64 public int maxWaitTimeInMs = Integer.getInteger( "maxWaitTimeInMs" );
66 public String seleniumHost = System.getProperty( "seleniumHost", "localhost" );
68 public int seleniumPort = Integer.getInteger( "seleniumPort", 4444 );
70 public boolean remoteSelenium = Boolean.parseBoolean( System.getProperty( "remoteSelenium", "false" ) );
72 WebDriver webDriver = null;
77 * this method is called by the Rule before executing a test
85 p.load( this.getClass().getClassLoader().getResourceAsStream( "test.properties" ) );
87 baseUrl = WebdriverUtility.getBaseUrl()+"/index.html?request_lang=en";
89 open( baseUrl, browser, seleniumHost, seleniumPort, maxWaitTimeInMs, remoteSelenium );
94 * this method is called by the Rule after executing a tests
98 getWebDriver().close();
102 * Initialize selenium
104 public void open( String baseUrl, String browser, String seleniumHost, int seleniumPort, int maxWaitTimeInMs, boolean remoteSelenium)
109 if ( getWebDriver() == null )
111 WebDriver driver = WebdriverUtility.newWebDriver(browser, seleniumHost, seleniumPort, remoteSelenium);
113 // selenium.setTimeout( Integer.toString( maxWaitTimeInMs ) );
114 this.webDriver = driver;
117 catch ( Exception e )
120 System.out.print( e.getMessage() );
125 public void assertAdminCreated()
128 initializeArchiva( baseUrl, browser, maxWaitTimeInMs, seleniumHost, seleniumPort, remoteSelenium );
131 public void initializeArchiva( String baseUrl, String browser, int maxWaitTimeInMs, String seleniumHost,
132 int seleniumPort, boolean remoteSelenium)
136 open( baseUrl, browser, seleniumHost, seleniumPort, maxWaitTimeInMs, remoteSelenium);
138 getWebDriver().get(baseUrl);
139 WebDriverWait wait = new WebDriverWait(getWebDriver(),30);
140 wait.until(ExpectedConditions.presenceOfElementLocated(By.id("topbar-menu")));
142 FluentWait fluentWait = new FluentWait(getWebDriver()).withTimeout(10, TimeUnit.SECONDS);
143 fluentWait.until( ExpectedConditions.or(
144 ExpectedConditions.visibilityOfElementLocated(By.id("create-admin-link")),
145 ExpectedConditions.visibilityOfElementLocated(By.id("login-link-a"))));
148 // if not admin user created create one
149 if ( isElementVisible( "create-admin-link" ) )
151 Assert.assertFalse( isElementVisible( "login-link-a" ) );
152 Assert.assertFalse( isElementVisible( "register-link-a" ) );
153 // skygo need to set to true for passing is that work as expected ?
154 clickLinkWithLocator( "create-admin-link-a");
155 wait = new WebDriverWait(getWebDriver(), 5);
156 wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("user-create")));
158 String fullname = getProperty( "ADMIN_FULLNAME" );
159 String username = getAdminUsername();
160 String mail = getProperty( "ADMIN_EMAIL" );
161 String password = getProperty( "ADMIN_PASSWORD" );
162 submitAdminData( fullname, mail, password );
163 assertUserLoggedIn( username );
164 clickLinkWithLocator( "logout-link-a" , false);
168 Assert.assertTrue( isElementVisible( "login-link-a" ) );
169 Assert.assertTrue( isElementVisible( "register-link-a" ) );
170 login( getAdminUsername(), getAdminPassword() );
175 public WebDriver getWebDriver() {
176 return this.webDriver;
179 protected String getProperty( String key )
181 return p.getProperty( key );
184 public String getAdminUsername()
186 String adminUsername = getProperty( "ADMIN_USERNAME" );
187 return adminUsername;
190 public String getAdminPassword()
192 String adminPassword = getProperty( "ADMIN_PASSWORD" );
193 return adminPassword;
196 public void submitAdminData( String fullname, String email, String password )
198 setFieldValue( "fullname", fullname );
199 setFieldValue( "email", email );
200 setFieldValue( "password", password );
201 setFieldValue( "confirmPassword", password );
202 clickButtonWithLocator( "user-create-form-register-button" , false);
205 public void login( String username, String password )
207 login( username, password, true, "Login Page" );
210 public void login( String username, String password, boolean valid, String assertReturnPage )
212 if ( isElementVisible( "login-link-a" ) )//isElementPresent( "loginLink" ) )
216 submitLoginPage( username, password, false, valid, assertReturnPage );
220 assertUserLoggedIn( username );
225 public void goToLoginPage()
227 logger.info("Goto login page");
228 getWebDriver().get( baseUrl );
229 WebDriverWait wait = new WebDriverWait(getWebDriver(),30);
230 wait.until(ExpectedConditions.presenceOfElementLocated(By.id("topbar-menu")));
231 wait.until(ExpectedConditions.or(ExpectedConditions.visibilityOfElementLocated(By.id("logout-link")),
232 ExpectedConditions.visibilityOfElementLocated(By.id("login-link-a"))));
234 // are we already logged in ?
235 if ( isElementVisible( "logout-link" ) ) //isElementPresent( "logoutLink" ) )
237 logger.info("Logging out ");
239 clickLinkWithLocator( "logout-link-a", false );
241 wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("login-link-a")));
242 clickLinkWithLocator( "login-link-a", false );
243 // This is a workaround for bug with HTMLUnit. The display attribute of the
244 // login dialog is not changed via the click.
245 // TODO: Check after changing jquery, bootstrap or htmlunit version
246 if (getWebDriver() instanceof HtmlUnitDriver)
248 ( (JavascriptExecutor) getWebDriver() ).executeScript( "$('#modal-login').show();" );
251 wait = new WebDriverWait(getWebDriver(),20);
252 wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("modal-login")));
257 public void assertLoginModal()
259 assertElementPresent( "user-login-form" );
260 Assert.assertTrue( isElementVisible( "register-link" ) );
261 Assert.assertTrue( isElementVisible("user-login-form-username" ));
262 Assert.assertTrue( isElementVisible("user-login-form-password" ));
263 assertButtonWithIdPresent( "modal-login-ok" );
264 Assert.assertTrue( isElementVisible( "modal-login-ok" ));
268 public void submitLoginPage( String username, String password )
270 submitLoginPage( username, password, false, true, "Login Page" );
273 public void submitLoginPage( String username, String password, boolean validUsernamePassword )
275 submitLoginPage( username, password, false, validUsernamePassword, "Login Page" );
278 public void submitLoginPage( String username, String password, boolean rememberMe, boolean validUsernamePassword,
279 String assertReturnPage )
281 logger.info("Activating login form");
282 // clickLinkWithLocator( "login-link-a", false);
283 WebDriverWait wait = new WebDriverWait(getWebDriver(),5);
284 WebElement usernameField = wait.until(ExpectedConditions.visibilityOf(getWebDriver().findElement(By.id("user-login-form-username"))));
285 wait = new WebDriverWait(getWebDriver(),5);
286 WebElement passwordField = wait.until(ExpectedConditions.visibilityOf(getWebDriver().findElement(By.id("user-login-form-password"))));
287 wait = new WebDriverWait(getWebDriver(),5);
288 WebElement button = wait.until(ExpectedConditions.elementToBeClickable(By.id("modal-login-ok")));
289 usernameField.sendKeys(username);
290 passwordField.sendKeys(password);
294 checkField( "rememberMe" );
298 if ( validUsernamePassword )
300 assertUserLoggedIn( username );
305 if ( "Login Page".equals( assertReturnPage ) )
311 assertPage( assertReturnPage );
316 // *******************************************************
317 // Auxiliar methods. This method help us and simplify test.
318 // *******************************************************
320 protected void assertUserLoggedIn( String username )
322 WebDriverWait wait = new WebDriverWait(getWebDriver(), 10);
323 wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("logout-link")));
324 Assert.assertFalse( isElementVisible( "login-link" ) );
325 Assert.assertFalse( isElementVisible( "register-link" ) );
326 Assert.assertFalse( isElementVisible( "create-admin-link" ) );
329 public void assertCreateAdmin()
331 assertElementPresent( "user-create" );
332 assertFieldValue( "admin", "username" );
333 assertElementPresent( "fullname" );
334 assertElementPresent( "password" );
335 assertElementPresent( "confirmPassword" );
336 assertElementPresent( "email" );
339 public void assertFieldValue( String fieldValue, String fieldName )
341 assertElementPresent( fieldName );
342 Assert.assertEquals( fieldValue, findElement(fieldName ).getAttribute( "value") );
345 public void assertPage( String title )
347 Assert.assertEquals( title, getTitle());
350 public String getTitle()
353 return getWebDriver().getTitle().replaceAll( "[ \n\r]+", " " );
356 public String getHtmlContent()
358 return getWebDriver().getPageSource();
361 public String getText( String locator )
363 return findElement(locator ).getText();
366 public void assertTextPresent( String text )
368 Assert.assertTrue( "'" + text + "' isn't present.", getWebDriver().getPageSource().contains( text ) );
372 public void assertTextNotPresent( String text )
374 Assert.assertFalse( "'" + text + "' is present.", isTextPresent( text ) );
377 public void assertElementPresent( String elementLocator )
379 Assert.assertTrue( "'" + elementLocator + "' isn't present.", isElementPresent( elementLocator ) );
382 public void assertElementNotPresent( String elementLocator )
384 Assert.assertFalse( "'" + elementLocator + "' is present.", isElementPresent( elementLocator ) );
387 public void assertLinkPresent( String text )
389 Assert.assertTrue( "The link '" + text + "' isn't present.", isElementPresent( "//*[text()='" + text+"']//ancestor::a" ) );
392 public void assertLinkNotPresent( String text )
394 Assert.assertFalse( "The link('" + text + "' is present.", isElementPresent( "//*[text()='" + text+"']//ancestor::a" ) );
397 public void assertLinkNotVisible( String text )
399 Assert.assertFalse( "The link('" + text + "' is visible.", isElementVisible( "//*[text()='" + text+"']//ancestor::a" ) );
402 public void assertLinkVisible( String text )
404 Assert.assertTrue( "The link('" + text + "' is not visible.", isElementVisible( "//*[text()='" + text+"']//ancestor::a" ) );
407 public void assertImgWithAlt( String alt )
409 assertElementPresent( "/¯img[@alt='" + alt + "']" );
412 public void assertImgWithAltAtRowCol( boolean isALink, String alt, int row, int column )
414 String locator = "//tr[" + row + "]/td[" + column + "]/";
415 locator += isALink ? "a/" : "";
416 locator += "img[@alt='" + alt + "']";
418 assertElementPresent( locator );
421 public void assertImgWithAltNotPresent( String alt )
423 assertElementNotPresent( "/¯img[@alt='" + alt + "']" );
428 public boolean isTextPresent( String text )
430 return getWebDriver().getPageSource().contains(text);
433 public boolean isLinkPresent( String text )
435 return isElementPresent( "//*[text()='" + text +"']//ancestor::a" );
438 public boolean isElementPresent( String locator )
442 return findElement(locator ) != null;
443 } catch (Exception e) {
448 public boolean isElementVisible(String locator )
451 return findElement(locator).isDisplayed();
452 } catch (Exception e) {
458 public void waitPage()
460 // TODO define a smaller maxWaitTimeJsInMs for wait javascript response for browser side validation
461 //getSelenium().w .wait( Long.parseLong( maxWaitTimeInMs ) );
462 //getSelenium().waitForPageToLoad( maxWaitTimeInMs );
463 // http://jira.openqa.org/browse/SRC-302
464 // those hack looks to break some tests :-(
465 // getSelenium().waitForCondition( "selenium.isElementPresent('document.body');", maxWaitTimeInMs );
466 //getSelenium().waitForCondition( "selenium.isElementPresent('footer');", maxWaitTimeInMs );
467 //getSelenium().waitForCondition( "selenium.browserbot.getCurrentWindow().document.getElementById('footer')",
468 // maxWaitTimeInMs );
469 // so the only hack is to not use a too small wait time
473 Thread.sleep( maxWaitTimeInMs );
475 catch ( InterruptedException e )
477 throw new RuntimeException( "issue on Thread.sleep : " + e.getMessage(), e );
481 public String getFieldValue( String fieldName )
483 return findElement(fieldName ).getAttribute( "value" );
487 public void selectValue( String locator, String value )
489 WebElement element = findElement(locator );
490 Select select = new Select(element);
491 select.selectByValue( value );
494 public WebElement findElement(String locator) {
495 if (locator.startsWith("/")) {
496 return getWebDriver().findElement( By.xpath( locator ) );
498 return getWebDriver().findElement( By.id(locator) );
505 clickLinkWithXPath( "//input[@type='submit']" );
508 public void assertButtonWithValuePresent( String text )
510 Assert.assertTrue( "'" + text + "' button isn't present", isButtonWithValuePresent( text ) );
513 public void assertButtonWithIdPresent( String id )
515 Assert.assertTrue( "'Button with id =" + id + "' isn't present", isButtonWithIdPresent( id ) );
518 public void assertButtonWithValueNotPresent( String text )
520 Assert.assertFalse( "'" + text + "' button is present", isButtonWithValuePresent( text ) );
523 public boolean isButtonWithValuePresent( String text )
525 return isElementPresent( "//button[@value='" + text + "']" ) || isElementPresent(
526 "//input[@value='" + text + "']" );
529 public boolean isButtonWithIdPresent( String text )
531 return isElementPresent( "//button[@id='" + text + "']" ) || isElementPresent( "//input[@id='" + text + "']" );
534 public void clickButtonWithName( String text, boolean wait )
536 clickLinkWithXPath( "//input[@name='" + text + "']", wait );
539 public void clickButtonWithValue( String text )
541 clickButtonWithValue( text, false );
544 public void clickButtonWithValue( String text, boolean wait )
546 assertButtonWithValuePresent( text );
548 if ( isElementPresent( "//button[@value='" + text + "']" ) )
550 clickLinkWithXPath( "//button[@value='" + text + "']", wait );
554 clickLinkWithXPath( "//input[@value='" + text + "']", wait );
558 public void clickSubmitWithLocator( String locator )
560 clickLinkWithLocator( locator );
563 public void clickSubmitWithLocator( String locator, boolean wait )
565 clickLinkWithLocator( locator, wait );
568 public void clickImgWithAlt( String alt )
570 clickLinkWithLocator( "//img[@alt='" + alt + "']" );
573 public void clickLinkWithText( String text )
575 clickLinkWithText( text, false );
578 public void clickLinkWithText( String text, boolean wait )
580 clickLinkWithLocator( "//*[text()='" + text +"']//ancestor::a", wait );
583 public void clickLinkWithXPath( String xpath )
585 clickLinkWithXPath( xpath, false );
588 public void clickLinkWithXPath( String xpath, boolean wait )
590 clickLinkWithLocator( xpath, wait );
593 public void clickLinkWithLocator( String locator )
595 clickLinkWithLocator( locator, false );
598 public void clickLinkWithLocator( String locator, boolean wait )
600 assertElementPresent( locator );
601 findElement(locator).click();
608 public void clickButtonWithLocator( String locator )
610 clickButtonWithLocator( locator, false );
613 public void clickButtonWithLocator( String locator, boolean wait )
615 assertElementPresent( locator );
616 findElement(locator ).click();
624 * Executes click() on the WebElement <code>el</code> and waits for the conditions.
625 * If the condition is not fulfilled in <code>maxWaitTimeInS</code>, the click is executed again
626 * and waits again for the condition.
627 * After the number of attempts as given by the parameter an assertion error will be thrown, with
628 * the given <code>message</code>.
630 * If the click was successful the element is returned that was created by the condition.
632 * @param el The element where the click is executed
633 * @param conditions The conditions to wait for after the click
634 * @param message The assertion messages
635 * @param attempts Maximum number of click attempts
636 * @param maxWaitTimeInS The time in seconds to wait that the condition is fulfilled.
637 * @param <V> The return type
640 public <V> V tryClick( WebElement el, Function<? super WebDriver, V> conditions, String message, int attempts, int maxWaitTimeInS)
642 int count = attempts;
643 WebDriverWait wait = new WebDriverWait( getWebDriver(), maxWaitTimeInS );
651 result = wait.until( conditions );
654 } catch (Exception e) {
660 Assert.fail( message);
665 public <V> V tryClick(WebElement el, Function<? super WebDriver, V> conditions, String message, int attempts )
667 return tryClick( el, conditions, message, attempts, 10 );
670 public <V> V tryClick(WebElement el, Function<? super WebDriver, V> conditions, String message)
672 return tryClick( el, conditions, message, 3);
676 public void setFieldValues( Map<String, String> fieldMap )
678 Map.Entry<String, String> entry;
680 for ( Iterator<Entry<String, String>> entries = fieldMap.entrySet().iterator(); entries.hasNext(); )
682 entry = entries.next();
684 setFieldValue( entry.getKey(), entry.getValue() );
688 public void setFieldValue( String fieldName, String value )
690 findElement(fieldName ).sendKeys( value );
693 public void checkField( String locator )
695 WebElement element = findElement(locator );
696 if (!element.isSelected()) {
701 public void uncheckField( String locator )
703 WebElement element = findElement(locator );
704 if (element.isSelected()) {
709 public boolean isChecked( String locator )
711 return findElement(locator ).isSelected();
714 public void assertIsChecked( String locator )
717 Assert.assertTrue( isChecked( locator ));
720 public void assertIsNotChecked( String locator )
723 Assert.assertFalse( isChecked( locator ) );
728 public String captureScreenShotOnFailure( Throwable failure, String methodName, String className )
730 SimpleDateFormat sdf = new SimpleDateFormat( "yyyy.MM.dd-HH_mm_ss" );
731 String time = sdf.format( new Date() );
732 File targetPath = new File( "target", "screenshots" );
736 for ( StackTraceElement stackTrace : failure.getStackTrace() )
738 if ( stackTrace.getClassName().equals( this.getClass().getName() ) )
740 lineNumber = stackTrace.getLineNumber();
746 if (getWebDriver()!=null)
748 String fileBaseName = methodName + "_" + className + ".java_" + lineNumber + "-" + time;
749 File fileName = new File( targetPath, fileBaseName + ".png" );
750 Path screenshot = WebdriverUtility.takeScreenShot( fileName.getName(), getWebDriver());
751 return fileName.getAbsolutePath();