Debian Codegraph @

test/test_methods.py

raw
1 # test/test_methods.py
2 # Part of ‘dput’, a Debian package upload toolkit.
3 #
4 # This is free software, and you are welcome to redistribute it under
5 # certain conditions; see the end of this file for copyright
6 # information, grant of license, and disclaimer of warranty.
7
8 """ Unit tests for upload method behaviour. """
9
10 import collections
11 import contextlib
12 import doctest
13 import ftplib
14 import getpass
15 import http.client
16 import importlib
17 import io
18 import itertools
19 import os
20 import os.path
21 import pkgutil
22 import stat
23 import subprocess
24 import sys
25 import tempfile
26 import textwrap
27 import unittest.mock
28 import urllib.parse
29 import urllib.request
30
31 import testscenarios
32 import testtools
33
34 import dput.dput
35 import dput.helper.dputhelper
36 import dput.methods
37 import dput.methods.ftp
38 import dput.methods.http
39 import dput.methods.https
40 import dput.methods.local
41 import dput.methods.rsync
42 import dput.methods.scp
43
44 from .helper import (
45 ARG_ANY,
46 EXIT_STATUS_FAILURE,
47 EXIT_STATUS_SUCCESS,
48 FakeSystemExit,
49 FileDouble,
50 SubprocessDouble,
51 make_fake_fqdn,
52 patch_os_lstat,
53 patch_os_stat,
54 patch_subprocess_check_call,
55 patch_system_interfaces,
56 setup_file_double_behaviour,
57 )
58 from .test_dputhelper import (
59 patch_filewithprogress,
60 )
61
62
63 class import_upload_functions_TestCase(
64 testscenarios.WithScenarios,
65 testtools.TestCase):
66 """ Test cases for `import_upload_functions` function. """
67
68 scenarios = [
69 ('empty', {
70 'module_names': [],
71 }),
72 ('one', {
73 'module_names': ["foo"],
74 }),
75 ('three', {
76 'module_names': ["foo", "bar", "baz"],
77 }),
78 ]
79
80 for (scenario_name, scenario) in scenarios:
81 modules_by_name = collections.OrderedDict()
82 iter_modules_result = []
83 for module_name in scenario['module_names']:
84 module = unittest.mock.Mock()
85 module.__name__ = module_name
86 module.upload = unittest.mock.Mock()
87 modules_by_name[module_name] = module
88 module_entry = (module, module_name, False)
89 iter_modules_result.append(module_entry)
90 scenario['modules_by_name'] = modules_by_name
91 scenario['iter_modules_result'] = iter_modules_result
92 del scenario_name, scenario
93
94 def setUp(self):
95 """ Set up test fixtures. """
96 super().setUp()
97 patch_system_interfaces(self)
98
99 self.patch_import_functions()
100
101 def patch_import_functions(self):
102 """ Patch import functions used by the function. """
103 self.patch_pkgutil_iter_modules()
104 self.patch_importlib_import_module()
105
106 def patch_pkgutil_iter_modules(self):
107 """ Patch `pkgutil.iter_modules` function for this test case. """
108 func_patcher = unittest.mock.patch.object(
109 pkgutil, "iter_modules", autospec=True)
110 func_patcher.start()
111 self.addCleanup(func_patcher.stop)
112 pkgutil.iter_modules.return_value = self.iter_modules_result
113
114 def patch_importlib_import_module(self):
115 """ Patch `importlib.import_module` function for this test case. """
116 func_patcher = unittest.mock.patch.object(
117 importlib, "import_module", autospec=True)
118 func_patcher.start()
119 self.addCleanup(func_patcher.stop)
120
121 def fake_import_module(full_name):
122 module_name = full_name.split(".")[-1]
123 module = self.modules_by_name[module_name]
124 return module
125
126 importlib.import_module.side_effect = fake_import_module
127
128 @unittest.mock.patch.object(dput.dput, 'debug', new=True)
129 def test_emits_debug_message_for_modules_found(self):
130 """ Should emit a debug message for the modules found. """
131 expected_message = "D: modules_found: {names!r}".format(
132 names=self.module_names)
133 dput.dput.import_upload_functions()
134 self.assertIn(expected_message, sys.stdout.getvalue())
135
136 @unittest.mock.patch.object(dput.dput, 'debug', new=True)
137 def test_emits_debug_message_for_each_import(self):
138 """ Should emit a debug message for each module imported. """
139 dput.dput.import_upload_functions()
140 for (module_name, module) in self.modules_by_name.items():
141 expected_message = "D: Module: {name} ({module!r})".format(
142 name=module_name, module=module)
143 self.assertIn(expected_message, sys.stdout.getvalue())
144
145 @unittest.mock.patch.object(dput.dput, 'debug', new=True)
146 def test_emits_debug_message_for_each_upload_method(self):
147 """ Should emit a debug message for each upload method. """
148 dput.dput.import_upload_functions()
149 for module_name in self.module_names:
150 expected_message = "D: Method name: {name}".format(
151 name=module_name)
152 self.assertIn(expected_message, sys.stdout.getvalue())
153
154 def test_returns_expected_function_mapping(self):
155 """ Should return expected mapping of upload functions. """
156 result = dput.dput.import_upload_functions()
157 expected_result = {
158 name: self.modules_by_name[name].upload
159 for name in self.module_names}
160 self.assertEqual(expected_result, result)
161
162
163 def patch_getpass_getpass(testcase):
164 """ Patch the `getpass.getpass` function for the test case. """
165 func_patcher = unittest.mock.patch.object(
166 getpass, "getpass", autospec=True)
167 func_patcher.start()
168 testcase.addCleanup(func_patcher.stop)
169
170
171 class upload_BaseTestCase(
172 testscenarios.WithScenarios,
173 testtools.TestCase):
174 """ Base for test cases for method modules `upload` functions. """
175
176 files_scenarios = [
177 ('file-list-empty', {
178 'paths_to_upload': [],
179 }),
180 ('file-list-one', {
181 'paths_to_upload': [tempfile.mktemp()],
182 }),
183 ('file-list-three', {
184 'paths_to_upload': [tempfile.mktemp() for __ in range(3)],
185 }),
186 ]
187
188 check_call_scenarios = [
189 ('check-call-success', {
190 'check_call_scenario_name': 'success',
191 }),
192 ('check-call-failure', {
193 'check_call_scenario_name': 'failure',
194 'check_call_error': subprocess.CalledProcessError,
195 }),
196 ]
197
198 check_call_success_scenarios = [
199 (name, params) for (name, params) in check_call_scenarios
200 if 'check_call_error' not in params]
201
202 incoming_scenarios = [
203 ('incoming-simple', {
204 'incoming_path': tempfile.mktemp(),
205 }),
206 ('incoming-no-leading-slash', {
207 'incoming_path': tempfile.mktemp().lstrip("/"),
208 }),
209 ('incoming-has-trailing-slash', {
210 'incoming_path': "{}/".format(tempfile.mktemp()),
211 }),
212 ]
213
214 def setUp(self):
215 """ Set up test fixtures. """
216 super().setUp()
217 patch_system_interfaces(self)
218
219 patch_subprocess_check_call(self)
220
221 patch_os_stat(self)
222 self.set_file_doubles()
223 setup_file_double_behaviour(self)
224
225 patch_filewithprogress(self)
226
227 self.set_test_args()
228
229 def set_file_doubles(self):
230 """ Set the file doubles for this test case. """
231 for path in self.paths_to_upload:
232 fake_file = getattr(self, 'fake_file', None)
233 double = FileDouble(path, fake_file)
234 double.set_os_stat_scenario(
235 getattr(self, 'os_stat_scenario_name', "okay"))
236 double.register_for_testcase(self)
237
238 func_patcher = unittest.mock.patch.object(
239 double.fake_file, "close", autospec=True)
240 func_patcher.start()
241 self.addCleanup(func_patcher.stop)
242
243 def set_test_args(self):
244 """ Set the arguments for the test call to the function. """
245 raise NotImplementedError
246
247 def get_command_args_from_latest_check_call(self):
248 """ Get command line arguments from latest `subprocess.check_call`. """
249 latest_call = subprocess.check_call.call_args
250 (args, __) = latest_call
251 command_args = args[0]
252 return command_args
253
254
255 class local_upload_TestCase(upload_BaseTestCase):
256 """ Test cases for `methods.local.upload` function. """
257
258 scenarios = testscenarios.multiply_scenarios(
259 upload_BaseTestCase.incoming_scenarios,
260 upload_BaseTestCase.files_scenarios,
261 upload_BaseTestCase.check_call_success_scenarios)
262
263 command_file_path = os.path.join("/usr/bin", "install")
264
265 def setUp(self):
266 """ Set up test fixtures. """
267 super().setUp()
268
269 self.set_subprocess_double()
270
271 def set_test_args(self):
272 """ Set the arguments for the test call to the function. """
273 self.test_args = dict(
274 fqdn=object(),
275 login=object(),
276 incoming=self.incoming_path,
277 files_to_upload=self.paths_to_upload,
278 debug=None,
279 compress=object(),
280 progress=object(),
281 )
282
283 def set_subprocess_double(self):
284 """ Set the test double for the subprocess. """
285 argv = [self.command_file_path, "-m", ARG_ANY, ARG_ANY]
286 double = SubprocessDouble(self.command_file_path, argv=argv)
287 double.register_for_testcase(self)
288 double.set_subprocess_check_call_scenario(
289 self.check_call_scenario_name)
290 self.subprocess_double = double
291
292 def test_calls_check_call_with_install_command(self):
293 """ Should call `subprocess.check_call` to invoke ‘install’. """
294 dput.methods.local.upload(**self.test_args)
295 command_args = self.get_command_args_from_latest_check_call()
296 expected_command = self.command_file_path
297 self.assertEqual(expected_command, command_args[0])
298
299 def test_calls_check_call_with_mode_option_in_command(self):
300 """ Should call `subprocess.check_call`, invoke command with mode. """
301 dput.methods.local.upload(**self.test_args)
302 command_args = self.get_command_args_from_latest_check_call()
303 expected_mode = (
304 stat.S_IRUSR | stat.S_IWUSR
305 | stat.S_IRGRP
306 | stat.S_IROTH)
307 expected_mode_text = "{mode:04o}".format(mode=expected_mode)[-3:]
308 expected_option_args = ["-m", expected_mode_text]
309 self.assertEqual(expected_option_args, command_args[1:3])
310
311 def test_calls_check_call_with_file_paths_in_command(self):
312 """ Should call `subprocess.check_call` with file paths in command. """
313 dput.methods.local.upload(**self.test_args)
314 command_args = self.get_command_args_from_latest_check_call()
315 self.assertEqual(self.paths_to_upload, command_args[3:-1])
316
317 def test_calls_check_call_with_incoming_path_as_final_arg(self):
318 """ Should call `subprocess.check_call` with incoming path. """
319 dput.methods.local.upload(**self.test_args)
320 command_args = self.get_command_args_from_latest_check_call()
321 self.assertEqual(self.incoming_path, command_args[-1])
322
323 def test_emits_debug_message_for_upload_command(self):
324 """ Should emit a debug message for the upload command. """
325 self.test_args['debug'] = True
326 dput.methods.local.upload(**self.test_args)
327 expected_message = textwrap.dedent("""\
328 D: Uploading with cp to {dir_path}
329 D: ...
330 """).format(dir_path=self.incoming_path)
331 self.assertThat(
332 sys.stdout.getvalue(),
333 testtools.matchers.DocTestMatches(
334 expected_message, flags=doctest.ELLIPSIS))
335
336 def test_calls_sys_exit_if_check_call_returns_nonzero(self):
337 """ Should call `sys.exit` if `subprocess.check_call` fails. """
338 self.subprocess_double.set_subprocess_check_call_scenario('failure')
339 with testtools.ExpectedException(FakeSystemExit):
340 dput.methods.local.upload(**self.test_args)
341 expected_output = textwrap.dedent("""\
342 Error while uploading.
343 """)
344 self.assertIn(expected_output, sys.stdout.getvalue())
345 sys.exit.assert_called_with(EXIT_STATUS_FAILURE)
346
347
348 class ftp_upload_TestCase(upload_BaseTestCase):
349 """ Test cases for `methods.ftp.upload` function. """
350
351 scenarios = NotImplemented
352
353 def setUp(self):
354 """ Set up test fixtures. """
355 super().setUp()
356
357 self.set_ftp_client()
358 self.patch_ftplib_ftp()
359
360 patch_getpass_getpass(self)
361 self.fake_password = self.getUniqueString()
362 getpass.getpass.return_value = self.fake_password
363 if not hasattr(self, 'expected_password'):
364 self.expected_password = self.fake_password
365
366 def set_test_args(self):
367 """ Set the arguments for the test call to the function. """
368 if not hasattr(self, 'progress_type'):
369 self.progress_type = 0
370 self.test_args = dict(
371 fqdn=make_fake_fqdn(self),
372 login=self.login,
373 incoming=self.incoming_path,
374 files_to_upload=self.paths_to_upload,
375 debug=False,
376 ftp_mode=self.ftp_mode,
377 progress=self.progress_type,
378 port=object(),
379 )
380
381 def set_ftp_client(self):
382 """ Set the FTP client double. """
383 self.ftp_client = unittest.mock.MagicMock(name="FTP")
384
385 def patch_ftplib_ftp(self):
386 """ Patch `ftplib.FTP` class for this test case. """
387 patcher = unittest.mock.patch.object(
388 ftplib, "FTP", autospec=True)
389 patcher.start()
390 self.addCleanup(patcher.stop)
391
392 ftplib.FTP.return_value = self.ftp_client
393
394
395 class ftp_upload_NormalFilesTestCase(ftp_upload_TestCase):
396 """ Test cases for `methods.ftp.upload` function, upload normal files. """
397
398 login_scenarios = [
399 ('anonymous', {
400 'login': "anonymous",
401 'expected_password': "[email protected]",
402 }),
403 ('username', {
404 'login': "lorem",
405 }),
406 ]
407
408 ftp_client_scenarios = [
409 ('default', {
410 'ftp_mode': False,
411 }),
412 ('passive-mode', {
413 'ftp_mode': True,
414 }),
415 ]
416
417 scenarios = testscenarios.multiply_scenarios(
418 upload_BaseTestCase.incoming_scenarios,
419 upload_BaseTestCase.files_scenarios,
420 login_scenarios, ftp_client_scenarios)
421
422 def test_emits_debug_message_for_connect(self):
423 """ Should emit debug message for successful connect. """
424 self.test_args['debug'] = True
425 dput.methods.ftp.upload(**self.test_args)
426 expected_fqdn = self.test_args['fqdn']
427 expected_output = textwrap.dedent("""\
428 D: FTP-Connection to host: {fqdn}
429 """).format(fqdn=expected_fqdn)
430 self.assertIn(expected_output, sys.stdout.getvalue())
431
432 def test_emits_no_debug_message_when_debug_false(self):
433 """ Should emit no debug messages when `debug` is false. """
434 self.test_args['debug'] = False
435 dput.methods.ftp.upload(**self.test_args)
436 debug_message_lines = [
437 line for line in sys.stdout.getvalue().split()
438 if line.startswith("D: ")]
439 self.assertEqual([], debug_message_lines)
440
441 def test_calls_ftp_connect_with_expected_args(self):
442 """ Should call `FTP.connect` with expected args. """
443 dput.methods.ftp.upload(**self.test_args)
444 expected_args = (
445 self.test_args['fqdn'],
446 self.test_args['port'],
447 )
448 self.ftp_client.connect.assert_called_with(*expected_args)
449
450 def test_emits_error_message_when_ftp_connect_error(self):
451 """ Should emit error message when `FTP.connect` raises error. """
452 self.ftp_client.connect.side_effect = ftplib.error_temp
453 with contextlib.suppress(FakeSystemExit):
454 dput.methods.ftp.upload(**self.test_args)
455 expected_output = "Connection failed, aborting"
456 self.assertIn(expected_output, sys.stdout.getvalue())
457
458 def test_calls_sys_exit_when_ftp_connect_permission_error(self):
459 """ Should call `sys.exit` when `FTP.connect` raises error. """
460 self.ftp_client.connect.side_effect = ftplib.error_temp
461 with testtools.ExpectedException(FakeSystemExit):
462 dput.methods.ftp.upload(**self.test_args)
463 sys.exit.assert_called_with(EXIT_STATUS_FAILURE)
464
465 def test_calls_ftp_login_with_expected_args(self):
466 """ Should call `FTP.login` with expected args. """
467 dput.methods.ftp.upload(**self.test_args)
468 expected_args = (
469 self.test_args['login'],
470 self.expected_password,
471 )
472 self.ftp_client.login.assert_called_with(*expected_args)
473
474 def test_emits_error_message_when_ftp_login_permission_error(self):
475 """ Should emit error message when `FTP.login` permission error. """
476 self.ftp_client.login.side_effect = ftplib.error_perm
477 with contextlib.suppress(FakeSystemExit):
478 dput.methods.ftp.upload(**self.test_args)
479 expected_output = "Wrong Password"
480 self.assertIn(expected_output, sys.stdout.getvalue())
481
482 def test_calls_sys_exit_when_ftp_login_permission_error(self):
483 """ Should call `sys.exit` when `FTP.login` permission error. """
484 self.ftp_client.login.side_effect = ftplib.error_perm
485 with testtools.ExpectedException(FakeSystemExit):
486 dput.methods.ftp.upload(**self.test_args)
487 sys.exit.assert_called_with(EXIT_STATUS_FAILURE)
488
489 def test_emits_error_message_when_ftp_login_eof_error(self):
490 """ Should emit error message when `FTP.login` EOF error. """
491 self.ftp_client.login.side_effect = EOFError
492 with contextlib.suppress(FakeSystemExit):
493 dput.methods.ftp.upload(**self.test_args)
494 expected_output = "Server closed the connection"
495 self.assertIn(expected_output, sys.stdout.getvalue())
496
497 def test_calls_sys_exit_when_ftp_login_eof_error(self):
498 """ Should call `sys.exit` when `FTP.login` EOF error. """
499 self.ftp_client.login.side_effect = EOFError
500 with testtools.ExpectedException(FakeSystemExit):
501 dput.methods.ftp.upload(**self.test_args)
502 sys.exit.assert_called_with(EXIT_STATUS_FAILURE)
503
504 def test_calls_ftp_set_pasv_with_expected_args(self):
505 """ Should call `FTP.set_pasv` with expected args. """
506 dput.methods.ftp.upload(**self.test_args)
507 expected_mode = bool(self.test_args['ftp_mode'])
508 expected_args = (expected_mode,)
509 self.ftp_client.set_pasv.assert_called_with(*expected_args)
510
511 def test_calls_ftp_cwd_with_expected_args(self):
512 """ Should call `FTP.cwd` with expected args. """
513 dput.methods.ftp.upload(**self.test_args)
514 expected_path = self.incoming_path
515 expected_args = (expected_path,)
516 self.ftp_client.cwd.assert_called_with(*expected_args)
517
518 def test_emits_debug_message_for_cwd(self):
519 """ Should emit debug message for successful `FTP.cwd`. """
520 self.test_args['debug'] = True
521 dput.methods.ftp.upload(**self.test_args)
522 expected_output = textwrap.dedent("""\
523 D: Directory to upload to: {path}
524 """).format(path=self.incoming_path)
525 self.assertIn(expected_output, sys.stdout.getvalue())
526
527 def test_emits_error_message_when_destination_directory_not_found(self):
528 """ Should emit error message when destination directory not found. """
529 error = ftplib.error_perm("550 Not Found")
530 self.ftp_client.cwd.side_effect = error
531 with contextlib.suppress(FakeSystemExit):
532 dput.methods.ftp.upload(**self.test_args)
533 expected_output = "Directory to upload to does not exist."
534 self.assertIn(expected_output, sys.stdout.getvalue())
535
536 def test_calls_sys_exit_when_ftp_cwd_permission_error(self):
537 """ Should call `sys.exit` when `FTP.cwd` permission error. """
538 error = ftplib.error_perm("550 Not Found")
539 self.ftp_client.cwd.side_effect = error
540 with testtools.ExpectedException(FakeSystemExit):
541 dput.methods.ftp.upload(**self.test_args)
542 sys.exit.assert_called_with(EXIT_STATUS_FAILURE)
543
544 def test_propagates_exception_when_ftp_cwd_permission_error(self):
545 """ Should call `sys.exit` when `FTP.cwd` permission error. """
546 error = ftplib.error_perm("500 Bad Stuff Happened")
547 self.ftp_client.cwd.side_effect = error
548 with testtools.ExpectedException(error.__class__):
549 dput.methods.ftp.upload(**self.test_args)
550
551 def test_propagates_exception_when_ftp_cwd_eof_error(self):
552 """ Should call `sys.exit` when `FTP.cwd` EOF error. """
553 error = EOFError()
554 self.ftp_client.cwd.side_effect = error
555 with testtools.ExpectedException(error.__class__):
556 dput.methods.ftp.upload(**self.test_args)
557
558 def test_emits_debug_message_for_each_file(self):
559 """ Should emit debug message for each file to upload. """
560 self.test_args['debug'] = True
561 dput.methods.ftp.upload(**self.test_args)
562 expected_output = "".join(textwrap.dedent("""\
563 D: Uploading File: {path}
564 Uploading {filename}: done.
565 """).format(path=path, filename=os.path.basename(path))
566 for path in self.paths_to_upload)
567 self.assertIn(expected_output, sys.stdout.getvalue())
568
569 def test_calls_ftp_storbinary_for_each_file(self):
570 """ Should call `FTP.storbinary` for each file to upload. """
571 dput.methods.ftp.upload(**self.test_args)
572 registry = FileDouble.get_registry_for_testcase(self)
573 expected_blocksize = 1024
574 expected_calls = [
575 unittest.mock.call(
576 "STOR {filename}".format(filename=os.path.basename(path)),
577 registry[path].fake_file_opened_with_mode_and_encoding(
578 mode='b'),
579 expected_blocksize)
580 for path in self.paths_to_upload]
581 self.ftp_client.storbinary.assert_has_calls(
582 expected_calls, any_order=True)
583
584 def test_calls_close_for_each_file(self):
585 """ Should call `file.close` for each file to upload. """
586 dput.methods.ftp.upload(**self.test_args)
587 registry = FileDouble.get_registry_for_testcase(self)
588 for path in self.paths_to_upload:
589 file_double = registry[path]
590 fake_file = file_double.fake_file_opened_with_mode_and_encoding(
591 mode='b')
592 self.assertTrue(fake_file.closed)
593
594
595 class ftp_upload_ErrorTestCase(ftp_upload_TestCase):
596 """ Test cases for `methods.ftp.upload` function, error conditions. """
597
598 login_scenarios = [
599 ('login-anonymous', {
600 'login': "anonymous",
601 'expected_password': "[email protected]",
602 }),
603 ]
604
605 ftp_client_scenarios = [
606 ('client-default', {
607 'ftp_mode': False,
608 }),
609 ]
610
611 progress_scenarios = [
612 ('progress-type-0', {
613 'progress_type': 0,
614 }),
615 ('progress-type-1', {
616 'progress_type': 1,
617 }),
618 ('progress-type-2', {
619 'progress_type': 2,
620 }),
621 ]
622
623 files_scenarios = [
624 (scenario_name, scenario) for (scenario_name, scenario)
625 in upload_BaseTestCase.files_scenarios
626 if scenario['paths_to_upload']]
627
628 scenarios = testscenarios.multiply_scenarios(
629 upload_BaseTestCase.incoming_scenarios,
630 files_scenarios,
631 login_scenarios, ftp_client_scenarios, progress_scenarios)
632
633 def test_emits_no_debug_message_when_debug_false(self):
634 """ Should emit no debug messages when `debug` is false. """
635 self.test_args['debug'] = False
636 error = ftplib.error_perm("553 Exists")
637 self.ftp_client.storbinary.side_effect = error
638 dput.methods.ftp.upload(**self.test_args)
639 debug_message_lines = [
640 line for line in sys.stdout.getvalue().split()
641 if line.startswith("D: ")]
642 self.assertEqual([], debug_message_lines)
643
644 def test_emits_warning_when_remote_file_exists(self):
645 """ Should emit a warning message when remote file exists. """
646 error = ftplib.error_perm("553 Exists")
647 self.ftp_client.storbinary.side_effect = error
648 dput.methods.ftp.upload(**self.test_args)
649 for path in self.paths_to_upload:
650 expected_output = textwrap.dedent("""\
651 Leaving existing {path} on the server and continuing
652 """).format(path=os.path.basename(path))
653 self.expectThat(
654 sys.stdout.getvalue(),
655 testtools.matchers.Contains(expected_output))
656
657 def test_omits_sys_exit_when_remote_file_exists(self):
658 """ Should omit call to `sys.exit` when remote file exists. """
659 error = ftplib.error_perm("553 Exists")
660 self.ftp_client.storbinary.side_effect = error
661 dput.methods.ftp.upload(**self.test_args)
662 self.assertFalse(sys.exit.called)
663
664 def test_emits_error_message_when_storbinary_permanent_failure(self):
665 """
666 Should emit an error message when `FTP.storbinary` permanent failure.
667 """
668 error = ftplib.error_perm("504 Weird Stuff Happened")
669 self.ftp_client.storbinary.side_effect = error
670 with contextlib.suppress(FakeSystemExit):
671 dput.methods.ftp.upload(**self.test_args)
672 expected_output = (
673 "Note: This error might indicate a problem with"
674 " your passive_ftp setting.\n")
675 self.expectThat(
676 sys.stdout.getvalue(),
677 testtools.matchers.Contains(expected_output))
678
679 def test_calls_sys_exit_when_storbinary_permanent_failure(self):
680 """ Should call `sys.exit` when `FTP.storbinary` permanent failure. """
681 error = ftplib.error_perm("504 Weird Stuff Happened")
682 self.ftp_client.storbinary.side_effect = error
683 with testtools.ExpectedException(FakeSystemExit):
684 dput.methods.ftp.upload(**self.test_args)
685 sys.exit.assert_called_with(EXIT_STATUS_FAILURE)
686
687 def test_omits_error_message_when_temporary_error(self):
688 """ Should not emit an error message when error code 4xx. """
689 error = ftplib.error_perm("472 Semi-Weird Stuff Happened")
690 self.ftp_client.storbinary.side_effect = error
691 with contextlib.suppress(FakeSystemExit):
692 dput.methods.ftp.upload(**self.test_args)
693 error_message_lines = [
694 line for line in sys.stdout.getvalue().split()
695 if line.startswith("E ")]
696 self.assertEqual([], error_message_lines)
697
698 def test_calls_sys_exit_when_temporary_error(self):
699 """ Should call `sys.exit` when `FTP.storbinary` temporary failure. """
700 error = ftplib.error_perm("472 Semi-Weird Stuff Happened")
701 self.ftp_client.storbinary.side_effect = error
702 with testtools.ExpectedException(FakeSystemExit):
703 dput.methods.ftp.upload(**self.test_args)
704 sys.exit.assert_called_with(EXIT_STATUS_FAILURE)
705
706 def test_emits_debug_message_when_open_failure(self):
707 """ Should emit a debug message when `builtins.open` failure. """
708 self.test_args['debug'] = True
709 registry = FileDouble.get_registry_for_testcase(self)
710 for path in self.paths_to_upload:
711 double = registry[path]
712 double.set_open_scenario('nonexist')
713 with contextlib.suppress(EnvironmentError):
714 dput.methods.ftp.upload(**self.test_args)
715 expected_output = (
716 "D: Should exit silently now, but"
717 " will throw exception for debug.")
718 self.assertIn(expected_output, sys.stdout.getvalue())
719
720 def test_propagates_error_from_storbinary_for_debug(self):
721 """ Should propagate error from `FTP.storbinary` when debug. """
722 self.test_args['debug'] = True
723 error = ftplib.error_perm("504 Weird Stuff Happened")
724 self.ftp_client.storbinary.side_effect = error
725 with testtools.ExpectedException(error.__class__):
726 dput.methods.ftp.upload(**self.test_args)
727
728 def test_propagates_error_from_quit_for_debug(self):
729 """ Should propagate error from `FTP.quit` when debug. """
730 self.test_args['debug'] = True
731 error = ftplib.error_perm("504 Weird Stuff Happened")
732 self.ftp_client.quit.side_effect = error
733 with testtools.ExpectedException(error.__class__):
734 dput.methods.ftp.upload(**self.test_args)
735
736 def test_emits_debug_message_from_quit_when_debug_true(self):
737 """ Should emit text of error from `FTP.quit`. """
738 self.test_args['debug'] = True
739 error = ftplib.error_perm("504 Weird Stuff Happened")
740 self.ftp_client.quit.side_effect = error
741 with testtools.ExpectedException(error.__class__):
742 dput.methods.ftp.upload(**self.test_args)
743 expected_output = str(error)
744 self.assertIn(expected_output, sys.stdout.getvalue())
745
746 def test_emits_no_debug_message_from_quit_when_debug_false(self):
747 """ Should not raise nor emit any error from `FTP.quit`. """
748 self.test_args['debug'] = False
749 error = ftplib.error_perm("504 Weird Stuff Happened")
750 self.ftp_client.quit.side_effect = error
751 dput.methods.ftp.upload(**self.test_args)
752 unwanted_output = str(error)
753 self.assertNotIn(unwanted_output, sys.stdout.getvalue())
754
755
756 def make_expected_filewithprogress_attributes_by_path(testcase, attrs):
757 """ Make a mapping from path to expected FileWithProgress attribs. """
758 expected_attributes_by_path = {}
759 registry = FileDouble.get_registry_for_testcase(testcase)
760 for path in testcase.paths_to_upload:
761 file_double = registry[path]
762 with open(path, mode='rb') as fake_file:
763 expected_attributes = {
764 'f': fake_file,
765 'size': file_double.stat_result.st_size,
766 }
767 expected_attributes.update(attrs)
768 expected_attributes_by_path[path] = expected_attributes
769
770 return expected_attributes_by_path
771
772
773 class ftp_upload_ProgressTestCase(ftp_upload_TestCase):
774 """ Test cases for `methods.ftp.upload` function, with progress meter. """
775
776 login_scenarios = [
777 ('anonymous', {
778 'login': "anonymous",
779 'expected_password': "[email protected]",
780 }),
781 ]
782
783 ftp_client_scenarios = [
784 ('default', {
785 'ftp_mode': False,
786 }),
787 ]
788
789 progress_scenarios = [
790 ('progress-type-1', {
791 'progress_type': 1,
792 }),
793 ('progress-type-2', {
794 'progress_type': 2,
795 }),
796 ]
797
798 scenarios = testscenarios.multiply_scenarios(
799 upload_BaseTestCase.incoming_scenarios,
800 upload_BaseTestCase.files_scenarios,
801 login_scenarios, ftp_client_scenarios, progress_scenarios)
802
803 def test_calls_storbinary_with_filewithprogress(self):
804 """ Should use a `FileWithProgress` to call `FTP.storbinary`. """
805 dput.methods.ftp.upload(**self.test_args)
806 expected_calls = [
807 unittest.mock.call(
808 unittest.mock.ANY, self.fake_filewithprogress,
809 unittest.mock.ANY)
810 for path in self.paths_to_upload]
811 self.ftp_client.storbinary.assert_has_calls(
812 expected_calls, any_order=True)
813
814 def test_filewithprogress_has_expected_attributes(self):
815 """ Should have expected attributes on the `FileWithProgress`. """
816 expected_attributes_by_path = (
817 make_expected_filewithprogress_attributes_by_path(
818 self, {'ptype': self.progress_type}))
819 dput.methods.ftp.upload(**self.test_args)
820 for call in self.ftp_client.storbinary.mock_calls:
821 (__, call_args, __) = call
822 (__, stor_file, __) = call_args
823 path = stor_file.f.name
824 expected_attributes = expected_attributes_by_path[path]
825 stor_file_attributes = {
826 name: getattr(stor_file, name)
827 for name in expected_attributes}
828 self.expectThat(
829 expected_attributes,
830 testtools.matchers.Equals(stor_file_attributes))
831
832 def test_filewithprogress_has_sentinel_size_when_stat_failure(self):
833 """ Should have sentinel `size` value when `os.stat` failure. """
834 expected_attributes_by_path = (
835 make_expected_filewithprogress_attributes_by_path(
836 self, {'size': -1}))
837 registry = FileDouble.get_registry_for_testcase(self)
838 for path in self.paths_to_upload:
839 double = registry[path]
840 double.set_os_stat_scenario('notfound_error')
841 dput.methods.ftp.upload(**self.test_args)
842 for call in self.ftp_client.storbinary.mock_calls:
843 (__, call_args, __) = call
844 (__, stor_file, __) = call_args
845 path = stor_file.f.name
846 expected_attributes = expected_attributes_by_path[path]
847 stor_file_attributes = {
848 name: getattr(stor_file, name)
849 for name in expected_attributes}
850 self.expectThat(
851 expected_attributes,
852 testtools.matchers.Equals(stor_file_attributes))
853
854 def test_emits_debug_message_when_stat_failure(self):
855 """ Should have sentinel `size` value when `os.stat` failure. """
856 self.test_args['debug'] = True
857 registry = FileDouble.get_registry_for_testcase(self)
858 for path in self.paths_to_upload:
859 double = registry[path]
860 double.set_os_stat_scenario('notfound_error')
861 dput.methods.ftp.upload(**self.test_args)
862 for path in self.paths_to_upload:
863 expected_output = textwrap.dedent("""\
864 D: Determining size of file '{path}' failed
865 """).format(path=path)
866 self.expectThat(
867 sys.stdout.getvalue(),
868 testtools.matchers.Contains(expected_output))
869
870
871 def make_mock_httprequest(
872 *,
873 method="GET",
874 url=None,
875 header_fields=None,
876 body=None):
877 """ Make an instrumented mock for `urllib.request.Request`. """
878 request = unittest.mock.Mock(spec=urllib.request.Request)
879 request.url = url
880 request.headers = header_fields
881 if body is None:
882 body = ""
883 body_data = body.encode(dput.methods.http.MESSAGE_BODY_ENCODING)
884 request.data = body_data
885
886 return request
887
888
889 reason_by_http_status = {
890 http.client.OK: "Okay",
891 http.client.NON_AUTHORITATIVE_INFORMATION: "Non-Authoritative Information",
892 http.client.INTERNAL_SERVER_ERROR: "Internal Server Error",
893 http.client.UNAUTHORIZED: "Unauthorized",
894 }
895
896
897 def make_mock_httpresponse(
898 *,
899 version="HTTP/1.1",
900 status=http.client.OK,
901 header_fields=None,
902 body=None):
903 """ Make an instrumented mock for `http.client.HTTPResponse`. """
904 response = unittest.mock.Mock(spec=http.client.HTTPResponse)
905 response.version = version
906 response.status = status
907 response.reason = reason_by_http_status[status]
908
909 if header_fields is None:
910 header_fields = {}
911 response.headers = {name: value for (name, value) in header_fields.items()}
912 if body is None:
913 body = ""
914 body_data = body.encode(dput.methods.http.MESSAGE_BODY_ENCODING)
915 response.msg = body_data
916 response.read.return_value = body_data
917 response.getheader.side_effect = (lambda n: header_fields[n])
918 response.getheaders.return_value = list(header_fields.items())
919
920 return response
921
922
923 class http_upload_TestCase(upload_BaseTestCase):
924 """ Base for test cases for `methods.http.upload` function. """
925
926 scenarios = NotImplemented
927
928 protocol_scenarios = [
929 ('http', {
930 'function_to_test': dput.methods.http.upload,
931 'protocol': "http",
932 'protocol_version': "HTTP/1.0",
933 }),
934 ('https', {
935 'function_to_test': dput.methods.https.upload,
936 'protocol': "https",
937 'protocol_version': "HTTP/1.0",
938 }),
939 ]
940
941 login_scenarios = [
942 ('username', {
943 'login': "lorem",
944 }),
945 ]
946
947 def setUp(self):
948 """ Set up test fixtures. """
949 super().setUp()
950
951 self.set_response_header_fields()
952 self.patch_connection()
953
954 patch_getpass_getpass(self)
955 self.fake_password = self.getUniqueString()
956 getpass.getpass.return_value = self.fake_password
957 if not hasattr(self, 'expected_password'):
958 self.expected_password = self.fake_password
959
960 def set_test_args(self):
961 """ Set the arguments for the test call to the function. """
962 if not hasattr(self, 'progress_type'):
963 self.progress_type = 0
964 self.test_args = dict(
965 fqdn=make_fake_fqdn(self),
966 login=self.login,
967 incoming=self.incoming_path,
968 files_to_upload=self.paths_to_upload,
969 debug=False,
970 dummy=object(),
971 progress=self.progress_type,
972 )
973 if self.function_to_test is dput.methods.http.upload:
974 self.test_args['protocol'] = self.protocol
975
976 def make_upload_uri(self, file_name):
977 """ Make the URI for a file for upload. """
978 uri = urllib.parse.urlunsplit([
979 self.protocol, self.test_args['fqdn'],
980 os.path.join(os.path.sep, self.incoming_path, file_name),
981 None, None])
982 return uri
983
984 def set_response_header_fields(self):
985 """ Set the header fields for the HTTP response. """
986 if not hasattr(self, 'response_header_fields'):
987 self.response_header_fields = {}
988
989 def patch_connection(self):
990 """ Patch the connection instance. """
991 mock_connection = unittest.mock.Mock(spec=http.client.HTTPConnection)
992 mock_connection.getresponse.side_effect = itertools.chain(
993 self.responses,
994 itertools.repeat(self.responses[-1]))
995
996 def putrequest(method, url, *, skip_accept_encoding=True):
997 request = make_mock_httprequest(
998 method=method,
999 header_fields={},
1000 url=url)
1001 mock_connection.latest_request = request
1002
1003 mock_connection.putrequest = unittest.mock.Mock(
1004 spec=http.client.HTTPConnection.putrequest,
1005 wraps=putrequest)
1006
1007 def putheader(header, *values):
1008 values = list(values)
1009 field_value = "\r\n".join(values)
1010 mock_connection.latest_request.headers[header] = field_value
1011
1012 mock_connection.putheader = unittest.mock.Mock(
1013 spec=http.client.HTTPConnection.putheader,
1014 wraps=putheader)
1015
1016 def send(data):
1017 mock_connection.latest_request.data = data
1018
1019 mock_connection.send = unittest.mock.Mock(
1020 spec=http.client.HTTPConnection.send,
1021 wraps=send)
1022 self.mock_connection = mock_connection
1023 self.mock_connection_class = unittest.mock.Mock(
1024 spec=http.client.HTTPConnection,
1025 return_value=self.mock_connection)
1026 self.test_args['connection_class'] = self.mock_connection_class
1027
1028
1029 class http_upload_SuccessTestCase(http_upload_TestCase):
1030 """ Success test cases for `methods.http.upload` function. """
1031
1032 response_scenarios = [
1033 ('okay', {
1034 'responses': [
1035 make_mock_httpresponse(
1036 status=http.client.OK,
1037 body=textwrap.dedent("""\
1038 Lorem ipsum, dolor sit amet.
1039 """),
1040 ),
1041 ],
1042 }),
1043 ('chatter', {
1044 'responses': [
1045 make_mock_httpresponse(
1046 status=http.client.NON_AUTHORITATIVE_INFORMATION,
1047 body=textwrap.dedent("""\
1048 Lorem ipsum, dolor sit amet.
1049 """),
1050 ),
1051 ],
1052 }),
1053 ]
1054
1055 size_scenarios = [
1056 ('size-empty', {
1057 'fake_file': io.BytesIO(),
1058 }),
1059 ('size-1k', {
1060 'fake_file': io.BytesIO(
1061 b"Lorem ipsum, dolor sit amet.___\n" * 32),
1062 }),
1063 ('size-100k', {
1064 'fake_file': io.BytesIO(
1065 b"Lorem ipsum, dolor sit amet.___\n" * 3200),
1066 }),
1067 ]
1068
1069 incoming_scenarios = upload_BaseTestCase.incoming_scenarios.copy()
1070 for (scenario_name, scenario) in incoming_scenarios:
1071 scenario['expected_url_path_prefix'] = os.path.join(
1072 os.path.sep, scenario['incoming_path'])
1073 del scenario_name, scenario
1074
1075 scenarios = testscenarios.multiply_scenarios(
1076 upload_BaseTestCase.files_scenarios,
1077 size_scenarios,
1078 upload_BaseTestCase.incoming_scenarios,
1079 http_upload_TestCase.protocol_scenarios,
1080 http_upload_TestCase.login_scenarios,
1081 response_scenarios)
1082
1083 def test_emits_debug_message_for_upload(self):
1084 """ Should emit debug message for upload. """
1085 self.test_args['debug'] = True
1086 self.function_to_test(**self.test_args)
1087 for path in self.paths_to_upload:
1088 expected_uri = self.make_upload_uri(os.path.basename(path))
1089 expected_output = textwrap.dedent("""\
1090 D: HTTP-PUT to URL: {uri}
1091 """).format(uri=expected_uri)
1092 self.expectThat(
1093 sys.stdout.getvalue(),
1094 testtools.matchers.Contains(expected_output))
1095
1096 def test_request_has_expected_fields(self):
1097 """ Should send request with expected fields in header. """
1098 if not self.paths_to_upload:
1099 self.skipTest("No files to upload")
1100 self.function_to_test(**self.test_args)
1101 registry = FileDouble.get_registry_for_testcase(self)
1102 path = self.paths_to_upload[-1]
1103 double = registry[path]
1104 request = self.mock_connection.latest_request
1105 expected_fields = {
1106 'User-Agent': "dput",
1107 'Connection': "close",
1108 'Content-Length': "{size:d}".format(
1109 size=len(double.fake_file.getvalue())),
1110 }
1111 for (name, value) in expected_fields.items():
1112 self.expectThat(
1113 request.headers.get(name),
1114 testtools.matchers.Equals(value))
1115
1116
1117 class http_upload_ProgressTestCase(http_upload_TestCase):
1118 """ Test cases for `methods.http.upload` function, with progress meter. """
1119
1120 files_scenarios = [
1121 (scenario_name, scenario) for (scenario_name, scenario)
1122 in upload_BaseTestCase.files_scenarios
1123 if scenario['paths_to_upload']]
1124
1125 response_scenarios = [
1126 ('okay', {
1127 'responses': [
1128 make_mock_httpresponse(
1129 status=http.client.OK,
1130 body=textwrap.dedent("""\
1131 Lorem ipsum, dolor sit amet.
1132 """),
1133 ),
1134 ],
1135 }),
1136 ]
1137
1138 progress_scenarios = [
1139 ('progress-type-1', {
1140 'progress_type': 1,
1141 }),
1142 ('progress-type-2', {
1143 'progress_type': 2,
1144 }),
1145 ]
1146
1147 scenarios = testscenarios.multiply_scenarios(
1148 files_scenarios,
1149 progress_scenarios,
1150 upload_BaseTestCase.incoming_scenarios,
1151 http_upload_TestCase.protocol_scenarios,
1152 http_upload_TestCase.login_scenarios,
1153 response_scenarios)
1154
1155 def test_filewithprogress_has_expected_attributes(self):
1156 """ Should have expected attributes on the `FileWithProgress`. """
1157 expected_attributes_by_path = (
1158 make_expected_filewithprogress_attributes_by_path(
1159 self, {'ptype': self.progress_type}))
1160 self.function_to_test(**self.test_args)
1161 path = self.paths_to_upload[-1]
1162 expected_attributes = expected_attributes_by_path[path]
1163 fake_file_attributes = {
1164 name: getattr(self.fake_filewithprogress, name)
1165 for name in expected_attributes}
1166 self.expectThat(
1167 expected_attributes,
1168 testtools.matchers.Equals(fake_file_attributes))
1169
1170
1171 class http_upload_UnknownProtocolTestCase(http_upload_TestCase):
1172 """ Test cases for `methods.http.upload` function, unknown protocol. """
1173
1174 files_scenarios = [
1175 (scenario_name, scenario) for (scenario_name, scenario)
1176 in upload_BaseTestCase.files_scenarios
1177 if scenario['paths_to_upload']]
1178
1179 protocol_scenarios = [
1180 ('protocol-bogus', {
1181 'function_to_test': dput.methods.http.upload,
1182 'protocol': "b0gUs",
1183 'protocol_version': "b0gUs",
1184 'expected_exit_status': EXIT_STATUS_FAILURE,
1185 }),
1186 ]
1187
1188 response_scenarios = [
1189 (scenario_name, scenario) for (scenario_name, scenario)
1190 in http_upload_SuccessTestCase.response_scenarios]
1191
1192 scenarios = testscenarios.multiply_scenarios(
1193 files_scenarios,
1194 upload_BaseTestCase.incoming_scenarios,
1195 protocol_scenarios,
1196 http_upload_TestCase.login_scenarios,
1197 response_scenarios)
1198
1199 def test_emits_error_message_when_unknown_protocol(self):
1200 """ Should emit error message when unknown protocol. """
1201 with contextlib.suppress(FakeSystemExit):
1202 self.function_to_test(**self.test_args)
1203 expected_output = "Wrong protocol for upload "
1204 self.assertIn(expected_output, sys.stderr.getvalue())
1205
1206 def test_calls_sys_exit_when_unknown_protocol(self):
1207 """ Should call `sys.exit` when unknown protocol. """
1208 with testtools.ExpectedException(FakeSystemExit):
1209 self.function_to_test(**self.test_args)
1210 sys.exit.assert_called_with(self.expected_exit_status)
1211
1212
1213 class http_upload_FileStatFailureTestCase(http_upload_TestCase):
1214 """ Test cases for `methods.http.upload` function, `os.stat` failure. """
1215
1216 files_scenarios = [
1217 (scenario_name, scenario) for (scenario_name, scenario)
1218 in upload_BaseTestCase.files_scenarios
1219 if scenario['paths_to_upload']]
1220
1221 os_stat_scenarios = [
1222 ('os-stat-notfound', {
1223 'os_stat_scenario_name': "notfound_error",
1224 'expected_exit_status': EXIT_STATUS_FAILURE,
1225 }),
1226 ('os-stat-denied', {
1227 'os_stat_scenario_name': "denied_error",
1228 'expected_exit_status': EXIT_STATUS_FAILURE,
1229 }),
1230 ]
1231
1232 response_scenarios = [
1233 (scenario_name, scenario) for (scenario_name, scenario)
1234 in http_upload_SuccessTestCase.response_scenarios]
1235
1236 scenarios = testscenarios.multiply_scenarios(
1237 files_scenarios,
1238 os_stat_scenarios,
1239 upload_BaseTestCase.incoming_scenarios,
1240 http_upload_TestCase.protocol_scenarios,
1241 http_upload_TestCase.login_scenarios,
1242 response_scenarios)
1243
1244 def test_emits_error_message(self):
1245 """ Should emit error message when `os.stat` failure. """
1246 with contextlib.suppress(FakeSystemExit):
1247 self.function_to_test(**self.test_args)
1248 expected_output = textwrap.dedent("""\
1249 Determining size of file '{path}' failed
1250 """).format(path=self.paths_to_upload[0])
1251 self.assertIn(expected_output, sys.stderr.getvalue())
1252
1253 def test_calls_sys_exit_with_expected_exit_status(self):
1254 """ Should call `sys.exit` with expected exit status. """
1255 with testtools.ExpectedException(FakeSystemExit):
1256 self.function_to_test(**self.test_args)
1257 sys.exit.assert_called_with(self.expected_exit_status)
1258
1259
1260 class http_upload_ResponseErrorTestCase(http_upload_TestCase):
1261 """ Error test cases for `methods.http.upload` function. """
1262
1263 files_scenarios = [
1264 (scenario_name, scenario) for (scenario_name, scenario)
1265 in upload_BaseTestCase.files_scenarios
1266 if scenario['paths_to_upload']]
1267
1268 response_scenarios = [
1269 ('server-error body-text', {
1270 'responses': [
1271 make_mock_httpresponse(
1272 status=http.client.INTERNAL_SERVER_ERROR,
1273 body=textwrap.dedent("""\
1274 Lorem ipsum, dolor sit amet.
1275 """),
1276 ),
1277 ],
1278 'expected_final_status': (
1279 http.client.INTERNAL_SERVER_ERROR,
1280 "Internal Server Error"),
1281 'expected_debug_output': textwrap.dedent("""\
1282 Lorem ipsum, dolor sit amet.
1283 """),
1284 'expected_exit_status': EXIT_STATUS_FAILURE,
1285 }),
1286 ('server-error body-empty', {
1287 'responses': [
1288 make_mock_httpresponse(
1289 status=http.client.INTERNAL_SERVER_ERROR,
1290 body=""),
1291 ],
1292 'expected_final_status': (
1293 http.client.INTERNAL_SERVER_ERROR,
1294 "Internal Server Error"),
1295 'expected_exit_status': EXIT_STATUS_FAILURE,
1296 }),
1297 ('authorization-rejected', {
1298 'responses': [
1299 make_mock_httpresponse(
1300 status=http.client.UNAUTHORIZED,
1301 header_fields={
1302 'WWW-Authenticate': "Basic realm=\"pellentesque\"",
1303 },
1304 body=textwrap.dedent("""\
1305 Lorem ipsum, dolor sit amet.
1306 """),
1307 ),
1308 make_mock_httpresponse(
1309 status=http.client.UNAUTHORIZED,
1310 header_fields={
1311 'WWW-Authenticate': "Basic realm=\"pellentesque\"",
1312 },
1313 body=textwrap.dedent("""\
1314 Lorem ipsum, dolor sit amet.
1315 """),
1316 ),
1317 ],
1318 'expected_final_status': (
1319 http.client.UNAUTHORIZED, "Unauthorized"),
1320 'expected_debug_output': textwrap.dedent("""\
1321 Lorem ipsum, dolor sit amet.
1322 """),
1323 'expected_exit_status': EXIT_STATUS_FAILURE,
1324 }),
1325 ]
1326
1327 scenarios = testscenarios.multiply_scenarios(
1328 files_scenarios,
1329 upload_BaseTestCase.incoming_scenarios,
1330 http_upload_TestCase.protocol_scenarios,
1331 http_upload_TestCase.login_scenarios,
1332 response_scenarios)
1333
1334 def test_emits_error_message_when_response_status_error(self):
1335 """ Should emit debug message when response status is error. """
1336 if self.expected_final_status[0] == http.client.UNAUTHORIZED:
1337 self.skipTest("FIXME: can't see how this ever worked?")
1338 with contextlib.suppress(FakeSystemExit):
1339 self.function_to_test(**self.test_args)
1340 (code, reason) = self.expected_final_status
1341 expected_output = textwrap.dedent("""\
1342 Upload failed: {status} {reason}
1343 """).format(status=code, reason=reason)
1344 self.assertIn(expected_output, sys.stdout.getvalue())
1345
1346 def test_emits_error_response_body_text_when_debug_true(self):
1347 """ Should emit error response body text when debug is true. """
1348 self.test_args['debug'] = True
1349 if not hasattr(self, 'expected_debug_output'):
1350 self.skipTest("no response body expected")
1351 if self.expected_final_status[0] == http.client.UNAUTHORIZED:
1352 self.skipTest("FIXME: can't see how this ever worked?")
1353 with contextlib.suppress(FakeSystemExit):
1354 self.function_to_test(**self.test_args)
1355 expected_output = self.expected_debug_output
1356 self.assertIn(expected_output, sys.stdout.getvalue())
1357
1358 def test_emits_no_response_body_text_when_debug_false(self):
1359 """ Should emit no response body text when ‘debug’ is false. """
1360 self.test_args['debug'] = False
1361 if not hasattr(self, 'expected_debug_output'):
1362 self.skipTest("no response body expected")
1363 if self.expected_final_status[0] == http.client.UNAUTHORIZED:
1364 self.skipTest("FIXME: can't see how this ever worked?")
1365 with contextlib.suppress(FakeSystemExit):
1366 self.function_to_test(**self.test_args)
1367 unwanted_output = self.expected_debug_output
1368 self.assertNotIn(unwanted_output, sys.stdout.getvalue())
1369
1370 def test_calls_sys_exit_when_response_status_error(self):
1371 """ Should call `sys.exit` when response status is error. """
1372 if self.expected_final_status[0] == http.client.UNAUTHORIZED:
1373 self.skipTest("FIXME: can't see how this ever worked?")
1374 with testtools.ExpectedException(FakeSystemExit):
1375 self.function_to_test(**self.test_args)
1376 sys.exit.assert_called_with(self.expected_exit_status)
1377
1378
1379 class http_upload_ResponseUnauthorizedTestCase(http_upload_TestCase):
1380 """ Unauthorized test cases for `methods.http.upload` function. """
1381
1382 files_scenarios = [
1383 (scenario_name, scenario) for (scenario_name, scenario)
1384 in upload_BaseTestCase.files_scenarios
1385 if scenario['paths_to_upload']]
1386
1387 response_scenarios = [
1388 ('authorization-accepted', {
1389 'responses': [
1390 make_mock_httpresponse(
1391 status=http.client.UNAUTHORIZED,
1392 header_fields={
1393 'WWW-Authenticate': "Basic realm=\"pellentesque\"",
1394 },
1395 body=textwrap.dedent("""\
1396 Lorem ipsum, dolor sit amet.
1397 """),
1398 ),
1399 make_mock_httpresponse(
1400 status=http.client.OK,
1401 body=textwrap.dedent("""\
1402 Lorem ipsum, dolor sit amet.
1403 """),
1404 ),
1405 ],
1406 'expected_final_status': (http.client.OK, "Okay"),
1407 'expected_exit_status': EXIT_STATUS_SUCCESS,
1408 }),
1409 ]
1410
1411 scenarios = testscenarios.multiply_scenarios(
1412 files_scenarios,
1413 upload_BaseTestCase.incoming_scenarios,
1414 http_upload_TestCase.protocol_scenarios,
1415 http_upload_TestCase.login_scenarios,
1416 response_scenarios)
1417
1418 def test_calls_getpass(self):
1419 """ Should call `getpass.getpass` when status is unauthorized. """
1420 self.skipTest("FIXME: can't see how this ever worked?")
1421 self.function_to_test(**self.test_args)
1422 getpass.getpass.assert_called_with()
1423
1424
1425 def make_host_spec(username, host):
1426 """ Make an SSH host specification. """
1427 host_spec = host
1428 if username != "*":
1429 host_spec = "{user}@{fqdn}".format(user=username, fqdn=host)
1430 return host_spec
1431
1432
1433 def make_remote_spec(username, host, dir_path):
1434 """ Make an SCP remote specification. """
1435 host_spec = make_host_spec(username, host)
1436 remote_spec = "{host}:{dir}".format(host=host_spec, dir=dir_path)
1437 return remote_spec
1438
1439
1440 class ssh_channel_upload_TestCase(upload_BaseTestCase):
1441 """ Base for test cases for upload over SSH channel. """
1442
1443 function_to_test = NotImplemented
1444
1445 scenarios = NotImplemented
1446
1447 login_scenarios = [
1448 ('login-username', {
1449 'login': "lorem",
1450 }),
1451 ('login-wildcard', {
1452 'login': "*",
1453 }),
1454 ]
1455
1456 stat_mode_scenarios = [
1457 ('stat-mode-default', {}),
1458 ('stat-mode-0620', {
1459 'stat_mode': 0o0620,
1460 'expected_ssh_chmod': True,
1461 }),
1462 ('stat-mode-0640', {
1463 'stat_mode': 0o0644,
1464 'expected_ssh_chmod': False,
1465 }),
1466 ]
1467
1468 def set_upload_file_modes(self):
1469 """ Set filesystem modes for upload files. """
1470 registry = FileDouble.get_registry_for_testcase(self)
1471 if hasattr(self, 'stat_mode'):
1472 for path in self.paths_to_upload:
1473 file_double = registry[path]
1474 file_double.stat_result = file_double.stat_result._replace(
1475 st_mode=self.stat_mode)
1476
1477 def set_ssh_chmod_subprocess_double(self):
1478 """ Set the ‘ssh … chmod’ test double for the subprocess. """
1479 command_file_path = "/usr/bin/ssh"
1480 argv = [os.path.basename(command_file_path)]
1481 argv.extend(self.expected_ssh_options)
1482 argv.append(make_host_spec(
1483 username=self.login, host=self.test_args['fqdn']))
1484 argv.extend(["chmod", "0644"])
1485 argv.extend(
1486 os.path.join(self.incoming_path, os.path.basename(path))
1487 for path in self.paths_to_upload)
1488 double = SubprocessDouble(command_file_path, argv=argv)
1489 double.register_for_testcase(self)
1490 check_call_scenario_name = getattr(
1491 self, 'ssh_chmod_check_call_scenario_name', "success")
1492 double.set_subprocess_check_call_scenario(check_call_scenario_name)
1493 self.ssh_chmod_subprocess_double = double
1494
1495
1496 class scp_upload_TestCase(ssh_channel_upload_TestCase):
1497 """ Test cases for `methods.scp.upload` function. """
1498
1499 function_to_test = staticmethod(dput.methods.scp.upload)
1500
1501 scenarios = NotImplemented
1502
1503 ssh_config_scenarios = [
1504 ('ssh-opts-default', {
1505 'ssh_config_options': NotImplemented,
1506 'expected_ssh_options': [],
1507 }),
1508 ('ssh-opts-none', {
1509 'ssh_config_options': None,
1510 'expected_ssh_options': [],
1511 }),
1512 ('ssh-opts-empty', {
1513 'ssh_config_options': [],
1514 'expected_ssh_options': [],
1515 }),
1516 ('ssh-opts-one', {
1517 'ssh_config_options': ["foo"],
1518 'expected_ssh_options': ["-o", "foo"],
1519 }),
1520 ('ssh-opts-three', {
1521 'ssh_config_options': ["foo", "bar", "baz"],
1522 'expected_ssh_options': [
1523 "-o", "foo", "-o", "bar", "-o", "baz"],
1524 }),
1525 ]
1526
1527 def setUp(self):
1528 """ Set up test fixtures. """
1529 super().setUp()
1530
1531 patch_os_lstat(self)
1532 self.set_upload_file_modes()
1533
1534 self.set_scp_subprocess_double()
1535 self.set_ssh_chmod_subprocess_double()
1536
1537 def set_test_args(self):
1538 """ Set the arguments for the test call to the function. """
1539 self.test_args = dict(
1540 fqdn=make_fake_fqdn(self),
1541 login=self.login,
1542 incoming=self.incoming_path,
1543 files_to_upload=self.paths_to_upload,
1544 debug=None,
1545 compress=self.compress,
1546 progress=object(),
1547 )
1548 if self.ssh_config_options is not NotImplemented:
1549 self.test_args.update(dict(
1550 ssh_config_options=self.ssh_config_options,
1551 ))
1552
1553 def set_scp_subprocess_double(self):
1554 """ Set the ‘scp’ test double for the subprocess. """
1555 command_file_path = "/usr/bin/scp"
1556 argv = [os.path.basename(command_file_path), "-p"]
1557 argv.extend(self.scp_compress_options)
1558 argv.extend(self.expected_ssh_options)
1559 argv.extend(self.paths_to_upload)
1560 argv.append(make_remote_spec(
1561 username=self.login, host=self.test_args['fqdn'],
1562 dir_path=self.incoming_path))
1563 double = SubprocessDouble(command_file_path, argv=argv)
1564 double.register_for_testcase(self)
1565 check_call_scenario_name = getattr(
1566 self, 'scp_subprocess_check_call_scenario_name', "success")
1567 double.set_subprocess_check_call_scenario(check_call_scenario_name)
1568 self.scp_subprocess_double = double
1569
1570
1571 class scp_upload_ScpTestCase(scp_upload_TestCase):
1572 """ Test cases for `methods.scp.upload` function, with ‘scp’ command. """
1573
1574 compress_scenarios = [
1575 ('compress-false', {
1576 'compress': False,
1577 'scp_compress_options': [],
1578 }),
1579 ('compress-true', {
1580 'compress': True,
1581 'scp_compress_options': ["-C"],
1582 }),
1583 ]
1584
1585 scenarios = testscenarios.multiply_scenarios(
1586 upload_BaseTestCase.files_scenarios,
1587 upload_BaseTestCase.incoming_scenarios,
1588 ssh_channel_upload_TestCase.login_scenarios,
1589 ssh_channel_upload_TestCase.stat_mode_scenarios,
1590 compress_scenarios,
1591 scp_upload_TestCase.ssh_config_scenarios)
1592
1593 def test_emits_debug_message_for_upload(self):
1594 """ Should emit debug message for files upload. """
1595 self.test_args['debug'] = True
1596 self.function_to_test(**self.test_args)
1597 expected_output = textwrap.dedent("""\
1598 D: Uploading with scp to {host}:{incoming}
1599 """).format(
1600 host=make_host_spec(
1601 username=self.login, host=self.test_args['fqdn']),
1602 incoming=self.incoming_path)
1603 self.assertIn(expected_output, sys.stdout.getvalue())
1604
1605 def test_calls_check_call_with_expected_scp_command(self):
1606 """ Should call `subprocess.check_call` with ‘scp’ command. """
1607 self.function_to_test(**self.test_args)
1608 expected_call = unittest.mock.call(self.scp_subprocess_double.argv)
1609 self.assertIn(expected_call, subprocess.check_call.mock_calls)
1610
1611 def test_emits_error_message_when_scp_failure(self):
1612 """ Should emit error message when ‘scp’ command fails. """
1613 double = self.scp_subprocess_double
1614 double.set_subprocess_check_call_scenario("failure")
1615 with contextlib.suppress(FakeSystemExit):
1616 self.function_to_test(**self.test_args)
1617 expected_output = "Error while uploading."
1618 self.assertIn(expected_output, sys.stdout.getvalue())
1619
1620 def test_calls_sys_exit_when_scp_failure(self):
1621 """ Should call `sys.exit` when ‘scp’ command fails. """
1622 double = self.scp_subprocess_double
1623 double.set_subprocess_check_call_scenario("failure")
1624 with testtools.ExpectedException(FakeSystemExit):
1625 self.function_to_test(**self.test_args)
1626 sys.exit.assert_called_with(EXIT_STATUS_FAILURE)
1627
1628
1629 class scp_upload_ChmodTestCase(scp_upload_TestCase):
1630 """ Test cases for `methods.scp.upload` function, with ‘ssh … chmod’. """
1631
1632 files_scenarios = [
1633 (scenario_name, scenario) for (scenario_name, scenario)
1634 in upload_BaseTestCase.files_scenarios
1635 if scenario['paths_to_upload']]
1636
1637 stat_mode_scenarios = [
1638 (scenario_name, scenario) for (scenario_name, scenario)
1639 in ssh_channel_upload_TestCase.stat_mode_scenarios
1640 if scenario.get('expected_ssh_chmod', False)]
1641
1642 compress_scenarios = [
1643 ('compress-false', {
1644 'compress': False,
1645 'scp_compress_options': [],
1646 }),
1647 ]
1648
1649 scenarios = testscenarios.multiply_scenarios(
1650 files_scenarios,
1651 upload_BaseTestCase.incoming_scenarios,
1652 ssh_channel_upload_TestCase.login_scenarios,
1653 stat_mode_scenarios,
1654 compress_scenarios,
1655 scp_upload_TestCase.ssh_config_scenarios)
1656
1657 def test_emits_debug_message_for_fixing_permissions(self):
1658 """ Should emit debug message for fixing file permissions . """
1659 self.test_args['debug'] = True
1660 self.function_to_test(**self.test_args)
1661 expected_output = "D: Fixing some permissions"
1662 self.assertIn(expected_output, sys.stdout.getvalue())
1663
1664 def test_calls_check_call_with_expected_ssh_chmod_command(self):
1665 """ Should call `subprocess.check_call` with ‘ssh … chmod’ command. """
1666 self.function_to_test(**self.test_args)
1667 expected_call = unittest.mock.call(
1668 self.ssh_chmod_subprocess_double.argv)
1669 self.assertIn(expected_call, subprocess.check_call.mock_calls)
1670
1671 def test_emits_error_message_when_ssh_chmod_failure(self):
1672 """ Should emit error message when ‘ssh … chmod’ command fails. """
1673 double = self.ssh_chmod_subprocess_double
1674 double.set_subprocess_check_call_scenario("failure")
1675 with contextlib.suppress(FakeSystemExit):
1676 self.function_to_test(**self.test_args)
1677 expected_output = "Error while fixing permissions."
1678 self.assertIn(expected_output, sys.stdout.getvalue())
1679
1680 def test_calls_sys_exit_when_ssh_chmod_failure(self):
1681 """ Should call `sys.exit` when ‘ssh … chmod’ command fails. """
1682 double = self.ssh_chmod_subprocess_double
1683 double.set_subprocess_check_call_scenario("failure")
1684 with testtools.ExpectedException(FakeSystemExit):
1685 self.function_to_test(**self.test_args)
1686 sys.exit.assert_called_with(EXIT_STATUS_FAILURE)
1687
1688
1689 class rsync_upload_TestCase(ssh_channel_upload_TestCase):
1690 """ Test cases for `methods.rsync.upload` function. """
1691
1692 function_to_test = staticmethod(dput.methods.rsync.upload)
1693
1694 scenarios = testscenarios.multiply_scenarios(
1695 upload_BaseTestCase.files_scenarios,
1696 upload_BaseTestCase.incoming_scenarios,
1697 ssh_channel_upload_TestCase.login_scenarios,
1698 ssh_channel_upload_TestCase.stat_mode_scenarios)
1699
1700 def setUp(self):
1701 """ Set up test fixtures. """
1702 super().setUp()
1703
1704 self.expected_rsync_options = dput.methods.rsync.rsync_options
1705 self.set_rsync_subprocess_double()
1706
1707 self.expected_ssh_options = []
1708 self.set_ssh_chmod_subprocess_double()
1709
1710 def set_test_args(self):
1711 """ Set the arguments for the test call to the function. """
1712 self.test_args = dict(
1713 fqdn=make_fake_fqdn(self),
1714 login=self.login,
1715 incoming=self.incoming_path,
1716 files_to_upload=self.paths_to_upload,
1717 debug=False,
1718 dummy=object(),
1719 progress=object(),
1720 )
1721
1722 def set_rsync_subprocess_double(self):
1723 """ Set the ‘rsync’ test double for the subprocess. """
1724 command_file_path = "/usr/bin/rsync"
1725 argv = [os.path.basename(command_file_path)]
1726 argv.extend(self.paths_to_upload)
1727 argv.extend(self.expected_rsync_options)
1728 argv.append(make_remote_spec(
1729 username=self.login, host=self.test_args['fqdn'],
1730 dir_path=self.incoming_path))
1731 double = SubprocessDouble(command_file_path, argv=argv)
1732 double.register_for_testcase(self)
1733 check_call_scenario_name = getattr(
1734 self, 'rsync_check_call_scenario_name', "success")
1735 double.set_subprocess_check_call_scenario(check_call_scenario_name)
1736 self.rsync_subprocess_double = double
1737
1738 def test_emits_debug_message_for_upload(self):
1739 """ Should emit debug message for files upload. """
1740 self.test_args['debug'] = True
1741 self.function_to_test(**self.test_args)
1742 expected_output = textwrap.dedent("""\
1743 D: Uploading with rsync to {host}:{incoming}
1744 """).format(
1745 host=make_host_spec(
1746 username=self.login, host=self.test_args['fqdn']),
1747 incoming=self.incoming_path)
1748 self.assertIn(expected_output, sys.stdout.getvalue())
1749
1750 def test_calls_check_call_with_expected_rsync_command(self):
1751 """ Should call `subprocess.check_call` with ‘rsync’ command. """
1752 self.function_to_test(**self.test_args)
1753 expected_call = unittest.mock.call(self.rsync_subprocess_double.argv)
1754 self.assertIn(expected_call, subprocess.check_call.mock_calls)
1755
1756 def test_emits_error_message_when_rsync_failure(self):
1757 """ Should emit error message when ‘rsync’ command fails. """
1758 double = self.rsync_subprocess_double
1759 double.set_subprocess_check_call_scenario("failure")
1760 with contextlib.suppress(FakeSystemExit):
1761 self.function_to_test(**self.test_args)
1762 expected_output = "Error while uploading."
1763 self.assertIn(expected_output, sys.stdout.getvalue())
1764
1765 def test_calls_sys_exit_when_rsync_failure(self):
1766 """ Should call `sys.exit` when ‘rsync’ command fails. """
1767 double = self.rsync_subprocess_double
1768 double.set_subprocess_check_call_scenario("failure")
1769 with testtools.ExpectedException(FakeSystemExit):
1770 self.function_to_test(**self.test_args)
1771 sys.exit.assert_called_with(EXIT_STATUS_FAILURE)
1772
1773 def test_emits_debug_message_for_fixing_permissions(self):
1774 """ Should emit debug message for fixing file permissions . """
1775 self.test_args['debug'] = True
1776 self.function_to_test(**self.test_args)
1777 expected_output = textwrap.dedent("""\
1778 D: Fixing file permissions with {host}
1779 """).format(
1780 host=make_host_spec(
1781 username=self.login, host=self.test_args['fqdn']))
1782 self.assertIn(expected_output, sys.stdout.getvalue())
1783
1784 def test_calls_check_call_with_expected_ssh_chmod_command(self):
1785 """ Should call `subprocess.check_call` with ‘ssh … chmod’ command. """
1786 self.function_to_test(**self.test_args)
1787 expected_call = unittest.mock.call(
1788 list(self.ssh_chmod_subprocess_double.argv))
1789 self.assertIn(expected_call, subprocess.check_call.mock_calls)
1790
1791 def test_emits_error_message_when_ssh_chmod_failure(self):
1792 """ Should emit error message when ‘ssh … chmod’ command fails. """
1793 double = self.ssh_chmod_subprocess_double
1794 double.set_subprocess_check_call_scenario("failure")
1795 with contextlib.suppress(FakeSystemExit):
1796 self.function_to_test(**self.test_args)
1797 expected_output = "Error while fixing permission."
1798 self.assertIn(expected_output, sys.stdout.getvalue())
1799
1800 def test_calls_sys_exit_when_ssh_chmod_failure(self):
1801 """ Should call `sys.exit` when ‘ssh … chmod’ command fails. """
1802 double = self.ssh_chmod_subprocess_double
1803 double.set_subprocess_check_call_scenario("failure")
1804 with testtools.ExpectedException(FakeSystemExit):
1805 self.function_to_test(**self.test_args)
1806 sys.exit.assert_called_with(EXIT_STATUS_FAILURE)
1807
1808
1809 # Copyright © 2015–2026 Ben Finney <[email protected]>
1810 #
1811 # This is free software: you may copy, modify, and/or distribute this work
1812 # under the terms of the GNU General Public License as published by the
1813 # Free Software Foundation; version 3 of that license or any later version.
1814 # No warranty expressed or implied. See the file ‘LICENSE.GPL-3’ for details.
1815
1816
1817 # Local variables:
1818 # coding: utf-8
1819 # mode: python
1820 # End:
1821 # vim: fileencoding=utf-8 filetype=python :