Skip to content

Commit

Permalink
Fix JSONTop() == 1 and JSONbot() == 0
Browse files Browse the repository at this point in the history
The == operator in `is_top` and `is_bot` causes type confusion when
comparing `JSONTop()` and `JSONbot()` values.

Fix it by using identity test instead of equality.
  • Loading branch information
kmichel-aiven authored and shinnar committed Jul 8, 2024
1 parent 8c85130 commit f6dbeb7
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 2 deletions.
4 changes: 2 additions & 2 deletions jsonsubschema/_checkers.py
Original file line number Diff line number Diff line change
Expand Up @@ -235,7 +235,7 @@ def __bool__(self):


def is_top(obj):
return obj == True or obj == {} or isinstance(obj, JSONtop)
return obj is True or obj == {} or isinstance(obj, JSONtop)


class JSONbot(JSONschema):
Expand Down Expand Up @@ -275,7 +275,7 @@ def __bool__(self):


def is_bot(obj):
return obj == False \
return obj is False \
or (utils.is_dict(obj) and obj.get("not") == {}) \
or isinstance(obj, JSONbot) \
or (isinstance(obj, JSONschema) and obj.isUninhabited())
Expand Down
35 changes: 35 additions & 0 deletions test/test_checkers.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
from jsonsubschema._canonicalization import simplify_schema_and_embed_checkers
from jsonsubschema._checkers import JSONbot, JSONtop, is_bot, is_top
import unittest


class TestIsTop(unittest.TestCase):
def test_true_is_top(self) -> None:
self.assertTrue(is_top(True))

def test_empty_object_is_top(self) -> None:
self.assertTrue(is_top({}))

def test_json_top_is_top(self) -> None:
self.assertTrue(is_top(JSONtop()))

def test_one_is_not_top(self) -> None:
self.assertFalse(is_top(1))


class TestIsBot(unittest.TestCase):
def test_false_is_bot(self) -> None:
self.assertTrue(is_bot(False))

def test_not_empty_object_is_bot(self) -> None:
self.assertTrue(is_bot({"not": {}}))

def test_json_bot_is_bot(self) -> None:
self.assertTrue(is_bot(JSONbot()))

def test_uninhabited_schema_is_bot(self) -> None:
uninhabited_schema = simplify_schema_and_embed_checkers({"type": "integer", "minimum": 2, "maximum": 1})
self.assertTrue(is_bot(uninhabited_schema))

def test_zero_is_not_bot(self) -> None:
self.assertFalse(is_bot(0))

0 comments on commit f6dbeb7

Please sign in to comment.