Skip to content

Commit 8a26828

Browse files
committed
Fixes to account for new tests of invalid cases
1 parent 41f9dd1 commit 8a26828

File tree

2 files changed

+18
-4
lines changed

2 files changed

+18
-4
lines changed

bson/binary.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -450,6 +450,10 @@ def from_vector(
450450
raise ValueError(f"padding does not apply to {dtype=}")
451451
elif dtype == BinaryVectorDtype.PACKED_BIT: # pack ints in [0, 255] as unsigned uint8
452452
format_str = "B"
453+
if 0 <= padding > 7:
454+
raise ValueError(f"{padding=}. It must be in [0,1, ..7].")
455+
if padding and not vector:
456+
raise ValueError("Empty vector with non-zero padding.")
453457
elif dtype == BinaryVectorDtype.FLOAT32: # pack floats as float32
454458
format_str = "f"
455459
if padding:

test/test_bson_binary_vector.py

Lines changed: 14 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -49,7 +49,7 @@ def create_test(case_spec):
4949
def run_test(self):
5050
for test_case in case_spec.get("tests", []):
5151
description = test_case["description"]
52-
vector_exp = test_case["vector"]
52+
vector_exp = test_case.get("vector", [])
5353
dtype_hex_exp = test_case["dtype_hex"]
5454
dtype_alias_exp = test_case.get("dtype_alias")
5555
padding_exp = test_case.get("padding", 0)
@@ -76,17 +76,27 @@ def run_test(self):
7676
self.assertEqual(
7777
vector_obs.dtype, BinaryVectorDtype[dtype_alias_exp], description
7878
)
79-
self.assertEqual(vector_obs.data, vector_exp, description)
80-
self.assertEqual(vector_obs.padding, padding_exp, description)
81-
79+
if dtype_exp in [BinaryVectorDtype.FLOAT32]:
80+
[
81+
self.assertAlmostEqual(vector_obs.data[i], vector_exp[i], delta=1e-5)
82+
for i in range(len(vector_exp))
83+
]
84+
else:
85+
self.assertEqual(vector_obs.data, vector_exp, description)
8286
# Test Binary Vector to BSON
8387
vector_exp = Binary.from_vector(vector_exp, dtype_exp, padding_exp)
8488
cB_obs = binascii.hexlify(encode({test_key: vector_exp})).decode().upper()
8589
self.assertEqual(cB_obs, canonical_bson_exp, description)
8690

8791
else:
8892
with self.assertRaises((struct.error, ValueError), msg=description):
93+
# Tests Binary.from_vector
8994
Binary.from_vector(vector_exp, dtype_exp, padding_exp)
95+
# Tests Binary.as_vector
96+
cB_exp = binascii.unhexlify(canonical_bson_exp.encode("utf8"))
97+
decoded_doc = decode(cB_exp)
98+
binary_obs = decoded_doc[test_key]
99+
binary_obs.as_vector()
90100

91101
return run_test
92102

0 commit comments

Comments
 (0)