def is_post_deleted(post_id: int) -> bool: info("Checking that post was deleted") try: post_form.get_like_button(post_id).wait_for_element_disappearing() return True except TimeoutException: return False
def send(self): self.msg['Subject'] = self.title self.msg['From'] = self.sender self.msg['To'] = self.receiver if self.message: self.msg.attach(MIMEText(self.message)) if self.files: if isinstance(self.files, list): for f in self.files: self._attach_file(f) elif isinstance(self.files, str): self._attach_file(self.files) try: smtp = smtplib.SMTP() smtp.connect(self.server) except (gaierror ,error) as e: logger.exception('发送邮件失败,无法连接到SMTP服务器,检查网络以及SMTP服务器. %s', e) else: try: smtp.login(self.sender, self.password) except smtplib.SMTPAuthenticationError as e: logger.exception('用户名密码验证失败!%s', e) else: smtp.sendmail(self.sender, self.receiver.split(';'), self.msg.as_string()) finally: smtp.quit() logger.info('发送邮件"{0}"成功! 收件人:{1}。如果没有收到邮件,请检查垃圾箱,' '同时检查收件人地址是否正确'.format(self.title, self.receiver))
def _attach_file(self, att_file): att = MIMEText(open('%s' % att_file, 'rb').read(), 'plain', 'utf-8') att["Content-Type"] = 'application/octet-stream' file_name = os.path.basename(att_file) att["Content-Disposition"] = 'attachment; filename="%s"' % file_name self.msg.attach(att) logger.info('attach file {}'.format(att_file))
def quit(self, err=None): if self._state != "dead": logger.info("Now, quit the browser.") self._state = "dead" self.driver.quit() else: logger.warning( "Some error has occurred and Browser has been closed !") if err: raise err
def run(): suite = generate_suite(collect_case()) if not os.path.exists(REPORT_PATH): os.makedirs(REPORT_PATH) report_path = os.path.join(REPORT_PATH, "report.html") backupCount = config.get("report").get("backup", 10) report_title = config.get("report").get("title", "Test Report") report_description = config.get("report").get("description", "Test Description") fileHandler = RotatingFileHandler(filename=report_path, backupCount=int(backupCount)) fileName = fileHandler.emit() with open(fileName, "w", encoding="utf-8") as f: runner = HTMLTestRunner(stream=f, title=report_title, description=report_description) result = runner.run(suite) logger.info("generate report to %s" % (os.path.basename(fileName))) return result
def compare_two_images_with_accuracy( path_to_first_picture: str, path_to_second_picture: str, percent_of_accuracy: int = config.PERCENT_OF_ACCURACY) -> bool: info( f"Comparing two pictures, difference percentage must be no more than {config.PERCENT_OF_ACCURACY}" ) image_1 = Image.open(path_to_first_picture) image_2 = Image.open(path_to_second_picture) assert image_1.mode == image_2.mode, "Different kinds of images." assert image_1.size == image_2.size, "Different sizes." pairs = zip(image_1.getdata(), image_2.getdata()) if len(image_1.getbands()) == 1: # for gray-scale jpegs dif = sum(abs(p1 - p2) for p1, p2 in pairs) else: dif = sum(abs(c1 - c2) for p1, p2 in pairs for c1, c2 in zip(p1, p2)) components = image_1.size[0] * image_1.size[1] * 3 difference_percentage = (dif / 255.0 * 100) / components return difference_percentage <= percent_of_accuracy
def __init__(self, browser_type="chrome"): self._state = "unopen" self._type = browser_type.lower() if self._type in TYPES: self.webdriver = TYPES[self._type] logger.info("You had select %s browser." % browser_type) else: logger.info("only support %s !" % ", ".join(TYPES.keys())) logger.error("can't supoort %s browser." % browser_type) self.quit() chrome_options = ChromeOptions() if config.get(self._type).get("is_headless", False): chrome_options.add_argument('--headless') chrome_options.add_argument('--disable-gpu') self.driver = self.webdriver( executable_path=EXECUTABLE_PATH[self._type], chrome_options=chrome_options) # elif config.get(self._type).get("is_remote",False): # options = ChromeOptions() # options.update(config.get(self._type)["remote"]) # debug = config.get("selenium").get("debug",False) # logger_name = config.get("selenium").get("logger",None) # self.driver = Chrome(options=options, debug=debug, logger_name=logger_name) if config.get(self._type)["simple"].get("maximize_window", False): try: self.driver.maximize_window() logger.info("Maximize the current window.") except Exception as e: logger.warning(e.msg) implicitly_wait_timeout = config.get(self._type)["simple"].get( "implicitly_wait", False) if implicitly_wait_timeout: self.driver.implicitly_wait(implicitly_wait_timeout) logger.info("Set implicitly wait %s seconds." % implicitly_wait_timeout)
def tearDownModule(): logger.info("<<<< exit case: %s" % (os.path.split(os.path.abspath(__file__))[1]))
def setUpModule(): logger.info(">>>> run case: %s" % (os.path.split(os.path.abspath(__file__))[1]))
def is_doc_uploaded(post_id: int, path_to_file: str) -> bool: info("Checking that doc was uploaded to post") file_name = os.path.basename(path_to_file) return post_form.is_doc_attached_to_post(post_id, file_name)
def is_photo_uploaded(uploaded_photo_id: str, path_to_picture: str, path_to_download_picture: str) -> bool: info("Checking that photo was uploaded in post") download_picture(uploaded_photo_id, path_to_download_picture) return compare_two_images_with_accuracy(path_to_picture, path_to_download_picture)
def log_in(login: str, password: str): info("Authorize") unauthorized_page.type_login(login) unauthorized_page.type_password(password) unauthorized_page.click_submit()
def navigate_to(self, item: SideBarItems): info(f"Go to the side bar item with id '{item.value}'") self.get_side_bar_item(item).click()
def is_page_opened(self) -> bool: info(f"Checking that {self.__name} was opened") return BaseElement(self.__locator_type, self.__locator, self.__name).is_displayed()
def get(self, url): self._state = "open" logger.info("Now, open url: %s" % url) self.driver.get(url)
title=report_title, description=report_description) result = runner.run(suite) logger.info("generate report to %s" % (os.path.basename(fileName))) return result def email(title, message, report_path): """ 使用Jenkins 集成,本机就不需要配置了""" config = ConfigReader() server = config.get("email", "server") sender = config.get("email", "sender") password = config.get("email", "password") receiver = config.get("email", "receiver") mail = Email(title=title, message=message, server=server, sender=sender, password=password, receiver=receiver, path=report_path) mail.send() if __name__ == "__main__": logger.info("******** TEST START ********") result = run() if result.error_count or result.failure_count: raise Exception("本次构建过程存在失败用例") logger.info("********* TEST END *********")