helpers.py 32 KB

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