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 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 softlyGetActiveEnvironment(): global ACTIVE_ENVIRONMENT_VALUE if ObjectHelper.isNone(ACTIVE_ENVIRONMENT_VALUE): activeEnvironment = EnvironmentHelper.get(ACTIVE_ENVIRONMENT) if ObjectHelper.isNone(activeEnvironment): ACTIVE_ENVIRONMENT_VALUE = updateActiveEnvironment( DEFAULT_ENVIRONMENT) else: ACTIVE_ENVIRONMENT_VALUE = activeEnvironment return getValueAsString(ACTIVE_ENVIRONMENT_VALUE)
def sample(collection, length=None): if ObjectHelper.isCollection(collection): if ObjectHelper.isDictionary(collection): if ObjectHelper.isNone(length): key = RandomHelperHelper.sampleCollection( list(collection.keys()), list) return {key: collection[key]} sampleDictionaryKeys = RandomHelperHelper.sampleCollection( list(collection.keys()), list, length=length) sampleDictionary = {} for key in sampleDictionaryKeys: sampleDictionary[key] = collection[key] return sampleDictionary elif ObjectHelper.isList(collection): return RandomHelperHelper.sampleCollection(collection, list, length=length) elif ObjectHelper.isSet(collection): return RandomHelperHelper.sampleCollection(collection, set, length=length) elif ObjectHelper.isTuple(collection): return RandomHelperHelper.sampleCollection(collection, tuple, length=length) raise Exception(f'The "{collection}" argument is not a collection')
def prettyInstance( outterValue, quote, prettyFunction, tabCount, nullValue, trueValue, falseValue, withColors=False, joinAtReturn=False ) : strReturn = [] if (isinstance(outterValue, int) or isinstance(outterValue, float)) and not isinstance(outterValue, bool) : strReturn += getItAsColoredString(outterValue, prettyFunction, withColors) elif isinstance(outterValue, bool) : if True == outterValue: strReturn += getItAsColoredString(outterValue, prettyFunction, withColors, replaceBy=trueValue) elif False == outterValue: strReturn += getItAsColoredString(outterValue, prettyFunction, withColors, replaceBy=falseValue) elif ObjectHelper.isNone(outterValue) : strReturn += getItAsColoredString(outterValue, prettyFunction, withColors, replaceBy=nullValue, color=c.NONE_PROMP_COLOR) else : filteredAndColoredQuote = getFilteredAndColoredQuote(outterValue, quote, prettyFunction, withColors, c.QUOTE_PROMPT_COLOR) strReturn += [*filteredAndColoredQuote, *getItAsColoredString(outterValue, prettyFunction, withColors), *filteredAndColoredQuote] return returnStr(strReturn, joinAtReturn)
def updateTestModuleNames(testModuleNames, queryResult, runOnly, ignore): if not c.NOTHING == queryResult: for key, value in queryResult.items(): if c.NOTHING == value and key.endswith(TEST_DOT_PY): testModuleName = key[:-len(DOT_PY)] if ObjectHelper.isNone(runOnly) or ObjectHelper.isNotNone( runOnly) and testModuleName in runOnly: testModuleNames.append(testModuleName) else: updateTestModuleNames(testModuleNames, value, runOnly, ignore)
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 getTestModuleNames(runOnly, ignore, globalsInstance): testsToRun = [] if ObjectHelper.isNone( runOnly) or ObjectHelper.isNotCollection(runOnly) else runOnly testsToIgnore = [] if ObjectHelper.isNone( ignore) or ObjectHelper.isNotCollection(ignore) else ignore runSpecificTests = ObjectHelper.isNotEmpty(testsToRun) LogHelper.prettyPython(getTestModuleNames, f'runSpecificTests: {runSpecificTests}, testsToRun', testsToRun, logLevel=LogHelper.TEST) testModuleNames = [] if ObjectHelper.isEmpty(testsToRun): testQueryTree = SettingHelper.querySetting(TEST_PACKAGE, globalsInstance.apiTree) LogHelper.prettyPython(getTestModuleNames, 'Test query tree', testQueryTree, logLevel=LogHelper.TEST) testModuleNames += getTestModuleNamesFromQuerryTree( testQueryTree, runOnly, ignore) else: for testName in testsToIgnore: if testName in testsToRun: testModuleNames, testsToRun, runSpecificTests.remove(testName) for testName in testsToRun: testNameSplitted = testName.split(c.DOT) testModuleName = c.NOTHING if 2 == len(testNameSplitted): testModuleName = testNameSplitted[-2] if testModuleName not in testModuleNames and StringHelper.isNotBlank( testName): testModuleNames.append(testModuleName) LogHelper.prettyPython(getTestModuleNames, 'Test module names', testModuleNames, logLevel=LogHelper.TEST) return testModuleNames, testsToRun, runSpecificTests
def handleAfter(resourceInstanceMethod, actionClass, args, kwargs, returns, methodReturn, inspectGlobals, methodReturnException=None, logResult=True) : inspectGlobalsIfNeeded(inspectGlobals, resourceInstanceMethod, 'did run') if ObjectHelper.isNone(methodReturnException) : LogHelper.printSuccess(f'{ReflectionHelper.getMethodModuleNameDotName(resourceInstanceMethod)} test succeed', condition=logResult, newLine=False, margin=False) else : LogHelper.printError(f'{ReflectionHelper.getMethodModuleNameDotName(resourceInstanceMethod)} test failed', condition=logResult, newLine=False, margin=False, exception=methodReturnException) actionHandlerException = handle(resourceInstanceMethod, actionClass, args, kwargs, returns, AFTER_THE_TEST, RETURN_VALUE_FROM_CALL_AFTER) LogHelper.test(resourceInstanceMethod, 'Test completed') if ObjectHelper.isNotNone(methodReturnException) or ObjectHelper.isNotNone(actionHandlerException) : if ObjectHelper.isNotNone(methodReturnException) and ObjectHelper.isNotNone(actionHandlerException) : raise Exception(f'{LogHelper.getExceptionMessage(methodReturnException)}. Followed by: {LogHelper.getExceptionMessage(actionHandlerException)}') elif ObjectHelper.isNotNone(methodReturnException) : raise methodReturnException raise actionHandlerException if not TEST_VALUE_NOT_SET == methodReturn : return methodReturn
def getSettingInjectionValue(settingKey, settingValue, nodeKey, settingTree): unwrapedSettingInjectionValue = getUnwrappedSettingInjection(settingValue) if isSettingKey(unwrapedSettingInjectionValue): selfReferenceSettingValue = safelyAccessTree( unwrapedSettingInjectionValue, settingTree) if ObjectHelper.isNone(selfReferenceSettingValue): raise Exception( f'Not possible to associate "{nodeKey}{c.DOT}{settingKey}" key to "{unwrapedSettingInjectionValue}" value. "{unwrapedSettingInjectionValue}" value is probably not defined' ) return selfReferenceSettingValue environmentKey = unwrapedSettingInjectionValue.split(c.COLON)[0] environmentValue = EnvironmentHelper.get(environmentKey) if environmentValue: return environmentValue else: return getFilteredSetting(settingKey, unwrapedSettingInjectionValue, nodeKey, settingTree)
def updateSettingTree(toUpdateSettingTree, gatheringSettingTree): if ObjectHelper.isNotEmpty(gatheringSettingTree): if ObjectHelper.isNone(toUpdateSettingTree) or StringHelper.isBlank( toUpdateSettingTree): toUpdateSettingTree = {} if ObjectHelper.isCollection( gatheringSettingTree) and ObjectHelper.isDictionary( gatheringSettingTree): for key, value in gatheringSettingTree.items(): if ObjectHelper.isNotEmpty(value) and ObjectHelper.isNotNone( value): if key not in toUpdateSettingTree or ObjectHelper.isEmpty( toUpdateSettingTree[key]): toUpdateSettingTree[key] = value else: updateSettingTree(toUpdateSettingTree[key], gatheringSettingTree[key]) elif key not in toUpdateSettingTree: toUpdateSettingTree[key] = value
def instanciateItWithNoArgsConstructor(targetClass, amountOfNoneArgs=0, args=None, muteLogs=None): if ObjectHelper.isNone(args): args = [] for _ in range(amountOfNoneArgs): args.append(None) objectInstance = None for _ in range(MAXIMUN_ARGUMENTS): try: objectInstance = targetClass(*args) break except: args.append(None) if not isinstance(objectInstance, targetClass): raise Exception( f'Not possible to instanciate {getClassName(targetClass, typeClass=c.TYPE_CLASS, muteLogs=muteLogs)} with None as args constructor' ) return objectInstance
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
def parseToDateTime(givenDatetime, pattern=DEFAULT_DATETIME_PATTERN): return givenDatetime if ObjectHelper.isNone( givenDatetime) or not isinstance( givenDatetime, str) else parseToPattern(givenDatetime, pattern=pattern)
def hasAttributeOrMethod(instance, name): return False if ObjectHelper.isNone(instance) or ObjectHelper.isNone( name) else hasattr(instance, name)
def isMethodClass(methodClass): return False if ObjectHelper.isNone( methodClass) else methodClass.__name__ in METHOD_TYPE_NAME_LIST
def isNotMethodClass(methodClass): return False if ObjectHelper.isNone( methodClass) else not isMethodClass(methodClass)
def getItAsColoredString(thing, prettyFunction, withColors, replaceBy=None, color=None) : thingValue = str(thing) if ObjectHelper.isNone(replaceBy) else str(replaceBy) return [thingValue] if not withColors else [getColorValue(thing, color), thingValue, c.RESET_COLOR]
def isMethod(objectInstance, name): if ObjectHelper.isNone(objectInstance) or StringHelper.isBlank(name): return False return isMethodInstance(getAttributeOrMethod(objectInstance, name))
def toString(givenDatetime, pattern=DEFAULT_DATETIME_PATTERN): return givenDatetime if ObjectHelper.isNone(givenDatetime) or isinstance( givenDatetime, str) else parseToString(givenDatetime, pattern=pattern)
def forcedlyGetInterval(givenTime, pattern=DEFAULT_DATETIME_PATTERN): return givenTime if ObjectHelper.isNone(givenTime) or not isinstance( givenTime, str) else forcedlyParse( givenTime, pattern=pattern, timedelta=True)
def updateActiveEnvironment(activeEnvironment): global ACTIVE_ENVIRONMENT_VALUE ACTIVE_ENVIRONMENT_VALUE = DEFAULT_ENVIRONMENT if ObjectHelper.isNone( activeEnvironment) else activeEnvironment EnvironmentHelper.update(ACTIVE_ENVIRONMENT, ACTIVE_ENVIRONMENT_VALUE) return getValueAsString(ACTIVE_ENVIRONMENT_VALUE)
def forcedlyGetDate(givenDate, pattern=DEFAULT_DATE_PATTERN): return givenDate if ObjectHelper.isNone(givenDate) or not isinstance( givenDate, str) else forcedlyParse(givenDate, pattern=pattern)
def forcedlyGetTime(givenTime, pattern=DEFAULT_TIME_PATTERN): return givenTime if ObjectHelper.isNone(givenTime) or not isinstance( givenTime, str) else forcedlyParse(givenTime, pattern=pattern)
def getNewLine(newLine, exception=None, muteStackTrace=False): return c.NEW_LINE if (newLine and ObjectHelper.isNone(exception)) or ( ObjectHelper.isNotNone(exception) and NO_TRACEBACK_PRESENT_MESSAGE == LogHelper.getTracebackMessage(muteStackTrace)) else c.NOTHING
def get(environmentKey, default=None) : environmentValue = default if ObjectHelper.isNone(environmentKey) else OS.environ.get(environmentKey) return environmentValue if ObjectHelper.isNotNone(environmentValue) else default