From 7447fc1fad2c84ee6205b55b40a6cf3eb03f51f4 Mon Sep 17 00:00:00 2001 From: Akanksha Trehun Date: Thu, 17 Sep 2026 00:06:28 +0530 Subject: [PATCH] Fix to_bytes and to_str raising a string instead of an exception Signed-off-by: Akanksha Trehun --- dapr/clients/grpc/_helpers.py | 4 ++-- tests/clients/test_dapr_grpc_helpers.py | 24 ++++++++++++++++++++++++ 2 files changed, 26 insertions(+), 2 deletions(-) diff --git a/dapr/clients/grpc/_helpers.py b/dapr/clients/grpc/_helpers.py index fdfb6dbdf..9557f92a8 100644 --- a/dapr/clients/grpc/_helpers.py +++ b/dapr/clients/grpc/_helpers.py @@ -103,7 +103,7 @@ def to_bytes(data: Union[str, bytes]) -> bytes: elif isinstance(data, str): return data.encode('utf-8') else: - raise f'invalid data type {type(data)}' + raise TypeError(f'invalid data type {type(data)}') def to_str(data: Union[str, bytes]) -> str: @@ -113,7 +113,7 @@ def to_str(data: Union[str, bytes]) -> str: elif isinstance(data, bytes): return data.decode('utf-8') else: - raise f'invalid data type {type(data)}' + raise TypeError(f'invalid data type {type(data)}') # Data validation helpers diff --git a/tests/clients/test_dapr_grpc_helpers.py b/tests/clients/test_dapr_grpc_helpers.py index 6c7c27be9..137f0b12d 100644 --- a/tests/clients/test_dapr_grpc_helpers.py +++ b/tests/clients/test_dapr_grpc_helpers.py @@ -17,6 +17,8 @@ from dapr.clients.grpc._helpers import ( convert_dict_to_grpc_dict_of_any, convert_value_to_struct, + to_bytes, + to_str, ) @@ -185,5 +187,27 @@ def test_unsupported_type_raises_value_error(self): convert_dict_to_grpc_dict_of_any({'bad': [1, 2, 3]}) +class TestToBytesToStr(unittest.TestCase): + def test_to_bytes_passthrough(self): + self.assertEqual(to_bytes(b'abc'), b'abc') + + def test_to_bytes_encodes_str(self): + self.assertEqual(to_bytes('abc'), b'abc') + + def test_to_bytes_rejects_other_types(self): + with self.assertRaisesRegex(TypeError, 'invalid data type'): + to_bytes(123) # type: ignore[arg-type] + + def test_to_str_passthrough(self): + self.assertEqual(to_str('abc'), 'abc') + + def test_to_str_decodes_bytes(self): + self.assertEqual(to_str(b'abc'), 'abc') + + def test_to_str_rejects_other_types(self): + with self.assertRaisesRegex(TypeError, 'invalid data type'): + to_str(123) # type: ignore[arg-type] + + if __name__ == '__main__': unittest.main(verbosity=2)