def apiKeyManager_worksProperly(): # arrange SECRET = 'abcd' SESSION_DURATION = 10 + 360 ALGORITHM = 'HS256' HEADER_NAME = 'Context' HEADER_TYPE = 'ApiKey ' IDENTITY = RandomHelper.string(minimum=100, maximum=150) CONTEXT = 'ABCD' CONTEXT_LIST = [CONTEXT] DATA = {'personal': 'data'} deltaMinutes = DateTimeHelper.timeDelta(minutes=SESSION_DURATION) apiKeyManager = ApiKeyManager.JwtManager(SECRET, ALGORITHM, HEADER_NAME, HEADER_TYPE) timeNow = DateTimeHelper.dateTimeNow() payload = { JwtConstant.KW_IAT: timeNow, JwtConstant.KW_NFB: timeNow, JwtConstant.KW_JTI: f"{int(f'{time.time()}'.replace('.', ''))+int(f'{time.time()}'.replace('.', ''))}", JwtConstant.KW_EXPIRATION: timeNow + deltaMinutes, JwtConstant.KW_IDENTITY: IDENTITY, JwtConstant.KW_FRESH: False, JwtConstant.KW_TYPE: JwtConstant.ACCESS_VALUE_TYPE, JwtConstant.KW_CLAIMS: { JwtConstant.KW_CONTEXT: CONTEXT_LIST, JwtConstant.KW_DATA: DATA } } # act totalRuns = 10000 lines = 3 initTime = time.time() for i in range(totalRuns): encodedPayload = apiKeyManager.encode(payload) decodedPayload = apiKeyManager.decode(encodedPayload) accessException = TestHelper.getRaisedException( apiKeyManager.validateAccessApiKey, rawJwt=decodedPayload) refreshException = TestHelper.getRaisedException( apiKeyManager.validateRefreshApiKey, rawJwt=decodedPayload) endTime = time.time() - initTime # assert assert lines * .0001 > endTime / totalRuns, (lines * .0001, endTime / totalRuns) assert ObjectHelper.equals(payload, decodedPayload), (payload, decodedPayload) assert ObjectHelper.isNone(accessException), accessException assert ObjectHelper.isNotNone(refreshException), refreshException assert ObjectHelper.equals( GlobalException.__name__, type(refreshException).__name__), (GlobalException.__name__, type(refreshException).__name__, refreshException) assert ObjectHelper.equals(401, refreshException.status) assert ObjectHelper.equals('Invalid apiKey', refreshException.message) assert ObjectHelper.equals( 'Refresh apiKey should have type refresh, but it is access', refreshException.logMessage)
def appRun_whenEnvironmentIsLocalFromDevConfig_withSuccess(): # arrange muteLogs = False serverPort = 5002 process = getProcess( f'flask run --host=localhost --port={serverPort}', f'{CURRENT_PATH}{EnvironmentHelper.OS_SEPARATOR}apitests{EnvironmentHelper.OS_SEPARATOR}testone', muteLogs=muteLogs) BASE_URL = f'http://localhost:{serverPort}/dev-test-api' time.sleep(ESTIMATED_BUILD_TIME_IN_SECONDS) headers = { "User-Agent": "Mozilla/5.0 (X11; CrOS x86_64 12871.102.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.141 Safari/537.36", 'Cache-Control': 'no-cache' } # act responseGetHealth = requests.post(BASE_URL + GET_ACTUATOR_HEALTH_CONTROLLER_TEST, json={'status': 'UP'}) # assert assert ObjectHelper.equals([{'status': 'UP'}], responseGetHealth.json()) assert 200 == responseGetHealth.status_code killProcesses(process)
def jsonifyIt() : assert '{"myString": "myValue", "myInteger": 0, "myFloat": 0.099}' == Serializer.jsonifyIt(MY_DICTIONARY) myGenerator = generatorFunction() assert myGenerator == Serializer.jsonifyIt(myGenerator) assert '{"myAttribute": null, "myNeutralAttribute": "someString"}' == Serializer.jsonifyIt(MyClass()) assert ObjectHelper.equals('{"id": null}', Serializer.jsonifyIt(MyEntityClass()), ignoreKeyList=['registry']) father = Father() child = Child() brother = Brother() otherFather = Father() otherBrother = Brother() otherChild = Child() father.id = 1 child.id = 2 brother.id = 3 otherFather.id = 4 otherBrother.id = 5 otherChild.id = 6 father.childList = [child, otherChild] father.brotherList = [otherBrother] child.father = father child.fatherId = father.id child.brother = brother child.brotherId = brother.id brother.father = otherFather brother.fatherId = otherFather.id brother.child = child otherFather.childList = [] otherFather.brotherList = [brother] otherBrother.father = father otherBrother.fatherId = father.id otherBrother.child = otherChild otherChild.father = father otherChild.fatherId = father.id otherChild.brother = otherBrother otherChild.brotherId = otherBrother.id assert '{"brother": {"child": null, "father": {"brotherList": [], "childList": [], "id": 4}, "fatherId": 4, "id": 3}, "brotherId": 3, "father": {"brotherList": [{"child": {"brother": null, "brotherId": 5, "father": null, "fatherId": 1, "id": 6}, "father": null, "fatherId": 1, "id": 5}], "childList": [{"brother": {"child": null, "father": null, "fatherId": 1, "id": 5}, "brotherId": 5, "father": null, "fatherId": 1, "id": 6}], "id": 1}, "fatherId": 1, "id": 2}' == Serializer.jsonifyIt(child) assert '{"brotherList": [{"child": {"brother": null, "brotherId": 5, "father": null, "fatherId": 1, "id": 6}, "father": null, "fatherId": 1, "id": 5}], "childList": [{"brother": {"child": null, "father": {"brotherList": [], "childList": [], "id": 4}, "fatherId": 4, "id": 3}, "brotherId": 3, "father": null, "fatherId": 1, "id": 2}, {"brother": {"child": null, "father": null, "fatherId": 1, "id": 5}, "brotherId": 5, "father": null, "fatherId": 1, "id": 6}], "id": 1}' == Serializer.jsonifyIt(father) myClass = MyClass() myAttributeClass = MyAttributeClass(myClass=myClass) myClass.myAttribute = myAttributeClass assert '{"myAttribute": {"myClass": null, "myNeutralClassAttribute": "someOtherString"}, "myNeutralAttribute": "someString"}' == Serializer.jsonifyIt(myClass) assert '{"myClass": {"myAttribute": null, "myNeutralAttribute": "someString"}, "myNeutralClassAttribute": "someOtherString"}' == Serializer.jsonifyIt(myClass.myAttribute)
def mustIgnoreKeyCorrectly(): # arrange expected = {**{}, **DICTIONARY_INSTANCE} anotherDictionaryInstance = {**{}, **DICTIONARY_INSTANCE} IGNORABLE_KEY = 'ignorableKey' anotherDictionaryInstance[IGNORABLE_KEY] = 'ignorableValue' # act toAssert = ObjectHelper.filterIgnoreKeyList(anotherDictionaryInstance, [IGNORABLE_KEY]) # assert assert ObjectHelper.equals(expected, toAssert)
def convertFromObjectToObject_whenTargetClassIsList() : # arrange a = RandomHelper.string() b = RandomHelper.string() c = RandomHelper.string() otherA = MyOtherDto(RandomHelper.string()) otherB = MyOtherDto(RandomHelper.string()) otherC = MyOtherDto(RandomHelper.string()) myFirst = MyDto(RandomHelper.string(), otherA, [MyThirdDto(MyDto(RandomHelper.string(), MyOtherDto(RandomHelper.string()), [MyThirdDto(MyDto(RandomHelper.string(), MyOtherDto(RandomHelper.string()), [MyThirdDto(MyDto(RandomHelper.string(), MyOtherDto(RandomHelper.string()), [MyThirdDto(MyDto(RandomHelper.string(), MyOtherDto(RandomHelper.string()), None), RandomHelper.integer())]), RandomHelper.integer())]), RandomHelper.integer())]), RandomHelper.integer())]) mySecond = MyDto(RandomHelper.string(), otherB, [MyThirdDto(MyDto(RandomHelper.string(), MyOtherDto(RandomHelper.string()), [MyThirdDto(MyDto(RandomHelper.string(), MyOtherDto(RandomHelper.string()), [MyThirdDto(MyDto(RandomHelper.string(), MyOtherDto(RandomHelper.string()), [MyThirdDto(MyDto(RandomHelper.string(), MyOtherDto(RandomHelper.string()), None), RandomHelper.integer())]), RandomHelper.integer())]), RandomHelper.integer())]), RandomHelper.integer())]) myThird = MyDto(RandomHelper.string(), otherC, [MyThirdDto(MyDto(RandomHelper.string(), MyOtherDto(RandomHelper.string()), [MyThirdDto(MyDto(RandomHelper.string(), MyOtherDto(RandomHelper.string()), [MyThirdDto(MyDto(RandomHelper.string(), MyOtherDto(RandomHelper.string()), [MyThirdDto(MyDto(RandomHelper.string(), MyOtherDto(RandomHelper.string()), None), RandomHelper.integer())]), RandomHelper.integer())]), RandomHelper.integer())]), RandomHelper.integer())]) thirdOne = RandomHelper.integer() thirdTwo = RandomHelper.integer() thirdThree = RandomHelper.integer() myThirdOne = [MyThirdDto(myFirst, thirdOne)] myThirdTwo = [MyThirdDto(mySecond, thirdTwo)] myThirdThree = [MyThirdDto(myThird, thirdThree)] expected = [MyDto(a, otherA, myThirdOne), MyDto(b, otherB, myThirdTwo), MyDto(c, otherC, myThirdThree)] null = 'null' inspectEquals = False # act toAssert = Serializer.convertFromObjectToObject(expected, [[MyDto]]) another = Serializer.convertFromObjectToObject([MyDto(a, otherA, [MyThirdDto(myFirst, thirdOne)]), MyDto(b, otherB, myThirdTwo), MyDto(c, otherC, myThirdThree)], [[MyDto]]) another[0].myThirdList[0].my.myThirdList[0].my.myThirdList[0].my.myThirdList[0].my.myThirdList[0].my = MyDto( MyDto(RandomHelper.string(), None, None), expected[0].myThirdList[0].my.myOther, expected[0].myThirdList[0].my.myThirdList ) # assert assert expected == toAssert, f'{expected} == {toAssert}: {expected == toAssert}' assert ObjectHelper.equals(expected, toAssert) assert ObjectHelper.isNotNone(expected[0].myThirdList[0].my.myThirdList[0].my.myThirdList[0].my.myThirdList[0].my.myThirdList[0].my) assert expected[0].myThirdList[0].my.myThirdList[0].my.myThirdList[0].my.myThirdList[0].my.myThirdList[0].my == toAssert[0].myThirdList[0].my.myThirdList[0].my.myThirdList[0].my.myThirdList[0].my.myThirdList[0].my assert ObjectHelper.equals(expected[0].myThirdList[0].my.myThirdList[0].my.myThirdList[0].my.myThirdList[0].my.myThirdList[0].my, toAssert[0].myThirdList[0].my.myThirdList[0].my.myThirdList[0].my.myThirdList[0].my.myThirdList[0].my) assert ObjectHelper.isNone(expected[0].myThirdList[0].my.myThirdList[0].my.myThirdList[0].my.myThirdList[0].my.myThirdList[0].my.myThirdList) assert ObjectHelper.equals(expected[0].myThirdList[0].my.myThirdList[0].my.myThirdList[0].my.myThirdList[0].my.myThirdList[0].my.myThirdList, toAssert[0].myThirdList[0].my.myThirdList[0].my.myThirdList[0].my.myThirdList[0].my.myThirdList[0].my.myThirdList) assert ObjectHelper.equals(json.loads(Serializer.jsonifyIt(expected)), json.loads(Serializer.jsonifyIt(toAssert))), f'ObjectHelper.equals({json.loads(Serializer.jsonifyIt(expected))},\n\n{json.loads(Serializer.jsonifyIt(toAssert))})' assert False == (expected == another), f'False == ({expected} == {another}): False == {(expected == another)}' assert False == ObjectHelper.equals(expected, another, muteLogs=not inspectEquals) assert False == ObjectHelper.equals(another, expected, muteLogs=not inspectEquals) assert False == ObjectHelper.equals(another, toAssert, muteLogs=not inspectEquals) assert False == ObjectHelper.equals(toAssert, another, muteLogs=not inspectEquals) assert str(expected) == str(toAssert), f'str({str(expected)}) == str({str(toAssert)}): {str(expected) == str(toAssert)}'
def testing_Client(): #arrange muteLogs = False serverPort = 5010 process = getProcess( f'flask run --host=localhost --port={serverPort}', f'{CURRENT_PATH}{EnvironmentHelper.OS_SEPARATOR}apitests{EnvironmentHelper.OS_SEPARATOR}testone', muteLogs=muteLogs) log.debug(log.debug, f'variant: {EnvironmentHelper.get("URL_VARIANT")}') BASE_URL = f'http://localhost:{serverPort}/local-test-api' params = { 'first': 'first_p', 'second': 'second_p', 'ytu': 'uty', 'ytv': 'vty' } headers = { "User-Agent": "Mozilla/5.0 (X11; CrOS x86_64 12871.102.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.141 Safari/537.36", 'Cache-Control': 'no-cache', "Pragma": 'no-cache', 'Expires': '0', 'Cache-Control': 'public, max-age=0' } headers = { 'firstHeader': 'firstHeader_h', 'secondHeader': 'secondHeader_h', 'ytu': 'uty', 'ytv': 'vty', **headers } log.debug(log.debug, f'variant: {EnvironmentHelper.get("URL_VARIANT")}') time.sleep(ESTIMATED_BUILD_TIME_IN_SECONDS) #act responseComplete = requests.get( BASE_URL + f'/test/actuator/health/{EnvironmentHelper.get("URL_VARIANT")}/abcdef/oi', params=params, headers=headers) responseWithoutParams = requests.get( BASE_URL + f'/test/actuator/health/{EnvironmentHelper.get("URL_VARIANT")}/abcdef/oi', headers=headers) responseWithoutHeaders = requests.get( BASE_URL + f'/test/actuator/health/{EnvironmentHelper.get("URL_VARIANT")}/abcdef/oi', params=params) responseWithoutHeadersAndWithoutParams = requests.get( BASE_URL + f'/test/actuator/health/{EnvironmentHelper.get("URL_VARIANT")}/abcdef/oi' ) log.debug(log.debug, f'variant: {EnvironmentHelper.get("URL_VARIANT")}') #assert assert ObjectHelper.equals( { "first": "first_p", "firstHeader": "firstHeader_h", "second": "second_p", "secondHeader": "secondHeader_h", "status": "abcdefoi" }, responseComplete.json()) assert 200 == responseComplete.status_code assert ObjectHelper.equals( { "first": None, "firstHeader": "firstHeader_h", "second": None, "secondHeader": "secondHeader_h", "status": "abcdefoi" }, responseWithoutParams.json()) assert 200 == responseWithoutParams.status_code assert ObjectHelper.equals( { "first": "first_p", "firstHeader": None, "second": "second_p", "secondHeader": None, "status": "abcdefoi" }, responseWithoutHeaders.json()) assert 200 == responseWithoutHeaders.status_code assert ObjectHelper.equals( { "first": None, "firstHeader": None, "second": None, "secondHeader": None, "status": "abcdefoi" }, responseWithoutHeadersAndWithoutParams.json()) assert 200 == responseWithoutHeadersAndWithoutParams.status_code log.debug(log.debug, f'variant: {EnvironmentHelper.get("URL_VARIANT")}') killProcesses(process)
def appRun_whenEnvironmentIsLocalFromLocalConfig_withSuccess(): # arrange muteLogs = False serverPort = 5001 process = getProcess( f'flask run --host=localhost --port={serverPort}', f'{CURRENT_PATH}{EnvironmentHelper.OS_SEPARATOR}apitests{EnvironmentHelper.OS_SEPARATOR}testone', muteLogs=muteLogs) BASE_URL = f'http://localhost:{serverPort}/local-test-api' payload = {'me': 'and you'} payloadList = [payload] time.sleep(ESTIMATED_BUILD_TIME_IN_SECONDS) # act headers = { "User-Agent": "Mozilla/5.0 (X11; CrOS x86_64 12871.102.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.141 Safari/537.36", 'Cache-Control': 'no-cache' } session = requests.Session() responseGetHealth = session.get(BASE_URL + GET_ACTUATOR_HEALTH_CONTROLLER, headers=headers) responseGetNone = session.get(BASE_URL + GET_NONE_ONE) responseGetNoneBatch = session.post(BASE_URL + GET_NONE_ONE_BATCH, json=payload, headers=headers) responsePostSendPayload = session.post(BASE_URL + POST_PAYLOAD_ONE, json=payload, headers=headers) responsePostSendPayloadList = session.post(BASE_URL + POST_PAYLOAD_ONE, json=payloadList, headers=headers) responsePostSendPayloadBatch = session.post(BASE_URL + POST_PAYLOAD_ONE_BATCH, json=payload, headers=headers) responsePostSendPayloadListBatch = session.post(BASE_URL + POST_PAYLOAD_ONE_BATCH, json=payloadList, headers=headers) # print(requests.get('https://www.google.com/search?q=something&rlz=1C1GCEU_pt-BRBR884BR884&oq=something&aqs=chrome..69i57.5839j0j7&sourceid=chrome&ie=UTF-8')) # print(requests.get('https://www.google.com/search?q=something+else&rlz=1C1GCEU_pt-BRBR884BR884&sxsrf=ALeKk03rn_R9yREVJSkMqIUeAJfmFMVSfA%3A1619326195697&ei=8_SEYNWPKsGn5OUPobip-AQ&oq=something+else&gs_lcp=Cgdnd3Mtd2l6EAMyBQgAEJECMgUIABDLATIFCC4QywEyBQgAEMsBMgUILhDLATIFCC4QywEyBQgAEMsBMgUILhDLATICCAAyBQgAEMsBOgcIABBHELADOgcIABCwAxBDOg0ILhCwAxDIAxBDEJMCOgoILhCwAxDIAxBDOgIILjoHCAAQChDLAUoFCDgSATFQr_wLWPyCDGDdigxoAXACeACAAZYBiAGiBpIBAzAuNpgBAKABAaoBB2d3cy13aXrIAQ_AAQE&sclient=gws-wiz&ved=0ahUKEwiV1a2VzJjwAhXBE7kGHSFcCk8Q4dUDCA4&uact=5')) # print(f'responseGetNone: {responseGetNone.json()}') # print(f'responseGetNoneBatch: {responseGetNoneBatch.json()}') # # print(f'responsePostSendPayload: {responsePostSendPayload.json()}') # print(f'responsePostSendPayloadList: {responsePostSendPayloadList.json()}') # print(f'responsePostSendPayloadBatch: {responsePostSendPayloadBatch.json()}') # print(f'responsePostSendPayloadListBatch: {responsePostSendPayloadListBatch.json()}') # assert assert ObjectHelper.equals({'status': 'UP'}, responseGetHealth.json()) assert 200 == responseGetHealth.status_code {'message': 'OK'} { 'message': 'Something bad happened. Please, try again later', 'timestamp': '2021-03-18 21:43:47.299735' } {'message': 'Bad request', 'timestamp': '2021-03-18 21:43:47.405736'} {'me': 'and you'} { 'message': 'Something bad happened. Please, try again later', 'timestamp': '2021-03-18 21:43:47.636759' } {'message': 'Bad request', 'timestamp': '2021-03-18 21:43:47.767735'} # print(f'responseGetNone: {responseGetNone.json()}') assert ObjectHelper.equals({'message': 'OK'}, responseGetNone.json()) assert 200 == responseGetNone.status_code # print(f'responseGetNoneBatch: {responseGetNoneBatch.json()}') assert ObjectHelper.equals( { 'message': 'Something bad happened. Please, try again later', 'timestamp': '2021-03-18 21:43:47.299735' }, responseGetNoneBatch.json(), ignoreKeyList=['timestamp']) assert 500 == responseGetNoneBatch.status_code # print(f'responsePostSendPayload: {responsePostSendPayload.json()}') assert ObjectHelper.equals( { 'message': 'Bad request', 'timestamp': '2021-03-18 21:43:47.405736' }, responsePostSendPayload.json(), ignoreKeyList=['timestamp']) assert 400 == responsePostSendPayload.status_code # print(f'responsePostSendPayloadList: {responsePostSendPayloadList.json()}') assert ObjectHelper.equals( { 'message': 'Something bad happened. Please, try again later', 'timestamp': '2021-03-19 08:36:20.925177' }, responsePostSendPayloadList.json(), ignoreKeyList=['timestamp']) assert 500 == responsePostSendPayloadList.status_code assert ObjectHelper.equals( { 'message': 'Something bad happened. Please, try again later', 'timestamp': '2021-03-18 21:43:47.636759' }, responsePostSendPayloadBatch.json(), ignoreKeyList=['timestamp']) assert 500 == responsePostSendPayloadBatch.status_code assert ObjectHelper.equals( { 'message': 'Bad request', 'timestamp': '2021-03-18 21:43:47.767735' }, responsePostSendPayloadListBatch.json(), ignoreKeyList=['timestamp']) assert 400 == responsePostSendPayloadListBatch.status_code killProcesses(process)
def convertFromJsonToObject_whenThereAreEnums() : # arrange jsonToConvert = [ { "beginAtDate": "2021-03-11", "beginAtTime": "08:00:00", "endAtDate": "2021-03-11", "endAtTime": "09:00:00", "hoster": "Tati", "service": "teams", "url": "https://teams.microsoft.com/dl/launcher/launcher.html?url=%2F_%23%2Fl%2Fmeetup-join%2F19%3Ameeting_Y2Q1MWI1MWMtOWE0YS00OWJkLTkxNGMtYWMxNDczNTgxYTlj%40thread.v2%2F0%3Fcontext%3D%257b%2522Tid%2522%253a%2522b8329613-0680-4673-a03f-9a18a0b0e93b%2522%252c%2522Oid%2522%253a%2522fcb6e799-c1f0-4556-be74-3302ea89c13d%2522%257d%26anon%3Dtrue&type=meetup-join&deeplinkId=98d55d14-abc6-4abf-a4a8-5af45024d137&directDl=true&msLaunch=true&enableMobilePage=true&suppressPrompt=true" }, { "beginAtDate": "2021-03-11", "beginAtTime": "14:00:00", "endAtDate": "2021-03-11", "endAtTime": "15:00:00", "hoster": "Cristiano / Tati", "note": "Alinhamento Desmarcação", "service": "teams", "url": "https://teams.microsoft.com/l/meetup-join/19%3ameeting_YzQ3YTY1ZWUtYzg4Ny00NDg1LTkwNGEtYTBhYmNhM2RjOWZi%40thread.v2/0?context=%7b%22Tid%22%3a%22647631af-8bf8-4048-a98f-b1fbee134a6d%22%2c%22Oid%22%3a%22be78d394-2f08-4059-bee9-97b849e03cdb%22%7d" }, { "beginAtDate": "2021-03-16", "beginAtTime": "10:00:00", "endAtDate": "2021-03-16", "endAtTime": "11:00:00", "hoster": "Riachuelo", "note": "Daily Riachuelo - Terça", "type": "DAILY", "url": "https://teams.microsoft.com/l/meetup-join/19%3ameeting_MmQ5ZjliYmQtZDZhYi00MjkwLWE2NGMtOWIxMmUzYzZhYjFh%40thread.v2/0?context=%7b%22Tid%22%3a%22b8329613-0680-4673-a03f-9a18a0b0e93b%22%2c%22Oid%22%3a%22fcb6e799-c1f0-4556-be74-3302ea89c13d%22%7d" }, { "beginAtDate": "2021-03-10", "beginAtTime": "10:00:00", "endAtDate": "2021-03-10", "endAtTime": "11:00:00", "hoster": "Riachuelo", "note": "Daily Riachuelo - Quarda", "type": "DAILY", "url": "https://teams.microsoft.com/l/meetup-join/19%3ameeting_MmQ5ZjliYmQtZDZhYi00MjkwLWE2NGMtOWIxMmUzYzZhYjFh%40thread.v2/0?context=%7b%22Tid%22%3a%22b8329613-0680-4673-a03f-9a18a0b0e93b%22%2c%22Oid%22%3a%22fcb6e799-c1f0-4556-be74-3302ea89c13d%22%7d" }, { "beginAtDate": "2021-03-12", "beginAtTime": "10:00:00", "endAtDate": "2021-03-12", "endAtTime": "11:00:00", "hoster": "Riachuelo", "note": "Daily Riachuelo - Sexta", "type": "DAILY", "url": "https://teams.microsoft.com/l/meetup-join/19%3ameeting_MmQ5ZjliYmQtZDZhYi00MjkwLWE2NGMtOWIxMmUzYzZhYjFh%40thread.v2/0?context=%7b%22Tid%22%3a%22b8329613-0680-4673-a03f-9a18a0b0e93b%22%2c%22Oid%22%3a%22fcb6e799-c1f0-4556-be74-3302ea89c13d%22%7d" }, { "beginAtDate": "2021-03-15", "beginAtTime": "15:00:00", "endAtDate": "2021-03-15", "endAtTime": "16:00:00", "hoster": "Riachuelo", "note": "Daily Riachuelo - Segunda", "type": "DAILY", "url": "https://teams.microsoft.com/l/meetup-join/19%3ameeting_ZDZmMGUzY2UtZWQzZS00NDQ3LWEwZDMtMzc0MzQwYjYxNWQ1%40thread.v2/0?context=%7b%22Tid%22%3a%22b8329613-0680-4673-a03f-9a18a0b0e93b%22%2c%22Oid%22%3a%22fcb6e799-c1f0-4556-be74-3302ea89c13d%22%7d" }, { "beginAtDate": "2021-03-11", "beginAtTime": "17:30:00", "endAtDate": "2021-03-11", "endAtTime": "18:30:00", "hoster": "Riachuelo", "note": "Daily Riachuelo - Quinta", "type": "DAILY", "url": "https://teams.microsoft.com/l/meetup-join/19%3ameeting_Y2Q1MWI1MWMtOWE0YS00OWJkLTkxNGMtYWMxNDczNTgxYTlj%40thread.v2/0?context=%7b%22Tid%22%3a%22b8329613-0680-4673-a03f-9a18a0b0e93b%22%2c%22Oid%22%3a%22fcb6e799-c1f0-4556-be74-3302ea89c13d%22%7d" }, { "beginAtDate": "2021-03-18", "beginAtTime": "11:00:00", "endAtDate": "2021-03-18", "endAtTime": "12:00:00", "hoster": "Hoffmann", "note": "CWI - Trimestral", "service": "meet", "url": "https://teams.microsoft.com/l/meetup-join/19%3ameeting_Y2Q1MWI1MWMtOWE0YS00OWJkLTkxNGMtYWMxNDczNTgxYTlj%40thread.v2/0?context=%7b%22Tid%22%3a%22b8329613-0680-4673-a03f-9a18a0b0e93b%22%2c%22Oid%22%3a%22fcb6e799-c1f0-4556-be74-3302ea89c13d%22%7d" } ] # act toAssert = Serializer.convertFromJsonToObject(jsonToConvert, [[TestCallRequestDto]]) # assert # print(Serializer.prettify(Serializer.getObjectAsDictionary(toAssert))) assert 'meet' == CallServiceName.CallServiceName.map('meet') assert 'zoom' == CallServiceName.CallServiceName.map('zoom') assert 'teams' == CallServiceName.CallServiceName.map('teams') assert 'UNIQUE' == CallType.CallType.map('UNIQUE') assert 'DAILY' == CallType.CallType.map('DAILY') assert 'INCOMMING' == CallStatus.CallStatus.map('INCOMMING') assert 'WASTED' == CallStatus.CallStatus.map('WASTED') assert ObjectHelper.equals( [ { "beginAtDate": "2021-03-11", "beginAtTime": "08:00:00", "endAtDate": "2021-03-11", "endAtTime": "09:00:00", "hoster": "Tati", "note": None, "service": "teams", "status": None, "type": None, "url": "https://teams.microsoft.com/dl/launcher/launcher.html?url=%2F_%23%2Fl%2Fmeetup-join%2F19%3Ameeting_Y2Q1MWI1MWMtOWE0YS00OWJkLTkxNGMtYWMxNDczNTgxYTlj%40thread.v2%2F0%3Fcontext%3D%257b%2522Tid%2522%253a%2522b8329613-0680-4673-a03f-9a18a0b0e93b%2522%252c%2522Oid%2522%253a%2522fcb6e799-c1f0-4556-be74-3302ea89c13d%2522%257d%26anon%3Dtrue&type=meetup-join&deeplinkId=98d55d14-abc6-4abf-a4a8-5af45024d137&directDl=true&msLaunch=true&enableMobilePage=true&suppressPrompt=true" }, { "beginAtDate": "2021-03-11", "beginAtTime": "14:00:00", "endAtDate": "2021-03-11", "endAtTime": "15:00:00", "hoster": "Cristiano / Tati", "note": "Alinhamento Desmarcação", "service": "teams", "status": None, "type": None, "url": "https://teams.microsoft.com/l/meetup-join/19%3ameeting_YzQ3YTY1ZWUtYzg4Ny00NDg1LTkwNGEtYTBhYmNhM2RjOWZi%40thread.v2/0?context=%7b%22Tid%22%3a%22647631af-8bf8-4048-a98f-b1fbee134a6d%22%2c%22Oid%22%3a%22be78d394-2f08-4059-bee9-97b849e03cdb%22%7d" }, { "beginAtDate": "2021-03-16", "beginAtTime": "10:00:00", "endAtDate": "2021-03-16", "endAtTime": "11:00:00", "hoster": "Riachuelo", "note": "Daily Riachuelo - Terça", "service": None, "status": None, "type": "DAILY", "url": "https://teams.microsoft.com/l/meetup-join/19%3ameeting_MmQ5ZjliYmQtZDZhYi00MjkwLWE2NGMtOWIxMmUzYzZhYjFh%40thread.v2/0?context=%7b%22Tid%22%3a%22b8329613-0680-4673-a03f-9a18a0b0e93b%22%2c%22Oid%22%3a%22fcb6e799-c1f0-4556-be74-3302ea89c13d%22%7d" }, { "beginAtDate": "2021-03-10", "beginAtTime": "10:00:00", "endAtDate": "2021-03-10", "endAtTime": "11:00:00", "hoster": "Riachuelo", "note": "Daily Riachuelo - Quarda", "service": None, "status": None, "type": "DAILY", "url": "https://teams.microsoft.com/l/meetup-join/19%3ameeting_MmQ5ZjliYmQtZDZhYi00MjkwLWE2NGMtOWIxMmUzYzZhYjFh%40thread.v2/0?context=%7b%22Tid%22%3a%22b8329613-0680-4673-a03f-9a18a0b0e93b%22%2c%22Oid%22%3a%22fcb6e799-c1f0-4556-be74-3302ea89c13d%22%7d" }, { "beginAtDate": "2021-03-12", "beginAtTime": "10:00:00", "endAtDate": "2021-03-12", "endAtTime": "11:00:00", "hoster": "Riachuelo", "note": "Daily Riachuelo - Sexta", "service": None, "status": None, "type": "DAILY", "url": "https://teams.microsoft.com/l/meetup-join/19%3ameeting_MmQ5ZjliYmQtZDZhYi00MjkwLWE2NGMtOWIxMmUzYzZhYjFh%40thread.v2/0?context=%7b%22Tid%22%3a%22b8329613-0680-4673-a03f-9a18a0b0e93b%22%2c%22Oid%22%3a%22fcb6e799-c1f0-4556-be74-3302ea89c13d%22%7d" }, { "beginAtDate": "2021-03-15", "beginAtTime": "15:00:00", "endAtDate": "2021-03-15", "endAtTime": "16:00:00", "hoster": "Riachuelo", "note": "Daily Riachuelo - Segunda", "service": None, "status": None, "type": "DAILY", "url": "https://teams.microsoft.com/l/meetup-join/19%3ameeting_ZDZmMGUzY2UtZWQzZS00NDQ3LWEwZDMtMzc0MzQwYjYxNWQ1%40thread.v2/0?context=%7b%22Tid%22%3a%22b8329613-0680-4673-a03f-9a18a0b0e93b%22%2c%22Oid%22%3a%22fcb6e799-c1f0-4556-be74-3302ea89c13d%22%7d" }, { "beginAtDate": "2021-03-11", "beginAtTime": "17:30:00", "endAtDate": "2021-03-11", "endAtTime": "18:30:00", "hoster": "Riachuelo", "note": "Daily Riachuelo - Quinta", "service": None, "status": None, "type": "DAILY", "url": "https://teams.microsoft.com/l/meetup-join/19%3ameeting_Y2Q1MWI1MWMtOWE0YS00OWJkLTkxNGMtYWMxNDczNTgxYTlj%40thread.v2/0?context=%7b%22Tid%22%3a%22b8329613-0680-4673-a03f-9a18a0b0e93b%22%2c%22Oid%22%3a%22fcb6e799-c1f0-4556-be74-3302ea89c13d%22%7d" }, { "beginAtDate": "2021-03-18", "beginAtTime": "11:00:00", "endAtDate": "2021-03-18", "endAtTime": "12:00:00", "hoster": "Hoffmann", "note": "CWI - Trimestral", "service": "meet", "status": None, "type": None, "url": "https://teams.microsoft.com/l/meetup-join/19%3ameeting_Y2Q1MWI1MWMtOWE0YS00OWJkLTkxNGMtYWMxNDczNTgxYTlj%40thread.v2/0?context=%7b%22Tid%22%3a%22b8329613-0680-4673-a03f-9a18a0b0e93b%22%2c%22Oid%22%3a%22fcb6e799-c1f0-4556-be74-3302ea89c13d%22%7d" } ], Serializer.getObjectAsDictionary(toAssert) )
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' ] ) 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' ] )
def equal_whenObjects(): # arrange a = RandomHelper.string() b = RandomHelper.string() c = RandomHelper.string() otherA = MyOtherDto(RandomHelper.string()) otherB = MyOtherDto(RandomHelper.string()) otherC = MyOtherDto(RandomHelper.string()) myFirst = MyDto(None, None, None) mySecond = MyDto(None, None, None) myThird = MyDto(None, None, None) thirdOne = RandomHelper.integer() thirdTwo = RandomHelper.integer() thirdThree = RandomHelper.integer() myThirdOne = [MyThirdDto(myFirst, thirdOne)] myThirdTwo = [MyThirdDto(mySecond, thirdTwo)] myThirdThree = [MyThirdDto(myThird, thirdThree)] expected = [ MyDto(a, otherA, myThirdOne), MyDto(b, otherB, myThirdTwo), MyDto(c, otherC, myThirdThree) ] null = 'null' inspectEquals = False # act toAssert = [ MyDto(a, otherA, myThirdOne), MyDto(b, otherB, myThirdTwo), MyDto(c, otherC, myThirdThree) ] another = [ MyDto(a, otherA, [MyThirdDto(myFirst, thirdOne)]), MyDto(b, otherB, myThirdTwo), MyDto(c, otherC, myThirdThree) ] another[0].myThirdList[0].my = MyDto( MyDto(None, None, None), expected[0].myThirdList[0].my.myOther, expected[0].myThirdList[0].my.myThirdList) # assert assert False == ( expected == toAssert ), f'False == ({expected} == {toAssert}): {False == (expected == toAssert)}' assert ObjectHelper.equals(expected, toAssert) assert ObjectHelper.equals(toAssert, expected) assert ObjectHelper.isNotNone( expected[0].myThirdList[0].my), expected[0].myThirdList[0].my assert expected[0].myThirdList[0].my == toAssert[0].myThirdList[0].my assert ObjectHelper.equals(expected[0].myThirdList[0].my, toAssert[0].myThirdList[0].my) assert ObjectHelper.isNone(expected[0].myThirdList[0].my.myThirdList) assert ObjectHelper.equals(expected[0].myThirdList[0].my.myThirdList, toAssert[0].myThirdList[0].my.myThirdList) assert ObjectHelper.equals(expected[1].myThirdList[0], toAssert[1].myThirdList[0]) assert ObjectHelper.equals(toAssert[1].myThirdList[0], expected[1].myThirdList[0]) assert False == ( expected == another ), f'False == ({expected} == {another}): False == {(expected == another)}' assert False == ObjectHelper.equals(expected, another, muteLogs=not inspectEquals) assert False == ObjectHelper.equals(another, expected, muteLogs=not inspectEquals) assert False == ObjectHelper.equals(another, toAssert, muteLogs=not inspectEquals) assert False == ObjectHelper.equals(toAssert, another, muteLogs=not inspectEquals) assert False == ObjectHelper.equals(expected, [ MyDto(None, None, None), MyDto(None, None, None), MyDto(None, None, None) ])
def equal_whenListOfDictionaries(): # arrange null = 'null' LIST_OF_DICTIONARIES = [{ "myAttribute": "NW2", "myOther": { "myAttribute": "34PDZB" }, "myThirdList": [{ "my": { "myAttribute": "X1HC", "myOther": { "myAttribute": "34PDZB" }, "myThirdList": null }, "myAttribute": 9 }] }, { "myAttribute": "", "myOther": null, "myThirdList": [{ "my": { "myAttribute": "U", "myOther": null, "myThirdList": null }, "myAttribute": 3 }] }, { "myAttribute": "HNQ7QKW2", "myOther": { "myAttribute": "V9OXKD8" }, "myThirdList": [{ "my": { "myAttribute": "PVYA", "myOther": { "myAttribute": "V9OXKD8" }, "myThirdList": null }, "myAttribute": 10 }] }] DIFFERENT_LIST_OF_DICTIONARIES = [{ "myAttribute": "NW2", "myOther": { "myAttribute": "34PDZB" }, "myThirdList": [{ "my": { "myAttribute": "X1HC", "myOther": { "myAttribute": RandomHelper.integer() }, "myThirdList": null }, "myAttribute": 9 }] }, { "myAttribute": "", "myOther": null, "myThirdList": [{ "my": { "myAttribute": "U", "myOther": null, "myThirdList": null }, "myAttribute": 3 }] }, { "myAttribute": "HNQ7QKW2", "myOther": { "myAttribute": "V9OXKD8" }, "myThirdList": [{ "my": { "myAttribute": "PVYA", "myOther": { "myAttribute": "V9OXKD8" }, "myThirdList": null }, "myAttribute": 10 }] }] # act # assert assert ObjectHelper.equals(LIST_OF_DICTIONARIES, [{ "myAttribute": "NW2", "myOther": { "myAttribute": "34PDZB" }, "myThirdList": [{ "my": { "myAttribute": "X1HC", "myOther": { "myAttribute": "34PDZB" }, "myThirdList": null }, "myAttribute": 9 }] }, { "myAttribute": "", "myOther": null, "myThirdList": [{ "my": { "myAttribute": "U", "myOther": null, "myThirdList": null }, "myAttribute": 3 }] }, { "myAttribute": "HNQ7QKW2", "myOther": { "myAttribute": "V9OXKD8" }, "myThirdList": [{ "my": { "myAttribute": "PVYA", "myOther": { "myAttribute": "V9OXKD8" }, "myThirdList": null }, "myAttribute": 10 }] }]) assert False == ObjectHelper.equals(LIST_OF_DICTIONARIES, [{}, {}, {}]) assert False == ObjectHelper.equals(LIST_OF_DICTIONARIES, DIFFERENT_LIST_OF_DICTIONARIES)
def mustAssertEquals(): # arrange dictionaryInstance = {**{}, **JSON_INSTANCE} someDictionary = { 'a': 'b', 'c': 'd', 'e': { 'f': 'g', 't': [{'s1', 's1', 's3', 1, 3.3, False, None}, {'s1', False, 's3', 3.3, 1, None}], 1: 7, False: 2.3 }, 2.2: {False, 2, None, 'string'}, 'tuple': (2, 3, '3', 9) } someDictionaryList = [someDictionary, someDictionary] someOtherDictionary = { 'c': 'd', 'a': 'b', 'e': { False: 2.3, 1: 7, 'f': 'g', 't': [{3.3, 's1', 's3', 1, None, False}, {'s1', 's1', 's3', None, 1, 3.3, False}] }, 2.2: {False, 2, None, 'string'}, 'tuple': (2, 9, 3, '3') } someOtherDictionaryList = [someOtherDictionary, someOtherDictionary] differentDictionary = { 'c': 'd', 'a': 'b', 'e': { False: 2.3, 1: 7, 'f': 'g', 't': [{'s1', 's3', 1, 3.3, False, None}, {'s1', 's1', 's3', 1, 3.3, False, None}] }, 2.2: {False, 2, None, str()}, 'tuple': (9, 2, 3, '3') } differentDictionaryList = [differentDictionary, differentDictionary] aList = [{ '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' }] bList = [{ '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': '8: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': '8:30:00' }] # act toAssert = ObjectHelper.equals(dictionaryInstance, JSON_INSTANCE, ignoreCharactereList=[Constant.NEW_LINE]) unsortedDictionaryToAssert = ObjectHelper.equals(someDictionary, someOtherDictionary) unsortedDictionaryListToAssert = ObjectHelper.equals( someDictionaryList, someOtherDictionaryList) notEqualsToAssert = ObjectHelper.equals(someDictionary, differentDictionary) notEqualsListToAssert = ObjectHelper.equals(someDictionaryList, differentDictionaryList) # assert assert toAssert assert unsortedDictionaryToAssert assert not notEqualsToAssert assert unsortedDictionaryListToAssert assert not notEqualsListToAssert assert not ObjectHelper.equals(aList, bList) assert ObjectHelper.equals(aList, bList, ignoreKeyList=['timedelta'])
def mustLoadLocalConfiguration_correctly(): # Arrange expected = { 'print-status': False, 'server': { 'scheme': 'http', 'host': 'localhost', 'host-and-port': 'localhost:5050', 'port': 5050, 'servlet': { 'context-path': '/test-api' } }, 'has-it': { 'or-not': '?', 'here': '?' }, 'flask-specific-port': 'flask run --host=0.0.0.0 --port=5001', 'api': { 'name': 'TestApi', 'extension': 'yml', 'dependency': { 'update': False, 'list': { 'web': [ 'globals', 'python_helper', 'Popen', 'Path', 'numpy', 'pywin32', 'sqlalchemy' ] } }, 'git': { 'force-upgrade-command': 'pip install --upgrade --force python_framework' }, 'static-package': 'AppData\Local\Programs\Python\Python38-32\statics', 'list': [] }, 'swagger': { 'info': { 'title': 'TestApi', 'version': '0.0.1', 'description': 'description', 'terms-of-service': 'http://swagger.io/terms/', 'contact': { 'name': 'Samuel Jansen', 'email': '*****@*****.**' }, 'license': { 'name': 'Apache 2.0 / MIT License', 'url': 'http://www.apache.org/licenses/LICENSE-2.0.html' } }, 'host': 'localhost:5050', 'schemes': ['http'] }, 'python': { 'version': 3.9 } } # Act globalsInstance = globals.newGlobalsInstance( __file__, debugStatus=True, settingsFileName='fallback-priority') # log.prettyJson(mustLoadLocalConfiguration_correctly, 'Must Load Local Configuration setting tree', globalsInstance.settingTree, logLevel=log.DEBUG) # Assert assert ObjectHelper.equals(expected, globalsInstance.settingTree)
def myConfigurationTests_basicVariableDefinitions(): # Arrange and Act globalsInstance = globals.newGlobalsInstance(__file__, loadLocalConfig=False, debugStatus=True, warningStatus=False, errorStatus=True, successStatus=True, failureStatus=True, settingStatus=True, logStatus=False, infoStatus=True, encoding='utf-8', printRootPathStatus=False, globalsEverything=False) # log.prettyPython(myConfigurationTests_basicVariableDefinitions, 'settingTree', globalsInstance.settingTree, logLevel=log.DEBUG) # Assert assert 'self reference value' == globalsInstance.getSetting( 'my.self-reference-key') assert 'other self reference value as well' == globalsInstance.getSetting( 'my.other.self-reference-key.as-well') assert 'other repeated self reference value as well' == globalsInstance.getSetting( 'my.other.repeated.self-reference-key.as-well') assert 'my default value' == globalsInstance.getSetting( 'my.configuration-without-environment-variable-key') assert "my default value" == globalsInstance.getSetting( 'my.configuration-without-environment-variable-key-with-value-surrounded-by-single-quotes' ) assert 'my default value' == globalsInstance.getSetting( 'my.configuration-without-environment-variable-key-and-space-after-colon' ) assert 'self reference value' == globalsInstance.getSetting( 'my.configuration') assert 'self reference value' == globalsInstance.getSetting( 'my.own.configuration') assert 'other root value' == globalsInstance.getSetting('other.root.key') assert 'other root value' == globalsInstance.getSetting( 'my.own.very.deep.configuration') assert 'other self reference value as well' == globalsInstance.getSetting( 'my.other-with-other-name.self-reference-key.as-well') assert 'self reference value' == globalsInstance.getSetting( 'my.other-with-other-name.configuration') assert 'other self reference value as well' == globalsInstance.getSetting( 'my.other-with-other-name.configuration-as-well') assert 'other repeated self reference value as well' == globalsInstance.getSetting( 'my.other-with-other-name.configuration-repeated-as-well') assert globalsInstance.getSetting('my.override-case.overridden') is None assert 'overrider configuration' == globalsInstance.getSetting( 'my.override-case.overrider') assert 'delayed assignment value' == globalsInstance.getSetting( 'some-reference.before-its-assignment') assert 'delayed assignment value' == globalsInstance.getSetting( 'some-reference.much.before-its-assignment') assert "''' value ''' with spaces" == globalsInstance.getSetting( 'some-key.with-an-enter-in-between-the-previous-one') assert f"""Hi every one""".replace('\t', c.TAB) == globalsInstance.getSetting('long.string') assert f"""Hi every one this is the deepest long string here""".replace( '\t', c.TAB) == globalsInstance.getSetting( 'deepest.long.string.ever.long.string') assert f"""me being not fshds""".replace( '\t', c.TAB) == globalsInstance.getSetting('not.idented.long.string') assert 'abcdefg' == globalsInstance.getSetting( 'it.contains.one-setting-injection') assert 'abcdefghijklm' == globalsInstance.getSetting( 'it.contains.two-consecutive-setting-injection') assert 'abcdefghijklm' == globalsInstance.getSetting( 'it.contains.one-inside-of-the-other-setting-injection') assert 'ABCD-- my complex value --EFG' == globalsInstance.getSetting( 'it.contains.one-setting-injection-with-environment-variable') assert 'ABCDEFGEFG-- my complex value --HIJKLMNOP' == globalsInstance.getSetting( 'it.contains.one-inside-of-the-other-setting-injection-with-environment-variable' ) assert 'abcdefghijklm' == globalsInstance.getSetting( 'it.contains.two-consecutive-setting-injection-with-missing-environment-variable' ) assert 'abcd-- late value ----abcd---- late value ----abcd--efg' == globalsInstance.getSetting( 'it.contains.some-composed-key.pointing-to.a-late-value') assert 'abcd-- late environment value ----abcd--it.contains.late-value--abcd--efg' == globalsInstance.getSetting( 'it.contains.some-composed-key.pointing-to.a-late-value-with-an-environment-variable-in-between' ) assert '-- late value --' == globalsInstance.getSetting( 'it.contains.late-value') assert 'only environment variable value' == globalsInstance.getSetting( 'it.contains.environment-variable.only') assert 'ABCD -- only environment variable value -- EFGH' == globalsInstance.getSetting( 'it.contains.environment-variable.surrounded-by-default-values') assert 'ABCD -- "some value followed by: "only environment variable value\' and some following default value\' -- EFGH' == globalsInstance.getSetting( 'it.contains.environment-variable.in-between-default-values') assert 'ABCD -- very late definiton value -- EFGH' == globalsInstance.getSetting( 'it.contains.refference.to-a-late-definition') assert 222233444 == globalsInstance.getSetting('handle.integer') assert 2.3 == globalsInstance.getSetting('handle.float') assert True == globalsInstance.getSetting('handle.boolean') assert 222233444 == globalsInstance.getSetting('handle.late.integer') assert 2.3 == globalsInstance.getSetting('handle.late.float') assert True == globalsInstance.getSetting('handle.late.boolean') assert [] == globalsInstance.getSetting('handle.empty.list') assert {} == globalsInstance.getSetting('handle.empty.dictionary-or-set') assert (()) == globalsInstance.getSetting('handle.empty.tuple') assert 'local' == globalsInstance.getSetting('environment.test') assert 'not at all' == globalsInstance.getSetting('environment.missing') assert 'ABCD -- 222233444 -- EFGH' == globalsInstance.getSetting( 'some-not-string-selfreference.integer') assert 'ABCD -- 2.3 -- EFGH' == globalsInstance.getSetting( 'some-not-string-selfreference.float') assert 'ABCD -- True -- EFGH' == globalsInstance.getSetting( 'some-not-string-selfreference.boolean') assert ObjectHelper.equals( '/my/static/folder', globalsInstance.settingTree['python']['static-package']) assert ObjectHelper.equals( '/my/static/folder', globalsInstance.getSetting(globals.AttributeKey.PYTHON_STATIC_PACKAGE)) assert ObjectHelper.equals('/my/static/folder', globalsInstance.getStaticPackagePath())
def mustLoadLocalConfiguration(): # Arrange LOCAL_CONFIG_VALUE = 'local config setting value' FIRST_LONG_STRING = '''"""Hi every one """''' SECOND_LONG_STRING = '''"""Hi every one this is the deepest long string here """''' THIRD_LONG_STRING = '''""" me being not fshds """''' expected = { 'print-status': True, 'local': { 'config': { 'setting-key': 'local config setting value' } }, 'database': { 'dialect': 'a:b$c:d', 'username': '******', 'password': '******', 'host': 'm:n*o:p', 'port': '[q:r:s:t]', 'schema': '(u:v:w:x)' }, 'environment': { 'database': { 'key': 'DATABASE_URL', 'value': 'a:b$c:d://e:f?g:h:i:j!k:l@m:n*o:p:[q:r:s:t]/(u:v:w:x)' }, 'test': 'production', 'missing': 'not at all' }, 'server': { 'scheme': 'https', 'host': 'host', 'servlet': { 'context-path': '/test-api' }, 'port': 5050 }, 'api': { 'host-0': 'https://host', 'host-1': 'https://host/test-api', 'host-2': 'https://*****:*****@gmail.com' }, 'license': { 'name': 'Apache 2.0 / MIT License', 'url': 'http://www.apache.org/licenses/LICENSE-2.0.html' } }, 'schemes': ['https'] }, 'python': { 'version': 3.9 }, 'some-reference': { 'much': { 'before-its-assignment': 'delayed assignment value' }, 'before-its-assignment': 'delayed assignment value' }, 'other': { 'root': { 'key': 'other root value' } }, 'my': { 'self-reference-key': 'self reference value', 'other': { 'self-reference-key': { 'as-well': 'other self reference value as well' }, 'repeated': { 'self-reference-key': { 'as-well': 'other repeated self reference value as well' } } }, 'configuration-without-environment-variable-key': 'my default value', 'configuration-without-environment-variable-key-with-value-surrounded-by-single-quotes': 'my default value', 'configuration-without-environment-variable-key-and-space-after-colon': 'my default value', 'own': { 'very': { 'deep': { 'configuration': 'other root value' } }, 'configuration': 'self reference value' }, 'other-with-other-name': { 'self-reference-key': { 'as-well': 'other self reference value as well' }, 'configuration': 'self reference value', 'configuration-as-well': 'other self reference value as well', 'configuration-repeated-as-well': 'other repeated self reference value as well' }, 'override-case': { 'overrider': 'overrider configuration' }, 'configuration': 'self reference value' }, 'long': { 'string': FIRST_LONG_STRING }, 'deepest': { 'long': { 'string': { 'ever': { 'long': { 'string': SECOND_LONG_STRING } } } } }, 'not': { 'idented': { 'long': { 'string': THIRD_LONG_STRING } } }, 'new-key': 'new value', 'my-list': { 'numbers': [1, 2, 3, 4], 'simple-strings': ['a', 'b', 'c', 'd'], 'complex': [2, 'b', 'c', 'd', 1, 2, True, True], 'with-elemets-surrounded-by-all-sorts-of-quotes': ['a', 'b', 'c', 'd', 'e', 'f'] }, 'specific-for': { 'previous-assignment': 'delayed assignment value' }, 'some-key': { 'with-an-enter-in-between-the-previous-one': "''' value ''' with spaces" }, 'it': { 'contains': { 'some-composed-key': { 'pointing-to': { 'a-late-value': 'abcd-- late value ----abcd---- late value ----abcd--efg', 'a-late-value-with-an-environment-variable-in-between': 'abcd-- late environment value ----abcd--it.contains.late-value--abcd--efg' } }, 'late-value': '-- late value --', 'environment-variable': { 'only': 'only environment variable value', 'surrounded-by-default-values': 'ABCD -- only environment variable value -- EFGH', 'in-between-default-values': """ABCD -- "some value followed by: "only environment variable value' and some following default value' -- EFGH""" }, 'refference': { 'to-a-late-definition': 'ABCD -- very late definiton value -- EFGH' }, 'one-setting-injection': 'abcdefg', 'two-consecutive-setting-injection': 'abcdefghijklm', 'one-inside-of-the-other-setting-injection': 'abcdefghijklm', 'one-setting-injection-with-environment-variable': 'ABCD-- my complex value --EFG', 'one-inside-of-the-other-setting-injection-with-environment-variable': 'ABCDEFGEFG-- my complex value --HIJKLMNOP', 'two-consecutive-setting-injection-with-missing-environment-variable': 'abcdefghijklm' } }, 'very-late': { 'definition': 'very late definiton value' }, 'handle': { 'late': { 'integer': 222233444, 'float': 2.3, 'boolean': True }, 'integer': 222233444, 'float': 2.3, 'boolean': True, 'empty': { 'list': [], 'dictionary-or-set': {}, 'tuple': () } }, 'some': { 'dictionary': { 'yolo': 'yes', 'another-yolo': 'no', 'another-yolo-again': '', f'''{'{'}{" 'again?'"}''': f'''{"'yes' "}{'}'}''' } }, 'some-not-string-selfreference': { 'integer': 'ABCD -- 222233444 -- EFGH', 'float': 'ABCD -- 2.3 -- EFGH', 'boolean': 'ABCD -- True -- EFGH' } } # Act globalsInstance = globals.newGlobalsInstance( __file__, settingStatus=True, settingsFileName='other-application') # globalsInstance.printTree(globalsInstance.settingTree, 'settingTree') # globalsInstance.printTree(globalsInstance.defaultSettingTree, 'defaultSettingTree') # Assert assert LOCAL_CONFIG_VALUE == globalsInstance.getSetting( 'local.config.setting-key') assert True == globalsInstance.getSetting('print-status') assert 'Globals' == globalsInstance.getSetting('api.name') assert "a:b$c:d://e:f?g:h:i:j!k:l@m:n*o:p:[q:r:s:t]/(u:v:w:x)" == globalsInstance.getSetting( 'environment.database.value') assert expected['long']['string'] == globalsInstance.settingTree['long'][ 'string'] assert expected['deepest']['long']['string']['ever']['long'][ 'string'] == globalsInstance.settingTree['deepest']['long']['string'][ 'ever']['long']['string'] assert expected['not']['idented']['long'][ 'string'] == globalsInstance.settingTree['not']['idented']['long'][ 'string'] assert ObjectHelper.equals( expected['some']['dictionary'], globalsInstance.settingTree['some']['dictionary']) assert ObjectHelper.equals(expected, globalsInstance.settingTree, ignoreKeyList=[])
def importResourceAndModule_withSuccess(): # Arrange SOME_VALUE = 'some value' globalsInstance = GlobalsManager.newGlobalsInstance( __file__, debugStatus=True, warningStatus=True, errorStatus=True, successStatus=True, wrapperStatus=False, failureStatus=False, statusStatus=True, settingStatus=True, logStatus=False, testStatus=False # , debugStatus = True # , warningStatus = True # , errorStatus = True # , successStatus = True # , failureStatus = True # , statusStatus = True # , settingStatus = True # , infoStatus = True # , wrapperStatus = True # , logStatus = True # , testStatus = True , loadLocalConfig=False, encoding='utf-8', printRootPathStatus=False, globalsEverything=False) # Act myServiceClass = GlobalsManager.importResource('MyService', muteLogs=False) myOtherServiceClass = GlobalsManager.importResource( 'MyOtherService', resourceModuleName='MyService', muteLogs=False) myServiceModule = GlobalsManager.importModule('MyService', muteLogs=False) globalsInstance.ignoreResources += ['MyIgnorableService'] myIgnorableServiceClass = GlobalsManager.importResource( 'MyIgnorableService', muteLogs=False) myOtherIgnorableServiceClass = GlobalsManager.importResource( 'MyOtherIgnorableService', resourceModuleName='MyIgnorableService', muteLogs=False) myOtherServiceModule = GlobalsManager.importModule('MyIgnorableService', muteLogs=False) pythonHelperLogModule = GlobalsManager.importResource( 'log', resourceModuleName='python_helper', muteLogs=False) pythonHelperLogModuleLOGValue = GlobalsManager.importResource( 'log.LOG', resourceModuleName='python_helper', muteLogs=False) myDomainValue = GlobalsManager.importResource('MyDomain.myDomainValue', muteLogs=False) # Assert assert f'service value: {SOME_VALUE}' == myServiceClass().getServiceValue( SOME_VALUE) assert f'other service value: {SOME_VALUE}' == myOtherServiceClass( ).getServiceValue(SOME_VALUE) assert ObjectHelper.isNotNone(myServiceModule) assert ObjectHelper.isNone(myIgnorableServiceClass) assert ObjectHelper.isNone(myOtherIgnorableServiceClass) assert ObjectHelper.isNotNone(myOtherServiceModule) assert log == pythonHelperLogModule assert ObjectHelper.equals(log.LOG, pythonHelperLogModuleLOGValue) assert ObjectHelper.equals('my value', myDomainValue) assert ObjectHelper.isNotNone(GlobalsManager.getCachedImports()) assert ObjectHelper.isNone(GlobalsManager.clearCachedImports())