Best Python code snippet using Kiwi_python
selenium-test.py
Source:selenium-test.py  
1# web client2print("Web test here...")3from selenium import webdriver4from selenium.webdriver.common.by import By5from selenium.webdriver.support.ui import WebDriverWait6from selenium.webdriver.support import expected_conditions as EC7from selenium.webdriver.common.keys import Keys8import platform9import time10import random11if ("Windows" not in platform.platform()):12    exit()13driver = webdriver.Chrome(executable_path='./lib/chromedriver')14# local_username = ""15# options = webdriver.ChromeOptions()16# options.add_argument("user-data-dir=C:/Users/"+local_username+"/AppData/Local/Google/Chrome/User Data") #Path to your chrome profile17# driver = webdriver.Chrome(executable_path='./lib/chromedriver', chrome_options=options)18test_user_name = []19test_user_pwd = []20test_invalid_email = ['Abc.example.com',21                      '"\'OR 1=1--"@gmail.com',22                      '\'OR 1=1--@gmail.com',23                      '\' or 1=1--@gmail.com',24                      '" or 1=1--@gmail.com',25                      'or 1=1--@gmail.com',26                      '1\'or\'1\'=\'1',27                      '\' or \'a\'=\'a',28                      '" or "a"="a',29                      '\') or (\'a\'=\'a',30                      '") or ("a"="a']31test_invalid_username = ['admin\'',32                         'admin\' OR \'a\'=\'a',33                         'invalid-username\' UNION SELECT 1, username, passwords FROM members WHERE \'x\'=\'x',34                         '\' or 1=1--',35                         '" or 1=1--',36                         '"or 1=1--',37                         '1\'or\'1\'=\'1',38                         '\' or \'a\'=\'a',39                         '" or "a"="a',40                         '\') or (\'a\'=\'a',41                         '") or ("a"="a']42test_invalid_pwd = ['\' or 1=1--',43                    '" or 1=1--',44                    '"or 1=1--',45                    '1\'or\'1\'=\'1',46                    '\' or \'a\'=\'a',47                    '" or "a"="a',48                    '\') or (\'a\'=\'a',49                    '") or ("a"="a']50test_search_words = ['test', 'mar', 'a', '3']51def refresh(path):52    driver.get(path)53## registration54def register(email, username, pwd):55    print("Trying registering...")56    refresh("http://localhost:8080/Signup")57    path_prefix = "//label[@for = \'"58    path_suffix = "\']/following-sibling::div[1]/div/input"59    el_email = driver.find_element_by_xpath(path_prefix + 'email' + path_suffix)60    el_email.send_keys(email)61    el_username = driver.find_element_by_xpath(path_prefix + 'name' + path_suffix)62    el_username.send_keys(username)63    el_pwd = driver.find_element_by_xpath(path_prefix + 'pwd' + path_suffix)64    el_pwd.send_keys(pwd)65    driver.find_element_by_xpath("//button[@class ='el-button el-button--primary']").click()66    WebDriverWait(driver, 3).until(EC.alert_is_present())67    text = driver.switch_to.alert.text68    time.sleep(2)69    if text == "Register successfully!":70        driver.switch_to.alert.accept()71        test_user_name.append(username)72        test_user_pwd.append(pwd)73    elif text == "Please follow rules!":74        driver.switch_to.alert.accept()75        refresh("http://localhost:8080/Signup")76## login77def login(login_name, login_pwd):78    print("Trying logging in...")79    refresh("http://localhost:8080")80    username = driver.find_element_by_name("name")81    username.send_keys(login_name)82    pwd = driver.find_element_by_name("pwd")83    pwd.send_keys(login_pwd)84    path = "//div/form/div/div/div/div/button"85    signin_button = driver.find_elements_by_xpath(path)[0]86    signin_button.click()87    try:88        # Fail with alert89        WebDriverWait(driver, 3).until(EC.alert_is_present())90        time.sleep(1)91        driver.switch_to.alert.accept()92        refresh("http://localhost:8080/Signin")93    except:94        # Succeed95        time.sleep(1)96## Search for other users97def search_for_users(key_word):98    print("try searching users with keyword(\""+key_word+"\")...")99    path = "//i[@aria-haspopup]"100    dropdown = WebDriverWait(driver, 3).until(EC.element_to_be_clickable((By.XPATH, path)))101    dropdown.click()102    path = "//ul[@class = 'el-dropdown-menu el-popper']/li[2]"103    item = WebDriverWait(driver, 3).until(EC.element_to_be_clickable((By.XPATH, path)))104    item.click()105    path = "//div[@class = 'searchPanel']/div/div[1]/div/input"106    input = driver.find_elements_by_xpath(path)[0]107    input.send_keys(Keys.CONTROL+'a')108    input.send_keys(Keys.DELETE)109    input.send_keys(key_word)110    path = "//div[@class = 'searchPanel']/div/div[2]/button"111    button = driver.find_elements_by_xpath(path)[0]112    button.click()113    time.sleep(1)114## Create new chats and fetch latest histories115def create_random_new_chat():116    print('try creating new chat...')117    path = "//div[@class = 'single-user-info']"118    results = driver.find_elements_by_xpath(path)119    random_num = str(random.randint(1, len(results)))120    path = "//div[@class = 'single-user-info'][" + random_num + "]"121    single_user_info = WebDriverWait(driver, 3).until(EC.element_to_be_clickable((By.XPATH, path)))122    single_user_info.click()123## Message encryption and decryption124def send_message_to(object_user, message):125    print("try sending message (\""+message+"\") to user (\""+object_user+"\")...")126    path = "//div[@class='chat']/div/div[2]/div/div/label"127    user_names = driver.find_elements_by_xpath(path)128    for user_name in user_names:129        if object_user != user_name.text:130            continue131        user_name.find_element_by_xpath("../../../..").click()132        path = "//div[@id='main-panel']/section//div/section/header/div/div[2]/label"133        panels = driver.find_elements_by_xpath(path)134        for panel in panels:135            if panel.text != object_user:136                continue137            text_field = panel.find_element_by_xpath('../../../../footer/div/div[2]/div/input')138            text_field.send_keys(message)139            send_button = WebDriverWait(text_field, 3).until(EC.element_to_be_clickable((By.XPATH, '../../../div[3]/span//button')))140            send_button.click()141            time.sleep(0.5)142def search_and_create_chats(key_word):143    search_for_users(key_word)144    create_random_new_chat()145def test_register():146    print("Register test case 1: succeed with complying registration constrains")147    for i in range(0, 10):148        random_num = str(random.randint(10000, 99999))149        random_username = "test" + random_num150        constructed_pwd = "Aa1111!!"151        register("test" + random_num + "@test.com", random_username, constructed_pwd)152    print("Register test case 1: fail with stained inputs")153    for i in range(len(test_invalid_email) + len(test_invalid_username) + len(test_invalid_pwd)):154        random_num = str(random.randint(10000, 99999))155        random_email = "test" + random_num + "@test.com"156        random_username = "test" + random_num157        constructed_pwd = "Aa1111!!"158        if i < len(test_invalid_email):159            continue160            # Stained email address161            random_email = test_invalid_email[i]162        elif i < len(test_invalid_email) + len(test_invalid_username):163            # Stained username164            continue165            random_username = test_invalid_username[i - len(test_invalid_email)]166        else:167            # Stained password168            constructed_pwd = test_invalid_pwd[i - len(test_invalid_email) - len(test_invalid_username)]169        register(random_email, random_username, constructed_pwd)170def test_login():171    if len(test_user_pwd) == 0:172        random_num = str(random.randint(10000, 99999))173        random_username = "test" + random_num174        constructed_pwd = "Aa1111!!"175        register("test" + random_num + "@test.com", random_username, constructed_pwd)176    print("Login test case 1: succeed with local private key")177    for i in range(len(test_user_name)):178        username = test_user_name[i]179        pwd = test_user_pwd[i]180        login(username, pwd)181    print("Login test case 2: fail without local private key")182    for i in range(0, 10):183        random_num = str(random.randint(10000, 99999))184        random_username = "test" + random_num185        constructed_pwd = "Aa1111!!"186        login(random_username, constructed_pwd)187    print("Login test case 3: fail with unmatched passwords")188    for i in range(len(test_user_name)):189        username = test_user_name[i]190        pwd = "dfghjk"  # randomly constructed passwords191        login(username, pwd)192def test_search_users():193    if len(test_user_name) < 1:194        random_num = str(random.randint(10000, 99999))195        random_username = "test" + random_num196        constructed_pwd = "Aa1111!!"197        register("test" + random_num + "@test.com", random_username, constructed_pwd)198    login(test_user_name[0], test_user_pwd[0])199    for i in range(len(test_search_words)):200        search_and_create_chats(test_search_words[i])201def test_chat():202    if len(test_user_name) < 2:203        for i in range(2 - len(test_user_name)):204            random_num = str(random.randint(10000, 99999))205            random_username = "test" + random_num206            constructed_pwd = "Aa1111!!"207            register("test" + random_num + "@test.com", random_username, constructed_pwd)208    login(test_user_name[0], test_user_pwd[0])209    search_and_create_chats(test_user_name[1])210    for i in range(10):211        send_message_to(test_user_name[1], 'test_message' + str(i))212    login(test_user_name[1], test_user_pwd[1])213    send_message_to(test_user_name[0], 'test_message back')214# test_register()215test_login()216# test_search_users()...session_test.py
Source:session_test.py  
...30        self.assertRaises(31            session.AuthenticationError,32            lambda: self.session.authenticate('test@test.com', 'wrongsecret')33        )34    def test_invalid_email(self):35        """ test_invalid_email36        Test login with wrong email37        """38        self.assertRaises(39            session.AuthenticationError,40            lambda: self.session.authenticate('wrong@test.com', 'supersecret')41        )42if __name__ == '__main__':43    # Start the web-server in a background thread44    http = ServerThread()45    http.start()46    # Run tests47    unittest.main()48    # Stop threads...test_email_validation.py
Source:test_email_validation.py  
1import pytest2from src.helpers import email_validation3test_valid_email = ['vvv@gmail.com',4                    'anonymous123@ukr.net',5                    'myemail@outlook.sdf']6test_invalid_email = ['vvv@gmail',7                      'anonymous123@..urk.net',8                      'myemail@outlook.']9@pytest.mark.parametrize('email', test_valid_email)10def test_email_valid(email):11    assert email_validation(email)12@pytest.mark.parametrize('email', test_invalid_email)13def test_email_invalid(email):...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!!
