def formateo_de_tiempos(objeto_json): for i in range(3): objeto_json['steps'][i]['time'] = FormatUtils.truncar_float_cadena(objeto_json['steps'][i]['time']) objeto_json['time'] = FormatUtils.truncar_float_cadena(objeto_json['time']) return objeto_json
def navegar_a_portal_principal_owa(driver: WebDriver, url: str, result_list: ValidacionResultList): resultado = ResultStep() resultado.tiempo_inicio_de_ejecucion = 0 resultado.inicializar_tiempo_de_ejecucion() try: driver.set_page_load_timeout(100) driver.get(url) resultado.mensaje_error = constantes_webdriver_actions.NAVEGAR_SITIO_MSG_INGRESO_SITIO_CON_EXITO. \ format(url) resultado.validacion_correcta = True except selExcep.TimeoutException as e: resultado.mensaje_error = constantes_webdriver_actions.NAVEGAR_SITIO_MSG_TIMEOUT_EXCEP_MSG_ERROR. \ format(url, FormatUtils.formatear_excepcion(e)) resultado.validacion_correcta = False except selExcep.WebDriverException as e: resultado.mensaje_error = constantes_webdriver_actions.NAVEGAR_SITIO_MSG_WEBDRIVER_EXCEP_MSG_ERROR. \ format(FormatUtils.formatear_excepcion(e)) resultado.validacion_correcta = False resultado.finalizar_tiempo_de_ejecucion() resultado.establecer_tiempo_de_ejecucion() result_list.result_validacion_ingreso_url = resultado return result_list
def configuracion_log(correo_por_probar): # verifica si el folder del log existe if not os.path.isdir(constantes_json.DIR_BASE_LOG): try: os.mkdir(constantes_json.DIR_BASE_LOG) except OSError as e: print('sucedio un error al crear el directorio del log {} : {}'. format(constantes_json.DIR_BASE_LOG, e)) print( 'Favor de establecer la carpeta Logs dentro del proyecto con los permisos necesarios, se procede a ' 'terminar el script') sys.exit() # se verifica si el nombre del archivo existe, en caso contrario # crea el nuevo archivo log y sale del ciclo while True: # verifica que el archivo del log exista en caso contrario lo crea FormatUtils.generar_nombre_log(correo_por_probar) if not os.path.exists(constantes_json.PATH_ABSOLUTO_LOG): try: log = open(constantes_json.PATH_ABSOLUTO_LOG, 'x') log.close() break except OSError as e: print( 'Se tiene acceso denegado para escribir el archivo {}, favor de establecer los permisos necesarios' ' en el directorio Logs'.format(e)) print( 'Favor de establecer los permisos necesarios para escribir ficheros dentro del directorio Logs. ' 'Se procede a finalizar el script') sys.exit() else: print('El log {}, ya existe, se procede a generar un nuevo log'. format(constantes_json.PATH_ABSOLUTO_LOG)) continue logging.basicConfig( level=logging.INFO, filename=constantes_json.PATH_ABSOLUTO_LOG, filemode='w+', format='%(asctime)s %(lineno)d %(name)s %(levelname)s: %(message)s', datefmt='%d-%m-%YT%H:%M:%S') logging.info('Inicializando log: {}'.format( constantes_json.PATH_ABSOLUTO_LOG)) # verifica si es necesario la depuracion del directorio en donde residen los logs FormatUtils.verificacion_depuracion_de_logs(constantes_json.DIR_BASE_LOG)
def main(): argumentos_script = sys.argv[1:] if len(argumentos_script) == 0: print( 'Favor de establecer el JSON con los argumentos necesarios para la ejecucion correcta del script' ) sys.exit(1) constantes_json.configurar_paths_constantes(__file__) archivo_config = FormatUtils.obtener_archivo_de_configuracion() # verifica que el archivo config contenga todos los parametros de configuracion correctamente if not UtilsMain.verificacion_correcta_archivo_config(archivo_config): sys.exit(1) # obtiene el primer argumento del script el cual es el objeto JSON con los datos de la cuenta Exchange por # testear argumento_cadena_json = argumentos_script[0] # verifica que la cadena sea un json valido en caso contrario se omite la experiencia de usuario argumento_cadena_json = argumento_cadena_json.strip() # verifica que la cadena del argumento sea un JSON valido if not FormatUtils.cadena_a_json_valido(argumento_cadena_json): print( 'El argumento {} no es un JSON valido, favor de verificar nuevamente el argumento.' .format(argumento_cadena_json)) sys.exit() # una vez pasando todos los filtros correctos, se obtienen del objeto JSON el correo, url y password por verificar objeto_argumento_json = json.loads(argumento_cadena_json) portal_url_exchange = objeto_argumento_json['url'] correo_exchange = objeto_argumento_json['user'] password_cuenta_exchange = objeto_argumento_json['password'] correo_por_probar = Correo(correo_exchange, password_cuenta_exchange, portal_url_exchange) # se inicializa el archivo con el log de cada paso para la prueba UtilsMain.configuracion_log(correo_por_probar.correo) salida_log_json = iniciar_prueba(correo_por_probar) print(salida_log_json) logging.info('Respuesta Log JSON: {}'.format(salida_log_json))
def iniciar_prueba(correo, url_exchange): # obtiene los datos del archivo de configuracion config_web_driver = None archivo_configuracion_ini = FormatUtils.lector_archivo_ini() driver_por_usar = FormatUtils.CADENA_VACIA ruta_driver_navegador = FormatUtils.CADENA_VACIA driver = None objeto_json = None try: # url_exchange = archivo_configuracion_ini.get('UrlPorProbar','urlPortalExchange') driver_por_usar = archivo_configuracion_ini.get( 'Driver', 'driverPorUtilizar') ruta_driver_navegador = archivo_configuracion_ini.get('Driver', 'ruta') except configparser.Error as e: logging.error( 'Sucedio un error al momento de leer el archivo de configuracion') logging.error('{}'.format(e)) sys.exit() # lista de carpetas por navegar (estos los obtenemos por medio del webdriver) carpetas_formateadas = [] # obtiene los datos necesarios desde el archivo de configuracion # establece el driver por utilizar (chrome o firefox) config_web_driver = ConfiguracionWebDriver(ruta_driver_navegador, driver_por_usar) driver = config_web_driver.configurar_obtencion_web_driver() # se generan las validaciones y el resultado por medio de un objeto JSON objeto_json = generar_test_json(driver, url_exchange, correo) # se retorna el objeto json como cadena return json.dumps(objeto_json)
def obtener_carpetas_en_sesion(driver: WebDriver): lista_de_carpetas_localizadas = [] lista_nombres_de_carpetas_formateadas = [] tiempo_de_inicio = Temporizador.obtener_tiempo_timer() tiempo_de_finalizacion = 0 se_encontraron_carpetas = False while tiempo_de_finalizacion < 60: time.sleep(10) if ValidacionesHTML.verificar_elemento_encontrado_por_clase_js( driver, constantes_webdriver_actions.OBTENER_CARPETAS_EN_SESION_CSS_CARPETA_OWA_2016): AccionesHtml.owa_descubierto = 2016 se_encontraron_carpetas = True elif ValidacionesHTML.verificar_elemento_encontrado_por_clase_js( driver, constantes_webdriver_actions.OBTENER_CARPETAS_EN_SESION_CSS_CARPETA_OWA_2013): AccionesHtml.owa_descubierto = 2013 se_encontraron_carpetas = True elif ValidacionesHTML.verificar_elemento_encontrado_por_xpath( driver, constantes_webdriver_actions.OBTENER_CARPETAS_EN_SESION_XPATH_CARPETA_OWA_2010): AccionesHtml.owa_descubierto = 2010 se_encontraron_carpetas = True tiempo_de_finalizacion = Temporizador.obtener_tiempo_timer() - tiempo_de_inicio if tiempo_de_finalizacion % 20 == 0: AccionesHtml.navegar_a_portal_principal_owa(AccionesHtml.url_owa_exchange) driver.refresh() if not se_encontraron_carpetas: tiempo_de_finalizacion = Temporizador.obtener_tiempo_timer() - tiempo_de_inicio else: time.sleep(4) if AccionesHtml.owa_descubierto == 2010: lista_de_carpetas_localizadas = driver.find_elements_by_xpath( constantes_webdriver_actions.OBTENER_CARPETAS_EN_SESION_XPATH_CARPETA_OWA_2010) elif AccionesHtml.owa_descubierto == 2013: lista_de_carpetas_localizadas = driver.execute_script(constantes_webdriver_actions. OBTENER_CARPETAS_EN_SESION_JS_OBTENER_CARPETA_2013) elif AccionesHtml.owa_descubierto == 2016: lista_de_carpetas_localizadas = driver.execute_script(constantes_webdriver_actions. OBTENER_CARPETAS_EN_SESION_JS_OBTENER_CARPETA_2016) for carpeta in lista_de_carpetas_localizadas: if AccionesHtml.owa_descubierto == 2010: nombre_de_carpeta = carpeta.text else: nombre_de_carpeta = FormatUtils.remover_backspaces(carpeta.get_attribute('innerHTML')) lista_nombres_de_carpetas_formateadas.append(nombre_de_carpeta) return lista_nombres_de_carpetas_formateadas
def inicializar_webdriver_chrome(self): archivo_config_ini = FormatUtils.obtener_archivo_de_configuracion() modo_headless = archivo_config_ini.getboolean('Driver', 'headless') mandar_log_a_dev_null = archivo_config_ini.getboolean( 'Driver', 'log_path_dev_null') opciones_chrome = webdriver.ChromeOptions() # ignora las certificaciones de seguridad, esto solamente se realiza para la experiencia de usuario opciones_chrome.add_argument('--ignore-certificate-errors') opciones_chrome.add_argument('--allow-running-insecure-content') opciones_chrome.add_argument("--enable-javascript") opciones_chrome.add_argument('window-size=1920x1080') opciones_chrome.add_argument('--no-sandbox') # establece el modo headless, esto dependiendo de la opcion que se tenga en el archivo config.ini if modo_headless: opciones_chrome.add_argument("--headless") opciones_chrome.add_experimental_option('excludeSwitches', ['enable-logging']) chrome_capabilities = webdriver.DesiredCapabilities().CHROME.copy() chrome_capabilities['acceptSslCerts'] = True chrome_capabilities['acceptInsecureCerts'] = True # establece el directorio al cual se redireccionara el log generado por el chromedriver if mandar_log_a_dev_null: param_service_log_path = constantes_json.DEV_NULL else: param_service_log_path = None try: webdriver_chrome = webdriver.Chrome( self.ruta_web_driver, chrome_options=opciones_chrome, desired_capabilities=chrome_capabilities, service_log_path=param_service_log_path) except FileNotFoundError as e: print('Sucedio un error al intentar configurar el webdriver: {}'. format(e)) sys.exit() except Exception as e: print( 'Sucedio una excepcion al intentar configurar el webdriver {}'. format(e)) sys.exit() return webdriver_chrome
def navegar_a_portal_principal_owa(web_driver: WebDriver, url: str, result_list: ValidacionResultList): resultado = ResultStep() resultado.tiempo_inicio_de_ejecucion = 0 resultado.inicializar_tiempo_de_ejecucion() segundos_por_esperar_elemento_html = 10 try: web_driver.get(url) ValidacionesHTML.verificar_ingreso_exitoso_pagina_principal( web_driver, constantes_webdriver_actions. INICIAR_SESION_EN_OWA_ID_INPUT_PASSWORD, segundos_por_esperar_elemento_html) resultado.mensaje_error = constantes_webdriver_actions.NAVEGAR_SITIO_MSG_INGRESO_SITIO_CON_EXITO. \ format(url) resultado.validacion_correcta = True except sel_excep.TimeoutException as e: resultado.mensaje_error = constantes_webdriver_actions.NAVEGAR_SITIO_MSG_TIMEOUT_EXCEP_MSG_ERROR.format( segundos_por_esperar_elemento_html, url, FormatUtils.formatear_excepcion(e)) resultado.validacion_correcta = False except sel_excep.WebDriverException as e: resultado.mensaje_error = constantes_webdriver_actions.NAVEGAR_SITIO_MSG_WEBDRIVER_EXCEP_MSG_ERROR. \ format(FormatUtils.formatear_excepcion(e)) resultado.validacion_correcta = False resultado.finalizar_tiempo_de_ejecucion() resultado.establecer_tiempo_de_ejecucion() result_list.result_validacion_ingreso_url = resultado return result_list
def inicializar_webdriver_firefox(self): archivo_config_ini = FormatUtils.obtener_archivo_de_configuracion() modo_headless = archivo_config_ini.getboolean('Driver', 'headless') mandar_log_a_dev_null = archivo_config_ini.getboolean('Driver', 'log_path_dev_null') mime_types = 'application/zip,application/octet-stream,image/jpeg,application/vnd.ms-outlook,' \ 'text/html,application/pdf' # ruta para deshabilitar log inecesario del geckodriver opciones_firefox = webdriver.FirefoxOptions() perfil_firefox = webdriver.FirefoxProfile() firefox_capabilities = webdriver.DesiredCapabilities().FIREFOX.copy() firefox_capabilities.update({'acceptInsecureCerts': True, 'acceptSslCerts': True}) firefox_capabilities['acceptSslCerts'] = True # ignora las certificaciones de seguridad, esto solamente se realiza para la experiencia de usuario opciones_firefox.add_argument('--ignore-certificate-errors') opciones_firefox.accept_insecure_certs = True perfil_firefox.accept_untrusted_certs = True perfil_firefox.assume_untrusted_cert_issuer = False perfil_firefox.set_preference("browser.download.folderList", 2) perfil_firefox.set_preference("browser.download.manager.showWhenStarting", False) perfil_firefox.set_preference("browser.helperApps.alwaysAsk.force", False) perfil_firefox.set_preference("browser.helperApps.neverAsk.saveToDisk", mime_types) opciones_firefox.headless = modo_headless if mandar_log_a_dev_null: param_log_path = constantes_json.DEV_NULL else: param_log_path = None try: webdriver_firefox = webdriver.Firefox(executable_path=self.ruta_web_driver, firefox_options=opciones_firefox, firefox_profile=perfil_firefox, capabilities=firefox_capabilities, log_path=param_log_path) except FileNotFoundError as e: print('Sucedio un error al intentar configurar el webdriver: {}'.format(e)) sys.exit() except Exception as e: print('Sucedio una excepcion al intentar configurar el webdriver {}'.format(e)) sys.exit() return webdriver_firefox
def iniciar_prueba(correo): # obtiene los datos del archivo de configuracion archivo_configuracion = FormatUtils.obtener_archivo_de_configuracion() web_driver_por_utilizar = archivo_configuracion.get( 'Driver', 'driverPorUtilizar') path_web_driver = archivo_configuracion.get('Driver', 'ruta') # establece el driver por utilizar (chrome o firefox) config_web_driver = ConfiguracionWebDriver(path_web_driver, web_driver_por_utilizar) driver = config_web_driver.configurar_obtencion_web_driver() # se generan las validaciones y el resultado por medio de un objeto JSON objeto_json = generar_test_json(driver, correo.url, correo) # se retorna el objeto json como cadena return json.dumps(objeto_json)
def main(): args = sys.argv[1:] cadena_json = args[0] response = FormatUtils.CADENA_VACIA correo_a_probar = None constantes_json.configurar_paths_constantes(__file__) # verifica que la cadena sea un json valido en caso contrario # se omite la experiencia de usuario cadena_json = cadena_json.strip() if FormatUtils.cadena_a_json_valido(cadena_json): objeto_json = json.loads(cadena_json) url_exchange = objeto_json['url'] usuario = objeto_json['user'] password = objeto_json['password'] configuracion_log(usuario) correo_a_probar = Correo(usuario, password, url_exchange) logging.info('"{}" - JSON valido'.format(cadena_json)) response = iniciar_prueba(correo_a_probar, correo_a_probar.url) else: configuracion_log(constantes_json.JSON_INVALIDO) logging.error('"{}" - JSON invalido, se omite exp. de usuario'.format( cadena_json)) print('"{}" - JSON invalido, se omite exp. de usuario'.format( cadena_json)) response = '"{}" - JSON invalido, se omite exp. de usuario'.format( cadena_json) logging.info('Response generado: {}'.format(response)) print(response)
def iniciar_sesion_en_owa(webdriver: WebDriver, correo: Correo, result_list: ValidacionResultList): EvaluacionesHtml.cuenta_sin_dominio = FormatUtils.formatear_correo( correo.correo) EvaluacionesHtml.url_owa_exchange = correo.url resultado = ResultStep() resultado.tiempo_inicio_de_ejecucion = Temporizador.obtener_tiempo_timer( ) resultado.datetime_inicial = Temporizador.obtener_fecha_tiempo_actual() # verifica que haya ingresado correctamente a la url if not result_list.result_validacion_ingreso_url.validacion_correcta: resultado.validacion_correcta = False resultado.mensaje_error = 'No fue posible el inicio de sesion dentro de la plataforma Exchange. ' \ 'No se ingreso correctamente a la pagina principal de la plataforma' resultado.finalizar_tiempo_de_ejecucion() resultado.establecer_tiempo_de_ejecucion() result_list.result_validacion_acceso_portal_owa = resultado return result_list try: input_usuario = BusquedaElementosHtml.buscar_elemento_por_id_timeout( webdriver, constantes_webdriver_actions. INICIAR_SESION_EN_OWA_ID_INPUT_USER, 7) input_usuario.send_keys(correo.correo) input_password = BusquedaElementosHtml.buscar_elemento_por_id_timeout( webdriver, constantes_webdriver_actions. INICIAR_SESION_EN_OWA_ID_INPUT_PASSWORD, 7) input_password.send_keys(correo.password) boton_ingreso_correo = None if ValidacionesHTML.verificar_elemento_encontrado_por_id( webdriver, constantes_webdriver_actions. INICIAR_SESION_EN_OWA_ID_CHECKBOX_PORTAL_LIGHTWEIGHT_OWA_2010 ): check_casilla_owa_2010_version_ligera = BusquedaElementosHtml.buscar_elemento_por_id_timeout( webdriver, constantes_webdriver_actions. INICIAR_SESION_EN_OWA_ID_CHECKBOX_PORTAL_LIGHTWEIGHT_OWA_2010, 7) check_casilla_owa_2010_version_ligera.click() constantes_utils.owa_descubierto = 2010 if ValidacionesHTML.verificar_elemento_encontrado_por_xpath( webdriver, constantes_webdriver_actions. INICIAR_SESION_EN_OWA_XPATH_BTN_OWA_2010): boton_ingreso_correo = BusquedaElementosHtml.buscar_elemento_por_xpath_timeout( webdriver, constantes_webdriver_actions. INICIAR_SESION_EN_OWA_XPATH_BTN_OWA_2010, 7) constantes_utils.owa_descubierto = 2010 elif ValidacionesHTML.verificar_elemento_encontrado_por_xpath( webdriver, constantes_webdriver_actions. INICIAR_SESION_EN_OWA_XPATH_BTN_OWA_2013_2016): boton_ingreso_correo = BusquedaElementosHtml.buscar_elemento_por_xpath_timeout( webdriver, constantes_webdriver_actions. INICIAR_SESION_EN_OWA_XPATH_BTN_OWA_2013_2016, 7) constantes_utils.owa_descubierto = 2016 boton_ingreso_correo.click() except sel_excep.NoSuchElementException as e: resultado.mensaje_error = constantes_webdriver_actions.INICIAR_SESION_MSG_NOSUCHELEM_EXCEP_MSG_ERROR. \ format(FormatUtils.formatear_excepcion(e)) resultado.validacion_correcta = False except sel_excep.TimeoutException as e: resultado.mensaje_error = constantes_webdriver_actions.INICIAR_SESION_MSG_NOSUCHELEM_EXCEP_MSG_ERROR. \ format(FormatUtils.formatear_excepcion(e)) resultado.validacion_correcta = False except sel_excep.WebDriverException as e: resultado.mensaje_error = constantes_webdriver_actions.INICIAR_SESION_MSG_WEBDRIVER_EXCEP_MSG_ERROR. \ format(FormatUtils.formatear_excepcion(e)) resultado.validacion_correcta = False if not resultado.validacion_correcta: try: if constantes_utils.owa_descubierto == 2010: mensaje_error_de_credenciales = webdriver.find_element_by_xpath( constantes_webdriver_actions. INICIAR_SESION_EN_OWA_XPATH_ERROR_CREDENCIALES_OWA_2010 ) texto_mensaje_error = mensaje_error_de_credenciales.get_attribute( 'innerHTML') resultado.msg_error_de_credenciales = texto_mensaje_error resultado.mensaje_error = constantes_webdriver_actions. \ INICIAR_SESION_LOG_MSG_ERROR_CREDENCIALES_OWA.format(texto_mensaje_error) resultado.validacion_correcta = False resultado.error_inicio_de_sesion_credenciales_erroneas = True elif constantes_utils.owa_descubierto == 2016 or constantes_utils.owa_descubierto == 2013: mensaje_error_de_credenciales = webdriver.execute_script( constantes_webdriver_actions. INICIAR_SESION_JS_LOCATE_ID_MSG_ERROR_CREDENCIALES_OWA_2016_2013 ) resultado.mensaje_error = constantes_webdriver_actions. \ INICIAR_SESION_LOG_MSG_ERROR_CREDENCIALES_OWA.format(mensaje_error_de_credenciales) resultado.msg_error_de_credenciales = mensaje_error_de_credenciales resultado.validacion_correcta = False resultado.error_inicio_de_sesion_credenciales_erroneas = True except sel_excep.NoSuchElementException: resultado.mensaje_error = constantes_json.OUTPUT_EXITOSO_1_1 resultado.validacion_correcta = True except sel_excep.InvalidSessionIdException as e: resultado.mensaje_error = constantes_webdriver_actions. \ INICIAR_SESION_CREDENCIALES_INVALIDSESION_ID_EXCEP_MSG_ERROR.format(e) resultado.validacion_correcta = False except sel_excep.JavascriptException: # Se ingresa correctamente, debido a que no se encontro el mensaje de error de credenciales incorrectas resultado.mensaje_error = constantes_json.OUTPUT_EXITOSO_1_1 resultado.validacion_correcta = True except sel_excep.WebDriverException: # Se ingresa correctamente, debido a que no se encontro el mensaje de error de credenciales incorrectas resultado.mensaje_error = constantes_json.OUTPUT_EXITOSO_1_1 resultado.validacion_correcta = True # realiza la validacion de ingreso correcto de sesion se verifica que no haya algun error que se presente en la # plataforma en caso contrario se obtiene el mensaje del error y se establecer en el objeto resultado if ValidacionesHTML.verificar_error_plataforma(webdriver): msg_error = ValidacionesHTML.obtener_mensaje_error_plataforma( webdriver) resultado.mensaje_error = constantes_webdriver_actions.INICIAR_SESION_MSG_ERROR_EN_PLATAFORMA. \ format(msg_error) resultado.validacion_correcta = False resultado.error_plataforma_inicio_de_sesion = True resultado.finalizar_tiempo_de_ejecucion() resultado.establecer_tiempo_de_ejecucion() result_list.result_validacion_acceso_portal_owa = resultado return result_list
def cerrar_sesion(webdriver: WebDriver, result_list: ValidacionResultList, correo: Correo): resultado_cierre_sesion = ResultStep() resultado_cierre_sesion.inicializar_tiempo_de_ejecucion() cierre_sesion_exitosa = False # verifica si se tiene error de credenciales, por lo cual si se tiene este error, se establece el mensaje # de error y envia el result como finalizado, esto debido a que no puede localizar el boton de cierre de # sesion sin antes haberse loggeado dentro de la plataforma if result_list.result_validacion_acceso_portal_owa.error_inicio_de_sesion_credenciales_erroneas: resultado_cierre_sesion.finalizar_tiempo_de_ejecucion() resultado_cierre_sesion.establecer_tiempo_de_ejecucion() resultado_cierre_sesion.validacion_correcta = False resultado_cierre_sesion.mensaje_error = constantes_webdriver_actions. \ CERRAR_SESION_MSG_ERROR_CREDENCIALES_OWA.format(result_list.result_validacion_acceso_portal_owa. msg_error_de_credenciales) result_list.result_validacion_cierre_sesion = resultado_cierre_sesion return result_list # verifica si hay error en plataforma, en caso de ser asi, intenta realizar n intentos para volver a loggearse # y verificar si ingreso correctamente al buzon de entrada para navegar entre las carpetas if ValidacionesHTML.verificar_error_plataforma(webdriver): resultado_cierre_sesion = ValidacionesHTML.intento_ingreso_nuevamente_al_portal( resultado_cierre_sesion, correo, webdriver, step_evaluacion='cierre de sesion') try: if constantes_utils.owa_descubierto == 2013 or constantes_utils.owa_descubierto == 2016: btn_perfil_usuario = BusquedaElementosHtml.localizar_boton_perfil_usuario( webdriver) btn_perfil_usuario.click() btn_cierre_de_sesion = BusquedaElementosHtml.localizar_boton_cierre_sesion_owa_2013_2016( webdriver) btn_cierre_de_sesion.click() elif constantes_utils.owa_descubierto == 2010: enlace_cierre_sesion = BusquedaElementosHtml.localizar_enlace_cierre_sesion_owa_2010( webdriver) enlace_cierre_sesion.click() webdriver.get(correo.url) ValidacionesHTML.verificar_ingreso_exitoso_pagina_principal( webdriver, constantes_webdriver_actions. INICIAR_SESION_EN_OWA_ID_INPUT_PASSWORD, 10) cierre_sesion_exitosa = True except sel_excep.NoSuchElementException as e: resultado_cierre_sesion.mensaje_error = constantes_webdriver_actions. \ CERRAR_SESION_LOG_ERROR_NO_SUCH_ELEM_EXCEP.format(FormatUtils.formatear_excepcion(e)) resultado_cierre_sesion.validacion_correcta = False except sel_excep.ElementClickInterceptedException: webdriver.refresh() EvaluacionesHtml.cerrar_sesion(webdriver, result_list, correo) except sel_excep.TimeoutException as e: resultado_cierre_sesion.mensaje_error = constantes_webdriver_actions. \ CERRAR_SESION_LOG_ERROR_TIMEOUT_EXCEP.format(FormatUtils.formatear_excepcion(e)) resultado_cierre_sesion.validacion_correcta = False except sel_excep.WebDriverException as e: resultado_cierre_sesion.mensaje_error = constantes_webdriver_actions. \ CERRAR_SESION_LOG_ERROR_WEBDRIVER_EXCEP.format(FormatUtils.formatear_excepcion(e)) resultado_cierre_sesion.validacion_correcta = False except AttributeError: resultado_cierre_sesion.mensaje_error = constantes_webdriver_actions. \ CERRAR_SESION_LOG_ERROR_ATRIBUTE_ERROR_EXCEP resultado_cierre_sesion.validacion_correcta = False finally: # verifica que no haya algun mensaje de error en la plataforma, en caso contrario se muestra el mensaje de # error que aparace en la plataforma dentro del result if ValidacionesHTML.verificar_error_plataforma(webdriver): resultado_cierre_sesion.validacion_correcta = False msg_error = ValidacionesHTML.obtener_mensaje_error_plataforma( webdriver) resultado_cierre_sesion.mensaje_error = constantes_webdriver_actions.CERRAR_SESION_ERROR_PLATAFORMA. \ format(msg_error) cierre_sesion_exitosa = False if cierre_sesion_exitosa: resultado_cierre_sesion.mensaje_error = constantes_json.OUTPUT_EXITOSO_3_1 resultado_cierre_sesion.validacion_correcta = True resultado_cierre_sesion.finalizar_tiempo_de_ejecucion() resultado_cierre_sesion.establecer_tiempo_de_ejecucion() result_list.result_validacion_cierre_sesion = resultado_cierre_sesion return result_list
def cerrar_sesion(webdriver: WebDriver, result_list: ValidacionResultList, correo: Correo): timeout_cierre_sesion = 10 resultado_cierre_sesion = ResultStep() resultado_cierre_sesion.inicializar_tiempo_de_ejecucion() cierre_sesion_exitosa = False # verifica si se tiene error de credenciales, por lo cual si se tiene este error, se establece el mensaje # de error y envia el result como finalizado, esto debido a que no puede localizar el boton de cierre de # sesion sin antes haberse loggeado dentro de la plataforma if result_list.result_validacion_acceso_portal_owa.error_inicio_de_sesion_credenciales_erroneas: resultado_cierre_sesion.finalizar_tiempo_de_ejecucion() resultado_cierre_sesion.establecer_tiempo_de_ejecucion() resultado_cierre_sesion.validacion_correcta = False resultado_cierre_sesion.mensaje_error = constantes_webdriver_actions.\ CERRAR_SESION_MSG_ERROR_CREDENCIALES_OWA.format(result_list.result_validacion_acceso_portal_owa. msg_error_de_credenciales) result_list.result_validacion_cierre_sesion = resultado_cierre_sesion AccionesHtml.log.error(constantes_webdriver_actions.CERRAR_SESION_MSG_ERROR_CREDENCIALES_OWA.format( result_list.result_validacion_acceso_portal_owa.msg_error_de_credenciales)) webdriver.close() webdriver.quit() return result_list # verifica si hay error en plataforma, en caso de ser asi, intenta realizar n intentos para volver a loggearse # y verificar si ingreso correctamente al buzon de entrada para navegar entre las carpetas if ValidacionesHTML.verificar_error_plataforma(webdriver): resultado_cierre_sesion = ValidacionesHTML.intento_ingreso_nuevamente_al_portal( resultado_cierre_sesion, correo, webdriver, step_evaluacion='cierre de sesion') try: webdriver.refresh() time.sleep(5) # verifica que no haya algun dialogo que impida el cierre de sesion ValidacionesHTML.verificar_dialogo_de_interrupcion( webdriver, resultado_cierre_sesion) # intenta salir de la sesion ejecutando un script js el cual simula un clic en el boton de cierre de sesion if AccionesHtml.owa_descubierto == 2010: time.sleep(4) elemento_html_btn_cerrar_sesion = webdriver.find_element_by_id( constantes_webdriver_actions.CERRAR_SESION_CIERRE_SESION_ID_BTN_CIERRE_SESION_OWA_2010) time.sleep(4) elemento_html_btn_cerrar_sesion.click() time.sleep(4) elif AccionesHtml.owa_descubierto == 2016: time.sleep(4) boton_cierre_sesion_owa_2016 = webdriver.execute_script( constantes_webdriver_actions.JS_LOCATE_DIV_CONTENT_BTN_CIERRE_SESION_OWA_2016) time.sleep(4) boton_cierre_sesion_owa_2016.click() time.sleep(8) boton_cierre_sesion_owa_2016 = webdriver.execute_script( constantes_webdriver_actions.JS_LOCATE_BTN_CIERRE_SESION_OWA_2016) boton_cierre_sesion_owa_2016.click() elif AccionesHtml.owa_descubierto == 2013: boton_cierre_sesion_owa_2013 = webdriver.execute_script( constantes_webdriver_actions.JS_LOCATE_DIV_CONTENT_BTN_CIERRE_SESION_OWA_2013) boton_cierre_sesion_owa_2013.click() time.sleep(8) boton_cierre_sesion_owa_2013 = webdriver.execute_script( constantes_webdriver_actions.JS_LOCATE_BTN_CIERRE_SESION_OWA_2013_SPANISH) if boton_cierre_sesion_owa_2013 is None: AccionesHtml.log.error(constantes_webdriver_actions.CERRAR_SESION_LOG_ERROR_BTN_CIERRE_SIGN_OUT) boton_cierre_sesion_owa_2013 = webdriver.execute_script( constantes_webdriver_actions.JS_LOCATE_BTN_CIERRE_SESION_OWA_2013_ENGLISH) boton_cierre_sesion_owa_2013.click() # obtiene la url actual como una cadena time.sleep(2) AccionesHtml.log.info(constantes_webdriver_actions.CERRAR_SESION_LOG_INFO_CIERRE_SESION_TITLE_URL .format(webdriver.title, webdriver.current_url)) webdriver.refresh() time.sleep(2) # verifica que nos encontremos en la pagina de cierre de sesion del OWA verifica que el title de la pagina # contenfa Outlook condicion_contenido_en_title = EC.title_contains(constantes_webdriver_actions. CERRAR_SESION_TITLE_CIERRE_SESION) WebDriverWait(webdriver, timeout_cierre_sesion).until(condicion_contenido_en_title) cierre_sesion_exitosa = True except selExcep.NoSuchElementException as e: AccionesHtml.log.error(constantes_webdriver_actions.CERRAR_SESION_LOG_ERROR_NO_SUCH_ELEM_EXCEP.format( FormatUtils.formatear_excepcion(e))) resultado_cierre_sesion.mensaje_error = constantes_webdriver_actions. \ CERRAR_SESION_LOG_ERROR_NO_SUCH_ELEM_EXCEP.format(FormatUtils.formatear_excepcion(e)) resultado_cierre_sesion.validacion_correcta = False except selExcep.ElementClickInterceptedException as e: AccionesHtml.log.error(constantes_webdriver_actions.CERRAR_SESION_LOG_ERROR_ELEM_INTERCEP_EXCEP.format( FormatUtils.formatear_excepcion(e))) webdriver.refresh() time.sleep(2) AccionesHtml.cerrar_sesion(webdriver, result_list, correo) except selExcep.TimeoutException as e: AccionesHtml.log.error(constantes_webdriver_actions.CERRAR_SESION_LOG_ERROR_TIMEOUT_EXCEP.format( FormatUtils.formatear_excepcion(e))) resultado_cierre_sesion.mensaje_error = constantes_webdriver_actions. \ CERRAR_SESION_LOG_ERROR_TIMEOUT_EXCEP.format(FormatUtils.formatear_excepcion(e)) resultado_cierre_sesion.validacion_correcta = False except selExcep.WebDriverException as e: AccionesHtml.log.error(constantes_webdriver_actions.CERRAR_SESION_LOG_ERROR_WEBDRIVER_EXCEP .format(FormatUtils.formatear_excepcion(e))) resultado_cierre_sesion.mensaje_error = constantes_webdriver_actions. \ CERRAR_SESION_LOG_ERROR_WEBDRIVER_EXCEP.format(FormatUtils.formatear_excepcion(e)) resultado_cierre_sesion.validacion_correcta = False except AttributeError: AccionesHtml.log.error(constantes_webdriver_actions.CERRAR_SESION_LOG_ERROR_ATRIBUTE_ERROR_EXCEP) resultado_cierre_sesion.mensaje_error = constantes_webdriver_actions. \ CERRAR_SESION_LOG_ERROR_ATRIBUTE_ERROR_EXCEP resultado_cierre_sesion.validacion_correcta = False finally: # verifica que no haya algun mensaje de error en la plataforma, en caso contrario se muestra el mensaje de # error que aparace en la plataforma dentro del result if ValidacionesHTML.verificar_error_plataforma(webdriver): resultado_cierre_sesion.validacion_correcta = False msg_error = ValidacionesHTML.obtener_mensaje_error_plataforma(webdriver) resultado_cierre_sesion.mensaje_error = constantes_webdriver_actions.CERRAR_SESION_ERROR_PLATAFORMA. \ format(msg_error) cierre_sesion_exitosa = False AccionesHtml.log.info(constantes_webdriver_actions.CERRAR_SESION_LOG_INFO_CIERRE_WEB_DRIVER) webdriver.close() webdriver.quit() if cierre_sesion_exitosa: AccionesHtml.log.info(constantes_webdriver_actions.CERRAR_SESION_LOG_INFO_CIERRE_SESION_EXITOSA) resultado_cierre_sesion.mensaje_error = constantes_json.OUTPUT_EXITOSO_3_1 resultado_cierre_sesion.validacion_correcta = True resultado_cierre_sesion.finalizar_tiempo_de_ejecucion() resultado_cierre_sesion.establecer_tiempo_de_ejecucion() result_list.result_validacion_cierre_sesion = resultado_cierre_sesion return result_list
def navegacion_de_carpetas_por_segundos(correo: Correo, lista_carpetas: list, driver: WebDriver, result_list: ValidacionResultList, numero_de_segundos: int = 120): result_navegacion_carpetas = ResultStep() result_navegacion_carpetas.inicializar_tiempo_de_ejecucion() tiempo_por_verificar = numero_de_segundos + Temporizador.obtener_tiempo_timer() tiempo_de_inicio = Temporizador.obtener_tiempo_timer() segundos = 0 # verifica si se tiene error de credenciales, por lo cual si se tiene este error, se establece el mensaje # de error y envia el result como finalizado, esto debido a que no se podra navegar entre carpetas por no # estar loggeado y sin tener acceso al buzon de la plataforma if result_list.result_validacion_acceso_portal_owa.error_inicio_de_sesion_credenciales_erroneas: result_navegacion_carpetas.finalizar_tiempo_de_ejecucion() result_navegacion_carpetas.establecer_tiempo_de_ejecucion() result_navegacion_carpetas.validacion_correcta = False result_navegacion_carpetas.mensaje_error = constantes_webdriver_actions.\ NAVEGACION_CARPETAS_SEG_MSG_ERROR_CREDENCIALES_OWA.format( result_list.result_validacion_acceso_portal_owa.msg_error_de_credenciales) result_list.result_validacion_navegacion_carpetas = result_navegacion_carpetas AccionesHtml.log.error(constantes_webdriver_actions.NAVEGACION_CARPETAS_SEG_MSG_ERROR_CREDENCIALES_OWA. format(result_list.result_validacion_acceso_portal_owa.msg_error_de_credenciales)) return result_list # verifica si hay error en plataforma, en caso de ser asi, intenta realizar n intentos para volver a loggearse # y verificar si ingreso correctamente al buzon de entrada para navegar entre las carpetas if ValidacionesHTML.verificar_error_plataforma(driver): result_navegacion_carpetas = ValidacionesHTML.intento_ingreso_nuevamente_al_portal( result_navegacion_carpetas, correo, driver, step_evaluacion='Navegacion carpetas y buzon de entrada') # verifica si aun se sigue mostrando el mensaje de error en la plataforma, en caso contrario la prueba falla # y notificaria al cliente de presentar un error de plataforma if ValidacionesHTML.verificar_error_plataforma(driver): result_navegacion_carpetas.finalizar_tiempo_de_ejecucion() result_navegacion_carpetas.establecer_tiempo_de_ejecucion() result_navegacion_carpetas.validacion_correcta = False msg_error = ValidacionesHTML.obtener_mensaje_error_plataforma(driver) result_navegacion_carpetas.mensaje_error = constantes_webdriver_actions. \ NAVEGACION_CARPETAS_SEG_MSG_ERROR_PLATAFORMA_OWA.format(msg_error) result_list.result_validacion_navegacion_carpetas = result_navegacion_carpetas return result_list elif len(lista_carpetas) == 0: result_navegacion_carpetas.finalizar_tiempo_de_ejecucion() result_navegacion_carpetas.establecer_tiempo_de_ejecucion() result_navegacion_carpetas.validacion_correcta = False result_navegacion_carpetas.mensaje_error = constantes_webdriver_actions. \ NAVEGACION_CARPETAS_SEG_LOG_ERROR_LISTA_CARPETAS_VACIA result_list.result_validacion_navegacion_carpetas = result_navegacion_carpetas AccionesHtml.log.error(constantes_webdriver_actions.NAVEGACION_CARPETAS_SEG_LOG_ERROR_LISTA_CARPETAS_VACIA) return result_list while Temporizador.obtener_tiempo_timer() <= tiempo_por_verificar: for carpeta in lista_carpetas: segundos = Temporizador.obtener_tiempo_timer() - tiempo_de_inicio if segundos > numero_de_segundos: AccionesHtml.log.info(constantes_webdriver_actions. NAVEGACION_CARPETAS_SEG_LOG_INFO_NAVEGACION_CARPETAS_FINALIZADA) break AccionesHtml.log.info(constantes_webdriver_actions.NAVEGACION_CARPETAS_SEG_LOG_INFO_INGRESO_CARPETA. format(carpeta)) try: if AccionesHtml.owa_descubierto == 2016: elemento_html_carpeta = driver.execute_script(constantes_webdriver_actions. NAVEGACION_CARPETAS_SEG_JS_LOCALIZAR_CARPETA_OWA_2016.format( carpeta)) elemento_html_carpeta.click() time.sleep(6) elif AccionesHtml.owa_descubierto == 2010: elemento_html_carpeta = driver.find_element_by_xpath(constantes_webdriver_actions. NAVEGACION_CARPETAS_SEG_XPATH_CARPETA_OWA_2010.format( carpeta)) time.sleep(3) ValidacionesHTML.verificar_dialogo_de_interrupcion(driver, result_navegacion_carpetas) time.sleep(3) elemento_html_carpeta.click() elif AccionesHtml.owa_descubierto == 2013: elemento_html_carpeta = driver.execute_script(constantes_webdriver_actions. NAVEGACION_CARPETAS_SEG_JS_LOCALIZAR_CARPETA_OWA_2013.format( carpeta)) elemento_html_carpeta.click() time.sleep(6) except selExcep.StaleElementReferenceException as e: AccionesHtml.log.error( constantes_webdriver_actions.NAVEGACION_CARPETAS_SEG_LOG_ERROR_STA_ELEM_REF_EXCEP .format(FormatUtils.formatear_excepcion(e))) driver.refresh() time.sleep(3) except selExcep.ElementClickInterceptedException as e: AccionesHtml.log.error(constantes_webdriver_actions. NAVEGACION_CARPETAS_SEG_LOG_ERROR_ELEM_CLICK_INTERCEP_EXCEP.format( FormatUtils.formatear_excepcion(e))) driver.refresh() time.sleep(3) except selExcep.NoSuchElementException as e: AccionesHtml.log.error( constantes_webdriver_actions.NAVEGACION_CARPETAS_SEG_LOG_ERROR_NO_SUCH_ELEM_EXCEP.format( FormatUtils.formatear_excepcion(e))) driver.refresh() time.sleep(3) except selExcep.TimeoutException as e: AccionesHtml.log.error(constantes_webdriver_actions.NAVEGACION_CARPETAS_SEG_LOG_ERROR_TIMEOUT_EXCEP. format(FormatUtils.formatear_excepcion(e))) driver.refresh() time.sleep(3) except selExcep.WebDriverException as e: AccionesHtml.log.error( constantes_webdriver_actions.NAVEGACION_CARPETAS_SEG_LOG_ERROR_WEBDRIVER_EXCEP.format( FormatUtils.formatear_excepcion(e))) time.sleep(3) result_navegacion_carpetas.finalizar_tiempo_de_ejecucion() result_navegacion_carpetas.establecer_tiempo_de_ejecucion() # verifica que no haya algun mensaje de error en la plataforma, en caso contrario se muestra el mensaje de # error que aparace en la plataforma dentro del result if ValidacionesHTML.verificar_error_plataforma(driver): msg_error = ValidacionesHTML.obtener_mensaje_error_plataforma(driver) result_navegacion_carpetas.validacion_correcta = False result_navegacion_carpetas.mensaje_error = constantes_webdriver_actions. \ NAVEGACION_CARPETAS_SEG_MSG_ERROR_PLATAFORMA_OWA.format(msg_error) else: result_navegacion_carpetas.validacion_correcta = True result_navegacion_carpetas.mensaje_error = constantes_json.OUTPUT_EXITOSO_2_1 result_list.result_validacion_navegacion_carpetas = result_navegacion_carpetas return result_list
def obtener_carpetas_en_sesion(driver: WebDriver): lista_de_carpetas_localizadas = [] lista_nombres_de_carpetas_formateadas = [] tiempo_de_inicio = Temporizador.obtener_tiempo_timer() tiempo_de_finalizacion = 0 se_encontraron_carpetas = False while tiempo_de_finalizacion < 60: time.sleep(10) if ValidacionesHTML.verificar_elemento_encontrado_por_clase_js( driver, constantes_webdriver_actions.OBTENER_CARPETAS_EN_SESION_CSS_CARPETA_OWA_2016): AccionesHtml.owa_descubierto = 2016 se_encontraron_carpetas = True elif ValidacionesHTML.verificar_elemento_encontrado_por_clase_js( driver, constantes_webdriver_actions.OBTENER_CARPETAS_EN_SESION_CSS_CARPETA_OWA_2013): AccionesHtml.owa_descubierto = 2013 se_encontraron_carpetas = True elif ValidacionesHTML.verificar_elemento_encontrado_por_xpath( driver, constantes_webdriver_actions.OBTENER_CARPETAS_EN_SESION_XPATH_CARPETA_OWA_2010): AccionesHtml.owa_descubierto = 2010 se_encontraron_carpetas = True tiempo_de_finalizacion = Temporizador.obtener_tiempo_timer() - tiempo_de_inicio if tiempo_de_finalizacion % 20 == 0: AccionesHtml.navegar_a_portal_principal_owa(AccionesHtml.url_owa_exchange) driver.refresh() if se_encontraron_carpetas: AccionesHtml.log.info(constantes_webdriver_actions. OBTENER_CARPETAS_EN_SESION_LOG_INFO_LOCALIZACION_EXITOSA_CARPETAS.format( FormatUtils. truncar_float_cadena(tiempo_de_finalizacion))) break else: AccionesHtml.log.error(constantes_webdriver_actions. OBTENER_CARPETAS_EN_SESION_LOG_ERROR_LOCALIZACION_SIN_EXITO_CARPETAS) AccionesHtml.log.info(constantes_webdriver_actions.OBTENER_CARPETAS_EN_SESION_MOSTRAR_TITLE_AND_URL .format(driver.title, driver.current_url)) if not se_encontraron_carpetas: tiempo_de_finalizacion = Temporizador.obtener_tiempo_timer() - tiempo_de_inicio AccionesHtml.log.error(constantes_webdriver_actions. OBTENER_CARPETAS_EN_SESION_LOG_ERROR_LOCALIZACION_SIN_EXITO_CARPETAS_EXCESO_TIEMPO.format( FormatUtils.truncar_float_cadena(tiempo_de_finalizacion))) AccionesHtml.log.info(constantes_webdriver_actions.OBTENER_CARPETAS_EN_SESION_MOSTRAR_TITLE_AND_URL .format(driver.title, driver.current_url)) else: AccionesHtml.log.info(constantes_webdriver_actions.OBTENER_CARPETAS_EN_SESION_OWA_LOCALIZADO.format( AccionesHtml.owa_descubierto)) time.sleep(4) if AccionesHtml.owa_descubierto == 2010: lista_de_carpetas_localizadas = driver.find_elements_by_xpath( constantes_webdriver_actions.OBTENER_CARPETAS_EN_SESION_XPATH_CARPETA_OWA_2010) elif AccionesHtml.owa_descubierto == 2013: lista_de_carpetas_localizadas = driver.execute_script(constantes_webdriver_actions. OBTENER_CARPETAS_EN_SESION_JS_OBTENER_CARPETA_2013) elif AccionesHtml.owa_descubierto == 2016: lista_de_carpetas_localizadas = driver.execute_script(constantes_webdriver_actions. OBTENER_CARPETAS_EN_SESION_JS_OBTENER_CARPETA_2016) for carpeta in lista_de_carpetas_localizadas: if AccionesHtml.owa_descubierto == 2010: nombre_de_carpeta = carpeta.text else: nombre_de_carpeta = FormatUtils.remover_backspaces(carpeta.get_attribute('innerHTML')) AccionesHtml.log.info(constantes_webdriver_actions.OBTENER_CARPETAS_EN_SESION_OWA_CARPETA_OBTENIDA. format(nombre_de_carpeta)) lista_nombres_de_carpetas_formateadas.append(nombre_de_carpeta) return lista_nombres_de_carpetas_formateadas