helpers.py 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781
  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. import msgpack.fallback
  10. from ..helpers import exclude_path, Location, format_file_size, format_timedelta, PathPrefixPattern, FnmatchPattern, make_path_safe, \
  11. prune_within, prune_split, get_cache_dir, Statistics, is_slow_msgpack, yes, RegexPattern, \
  12. StableDict, int_to_bigint, bigint_to_int, parse_timestamp, CompressionSpec, ChunkerParams, \
  13. ProgressIndicatorPercent, ProgressIndicatorEndless, load_excludes, parse_pattern, PatternMatcher
  14. from . import BaseTestCase, environment_variable, FakeInputs
  15. class BigIntTestCase(BaseTestCase):
  16. def test_bigint(self):
  17. self.assert_equal(int_to_bigint(0), 0)
  18. self.assert_equal(int_to_bigint(2**63-1), 2**63-1)
  19. self.assert_equal(int_to_bigint(-2**63+1), -2**63+1)
  20. self.assert_equal(int_to_bigint(2**63), b'\x00\x00\x00\x00\x00\x00\x00\x80\x00')
  21. self.assert_equal(int_to_bigint(-2**63), b'\x00\x00\x00\x00\x00\x00\x00\x80\xff')
  22. self.assert_equal(bigint_to_int(int_to_bigint(-2**70)), -2**70)
  23. self.assert_equal(bigint_to_int(int_to_bigint(2**70)), 2**70)
  24. class TestLocationWithoutEnv:
  25. def test_ssh(self, monkeypatch):
  26. monkeypatch.delenv('BORG_REPO', raising=False)
  27. assert repr(Location('ssh://user@host:1234/some/path::archive')) == \
  28. "Location(proto='ssh', user='user', host='host', port=1234, path='/some/path', archive='archive')"
  29. assert repr(Location('ssh://user@host:1234/some/path')) == \
  30. "Location(proto='ssh', user='user', host='host', port=1234, path='/some/path', archive=None)"
  31. def test_file(self, monkeypatch):
  32. monkeypatch.delenv('BORG_REPO', raising=False)
  33. assert repr(Location('file:///some/path::archive')) == \
  34. "Location(proto='file', user=None, host=None, port=None, path='/some/path', archive='archive')"
  35. assert repr(Location('file:///some/path')) == \
  36. "Location(proto='file', user=None, host=None, port=None, path='/some/path', archive=None)"
  37. def test_scp(self, monkeypatch):
  38. monkeypatch.delenv('BORG_REPO', raising=False)
  39. assert repr(Location('user@host:/some/path::archive')) == \
  40. "Location(proto='ssh', user='user', host='host', port=None, path='/some/path', archive='archive')"
  41. assert repr(Location('user@host:/some/path')) == \
  42. "Location(proto='ssh', user='user', host='host', port=None, path='/some/path', archive=None)"
  43. def test_folder(self, monkeypatch):
  44. monkeypatch.delenv('BORG_REPO', raising=False)
  45. assert repr(Location('path::archive')) == \
  46. "Location(proto='file', user=None, host=None, port=None, path='path', archive='archive')"
  47. assert repr(Location('path')) == \
  48. "Location(proto='file', user=None, host=None, port=None, path='path', archive=None)"
  49. def test_abspath(self, monkeypatch):
  50. monkeypatch.delenv('BORG_REPO', raising=False)
  51. assert repr(Location('/some/absolute/path::archive')) == \
  52. "Location(proto='file', user=None, host=None, port=None, path='/some/absolute/path', archive='archive')"
  53. assert repr(Location('/some/absolute/path')) == \
  54. "Location(proto='file', user=None, host=None, port=None, path='/some/absolute/path', archive=None)"
  55. def test_relpath(self, monkeypatch):
  56. monkeypatch.delenv('BORG_REPO', raising=False)
  57. assert repr(Location('some/relative/path::archive')) == \
  58. "Location(proto='file', user=None, host=None, port=None, path='some/relative/path', archive='archive')"
  59. assert repr(Location('some/relative/path')) == \
  60. "Location(proto='file', user=None, host=None, port=None, path='some/relative/path', archive=None)"
  61. def test_underspecified(self, monkeypatch):
  62. monkeypatch.delenv('BORG_REPO', raising=False)
  63. with pytest.raises(ValueError):
  64. Location('::archive')
  65. with pytest.raises(ValueError):
  66. Location('::')
  67. with pytest.raises(ValueError):
  68. Location()
  69. def test_no_double_colon(self, monkeypatch):
  70. monkeypatch.delenv('BORG_REPO', raising=False)
  71. with pytest.raises(ValueError):
  72. Location('ssh://localhost:22/path:archive')
  73. def test_no_slashes(self, monkeypatch):
  74. monkeypatch.delenv('BORG_REPO', raising=False)
  75. with pytest.raises(ValueError):
  76. Location('/some/path/to/repo::archive_name_with/slashes/is_invalid')
  77. def test_canonical_path(self, monkeypatch):
  78. monkeypatch.delenv('BORG_REPO', raising=False)
  79. locations = ['some/path::archive', 'file://some/path::archive', 'host:some/path::archive',
  80. 'host:~user/some/path::archive', 'ssh://host/some/path::archive',
  81. 'ssh://user@host:1234/some/path::archive']
  82. for location in locations:
  83. assert Location(location).canonical_path() == \
  84. Location(Location(location).canonical_path()).canonical_path()
  85. class TestLocationWithEnv:
  86. def test_ssh(self, monkeypatch):
  87. monkeypatch.setenv('BORG_REPO', 'ssh://user@host:1234/some/path')
  88. assert repr(Location('::archive')) == \
  89. "Location(proto='ssh', user='user', host='host', port=1234, path='/some/path', archive='archive')"
  90. assert repr(Location()) == \
  91. "Location(proto='ssh', user='user', host='host', port=1234, path='/some/path', archive=None)"
  92. def test_file(self, monkeypatch):
  93. monkeypatch.setenv('BORG_REPO', 'file:///some/path')
  94. assert repr(Location('::archive')) == \
  95. "Location(proto='file', user=None, host=None, port=None, path='/some/path', archive='archive')"
  96. assert repr(Location()) == \
  97. "Location(proto='file', user=None, host=None, port=None, path='/some/path', archive=None)"
  98. def test_scp(self, monkeypatch):
  99. monkeypatch.setenv('BORG_REPO', 'user@host:/some/path')
  100. assert repr(Location('::archive')) == \
  101. "Location(proto='ssh', user='user', host='host', port=None, path='/some/path', archive='archive')"
  102. assert repr(Location()) == \
  103. "Location(proto='ssh', user='user', host='host', port=None, path='/some/path', archive=None)"
  104. def test_folder(self, monkeypatch):
  105. monkeypatch.setenv('BORG_REPO', 'path')
  106. assert repr(Location('::archive')) == \
  107. "Location(proto='file', user=None, host=None, port=None, path='path', archive='archive')"
  108. assert repr(Location()) == \
  109. "Location(proto='file', user=None, host=None, port=None, path='path', archive=None)"
  110. def test_abspath(self, monkeypatch):
  111. monkeypatch.setenv('BORG_REPO', '/some/absolute/path')
  112. assert repr(Location('::archive')) == \
  113. "Location(proto='file', user=None, host=None, port=None, path='/some/absolute/path', archive='archive')"
  114. assert repr(Location()) == \
  115. "Location(proto='file', user=None, host=None, port=None, path='/some/absolute/path', archive=None)"
  116. def test_relpath(self, monkeypatch):
  117. monkeypatch.setenv('BORG_REPO', 'some/relative/path')
  118. assert repr(Location('::archive')) == \
  119. "Location(proto='file', user=None, host=None, port=None, path='some/relative/path', archive='archive')"
  120. assert repr(Location()) == \
  121. "Location(proto='file', user=None, host=None, port=None, path='some/relative/path', archive=None)"
  122. def test_no_slashes(self, monkeypatch):
  123. monkeypatch.setenv('BORG_REPO', '/some/absolute/path')
  124. with pytest.raises(ValueError):
  125. Location('::archive_name_with/slashes/is_invalid')
  126. class FormatTimedeltaTestCase(BaseTestCase):
  127. def test(self):
  128. t0 = datetime(2001, 1, 1, 10, 20, 3, 0)
  129. t1 = datetime(2001, 1, 1, 12, 20, 4, 100000)
  130. self.assert_equal(
  131. format_timedelta(t1 - t0),
  132. '2 hours 1.10 seconds'
  133. )
  134. def check_patterns(files, pattern, expected):
  135. """Utility for testing patterns.
  136. """
  137. assert all([f == os.path.normpath(f) for f in files]), \
  138. "Pattern matchers expect normalized input paths"
  139. matched = [f for f in files if pattern.match(f)]
  140. assert matched == (files if expected is None else expected)
  141. @pytest.mark.parametrize("pattern, expected", [
  142. # "None" means all files, i.e. all match the given pattern
  143. ("/", None),
  144. ("/./", None),
  145. ("", []),
  146. ("/home/u", []),
  147. ("/home/user", ["/home/user/.profile", "/home/user/.bashrc"]),
  148. ("/etc", ["/etc/server/config", "/etc/server/hosts"]),
  149. ("///etc//////", ["/etc/server/config", "/etc/server/hosts"]),
  150. ("/./home//..//home/user2", ["/home/user2/.profile", "/home/user2/public_html/index.html"]),
  151. ("/srv", ["/srv/messages", "/srv/dmesg"]),
  152. ])
  153. def test_patterns_prefix(pattern, expected):
  154. files = [
  155. "/etc/server/config", "/etc/server/hosts", "/home", "/home/user/.profile", "/home/user/.bashrc",
  156. "/home/user2/.profile", "/home/user2/public_html/index.html", "/srv/messages", "/srv/dmesg",
  157. ]
  158. check_patterns(files, PathPrefixPattern(pattern), expected)
  159. @pytest.mark.parametrize("pattern, expected", [
  160. # "None" means all files, i.e. all match the given pattern
  161. ("", []),
  162. ("foo", []),
  163. ("relative", ["relative/path1", "relative/two"]),
  164. ("more", ["more/relative"]),
  165. ])
  166. def test_patterns_prefix_relative(pattern, expected):
  167. files = ["relative/path1", "relative/two", "more/relative"]
  168. check_patterns(files, PathPrefixPattern(pattern), expected)
  169. @pytest.mark.parametrize("pattern, expected", [
  170. # "None" means all files, i.e. all match the given pattern
  171. ("/*", None),
  172. ("/./*", None),
  173. ("*", None),
  174. ("*/*", None),
  175. ("*///*", None),
  176. ("/home/u", []),
  177. ("/home/*",
  178. ["/home/user/.profile", "/home/user/.bashrc", "/home/user2/.profile", "/home/user2/public_html/index.html",
  179. "/home/foo/.thumbnails", "/home/foo/bar/.thumbnails"]),
  180. ("/home/user/*", ["/home/user/.profile", "/home/user/.bashrc"]),
  181. ("/etc/*", ["/etc/server/config", "/etc/server/hosts"]),
  182. ("*/.pr????e", ["/home/user/.profile", "/home/user2/.profile"]),
  183. ("///etc//////*", ["/etc/server/config", "/etc/server/hosts"]),
  184. ("/./home//..//home/user2/*", ["/home/user2/.profile", "/home/user2/public_html/index.html"]),
  185. ("/srv*", ["/srv/messages", "/srv/dmesg"]),
  186. ("/home/*/.thumbnails", ["/home/foo/.thumbnails", "/home/foo/bar/.thumbnails"]),
  187. ])
  188. def test_patterns_fnmatch(pattern, expected):
  189. files = [
  190. "/etc/server/config", "/etc/server/hosts", "/home", "/home/user/.profile", "/home/user/.bashrc",
  191. "/home/user2/.profile", "/home/user2/public_html/index.html", "/srv/messages", "/srv/dmesg",
  192. "/home/foo/.thumbnails", "/home/foo/bar/.thumbnails",
  193. ]
  194. check_patterns(files, FnmatchPattern(pattern), expected)
  195. @pytest.mark.parametrize("pattern, expected", [
  196. # "None" means all files, i.e. all match the given pattern
  197. ("", None),
  198. (".*", None),
  199. ("^/", None),
  200. ("^abc$", []),
  201. ("^[^/]", []),
  202. ("^(?!/srv|/foo|/opt)",
  203. ["/home", "/home/user/.profile", "/home/user/.bashrc", "/home/user2/.profile",
  204. "/home/user2/public_html/index.html", "/home/foo/.thumbnails", "/home/foo/bar/.thumbnails",]),
  205. ])
  206. def test_patterns_regex(pattern, expected):
  207. files = [
  208. '/srv/data', '/foo/bar', '/home',
  209. '/home/user/.profile', '/home/user/.bashrc',
  210. '/home/user2/.profile', '/home/user2/public_html/index.html',
  211. '/opt/log/messages.txt', '/opt/log/dmesg.txt',
  212. "/home/foo/.thumbnails", "/home/foo/bar/.thumbnails",
  213. ]
  214. obj = RegexPattern(pattern)
  215. assert str(obj) == pattern
  216. assert obj.pattern == pattern
  217. check_patterns(files, obj, expected)
  218. def test_regex_pattern():
  219. # The forward slash must match the platform-specific path separator
  220. assert RegexPattern("^/$").match("/")
  221. assert RegexPattern("^/$").match(os.path.sep)
  222. assert not RegexPattern(r"^\\$").match("/")
  223. def use_normalized_unicode():
  224. return sys.platform in ("darwin",)
  225. def _make_test_patterns(pattern):
  226. return [PathPrefixPattern(pattern),
  227. FnmatchPattern(pattern),
  228. RegexPattern("^{}/foo$".format(pattern)),
  229. ]
  230. @pytest.mark.parametrize("pattern", _make_test_patterns("b\N{LATIN SMALL LETTER A WITH ACUTE}"))
  231. def test_composed_unicode_pattern(pattern):
  232. assert pattern.match("b\N{LATIN SMALL LETTER A WITH ACUTE}/foo")
  233. assert pattern.match("ba\N{COMBINING ACUTE ACCENT}/foo") == use_normalized_unicode()
  234. @pytest.mark.parametrize("pattern", _make_test_patterns("ba\N{COMBINING ACUTE ACCENT}"))
  235. def test_decomposed_unicode_pattern(pattern):
  236. assert pattern.match("b\N{LATIN SMALL LETTER A WITH ACUTE}/foo") == use_normalized_unicode()
  237. assert pattern.match("ba\N{COMBINING ACUTE ACCENT}/foo")
  238. @pytest.mark.parametrize("pattern", _make_test_patterns(str(b"ba\x80", "latin1")))
  239. def test_invalid_unicode_pattern(pattern):
  240. assert not pattern.match("ba/foo")
  241. assert pattern.match(str(b"ba\x80/foo", "latin1"))
  242. @pytest.mark.parametrize("lines, expected", [
  243. # "None" means all files, i.e. none excluded
  244. ([], None),
  245. (["# Comment only"], None),
  246. (["*"], []),
  247. (["# Comment",
  248. "*/something00.txt",
  249. " *whitespace* ",
  250. # Whitespace before comment
  251. " #/ws*",
  252. # Empty line
  253. "",
  254. "# EOF"],
  255. ["/more/data", "/home", " #/wsfoobar"]),
  256. (["re:.*"], []),
  257. (["re:\s"], ["/data/something00.txt", "/more/data", "/home"]),
  258. ([r"re:(.)(\1)"], ["/more/data", "/home", "\tstart/whitespace", "/whitespace/end\t"]),
  259. (["", "", "",
  260. "# This is a test with mixed pattern styles",
  261. # Case-insensitive pattern
  262. "re:(?i)BAR|ME$",
  263. "",
  264. "*whitespace*",
  265. "fm:*/something00*"],
  266. ["/more/data"]),
  267. ([r" re:^\s "], ["/data/something00.txt", "/more/data", "/home", "/whitespace/end\t"]),
  268. ([r" re:\s$ "], ["/data/something00.txt", "/more/data", "/home", " #/wsfoobar", "\tstart/whitespace"]),
  269. ])
  270. def test_patterns_from_file(tmpdir, lines, expected):
  271. files = [
  272. '/data/something00.txt', '/more/data', '/home',
  273. ' #/wsfoobar',
  274. '\tstart/whitespace',
  275. '/whitespace/end\t',
  276. ]
  277. def evaluate(filename):
  278. patterns = load_excludes(open(filename, "rt"))
  279. return [path for path in files if not exclude_path(path, patterns)]
  280. exclfile = tmpdir.join("exclude.txt")
  281. with exclfile.open("wt") as fh:
  282. fh.write("\n".join(lines))
  283. assert evaluate(str(exclfile)) == (files if expected is None else expected)
  284. @pytest.mark.parametrize("pattern, cls", [
  285. ("", FnmatchPattern),
  286. # Default style
  287. ("*", FnmatchPattern),
  288. ("/data/*", FnmatchPattern),
  289. # fnmatch style
  290. ("fm:", FnmatchPattern),
  291. ("fm:*", FnmatchPattern),
  292. ("fm:/data/*", FnmatchPattern),
  293. ("fm:fm:/data/*", FnmatchPattern),
  294. # Regular expression
  295. ("re:", RegexPattern),
  296. ("re:.*", RegexPattern),
  297. ("re:^/something/", RegexPattern),
  298. ("re:re:^/something/", RegexPattern),
  299. ])
  300. def test_parse_pattern(pattern, cls):
  301. assert isinstance(parse_pattern(pattern), cls)
  302. @pytest.mark.parametrize("pattern", ["aa:", "fo:*", "00:", "x1:abc"])
  303. def test_parse_pattern_error(pattern):
  304. with pytest.raises(ValueError):
  305. parse_pattern(pattern)
  306. def test_pattern_matcher():
  307. pm = PatternMatcher()
  308. assert pm.fallback is None
  309. for i in ["", "foo", "bar"]:
  310. assert pm.match(i) is None
  311. pm.add([RegexPattern("^a")], "A")
  312. pm.add([RegexPattern("^b"), RegexPattern("^z")], "B")
  313. pm.add([RegexPattern("^$")], "Empty")
  314. pm.fallback = "FileNotFound"
  315. assert pm.match("") == "Empty"
  316. assert pm.match("aaa") == "A"
  317. assert pm.match("bbb") == "B"
  318. assert pm.match("ccc") == "FileNotFound"
  319. assert pm.match("xyz") == "FileNotFound"
  320. assert pm.match("z") == "B"
  321. assert PatternMatcher(fallback="hey!").fallback == "hey!"
  322. def test_compression_specs():
  323. with pytest.raises(ValueError):
  324. CompressionSpec('')
  325. assert CompressionSpec('0') == dict(name='zlib', level=0)
  326. assert CompressionSpec('1') == dict(name='zlib', level=1)
  327. assert CompressionSpec('9') == dict(name='zlib', level=9)
  328. with pytest.raises(ValueError):
  329. CompressionSpec('10')
  330. assert CompressionSpec('none') == dict(name='none')
  331. assert CompressionSpec('lz4') == dict(name='lz4')
  332. assert CompressionSpec('zlib') == dict(name='zlib', level=6)
  333. assert CompressionSpec('zlib,0') == dict(name='zlib', level=0)
  334. assert CompressionSpec('zlib,9') == dict(name='zlib', level=9)
  335. with pytest.raises(ValueError):
  336. CompressionSpec('zlib,9,invalid')
  337. assert CompressionSpec('lzma') == dict(name='lzma', level=6)
  338. assert CompressionSpec('lzma,0') == dict(name='lzma', level=0)
  339. assert CompressionSpec('lzma,9') == dict(name='lzma', level=9)
  340. with pytest.raises(ValueError):
  341. CompressionSpec('lzma,9,invalid')
  342. with pytest.raises(ValueError):
  343. CompressionSpec('invalid')
  344. def test_chunkerparams():
  345. assert ChunkerParams('19,23,21,4095') == (19, 23, 21, 4095)
  346. assert ChunkerParams('10,23,16,4095') == (10, 23, 16, 4095)
  347. with pytest.raises(ValueError):
  348. ChunkerParams('19,24,21,4095')
  349. class MakePathSafeTestCase(BaseTestCase):
  350. def test(self):
  351. self.assert_equal(make_path_safe('/foo/bar'), 'foo/bar')
  352. self.assert_equal(make_path_safe('/foo/bar'), 'foo/bar')
  353. self.assert_equal(make_path_safe('/f/bar'), 'f/bar')
  354. self.assert_equal(make_path_safe('fo/bar'), 'fo/bar')
  355. self.assert_equal(make_path_safe('../foo/bar'), 'foo/bar')
  356. self.assert_equal(make_path_safe('../../foo/bar'), 'foo/bar')
  357. self.assert_equal(make_path_safe('/'), '.')
  358. self.assert_equal(make_path_safe('/'), '.')
  359. class MockArchive:
  360. def __init__(self, ts):
  361. self.ts = ts
  362. def __repr__(self):
  363. return repr(self.ts)
  364. class PruneSplitTestCase(BaseTestCase):
  365. def test(self):
  366. def local_to_UTC(month, day):
  367. """Convert noon on the month and day in 2013 to UTC."""
  368. seconds = mktime(strptime('2013-%02d-%02d 12:00' % (month, day), '%Y-%m-%d %H:%M'))
  369. return datetime.fromtimestamp(seconds, tz=timezone.utc)
  370. def subset(lst, indices):
  371. return {lst[i] for i in indices}
  372. def dotest(test_archives, n, skip, indices):
  373. for ta in test_archives, reversed(test_archives):
  374. self.assert_equal(set(prune_split(ta, '%Y-%m', n, skip)),
  375. subset(test_archives, indices))
  376. test_pairs = [(1, 1), (2, 1), (2, 28), (3, 1), (3, 2), (3, 31), (5, 1)]
  377. test_dates = [local_to_UTC(month, day) for month, day in test_pairs]
  378. test_archives = [MockArchive(date) for date in test_dates]
  379. dotest(test_archives, 3, [], [6, 5, 2])
  380. dotest(test_archives, -1, [], [6, 5, 2, 0])
  381. dotest(test_archives, 3, [test_archives[6]], [5, 2, 0])
  382. dotest(test_archives, 3, [test_archives[5]], [6, 2, 0])
  383. dotest(test_archives, 3, [test_archives[4]], [6, 5, 2])
  384. dotest(test_archives, 0, [], [])
  385. class PruneWithinTestCase(BaseTestCase):
  386. def test(self):
  387. def subset(lst, indices):
  388. return {lst[i] for i in indices}
  389. def dotest(test_archives, within, indices):
  390. for ta in test_archives, reversed(test_archives):
  391. self.assert_equal(set(prune_within(ta, within)),
  392. subset(test_archives, indices))
  393. # 1 minute, 1.5 hours, 2.5 hours, 3.5 hours, 25 hours, 49 hours
  394. test_offsets = [60, 90*60, 150*60, 210*60, 25*60*60, 49*60*60]
  395. now = datetime.now(timezone.utc)
  396. test_dates = [now - timedelta(seconds=s) for s in test_offsets]
  397. test_archives = [MockArchive(date) for date in test_dates]
  398. dotest(test_archives, '1H', [0])
  399. dotest(test_archives, '2H', [0, 1])
  400. dotest(test_archives, '3H', [0, 1, 2])
  401. dotest(test_archives, '24H', [0, 1, 2, 3])
  402. dotest(test_archives, '26H', [0, 1, 2, 3, 4])
  403. dotest(test_archives, '2d', [0, 1, 2, 3, 4])
  404. dotest(test_archives, '50H', [0, 1, 2, 3, 4, 5])
  405. dotest(test_archives, '3d', [0, 1, 2, 3, 4, 5])
  406. dotest(test_archives, '1w', [0, 1, 2, 3, 4, 5])
  407. dotest(test_archives, '1m', [0, 1, 2, 3, 4, 5])
  408. dotest(test_archives, '1y', [0, 1, 2, 3, 4, 5])
  409. class StableDictTestCase(BaseTestCase):
  410. def test(self):
  411. d = StableDict(foo=1, bar=2, boo=3, baz=4)
  412. self.assert_equal(list(d.items()), [('bar', 2), ('baz', 4), ('boo', 3), ('foo', 1)])
  413. self.assert_equal(hashlib.md5(msgpack.packb(d)).hexdigest(), 'fc78df42cd60691b3ac3dd2a2b39903f')
  414. class TestParseTimestamp(BaseTestCase):
  415. def test(self):
  416. self.assert_equal(parse_timestamp('2015-04-19T20:25:00.226410'), datetime(2015, 4, 19, 20, 25, 0, 226410, timezone.utc))
  417. self.assert_equal(parse_timestamp('2015-04-19T20:25:00'), datetime(2015, 4, 19, 20, 25, 0, 0, timezone.utc))
  418. def test_get_cache_dir():
  419. """test that get_cache_dir respects environement"""
  420. # reset BORG_CACHE_DIR in order to test default
  421. old_env = None
  422. if os.environ.get('BORG_CACHE_DIR'):
  423. old_env = os.environ['BORG_CACHE_DIR']
  424. del(os.environ['BORG_CACHE_DIR'])
  425. assert get_cache_dir() == os.path.join(os.path.expanduser('~'), '.cache', 'borg')
  426. os.environ['XDG_CACHE_HOME'] = '/var/tmp/.cache'
  427. assert get_cache_dir() == os.path.join('/var/tmp/.cache', 'borg')
  428. os.environ['BORG_CACHE_DIR'] = '/var/tmp'
  429. assert get_cache_dir() == '/var/tmp'
  430. # reset old env
  431. if old_env is not None:
  432. os.environ['BORG_CACHE_DIR'] = old_env
  433. @pytest.fixture()
  434. def stats():
  435. stats = Statistics()
  436. stats.update(20, 10, unique=True)
  437. return stats
  438. def test_stats_basic(stats):
  439. assert stats.osize == 20
  440. assert stats.csize == stats.usize == 10
  441. stats.update(20, 10, unique=False)
  442. assert stats.osize == 40
  443. assert stats.csize == 20
  444. assert stats.usize == 10
  445. def tests_stats_progress(stats, columns=80):
  446. os.environ['COLUMNS'] = str(columns)
  447. out = StringIO()
  448. stats.show_progress(stream=out)
  449. s = '20 B O 10 B C 10 B D 0 N '
  450. buf = ' ' * (columns - len(s))
  451. assert out.getvalue() == s + buf + "\r"
  452. out = StringIO()
  453. stats.update(10**3, 0, unique=False)
  454. stats.show_progress(item={b'path': 'foo'}, final=False, stream=out)
  455. s = '1.02 kB O 10 B C 10 B D 0 N foo'
  456. buf = ' ' * (columns - len(s))
  457. assert out.getvalue() == s + buf + "\r"
  458. out = StringIO()
  459. stats.show_progress(item={b'path': 'foo'*40}, final=False, stream=out)
  460. s = '1.02 kB O 10 B C 10 B D 0 N foofoofoofoofoofoofoofo...oofoofoofoofoofoofoofoofoo'
  461. buf = ' ' * (columns - len(s))
  462. assert out.getvalue() == s + buf + "\r"
  463. def test_stats_format(stats):
  464. assert str(stats) == """\
  465. Original size Compressed size Deduplicated size
  466. This archive: 20 B 10 B 10 B"""
  467. s = "{0.osize_fmt}".format(stats)
  468. assert s == "20 B"
  469. # kind of redundant, but id is variable so we can't match reliably
  470. assert repr(stats) == '<Statistics object at {:#x} (20, 10, 10)>'.format(id(stats))
  471. def test_file_size():
  472. """test the size formatting routines"""
  473. si_size_map = {
  474. 0: '0 B', # no rounding necessary for those
  475. 1: '1 B',
  476. 142: '142 B',
  477. 999: '999 B',
  478. 1000: '1.00 kB', # rounding starts here
  479. 1001: '1.00 kB', # should be rounded away
  480. 1234: '1.23 kB', # should be rounded down
  481. 1235: '1.24 kB', # should be rounded up
  482. 1010: '1.01 kB', # rounded down as well
  483. 999990000: '999.99 MB', # rounded down
  484. 999990001: '999.99 MB', # rounded down
  485. 999995000: '1.00 GB', # rounded up to next unit
  486. 10**6: '1.00 MB', # and all the remaining units, megabytes
  487. 10**9: '1.00 GB', # gigabytes
  488. 10**12: '1.00 TB', # terabytes
  489. 10**15: '1.00 PB', # petabytes
  490. 10**18: '1.00 EB', # exabytes
  491. 10**21: '1.00 ZB', # zottabytes
  492. 10**24: '1.00 YB', # yottabytes
  493. }
  494. for size, fmt in si_size_map.items():
  495. assert format_file_size(size) == fmt
  496. def test_file_size_precision():
  497. assert format_file_size(1234, precision=1) == '1.2 kB' # rounded down
  498. assert format_file_size(1254, precision=1) == '1.3 kB' # rounded up
  499. assert format_file_size(999990000, precision=1) == '1.0 GB' # and not 999.9 MB or 1000.0 MB
  500. def test_is_slow_msgpack():
  501. saved_packer = msgpack.Packer
  502. try:
  503. msgpack.Packer = msgpack.fallback.Packer
  504. assert is_slow_msgpack()
  505. finally:
  506. msgpack.Packer = saved_packer
  507. # this assumes that we have fast msgpack on test platform:
  508. assert not is_slow_msgpack()
  509. def test_yes_simple():
  510. input = FakeInputs(['y', 'Y', 'yes', 'Yes', ])
  511. assert yes(input=input)
  512. assert yes(input=input)
  513. assert yes(input=input)
  514. assert yes(input=input)
  515. input = FakeInputs(['n', 'N', 'no', 'No', ])
  516. assert not yes(input=input)
  517. assert not yes(input=input)
  518. assert not yes(input=input)
  519. assert not yes(input=input)
  520. def test_yes_custom():
  521. input = FakeInputs(['YES', 'SURE', 'NOPE', ])
  522. assert yes(truish=('YES', ), input=input)
  523. assert yes(truish=('SURE', ), input=input)
  524. assert not yes(falsish=('NOPE', ), input=input)
  525. def test_yes_env():
  526. input = FakeInputs(['n', 'n'])
  527. with environment_variable(OVERRIDE_THIS='nonempty'):
  528. assert yes(env_var_override='OVERRIDE_THIS', input=input)
  529. with environment_variable(OVERRIDE_THIS=None): # env not set
  530. assert not yes(env_var_override='OVERRIDE_THIS', input=input)
  531. def test_yes_defaults():
  532. input = FakeInputs(['invalid', '', ' '])
  533. assert not yes(input=input) # default=False
  534. assert not yes(input=input)
  535. assert not yes(input=input)
  536. input = FakeInputs(['invalid', '', ' '])
  537. assert yes(default=True, input=input)
  538. assert yes(default=True, input=input)
  539. assert yes(default=True, input=input)
  540. ifile = StringIO()
  541. assert yes(default_notty=True, ifile=ifile)
  542. assert not yes(default_notty=False, ifile=ifile)
  543. input = FakeInputs([])
  544. assert yes(default_eof=True, input=input)
  545. assert not yes(default_eof=False, input=input)
  546. with pytest.raises(ValueError):
  547. yes(default=None)
  548. with pytest.raises(ValueError):
  549. yes(default_notty='invalid')
  550. with pytest.raises(ValueError):
  551. yes(default_eof='invalid')
  552. def test_yes_retry():
  553. input = FakeInputs(['foo', 'bar', 'y', ])
  554. assert yes(retry_msg='Retry: ', input=input)
  555. input = FakeInputs(['foo', 'bar', 'N', ])
  556. assert not yes(retry_msg='Retry: ', input=input)
  557. def test_yes_output(capfd):
  558. input = FakeInputs(['invalid', 'y', 'n'])
  559. assert yes(msg='intro-msg', false_msg='false-msg', true_msg='true-msg', retry_msg='retry-msg', input=input)
  560. out, err = capfd.readouterr()
  561. assert out == ''
  562. assert 'intro-msg' in err
  563. assert 'retry-msg' in err
  564. assert 'true-msg' in err
  565. assert not yes(msg='intro-msg', false_msg='false-msg', true_msg='true-msg', retry_msg='retry-msg', input=input)
  566. out, err = capfd.readouterr()
  567. assert out == ''
  568. assert 'intro-msg' in err
  569. assert 'retry-msg' not in err
  570. assert 'false-msg' in err
  571. def test_progress_percentage_multiline(capfd):
  572. pi = ProgressIndicatorPercent(1000, step=5, start=0, same_line=False, msg="%3.0f%%", file=sys.stderr)
  573. pi.show(0)
  574. out, err = capfd.readouterr()
  575. assert err == ' 0%\n'
  576. pi.show(420)
  577. out, err = capfd.readouterr()
  578. assert err == ' 42%\n'
  579. pi.show(1000)
  580. out, err = capfd.readouterr()
  581. assert err == '100%\n'
  582. pi.finish()
  583. out, err = capfd.readouterr()
  584. assert err == ''
  585. def test_progress_percentage_sameline(capfd):
  586. pi = ProgressIndicatorPercent(1000, step=5, start=0, same_line=True, msg="%3.0f%%", file=sys.stderr)
  587. pi.show(0)
  588. out, err = capfd.readouterr()
  589. assert err == ' 0%\r'
  590. pi.show(420)
  591. out, err = capfd.readouterr()
  592. assert err == ' 42%\r'
  593. pi.show(1000)
  594. out, err = capfd.readouterr()
  595. assert err == '100%\r'
  596. pi.finish()
  597. out, err = capfd.readouterr()
  598. assert err == ' ' * 4 + '\r'
  599. def test_progress_percentage_step(capfd):
  600. pi = ProgressIndicatorPercent(100, step=2, start=0, same_line=False, msg="%3.0f%%", file=sys.stderr)
  601. pi.show()
  602. out, err = capfd.readouterr()
  603. assert err == ' 0%\n'
  604. pi.show()
  605. out, err = capfd.readouterr()
  606. assert err == '' # no output at 1% as we have step == 2
  607. pi.show()
  608. out, err = capfd.readouterr()
  609. assert err == ' 2%\n'
  610. def test_progress_endless(capfd):
  611. pi = ProgressIndicatorEndless(step=1, file=sys.stderr)
  612. pi.show()
  613. out, err = capfd.readouterr()
  614. assert err == '.'
  615. pi.show()
  616. out, err = capfd.readouterr()
  617. assert err == '.'
  618. pi.finish()
  619. out, err = capfd.readouterr()
  620. assert err == '\n'
  621. def test_progress_endless_step(capfd):
  622. pi = ProgressIndicatorEndless(step=2, file=sys.stderr)
  623. pi.show()
  624. out, err = capfd.readouterr()
  625. assert err == '' # no output here as we have step == 2
  626. pi.show()
  627. out, err = capfd.readouterr()
  628. assert err == '.'
  629. pi.show()
  630. out, err = capfd.readouterr()
  631. assert err == '' # no output here as we have step == 2
  632. pi.show()
  633. out, err = capfd.readouterr()
  634. assert err == '.'