Esempio n. 1
0
def validateCompleteResponse(responseClass, completeResponse):
    if isNotPythonFrameworkHttpsResponseBody(completeResponse):
        raiseBadResponseImplementation(
            f'It should be a tuple like this: ({"RESPONSE_CLASS" if ObjectHelper.isNone(responseClass) else responseClass if ObjectHelper.isNotList(responseClass) else responseClass[0]}, HEADERS, HTTPS_CODE). But it is: {completeResponse}'
        )
    if ObjectHelper.isNotNone(responseClass):
        if Serializer.isSerializerList(responseClass):
            if 0 == len(responseClass):
                log.log(validateCompleteResponse,
                        f'"responseClass" was not defined')
            elif 1 == len(responseClass):
                if ObjectHelper.isNotList(responseClass[0]):
                    if not isinstance(completeResponse[0], responseClass[0]):
                        raiseBadResponseImplementation(
                            f'Response does not match expected class. Expected "{responseClass[0].__name__}", but got "{completeResponse[0].__class__.__name__}"'
                        )
                elif ObjectHelper.isNotList(responseClass[0][0]):
                    if ObjectHelper.isNotList(completeResponse[0]):
                        raiseBadResponseImplementation(
                            f'Response is not a list. Expected "{responseClass[0].__class__.__name__}", but found "{completeResponse[0].__class__.__name__}"'
                        )
                    elif Serializer.isSerializerList(
                            completeResponse[0]
                    ) and 0 < len(completeResponse[0]) and not isinstance(
                            completeResponse[0][0], responseClass[0][0]):
                        raiseBadResponseImplementation(
                            f'Response element class does not match expected element class. Expected "{responseClass[0][0].__name__}", response "{completeResponse[0][0].__class__.__name__}"'
                        )
        else:
            if not isinstance(completeResponse[0], responseClass):
                raiseBadResponseImplementation(
                    f'Response does not match expected class. Expected "{responseClass.__name__}", but got "{completeResponse[0].__class__.__name__}"'
                )
    else:
        log.log(validateCompleteResponse, f'"responseClass" was not defined')
Esempio n. 2
0
def validateArgs(args, requestClass, resourceInstanceMethod):
    if ObjectHelper.isNotNone(requestClass):
        resourceInstance = args[0]
        if Serializer.isSerializerList(requestClass):
            if 0 < len(requestClass):
                for index in range(len(requestClass)):
                    if Serializer.isSerializerList(
                            args[index + 1]) and len(args[index + 1]) > 0:
                        expecteObjectClass = requestClass[index][0]
                        for objectInstance in args[index + 1]:
                            ExceptionHandler.validateArgs(
                                resourceInstance, resourceInstanceMethod,
                                objectInstance, expecteObjectClass)
                    else:
                        objectRequest = args[index + 1]
                        expecteObjectClass = requestClass[index]
                        ExceptionHandler.validateArgs(resourceInstance,
                                                      resourceInstanceMethod,
                                                      objectRequest,
                                                      expecteObjectClass)
        else:
            objectRequest = args[1]
            expecteObjectClass = requestClass
            ExceptionHandler.validateArgs(resourceInstance,
                                          resourceInstanceMethod,
                                          objectRequest, expecteObjectClass)
Esempio n. 3
0
 def getMethod(self, uri, headers=None, params=None):
     return self.get(additionalUrl=uri,
                     params=Serializer.getObjectAsDictionary(params),
                     headers={
                         'Some-Cool-Header': 'cool-value',
                         **Serializer.getObjectAsDictionary(headers)
                     })
Esempio n. 4
0
def handleControllerMethod(args, kwargs, contentType, resourceInstance,
                           resourceInstanceMethod, requestHeaderClass,
                           requestParamClass, requestClass, logRequest,
                           muteStacktraceOnBusinessRuleException):
    requestBodyAsJson = {}
    if resourceInstanceMethod.__name__ in OpenApiManager.ABLE_TO_RECIEVE_BODY_LIST and requestClass:
        requestBodyAsJson = getRequestBodyAsJson(contentType, requestClass)
        if Serializer.requestBodyIsPresent(requestBodyAsJson):
            requestBodyAsJsonSerialized = Serializer.convertFromJsonToObject(
                requestBodyAsJson, requestClass)
            args = getArgsWithSerializerReturnAppended(
                args, requestBodyAsJsonSerialized)
    headers = FlaskUtil.addToKwargs(FlaskUtil.KW_HEADERS, requestHeaderClass,
                                    FlaskUtil.safellyGetHeaders(), kwargs)
    query = FlaskUtil.addToKwargs(FlaskUtil.KW_PARAMETERS, requestParamClass,
                                  FlaskUtil.safellyGetArgs(), kwargs)
    try:
        if resourceInstance.logRequest or logRequest:
            log.prettyJson(
                resourceInstanceMethod,
                '[CONTROLLER] Request',
                {
                    'headers': headers,
                    # 'query': FlaskUtil.addToKwargs(FlaskUtil.KW_PARAMETERS, requestParamClass, FlaskUtil.safellyGetArgs(), kwargs), ###- safellyGetUrl() returns query param
                    'body': requestBodyAsJson
                },
                condition=True,
                logLevel=log.INFO)
    except Exception as exception:
        log.failure(innerResourceInstanceMethod,
                    'Not possible to log request properly', exception)
    return validateAndReturnResponse(
        handleAdditionalResponseHeadersIfNeeded(
            resourceInstanceMethod(resourceInstance, *args[1:], **kwargs)))
Esempio n. 5
0
 def deleteMethod(self, uri, dto, headers=None, params=None):
     return self.delete(body=Serializer.getObjectAsDictionary(dto),
                        additionalUrl=uri,
                        params=Serializer.getObjectAsDictionary(params),
                        headers={
                            'Some-Cool-Header': 'cool-value',
                            **Serializer.getObjectAsDictionary(headers)
                        })
Esempio n. 6
0
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)
Esempio n. 7
0
 def get(self,
         urlParam=None,
         otherUrlParam=None,
         params=None,
         headers=None):
     return [
         ClientTestDto.ClientTestResponseDto(
             someBody=urlParam + otherUrlParam,
             someOtherBody={
                 **Serializer.getObjectAsDictionary(headers),
                 **Serializer.getObjectAsDictionary(params)
             })
     ], {
         f'{GET_TEST}All': f'headers-{GET_TEST}-all'
     }, HttpStatus.OK
Esempio n. 8
0
def weirdIdList() :
    #arrange
    class TestContact(MODEL):
        __tablename__ = 'TestContact'
        id = sap.Column(sap.Integer(), sap.Sequence(f'{__tablename__}{sap.ID}{sap.SEQ}'), primary_key=True)
        key = sap.Column(sap.String(128), nullable=False)
        def __init__(self,
            id = None,
            key = None
        ):
            self.id = id
            self.key = key
        def __repr__(self):
            return f'{self.__tablename__}(id: {self.id}, key: {self.key})'
    class TestContactRequestDto :
        def __init__(self,
            key = None
        ) :
            self.key = key
    class TestContactResponseDto :
        def __init__(self,
            id = None,
            key = None
        ) :
            self.id = id
            self.key = key
    model = TestContact(id=2, key="a")

    #act
    dto = Serializer.convertFromObjectToObject(model, TestContactResponseDto)

    assert int == type(dto.id)
    assert 2 == dto.id
Esempio n. 9
0
def addToKwargs(key, givenClass, valuesAsDictionary, kwargs):
    if ObjectHelper.isNotEmpty(givenClass):
        toClass = givenClass if ObjectHelper.isNotList(
            givenClass) else givenClass[0]
        kwargs[key] = Serializer.convertFromJsonToObject(
            {k: v
             for k, v in valuesAsDictionary.items()}, toClass)
    return valuesAsDictionary
Esempio n. 10
0
def buildHttpResponse(additionalResponseHeaders, controllerResponseBody,
                      status, contentType):
    httpResponse = Response(Serializer.jsonifyIt(controllerResponseBody),
                            mimetype=contentType,
                            status=status)
    for key, value in additionalResponseHeaders.items():
        httpResponse.headers[key] = value
    return httpResponse
Esempio n. 11
0
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)}'
Esempio n. 12
0
def getArgsWithResponseClassInstanceAppended(args, responseClass):
    if responseClass:
        resourceInstance = args[0]
        objectRequest = args[1]
        objectRequestSerialized = Serializer.convertFromObjectToObject(
            objectRequest, responseClass)
        return getArgsWithSerializerReturnAppended(args,
                                                   objectRequestSerialized)
    return args
 def innerResourceInstanceMethod(*args, **kwargs):
     f'''(*args, {FlaskUtil.KW_HEADERS}={{}}, {FlaskUtil.KW_PARAMETERS}={{}}, **kwargs)'''
     resourceInstance = args[0]
     clientResponse = None
     completeResponse = None
     try :
         FlaskManager.validateKwargs(
             kwargs,
             resourceInstance,
             resourceInstanceMethod,
             requestHeaderClass,
             requestParamClass
         )
         FlaskManager.validateArgs(args, requestClass, resourceInstanceMethod)
         clientResponse = None
         httpClientEvent = getHttpClientEvent(resourceInstanceMethod, *args, **kwargs)
         if isinstance(httpClientEvent, ManualHttpClientEvent):
             completeResponse = httpClientEvent.completeResponse
         elif isinstance(httpClientEvent, HttpClientEvent):
             try :
                 clientResponse = HTTP_CLIENT_RESOLVERS_MAP.get(
                     httpClientEvent.verb,
                     raiseHttpClientEventNotFoundException
                 )(
                     resourceInstance,
                     *httpClientEvent.args,
                     **httpClientEvent.kwargs
                 )
             except Exception as exception:
                 raiseException(clientResponse, exception)
             raiseExceptionIfNeeded(clientResponse)
             completeResponse = getCompleteResponse(clientResponse, responseClass, produces)
             FlaskManager.validateCompleteResponse(responseClass, completeResponse)
         else:
             raise Exception('Unknown http client event')
     except Exception as exception:
         log.log(innerResourceInstanceMethod, 'Failure at client method execution', exception=exception, muteStackTrace=True)
         FlaskManager.raiseAndPersistGlobalException(exception, resourceInstance, resourceInstanceMethod, context=HttpDomain.CLIENT_CONTEXT)
     clientResponseStatus = completeResponse[-1]
     clientResponseHeaders = completeResponse[1]
     clientResponseBody = completeResponse[0] if ObjectHelper.isNotNone(completeResponse[0]) else {'message' : HttpStatus.map(clientResponseStatus).enumName}
     if resourceInstance.logResponse or logResponse :
         log.prettyJson(
             resourceInstanceMethod,
             '[CLIENT    ] Response',
             {
                 'headers': clientResponseHeaders,
                 'body': Serializer.getObjectAsDictionary(clientResponseBody),
                 'status': clientResponseStatus
             },
             condition = True,
             logLevel = log.INFO
         )
     if returnOnlyBody:
         return completeResponse[0]
     else:
         return completeResponse
Esempio n. 14
0
 def getOnActuatorHealth(self, dto, headers=None, params=None):
     # print(dto.__dict__)
     # print(headers.__dict__)
     # print(params.__dict__)
     response = requests.put(
         f'{self.url}{self.getOnActuatorHealth.url}',
         data = Serializer.jsonifyIt(dto),
         params = Serializer.getObjectAsDictionary(params),
         headers = {'Content-Type': self.getOnActuatorHealth.consumes, **Serializer.getObjectAsDictionary(headers)}
     )
     # print(response.json());
     return TestRequestDto.TestResponseDto(
         status = Serializer.convertFromJsonToObject(response.json(), [[ActuatorHealthDto.ActuatorHealthResponseDto]])[0].status,
         first = params.first,
         second = params.second,
         firstHeader = headers.firstHeader,
         secondHeader = headers.secondHeader
     ), HttpStatus.map(response.status_code)
Esempio n. 15
0
def getNullableChildDtoClass(attributeName, dtoClass, verb, url,
                             documentation):
    log.log(
        getNullableChildDtoClass,
        f'attributeName: {attributeName}, dtoClass: {dtoClass}, verb: {verb}, url: {url}'
    )
    childDtoClass = Serializer.getTargetClassFromFatherClassAndChildMethodName(
        dtoClass, attributeName)
    log.log(getNullableChildDtoClass, f'childDtoClass: {childDtoClass}')
    if childDtoClass:
        if ReflectionHelper.getName(type(type)) == ReflectionHelper.getName(
                type(childDtoClass)):
            addDtoToUrlVerb(verb, url, childDtoClass, documentation)
        else:
            addDtoToUrlVerb(verb, url, type(childDtoClass), documentation)
    return childDtoClass
def getCompleteResponse(clientResponse, responseClass, produces, fallbackStatus=HttpStatus.INTERNAL_SERVER_ERROR):
    responseBody, responseHeaders, responseStatus = dict(), dict(), fallbackStatus
    responseHeaders = FlaskUtil.safellyGetResponseHeaders(clientResponse)
    responseBody = FlaskUtil.safellyGetResponseJson(clientResponse)
    try :
        responseStatus = HttpStatus.map(HttpStatus.NOT_FOUND if ObjectHelper.isNone(clientResponse.status_code) else clientResponse.status_code)
    except Exception as exception :
        responseStatus = HttpStatus.map(fallbackStatus)
        log.warning(getCompleteResponse, f'Not possible to get client response status. Returning {responseStatus} by default', exception=exception)
    responseHeaders = {
        **{HttpDomain.HeaderKey.CONTENT_TYPE: produces},
        **responseHeaders
    }
    responseStatus = ConverterStatic.getValueOrDefault(responseStatus, HttpStatus.map(fallbackStatus))
    if ObjectHelper.isNone(responseClass):
        return responseBody, responseHeaders, responseStatus
    return Serializer.convertFromJsonToObject(responseBody, responseClass), responseHeaders, responseStatus
Esempio n. 17
0
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'
        ]
    )
Esempio n. 18
0
def toResponseDto(dto, toClass):
    if not (ObjectHelper.isNone(dto) or ObjectHelper.isNone(toClass)):
        return Serializer.convertFromObjectToObject(dto, toClass)
    return dto
Esempio n. 19
0
def safellyGetData(data):
    return dict() if ObjectHelper.isNone(
        data) else Serializer.getObjectAsDictionary(data)
Esempio n. 20
0
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)
    )
Esempio n. 21
0
def getNewJti():
    return Serializer.newUuidAsString()
Esempio n. 22
0
def isJsonifyable() :
    assert False == Serializer.isJsonifyable(generatorFunction())
    assert True == Serializer.isJsonifyable(MyClass())
    assert True == Serializer.isJsonifyable(MyEntityClass())
Esempio n. 23
0
def isModelTest() :
    assert False == Serializer.isModel(generatorFunction())
    assert False == Serializer.isModel(MyClass())
    assert True == Serializer.isModel(MyEntityClass())
Esempio n. 24
0
def safellyGetContext(contextList):
    return Serializer.getObjectAsDictionary(
        contextList) if ObjectHelper.isList(
            contextList) else [] if ObjectHelper.isNone(
                contextList) else raiseSessionContextCannotBeNone()