コード例 #1
0
def testMissingJSONFields(obj):
    """Test handling of missing fields."""

    with raises(ValueError, match="Missing values for fields:"):
        jsonToData(obj, HeroData)

    with raises(ValueError, match="Missing values for fields:"):
        mapJSON(obj, HeroData, partial=False)

    assert mapJSON(obj, HeroData, partial=True) == obj
コード例 #2
0
ファイル: newapi.py プロジェクト: boxingbeetle/softfab
    def render_PUT(self, request: Request) -> bytes:
        try:
            jsonNode = json.load(request.content)
        except json.JSONDecodeError as ex:
            return textReply(request, 400, f"Invalid JSON: {ex}\n")

        try:
            data = jsonToData(jsonNode, UserDataCreate)
        except ValueError as ex:
            return textReply(request, 400, f"Not a valid record: {ex}\n")

        userDB = self._userDB
        name = self._name
        try:
            addUserAccount(userDB, name, uiRoleToSet(data.role))
        except ValueError as ex:
            return textReply(request, 400, f"Error creating user: {ex}\n")

        reply = {}
        if data.password is PasswordActions.RESET:
            reply['reset'] = _resetPasswordJSON(userDB, name, self._tokenDB)

        if reply:
            return jsonReply(request, reply)
        else:
            return textReply(request, 201, f"User created: {name}\n")
コード例 #3
0
ファイル: newapi.py プロジェクト: boxingbeetle/softfab
    def render_PATCH(self, request: Request) -> bytes:
        try:
            jsonNode = json.load(request.content)
        except json.JSONDecodeError as ex:
            return textReply(request, 400, f"Invalid JSON: {ex}\n")

        try:
            data = jsonToData(jsonNode, UserDataUpdate)
        except ValueError as ex:
            return textReply(request, 400, f"Data mismatch: {ex}\n")

        userDB = self._userDB
        userName = self._user.name
        user = userDB[userName]
        reply = {}

        role = data.role
        if role is not None:
            user.roles = uiRoleToSet(role)

        password = data.password
        if password is not None:
            tokenDB = self._tokenDB
            if password is PasswordActions.REMOVE:
                removePassword(userDB, userName, tokenDB)
            elif password is PasswordActions.RESET:
                reply['reset'] = _resetPasswordJSON(userDB, userName, tokenDB)

        if reply:
            return jsonReply(request, reply)
        else:
            return emptyReply(request)
コード例 #4
0
def testJSONOptional():
    """Test binding to a data transfer class with optional fields."""

    # All fields.
    data = HeroDataOptional(**knightArgs)
    json = dict(knightJSON)
    assert jsonToData(json, HeroDataOptional) == data

    # Provide null value for optional field with default.
    data.fav_color = None
    json['fav_color'] = None
    assert jsonToData(json, HeroDataOptional) == data

    # Drop optional field with default.
    del json['fav_color']
    assert jsonToData(json, HeroDataOptional) == data

    # Provide null value for optional field without default.
    data.age = None
    json['age'] = None
    assert jsonToData(json, HeroDataOptional) == data

    # Drop optional field without default.
    del json['age']
    with raises(ValueError, match="Missing values for fields:"):
        jsonToData(json, HeroDataOptional)
コード例 #5
0
def testJSONDefault():
    """Test binding to a data transfer class with defaults for some fields."""

    defaultKnight = jsonToData(dict(knightJSON, armor='ring'), HeroDataDefault)
    assert defaultKnight.armor == 'ring' # overridden
    assert defaultKnight.shield is True # default
コード例 #6
0
def testJSONToHeroData():
    """Test whether a we can create a simple object from JSON."""
    assert jsonToData(knightJSON, HeroData) == knight
コード例 #7
0
def testBadDataClass():
    """Test handling of errors in the passed data class."""

    BrokenData = attr.make_class('BrokenData', ['emblem'])
    with raises(TypeError, match="No type specified for attribute 'emblem'"):
        jsonToData({'emblem': 'chicken'}, BrokenData)