This article is mainly to help colleagues who can write basic selenium test code but have no plan.
This article applies POM model, selenium, unittest framework, configparser configuration file, smtplib email sending, HTMLTestRunner test report module combined with login case to implement a simple automated testing framework
The project mainly includes the following parts
conif.ini placement configuration file
Example:
Browser operation code placed in the myunit.py file
import unittest from selenium import webdriver class MyTest(unittest.TestCase): def setUp(self): self.driver = webdriver.Chrome() self.driver.implicitly_wait(10) self.driver.maximize_window() def tearDown(self): self.driver.quit() if __name__=='__main__': unittest.main()
Place browser object operation code in base.py
from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.support.wait import WebDriverWait import os,configparser class Page(object): path = os.path.dirname(os.path.abspath(".")) cfpath = os.path.join(path, 'autoparker\config\conf.ini') conf = configparser.ConfigParser() conf.read(cfpath) url=conf.get('base','url') def __init__(self,driver,url=url): self.driver=driver self.url=url def open(self): self.driver.get(self.url) def find_element(self,*loc):#If the incoming parameter is a tuple, you need to add *, if it is a tuple itself, you don’t need * #print(*loc) try: WebDriverWait(self.driver,10).until(EC.visibility_of_element_located(loc)) return self.driver.find_element(*loc) except: print('The %s element was not found in the page'%(self,loc)) def find_elements(self,*loc): return self.driver.find_elements(*loc) def send_keys(self,loc,value): self.find_element(*loc).send_keys(value) def click(self,loc): self.find_element(*loc).click() def clear(self,loc): self.find_element(*loc).clear()
Now I have also found a lot of test friends and created a communication group to share technology, sharing a lot of technical documents and video tutorials we collected. If you don’t want to experience the feeling of not being able to find resources when studying on your own, having no one to answer your questions, and persisting for a few days before giving up. You can join us to communicate. And there are many technical experts who have made certain achievements in automation, performance, security, test development, etc. Share their experience, and also share many live lectures and technical salons You can learn for free! Focus on it! Open source! ! ! QQ group number: 110685036
Place the universal login module code in loginpage.py (try to avoid duplication of code)
from selenium.webdriver.common.by import By from time import sleep from objpage.base import Page class login(Page): username_loc=(By.NAME,'accounts') password_loc=(By.NAME,'pwd') login_button_loc=(By.XPATH,'/html/body/div[5]/div/form/fieldset/p/button') login_error_loc=(By.XPATH,'//*[@id="common-prompt"]/p') def login_username(self,username): self.find_element(*self.username_loc).clear() self.find_element(*self.username_loc).send_keys(username) def login_password(self,password): self.find_element(*self.password_loc).clear() self.find_element(*self.password_loc).send_keys(password) def login_button(self): self.find_element(*self.login_button_loc).click() #Unified login entrance def user_login(self,username,password): self.open() self.login_username(username) self.login_password(password) self.login_button() sleep(2) #Login prompt information def login_error_text(self): return self.find_element(*self.login_error_loc).text
Place the public element operation code in parker.py (I named parker casually, so I don’t have to worry about it)
from selenium import webdriver from selenium.webdriver.common.action_chains import ActionChains from selenium.webdriver.support.select import Select class Parker(object): def __init__(self,browser='chrome'): if browser=='ie' or browser=='internet explorer': driver=webdriver.Ie() elif browser=='firefox' or browser=='ff': driver=webdriver.Firefox() elif browser=='chrome': driver=webdriver.Chrome() try: self.driver=driver exceptException: raise NameError('Browser not found, please enter"ie","chrome","ff"') def wait(self,secs=5): #Implicit wait self.driver.implicitly_wait(secs) def to_element(self,key):#Element positioning if '->' not in key: #If the key does not contain =, execute the following statement raise NameError('Parameter type input error') by=key.split('->')[0] #Get the value corresponding to [0] through separation val=key.split('->')[1]#Get the value corresponding to [1] through separation if by=='id': element=self.driver.find_element_by_id(val) elif by=='name': element=self.driver.find_element_by_name(val) elif by=='class': element=self.driver.find_element_by_class_name(val) elif by=='link_text': element=self.driver.find_element_by_link_text(val) elif by=='xpath': element=self.driver.find_element_by_xpath(val) elif by=='css': element=self.driver.find_element_by_css_selector(val) else: raise NameError('Please enter the correct positioning method: id, name, class, link_text, xpath, css') return element def open(self,url):#Open a URL self.driver.get(url) def max_window(self):#Maximize window (browser) self.driver.maximize_window() def set_windows(self,wide,high):#Set window size self.driver.set_window_size(wide,high) def input(self,key,text):#Enter the text box el=self.to_element(key) el.send_keys(text) def click(self,key):#Click el=self.to_element(key) el.click() def clear(self,key):#Clear the contents of the text box el=self.to_element(key) el.clear() def right_click(self,key):#right-click operation el=self.to_element(key) ActionChains(self.driver).context_click(el).perform() def move_to_element(self,key):#Mouseover el=self.to_element(key) ActionChains(self.driver).move_to_element(el).perform() def drag_and_drop(self,el_key,ta_key):#Drag drag from one element to another element el=self.to_element(el_key) target=self.to_element(ta_key) ActionChains(self.driver).drag_and_drop(el,target).perform() def click_text(self,text): self.driver.find_element_by_partial_link_text(text).click() def close(self):#Close the current browser window self.driver.close() def quit(self):#Exit the browser self.driver.quit() def submit(self,key):#Submit event el=self.to_element(key) el.submit() def F5(self):#Refresh self.driver.refresh() def js(self,script):#Execute js self.driver.execute_script(script) def get_attribute(self,key,attribute):#Get element attributes el=self.to_element(key) return el.get_attribute(attribute) def get_text(self,key):#Get text el=self.to_element(key) return el.text def get_title(self):#Get title return self.driver.title def get_url(self):#Get url return self.driver.current_url def to_frame(self,key):#Window switching el=self.to_element(key) self.driver.switch_to.frame(el) def alert_accept(self):#Dialog confirmation operation self.driver.switch_to.alert.accept() def alert_dismiss(self):#Dialog cancellation operation self.driver.switch_to.alert.dismiss() def img(self,fp):#Screenshot self.driver.get_screenshot_as_file(fp) def select_by_value(self,key,value):#Drop-down box operation el=self.to_element(key) Select(el).select_by_value(value)
send_email.py places the email sending code
import smtplib from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart import configparser import os def sendEmail(file_path): path=os.path.dirname(os.path.abspath(".")) cfpath=os.path.join(path,'autoparker\config\conf.ini') conf = configparser.ConfigParser() conf.read(cfpath) smtpserver = conf.get('emailqq','smtpserver') sender = conf.get('emailqq','sender') pwd = conf.get('emailqq','pwd') receiver=[] email_to=conf.get('emailqq','receiver') email_array=email_to.split(';') for i in range(len(email_array)): receiver.append(email_array[i]) print(receiver) with open(file_path,'rb') as fp: mail_boby=fp.read() msg=MIMEMultipart() msg['From']=sender msg['To']=",".join(receiver) msg['Subject']='I once broke a complete mirror' body=MIMEText(mail_boby,'html','utf-8') msg.attach(body) att=MIMEText(mail_boby,'html','utf-8') att['Content-Type']='application/octet-stream' att['Content-Disposition']='attachment;filename="test_reuslt.html"' msg.attach(att) try: smtp=smtplib.SMTP() smtp.connect(smtpserver) smtp.login(sender,pwd) except: smtp=smtplib.SMTP_SSL(smtpserver,465) smtp.login(sender,pwd) smtp.sendmail(sender,receiver,msg.as_string()) smtp.quit() sendEmail('D:\report.html')
The last main.py file contains the running code (just execute this file for testing)
import HTMLTestRunner import unittest from test_case.login import loginTest from public.send_email import sendEmail if __name__=='__main__': testunit=unittest.TestLoader().loadTestsFromTestCase(loginTest) suite=unittest.TestSuite(testunit) file_path="D:\html_report.html" fp=open(file_path,'wb') runner=HTMLTestRunner.HTMLTestRunner(stream=fp,title='Login test', description='Test execution result') runner.run(suite) fp.close() sendEmail(file_path)
Collect, follow + like~Develop good habits~
Finally, I would like to thank everyone who has read my article carefully. Looking at the increase in fans and attention, there is always some courtesy. Although it is not a very valuable thing, if you can use it, you can take it directly!
Software testing interview document
We must study to find a high-paying job. The following interview questions are the latest interview materials from first-tier Internet companies such as Alibaba, Tencent, Byte, etc., and some Byte bosses have given authoritative answers. After finishing this set I believe everyone can find a satisfactory job based on the interview information.
The knowledge points of the article match the official knowledge files, and you can further learn relevant knowledge. Python entry skill treeWeb crawlerSelenium387077 people are learning the system