From 069b916e9443923a2c465465289195ad83d85c4d Mon Sep 17 00:00:00 2001
From: pompolic <pompolic@special-circumstanc.es>
Date: Wed, 20 Jul 2022 18:00:31 +0200
Subject: [PATCH] HBytes string representation tests

- Also fixes double curly braces when printing HByte structs when len is 0
---
 gdb-port/ast.py            |  2 +-
 gdb-port/tests/unit/ast.py | 22 ++++++++++++++++++----
 2 files changed, 19 insertions(+), 5 deletions(-)

diff --git a/gdb-port/ast.py b/gdb-port/ast.py
index 75a79ef..1664954 100644
--- a/gdb-port/ast.py
+++ b/gdb-port/ast.py
@@ -206,7 +206,7 @@ class HBytes:
 
 	def __str__(self):
 		if self.len == 0:
-			return "{{ token: \"\", len: 0 }}"
+			return "{ token: \"\", len: 0 }"
 		else:
 			return "{{ token: \"{0}\", len: {1} }}".format(self.token.string("UTF-8", "replace", self.len), self.len)
 
diff --git a/gdb-port/tests/unit/ast.py b/gdb-port/tests/unit/ast.py
index fb5c3d3..e78ae6f 100644
--- a/gdb-port/tests/unit/ast.py
+++ b/gdb-port/tests/unit/ast.py
@@ -143,20 +143,34 @@ class HBytesStr(unittest.TestCase):
 	#@unittest.mock.patch.object(gdb.Value, '__getitem__', return_value=4)
 	#@unittest.mock.patch.object(gdb.Value, 'string', return_value='test')
 	def test_str(self, gdbv_mock):
-		gdbv_mock.__getitem__.return_value = 4
-		gdbv_mock.string.return_value = 'test'
+		len_mock = unittest.mock.MagicMock()
+		len_mock.__eq__.return_value = False
+		len_mock.__str__.return_value = "4"
+
+		token_mock = unittest.mock.MagicMock()
+		token_mock.string.return_value = 'test'
 		hb = HBytes(gdb.Value(0xdeadbeef))
-		hb.token = gdb.Value('foo') # Doesn't matter what value is used here, since string() is mocked to return 'test'
+		hb.len = len_mock
+		hb.token = token_mock
 		teststr = hb.__str__()
 		self.assertEqual(teststr, "{ token: \"test\", len: 4 }")
+		self.assertEqual(len_mock.mock_calls, [unittest.mock.call.__eq__(0),  unittest.mock._Call(("__str__", (), {}))]) # using _Call() here is a workaround to .__str__() just converting call() to a string when using the call() shorthand
+		self.assertEqual(token_mock.mock_calls, [unittest.mock.call.string("UTF-8", "replace", len_mock)])
 
 	@unittest.mock.patch('gdb.Value', autospec=True)
 	#@unittest.mock.patch.object(gdb.Value, '__getitem__', return_value=0)
 	def test_str_len_0(self, gdbv_mock):
-		gdbv_mock.__getitem__.return_value = 0
+		len_mock = unittest.mock.MagicMock()
+		len_mock.__eq__.return_value = True
+
+		token_mock = unittest.mock.MagicMock()
 		hb = HBytes(gdb.Value(0xdeadbeef))
+		hb.len = len_mock
+		hb.token = token_mock
 		teststr = hb.__str__()
 		self.assertEqual(teststr, "{ token: \"\", len: 0 }")
+		self.assertNotIn(unittest.mock.call().__str__(), len_mock.mock_calls)
+		self.assertNotIn(unittest.mock.call().__str__(), token_mock.mock_calls)
 
 
 class ASTManagerSetTopNode(unittest.TestCase):
-- 
GitLab