helpers.py 32 KB

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