def setUpClass(context): driver = MyDriverFactory.getDriverManager(Browsers.chrome).getDriver() context.driver = driver lg = MyLogger() context.logger = lg.customLogger(logging.DEBUG) yield context.driver if context.driver is not None: context.driver.close()
def __init__(self): self.mylogger = MyLogger(self.__class__.__name__).getlogger() self.read = ReadYaml() btclassDB = self.read.getStream(FilePath.dbConfigPath)["DB_data"] self.host = btclassDB["host"] self.username = btclassDB["username"] self.password = btclassDB["password"] self.port = btclassDB["port"] self.basename = btclassDB["basename"] self.conn = None
class GuineenewsArchivesPage(BasePage): mylg = MyLogger () logger = mylg.customLogger ( logging.DEBUG ) def __init__(self, driver): super().__init__(driver) self.driver = driver calendar_table_id = "wp-calendar" calendar_day_having_archives = "//table[@id='wp-calendar']//child::a[contains(@aria-label, 'Publications')]" previous_month = "//nav[@class='wp-calendar-nav']/span[@class='wp-calendar-nav-prev']/a" next_month = "//nav[@class='wp-calendar-nav']/span[@class='wp-calendar-nav-next']/a" def select_archives(self, day): day_index = (int(day)-1) element = self.getListElement(myLocator=self.calendar_day_having_archives,locatorType="xpath",elementPosition=day_index) #self.scrollElementIntoView(element) self.arrow_down_up ( 2, "up" ) if self.isListElementClickable(element=element): self.clickListElement ( myLocator=self.calendar_day_having_archives, locatorType="xpath", elementPosition=day_index ) else: self.arrow_down_up ( 2, "up" ) self.clickListElement ( myLocator=self.calendar_day_having_archives, locatorType="xpath", elementPosition=day_index ) def click_previous_month(self): self.clickElement(myLocator=self.previous_month,locatorType="xpath") def click_next_month(self): self.clickElement(myLocator=self.next_month,locatorType="xpath")
def __init__(self, driver): self.driver = driver self.logger = MyLogger(self.__class__.__name__).getlogger() # 获取日志 self.baseView = BaseApi(self.driver) self.launchPath = FilePath().androidLaunchPage self.readYaml = ReadYaml() self.myself = MySelf(driver) self.launchPage = self.readYaml.getStream(self.launchPath) self.launchEle = self.launchPage.get("launch", False) self.checkLoginEle = self.launchPage.get("ckeckLogin", False) # 登录成功校验元素 self.mobileLoginButton = self.readYaml.getNode(self.launchEle, "mobileLoginButton") self.aaccount = self.readYaml.getNode(self.launchEle, "aaccount") self.passwd = self.readYaml.getNode(self.launchEle, "passwd") self.submitButton = self.readYaml.getNode(self.launchEle, "submitButton") self.forgetPasswd = self.readYaml.getNode(self.launchEle, "forgetPasswd") self.androidUserInfoPage = self.readYaml.getStream( FilePath.androidUserInfoPage) self.settingPage = self.readYaml.getStream(FilePath.androidSettingPage) self.settingButton = self.readYaml.getNode(self.androidUserInfoPage, "settingButton") self.loginOutButton = self.readYaml.getNode(self.settingPage, "loginOutButton") self.affirmLoginoutButton = self.readYaml.getNode( self.settingPage, "affirmLoginoutButton")
class GuineenewsSearchPage(BasePage): mylg = MyLogger() logger = mylg.customLogger(logging.DEBUG) pages = "//span[contains(@class, 'pages') and contains(text(), 'Page') and contains(text(), 'sur') ]" next_page_icon = "//div['page-nav td-pb-padding-side']/child::a/i[@class='td-icon-menu-right']/parent::a" previous_page_icon = "//div['page-nav td-pb-padding-side']/child::a/i[@class='td-icon-menu-left']/parent::a" last_page = "//div['page-nav td-pb-padding-side']/child::a[@class='last']" result_list = "//div[@class='td-ss-main-content']//child::h3[@class='entry-title td-module-title']/a" logo = "//div[@class='td-main-menu-logo td-logo-in-header td-logo-sticky']/a[@class='td-main-logo']" def __init__(self, driver): super().__init__(driver) self.driver = driver def is_more_than_one_result_page(self): if self.isVisible(self.pages, "xpath") is not None: return True else: return False def paginate_to_next_Page(self): element = self.getElement(self.next_page_icon, "xpath") self.scrollElementIntoView(element) sleep(2) self.clickElement(element=element) def click_a_random_search_result(self): elements = self.getElements(self.result_list, "xpath") if len(elements) > 0: random_index = random.randint(0, (len(elements) - 1)) element = self.getListElement(self.result_list, "xpath", random_index) self.scrollElementIntoView(element) sleep(1) self.clickElement(element=element) def click_a_specific_search_result(self, position): elements = self.getElements(self.result_list, "xpath") if len(elements) > 0: if position == "last": article_index = int(len(elements)) - 1 else: article_index = int(position) element = self.getListElement(self.result_list, "xpath", article_index) self.scrollElementIntoView(element) sleep(1) self.clickElement(element=element) def paginate_to_last_result_page(self): self.clickElement(myLocator=self.last_page, locatorType="xpath")
class JeuneAfriqueStartPage(BasePage): iframe = "//iframe[@name='__cmpLocator']" cookies_div = "//div[@id='main']" btn_accepter_cookies = "//button[@id='scmp-btn-allow']" #"scmp-btn-allow" menu = "main-menu-nav" btn_voir_tous_les_articles = "//div[@id='container__ribbon-cta']" btn_les_pays = "//a[@class='header-nav-left open-country-selection']" btn_politique = "//nav['main-navigation']//a[contains(@data-label, 'Politique')]" #btn_politique = "//a[contains(@data-label, 'Politique')]" #"//a[contains(@data-label, 'dropdown-menu Politique')]" #"//a[contains(@href,'/rubriques/politique/')]" btn_economie = "//a[contains(@data-label, 'Économie')]" btn_societe = "//a[contains(@data-label, 'Société')]" #"//a[contains(@data-category,'menu-main-navigation Menu Principal par défaut') and contains(@href,'/rubriques/societe/')]" btn_culture = "//a[contains(@data-label, 'Culture')]" #"//a[contains(@data-category,'menu-main-navigation Menu Principal par défaut') and contains(@href,'/rubriques/culture/')]" btn_sport = "//a[contains(@data-label, 'Sport')]" #"//a[contains(@data-category,'menu-main-navigation Menu Principal par défaut') and contains(@href,'/rubriques/sport/')]" btn_lifestyle = "//a[contains(@data-label, 'Lifestyle')]" #"//a[contains(@data-category,'menu-main-navigation Menu Principal par défaut') and contains(@href,'/campagnes-luxe/')]" myLg = MyLogger() logger = myLg.customLogger(logging.DEBUG) def __init__(self, driver): super().__init__(driver) def accept_cookies(self): try: print("current_handle............") print(self.driver.current_window_handle) handles = self.driver.window_handles #iframe = self.getElement(self.iframe, "xpath") #self.driver.switch_to.frame(self.iframe) #self.driver.switch_to.active_element () #self.waitForElementToBe(self.btn_accepter_cookies,"id", 10, 1) #if self.isClickable(self.btn_accepter_cookies,"xpath"): self.clickElement(self.btn_accepter_cookies, "xpath") #self.clickElement(self.btn_voir_tous_les_articles,"xpath") #self.driver.switch_to.default_content () except Exception as error: self.logger.error(error) def go_to_rubrique(self, rubrique, locatorType="xpath"): if rubrique == "Politique": self.clickElement(self.btn_politique, "xpath") #self.waitForElementToBe(self.menu, "id") if rubrique == "Economie": self.clickElement(self.btn_economie, "xpath") if rubrique == "Societe": self.clickElement(self.btn_societe, "xpath") if rubrique == "Culture": self.clickElement(self.btn_culture, "xpath") if rubrique == "Lifestyle": self.clickElement(self.btn_lifestyle, "xpath") if rubrique == "Sport": self.clickElement(self.btn_sport, "xpath")
""" This module defines the basic packet class. The packet class is extracted from the IP object of `scapy.layers.inet.IP`. """ from utils.logger import MyLogger from scapy.layers.inet import IP logger = MyLogger('BasicPacket') # Please don't put logger into the class class BasicPacket(object): """ The basic packet class. Parameters ---------- packet_id : int The global ID of the packet. timestamp : int The arrival time of the packet. (in microsecond) ip_packet : scapy.layers.inet.IP The packet extracted from `scapy`. Attributes ---------- packet_id : int The global ID of the packet. timestamp : int
def __init__(self, driver): self.driver = driver self.logger = MyLogger(self.__class__.__name__).getlogger()
class BaseApi(object): def __init__(self, driver): self.driver = driver self.logger = MyLogger(self.__class__.__name__).getlogger() def supperElement(self, loc, errorString, time=5): if not self.checkElement(loc, time): raise EleNotFound(errorString) def checkElement(self, loc, timeout=5): """ 检查元素是否存在 :param loc: loc type is tuple :return: check result """ if not isinstance(timeout, int): raise EleNotFound("超时时间必须是的整数") flage = True while flage and timeout > 0: try: self.driver.find_element(*loc) return True except: pass time.sleep(0.5) if flage and timeout == 0: return False timeout -= 0.5 def checkElements(self, loc, time=10): """ 检查元素是否存在 :param loc: loc type is tuple :return: check result """ try: WebDriverWait(self.driver, time).until(lambda x: x.find_elements(*loc)) return True except: return False def findElement(self, loc, timeout=5): """ 查找单个元素 :param loc: id,kw :param timeout: 超时时间 :return: Element """ if self.checkElement(loc, timeout): return self.driver.find_element(*loc) else: self.logger.error("元素:{0} 查找失败".format(loc)) raise EleNotFound("{0} 元素列表未找到".format(loc)) def findElements(self, loc, timeout=5): """ 查找多个元素 :param loc: id,kw :param timeout: 超时时间 :return: Element LIst """ if self.checkElement(loc, timeout): return self.driver.find_elements(*loc) else: self.logger.error("元素:{0} 查找失败".format(loc)) raise EleNotFound("{0} 元素列表未找到".format(loc)) def findElementUiautomator(self, loc): """ 使用uiuatomator定位元素 Android专用 :param loc: new UiSelector().text("id") :return: Element """ self.logger.info( str(('正在使用 new UiSelector().{0}(\"{1}\")'.format(loc[0], loc[1])))) try: EleRes = self.driver.find_element_by_android_uiautomator \ ('new UiSelector().{0}(\"{1}\")'.format(loc[0], loc[1])) return EleRes except: self.logger.error("元素:{0} 查找失败".format(loc)) raise EleNotFound("findElementUiautomator Error") def checkAccessiblity(self, loc, timeout=10): """ Accessiblity 检查元素是否存在 :param loc: accessibility Id :param timeout: 超时时间 :return: Element """ try: WebDriverWait(self.driver, timeout).until( lambda x: x.find_element_by_accessibility_id(loc)) return True except: return False def findAccessiblity(self, loc, timeout=10): """ accessibility Android 使用的是 content-desc 属性 IOS使用的是 accessibility identifier属性 :param loc: :param timeout: :return: """ if self.checkAccessiblity(loc, timeout): ele = self.driver.find_element_by_accessibility_id(loc) return ele else: self.logger.error("元素:{0} 查找失败".format(loc)) raise EleNotFound("findAccessiblity find element error ") def iosPredicates(self, ele, timeout=5): """ 查找多个元素 iOS 专用 :param ele: :param timeout: :return: """ if self.iosCheckElements(ele, timeout): ele = self.driver.find_elements_by_ios_predicate(ele) return ele else: raise EleNotFound("iOS ios_predicates:{} 元素未找到".format(ele)) def iosPredicate(self, ele, timeout=5): """ 查找单个元素 iOS专用 :param ele: :param timeout: :return: """ if self.iosCheckElement(ele, timeout): ele = self.driver.find_element_by_ios_predicate(ele) return ele else: raise EleNotFound("iOS ios_predicate:{} 元素未找到".format(ele)) def iosCheckElement(self, ele, timeout=5): """ 检查 iOS 单个元素是否存在 :param ele: :param timeout: :return: """ findFlage = True while findFlage and timeout > 0: try: self.driver.find_element_by_ios_predicate(ele) return True except: pass timeout -= 0.5 if timeout == 0: return False def iosCheckElements(self, ele, timeout=10): """ 检查 ios 多个元素是否存在 :param ele: :param timeout: :return: """ findFlage = True while findFlage and timeout > 0: try: self.driver.find_element_by_ios_predicate(ele) return True except: pass timeout -= 0.5 if timeout == 0: return False def Select(self, loc): """ Select 下拉框 :param loc: :return: """ s = Select(self.findElement(loc)) return s def click(self, *loc): """ 点击操作 :param loc: """ self.findElement(*loc).click() def getText(self, loc): """ 获取元素text文本 :param loc: 元素 :return: """ textData = self.findElement(loc, 10).text return textData def iosClick(self, loc, timeout=5): """ ios 点击元素 :param loc: :return: """ self.iosPredicate(loc, timeout).click() def setValue(self, loc, params, lenth=10): """ ios 输入值 :param ele: 元素 :param params: 输入值 :param lenth: 清除次数 :return: """ destEle = self.iosPredicate(loc) destEle.click() self.iosClearText(lenth) destEle.set_value(params) def iosClearText(self, lenth): """ ios 使用键盘删除 输入框内的数据 :param lenth: 删除的次数 """ if lenth: try: ele_button = 'type=="XCUIElementTypeKey" and label=="删除"' ele = self.iosPredicate(ele_button, 5) except: ele_button = 'type=="XCUIElementTypeKey" and label=="delete"' ele = self.iosPredicate(ele_button, 5) for l in range(lenth): ele.click() def sendKeys(self, loc, text): """ 输入 :param loc: 元素 :param text: 文本 :return: """ ele = self.findElement(loc) ele.clear() ele.send_keys(text) def back(self): """ 键盘返回 :return: """ self.driver.keyevent(4) def getSize(self): """ 获取窗口大小 :return: x轴、y轴坐标 """ are = self.driver.get_window_size() x = are['width'] y = are['height'] return x, y def getPage(self): """ 获取当前的 source Page :return: page """ page = self.driver.page_source return page def opterioneycode(self, keycode, metastate=None): """ 键盘输入 具体请看文档: https://blog.csdn.net/weixin_40180628/article/details/79169846 """ self.driver.press_keycode(keycode, metastate) def swipe(self, start_x, start_y, end_x, end_y, duration): """ 从一个坐标移动到另一个坐标 :param start_x: 起始x坐标 :param start_y: 起始y坐标 :param end_x: 结束X 坐标 :param end_y: 结束Y坐标 :param duration: :return: """ return self.driver.swipe(start_x, start_y, end_x, end_y, duration) def androidap(self, udid, x, y): """ Android adb 命令点击坐标 :param udid: 手机udid :param x: 横坐标 :param y: 纵坐标 :return: """ os.popen('adb -s {0} shell input tap {1} {2}'.format(udid, x, y)) def iosap(self, x, y): """ ios tap 方法 :return: """ are = self.driver.get_window_size() x = int(float(x / are["width"]) * are["width"]) y = int(float(y / are["height"]) * are["height"]) self.driver.execute_script("mobile: tap", { "x": x, "y": y, "duration": 500 }) def touch(self, x, y, x1, y1): """ 触摸移动 :param x: :param y: :param x1: :param y1: :return: """ TouchAction(self.driver).press(x=x, y=y).move_to(x=x1, y=y1).release().perform() def swipeUp(self, x_num=0.5, y1_num=0.25, y2_num=0.75, time=1000): """ 屏幕上滑 :param x_num: :param y1_num: :param y2_num: :param time: :return: """ are = self.getSize() x = int(are[0] * x_num) y1 = int(are[1] * y1_num) y2 = int(are[1] * y2_num) self.swipe(x, y1, x, y2, time) def swipeDown(self, x_num=0.5, y1_num=0.75, y2_num=0.25, time=1000): """ 屏幕下滑 :param x_num: :param y1_num: :param y2_num: :param time: :return: """ are = self.getSize() x = int(are[0] * x_num) y1 = int(are[1] * y1_num) y2 = int(are[1] * y2_num) self.swipe(x, y1, x, y2, time) def swipeRight(self, time=500): """ 屏幕右滑 :param time: :return: """ are = self.getSize() x1 = int(are[0] * 0.1) x2 = int(are[0] * 0.9) y = int(are[1] * 0.5) self.swipe(x1, y, x2, y, time) def swipeLeft(self, x_num=0.1, y1_num=0.5, x2_num=0.9, time=500): """ 屏幕左滑 :param x_num: :param y1_num: :param x2_num: :param time: :return: """ are = self.getSize() x1 = int(are[0] * x_num) x2 = int(are[0] * x2_num) y = int(are[1] * y1_num) self.swipe(x2, y, x1, y, time) def moveTo(self, loc): """ 鼠标移动到元素ele :param loc: :return: """ ele = self.findElement(loc) ActionChains(self.driver).move_to_element(ele).perform() def scroll(self, ele1, ele2): """ 从ele1 滑动到ele2 :param ele1: :param ele2: :return: """ self.driver.scroll(ele1, ele2) def getAllContext(self): """ 获取所有的Context :return: """ contexts = self.driver.Contexts self.logger.info("当前所有的contexts: {0}".format(contexts)) return contexts def getCurrentContext(self): """ 获取当前窗口 context :return: :return: """ currentContext = self.driver.current_context self.logger.info("当前Context: {0}".format(currentContext)) return self.driver.current_context def switchContext(self, context): """ 切换到指定的context 上 :param context: :return: """ self.driver._switch_to.context(context) def getAllHandles(self): """ 获取所有的窗口的handles :return: """ allHandles = self.driver.window_handles return allHandles def switchHandles(self, handles): """ 切换到指定的headles :param handles: 需啊哟切换的hadles :return: """ self.driver._switch_to.window(handles) def switchToFrame(self, loc): """frame 窗口切换""" self.driver.switch_to.frame(loc)
def __init__(self, flow_timeout): self.current_flows = {} self.finished_flows = [] self.flow_timeout = flow_timeout self.logger = MyLogger('FlowGenerator')
class FlowGenerator(object): """ The flow generator class. It maintains two collection spaces, one represents the currently processing flows `current_flows`, the other is the flows finished processing `finished_flows`. Attributes ---------- current_flows : dict of {str: Flow} The flows which are currently processing. finished_flows : list of Flow The flows which are considered as finished. flow_timeout : int The timeout of a flow. Parameters ---------- flow_timeout: int The timeout of a flow. """ def __init__(self, flow_timeout): self.current_flows = {} self.finished_flows = [] self.flow_timeout = flow_timeout self.logger = MyLogger('FlowGenerator') def add_packet(self, packet): """ Add the packet to current flow. Parameters ---------- packet: BasicPacket The processed `BasicPacket` object. """ if not packet: return forward_packet_flow_id = packet.forward_flow_id() backward_packet_flow_id = packet.backward_flow_id() current_timestamp = packet.timestamp if forward_packet_flow_id not in self.current_flows and backward_packet_flow_id not in self.current_flows: # A new flow begins self.current_flows[forward_packet_flow_id] = Flow(packet, self.flow_timeout) else: if forward_packet_flow_id in self.current_flows: flow = self.current_flows[forward_packet_flow_id] else: flow = self.current_flows[backward_packet_flow_id] # Under the status of ACTIVE: # 1. When received a packet and it is timeout, finish current flow and genenrate a new flow. # 2. When received a forward FIN packet, turn to FIN_WAIT_1 status. # 3. When received a backward FIN packet, turn to CLOSE_WAIT status. # 4. When received a RST packet, finish current flow. # 5. When received a normal packet, add the packet to current flow. if flow.flow_status == FlowStatus.ACTIVE: if current_timestamp - flow.end_timestamp > self.flow_timeout: self._timeout_process(flow, packet) elif packet.hasFIN: flow.add_packet(packet) if packet.forward_flow_id() == flow.flow_id: flow.flow_status = FlowStatus.FIN_WAIT_1 else: flow.flow_status = FlowStatus.CLOSE_WAIT elif packet.hasRST: self.logger.debug(f'Received a RST packet: {flow.flow_id}') flow.add_packet(packet) self._move_flow_from_current_to_finished(flow) else: flow.add_packet(packet) elif flow.flow_status == FlowStatus.FIN_WAIT_1: flow.add_packet(packet) if packet.hasFIN: flow.flow_status = FlowStatus.CLOSING else: flow.flow_status = FlowStatus.FIN_WAIT_2 elif flow.flow_status == FlowStatus.FIN_WAIT_2: flow.add_packet(packet) if packet.hasFIN: flow.flow_status = FlowStatus.TIME_WAIT elif current_timestamp - flow.end_timestamp > self.flow_timeout: self._timeout_process(flow, packet) elif flow.flow_status == FlowStatus.CLOSING: flow.add_packet(packet) if packet.hasACK: self._move_flow_from_current_to_finished(flow) elif current_timestamp - flow.end_timestamp > self.flow_timeout: self._timeout_process(flow, packet) elif flow.flow_status == FlowStatus.CLOSE_WAIT: flow.add_packet(packet) if packet.backward_flow_id() == flow.flow_id and packet.hasFIN: flow.flow_status = FlowStatus.LAST_ACK elif current_timestamp - flow.end_timestamp > self.flow_timeout: self._timeout_process(flow, packet) elif flow.flow_status == FlowStatus.LAST_ACK: flow.add_packet(packet) if packet.hasACK: self._move_flow_from_current_to_finished(flow) elif current_timestamp - flow.end_timestamp > self.flow_timeout: self._timeout_process(flow, packet) elif flow.flow_status == FlowStatus.TIME_WAIT: if current_timestamp - flow.end_timestamp > self.flow_timeout: self._timeout_process(flow, packet) def _move_flow_from_current_to_finished(self, flow): """ Move the flow from `current_flows` to `finished_flows`. Parameters ---------- flow: Flow The flow to be moved. """ self.finished_flows.append(flow) if flow.flow_id in self.current_flows.keys(): self.current_flows.pop(flow.flow_id) else: self.logger.warning("flow id %s is not in current_flows.keys()", flow.flow_id) self.logger.warning("Reverse the flow ID.") self.current_flows.pop(flow.reverse_flow_id()) def _timeout_process(self, flow, packet): """ The encapsulation of the process of timeout packets. Parameters ---------- flow: Flow Currently processing flow. packet: BasicPacket The timeout packet. """ self.logger.debug(f'Flow Timeout: {flow.flow_id}') if flow.packet_count > 1: self.finished_flows.append(flow) if flow.flow_id in self.current_flows: self.current_flows.pop(flow.flow_id) self.current_flows[flow.flow_id] = Flow(packet, self.flow_timeout) def dumpflows_to_csv(self, output_file): """ Dump the statistics of all flows in `finished_flow` and generate target CSV file. If there are remaining flows in `current_flows`, move them to `finished_flows`. Parameters ---------- output_file: str The file name of output file. """ header = [ "Flow ID", "Src IP", "Src Port", "Dst IP", "Dst Port", "Protocol", "Start Time", "End Time", "Start Timestamp", "End Timestamp", "Flow Duration", "Total Packet Length", "Min Packet Length", "Max Packet Length", "Mean Packet Length", "Std Packet Length", "Total Fwd Packet Length", "Min Fwd Packet Length", "Max Fwd Packet Length", "Mean Fwd Packet Length", "Std Fwd Packet Length", "Total Bwd Packet Length", "Min Bwd Packet Length", "Max Bwd Packet Length", "Mean Bwd Packet Length", "Std Bwd Packet Length", "Total Fwd Header Length", "Min Fwd Header Length", "Max Fwd Header Length", "Mean Fwd Header Length", "Std Fwd Header Length", "Total Bwd Header Length", "Min Bwd Header Length", "Max Bwd Header Length", "Mean Bwd Header Length", "Std Bwd Header Length", "Total Fwd Payload Length", "Min Fwd Payload Length", "Max Fwd Payload Length", "Mean Fwd Payload Length", "Std Fwd Payload Length", "Total Bwd Payload Length", "Min Bwd Payload Length", "Max Bwd Payload Length", "Mean Bwd Payload Length", "Std Bwd Payload Length", "Packet Count", "Fwd Packet Count", "Bwd Packet Count", "Packet Rate", "Fwd Packet Rate", "Bwd Packet Rate", "Bytes Rate", "Fwd Bytes Rate", "Bwd Bytes Rate", "SYN Count", "ACK Count", "RST Count", "URG Count", "PSH Count", "FIN Count", "Init Window Size", "Min Packet Interval", "Max Packet Interval", "Mean Packet Interval", "Std Packet Interval", "Min Fwd Packet Interval", "Max Fwd Packet Interval", "Mean Fwd Packet Interval", "Std Fwd Packet Interval", "Min Bwd Packet Interval", "Max Bwd Packet Interval", "Mean Bwd Packet Interval", "Std Bwd Packet Interval", ] lines = [','.join(header) + '\n'] while self.current_flows: flow_id = list(self.current_flows.keys())[0] self._move_flow_from_current_to_finished(self.current_flows[flow_id]) for flow in tqdm(self.finished_flows, total=len(self.finished_flows)): data_line = [ flow.flow_id, flow.src_ip, flow.src_port, flow.dst_ip, flow.dst_port, flow.protocol, flow.start_time, flow.end_time, flow.start_timestamp, flow.end_timestamp, flow.flow_duration, flow.total_packet_length, flow.min_packet_length, flow.max_packet_length, flow.mean_packet_length, flow.std_packet_length, flow.total_forward_packet_length, flow.min_forward_packet_length, flow.max_forward_packet_length, flow.mean_forward_packet_length, flow.std_forward_packet_length, flow.total_backward_packet_length, flow.min_backward_packet_length, flow.max_backward_packet_length, flow.mean_backward_packet_length, flow.std_backward_packet_length, flow.total_forward_packet_header_length, flow.min_forward_packet_header_length, flow.max_forward_packet_header_length, flow.mean_forward_packet_header_length, flow.std_forward_packet_header_length, flow.total_backward_packet_header_length, flow.min_backward_packet_header_length, flow.max_backward_packet_header_length, flow.mean_backward_packet_header_length, flow.std_backward_packet_header_length, flow.total_forward_packet_header_length, flow.min_forward_packet_payload_length, flow.max_forward_packet_payload_length, flow.mean_forward_packet_payload_length, flow.std_forward_packet_payload_length, flow.total_backward_packet_payload_length, flow.min_backward_packet_payload_length, flow.max_backward_packet_payload_length, flow.mean_backward_packet_payload_length, flow.std_backward_packet_payload_length, flow.packet_count, flow.forward_packet_count, flow.backward_packet_count, flow.packet_rate, flow.forward_packet_rate, flow.backward_packet_rate, flow.bytes_rate, flow.forward_bytes_rate, flow.backward_bytes_rate, flow.tcp_flags[0], flow.tcp_flags[1], flow.tcp_flags[2], flow.tcp_flags[3], flow.tcp_flags[4], flow.tcp_flags[5], flow.init_window_size, flow.min_packet_interval, flow.max_packet_interval, flow.mean_packet_interval, flow.std_packet_interval, flow.min_forward_packet_interval, flow.max_forward_packet_interval, flow.mean_forward_packet_interval, flow.std_forward_packet_interval, flow.min_backward_packet_interval, flow.max_backward_packet_interval, flow.mean_backward_packet_interval, flow.std_backward_packet_interval, ] data_line = list(map(str, data_line)) data_str = ','.join(data_line) + '\n' lines.append(data_str) try: of = open(output_file, 'w+') of.writelines(lines) self.logger.info(f'Create output file {output_file} successfully.') of.close() except FileNotFoundError: self.logger.error(f'Create output file {output_file} failed!', exc_info=True)
class DbOption(object): def __init__(self): self.mylogger = MyLogger(self.__class__.__name__).getlogger() self.read = ReadYaml() btclassDB = self.read.getStream(FilePath.dbConfigPath)["DB_data"] self.host = btclassDB["host"] self.username = btclassDB["username"] self.password = btclassDB["password"] self.port = btclassDB["port"] self.basename = btclassDB["basename"] self.conn = None def connect(self): try: self.conn = pymysql.connect(host=self.host, user=self.username, passwd=self.password, db=self.basename, port=self.port, charset='utf8') except Exception as msg: self.mylogger.info("数据库连接错误:{0}".format(msg)) return self.conn def reconnect(self): """ 数据库重连机制 :return: """ try: self.conn.ping() return False except: return self.connect() def select(self, sql): cursor = self.connect().cursor() try: reconnect = self.reconnect() if reconnect: cursor = reconnect.cursor() cursor.execute(sql) data = cursor.fetchall() except Exception as msg: self.mylogger.info("sql查询错误:{0}".format(msg) + "\n" + "错误sql:{0}".format(sql)) data = () cursor.close() self.conn.close() return data def operation(self, sql): cursor = self.connect().cursor() try: reconnect = self.reconnect() if reconnect: cursor = reconnect.cursor() cursor.execute(sql) self.conn.commit() except Exception as msg: self.conn.rollback() self.mylogger.info("sql:{0} 操作失败:{1}".format(msg, sql)) cursor.close() self.conn.close()
class GuineenewsStartPageTest(unittest.TestCase): lg = MyLogger() logger = lg.customLogger(logging.DEBUG) @classmethod def setUpClass(cls) -> None: try: cls.driver = MyDriverFactory.getDriverManager("CHROME").getDriver() cls.logger.info("driver was successfuly created") cls.startPage = GuineenewsStartPage(cls.driver) cls.menuPage = GuineenewsMenu(cls.driver) except Exception as error: cls.logger.error(error) def setUp(self) -> None: pass @pytest.mark.run(order=1) def test_start_guineenews(self): try: self.driver.get(Pages.getPageURL("guineenewsStartPage")) self.logger.info("Guineenews started successfully") # current_hd = self.driver.current_window_handle # self.logger.info("current handle"+current_hd) # hd = self.driver.window_handles # if hd is not None: # for h in hd: # self.logger.info(h) # self.startPage.takescreenShotOnError("test_start_guineenews") self.driver.switch_to.default_content() # sleep(5) except Exception as error: self.logger.error(error) @pytest.mark.run(order=2) def test_click_sport(self): sleep(10) # self.startPage.takescreenShotOnError("before_clicking_sport") self.startPage.go_to_rubrique("Sport") # self.startPage.takescreenShotOnError("after_clicking_sport") @pytest.mark.run(order=3) def test_Mouse_0n_News(self): try: self.menuPage.move_mouse_on("News") sleep(2) except Exception as error: self.logger.error(error) @pytest.mark.run(order=4) def test_Mouse_0n_Politique(self): try: self.menuPage.move_mouse_on("Politique") sleep(2) except Exception as error: self.logger.error(error) @pytest.mark.run(order=5) def test_Mouse_0n_Revue_de_Presse(self): try: self.menuPage.move_mouse_on("Revue") sleep(2) except Exception as error: self.logger.error(error) @pytest.mark.run(order=6) def test_Mouse_0n_Societe(self): try: self.menuPage.move_mouse_on("Societe") sleep(2) except Exception as error: self.logger.error(error) @pytest.mark.run(order=7) def test_click_Random_article_in_Revue_de_Presse(self): try: self.menuPage.click_random_sub_article_in("Region") sleep(3) except Exception as error: self.logger.error(error) @pytest.mark.run(order=8) #@data ("Alpha code", "Cellou Dalein Diallo") @file_data("C:\\MyWorkspace\\python_workspace\\myFrameWork\\testData.json") @unpack def test_search_text_alpha_conde(self, txt): try: self.startPage.search(txt) sleep(3) except Exception as error: self.logger.error(error) @pytest.mark.run(order=9) # @data ("Alpha code", "Cellou Dalein Diallo") @data(*readCSV( "C:\\MyWorkspace\\python_workspace\\myFrameWork\\resources\\testData.csv" )) @unpack def test_search_text_Titi(self, txt): try: self.startPage.search(txt) sleep(3) except Exception as error: self.logger.error(error) def tearDown(self) -> None: pass @classmethod def tearDownClass(cls) -> None: if cls.driver is not None: #cls.driver.implicitly_wait (5) sleep(5) cls.driver.close()
class GuineenewsStartPage(BasePage): lg = MyLogger() logger = lg.customLogger(logging.DEBUG) menu_acceuil = "//ul[@id='menu-mainmenu-1']/li[1]/a" menu_news = "//ul[@id='menu-mainmenu-1']/li[2]/a" menu_grands_dossiers = "//ul[@id='menu-mainmenu-1']/li[3]/a" menu_interviews = "//ul[@id='menu-mainmenu-1']/li[4]/a" menu_publireportage = "//ul[@id='menu-mainmenu-1']/li[5]/a" menu_region = "//ul[@id='menu-mainmenu-1']/li[6]/a" menu_sport = "//ul[@id='menu-mainmenu-1']/li[7]/a" menu_le_monde = "//ul[@id='menu-mainmenu-1']/li[8]/a" sub_menu_tous = "//ul[@id='menu-mainmenu-1']/li[2]/ul//child::div[@class='block-mega-child-cats']/a[1]" sub_menu_art_et_culture = "//ul[@id='menu-mainmenu-1']/li[2]/ul//child::div[@class='block-mega-child-cats']/a[2]" sub_menu_economie = "//ul[@id='menu-mainmenu-1']/li[2]/ul//child::div[@class='block-mega-child-cats']/a[3]" sub_menu_faits_divers = "//ul[@id='menu-mainmenu-1']/li[2]/ul//child::div[@class='block-mega-child-cats']/a[4]" sub_menu_politique = "//ul[@id='menu-mainmenu-1']/li[2]/ul//child::div[@class='block-mega-child-cats']/a[5]" sub_menu_revue_de_presse = "//ul[@id='menu-mainmenu-1']/li[2]/ul//child::div[@class='block-mega-child-cats']/a[6]" sub_menu_societe = "//ul[@id='menu-mainmenu-1']/li[2]/ul//child::div[@class='block-mega-child-cats']/a[7]" search_icon = 'td-header-search-button' #"//a[@id='td-header-search-button']" search_field = 'td-header-search' #"//input[@id='td-header-search']" search_btn = 'td-header-search-top' #"//input[@id='td-header-search-top']" def __init__(self, driver): try: super().__init__(driver) self.driver = driver self.logger.info("StartPage successfully created") except Exception as error: self.logger.error(error) def go_to_rubrique(self, rubrique, locatorType="xpath"): if rubrique == Menu.Acceuil: self.clickElement(self.menu_acceuil, "xpath") # self.waitForElementToBe(self.menu, "id") if rubrique == Menu.News: self.clickElement(self.menu_news, "xpath") if rubrique == Menu.Grands_Dossiers: self.clickElement(self.menu_grands_dossiers, "xpath") if rubrique == Menu.Interviews: self.clickElement(self.menu_interviews, "xpath") if rubrique == Menu.Publireportage: self.clickElement(self.menu_publireportage, "xpath") if rubrique == Menu.Region: self.clickElement(self.menu_region, "xpath") if rubrique == Menu.Sport: self.clickElement(self.menu_sport, "xpath") if rubrique == Menu.Le_Monde: self.clickElement(self.menu_le_monde, "xpath") def go_to_sub_rubrique(self, sub_rubrique, locatorType="xpath"): if sub_rubrique == Menu.Tous: self.clickElement(self.sub_menu_tous, "xpath") # self.waitForElementToBe(self.menu, "id") if sub_rubrique == Menu.Art_et_Culture: self.clickElement(self.sub_menu_art_et_culture, "xpath") if sub_rubrique == Menu.Economie: self.clickElement(self.sub_menu_economie, "xpath") if sub_rubrique == Menu.Faits_Divers: self.clickElement(self.sub_menu_faits_divers, "xpath") if sub_rubrique == Menu.Politique: self.clickElement(self.sub_menu_politique, "xpath") if sub_rubrique == Menu.Societe: self.clickElement(self.sub_menu_societe, "xpath") if sub_rubrique == Menu.Revue_de_presse: self.clickElement(self.sub_menu_revue_de_presse, "xpath") if sub_rubrique == Menu.Le_Monde: self.clickElement(self.menu_le_monde, "xpath") def move_mouse_on(self, menu_locator, locatorType="xpath"): if menu_locator == Menu.News: self.moveMouseOnElement(self.menu_news, locatorType) if menu_locator == Menu.Politique: self.moveMouseOnElement(self.sub_menu_politique, locatorType) if menu_locator == Menu.Revue_de_presse: self.moveMouseOnElement(self.sub_menu_revue_de_presse, locatorType) def search(self, txt): self.clickElement(self.search_icon) searchField_input = self.waitForElementToBe(self.search_field, "id", event="visible") self.clearField(element=searchField_input) self.typeTextInField(text=txt, element=searchField_input) self.clickElement(self.search_btn, "id")
def __init__(self,host,port,udid,webDriver=None): self.logger = MyLogger("AppiumServer").getlogger() self.host = host self.port = port self.udid = udid self.webDriver = webDriver
class AppiumServer(object): def __init__(self,host,port,udid,webDriver=None): self.logger = MyLogger("AppiumServer").getlogger() self.host = host self.port = port self.udid = udid self.webDriver = webDriver def startAppiumServer(self): """ 启动Appium Server :param host: 启动的本地ip :param port: 启动端口 :param udid: 绑定的udid """ bootStarpPort = str(self.port+1) cmd = " appium -a {0} -p {1} -bp {2} -U {3}".format(self.host, self.port, bootStarpPort,self.udid) appium_log = os.path.join(FilePath.appiumLog, str(self.port) + '.log') if self.checkPort(): self.logger.info("端口:{0}已被占用".format(self.port)) self.stopPort() if os.path.exists(appium_log): os.remove(appium_log) subprocess.Popen(cmd, shell=True, stdout=open(appium_log, 'a'), stderr=subprocess.STDOUT) flage = False checkCount = 0 while not flage and checkCount<7: time.sleep(1) flage = self.checkPort() if flage: self.logger.info("端口:{0} Appium 系统服务启动成功".format(self.port)) if not flage and checkCount==6: self.logger.info("端口:{0} Appium 系统服务启动成功".format(self.port)) checkCount +=1 def checkPort(self): """ 端口检查 :return: check res """ try: requests.get("http://{0}:{1}/wd/hub/status".format(self.host, self.port)) res = True except: res = False return res def stopPort(self): """ 关闭appium server :param port: :return: """ if self.webDriver: # 关闭webDriver CloseWebdriver().closeWebdriver(self.webDriver) platform = sys.platform if "win" in platform : cmd = 'netstat -ano|findstr "{0}"' .format(self.port) else: cmd = "ps -ef | grep {0}".format(self.port) + "| awk '{print $2}'" pid_list = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE).stdout.readlines() pattrn = re.compile(r"(\d+)") for pid in pid_list: if "win" in platform : cmd = "taskkill /pid {0} /f".format(pattrn.findall(str(pid))[-1]) print(cmd) else: cmd = 'kill -9 {0}'.format(pattrn.findall(str(pid))[0]) os.system(cmd) self.logger.info("端口:{0}退出成功".format(self.port))
from tqdm import tqdm from pcapfile.savefile import load_savefile from analyzer.FlowGenerator import FlowGenerator from utils.logger import MyLogger from entities.BasicPacket import BasicPacket from utils.NotifierWin32 import NotifierWin32 try: from utils.NotifierLinux import NotifierLinux except ImportError: pass FLOW_TIMEOUT = 120000000 # 120 seconds APP_NAME = 'NetworkPacketAnalyzer' if __name__ == '__main__': logger = MyLogger('main') if len(sys.argv) != 3: logger.error('Argument insufficient. Need Inputfile and Outputfile') exit(1) input_file = sys.argv[1] output_file = sys.argv[2] # Set notifier if sys.platform == 'win32': notifier = NotifierWin32(APP_NAME) elif sys.platform == 'linux': notifier = NotifierLinux(APP_NAME) else: notifier = None
class SeleniumDriverWrapper: mylogger = MyLogger () logger = mylogger.customLogger ( logging.DEBUG ) logger = None def __init__(self, driver): self.driver = driver def getByType(self, locatorType): #webdriver.Chrome. wb=None try: if locatorType.upper() == "ID": return By.ID if locatorType.upper() == "NAME": return By.NAME if locatorType.upper() == "CLASS_NAME": return By.CLASS_NAME if locatorType.upper() == "TAG_NAME": return By.TAG_NAME if locatorType.upper() == "LINK_TEXT": return By.LINK_TEXT if locatorType.upper() == "PARTIAL_LINK_TEXT": return By.PARTIAL_LINK_TEXT if locatorType.upper() == "XPATH": return By.XPATH except Exception as error: self.logger.error(error) def getElement(self, myLocator, locatorType="id"): """ :type locator: string """ byType=None try: byType = self.getByType(locatorType) #self.logger.info(byType) el = self.driver.find_element(byType, myLocator) return el except (Exception, NoSuchElementException) as error: self.logger.error(error) def getElements(self, myLocator, locatorType="id"): """ :type locator: string """ try: byType = self.getByType(locatorType) el = self.driver.find_elements(byType, myLocator) return el except (Exception, NoSuchElementException) as error: self.logger.error(error) def clickElement(self, myLocator="None", locatorType="id", element=None): try: if element is None: element = self.getElement(myLocator, locatorType) element.click() except ElementNotVisibleException as error: self.logger.error(str(error)) def typeTextInField(self, myLocator='', locatorType="id",text='', element=None): try: if element is None: element = self.getElement(myLocator, locatorType) element.send_keys(text) except ElementNotVisibleException as error: self.logger.error(error) def clearField(self, myLocator='', locatorType='id',element=None): try: if element is None: element = self.getElement(myLocator, locatorType) element.clear() except ElementNotVisibleException as error: self.logger.error(error) def getElementText(self, myLocator="", locatorType="", element=None): try: if element is None: element = self.getElement(myLocator, locatorType) return element.text except ElementNotVisibleException as error: self.logger.error(error) def getPageTitle(self): try: return self.driver.title except Exception as error: self.logger.error(error) def getCurrentUrl(self): try: return self.driver.current_url except Exception as e: self.logger.error(e.__str__()) def getTagName(self, myLocator, locatorType): try: return self.getElement(myLocator, locatorType).tag_name except ElementNotVisibleException as error: self.logger.error(error) def isEnabled(self, myLocator, locatorType): try: return self.getElement(myLocator, locatorType).is_enabled() except (ElementNotSelectableException, ElementNotVisibleException) as error: self.logger.error(error) def isVisible(self, myLocator="", locatorType="xpath", element=None): is_visible=True try: if element is None: element = self.getElement(myLocator, locatorType) is_visible=element.is_displayed() #self.logger.warning(f"checking element visibility {is_visible}") return is_visible except (ElementNotSelectableException, ElementNotVisibleException) as error: self.logger.error(error) def isSelected(self, myLocator, locatorType): try: return self.getElement(myLocator, locatorType).is_selected() except (ElementNotSelectableException, ElementNotVisibleException) as error: self.logger.error(error) #def isEmpty(self, myLocator, locatorType): # self.getElement(myLocator, locatorType). def isChecked(self, myLocator, locatorType): try: return self.getElement(myLocator, locatorType).get_attribute("checked") except (ElementNotSelectableException, ElementNotVisibleException) as error: self.logger.error(error) def isFocused(self, myLocator, locatorType): try: return self.getElement(myLocator, locatorType).get_attribute("focused") except (ElementNotSelectableException, ElementNotVisibleException) as error: self.logger.error(error) def isClickable(self, myLocator="", locatorType="xpath", element=None): is_clickable=True try: if element is None: byType = self.getByType(locatorType) element = self.getElement(myLocator, byType) is_clickable = element.get_attribute("clickable") webdriver.Chrome.find_element( By.id, myLocator ).get self.logger.warning ( f"checking element clickbility {is_clickable}" ) return is_clickable except (ElementNotSelectableException, ElementNotVisibleException) as error: self.logger.error(error) def selectElementDropDownElement(self, myLocator=None, locatorType="xpath", value=None, index=None, text=None, criteria="value", element=None): try: if element is None: element = self.getElement(myLocator,locatorType) if criteria == "value": return Select(element).select_by_value(value) if criteria == "index": return Select ( element ).select_by_index(index) if criteria == "text": return Select ( element ).select_by_visible_text(text) except Exception as error: self.logger.error(error) def deselectDropDownElement(self, myLocator=None, locatorType="xpath", value=None, index=None, text=None, criteria="value", element=None): try: if element is None: element = self.getElement ( myLocator, locatorType ) if criteria == "value": return Select ( element ).select_by_value ( value ) if criteria == "index": return Select ( element ).select_by_index ( index ) if criteria == "text": return Select ( element ).select_by_visible_text ( text ) except Exception as error: self.logger.error ( error ) def isListElementClickable(self, myLocator=None, locatorType="xpath", position=None, element=None): try: if element is None: byType = self.getByType(locatorType) element = self.getElements(myLocator, byType).__getitem__(position) return element.get_attribute("clickable") except Exception as error: self.logger.error(error) def getClassName(self, myLocator, locatorType): try: return self.getElement(myLocator, locatorType).get_attribute("classname") #webdriver.Chrome.find_elements(By.id, myLocator).__getitem__().__len__() except (ElementNotSelectableException, ElementNotVisibleException) as error: self.logger.error(error) def getContentDescription(self, myLocator, locatorType): try: return self.getElement(myLocator, locatorType).get_attribute("content-Desc") except (ElementNotSelectableException, ElementNotVisibleException) as error: self.logger.error(error) def getName(self, myLocator, locatorType): try: return self.getElement(myLocator, locatorType).get_attribute("name") except (ElementNotSelectableException, ElementNotVisibleException) as error: self.logger.error(error) def getLocation(self, myLocator, locatorType): try: return self.getElement(myLocator, locatorType).location except (ElementNotSelectableException, ElementNotVisibleException) as error: self.logger.error(error) def is_text_present(self, text): try: return str ( text ) in self.driver.page_source except ElementNotVisibleException as error: self.logger.error(error) def clickListElement(self, myLocator=None, locatorType="xpath", elementPosition=0, element=None, elements=None): try: if elements is not None: element = elements.__getitem__(elementPosition) elif element is None and myLocator is not None: element = self.getElements(myLocator,locatorType).__getitem__(elementPosition) #element = self.waitForElementToBe(myLocator, locatorType) element.click() #self.getElements(myLocator, locatorType).__getitem__(elementPosition).click() except (ElementNotSelectableException, ElementNotVisibleException) as error: self.takescreenShotOnError() self.logger.error(error) def getListElement(self, myLocator=None, locatorType="xpath", elementPosition=0, element=None): try: if element is None: element = self.getElements(myLocator,locatorType).__getitem__(elementPosition) #element = self.waitForElementToBe(myLocator, locatorType) return element #self.getElements(myLocator, locatorType).__getitem__(elementPosition).click() except (ElementNotSelectableException, ElementNotVisibleException) as error: self.takescreenShotOnError() self.logger.error(error) def waitForElementToBe(self, myLocator, locatorType="xpath", timeout=15, poll_frequency=.5, element=None, event="clickable"): try: #wt = WebDriverWait(self.driver,10) wt = WebDriverWait(self.driver,timeout=timeout,poll_frequency=poll_frequency, ignored_exceptions=[NoSuchElementException,ElementNotVisibleException, ElementNotSelectableException, ElementNotInteractableException]) byType = self.getByType ( locatorType) if event == 'visible': element = wt.until(EC.presence_of_element_located((byType, myLocator))) if event == "clickable": element = wt.until(EC.element_to_be_clickable((byType, myLocator))) else: element = wt.until(EC.element_to_be_clickable((byType, myLocator))) return element except Exception as error: self.logger.error(str(error)) def scrollDownToBottom(self): try: windowHeight = self.driver.execute_script("return document.body.scrollHeight;") while True: self.driver.execute_script("window.scrollTo(0, document.body.scrollHeight);") newWidowHeight = self.driver.execute_script("return document.body.scrollHeight;") if windowHeight == newWidowHeight: break windowHeight=newWidowHeight except Exception as error: self.logger.error(error) def scrollUpToTop(self): try: windowHeight = self.driver.execute_script("return document.body.scrollHeight;") while True: self.driver.execute_script("window.scrollTo(0, -document.body.scrollHeight);") newWidowHeight = self.driver.execute_script("return document.body.scrollHeight;") if windowHeight == newWidowHeight: break windowHeight = newWidowHeight except Exception as error: self.logger.error(error) def scrollElementIntoView(self, element): try: self.driver.execute_script("arguments[0].scrollIntoView(true);", element) #actions = ActionChains ( self.driver ) #actions.move_to_element(element).perform() except Exception as error: self.logger.error(error) def moveToElement(self, element): try: #self.driver.execute_script("arguments[0].scrollIntoView(true);", element) actions = ActionChains ( self.driver ) actions.move_to_element(element).perform() except Exception as error: self.logger.error(error) def scrollDownToElement(self, element): try: element.send_keys(Keys.PAGE_DOWN) except Exception as error: self.logger.error(error) def scrollUpToElement(self, element): try: element.send_keys(Keys.PAGE_UP) except Exception as error: self.logger.error(error) def pageDown(self): try: actions = ActionChains(self.driver) actions.send_keys(Keys.PAGE_DOWN).perform() except Exception as error: self.logger.error(error) def pageUp(self): try: actions = ActionChains ( self.driver ) actions.send_keys ( Keys.PAGE_UP ).perform () except Exception as error: self.logger.error(error) def arrow_down_up(self, count, direction): actions = ActionChains ( self.driver ) i = 0 try: if direction.upper() == "DOWN": while i < int(count): actions.send_keys ( Keys.ARROW_DOWN ).perform () time.sleep ( 2 ) i =i+1 elif direction.upper() == "UP": while i < int ( count ): actions.send_keys ( Keys.ARROW_UP ).perform () time.sleep ( 2 ) i = i+1 except Exception as error: self.logger.error(error) def goBack(self): try: last_height = self.driver.execute_script ( "return document.body.scrollHeight" ) self.driver.execute_script ( "window.scrollTo(0, document.body.scrollHeight);" ) self.driver.execute_script ( "window.history.go(-1)" ) #actions = ActionChains(self.driver) #actions.send_keys(Keys.ALT, Keys.LEFT).perform() #actions.key_down(Keys.ALT).send_keys(Keys.LEFT).key_up(Keys.ALT).perform() except Exception as error: self.logger.error(error) def moveMouseOnElement(self, mylocator, locatorType): try: actions = ActionChains(self.driver) byType = self.getByType(locatorType) element = self.getElement(mylocator, locatorType) actions.move_to_element(element).perform() except Exception as error: self.takescreenShotOnError() self.logger.error(error) #finally: #self.takescreenShotOnError() def takescreenShotOnError(self, stepname="click"): try: tsp = time.time().__str__() #datetime.now() #self.logger.warn(tsp) name=stepname+tsp+".png" self.driver.save_screenshot(name) #webdriver.Chrome.get_screenshot_as_png() self.logger.info("taking screenshot "+name) except Exception as error: self.logger.error ( "Error could not take screenshot") self.logger.error(error)
class GuineenewsMenu(BasePage): mylg = MyLogger() logger = mylg.customLogger(logging.DEBUG) logo = "//div[@class='td-main-menu-logo td-logo-in-header td-logo-sticky']/a[@class='td-main-logo']" # menu_acceuil = "//ul[@id='menu-mainmenu-1']/li[1]/a" # menu_news = "//ul[@id='menu-mainmenu-1']/li[2]/a" # menu_grands_dossiers = "//ul[@id='menu-mainmenu-1']/li[3]/a" # menu_interviews = "//ul[@id='menu-mainmenu-1']/li[4]/a" # menu_publireportage = "//ul[@id='menu-mainmenu-1']/li[5]/a" # menu_region = "//ul[@id='menu-mainmenu-1']/li[6]/a" # menu_sport = "//ul[@id='menu-mainmenu-1']/li[7]/a" # menu_le_monde = "//ul[@id='menu-mainmenu-1']/li[8]/a" sub_menus_news = "//ul[@id='menu-mainmenu-1']/li[2]/ul//child::div[@class='block-mega-child-cats']/a" sub_menus_grandossiers = "//ul[@id='menu-mainmenu-1']/li[3]/ul//child::h3[@class='entry-title td-module-title']/a" sub_menus_publireportage = "//ul[@id='menu-mainmenu-1']/li[5]/ul//child::h3[@class='entry-title td-module-title']/a" sub_menus_region = "//ul[@id='menu-mainmenu-1']/li[6]/ul//child::div[@class='block-mega-child-cats']/a" # sub_menu_tous = "//ul[@id='menu-mainmenu-1']/li[2]/ul//child::div[@class='block-mega-child-cats']/a[1]" # sub_menu_art_et_culture = "//ul[@id='menu-mainmenu-1']/li[2]/ul//child::div[@class='block-mega-child-cats']/a[2]" # sub_menu_faits_divers = "//ul[@id='menu-mainmenu-1']/li[2]/ul//child::div[@class='block-mega-child-cats']/a[4]" # sub_menu_economie = "//ul[@id='menu-mainmenu-1']/li[2]/ul//child::div[@class='block-mega-child-cats']/a[3]" # sub_menu_politique = "//ul[@id='menu-mainmenu-1']/li[2]/ul//child::div[@class='block-mega-child-cats']/a[5]" # sub_menu_revue_de_presse = "//ul[@id='menu-mainmenu-1']/li[2]/ul//child::div[@class='block-mega-child-cats']/a[6]" # sub_menu_societe = "//ul[@id='menu-mainmenu-1']/li[2]/ul//child::div[@class='block-mega-child-cats']/a[7]" search_icon = 'td-header-search-button' #"//a[@id='td-header-search-button']" search_field = 'td-header-search' #"//input[@id='td-header-search']" search_btn = 'td-header-search-top' #"//input[@id='td-header-search-top']" articles_filter = "//div[contains(@class,'td-subcat-more') and contains(text(), 'Dernier')]" filter_ul = "//div[@class='td-pulldown-filter-display-option']//child::ul[@class='td-pulldown-filter-list']" filter_lis = "//div[@class='td-pulldown-filter-display-option']//child::li[@class='td-pulldown-filter-item']" filter_result_list = "//div[@class='td-ss-main-content']//h3/a" def __init__(self, driver): super().__init__(driver) self.driver = driver def get_Menu_xpath_locator(self, menu): return "//ul[@id='menu-mainmenu-1']//child::a[contains(text(), '{}')]".format( str(menu)) def get_sub_Menu_xpath_locator(self, menu, sub_menu): return "//ul[@id='menu-mainmenu-1']//child::a[contains(text(), '{}')]//following-sibling::ul//" \ "child::div[@class='block-mega-child-cats']/a[contains(text(), '{}')]".format(menu, sub_menu) def go_to_rubrique(self, rubrique, locatorType="xpath"): myLocator = self.get_Menu_xpath_locator(rubrique) self.clickElement(myLocator, "xpath") # if rubrique == Menu.Acceuil: # self.clickElement ( self.menu_acceuil, "xpath" ) # # self.waitForElementToBe(self.menu, "id") # # if rubrique == Menu.News: # self.clickElement ( self.menu_news, "xpath" ) # # if rubrique == Menu.Grands_Dossiers: # self.clickElement ( self.menu_grands_dossiers, "xpath" ) # # if rubrique == Menu.Interviews: # self.clickElement ( self.menu_interviews, "xpath" ) # # if rubrique == Menu.Publireportage: # self.clickElement ( self.menu_publireportage, "xpath" ) # # if rubrique == Menu.Region: # self.clickElement ( self.menu_region, "xpath" ) # # if rubrique == Menu.Sport: # self.clickElement ( self.menu_sport, "xpath" ) # # if rubrique == Menu.Le_Monde: # self.clickElement ( self.menu_le_monde, "xpath" ) def move_mouse_on_main_menu_element(self, menu, locatorType="xpath"): myLocator = self.get_Menu_xpath_locator(menu) #self.logger.warning(myLocator) self.moveMouseOnElement(myLocator, locatorType) # if menu_locator == Menu.News: # self.moveMouseOnElement(self.menu_news,locatorType) # # if menu_locator == Menu.Grands_Dossiers: # self.moveMouseOnElement(self.menu_grands_dossiers,locatorType) # # if menu_locator == Menu.Publireportage: # self.moveMouseOnElement(self.menu_publireportage,locatorType) # # if menu_locator == Menu.Region: # self.moveMouseOnElement(self.menu_region,locatorType) #sleep(2) def go_to_sub_menu(self, menu, sub_menu, locatorType="xpath"): self.move_mouse_on(menu, locatorType) #if menu == Menu.Region: # self.move_mouse_on ( Menu.Region, locatorType ) sleep(1) myLocator = self.get_sub_Menu_xpath_locator(Menu.News, sub_menu) #self.logger.info(myLocator) element = self.waitForElementToBe(myLocator) self.clickElement(element=element) # if sub_menu == Menu.Tous: # element = self.waitForElementToBe(self.sub_menu_tous) # self.clickElement(element=element) # # self.waitForElementToBe(self.menu, "id") # # if sub_menu == Menu.Art_et_Culture: # element = self.waitForElementToBe (self.sub_menu_art_et_culture) # self.clickElement(element=element) # # if sub_menu == Menu.Economie: # element = self.waitForElementToBe (self.sub_menu_economie, locatorType=locatorType, event="visible") # self.clickElement ( element=element ) # #self.clickElement ( self.sub_menu_economie, locatorType ) # # if sub_menu == Menu.Faits_Divers: # element = self.waitForElementToBe (self.sub_menu_faits_divers) # self.clickElement (element=element) # # if sub_menu == Menu.Politique: # element = self.waitForElementToBe ( self.sub_menu_politique ) # self.clickElement ( element=element ) # # if sub_menu == Menu.Societe: # element = self.waitForElementToBe ( self.sub_menu_societe ) # self.clickElement ( element=element ) # #self.clickElement ( self.sub_menu_societe ) # # if sub_menu == Menu.Revue_de_presse: # element = self.waitForElementToBe ( self.sub_menu_revue_de_presse ) # self.clickElement ( element=element ) #if sub_rubrique == "Le_monde": # self.clickElement ( self.menu_le_monde, "xpath" ) def click_random_sub_article_in(self, menu, locatorType="xpath"): #try: if menu == Menu.Region: sub_menus = self.sub_menus_region #main_menu = self.menu_region if menu == Menu.Publireportage: sub_menus = self.sub_menus_publireportage #main_menu = self.menu_publireportage if menu == Menu.Grands_Dossiers: #self.logger.warning(self.sub_menus_grandossiers) sub_menus = self.sub_menus_grandossiers #main_menu = self.menu_grands_dossiers self.move_mouse_on_main_menu_element(menu) #sleep(2) #if menu == "menu_grands_dossiers": articles = self.getElements(sub_menus, "xpath") if len(articles) > 0: random_index = random.randint(1, (len(articles) - 1)) #self.logger.warning(str(len(articles))) self.clickListElement(myLocator=sub_menus, locatorType=locatorType, elementPosition=random_index) # except Exception as error: # self.logger.error(error) def move_mouse_on(self, menu_titel, locatorType="xpath"): myLocator = self.get_Menu_xpath_locator(menu_titel) self.moveMouseOnElement(myLocator, locatorType) # if menu_locator == Menu.News: # self.moveMouseOnElement(self.menu_news,locatorType) # # if menu_locator == Menu.Politique: # self.moveMouseOnElement(self.sub_menu_politique,locatorType) # # if menu_locator == Menu.Revue_de_presse: # self.moveMouseOnElement(self.sub_menu_revue_de_presse,locatorType) # # if menu_locator == Menu.Societe: # self.moveMouseOnElement(self.sub_menu_societe,locatorType) def search(self, txt): self.clickElement(self.search_icon) searchField_input = self.waitForElementToBe(self.search_field, "id", event="visible") self.clearField(element=searchField_input) self.typeTextInField(text=txt, element=searchField_input) self.clickElement(self.search_btn, "id") def select_from_derniers_drop_down_Menu(self, criteria): self.moveMouseOnElement(self.articles_filter, "xpath") sleep(3) filter_elements = self.getElements(self.filter_lis, locatorType="xpath") if (criteria == Menu.Filter_cretaria_vedette): #self.clickListElement(elementPosition=1, element=filter_elements) self.clickListElement(elementPosition=1, elements=filter_elements) if (criteria == Menu.Filter_cretaria_plus_populaire): self.clickListElement(elementPosition=2, elements=filter_elements) if (criteria == Menu.Filter_cretaria_7_j_populaire): self.clickListElement(elementPosition=3, elements=filter_elements) if (criteria == Menu.Filter_cretaria_mieux_notes): self.clickListElement(elementPosition=4, elements=filter_elements) if (criteria == Menu.Filter_cretaria_hasard): self.clickListElement(elementPosition=5, elements=filter_elements) def click_logo(self): self.clickElement(myLocator=self.logo, locatorType="xpath")
class GuineenewsAcceuil(BasePage): mylg = MyLogger() logger = mylg.customLogger(logging.DEBUG) # rubrique_title_dernieres_novelles = "//div[@class='td-block-title-wrap']//child::a[contains(text(), 'DERNIERES NOUVELLES')]" # rubrique_title_politique = "//div[@class='td-block-title-wrap']//child::a[contains(text(), 'POLITIQUE')]" # rubrique_title_Publi_reportage = "//div[@class='td-block-title-wrap']//child::span[contains(text(), 'PUBLIREPORTAGE')]" # rubrique_title_Grand_Dossiers = "//div[@class='td-block-title-wrap']//child::a[contains(text(), 'GRANDS DOSSIERS')]" # rubrique_title_Grand_Economie = "//div[@class='td-block-title-wrap']//child::a[contains(text(), 'ECONOMIE')]" # rubrique_title_Grand_Sport = "//div[@class='td-block-title-wrap']//child::a[contains(text(), 'SPORT')]" # rubrique_title_Grand_Societe = "//div[@class='td-block-title-wrap']//child::a[contains(text(), 'SOCIETE')]" # rubrique_title_Grand_Dossiers = "//div[@class='td-block-title-wrap']//child::a[contains(text(), 'GRANDS DOSSIERS')]" # rubrique_title_Grand_Economie = "//div[@class='td-block-title-wrap']//child::a[contains(text(), 'ECONOMIE')]" # rubrique_title_Grand_Sport = "//div[@class='td-block-title-wrap']//child::a[contains(text(), 'SPORT')]" # rubrique_title_Grand_Societe = "//div[@class='td-block-title-wrap']//child::a[contains(text(), 'SOCIETE')]" rubrique_tags = "//ul[@class='td-category']/li" def __init__(self, driver): super().__init__(driver) self.driver = driver def is_rubrique_tag_on_page(self, rubrique): rubriques = self.getElements(self.rubrique_tags, "xpath") if Menu.Le_Monde.upper() == rubrique.upper() or Menu.Societe_sa.upper( ) == rubrique: return True elif len(rubriques) > 0: for r in rubriques: if self.getElementText(element=r).upper() == rubrique.upper(): return True return False else: return False def get_rubrique_xpath(self, rubrique): if rubrique == 'PUBLIREPORTAGE': return "//div[@class='td-block-title-wrap']//child::span[contains(text(), '{}')]".format( str(rubrique).upper()) else: return "//div[@class='td-block-title-wrap']//child::a[contains(text(), '{}')]".format( str(rubrique).upper()) def get_rubrique_elements_xpath_locaor(self, rubrique): #myLocator = "//div[@id='{}']//child::div[@class='item-details']//a".format(str(rubrique_div_id)) if rubrique.upper() == 'PUBLIREPORTAGE': myLocator = "//div[@class='td-block-title-wrap']//child::span[contains(text(), '{}')]/ancestor::div[@class='td-block-title-wrap']//" \ "following-sibling::div[@class='td_block_inner']//child::h3[@class='entry-title td-module-title']//a" \ .format ( str ( rubrique ).upper () ) else: myLocator = "//div[@class='td-block-title-wrap']//child::a[contains(text(), '{}')]/ancestor::div[@class='td-block-title-wrap']//" \ "following-sibling::div[@class='td_block_inner']//child::h3[@class='entry-title td-module-title']//a"\ .format(str(rubrique).upper()) return myLocator def scroll_to_rubrique(self, rubrique, locatorType="xpath"): myLocator = self.get_rubrique_xpath(rubrique) element = self.getElement(myLocator, locatorType) self.moveToElement(element) if rubrique.upper() == "POLITIQUE" or rubrique.upper() == "ART": self.arrow_down_up(3, "down") def click_a_rubrique_element(self, rubrique, element_index_str=None): myLocator = self.get_rubrique_elements_xpath_locaor(rubrique) elements = self.getElements(myLocator=myLocator, locatorType="xpath") if element_index_str == "random": element_index = random.randint(0, int(len(elements) - 1)) element = self.getListElement(myLocator=myLocator, locatorType="xpath", elementPosition=int(element_index)) self.moveToElement(element) self.arrow_down_up(3, "UP") elif element_index_str == "last": element_index = int(len(elements) - 1) else: element_index = int(element_index_str) #if self.isVisible(element=element) is False or self.isClickable(element=element) is False: #self.arrow_down_up(3,"UP") #self.logger.warning("element was not visible i scrolled") self.clickListElement(elements=elements, elementPosition=int(element_index))
Every flow is divided to two directions, forward and backward. When a packet comes, it is judged by its header information and classified to forward packet and backward packet. When every packet belongs to this flow joined, the related statistics will be updated. """ import time from entities.BasicPacket import BasicPacket from utils.logger import MyLogger from analyzer.FlowStatistics import FlowStatistics from utils.FlowStatus import FlowStatus TIME_FORMAT = "%Y-%m-%d %H:%M:%S" logger = MyLogger('Flow') # Please don't put logger into the class class Flow(object): """ The flow entity. Attributes ---------- _forward: list of BasicPacket A list to save forward packets. _backward: list of BasicPacket A list to save backward packets. flow_id: str The flow id with format "SrcIP-SrcPort-DstIP-DstPort-Protocol"
def __init__(self, driver): self.logger = MyLogger(self.__class__.__name__).getlogger() self.driver = driver self.base = BaseApi(self.driver) self.readYaml = ReadYaml() self.mySelf = MySelf(self.driver) # 我的页面 self.userInfoPage = self.readYaml.getStream( FilePath.androidUserInfoPage) # 个人资料按钮 self.personalCenter = self.readYaml.getNode(self.userInfoPage, "personalCenter") #获取我的页面当前用户名 self.userName = self.readYaml.getNode(self.userInfoPage, 'userName') # 个人资料页面 self.personalPage = self.readYaml.getStream( FilePath.androidPersonalPage) self.updateNameButton = self.readYaml.getNode(self.personalPage, "updateNameButton") self.updateNameInputButton = self.readYaml.getNode( self.personalPage, "updateNameInputButton") self.updateNameSaveButton = self.readYaml.getNode( self.personalPage, "updateNameSaveButton") #返回 self.backButton = self.readYaml.getNode(self.personalPage, "backButton") #修改密码 self.updatePasswdButton = self.readYaml.getNode( self.personalPage, "updatePasswdButton") self.oldPasswordFild = self.readYaml.getNode(self.personalPage, "oldPasswordFild") self.newPasswordFild = self.readYaml.getNode(self.personalPage, "newPasswordFild") self.affirePasswordFild = self.readYaml.getNode( self.personalPage, "affirePasswordFild") self.savePassword = self.readYaml.getNode(self.personalPage, "savePassword") #修改学校 self.schoolButton = self.readYaml.getNode(self.personalPage, "schoolButton") self.schoolFile = self.readYaml.getNode(self.personalPage, "schoolFile") self.schoolNameText = self.readYaml.getNode(self.personalPage, "schoolNameText") #修改简介 self.updateSummaryButton = self.readYaml.getNode( self.personalPage, "updateSummaryButton") self.newSummaryFild = self.readYaml.getNode(self.personalPage, "newSummaryFild") self.newSummaryText = self.readYaml.getNode(self.personalPage, "newSummaryText") #修改工作单位 self.workButton = self.readYaml.getNode(self.personalPage, "workButton") self.workFild = self.readYaml.getNode(self.personalPage, "workFild") self.workNameText = self.readYaml.getNode(self.personalPage, "workNameText")
#!/usr/bin/env python # from appium import webdriver from utils.myconf import myconf import os, time from appium import webdriver from utils.logger import MyLogger import logging PATH = os.path.abspath(os.path.dirname(os.path.dirname(__file__))) log = MyLogger(logging.DEBUG, logging.DEBUG) def read_cofig(file, config): fileName = PATH+'\\config\\'+file+'.ini' #fileName = PATH+'/config/'+file+'.ini' if not os.path.exists(fileName): print("当前没有该文件") return cf = myconf() cf.read(fileName) item = cf.items(config) kvs = dict(item) return kvs def getDriver(desired_caps): log.info('启动端口地址------http://127.0.0.1:'+desired_caps['port']+'/wd/hub') driver = webdriver.Remote('http://127.0.0.1:'+desired_caps['port']+'/wd/hub', desired_caps) return driver def get_data(): now = time.localtime(time.time()) return time.strftime('%Y%m%d%H%M%S', now)
class JeuneAfriqueStartPageTestSteps(unittest.TestCase): driver = None myLg = MyLogger() logger = myLg.customLogger(logging.DEBUG) @classmethod def setUpClass(cls) -> None: #cls.logger = cls. if driverFactory.MyDriverFactory.getDriverManager( "CHROME") is not None: cls.driver = driverFactory.MyDriverFactory.getDriverManager( "CHROME").getDriver() cls.startPage = JeuneAfriqueStartPage(cls.driver) else: cls.logger.error("drivermanager is null") def setUp(self) -> None: pass @pytest.mark.run(order=1) def test_startjeuneAfrique(self): if self.driver is not None: self.driver.get(Pages.getPageURL("startPage")) self.startPage.accept_cookies() # sleep (3) else: self.logger.error("driver is null") @pytest.mark.run(order=2) def test_go_to_politique_page(self): try: #self.driver.implicitly_wait(15) self.startPage.go_to_rubrique("Politique") #self.driver.get ( Pages.getPageURL ( "politiquePage" ) ) self.logger.info("... going to politique page ...") self.driver.implicitly_wait(3) #sleep (3) except Exception as error: self.logger.error(error) @pytest.mark.run(order=3) def test_go_to_culture_page(self): try: self.startPage.go_to_rubrique("Culture") self.logger.info("... going to culture page ...") sleep(3) except Exception as error: self.logger.error(error) @pytest.mark.run(order=4) def test_scrolltoBottom(self): try: self.startPage.scrollDownToBottom() sleep(3) except Exception as error: self.logger.error(error) @pytest.mark.run(order=5) def test_scrolltoTop(self): try: self.startPage.scrollUpToTop() sleep(3) except Exception as error: self.logger.error(error) @pytest.mark.run(order=6) def test_go_to_societe_page(self): try: self.startPage.go_to_rubrique("Societe") self.logger.info("... going to societe page ...") sleep(3) except Exception as error: self.logger.error(error) @pytest.mark.run(order=7) def test_go_to_sport_page(self): try: self.startPage.go_to_rubrique("Sport") self.logger.info("... going to sport page ...") sleep(3) except Exception as error: self.logger.error(error) @pytest.mark.run(order=8) def test_go_to_lifestyle_page(self): try: self.startPage.go_to_rubrique("Lifestyle") self.logger.info("... going to lifestyle page ...") sleep(3) except Exception as error: self.logger.error(error) @pytest.mark.run(order=9) def test_go_to_economie_page(self): try: self.startPage.go_to_rubrique("Economie") self.logger.info("... going to economie page ...") sleep(3) except Exception as error: self.logger.error(error) # @pytest.mark.run(order=7) # def test_go_back(self): # try: # self.startPage.goBack() # self.logger.info("... going back ...") # sleep(3) # except Exception as error: # self.logger.error(error) def tearDown(self) -> None: pass @classmethod def tearDownClass(cls) -> None: if cls.driver is not None: cls.driver.quit()