idx
int64
0
41.2k
question
stringlengths
74
4.04k
target
stringlengths
7
750
36,000
protected static void setAppURL ( Selenified clazz , ITestContext context , String siteURL ) { context . setAttribute ( clazz . getClass ( ) . getName ( ) + APP_URL , siteURL ) ; }
Sets the URL of the application under test . If the site was provided as a system property this method ignores the passed in value and uses the system property .
36,001
private String getVersion ( String clazz , ITestContext context ) { return ( String ) context . getAttribute ( clazz + "Version" ) ; }
Obtains the version of the current test suite being executed . If no version was set null will be returned
36,002
protected static void setVersion ( Selenified clazz , ITestContext context , String version ) { context . setAttribute ( clazz . getClass ( ) . getName ( ) + "Version" , version ) ; }
Sets the version of the current test suite being executed .
36,003
private String getAuthor ( String clazz , ITestContext context ) { return ( String ) context . getAttribute ( clazz + "Author" ) ; }
Obtains the author of the current test suite being executed . If no author was set null will be returned
36,004
protected static void setAuthor ( Selenified clazz , ITestContext context , String author ) { context . setAttribute ( clazz . getClass ( ) . getName ( ) + "Author" , author ) ; }
Sets the author of the current test suite being executed .
36,005
private static Map < String , Object > getExtraHeaders ( String clazz , ITestContext context ) { return ( Map < String , Object > ) context . getAttribute ( clazz + "Headers" ) ; }
Obtains the additional headers of the current test suite being executed . If no additional headers were set null will be returned
36,006
protected static void addAdditionalDesiredCapabilities ( Selenified clazz , ITestContext context , String capabilityName , Object capabilityValue ) { DesiredCapabilities desiredCapabilities = new DesiredCapabilities ( ) ; if ( context . getAttributeNames ( ) . contains ( clazz . getClass ( ) . getName ( ) + DESIRED_CAPABILITIES ) ) { desiredCapabilities = ( DesiredCapabilities ) context . getAttribute ( clazz . getClass ( ) . getName ( ) + DESIRED_CAPABILITIES ) ; } desiredCapabilities . setCapability ( capabilityName , capabilityValue ) ; context . setAttribute ( clazz . getClass ( ) . getName ( ) + DESIRED_CAPABILITIES , desiredCapabilities ) ; }
Sets any additional capabilities desired for the browsers . Things like enabling javascript accepting insecure certs . etc can all be added here on a per test class basis .
36,007
private static DesiredCapabilities getAdditionalDesiredCapabilities ( String clazz , ITestContext context ) { return ( DesiredCapabilities ) context . getAttribute ( clazz + DESIRED_CAPABILITIES ) ; }
Retrieves the additional desired capabilities set by the current class for the browsers
36,008
private static String getServiceUserCredential ( String clazz , ITestContext context ) { if ( System . getenv ( "SERVICES_USER" ) != null ) { return System . getenv ( "SERVICES_USER" ) ; } if ( context . getAttribute ( clazz + SERVICES_USER ) != null ) { return ( String ) context . getAttribute ( clazz + SERVICES_USER ) ; } else { return "" ; } }
Obtains the web services username provided for the current test suite being executed . Anything passed in from the command line will first be taken to override any other values . Next values being set in the classes will be checked for . If neither of these are set an empty string will be returned
36,009
private static String getServicePassCredential ( String clazz , ITestContext context ) { if ( System . getenv ( "SERVICES_PASS" ) != null ) { return System . getenv ( "SERVICES_PASS" ) ; } if ( context . getAttribute ( clazz + SERVICES_PASS ) != null ) { return ( String ) context . getAttribute ( clazz + SERVICES_PASS ) ; } else { return "" ; } }
Obtains the web services password provided for the current test suite being executed . Anything passed in from the command line will first be taken to override any other values . Next values being set in the classes will be checked for . If neither of these are set an empty string will be returned
36,010
private void loadInitialPage ( App app , String url , Reporter reporter ) { String startingPage = "The initial url of <i>" ; String act = "Opening new browser and loading up initial url" ; String expected = startingPage + url + "</i> will successfully load" ; if ( app != null ) { try { app . getDriver ( ) . get ( url ) ; if ( ! app . get ( ) . url ( ) . contains ( url ) ) { reporter . fail ( act , expected , startingPage + app . get ( ) . url ( ) + "</i> loaded instead of <i>" + url + "</i>" ) ; return ; } reporter . pass ( act , expected , startingPage + url + "</i> loaded successfully" ) ; } catch ( Exception e ) { log . warn ( e ) ; reporter . fail ( act , expected , startingPage + url + "</i> did not load successfully" ) ; } app . acceptCertificate ( ) ; } }
Loads the initial app specified by the url and ensures the app loads successfully
36,011
protected void finish ( ) { Reporter reporter = this . reporterThreadLocal . get ( ) ; assertEquals ( "Detailed results found at: " + reporter . getFileName ( ) , "0 errors" , Integer . toString ( reporter . getFails ( ) ) + ERRORS_CHECK ) ; }
Concludes each test case . This should be run as the last time of each
36,012
private void setupScreenSize ( App app ) { String screensize = app . getBrowser ( ) . getScreensize ( ) ; if ( screensize != null ) { if ( screensize . matches ( "(\\d+)x(\\d+)" ) ) { int width = Integer . parseInt ( screensize . split ( "x" ) [ 0 ] ) ; int height = Integer . parseInt ( screensize . split ( "x" ) [ 1 ] ) ; app . resize ( width , height ) ; } else if ( "maximum" . equalsIgnoreCase ( screensize ) ) { app . maximize ( ) ; } else { log . error ( "Provided screensize does not match expected pattern" ) ; } } }
Sets up the initial size of the browser . Checks for the passed in parameter of screensize . If set to width x height sets the browser to that size ; if set to maximum maximizes the browser .
36,013
private void init ( WebDriver driver , Reporter reporter ) { this . driver = driver ; this . reporter = reporter ; App app = null ; if ( reporter != null ) { app = reporter . getApp ( ) ; } is = new Is ( this ) ; get = new Get ( app , driver , this ) ; verifyState = new VerifyState ( this , reporter ) ; assertState = new AssertState ( this , reporter ) ; waitForState = new WaitForState ( this , reporter ) ; verifyContains = new VerifyContains ( this , reporter ) ; assertContains = new AssertContains ( this , reporter ) ; verifyExcludes = new VerifyExcludes ( this , reporter ) ; assertExcludes = new AssertExcludes ( this , reporter ) ; verifyEquals = new VerifyEquals ( this , reporter ) ; assertEquals = new AssertEquals ( this , reporter ) ; waitForEquals = new WaitForEquals ( this , reporter ) ; verifyMatches = new VerifyMatches ( this , reporter ) ; assertMatches = new AssertMatches ( this , reporter ) ; }
A private method to finish setting up each element
36,014
private String prettyOutputStart ( String initialString ) { initialString += Reporter . ordinal ( match + 1 ) + " element with <i>" + type . toString ( ) + "</i> of <i>" + locator + "</i>" ; if ( parent != null ) { initialString = parent . prettyOutputStart ( initialString + " and parent of " ) ; } return initialString ; }
Builds the nicely HTML formatted output of the element by retrieving parent element information
36,015
public By defineByElement ( ) { By byElement = null ; switch ( type ) { case XPATH : byElement = By . xpath ( locator ) ; break ; case ID : byElement = By . id ( locator ) ; break ; case NAME : byElement = By . name ( locator ) ; break ; case CLASSNAME : byElement = By . className ( locator ) ; break ; case CSS : byElement = By . cssSelector ( locator ) ; break ; case LINKTEXT : byElement = By . linkText ( locator ) ; break ; case PARTIALLINKTEXT : byElement = By . partialLinkText ( locator ) ; break ; case TAGNAME : byElement = By . tagName ( locator ) ; break ; } return byElement ; }
Determines Selenium s By object using Webdriver
36,016
public WebElement getWebElement ( ) { List < WebElement > elements = getWebElements ( ) ; if ( elements . size ( ) > match ) { return elements . get ( match ) ; } String reason = this . prettyOutputStart ( ) + " was not located on the page" ; if ( ! elements . isEmpty ( ) ) { reason += ", but " + elements . size ( ) + " elements matching the locator were. Try using a lower match" ; } throw new NoSuchElementException ( reason ) ; }
Retrieves the identified matching web element using Webdriver . Use this sparingly only when the action you want to perform on the element isn t available as commands from it won t be checked logged caught or screenshotted .
36,017
public List < WebElement > getWebElements ( ) { if ( parent != null ) { return parent . getWebElement ( ) . findElements ( defineByElement ( ) ) ; } return driver . findElements ( defineByElement ( ) ) ; }
Retrieves all matching web elements using Webdriver . Use this sparingly only when the action you want to perform on the element isn t available as commands from it won t be checked logged caught or screenshotted .
36,018
public Element findChild ( Element child ) { return new Element ( child . getDriver ( ) , reporter , child . getType ( ) , child . getLocator ( ) , child . getMatch ( ) , this ) ; }
Searches for a child element within the element and creates and returns this new child element
36,019
private boolean isNotInput ( String action , String expected , String extra ) { if ( ! is . input ( ) ) { reporter . fail ( action , expected , extra + prettyOutput ( ) + NOT_AN_INPUT ) ; return true ; } return false ; }
Determines if the element is an input .
36,020
private boolean isSelect ( String action , String expected ) { if ( ! is . select ( ) ) { reporter . fail ( action , expected , Element . CANT_SELECT + prettyOutput ( ) + NOT_A_SELECT ) ; return false ; } return true ; }
Determines if the element is a select .
36,021
private boolean isNotPresentDisplayedEnabled ( String action , String expected , String extra ) { if ( isNotPresent ( action , expected , extra ) ) { return true ; } if ( isNotDisplayed ( action , expected , extra ) ) { return true ; } return isNotEnabled ( action , expected , extra ) ; }
Determines if something is present displayed and enabled . This returns true if all three are true otherwise it returns false
36,022
private boolean isNotPresentEnabledInput ( String action , String expected ) { if ( isNotPresent ( action , expected , Element . CANT_TYPE ) ) { return true ; } return isNotEnabled ( action , expected , Element . CANT_TYPE ) || isNotInput ( action , expected , Element . CANT_TYPE ) ; }
Determines if something is present enabled and an input . This returns true if all three are true otherwise it returns false
36,023
private boolean isNotPresentDisplayedEnabledInput ( String action , String expected , String extra ) { if ( isNotPresent ( action , expected , extra ) ) { return true ; } if ( isNotDisplayed ( action , expected , extra ) ) { return true ; } return isNotEnabled ( action , expected , extra ) || isNotInput ( action , expected , extra ) ; }
Determines if something is present displayed enabled and an input . This returns true if all four are true otherwise it returns false
36,024
private boolean isNotPresentDisplayedEnabledSelect ( String action , String expected ) { if ( isNotPresent ( action , expected , Element . CANT_SELECT ) ) { return true ; } if ( isNotDisplayed ( action , expected , Element . CANT_SELECT ) ) { return true ; } return isNotEnabled ( action , expected , Element . CANT_SELECT ) || ! isSelect ( action , expected ) ; }
Determines if something is present displayed enabled and a select . This returns true if all four are true otherwise it returns false
36,025
public void click ( ) { String cantClick = "Unable to click " ; String action = "Clicking " + prettyOutput ( ) ; String expected = prettyOutputStart ( ) + " is present, displayed, and enabled to be clicked" ; try { if ( isNotPresentDisplayedEnabled ( action , expected , cantClick ) ) { return ; } WebElement webElement = getWebElement ( ) ; webElement . click ( ) ; } catch ( Exception e ) { reporter . fail ( action , expected , cantClick + prettyOutputEnd ( ) + e . getMessage ( ) ) ; log . warn ( e ) ; return ; } reporter . pass ( action , expected , "Clicked " + prettyOutputEnd ( ) . trim ( ) ) ; }
Clicks on the element but only if the element is present displayed and enabled . If those conditions are not met the click action will be logged but skipped and the test will continue .
36,026
public void hover ( ) { String cantHover = "Unable to hover over " ; String action = "Hovering over " + prettyOutput ( ) ; String expected = prettyOutputStart ( ) + " is present, and displayed to be hovered over" ; try { if ( isNotPresent ( action , expected , cantHover ) ) { return ; } if ( isNotDisplayed ( action , expected , cantHover ) ) { return ; } Actions selAction = new Actions ( driver ) ; WebElement webElement = getWebElement ( ) ; selAction . moveToElement ( webElement ) . perform ( ) ; } catch ( Exception e ) { log . warn ( e ) ; reporter . fail ( action , expected , cantHover + prettyOutputEnd ( ) + e . getMessage ( ) ) ; return ; } reporter . pass ( action , expected , "Hovered over " + prettyOutputEnd ( ) . trim ( ) ) ; }
Hovers over the element but only if the element is present and displayed . If those conditions are not met the hover action will be logged but skipped and the test will continue .
36,027
public void focus ( ) { String cantFocus = "Unable to focus on " ; String action = "Focusing on " + prettyOutput ( ) ; String expected = prettyOutputStart ( ) + " is present, displayed, and enabled to be focused" ; try { if ( isNotPresentDisplayedEnabledInput ( action , expected , cantFocus ) ) { return ; } WebElement webElement = getWebElement ( ) ; new Actions ( driver ) . moveToElement ( webElement ) . perform ( ) ; } catch ( Exception e ) { log . warn ( e ) ; reporter . fail ( action , expected , cantFocus + prettyOutputEnd ( ) + e . getMessage ( ) ) ; return ; } reporter . pass ( action , expected , "Focused on " + prettyOutputEnd ( ) . trim ( ) ) ; }
Focuses on the element but only if the element is present displayed enabled and an input . If those conditions are not met the focus action will be logged but skipped and the test will continue .
36,028
public void type ( String text ) { String action = "Typing text '" + text + IN + prettyOutput ( ) ; String expected = prettyOutputStart ( ) + " is present, displayed, and enabled to have text " + text + " typed in" ; boolean warning = false ; try { if ( isNotPresentEnabledInput ( action , expected ) ) { return ; } if ( ! is . displayed ( ) ) { warning = true ; } WebElement webElement = getWebElement ( ) ; webElement . sendKeys ( text ) ; } catch ( Exception e ) { log . warn ( e ) ; reporter . fail ( action , expected , CANT_TYPE + prettyOutputEnd ( ) + e . getMessage ( ) ) ; return ; } if ( warning ) { reporter . check ( action , expected , TYPED + text + IN + prettyOutput ( ) + ". <b>THIS ELEMENT WAS NOT DISPLAYED. THIS MIGHT BE AN ISSUE.</b>" ) ; } else { reporter . pass ( action , expected , TYPED + text + IN + prettyOutputEnd ( ) . trim ( ) ) ; } }
Type the supplied text into the element but only if the element is present enabled and an input . If those conditions are not met the type action will be logged but skipped and the test will continue . If the element is not displayed a warning will be written in the log to indicate this is not a normal action as could be performed by the user .
36,029
public void clear ( ) { String cantClear = "Unable to clear " ; String action = "Clearing text in " + prettyOutput ( ) ; String expected = prettyOutputStart ( ) + " is present, displayed, and enabled to have text cleared" ; try { if ( isNotPresentDisplayedEnabledInput ( action , expected , cantClear ) ) { return ; } WebElement webElement = getWebElement ( ) ; webElement . clear ( ) ; } catch ( Exception e ) { log . warn ( e ) ; reporter . fail ( action , expected , cantClear + prettyOutputEnd ( ) + e . getMessage ( ) ) ; return ; } reporter . pass ( action , expected , "Cleared text in " + prettyOutputEnd ( ) . trim ( ) ) ; }
Clears text from the element but only if the element is present displayed enabled and an input . If those conditions are not met the clear action will be logged but skipped and the test will continue .
36,030
public void select ( int index ) { String action = SELECTING + index + " in " + prettyOutput ( ) ; String expected = prettyOutputStart ( ) + PRESENT_DISPLAYED_AND_ENABLED + index + SELECTED ; try { if ( isNotPresentDisplayedEnabledSelect ( action , expected ) ) { return ; } String [ ] options = get . selectOptions ( ) ; if ( index > options . length ) { reporter . fail ( action , expected , "Unable to select the <i>" + index + "</i> option, as there are only <i>" + options . length + "</i> available." ) ; return ; } WebElement webElement = getWebElement ( ) ; Select dropdown = new Select ( webElement ) ; dropdown . selectByIndex ( index ) ; } catch ( Exception e ) { log . warn ( e ) ; reporter . fail ( action , expected , CANT_SELECT + prettyOutputEnd ( ) + e . getMessage ( ) ) ; return ; } reporter . pass ( action , expected , "Selected option <b>" + index + INN + prettyOutputEnd ( ) . trim ( ) ) ; }
Selects the Nth option from the element starting from 0 but only if the element is present displayed enabled and an input . If those conditions are not met the select action will be logged but skipped and the test will continue .
36,031
public void selectOption ( String option ) { String action = SELECTING + option + " in " + prettyOutput ( ) ; String expected = prettyOutputStart ( ) + PRESENT_DISPLAYED_AND_ENABLED + option + SELECTED ; try { if ( isNotPresentDisplayedEnabledSelect ( action , expected ) ) { return ; } if ( ! Arrays . asList ( get . selectOptions ( ) ) . contains ( option ) ) { reporter . fail ( action , expected , CANT_SELECT + option + " in " + prettyOutput ( ) + " as that option isn't present. Available options are:<i><br/>&nbsp;&nbsp;&nbsp;" + String . join ( "<br/>&nbsp;&nbsp;&nbsp;" , get . selectOptions ( ) ) + "</i>" ) ; return ; } WebElement webElement = getWebElement ( ) ; Select dropdown = new Select ( webElement ) ; dropdown . selectByVisibleText ( option ) ; } catch ( Exception e ) { log . warn ( e ) ; reporter . fail ( action , expected , CANT_SELECT + prettyOutputEnd ( ) + e . getMessage ( ) ) ; return ; } reporter . pass ( action , expected , "Selected <b>" + option + INN + prettyOutputEnd ( ) . trim ( ) ) ; }
Selects the option from the dropdown matching the provided value but only if the element is present displayed enabled and an input . If those conditions are not met the select action will be logged but skipped and the test will continue .
36,032
public void selectValue ( String value ) { String action = SELECTING + value + " in " + prettyOutput ( ) ; String expected = prettyOutputStart ( ) + PRESENT_DISPLAYED_AND_ENABLED + value + SELECTED ; try { if ( isNotPresentDisplayedEnabledSelect ( action , expected ) ) { return ; } if ( ! Arrays . asList ( get . selectValues ( ) ) . contains ( value ) ) { reporter . fail ( action , expected , CANT_SELECT + value + " in " + prettyOutput ( ) + " as that value isn't present. Available values are:<i><br/>&nbsp;&nbsp;&nbsp;" + String . join ( "<br/>&nbsp;&nbsp;&nbsp;" , get . selectValues ( ) ) + "</i>" ) ; return ; } WebElement webElement = getWebElement ( ) ; Select dropdown = new Select ( webElement ) ; dropdown . selectByValue ( value ) ; } catch ( Exception e ) { log . warn ( e ) ; reporter . fail ( action , expected , CANT_SELECT + prettyOutputEnd ( ) + e . getMessage ( ) ) ; return ; } reporter . pass ( action , expected , "Selected <b>" + value + INN + prettyOutputEnd ( ) . trim ( ) ) ; }
Selects the value from the dropdown matching the provided value but only if the element is present displayed enabled and an input . If those conditions are not met the select action will be logged but skipped and the test will continue .
36,033
private void isScrolledTo ( String action , String expected ) { WebElement webElement = getWebElement ( ) ; long elementPosition = webElement . getLocation ( ) . getY ( ) ; JavascriptExecutor js = ( JavascriptExecutor ) driver ; int scrollHeight = ( ( Number ) js . executeScript ( "return document.documentElement.scrollTop || document.body.scrollTop;" ) ) . intValue ( ) ; int viewportHeight = ( ( Number ) js . executeScript ( "return Math.max(document.documentElement.clientHeight, window.innerHeight || 0);" ) ) . intValue ( ) ; if ( elementPosition < scrollHeight || elementPosition > viewportHeight + scrollHeight ) { reporter . fail ( action , expected , prettyOutputStart ( ) + " was scrolled to, but is not within the current viewport" ) ; } else { reporter . pass ( action , expected , prettyOutputStart ( ) + " is properly scrolled to and within the current viewport" ) ; } }
Determines if the element scrolled towards is now currently displayed on the screen
36,034
public void scrollTo ( ) { String action = "Scrolling screen to " + prettyOutput ( ) ; String expected = prettyOutputStart ( ) + " is now within the current viewport" ; try { if ( isNotPresent ( action , expected , CANT_SCROLL ) ) { return ; } WebElement webElement = getWebElement ( ) ; Actions builder = new Actions ( driver ) ; builder . moveToElement ( webElement ) ; } catch ( Exception e ) { cantScroll ( e , action , expected ) ; return ; } isScrolledTo ( action , expected ) ; }
Scrolls the page to the element making it displayed on the current viewport but only if the element is present . If that condition is not met the scroll action will be logged but skipped and the test will continue .
36,035
public void scrollTo ( long position ) { String action = "Scrolling screen to " + position + " pixels above " + prettyOutput ( ) ; String expected = prettyOutputStart ( ) + " is now within the current viewport" ; try { if ( isNotPresent ( action , expected , CANT_SCROLL ) ) { return ; } JavascriptExecutor jse = ( JavascriptExecutor ) driver ; WebElement webElement = getWebElement ( ) ; long elementPosition = webElement . getLocation ( ) . getY ( ) ; long newPosition = elementPosition - position ; jse . executeScript ( "window.scrollBy(0, " + newPosition + ")" ) ; } catch ( Exception e ) { cantScroll ( e , action , expected ) ; return ; } isScrolledTo ( action , expected ) ; }
Scrolls the page to the element leaving X pixels at the top of the viewport above it making it displayed on the current viewport but only if the element is present . If that condition is not met the scroll action will be logged but skipped and the test will continue .
36,036
public void draw ( List < Point < Integer , Integer > > points ) { if ( points . isEmpty ( ) ) { reporter . fail ( "Drawing object in " + prettyOutput ( ) , "Drew object in " + prettyOutput ( ) , "Unable to draw in " + prettyOutput ( ) + " as no points were supplied" ) ; return ; } StringBuilder pointString = new StringBuilder ( ) ; String prefix = "" ; for ( Point < Integer , Integer > point : points ) { pointString . append ( prefix ) ; prefix = " to " ; pointString . append ( "<i>" ) . append ( point . getX ( ) ) . append ( "x" ) . append ( point . getY ( ) ) . append ( "</i>" ) ; } String action = "Drawing object from " + pointString . toString ( ) + " in " + prettyOutput ( ) ; String expected = prettyOutputStart ( ) + " now has object drawn on it from " + pointString . toString ( ) ; try { if ( isNotPresentDisplayedEnabled ( action , expected , "Unable to drawn in " ) ) { return ; } WebElement webElement = getWebElement ( ) ; Actions builder = new Actions ( driver ) ; Point < Integer , Integer > firstPoint = points . get ( 0 ) ; points . remove ( 0 ) ; builder . moveToElement ( webElement , firstPoint . getX ( ) , firstPoint . getY ( ) ) . clickAndHold ( ) ; for ( Point < Integer , Integer > point : points ) { builder . moveByOffset ( point . getX ( ) , point . getY ( ) ) ; } Action drawAction = builder . release ( ) . build ( ) ; drawAction . perform ( ) ; } catch ( Exception e ) { log . error ( e ) ; reporter . fail ( action , expected , "Unable to draw in " + prettyOutputEnd ( ) + e . getMessage ( ) ) ; return ; } reporter . pass ( action , expected , "Drew object in " + prettyOutput ( ) + getScreenshot ( ) ) ; }
Simulates moving the mouse around while the cursor is pressed . Can be used for drawing on canvases or swiping on certain elements . Note this is not supported in HTMLUNIT
36,037
public void selectFrame ( ) { String cantSelect = "Unable to focus on frame " ; String action = "Focusing on frame " + prettyOutput ( ) ; String expected = "Frame " + prettyOutput ( ) + " is present, displayed, and focused" ; try { if ( isNotPresent ( action , expected , cantSelect ) ) { return ; } if ( isNotDisplayed ( action , expected , cantSelect ) ) { return ; } WebElement webElement = getWebElement ( ) ; driver . switchTo ( ) . frame ( webElement ) ; } catch ( Exception e ) { log . warn ( e ) ; reporter . fail ( action , expected , cantSelect + prettyOutputEnd ( ) + e . getMessage ( ) ) ; return ; } reporter . pass ( action , expected , "Focused on frame " + prettyOutputEnd ( ) . trim ( ) ) ; }
Selects the frame represented by the element but only if the element is present and displayed . If these conditions are not met the move action will be logged but skipped and the test will continue .
36,038
private String getScreenshot ( ) { WebElement webElement = getWebElement ( ) ; String imageLink = "<b><font class='fail'>No Image Preview</font></b>" ; try { imageLink = reporter . captureEntirePageScreenshot ( ) ; File image = new File ( reporter . getDirectory ( ) , imageLink . split ( "\"" ) [ 1 ] ) ; BufferedImage fullImg = ImageIO . read ( image ) ; org . openqa . selenium . Point point = webElement . getLocation ( ) ; int eleWidth = webElement . getSize ( ) . getWidth ( ) ; int eleHeight = webElement . getSize ( ) . getHeight ( ) ; BufferedImage eleScreenshot = fullImg . getSubimage ( point . getX ( ) , point . getY ( ) , eleWidth , eleHeight ) ; ImageIO . write ( eleScreenshot , "png" , image ) ; } catch ( WebDriverException | RasterFormatException | IOException e ) { log . error ( e ) ; } return imageLink ; }
Captures an image of the element and returns the html friendly link of it for use in the logging file . If there is a problem capturing the image an error message is returned instead .
36,039
public String selectedOption ( ) { if ( isNotPresentSelect ( ) ) { return null ; } WebElement webElement = element . getWebElement ( ) ; Select dropdown = new Select ( webElement ) ; WebElement option = dropdown . getFirstSelectedOption ( ) ; return option . getText ( ) ; }
Retrieves the selected option for the element . If the element isn t present or a select a null value will be returned .
36,040
public String selectedValue ( ) { if ( isNotPresentSelect ( ) ) { return null ; } WebElement webElement = element . getWebElement ( ) ; Select dropdown = new Select ( webElement ) ; WebElement option = dropdown . getFirstSelectedOption ( ) ; return option . getAttribute ( VALUE ) ; }
Retrieves the selected value for the element . If the element isn t present or a select a null value will be returned .
36,041
@ SuppressWarnings ( "squid:S1168" ) public String [ ] selectedValues ( ) { if ( isNotPresentSelect ( ) ) { return null ; } WebElement webElement = element . getWebElement ( ) ; Select dropdown = new Select ( webElement ) ; List < WebElement > options = dropdown . getAllSelectedOptions ( ) ; String [ ] stringOptions = new String [ options . size ( ) ] ; for ( int i = 0 ; i < options . size ( ) ; i ++ ) { stringOptions [ i ] = options . get ( i ) . getAttribute ( VALUE ) ; } return stringOptions ; }
Retrieves the selected values for the element . If the element isn t present or a select a null value will be returned .
36,042
public String text ( ) { if ( ! element . is ( ) . present ( ) ) { return null ; } WebElement webElement = element . getWebElement ( ) ; return webElement . getText ( ) ; }
Retrieves the text of the element . If the element isn t present a null value will be returned .
36,043
public String value ( ) { if ( ! element . is ( ) . present ( ) || ! element . is ( ) . input ( ) ) { return null ; } WebElement webElement = element . getWebElement ( ) ; return webElement . getAttribute ( VALUE ) ; }
Retrieves the value of the element . If the element isn t present or isn t an input a null value will be returned .
36,044
public String css ( String attribute ) { if ( ! element . is ( ) . present ( ) ) { return null ; } try { WebElement webElement = element . getWebElement ( ) ; return webElement . getCssValue ( attribute ) ; } catch ( NoSuchMethodError | Exception e ) { log . warn ( e ) ; return null ; } }
Retrieves the provided css attribute of the element . If the element isn t present the css attribute doesn t exist or the attributes can t be accessed a null value will be returned .
36,045
@ SuppressWarnings ( "unchecked" ) public Map < String , String > allAttributes ( ) { if ( ! element . is ( ) . present ( ) ) { return null ; } try { WebElement webElement = element . getWebElement ( ) ; JavascriptExecutor js = ( JavascriptExecutor ) driver ; return ( Map < String , String > ) js . executeScript ( "var items = {}; for (index = 0; index < arguments[0].attributes.length; ++index) { items[arguments[0].attributes[index].name] = arguments[0].attributes[index].value }; return items;" , webElement ) ; } catch ( NoSuchMethodError | Exception e ) { log . warn ( e ) ; return null ; } }
Retrieves all attributes of the element . If the element isn t present or the attributes can t be accessed a null value will be returned .
36,046
public Object eval ( String javascriptFunction ) { if ( ! element . is ( ) . present ( ) ) { return null ; } try { WebElement webElement = element . getWebElement ( ) ; JavascriptExecutor js = ( JavascriptExecutor ) driver ; return js . executeScript ( javascriptFunction , webElement ) ; } catch ( NoSuchMethodError | Exception e ) { log . warn ( e ) ; return null ; } }
Executes a provided script on the element and returns the output of that script . If the element doesn t exist or there is an error executing this script a null value will be returned .
36,047
public int numOfSelectOptions ( ) { if ( isNotPresentSelect ( ) ) { return - 1 ; } WebElement webElement = element . getWebElement ( ) ; Select dropdown = new Select ( webElement ) ; List < WebElement > options = dropdown . getOptions ( ) ; return options . size ( ) ; }
Retrieves the number of select options in the element . If the element isn t present or a select the returned response will be negative 1 .
36,048
@ SuppressWarnings ( "squid:S1168" ) public String [ ] selectOptions ( ) { if ( isNotPresentSelect ( ) ) { return null ; } WebElement webElement = element . getWebElement ( ) ; Select dropdown = new Select ( webElement ) ; List < WebElement > options = dropdown . getOptions ( ) ; String [ ] stringOptions = new String [ options . size ( ) ] ; for ( int i = 0 ; i < options . size ( ) ; i ++ ) { stringOptions [ i ] = options . get ( i ) . getText ( ) ; } return stringOptions ; }
Retrieves the select options in the element . If the element isn t present or a select a null value will be returned .
36,049
@ SuppressWarnings ( "squid:S1168" ) public Element tableRows ( ) { if ( ! element . is ( ) . present ( ) ) { return null ; } if ( ! element . is ( ) . table ( ) ) { return null ; } return element . findChild ( app . newElement ( Locator . TAGNAME , "tr" ) ) ; }
Retrieves the rows in the element . If the element isn t present or a table a null value will be returned . The rows will be returned in one element and they can be iterated through or selecting using the setMatch method
36,050
public int numOfTableColumns ( ) { Element rows = tableRows ( ) ; if ( rows == null ) { return - 1 ; } Element thCells = rows . findChild ( app . newElement ( Locator . TAGNAME , "th" ) ) ; Element tdCells = rows . findChild ( app . newElement ( Locator . TAGNAME , "td" ) ) ; return thCells . get ( ) . matchCount ( ) + tdCells . get ( ) . matchCount ( ) ; }
Retrieves the number of columns in the element . If the element isn t present or a table the returned response will be negative one
36,051
@ SuppressWarnings ( "squid:S1168" ) public Element tableRow ( int rowNum ) { Element rows = tableRows ( ) ; if ( rows == null ) { return null ; } if ( numOfTableRows ( ) < rowNum ) { return null ; } return rows . get ( rowNum ) ; }
Retrieves a specific row from the element . If the element isn t present or a table or doesn t have that many rows a null value will be returned .
36,052
public Element tableCell ( int rowNum , int colNum ) { Element row = tableRow ( rowNum ) ; if ( row == null || numOfTableColumns ( ) < colNum ) { return null ; } Element thCells = row . findChild ( app . newElement ( Locator . TAGNAME , "th" ) ) ; Element tdCells = row . findChild ( app . newElement ( Locator . TAGNAME , "td" ) ) ; if ( thCells . get ( ) . matchCount ( ) > colNum ) { return thCells . get ( colNum ) ; } else { return tdCells . get ( colNum - thCells . get ( ) . matchCount ( ) ) ; } }
Retrieves a specific cell from the element . If the element isn t present or a table or the row and cell combination doesn t exist a null value will be returned .
36,053
public Map < String , Object > getHeaders ( ) { Map < String , Object > map = new HashMap < > ( ) ; map . put ( "Content-length" , "0" ) ; map . put ( CONTENT_TYPE , contentType ) ; map . put ( "Accept" , "application/json" ) ; for ( Map . Entry < String , Object > entry : extraHeaders . entrySet ( ) ) { map . put ( entry . getKey ( ) , entry . getValue ( ) ) ; } return map ; }
Builds the headers to be passed in the HTTP call
36,054
public Response get ( String service , Request request ) throws IOException { return call ( Method . GET , service , request , null ) ; }
A basic http get call
36,055
public Response post ( String service , Request request , File file ) throws IOException { if ( file != null ) { this . contentType = MULTIPART + BOUNDARY ; } return call ( Method . POST , service , request , file ) ; }
A basic http post call
36,056
public Response put ( String service , Request request , File file ) throws IOException { if ( file != null ) { this . contentType = MULTIPART + BOUNDARY ; } return call ( Method . PUT , service , request , file ) ; }
A basic http put call
36,057
public Response delete ( String service , Request request , File file ) throws IOException { if ( file != null ) { this . contentType = MULTIPART + BOUNDARY ; } return call ( Method . DELETE , service , request , file ) ; }
A basic http delete call
36,058
public String getRequestParams ( Request request ) { StringBuilder params = new StringBuilder ( ) ; if ( request != null && request . getUrlParams ( ) != null ) { params . append ( "?" ) ; for ( String key : request . getUrlParams ( ) . keySet ( ) ) { params . append ( key ) ; params . append ( "=" ) ; params . append ( String . valueOf ( request . getUrlParams ( ) . get ( key ) ) ) ; params . append ( "&" ) ; } params . deleteCharAt ( params . length ( ) - 1 ) ; } return params . toString ( ) ; }
Returns a string representation of the parameters able to be appended to the url
36,059
private void setupHeaders ( HttpURLConnection connection ) { for ( Map . Entry < String , Object > entry : getHeaders ( ) . entrySet ( ) ) { connection . setRequestProperty ( entry . getKey ( ) , String . valueOf ( entry . getValue ( ) ) ) ; } connection . setDoOutput ( true ) ; connection . setDoInput ( true ) ; connection . setUseCaches ( false ) ; connection . setAllowUserInteraction ( false ) ; }
Setups up the header and basic connection information
36,060
private Response call ( Method method , String service , Request request , File file ) throws IOException { URL url = new URL ( this . serviceBaseUrl + service + getRequestParams ( request ) ) ; HttpURLConnection connection = getConnection ( url ) ; connection . setRequestMethod ( method . toString ( ) ) ; setupHeaders ( connection ) ; if ( useCredentials ( ) ) { String userpass = user + ":" + pass ; String encoding = new String ( Base64 . encodeBase64 ( userpass . getBytes ( ) ) ) ; connection . setRequestProperty ( "Authorization" , "Basic " + encoding ) ; } connection . connect ( ) ; if ( ( request != null && request . isPayload ( ) ) || file != null ) { if ( connection . getRequestProperty ( CONTENT_TYPE ) . startsWith ( "multipart/form-data" ) || ( request != null && request . getMultipartData ( ) != null ) || file != null ) { writeMultipartDataRequest ( connection , request , file ) ; } else if ( connection . getRequestProperty ( CONTENT_TYPE ) . startsWith ( "application/json" ) ) { writeJsonDataRequest ( connection , request ) ; } else { throw new InvalidHTTPException ( "Content-Type '" + connection . getRequestProperty ( CONTENT_TYPE ) + "' not currently supported by Selenified. Current supported types are " + "'application/json' and 'multipart/form-data'." ) ; } } return getResponse ( connection ) ; }
A basic generic http call
36,061
private HttpURLConnection getConnection ( URL url ) throws IOException { Proxy proxy = Proxy . NO_PROXY ; if ( Property . isProxySet ( ) ) { SocketAddress addr = new InetSocketAddress ( Property . getProxyHost ( ) , Property . getProxyPort ( ) ) ; proxy = new Proxy ( Proxy . Type . HTTP , addr ) ; } return ( HttpURLConnection ) url . openConnection ( proxy ) ; }
Opens the URL connection and if a proxy is provided uses the proxy to establish the connection
36,062
@ SuppressWarnings ( { "squid:S3776" , "squid:S2093" } ) private Response getResponse ( HttpURLConnection connection ) { int status ; Map headers ; try { status = connection . getResponseCode ( ) ; headers = connection . getHeaderFields ( ) ; } catch ( IOException e ) { log . error ( e ) ; return null ; } JsonObject object = null ; JsonArray array = null ; String data = null ; BufferedReader rd = null ; try { rd = new BufferedReader ( new InputStreamReader ( connection . getInputStream ( ) ) ) ; } catch ( IOException e ) { log . warn ( e ) ; try { rd = new BufferedReader ( new InputStreamReader ( connection . getErrorStream ( ) ) ) ; } catch ( NullPointerException ee ) { log . warn ( ee ) ; } } finally { StringBuilder sb = new StringBuilder ( ) ; String line ; if ( rd != null ) { try { while ( ( line = rd . readLine ( ) ) != null ) { sb . append ( line ) ; } } catch ( IOException e ) { log . error ( e ) ; } try { rd . close ( ) ; } catch ( IOException e ) { log . error ( e ) ; } data = sb . toString ( ) ; JsonParser parser = new JsonParser ( ) ; try { object = ( JsonObject ) parser . parse ( data ) ; } catch ( JsonSyntaxException | ClassCastException e ) { log . debug ( e ) ; try { array = ( JsonArray ) parser . parse ( data ) ; } catch ( JsonSyntaxException | ClassCastException ee ) { log . debug ( ee ) ; } } } } return new Response ( reporter , headers , status , object , array , data ) ; }
Extracts the response data from the open http connection
36,063
@ SuppressWarnings ( "rawtypes" ) public void transform ( ITestAnnotation annotation , Class testClass , Constructor testConstructor , Method testMethod ) { annotation . setInvocationCount ( StringUtils . countMatches ( getBrowser ( ) , "," ) + 1 ) ; }
overrides the basic TestNG transform function to provide dynamic access to an invocation count
36,064
private boolean isRealBrowser ( ) { Browser browser = capabilities . getBrowser ( ) ; return browser . getName ( ) != BrowserName . NONE && browser . getName ( ) != BrowserName . HTMLUNIT ; }
Determines if a real browser is being used . If the browser is NONE or HTMLUNIT it is not considered a real browser
36,065
private String generateFilename ( ) { String counter = "" ; if ( capabilities . getInstance ( ) > 0 ) { counter = "_" + capabilities . getInstance ( ) ; } return test + counter ; }
Generates a unique filename based on the package class method name and invocation count
36,066
private void setupFile ( ) { if ( ! new File ( directory ) . exists ( ) && ! new File ( directory ) . mkdirs ( ) ) { try { throw new IOException ( "Unable to create output directory" ) ; } catch ( IOException e ) { log . info ( e ) ; } } if ( ! file . exists ( ) ) { try { if ( ! file . createNewFile ( ) ) { throw new IOException ( "Unable to create output file" ) ; } } catch ( IOException e ) { log . error ( e ) ; } } }
Creates the directory and file to hold the test output file
36,067
private void replaceInFile ( String oldText , String newText ) { StringBuilder oldContent = new StringBuilder ( ) ; try ( FileReader fr = new FileReader ( file ) ; BufferedReader reader = new BufferedReader ( fr ) ) { String line ; while ( ( line = reader . readLine ( ) ) != null ) { oldContent . append ( line ) ; oldContent . append ( "\r\n" ) ; } } catch ( IOException e ) { log . error ( e ) ; } String newContent = oldContent . toString ( ) . replaceAll ( oldText , newText ) ; try ( FileWriter writer = new FileWriter ( file ) ) { writer . write ( newContent ) ; } catch ( IOException ioe ) { log . error ( ioe ) ; } }
Replaces an occurrence of a string within a file
36,068
private String getHtmlForPDFConversion ( ) throws IOException { StringBuilder oldContent = new StringBuilder ( ) ; FileReader fr = new FileReader ( file ) ; try ( BufferedReader reader = new BufferedReader ( fr ) ) { String line ; while ( ( line = reader . readLine ( ) ) != null ) { oldContent . append ( line ) ; oldContent . append ( "\r\n" ) ; } } String str = oldContent . toString ( ) . replaceAll ( "<script type='text/javascript'>(?s).*</script>" , "" ) . replaceAll ( "<tr>\\s*<th>View Results</th>(?s).*?</tr>" , "" ) . replaceAll ( "&nbsp;" , " " ) ; String imagePattern = "(<img(?s).*? src='(.*?)'(?s).*?)</img>" ; Pattern r = Pattern . compile ( imagePattern ) ; Matcher m = r . matcher ( str ) ; int imageCount = 0 ; while ( m . find ( ) ) { str = str . replaceFirst ( "<a href='javascript:void\\(0\\)'(?s).*?(<img(?s).*? src='(.*?)'(?s).*?)" + " style(?s).*?</img>" , "<a href=\"#image-" + imageCount + "\">View Screenshot</a>" ) ; str = str . replaceFirst ( "</body>" , "<p style='page-break-before: always' id='image-" + imageCount ++ + "'></p" + ">" + m . group ( ) . replaceAll ( "width='300px' style(?s).*?'>" , "height='600px' width='1000px'>" ) + "</body>" ) ; } return str ; }
Removes all elements that cannot be converted to pdf this method is to be used before converting the html file to pdf with openhtmltopdf . pdfboxout . PdfRendererBuilder
36,069
public String captureEntirePageScreenshot ( ) { String imageName = generateImageName ( ) ; String imageLink = generateImageLink ( imageName ) ; try { app . takeScreenshot ( imageName ) ; screenshots . add ( imageName ) ; } catch ( Exception e ) { log . error ( e ) ; imageLink = "<br/><b><font class='fail'>No Screenshot Available</font></b>" ; } return imageLink ; }
Captures the entire page screen shot and created an HTML file friendly link to place in the output file
36,070
private String getAction ( String check , double waitFor ) { String action = "" ; if ( waitFor > 0 ) { action = "Waiting up to " + waitFor + " seconds " + check ; } return action ; }
Helper to recordStep which takes in a check being performed and determines if a wait is occuring or not . If no wait no action is recorded . If a wait was performed that wait is added to the check and provided back as the action
36,071
private String getActual ( String actual , double timeTook ) { if ( timeTook > 0 ) { String lowercase = actual . substring ( 0 , 1 ) . toLowerCase ( ) ; actual = "After waiting for " + timeTook + " seconds, " + lowercase + actual . substring ( 1 ) ; } return actual ; }
Helper to recordStep which takes in some result and appends a time waited if appropriate . If timeTook is greater than zero some time was waited along with the action and the returned result will reflect that
36,072
public void pass ( String action , String expectedResult , String actualResult ) { passes ++ ; recordStep ( action , expectedResult , actualResult , false , Success . PASS ) ; }
Records the performed step as a pass to the output file . This includes the action taken if any the expected result and the actual result .
36,073
public void finalizeReporter ( int testStatus ) { try ( FileWriter fw = new FileWriter ( file , true ) ; BufferedWriter out = new BufferedWriter ( fw ) ) { out . write ( " </table>\n" ) ; out . write ( " </body>\n" ) ; out . write ( "</html>\n" ) ; } catch ( IOException e ) { log . error ( e ) ; } if ( ( fails + passes + checks ) != stepNum ) { log . error ( "There was some error recording your test steps. Step results don't equal steps performed" ) ; } replaceInFile ( "STEPSPERFORMED" , Integer . toString ( fails + passes + checks ) ) ; replaceInFile ( "STEPSPASSED" , Integer . toString ( passes ) ) ; replaceInFile ( "STEPSFAILED" , Integer . toString ( fails ) ) ; if ( fails == 0 && checks == 0 && testStatus == 0 ) { replaceInFile ( PASSORFAIL , "<font size='+2' class='pass'><b>PASS</b></font>" ) ; } else if ( fails == 0 ) { replaceInFile ( PASSORFAIL , "<font size='+2' class='check'><b>CHECK</b" + "></font>" ) ; } else { replaceInFile ( PASSORFAIL , "<font size='+2' class='fail'><b>FAIL</b></font>" ) ; } addTimeToReport ( ) ; if ( Property . packageResults ( ) ) { packageTestResults ( ) ; } if ( Property . generatePDF ( ) ) { generatePdf ( ) ; } }
Ends and closes the output test file . The HTML is properly ended and the file is analyzed to determine if the test passed or failed and that information is updated along with the overall timing of the test
36,074
private void addTimeToReport ( ) { SimpleDateFormat stf = new SimpleDateFormat ( "HH:mm:ss" ) ; String timeNow = stf . format ( new Date ( ) ) ; long totalTime = ( new Date ( ) ) . getTime ( ) - startTime ; long time = totalTime / 1000 ; StringBuilder seconds = new StringBuilder ( Integer . toString ( ( int ) ( time % 60 ) ) ) ; StringBuilder minutes = new StringBuilder ( Integer . toString ( ( int ) ( ( time % 3600 ) / 60 ) ) ) ; StringBuilder hours = new StringBuilder ( Integer . toString ( ( int ) ( time / 3600 ) ) ) ; for ( int i = 0 ; i < 2 ; i ++ ) { if ( seconds . length ( ) < 2 ) { seconds . insert ( 0 , "0" ) ; } if ( minutes . length ( ) < 2 ) { minutes . insert ( 0 , "0" ) ; } if ( hours . length ( ) < 2 ) { hours . insert ( 0 , "0" ) ; } } replaceInFile ( "RUNTIME" , hours + ":" + minutes + ":" + seconds ) ; replaceInFile ( "TIMEFINISHED" , timeNow ) ; }
Updates the output file with timing information including run time and finish time
36,075
private void generatePdf ( ) { File pdfFile = new File ( directory , filename + ".pdf" ) ; try ( OutputStream os = new FileOutputStream ( pdfFile ) ) { PdfRendererBuilder builder = new PdfRendererBuilder ( ) ; builder . withHtmlContent ( getHtmlForPDFConversion ( ) , "file://" + pdfFile . getAbsolutePath ( ) . replaceAll ( " " , "%20" ) ) ; builder . toStream ( os ) ; builder . run ( ) ; } catch ( Exception e ) { log . error ( e ) ; } }
Generates a pdf report in the same directory as the html report
36,076
private String generateImageLink ( String imageName ) { StringBuilder imageLink = new StringBuilder ( "<br/>" ) ; if ( imageName . length ( ) >= directory . length ( ) + 1 ) { imageLink . append ( ONCLICK_TOGGLE ) . append ( imageName . substring ( directory . length ( ) + 1 ) ) . append ( "\")'>Toggle Screenshot Thumbnail</a>" ) ; imageLink . append ( " <a href='javascript:void(0)' onclick='display(\"" ) . append ( imageName . substring ( directory . length ( ) + 1 ) ) . append ( "\")'>View Screenshot Fullscreen</a>" ) ; imageLink . append ( "<br/><img id='" ) . append ( imageName . substring ( directory . length ( ) + 1 ) ) . append ( "' border='1px' src='" ) . append ( imageName . substring ( directory . length ( ) + 1 ) ) . append ( "' width='" ) . append ( EMBEDDED_IMAGE_WIDTH ) . append ( "px' style='display:none;'></img>" ) ; } else { imageLink . append ( "<b><font class='fail'>No Image Preview</font></b>" ) ; } return imageLink . toString ( ) ; }
Generates the HTML friendly link for the image
36,077
public static String formatResponse ( Response response ) { if ( response == null ) { return "" ; } StringBuilder output = new StringBuilder ( ) ; if ( response . isData ( ) ) { output . append ( DIV_I ) ; Gson gson = new GsonBuilder ( ) . setPrettyPrinting ( ) . create ( ) ; if ( response . getArrayData ( ) != null ) { output . append ( gson . toJson ( response . getArrayData ( ) ) ) ; } if ( response . getObjectData ( ) != null ) { output . append ( gson . toJson ( response . getObjectData ( ) ) ) ; } output . append ( END_IDIV ) ; } return formatHTML ( output . toString ( ) ) ; }
Formats the response parameters to be prettily printed out in HTML
36,078
public static String formatKeyPair ( Map < String , Object > keyPairs ) { if ( keyPairs == null ) { return "" ; } StringBuilder stringBuilder = new StringBuilder ( ) ; for ( Map . Entry < String , Object > entry : keyPairs . entrySet ( ) ) { stringBuilder . append ( DIV ) ; stringBuilder . append ( entry . getKey ( ) ) ; stringBuilder . append ( " : " ) ; stringBuilder . append ( Reporter . formatHTML ( String . valueOf ( entry . getValue ( ) ) ) ) ; stringBuilder . append ( END_DIV ) ; } return stringBuilder . toString ( ) ; }
From an object map passed in building a key value set properly html formatted for used in reporting
36,079
public static String getRequestPayloadOutput ( Request params , File file ) { StringBuilder payload = new StringBuilder ( ) ; String uuid = getUUID ( ) ; payload . append ( ONCLICK_TOGGLE ) . append ( uuid ) . append ( "\")'>Toggle Payload</a> " ) ; payload . append ( SPAN_ID ) . append ( uuid ) . append ( DISPLAY_NONE ) ; if ( params != null && params . getJsonPayload ( ) != null ) { Gson gson = new GsonBuilder ( ) . setPrettyPrinting ( ) . create ( ) ; payload . append ( DIV ) ; payload . append ( formatHTML ( gson . toJson ( params . getJsonPayload ( ) ) ) ) ; payload . append ( END_DIV ) ; } if ( params != null && params . getMultipartData ( ) != null ) { for ( Map . Entry < String , Object > entry : params . getMultipartData ( ) . entrySet ( ) ) { payload . append ( DIV ) ; payload . append ( entry . getKey ( ) ) ; payload . append ( " : " ) ; payload . append ( entry . getValue ( ) ) ; payload . append ( END_DIV ) ; } } if ( file != null ) { payload . append ( "<div> with file: <a href='file:///" ) . append ( file . getAbsoluteFile ( ) ) . append ( "'>" ) . append ( file . getName ( ) ) . append ( "</a></div>" ) ; } payload . append ( END_SPAN ) ; if ( payload . toString ( ) . equals ( ONCLICK_TOGGLE + uuid + "\")'>Toggle Payload</a> " + SPAN_ID + uuid + DISPLAY_NONE + END_SPAN ) ) { return "" ; } else { return payload . toString ( ) ; } }
Formats the request parameters to be prettily printed out in HTML
36,080
public static String getCredentialStringOutput ( HTTP http ) { if ( http == null || ! http . useCredentials ( ) ) { return "" ; } StringBuilder credentials = new StringBuilder ( ) ; String uuid = getUUID ( ) ; credentials . append ( ONCLICK_TOGGLE ) . append ( uuid ) . append ( "\")'>Toggle Credentials</a> " ) ; credentials . append ( SPAN_ID ) . append ( uuid ) . append ( DISPLAY_NONE ) ; credentials . append ( "<div><i>" ) ; credentials . append ( "Username: " ) ; credentials . append ( http . getUser ( ) ) ; credentials . append ( "</div><div>" ) ; credentials . append ( "Password: " ) ; credentials . append ( http . getPass ( ) ) ; credentials . append ( "</i></div>" ) ; credentials . append ( END_SPAN ) ; return credentials . toString ( ) ; }
Looks for the simple login credentials username and password and if they are both set turns that into a string which will be formatted for HTML to be printed into the output file
36,081
public static String getRequestHeadersOutput ( HTTP http ) { if ( http == null ) { return "" ; } StringBuilder requestHeaders = new StringBuilder ( ) ; String uuid = getUUID ( ) ; requestHeaders . append ( ONCLICK_TOGGLE ) . append ( uuid ) . append ( "\")'>Toggle Headers</a> " ) ; requestHeaders . append ( SPAN_ID ) . append ( uuid ) . append ( DISPLAY_NONE ) ; requestHeaders . append ( formatKeyPair ( http . getHeaders ( ) ) ) ; requestHeaders . append ( END_SPAN ) ; return requestHeaders . toString ( ) ; }
Takes the headers set in the HTTP request and writes them to the output file in properly HTML formatted fashion
36,082
public static String getResponseHeadersOutput ( Response response ) { if ( response == null ) { return "" ; } StringBuilder responseHeaders = new StringBuilder ( ) ; String uuid = getUUID ( ) ; responseHeaders . append ( ONCLICK_TOGGLE ) . append ( uuid ) . append ( "\")'>Toggle Headers</a> " ) ; responseHeaders . append ( SPAN_ID ) . append ( uuid ) . append ( DISPLAY_NONE ) ; responseHeaders . append ( formatKeyPair ( response . getHeaders ( ) ) ) ; responseHeaders . append ( END_SPAN ) ; return responseHeaders . toString ( ) ; }
Takes the headers returned in the HTTP response and writes them to the output file in properly HTML formatted fashion
36,083
public static String getResponseCodeOutput ( Response response ) { if ( response == null ) { return "" ; } StringBuilder responseOutput = new StringBuilder ( ) ; String uuid = getUUID ( ) ; responseOutput . append ( ONCLICK_TOGGLE ) . append ( uuid ) . append ( "\")'>Toggle Response Status Code</a> " ) ; responseOutput . append ( SPAN_ID ) . append ( uuid ) . append ( DISPLAY_NONE ) ; responseOutput . append ( DIV ) . append ( response . getCode ( ) ) . append ( END_DIV ) ; responseOutput . append ( END_SPAN ) ; return responseOutput . toString ( ) ; }
Takes the response code returned in the HTTP response and writes them to the output file in properly HTML formatted fashion
36,084
public static String getResponseOutput ( Response response ) { if ( response == null || response . getMessage ( ) == null || "" . equals ( response . getMessage ( ) ) ) { return "" ; } StringBuilder responseOutput = new StringBuilder ( ) ; String uuid = getUUID ( ) ; responseOutput . append ( ONCLICK_TOGGLE ) . append ( uuid ) . append ( "\")'>Toggle Raw Response</a> " ) ; responseOutput . append ( SPAN_ID ) . append ( uuid ) . append ( DISPLAY_NONE ) ; responseOutput . append ( DIV ) . append ( response . getMessage ( ) ) . append ( END_DIV ) ; responseOutput . append ( END_SPAN ) ; return responseOutput . toString ( ) ; }
Takes the response returned from the HTTP call and writes it to the output file in properly HTML formatted fashion
36,085
public static String getUUID ( ) { long timeInSeconds = new Date ( ) . getTime ( ) ; String randomChars = TestCase . getRandomString ( 10 ) ; return timeInSeconds + "_" + randomChars ; }
Generates a unique id
36,086
public String url ( ) { try { return driver . getCurrentUrl ( ) ; } catch ( Exception e ) { log . warn ( e ) ; return null ; } }
Retrieves the current url of the application .
36,087
public String title ( ) { try { return driver . getTitle ( ) ; } catch ( Exception e ) { log . warn ( e ) ; return null ; } }
Retrieves the title of the current page the application is on
36,088
public String htmlSource ( ) { try { return driver . getPageSource ( ) ; } catch ( Exception e ) { log . warn ( e ) ; return null ; } }
Retrieves the full html source of the current page the application is on
36,089
public Object eval ( String javascriptFunction ) { try { JavascriptExecutor js = ( JavascriptExecutor ) driver ; return js . executeScript ( javascriptFunction ) ; } catch ( NoSuchMethodError | Exception e ) { log . warn ( e ) ; return null ; } }
Executes a provided script and returns the output of that script . If there is an error executing this script a null value will be returned .
36,090
public String confirmation ( ) { if ( ! is . confirmationPresent ( ) ) { return null ; } try { Alert alert = driver . switchTo ( ) . alert ( ) ; return alert . getText ( ) ; } catch ( Exception e ) { log . warn ( e ) ; return null ; } }
Retrieves the content of a confirmation present on the page . If the confirmation doesn t exist a null value will be returned .
36,091
public Cookie cookie ( String expectedCookieName ) { try { return driver . manage ( ) . getCookieNamed ( expectedCookieName ) ; } catch ( Exception e ) { log . warn ( e ) ; return null ; } }
Retrieves the full cookie in the application with the provided cookieName . If the cookie doesn t exist a null value will be returned .
36,092
public String cookieValue ( String expectedCookieName ) { Cookie cookie = cookie ( expectedCookieName ) ; if ( cookie != null ) { return cookie . getValue ( ) ; } return null ; }
Retrieves the cookie value in the application with the provided cookieName . If the cookie doesn t exist a null value will be returned .
36,093
public String cookiePath ( String expectedCookieName ) { Cookie cookie = cookie ( expectedCookieName ) ; if ( cookie != null ) { return cookie . getPath ( ) ; } return null ; }
Retrieves the cookie path in the application with the provided cookieName . If the cookie doesn t exist a null value will be returned .
36,094
public String cookieDomain ( String expectedCookieName ) { Cookie cookie = cookie ( expectedCookieName ) ; if ( cookie != null ) { return cookie . getDomain ( ) ; } return null ; }
Retrieves the cookie domain in the application with the provided cookieName . If the cookie doesn t exist a null value will be returned .
36,095
public Date cookieExpiration ( String expectedCookieName ) { Cookie cookie = cookie ( expectedCookieName ) ; if ( cookie != null ) { return cookie . getExpiry ( ) ; } return null ; }
Retrieves the cookie expiration in the application with the provided cookieName . If the cookie doesn t exist a null value will be returned .
36,096
public void urlEquals ( double seconds , String expectedURL ) { double end = System . currentTimeMillis ( ) + ( seconds * 1000 ) ; try { WebDriverWait wait = new WebDriverWait ( app . getDriver ( ) , ( long ) seconds , DEFAULT_POLLING_INTERVAL ) ; wait . until ( ExpectedConditions . urlToBe ( expectedURL ) ) ; double timeTook = Math . min ( ( seconds * 1000 ) - ( end - System . currentTimeMillis ( ) ) , seconds * 1000 ) / 1000 ; checkUrlEquals ( expectedURL , seconds , timeTook ) ; } catch ( TimeoutException e ) { checkUrlEquals ( expectedURL , seconds , seconds ) ; } }
Asserts that the provided URL equals the actual URL the application is currently on . This information will be logged and recorded with a screenshot for traceability and added debugging support .
36,097
private double popup ( double seconds ) { double end = System . currentTimeMillis ( ) + ( seconds * 1000 ) ; WebDriverWait wait = new WebDriverWait ( app . getDriver ( ) , ( long ) seconds , DEFAULT_POLLING_INTERVAL ) ; wait . until ( ExpectedConditions . alertIsPresent ( ) ) ; return Math . min ( ( seconds * 1000 ) - ( end - System . currentTimeMillis ( ) ) , seconds * 1000 ) / 1000 ; }
Wait for a popup to be present and then returns the amount of time that was waited
36,098
public void alertPresent ( double seconds ) { try { double timeTook = popup ( seconds ) ; checkAlertPresent ( seconds , timeTook ) ; } catch ( TimeoutException e ) { checkAlertPresent ( seconds , seconds ) ; } }
Asserts that an alert is present on the page . This information will be logged and recorded with a screenshot for traceability and added debugging support .
36,099
public void alertNotPresent ( double seconds ) { try { double timeTook = noPopup ( seconds ) ; checkAlertNotPresent ( seconds , timeTook ) ; } catch ( TimeoutException e ) { checkAlertNotPresent ( seconds , seconds ) ; } }
Waits up to the provided wait time for an alert is not present on the page . This information will be logged and recorded with a screenshot for traceability and added debugging support .