MongoEngine / MongoEngine/mongoengine

BooleanField validation issue?

Open
#1,873 9 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
Python
Stars
4.3k
Forks
1.2k
Avg merge
4h 41m
Merged PRs (30d)
11

Description

The following simple code shows the boolean field is not been validated.
Is there anything wrong?

import json
from mongoengine import Document
from mongoengine import BooleanField


class Validator(Document):
    a_bool_field = BooleanField()


body_json = {
  "a_bool_field": "fffffff"
}
validator = Validator.from_json(json.dumps(body_json))
try:
    validator.validate()
except Exception as e:
    print(e.to_dict())

There's no any errors printed.


Update

I found BooleanField to_python will cause Class.from_json() convert everything not None to True,
I think the behavior is odd.

class BooleanField(BaseField):
"""Boolean field type.
.. versionadded:: 0.1.2
"""

def to_python(self, value):
    try:
        value = bool(value)
    except ValueError:
        pass
    return value

def validate(self, value):
    if not isinstance(value, bool):
        self.error('BooleanField only accepts boolean values')

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with BooleanField.to_python and validate, then trace how Document.from_json passes the parsed value into validation. Run the supplied reproduction and verify that an invalid string is not silently accepted as True; preserve or add coverage for the expected validation behavior.

Written by the indexing model from the issue text.

Assessment

Tech stack
mongodb, python
Domain
databases
Issue type
Bug
Difficulty
2/5
Estimated time
1-3 hours
Activity status
Stale
Clarity
Clearly specified
Newbie friendliness
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.