Best Balin code snippet using com.github.epadronu.balin.core.Browser.Browser.withFrame
Browser.kt
Source:Browser.kt  
1/******************************************************************************2 * Copyright 2016 Edinson E. Padrón Urdaneta3 *4 * Licensed under the Apache License, Version 2.0 (the "License");5 * you may not use this file except in compliance with the License.6 * You may obtain a copy of the License at7 *8 *     http://www.apache.org/licenses/LICENSE-2.09 *10 * Unless required by applicable law or agreed to in writing, software11 * distributed under the License is distributed on an "AS IS" BASIS,12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.13 * See the License for the specific language governing permissions and14 * limitations under the License.15 *****************************************************************************/16/* ***************************************************************************/17package com.github.epadronu.balin.core18/* ***************************************************************************/19/* ***************************************************************************/20import com.github.epadronu.balin.config.Configuration21import com.github.epadronu.balin.config.ConfigurationBuilder22import com.github.epadronu.balin.config.ConfigurationSetup23import com.github.epadronu.balin.exceptions.MissingPageUrlException24import com.github.epadronu.balin.exceptions.PageImplicitAtVerificationException25import com.github.epadronu.balin.utils.ThreadLocalDelegate26import org.openqa.selenium.Alert27import org.openqa.selenium.NoSuchWindowException28import org.openqa.selenium.WebDriver29import org.openqa.selenium.WebElement30import org.openqa.selenium.support.ui.ExpectedConditions.alertIsPresent31import kotlin.reflect.full.primaryConstructor32/* ***************************************************************************/33/* ***************************************************************************/34/**35 * Balin's backbone. The `Browser` interface binds together the different36 * abstractions that form part of the library.37 *38 * Additionally, this interface defines the entry point for the Domain-Specific39 * Language which Balin is built around.40 */41interface Browser : JavaScriptSupport, WaitingSupport, WebDriver {42    companion object {43        /**44         * The builder in charge of generating the configuration.45         */46        private val configurationBuilder: ConfigurationBuilder by ThreadLocalDelegate {47            ConfigurationBuilder()48        }49        /**50         * The name of the property that dictates which setup to use.51         */52        internal const val BALIN_SETUP_NAME_PROPERTY: String = "balin.setup.name"53        /**54         * Retrieves the configuration generated by the builder, taking in55         * account the value of the [BALIN_SETUP_NAME_PROPERTY] property.56         */57        internal val desiredConfiguration: ConfigurationSetup58            get() = configurationBuilder.build().run {59                setups[System.getProperty(BALIN_SETUP_NAME_PROPERTY) ?: "default"] ?: this60            }61        /**62         * Domain-Specific language that let's you configure Balin's global63         * behavior.64         *65         * @sample com.github.epadronu.balin.config.ConfigurationTests.call_the_configure_method_and_make_changes66         *67         * @param block here you can interact with the DSL.68         */69        fun configure(block: ConfigurationBuilder.() -> Unit) {70            block(configurationBuilder)71        }72        /**73         * This method represents the entry point for the Domain-Specific74         * Language which Balin is built around.75         *76         * `drive` is the main abstraction layer for Selenium-WebDriver. Inside77         * the [block] it receives as parameter, you can interact with the78         * driver and use all the features Balin has to offer.79         *80         * @sample com.github.epadronu.balin.core.BrowserTests.perform_a_simple_web_navigation81         *82         * @param driverFactory provides the driver on which the navigation and interactions will be performed.83         * @param autoQuit indicates if the driver should quit at the end of the [block].84         * @param block here you interact with the driver alongside of Balin's assistance.85         */86        fun drive(87            driverFactory: () -> WebDriver = desiredConfiguration.driverFactory,88            autoQuit: Boolean = desiredConfiguration.autoQuit,89            block: Browser.() -> Unit) = drive(Configuration(autoQuit, driverFactory), block)90        /**91         * This method represents the entry point for the Domain-Specific92         * Language which Balin is built around.93         *94         * `drive` is the main abstraction layer for Selenium-WebDriver. Inside95         * the [block] it receives as parameter, you can interact with the96         * driver and use all the features Balin has to offer.97         *98         * @sample com.github.epadronu.balin.core.BrowserTests.perform_a_simple_web_navigation99         *100         * @param configuration defines Balin's local behavior for [block] only.101         * @param block here you interact with the driver alongside of Balin's assistance.102         */103        fun drive(configuration: Configuration, block: Browser.() -> Unit) {104            val desiredConfiguration = configuration.run {105                setups[System.getProperty(BALIN_SETUP_NAME_PROPERTY) ?: "default"] ?: this106            }107            BrowserImpl(desiredConfiguration).apply {108                try {109                    block()110                } catch (throwable: Throwable) {111                    throw throwable112                } finally {113                    if (configurationSetup.autoQuit) {114                        quit()115                    }116                }117            }118        }119    }120    /**121     * Tells the browser at what page it should be located.122     *123     * If the page defines an _implicit at verification_, then it will be124     * invoked immediately. If such verification fails, Balin will throw a125     * [PageImplicitAtVerificationException] in order to perform an early126     * failure.127     *128     * @sample com.github.epadronu.balin.core.BrowserTests.model_a_page_into_a_Page_Object_and_interact_with_it_via_the_at_method129     *130     * @param T the page's type.131     * @param factory provides an instance of the page given the driver being used by the browser.132     * @Returns An instance of the current page.133     * @throws PageImplicitAtVerificationException if the page has an _implicit at verification_ which have failed.134     */135    fun <T : Page> at(factory: (Browser) -> T): T = factory(this).apply {136        if (!verifyAt()) {137            throw PageImplicitAtVerificationException()138        }139    }140    /**141     * Navigates to the given page.142     *143     * If the page has not defined a URL, then a144     * [MissingPageUrlException] will be thrown immediately since145     * is not possible to perform the navigation.146     *147     * If the page defines an _implicit at verification_, then it148     * will be invoked immediately. If such verification fails, Balin149     * will throw a [PageImplicitAtVerificationException] in order to150     * perform an early failure.151     *152     * @sample com.github.epadronu.balin.core.BrowserTests.perform_a_simple_web_navigation153     *154     * @param T the page's type.155     * @param factory provides an instance of the page given the driver being used by the browser.156     * @Returns An instance of the current page.157     * @throws MissingPageUrlException if the page has not defined a URL.158     * @throws PageImplicitAtVerificationException if the page has an _implicit at verification_ which have failed.159     * @see org.openqa.selenium.WebDriver.get160     */161    fun <T : Page> to(factory: (Browser) -> T): T = factory(this).apply {162        get(url ?: throw MissingPageUrlException())163        if (!verifyAt()) {164            throw PageImplicitAtVerificationException()165        }166    }167    /**168     * Navigates to the given URL.169     *170     * @param url the URL the browser will navigate to.171     * @return The browser's current URL.172     *173     * @see org.openqa.selenium.WebDriver.get174     */175    fun to(url: String): String {176        get(url)177        return currentUrl178    }179}180/* ***************************************************************************/181/* ***************************************************************************/182/**183 * Switches to the currently active modal dialog for this particular driver instance.184 *185 * You can interact with the dialog handler only inside [alertContext].186 *187 * @sample com.github.epadronu.balin.core.WithAlertTests.validate_context_switching_to_and_from_an_alert_popup_and_accept_it188 *189 * @param alertContext here you can interact with the dialog handler.190 * @throws org.openqa.selenium.NoAlertPresentException If the dialog cannot be found.191 */192inline fun Browser.withAlert(alertContext: Alert.() -> Unit): Unit = try {193    switchTo().alert().run {194        alertContext()195        if (this == alertIsPresent().apply(driver)) {196            dismiss()197        }198    }199} catch (throwable: Throwable) {200    throw throwable201} finally {202    switchTo().defaultContent()203}204/**205 * Select a frame by its (zero-based) index and switch the driver's context to206 * it.207 *208 * Once the frame has been selected, all subsequent calls on the WebDriver209 * interface are made to that frame till the end of [iFrameContext].210 *211 * If a exception is thrown inside [iFrameContext], the driver will return to212 * its default context.213 *214 * @sample com.github.epadronu.balin.core.WithFrameTests.validate_context_switching_to_and_from_an_iframe_with_index215 *216 * @param index (zero-based) index.217 * @param iFrameContext here you can interact with the given IFrame.218 * @throws org.openqa.selenium.NoSuchFrameException If the frame cannot be found.219 */220inline fun Browser.withFrame(index: Int, iFrameContext: () -> Unit): Unit = try {221    switchTo().frame(index)222    iFrameContext()223} catch (throwable: Throwable) {224    throw throwable225} finally {226    switchTo().defaultContent()227}228/**229 * Select a frame by its name or ID. Frames located by matching name attributes230 * are always given precedence over those matched by ID.231 *232 * Once the frame has been selected, all subsequent calls on the WebDriver233 * interface are made to that frame till the end of [iFrameContext].234 *235 * If a exception is thrown inside [iFrameContext], the driver will return to236 * its default context.237 *238 * @sample com.github.epadronu.balin.core.WithFrameTests.validate_context_switching_to_and_from_an_iframe_with_id239 *240 * @param nameOrId the name of the frame window, the id of the <frame> or <iframe> element, or the (zero-based) index.241 * @param iFrameContext here you can interact with the given IFrame.242 * @throws org.openqa.selenium.NoSuchFrameException If the frame cannot be found.243 */244inline fun Browser.withFrame(nameOrId: String, iFrameContext: () -> Unit): Unit = try {245    switchTo().frame(nameOrId)246    iFrameContext()247} catch (throwable: Throwable) {248    throw throwable249} finally {250    switchTo().defaultContent()251}252/**253 * Select a frame using its previously located WebElement.254 *255 * Once the frame has been selected, all subsequent calls on the WebDriver256 * interface are made to that frame till the end of [iFrameContext].257 *258 * If a exception is thrown inside [iFrameContext], the driver will return to259 * its default context.260 *261 * @sample com.github.epadronu.balin.core.WithFrameTests.validate_context_switching_to_and_from_an_iframe_with_web_element262 *263 * @param webElement the frame element to switch to.264 * @param iFrameContext here you can interact with the given IFrame.265 * @throws org.openqa.selenium.NoSuchFrameException If the frame cannot be found.266 */267inline fun Browser.withFrame(webElement: WebElement, iFrameContext: () -> Unit): Unit = try {268    switchTo().frame(webElement)269    iFrameContext()270} catch (throwable: Throwable) {271    throw throwable272} finally {273    switchTo().defaultContent()274}275/**276 * Select a frame by its (zero-based) index and switch the driver's context to277 * it.278 *279 * Once the frame has been selected, all subsequent calls on the WebDriver280 * interface are made to that frame via a `Page Object` of type [T] till281 * the end of [iFrameContext].282 *283 * If a exception is thrown inside [iFrameContext], the driver will return to284 * its default context.285 *286 * @sample com.github.epadronu.balin.core.WithFrameTests.validate_context_switching_to_and_from_an_iframe_with_index_and_pages287 *288 * @param T the `Page Object`'s type.289 * @param index (zero-based) index.290 * @param iFrameContext here you can interact with the given IFrame via a `Page Object`.291 * @throws org.openqa.selenium.NoSuchFrameException If the frame cannot be found.292 */293inline fun <reified T : Page> Browser.withFrame(index: Int, iFrameContext: T.() -> Unit): Unit = try {294    switchTo().frame(index)295    @Suppress("UNCHECKED_CAST")296    iFrameContext(at(T::class.primaryConstructor as (Browser) -> T))297} catch (throwable: Throwable) {298    throw throwable299} finally {300    switchTo().defaultContent()301}302/**303 * Select a frame by its name or ID. Frames located by matching name attributes304 * are always given precedence over those matched by ID.305 *306 * Once the frame has been selected, all subsequent calls on the WebDriver307 * interface are made to that frame via a `Page Object` of type [T] till308 * the end of [iFrameContext].309 *310 * If a exception is thrown inside [iFrameContext], the driver will return to311 * its default context.312 *313 * @sample com.github.epadronu.balin.core.WithFrameTests.validate_context_switching_to_and_from_an_iframe_with_id_and_pages314 *315 * @param T the `Page Object`'s type.316 * @param nameOrId the name of the frame window, the id of the <frame> or <iframe> element, or the (zero-based) index.317 * @param iFrameContext here you can interact with the given IFrame via a `Page Object`.318 * @throws org.openqa.selenium.NoSuchFrameException If the frame cannot be found.319 */320inline fun <reified T : Page> Browser.withFrame(nameOrId: String, iFrameContext: T.() -> Unit): Unit = try {321    switchTo().frame(nameOrId)322    @Suppress("UNCHECKED_CAST")323    iFrameContext(at(T::class.primaryConstructor as (Browser) -> T))324} catch (throwable: Throwable) {325    throw throwable326} finally {327    switchTo().defaultContent()328}329/**330 * Select a frame using its previously located WebElement.331 *332 * Once the frame has been selected, all subsequent calls on the WebDriver333 * interface are made to that frame via a `Page Object` of type [T] till334 * the end of [iFrameContext].335 *336 * If a exception is thrown inside [iFrameContext], the driver will return to337 * its default context.338 *339 * @sample com.github.epadronu.balin.core.WithFrameTests.validate_context_switching_to_and_from_an_iframe_with_web_element_and_pages340 *341 * @param T the `Page Object`'s type.342 * @param webElement the frame element to switch to.343 * @param iFrameContext here you can interact with the given IFrame via a `Page Object`.344 * @throws org.openqa.selenium.NoSuchFrameException If the frame cannot be found.345 */346inline fun <reified T : Page> Browser.withFrame(webElement: WebElement, iFrameContext: T.() -> Unit): Unit = try {347    switchTo().frame(webElement)348    @Suppress("UNCHECKED_CAST")349    iFrameContext(at(T::class.primaryConstructor as (Browser) -> T))350} catch (throwable: Throwable) {351    throw throwable352} finally {353    switchTo().defaultContent()354}355/**356 * Switch the focus of future commands for this driver to the window with the357 * given name/handle.358 *359 * The name/handle can be omitted and the switching will be performed360 * automatically if and only if there is only two windows currently361 * opened.362 *363 * Once the window has been selected, all subsequent calls on the WebDriver364 * interface are made to that window till the end of [windowContext].365 *366 * If a exception is thrown inside [windowContext], the driver will return to367 * the previous window.368 *369 * @sample com.github.epadronu.balin.core.WithWindowTests.validate_context_switching_to_and_from_a_window370 *371 * @param nameOrHandle The name of the window or the handle as returned by [WebDriver.getWindowHandle]372 * @param windowContext Here you can interact with the given window.373 * @throws NoSuchWindowException If the window cannot be found or, in the case of no name or handle is indicated,374 *                               there is not exactly two windows currently opened.375 */376inline fun Browser.withWindow(nameOrHandle: String? = null, windowContext: WebDriver.() -> Unit) {377    val originalWindow = windowHandle378    val targetWindow = nameOrHandle ?: windowHandles.toSet().minus(originalWindow).run {379        when (size) {380            0 -> throw NoSuchWindowException("No new window was found")381            1 -> first()382            else -> throw NoSuchWindowException("The window cannot be determined automatically")383        }384    }385    try {386        switchTo().window(targetWindow).windowContext()387    } catch (throwable: Throwable) {388        throw throwable389    } finally {390        if (originalWindow != targetWindow && windowHandles.contains(targetWindow)) {391            close()392        }393        switchTo().window(originalWindow)394    }395}396/* ***************************************************************************/...WithFrameTests.kt
Source:WithFrameTests.kt  
1/******************************************************************************2 * Copyright 2016 Edinson E. Padrón Urdaneta3 *4 * Licensed under the Apache License, Version 2.0 (the "License");5 * you may not use this file except in compliance with the License.6 * You may obtain a copy of the License at7 *8 *     http://www.apache.org/licenses/LICENSE-2.09 *10 * Unless required by applicable law or agreed to in writing, software11 * distributed under the License is distributed on an "AS IS" BASIS,12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.13 * See the License for the specific language governing permissions and14 * limitations under the License.15 *****************************************************************************/16/* ***************************************************************************/17package com.github.epadronu.balin.core18/* ***************************************************************************/19/* ***************************************************************************/20import com.github.epadronu.balin.extensions.`$`21import org.openqa.selenium.NoSuchFrameException22import org.openqa.selenium.WebDriver23import org.openqa.selenium.htmlunit.HtmlUnitDriver24import org.testng.Assert.assertEquals25import org.testng.Assert.assertThrows26import org.testng.Assert.fail27import org.testng.annotations.DataProvider28import org.testng.annotations.Test29import com.gargoylesoftware.htmlunit.BrowserVersion.FIREFOX_60 as BROWSER_VERSION30/* ***************************************************************************/31/* ***************************************************************************/32class WithFrameTests {33    companion object {34        @JvmStatic35        val pageWithIFramesUrl = WithFrameTests::class.java36            .getResource("/test-pages/page-with-iframes.html")37            .toString()38    }39    @DataProvider(name = "JavaScript-incapable WebDriver factory", parallel = true)40    fun `Create a JavaScript-incapable WebDriver factory`() = arrayOf(41        arrayOf({ HtmlUnitDriver(BROWSER_VERSION) })42    )43    @Test(description = "Validate context switching to and from an IFrame with index",44        dataProvider = "JavaScript-incapable WebDriver factory")45    fun validate_context_switching_to_and_from_an_iframe_with_index(driverFactory: () -> WebDriver) {46        Browser.drive(driverFactory) {47            // Given I navigate to the page under test, which contains three IFrames48            to(pageWithIFramesUrl)49            // And I'm in the context of the page50            assertEquals(`$`("h1", 0).text, "Page with IFrames")51            // When I change the driver's context to the second IFrame52            withFrame(1) {53                // Then I should be able to interact with such IFrame54                assertEquals(55                    `$`(".tag-home__item", 0).text.trim(),56                    "The search engine that doesn't track you. Learn More.")57            }58            // And I should return into the context of the page at the end of the `withFrame` method59            assertEquals(`$`("h1", 0).text, "Page with IFrames")60        }61    }62    @Test(description = "Validate context switching to and from an IFrame with ID",63        dataProvider = "JavaScript-incapable WebDriver factory")64    fun validate_context_switching_to_and_from_an_iframe_with_id(driverFactory: () -> WebDriver) {65        Browser.drive(driverFactory) {66            // Given I navigate to the page under test, which contains three IFrames67            to(pageWithIFramesUrl)68            // And I'm in the context of the page69            assertEquals(`$`("h1", 0).text, "Page with IFrames")70            // When I change the driver's context to the searx.me IFrame71            withFrame("searx-iframe") {72                // Then I should be able to interact with such IFrame73                assertEquals(`$`("#main-logo", 0).text.trim(), "searx")74            }75            // And I should return into the context of the page at the end of the `withFrame` method76            assertEquals(`$`("h1", 0).text, "Page with IFrames")77        }78    }79    @Test(description = "Validate context switching to and from an IFrame with WebElement",80        dataProvider = "JavaScript-incapable WebDriver factory")81    fun validate_context_switching_to_and_from_an_iframe_with_web_element(driverFactory: () -> WebDriver) {82        Browser.drive(driverFactory) {83            // Given I navigate to the page under test, which contains three IFrames84            to(pageWithIFramesUrl)85            // And I'm in the context of the page86            assertEquals(`$`("h1", 0).text, "Page with IFrames")87            // When I change the driver's context to the first IFrame88            withFrame(`$`("iframe", 0)) {89                // Then I should be able to interact with such IFrame90                assertEquals(`$`(".overview-header", 0).text, "Try Kotlin")91            }92            // And I should return into the context of the page at the end of the `withFrame` method93            assertEquals(`$`("h1", 0).text, "Page with IFrames")94        }95    }96    @Test(description = "Validate context switching to and from an IFrame with index and pages",97        dataProvider = "JavaScript-incapable WebDriver factory")98    fun validate_context_switching_to_and_from_an_iframe_with_index_and_pages(driverFactory: () -> WebDriver) {99        // Given a Page Object for the page under test, which contains three IFrames100        class IndexPage(browser: Browser) : Page(browser) {101            override val url = pageWithIFramesUrl102            override val at = at {103                title == "Page with IFrames"104            }105            val headerText106                get() = `$`("h1", 0).text107        }108        // And a Page Object for the DuckDuckGo IFrame109        class DuckDuckGoHomePage(browser: Browser) : Page(browser) {110            override val at = at {111                `$`(".cw--c > div > a", 0).text.trim() == "About DuckDuckGo"112            }113            val homeFooterText114                get() = `$`(".tag-home__item", 0).text.trim()115        }116        Browser.drive(driverFactory) {117            // And I navigate to the page under test118            val indexPage = to(::IndexPage)119            // And I'm in the context of such page120            assertEquals(indexPage.headerText, "Page with IFrames")121            // When I change the driver's context to DuckDuckGo IFrame122            withFrame<DuckDuckGoHomePage>(1) {123                // Then I should be able to interact with such IFrame via its Page Object124                assertEquals(homeFooterText, "The search engine that doesn't track you. Learn More.")125            }126            // And I should return into the context of the page under test at the end of the `withFrame` method127            assertEquals(indexPage.headerText, "Page with IFrames")128        }129    }130    @Test(description = "Validate context switching to and from an IFrame with ID and pages",131        dataProvider = "JavaScript-incapable WebDriver factory")132    fun validate_context_switching_to_and_from_an_iframe_with_id_and_pages(driverFactory: () -> WebDriver) {133        // Given a Page Object for the page under test, which contains three IFrames134        class IndexPage(browser: Browser) : Page(browser) {135            override val url = pageWithIFramesUrl136            override val at = at {137                title == "Page with IFrames"138            }139            val headerText140                get() = `$`("h1", 0).text141        }142        // And a Page Object for the searx.me IFrame143        class SearxHomePage(browser: Browser) : Page(browser) {144            override val at = at {145                `$`(".instance > a", 0).text.trim() == "searx.me"146            }147            val logoImageText148                get() = `$`("#main-logo", 0).text149        }150        Browser.drive(driverFactory) {151            // And I navigate to the page under test152            val indexPage = to(::IndexPage)153            // And I'm in the context of such page154            assertEquals(indexPage.headerText, "Page with IFrames")155            // When I change the driver's context to searx.me IFrame156            withFrame<SearxHomePage>("searx-iframe") {157                // Then I should be able to interact with such IFrame via its Page Object158                assertEquals(logoImageText, "searx")159            }160            // And I should return into the context of the page under test at the end of the `withFrame` method161            assertEquals(indexPage.headerText, "Page with IFrames")162        }163    }164    @Test(description = "Validate context switching to and from an IFrame with WebElement and pages",165        dataProvider = "JavaScript-incapable WebDriver factory")166    fun validate_context_switching_to_and_from_an_iframe_with_web_element_and_pages(driverFactory: () -> WebDriver) {167        // Given a Page Object for the page under test, which contains three IFrames168        class IndexPage(browser: Browser) : Page(browser) {169            override val url = pageWithIFramesUrl170            override val at = at {171                title == "Page with IFrames"172            }173            val headerText174                get() = `$`("h1", 0).text175        }176        // And a Page Object for the KotlinLang IFrame177        class KotlinLangIndexPage(browser: Browser) : Page(browser) {178            override val at = at {179                `$`("a.global-header-logo", 0).text == "Kotlin"180            }181            val tryKotlinHeaderText182                get() = `$`(".overview-header", 0).text183        }184        Browser.drive(driverFactory) {185            // And I navigate to the page under test186            val indexPage = to(::IndexPage)187            // And I'm in the context of such page188            assertEquals(indexPage.headerText, "Page with IFrames")189            // When I change the driver's context to KotlinLang IFrame190            withFrame<KotlinLangIndexPage>(`$`("iframe", 0)) {191                // Then I should be able to interact with such IFrame via its Page Object192                assertEquals(tryKotlinHeaderText, "Try Kotlin")193            }194            // And I should return into the context of the page under test at the end of the `withFrame` method195            assertEquals(indexPage.headerText, "Page with IFrames")196        }197    }198    @Test(dataProvider = "JavaScript-incapable WebDriver factory")199    fun `Frame switching should fail when an invalid IFrame index is provided`(driverFactory: () -> WebDriver) {200        Browser.drive(driverFactory) {201            // Given I navigate to the page under test, which contains three IFrames202            to(pageWithIFramesUrl)203            // When I change the driver's context via an invalid index204            // Then a failure should be communicated205            assertThrows(NoSuchFrameException::class.java) {206                withFrame(4) {207                    fail("This shouldn't be reached")208                }209            }210            // And I should return into the context of the page at the end of the `withFrame` method211            assertEquals(`$`("h1", 0).text, "Page with IFrames")212        }213    }214    @Test(dataProvider = "JavaScript-incapable WebDriver factory")215    fun `Frame switching should fail when an invalid IFrame ID is provided`(driverFactory: () -> WebDriver) {216        Browser.drive(driverFactory) {217            // Given I navigate to the page under test, which contains three IFrames218            to(pageWithIFramesUrl)219            // When I change the driver's context via an invalid ID220            // Then a failure should be communicated221            assertThrows(NoSuchFrameException::class.java) {222                withFrame("invalid-iframe") {223                    fail("This shouldn't be reached")224                }225            }226            // And I should return into the context of the page at the end of the `withFrame` method227            assertEquals(`$`("h1", 0).text, "Page with IFrames")228        }229    }230    @Test(dataProvider = "JavaScript-incapable WebDriver factory")231    fun `Frame switching should fail when a WebElement other than an IFrame is provided`(driverFactory: () -> WebDriver) {232        Browser.drive(driverFactory) {233            // Given I navigate to the page under test, which contains three IFrames234            to(pageWithIFramesUrl)235            // When I change the driver's context via a WebElement other than an IFrame236            // Then a failure should be communicated237            assertThrows(NoSuchFrameException::class.java) {238                withFrame(`$`("p", 0)) {239                    fail("This shouldn't be reached")240                }241            }242            // And I should return into the context of the page at the end of the `withFrame` method243            assertEquals(`$`("h1", 0).text, "Page with IFrames")244        }245    }246}247/* ***************************************************************************/...Browser.withFrame
Using AI Code Generation
1import com.github.epadronu.balin.core.Browser;2import com.github.epadronu.balin.core.BrowserFrame;3import org.openqa.selenium.WebDriver;4import org.openqa.selenium.WebElement;5import org.openqa.selenium.support.FindBy;6import org.testng.annotations.AfterMethod;7import org.testng.annotations.BeforeMethod;8import org.testng.annotations.Test;9import java.util.concurrent.TimeUnit;10import static org.assertj.core.api.Assertions.assertThat;11public class WithFrameTest {12    private WebDriver driver;13    private Browser browser;14    public void setUp() {15        driver = new HtmlUnitDriver() {16            public void switchTo() {17                getWrappedDriver().switchTo();18            }19        };20        browser = new Browser(driver);21        driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);22    }23    public void tearDown() {24        driver.quit();25    }26    public void withFrame() {27        browser.withFrame("mw-mf-main-menu", new BrowserFrame() {28            @FindBy(css = "a[href='/wiki/Wikipedia:About']")29            private WebElement aboutLink;30            public void run() {31                assertThat(aboutLink.isDisplayed()).isTrue();32            }33        });34    }35}36import com.github.epadronu.balin.core.Browser;37import com.github.epadronu.balin.core.BrowserFrame;38import org.openqa.selenium.WebDriver;39import org.openqa.selenium.WebElement;40import org.openqa.selenium.support.FindBy;41import org.testng.annotations.AfterMethod;42import org.testng.annotations.BeforeMethod;43import org.testng.annotations.Test;44import java.util.concurrent.TimeUnit;45import static org.assertj.core.api.Assertions.assertThat;46public class WithFrameTest {47    private WebDriver driver;48    private Browser browser;49    public void setUp() {50        driver = new HtmlUnitDriver() {51            public void switchTo() {52                getWrappedDriver().switchTo();53            }54        };55        browser = new Browser(driver);56        driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);57    }Browser.withFrame
Using AI Code Generation
1import com.github.epadronu.balin.core.Browser2import com.github.epadronu.balin.core.Browser.withFrame3import com.github.epadronu.balin.core.Browser.withFrame4Browser.withFrame(WebElement frame) {5}6import com.github.epadronu.balin.core.Browser7import com.github.epadronu.balin.core.Browser.withFrame8import com.github.epadronu.balin.core.Browser.withFrame9Browser.withFrame(WebElement frame) {10}11import com.github.epadronu.balin.core.Browser12import com.github.epadronu.balin.core.Browser.withFrame13import com.github.epadronu.balin.core.Browser.withFrame14Browser.withFrame(WebElement frame) {15}16import com.github.epadronu.balin.core.Browser17import com.github.epadronu.balin.core.Browser.withFrame18import com.github.epadronu.balin.core.Browser.withFrame19Browser.withFrame(WebElement frame) {20}21import com.github.epadronu.balin.core.Browser22import com.github.epadronu.balin.core.Browser.withFrame23import com.github.epadronu.balin.core.Browser.withFrame24Browser.withFrame(WebElement frame) {25}26import com.github.epadronu.balin.core.Browser27import com.github.epadronu.balin.core.Browser.withFrame28import com.github.epadronu.balin.core.Browser.withFrame29Browser.withFrame(WebElement frame) {30}Browser.withFrame
Using AI Code Generation
1Browser.withFrame("frameName", () -> {2    Browser.withFrame(0, () -> {3        Browser.withFrame(element, () -> {4            Browser.withFrame(By.id("id"), () -> {5                Browser.withFrame(Locator.id("id"), () -> {6                    Browser.withFrame("id", () -> {7                        Browser.withFrame(Locator.id("id"), () -> {8                            Browser.withFrame("id", () -> {9                                Browser.withFrame(Locator.id("id"), () -> {10                                    Browser.withFrame("id", () -> {11                                        Browser.withFrame(Locator.id("id"), () -> {Browser.withFrame
Using AI Code Generation
1		browser.withFrame(0).withFrame(2);2		browser.withFrame(0).withFrame("MyFrame");3		browser.withFrame(0).withFrame(frameWebElement);4		browser.withFrame("MyFrame").withFrame(0);5		browser.withFrame("MyFrame").withFrame(1);6		browser.withFrame("MyFrame").withFrame("MyFrame");7		browser.withFrame("MyFrame").withFrame(frameWebElement);8		browser.withFrame(frameWebElement).withFrame(0);9		browser.withFrame(frameWebElement).withFrame(1);Browser.withFrame
Using AI Code Generation
1import com.github.epadronu.balin.core.Browser;2import com.github.epadronu.balin.core.BrowserFactory;3import com.github.epadronu.balin.core.BrowserFactory.Browsers;4public class SwitchToFrame {5  public static void main(String[] args) {6    Browser browser = BrowserFactory.getBrowser(Browsers.Chrome);7    browser.withFrame("iframeResult", () -> {8      System.out.println(browser.getText("h1"));9    });10    browser.withFrame("iframeResult", () -> {11      browser.withFrame("frame", () -> {12        System.out.println(browser.getText("h1"));13      });14    });15    browser.withFrame("iframeResult", () -> {16      browser.withFrame("frame2", () -> {17        System.out.println(browser.getText("h1"));18      });19    });20    browser.close();21  }22}23import com.github.epadronu.balin.core.Browser;24import com.github.epadronu.balin.core.BrowserFactory;25import com.github.epadronu.balin.core.BrowserFactory.Browsers;26public class SwitchToFrame {27  public static void main(String[] args) {28    Browser browser = BrowserFactory.getBrowser(Browsers.Chrome);29    browser.withFrame("iframeResult", new Runnable() {30      public void run() {31        System.out.println(browser.getText("h1"));32      }33    });34    browser.withFrame("iframeResult", new Runnable() {35      public void run() {36        browser.withFrame("frame", new Runnable() {Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
