Best Python code snippet using elementium_python
helper.sub.js
Source:helper.sub.js  
1// Helpers called on the main test HTMLs.2// Functions in `RemoteContext.execute_script()`'s 1st argument are evaluated3// on the executors (`executor.html`), and helpers available on the executors4// are defined in `executor.html`.5const originSameOrigin =6  location.protocol === 'http:' ?7  'http://{{host}}:{{ports[http][0]}}' :8  'https://{{host}}:{{ports[https][0]}}';9const originSameSite =10  location.protocol === 'http:' ?11  'http://{{host}}:{{ports[http][1]}}' :12  'https://{{host}}:{{ports[https][1]}}';13const originCrossSite =14  location.protocol === 'http:' ?15  'http://{{hosts[alt][www]}}:{{ports[http][0]}}' :16  'https://{{hosts[alt][www]}}:{{ports[https][0]}}';17const executorPath =18  '/html/browsers/browsing-the-web/back-forward-cache/resources/executor.html?uuid=';19// Asserts that the executor `target` is (or isn't, respectively)20// restored from BFCache. These should be used in the following fashion:21// 1. Call prepareNavigation() on the executor `target`.22// 2. Navigate the executor to another page.23// 3. Navigate back to the executor `target`.24// 4. Call assert_bfcached() or assert_not_bfcached() on the main test HTML.25async function assert_bfcached(target) {26  const status = await getBFCachedStatus(target);27  assert_implements_optional(status === 'BFCached',28      "Should be BFCached but actually wasn't");29}30async function assert_not_bfcached(target) {31  const status = await getBFCachedStatus(target);32  assert_implements(status !== 'BFCached',33      'Should not be BFCached but actually was');34}35async function getBFCachedStatus(target) {36  const [loadCount, isPageshowFired, isPageshowPersisted] =37    await target.execute_script(() => [38        window.loadCount, window.isPageshowFired, window.isPageshowPersisted]);39  if (loadCount === 1 && isPageshowFired === true &&40      isPageshowPersisted === true) {41    return 'BFCached';42  } else if (loadCount === 2 && isPageshowFired === false) {43    return 'Not BFCached';44  } else {45    // This can occur for example when this is called before first navigating46    // away (loadCount = 1, isPageshowFired = false), e.g. when47    // 1. sending a script for navigation and then48    // 2. calling getBFCachedStatus() without waiting for the completion of49    //    the script on the `target` page.50    assert_unreached(51      `Got unexpected BFCache status: loadCount = ${loadCount}, ` +52      `isPageshowFired = ${isPageshowFired}, ` +53      `isPageshowPersisted = ${isPageshowPersisted}`);54  }55}56// Always call `await remoteContext.execute_script(waitForPageShow);` after57// triggering to navigation to the page, to wait for pageshow event on the58// remote context.59const waitForPageShow = () => window.pageShowPromise;60// Run a test that navigates A->B->A:61// 1. Page A is opened by `params.openFunc(url)`.62// 2. `params.funcBeforeNavigation` is executed on page A.63// 3. The window is navigated to page B on `params.targetOrigin`.64// 4. The window is back navigated to page A (expecting BFCached).65//66// Events `params.events` (an array of strings) are observed on page A and67// `params.expectedEvents` (an array of strings) is expected to be recorded.68// See `event-recorder.js` for event recording.69//70// Parameters can be omitted. See `defaultParams` below for default.71function runEventTest(params, description) {72  const defaultParams = {73    openFunc(url) {74      window.open(75        `${url}&events=${this.events.join(',')}`,76        '_blank',77        'noopener'78      )79    },80    events: ['pagehide', 'pageshow', 'load'],81    expectedEvents: [82      'window.load',83      'window.pageshow',84      'window.pagehide.persisted',85      'window.pageshow.persisted'86    ],87    async funcAfterAssertion(pageA) {88      assert_array_equals(89        await pageA.execute_script(() => getRecordedEvents()),90        this.expectedEvents);91    }92  }93  // Apply defaults.94  params = { ...defaultParams, ...params };95  runBfcacheTest(params, description);96}97async function navigateAndThenBack(pageA, pageB, urlB) {98  await pageA.execute_script(99    (url) => {100      prepareNavigation(() => {101        location.href = url;102      });103    },104    [urlB]105  );106  await pageB.execute_script(waitForPageShow);107  await pageB.execute_script(108    () => {109      prepareNavigation(() => { history.back(); });110    }111  );112  await pageA.execute_script(waitForPageShow);113}114function runBfcacheTest(params, description) {115  const defaultParams = {116    openFunc: url => window.open(url, '_blank', 'noopener'),117    scripts: [],118    funcBeforeNavigation: () => {},119    targetOrigin: originCrossSite,120    shouldBeCached: true,121    funcAfterAssertion: () => {},122  }123  // Apply defaults.124  params = {...defaultParams, ...params };125  promise_test(async t => {126    const pageA = new RemoteContext(token());127    const pageB = new RemoteContext(token());128    const urlA = executorPath + pageA.context_id;129    const urlB = params.targetOrigin + executorPath + pageB.context_id;130    params.openFunc(urlA);131    await pageA.execute_script(waitForPageShow);132    for (const src of params.scripts) {133      await pageA.execute_script((src) => {134        const script = document.createElement("script");135        script.src = src;136        document.head.append(script);137        return new Promise(resolve => script.onload = resolve);138      }, [src]);139    }140    await pageA.execute_script(params.funcBeforeNavigation);141    await navigateAndThenBack(pageA, pageB, urlB);142    if (params.shouldBeCached) {143      await assert_bfcached(pageA);144    } else {145      await assert_not_bfcached(pageA);146    }147    if (params.funcAfterAssertion) {148      await params.funcAfterAssertion(pageA, pageB);149    }150  }, description);...otworz_strony.py
Source:otworz_strony.py  
...1011driver = webdriver.Chrome(options=options)1213"""14driver.execute_script("Object.defineProperty(navigator, 'webdriver', {get: () => undefined})")15driver.execute_cdp_cmd('Network.setUserAgentOverride', {"userAgent": 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.53 Safari/537.36'})16print(driver.execute_script("return navigator.userAgent;"))17"""1819driver.get("https://phenotype.pl/")20driver.execute_script('''window.open("https://the100clth.pl/","_blank");''')21driver.execute_script('''window.open("https://animalswave.com/","_blank");''')22driver.execute_script('''window.open("https://relab.store/","_blank");''')23driver.execute_script('''window.open("https://hazel21.com/","_blank");''')24driver.execute_script('''window.open("https://zoology.pl/","_blank");''')25driver.execute_script('''window.open("https://premieresociety.com/pl/","_blank");''')26driver.execute_script('''window.open("https://hillswear.com/","_blank");''')27driver.execute_script('''window.open("https://www.snipes.pl/","_blank");''')28driver.execute_script('''window.open("https://www.alexanderbigwig.com/","_blank");''')29driver.execute_script('''window.open("https://inrablew.pl/pl/","_blank");''')30driver.execute_script('''window.open("https://mindstate.pl/pl/","_blank");''')31driver.execute_script('''window.open("https://zillamob.com/","_blank");''')32driver.execute_script('''window.open("https://majors.pl/","_blank");''')33driver.execute_script('''window.open("https://rareeverywhere.pl/","_blank");''')34driver.execute_script('''window.open("https://ideologyproject.com/store/","_blank");''')35driver.execute_script('''window.open("https://enragecustoms.pl/shop/","_blank");''')36driver.execute_script('''window.open("https://an-appendage.com/?v=9b7d173b068d&c=2a7c42566189","_blank");''')37driver.execute_script('''window.open("https://www.7more7.com/","_blank");''')38driver.execute_script('''window.open("https://velpa.pl/","_blank");''')39driver.execute_script('''window.open("https://debrande.pl/","_blank");''')40driver.execute_script('''window.open("https://www.gugushop.pl/","_blank");''')41driver.execute_script('''window.open("https://www.reserved.com/pl/pl/","_blank");''')42driver.execute_script('''window.open("https://www.zara.com/pl/","_blank");''')43driver.execute_script('''window.open("https://www.vangraaf.com/pl/","_blank");''')44driver.execute_script('''window.open("https://www.vitkac.com/pl","_blank");''')45driver.execute_script('''window.open("https://www.zalando-lounge.pl/event#","_blank");''')46driver.execute_script('''window.open("https://www.moliera2.com/","_blank");''')47driver.execute_script('''window.open("https://gomez.pl/pl/dla_niego","_blank");''')48driver.execute_script('''window.open("https://modivo.pl/m/mezczyzni.html","_blank");''')49driver.execute_script('''window.open("https://www.guess.eu/pl-pl/homepage","_blank");''')50driver.execute_script('''window.open("https://www.asos.com/pl/mezczyzni/","_blank");''')51driver.execute_script('''window.open("https://www.forpro.pl/","_blank");''')52driver.execute_script('''window.open("https://www.aboutyou.pl/","_blank");''')53driver.execute_script('''window.open("https://www.ataf.pl/pl/","_blank");''')54driver.execute_script('''window.open("https://www.nike.com/pl/","_blank");''')55driver.execute_script('''window.open("https://www.adidas.pl/","_blank");''')56driver.execute_script('''window.open("https://answear.com/c/on","_blank");''')57driver.execute_script('''window.open("https://www.peek-cloppenburg.pl/mezczyzni/","_blank");''')58driver.execute_script('''window.open("https://skstore.eu/pl","_blank");''')59driver.execute_script('''window.open("https://streetsupply.pl/","_blank");''')60driver.execute_script('''window.open("https://www.mandmdirect.pl/","_blank");''')61driver.execute_script('''window.open("https://worldbox.pl/","_blank");''')62driver.execute_script('''window.open("https://streetstyle24.pl/","_blank");''')63driver.execute_script('''window.open("https://eastendshop.com/pl/men-landing","_blank");''')64driver.execute_script('''window.open("https://runcolors.pl/","_blank");''')65driver.execute_script('''window.open("https://www.luisaviaroma.com/","_blank");''')66driver.execute_script('''window.open("https://warsawsneakerstore.com/","_blank");''')67driver.execute_script('''window.open("https://www.caliroots.com/pl","_blank");''')
...test_execute_script.py
Source:test_execute_script.py  
...5from errors import JavascriptException, MarionetteException6class TestExecuteContent(MarionetteTestCase):7    def test_stack_trace(self):8        try:9            self.marionette.execute_script("""10                let a = 1;11                return b;12                """)13            self.assertFalse(True)14        except JavascriptException, inst:15            self.assertTrue('return b' in inst.stacktrace)16    def test_execute_simple(self):17        self.assertEqual(1, self.marionette.execute_script("return 1;"))18    def test_check_window(self):19        self.assertTrue(self.marionette.execute_script("return (window !=null && window != undefined);"))20    def test_execute_no_return(self):21        self.assertEqual(self.marionette.execute_script("1;"), None)22    def test_execute_js_exception(self):23        self.assertRaises(JavascriptException,24            self.marionette.execute_script, "return foo(bar);")25    def test_execute_permission(self):26        self.assertRaises(JavascriptException,27                          self.marionette.execute_script,28                          """29let prefs = Components.classes["@mozilla.org/preferences-service;1"]30                              .getService(Components.interfaces.nsIPrefBranch);31""")32    def test_complex_return_values(self):33        self.assertEqual(self.marionette.execute_script("return [1, 2];"), [1, 2])34        self.assertEqual(self.marionette.execute_script("return {'foo': 'bar', 'fizz': 'fazz'};"),35                         {'foo': 'bar', 'fizz': 'fazz'})36        self.assertEqual(self.marionette.execute_script("return [1, {'foo': 'bar'}, 2];"),37                         [1, {'foo': 'bar'}, 2])38        self.assertEqual(self.marionette.execute_script("return {'foo': [1, 'a', 2]};"),39                         {'foo': [1, 'a', 2]})40    def test_sandbox_reuse(self):41        # Sandboxes between `execute_script()` invocations are shared.42        self.marionette.execute_script("this.foobar = [23, 42];")43        self.assertEqual(self.marionette.execute_script("return this.foobar;", new_sandbox=False), [23, 42])44        self.marionette.execute_script("global.barfoo = [42, 23];")45        self.assertEqual(self.marionette.execute_script("return global.barfoo;", new_sandbox=False), [42, 23])46    def test_that_we_can_pass_in_floats(self):47        expected_result = 1.248        result = self.marionette.execute_script("return arguments[0]",49                                                [expected_result])50        self.assertTrue(isinstance(result, float))51        self.assertEqual(result, expected_result)52class TestExecuteChrome(TestExecuteContent):53    def setUp(self):54        super(TestExecuteChrome, self).setUp()55        self.marionette.set_context("chrome")56    def test_execute_permission(self):57        self.assertEqual(1, self.marionette.execute_script("var c = Components.classes;return 1;"))58    def test_sandbox_reuse(self):...setup.py
Source:setup.py  
...11                      f"\tuser='{user}',\n",12                      f"\tpassword='{password}',\n",13                      f"\tdatabase='univ_db'\n)"])14# https://stackoverflow.com/questions/745538/create-function-through-mysqldb15def execute_script(fname, db):16    delimiter = ';'17    statement = ""18    with open(fname, encoding='utf-8') as f:19        for line in f.readlines():20            line = line.strip()21            if line.startswith('delimiter'):22                delimiter = line[10:]23            else:24                statement += line + '\n'25                if line.endswith(delimiter):26                    statement = statement.strip().strip(delimiter)27                    with db.cursor() as cursor:28                        try:29                            cursor.execute(statement)30                            db.commit()31                            statement = ""32                        except cursor.Error as e:33                            print(f"{fname} - error applying ({str(e)})\nstatement:{statement}\nterminating...")34                            sys.exit(1)35if __name__ == '__main__':36    print('enter connection parameters:')37    host = input('\thost (leave empty for default localhost): ') or 'localhost'38    port = input('\tport (leave empty for default 3307): ') or 330739    user = input('\tuser (leave empty for default root): ') or 'root'40    password = getpass.getpass(f'\tpassword for {user}: ')41    update_config(host, port, user, password)42    db = pymysql.connect(host=host, port=port, user=user, password=password)43    print('creating schema and tables...')44    tock = time.time()45    execute_script('./inserts/create_tables.sql', db)46    tick = time.time()47    print(f'\tdone in {(tick-tock):.3f} sec')48    db = pymysql.connect(host=host, port=port, user=user, password=password, database='univ_db')49    print('inserting data...')50    tock = time.time()51    execute_script('./inserts/faculties.sql', db)52    execute_script('./inserts/chairs.sql', db)53    execute_script('./inserts/teachers.sql', db)54    execute_script('./inserts/groups.sql', db)55    execute_script('./inserts/students.sql', db)56    execute_script('./inserts/subjects.sql', db)57    execute_script('./inserts/schedule.sql', db)58    execute_script('./inserts/mega_session.sql', db)59    tick = time.time()60    print(f'\tdone in {(tick-tock):.3f} sec')61    print('creating stored procedures...')62    tock = time.time()63    for i in range(1, 14):64        execute_script(f'./queries/task_{i}.sql', db)65    tick = time.time()66    print(f'\tdone in {(tick-tock):.3f} sec')...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!!
