helpers.py 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782
  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 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. matcher = PatternMatcher(fallback=True)
  279. matcher.add(load_excludes(open(filename, "rt")), False)
  280. return [path for path in files if matcher.match(path)]
  281. exclfile = tmpdir.join("exclude.txt")
  282. with exclfile.open("wt") as fh:
  283. fh.write("\n".join(lines))
  284. assert evaluate(str(exclfile)) == (files if expected is None else expected)
  285. @pytest.mark.parametrize("pattern, cls", [
  286. ("", FnmatchPattern),
  287. # Default style
  288. ("*", FnmatchPattern),
  289. ("/data/*", FnmatchPattern),
  290. # fnmatch style
  291. ("fm:", FnmatchPattern),
  292. ("fm:*", FnmatchPattern),
  293. ("fm:/data/*", FnmatchPattern),
  294. ("fm:fm:/data/*", FnmatchPattern),
  295. # Regular expression
  296. ("re:", RegexPattern),
  297. ("re:.*", RegexPattern),
  298. ("re:^/something/", RegexPattern),
  299. ("re:re:^/something/", RegexPattern),
  300. ])
  301. def test_parse_pattern(pattern, cls):
  302. assert isinstance(parse_pattern(pattern), cls)
  303. @pytest.mark.parametrize("pattern", ["aa:", "fo:*", "00:", "x1:abc"])
  304. def test_parse_pattern_error(pattern):
  305. with pytest.raises(ValueError):
  306. parse_pattern(pattern)
  307. def test_pattern_matcher():
  308. pm = PatternMatcher()
  309. assert pm.fallback is None
  310. for i in ["", "foo", "bar"]:
  311. assert pm.match(i) is None
  312. pm.add([RegexPattern("^a")], "A")
  313. pm.add([RegexPattern("^b"), RegexPattern("^z")], "B")
  314. pm.add([RegexPattern("^$")], "Empty")
  315. pm.fallback = "FileNotFound"
  316. assert pm.match("") == "Empty"
  317. assert pm.match("aaa") == "A"
  318. assert pm.match("bbb") == "B"
  319. assert pm.match("ccc") == "FileNotFound"
  320. assert pm.match("xyz") == "FileNotFound"
  321. assert pm.match("z") == "B"
  322. assert PatternMatcher(fallback="hey!").fallback == "hey!"
  323. def test_compression_specs():
  324. with pytest.raises(ValueError):
  325. CompressionSpec('')
  326. assert CompressionSpec('0') == dict(name='zlib', level=0)
  327. assert CompressionSpec('1') == dict(name='zlib', level=1)
  328. assert CompressionSpec('9') == dict(name='zlib', level=9)
  329. with pytest.raises(ValueError):
  330. CompressionSpec('10')
  331. assert CompressionSpec('none') == dict(name='none')
  332. assert CompressionSpec('lz4') == dict(name='lz4')
  333. assert CompressionSpec('zlib') == dict(name='zlib', level=6)
  334. assert CompressionSpec('zlib,0') == dict(name='zlib', level=0)
  335. assert CompressionSpec('zlib,9') == dict(name='zlib', level=9)
  336. with pytest.raises(ValueError):
  337. CompressionSpec('zlib,9,invalid')
  338. assert CompressionSpec('lzma') == dict(name='lzma', level=6)
  339. assert CompressionSpec('lzma,0') == dict(name='lzma', level=0)
  340. assert CompressionSpec('lzma,9') == dict(name='lzma', level=9)
  341. with pytest.raises(ValueError):
  342. CompressionSpec('lzma,9,invalid')
  343. with pytest.raises(ValueError):
  344. CompressionSpec('invalid')
  345. def test_chunkerparams():
  346. assert ChunkerParams('19,23,21,4095') == (19, 23, 21, 4095)
  347. assert ChunkerParams('10,23,16,4095') == (10, 23, 16, 4095)
  348. with pytest.raises(ValueError):
  349. ChunkerParams('19,24,21,4095')
  350. class MakePathSafeTestCase(BaseTestCase):
  351. def test(self):
  352. self.assert_equal(make_path_safe('/foo/bar'), 'foo/bar')
  353. self.assert_equal(make_path_safe('/foo/bar'), 'foo/bar')
  354. self.assert_equal(make_path_safe('/f/bar'), 'f/bar')
  355. self.assert_equal(make_path_safe('fo/bar'), 'fo/bar')
  356. self.assert_equal(make_path_safe('../foo/bar'), 'foo/bar')
  357. self.assert_equal(make_path_safe('../../foo/bar'), 'foo/bar')
  358. self.assert_equal(make_path_safe('/'), '.')
  359. self.assert_equal(make_path_safe('/'), '.')
  360. class MockArchive:
  361. def __init__(self, ts):
  362. self.ts = ts
  363. def __repr__(self):
  364. return repr(self.ts)
  365. class PruneSplitTestCase(BaseTestCase):
  366. def test(self):
  367. def local_to_UTC(month, day):
  368. """Convert noon on the month and day in 2013 to UTC."""
  369. seconds = mktime(strptime('2013-%02d-%02d 12:00' % (month, day), '%Y-%m-%d %H:%M'))
  370. return datetime.fromtimestamp(seconds, tz=timezone.utc)
  371. def subset(lst, indices):
  372. return {lst[i] for i in indices}
  373. def dotest(test_archives, n, skip, indices):
  374. for ta in test_archives, reversed(test_archives):
  375. self.assert_equal(set(prune_split(ta, '%Y-%m', n, skip)),
  376. subset(test_archives, indices))
  377. test_pairs = [(1, 1), (2, 1), (2, 28), (3, 1), (3, 2), (3, 31), (5, 1)]
  378. test_dates = [local_to_UTC(month, day) for month, day in test_pairs]
  379. test_archives = [MockArchive(date) for date in test_dates]
  380. dotest(test_archives, 3, [], [6, 5, 2])
  381. dotest(test_archives, -1, [], [6, 5, 2, 0])
  382. dotest(test_archives, 3, [test_archives[6]], [5, 2, 0])
  383. dotest(test_archives, 3, [test_archives[5]], [6, 2, 0])
  384. dotest(test_archives, 3, [test_archives[4]], [6, 5, 2])
  385. dotest(test_archives, 0, [], [])
  386. class PruneWithinTestCase(BaseTestCase):
  387. def test(self):
  388. def subset(lst, indices):
  389. return {lst[i] for i in indices}
  390. def dotest(test_archives, within, indices):
  391. for ta in test_archives, reversed(test_archives):
  392. self.assert_equal(set(prune_within(ta, within)),
  393. subset(test_archives, indices))
  394. # 1 minute, 1.5 hours, 2.5 hours, 3.5 hours, 25 hours, 49 hours
  395. test_offsets = [60, 90*60, 150*60, 210*60, 25*60*60, 49*60*60]
  396. now = datetime.now(timezone.utc)
  397. test_dates = [now - timedelta(seconds=s) for s in test_offsets]
  398. test_archives = [MockArchive(date) for date in test_dates]
  399. dotest(test_archives, '1H', [0])
  400. dotest(test_archives, '2H', [0, 1])
  401. dotest(test_archives, '3H', [0, 1, 2])
  402. dotest(test_archives, '24H', [0, 1, 2, 3])
  403. dotest(test_archives, '26H', [0, 1, 2, 3, 4])
  404. dotest(test_archives, '2d', [0, 1, 2, 3, 4])
  405. dotest(test_archives, '50H', [0, 1, 2, 3, 4, 5])
  406. dotest(test_archives, '3d', [0, 1, 2, 3, 4, 5])
  407. dotest(test_archives, '1w', [0, 1, 2, 3, 4, 5])
  408. dotest(test_archives, '1m', [0, 1, 2, 3, 4, 5])
  409. dotest(test_archives, '1y', [0, 1, 2, 3, 4, 5])
  410. class StableDictTestCase(BaseTestCase):
  411. def test(self):
  412. d = StableDict(foo=1, bar=2, boo=3, baz=4)
  413. self.assert_equal(list(d.items()), [('bar', 2), ('baz', 4), ('boo', 3), ('foo', 1)])
  414. self.assert_equal(hashlib.md5(msgpack.packb(d)).hexdigest(), 'fc78df42cd60691b3ac3dd2a2b39903f')
  415. class TestParseTimestamp(BaseTestCase):
  416. def test(self):
  417. self.assert_equal(parse_timestamp('2015-04-19T20:25:00.226410'), datetime(2015, 4, 19, 20, 25, 0, 226410, timezone.utc))
  418. self.assert_equal(parse_timestamp('2015-04-19T20:25:00'), datetime(2015, 4, 19, 20, 25, 0, 0, timezone.utc))
  419. def test_get_cache_dir():
  420. """test that get_cache_dir respects environement"""
  421. # reset BORG_CACHE_DIR in order to test default
  422. old_env = None
  423. if os.environ.get('BORG_CACHE_DIR'):
  424. old_env = os.environ['BORG_CACHE_DIR']
  425. del(os.environ['BORG_CACHE_DIR'])
  426. assert get_cache_dir() == os.path.join(os.path.expanduser('~'), '.cache', 'borg')
  427. os.environ['XDG_CACHE_HOME'] = '/var/tmp/.cache'
  428. assert get_cache_dir() == os.path.join('/var/tmp/.cache', 'borg')
  429. os.environ['BORG_CACHE_DIR'] = '/var/tmp'
  430. assert get_cache_dir() == '/var/tmp'
  431. # reset old env
  432. if old_env is not None:
  433. os.environ['BORG_CACHE_DIR'] = old_env
  434. @pytest.fixture()
  435. def stats():
  436. stats = Statistics()
  437. stats.update(20, 10, unique=True)
  438. return stats
  439. def test_stats_basic(stats):
  440. assert stats.osize == 20
  441. assert stats.csize == stats.usize == 10
  442. stats.update(20, 10, unique=False)
  443. assert stats.osize == 40
  444. assert stats.csize == 20
  445. assert stats.usize == 10
  446. def tests_stats_progress(stats, columns=80):
  447. os.environ['COLUMNS'] = str(columns)
  448. out = StringIO()
  449. stats.show_progress(stream=out)
  450. s = '20 B O 10 B C 10 B D 0 N '
  451. buf = ' ' * (columns - len(s))
  452. assert out.getvalue() == s + buf + "\r"
  453. out = StringIO()
  454. stats.update(10**3, 0, unique=False)
  455. stats.show_progress(item={b'path': 'foo'}, final=False, stream=out)
  456. s = '1.02 kB O 10 B C 10 B D 0 N foo'
  457. buf = ' ' * (columns - len(s))
  458. assert out.getvalue() == s + buf + "\r"
  459. out = StringIO()
  460. stats.show_progress(item={b'path': 'foo'*40}, final=False, stream=out)
  461. s = '1.02 kB O 10 B C 10 B D 0 N foofoofoofoofoofoofoofo...oofoofoofoofoofoofoofoofoo'
  462. buf = ' ' * (columns - len(s))
  463. assert out.getvalue() == s + buf + "\r"
  464. def test_stats_format(stats):
  465. assert str(stats) == """\
  466. Original size Compressed size Deduplicated size
  467. This archive: 20 B 10 B 10 B"""
  468. s = "{0.osize_fmt}".format(stats)
  469. assert s == "20 B"
  470. # kind of redundant, but id is variable so we can't match reliably
  471. assert repr(stats) == '<Statistics object at {:#x} (20, 10, 10)>'.format(id(stats))
  472. def test_file_size():
  473. """test the size formatting routines"""
  474. si_size_map = {
  475. 0: '0 B', # no rounding necessary for those
  476. 1: '1 B',
  477. 142: '142 B',
  478. 999: '999 B',
  479. 1000: '1.00 kB', # rounding starts here
  480. 1001: '1.00 kB', # should be rounded away
  481. 1234: '1.23 kB', # should be rounded down
  482. 1235: '1.24 kB', # should be rounded up
  483. 1010: '1.01 kB', # rounded down as well
  484. 999990000: '999.99 MB', # rounded down
  485. 999990001: '999.99 MB', # rounded down
  486. 999995000: '1.00 GB', # rounded up to next unit
  487. 10**6: '1.00 MB', # and all the remaining units, megabytes
  488. 10**9: '1.00 GB', # gigabytes
  489. 10**12: '1.00 TB', # terabytes
  490. 10**15: '1.00 PB', # petabytes
  491. 10**18: '1.00 EB', # exabytes
  492. 10**21: '1.00 ZB', # zottabytes
  493. 10**24: '1.00 YB', # yottabytes
  494. }
  495. for size, fmt in si_size_map.items():
  496. assert format_file_size(size) == fmt
  497. def test_file_size_precision():
  498. assert format_file_size(1234, precision=1) == '1.2 kB' # rounded down
  499. assert format_file_size(1254, precision=1) == '1.3 kB' # rounded up
  500. assert format_file_size(999990000, precision=1) == '1.0 GB' # and not 999.9 MB or 1000.0 MB
  501. def test_is_slow_msgpack():
  502. saved_packer = msgpack.Packer
  503. try:
  504. msgpack.Packer = msgpack.fallback.Packer
  505. assert is_slow_msgpack()
  506. finally:
  507. msgpack.Packer = saved_packer
  508. # this assumes that we have fast msgpack on test platform:
  509. assert not is_slow_msgpack()
  510. def test_yes_simple():
  511. input = FakeInputs(['y', 'Y', 'yes', 'Yes', ])
  512. assert yes(input=input)
  513. assert yes(input=input)
  514. assert yes(input=input)
  515. assert yes(input=input)
  516. input = FakeInputs(['n', 'N', 'no', 'No', ])
  517. assert not yes(input=input)
  518. assert not yes(input=input)
  519. assert not yes(input=input)
  520. assert not yes(input=input)
  521. def test_yes_custom():
  522. input = FakeInputs(['YES', 'SURE', 'NOPE', ])
  523. assert yes(truish=('YES', ), input=input)
  524. assert yes(truish=('SURE', ), input=input)
  525. assert not yes(falsish=('NOPE', ), input=input)
  526. def test_yes_env():
  527. input = FakeInputs(['n', 'n'])
  528. with environment_variable(OVERRIDE_THIS='nonempty'):
  529. assert yes(env_var_override='OVERRIDE_THIS', input=input)
  530. with environment_variable(OVERRIDE_THIS=None): # env not set
  531. assert not yes(env_var_override='OVERRIDE_THIS', input=input)
  532. def test_yes_defaults():
  533. input = FakeInputs(['invalid', '', ' '])
  534. assert not yes(input=input) # default=False
  535. assert not yes(input=input)
  536. assert not yes(input=input)
  537. input = FakeInputs(['invalid', '', ' '])
  538. assert yes(default=True, input=input)
  539. assert yes(default=True, input=input)
  540. assert yes(default=True, input=input)
  541. ifile = StringIO()
  542. assert yes(default_notty=True, ifile=ifile)
  543. assert not yes(default_notty=False, ifile=ifile)
  544. input = FakeInputs([])
  545. assert yes(default_eof=True, input=input)
  546. assert not yes(default_eof=False, input=input)
  547. with pytest.raises(ValueError):
  548. yes(default=None)
  549. with pytest.raises(ValueError):
  550. yes(default_notty='invalid')
  551. with pytest.raises(ValueError):
  552. yes(default_eof='invalid')
  553. def test_yes_retry():
  554. input = FakeInputs(['foo', 'bar', 'y', ])
  555. assert yes(retry_msg='Retry: ', input=input)
  556. input = FakeInputs(['foo', 'bar', 'N', ])
  557. assert not yes(retry_msg='Retry: ', input=input)
  558. def test_yes_output(capfd):
  559. input = FakeInputs(['invalid', 'y', 'n'])
  560. assert yes(msg='intro-msg', false_msg='false-msg', true_msg='true-msg', retry_msg='retry-msg', input=input)
  561. out, err = capfd.readouterr()
  562. assert out == ''
  563. assert 'intro-msg' in err
  564. assert 'retry-msg' in err
  565. assert 'true-msg' in err
  566. assert not yes(msg='intro-msg', false_msg='false-msg', true_msg='true-msg', retry_msg='retry-msg', input=input)
  567. out, err = capfd.readouterr()
  568. assert out == ''
  569. assert 'intro-msg' in err
  570. assert 'retry-msg' not in err
  571. assert 'false-msg' in err
  572. def test_progress_percentage_multiline(capfd):
  573. pi = ProgressIndicatorPercent(1000, step=5, start=0, same_line=False, msg="%3.0f%%", file=sys.stderr)
  574. pi.show(0)
  575. out, err = capfd.readouterr()
  576. assert err == ' 0%\n'
  577. pi.show(420)
  578. out, err = capfd.readouterr()
  579. assert err == ' 42%\n'
  580. pi.show(1000)
  581. out, err = capfd.readouterr()
  582. assert err == '100%\n'
  583. pi.finish()
  584. out, err = capfd.readouterr()
  585. assert err == ''
  586. def test_progress_percentage_sameline(capfd):
  587. pi = ProgressIndicatorPercent(1000, step=5, start=0, same_line=True, msg="%3.0f%%", file=sys.stderr)
  588. pi.show(0)
  589. out, err = capfd.readouterr()
  590. assert err == ' 0%\r'
  591. pi.show(420)
  592. out, err = capfd.readouterr()
  593. assert err == ' 42%\r'
  594. pi.show(1000)
  595. out, err = capfd.readouterr()
  596. assert err == '100%\r'
  597. pi.finish()
  598. out, err = capfd.readouterr()
  599. assert err == ' ' * 4 + '\r'
  600. def test_progress_percentage_step(capfd):
  601. pi = ProgressIndicatorPercent(100, step=2, start=0, same_line=False, msg="%3.0f%%", file=sys.stderr)
  602. pi.show()
  603. out, err = capfd.readouterr()
  604. assert err == ' 0%\n'
  605. pi.show()
  606. out, err = capfd.readouterr()
  607. assert err == '' # no output at 1% as we have step == 2
  608. pi.show()
  609. out, err = capfd.readouterr()
  610. assert err == ' 2%\n'
  611. def test_progress_endless(capfd):
  612. pi = ProgressIndicatorEndless(step=1, file=sys.stderr)
  613. pi.show()
  614. out, err = capfd.readouterr()
  615. assert err == '.'
  616. pi.show()
  617. out, err = capfd.readouterr()
  618. assert err == '.'
  619. pi.finish()
  620. out, err = capfd.readouterr()
  621. assert err == '\n'
  622. def test_progress_endless_step(capfd):
  623. pi = ProgressIndicatorEndless(step=2, file=sys.stderr)
  624. pi.show()
  625. out, err = capfd.readouterr()
  626. assert err == '' # no output here as we have step == 2
  627. pi.show()
  628. out, err = capfd.readouterr()
  629. assert err == '.'
  630. pi.show()
  631. out, err = capfd.readouterr()
  632. assert err == '' # no output here as we have step == 2
  633. pi.show()
  634. out, err = capfd.readouterr()
  635. assert err == '.'