def __jq_confirm_dialog(self, question): count = self.manual_check_count + 1 title = self.DEFAULT_VALIDATION_TITLE title_content = ( '<center><font color="#7700bb">%s #%s:' '</font></center><hr><font color="#0066ff">%s</font>' "" % (title, count, question) ) title_content = js_utils.escape_quotes_if_needed(title_content) jqcd = ( """jconfirm({ boxWidth: '32.5%%', useBootstrap: false, containerFluid: false, animationBounce: 1, type: 'default', theme: 'bootstrap', typeAnimated: true, animation: 'scale', draggable: true, dragWindowGap: 1, container: 'body', title: '%s', content: '', buttons: { fail_button: { btnClass: 'btn-red', text: 'NO / FAIL', action: function(){ $jqc_status = "Failure!" } }, pass_button: { btnClass: 'btn-green', text: 'YES / PASS', action: function(){ $jqc_status = "Success!" } } } });""" % title_content ) self.execute_script(jqcd)
def jq_confirm_dialog(self, question): count = self.manual_check_count + 1 title_content = ('<center><font color="#7700bb">Manual Check #%s:' '</font></center><hr><font color="#0066ff">%s</font>' '' % (count, question)) title_content = js_utils.escape_quotes_if_needed(title_content) jqcd = ("""jconfirm({ boxWidth: '32.5%%', useBootstrap: false, containerFluid: false, animationBounce: 1, type: 'default', theme: 'bootstrap', typeAnimated: true, animation: 'scale', draggable: true, dragWindowGap: 1, container: 'body', title: '%s', content: '', buttons: { fail_button: { btnClass: 'btn-red', text: 'NO / FAIL', action: function(){ $jqc_status = "Failure!" } }, pass_button: { btnClass: 'btn-green', text: 'YES / PASS', action: function(){ $jqc_status = "Success!" } } } });""" % title_content) self.execute_script(jqcd)
def main(): expected_arg = ("[A PYTHON_WEBDRIVER_UNITTEST_FILE exported from a " "Katalon/Selenium-IDE recording].py") num_args = len(sys.argv) if sys.argv[0].split('/')[-1] == "seleniumbase" or ( sys.argv[0].split('\\')[-1] == "seleniumbase"): if num_args < 3 or num_args > 3: raise Exception('\n\n* INVALID RUN COMMAND! * Usage:\n' '"seleniumbase convert %s"\n' % expected_arg) else: if num_args < 2 or num_args > 2: raise Exception('\n\n* INVALID RUN COMMAND! * Usage:\n' '"python convert_ide.py %s"\n' % expected_arg) webdriver_python_file = sys.argv[num_args - 1] if not webdriver_python_file.endswith('.py'): raise Exception("\n\n`%s` is not a Python file!\n\n" "Expecting: %s\n" % (webdriver_python_file, expected_arg)) seleniumbase_lines = [] seleniumbase_lines.append("from seleniumbase import BaseCase") seleniumbase_lines.append("") # Flake8 is very specific on whitespace seleniumbase_lines.append("") ide_base_url = "" in_test_method = False has_unicode = False uses_keys = False uses_select = False f = open(webdriver_python_file, 'r') all_code = f.read() f.close() if "def test_" not in all_code: raise Exception("\n\n`%s` is not a valid Python unittest.TestCase " "file!\n\nExpecting: %s\n\n" "Did you properly export your Katalon/Selenium-IDE " "recording as a Python WebDriver unittest file?\n" % (webdriver_python_file, expected_arg)) code_lines = all_code.split('\n') for line in code_lines: # Handle utf-8 encoding if present data = re.findall(r'^\s*# -\*- coding: utf-8 -\*-\s*$', line) if data: has_unicode = True continue # Keep SeleniumBase classes if already used in the test script data = re.findall(r'^class\s\S+\(BaseCase\):\s*$', line) if data: seleniumbase_lines.append(line) continue # Have unittest.TestCase classes inherit BaseCase instead data = re.findall(r'^class\s\S+\(unittest\.TestCase\):\s*$', line) if data: data = data[0].replace("unittest.TestCase", "BaseCase") seleniumbase_lines.append(data) continue # Get base_url if defined data = re.match(r'^\s*self.base_url = "(\S+)"\s*$', line) if data: ide_base_url = data.group(1) continue # Handle method definitions data = re.match(r'^\s*def\s(\S+)\(self[,\s\S]*\):\s*$', line) if data: method_name = data.group(1) if method_name.startswith('test_'): in_test_method = True seleniumbase_lines.append("") seleniumbase_lines.append(data.group()) else: in_test_method = False continue # If not in a test method, skip if not in_test_method: continue # If a comment, skip if line.strip().startswith("#"): continue # If a blank line, skip if len(line.strip()) == 0: continue # If .clear(), skip because .update_text() already does this if line.strip().endswith(".clear()"): continue # Skip edge case data = re.findall(r'^\s*driver = self.driver\s*$', line) if data: continue # Handle page loads data = re.match( r'^(\s*)driver\.get\((self\.base_url \+ \"/\S*\")\)\s*$', line) if data: whitespace = data.group(1) url = data.group(2) url = url.replace("self.base_url", '"%s"' % ide_base_url) if '/" + "/' in url: url = url.replace('/" + "/', '/') if "/' + '/" in url: url = url.replace("/' + '/", "/") command = '''%sself.open(%s)''' % (whitespace, url) seleniumbase_lines.append(command) continue # Handle more page loads data = re.match( r'^(\s*)driver\.get\(\"(\S*)\"\)\s*$', line) if data: whitespace = data.group(1) url = data.group(2) command = '''%sself.open('%s')''' % (whitespace, url) seleniumbase_lines.append(command) continue # Handle .find_element_by_id() + .click() data = re.match( r'''^(\s*)driver\.find_element_by_id\(\"(\S+)\"\)''' r'''\.click\(\)\s*$''', line) if data: whitespace = data.group(1) selector = '#%s' % data.group(2).replace('#', '\\#') selector = selector.replace('[', '\\[').replace(']', '\\]') selector = selector.replace('.', '\\.') raw = "" if "\\[" in selector or "\\]" in selector or "\\." in selector: raw = "r" command = '''%sself.click(%s'%s')''' % (whitespace, raw, selector) seleniumbase_lines.append(command) continue # Handle .find_element_by_id() + .submit() data = re.match( r'''^(\s*)driver\.find_element_by_id\(\"(\S+)\"\)''' r'''\.submit\(\)\s*$''', line) if data: whitespace = data.group(1) selector = '#%s' % data.group(2).replace('#', '\\#') selector = selector.replace('[', '\\[').replace(']', '\\]') selector = selector.replace('.', '\\.') raw = "" if "\\[" in selector or "\\]" in selector or "\\." in selector: raw = "r" command = '''%sself.submit(%s'%s')''' % (whitespace, raw, selector) seleniumbase_lines.append(command) continue # Handle .find_element_by_id() + .send_keys() data = re.match( r'''^(\s*)driver\.find_element_by_id\(\"(\S+)\"\)''' r'''\.send_keys\(\"([\S\s]+)\"\)\s*$''', line) if data: whitespace = data.group(1) selector = '#%s' % data.group(2).replace('#', '\\#') selector = selector.replace('[', '\\[').replace(']', '\\]') selector = selector.replace('.', '\\.') raw = "" if "\\[" in selector or "\\]" in selector or "\\." in selector: raw = "r" text = data.group(3) command = '''%sself.update_text(%s'%s', '%s')''' % ( whitespace, raw, selector, text) seleniumbase_lines.append(command) continue # Handle .find_element_by_id() + .send_keys(Keys.<KEY>) data = re.match( r'''^(\s*)driver\.find_element_by_id\(\"(\S+)\"\)''' r'''\.send_keys\(Keys\.([\S]+)\)\s*$''', line) if data: uses_keys = True whitespace = data.group(1) selector = '#%s' % data.group(2).replace('#', '\\#') selector = selector.replace('[', '\\[').replace(']', '\\]') selector = selector.replace('.', '\\.') raw = "" if "\\[" in selector or "\\]" in selector or "\\." in selector: raw = "r" key = 'Keys.%s' % data.group(3) command = '''%sself.send_keys(%s'%s', %s)''' % ( whitespace, raw, selector, key) seleniumbase_lines.append(command) continue # Handle .find_element_by_name() + .click() data = re.match( r'''^(\s*)driver\.find_element_by_name\(\"(\S+)\"\)''' r'''\.click\(\)\s*$''', line) if data: whitespace = data.group(1) selector = '[name="%s"]' % data.group(2) command = '''%sself.click('%s')''' % (whitespace, selector) seleniumbase_lines.append(command) continue # Handle .find_element_by_name() + .submit() data = re.match( r'''^(\s*)driver\.find_element_by_name\(\"(\S+)\"\)''' r'''\.submit\(\)\s*$''', line) if data: whitespace = data.group(1) selector = '[name="%s"]' % data.group(2) command = '''%sself.submit('%s')''' % (whitespace, selector) seleniumbase_lines.append(command) continue # Handle .find_element_by_name() + .send_keys() data = re.match( r'''^(\s*)driver\.find_element_by_name\(\"(\S+)\"\)''' r'''\.send_keys\(\"([\S\s]+)\"\)\s*$''', line) if data: whitespace = data.group(1) selector = '[name="%s"]' % data.group(2) text = data.group(3) command = '''%sself.update_text('%s', '%s')''' % ( whitespace, selector, text) seleniumbase_lines.append(command) continue # Handle .find_element_by_name() + .send_keys(Keys.<KEY>) data = re.match( r'''^(\s*)driver\.find_element_by_name\(\"(\S+)\"\)''' r'''\.send_keys\(Keys\.([\S]+)\)\s*$''', line) if data: uses_keys = True whitespace = data.group(1) selector = '[name="%s"]' % data.group(2) key = 'Keys.%s' % data.group(3) command = '''%sself.send_keys('%s', %s)''' % ( whitespace, selector, key) seleniumbase_lines.append(command) continue # Handle .find_element_by_css_selector() + .click() data = re.match( r'''^(\s*)driver\.find_element_by_css_selector\(\"([\S\s]+)\"\)''' r'''\.click\(\)\s*$''', line) if data: whitespace = data.group(1) selector = '%s' % data.group(2) command = '''%sself.click('%s')''' % (whitespace, selector) if command.count('\\"') == command.count('"'): command = command.replace('\\"', '"') seleniumbase_lines.append(command) continue # Handle .find_element_by_css_selector() + .submit() data = re.match( r'''^(\s*)driver\.find_element_by_css_selector\(\"([\S\s]+)\"\)''' r'''\.submit\(\)\s*$''', line) if data: whitespace = data.group(1) selector = '%s' % data.group(2) command = '''%sself.submit('%s')''' % (whitespace, selector) if command.count('\\"') == command.count('"'): command = command.replace('\\"', '"') seleniumbase_lines.append(command) continue # Handle .find_element_by_css_selector() + .send_keys() data = re.match( r'''^(\s*)driver\.find_element_by_css_selector\(\"([\S\s]+)\"\)''' r'''\.send_keys\(\"([\S\s]+)\"\)\s*$''', line) if data: whitespace = data.group(1) selector = '%s' % data.group(2) text = data.group(3) command = '''%sself.update_text('%s', '%s')''' % ( whitespace, selector, text) if command.count('\\"') == command.count('"'): command = command.replace('\\"', '"') seleniumbase_lines.append(command) continue # Handle .find_element_by_css_selector() + .send_keys(Keys.<KEY>) data = re.match( r'''^(\s*)driver\.find_element_by_css_selector\(\"([\S\s]+)\"\)''' r'''\.send_keys\(Keys\.([\S]+)\)\s*$''', line) if data: uses_keys = True whitespace = data.group(1) selector = '%s' % data.group(2) key = 'Keys.%s' % data.group(3) command = '''%sself.send_keys('%s', %s)''' % ( whitespace, selector, key) if command.count('\\"') == command.count('"'): command = command.replace('\\"', '"') seleniumbase_lines.append(command) continue # Handle .find_element_by_xpath() + .send_keys() data = re.match( r'''^(\s*)driver\.find_element_by_xpath\(\"([\S\s]+)\"\)''' r'''\.send_keys\(\"([\S\s]+)\"\)\s*$''', line) if data: whitespace = data.group(1) selector = '%s' % data.group(2) text = data.group(3) command = '''%sself.update_text("%s", '%s')''' % ( whitespace, selector, text) if command.count('\\"') == command.count('"'): command = command.replace('\\"', '"') seleniumbase_lines.append(command) continue # Handle .find_element_by_xpath() + .send_keys(Keys.<KEY>) data = re.match( r'''^(\s*)driver\.find_element_by_xpath\(\"([\S\s]+)\"\)''' r'''\.send_keys\(Keys\.([\S]+)\)\s*$''', line) if data: uses_keys = True whitespace = data.group(1) selector = '%s' % data.group(2) key = 'Keys.%s' % data.group(3) command = '''%sself.send_keys("%s", %s)''' % ( whitespace, selector, key) if command.count('\\"') == command.count('"'): command = command.replace('\\"', '"') seleniumbase_lines.append(command) continue # Handle Select / by_css_selector() / select_by_visible_text() data = re.match( r'''^(\s*)Select\(driver\.find_element_by_css_selector\(''' r'''\"([\S\s]+)\"\)\)\.select_by_visible_text\(''' r'''\"([\S\s]+)\"\)\s*$''', line) if data: whitespace = data.group(1) selector = '%s' % data.group(2) visible_text = '%s' % data.group(3) command = '''%sself.select_option_by_text('%s', '%s')''' % ( whitespace, selector, visible_text) if command.count('\\"') == command.count('"'): command = command.replace('\\"', '"') seleniumbase_lines.append(command) continue # Handle Select / by_id() / select_by_visible_text() data = re.match( r'''^(\s*)Select\(driver\.find_element_by_id\(''' r'''\"([\S\s]+)\"\)\)\.select_by_visible_text\(''' r'''\"([\S\s]+)\"\)\s*$''', line) if data: whitespace = data.group(1) selector = '#%s' % data.group(2).replace('#', '\\#') selector = selector.replace('[', '\\[').replace(']', '\\]') selector = selector.replace('.', '\\.') raw = "" if "\\[" in selector or "\\]" in selector or "\\." in selector: raw = "r" visible_text = '%s' % data.group(3) command = '''%sself.select_option_by_text(%s'%s', '%s')''' % ( whitespace, raw, selector, visible_text) if command.count('\\"') == command.count('"'): command = command.replace('\\"', '"') seleniumbase_lines.append(command) continue # Handle Select / by_xpath() / select_by_visible_text() data = re.match( r'''^(\s*)Select\(driver\.find_element_by_xpath\(''' r'''\"([\S\s]+)\"\)\)\.select_by_visible_text\(''' r'''\"([\S\s]+)\"\)\s*$''', line) if data: whitespace = data.group(1) selector = '%s' % data.group(2) visible_text = '%s' % data.group(3) command = '''%sself.select_option_by_text("%s", '%s')''' % ( whitespace, selector, visible_text) if command.count('\\"') == command.count('"'): command = command.replace('\\"', '"') seleniumbase_lines.append(command) continue # Handle Select / by_name() / select_by_visible_text() data = re.match( r'''^(\s*)Select\(driver\.find_element_by_name\(''' r'''\"([\S\s]+)\"\)\)\.select_by_visible_text\(''' r'''\"([\S\s]+)\"\)\s*$''', line) if data: whitespace = data.group(1) selector = '[name="%s"]' % data.group(2) visible_text = '%s' % data.group(3) command = '''%sself.select_option_by_text('%s', '%s')''' % ( whitespace, selector, visible_text) if command.count('\\"') == command.count('"'): command = command.replace('\\"', '"') seleniumbase_lines.append(command) continue # Handle .find_element_by_xpath() + .click() data = re.match( r'''^(\s*)driver\.find_element_by_xpath\(u?\"([\S\s]+)\"\)''' r'''\.click\(\)\s*$''', line) if data: whitespace = data.group(1) xpath = '%s' % data.group(2) uni = "" if '(u"' in line: uni = "u" has_unicode = True command = '''%sself.click(%s"%s")''' % ( whitespace, uni, xpath) seleniumbase_lines.append(command) continue # Handle .find_element_by_xpath() + .submit() data = re.match( r'''^(\s*)driver\.find_element_by_xpath\(u?\"([\S\s]+)\"\)''' r'''\.submit\(\)\s*$''', line) if data: whitespace = data.group(1) xpath = '%s' % data.group(2) uni = "" if '(u"' in line: uni = "u" has_unicode = True command = '''%sself.submit(%s"%s")''' % ( whitespace, uni, xpath) seleniumbase_lines.append(command) continue # Handle .find_element_by_link_text() + .click() data = re.match( r'''^(\s*)driver\.find_element_by_link_text\(u?\"([\S\s]+)\"\)''' r'''\.click\(\)\s*$''', line) if data: whitespace = data.group(1) link_text = '''%s''' % data.group(2) uni = "" if '(u"' in line: uni = "u" has_unicode = True command = '''%sself.click(%s"link=%s")''' % ( whitespace, uni, link_text) seleniumbase_lines.append(command) continue # Handle self.is_element_present(By.LINK_TEXT, *) data = re.match( r'''^(\s*)([\S\s]*)self\.is_element_present\(By.LINK_TEXT, ''' r'''u?\"([\S\s]+)\"\)([\S\s]*)$''', line) if data: whitespace = data.group(1) pre = data.group(2) link_text = '''%s''' % data.group(3) post = data.group(4) uni = "" if '(u"' in line: uni = "u" has_unicode = True command = '''%s%sself.is_link_text_present(%s"%s")%s''' % ( whitespace, pre, uni, link_text, post) seleniumbase_lines.append(command) continue # Handle self.is_element_present(By.NAME, *) data = re.match( r'''^(\s*)([\S\s]*)self\.is_element_present\(By.NAME, ''' r'''u?\"([\S\s]+)\"\)([\S\s]*)$''', line) if data: whitespace = data.group(1) pre = data.group(2) name = '''%s''' % data.group(3) post = data.group(4) uni = "" if '(u"' in line: uni = "u" has_unicode = True command = '''%s%sself.is_element_present('[name="%s"]')%s''' % ( whitespace, pre, name, post) seleniumbase_lines.append(command) continue # Handle self.is_element_present(By.ID, *) data = re.match( r'''^(\s*)([\S\s]*)self\.is_element_present\(By.ID, ''' r'''u?\"([\S\s]+)\"\)([\S\s]*)$''', line) if data: whitespace = data.group(1) pre = data.group(2) the_id = '''%s''' % data.group(3) post = data.group(4) uni = "" if '(u"' in line: uni = "u" has_unicode = True command = '''%s%sself.is_element_present("#%s")%s''' % ( whitespace, pre, the_id, post) seleniumbase_lines.append(command) continue # Handle self.is_element_present(By.CLASS, *) data = re.match( r'''^(\s*)([\S\s]*)self\.is_element_present\(By.CLASS, ''' r'''u?\"([\S\s]+)\"\)([\S\s]*)$''', line) if data: whitespace = data.group(1) pre = data.group(2) the_class = '''%s''' % data.group(3) post = data.group(4) uni = "" if '(u"' in line: uni = "u" has_unicode = True command = '''%s%sself.is_element_present(".%s")%s''' % ( whitespace, pre, the_class, post) seleniumbase_lines.append(command) continue # Handle self.is_element_present(By.CSS_SELECTOR, *) data = re.match( r'''^(\s*)([\S\s]*)self\.is_element_present\(By.CSS_SELECTOR, ''' r'''u?\"([\S\s]+)\"\)([\S\s]*)$''', line) if data: whitespace = data.group(1) pre = data.group(2) selector = '''%s''' % data.group(3) post = data.group(4) uni = "" if '(u"' in line: uni = "u" has_unicode = True command = '''%s%sself.is_element_present("%s")%s''' % ( whitespace, pre, selector, post) seleniumbase_lines.append(command) continue # Handle self.is_element_present(By.XPATH, *) data = re.match( r'''^(\s*)([\S\s]*)self\.is_element_present\(By.XPATH, ''' r'''u?\"([\S\s]+)\"\)([\S\s]*)$''', line) if data: whitespace = data.group(1) pre = data.group(2) xpath = '''%s''' % data.group(3) post = data.group(4) uni = "" if '(u"' in line: uni = "u" has_unicode = True command = '''%s%sself.is_element_present("%s")%s''' % ( whitespace, pre, xpath, post) seleniumbase_lines.append(command) continue # Replace "self.base_url" with actual url if not already done if 'self.base_url' in line: line = line.replace("self.base_url", '"%s"' % ide_base_url) # Convert "driver." to "self.driver." if not already done if 'driver.' in line and 'self.driver' not in line: line = line.replace('driver.', 'self.driver.') # Add all other lines to final script without making changes seleniumbase_lines.append(line) # Chunk processing of inefficient waiting from Selenium IDE in_inefficient_wait = False whitespace = "" lines = seleniumbase_lines seleniumbase_lines = [] for line in lines: data = re.match(r'^(\s*)for i in range\(60\):\s*$', line) if data: in_inefficient_wait = True whitespace = data.group(1) continue data = re.match(r'^(\s*)else: self.fail\("time out"\)\s*$', line) if data: in_inefficient_wait = False continue if in_inefficient_wait: data = re.match( r'''^\s*if self.is_element_present\("([\S\s]+)"\)''' r''': break\s*$''', line) if data: selector = data.group(1) command = '%sself.wait_for_element("%s")' % ( whitespace, selector) seleniumbase_lines.append(command) continue data = re.match( r'''^\s*if self.is_element_present\('([\S\s]+)'\)''' r''': break\s*$''', line) if data: selector = data.group(1) command = "%sself.wait_for_element('%s')" % ( whitespace, selector) seleniumbase_lines.append(command) continue data = re.match( r'''^\s*if self.is_link_text_present''' r'''\("([\S\s]+)"\): break\s*$''', line) if data: uni = "" if '(u"' in line: uni = "u" link_text = data.group(1) command = '''%sself.wait_for_link_text(%s"%s")''' % ( whitespace, uni, link_text) seleniumbase_lines.append(command) continue else: seleniumbase_lines.append(line) continue # Is there a Select() still present? lines = seleniumbase_lines for line_num in range(len(lines)): if "Select(self.driver" in lines[line_num]: uses_select = True # Remove duplicate functionality (wait_for_element) lines = seleniumbase_lines seleniumbase_lines = [] num_lines = len(lines) for line_num in range(len(lines)): data = re.match( r'''^\s*self.wait_for_element''' r'''\((["|'])([\S\s]+)(["|'])\)''' r'''\s*$''', lines[line_num]) if data: # quote_type = data.group(1) selector = data.group(2) selector = re.escape(selector) selector = js_utils.escape_quotes_if_needed(selector) if int(line_num) < num_lines - 1: regex_string = (r'''^\s*self.click\(["|']''' '' + selector + r'''["|']\)\s*$''') data2 = re.match(regex_string, lines[line_num + 1]) if data2: continue regex_string = (r'''^\s*self.update_text\(["|']''' '' + selector + '' '' + r'''["|'], [\S\s]+\)\s*$''') data2 = re.match(regex_string, lines[line_num + 1]) if data2: continue seleniumbase_lines.append(lines[line_num]) # Remove duplicate functionality (wait_for_link_text) lines = seleniumbase_lines seleniumbase_lines = [] num_lines = len(lines) for line_num in range(len(lines)): data = re.match( r'''^\s*self.wait_for_link_text''' r'''\((["|'])([\S\s]+)(["|'])\)''' r'''\s*$''', lines[line_num]) if data: # quote_type = data.group(1) link_text = data.group(2) link_text = re.escape(link_text) link_text = js_utils.escape_quotes_if_needed(link_text) if int(line_num) < num_lines - 2: regex_string = (r'''^\s*self.click\(["|']link=''' '' + link_text + r'''["|']\)\s*$''') data2 = re.match(regex_string, lines[line_num + 1]) if data2: continue seleniumbase_lines.append(lines[line_num]) seleniumbase_code = "" if has_unicode: seleniumbase_code = "# -*- coding: utf-8 -*-\n" if uses_keys: seleniumbase_code += ( "from selenium.webdriver.common.keys import Keys\n") if uses_select: seleniumbase_code += ( "from selenium.webdriver.support.ui import Select\n") for line in seleniumbase_lines: seleniumbase_code += line seleniumbase_code += "\n" # print(seleniumbase_code) # (For debugging) # Create SeleniumBase test file base_file_name = webdriver_python_file.split('.py')[0] converted_file_name = base_file_name + "_SB.py" out_file = codecs.open(converted_file_name, "w+") out_file.writelines(seleniumbase_code) out_file.close() print('\n>>> [%s] was created from [%s]\n' % ( converted_file_name, webdriver_python_file))
def main(): expected_arg = ("[A PYTHON_WEBDRIVER_UNITTEST_FILE exported from a " "Katalon/Selenium-IDE recording].py") num_args = len(sys.argv) if sys.argv[0].split('/')[-1] == "seleniumbase" or ( sys.argv[0].split('\\')[-1] == "seleniumbase"): if num_args < 3 or num_args > 3: raise Exception('\n\n* INVALID RUN COMMAND! * Usage:\n' '"seleniumbase convert %s"\n' % expected_arg) else: if num_args < 2 or num_args > 2: raise Exception('\n\n* INVALID RUN COMMAND! * Usage:\n' '"python convert_ide.py %s"\n' % expected_arg) webdriver_python_file = sys.argv[num_args - 1] if not webdriver_python_file.endswith('.py'): raise Exception("\n\n`%s` is not a Python file!\n\n" "Expecting: %s\n" % (webdriver_python_file, expected_arg)) seleniumbase_lines = [] seleniumbase_lines.append("from seleniumbase import BaseCase") seleniumbase_lines.append("") # Flake8 is very specific on whitespace seleniumbase_lines.append("") ide_base_url = "" in_test_method = False has_unicode = False uses_keys = False uses_select = False f = open(webdriver_python_file, 'r') all_code = f.read() f.close() if "def test_" not in all_code: raise Exception("\n\n`%s` is not a valid Python unittest.TestCase " "file!\n\nExpecting: %s\n\n" "Did you properly export your Katalon/Selenium-IDE " "recording as a Python WebDriver unittest file?\n" % (webdriver_python_file, expected_arg)) code_lines = all_code.split('\n') for line in code_lines: # Handle utf-8 encoding if present data = re.findall(r'^\s*# -\*- coding: utf-8 -\*-\s*$', line) if data: has_unicode = True continue # Keep SeleniumBase classes if already used in the test script data = re.findall(r'^class\s\S+\(BaseCase\):\s*$', line) if data: seleniumbase_lines.append(line) continue # Have unittest.TestCase classes inherit BaseCase instead data = re.findall(r'^class\s\S+\(unittest\.TestCase\):\s*$', line) if data: data = data[0].replace("unittest.TestCase", "BaseCase") seleniumbase_lines.append(data) continue # Get base_url if defined data = re.match(r'^\s*self.base_url = "(\S+)"\s*$', line) if data: ide_base_url = data.group(1) continue # Handle method definitions data = re.match(r'^\s*def\s(\S+)\(self[,\s\S]*\):\s*$', line) if data: method_name = data.group(1) if method_name.startswith('test_'): in_test_method = True seleniumbase_lines.append("") seleniumbase_lines.append(data.group()) else: in_test_method = False continue # If not in a test method, skip if not in_test_method: continue # If a comment, skip if line.strip().startswith("#"): continue # If a blank line, skip if len(line.strip()) == 0: continue # If .clear(), skip because .update_text() already does this if line.strip().endswith(".clear()"): continue # Skip edge case data = re.findall(r'^\s*driver = self.driver\s*$', line) if data: continue # Handle page loads data = re.match( r'^(\s*)driver\.get\((self\.base_url \+ \"/\S*\")\)\s*$', line) if data: whitespace = data.group(1) url = data.group(2) url = url.replace("self.base_url", '"%s"' % ide_base_url) if '/" + "/' in url: url = url.replace('/" + "/', '/') if "/' + '/" in url: url = url.replace("/' + '/", "/") command = '''%sself.open(%s)''' % (whitespace, url) seleniumbase_lines.append(command) continue # Handle more page loads data = re.match(r'^(\s*)driver\.get\(\"(\S*)\"\)\s*$', line) if data: whitespace = data.group(1) url = data.group(2) command = '''%sself.open('%s')''' % (whitespace, url) seleniumbase_lines.append(command) continue # Handle .find_element_by_id() + .click() data = re.match( r'''^(\s*)driver\.find_element_by_id\(\"(\S+)\"\)''' r'''\.click\(\)\s*$''', line) if data: whitespace = data.group(1) selector = '#%s' % data.group(2).replace('#', '\\#') selector = selector.replace('[', '\\[').replace(']', '\\]') selector = selector.replace('.', '\\.') raw = "" if "\\[" in selector or "\\]" in selector or "\\." in selector: raw = "r" command = '''%sself.click(%s'%s')''' % (whitespace, raw, selector) seleniumbase_lines.append(command) continue # Handle .find_element_by_id() + .submit() data = re.match( r'''^(\s*)driver\.find_element_by_id\(\"(\S+)\"\)''' r'''\.submit\(\)\s*$''', line) if data: whitespace = data.group(1) selector = '#%s' % data.group(2).replace('#', '\\#') selector = selector.replace('[', '\\[').replace(']', '\\]') selector = selector.replace('.', '\\.') raw = "" if "\\[" in selector or "\\]" in selector or "\\." in selector: raw = "r" command = '''%sself.submit(%s'%s')''' % (whitespace, raw, selector) seleniumbase_lines.append(command) continue # Handle .find_element_by_id() + .send_keys() data = re.match( r'''^(\s*)driver\.find_element_by_id\(\"(\S+)\"\)''' r'''\.send_keys\(\"([\S\s]+)\"\)\s*$''', line) if data: whitespace = data.group(1) selector = '#%s' % data.group(2).replace('#', '\\#') selector = selector.replace('[', '\\[').replace(']', '\\]') selector = selector.replace('.', '\\.') raw = "" if "\\[" in selector or "\\]" in selector or "\\." in selector: raw = "r" text = data.group(3) command = '''%sself.update_text(%s'%s', '%s')''' % ( whitespace, raw, selector, text) seleniumbase_lines.append(command) continue # Handle .find_element_by_id() + .send_keys(Keys.<KEY>) data = re.match( r'''^(\s*)driver\.find_element_by_id\(\"(\S+)\"\)''' r'''\.send_keys\(Keys\.([\S]+)\)\s*$''', line) if data: uses_keys = True whitespace = data.group(1) selector = '#%s' % data.group(2).replace('#', '\\#') selector = selector.replace('[', '\\[').replace(']', '\\]') selector = selector.replace('.', '\\.') raw = "" if "\\[" in selector or "\\]" in selector or "\\." in selector: raw = "r" key = 'Keys.%s' % data.group(3) command = '''%sself.send_keys(%s'%s', %s)''' % (whitespace, raw, selector, key) seleniumbase_lines.append(command) continue # Handle .find_element_by_name() + .click() data = re.match( r'''^(\s*)driver\.find_element_by_name\(\"(\S+)\"\)''' r'''\.click\(\)\s*$''', line) if data: whitespace = data.group(1) selector = '[name="%s"]' % data.group(2) command = '''%sself.click('%s')''' % (whitespace, selector) seleniumbase_lines.append(command) continue # Handle .find_element_by_name() + .submit() data = re.match( r'''^(\s*)driver\.find_element_by_name\(\"(\S+)\"\)''' r'''\.submit\(\)\s*$''', line) if data: whitespace = data.group(1) selector = '[name="%s"]' % data.group(2) command = '''%sself.submit('%s')''' % (whitespace, selector) seleniumbase_lines.append(command) continue # Handle .find_element_by_name() + .send_keys() data = re.match( r'''^(\s*)driver\.find_element_by_name\(\"(\S+)\"\)''' r'''\.send_keys\(\"([\S\s]+)\"\)\s*$''', line) if data: whitespace = data.group(1) selector = '[name="%s"]' % data.group(2) text = data.group(3) command = '''%sself.update_text('%s', '%s')''' % (whitespace, selector, text) seleniumbase_lines.append(command) continue # Handle .find_element_by_name() + .send_keys(Keys.<KEY>) data = re.match( r'''^(\s*)driver\.find_element_by_name\(\"(\S+)\"\)''' r'''\.send_keys\(Keys\.([\S]+)\)\s*$''', line) if data: uses_keys = True whitespace = data.group(1) selector = '[name="%s"]' % data.group(2) key = 'Keys.%s' % data.group(3) command = '''%sself.send_keys('%s', %s)''' % (whitespace, selector, key) seleniumbase_lines.append(command) continue # Handle .find_element_by_css_selector() + .click() data = re.match( r'''^(\s*)driver\.find_element_by_css_selector\(\"([\S\s]+)\"\)''' r'''\.click\(\)\s*$''', line) if data: whitespace = data.group(1) selector = '%s' % data.group(2) command = '''%sself.click('%s')''' % (whitespace, selector) if command.count('\\"') == command.count('"'): command = command.replace('\\"', '"') seleniumbase_lines.append(command) continue # Handle .find_element_by_css_selector() + .submit() data = re.match( r'''^(\s*)driver\.find_element_by_css_selector\(\"([\S\s]+)\"\)''' r'''\.submit\(\)\s*$''', line) if data: whitespace = data.group(1) selector = '%s' % data.group(2) command = '''%sself.submit('%s')''' % (whitespace, selector) if command.count('\\"') == command.count('"'): command = command.replace('\\"', '"') seleniumbase_lines.append(command) continue # Handle .find_element_by_css_selector() + .send_keys() data = re.match( r'''^(\s*)driver\.find_element_by_css_selector\(\"([\S\s]+)\"\)''' r'''\.send_keys\(\"([\S\s]+)\"\)\s*$''', line) if data: whitespace = data.group(1) selector = '%s' % data.group(2) text = data.group(3) command = '''%sself.update_text('%s', '%s')''' % (whitespace, selector, text) if command.count('\\"') == command.count('"'): command = command.replace('\\"', '"') seleniumbase_lines.append(command) continue # Handle .find_element_by_css_selector() + .send_keys(Keys.<KEY>) data = re.match( r'''^(\s*)driver\.find_element_by_css_selector\(\"([\S\s]+)\"\)''' r'''\.send_keys\(Keys\.([\S]+)\)\s*$''', line) if data: uses_keys = True whitespace = data.group(1) selector = '%s' % data.group(2) key = 'Keys.%s' % data.group(3) command = '''%sself.send_keys('%s', %s)''' % (whitespace, selector, key) if command.count('\\"') == command.count('"'): command = command.replace('\\"', '"') seleniumbase_lines.append(command) continue # Handle .find_element_by_xpath() + .send_keys() data = re.match( r'''^(\s*)driver\.find_element_by_xpath\(\"([\S\s]+)\"\)''' r'''\.send_keys\(\"([\S\s]+)\"\)\s*$''', line) if data: whitespace = data.group(1) selector = '%s' % data.group(2) text = data.group(3) command = '''%sself.update_text("%s", '%s')''' % (whitespace, selector, text) if command.count('\\"') == command.count('"'): command = command.replace('\\"', '"') seleniumbase_lines.append(command) continue # Handle .find_element_by_xpath() + .send_keys(Keys.<KEY>) data = re.match( r'''^(\s*)driver\.find_element_by_xpath\(\"([\S\s]+)\"\)''' r'''\.send_keys\(Keys\.([\S]+)\)\s*$''', line) if data: uses_keys = True whitespace = data.group(1) selector = '%s' % data.group(2) key = 'Keys.%s' % data.group(3) command = '''%sself.send_keys("%s", %s)''' % (whitespace, selector, key) if command.count('\\"') == command.count('"'): command = command.replace('\\"', '"') seleniumbase_lines.append(command) continue # Handle Select / by_css_selector() / select_by_visible_text() data = re.match( r'''^(\s*)Select\(driver\.find_element_by_css_selector\(''' r'''\"([\S\s]+)\"\)\)\.select_by_visible_text\(''' r'''\"([\S\s]+)\"\)\s*$''', line) if data: whitespace = data.group(1) selector = '%s' % data.group(2) visible_text = '%s' % data.group(3) command = '''%sself.select_option_by_text('%s', '%s')''' % ( whitespace, selector, visible_text) if command.count('\\"') == command.count('"'): command = command.replace('\\"', '"') seleniumbase_lines.append(command) continue # Handle Select / by_id() / select_by_visible_text() data = re.match( r'''^(\s*)Select\(driver\.find_element_by_id\(''' r'''\"([\S\s]+)\"\)\)\.select_by_visible_text\(''' r'''\"([\S\s]+)\"\)\s*$''', line) if data: whitespace = data.group(1) selector = '#%s' % data.group(2).replace('#', '\\#') selector = selector.replace('[', '\\[').replace(']', '\\]') selector = selector.replace('.', '\\.') raw = "" if "\\[" in selector or "\\]" in selector or "\\." in selector: raw = "r" visible_text = '%s' % data.group(3) command = '''%sself.select_option_by_text(%s'%s', '%s')''' % ( whitespace, raw, selector, visible_text) if command.count('\\"') == command.count('"'): command = command.replace('\\"', '"') seleniumbase_lines.append(command) continue # Handle Select / by_xpath() / select_by_visible_text() data = re.match( r'''^(\s*)Select\(driver\.find_element_by_xpath\(''' r'''\"([\S\s]+)\"\)\)\.select_by_visible_text\(''' r'''\"([\S\s]+)\"\)\s*$''', line) if data: whitespace = data.group(1) selector = '%s' % data.group(2) visible_text = '%s' % data.group(3) command = '''%sself.select_option_by_text("%s", '%s')''' % ( whitespace, selector, visible_text) if command.count('\\"') == command.count('"'): command = command.replace('\\"', '"') seleniumbase_lines.append(command) continue # Handle Select / by_name() / select_by_visible_text() data = re.match( r'''^(\s*)Select\(driver\.find_element_by_name\(''' r'''\"([\S\s]+)\"\)\)\.select_by_visible_text\(''' r'''\"([\S\s]+)\"\)\s*$''', line) if data: whitespace = data.group(1) selector = '[name="%s"]' % data.group(2) visible_text = '%s' % data.group(3) command = '''%sself.select_option_by_text('%s', '%s')''' % ( whitespace, selector, visible_text) if command.count('\\"') == command.count('"'): command = command.replace('\\"', '"') seleniumbase_lines.append(command) continue # Handle .find_element_by_xpath() + .click() data = re.match( r'''^(\s*)driver\.find_element_by_xpath\(u?\"([\S\s]+)\"\)''' r'''\.click\(\)\s*$''', line) if data: whitespace = data.group(1) xpath = '%s' % data.group(2) uni = "" if '(u"' in line: uni = "u" has_unicode = True command = '''%sself.click(%s"%s")''' % (whitespace, uni, xpath) seleniumbase_lines.append(command) continue # Handle .find_element_by_xpath() + .submit() data = re.match( r'''^(\s*)driver\.find_element_by_xpath\(u?\"([\S\s]+)\"\)''' r'''\.submit\(\)\s*$''', line) if data: whitespace = data.group(1) xpath = '%s' % data.group(2) uni = "" if '(u"' in line: uni = "u" has_unicode = True command = '''%sself.submit(%s"%s")''' % (whitespace, uni, xpath) seleniumbase_lines.append(command) continue # Handle .find_element_by_link_text() + .click() data = re.match( r'''^(\s*)driver\.find_element_by_link_text\(u?\"([\S\s]+)\"\)''' r'''\.click\(\)\s*$''', line) if data: whitespace = data.group(1) link_text = '''%s''' % data.group(2) uni = "" if '(u"' in line: uni = "u" has_unicode = True command = '''%sself.click(%s"link=%s")''' % (whitespace, uni, link_text) seleniumbase_lines.append(command) continue # Handle self.is_element_present(By.LINK_TEXT, *) data = re.match( r'''^(\s*)([\S\s]*)self\.is_element_present\(By.LINK_TEXT, ''' r'''u?\"([\S\s]+)\"\)([\S\s]*)$''', line) if data: whitespace = data.group(1) pre = data.group(2) link_text = '''%s''' % data.group(3) post = data.group(4) uni = "" if '(u"' in line: uni = "u" has_unicode = True command = '''%s%sself.is_link_text_present(%s"%s")%s''' % ( whitespace, pre, uni, link_text, post) seleniumbase_lines.append(command) continue # Handle self.is_element_present(By.NAME, *) data = re.match( r'''^(\s*)([\S\s]*)self\.is_element_present\(By.NAME, ''' r'''u?\"([\S\s]+)\"\)([\S\s]*)$''', line) if data: whitespace = data.group(1) pre = data.group(2) name = '''%s''' % data.group(3) post = data.group(4) uni = "" if '(u"' in line: uni = "u" has_unicode = True command = '''%s%sself.is_element_present('[name="%s"]')%s''' % ( whitespace, pre, name, post) seleniumbase_lines.append(command) continue # Handle self.is_element_present(By.ID, *) data = re.match( r'''^(\s*)([\S\s]*)self\.is_element_present\(By.ID, ''' r'''u?\"([\S\s]+)\"\)([\S\s]*)$''', line) if data: whitespace = data.group(1) pre = data.group(2) the_id = '''%s''' % data.group(3) post = data.group(4) uni = "" if '(u"' in line: uni = "u" has_unicode = True command = '''%s%sself.is_element_present("#%s")%s''' % ( whitespace, pre, the_id, post) seleniumbase_lines.append(command) continue # Handle self.is_element_present(By.CLASS, *) data = re.match( r'''^(\s*)([\S\s]*)self\.is_element_present\(By.CLASS, ''' r'''u?\"([\S\s]+)\"\)([\S\s]*)$''', line) if data: whitespace = data.group(1) pre = data.group(2) the_class = '''%s''' % data.group(3) post = data.group(4) uni = "" if '(u"' in line: uni = "u" has_unicode = True command = '''%s%sself.is_element_present(".%s")%s''' % ( whitespace, pre, the_class, post) seleniumbase_lines.append(command) continue # Handle self.is_element_present(By.CSS_SELECTOR, *) data = re.match( r'''^(\s*)([\S\s]*)self\.is_element_present\(By.CSS_SELECTOR, ''' r'''u?\"([\S\s]+)\"\)([\S\s]*)$''', line) if data: whitespace = data.group(1) pre = data.group(2) selector = '''%s''' % data.group(3) post = data.group(4) uni = "" if '(u"' in line: uni = "u" has_unicode = True command = '''%s%sself.is_element_present("%s")%s''' % ( whitespace, pre, selector, post) seleniumbase_lines.append(command) continue # Handle self.is_element_present(By.XPATH, *) data = re.match( r'''^(\s*)([\S\s]*)self\.is_element_present\(By.XPATH, ''' r'''u?\"([\S\s]+)\"\)([\S\s]*)$''', line) if data: whitespace = data.group(1) pre = data.group(2) xpath = '''%s''' % data.group(3) post = data.group(4) uni = "" if '(u"' in line: uni = "u" has_unicode = True command = '''%s%sself.is_element_present("%s")%s''' % ( whitespace, pre, xpath, post) seleniumbase_lines.append(command) continue # Replace "self.base_url" with actual url if not already done if 'self.base_url' in line: line = line.replace("self.base_url", '"%s"' % ide_base_url) # Convert "driver." to "self.driver." if not already done if 'driver.' in line and 'self.driver' not in line: line = line.replace('driver.', 'self.driver.') # Add all other lines to final script without making changes seleniumbase_lines.append(line) # Chunk processing of inefficient waiting from Selenium IDE in_inefficient_wait = False whitespace = "" lines = seleniumbase_lines seleniumbase_lines = [] for line in lines: data = re.match(r'^(\s*)for i in range\(60\):\s*$', line) if data: in_inefficient_wait = True whitespace = data.group(1) continue data = re.match(r'^(\s*)else: self.fail\("time out"\)\s*$', line) if data: in_inefficient_wait = False continue if in_inefficient_wait: data = re.match( r'''^\s*if self.is_element_present\("([\S\s]+)"\)''' r''': break\s*$''', line) if data: selector = data.group(1) command = '%sself.wait_for_element("%s")' % (whitespace, selector) seleniumbase_lines.append(command) continue data = re.match( r'''^\s*if self.is_element_present\('([\S\s]+)'\)''' r''': break\s*$''', line) if data: selector = data.group(1) command = "%sself.wait_for_element('%s')" % (whitespace, selector) seleniumbase_lines.append(command) continue data = re.match( r'''^\s*if self.is_link_text_present''' r'''\("([\S\s]+)"\): break\s*$''', line) if data: uni = "" if '(u"' in line: uni = "u" link_text = data.group(1) command = '''%sself.wait_for_link_text(%s"%s")''' % ( whitespace, uni, link_text) seleniumbase_lines.append(command) continue else: seleniumbase_lines.append(line) continue # Is there a Select() still present? lines = seleniumbase_lines for line_num in range(len(lines)): if "Select(self.driver" in lines[line_num]: uses_select = True # Remove duplicate functionality (wait_for_element) lines = seleniumbase_lines seleniumbase_lines = [] num_lines = len(lines) for line_num in range(len(lines)): data = re.match( r'''^\s*self.wait_for_element''' r'''\((["|'])([\S\s]+)(["|'])\)''' r'''\s*$''', lines[line_num]) if data: # quote_type = data.group(1) selector = data.group(2) selector = re.escape(selector) selector = js_utils.escape_quotes_if_needed(selector) if int(line_num) < num_lines - 1: regex_string = (r'''^\s*self.click\(["|']''' '' + selector + r'''["|']\)\s*$''') data2 = re.match(regex_string, lines[line_num + 1]) if data2: continue regex_string = (r'''^\s*self.update_text\(["|']''' '' + selector + '' '' + r'''["|'], [\S\s]+\)\s*$''') data2 = re.match(regex_string, lines[line_num + 1]) if data2: continue seleniumbase_lines.append(lines[line_num]) # Remove duplicate functionality (wait_for_link_text) lines = seleniumbase_lines seleniumbase_lines = [] num_lines = len(lines) for line_num in range(len(lines)): data = re.match( r'''^\s*self.wait_for_link_text''' r'''\((["|'])([\S\s]+)(["|'])\)''' r'''\s*$''', lines[line_num]) if data: # quote_type = data.group(1) link_text = data.group(2) link_text = re.escape(link_text) link_text = js_utils.escape_quotes_if_needed(link_text) if int(line_num) < num_lines - 2: regex_string = (r'''^\s*self.click\(["|']link=''' '' + link_text + r'''["|']\)\s*$''') data2 = re.match(regex_string, lines[line_num + 1]) if data2: continue seleniumbase_lines.append(lines[line_num]) seleniumbase_code = "" if has_unicode: seleniumbase_code = "# -*- coding: utf-8 -*-\n" if uses_keys: seleniumbase_code += ( "from selenium.webdriver.common.keys import Keys\n") if uses_select: seleniumbase_code += ( "from selenium.webdriver.support.ui import Select\n") for line in seleniumbase_lines: seleniumbase_code += line seleniumbase_code += "\n" # print(seleniumbase_code) # (For debugging) # Create SeleniumBase test file base_file_name = webdriver_python_file.split('.py')[0] converted_file_name = base_file_name + "_SB.py" out_file = codecs.open(converted_file_name, "w+") out_file.writelines(seleniumbase_code) out_file.close() print('\n>>> [%s] was created from [%s]\n' % (converted_file_name, webdriver_python_file))
def export_tour(tour_steps, name=None, filename="my_tour.js", url=None): """ Exports a tour as a JS file. It will include necessary resources as well, such as jQuery. You'll be able to copy the tour directly into the Console of any web browser to play the tour outside of SeleniumBase runs. """ if not name: name = "default" if name not in tour_steps: raise Exception("Tour {%s} does not exist!" % name) if not filename.endswith('.js'): raise Exception('Tour file must end in ".js"!') if not url: url = "data:," tour_type = None if "Bootstrap" in tour_steps[name][0]: tour_type = "bootstrap" elif "Hopscotch" in tour_steps[name][0]: tour_type = "hopscotch" elif "IntroJS" in tour_steps[name][0]: tour_type = "introjs" elif "Shepherd" in tour_steps[name][0]: tour_type = "shepherd" else: raise Exception('Unknown tour type!') instructions = ( '''//////// Load Tour Start Page (if not there now) ////////\n\n''' '''if (window.location.href != "%s") {\n''' ''' window.location.href="%s";\n''' '''}\n\n''' '''//////// Resources ////////\n\n''' '''function injectCSS(css_link) {''' '''var head = document.getElementsByTagName("head")[0];''' '''var link = document.createElement("link");''' '''link.rel = "stylesheet";''' '''link.type = "text/css";''' '''link.href = css_link;''' '''link.crossorigin = "anonymous";''' '''head.appendChild(link);''' '''};\n''' '''function injectJS(js_link) {''' '''var head = document.getElementsByTagName("head")[0];''' '''var script = document.createElement("script");''' '''script.src = js_link;''' '''script.defer;''' '''script.type="text/javascript";''' '''script.crossorigin = "anonymous";''' '''script.onload = function() { null };''' '''head.appendChild(script);''' '''};\n''' '''function injectStyle(css) {''' '''var head = document.getElementsByTagName("head")[0];''' '''var style = document.createElement("style");''' '''style.type = "text/css";''' '''style.appendChild(document.createTextNode(css));''' '''head.appendChild(style);''' '''};\n''' % (url, url)) if tour_type == "bootstrap": jquery_js = constants.JQuery.MIN_JS bootstrap_tour_css = constants.BootstrapTour.MIN_CSS bootstrap_tour_js = constants.BootstrapTour.MIN_JS backdrop_style = style_sheet.bt_backdrop_style backdrop_style = backdrop_style.replace('\n', '') backdrop_style = js_utils.escape_quotes_if_needed(backdrop_style) instructions += 'injectJS("%s");\n' % jquery_js instructions += '\n' instructions += 'function loadResources() { ' instructions += 'if ( typeof jQuery !== "undefined" ) {\n' instructions += 'injectCSS("%s");\n' % bootstrap_tour_css instructions += 'injectStyle("%s");\n' % backdrop_style instructions += 'injectJS("%s");' % bootstrap_tour_js instructions += '} else { window.setTimeout("loadResources();",100); ' instructions += '} }\n' instructions += 'loadResources()' elif tour_type == "hopscotch": hopscotch_css = constants.Hopscotch.MIN_CSS hopscotch_js = constants.Hopscotch.MIN_JS backdrop_style = style_sheet.hops_backdrop_style backdrop_style = backdrop_style.replace('\n', '') backdrop_style = js_utils.escape_quotes_if_needed(backdrop_style) instructions += 'injectCSS("%s");\n' % hopscotch_css instructions += 'injectStyle("%s");\n' % backdrop_style instructions += 'injectJS("%s");' % hopscotch_js elif tour_type == "introjs": intro_css = constants.IntroJS.MIN_CSS intro_js = constants.IntroJS.MIN_JS instructions += 'injectCSS("%s");\n' % intro_css instructions += 'injectJS("%s");' % intro_js elif tour_type == "shepherd": jquery_js = constants.JQuery.MIN_JS shepherd_js = constants.Shepherd.MIN_JS sh_theme_arrows_css = constants.Shepherd.THEME_ARROWS_CSS sh_theme_arrows_fix_css = constants.Shepherd.THEME_ARR_FIX_CSS sh_theme_default_css = constants.Shepherd.THEME_DEFAULT_CSS sh_theme_dark_css = constants.Shepherd.THEME_DARK_CSS sh_theme_sq_css = constants.Shepherd.THEME_SQ_CSS sh_theme_sq_dark_css = constants.Shepherd.THEME_SQ_DK_CSS tether_js = constants.Tether.MIN_JS spinner_css = constants.Messenger.SPINNER_CSS backdrop_style = style_sheet.sh_backdrop_style backdrop_style = backdrop_style.replace('\n', '') backdrop_style = js_utils.escape_quotes_if_needed(backdrop_style) instructions += 'injectCSS("%s");\n' % spinner_css instructions += 'injectJS("%s");\n' % jquery_js instructions += 'injectJS("%s");\n' % tether_js instructions += '\n' instructions += 'function loadResources() { ' instructions += 'if ( typeof jQuery !== "undefined" ) {\n' instructions += 'injectCSS("%s");' % sh_theme_arrows_css instructions += 'injectCSS("%s");' % sh_theme_arrows_fix_css instructions += 'injectCSS("%s");' % sh_theme_default_css instructions += 'injectCSS("%s");' % sh_theme_dark_css instructions += 'injectCSS("%s");' % sh_theme_sq_css instructions += 'injectCSS("%s");\n' % sh_theme_sq_dark_css instructions += 'injectStyle("%s");\n' % backdrop_style instructions += 'injectJS("%s");\n' % shepherd_js instructions += '} else { window.setTimeout("loadResources();",100); ' instructions += '} }\n' instructions += 'loadResources()' instructions += '\n\n//////// Tour Code ////////\n\n' if tour_type == "bootstrap": instructions += 'function loadTour() { ' instructions += 'if ( typeof Tour !== "undefined" ) {\n' elif tour_type == "hopscotch": instructions += 'function loadTour() { ' instructions += 'if ( typeof hopscotch !== "undefined" ) {\n' elif tour_type == "introjs": instructions += 'function loadTour() { ' instructions += 'if ( typeof introJs !== "undefined" ) {\n' elif tour_type == "shepherd": instructions += 'function loadTour() { ' instructions += 'if ( typeof Shepherd !== "undefined" ) {\n' for tour_step in tour_steps[name]: instructions += tour_step if tour_type == "bootstrap": instructions += ( """]); // Initialize the tour tour.init(); // Start the tour tour.start(); $tour = tour; $tour.restart();\n""") elif tour_type == "hopscotch": instructions += ( """] }; // Start the tour! hopscotch.startTour(tour); $tour = hopscotch;\n""") elif tour_type == "introjs": instructions += ( """] }); intro.setOption("disableInteraction", true); intro.setOption("overlayOpacity", .29); intro.setOption("scrollToElement", true); intro.setOption("keyboardNavigation", true); intro.setOption("exitOnEsc", false); intro.setOption("exitOnOverlayClick", false); intro.setOption("showStepNumbers", false); intro.setOption("showProgress", false); intro.start(); $tour = intro; }; startIntro();\n""") elif tour_type == "shepherd": instructions += ( """ tour.start(); $tour = tour;\n""") else: pass instructions += '\n} else { window.setTimeout("loadTour();",100); } ' instructions += '}\n' instructions += 'loadTour()\n' exported_tours_folder = EXPORTED_TOURS_FOLDER if exported_tours_folder.endswith("/"): exported_tours_folder = exported_tours_folder[:-1] if not os.path.exists(exported_tours_folder): try: os.makedirs(exported_tours_folder) except Exception: pass import codecs file_path = exported_tours_folder + "/" + filename out_file = codecs.open(file_path, "w+") out_file.writelines(instructions) out_file.close() print('\n>>> [%s] was saved!\n' % file_path)
def jquery_confirm_full_dialog(driver, message, buttons, options=None): js_utils.activate_jquery_confirm(driver) # These defaults will be overwritten later if set theme = constants.JqueryConfirm.DEFAULT_THEME border_color = constants.JqueryConfirm.DEFAULT_COLOR width = constants.JqueryConfirm.DEFAULT_WIDTH if not message: message = "" btn_count = 0 b_html = """button_%s: { btnClass: 'btn-%s', text: '%s', action: function(){ jqc_input = this.$content.find('.jqc_input').val(); $jqc_input = this.$content.find('.jqc_input').val(); jconfirm.lastInputText = jqc_input; $jqc_status = '%s'; } },""" b1_html = """formSubmit: { btnClass: 'btn-%s', text: '%s', action: function(){ jqc_input = this.$content.find('.jqc_input').val(); $jqc_input = this.$content.find('.jqc_input').val(); jconfirm.lastInputText = jqc_input; jqc_status = '%s'; $jqc_status = jqc_status; jconfirm.lastButtonText = jqc_status; } },""" one_button_trigger = "" if len(buttons) == 1: # If there's only one button, allow form submit with "Enter/Return" one_button_trigger = "jc.$$formSubmit.trigger('click');" all_buttons = "" for button in buttons: text = button[0] text = js_utils.escape_quotes_if_needed(text) color = button[1] if not color: color = "blue" btn_count += 1 if len(buttons) == 1: new_button = b1_html % (color, text, text) else: new_button = b_html % (btn_count, color, text, text) all_buttons += new_button if options: for option in options: if option[0].lower() == "theme": theme = option[1] elif option[0].lower() == "color": border_color = option[1] elif option[0].lower() == "width": width = option[1] else: raise Exception('Unknown option: "%s"' % option[0]) content = '<div></div><font color="#0066ee">%s</font>' % (message) content = js_utils.escape_quotes_if_needed(content) overlay_opacity = "0.32" if theme.lower() == "supervan": overlay_opacity = "0.56" if theme.lower() == "bootstrap": overlay_opacity = "0.64" if theme.lower() == "modern": overlay_opacity = "0.5" if theme.lower() == "material": overlay_opacity = "0.4" jqcd = """jconfirm({ boxWidth: '%s', useBootstrap: false, containerFluid: true, bgOpacity: %s, type: '%s', theme: '%s', animationBounce: 1, typeAnimated: true, animation: 'scale', draggable: true, dragWindowGap: 1, container: 'body', title: '%s', content: '<div></div>' + %s, buttons: { %s }, onContentReady: function () { var jc = this; this.$content.find('form.jqc_form').on('submit', function (e) { // User submits the form by pressing "Enter" in the field e.preventDefault(); %s }); } });""" % ( width, overlay_opacity, border_color, theme, content, form_code, all_buttons, one_button_trigger, ) driver.execute_script(jqcd)
def jquery_confirm_button_dialog(driver, message, buttons, options=None): js_utils.activate_jquery_confirm(driver) # These defaults will be overwritten later if set theme = constants.JqueryConfirm.DEFAULT_THEME border_color = constants.JqueryConfirm.DEFAULT_COLOR width = constants.JqueryConfirm.DEFAULT_WIDTH if options: for option in options: if option[0].lower() == "theme": theme = option[1] elif option[0].lower() == "color": border_color = option[1] elif option[0].lower() == "width": width = option[1] else: raise Exception('Unknown option: "%s"' % option[0]) if not message: message = "" key_row = "" if len(buttons) == 1: # There's only one button as an option key_row = "keys: ['enter', 'y', '1']," # Shortcut: "Enter","Y","1" b_html = """button_%s: { btnClass: 'btn-%s', text: '<b>%s</b>', %s action: function(){ jqc_status = '%s'; $jqc_status = jqc_status; jconfirm.lastButtonText = jqc_status; } },""" all_buttons = "" btn_count = 0 for button in buttons: btn_count += 1 text = button[0] text = js_utils.escape_quotes_if_needed(text) if len(buttons) > 1 and text.lower() == "yes": key_row = "keys: ['y']," if btn_count < 10: key_row = "keys: ['y', '%s']," % btn_count elif len(buttons) > 1 and text.lower() == "no": key_row = "keys: ['n']," if btn_count < 10: key_row = "keys: ['n', '%s']," % btn_count elif len(buttons) > 1: if btn_count < 10: key_row = "keys: ['%s']," % btn_count color = button[1] if not color: color = "blue" new_button = b_html % (btn_count, color, text, key_row, text) all_buttons += new_button content = '<div></div><font color="#0066ee">%s</font>' % (message) content = js_utils.escape_quotes_if_needed(content) overlay_opacity = "0.32" if theme.lower() == "supervan": overlay_opacity = "0.56" if theme.lower() == "bootstrap": overlay_opacity = "0.64" if theme.lower() == "modern": overlay_opacity = "0.5" if theme.lower() == "material": overlay_opacity = "0.4" jqcd = """jconfirm({ boxWidth: '%s', useBootstrap: false, containerFluid: true, bgOpacity: %s, type: '%s', theme: '%s', animationBounce: 1, typeAnimated: true, animation: 'scale', draggable: true, dragWindowGap: 1, container: 'body', title: '%s', content: '<div></div>', buttons: { %s } });""" % ( width, overlay_opacity, border_color, theme, content, all_buttons, ) driver.execute_script(jqcd)
def jquery_confirm_text_dialog(driver, message, button=None, options=None): js_utils.activate_jquery_confirm(driver) # These defaults will be overwritten later if set theme = constants.JqueryConfirm.DEFAULT_THEME border_color = constants.JqueryConfirm.DEFAULT_COLOR width = constants.JqueryConfirm.DEFAULT_WIDTH if not message: message = "" if button: if not type(button) is list and not type(button) is tuple: raise Exception('"button" should be a (text, color) tuple!') if len(button) != 2: raise Exception('"button" should be a (text, color) tuple!') else: button = ("Submit", "blue") if options: for option in options: if option[0].lower() == "theme": theme = option[1] elif option[0].lower() == "color": border_color = option[1] elif option[0].lower() == "width": width = option[1] else: raise Exception('Unknown option: "%s"' % option[0]) btn_text = button[0] btn_color = button[1] if not btn_color: btn_color = "blue" content = '<div></div><font color="#0066ee">%s</font>' % (message) content = js_utils.escape_quotes_if_needed(content) overlay_opacity = "0.32" if theme.lower() == "supervan": overlay_opacity = "0.56" if theme.lower() == "bootstrap": overlay_opacity = "0.64" if theme.lower() == "modern": overlay_opacity = "0.5" if theme.lower() == "material": overlay_opacity = "0.4" jqcd = """jconfirm({ boxWidth: '%s', useBootstrap: false, containerFluid: true, bgOpacity: %s, type: '%s', theme: '%s', animationBounce: 1, typeAnimated: true, animation: 'scale', draggable: true, dragWindowGap: 1, container: 'body', title: '%s', content: '<div></div>' + %s, buttons: { formSubmit: { btnClass: 'btn-%s', text: '%s', action: function () { jqc_input = this.$content.find('.jqc_input').val(); $jqc_input = this.$content.find('.jqc_input').val(); jconfirm.lastInputText = jqc_input; $jqc_status = '%s'; // There is only one button }, }, }, onContentReady: function () { var jc = this; this.$content.find('form.jqc_form').on('submit', function (e) { // User submits the form by pressing "Enter" in the field e.preventDefault(); jc.$$formSubmit.trigger('click'); // Click the button }); } });""" % ( width, overlay_opacity, border_color, theme, content, form_code, btn_color, btn_text, btn_text, ) driver.execute_script(jqcd)