def __init__(self, message=None, logMessage=None, status=None, logResource=None, logResourceMethod=None, verb=None, url=None, logPayload=None, logHeaders=None, context=None): self.timeStamp = DateTimeHelper.now() self.status = HttpStatus.map(DEFAULT_STATUS if ObjectHelper. isNone(status) else status).enumValue self.message = message if ObjectHelper.isNotEmpty( message ) and StringHelper.isNotBlank( message ) else DEFAULT_MESSAGE if 500 <= self.status else self.status.enumName self.verb = verb if ObjectHelper.isNotNone( verb) else self.getRequestVerb() self.url = url if ObjectHelper.isNotNone(url) else self.getRequestUrl() self.logMessage = DEFAULT_LOG_MESSAGE if ObjectHelper.isNone( logMessage) or StringHelper.isBlank(logMessage) else logMessage self.logResource = DEFAULT_LOG_RESOURCE if ObjectHelper.isNone( logResource) else logResource self.logResourceMethod = DEFAULT_LOG_RESOURCE_METHOD if ObjectHelper.isNone( logResourceMethod) else logResourceMethod self.logPayload = logPayload if ObjectHelper.isNotNone( logPayload) else self.getRequestBody() self.logHeaders = logHeaders if ObjectHelper.isNotNone( logHeaders) else self.getRequestHeaders() self.context = HttpDomain.CONTROLLER_CONTEXT if ObjectHelper.isNone( context) else context
def prettifyPerformance(): # arrange TEST_SIZE = 100 dictionaryToPrettify = {} for index in range(TEST_SIZE): dictionaryToPrettify[f'key_{index}'] = DICTIONARY_INSTANCE # act performanceTime = 0 performanceTimeInit = time.time() toAssertPython = StringHelper.prettyPython(dictionaryToPrettify, tabCount=1, withColors=True) toAssertJson = StringHelper.prettyJson(dictionaryToPrettify, tabCount=1, withColors=True) performanceTime += time.time() - performanceTimeInit ###- 10000 returning f'{strInstance}{strInstance}' : 365.3402144908905 seconds ###- 10000 returning ''.join([strInstance, strInstance]) : 46.94538736343384 seconds # assert assert ObjectHelper.isNotNone(toAssertPython) and StringHelper.isNotBlank( toAssertPython) assert ObjectHelper.isNotNone(toAssertJson) and StringHelper.isNotBlank( toAssertJson) log.test( prettifyPerformance, f'performance time on a {len(str(dictionaryToPrettify))} dictionary size: {performanceTime} seconds', None)
def getErrorMessage(clientResponse, exception=None): completeErrorMessage = f'{HttpClientConstant.ERROR_AT_CLIENT_CALL_MESSAGE}{c.DOT_SPACE}{HttpClientConstant.CLIENT_DID_NOT_SENT_ANY_MESSAGE}' errorMessage = HttpClientConstant.CLIENT_DID_NOT_SENT_ANY_MESSAGE possibleErrorMessage = None bodyAsJson = {} try : bodyAsJson = clientResponse.json() except Exception as innerException : bodyAsJsonException = FlaskUtil.safellyGetResponseJson(clientResponse) log.log(getErrorMessage, f'Invalid client response: {bodyAsJsonException}', exception=innerException) log.debug(getErrorMessage, f'Not possible to get error message from client response: {bodyAsJsonException}. Proceeding with value {bodyAsJson} by default', exception=innerException, muteStackTrace=True) try: if ObjectHelper.isNotNone(clientResponse): if ObjectHelper.isDictionary(bodyAsJson): possibleErrorMessage = bodyAsJson.get('message', bodyAsJson.get('error')).strip() if ObjectHelper.isList(bodyAsJson) and 0 < len(bodyAsJson): possibleErrorMessage = bodyAsJson[0].get('message', bodyAsJson[0].get('error')).strip() if ObjectHelper.isNotNone(possibleErrorMessage) and StringHelper.isNotBlank(possibleErrorMessage): errorMessage = f'{c.LOG_CAUSE}{possibleErrorMessage}' else: log.debug(getErrorMessage, f'Client response {FlaskUtil.safellyGetResponseJson(clientResponse)}') exceptionPortion = HttpClientConstant.ERROR_AT_CLIENT_CALL_MESSAGE if ObjectHelper.isNone(exception) or StringHelper.isBlank(exception) else str(exception) completeErrorMessage = f'{exceptionPortion}{c.DOT_SPACE}{errorMessage}' except Exception as exception: log.warning(getErrorMessage, f'Not possible to get error message. Returning {completeErrorMessage} by default', exception=exception) return completeErrorMessage
def overrideDocumentation(apiInstance): globals = apiInstance.globals documentationAsString = StringHelper.stringfyThisDictionary( apiInstance.documentation) with open(getDocumentationFilePath(apiInstance), globals.OVERRIDE, encoding=globals.ENCODING) as documentationFile: documentationFile.write(documentationAsString)
def getText(self, tag): text = StringHelper.join([ str(t) for t in tag.strings if StringHelper.isNotBlank( StringHelper.join(str(t).split(), character=c.BLANK).replace( c.SPACE, c.BLANK)) ], character=c.NEW_LINE) constant = 40 for i in range(constant): if i < constant - 1: text = text.replace( GoogleSearchConstants.TOKENT_TEXT_SEPARATOR * (constant - i), c.BLANK) else: text = text.replace( GoogleSearchConstants.TOKENT_TEXT_SEPARATOR, c.SPACE) return text
def overrideDocumentation(apiInstance): globals = apiInstance.globals try : documentationAsString = StringHelper.prettyJson(apiInstance.documentation) # with open(getDocumentationFilePath(apiInstance), globals.OVERRIDE, encoding=globals.ENCODING) as documentationFile : with open(getDocumentationFilePath(apiInstance), c.OVERRIDE, encoding=c.ENCODING) as documentationFile : documentationFile.write(documentationAsString) except Exception as exception : log.error(overrideDocumentation,"Error while overriding OpenApi documentation file",exception)
def getUrl(client, clientMethodConfig, additionalUrl): return StringHelper.join( [ ConverterStatic.getValueOrDefault(u, c.BLANK) for u in [ client.url, clientMethodConfig.url, additionalUrl ] ], character = c.BLANK )
def filterJson_withSucces(): # Arrange simpleDictionaryInstance = { 'key': 'value', 'anotherKey': { 'key': 'value' }, 'aThirdKey': [ 'a', 'b', { 'c': 'd' }, [None, True, 'True', 3.3, (2, '2')], { 'key': ('e', 'f', { 'g': { 'h': ['i', 'j'] } }) }, { 'someKey': 'someValue', 'someOtherKey': {'q', 'r', 1, 2, 3, 's'} } ] } expectedWithSpace = '''{ 'key': 'value', 'anotherKey': { 'key': 'value' }, 'aThirdKey': [ 'a', 'b', { 'c': 'd' }, [ None, True, 'True', 3.3, ( 2, '2' ) ], { 'key': ( 'e', 'f', { 'g': { 'h': [ 'i', 'j' ] } } ) }, { 'someKey': 'someValue', 'someOtherKey': { 1, 2, 3, 'q', 'r', 's' } } ] }''' expectedWithoutSpace = '''{'key':'value','anotherKey':{'key':'value'},'aThirdKey':['a','b',{'c':'d'},[None,True,'True',3.3,(2,'2')],{'key':('e','f',{'g':{'h':['i','j']}})},{'someKey':'someValue','someOtherKey':{1,2,3,'q','r','s'}}]}''' filteredJson = StringHelper.prettyPython(simpleDictionaryInstance, tabCount=1, withColors=True) # Act toAssertWithSpace = StringHelper.filterJson(filteredJson) toAssertWithoutSpace = StringHelper.filterJson(filteredJson, extraCharacterList=[' ']) # Assert toAssertWithSpace = StringHelper.removeColors(toAssertWithSpace) toAssertWithoutSpace = StringHelper.removeColors(toAssertWithoutSpace) assert expectedWithSpace == toAssertWithSpace assert expectedWithoutSpace == toAssertWithoutSpace
def findAllClassByPartialClass(self, partialClass, browser, html=None) : # print(f'partialClass: {partialClass}') # print(browser.get_attribute('innerHTML')) soup = BeautifulSoup(html if ObjectHelper.isNotNone(html) else self.getAttribute('innerHTML', browser), 'html.parser') # print(soup.prettify()) soupElementList = soup.find_all('span', attrs={'class': lambda e: partialClass in e if e else False}) # print(f'soupElementList: {soupElementList}') # from python_helper import ReflectionHelper # for soupElement in soupElementList : # print(f'type({soupElement.span}): {type(soupElement.span)}') # log.prettyPython(self.findAllClassByPartialClass, 'soupElement', ReflectionHelper.getItNaked(soupElement), logLevel=log.DEBUG) # print(soupElement.__dict__) # return [self.findByClass(str(StringHelper.join(soupElement.attrs['class'], character=c.SPACE)), browser) for soupElement in soupElementList] return [self.findByClass(str(StringHelper.join(soupElement.attrs['class'], character=c.SPACE)), browser) for soupElement in soupElementList]
def mustFilterSetting(): # Arrange expectedSingleQuoteSettingCase = 'b' singleQuoteSettingCase = f' " {expectedSingleQuoteSettingCase} " ' expectedTripleQuoteSettingCase = 'b' tripleQuoteSettingCase = f''' """ {expectedTripleQuoteSettingCase} """ ''' expectedBothCasesSingleQuoteSettingCase = 'b' bothCasesSingleQuoteSettingCase = f' " {expectedBothCasesSingleQuoteSettingCase} " ' bothCases = f''' """ {bothCasesSingleQuoteSettingCase} """ ''' someCommentsInBetween = 'b' someCommentsInBetweenSingle = f" ' {someCommentsInBetween} # ' # " someCommentsInBetweenTriple = f""" ''' {someCommentsInBetweenSingle} # ''' # """ onlyComment = Constant.HASH_TAG * 4 onlyCommentSurroundleByTriples = f'''"""{onlyComment}Something after comment token"""''' onlyCommentSetting = f'"{onlyCommentSurroundleByTriples}"' # Act filteredStringSingleQuoteSettingCase = StringHelper.filterString( singleQuoteSettingCase) filteredStringTripleQuoteSettingCase = StringHelper.filterString( tripleQuoteSettingCase) filteredStringBothCasesSingleQuoteSettingCase = StringHelper.filterString( bothCases) filteredStringSomeCommentsInBetween = StringHelper.filterString( someCommentsInBetweenTriple) filteredStringOnlyComment = StringHelper.filterString(onlyCommentSetting) # Assert assert expectedSingleQuoteSettingCase == filteredStringSingleQuoteSettingCase assert expectedTripleQuoteSettingCase == filteredStringTripleQuoteSettingCase assert expectedBothCasesSingleQuoteSettingCase == filteredStringBothCasesSingleQuoteSettingCase assert someCommentsInBetween == filteredStringSomeCommentsInBetween assert Constant.NOTHING == filteredStringOnlyComment
def buildApplicationPath(self): if ObjectHelper.isNotEmpty(self.filePath): self.currentPath = f'{str(Path(self.filePath).parent.absolute())}{EnvironmentHelper.OS_SEPARATOR}' else: self.currentPath = f'{str(Path(__file__).parent.absolute())}{EnvironmentHelper.OS_SEPARATOR}' self.log(f'{self.__class__.__name__}{c.DOT}filePath: {self.filePath}') self.log( f'{self.__class__.__name__}{c.DOT}currentPath: {self.currentPath}') self.localPath = str(Path.home()) if not self.localPath[-1] == str(EnvironmentHelper.OS_SEPARATOR): self.localPath = f'{self.localPath}{EnvironmentHelper.OS_SEPARATOR}' self.log( f'{self.__class__.__name__}{c.DOT}localPath: {self.localPath}') self.baseApiPath = Globals.BASE_API_PATH self.apiPath = self.currentPath.split(self.baseApiPath)[0] self.log(f'{self.__class__.__name__}{c.DOT}apiPath: {self.apiPath}') lastLocalPathPackage = self.localPath.split( EnvironmentHelper.OS_SEPARATOR)[-2] firstBaseApiPath = self.baseApiPath.split( EnvironmentHelper.OS_SEPARATOR)[0] lastLocalPathPackageNotFound = True self.apiPackage = c.NOTHING for currentPackage in self.currentPath.split( EnvironmentHelper.OS_SEPARATOR): if lastLocalPathPackageNotFound: if currentPackage == lastLocalPathPackage: lastLocalPathPackageNotFound = False elif not currentPackage or currentPackage == firstBaseApiPath: break else: self.apiPackage = currentPackage self.log( f'{self.__class__.__name__}{c.DOT}apiPackage: {self.apiPackage}') if StringHelper.isNotBlank(self.apiPackage): if len( self.currentPath.split(self.localPath)[1].split( self.apiPackage)) > 1: self.apisRoot = self.currentPath.split( self.localPath)[1].split(self.apiPackage)[0] self.apisPath = f'{self.currentPath.split(self.apiPackage)[0]}' else: self.apisRoot = c.NOTHING self.apisPath = c.NOTHING self.log(f'{self.__class__.__name__}{c.DOT}apisRoot: {self.apisRoot}') self.log(f'{self.__class__.__name__}{c.DOT}apisPath: {self.apisPath}')
def getDefaultBodyException(exception=None): try: bodyErrorResponse = { 'message': exception.message, 'timestamp': str(exception.timeStamp) } except: bodyErrorResponse = { 'message': DEFAULT_MESSAGE, 'timestamp': str(DateTimeHelper.now()) } uriIfAny = FlaskUtil.safellyGetPath() if ObjectHelper.isNotNone(uriIfAny) and StringHelper.isNotBlank(uriIfAny): bodyErrorResponse['uri'] = uriIfAny return bodyErrorResponse
def innerMethodWrapper(resourceInstanceMethod, *innerMethodArgs, **innerMethodKwargs): log.debug(SchedulerMethod, f'''wrapping {resourceInstanceMethod.__name__}''') apiInstance = FlaskManager.getApi() methodClassName = ReflectionHelper.getMethodClassName( resourceInstanceMethod) methodName = ReflectionHelper.getName(resourceInstanceMethod) methodKwargs['id'] = methodKwargs.get( 'id', f'{methodClassName}{c.DOT}{methodName}') instancesUpTo = methodKwargs.pop('instancesUpTo', 1) weekDays = methodKwargs.pop('weekDays', None) if ObjectHelper.isNotEmpty( methodArgs ) and SchedulerType.CRON == methodArgs[0] and ObjectHelper.isNotNone( weekDays) and StringHelper.isNotBlank(weekDays): methodKwargs['day_of_week'] = weekDays if ObjectHelper.isNotNone(instancesUpTo): methodKwargs['max_instances'] = instancesUpTo shedulerArgs = [*methodArgs] shedulerKwargs = {**methodKwargs} @apiInstance.scheduler.task(*shedulerArgs, **shedulerKwargs) def innerResourceInstanceMethod(*args, **kwargs): resourceInstanceName = methodClassName[:-len( FlaskManager.KW_SCHEDULER_RESOURCE)] resourceInstanceName = f'{resourceInstanceName[0].lower()}{resourceInstanceName[1:]}' args = FlaskManager.getArgumentInFrontOfArgs( args, ReflectionHelper.getAttributeOrMethod( apiInstance.resource.scheduler, resourceInstanceName)) resourceInstance = args[0] methodReturn = None try: FlaskManager.validateArgs(args, requestClass, innerResourceInstanceMethod) methodReturn = resourceInstanceMethod(*args, **kwargs) except Exception as exception: FlaskManager.raiseGlobalException(exception, resourceInstance, resourceInstanceMethod) log.log(innerResourceInstanceMethod, f'Not possible to run {shedulerId} properly', exception=exception) return methodReturn ReflectionHelper.overrideSignatures(innerResourceInstanceMethod, resourceInstanceMethod) return innerResourceInstanceMethod
def overrideDocumentation(apiInstance): try : documentationAsString = StringHelper.prettyJson(apiInstance.documentation) documentationFolderPath = getDocumentationFolderPath(apiInstance) documentationFilePath = getDocumentationFilePath(apiInstance) try: if not EnvironmentHelper.isDirectory(documentationFolderPath) : accessRights = 0o777 # define the access rights. write and read EnvironmentHelper.makeDirectory(documentationFolderPath, accessRights) except OSError as exception: exceptionMessage = f'Creation of the directory {documentationFilePath} failed' log.log(overrideDocumentation, exceptionMessage, exception=exception) raise Exception(exceptionMessage) with open(getDocumentationFilePath(apiInstance), c.OVERRIDE, encoding=c.ENCODING) as documentationFile : documentationFile.write(documentationAsString) except Exception as exception : log.log(overrideDocumentation,"Error while overriding OpenApi documentation file",exception) raise exception
def newApp(filePath, successStatus=True, errorStatus=True, failureStatus=True, warningStatus=True, settingStatus=True, statusStatus=True, infoStatus=True, debugStatus=False, wrapperStatus=False, testStatus=False, logStatus=False): globalsInstance = globals.newGlobalsInstance(filePath, successStatus=successStatus, errorStatus=errorStatus, failureStatus=failureStatus, settingStatus=settingStatus, statusStatus=statusStatus, infoStatus=infoStatus, debugStatus=debugStatus, warningStatus=warningStatus, wrapperStatus=wrapperStatus, testStatus=testStatus, logStatus=logStatus) try: app = globals.importResource( KW_APP, resourceModuleName=ConverterStatic.getValueOrDefault( globalsInstance.apiName, StringHelper.join(EnvironmentHelper.listDirectoryContent( f'{globalsInstance.BASE_API_PATH}')[0].split(c.DOT)[:-1], character=c.DOT)), required=True) except Exception as exception: apiPath = f'{c.DOT}{EnvironmentHelper.OS_SEPARATOR}{globalsInstance.BASE_API_PATH}{globalsInstance.apiName}.py' errorMessage = f"Not possible to load app. Make shure it's name is properlly configured at '{globalsInstance.settingFilePath}' and it's instance is named 'app' at '{apiPath}'" log.error(newApp, errorMessage, exception) raise exception if ObjectHelper.isNone(app): app = globals.importResource( KW_APP, resourceModuleName=globalsInstance.apiName) raise Exception( 'Not possible to load app. Check logs for more details') return app
def addInfo(apiInstance): globalsInstance = apiInstance.globals apiInstance.documentation[k.INFO] = { k.TITLE: ConverterStatic.getValueOrDefault( globalsInstance.getSetting(f'{KW_OPEN_API}.{KW_INFO}.{KW_TITLE}'), StringHelper.toTitle(globalsInstance.apiName)), k.DESCRIPTION: ConverterStatic.getValueOrDefault( globalsInstance.getSetting( f'{KW_OPEN_API}.{KW_INFO}.{KW_DESCRIPTION}'), f'This is a {StringHelper.toTitle(globalsInstance.apiName)} service' ), k.VERSION: globalsInstance.getSetting(f'{KW_OPEN_API}.{KW_INFO}.{KW_VERSION}'), k.TERMS_OF_SERVICE: globalsInstance.getSetting( f'{KW_OPEN_API}.{KW_INFO}.{KW_TERMS_OF_SERVICE}') } addContact(globalsInstance, apiInstance.documentation) addLisence(globalsInstance, apiInstance.documentation)
def wrapedFunction(*args, **kwargs): try: functionReturn = function(*args, **kwargs) except Exception as exception: if isinstance(exception, GlobalException): raise exception logMessage = str(exception) if StringHelper.isNotBlank( str(exception)) else LOG_MESSAGE_NOT_PRESENT functionName = ReflectionHelper.getName( function, typeName=c.TYPE_FUNCTION) log.wrapper( EncapsulateItWithGlobalException, f'''Failed to execute "{functionName}(args={args}, kwargs={kwargs})" {c.TYPE_FUNCTION} call''', exception) raise GlobalException( message=message, logMessage=logMessage, logResource=ReflectionHelper.getParentClass(function), logResourceMethod=function, status=HttpStatus.map( encapsulateItWithGlobalExceptionStatus).enumValue) return functionReturn
def getSettingTree(self, settingFilePath=None, defaultSettingFilePath=None, settingTree=None): if ObjectHelper.isEmpty(settingTree): settingTree = {} fallbackSettingFilePath = defaultSettingFilePath if not settingFilePath == defaultSettingFilePath else None if ObjectHelper.isNone(settingFilePath) or StringHelper.isBlank( settingFilePath ) or not EnvironmentHelper.OS.path.isfile(settingFilePath): self.failure( f'The "{settingFilePath}" setting file path was not found', None) return self.getSettingTree(settingFilePath=fallbackSettingFilePath, settingTree=settingTree) try: settingTree = SettingHelper.getSettingTree( settingFilePath, fallbackSettingFilePath=fallbackSettingFilePath, fallbackSettingTree=settingTree, keepDepthInLongString=True) except Exception as exception: if ObjectHelper.isNone(fallbackSettingFilePath): self.error( f'Failed to load setting tree from "{settingFilePath}" setting file path. Returning {settingTree} by default', exception) else: self.failure( f'Failed to load setting tree from "{settingFilePath}" setting file path and "{fallbackSettingFilePath}" default setting file path. Only setting file path will be loadded now', exception) try: settingTree = SettingHelper.getSettingTree( settingFilePath, keepDepthInLongString=True) except Exception as exception: self.failure( f'Failed to load setting tree from "{settingFilePath}" setting file path as well. Returning {settingTree} by default', exception) return settingTree
def isLongString_withSuccess(): # Arrange tripleSinleQuotes = f'{Constant.TRIPLE_SINGLE_QUOTE}' tripleDoubleQuotes = f'{Constant.TRIPLE_DOUBLE_QUOTE}' doubleTripleSinleQuotes = f'{2*Constant.TRIPLE_SINGLE_QUOTE}' doubleTripleDoubleQuotes = f'{2*Constant.TRIPLE_DOUBLE_QUOTE}' doubleTripleSinleAndDoubleQuotes = f"{Constant.TRIPLE_SINGLE_QUOTE}{2*Constant.TRIPLE_DOUBLE_QUOTE}{Constant.TRIPLE_SINGLE_QUOTE}" actualLongStringWithTripleSinleQuotes = f'''{Constant.TRIPLE_SINGLE_QUOTE} longSring {Constant.TRIPLE_SINGLE_QUOTE}''' actualLongStringWithTripleDoubleQuotes = f'''{Constant.TRIPLE_DOUBLE_QUOTE} longSring {Constant.TRIPLE_DOUBLE_QUOTE}''' # Act toAssertTripleSinleQuotes = StringHelper.isLongString(tripleSinleQuotes) toAssertTripleDoubleQuotes = StringHelper.isLongString(tripleDoubleQuotes) toAssertDoubleTripleSinleQuotes = StringHelper.isLongString( doubleTripleSinleQuotes) toAssertDoubleTripleDoubleQuotes = StringHelper.isLongString( doubleTripleDoubleQuotes) toAssertDoubleTripleSinleAndDoubleQuotes = StringHelper.isLongString( doubleTripleSinleAndDoubleQuotes) toAssertActualLongStringWithTripleSinleQuotes = StringHelper.isLongString( actualLongStringWithTripleSinleQuotes) toAssertActualLongStringWithTripleDoubleQuotes = StringHelper.isLongString( actualLongStringWithTripleDoubleQuotes) # Assert assert toAssertTripleSinleQuotes assert toAssertTripleDoubleQuotes assert not toAssertDoubleTripleSinleQuotes assert not toAssertDoubleTripleDoubleQuotes assert not toAssertDoubleTripleSinleAndDoubleQuotes assert not toAssertActualLongStringWithTripleSinleQuotes assert not toAssertActualLongStringWithTripleDoubleQuotes
def prettify(objectAsDict) : if ObjectHelper.isNativeClassInstance(objectAsDict) : return objectAsDict return StringHelper.prettyJson(objectAsDict)
def prettyPython_withSucces(): # Arrange simpleDictionaryInstance = {**{}, **DICTIONARY_INSTANCE} expected = '''{ 11: 'yolo', 10: 2.2, True: False, 'key': 'value', 'anotherKey': { 'key': 'value' }, 'aThirdKey': [ 'a', 'b', { 'c': 'd' }, [ None, True, 'True', 3.3, ( 2, '2' ) ], { 'key': ( 'e', 'f', { 'g': { 'h': [ 'i', 'j' ] } } ) }, { 'someKey': 'someValue', 'someOtherKey': { 1, 2, 3, 'q', 'r', 's' } } ] }'''.replace('\t', ' ') # Act toAssert = StringHelper.prettyPython(simpleDictionaryInstance, tabCount=1, withColors=True) # log.debug(prettyPython_withSucces, 'does it works ' + toAssert + ' correctly?') # Assert toAssert = StringHelper.removeColors(toAssert) assert expected == toAssert
def isNeitherNoneNorBlank(thing): return ObjectHelper.isNotNone(thing) and StringHelper.isNotBlank( str(thing))
def fromDtoToModel() : # arrange mockedDatetimeAsString = '2021-03-11 08:30:00' mockedDateAsString = mockedDatetimeAsString.split()[0] mockedTimeAsString = mockedDatetimeAsString.split()[1] instance = DateTimeTestResponseDto( beginAtDatetime = mockedDatetimeAsString, endAtDatetime = mockedDatetimeAsString, beginAtDate = mockedDateAsString, endAtDate = mockedDateAsString, beginAtTime = mockedTimeAsString, endAtTime = mockedTimeAsString, intervalTime = mockedDatetimeAsString, timedelta = mockedTimeAsString ) # log.prettyPython(fromModelToDto, 'instance', Serializer.getObjectAsDictionary(instance), logLevel=log.DEBUG) instanceList = [ instance, instance ] # act toAssert = Serializer.convertFromObjectToObject(instance, DateTimeTest) listToAssert = Serializer.convertFromObjectToObject(instanceList, [[DateTimeTest]]) # log.prettyPython(fromDtoToModel, 'toAssert', Serializer.getObjectAsDictionary(toAssert), logLevel=log.DEBUG) # log.prettyPython(fromModelToDto, 'listToAssert', Serializer.getObjectAsDictionary(listToAssert), logLevel=log.DEBUG) # assert assert ObjectHelper.isNotEmpty(toAssert) assert datetime.datetime == type(toAssert.beginAtDatetime) assert datetime.datetime == type(toAssert.endAtDatetime) assert datetime.date == type(toAssert.beginAtDate) assert datetime.date == type(toAssert.endAtDate) assert datetime.time == type(toAssert.beginAtTime) assert datetime.time == type(toAssert.endAtTime) assert datetime.datetime == type(toAssert.intervalTime) assert datetime.timedelta == type(toAssert.timedelta) assert ObjectHelper.equals( { 'beginAtDate': '2021-03-11', 'beginAtDatetime': '2021-03-11 08:30:00', 'beginAtTime': '08:30:00', 'endAtDate': '2021-03-11', 'endAtDatetime': '2021-03-11 08:30:00', 'endAtTime': '08:30:00', 'id': None, 'intervalTime': '2021-03-11 08:30:00', 'timedelta': '08:30:00' }, Serializer.getObjectAsDictionary(toAssert), ignoreKeyList = [ 'timedelta', 'registry' ] ), StringHelper.prettyPython(Serializer.getObjectAsDictionary(toAssert)) assert ObjectHelper.isNotEmpty(listToAssert) assert ObjectHelper.equals( [ { 'beginAtDate': '2021-03-11', 'beginAtDatetime': '2021-03-11 08:30:00', 'beginAtTime': '08:30:00', 'endAtDate': '2021-03-11', 'endAtDatetime': '2021-03-11 08:30:00', 'endAtTime': '08:30:00', 'id': None, 'intervalTime': '2021-03-11 08:30:00', 'timedelta': '08:30:00' }, { 'beginAtDate': '2021-03-11', 'beginAtDatetime': '2021-03-11 08:30:00', 'beginAtTime': '08:30:00', 'endAtDate': '2021-03-11', 'endAtDatetime': '2021-03-11 08:30:00', 'endAtTime': '08:30:00', 'id': None, 'intervalTime': '2021-03-11 08:30:00', 'timedelta': '08:30:00' } ], Serializer.getObjectAsDictionary(listToAssert), ignoreKeyList = [ 'timedelta', 'registry' ] )
def prettify(objectAsDict): if ObjectHelper.isNativeClassInstance(objectAsDict): return objectAsDict ###- someone please give a hint on SqlAlchemy developers on this f*****g "registry" thing... return StringHelper.prettyJson(objectAsDict, ignoreKeyList=[SQL_ALCHEMY_RESGITRY_PUBLIC_REFLECTED_ATTRIBUTE_PRETTY_MUCH_THE_WORST_CODE_I_SAW_IN_MY_LIFE] if isModel(objectAsDict) else [])
def findByClass(self, className, browser) : if c.SPACE in className : return self.findByCss(StringHelper.join([c.NOTHING, *className.split()], character=c.DOT), browser) element = browser.find_element_by_class_name(className) time.sleep(BrowserConstants.DEFAULT_WEBDRIVER_DELAY_FRACTION) return element
def getValue(soupElement, attributeName): if ObjectHelper.isNotNone(soupElement) and soupElement.has_attr( attributeName): value = soupElement[attributeName] return value if ObjectHelper.isNotList(value) else StringHelper.join( value, character=c.SPACE)
def prettyJson_withSucces(): # Arrange simpleDictionaryInstance = {**{}, **DICTIONARY_INSTANCE} expected = '''{ "11": "yolo", "10": 2.2, "true": false, "key": "value", "anotherKey": { "key": "value" }, "aThirdKey": [ "a", "b", { "c": "d" }, [ null, true, "True", 3.3, [ 2, "2" ] ], { "key": [ "e", "f", { "g": { "h": [ "i", "j" ] } } ] }, { "someKey": "someValue", "someOtherKey": [ 1, 2, 3, "q", "r", "s" ] } ] }'''.replace(Constant.SYSTEM_TAB, Constant.TAB_UNITS * Constant.SPACE) # Act toAssert = StringHelper.prettyJson(simpleDictionaryInstance, tabCount=1, withColors=True) # Assert toAssert = StringHelper.removeColors(toAssert) assert expected == toAssert
def isNoneOrBlank(thing): return ObjectHelper.isNone(thing) or StringHelper.isBlank(str(thing))
def getCompositeModuleName(resourceModuleName, resourceNameList): return StringHelper.join([resourceModuleName, *resourceNameList], character=c.DOT)
def innerMethodWrapper(resourceMethod, *innerMethodArgs, **innerMethodKwargs): log.wrapper(SchedulerMethod, f'''wrapping {resourceMethod.__name__}''') apiInstance = FlaskManager.getApi() methodClassName = ReflectionHelper.getMethodClassName(resourceMethod) methodName = ReflectionHelper.getName(resourceMethod) methodKwargs['id'] = methodKwargs.get( 'id', f'{methodClassName}{c.DOT}{methodName}') instancesUpTo = methodKwargs.pop('instancesUpTo', 1) weekDays = methodKwargs.pop('weekDays', None) resourceMethod.disabled = disable resourceMethod.shedulerId = methodKwargs['id'] resourceMethod.muteLogs = muteLogs or ConverterStatic.getValueOrDefault( apiInstance.globals.getApiSetting( ConfigurationKeyConstant.API_SCHEDULER_MUTE_LOGS), DEFAUTL_MUTE_LOGS) if ObjectHelper.isNotEmpty( methodArgs ) and SchedulerType.CRON == methodArgs[0] and ObjectHelper.isNotNone( weekDays) and StringHelper.isNotBlank(weekDays): methodKwargs['day_of_week'] = weekDays if ObjectHelper.isNotNone(instancesUpTo): methodKwargs['max_instances'] = instancesUpTo shedulerArgs = [*methodArgs] shedulerKwargs = {**methodKwargs} @apiInstance.schedulerManager.task(*shedulerArgs, **shedulerKwargs) def innerResourceInstanceMethod(*args, **kwargs): resourceInstanceName = methodClassName[:-len( FlaskManager.KW_SCHEDULER_RESOURCE)] resourceInstanceName = f'{resourceInstanceName[0].lower()}{resourceInstanceName[1:]}' args = FlaskManager.getArgumentInFrontOfArgs( args, ReflectionHelper.getAttributeOrMethod( apiInstance.resource.scheduler, resourceInstanceName)) resourceInstance = args[0] muteLogs = resourceInstance.muteLogs or resourceMethod.muteLogs if resourceInstance.enabled and not resourceInstance.disabled and not resourceMethod.disabled: if not muteLogs: log.debug( resourceMethod, f'{resourceMethod.shedulerId} scheduler started with args={methodArgs} and kwargs={methodKwargs}' ) methodReturn = None try: FlaskManager.validateArgs(args, requestClass, innerResourceInstanceMethod) methodReturn = resourceMethod(*args, **kwargs) except Exception as exception: if not muteLogs: log.warning( resourceMethod, f'Not possible to run {resourceMethod.shedulerId} properly', exception=exception, muteStackTrace=True) FlaskManager.raiseAndPersistGlobalException( exception, resourceInstance, resourceMethod) if not muteLogs: log.debug( resourceMethod, f'{resourceMethod.shedulerId} scheduler finished') return methodReturn if not muteLogs: log.warning( resourceMethod, f'{resourceMethod.shedulerId} scheduler didn{c.SINGLE_QUOTE}t started. {"Schedulers are disabled" if not resourceInstance.enabled else "This scheduler is disabled" if resourceInstance.disabled else "This scheduler method is disabled"}' ) ReflectionHelper.overrideSignatures(innerResourceInstanceMethod, resourceMethod) resourceMethod.shedulerId = methodKwargs.get('id') innerResourceInstanceMethod.disable = resourceMethodDisable innerResourceInstanceMethod.muteLogs = resourceMethodMuteLogs return innerResourceInstanceMethod