test_utils.py 41 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138
  1. # Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License"). You
  4. # may not use this file except in compliance with the License. A copy of
  5. # the License is located at
  6. #
  7. # http://aws.amazon.com/apache2.0/
  8. #
  9. # or in the "license" file accompanying this file. This file is
  10. # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
  11. # ANY KIND, either express or implied. See the License for the specific
  12. # language governing permissions and limitations under the License.
  13. import os.path
  14. import shutil
  15. import tempfile
  16. import threading
  17. import random
  18. import re
  19. import time
  20. import io
  21. import mock
  22. from __tests__ import unittest
  23. from __tests__ import RecordingSubscriber
  24. from __tests__ import NonSeekableWriter
  25. from s3transfer.compat import six
  26. from s3transfer.futures import TransferFuture
  27. from s3transfer.futures import TransferMeta
  28. from s3transfer.utils import get_callbacks
  29. from s3transfer.utils import random_file_extension
  30. from s3transfer.utils import invoke_progress_callbacks
  31. from s3transfer.utils import calculate_num_parts
  32. from s3transfer.utils import calculate_range_parameter
  33. from s3transfer.utils import get_filtered_dict
  34. from s3transfer.utils import CallArgs
  35. from s3transfer.utils import FunctionContainer
  36. from s3transfer.utils import CountCallbackInvoker
  37. from s3transfer.utils import OSUtils
  38. from s3transfer.utils import DeferredOpenFile
  39. from s3transfer.utils import ReadFileChunk
  40. from s3transfer.utils import StreamReaderProgress
  41. from s3transfer.utils import TaskSemaphore
  42. from s3transfer.utils import SlidingWindowSemaphore
  43. from s3transfer.utils import NoResourcesAvailable
  44. from s3transfer.utils import ChunksizeAdjuster
  45. from s3transfer.utils import MIN_UPLOAD_CHUNKSIZE, MAX_SINGLE_UPLOAD_SIZE
  46. from s3transfer.utils import MAX_PARTS
  47. class TestGetCallbacks(unittest.TestCase):
  48. def setUp(self):
  49. self.subscriber = RecordingSubscriber()
  50. self.second_subscriber = RecordingSubscriber()
  51. self.call_args = CallArgs(subscribers=[
  52. self.subscriber, self.second_subscriber]
  53. )
  54. self.transfer_meta = TransferMeta(self.call_args)
  55. self.transfer_future = TransferFuture(self.transfer_meta)
  56. def test_get_callbacks(self):
  57. callbacks = get_callbacks(self.transfer_future, 'queued')
  58. # Make sure two callbacks were added as both subscribers had
  59. # an on_queued method.
  60. self.assertEqual(len(callbacks), 2)
  61. # Ensure that the callback was injected with the future by calling
  62. # one of them and checking that the future was used in the call.
  63. callbacks[0]()
  64. self.assertEqual(
  65. self.subscriber.on_queued_calls,
  66. [{'future': self.transfer_future}]
  67. )
  68. def test_get_callbacks_for_missing_type(self):
  69. callbacks = get_callbacks(self.transfer_future, 'fake_state')
  70. # There should be no callbacks as the subscribers will not have the
  71. # on_fake_state method
  72. self.assertEqual(len(callbacks), 0)
  73. class TestGetFilteredDict(unittest.TestCase):
  74. def test_get_filtered_dict(self):
  75. original = {
  76. 'Include': 'IncludeValue',
  77. 'NotInlude': 'NotIncludeValue'
  78. }
  79. whitelist = ['Include']
  80. self.assertEqual(
  81. get_filtered_dict(original, whitelist),
  82. {'Include': 'IncludeValue'}
  83. )
  84. class TestCallArgs(unittest.TestCase):
  85. def test_call_args(self):
  86. call_args = CallArgs(foo='bar', biz='baz')
  87. self.assertEqual(call_args.foo, 'bar')
  88. self.assertEqual(call_args.biz, 'baz')
  89. class TestFunctionContainer(unittest.TestCase):
  90. def get_args_kwargs(self, *args, **kwargs):
  91. return args, kwargs
  92. def test_call(self):
  93. func_container = FunctionContainer(
  94. self.get_args_kwargs, 'foo', bar='baz')
  95. self.assertEqual(func_container(), (('foo',), {'bar': 'baz'}))
  96. def test_repr(self):
  97. func_container = FunctionContainer(
  98. self.get_args_kwargs, 'foo', bar='baz')
  99. self.assertEqual(
  100. str(func_container), 'Function: %s with args %s and kwargs %s' % (
  101. self.get_args_kwargs, ('foo',), {'bar': 'baz'}))
  102. class TestCountCallbackInvoker(unittest.TestCase):
  103. def invoke_callback(self):
  104. self.ref_results.append('callback invoked')
  105. def assert_callback_invoked(self):
  106. self.assertEqual(self.ref_results, ['callback invoked'])
  107. def assert_callback_not_invoked(self):
  108. self.assertEqual(self.ref_results, [])
  109. def setUp(self):
  110. self.ref_results = []
  111. self.invoker = CountCallbackInvoker(self.invoke_callback)
  112. def test_increment(self):
  113. self.invoker.increment()
  114. self.assertEqual(self.invoker.current_count, 1)
  115. def test_decrement(self):
  116. self.invoker.increment()
  117. self.invoker.increment()
  118. self.invoker.decrement()
  119. self.assertEqual(self.invoker.current_count, 1)
  120. def test_count_cannot_go_below_zero(self):
  121. with self.assertRaises(RuntimeError):
  122. self.invoker.decrement()
  123. def test_callback_invoked_only_once_finalized(self):
  124. self.invoker.increment()
  125. self.invoker.decrement()
  126. self.assert_callback_not_invoked()
  127. self.invoker.finalize()
  128. # Callback should only be invoked once finalized
  129. self.assert_callback_invoked()
  130. def test_callback_invoked_after_finalizing_and_count_reaching_zero(self):
  131. self.invoker.increment()
  132. self.invoker.finalize()
  133. # Make sure that it does not get invoked immediately after
  134. # finalizing as the count is currently one
  135. self.assert_callback_not_invoked()
  136. self.invoker.decrement()
  137. self.assert_callback_invoked()
  138. def test_cannot_increment_after_finalization(self):
  139. self.invoker.finalize()
  140. with self.assertRaises(RuntimeError):
  141. self.invoker.increment()
  142. class TestRandomFileExtension(unittest.TestCase):
  143. def test_has_proper_length(self):
  144. self.assertEqual(
  145. len(random_file_extension(num_digits=4)), 4)
  146. class TestInvokeProgressCallbacks(unittest.TestCase):
  147. def test_invoke_progress_callbacks(self):
  148. recording_subscriber = RecordingSubscriber()
  149. invoke_progress_callbacks([recording_subscriber.on_progress], 2)
  150. self.assertEqual(recording_subscriber.calculate_bytes_seen(), 2)
  151. def test_invoke_progress_callbacks_with_no_progress(self):
  152. recording_subscriber = RecordingSubscriber()
  153. invoke_progress_callbacks([recording_subscriber.on_progress], 0)
  154. self.assertEqual(len(recording_subscriber.on_progress_calls), 0)
  155. class TestCalculateNumParts(unittest.TestCase):
  156. def test_calculate_num_parts_divisible(self):
  157. self.assertEqual(calculate_num_parts(size=4, part_size=2), 2)
  158. def test_calculate_num_parts_not_divisible(self):
  159. self.assertEqual(calculate_num_parts(size=3, part_size=2), 2)
  160. class TestCalculateRangeParameter(unittest.TestCase):
  161. def setUp(self):
  162. self.part_size = 5
  163. self.part_index = 1
  164. self.num_parts = 3
  165. def test_calculate_range_paramter(self):
  166. range_val = calculate_range_parameter(
  167. self.part_size, self.part_index, self.num_parts)
  168. self.assertEqual(range_val, 'bytes=5-9')
  169. def test_last_part_with_no_total_size(self):
  170. range_val = calculate_range_parameter(
  171. self.part_size, self.part_index, num_parts=2)
  172. self.assertEqual(range_val, 'bytes=5-')
  173. def test_last_part_with_total_size(self):
  174. range_val = calculate_range_parameter(
  175. self.part_size, self.part_index, num_parts=2, total_size=8)
  176. self.assertEqual(range_val, 'bytes=5-7')
  177. class BaseUtilsTest(unittest.TestCase):
  178. def setUp(self):
  179. self.tempdir = tempfile.mkdtemp()
  180. self.filename = os.path.join(self.tempdir, 'foo')
  181. self.content = b'abc'
  182. with open(self.filename, 'wb') as f:
  183. f.write(self.content)
  184. self.amounts_seen = []
  185. self.num_close_callback_calls = 0
  186. def tearDown(self):
  187. shutil.rmtree(self.tempdir)
  188. def callback(self, bytes_transferred):
  189. self.amounts_seen.append(bytes_transferred)
  190. def close_callback(self):
  191. self.num_close_callback_calls += 1
  192. class TestOSUtils(BaseUtilsTest):
  193. def test_get_file_size(self):
  194. self.assertEqual(
  195. OSUtils().get_file_size(self.filename), len(self.content))
  196. def test_open_file_chunk_reader(self):
  197. reader = OSUtils().open_file_chunk_reader(
  198. self.filename, 0, 3, [self.callback])
  199. # The returned reader should be a ReadFileChunk.
  200. self.assertIsInstance(reader, ReadFileChunk)
  201. # The content of the reader should be correct.
  202. self.assertEqual(reader.read(), self.content)
  203. # Callbacks should be disabled depspite being passed in.
  204. self.assertEqual(self.amounts_seen, [])
  205. def test_open_file_chunk_reader_from_fileobj(self):
  206. with open(self.filename, 'rb') as f:
  207. reader = OSUtils().open_file_chunk_reader_from_fileobj(
  208. f, len(self.content), len(self.content), [self.callback])
  209. # The returned reader should be a ReadFileChunk.
  210. self.assertIsInstance(reader, ReadFileChunk)
  211. # The content of the reader should be correct.
  212. self.assertEqual(reader.read(), self.content)
  213. reader.close()
  214. # Callbacks should be disabled depspite being passed in.
  215. self.assertEqual(self.amounts_seen, [])
  216. self.assertEqual(self.num_close_callback_calls, 0)
  217. def test_open_file(self):
  218. fileobj = OSUtils().open(os.path.join(self.tempdir, 'foo'), 'w')
  219. self.assertTrue(hasattr(fileobj, 'write'))
  220. def test_remove_file_ignores_errors(self):
  221. non_existent_file = os.path.join(self.tempdir, 'no-exist')
  222. # This should not exist to start.
  223. self.assertFalse(os.path.exists(non_existent_file))
  224. try:
  225. OSUtils().remove_file(non_existent_file)
  226. except OSError as e:
  227. self.fail('OSError should have been caught: %s' % e)
  228. def test_remove_file_proxies_remove_file(self):
  229. OSUtils().remove_file(self.filename)
  230. self.assertFalse(os.path.exists(self.filename))
  231. def test_rename_file(self):
  232. new_filename = os.path.join(self.tempdir, 'newfoo')
  233. OSUtils().rename_file(self.filename, new_filename)
  234. self.assertFalse(os.path.exists(self.filename))
  235. self.assertTrue(os.path.exists(new_filename))
  236. def test_is_special_file_for_normal_file(self):
  237. self.assertFalse(OSUtils().is_special_file(self.filename))
  238. def test_is_special_file_for_non_existant_file(self):
  239. non_existant_filename = os.path.join(self.tempdir, 'no-exist')
  240. self.assertFalse(os.path.exists(non_existant_filename))
  241. self.assertFalse(OSUtils().is_special_file(non_existant_filename))
  242. def test_get_temp_filename(self):
  243. filename = 'myfile'
  244. self.assertIsNotNone(
  245. re.match(
  246. '%s\.[0-9A-Fa-f]{8}$' % filename,
  247. OSUtils().get_temp_filename(filename)
  248. )
  249. )
  250. def test_get_temp_filename_len_255(self):
  251. filename = 'a'*255
  252. temp_filename = OSUtils().get_temp_filename(filename)
  253. self.assertLessEqual(len(temp_filename), 255)
  254. def test_get_temp_filename_len_gt_255(self):
  255. filename = 'a'*280
  256. temp_filename = OSUtils().get_temp_filename(filename)
  257. self.assertLessEqual(len(temp_filename), 255)
  258. def test_allocate(self):
  259. truncate_size = 1
  260. OSUtils().allocate(self.filename, truncate_size)
  261. with open(self.filename, 'rb') as f:
  262. self.assertEqual(len(f.read()), truncate_size)
  263. @mock.patch('s3transfer.utils.fallocate')
  264. def test_allocate_with_io_error(self, mock_fallocate):
  265. mock_fallocate.side_effect = IOError()
  266. with self.assertRaises(IOError):
  267. OSUtils().allocate(self.filename, 1)
  268. self.assertFalse(os.path.exists(self.filename))
  269. @mock.patch('s3transfer.utils.fallocate')
  270. def test_allocate_with_os_error(self, mock_fallocate):
  271. mock_fallocate.side_effect = OSError()
  272. with self.assertRaises(OSError):
  273. OSUtils().allocate(self.filename, 1)
  274. self.assertFalse(os.path.exists(self.filename))
  275. class TestDeferredOpenFile(BaseUtilsTest):
  276. def setUp(self):
  277. super(TestDeferredOpenFile, self).setUp()
  278. self.filename = os.path.join(self.tempdir, 'foo')
  279. self.contents = b'my contents'
  280. with open(self.filename, 'wb') as f:
  281. f.write(self.contents)
  282. self.deferred_open_file = DeferredOpenFile(
  283. self.filename, open_function=self.recording_open_function)
  284. self.open_call_args = []
  285. def tearDown(self):
  286. self.deferred_open_file.close()
  287. super(TestDeferredOpenFile, self).tearDown()
  288. def recording_open_function(self, filename, mode):
  289. self.open_call_args.append((filename, mode))
  290. return open(filename, mode)
  291. def open_nonseekable(self, filename, mode):
  292. self.open_call_args.append((filename, mode))
  293. return NonSeekableWriter(six.BytesIO(self.content))
  294. def test_instantiation_does_not_open_file(self):
  295. DeferredOpenFile(
  296. self.filename, open_function=self.recording_open_function)
  297. self.assertEqual(len(self.open_call_args), 0)
  298. def test_name(self):
  299. self.assertEqual(self.deferred_open_file.name, self.filename)
  300. def test_read(self):
  301. content = self.deferred_open_file.read(2)
  302. self.assertEqual(content, self.contents[0:2])
  303. content = self.deferred_open_file.read(2)
  304. self.assertEqual(content, self.contents[2:4])
  305. self.assertEqual(len(self.open_call_args), 1)
  306. def test_write(self):
  307. self.deferred_open_file = DeferredOpenFile(
  308. self.filename, mode='wb',
  309. open_function=self.recording_open_function)
  310. write_content = b'foo'
  311. self.deferred_open_file.write(write_content)
  312. self.deferred_open_file.write(write_content)
  313. self.deferred_open_file.close()
  314. # Both of the writes should now be in the file.
  315. with open(self.filename, 'rb') as f:
  316. self.assertEqual(f.read(), write_content*2)
  317. # Open should have only been called once.
  318. self.assertEqual(len(self.open_call_args), 1)
  319. def test_seek(self):
  320. self.deferred_open_file.seek(2)
  321. content = self.deferred_open_file.read(2)
  322. self.assertEqual(content, self.contents[2:4])
  323. self.assertEqual(len(self.open_call_args), 1)
  324. def test_open_does_not_seek_with_zero_start_byte(self):
  325. self.deferred_open_file = DeferredOpenFile(
  326. self.filename, mode='wb', start_byte=0,
  327. open_function=self.open_nonseekable)
  328. try:
  329. # If this seeks, an UnsupportedOperation error will be raised.
  330. self.deferred_open_file.write(b'data')
  331. except io.UnsupportedOperation:
  332. self.fail('DeferredOpenFile seeked upon opening')
  333. def test_open_seeks_with_nonzero_start_byte(self):
  334. self.deferred_open_file = DeferredOpenFile(
  335. self.filename, mode='wb', start_byte=5,
  336. open_function=self.open_nonseekable)
  337. # Since a non-seekable file is being opened, calling Seek will raise
  338. # an UnsupportedOperation error.
  339. with self.assertRaises(io.UnsupportedOperation):
  340. self.deferred_open_file.write(b'data')
  341. def test_tell(self):
  342. self.deferred_open_file.tell()
  343. # tell() should not have opened the file if it has not been seeked
  344. # or read because we know the start bytes upfront.
  345. self.assertEqual(len(self.open_call_args), 0)
  346. self.deferred_open_file.seek(2)
  347. self.assertEqual(self.deferred_open_file.tell(), 2)
  348. self.assertEqual(len(self.open_call_args), 1)
  349. def test_open_args(self):
  350. self.deferred_open_file = DeferredOpenFile(
  351. self.filename, mode='ab+',
  352. open_function=self.recording_open_function)
  353. # Force an open
  354. self.deferred_open_file.write(b'data')
  355. self.assertEqual(len(self.open_call_args), 1)
  356. self.assertEqual(self.open_call_args[0], (self.filename, 'ab+'))
  357. def test_context_handler(self):
  358. with self.deferred_open_file:
  359. self.assertEqual(len(self.open_call_args), 1)
  360. class TestReadFileChunk(BaseUtilsTest):
  361. def test_read_entire_chunk(self):
  362. filename = os.path.join(self.tempdir, 'foo')
  363. with open(filename, 'wb') as f:
  364. f.write(b'onetwothreefourfivesixseveneightnineten')
  365. chunk = ReadFileChunk.from_filename(
  366. filename, start_byte=0, chunk_size=3)
  367. self.assertEqual(chunk.read(), b'one')
  368. self.assertEqual(chunk.read(), b'')
  369. def test_read_with_amount_size(self):
  370. filename = os.path.join(self.tempdir, 'foo')
  371. with open(filename, 'wb') as f:
  372. f.write(b'onetwothreefourfivesixseveneightnineten')
  373. chunk = ReadFileChunk.from_filename(
  374. filename, start_byte=11, chunk_size=4)
  375. self.assertEqual(chunk.read(1), b'f')
  376. self.assertEqual(chunk.read(1), b'o')
  377. self.assertEqual(chunk.read(1), b'u')
  378. self.assertEqual(chunk.read(1), b'r')
  379. self.assertEqual(chunk.read(1), b'')
  380. def test_reset_stream_emulation(self):
  381. filename = os.path.join(self.tempdir, 'foo')
  382. with open(filename, 'wb') as f:
  383. f.write(b'onetwothreefourfivesixseveneightnineten')
  384. chunk = ReadFileChunk.from_filename(
  385. filename, start_byte=11, chunk_size=4)
  386. self.assertEqual(chunk.read(), b'four')
  387. chunk.seek(0)
  388. self.assertEqual(chunk.read(), b'four')
  389. def test_read_past_end_of_file(self):
  390. filename = os.path.join(self.tempdir, 'foo')
  391. with open(filename, 'wb') as f:
  392. f.write(b'onetwothreefourfivesixseveneightnineten')
  393. chunk = ReadFileChunk.from_filename(
  394. filename, start_byte=36, chunk_size=100000)
  395. self.assertEqual(chunk.read(), b'ten')
  396. self.assertEqual(chunk.read(), b'')
  397. self.assertEqual(len(chunk), 3)
  398. def test_tell_and_seek(self):
  399. filename = os.path.join(self.tempdir, 'foo')
  400. with open(filename, 'wb') as f:
  401. f.write(b'onetwothreefourfivesixseveneightnineten')
  402. chunk = ReadFileChunk.from_filename(
  403. filename, start_byte=36, chunk_size=100000)
  404. self.assertEqual(chunk.tell(), 0)
  405. self.assertEqual(chunk.read(), b'ten')
  406. self.assertEqual(chunk.tell(), 3)
  407. chunk.seek(0)
  408. self.assertEqual(chunk.tell(), 0)
  409. chunk.seek(1, whence=1)
  410. self.assertEqual(chunk.tell(), 1)
  411. chunk.seek(-1, whence=1)
  412. self.assertEqual(chunk.tell(), 0)
  413. chunk.seek(-1, whence=2)
  414. self.assertEqual(chunk.tell(), 2)
  415. def test_tell_and_seek_boundaries(self):
  416. # Test to ensure ReadFileChunk behaves the same as the
  417. # Python standard library around seeking and reading out
  418. # of bounds in a file object.
  419. data = b'abcdefghij12345678klmnopqrst'
  420. start_pos = 10
  421. chunk_size = 8
  422. # Create test file
  423. filename = os.path.join(self.tempdir, 'foo')
  424. with open(filename, 'wb') as f:
  425. f.write(data)
  426. # ReadFileChunk should be a substring of only numbers
  427. file_objects = [
  428. ReadFileChunk.from_filename(
  429. filename, start_byte=start_pos, chunk_size=chunk_size
  430. )]
  431. # Uncomment next line to validate we match Python's io.BytesIO
  432. # file_objects.append(io.BytesIO(data[start_pos:start_pos+chunk_size]))
  433. for obj in file_objects:
  434. self._assert_whence_start_behavior(obj)
  435. self._assert_whence_end_behavior(obj)
  436. self._assert_whence_relative_behavior(obj)
  437. self._assert_boundary_behavior(obj)
  438. def _assert_whence_start_behavior(self, file_obj):
  439. self.assertEqual(file_obj.tell(), 0)
  440. file_obj.seek(1, 0)
  441. self.assertEqual(file_obj.tell(), 1)
  442. file_obj.seek(1)
  443. self.assertEqual(file_obj.tell(), 1)
  444. self.assertEqual(file_obj.read(), b'2345678')
  445. file_obj.seek(3, 0)
  446. self.assertEqual(file_obj.tell(), 3)
  447. file_obj.seek(0, 0)
  448. self.assertEqual(file_obj.tell(), 0)
  449. def _assert_whence_relative_behavior(self, file_obj):
  450. self.assertEqual(file_obj.tell(), 0)
  451. file_obj.seek(2, 1)
  452. self.assertEqual(file_obj.tell(), 2)
  453. file_obj.seek(1, 1)
  454. self.assertEqual(file_obj.tell(), 3)
  455. self.assertEqual(file_obj.read(), b'45678')
  456. file_obj.seek(20, 1)
  457. self.assertEqual(file_obj.tell(), 28)
  458. file_obj.seek(-30, 1)
  459. self.assertEqual(file_obj.tell(), 0)
  460. self.assertEqual(file_obj.read(), b'12345678')
  461. file_obj.seek(-8, 1)
  462. self.assertEqual(file_obj.tell(), 0)
  463. def _assert_whence_end_behavior(self, file_obj):
  464. self.assertEqual(file_obj.tell(), 0)
  465. file_obj.seek(-1, 2)
  466. self.assertEqual(file_obj.tell(), 7)
  467. file_obj.seek(1, 2)
  468. self.assertEqual(file_obj.tell(), 9)
  469. file_obj.seek(3, 2)
  470. self.assertEqual(file_obj.tell(), 11)
  471. self.assertEqual(file_obj.read(), b'')
  472. file_obj.seek(-15, 2)
  473. self.assertEqual(file_obj.tell(), 0)
  474. self.assertEqual(file_obj.read(), b'12345678')
  475. file_obj.seek(-8, 2)
  476. self.assertEqual(file_obj.tell(), 0)
  477. def _assert_boundary_behavior(self, file_obj):
  478. # Verify we're at the start
  479. self.assertEqual(file_obj.tell(), 0)
  480. # Verify we can't move backwards beyond start of file
  481. file_obj.seek(-10, 1)
  482. self.assertEqual(file_obj.tell(), 0)
  483. # Verify we *can* move after end of file, but return nothing
  484. file_obj.seek(10, 2)
  485. self.assertEqual(file_obj.tell(), 18)
  486. self.assertEqual(file_obj.read(), b'')
  487. self.assertEqual(file_obj.read(10), b'')
  488. # Verify we can partially rewind
  489. file_obj.seek(-12, 1)
  490. self.assertEqual(file_obj.tell(), 6)
  491. self.assertEqual(file_obj.read(), b'78')
  492. self.assertEqual(file_obj.tell(), 8)
  493. # Verify we can rewind to start
  494. file_obj.seek(0)
  495. self.assertEqual(file_obj.tell(), 0)
  496. def test_file_chunk_supports_context_manager(self):
  497. filename = os.path.join(self.tempdir, 'foo')
  498. with open(filename, 'wb') as f:
  499. f.write(b'abc')
  500. with ReadFileChunk.from_filename(filename,
  501. start_byte=0,
  502. chunk_size=2) as chunk:
  503. val = chunk.read()
  504. self.assertEqual(val, b'ab')
  505. def test_iter_is_always_empty(self):
  506. # This tests the workaround for the httplib bug (see
  507. # the source for more info).
  508. filename = os.path.join(self.tempdir, 'foo')
  509. open(filename, 'wb').close()
  510. chunk = ReadFileChunk.from_filename(
  511. filename, start_byte=0, chunk_size=10)
  512. self.assertEqual(list(chunk), [])
  513. def test_callback_is_invoked_on_read(self):
  514. chunk = ReadFileChunk.from_filename(
  515. self.filename, start_byte=0, chunk_size=3,
  516. callbacks=[self.callback])
  517. chunk.read(1)
  518. chunk.read(1)
  519. chunk.read(1)
  520. self.assertEqual(self.amounts_seen, [1, 1, 1])
  521. def test_all_callbacks_invoked_on_read(self):
  522. chunk = ReadFileChunk.from_filename(
  523. self.filename, start_byte=0, chunk_size=3,
  524. callbacks=[self.callback, self.callback])
  525. chunk.read(1)
  526. chunk.read(1)
  527. chunk.read(1)
  528. # The list should be twice as long because there are two callbacks
  529. # recording the amount read.
  530. self.assertEqual(self.amounts_seen, [1, 1, 1, 1, 1, 1])
  531. def test_callback_can_be_disabled(self):
  532. chunk = ReadFileChunk.from_filename(
  533. self.filename, start_byte=0, chunk_size=3,
  534. callbacks=[self.callback])
  535. chunk.disable_callback()
  536. # Now reading from the ReadFileChunk should not invoke
  537. # the callback.
  538. chunk.read()
  539. self.assertEqual(self.amounts_seen, [])
  540. def test_callback_will_also_be_triggered_by_seek(self):
  541. chunk = ReadFileChunk.from_filename(
  542. self.filename, start_byte=0, chunk_size=3,
  543. callbacks=[self.callback])
  544. chunk.read(2)
  545. chunk.seek(0)
  546. chunk.read(2)
  547. chunk.seek(1)
  548. chunk.read(2)
  549. self.assertEqual(self.amounts_seen, [2, -2, 2, -1, 2])
  550. def test_callback_triggered_by_out_of_bound_seeks(self):
  551. data = b'abcdefghij1234567890klmnopqr'
  552. # Create test file
  553. filename = os.path.join(self.tempdir, 'foo')
  554. with open(filename, 'wb') as f:
  555. f.write(data)
  556. chunk = ReadFileChunk.from_filename(
  557. filename, start_byte=10, chunk_size=10,
  558. callbacks=[self.callback])
  559. # Seek calls that generate "0" progress are skipped by
  560. # invoke_progress_callbacks and won't appear in the list.
  561. expected_callback_prog = [10, -5, 5, -1, 1, -1, 1, -5, 5, -10]
  562. self._assert_out_of_bound_start_seek(chunk, expected_callback_prog)
  563. self._assert_out_of_bound_relative_seek(chunk, expected_callback_prog)
  564. self._assert_out_of_bound_end_seek(chunk, expected_callback_prog)
  565. def _assert_out_of_bound_start_seek(self, chunk, expected):
  566. # clear amounts_seen
  567. self.amounts_seen = []
  568. self.assertEqual(self.amounts_seen, [])
  569. # (position, change)
  570. chunk.seek(20) # (20, 10)
  571. chunk.seek(5) # (5, -5)
  572. chunk.seek(20) # (20, 5)
  573. chunk.seek(9) # (9, -1)
  574. chunk.seek(20) # (20, 1)
  575. chunk.seek(11) # (11, 0)
  576. chunk.seek(20) # (20, 0)
  577. chunk.seek(9) # (9, -1)
  578. chunk.seek(20) # (20, 1)
  579. chunk.seek(5) # (5, -5)
  580. chunk.seek(20) # (20, 5)
  581. chunk.seek(0) # (0, -10)
  582. chunk.seek(0) # (0, 0)
  583. self.assertEqual(self.amounts_seen, expected)
  584. def _assert_out_of_bound_relative_seek(self, chunk, expected):
  585. # clear amounts_seen
  586. self.amounts_seen = []
  587. self.assertEqual(self.amounts_seen, [])
  588. # (position, change)
  589. chunk.seek(20, 1) # (20, 10)
  590. chunk.seek(-15, 1) # (5, -5)
  591. chunk.seek(15, 1) # (20, 5)
  592. chunk.seek(-11, 1) # (9, -1)
  593. chunk.seek(11, 1) # (20, 1)
  594. chunk.seek(-9, 1) # (11, 0)
  595. chunk.seek(9, 1) # (20, 0)
  596. chunk.seek(-11, 1) # (9, -1)
  597. chunk.seek(11, 1) # (20, 1)
  598. chunk.seek(-15, 1) # (5, -5)
  599. chunk.seek(15, 1) # (20, 5)
  600. chunk.seek(-20, 1) # (0, -10)
  601. chunk.seek(-1000, 1) # (0, 0)
  602. self.assertEqual(self.amounts_seen, expected)
  603. def _assert_out_of_bound_end_seek(self, chunk, expected):
  604. # clear amounts_seen
  605. self.amounts_seen = []
  606. self.assertEqual(self.amounts_seen, [])
  607. # (position, change)
  608. chunk.seek(10, 2) # (20, 10)
  609. chunk.seek(-5, 2) # (5, -5)
  610. chunk.seek(10, 2) # (20, 5)
  611. chunk.seek(-1, 2) # (9, -1)
  612. chunk.seek(10, 2) # (20, 1)
  613. chunk.seek(1, 2) # (11, 0)
  614. chunk.seek(10, 2) # (20, 0)
  615. chunk.seek(-1, 2) # (9, -1)
  616. chunk.seek(10, 2) # (20, 1)
  617. chunk.seek(-5, 2) # (5, -5)
  618. chunk.seek(10, 2) # (20, 5)
  619. chunk.seek(-10, 2) # (0, -10)
  620. chunk.seek(-1000, 2) # (0, 0)
  621. self.assertEqual(self.amounts_seen, expected)
  622. def test_close_callbacks(self):
  623. with open(self.filename) as f:
  624. chunk = ReadFileChunk(f, chunk_size=1, full_file_size=3,
  625. close_callbacks=[self.close_callback])
  626. chunk.close()
  627. self.assertEqual(self.num_close_callback_calls, 1)
  628. def test_close_callbacks_when_not_enabled(self):
  629. with open(self.filename) as f:
  630. chunk = ReadFileChunk(f, chunk_size=1, full_file_size=3,
  631. enable_callbacks=False,
  632. close_callbacks=[self.close_callback])
  633. chunk.close()
  634. self.assertEqual(self.num_close_callback_calls, 0)
  635. def test_close_callbacks_when_context_handler_is_used(self):
  636. with open(self.filename) as f:
  637. with ReadFileChunk(f, chunk_size=1, full_file_size=3,
  638. close_callbacks=[self.close_callback]) as chunk:
  639. chunk.read(1)
  640. self.assertEqual(self.num_close_callback_calls, 1)
  641. def test_signal_transferring(self):
  642. chunk = ReadFileChunk.from_filename(
  643. self.filename, start_byte=0, chunk_size=3,
  644. callbacks=[self.callback])
  645. chunk.signal_not_transferring()
  646. chunk.read(1)
  647. self.assertEqual(self.amounts_seen, [])
  648. chunk.signal_transferring()
  649. chunk.read(1)
  650. self.assertEqual(self.amounts_seen, [1])
  651. def test_signal_transferring_to_underlying_fileobj(self):
  652. underlying_stream = mock.Mock()
  653. underlying_stream.tell.return_value = 0
  654. chunk = ReadFileChunk(underlying_stream, 3, 3)
  655. chunk.signal_transferring()
  656. self.assertTrue(underlying_stream.signal_transferring.called)
  657. def test_no_call_signal_transferring_to_underlying_fileobj(self):
  658. underlying_stream = mock.Mock(io.RawIOBase)
  659. underlying_stream.tell.return_value = 0
  660. chunk = ReadFileChunk(underlying_stream, 3, 3)
  661. try:
  662. chunk.signal_transferring()
  663. except AttributeError:
  664. self.fail(
  665. 'The stream should not have tried to call signal_transferring '
  666. 'to the underlying stream.'
  667. )
  668. def test_signal_not_transferring_to_underlying_fileobj(self):
  669. underlying_stream = mock.Mock()
  670. underlying_stream.tell.return_value = 0
  671. chunk = ReadFileChunk(underlying_stream, 3, 3)
  672. chunk.signal_not_transferring()
  673. self.assertTrue(underlying_stream.signal_not_transferring.called)
  674. def test_no_call_signal_not_transferring_to_underlying_fileobj(self):
  675. underlying_stream = mock.Mock(io.RawIOBase)
  676. underlying_stream.tell.return_value = 0
  677. chunk = ReadFileChunk(underlying_stream, 3, 3)
  678. try:
  679. chunk.signal_not_transferring()
  680. except AttributeError:
  681. self.fail(
  682. 'The stream should not have tried to call '
  683. 'signal_not_transferring to the underlying stream.'
  684. )
  685. class TestStreamReaderProgress(BaseUtilsTest):
  686. def test_proxies_to_wrapped_stream(self):
  687. original_stream = six.StringIO('foobarbaz')
  688. wrapped = StreamReaderProgress(original_stream)
  689. self.assertEqual(wrapped.read(), 'foobarbaz')
  690. def test_callback_invoked(self):
  691. original_stream = six.StringIO('foobarbaz')
  692. wrapped = StreamReaderProgress(
  693. original_stream, [self.callback, self.callback])
  694. self.assertEqual(wrapped.read(), 'foobarbaz')
  695. self.assertEqual(self.amounts_seen, [9, 9])
  696. class TestTaskSemaphore(unittest.TestCase):
  697. def setUp(self):
  698. self.semaphore = TaskSemaphore(1)
  699. def test_should_block_at_max_capacity(self):
  700. self.semaphore.acquire('a', blocking=False)
  701. with self.assertRaises(NoResourcesAvailable):
  702. self.semaphore.acquire('a', blocking=False)
  703. def test_release_capacity(self):
  704. acquire_token = self.semaphore.acquire('a', blocking=False)
  705. self.semaphore.release('a', acquire_token)
  706. try:
  707. self.semaphore.acquire('a', blocking=False)
  708. except NoResourcesAvailable:
  709. self.fail(
  710. 'The release of the semaphore should have allowed for '
  711. 'the second acquire to not be blocked'
  712. )
  713. class TestSlidingWindowSemaphore(unittest.TestCase):
  714. # These tests use block=False to tests will fail
  715. # instead of hang the test runner in the case of x
  716. # incorrect behavior.
  717. def test_acquire_release_basic_case(self):
  718. sem = SlidingWindowSemaphore(1)
  719. # Count is 1
  720. num = sem.acquire('a', blocking=False)
  721. self.assertEqual(num, 0)
  722. sem.release('a', 0)
  723. # Count now back to 1.
  724. def test_can_acquire_release_multiple_times(self):
  725. sem = SlidingWindowSemaphore(1)
  726. num = sem.acquire('a', blocking=False)
  727. self.assertEqual(num, 0)
  728. sem.release('a', num)
  729. num = sem.acquire('a', blocking=False)
  730. self.assertEqual(num, 1)
  731. sem.release('a', num)
  732. def test_can_acquire_a_range(self):
  733. sem = SlidingWindowSemaphore(3)
  734. self.assertEqual(sem.acquire('a', blocking=False), 0)
  735. self.assertEqual(sem.acquire('a', blocking=False), 1)
  736. self.assertEqual(sem.acquire('a', blocking=False), 2)
  737. sem.release('a', 0)
  738. sem.release('a', 1)
  739. sem.release('a', 2)
  740. # Now we're reset so we should be able to acquire the same
  741. # sequence again.
  742. self.assertEqual(sem.acquire('a', blocking=False), 3)
  743. self.assertEqual(sem.acquire('a', blocking=False), 4)
  744. self.assertEqual(sem.acquire('a', blocking=False), 5)
  745. self.assertEqual(sem.current_count(), 0)
  746. def test_counter_release_only_on_min_element(self):
  747. sem = SlidingWindowSemaphore(3)
  748. sem.acquire('a', blocking=False)
  749. sem.acquire('a', blocking=False)
  750. sem.acquire('a', blocking=False)
  751. # The count only increases when we free the min
  752. # element. This means if we're currently failing to
  753. # acquire now:
  754. with self.assertRaises(NoResourcesAvailable):
  755. sem.acquire('a', blocking=False)
  756. # Then freeing a non-min element:
  757. sem.release('a', 1)
  758. # doesn't change anything. We still fail to acquire.
  759. with self.assertRaises(NoResourcesAvailable):
  760. sem.acquire('a', blocking=False)
  761. self.assertEqual(sem.current_count(), 0)
  762. def test_raises_error_when_count_is_zero(self):
  763. sem = SlidingWindowSemaphore(3)
  764. sem.acquire('a', blocking=False)
  765. sem.acquire('a', blocking=False)
  766. sem.acquire('a', blocking=False)
  767. # Count is now 0 so trying to acquire should fail.
  768. with self.assertRaises(NoResourcesAvailable):
  769. sem.acquire('a', blocking=False)
  770. def test_release_counters_can_increment_counter_repeatedly(self):
  771. sem = SlidingWindowSemaphore(3)
  772. sem.acquire('a', blocking=False)
  773. sem.acquire('a', blocking=False)
  774. sem.acquire('a', blocking=False)
  775. # These two releases don't increment the counter
  776. # because we're waiting on 0.
  777. sem.release('a', 1)
  778. sem.release('a', 2)
  779. self.assertEqual(sem.current_count(), 0)
  780. # But as soon as we release 0, we free up 0, 1, and 2.
  781. sem.release('a', 0)
  782. self.assertEqual(sem.current_count(), 3)
  783. sem.acquire('a', blocking=False)
  784. sem.acquire('a', blocking=False)
  785. sem.acquire('a', blocking=False)
  786. def test_error_to_release_unknown_tag(self):
  787. sem = SlidingWindowSemaphore(3)
  788. with self.assertRaises(ValueError):
  789. sem.release('a', 0)
  790. def test_can_track_multiple_tags(self):
  791. sem = SlidingWindowSemaphore(3)
  792. self.assertEqual(sem.acquire('a', blocking=False), 0)
  793. self.assertEqual(sem.acquire('b', blocking=False), 0)
  794. self.assertEqual(sem.acquire('a', blocking=False), 1)
  795. # We're at our max of 3 even though 2 are for A and 1 is for B.
  796. with self.assertRaises(NoResourcesAvailable):
  797. sem.acquire('a', blocking=False)
  798. with self.assertRaises(NoResourcesAvailable):
  799. sem.acquire('b', blocking=False)
  800. def test_can_handle_multiple_tags_released(self):
  801. sem = SlidingWindowSemaphore(4)
  802. sem.acquire('a', blocking=False)
  803. sem.acquire('a', blocking=False)
  804. sem.acquire('b', blocking=False)
  805. sem.acquire('b', blocking=False)
  806. sem.release('b', 1)
  807. sem.release('a', 1)
  808. self.assertEqual(sem.current_count(), 0)
  809. sem.release('b', 0)
  810. self.assertEqual(sem.acquire('a', blocking=False), 2)
  811. sem.release('a', 0)
  812. self.assertEqual(sem.acquire('b', blocking=False), 2)
  813. def test_is_error_to_release_unknown_sequence_number(self):
  814. sem = SlidingWindowSemaphore(3)
  815. sem.acquire('a', blocking=False)
  816. with self.assertRaises(ValueError):
  817. sem.release('a', 1)
  818. def test_is_error_to_double_release(self):
  819. # This is different than other error tests because
  820. # we're verifying we can reset the state after an
  821. # acquire/release cycle.
  822. sem = SlidingWindowSemaphore(2)
  823. sem.acquire('a', blocking=False)
  824. sem.acquire('a', blocking=False)
  825. sem.release('a', 0)
  826. sem.release('a', 1)
  827. self.assertEqual(sem.current_count(), 2)
  828. with self.assertRaises(ValueError):
  829. sem.release('a', 0)
  830. def test_can_check_in_partial_range(self):
  831. sem = SlidingWindowSemaphore(4)
  832. sem.acquire('a', blocking=False)
  833. sem.acquire('a', blocking=False)
  834. sem.acquire('a', blocking=False)
  835. sem.acquire('a', blocking=False)
  836. sem.release('a', 1)
  837. sem.release('a', 3)
  838. sem.release('a', 0)
  839. self.assertEqual(sem.current_count(), 2)
  840. class TestThreadingPropertiesForSlidingWindowSemaphore(unittest.TestCase):
  841. # These tests focus on mutithreaded properties of the range
  842. # semaphore. Basic functionality is tested in TestSlidingWindowSemaphore.
  843. def setUp(self):
  844. self.threads = []
  845. def tearDown(self):
  846. self.join_threads()
  847. def join_threads(self):
  848. for thread in self.threads:
  849. thread.join()
  850. self.threads = []
  851. def start_threads(self):
  852. for thread in self.threads:
  853. thread.start()
  854. def test_acquire_blocks_until_release_is_called(self):
  855. sem = SlidingWindowSemaphore(2)
  856. sem.acquire('a', blocking=False)
  857. sem.acquire('a', blocking=False)
  858. def acquire():
  859. # This next call to acquire will block.
  860. self.assertEqual(sem.acquire('a', blocking=True), 2)
  861. t = threading.Thread(target=acquire)
  862. self.threads.append(t)
  863. # Starting the thread will block the sem.acquire()
  864. # in the acquire function above.
  865. t.start()
  866. # This still will keep the thread blocked.
  867. sem.release('a', 1)
  868. # Releasing the min element will unblock the thread.
  869. sem.release('a', 0)
  870. t.join()
  871. sem.release('a', 2)
  872. def test_stress_invariants_random_order(self):
  873. sem = SlidingWindowSemaphore(100)
  874. for _ in range(10):
  875. recorded = []
  876. for _ in range(100):
  877. recorded.append(sem.acquire('a', blocking=False))
  878. # Release them in randomized order. As long as we
  879. # eventually free all 100, we should have all the
  880. # resources released.
  881. random.shuffle(recorded)
  882. for i in recorded:
  883. sem.release('a', i)
  884. # Everything's freed so should be back at count == 100
  885. self.assertEqual(sem.current_count(), 100)
  886. def test_blocking_stress(self):
  887. sem = SlidingWindowSemaphore(5)
  888. num_threads = 10
  889. num_iterations = 50
  890. def acquire():
  891. for _ in range(num_iterations):
  892. num = sem.acquire('a', blocking=True)
  893. time.sleep(0.001)
  894. sem.release('a', num)
  895. for i in range(num_threads):
  896. t = threading.Thread(target=acquire)
  897. self.threads.append(t)
  898. self.start_threads()
  899. self.join_threads()
  900. # Should have all the available resources freed.
  901. self.assertEqual(sem.current_count(), 5)
  902. # Should have acquired num_threads * num_iterations
  903. self.assertEqual(sem.acquire('a', blocking=False),
  904. num_threads * num_iterations)
  905. class TestAdjustChunksize(unittest.TestCase):
  906. def setUp(self):
  907. self.adjuster = ChunksizeAdjuster()
  908. def test_valid_chunksize(self):
  909. chunksize = 7 * (1024 ** 2)
  910. file_size = 8 * (1024 ** 2)
  911. new_size = self.adjuster.adjust_chunksize(chunksize, file_size)
  912. self.assertEqual(new_size, chunksize)
  913. def test_chunksize_below_minimum(self):
  914. chunksize = MIN_UPLOAD_CHUNKSIZE - 1
  915. file_size = 3 * MIN_UPLOAD_CHUNKSIZE
  916. new_size = self.adjuster.adjust_chunksize(chunksize, file_size)
  917. self.assertEqual(new_size, MIN_UPLOAD_CHUNKSIZE)
  918. def test_chunksize_above_maximum(self):
  919. chunksize = MAX_SINGLE_UPLOAD_SIZE + 1
  920. file_size = MAX_SINGLE_UPLOAD_SIZE * 2
  921. new_size = self.adjuster.adjust_chunksize(chunksize, file_size)
  922. self.assertEqual(new_size, MAX_SINGLE_UPLOAD_SIZE)
  923. def test_chunksize_too_small(self):
  924. chunksize = 7 * (1024 ** 2)
  925. file_size = 5 * (1024 ** 4)
  926. # If we try to upload a 5TB file, we'll need to use 896MB part
  927. # sizes.
  928. new_size = self.adjuster.adjust_chunksize(chunksize, file_size)
  929. self.assertEqual(new_size, 896 * (1024 ** 2))
  930. num_parts = file_size / new_size
  931. self.assertLessEqual(num_parts, MAX_PARTS)
  932. def test_unknown_file_size_with_valid_chunksize(self):
  933. chunksize = 7 * (1024 ** 2)
  934. new_size = self.adjuster.adjust_chunksize(chunksize)
  935. self.assertEqual(new_size, chunksize)
  936. def test_unknown_file_size_below_minimum(self):
  937. chunksize = MIN_UPLOAD_CHUNKSIZE - 1
  938. new_size = self.adjuster.adjust_chunksize(chunksize)
  939. self.assertEqual(new_size, MIN_UPLOAD_CHUNKSIZE)
  940. def test_unknown_file_size_above_maximum(self):
  941. chunksize = MAX_SINGLE_UPLOAD_SIZE + 1
  942. new_size = self.adjuster.adjust_chunksize(chunksize)
  943. self.assertEqual(new_size, MAX_SINGLE_UPLOAD_SIZE)