def write_to_console(self, type, line, message, args): # Just return if there is no message if message == None or message == "" or self.should_message_be_logged(type) == True: return; result = StringProcessor.safeFormatter(message, args); try: # If this a write-line command if (line): print(result); else: print(result); except Exception as e: print(StringProcessor.safeFormatter("Failed to write to the console because: " + e.args))
def file_logger(self, append, logFolder, name, messageLevel): super(messageLevel) if (logFolder == None or logFolder == ""): directory = DEFAULTLOGFOLDER else: directory = logFolder if not os.path.exists(directory): pathlib.Path(directory).mkdir(parents=True, exist_ok=True) newName = make_valid_file_name(name) # if (!name.toLowerCase().endsWith(this.getExtension())): if (not name.lower().endswith(get_extension())): name += get_extension() fileName = name filePath = Path.get(directory, name).normalize().toString() messageType = messageLevel if (path.exists(filePath) and not append): try: writer = [filePath, False] writer.write("") writer.flush() except Exception as e: # Failed to write to the event log, write error to the console instead console = ConsoleLogger() console.log_message( MessageType.ERROR, StringProcessor.safeFormatter( "Failed to write to event log because: " + e.args))
def get_driver_location(driverFile, defaultHintPath, mustExist): # Get the hint path from the config hintPath = SeleniumConfig.get_driver_hint_path() # Try the hint path first if (hintPath != "" and Path.get(hintPath, driverFile).toFile().exists()): return hintPath # Try the default hint path next if (defaultHintPath != "" and Path.get(defaultHintPath, driverFile).toFile().exists()): return Path.get(defaultHintPath).toString() # Try the test location #path = Path.get(File("").getAbsolutePath()); path = os.path.abspath("") testLocation = path.getParent().toString() if (Path.get(testLocation, driverFile).toFile().exists()): return testLocation # Try resources classLoader = WebDriverFactory.__class__ url = classLoader.getResource(driverFile) if (url != ""): file = url.getPath() return file.getParent() # We didn't find the web driver so throw an error if we need to know where it is if (mustExist): raise TimeoutError( StringProcessor.safeFormatter("Unable to find driver for " + driverFile)) return ""
def get_browser_with_default_configuration(browser): size = SeleniumConfig.get_browser_size() try: if browser == BrowserType.IE: return get_internet_explorer_driver( get_default_internet_explorer_options(), size) elif browser == BrowserType.FIREFOX: return get_firefox_driver(get_default_firefox_options(), size) elif browser == BrowserType.CHROME: return get_chrome_driver(get_default_chrome_options(), size) elif browser == BrowserType.HEADLESS_CHROME: return get_headless_chrome_driver( get_default_headless_chrome_options(size)) elif browser == BrowserType.EDGE: return get_edge_driver(get_default_edge_options(), size) elif browser == BrowserType.REMOTE: return webdriver.RemoteWebDriver(SeleniumConfig.getHubUrl(), get_default_remote_options()) else: raise ArgumentError( StringProcessor.safeFormatter( "Browser type '%s' is not supported", browser)) except Exception as e: # Log that something went wrong raise Error("Your web driver may be out of date or unsupported. " + e.message)
def get_remote_options(remoteBrowser, remotePlatform, remoteBrowserVersion, remoteCapabilities): if remoteBrowser == RemoteBrowserType.IE: options = webdriver.InternetExplorerOptions() elif remoteBrowser == RemoteBrowserType.FIREFOX: options = webdriver.FirefoxOptions() elif remoteBrowser == RemoteBrowserType.CHROME: options = webdriver.ChromeOptions() elif remoteBrowser == RemoteBrowserType.EDGE: options = webdriver.EdgeOptions() elif remoteBrowser == RemoteBrowserType.SAFARI: options = webdriver.SafariOptions() else: raise Exception( StringProcessor.safeFormatter("Remote browser type " + remoteBrowser + " is not supported")) # Add a platform setting if one was provided if (remotePlatform != "" and "platform" not in remoteCapabilities): remoteCapabilities.put("platform", remotePlatform) # Add a remote browser setting if one was provided if (remotePlatform != "" and "platform" not in remoteCapabilities): remoteCapabilities.put("version", remoteBrowserVersion) # Add additional capabilities to the driver options set_driver_options(options, remoteCapabilities) return options
def get_logging_level_setting(self): loggingLevel = Config.getGeneralValue("LogLevel", "INFORMATION").toUpperCase() if loggingLevel == "VERBOSE": # Includes this and all of those below return MessageType.VERBOSE elif loggingLevel == "INFORMATION": # Includes this and all of those below return MessageType.INFORMATION elif loggingLevel == "GENERIC": # Includes this and all of those below return MessageType.GENERIC elif loggingLevel == "SUCCESS": # Includes this and all of those below return MessageType.SUCCESS elif loggingLevel == "WARNING": # Includes this and all of those below return MessageType.WARNING elif loggingLevel == "ERROR": # Includes errors only return MessageType.ERROR elif loggingLevel == "SUSPENDED": # All logging is suspended return MessageType.SUSPENDED else: raise ValueError( StringProcessor.safeFormatter( "Logging level value '{0}' is not a valid option", Config.getGeneralValue("LogLevel")))
def logVerbose(self, message, args): messages = [] messages.append(StringProcessor.safeFormatter(message, args) + os.linesep) for element in traceback.format_stack(): # If the stack trace element is from the com.magenic package (excluding this method) append the stack trace line if (element.toString().startsWith("com.magenic") and not element.contains("BaseTest.logVerbose")): messages.append(element + os.linesep) get_logger().logMessage(MessageType.VERBOSE, messages)
def getRemoteBrowserType(self, remoteBrowser): remoteBrowser = remoteBrowser.ascii_uppercase() if remoteBrowser in ["INTERNET EXPLORER", "INTERNETEXPLORER", "IE"]: return RemoteBrowserType.IE elif remoteBrowser == "FIREFOX": return RemoteBrowserType.FIREFOX elif remoteBrowser == "CHROME": return RemoteBrowserType.CHROME elif remoteBrowser == "SAFARI": return RemoteBrowserType.SAFARI elif remoteBrowser == "EDGE": return RemoteBrowserType.EDGE else: raise ArgumentError(StringProcessor.safeFormatter("Remote browser type '%s' is not supported", remoteBrowser))
def tryToLog(self, messageType, message, args): # Get the formatted message formattedMessage = StringProcessor.safeFormatter(message, args) try: # Write to the log get_logger().logMessage(messageType, formattedMessage) # If this was an error and written to a file, add it to the console output as well if messageType == MessageType.ERROR and not isinstance(get_logger(), ConsoleLogger): print(formattedMessage) except Exception as e: print(formattedMessage); print("Logging failed because: " + e.getMessage())
def get_logging_enabled_setting(self): enabledSetting = Config.getGeneralValue("Log", "NO").toUpperCase() if enabledSetting == "YES": return LoggingEnabled.YES elif enabledSetting == "ONFAIL": return LoggingEnabled.ONFAIL elif enabledSetting == "NO": return LoggingEnabled.NO else: raise ValueError( StringProcessor.safeFormatter( "Log value %s is not a valid option", Config.get_general_value("Log", "NO")))
def make_valid_file_name(name): if name == None or name == "": raise FormatError("Blank or null file name was provided") # Replace invalid characters replacedName = name try: replacedName = name.replaceAll("[^a-zA-Z0-9\\._\\- ]+", "~") except Error as e: console = ConsoleLogger() console.logMessage( MessageType.ERROR, StringProcessor.safeFormatter( "Failed to Replace Invalid Characters because: " + e.args)) return replacedName
def get_logger(self, fileName): # Disable logging means we just send any logged messages to the console if (get_logging_enabled_setting() == LoggingEnabled.NO): return ConsoleLogger() logDirectory = get_log_directory() loggingLevel = get_logging_level_setting() logType = Config.getGeneralValue("LogType", "CONSOLE").toUpperCase() if logType == "CONSOLE": return ConsoleLogger(loggingLevel) elif logType == "TXT": return FileLogger(False, logDirectory, fileName, loggingLevel) else: raise ValueError( StringProcessor.safeFormatter( "Log type %s is not a valid option", Config.get_general_value("LogType", "CONSOLE")))
def get_browser_type(self, browserName): browserName = browserName.ascii_uppercase() if browserName in ["INTERNET EXPLORER", "INTERNETEXPLORER", "IE"]: return BrowserType.IE elif browserName == "FIREFOX": return BrowserType.FIREFOX elif browserName == "CHROME": return BrowserType.CHROME elif browserName == "HEADLESSCHROME": return BrowserType.HEADLESS_CHROME elif browserName == "SAFARI": return BrowserType.SAFARI elif browserName == "EDGE": return BrowserType.EDGE elif browserName in ["PHANTOMJS", "PHANTOM JS", "PHANTOM"]: raise ArgumentError("Selenium no longer supports PhantomJS") else: raise ArgumentError(StringProcessor.safeFormatter("Remote browser type '%s' is not supported", browserName))
def FileLoggerMessagingLevelFileName(self): logger = HtmlFileLogger(MessageType.WARNING, "MessagingTypeFile.html") softAssert = SoftAssert() softAssert.assertEquals( System.getProperty("java.io.tmpdir"), logger.getDirectory(), StringProcessor.safeFormatter( "Expected Directory '%s'.", System.getProperty("java.io.tmpdir"))) softAssert.assertEquals("MessagingTypeFile.html", logger.getFileName(), "Expected correct File Name.") softAssert.assertEquals(MessageType.WARNING, logger.getMessageType(), "Expected Warning Message Type.") softAssert.assertAll() file = logger.getFilePath() file.delete()
def config(parameter_list): try: if path.exists(CONFIG_FILE): tree = et.parse(CONFIG_FILE) root = tree.getroot() for node in root: configValues.add(node) ''' builder = configs.xmlBuilder(CONFIG_FILE) configValues = builder.getConfiguration(); configValues.setSynchronizer(ReadWriteSynchronizer()) ''' except Exception as e: raise TimeoutError( StringProcessor.safeFormatter( "Exception creating the xml configuration object from the file : " + e.message))
def FileLoggerAppendFileName(self): logger = HtmlFileLogger(True, "AppendFileName") softAssert = SoftAssert() softAssert.assertEquals( System.getProperty("java.io.tmpdir"), logger.getDirectory(), StringProcessor.safeFormatter( "Expected Directory '%s'.", System.getProperty("java.io.tmpdir"))) softAssert.assertEquals("AppendFileName.html", logger.getFileName(), "Expected correct File Name.") softAssert.assertEquals(MessageType.INFORMATION, logger.getMessageType(), "Expected Information Message Type.") softAssert.assertAll() file = logger.getFilePath() file.delete()
def log_message(self, messageType, message, args): # If the message level is greater that the current log level then do not log it. if (self.should_message_be_logged(messageType)): try: ''' (FileWriter fw = new FileWriter(this.filePath, true); BufferedWriter bw = new BufferedWriter(fw); PrintWriter writer = new PrintWriter(bw)) writer.println( StringProcessor.safeFormatter("%s%s", Config.NEW_LINE, System.currentTimeMillis())); writer.print(StringProcessor.safeFormatter("%s:\t", messageType.toString())); writer.println(StringProcessor.safeFormatter(message, args)); writer.flush(); ''' except Error as e: # Failed to write to the event log, write error to the console instead console = ConsoleLogger() console.logMessage( MessageType.ERROR, StringProcessor.safeFormatter( "Failed to write to event log because: " + e.args)) console.logMessage(messageType, message, args)
def unknown_message_type_message(self, type): return StringProcessor.safeFormatter( "Unknown MessageType: %s%s%s%s", type.name(), os.linesep, "Message will be displayed with the MessageType of: ", MessageType.GENERIC.name())