helpers.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482
  1. import hashlib
  2. from time import mktime, strptime
  3. from datetime import datetime, timezone, timedelta
  4. from io import StringIO
  5. import os
  6. import pytest
  7. import sys
  8. import msgpack
  9. from ..helpers import adjust_patterns, exclude_path, Location, format_file_size, format_timedelta, IncludePattern, ExcludePattern, make_path_safe, \
  10. prune_within, prune_split, get_cache_dir, Statistics, \
  11. StableDict, int_to_bigint, bigint_to_int, parse_timestamp, CompressionSpec, ChunkerParams
  12. from . import BaseTestCase
  13. class BigIntTestCase(BaseTestCase):
  14. def test_bigint(self):
  15. self.assert_equal(int_to_bigint(0), 0)
  16. self.assert_equal(int_to_bigint(2**63-1), 2**63-1)
  17. self.assert_equal(int_to_bigint(-2**63+1), -2**63+1)
  18. self.assert_equal(int_to_bigint(2**63), b'\x00\x00\x00\x00\x00\x00\x00\x80\x00')
  19. self.assert_equal(int_to_bigint(-2**63), b'\x00\x00\x00\x00\x00\x00\x00\x80\xff')
  20. self.assert_equal(bigint_to_int(int_to_bigint(-2**70)), -2**70)
  21. self.assert_equal(bigint_to_int(int_to_bigint(2**70)), 2**70)
  22. class TestLocationWithoutEnv:
  23. def test_ssh(self, monkeypatch):
  24. monkeypatch.delenv('BORG_REPO', raising=False)
  25. assert repr(Location('ssh://user@host:1234/some/path::archive')) == \
  26. "Location(proto='ssh', user='user', host='host', port=1234, path='/some/path', archive='archive')"
  27. assert repr(Location('ssh://user@host:1234/some/path')) == \
  28. "Location(proto='ssh', user='user', host='host', port=1234, path='/some/path', archive=None)"
  29. def test_file(self, monkeypatch):
  30. monkeypatch.delenv('BORG_REPO', raising=False)
  31. assert repr(Location('file:///some/path::archive')) == \
  32. "Location(proto='file', user=None, host=None, port=None, path='/some/path', archive='archive')"
  33. assert repr(Location('file:///some/path')) == \
  34. "Location(proto='file', user=None, host=None, port=None, path='/some/path', archive=None)"
  35. def test_scp(self, monkeypatch):
  36. monkeypatch.delenv('BORG_REPO', raising=False)
  37. assert repr(Location('user@host:/some/path::archive')) == \
  38. "Location(proto='ssh', user='user', host='host', port=None, path='/some/path', archive='archive')"
  39. assert repr(Location('user@host:/some/path')) == \
  40. "Location(proto='ssh', user='user', host='host', port=None, path='/some/path', archive=None)"
  41. def test_folder(self, monkeypatch):
  42. monkeypatch.delenv('BORG_REPO', raising=False)
  43. assert repr(Location('path::archive')) == \
  44. "Location(proto='file', user=None, host=None, port=None, path='path', archive='archive')"
  45. assert repr(Location('path')) == \
  46. "Location(proto='file', user=None, host=None, port=None, path='path', archive=None)"
  47. def test_abspath(self, monkeypatch):
  48. monkeypatch.delenv('BORG_REPO', raising=False)
  49. assert repr(Location('/some/absolute/path::archive')) == \
  50. "Location(proto='file', user=None, host=None, port=None, path='/some/absolute/path', archive='archive')"
  51. assert repr(Location('/some/absolute/path')) == \
  52. "Location(proto='file', user=None, host=None, port=None, path='/some/absolute/path', archive=None)"
  53. def test_relpath(self, monkeypatch):
  54. monkeypatch.delenv('BORG_REPO', raising=False)
  55. assert repr(Location('some/relative/path::archive')) == \
  56. "Location(proto='file', user=None, host=None, port=None, path='some/relative/path', archive='archive')"
  57. assert repr(Location('some/relative/path')) == \
  58. "Location(proto='file', user=None, host=None, port=None, path='some/relative/path', archive=None)"
  59. def test_underspecified(self, monkeypatch):
  60. monkeypatch.delenv('BORG_REPO', raising=False)
  61. with pytest.raises(ValueError):
  62. Location('::archive')
  63. with pytest.raises(ValueError):
  64. Location('::')
  65. with pytest.raises(ValueError):
  66. Location()
  67. def test_no_double_colon(self, monkeypatch):
  68. monkeypatch.delenv('BORG_REPO', raising=False)
  69. with pytest.raises(ValueError):
  70. Location('ssh://localhost:22/path:archive')
  71. def test_no_slashes(self, monkeypatch):
  72. monkeypatch.delenv('BORG_REPO', raising=False)
  73. with pytest.raises(ValueError):
  74. Location('/some/path/to/repo::archive_name_with/slashes/is_invalid')
  75. def test_canonical_path(self, monkeypatch):
  76. monkeypatch.delenv('BORG_REPO', raising=False)
  77. locations = ['some/path::archive', 'file://some/path::archive', 'host:some/path::archive',
  78. 'host:~user/some/path::archive', 'ssh://host/some/path::archive',
  79. 'ssh://user@host:1234/some/path::archive']
  80. for location in locations:
  81. assert Location(location).canonical_path() == \
  82. Location(Location(location).canonical_path()).canonical_path()
  83. class TestLocationWithEnv:
  84. def test_ssh(self, monkeypatch):
  85. monkeypatch.setenv('BORG_REPO', 'ssh://user@host:1234/some/path')
  86. assert repr(Location('::archive')) == \
  87. "Location(proto='ssh', user='user', host='host', port=1234, path='/some/path', archive='archive')"
  88. assert repr(Location()) == \
  89. "Location(proto='ssh', user='user', host='host', port=1234, path='/some/path', archive=None)"
  90. def test_file(self, monkeypatch):
  91. monkeypatch.setenv('BORG_REPO', 'file:///some/path')
  92. assert repr(Location('::archive')) == \
  93. "Location(proto='file', user=None, host=None, port=None, path='/some/path', archive='archive')"
  94. assert repr(Location()) == \
  95. "Location(proto='file', user=None, host=None, port=None, path='/some/path', archive=None)"
  96. def test_scp(self, monkeypatch):
  97. monkeypatch.setenv('BORG_REPO', 'user@host:/some/path')
  98. assert repr(Location('::archive')) == \
  99. "Location(proto='ssh', user='user', host='host', port=None, path='/some/path', archive='archive')"
  100. assert repr(Location()) == \
  101. "Location(proto='ssh', user='user', host='host', port=None, path='/some/path', archive=None)"
  102. def test_folder(self, monkeypatch):
  103. monkeypatch.setenv('BORG_REPO', 'path')
  104. assert repr(Location('::archive')) == \
  105. "Location(proto='file', user=None, host=None, port=None, path='path', archive='archive')"
  106. assert repr(Location()) == \
  107. "Location(proto='file', user=None, host=None, port=None, path='path', archive=None)"
  108. def test_abspath(self, monkeypatch):
  109. monkeypatch.setenv('BORG_REPO', '/some/absolute/path')
  110. assert repr(Location('::archive')) == \
  111. "Location(proto='file', user=None, host=None, port=None, path='/some/absolute/path', archive='archive')"
  112. assert repr(Location()) == \
  113. "Location(proto='file', user=None, host=None, port=None, path='/some/absolute/path', archive=None)"
  114. def test_relpath(self, monkeypatch):
  115. monkeypatch.setenv('BORG_REPO', 'some/relative/path')
  116. assert repr(Location('::archive')) == \
  117. "Location(proto='file', user=None, host=None, port=None, path='some/relative/path', archive='archive')"
  118. assert repr(Location()) == \
  119. "Location(proto='file', user=None, host=None, port=None, path='some/relative/path', archive=None)"
  120. def test_no_slashes(self, monkeypatch):
  121. monkeypatch.setenv('BORG_REPO', '/some/absolute/path')
  122. with pytest.raises(ValueError):
  123. Location('::archive_name_with/slashes/is_invalid')
  124. class FormatTimedeltaTestCase(BaseTestCase):
  125. def test(self):
  126. t0 = datetime(2001, 1, 1, 10, 20, 3, 0)
  127. t1 = datetime(2001, 1, 1, 12, 20, 4, 100000)
  128. self.assert_equal(
  129. format_timedelta(t1 - t0),
  130. '2 hours 1.10 seconds'
  131. )
  132. class PatternTestCase(BaseTestCase):
  133. files = [
  134. '/etc/passwd', '/etc/hosts', '/home',
  135. '/home/user/.profile', '/home/user/.bashrc',
  136. '/home/user2/.profile', '/home/user2/public_html/index.html',
  137. '/var/log/messages', '/var/log/dmesg',
  138. ]
  139. def evaluate(self, paths, excludes):
  140. patterns = adjust_patterns(paths, [ExcludePattern(p) for p in excludes])
  141. return [path for path in self.files if not exclude_path(path, patterns)]
  142. def test(self):
  143. self.assert_equal(self.evaluate(['/'], []), self.files)
  144. self.assert_equal(self.evaluate([], []), self.files)
  145. self.assert_equal(self.evaluate(['/'], ['/h']), self.files)
  146. self.assert_equal(self.evaluate(['/'], ['/home']),
  147. ['/etc/passwd', '/etc/hosts', '/var/log/messages', '/var/log/dmesg'])
  148. self.assert_equal(self.evaluate(['/'], ['/home/']),
  149. ['/etc/passwd', '/etc/hosts', '/home', '/var/log/messages', '/var/log/dmesg'])
  150. self.assert_equal(self.evaluate(['/home/u'], []), [])
  151. self.assert_equal(self.evaluate(['/', '/home', '/etc/hosts'], ['/']), [])
  152. self.assert_equal(self.evaluate(['/home/'], ['/home/user2']),
  153. ['/home', '/home/user/.profile', '/home/user/.bashrc'])
  154. self.assert_equal(self.evaluate(['/'], ['*.profile', '/var/log']),
  155. ['/etc/passwd', '/etc/hosts', '/home', '/home/user/.bashrc', '/home/user2/public_html/index.html'])
  156. self.assert_equal(self.evaluate(['/'], ['/home/*/public_html', '*.profile', '*/log/*']),
  157. ['/etc/passwd', '/etc/hosts', '/home', '/home/user/.bashrc'])
  158. self.assert_equal(self.evaluate(['/etc/', '/var'], ['dmesg']),
  159. ['/etc/passwd', '/etc/hosts', '/var/log/messages', '/var/log/dmesg'])
  160. @pytest.mark.skipif(sys.platform in ('darwin',), reason='all but OS X test')
  161. class PatternNonAsciiTestCase(BaseTestCase):
  162. def testComposedUnicode(self):
  163. pattern = 'b\N{LATIN SMALL LETTER A WITH ACUTE}'
  164. i = IncludePattern(pattern)
  165. e = ExcludePattern(pattern)
  166. assert i.match("b\N{LATIN SMALL LETTER A WITH ACUTE}/foo")
  167. assert not i.match("ba\N{COMBINING ACUTE ACCENT}/foo")
  168. assert e.match("b\N{LATIN SMALL LETTER A WITH ACUTE}/foo")
  169. assert not e.match("ba\N{COMBINING ACUTE ACCENT}/foo")
  170. def testDecomposedUnicode(self):
  171. pattern = 'ba\N{COMBINING ACUTE ACCENT}'
  172. i = IncludePattern(pattern)
  173. e = ExcludePattern(pattern)
  174. assert not i.match("b\N{LATIN SMALL LETTER A WITH ACUTE}/foo")
  175. assert i.match("ba\N{COMBINING ACUTE ACCENT}/foo")
  176. assert not e.match("b\N{LATIN SMALL LETTER A WITH ACUTE}/foo")
  177. assert e.match("ba\N{COMBINING ACUTE ACCENT}/foo")
  178. def testInvalidUnicode(self):
  179. pattern = str(b'ba\x80', 'latin1')
  180. i = IncludePattern(pattern)
  181. e = ExcludePattern(pattern)
  182. assert not i.match("ba/foo")
  183. assert i.match(str(b"ba\x80/foo", 'latin1'))
  184. assert not e.match("ba/foo")
  185. assert e.match(str(b"ba\x80/foo", 'latin1'))
  186. @pytest.mark.skipif(sys.platform not in ('darwin',), reason='OS X test')
  187. class OSXPatternNormalizationTestCase(BaseTestCase):
  188. def testComposedUnicode(self):
  189. pattern = 'b\N{LATIN SMALL LETTER A WITH ACUTE}'
  190. i = IncludePattern(pattern)
  191. e = ExcludePattern(pattern)
  192. assert i.match("b\N{LATIN SMALL LETTER A WITH ACUTE}/foo")
  193. assert i.match("ba\N{COMBINING ACUTE ACCENT}/foo")
  194. assert e.match("b\N{LATIN SMALL LETTER A WITH ACUTE}/foo")
  195. assert e.match("ba\N{COMBINING ACUTE ACCENT}/foo")
  196. def testDecomposedUnicode(self):
  197. pattern = 'ba\N{COMBINING ACUTE ACCENT}'
  198. i = IncludePattern(pattern)
  199. e = ExcludePattern(pattern)
  200. assert i.match("b\N{LATIN SMALL LETTER A WITH ACUTE}/foo")
  201. assert i.match("ba\N{COMBINING ACUTE ACCENT}/foo")
  202. assert e.match("b\N{LATIN SMALL LETTER A WITH ACUTE}/foo")
  203. assert e.match("ba\N{COMBINING ACUTE ACCENT}/foo")
  204. def testInvalidUnicode(self):
  205. pattern = str(b'ba\x80', 'latin1')
  206. i = IncludePattern(pattern)
  207. e = ExcludePattern(pattern)
  208. assert not i.match("ba/foo")
  209. assert i.match(str(b"ba\x80/foo", 'latin1'))
  210. assert not e.match("ba/foo")
  211. assert e.match(str(b"ba\x80/foo", 'latin1'))
  212. def test_compression_specs():
  213. with pytest.raises(ValueError):
  214. CompressionSpec('')
  215. assert CompressionSpec('0') == dict(name='zlib', level=0)
  216. assert CompressionSpec('1') == dict(name='zlib', level=1)
  217. assert CompressionSpec('9') == dict(name='zlib', level=9)
  218. with pytest.raises(ValueError):
  219. CompressionSpec('10')
  220. assert CompressionSpec('none') == dict(name='none')
  221. assert CompressionSpec('lz4') == dict(name='lz4')
  222. assert CompressionSpec('zlib') == dict(name='zlib', level=6)
  223. assert CompressionSpec('zlib,0') == dict(name='zlib', level=0)
  224. assert CompressionSpec('zlib,9') == dict(name='zlib', level=9)
  225. with pytest.raises(ValueError):
  226. CompressionSpec('zlib,9,invalid')
  227. assert CompressionSpec('lzma') == dict(name='lzma', level=6)
  228. assert CompressionSpec('lzma,0') == dict(name='lzma', level=0)
  229. assert CompressionSpec('lzma,9') == dict(name='lzma', level=9)
  230. with pytest.raises(ValueError):
  231. CompressionSpec('lzma,9,invalid')
  232. with pytest.raises(ValueError):
  233. CompressionSpec('invalid')
  234. def test_chunkerparams():
  235. assert ChunkerParams('19,23,21,4095') == (19, 23, 21, 4095)
  236. assert ChunkerParams('10,23,16,4095') == (10, 23, 16, 4095)
  237. with pytest.raises(ValueError):
  238. ChunkerParams('19,24,21,4095')
  239. class MakePathSafeTestCase(BaseTestCase):
  240. def test(self):
  241. self.assert_equal(make_path_safe('/foo/bar'), 'foo/bar')
  242. self.assert_equal(make_path_safe('/foo/bar'), 'foo/bar')
  243. self.assert_equal(make_path_safe('/f/bar'), 'f/bar')
  244. self.assert_equal(make_path_safe('fo/bar'), 'fo/bar')
  245. self.assert_equal(make_path_safe('../foo/bar'), 'foo/bar')
  246. self.assert_equal(make_path_safe('../../foo/bar'), 'foo/bar')
  247. self.assert_equal(make_path_safe('/'), '.')
  248. self.assert_equal(make_path_safe('/'), '.')
  249. class MockArchive:
  250. def __init__(self, ts):
  251. self.ts = ts
  252. def __repr__(self):
  253. return repr(self.ts)
  254. class PruneSplitTestCase(BaseTestCase):
  255. def test(self):
  256. def local_to_UTC(month, day):
  257. """Convert noon on the month and day in 2013 to UTC."""
  258. seconds = mktime(strptime('2013-%02d-%02d 12:00' % (month, day), '%Y-%m-%d %H:%M'))
  259. return datetime.fromtimestamp(seconds, tz=timezone.utc)
  260. def subset(lst, indices):
  261. return {lst[i] for i in indices}
  262. def dotest(test_archives, n, skip, indices):
  263. for ta in test_archives, reversed(test_archives):
  264. self.assert_equal(set(prune_split(ta, '%Y-%m', n, skip)),
  265. subset(test_archives, indices))
  266. test_pairs = [(1, 1), (2, 1), (2, 28), (3, 1), (3, 2), (3, 31), (5, 1)]
  267. test_dates = [local_to_UTC(month, day) for month, day in test_pairs]
  268. test_archives = [MockArchive(date) for date in test_dates]
  269. dotest(test_archives, 3, [], [6, 5, 2])
  270. dotest(test_archives, -1, [], [6, 5, 2, 0])
  271. dotest(test_archives, 3, [test_archives[6]], [5, 2, 0])
  272. dotest(test_archives, 3, [test_archives[5]], [6, 2, 0])
  273. dotest(test_archives, 3, [test_archives[4]], [6, 5, 2])
  274. dotest(test_archives, 0, [], [])
  275. class PruneWithinTestCase(BaseTestCase):
  276. def test(self):
  277. def subset(lst, indices):
  278. return {lst[i] for i in indices}
  279. def dotest(test_archives, within, indices):
  280. for ta in test_archives, reversed(test_archives):
  281. self.assert_equal(set(prune_within(ta, within)),
  282. subset(test_archives, indices))
  283. # 1 minute, 1.5 hours, 2.5 hours, 3.5 hours, 25 hours, 49 hours
  284. test_offsets = [60, 90*60, 150*60, 210*60, 25*60*60, 49*60*60]
  285. now = datetime.now(timezone.utc)
  286. test_dates = [now - timedelta(seconds=s) for s in test_offsets]
  287. test_archives = [MockArchive(date) for date in test_dates]
  288. dotest(test_archives, '1H', [0])
  289. dotest(test_archives, '2H', [0, 1])
  290. dotest(test_archives, '3H', [0, 1, 2])
  291. dotest(test_archives, '24H', [0, 1, 2, 3])
  292. dotest(test_archives, '26H', [0, 1, 2, 3, 4])
  293. dotest(test_archives, '2d', [0, 1, 2, 3, 4])
  294. dotest(test_archives, '50H', [0, 1, 2, 3, 4, 5])
  295. dotest(test_archives, '3d', [0, 1, 2, 3, 4, 5])
  296. dotest(test_archives, '1w', [0, 1, 2, 3, 4, 5])
  297. dotest(test_archives, '1m', [0, 1, 2, 3, 4, 5])
  298. dotest(test_archives, '1y', [0, 1, 2, 3, 4, 5])
  299. class StableDictTestCase(BaseTestCase):
  300. def test(self):
  301. d = StableDict(foo=1, bar=2, boo=3, baz=4)
  302. self.assert_equal(list(d.items()), [('bar', 2), ('baz', 4), ('boo', 3), ('foo', 1)])
  303. self.assert_equal(hashlib.md5(msgpack.packb(d)).hexdigest(), 'fc78df42cd60691b3ac3dd2a2b39903f')
  304. class TestParseTimestamp(BaseTestCase):
  305. def test(self):
  306. self.assert_equal(parse_timestamp('2015-04-19T20:25:00.226410'), datetime(2015, 4, 19, 20, 25, 0, 226410, timezone.utc))
  307. self.assert_equal(parse_timestamp('2015-04-19T20:25:00'), datetime(2015, 4, 19, 20, 25, 0, 0, timezone.utc))
  308. def test_get_cache_dir():
  309. """test that get_cache_dir respects environement"""
  310. # reset BORG_CACHE_DIR in order to test default
  311. old_env = None
  312. if os.environ.get('BORG_CACHE_DIR'):
  313. old_env = os.environ['BORG_CACHE_DIR']
  314. del(os.environ['BORG_CACHE_DIR'])
  315. assert get_cache_dir() == os.path.join(os.path.expanduser('~'), '.cache', 'borg')
  316. os.environ['XDG_CACHE_HOME'] = '/var/tmp/.cache'
  317. assert get_cache_dir() == os.path.join('/var/tmp/.cache', 'borg')
  318. os.environ['BORG_CACHE_DIR'] = '/var/tmp'
  319. assert get_cache_dir() == '/var/tmp'
  320. # reset old env
  321. if old_env is not None:
  322. os.environ['BORG_CACHE_DIR'] = old_env
  323. @pytest.fixture()
  324. def stats():
  325. stats = Statistics()
  326. stats.update(20, 10, unique=True)
  327. return stats
  328. def test_stats_basic(stats):
  329. assert stats.osize == 20
  330. assert stats.csize == stats.usize == 10
  331. stats.update(20, 10, unique=False)
  332. assert stats.osize == 40
  333. assert stats.csize == 20
  334. assert stats.usize == 10
  335. def tests_stats_progress(stats, columns=80):
  336. os.environ['COLUMNS'] = str(columns)
  337. out = StringIO()
  338. stats.show_progress(stream=out)
  339. s = '20 B O 10 B C 10 B D 0 N '
  340. buf = ' ' * (columns - len(s))
  341. assert out.getvalue() == s + buf + "\r"
  342. out = StringIO()
  343. stats.update(10**3, 0, unique=False)
  344. stats.show_progress(item={b'path': 'foo'}, final=False, stream=out)
  345. s = '1.02 kB O 10 B C 10 B D 0 N foo'
  346. buf = ' ' * (columns - len(s))
  347. assert out.getvalue() == s + buf + "\r"
  348. out = StringIO()
  349. stats.show_progress(item={b'path': 'foo'*40}, final=False, stream=out)
  350. s = '1.02 kB O 10 B C 10 B D 0 N foofoofoofoofoofoofoofo...oofoofoofoofoofoofoofoofoo'
  351. buf = ' ' * (columns - len(s))
  352. assert out.getvalue() == s + buf + "\r"
  353. def test_stats_format(stats):
  354. assert str(stats) == """\
  355. Original size Compressed size Deduplicated size
  356. This archive: 20 B 10 B 10 B"""
  357. s = "{0.osize_fmt}".format(stats)
  358. assert s == "20 B"
  359. # kind of redundant, but id is variable so we can't match reliably
  360. assert repr(stats) == '<Statistics object at {:#x} (20, 10, 10)>'.format(id(stats))
  361. def test_file_size():
  362. """test the size formatting routines"""
  363. si_size_map = {
  364. 0: '0 B', # no rounding necessary for those
  365. 1: '1 B',
  366. 142: '142 B',
  367. 999: '999 B',
  368. 1000: '1.00 kB', # rounding starts here
  369. 1001: '1.00 kB', # should be rounded away
  370. 1234: '1.23 kB', # should be rounded down
  371. 1235: '1.24 kB', # should be rounded up
  372. 1010: '1.01 kB', # rounded down as well
  373. 999990000: '999.99 MB', # rounded down
  374. 999990001: '999.99 MB', # rounded down
  375. 999995000: '1.00 GB', # rounded up to next unit
  376. 10**6: '1.00 MB', # and all the remaining units, megabytes
  377. 10**9: '1.00 GB', # gigabytes
  378. 10**12: '1.00 TB', # terabytes
  379. 10**15: '1.00 PB', # petabytes
  380. 10**18: '1.00 EB', # exabytes
  381. 10**21: '1.00 ZB', # zottabytes
  382. 10**24: '1.00 YB', # yottabytes
  383. }
  384. for size, fmt in si_size_map.items():
  385. assert format_file_size(size) == fmt
  386. def test_file_size_precision():
  387. assert format_file_size(1234, precision=1) == '1.2 kB' # rounded down
  388. assert format_file_size(1254, precision=1) == '1.3 kB' # rounded up
  389. assert format_file_size(999990000, precision=1) == '1.0 GB' # and not 999.9 MB or 1000.0 MB