MCPcopy Index your code
hub / github.com/mongodb/mongo-python-driver / test_vector

Method test_vector

test/test_bson.py:737–813  ·  view source on GitHub ↗

Tests of subtype 9

(self)

Source from the content-addressed store, hash-verified

735 self.assertEqual(id, transformed)
736
737 def test_vector(self):
738 """Tests of subtype 9"""
739 # We start with valid cases, across the 3 dtypes implemented.
740 # Work with a simple vector that can be interpreted as int8, float32, or ubyte
741 list_vector = [127, 8]
742 # As INT8, vector has length 2
743 binary_vector = Binary.from_vector(list_vector, BinaryVectorDtype.INT8)
744 vector = binary_vector.as_vector()
745 assert vector.data == list_vector
746 # test encoding roundtrip
747 assert {"vector": binary_vector} == decode(encode({"vector": binary_vector}))
748 # test json roundtrip
749 assert binary_vector == json_util.loads(json_util.dumps(binary_vector))
750
751 # For vectors of bits, aka PACKED_BIT type, vector has length 8 * 2
752 packed_bit_binary = Binary.from_vector(list_vector, BinaryVectorDtype.PACKED_BIT)
753 packed_bit_vec = packed_bit_binary.as_vector()
754 assert packed_bit_vec.data == list_vector
755
756 # A padding parameter permits vectors of length that aren't divisible by 8
757 # The following ignores the last 3 bits in list_vector,
758 # hence it's length is 8 * len(list_vector) - padding
759 padding = 3
760 padded_vec = Binary.from_vector(list_vector, BinaryVectorDtype.PACKED_BIT, padding=padding)
761 assert padded_vec.as_vector().data == list_vector
762 # To visualize how this looks as a binary vector..
763 uncompressed = ""
764 for val in list_vector:
765 uncompressed += format(val, "08b")
766 assert uncompressed[:-padding] == "0111111100001"
767
768 # It is worthwhile explicitly showing the values encoded to BSON
769 padded_doc = {"padded_vec": padded_vec}
770 assert (
771 encode(padded_doc)
772 == b"\x1a\x00\x00\x00\x05padded_vec\x00\x04\x00\x00\x00\t\x10\x03\x7f\x08\x00"
773 )
774 # and dumped to json
775 assert (
776 json_util.dumps(padded_doc)
777 == '{"padded_vec": {"$binary": {"base64": "EAN/CA==", "subType": "09"}}}'
778 )
779
780 # FLOAT32 is also implemented
781 float_binary = Binary.from_vector(list_vector, BinaryVectorDtype.FLOAT32)
782 assert all(isinstance(d, float) for d in float_binary.as_vector().data)
783
784 # Now some invalid cases
785 for x in [-1, 257]:
786 with self.assertRaises(struct.error):
787 Binary.from_vector([x], BinaryVectorDtype.PACKED_BIT)
788
789 # Test one must pass zeros for all ignored bits
790 with self.assertRaises(ValueError):
791 Binary.from_vector([255], BinaryVectorDtype.PACKED_BIT, padding=7)
792
793 with self.assertWarns(DeprecationWarning):
794 meta = struct.pack("<sB", BinaryVectorDtype.PACKED_BIT.value, 7)

Callers

nothing calls this directly

Calls 6

decodeFunction · 0.90
encodeFunction · 0.90
BinaryClass · 0.90
BinaryVectorClass · 0.90
from_vectorMethod · 0.80
as_vectorMethod · 0.80

Tested by

no test coverage detected