helpers.py 38 KB

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