def leftEqual(left, right, visitedIdInstances, muteLogs=True) : if ObjectHelper.isNone(left) or ObjectHelper.isNone(right) : return left is None and right is None isEqual = True leftIsCollection = ObjectHelper.isCollection(left) rightIsCollection = ObjectHelper.isCollection(right) if leftIsCollection and rightIsCollection : if len(left) == len(right) : for itemLeft, itemRight in zip(left, right) : if isEqual : isEqual = isEqual and ObjectHelper.equals(itemLeft, itemRight, visitedIdInstances=visitedIdInstances, muteLogs=muteLogs) else : break return isEqual else : return False elif (leftIsCollection and not rightIsCollection) or (not leftIsCollection and rightIsCollection) : return False else : attrinuteDataList = ReflectionHelper.getAttributeDataList(left) if not muteLogs : LogHelper.prettyPython(leftEqual, f'{left} data list', attrinuteDataList, logLevel=LogHelper.DEBUG, condition=not muteLogs) if 0 == len(attrinuteDataList) : return False for value, name in attrinuteDataList : if isEqual : isEqual = isEqual and ObjectHelper.equals(value, ReflectionHelper.getAttributeOrMethod(right, name), visitedIdInstances=visitedIdInstances, muteLogs=muteLogs) else : break return isEqual
def recoverEnvironmentVariables(environmentVariables, originalEnvironmentVariables, originalActiveEnvironment): global ACTIVE_ENVIRONMENT_VALUE EnvironmentHelper.reset(environmentVariables, originalEnvironmentVariables) LogHelper.loadSettings() ACTIVE_ENVIRONMENT_VALUE = originalActiveEnvironment
def overrideSignatures(toOverride, original, forceName=None, forceModuleName=None): try: if ObjectHelper.isNotNone(original): toOverride.__name__ = original.__name__ if ObjectHelper.isNone( forceName) else set(forceName) toOverride.__qualname__ = original.__qualname__ if ObjectHelper.isNone( forceName) else set(forceName) toOverride.__module__ = original.__module__ if ObjectHelper.isNone( forceName) else set(c.NOTHING) else: toOverride.__name__ = forceName if ObjectHelper.isNotNone( forceName) else set(toOverride.__name__) toOverride.__qualname__ = forceName if ObjectHelper.isNotNone( forceName) else set(toOverride.__qualname__) toOverride.__module__ = forceModuleName if ObjectHelper.isNotNone( forceModuleName) else set(toOverride.__module__) except Exception as exception: LogHelper.error( overrideSignatures, f'''Not possible to override signatures of {toOverride} by signatures of {original} method''', exception) raise exception
def settingTreeInnerLoop(settingLine, nodeKey, settingTree, longStringCapturing, quoteType, longStringList, settingInjectionList, lazyLoad, isSameDepth): # print(f'settingTreeInnerLoop: nodeKey: {nodeKey}') # print(f' isSameDepth: {isSameDepth}') settingKey, settingValue = getAttributeKeyValue(settingLine) # print(f' settingKey: {settingKey}, settingValue: {settingValue}') # print(f' value:{settingLine}') if containsSettingInjection(settingValue): try: settingKey, settingValue, nodeKey, longStringCapturing, quoteType, longStringList = handleSettingInjection( settingKey, settingValue, nodeKey, settingTree, longStringCapturing, quoteType, longStringList, settingInjectionList, lazyLoad, isSameDepth) except Exception as exception: LogHelper.log( settingTreeInnerLoop, f'Not possible to handle association of "{nodeKey}{c.DOT}{settingKey}" setting key to "{settingValue}" setting value', exception=exception) settingInjectionList.append({ SETTING_KEY: settingKey, SETTING_VALUE: settingValue, SETTING_NODE_KEY: nodeKey }) return settingKey, settingValue, nodeKey, longStringCapturing, quoteType, longStringList else: # print(f' nodeKey: {nodeKey}') settingKey, filteredSettingValue, nodeKey, longStringCapturing, quoteType, longStringList = handleLongStringOrSetting( settingKey, settingValue, nodeKey, settingTree, longStringCapturing, quoteType, longStringList, settingInjectionList, isSameDepth) # print(f'----------> nodeKey: {nodeKey}') return settingKey, filteredSettingValue, nodeKey, longStringCapturing, quoteType, longStringList
def softLog(origin, message, level, exception=None, muteStackTrace=False, newLine=False): if ObjectHelper.isNotNone(exception): hardLog(origin, message, exception, level, muteStackTrace=muteStackTrace) elif c.TRUE == getStatus(level): firstLayerColor, secondLayerColor, tirdLayerColor, resetColor = getColors( level) LogHelper.logIt( StringHelper.join([ firstLayerColor, LEVEL_DICTIONARY[level][LOG_TEXT], *getOriginPortion(origin, tirdLayerColor, resetColor), secondLayerColor, message, resetColor, getNewLine(newLine, exception=exception, muteStackTrace=muteStackTrace) ])) elif not c.FALSE == getStatus(level): levelStatusError(method, level)
def getTestModuleNamesFromQuerryTree(testQueryTree, runOnly, ignore): testModuleNames = [] for queryResultKey, queryResult in testQueryTree.items(): LogHelper.prettyPython(getTestModuleNamesFromQuerryTree, 'Query result', queryResult, logLevel=LogHelper.TEST) updateTestModuleNames(testModuleNames, queryResult, runOnly, ignore) return testModuleNames
def safelyAccessTree(nodeKey, settingTree): setting = None try: setting = accessTree(nodeKey, settingTree) except Exception as exception: LogHelper.log( safelyAccessTree, f'Not possible to safely access "{nodeKey}" node key while looping through setting tree. Returning "{setting}" by default', exception=exception) return setting
def getTestRuntimeInfo(times, testTime, totalTestTime): testRuntimeInfo = None try: testRuntimeInfo = f'It {StringHelper.getToBe(True, singular=1==times, tense=StringHelper.PAST)} {times} test run{StringHelper.getS(times > 1)} in {testTime} seconds. Total test time: {totalTestTime} seconds' except Exception as exception: LogHelper.warning(getTestRuntimeInfo, 'Not possible do get test runtime info', exception=exception) testRuntimeInfo = c.NOTHING return testRuntimeInfo
def querySetting(keywordQuery, tree): if StringHelper.isBlank(keywordQuery) or ObjectHelper.isNotDictionary( tree): LogHelper.warning( querySetting, f'''Not possible to parse "{tree}". It's either is not a dictionary or "{keywordQuery}" keyword query is blank''' ) querySet = {} SettingHelperHelper.keepSearching(keywordQuery, tree, querySet) return querySet
def getSetting(nodeKey, settingTree): setting = None try: setting = SettingHelperHelper.accessTree(nodeKey, settingTree) except Exception as exception: LogHelper.failure( getSetting, f'Not possible to get {nodeKey} node key. Returning "{setting}" by default', exception) return StringHelper.filterString(setting) if isinstance(setting, str) else setting
def handleSettingInjectionListByCallingHandler(done, stuck, isSettingInjectionCount, containsSettingInjectionCount, settingInjection, settingTree, settingInjectionList, fallbackSettingTree, handler): try: if isSettingInjection(settingInjection[SETTING_VALUE]): settingInjection[SETTING_VALUE] = handler( settingInjection[SETTING_KEY], settingInjection[SETTING_VALUE], settingInjection[SETTING_NODE_KEY], settingTree, fallbackSettingTree=fallbackSettingTree) settingInjectionArgs = list( settingInjection.values()) + [settingTree] updateSettingValue(*settingInjectionArgs, isSettingInjection=True) if not containsSettingInjection(settingInjection[SETTING_VALUE]): settingInjectionList.remove(settingInjection) isSettingInjectionCount += 1 stuck = False elif containsSettingInjection(settingInjection[SETTING_VALUE]): settingInjectionListFromSettingValue = getSettingInjectionListFromSettingValue( settingInjection[SETTING_VALUE]) newSettingInjection = settingInjection[SETTING_VALUE] for settingValue in settingInjectionListFromSettingValue: newSettingValue = handler( settingInjection[SETTING_KEY], settingValue, settingInjection[SETTING_NODE_KEY], settingTree, fallbackSettingTree=fallbackSettingTree) if ObjectHelper.isList(newSettingInjection): for index, element in enumerate(newSettingInjection): if settingValue == element: newSettingInjection[index] = newSettingValue else: newSettingInjection = newSettingInjection.replace( settingValue, str(newSettingValue)) settingInjection[SETTING_VALUE] = newSettingInjection settingInjectionArgs = list( settingInjection.values()) + [settingTree] updateSettingValue(*settingInjectionArgs, isSettingInjection=True) if not containsSettingInjection(settingInjection[SETTING_VALUE]): settingInjectionList.remove(settingInjection) containsSettingInjectionCount += 1 stuck = False except Exception as exception: LogHelper.log( handleSettingInjectionListByCallingHandler, f'Ignored exception while handling {StringHelper.prettyPython(settingInjection)} setting injection list', exception=exception) return done, stuck, isSettingInjectionCount, containsSettingInjectionCount
def wrapedFunction(*args, **kwargs): try: functionReturn = function(*args, **kwargs) except Exception as exception: functionName = ReflectionHelper.getName(function, typeName=c.TYPE_FUNCTION) LogHelper.wraper( Function, f'''Failed to execute "{functionName}(args={args}, kwargs={kwargs})" {c.TYPE_FUNCTION} call''', exception) raise exception return functionReturn
def setAttributeOrMethod(instance, name, attributeOrMethodInstance, muteLogs=False): if ObjectHelper.isNotNone(instance) and ObjectHelper.isNotNone(name): try: setattr(instance, name, attributeOrMethodInstance) except Exception as exception: if not muteLogs: LogHelper.warning( setAttributeOrMethod, f'Not possible to set "{name}:{attributeOrMethodInstance}" to "{getClassName(instance, typeClass=c.TYPE_CLASS, muteLogs=muteLogs) if ObjectHelper.isNotNone(instance) else instance}" instance', exception=exception)
def unitTest(testModule, testName, data, testReturns, logResult): discountTimeEnd = time.time() unitTestException = None if logResult: LogHelper.test(unitTest, f'{testName}{c.DOT}{data[1]} test started') moduleTestStartTime = time.time() try: testReturns[data[1]] = data[0]() LogHelper.printSuccess( f'{data[0].__module__}{c.DOT}{data[0].__name__} succeed', condition=logResult, newLine=False, margin=False) except Exception as exception: LogHelper.printError( f'{data[0].__module__}{c.DOT}{data[0].__name__} failed', condition=True, newLine=False, margin=False, exception=exception) unitTestException = exception if logResult: LogHelper.test( unitTest, f'{testName}{c.DOT}{data[1]} test completed in {time.time() - moduleTestStartTime} seconds' ) if ObjectHelper.isNotNone(unitTestException): raise unitTestException someDidRun = True return testName, data, testReturns, someDidRun, logResult, discountTimeEnd
def wrapedMethod(*args, **kwargs): try: methodReturn = method(*args, **kwargs) except Exception as exception: className = ReflectionHelper.getClassName(args[0].__class__, typeClass=c.TYPE_CLASS) methodName = ReflectionHelper.getClassName(method, typeClass=c.TYPE_METHOD) LogHelper.wraper( Method, f'''Failed to execute "{className}{c.DOT}{methodName}(args={args}, kwargs={kwargs})" {c.TYPE_METHOD} call''', exception) raise exception return methodReturn
def getAttributeOrMethod(instance, name, muteLogs=False, default=None): attributeOrMethodInstance = None if ObjectHelper.isNotNone(instance) and ObjectHelper.isNotNone(name): try: attributeOrMethodInstance = default if not hasattr( instance, name) else getattr(instance, name) except Exception as exception: if not muteLogs: LogHelper.warning( getAttributeOrMethod, f'Not possible to get "{name}" from "{getClassName(instance, typeClass=c.TYPE_CLASS, muteLogs=muteLogs) if ObjectHelper.isNotNone(instance) else instance}" instance', exception=exception) return default if ObjectHelper.isNone( attributeOrMethodInstance) else attributeOrMethodInstance
def replaceEnvironmentVariables(environmentVariables): global ACTIVE_ENVIRONMENT_VALUE originalActiveEnvironment = None if ObjectHelper.isNone( ACTIVE_ENVIRONMENT_VALUE) else f'{c.NOTHING}{ACTIVE_ENVIRONMENT_VALUE}' if ObjectHelper.isNotEmpty(originalActiveEnvironment): ACTIVE_ENVIRONMENT_VALUE = None originalEnvironmentVariables = {} if ObjectHelper.isDictionary(environmentVariables): for key, value in environmentVariables.items(): originalEnvironmentVariables[key] = EnvironmentHelper.switch( key, value) getActiveEnvironment() LogHelper.loadSettings() return originalEnvironmentVariables, originalActiveEnvironment
def getErrorPortion(exception, muteStackTrace, firstLayerColor, secondLayerColor, tirdLayerColor, resetColor): if ObjectHelper.isEmpty(exception): return [c.NOTHING] exceptionMessage = LogHelper.getExceptionMessage(exception) traceBackMessage = LogHelper.getTracebackMessage(muteStackTrace) traceBackMessageSplited = traceBackMessage.split(exceptionMessage) return [ c.NEW_LINE, tirdLayerColor, *[ t if t is not traceBackMessageSplited[-1] else t if t[-1] is not c.NEW_LINE else t[:-1] for t in traceBackMessageSplited if ObjectHelper.isNotNone(t) ], secondLayerColor, exceptionMessage, resetColor ]
def getName(thing, typeName=None, muteLogs=False): name = None try: if ObjectHelper.isEmpty(thing): name = getUndefindeName(typeName) else: name = thing.__name__ except Exception as exception: name = getUndefindeName(typeName) if not muteLogs: LogHelper.warning( None, f'Not possible to get name of {thing}. Returning {name} insted', exception=exception) return name
def getClass(thing, typeClass=None, muteLogs=False): thingClass = None try: if ObjectHelper.isEmpty(thing): thingClass = typeClass else: thingClass = thing.__class__ except Exception as exception: thingClass = type(None) if not muteLogs: LogHelper.warning( None, f'Not possible to get class of {thing}. Returning {thingClass} insted', exception=exception) return thingClass
def getModuleName(thing, typeModule=None, muteLogs=False): name = None try: if ObjectHelper.isEmpty(thing): name = getUndefindeName(typeModule) else: name = thing.__module__.split(c.DOT)[-1] except Exception as exception: name = getUndefindeName(typeModule) if not muteLogs: LogHelper.warning( None, f'Not possible to get module name of {thing}. Returning {name} insted', exception=exception) return name
def getClassName(thing, typeClass=None, muteLogs=False): name = None try: if ObjectHelper.isEmpty(thing): name = getUndefindeName(typeClass) else: name = getName(getClass(thing, muteLogs=muteLogs), muteLogs=muteLogs) except Exception as exception: name = getUndefindeName(typeClass) if not muteLogs: LogHelper.warning( None, f'Not possible to get class name of {thing}. Returning {name} insted', exception=exception) return name
def run(filePath, runOnly=None, ignore=None, times=1, successStatus=True, errorStatus=True, settingStatus=False, debugStatus=True, warningStatus=True, failureStatus=True, wrapperStatus=False, testStatus=False, logStatus=False, inspectGlobals=False, logResult=True): import globals globalsInstance = globals.newGlobalsInstance(filePath, successStatus=successStatus, errorStatus=errorStatus, settingStatus=settingStatus or inspectGlobals, debugStatus=debugStatus, warningStatus=warningStatus, failureStatus=failureStatus, wrapperStatus=wrapperStatus, testStatus=testStatus, logStatus=logStatus) testModuleNames, testsToRun, runSpecificTests = getTestModuleNames( runOnly, ignore, globalsInstance) returns = {} totalTestTimeStart = time.time() testTime = 0 for testModuleName in testModuleNames: runnableTddModule = getModuleTest(inspectGlobals, logResult, globalsInstance) allDidRun, didRun, moduleTestTime, testReturns = runModuleTests( testModuleName, runnableTddModule, times, runSpecificTests, testsToRun, logResult, globalsInstance) returns[testModuleName] = testReturns testTime += moduleTestTime totalTestTime = time.time() - totalTestTimeStart if logResult: LogHelper.success( run, f'{globalsInstance.apiName} tests completed. {getTestRuntimeInfo(times, testTime, totalTestTime)}' ) return returns
def update(environmentKey, environmentValue, default=None) : if ObjectHelper.isNotEmpty(environmentKey) : associatedValue = None if not environmentValue is None : associatedValue = str(StringHelper.filterString(environmentValue)) OS.environ[environmentKey] = associatedValue elif not default is None : associatedValue = str(StringHelper.filterString(default)) OS.environ[environmentKey] = associatedValue else : try: delete(environmentKey) except Exception as exception : LogHelper.warning(update, f'Failed to delete "{environmentKey}" enviroment variable key', exception=exception) return associatedValue else : LogHelper.debug(update, f'arguments: environmentKey: {environmentKey}, environmentValue: {environmentValue}, default: {default}') raise Exception(f'Error associating environment variable "{environmentKey}" key to environment variable "{environmentValue}" value')
def handleSettingInjectionList(settingInjectionList, settingTree, fallbackSettingTree=None): if ObjectHelper.isNotEmptyCollection( settingInjectionList) and ObjectHelper.isNotNone(settingTree): try: done, stuck = handleSettingInjectionListLoop( False, False, settingTree, settingInjectionList, fallbackSettingTree, getSettingInjectionValueIgnoringFallbackSettingTree, verifyer=verifyDefaultSettingInjectionListHandler) except Exception as exception: LogHelper.error( handleSettingInjectionList, 'Not possible to load setting injections properly', exception) raise exception
def updateSettingValue(settingKey, settingValue, nodeKey, settingTree, isSameDepth=False, isSettingInjection=False): # print(f'settingKey: {settingKey}, settingValue: {settingValue}, nodeKey: {nodeKey}, settingTree: {settingTree}, isSameDepth: {isSameDepth}') if StringHelper.isNotBlank(settingKey) and ObjectHelper.isNotNone( settingKey): # print(f'accessTree({nodeKey},{settingTree})[{settingKey}]: {accessTree(nodeKey,settingTree)}[{settingKey}]') # print(f'type(accessTree(nodeKey,settingTree)): {type(accessTree(nodeKey,settingTree))}') accessTree(nodeKey, settingTree)[settingKey] = getSettingValueOrNewNode( nodeKey, settingKey, settingValue, isSameDepth=isSameDepth, isSettingInjection=isSettingInjection) elif StringHelper.isNotBlank(nodeKey) and ObjectHelper.isNotNone(nodeKey): splittedNodeKey = nodeKey.split(c.DOT) if 1 < len(splittedNodeKey): accessSettingKey = splittedNodeKey[-1] accessNodeKey = c.DOT.join(splittedNodeKey[:-1]) else: accessSettingKey = splittedNodeKey[-1] accessNodeKey = None accessTree(accessNodeKey, settingTree)[accessSettingKey] = getSettingValueOrNewNode( nodeKey, settingKey, settingValue, isSameDepth=isSameDepth, isSettingInjection=isSettingInjection) else: errorMessage = 'Node key and setting key cannot be None at the same time' exception = Exception(errorMessage) LogHelper.error( updateSettingValue, f'Error parsing settingKey: "{settingKey}", settingValue: {settingValue}, nodeKey: {nodeKey}, settingTree: {StringHelper.prettyPython(settingTree)}', errorMessage) raise exception
def printMessageLog(level, message, condition=False, muteStackTrace=False, newLine=True, margin=True, exception=None): if condition: firstLayerColor, secondLayerColor, tirdLayerColor, resetColor = getColors( level) LogHelper.logIt( StringHelper.join([ c.TAB if margin else c.NOTHING, firstLayerColor, LEVEL_DICTIONARY[level][LOG_TEXT], secondLayerColor, message, *getErrorPortion(exception, muteStackTrace, firstLayerColor, secondLayerColor, tirdLayerColor, resetColor), resetColor, getNewLine(newLine, exception=exception, muteStackTrace=muteStackTrace) ]))
def accessTree(nodeKey, tree): if ObjectHelper.isNotNone(tree): strippedNodeKey = nodeKey.strip() if ObjectHelper.isEmpty(nodeKey): returnTree = None try: returnTree = StringHelper.filterString(tree) except Exception as exception: LogHelper.failure( accessTree, f'Failed to get filtered string from {tree} tree. Returning it the way it is by default', exception) returnTree = tree return returnTree elif isinstance(nodeKey, str): nodeKeyList = nodeKey.split(c.DOT) if len(nodeKeyList) == 1: nextNodeKey = c.NOTHING else: nextNodeKey = c.DOT.join(nodeKeyList[1:]) return accessTree(nextNodeKey, tree.get(nodeKeyList[0]))
def getItNaked(it): printDetails(it) printClass(it) try: LogHelper.prettyPython(getAttributeDataDictionary, 'getAttributeDataDictionary', getAttributePointerList(it), logLevel=LogHelper.DEBUG) except: pass try: LogHelper.prettyPython(getAttributeAndMethodNameList, 'getAttributeAndMethodNameList', getAttributeAndMethodNameList(it), logLevel=LogHelper.DEBUG) except: pass try: LogHelper.prettyPython(getAttributeNameList, 'getAttributeNameList', getAttributeNameList(it), logLevel=LogHelper.DEBUG) except: pass try: LogHelper.prettyPython(getAttributeDataList, 'getAttributeDataList', getAttributeDataList(it), logLevel=LogHelper.DEBUG) except: pass try: LogHelper.prettyPython(getAttributeDataDictionary, 'getAttributeDataDictionary', getAttributeDataDictionary(it), logLevel=LogHelper.DEBUG) except: pass
def safelyGetSettingInjectionValue(settingKey, settingValue, nodeKey, settingTree, fallbackSettingTree=None): exception = None newSettingValue = None try: newSettingValue = getSettingInjectionValue(settingKey, settingValue, nodeKey, settingTree) except Exception as e: exception = e LogHelper.log( safelyGetSettingInjectionValue, f'Not possible to load "{settingKey}" setting key from setting tree. Now trying to load it from fallback setting tree', exception=exception) if ObjectHelper.isNone(newSettingValue) and ObjectHelper.isNotNone( fallbackSettingTree): return getSettingInjectionValue(settingKey, settingValue, nodeKey, fallbackSettingTree) if ObjectHelper.isNotNone(exception): raise exception return newSettingValue