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 innerResourceInstanceMethod(*innerArgs,**innerKwargs) : handlerException = None handlerReturn = None inspectGlobalsIfNeeded(inspectGlobals, resourceInstanceMethod, 'will impartialy observe') try : methodReturnException = None methodReturn = TEST_VALUE_NOT_SET handleBefore(resourceInstanceMethod, callBefore, argsOfCallBefore, kwargsOfCallBefore, returns, inspectGlobals) originalEnvironmentVariables, originalActiveEnvironment = SettingHelper.replaceEnvironmentVariables(environmentVariables) inspectGlobalsIfNeeded(inspectGlobals, resourceInstanceMethod, 'is about to run') try : methodReturn = resourceInstanceMethod(*innerArgs,**innerKwargs) except Exception as exception : methodReturnException = exception inspectGlobalsIfNeeded(inspectGlobals, resourceInstanceMethod, 'just run') SettingHelper.recoverEnvironmentVariables(environmentVariables, originalEnvironmentVariables, originalActiveEnvironment) handlerReturn = handleAfter(resourceInstanceMethod, callAfter, argsOfCallAfter, kwargsOfCallAfter, returns, methodReturn, inspectGlobals, methodReturnException=methodReturnException, logResult=logResult) except Exception as exception : handlerException = exception inspectGlobalsIfNeeded(inspectGlobals, resourceInstanceMethod, 'impartialy observed') if ObjectHelper.isNotNone(handlerException) : raise handlerException return handlerReturn
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 actionIsPresent(actionClass) : return not TEST_VALUE_NOT_SET == actionClass and ObjectHelper.isNotNone(actionClass)
def plusSeconds(givenDateTime, seconds=None, deltaInSeconds=None): if ObjectHelper.isNotNone(seconds): deltaInMinutes = datetime.timedelta(seconds=seconds) if isinstance(givenDateTime, datetime.time): givenDateTime = forcedlyParse(f'{str(dateNow())} {givenDateTime}') return forcedlyGetDateTime(str(givenDateTime)) + deltaInMinutes
def getUndefindeName(typeThing): if ObjectHelper.isEmpty(typeThing): return f'({UNDEFINED})' else: return f'({typeThing} {UNDEFINED})'
def getSettingTree(settingFilePath, settingTree=None, fallbackSettingFilePath=None, fallbackSettingTree=None, lazyLoad=False, keepDepthInLongString=False, depthStep=c.TAB_UNITS, encoding=c.ENCODING): settingInjectionList = [] fallbackSettingInjectionList = [] if ObjectHelper.isNotNone(fallbackSettingFilePath): innerFallbackSettingTree, fallbackSettingInjectionList = getSettingTree( fallbackSettingFilePath, lazyLoad=True, keepDepthInLongString=keepDepthInLongString, depthStep=depthStep, encoding=encoding) else: innerFallbackSettingTree = {} with open(settingFilePath, c.READ, encoding=encoding) as settingsFile: allSettingLines = settingsFile.readlines() longStringCapturing = False quoteType = None longStringList = None depth = 0 nodeRefference = 0 nodeKey = c.NOTHING if settingTree is None: settingTree = {} for line, settingLine in enumerate(allSettingLines): if SettingHelperHelper.lineAproved(settingLine): if longStringCapturing: # print('lineAproved') if not currentDepth: currentDepth = 0 longStringList.append(depthStep * c.SPACE + settingLine if keepDepthInLongString else settingLine[depth:]) if quoteType in str(settingLine): longStringList[-1] = c.NOTHING.join( longStringList[-1].split(quoteType))[:-1] + quoteType settingValue = c.NOTHING.join(longStringList) nodeKey = SettingHelperHelper.updateSettingTreeAndReturnNodeKey( settingKey, settingValue, nodeKey, settingTree, False) longStringCapturing = False quoteType = None longStringList = None else: currentDepth = SettingHelperHelper.getDepth(settingLine) isSameDepth = SettingHelperHelper.nextValidLineIsAtTheSameDepthOrLess( currentDepth, line, allSettingLines) # print(f'isSameDepth: {isSameDepth}') if currentDepth == depth: # print('currentDepth == depth') settingKey, settingValue, nodeKey, longStringCapturing, quoteType, longStringList = SettingHelperHelper.settingTreeInnerLoop( settingLine, nodeKey, settingTree, longStringCapturing, quoteType, longStringList, settingInjectionList, lazyLoad, isSameDepth) elif currentDepth > depth: # print('currentDepth > depth') currentNodeRefference = currentDepth // (currentDepth - depth) if currentNodeRefference - nodeRefference == 1: settingKey, settingValue, nodeKey, longStringCapturing, quoteType, longStringList = SettingHelperHelper.settingTreeInnerLoop( settingLine, nodeKey, settingTree, longStringCapturing, quoteType, longStringList, settingInjectionList, lazyLoad, isSameDepth) nodeRefference = currentNodeRefference depth = currentDepth elif currentDepth < depth: # print('currentDepth < depth') nodeRefference = currentDepth // depthStep ###- if line.split(':')[0] == currentDepth + c.TAB_UNITS * ' ' + depth = currentDepth # print() # print() # print() # print(str(line)) # print(str(nodeKey)) # print(str(settingLine)) splitedNodeKey = nodeKey.split(c.DOT)[:nodeRefference] splitedNodeKeyLength = len(splitedNodeKey) if splitedNodeKeyLength == 0: nodeKey = c.NOTHING elif splitedNodeKeyLength == 1: nodeKey = splitedNodeKey[0] else: nodeKey = c.DOT.join(splitedNodeKey) settingKey, settingValue, nodeKey, longStringCapturing, quoteType, longStringList = SettingHelperHelper.settingTreeInnerLoop( settingLine, nodeKey, settingTree, longStringCapturing, quoteType, longStringList, settingInjectionList, lazyLoad, isSameDepth) # if ObjectHelper.isNotNone(settingValue) and ObjectHelper.isNotEmpty(settingValue) : depth = currentDepth if lazyLoad: return settingTree, settingInjectionList elif (ObjectHelper.isNotEmptyCollection(innerFallbackSettingTree) and ObjectHelper.isNotNone(fallbackSettingFilePath)): for fallbackSettingInjection in fallbackSettingInjectionList.copy(): for settingInjection in settingInjectionList.copy(): if (fallbackSettingInjection[SettingHelperHelper.SETTING_KEY] == settingInjection[SettingHelperHelper.SETTING_KEY] and fallbackSettingInjection[ SettingHelperHelper.SETTING_NODE_KEY] == settingInjection[ SettingHelperHelper.SETTING_NODE_KEY]): fallbackSettingInjectionList.remove( fallbackSettingInjection) settingInjectionList += fallbackSettingInjectionList updateSettingTree(settingTree, innerFallbackSettingTree) SettingHelperHelper.handleSettingInjectionList( settingInjectionList, settingTree, fallbackSettingTree=innerFallbackSettingTree) SettingHelperHelper.handleSettingInjectionList( settingInjectionList, settingTree, fallbackSettingTree=fallbackSettingTree) updateSettingTree(settingTree, fallbackSettingTree) return settingTree
def isNotMethodClass(methodClass): return False if ObjectHelper.isNone( methodClass) else not isMethodClass(methodClass)
def getFilteredAndColoredQuote(keyOrValue, string, prettyFunction, withColors, color) : if ObjectHelper.isNativeClassInstance(keyOrValue) and not isinstance(keyOrValue, str) : return [c.NOTHING] if StringHelper.prettyPython == prettyFunction else getItAsColoredString(string, prettyFunction, withColors, color=color) return getItAsColoredString(string, prettyFunction, withColors, color=color)
def of(date=None, time=None, dateTime=None): if ObjectHelper.isNotNone(dateTime): date = dateTime.split()[0] time = dateTime.split()[1] return datetime.datetime.combine(forcedlyGetDate(date), forcedlyGetTime(time))
def handleBefore(resourceInstanceMethod, actionClass, args, kwargs, returns, inspectGlobals) : LogHelper.test(resourceInstanceMethod, 'Test started') actionHandlerException = handle(resourceInstanceMethod, actionClass, args, kwargs, returns, BEFORE_THE_TEST, RETURN_VALUE_FROM_CALL_BEFORE) if ObjectHelper.isNotNone(actionHandlerException) : raise actionHandlerException inspectGlobalsIfNeeded(inspectGlobals, resourceInstanceMethod, 'will run')
def minusMinutes(givenDateTime, minutes=None, deltaInMinutes=None): if ObjectHelper.isNotNone(minutes): deltaInMinutes = datetime.timedelta(minutes=minutes) if isinstance(givenDateTime, datetime.time): givenDateTime = forcedlyParse(f'{str(dateNow())} {givenDateTime}') return forcedlyGetDateTime(str(givenDateTime)) - deltaInMinutes
def minusDays(givenDay, days=None, deltaInDays=None): if ObjectHelper.isNotNone(minutes): deltaInDays = datetime.timedelta(days=days) return forcedlyGetDateTime(str(givenDay)) - deltaInDays
def isSettingInjection(settingValue): return ObjectHelper.isNotNone(settingValue) and ( isinstance(settingValue, str) and settingValue.startswith(OPEN_SETTING_INJECTION) and settingValue.endswith(CLOSE_SETTING_INJECTION) and containsOnlyOneSettingInjection(settingValue))
def isSettingValue(settingValue): return ObjectHelper.isNotEmpty(settingValue) or ObjectHelper.isCollection( settingValue)
def isMethod(objectInstance, name): if ObjectHelper.isNone(objectInstance) or StringHelper.isBlank(name): return False return isMethodInstance(getAttributeOrMethod(objectInstance, name))
def returnsValueIsPresent(returns) : isPresent = ObjectHelper.isDictionary(returns) if not isPresent : LogHelper.test(returnsValueIsPresent, f'the key "returns" from {ReflectionHelper.getMethodModuleNameDotName(Test)} annotation call was not defined') return isPresent
def getValueCollection(outterValue) : return outterValue if not isinstance(outterValue, set) else ObjectHelper.getSortedCollection(outterValue)
def getWeekDay(ofDatetime=None, ofDate=None, ofTime=None): if ObjectHelper.isNotNone(ofDatetime): return forcedlyGetDateTime(ofDatetime).weekday() elif ObjectHelper.isNotNone(ofDate) and ObjectHelper.isNotNone(ofTime): return of(forcedlyGetDate(ofDate), forcedlyGetTime(ofTime)).weekday() return datetime.datetime.now().weekday()
def isMethodClass(methodClass): return False if ObjectHelper.isNone( methodClass) else methodClass.__name__ in METHOD_TYPE_NAME_LIST
def toString(givenDatetime, pattern=DEFAULT_DATETIME_PATTERN): return givenDatetime if ObjectHelper.isNone(givenDatetime) or isinstance( givenDatetime, str) else parseToString(givenDatetime, pattern=pattern)
def parseToDateTime(givenDatetime, pattern=DEFAULT_DATETIME_PATTERN): return givenDatetime if ObjectHelper.isNone( givenDatetime) or not isinstance( givenDatetime, str) else parseToPattern(givenDatetime, pattern=pattern)
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 forcedlyGetDate(givenDate, pattern=DEFAULT_DATE_PATTERN): return givenDate if ObjectHelper.isNone(givenDate) or not isinstance( givenDate, str) else forcedlyParse(givenDate, pattern=pattern)
def getColorValue(thing, color) : return color if ObjectHelper.isNotNone(color) else c.NATIVE_PROMPT_COLOR.get( ReflectionHelper.getName(type(thing)), c.DARK_BLUE )
def forcedlyGetTime(givenTime, pattern=DEFAULT_TIME_PATTERN): return givenTime if ObjectHelper.isNone(givenTime) or not isinstance( givenTime, str) else forcedlyParse(givenTime, pattern=pattern)
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 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 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 hasAttributeOrMethod(instance, name): return False if ObjectHelper.isNone(instance) or ObjectHelper.isNone( name) else hasattr(instance, name)