test_changesfile.py 48 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232
  1. # -*- coding: utf-8; -*-
  2. #
  3. # test/test_changesfile.py
  4. # Part of ‘dput’, a Debian package upload toolkit.
  5. #
  6. # Copyright © 2015 Ben Finney <ben+python@benfinney.id.au>
  7. #
  8. # This is free software: you may copy, modify, and/or distribute this work
  9. # under the terms of the GNU General Public License as published by the
  10. # Free Software Foundation; version 3 of that license or any later version.
  11. # No warranty expressed or implied. See the file ‘LICENSE.GPL-3’ for details.
  12. """ Unit tests for Debian upload control (‘*.changes’) files. """
  13. import sys
  14. import os
  15. import os.path
  16. import tempfile
  17. import textwrap
  18. import doctest
  19. import email.message
  20. import collections
  21. import testtools
  22. import testscenarios
  23. __package__ = str("test")
  24. __import__(__package__)
  25. sys.path.insert(1, os.path.dirname(os.path.dirname(__file__)))
  26. import dput.dput
  27. from dput.helper import dputhelper
  28. from .helper import (
  29. StringIO,
  30. mock,
  31. patch_system_interfaces,
  32. make_unique_slug,
  33. FakeSystemExit,
  34. EXIT_STATUS_FAILURE,
  35. make_fake_file_scenarios,
  36. get_file_doubles_from_fake_file_scenarios,
  37. setup_file_double_behaviour,
  38. patch_os_stat,
  39. FileDouble,
  40. )
  41. from .test_configfile import (
  42. set_config,
  43. patch_runtime_config_options,
  44. )
  45. __metaclass__ = type
  46. class _FieldsMapping:
  47. """ A mapping to stand in for the `dict` of an `email.message.Message`. """
  48. def __init__(self, *args, **kwargs):
  49. try:
  50. self._message = kwargs.pop('_message')
  51. except KeyError:
  52. raise TypeError("no ‘_message’ specified for this mapping")
  53. super(_FieldsMapping, self).__init__(*args, **kwargs)
  54. def __len__(self, *args, **kwargs):
  55. return self._message.__len__(*args, **kwargs)
  56. def __contains__(self, *args, **kwargs):
  57. return self._message.__contains__(*args, **kwargs)
  58. def __getitem__(self, *args, **kwargs):
  59. return self._message.__getitem__(*args, **kwargs)
  60. def __setitem__(self, *args, **kwargs):
  61. self._message.__setitem__(*args, **kwargs)
  62. def __delitem__(self, *args, **kwargs):
  63. self._message.__delitem__(*args, **kwargs)
  64. def has_key(self, *args, **kwargs):
  65. return self._message.has_key(*args, **kwargs)
  66. def keys(self, *args, **kwargs):
  67. return self._message.keys(*args, **kwargs)
  68. def values(self, *args, **kwargs):
  69. return self._message.values(*args, **kwargs)
  70. def items(self, *args, **kwargs):
  71. return self._message.items(*args, **kwargs)
  72. def get(self, *args, **kwargs):
  73. return self._message.get(*args, **kwargs)
  74. class FakeMessage(email.message.Message, object):
  75. """ A fake RFC 2822 message that mocks the obsolete `rfc822.Message`. """
  76. def __init__(self, *args, **kwargs):
  77. super(FakeMessage, self).__init__(*args, **kwargs)
  78. self.dict = _FieldsMapping(_message=self)
  79. def make_fake_message(fields):
  80. """ Make a fake message instance. """
  81. message = FakeMessage()
  82. for (name, value) in fields.items():
  83. message.add_header(name, value)
  84. return message
  85. def make_files_field_value(params_by_name):
  86. """ Make a value for “Files” field of a changes document. """
  87. result = "\n".join(
  88. " ".join(params)
  89. for (file_name, params) in params_by_name.items())
  90. return result
  91. def make_upload_files_params(checksums_by_file_name, sizes_by_file_name):
  92. """ Make a mapping of upload parameters for files. """
  93. params_by_name = {
  94. file_name: [
  95. checksums_by_file_name[file_name],
  96. str(sizes_by_file_name[file_name]),
  97. "foo", "bar", file_name]
  98. for file_name in checksums_by_file_name}
  99. return params_by_name
  100. def make_changes_document(fields, upload_params_by_name=None):
  101. """ Make a changes document from field values.
  102. :param fields: Sequence of (name, value) tuples for fields.
  103. :param upload_params_by_name: Mapping from filename to upload
  104. parameters for each file.
  105. :return: The changes document as an RFC 822 formatted text.
  106. """
  107. document_fields = fields.copy()
  108. if upload_params_by_name is not None:
  109. files_field_text = make_files_field_value(upload_params_by_name)
  110. document_fields.update({'files': files_field_text})
  111. document = make_fake_message(document_fields)
  112. return document
  113. def make_changes_file_scenarios():
  114. """ Make fake Debian upload control (‘*.changes’) scenarios. """
  115. file_path = make_changes_file_path()
  116. fake_file_empty = StringIO()
  117. fake_file_no_format = StringIO(textwrap.dedent("""\
  118. FOO
  119. BAR
  120. Files:
  121. Lorem ipsum dolor sit amet
  122. """))
  123. fake_file_with_signature = StringIO(textwrap.dedent("""\
  124. -----BEGIN PGP SIGNED MESSAGE-----
  125. Hash: SHA1
  126. FOO
  127. BAR
  128. Files:
  129. Lorem ipsum dolor sit amet
  130. -----BEGIN PGP SIGNATURE-----
  131. Version: 0.0
  132. Comment: Proin ac massa at orci sagittis fermentum.
  133. gibberishgibberishgibberishgibberishgibberishgibberish
  134. gibberishgibberishgibberishgibberishgibberishgibberish
  135. gibberishgibberishgibberishgibberishgibberishgibberish
  136. -----END PGP SIGNATURE-----
  137. """))
  138. fake_file_with_format = StringIO(textwrap.dedent("""\
  139. Format: FOO
  140. Files:
  141. Lorem ipsum dolor sit amet
  142. """))
  143. fake_file_invalid = StringIO(textwrap.dedent("""\
  144. Format: FOO
  145. Files:
  146. FOO BAR
  147. """))
  148. scenarios = [
  149. ('no-format', {
  150. 'file_double': FileDouble(
  151. path=file_path,
  152. fake_file=fake_file_no_format),
  153. 'expected_result': make_changes_document({
  154. 'files': "Lorem ipsum dolor sit amet",
  155. }),
  156. }),
  157. ('with-pgp-signature', {
  158. 'file_double': FileDouble(
  159. path=file_path,
  160. fake_file=fake_file_with_signature),
  161. 'expected_result': make_changes_document({
  162. 'files': "Lorem ipsum dolor sit amet",
  163. }),
  164. }),
  165. ('with-format', {
  166. 'file_double': FileDouble(
  167. path=file_path,
  168. fake_file=fake_file_with_format),
  169. 'expected_result': make_changes_document({
  170. 'files': "Lorem ipsum dolor sit amet",
  171. }),
  172. }),
  173. ('error empty', {
  174. 'file_double': FileDouble(
  175. path=file_path, fake_file=fake_file_empty),
  176. 'expected_error': KeyError,
  177. }),
  178. ('error invalid', {
  179. 'file_double': FileDouble(
  180. path=file_path,
  181. fake_file=fake_file_invalid),
  182. 'expected_error': FakeSystemExit,
  183. }),
  184. ]
  185. for (scenario_name, scenario) in scenarios:
  186. scenario['changes_file_scenario_name'] = scenario_name
  187. return scenarios
  188. def set_fake_upload_file_paths(testcase):
  189. """ Set the fake upload file paths. """
  190. testcase.fake_upload_file_paths = [
  191. os.path.join(
  192. os.path.dirname(testcase.changes_file_double.path),
  193. os.path.basename(tempfile.mktemp()))
  194. for __ in range(10)]
  195. required_suffixes = [".dsc", ".tar.xz"]
  196. suffixes = required_suffixes + getattr(
  197. testcase, 'additional_file_suffixes', [])
  198. file_path_base = testcase.fake_upload_file_paths.pop()
  199. for suffix in suffixes:
  200. file_path = file_path_base + suffix
  201. testcase.fake_upload_file_paths.insert(0, file_path)
  202. def set_file_checksums(testcase):
  203. """ Set the fake file checksums for the test case. """
  204. testcase.fake_checksum_by_file = {
  205. os.path.basename(file_path): make_unique_slug(testcase)
  206. for file_path in testcase.fake_upload_file_paths}
  207. def set_file_sizes(testcase):
  208. """ Set the fake file sizes for the test case. """
  209. testcase.fake_size_by_file = {
  210. os.path.basename(file_path): testcase.getUniqueInteger()
  211. for file_path in testcase.fake_upload_file_paths}
  212. def set_file_doubles(testcase):
  213. """ Set the file doubles for the test case. """
  214. for file_path in testcase.fake_upload_file_paths:
  215. file_double = FileDouble(file_path)
  216. file_double.set_os_stat_scenario('okay')
  217. file_double.stat_result = file_double.stat_result._replace(
  218. st_size=testcase.fake_size_by_file[
  219. os.path.basename(file_path)],
  220. )
  221. file_double.register_for_testcase(testcase)
  222. def setup_upload_file_fixtures(testcase):
  223. """ Set fixtures for fake files to upload for the test case. """
  224. set_fake_upload_file_paths(testcase)
  225. set_file_checksums(testcase)
  226. set_file_sizes(testcase)
  227. set_file_doubles(testcase)
  228. def make_changes_file_path(file_dir_path=None):
  229. """ Make a filesystem path for the changes file. """
  230. if file_dir_path is None:
  231. file_dir_path = tempfile.mktemp()
  232. file_name = os.path.basename(
  233. "{base}.changes".format(base=tempfile.mktemp()))
  234. file_path = os.path.join(file_dir_path, file_name)
  235. return file_path
  236. def setup_changes_file_fixtures(testcase):
  237. """ Set up fixtures for changes file doubles. """
  238. file_path = make_changes_file_path()
  239. scenarios = make_fake_file_scenarios(file_path)
  240. testcase.changes_file_scenarios = scenarios
  241. file_doubles = get_file_doubles_from_fake_file_scenarios(
  242. scenarios.values())
  243. setup_file_double_behaviour(testcase, file_doubles)
  244. def set_changes_file_scenario(testcase, name):
  245. """ Set the changes file scenario for this test case. """
  246. scenario = dict(testcase.changes_file_scenarios)[name]
  247. testcase.changes_file_scenario = scenario
  248. testcase.changes_file_double = scenario['file_double']
  249. testcase.changes_file_double.register_for_testcase(testcase)
  250. class parse_changes_TestCase(
  251. testscenarios.WithScenarios,
  252. testtools.TestCase):
  253. """ Base for test cases for `parse_changes` function. """
  254. scenarios = NotImplemented
  255. def setUp(self):
  256. """ Set up test fixtures. """
  257. super(parse_changes_TestCase, self).setUp()
  258. patch_system_interfaces(self)
  259. self.test_infile = StringIO()
  260. class parse_changes_SuccessTestCase(parse_changes_TestCase):
  261. """ Success test cases for `parse_changes` function. """
  262. scenarios = list(
  263. (name, scenario)
  264. for (name, scenario) in make_changes_file_scenarios()
  265. if not name.startswith('error'))
  266. def test_gives_expected_result_for_infile(self):
  267. """ Should give the expected result for specified input file. """
  268. result = dput.dput.parse_changes(self.file_double.fake_file)
  269. normalised_result_set = set(
  270. (key.lower(), value.strip())
  271. for (key, value) in result.items())
  272. self.assertEqual(
  273. set(self.expected_result.items()), normalised_result_set)
  274. class parse_changes_ErrorTestCase(parse_changes_TestCase):
  275. """ Error test cases for `parse_changes` function. """
  276. scenarios = list(
  277. (name, scenario)
  278. for (name, scenario) in make_changes_file_scenarios()
  279. if name.startswith('error'))
  280. def test_raises_expected_exception_for_infile(self):
  281. """ Should raise the expected exception for specified input file. """
  282. with testtools.ExpectedException(self.expected_error):
  283. dput.dput.parse_changes(self.file_double.fake_file)
  284. class check_upload_variant_TestCase(
  285. testscenarios.WithScenarios,
  286. testtools.TestCase):
  287. """ Test cases for `check_upload_variant` function. """
  288. scenarios = [
  289. ('simple', {
  290. 'fields': {
  291. 'architecture': "foo bar baz",
  292. },
  293. 'expected_result': True,
  294. }),
  295. ('arch-missing', {
  296. 'fields': {
  297. 'spam': "Lorem ipsum dolor sit amet",
  298. },
  299. 'expected_result': False,
  300. }),
  301. ('source-only', {
  302. 'fields': {
  303. 'architecture': "source",
  304. },
  305. 'expected_result': False,
  306. }),
  307. ('source-and-others', {
  308. 'fields': {
  309. 'architecture': "foo source bar",
  310. },
  311. 'expected_result': False,
  312. }),
  313. ]
  314. def setUp(self):
  315. """ Set up test fixtures. """
  316. super(check_upload_variant_TestCase, self).setUp()
  317. patch_system_interfaces(self)
  318. self.set_changes_document(self.fields)
  319. self.set_test_args()
  320. def set_changes_document(self, fields):
  321. """ Set the package changes document based on specified fields. """
  322. self.test_changes_document = make_changes_document(fields)
  323. def set_test_args(self):
  324. """ Set the arguments for the test call to the function. """
  325. self.test_args = {
  326. 'changes': self.test_changes_document,
  327. 'debug': False,
  328. }
  329. def test_returns_expected_result_for_changes_document(self):
  330. """ Should return expected result for specified changes document. """
  331. result = dput.dput.check_upload_variant(**self.test_args)
  332. self.assertEqual(self.expected_result, result)
  333. def test_emits_debug_message_showing_architecture(self):
  334. """ Should emit a debug message for the specified architecture. """
  335. if 'architecture' not in self.fields:
  336. self.skipTest("Architecture field not in this scenario")
  337. self.test_args['debug'] = True
  338. dput.dput.check_upload_variant(**self.test_args)
  339. expected_output = textwrap.dedent("""\
  340. D: Architecture: {arch}
  341. """).format(arch=self.fields['architecture'])
  342. self.assertIn(expected_output, sys.stdout.getvalue())
  343. def test_emits_debug_message_for_binary_upload(self):
  344. """ Should emit a debug message for the specified architecture. """
  345. triggers_binaryonly = bool(self.expected_result)
  346. if not triggers_binaryonly:
  347. self.skipTest("Scenario does not trigger binary-only upload")
  348. self.test_args['debug'] = True
  349. dput.dput.check_upload_variant(**self.test_args)
  350. expected_output = textwrap.dedent("""\
  351. D: Doing a binary upload only.
  352. """)
  353. self.assertIn(expected_output, sys.stdout.getvalue())
  354. SourceCheckResult = collections.namedtuple(
  355. 'SourceCheckResult', ['include_orig', 'include_tar'])
  356. class source_check_TestCase(
  357. testscenarios.WithScenarios,
  358. testtools.TestCase):
  359. """ Test cases for `source_check` function. """
  360. default_expected_result = SourceCheckResult(
  361. include_orig=False, include_tar=False)
  362. scenarios = [
  363. ('no-version', {
  364. 'expected_result': default_expected_result,
  365. }),
  366. ('no-epoch native-version', {
  367. 'upstream_version': "1.2",
  368. 'expected_result': SourceCheckResult(
  369. include_orig=False, include_tar=True),
  370. }),
  371. ('epoch native-version', {
  372. 'epoch': "3",
  373. 'upstream_version': "1.2",
  374. 'expected_result': SourceCheckResult(
  375. include_orig=False, include_tar=True),
  376. }),
  377. ('no-epoch debian-release', {
  378. 'upstream_version': "1.2",
  379. 'release': "5",
  380. 'expected_result': SourceCheckResult(
  381. include_orig=False, include_tar=True),
  382. }),
  383. ('epoch debian-release', {
  384. 'epoch': "3",
  385. 'upstream_version': "1.2",
  386. 'release': "5",
  387. 'expected_result': SourceCheckResult(
  388. include_orig=False, include_tar=True),
  389. }),
  390. ('no-epoch new-upstream-version', {
  391. 'upstream_version': "1.2",
  392. 'release': "1",
  393. 'expected_result': SourceCheckResult(
  394. include_orig=True, include_tar=False),
  395. }),
  396. ('epoch new_upstream-version', {
  397. 'epoch': "3",
  398. 'upstream_version': "1.2",
  399. 'release': "1",
  400. 'expected_result': SourceCheckResult(
  401. include_orig=True, include_tar=False),
  402. }),
  403. ('no-epoch nmu', {
  404. 'upstream_version': "1.2",
  405. 'release': "4.5",
  406. 'expected_result': SourceCheckResult(
  407. include_orig=False, include_tar=True),
  408. }),
  409. ('epoch nmu', {
  410. 'epoch': "3",
  411. 'upstream_version': "1.2",
  412. 'release': "4.5",
  413. 'expected_result': SourceCheckResult(
  414. include_orig=False, include_tar=True),
  415. }),
  416. ('no-epoch nmu before-first-release', {
  417. 'upstream_version': "1.2",
  418. 'release': "0.1",
  419. 'expected_result': SourceCheckResult(
  420. include_orig=True, include_tar=False),
  421. }),
  422. ('epoch nmu before-first-release', {
  423. 'epoch': "3",
  424. 'upstream_version': "1.2",
  425. 'release': "0.1",
  426. 'expected_result': SourceCheckResult(
  427. include_orig=True, include_tar=False),
  428. }),
  429. ('no-epoch nmu after-first-release', {
  430. 'upstream_version': "1.2",
  431. 'release': "1.1",
  432. 'expected_result': SourceCheckResult(
  433. include_orig=True, include_tar=False),
  434. }),
  435. ('epoch nmu after-first-release', {
  436. 'epoch': "3",
  437. 'upstream_version': "1.2",
  438. 'release': "1.1",
  439. 'expected_result': SourceCheckResult(
  440. include_orig=True, include_tar=False),
  441. }),
  442. ]
  443. for (scenario_name, scenario) in scenarios:
  444. fields = {}
  445. if 'upstream_version' in scenario:
  446. version_string = scenario['upstream_version']
  447. if 'epoch' in scenario:
  448. version_string = "{epoch}:{version}".format(
  449. epoch=scenario['epoch'], version=version_string)
  450. if 'release' in scenario:
  451. version_string = "{version}-{release}".format(
  452. version=version_string, release=scenario['release'])
  453. fields.update({'version': version_string})
  454. scenario['version'] = version_string
  455. scenario['changes_document'] = make_changes_document(fields)
  456. del scenario_name, scenario
  457. del fields, version_string
  458. def setUp(self):
  459. """ Set up test fixtures. """
  460. super(source_check_TestCase, self).setUp()
  461. patch_system_interfaces(self)
  462. self.test_args = {
  463. 'changes': self.changes_document,
  464. 'debug': False,
  465. }
  466. def test_returns_expected_result_for_changes_document(self):
  467. """ Should return expected result for specified changes document. """
  468. result = dput.dput.source_check(**self.test_args)
  469. self.assertEqual(self.expected_result, result)
  470. def test_emits_version_string_debug_message_only_if_version(self):
  471. """ Should emit message for version only if has version. """
  472. self.test_args['debug'] = True
  473. version = getattr(self, 'version', None)
  474. message_lead = "D: Package Version:"
  475. expected_output = textwrap.dedent("""\
  476. {lead} {version}
  477. """).format(
  478. lead=message_lead, version=version)
  479. dput.dput.source_check(**self.test_args)
  480. if hasattr(self, 'version'):
  481. self.assertIn(expected_output, sys.stdout.getvalue())
  482. else:
  483. self.assertNotIn(message_lead, sys.stdout.getvalue())
  484. def test_emits_epoch_debug_message_only_if_epoch(self):
  485. """ Should emit message for epoch only if has an epoch. """
  486. self.test_args['debug'] = True
  487. dput.dput.source_check(**self.test_args)
  488. expected_output = textwrap.dedent("""\
  489. D: Epoch found
  490. """)
  491. dput.dput.source_check(**self.test_args)
  492. if (hasattr(self, 'epoch') and hasattr(self, 'release')):
  493. self.assertIn(expected_output, sys.stdout.getvalue())
  494. else:
  495. self.assertNotIn(expected_output, sys.stdout.getvalue())
  496. def test_emits_upstream_version_debug_message_only_if_nonnative(self):
  497. """ Should emit message for upstream version only if non-native. """
  498. self.test_args['debug'] = True
  499. upstream_version = getattr(self, 'upstream_version', None)
  500. message_lead = "D: Upstream Version:"
  501. expected_output = textwrap.dedent("""\
  502. {lead} {version}
  503. """).format(
  504. lead=message_lead, version=upstream_version)
  505. dput.dput.source_check(**self.test_args)
  506. if hasattr(self, 'release'):
  507. self.assertIn(expected_output, sys.stdout.getvalue())
  508. else:
  509. self.assertNotIn(message_lead, sys.stdout.getvalue())
  510. def test_emits_debian_release_debug_message_only_if_nonnative(self):
  511. """ Should emit message for Debian release only if non-native. """
  512. self.test_args['debug'] = True
  513. debian_release = getattr(self, 'release', None)
  514. message_lead = "D: Debian Version:"
  515. expected_output = textwrap.dedent("""\
  516. {lead} {version}
  517. """).format(
  518. lead=message_lead, version=debian_release)
  519. dput.dput.source_check(**self.test_args)
  520. if hasattr(self, 'release'):
  521. self.assertIn(expected_output, sys.stdout.getvalue())
  522. else:
  523. self.assertNotIn(message_lead, sys.stdout.getvalue())
  524. class verify_files_TestCase(
  525. testscenarios.WithScenarios,
  526. testtools.TestCase):
  527. """ Test cases for `verify_files` function. """
  528. default_args = dict(
  529. host="foo",
  530. check_only=None,
  531. check_version=None,
  532. unsigned_upload=None,
  533. debug=None,
  534. )
  535. scenarios = [
  536. ('default', {}),
  537. ('binary-only', {
  538. 'check_upload_variant_return_value': False,
  539. }),
  540. ('include foo.tar.gz', {
  541. 'additional_file_suffixes': [".tar.gz"],
  542. 'source_check_result': SourceCheckResult(
  543. include_orig=False, include_tar=True),
  544. }),
  545. ('include foo.orig.tar.gz', {
  546. 'additional_file_suffixes': [".orig.tar.gz"],
  547. 'source_check_result': SourceCheckResult(
  548. include_orig=True, include_tar=False),
  549. }),
  550. ('unexpected foo.tar.gz', {
  551. 'additional_file_suffixes': [".tar.gz"],
  552. 'expected_rejection_message': (
  553. "Package includes a .tar.gz file although"),
  554. }),
  555. ('unexpected foo.orig.tar.gz', {
  556. 'additional_file_suffixes': [".orig.tar.gz"],
  557. 'expected_rejection_message': (
  558. "Package includes an .orig.tar.gz file although"),
  559. }),
  560. ('no distribution', {
  561. 'test_distribution': None,
  562. }),
  563. ]
  564. def setUp(self):
  565. """ Set up test fixtures. """
  566. super(verify_files_TestCase, self).setUp()
  567. patch_system_interfaces(self)
  568. self.file_double_by_path = {}
  569. set_config(self, 'exist-simple')
  570. patch_runtime_config_options(self)
  571. self.set_test_args()
  572. setup_changes_file_fixtures(self)
  573. set_changes_file_scenario(self, 'exist-minimal')
  574. self.test_args.update(dict(
  575. path=os.path.dirname(self.changes_file_double.path),
  576. filename=os.path.basename(self.changes_file_double.path),
  577. ))
  578. patch_os_stat(self)
  579. setup_upload_file_fixtures(self)
  580. self.set_expected_files_to_upload()
  581. self.patch_checksum_test()
  582. self.patch_parse_changes()
  583. self.patch_check_upload_variant()
  584. self.set_expected_binary_upload()
  585. self.set_expected_source_control_file_path()
  586. self.patch_version_check()
  587. self.patch_verify_signature()
  588. self.patch_source_check()
  589. def set_expected_files_to_upload(self):
  590. """ Set the expected `files_to_upload` result for this test case. """
  591. self.expected_files_to_upload = set(
  592. path for path in self.fake_upload_file_paths)
  593. self.expected_files_to_upload.add(self.changes_file_double.path)
  594. def patch_checksum_test(self):
  595. """ Patch `checksum_test` function for this test case. """
  596. func_patcher = mock.patch.object(dput.dput, 'checksum_test')
  597. mock_func = func_patcher.start()
  598. self.addCleanup(func_patcher.stop)
  599. def get_checksum_for_file(path, hash):
  600. return self.fake_checksum_by_file[os.path.basename(path)]
  601. mock_func.side_effect = get_checksum_for_file
  602. def set_changes_document(self):
  603. """ Set the changes document for this test case. """
  604. self.changes_document = make_changes_document(
  605. fields={},
  606. upload_params_by_name=self.upload_params_by_name)
  607. self.test_distribution = getattr(self, 'test_distribution', "lorem")
  608. if self.test_distribution is not None:
  609. self.changes_document.add_header(
  610. 'distribution', self.test_distribution)
  611. self.runtime_config_parser.set(
  612. self.test_args['host'], 'allowed_distributions',
  613. self.test_distribution)
  614. dput.dput.parse_changes.return_value = self.changes_document
  615. def patch_parse_changes(self):
  616. """ Patch `parse_changes` function for this test case. """
  617. func_patcher = mock.patch.object(dput.dput, 'parse_changes')
  618. func_patcher.start()
  619. self.addCleanup(func_patcher.stop)
  620. self.upload_params_by_name = make_upload_files_params(
  621. self.fake_checksum_by_file,
  622. self.fake_size_by_file)
  623. self.set_changes_document()
  624. def patch_check_upload_variant(self):
  625. """ Patch `check_upload_variant` function for this test case. """
  626. if not hasattr(self, 'check_upload_variant_return_value'):
  627. self.check_upload_variant_return_value = True
  628. func_patcher = mock.patch.object(
  629. dput.dput, 'check_upload_variant',
  630. return_value=self.check_upload_variant_return_value)
  631. func_patcher.start()
  632. self.addCleanup(func_patcher.stop)
  633. def patch_version_check(self):
  634. """ Patch `version_check` function for this test case. """
  635. func_patcher = mock.patch.object(dput.dput, 'version_check')
  636. func_patcher.start()
  637. self.addCleanup(func_patcher.stop)
  638. def patch_verify_signature(self):
  639. """ Patch `verify_signature` function for this test case. """
  640. func_patcher = mock.patch.object(dput.dput, 'verify_signature')
  641. func_patcher.start()
  642. self.addCleanup(func_patcher.stop)
  643. def patch_source_check(self):
  644. """ Patch `source_check` function for this test case. """
  645. func_patcher = mock.patch.object(dput.dput, 'source_check')
  646. mock_func = func_patcher.start()
  647. self.addCleanup(func_patcher.stop)
  648. source_check_result = getattr(
  649. self, 'source_check_result', SourceCheckResult(
  650. include_orig=False, include_tar=False))
  651. mock_func.return_value = source_check_result
  652. def set_test_args(self):
  653. """ Set test args for this test case. """
  654. extra_args = getattr(self, 'extra_args', {})
  655. self.test_args = self.default_args.copy()
  656. self.test_args['config'] = self.runtime_config_parser
  657. self.test_args.update(extra_args)
  658. def set_expected_binary_upload(self):
  659. """ Set expected value for `binary_upload` flag. """
  660. self.expected_binary_upload = self.check_upload_variant_return_value
  661. def set_expected_source_control_file_path(self):
  662. """ Set expected value for source control file path. """
  663. file_name = next(
  664. os.path.basename(file_path)
  665. for file_path in self.fake_upload_file_paths
  666. if file_path.endswith(".dsc"))
  667. if not self.expected_binary_upload:
  668. self.expected_source_control_file_path = os.path.join(
  669. os.path.dirname(self.changes_file_double.path), file_name)
  670. else:
  671. self.expected_source_control_file_path = ""
  672. def test_emits_changes_file_path_debug_message(self):
  673. """ Should emit debug message for changes file path. """
  674. self.test_args['debug'] = True
  675. dput.dput.verify_files(**self.test_args)
  676. expected_output = textwrap.dedent("""\
  677. D: Validating contents of changes file {path}
  678. """).format(path=self.changes_file_double.path)
  679. self.assertIn(expected_output, sys.stdout.getvalue())
  680. def test_calls_sys_exit_if_input_read_denied(self):
  681. """ Should call `sys.exit` if input file read access is denied. """
  682. set_changes_file_scenario(self, 'error-read-denied')
  683. with testtools.ExpectedException(FakeSystemExit):
  684. dput.dput.verify_files(**self.test_args)
  685. expected_output = textwrap.dedent("""\
  686. Can't open {path}
  687. """).format(path=self.changes_file_double.path)
  688. self.assertIn(expected_output, sys.stdout.getvalue())
  689. sys.exit.assert_called_with(EXIT_STATUS_FAILURE)
  690. def test_calls_parse_changes_with_changes_files(self):
  691. """ Should call `parse_changes` with changes file. """
  692. dput.dput.verify_files(**self.test_args)
  693. dput.dput.parse_changes.assert_called_with(
  694. self.changes_file_double.fake_file)
  695. def test_calls_check_upload_variant_with_changes_document(self):
  696. """ Should call `check_upload_variant` with changes document. """
  697. dput.dput.verify_files(**self.test_args)
  698. dput.dput.check_upload_variant.assert_called_with(
  699. self.changes_document, mock.ANY)
  700. def test_emits_upload_dsc_file_debug_message(self):
  701. """ Should emit debug message for ‘*.dsc’ file. """
  702. if getattr(self, 'check_upload_variant_return_value', True):
  703. self.skipTest("Binary package upload for this scenario")
  704. self.test_args['debug'] = True
  705. dput.dput.verify_files(**self.test_args)
  706. dsc_file_path = next(
  707. os.path.basename(file_path)
  708. for file_path in self.fake_upload_file_paths
  709. if file_path.endswith(".dsc"))
  710. expected_output = textwrap.dedent("""\
  711. D: dsc-File: {path}
  712. """).format(path=dsc_file_path)
  713. self.assertThat(
  714. sys.stdout.getvalue(),
  715. testtools.matchers.Contains(expected_output))
  716. def test_calls_sys_exit_when_source_upload_omits_dsc_file(self):
  717. """ Should call `sys.exit` when source upload omits ‘*.dsc’ file. """
  718. if getattr(self, 'check_upload_variant_return_value', True):
  719. self.skipTest("Binary package upload for this scenario")
  720. self.fake_checksum_by_file = dict(
  721. (file_path, checksum)
  722. for (file_path, checksum)
  723. in self.fake_checksum_by_file.items()
  724. if not file_path.endswith(".dsc"))
  725. self.patch_parse_changes()
  726. with testtools.ExpectedException(FakeSystemExit):
  727. dput.dput.verify_files(**self.test_args)
  728. expected_output = textwrap.dedent("""\
  729. Error: no dsc file found in sourceful upload
  730. """)
  731. self.assertThat(
  732. sys.stderr.getvalue(),
  733. testtools.matchers.Contains(expected_output))
  734. sys.exit.assert_called_with(EXIT_STATUS_FAILURE)
  735. def test_calls_version_check_when_specified_in_config(self):
  736. """ Should call `version_check` when specified in config. """
  737. self.runtime_config_parser.set(
  738. self.test_args['host'], 'check_version', "true")
  739. dput.dput.verify_files(**self.test_args)
  740. dput.dput.version_check.assert_called_with(
  741. os.path.dirname(self.changes_file_double.path),
  742. self.changes_document,
  743. self.test_args['debug'])
  744. def test_calls_version_check_when_specified_in_args(self):
  745. """ Should call `version_check` when specified in arguments. """
  746. self.test_args['check_version'] = True
  747. dput.dput.verify_files(**self.test_args)
  748. dput.dput.version_check.assert_called_with(
  749. os.path.dirname(self.changes_file_double.path),
  750. self.changes_document,
  751. self.test_args['debug'])
  752. def test_calls_sys_exit_when_host_section_not_in_config(self):
  753. """ Should call `sys.exit` when specified host not in config. """
  754. self.runtime_config_parser.remove_section(self.test_args['host'])
  755. with testtools.ExpectedException(FakeSystemExit):
  756. dput.dput.verify_files(**self.test_args)
  757. expected_output = textwrap.dedent("""\
  758. Error in config file:
  759. No section: ...
  760. """)
  761. self.assertThat(
  762. sys.stderr.getvalue(),
  763. testtools.matchers.DocTestMatches(
  764. expected_output, doctest.ELLIPSIS))
  765. sys.exit.assert_called_with(EXIT_STATUS_FAILURE)
  766. def test_calls_verify_signature_with_expected_args(self):
  767. """ Should call `verify_signature` with expected args. """
  768. dput.dput.verify_files(**self.test_args)
  769. dput.dput.verify_signature.assert_called_with(
  770. self.test_args['host'],
  771. self.changes_file_double.path,
  772. self.expected_source_control_file_path,
  773. self.runtime_config_parser,
  774. self.test_args['check_only'],
  775. self.test_args['unsigned_upload'], mock.ANY,
  776. self.test_args['debug'])
  777. def test_calls_source_check_with_changes_document(self):
  778. """ Should call `source_check` with changes document. """
  779. dput.dput.verify_files(**self.test_args)
  780. dput.dput.source_check.assert_called_with(
  781. self.changes_document, self.test_args['debug'])
  782. def test_emits_upload_file_path_debug_message(self):
  783. """ Should emit debug message for each upload file path. """
  784. self.test_args['debug'] = True
  785. dput.dput.verify_files(**self.test_args)
  786. for file_path in self.fake_upload_file_paths:
  787. expected_output = textwrap.dedent("""\
  788. D: File to upload: {path}
  789. """).format(path=file_path)
  790. self.expectThat(
  791. sys.stdout.getvalue(),
  792. testtools.matchers.Contains(expected_output))
  793. def test_calls_checksum_test_with_upload_files(self):
  794. """ Should call `checksum_test` with each upload file path. """
  795. dput.dput.verify_files(**self.test_args)
  796. expected_calls = [
  797. mock.call(file_path, mock.ANY)
  798. for file_path in self.fake_upload_file_paths]
  799. dput.dput.checksum_test.assert_has_calls(
  800. expected_calls, any_order=True)
  801. def set_bogus_file_checksums(self):
  802. """ Set bogus file checksums that will not match. """
  803. self.fake_checksum_by_file = {
  804. file_name: self.getUniqueString()
  805. for file_name in self.fake_checksum_by_file}
  806. def test_emits_checksum_okay_debug_message(self):
  807. """ Should emit debug message checksum okay for each file. """
  808. self.test_args['debug'] = True
  809. dput.dput.verify_files(**self.test_args)
  810. for file_path in self.fake_upload_file_paths:
  811. expected_output = textwrap.dedent("""\
  812. D: Checksum for {path} is fine
  813. """).format(path=file_path)
  814. self.expectThat(
  815. sys.stdout.getvalue(),
  816. testtools.matchers.Contains(expected_output))
  817. def test_emits_checksum_mismatch_debug_message(self):
  818. """ Should emit debug message when a checksum does not match. """
  819. self.test_args['debug'] = True
  820. self.set_bogus_file_checksums()
  821. with testtools.ExpectedException(FakeSystemExit):
  822. dput.dput.verify_files(**self.test_args)
  823. expected_output = textwrap.dedent("""\
  824. ...
  825. D: Checksum from .changes: ...
  826. D: Generated Checksum: ...
  827. ...
  828. """)
  829. self.assertThat(
  830. sys.stdout.getvalue(),
  831. testtools.matchers.DocTestMatches(
  832. expected_output, doctest.ELLIPSIS))
  833. def test_calls_sys_exit_when_checksum_mismatch(self):
  834. """ Should call `sys.exit` when a checksum does not match. """
  835. specified_checksum_by_file = self.fake_checksum_by_file
  836. self.set_bogus_file_checksums()
  837. with testtools.ExpectedException(FakeSystemExit):
  838. dput.dput.verify_files(**self.test_args)
  839. expected_output_for_files = [
  840. textwrap.dedent("""\
  841. Checksum doesn't match for {file_name}
  842. """).format(
  843. file_name=os.path.join(
  844. os.path.dirname(self.changes_file_double.path),
  845. file_name),
  846. specified_hash=specified_hash,
  847. computed_hash=self.fake_checksum_by_file[file_name])
  848. for (file_name, specified_hash)
  849. in specified_checksum_by_file.items()]
  850. self.assertThat(
  851. sys.stdout.getvalue(),
  852. testtools.matchers.MatchesAny(*[
  853. testtools.matchers.Contains(expected_output)
  854. for expected_output in expected_output_for_files]))
  855. sys.exit.assert_called_with(EXIT_STATUS_FAILURE)
  856. def test_calls_os_stat_with_upload_files(self):
  857. """ Should call `os.stat` with each upload file path. """
  858. dput.dput.verify_files(**self.test_args)
  859. expected_calls = [
  860. mock.call(file_path)
  861. for file_path in self.fake_upload_file_paths]
  862. os.stat.assert_has_calls(expected_calls, any_order=True)
  863. def set_bogus_file_sizes(self):
  864. """ Set bogus file sizes that will not match. """
  865. file_double_registry = FileDouble.get_registry_for_testcase(self)
  866. for file_name in self.fake_size_by_file:
  867. bogus_size = self.getUniqueInteger()
  868. self.fake_size_by_file[file_name] = bogus_size
  869. file_path = os.path.join(
  870. os.path.dirname(self.changes_file_double.path),
  871. file_name)
  872. file_double = file_double_registry[file_path]
  873. file_double.stat_result = file_double.stat_result._replace(
  874. st_size=bogus_size)
  875. def test_emits_size_mismatch_debug_message(self):
  876. """ Should emit debug message when a size does not match. """
  877. self.test_args['debug'] = True
  878. self.set_bogus_file_sizes()
  879. dput.dput.verify_files(**self.test_args)
  880. expected_output = textwrap.dedent("""\
  881. ...
  882. D: size from .changes: ...
  883. D: calculated size: ...
  884. ...
  885. """)
  886. self.assertThat(
  887. sys.stdout.getvalue(),
  888. testtools.matchers.DocTestMatches(
  889. expected_output, doctest.ELLIPSIS))
  890. def test_emits_size_mismatch_message_for_each_file(self):
  891. """ Should emit error message for each file with size mismatch. """
  892. self.set_bogus_file_sizes()
  893. dput.dput.verify_files(**self.test_args)
  894. for file_path in self.fake_upload_file_paths:
  895. expected_output = textwrap.dedent("""\
  896. size doesn't match for {path}
  897. """).format(path=file_path)
  898. self.expectThat(
  899. sys.stdout.getvalue(),
  900. testtools.matchers.Contains(expected_output))
  901. def test_emits_rejection_warning_when_unexpected_tarball(self):
  902. """ Should emit warning of rejection when unexpected tarball. """
  903. if not hasattr(self, 'expected_rejection_message'):
  904. self.skipTest("No rejection message expected")
  905. dput.dput.verify_files(**self.test_args)
  906. sys.stderr.write("calls: {calls!r}\n".format(
  907. calls=sys.stdout.write.mock_calls))
  908. self.assertThat(
  909. sys.stdout.getvalue(),
  910. testtools.matchers.Contains(self.expected_rejection_message))
  911. def test_raises_error_when_distribution_mismatch(self):
  912. """ Should raise error when distribution mismatch against allowed. """
  913. if not getattr(self, 'test_distribution', None):
  914. self.skipTest("No distribution set for this test case")
  915. self.runtime_config_parser.set(
  916. self.test_args['host'], 'allowed_distributions',
  917. "dolor sit amet")
  918. with testtools.ExpectedException(dputhelper.DputUploadFatalException):
  919. dput.dput.verify_files(**self.test_args)
  920. def test_emits_changes_file_upload_debug_message(self):
  921. """ Should emit debug message for upload of changes file. """
  922. self.test_args['debug'] = True
  923. dput.dput.verify_files(**self.test_args)
  924. expected_output = textwrap.dedent("""\
  925. D: File to upload: {path}
  926. """).format(path=self.changes_file_double.path)
  927. self.assertIn(expected_output, sys.stdout.getvalue())
  928. def test_returns_expected_files_to_upload_collection(self):
  929. """ Should return expected `files_to_upload` collection value. """
  930. result = dput.dput.verify_files(**self.test_args)
  931. expected_result = self.expected_files_to_upload
  932. self.assertEqual(expected_result, set(result))
  933. class guess_upload_host_TestCase(
  934. testscenarios.WithScenarios,
  935. testtools.TestCase):
  936. """ Test cases for `guess_upload_host` function. """
  937. changes_file_scenarios = [
  938. ('no-distribution', {
  939. 'fake_file': StringIO(textwrap.dedent("""\
  940. Files:
  941. Lorem ipsum dolor sit amet
  942. """)),
  943. }),
  944. ('distribution-spam', {
  945. 'fake_file': StringIO(textwrap.dedent("""\
  946. Distribution: spam
  947. Files:
  948. Lorem ipsum dolor sit amet
  949. """)),
  950. }),
  951. ('distribution-beans', {
  952. 'fake_file': StringIO(textwrap.dedent("""\
  953. Distribution: beans
  954. Files:
  955. Lorem ipsum dolor sit amet
  956. """)),
  957. }),
  958. ]
  959. scenarios = [
  960. ('distribution-found-of-one', {
  961. 'changes_file_scenario_name': "distribution-spam",
  962. 'test_distribution': "spam",
  963. 'config_scenario_name': "exist-distribution-one",
  964. 'expected_host': "foo",
  965. }),
  966. ('distribution-notfound-of-one', {
  967. 'changes_file_scenario_name': "distribution-beans",
  968. 'test_distribution': "beans",
  969. 'config_scenario_name': "exist-distribution-one",
  970. 'expected_host': "ftp-master",
  971. }),
  972. ('distribution-first-of-three', {
  973. 'changes_file_scenario_name': "distribution-spam",
  974. 'test_distribution': "spam",
  975. 'config_scenario_name': "exist-distribution-three",
  976. 'expected_host': "foo",
  977. }),
  978. ('distribution-last-of-three', {
  979. 'changes_file_scenario_name': "distribution-beans",
  980. 'test_distribution': "beans",
  981. 'config_scenario_name': "exist-distribution-three",
  982. 'expected_host': "foo",
  983. }),
  984. ('no-configured-distribution', {
  985. 'changes_file_scenario_name': "distribution-beans",
  986. 'config_scenario_name': "exist-distribution-none",
  987. 'expected_host': "ftp-master",
  988. }),
  989. ('no-distribution', {
  990. 'changes_file_scenario_name': "no-distribution",
  991. 'config_scenario_name': "exist-simple",
  992. 'expected_host': "ftp-master",
  993. }),
  994. ('default-distribution', {
  995. 'config_scenario_name': "exist-default-distribution-only",
  996. 'config_default_default_host_main': "consecteur",
  997. 'expected_host': "consecteur",
  998. }),
  999. ]
  1000. def setUp(self):
  1001. """ Set up test fixtures. """
  1002. super(guess_upload_host_TestCase, self).setUp()
  1003. patch_system_interfaces(self)
  1004. set_config(
  1005. self,
  1006. getattr(self, 'config_scenario_name', 'exist-minimal'))
  1007. patch_runtime_config_options(self)
  1008. self.setup_changes_file_fixtures()
  1009. set_changes_file_scenario(
  1010. self,
  1011. getattr(self, 'changes_file_scenario_name', 'no-distribution'))
  1012. self.set_test_args()
  1013. def set_test_args(self):
  1014. """ Set the arguments for the test call to the function. """
  1015. self.test_args = dict(
  1016. path=os.path.dirname(self.changes_file_double.path),
  1017. filename=os.path.basename(self.changes_file_double.path),
  1018. config=self.runtime_config_parser,
  1019. )
  1020. def setup_changes_file_fixtures(self):
  1021. """ Set up fixtures for fake changes file. """
  1022. file_path = make_changes_file_path()
  1023. scenarios = [s for (__, s) in self.changes_file_scenarios]
  1024. for scenario in scenarios:
  1025. scenario['file_double'] = FileDouble(
  1026. file_path, scenario['fake_file'])
  1027. setup_file_double_behaviour(
  1028. self,
  1029. get_file_doubles_from_fake_file_scenarios(scenarios))
  1030. def test_calls_sys_exit_if_read_denied(self):
  1031. """ Should call `sys.exit` if read permission denied. """
  1032. self.changes_file_double.set_os_access_scenario('denied')
  1033. self.changes_file_double.set_open_scenario('read_denied')
  1034. with testtools.ExpectedException(FakeSystemExit):
  1035. dput.dput.guess_upload_host(**self.test_args)
  1036. expected_output = textwrap.dedent("""\
  1037. Can't open {path}
  1038. """).format(path=self.changes_file_double.path)
  1039. self.assertIn(expected_output, sys.stdout.getvalue())
  1040. sys.exit.assert_called_with(EXIT_STATUS_FAILURE)
  1041. def test_returns_expected_host(self):
  1042. """ Should return expected host value. """
  1043. result = dput.dput.guess_upload_host(**self.test_args)
  1044. self.assertEqual(self.expected_host, result)
  1045. @mock.patch.object(dput.dput, 'debug', True)
  1046. def test_emits_debug_message_for_host(self):
  1047. """ Should emit a debug message for the discovered host. """
  1048. config_parser = self.runtime_config_parser
  1049. if not (
  1050. config_parser.has_section(self.expected_host)
  1051. and config_parser.get(self.expected_host, 'distributions')):
  1052. self.skipTest("No distributions specified")
  1053. dput.dput.guess_upload_host(**self.test_args)
  1054. expected_output = textwrap.dedent("""\
  1055. D: guessing host {host} based on distribution {dist}
  1056. """).format(
  1057. host=self.expected_host, dist=self.test_distribution)
  1058. self.assertIn(expected_output, sys.stdout.getvalue())
  1059. # Local variables:
  1060. # coding: utf-8
  1061. # mode: python
  1062. # End:
  1063. # vim: fileencoding=utf-8 filetype=python :