Update example tests

This commit is contained in:
Michael Mintz 2023-02-17 23:55:54 -05:00
parent 6c91d14e89
commit 1993642049
26 changed files with 130 additions and 89 deletions

View File

@ -1,4 +1,5 @@
"""Use SeleniumBase to test the Coffee Cart App."""
from parameterized import parameterized
from seleniumbase import BaseCase
BaseCase.main(__name__, __file__)
@ -25,7 +26,8 @@ class CoffeeCartTests(BaseCase):
self.assert_exact_text("cart (0)", 'a[aria-label="Cart page"]')
self.assert_exact_text("Total: $0.00", 'button[data-test="checkout"]')
def test_coffee_promo_with_preview(self):
@parameterized.expand([[False], [True]])
def test_coffee_promo_with_preview(self, accept_promo):
self.open("https://seleniumbase.io/coffee/")
self.click('div[data-test="Espresso"]')
self.click('div[data-test="Americano"]')
@ -35,15 +37,23 @@ class CoffeeCartTests(BaseCase):
total_string = "Total: $33.00"
if self.is_element_visible("div.promo"):
self.assert_text("Get an extra cup of Mocha for $4.", "div.promo")
self.click("div.promo button.yes")
self.assert_exact_text("cart (4)", 'a[aria-label="Cart page"]')
promo = True
total_string = "Total: $37.00"
self.hover('button[data-test="checkout"]')
if accept_promo:
self.click("div.promo button.yes")
self.assert_exact_text("cart (4)", 'a[aria-label="Cart page"]')
promo = True
total_string = "Total: $37.00"
else:
self.click("div.promo button.no")
checkout_button = 'button[data-test="checkout"]'
if promo:
self.hover(checkout_button)
if not self.is_element_visible("ul.cart-preview"):
self.highlight(checkout_button)
self.post_message("STOP moving the mouse!<br />Hover blocked!")
self.hover(checkout_button)
self.assert_text("(Discounted) Mocha", "ul.cart-preview")
self.assert_exact_text(total_string, 'button[data-test="checkout"]')
self.click('button[data-test="checkout"]')
self.assert_exact_text(total_string, checkout_button)
self.click(checkout_button)
self.type("input#name", "Selenium Coffee")
self.type("input#email", "test@test.test")
self.click("button#submit-payment")

View File

@ -9,12 +9,12 @@ if __name__ == "__main__":
class EdgeTests(BaseCase):
def test_edge(self):
if self.browser != "edge":
self.open("data:,")
self.open("about:blank")
print("\n This test is only for Microsoft Edge (Chromium)!")
print(' (Run this test using "--edge" or "--browser=edge")')
self.skip('Use "--edge" or "--browser=edge"')
if self.headless:
self.open("data:,")
self.open("about:blank")
print("\n This test is NOT designed for Headless Mode!")
self.skip('Do NOT use "--headless" with this test!')
self.open("edge://settings/help")

View File

@ -43,7 +43,7 @@ class HackTests(BaseCase):
self.set_text_content('#shelf-1 a[href*="airtag"]', "TO")
self.set_text_content('#shelf-1 a[href*="tv"]', "US")
self.set_text_content('#shelf-1 a[href*="homepod"]', ".")
self.set_text_content("h2", aybabtu + ". ")
self.set_text_content("#shelf-3 h2", aybabtu + ". ")
self.highlight("div.rs-shop-subheader", loops=6, scroll=False)
self.highlight("#shelf-1", loops=2, scroll=False)
self.highlight('#shelf-1 a[href*="mac"]', loops=1, scroll=False)
@ -53,7 +53,7 @@ class HackTests(BaseCase):
self.highlight('#shelf-1 a[href*="airpod"]', loops=1, scroll=False)
self.highlight('#shelf-1 a[href*="airtag"]', loops=1, scroll=False)
self.highlight('#shelf-1 a[href*="tv"]', loops=3, scroll=False)
self.highlight("h2", loops=9, scroll=False)
self.highlight("#shelf-3 h2", loops=9, scroll=False)
self.open("https://google.com/ncr")
self.hide_elements("iframe")
@ -240,11 +240,11 @@ class HackTests(BaseCase):
self.set_text_content('li a:contains("Support")', "BELONG")
self.set_text_content('li a:contains("Blog")', "TO")
self.set_text_content('li a:contains("English")', "US")
self.set_text_content("div.lead", aybabtu)
self.set_text_content("div.mx-auto p", aybabtu)
self.set_text_content("h2", aybabtu)
if self.is_element_visible('button[data-dismiss="alert"] span'):
self.js_click('button[data-dismiss="alert"] span', scroll=False)
zoom_in = "div.lead{zoom: 1.25;-moz-transform: scale(1.25);}"
zoom_in = "div.mx-auto p{zoom: 1.1;-moz-transform: scale(1.1);}"
self.add_css_style(zoom_in)
self.highlight("div#main_navbar", loops=1, scroll=False)
self.highlight('li a:contains("ALL")', loops=1, scroll=False)
@ -254,7 +254,7 @@ class HackTests(BaseCase):
self.highlight('li a:contains("BELONG")', loops=1, scroll=False)
self.highlight('li a:contains("TO")', loops=1, scroll=False)
self.highlight('li a:contains("US")', loops=2, scroll=False)
self.highlight("div.lead", loops=6, scroll=False)
self.highlight("div.mx-auto p", loops=6, scroll=False)
self.highlight("h2", loops=8, scroll=False)
self.open("https://www.python.org/")
@ -284,6 +284,8 @@ class HackTests(BaseCase):
self.set_text_content('a[title="Plans & Pricing"]', aybabtu)
self.set_text_content('a[title="Get Started"]', ayb)
self.set_text_content("p.no-widows", aybabtu)
zoom_out = "h1{zoom: 0.8;-moz-transform: scale(0.8);}"
self.add_css_style(zoom_out)
self.set_text_content("h1.no-widows", aybabtu)
self.set_text_content("a#lpc-button", "Automate with SeleniumBase")
self.highlight('a[title="Plans & Pricing"]', loops=6, scroll=False)
@ -308,7 +310,6 @@ class HackTests(BaseCase):
self.set_text_content('a[href*="jira/pricing"]', ayb)
self.set_text_content('a[href*="jira/enterprise"]', abtu)
self.set_text_content('a[href="/software/jira/features"]', "")
self.set_text_content('a[href="/software/jira/guides"]', "")
self.set_text_content("h1", aybabtu)
self.highlight("ul.imkt-navbar__link-list", loops=2, scroll=False)
self.highlight('a[href*="jira/pricing"]', loops=3, scroll=False)

View File

@ -9,7 +9,7 @@ class OfflineTests(BaseCase):
def test_demo_page(self):
# Load a local html file into the web browser
dir_path = os.path.dirname(os.path.abspath(__file__))
file_path = dir_path + "/demo_page.html"
file_path = os.path.join(dir_path, "demo_page.html")
self.load_html_file(file_path)
# Assert the title of the current web page

View File

@ -6,14 +6,13 @@ BaseCase.main(__name__, __file__)
class SearchTests(BaseCase):
@parameterized.expand(
[
["site:Python.org Download", "Download Python", "img.python-logo"],
["site:SeleniumBase.io", "SeleniumBase", 'img[alt*="SeleniumB"]'],
["site:Wikipedia.org", "Wikipedia", "img.central-featured-logo"],
["SeleniumBase Commander", "Commander", "GUI / Commander"],
["SeleniumBase Recorder", "Recorder", "Recorder Mode"],
["SeleniumBase Syntax", "Syntax", "Syntax Formats"],
]
)
def test_parameterized_search(self, search_key, expected_text, img):
self.open("https://duckduckgo.com/")
self.type('input[name="q"]', search_key + "\n")
self.assert_text(expected_text, "div.results")
self.click('a:contains("%s")' % expected_text)
self.assert_element(img)
def test_parameterized_search(self, search_term, keyword, title_text):
self.open("https://seleniumbase.io/help_docs/how_it_works/")
self.type('input[aria-label="Search"]', search_term)
self.click('mark:contains("%s")' % keyword)
self.assert_title_contains(title_text)

View File

@ -30,6 +30,7 @@ BaseCase.main(__name__, __file__)
class PerformanceClass(BaseCase):
@decorators.print_runtime("Open Swag Labs and Log In")
def login_to_swag_labs(self):
print()
with decorators.print_runtime("Open Swag Labs"):
self.open("https://www.saucedemo.com")
self.type("#user-name", "standard_user")

View File

@ -5,6 +5,10 @@ BaseCase.main(__name__, __file__)
class ProxyTests(BaseCase):
def test_proxy(self):
if self.recorder_mode:
self.open("about:blank")
print("Skipping test in Recorder Mode.")
self.skip("Skipping test in Recorder Mode.")
settings.SKIP_JS_WAITS = True
if not self.page_load_strategy == "none":
# This page takes too long to load otherwise

View File

@ -14,6 +14,10 @@ class RateLimitingTests(BaseCase):
self.open("data:,")
print("Skipping test in multi-threaded mode.")
self.skip("Skipping test in multi-threaded mode.")
if self.recorder_mode:
self.open("data:,")
print("Skipping test in Recorder Mode.")
self.skip("Skipping test in Recorder Mode.")
message = "Running rate-limited print() on the command line"
self.open("data:text/html,<p>%s</p>" % message)
print("\n%s:" % message)

View File

@ -1,7 +1,10 @@
"""Call a file with "python" instead of "pytest".
"""Call a file with "python" instead of "pytest" directly.
Added pytest args from the command-line won't be included.
To run, use: "python raw_file_call.py"."""
from seleniumbase import BaseCase
BaseCase.main(__name__, __file__)
if __name__ == "__main__":
from pytest import main
main([__file__, "-s"])
class TinyMceTest(BaseCase):

View File

@ -1,5 +1,6 @@
"""Call a file with "python" instead of using "pytest" directly.
To run, type: "python raw_main_call.py"."""
Added pytest args will be included in the run.
To run, use: "python raw_file_call.py"."""
from seleniumbase import BaseCase
BaseCase.main(__name__, __file__)

View File

@ -6,6 +6,10 @@ BaseCase.main(__name__, __file__)
class ShadowRootTest(BaseCase):
def test_shadow_root(self):
if self.recorder_mode:
self.open("about:blank")
print("Skipping test in Recorder Mode.")
self.skip("Skipping test in Recorder Mode.")
self.open("https://seleniumbase.io/other/shadow_dom")
print("")
self.click("button.tab_1")

View File

@ -10,13 +10,17 @@ class AppleTests(BaseCase):
self.message_duration = 2.0
if self.headless:
if self._multithreaded:
self.open("data:,")
self.open("about:blank")
print("Skipping test in headless multi-threaded mode.")
self.skip("Skipping test in headless multi-threaded mode.")
elif self.undetectable:
self.open("data:,")
self.open("about:blank")
print("Skipping test in headless undetectable mode.")
self.skip("Skipping test in headless undetectable mode.")
elif self.recorder_mode:
self.open("about:blank")
print("Skipping test in headless Recorder Mode.")
self.skip("Skipping test in headless Recorder Mode.")
elif self.browser == "chrome" or self.browser == "edge":
self.get_new_driver(browser=self.browser, headless2=True)
self.open("https://developer.apple.com/search/")

View File

@ -33,20 +33,14 @@ class DownloadTests(BaseCase):
# Click the links to download the files into: "./downloaded_files/"
# (If using Safari, IE, or Chromium Guest Mode: download directly.)
# (The default Downloads Folder can't be changed when using those.)
# (The same problem occurs when using an out-of-date chromedriver.)
# (Use self.get_browser_downloads_folder() to get the folder used.)
whl_selector = 'div#files a[href$="%s"]' % whl_file
tar_selector = 'div#files a[href$="%s"]' % tar_gz_file
if (
self.browser == "safari"
or self.browser == "ie"
or (self.is_chromium() and self.guest_mode and not self.headless)
or (self.undetectable and (self.headless or self.headless2))
or (
self.is_chromium()
and int(self.get_chromium_version()) >= 110
and self.headless
)
or (self.is_chromium() and self.guest_mode)
or (self.is_chromium() and (self.headless or self.headless2))
):
whl_href = self.get_attribute(whl_selector, "href")
tar_href = self.get_attribute(tar_selector, "href")

View File

@ -25,6 +25,10 @@ class DownloadImages(BaseCase):
print(file_path)
def test_download_images_via_screenshot(self):
if self.recorder_mode:
self.open("about:blank")
print("Skipping test in Recorder Mode.")
self.skip("Skipping test in Recorder Mode.")
self.open("seleniumbase.io/error_page/")
img_elements_with_src = self.find_elements("img[src]")
unique_src_values = []

View File

@ -13,7 +13,7 @@ class SoupParsingTests(BaseCase):
the_id = soup.find(string=pattern).parent.parent.attrs["id"]
self.click("#%s" % the_id)
def test_beautiful_soup_and_tinymce(self):
def test_beautiful_soup_parsing(self):
self.open("https://seleniumbase.io/tinymce/")
self.wait_for_element("div.mce-container-body")
self.click_menu_item("File")

View File

@ -1,16 +1,24 @@
import pytest
@pytest.mark.parametrize("value", ["pytest", "selenium"])
@pytest.mark.parametrize(
"value", ["List of Features", "Command Line Options"]
)
def test_sb_fixture_with_no_class(sb, value):
sb.open("https://duckduckgo.com/")
sb.type('input[name="q"]', value + "\n")
sb.assert_text(value, "div.results")
sb.open("https://seleniumbase.io/help_docs/install/")
sb.type('input[aria-label="Search"]', value)
sb.click("nav h1 mark")
sb.assert_title_contains(value)
sb.assert_text(value, "div.md-content")
class Test_SB_Fixture:
@pytest.mark.parametrize("value", ["pytest", "selenium"])
@pytest.mark.parametrize(
"value", ["Console Scripts", "API Reference"]
)
def test_sb_fixture_inside_class(self, sb, value):
sb.open("https://duckduckgo.com/")
sb.type('input[name="q"]', value + "\n")
sb.assert_text(value, "div.results")
sb.open("https://seleniumbase.io/help_docs/install/")
sb.type('input[aria-label="Search"]', value)
sb.click("nav h1 mark")
sb.assert_title_contains(value)
sb.assert_text(value, "div.md-content")

View File

@ -1,17 +1,15 @@
# "sb" pytest fixture test in a method with no class
def test_sb_fixture_with_no_class(sb):
sb.open("https://google.com/ncr")
sb.remove_elements("iframe")
sb.type('input[title="Search"]', "SeleniumBase GitHub\n")
sb.click('a[href*="github.com/seleniumbase/SeleniumBase"]')
sb.click('a[title="seleniumbase"]')
sb.open("https://seleniumbase.io/help_docs/install/")
sb.type('input[aria-label="Search"]', "GUI Commander")
sb.click('mark:contains("Commander")')
sb.assert_title_contains("GUI / Commander")
# "sb" pytest fixture test in a method inside a class
class Test_SB_Fixture:
def test_sb_fixture_inside_class(self, sb):
sb.open("https://google.com/ncr")
sb.remove_elements("iframe")
sb.type('input[title="Search"]', "SeleniumBase GitHub\n")
sb.click('a[href*="github.com/seleniumbase/SeleniumBase"]')
sb.click('a[title="seleniumbase"]')
sb.open("https://seleniumbase.io/help_docs/install/")
sb.type('input[aria-label="Search"]', "GUI Commander")
sb.click('mark:contains("Commander")')
sb.assert_title_contains("GUI / Commander")

View File

@ -27,6 +27,10 @@ class ShadowDomTests(BaseCase):
self.open("about:blank")
print("\n This test doesn't run in headless mode!")
self.skip("This test doesn't run in headless mode!")
if self.recorder_mode:
self.open("about:blank")
print("Skipping test in Recorder Mode.")
self.skip("Skipping test in Recorder Mode.")
# Download Python package files from PyPI
file_name_1 = self.download_tar_file_from_pypi("sbase")

View File

@ -6,7 +6,6 @@ BaseCase.main(__name__, __file__)
class TodoMVC(BaseCase):
@parameterized.expand(
[
["angularjs"],
["mithril"],
["react"],
["vue"],

View File

@ -7,7 +7,7 @@ class MiaClasseDiTest(CasoDiProva):
def test_esempio_1(self):
self.apri("https://it.wikipedia.org/wiki/")
self.verificare_testo("Wikipedia")
self.verificare_elemento('[title="Lingua italiana"]')
self.verificare_elemento('a[title="Lingua italiana"]')
self.digitare("#searchInput", "Pizza")
self.fare_clic("#searchButton")
self.verificare_testo("Pizza", "#firstHeading")
@ -15,7 +15,7 @@ class MiaClasseDiTest(CasoDiProva):
self.digitare("#searchInput", "Colosseo")
self.fare_clic("#searchButton")
self.verificare_testo("Colosseo", "#firstHeading")
self.verificare_elemento('img[alt*="Colosse"]')
self.verificare_elemento('figure img[src*="Colosseo"]')
self.indietro()
self.verificare_url_contiene("Pizza")
self.avanti()

View File

@ -1,10 +1,13 @@
""" Run with pytest """
""" SeleniumBase Verification """
if __name__ == "__main__":
from pytest import main
main([__file__, "-v", "-s"])
def test_simple_cases(testdir):
def test_simple_cases(pytester):
"""Verify a simple passing test and a simple failing test.
The failing test is marked as xfail to have it skipped."""
testdir.makepyfile(
pytester.makepyfile(
"""
import pytest
from seleniumbase import BaseCase
@ -16,13 +19,13 @@ def test_simple_cases(testdir):
self.assert_equal('yes', 'no')
"""
)
result = testdir.inline_run("--headless", "--rs", "-v")
result = pytester.inline_run("--headless", "--rs", "-v")
assert result.matchreport("test_passing").passed
assert result.matchreport("test_failing").skipped
def test_basecase(testdir):
testdir.makepyfile(
def test_basecase(pytester):
pytester.makepyfile(
"""
from seleniumbase import BaseCase
class MyTest(BaseCase):
@ -34,12 +37,12 @@ def test_basecase(testdir):
self.click("body p") # selector
"""
)
result = testdir.inline_run("--headless", "-v")
result = pytester.inline_run("--headless", "-v")
assert result.matchreport("test_basecase").passed
def test_run_with_dashboard(testdir):
testdir.makepyfile(
def test_run_with_dashboard(pytester):
pytester.makepyfile(
"""
from seleniumbase import BaseCase
class MyTestCase(BaseCase):
@ -51,14 +54,14 @@ def test_run_with_dashboard(testdir):
self.skip("Skip!")
"""
)
result = testdir.inline_run("--headless", "--rs", "--dashboard", "-v")
result = pytester.inline_run("--headless", "--rs", "--dashboard", "-v")
assert result.matchreport("test_1_passing").passed
assert result.matchreport("test_2_failing").failed
assert result.matchreport("test_3_skipped").skipped
def test_sb_fixture(testdir):
testdir.makepyfile(
def test_sb_fixture(pytester):
pytester.makepyfile(
"""
def test_sb_fixture(sb):
sb.open("data:text/html,<p>Hello<br><input></p>")
@ -68,12 +71,12 @@ def test_sb_fixture(testdir):
sb.click("body p") # selector
"""
)
result = testdir.inline_run("--headless", "-v")
result = pytester.inline_run("--headless", "-v")
assert result.matchreport("test_sb_fixture").passed
def test_request_sb_fixture(testdir):
testdir.makepyfile(
def test_request_sb_fixture(pytester):
pytester.makepyfile(
"""
def test_request_sb_fixture(request):
sb = request.getfixturevalue('sb')
@ -85,7 +88,7 @@ def test_request_sb_fixture(testdir):
sb.tearDown()
"""
)
result = testdir.inline_run("--headless", "-v")
result = pytester.inline_run("--headless", "-v")
assert result.matchreport("test_request_sb_fixture").passed
@ -116,8 +119,8 @@ def assert_outcomes(
check_outcome_field(outcomes, "rerun", rerun)
def test_rerun_failures(testdir):
testdir.makepyfile(
def test_rerun_failures(pytester):
pytester.makepyfile(
"""
from seleniumbase import BaseCase
class MyTestCase(BaseCase):
@ -127,12 +130,12 @@ def test_rerun_failures(testdir):
self.assert_equal('yes', 'no')
"""
)
result = testdir.runpytest("--headless", "--reruns=1", "--rs", "-v")
result = pytester.runpytest("--headless", "--reruns=1", "--rs", "-v")
assert_outcomes(result, passed=1, failed=1, rerun=1)
def test_browser_launcher(testdir):
testdir.makepyfile(
def test_browser_launcher(pytester):
pytester.makepyfile(
"""
from seleniumbase import get_driver
def test_browser_launcher():
@ -148,12 +151,12 @@ def test_browser_launcher(testdir):
assert success
"""
)
result = testdir.inline_run("--headless", "-v")
result = pytester.inline_run("--headless", "-v")
assert result.matchreport("test_browser_launcher").passed
def test_framework_components(testdir):
testdir.makepyfile(
def test_framework_components(pytester):
pytester.makepyfile(
"""
from seleniumbase import get_driver
from seleniumbase import js_utils
@ -173,5 +176,5 @@ def test_framework_components(testdir):
assert success
"""
)
result = testdir.inline_run("--headless", "-v")
result = pytester.inline_run("--headless", "-v", "-s")
assert result.matchreport("test_framework_components").passed

View File

@ -10,7 +10,7 @@ if __name__ == "__main__":
class UndetectedTest(BaseCase):
def verify_success(self):
self.assert_text("OH YEAH, you passed!", "h1", timeout=6.25)
self.assert_text("OH YEAH, you passed!", "h1", timeout=6.75)
self.post_message("Selenium wasn't detected!", duration=2.8)
self._print("\n Success! Website did not detect Selenium! ")

View File

@ -4,7 +4,7 @@ BaseCase.main(__name__, __file__)
class VisualLayoutTests(BaseCase):
def test_applitools_layout_change(self):
self.open("https://applitools.com/helloworld?diff1")
self.open("https://applitools.com/helloworld/?diff1")
self.wait_for_element('a[href="?diff1"]')
print('\nCreating baseline in "visual_baseline" folder.')
self.sleep(0.06)

View File

@ -16,7 +16,7 @@ class VisualLayout_FixtureTests:
class VisualLayoutFailureTests(BaseCase):
def test_applitools_change(self):
self.open("https://applitools.com/helloworld?diff1")
self.open("https://applitools.com/helloworld/?diff1")
print('\nCreating baseline in "visual_baseline" folder.')
self.check_window(name="helloworld", baseline=True)
# Click a button that changes the text of an element