Debian Codegraph @

lib/tests/test_subprocess.py

raw symbols SCIP
1 # -*- coding: utf-8 -*-
2 #
3 # QBrz - Qt frontend to Breezy commands
4 #
5 # Contributors:
6 # Alexander Belchenko, 2009
7 #
8 # This program is free software; you can redistribute it and/or
9 # modify it under the terms of the GNU General Public License
10 # as published by the Free Software Foundation; either version 2
11 # of the License, or (at your option) any later version.
12 #
13 # This program is distributed in the hope that it will be useful,
14 # but WITHOUT ANY WARRANTY; without even the implied warranty of
15 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 # GNU General Public License for more details.
17 #
18 # You should have received a copy of the GNU General Public License
19 # along with this program; if not, write to the Free Software
20 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
21
22 import fastbencode as bencode
23 from io import StringIO
24
25 from breezy import (
26 errors,
27 progress,
28 urlutils,
29 )
30 from breezy.tests import (
31 TestCase,
32 features,
33 )
34 from breezy.plugins.qbrz.lib.subprocess import (
35 bittorrent_b_decode_prompt,
36 bittorrent_b_encode_prompt,
37 bittorrent_b_encode_unicode,
38 bittorrent_b_encode_exception_instance,
39 bittorrent_b_decode_exception_instance,
40 # bittorrent_b_encode_unicode_escape,
41 # bittorrent_b_decode_unicode_escape,
42 SubprocessProgressView,
43 SUB_PROGRESS,
44 )
45
46
47 class TestBencode(TestCase):
48
49
50 def test_bittorrent_b_encode_unicode(self):
51 # Encoding should ALWAYS give bytes and expects bytes BUT our routines convert
52 self.assertEqual(b"l7:versione", bittorrent_b_encode_unicode(["version"]))
53 # self.assertEqual(b"l3:add3:\u1234e", bittorrent_b_encode_unicode(["add", "\u1234"]))
54 result = bittorrent_b_encode_unicode(["add", "\u1234"])
55 self.assertEqual(b'l3:add3:\xe1\x88\xb4e', result)
56 # Now check the '\u1234' comes back when it's a string...
57 u = bencode.bdecode(result)
58 self.assertIsInstance(u, list)
59 self.assertEqual("\u1234", u[1].decode('utf-8'))
60
61 def test_bad_bittorrent_examples(self):
62 self.assertRaises(ValueError, bencode.bdecode, b'@/tmp/QBrz/qsubprocess/tmprkdrsdyi')
63
64 def test_bittorrent_b_encode_prompt(self):
65 self.assertEqual(b"4:spam", bittorrent_b_encode_prompt(utf_string='spam'))
66 self.assertEqual(b"9:spam\neggs", bittorrent_b_encode_prompt('spam' + '\n' + 'eggs'))
67 # "Р\nС" is NOT "P\nC" it's b'\xd0\xa0\n\xd0\xa1'
68 # CYRILLIC CAPITAL LETTER ER, \n and CYRILLIC CAPITAL LETTER ES
69 self.assertEqual(b'5:\xd0\xa0\n\xd0\xa1', bittorrent_b_encode_prompt("Р\nС"))
70
71 def test_bittorrent_b_decode_prompt(self):
72 # Decode must always give not-bytes
73 self.assertEqual('spam', bittorrent_b_decode_prompt(b"4:spam"))
74 self.assertEqual('spam'+'\n'+'eggs', bittorrent_b_decode_prompt(b"9:spam\neggs"))
75 # "Р\nС" is NOT "P\nC" it's b'\xd0\xa0\n\xd0\xa1'
76 # CYRILLIC CAPITAL LETTER ER, \n and CYRILLIC CAPITAL LETTER ES
77 self.assertEqual("Р\nС", bittorrent_b_decode_prompt(b'5:\xd0\xa0\n\xd0\xa1'))
78
79
80 # def test_bittorrent_b_encode_unicode_escape_dict(self):
81 # self.assertEqual({'key': 'foo\\nbar', 'ukey': '\\u1234'},
82 # bittorrent_b_encode_unicode_escape({'key': 'foo\nbar', 'ukey': '\u1234'}))
83
84 # def test_bittorrent_b_decode_unicode_escape_dict(self):
85 # self.assertEqual({'key': 'foo\nbar', 'ukey': '\u1234'},
86 # bittorrent_b_decode_unicode_escape({'key': 'foo\\nbar', 'ukey': '\\u1234'}))
87
88
89 class TestExceptionInstanceSerialisation(TestCase):
90 """Check exceptions can serialised safely with needed details preserved"""
91
92 def check_exception_instance(self, e):
93 encoded = bittorrent_b_encode_exception_instance(e)
94 name, attr_dict = bittorrent_b_decode_exception_instance(encoded)
95 self.assertEqual(name, e.__class__.__name__)
96 return attr_dict
97
98 def test_simple_error(self):
99 """A common error with just an args attribute"""
100 self.check_exception_instance(ValueError("Simple"))
101 # TODO: if transmitted assert args/message in return dict
102
103 def test_non_ascii_bytes(self):
104 """An error with a non-ascii bytestring attribute"""
105 self.check_exception_instance(OSError(13, "Lupa ev\xc3\xa4tty"))
106 # TODO: if transmitted assert errno/strerror/etc in return dict
107
108 def test_unreprable_obj(self):
109 """Ensure an object with a broken repr doesn't break the exception"""
110 class Bad(object):
111 def __repr__(self):
112 return self.attribute_that_does_not_exist
113 self.check_exception_instance(ValueError(Bad()))
114 # TODO: if transmitted assert message equals the placeholder string
115
116 def test_uncommittedchanges_display_url(self):
117 """The display_url of UncommittedChanges errors should be serialised"""
118 self.requireFeature(features.UnicodeFilenameFeature)
119 path = "\u1234"
120 class FakeTree(object):
121 def __init__(self, url):
122 self.user_url = url
123 attrs = self.check_exception_instance(errors.UncommittedChanges(FakeTree(urlutils.local_path_to_url(path))))
124 self.assertIsSameRealPath(path, urlutils.local_path_from_url(attrs["display_url"]))
125
126
127 class TestSubprocessProgressView(TestCase):
128 """Check serialisation of progress updates"""
129
130 def decode_progress(self, bencoded_data:bytes) -> list:
131 """Decodes string of bencoded progress output to list of updates
132
133 Duplicates logic decoding logic from `SubProcessWidget.readStdout` and
134 `SubProcessWidget.setProgress` which would be good to factor out.
135
136 bdecode requires bencoded bytes and bencoded_data should BE bytes
137 but doesn't appear to be.
138 """
139 updates = []
140 for line in bencoded_data.split("\n"):
141 if line.startswith(SUB_PROGRESS):
142 # bdecode needs bytes, but we need to snip off the leading SUB_PROGRESS first
143 n, transport_activity, task_info = bencode.bdecode(line[len(SUB_PROGRESS):].encode('utf-8'))
144 if n == 1000000 and not task_info:
145 task_message = "Finished!"
146 else:
147 # task_info will be a list of byte-strings, so join and then decode
148 task_message = b" / ".join(task_info).decode("utf-8")
149 # transport_activity will be bytes too...
150 updates.append((n, transport_activity.decode('utf-8'), task_message))
151 # Now we'll return a list of lines like: (0, '', 'Finding revisions / 0/2')
152 return updates
153
154 def make_stream_and_task(self):
155 """Create a new output stream and ProgressTask for testing"""
156 sio = StringIO()
157 task = progress.ProgressTask(progress_view=SubprocessProgressView(sio))
158 return sio, task
159
160 @staticmethod
161 def refresh(task):
162 """Allow a new update without a time delay"""
163 task.progress_view._last_repaint = 0
164
165 def test_task_one_update(self):
166 """Sending a single progress update should work"""
167 sio, task = self.make_stream_and_task()
168 task.update("Finding revisions", 0, 2)
169 self.assertEqual([(0, "", "Finding revisions / 0/2")],
170 self.decode_progress(sio.getvalue()))
171
172 def test_task_multiple_updates(self):
173 """Sending a single progress update should work"""
174 sio, task = self.make_stream_and_task()
175 task.update("Finding revisions", 0, 2)
176 self.refresh(task)
177 task.update("Finding revisions", 1, 2)
178 self.refresh(task)
179 task.update("Finding revisions", 2, 2)
180 self.assertEqual([
181 (0, "", "Finding revisions / 0/2"),
182 (500000, "", "Finding revisions / 1/2"),
183 (1000000, "", "Finding revisions / 2/2")],
184 self.decode_progress(sio.getvalue()))
185
186 def test_task_update_and_finished(self):
187 """Sending a single progress update should work"""
188 sio, task = self.make_stream_and_task()
189 task.update("Finding revisions", 0, 2)
190 self.refresh(task)
191 # RJLRJL task.finished() no longer exists...
192 # try:
193 # task.finished()
194 # except AttributeError:
195 # self.knownFailure("No ui_factory so calls missing task_finished")
196 self.assertEqual([(0, "", "Finding revisions / 0/2")], self.decode_progress(sio.getvalue()))
197
198 def test_task_non_ascii_message(self):
199 """A localised progress message should be transmitted cleanly"""
200 sio, task = self.make_stream_and_task()
201 # Would be nice to use an actual translation
202 task.update("\u1234", 0, 2)
203 self.assertEqual([(0, "", "\u1234 / 0/2")], self.decode_progress(sio.getvalue()))
204
205