archiver.py 50 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056
  1. from binascii import hexlify
  2. from configparser import ConfigParser
  3. import errno
  4. import os
  5. from io import StringIO
  6. import random
  7. import stat
  8. import subprocess
  9. import sys
  10. import shutil
  11. import tempfile
  12. import time
  13. import unittest
  14. from hashlib import sha256
  15. from mock import patch
  16. import pytest
  17. from .. import xattr
  18. from ..archive import Archive, ChunkBuffer, CHUNK_MAX_EXP
  19. from ..archiver import Archiver
  20. from ..cache import Cache
  21. from ..crypto import bytes_to_long, num_aes_blocks
  22. from ..helpers import Manifest, EXIT_SUCCESS, EXIT_WARNING, EXIT_ERROR, st_atime_ns, st_mtime_ns
  23. from ..remote import RemoteRepository, PathNotAllowed
  24. from ..repository import Repository
  25. from . import BaseTestCase, changedir, environment_variable
  26. try:
  27. import llfuse
  28. has_llfuse = True or llfuse # avoids "unused import"
  29. except ImportError:
  30. has_llfuse = False
  31. has_lchflags = hasattr(os, 'lchflags')
  32. src_dir = os.path.join(os.getcwd(), os.path.dirname(__file__), '..')
  33. # Python <= 3.2 raises OSError instead of PermissionError (See #164)
  34. try:
  35. PermissionError = PermissionError
  36. except NameError:
  37. PermissionError = OSError
  38. def exec_cmd(*args, archiver=None, fork=False, exe=None, **kw):
  39. if fork:
  40. try:
  41. if exe is None:
  42. borg = (sys.executable, '-m', 'borg.archiver')
  43. elif isinstance(exe, str):
  44. borg = (exe, )
  45. elif not isinstance(exe, tuple):
  46. raise ValueError('exe must be None, a tuple or a str')
  47. output = subprocess.check_output(borg + args, stderr=subprocess.STDOUT)
  48. ret = 0
  49. except subprocess.CalledProcessError as e:
  50. output = e.output
  51. ret = e.returncode
  52. return ret, os.fsdecode(output)
  53. else:
  54. stdin, stdout, stderr = sys.stdin, sys.stdout, sys.stderr
  55. try:
  56. sys.stdin = StringIO()
  57. sys.stdout = sys.stderr = output = StringIO()
  58. if archiver is None:
  59. archiver = Archiver()
  60. args = archiver.parse_args(list(args))
  61. ret = archiver.run(args)
  62. return ret, output.getvalue()
  63. finally:
  64. sys.stdin, sys.stdout, sys.stderr = stdin, stdout, stderr
  65. # check if the binary "borg.exe" is available
  66. try:
  67. exec_cmd('help', exe='borg.exe', fork=True)
  68. BORG_EXES = ['python', 'binary', ]
  69. except (IOError, OSError) as err:
  70. if err.errno != errno.ENOENT:
  71. raise
  72. BORG_EXES = ['python', ]
  73. @pytest.fixture(params=BORG_EXES)
  74. def cmd(request):
  75. if request.param == 'python':
  76. exe = None
  77. elif request.param == 'binary':
  78. exe = 'borg.exe'
  79. else:
  80. raise ValueError("param must be 'python' or 'binary'")
  81. def exec_fn(*args, **kw):
  82. return exec_cmd(*args, exe=exe, fork=True, **kw)
  83. return exec_fn
  84. def test_return_codes(cmd, tmpdir):
  85. repo = tmpdir.mkdir('repo')
  86. input = tmpdir.mkdir('input')
  87. output = tmpdir.mkdir('output')
  88. input.join('test_file').write('content')
  89. rc, out = cmd('init', '%s' % str(repo))
  90. assert rc == EXIT_SUCCESS
  91. rc, out = cmd('create', '%s::archive' % repo, str(input))
  92. assert rc == EXIT_SUCCESS
  93. with changedir(str(output)):
  94. rc, out = cmd('extract', '%s::archive' % repo)
  95. assert rc == EXIT_SUCCESS
  96. rc, out = cmd('extract', '%s::archive' % repo, 'does/not/match')
  97. assert rc == EXIT_WARNING # pattern did not match
  98. rc, out = cmd('create', '%s::archive' % repo, str(input))
  99. assert rc == EXIT_ERROR # duplicate archive name
  100. """
  101. test_disk_full is very slow and not recommended to be included in daily testing.
  102. for this test, an empty, writable 16MB filesystem mounted on DF_MOUNT is required.
  103. for speed and other reasons, it is recommended that the underlying block device is
  104. in RAM, not a magnetic or flash disk.
  105. assuming /tmp is a tmpfs (in memory filesystem), one can use this:
  106. dd if=/dev/zero of=/tmp/borg-disk bs=16M count=1
  107. mkfs.ext4 /tmp/borg-disk
  108. mkdir /tmp/borg-mount
  109. sudo mount /tmp/borg-disk /tmp/borg-mount
  110. if the directory does not exist, the test will be skipped.
  111. """
  112. DF_MOUNT = '/tmp/borg-mount'
  113. @pytest.mark.skipif(not os.path.exists(DF_MOUNT), reason="needs a 16MB fs mounted on %s" % DF_MOUNT)
  114. def test_disk_full(cmd):
  115. def make_files(dir, count, size, rnd=True):
  116. shutil.rmtree(dir, ignore_errors=True)
  117. os.mkdir(dir)
  118. if rnd:
  119. count = random.randint(1, count)
  120. if size > 1:
  121. size = random.randint(1, size)
  122. for i in range(count):
  123. fn = os.path.join(dir, "file%03d" % i)
  124. with open(fn, 'wb') as f:
  125. data = os.urandom(size)
  126. f.write(data)
  127. with environment_variable(BORG_CHECK_I_KNOW_WHAT_I_AM_DOING='1'):
  128. mount = DF_MOUNT
  129. assert os.path.exists(mount)
  130. repo = os.path.join(mount, 'repo')
  131. input = os.path.join(mount, 'input')
  132. reserve = os.path.join(mount, 'reserve')
  133. for j in range(100):
  134. shutil.rmtree(repo, ignore_errors=True)
  135. shutil.rmtree(input, ignore_errors=True)
  136. # keep some space and some inodes in reserve that we can free up later:
  137. make_files(reserve, 80, 100000, rnd=False)
  138. rc, out = cmd('init', repo)
  139. if rc != EXIT_SUCCESS:
  140. print('init', rc, out)
  141. assert rc == EXIT_SUCCESS
  142. try:
  143. success, i = True, 0
  144. while success:
  145. i += 1
  146. try:
  147. make_files(input, 20, 200000)
  148. except OSError as err:
  149. if err.errno == errno.ENOSPC:
  150. # already out of space
  151. break
  152. raise
  153. try:
  154. rc, out = cmd('create', '%s::test%03d' % (repo, i), input)
  155. success = rc == EXIT_SUCCESS
  156. if not success:
  157. print('create', rc, out)
  158. finally:
  159. # make sure repo is not locked
  160. shutil.rmtree(os.path.join(repo, 'lock.exclusive'), ignore_errors=True)
  161. os.remove(os.path.join(repo, 'lock.roster'))
  162. finally:
  163. # now some error happened, likely we are out of disk space.
  164. # free some space so we can expect borg to be able to work normally:
  165. shutil.rmtree(reserve, ignore_errors=True)
  166. rc, out = cmd('list', repo)
  167. if rc != EXIT_SUCCESS:
  168. print('list', rc, out)
  169. rc, out = cmd('check', '--repair', repo)
  170. if rc != EXIT_SUCCESS:
  171. print('check', rc, out)
  172. assert rc == EXIT_SUCCESS
  173. class ArchiverTestCaseBase(BaseTestCase):
  174. EXE = None # python source based
  175. FORK_DEFAULT = False
  176. prefix = ''
  177. def setUp(self):
  178. os.environ['BORG_CHECK_I_KNOW_WHAT_I_AM_DOING'] = '1'
  179. self.archiver = not self.FORK_DEFAULT and Archiver() or None
  180. self.tmpdir = tempfile.mkdtemp()
  181. self.repository_path = os.path.join(self.tmpdir, 'repository')
  182. self.repository_location = self.prefix + self.repository_path
  183. self.input_path = os.path.join(self.tmpdir, 'input')
  184. self.output_path = os.path.join(self.tmpdir, 'output')
  185. self.keys_path = os.path.join(self.tmpdir, 'keys')
  186. self.cache_path = os.path.join(self.tmpdir, 'cache')
  187. self.exclude_file_path = os.path.join(self.tmpdir, 'excludes')
  188. os.environ['BORG_KEYS_DIR'] = self.keys_path
  189. os.environ['BORG_CACHE_DIR'] = self.cache_path
  190. os.mkdir(self.input_path)
  191. os.mkdir(self.output_path)
  192. os.mkdir(self.keys_path)
  193. os.mkdir(self.cache_path)
  194. with open(self.exclude_file_path, 'wb') as fd:
  195. fd.write(b'input/file2\n# A comment line, then a blank line\n\n')
  196. self._old_wd = os.getcwd()
  197. os.chdir(self.tmpdir)
  198. def tearDown(self):
  199. os.chdir(self._old_wd)
  200. shutil.rmtree(self.tmpdir)
  201. def cmd(self, *args, **kw):
  202. exit_code = kw.pop('exit_code', 0)
  203. fork = kw.pop('fork', None)
  204. if fork is None:
  205. fork = self.FORK_DEFAULT
  206. ret, output = exec_cmd(*args, fork=fork, exe=self.EXE, archiver=self.archiver, **kw)
  207. if ret != exit_code:
  208. print(output)
  209. self.assert_equal(ret, exit_code)
  210. return output
  211. def create_src_archive(self, name):
  212. self.cmd('create', self.repository_location + '::' + name, src_dir)
  213. class ArchiverTestCase(ArchiverTestCaseBase):
  214. def create_regular_file(self, name, size=0, contents=None):
  215. filename = os.path.join(self.input_path, name)
  216. if not os.path.exists(os.path.dirname(filename)):
  217. os.makedirs(os.path.dirname(filename))
  218. with open(filename, 'wb') as fd:
  219. if contents is None:
  220. contents = b'X' * size
  221. fd.write(contents)
  222. def create_test_files(self):
  223. """Create a minimal test case including all supported file types
  224. """
  225. # File
  226. self.create_regular_file('empty', size=0)
  227. # next code line raises OverflowError on 32bit cpu (raspberry pi 2):
  228. # 2600-01-01 > 2**64 ns
  229. # os.utime('input/empty', (19880895600, 19880895600))
  230. # thus, we better test with something not that far in future:
  231. # 2038-01-19 (1970 + 2^31 - 1 seconds) is the 32bit "deadline":
  232. os.utime('input/empty', (2**31 - 1, 2**31 - 1))
  233. self.create_regular_file('file1', size=1024 * 80)
  234. self.create_regular_file('flagfile', size=1024)
  235. # Directory
  236. self.create_regular_file('dir2/file2', size=1024 * 80)
  237. # File mode
  238. os.chmod('input/file1', 0o4755)
  239. # Hard link
  240. os.link(os.path.join(self.input_path, 'file1'),
  241. os.path.join(self.input_path, 'hardlink'))
  242. # Symlink
  243. os.symlink('somewhere', os.path.join(self.input_path, 'link1'))
  244. if xattr.is_enabled(self.input_path):
  245. xattr.setxattr(os.path.join(self.input_path, 'file1'), 'user.foo', b'bar')
  246. # XXX this always fails for me
  247. # ubuntu 14.04, on a TMP dir filesystem with user_xattr, using fakeroot
  248. # same for newer ubuntu and centos.
  249. # if this is supported just on specific platform, platform should be checked first,
  250. # so that the test setup for all tests using it does not fail here always for others.
  251. # xattr.setxattr(os.path.join(self.input_path, 'link1'), 'user.foo_symlink', b'bar_symlink', follow_symlinks=False)
  252. # FIFO node
  253. os.mkfifo(os.path.join(self.input_path, 'fifo1'))
  254. if has_lchflags:
  255. os.lchflags(os.path.join(self.input_path, 'flagfile'), stat.UF_NODUMP)
  256. try:
  257. # Block device
  258. os.mknod('input/bdev', 0o600 | stat.S_IFBLK, os.makedev(10, 20))
  259. # Char device
  260. os.mknod('input/cdev', 0o600 | stat.S_IFCHR, os.makedev(30, 40))
  261. # File mode
  262. os.chmod('input/dir2', 0o555) # if we take away write perms, we need root to remove contents
  263. # File owner
  264. os.chown('input/file1', 100, 200)
  265. have_root = True # we have (fake)root
  266. except PermissionError:
  267. have_root = False
  268. return have_root
  269. def test_basic_functionality(self):
  270. have_root = self.create_test_files()
  271. self.cmd('init', self.repository_location)
  272. self.cmd('create', self.repository_location + '::test', 'input')
  273. self.cmd('create', '--stats', self.repository_location + '::test.2', 'input')
  274. with changedir('output'):
  275. self.cmd('extract', self.repository_location + '::test')
  276. list_output = self.cmd('list', '--short', self.repository_location)
  277. self.assert_in('test', list_output)
  278. self.assert_in('test.2', list_output)
  279. expected = [
  280. 'input',
  281. 'input/bdev',
  282. 'input/cdev',
  283. 'input/dir2',
  284. 'input/dir2/file2',
  285. 'input/empty',
  286. 'input/fifo1',
  287. 'input/file1',
  288. 'input/flagfile',
  289. 'input/hardlink',
  290. 'input/link1',
  291. ]
  292. if not have_root:
  293. # we could not create these device files without (fake)root
  294. expected.remove('input/bdev')
  295. expected.remove('input/cdev')
  296. if has_lchflags:
  297. # remove the file we did not backup, so input and output become equal
  298. expected.remove('input/flagfile') # this file is UF_NODUMP
  299. os.remove(os.path.join('input', 'flagfile'))
  300. list_output = self.cmd('list', '--short', self.repository_location + '::test')
  301. for name in expected:
  302. self.assert_in(name, list_output)
  303. self.assert_dirs_equal('input', 'output/input')
  304. info_output = self.cmd('info', self.repository_location + '::test')
  305. item_count = 3 if has_lchflags else 4 # one file is UF_NODUMP
  306. self.assert_in('Number of files: %d' % item_count, info_output)
  307. shutil.rmtree(self.cache_path)
  308. with environment_variable(BORG_UNKNOWN_UNENCRYPTED_REPO_ACCESS_IS_OK='1'):
  309. info_output2 = self.cmd('info', self.repository_location + '::test')
  310. def filter(output):
  311. # filter for interesting "info" output, ignore cache rebuilding related stuff
  312. prefixes = ['Name:', 'Fingerprint:', 'Number of files:', 'This archive:',
  313. 'All archives:', 'Chunk index:', ]
  314. result = []
  315. for line in output.splitlines():
  316. for prefix in prefixes:
  317. if line.startswith(prefix):
  318. result.append(line)
  319. return '\n'.join(result)
  320. # the interesting parts of info_output2 and info_output should be same
  321. self.assert_equal(filter(info_output), filter(info_output2))
  322. def test_atime(self):
  323. have_root = self.create_test_files()
  324. atime, mtime = 123456780, 234567890
  325. os.utime('input/file1', (atime, mtime))
  326. self.cmd('init', self.repository_location)
  327. self.cmd('create', self.repository_location + '::test', 'input')
  328. with changedir('output'):
  329. self.cmd('extract', self.repository_location + '::test')
  330. sti = os.stat('input/file1')
  331. sto = os.stat('output/input/file1')
  332. assert st_mtime_ns(sti) == st_mtime_ns(sto) == mtime * 1e9
  333. if hasattr(os, 'O_NOATIME'):
  334. assert st_atime_ns(sti) == st_atime_ns(sto) == atime * 1e9
  335. else:
  336. # it touched the input file's atime while backing it up
  337. assert st_atime_ns(sto) == atime * 1e9
  338. def _extract_repository_id(self, path):
  339. return Repository(self.repository_path).id
  340. def _set_repository_id(self, path, id):
  341. config = ConfigParser(interpolation=None)
  342. config.read(os.path.join(path, 'config'))
  343. config.set('repository', 'id', hexlify(id).decode('ascii'))
  344. with open(os.path.join(path, 'config'), 'w') as fd:
  345. config.write(fd)
  346. return Repository(self.repository_path).id
  347. def test_sparse_file(self):
  348. # no sparse file support on Mac OS X
  349. sparse_support = sys.platform != 'darwin'
  350. filename = os.path.join(self.input_path, 'sparse')
  351. content = b'foobar'
  352. hole_size = 5 * (1 << CHUNK_MAX_EXP) # 5 full chunker buffers
  353. with open(filename, 'wb') as fd:
  354. # create a file that has a hole at the beginning and end (if the
  355. # OS and filesystem supports sparse files)
  356. fd.seek(hole_size, 1)
  357. fd.write(content)
  358. fd.seek(hole_size, 1)
  359. pos = fd.tell()
  360. fd.truncate(pos)
  361. total_len = hole_size + len(content) + hole_size
  362. st = os.stat(filename)
  363. self.assert_equal(st.st_size, total_len)
  364. if sparse_support and hasattr(st, 'st_blocks'):
  365. self.assert_true(st.st_blocks * 512 < total_len / 9) # is input sparse?
  366. self.cmd('init', self.repository_location)
  367. self.cmd('create', self.repository_location + '::test', 'input')
  368. with changedir('output'):
  369. self.cmd('extract', '--sparse', self.repository_location + '::test')
  370. self.assert_dirs_equal('input', 'output/input')
  371. filename = os.path.join(self.output_path, 'input', 'sparse')
  372. with open(filename, 'rb') as fd:
  373. # check if file contents are as expected
  374. self.assert_equal(fd.read(hole_size), b'\0' * hole_size)
  375. self.assert_equal(fd.read(len(content)), content)
  376. self.assert_equal(fd.read(hole_size), b'\0' * hole_size)
  377. st = os.stat(filename)
  378. self.assert_equal(st.st_size, total_len)
  379. if sparse_support and hasattr(st, 'st_blocks'):
  380. self.assert_true(st.st_blocks * 512 < total_len / 9) # is output sparse?
  381. def test_unusual_filenames(self):
  382. filenames = ['normal', 'with some blanks', '(with_parens)', ]
  383. for filename in filenames:
  384. filename = os.path.join(self.input_path, filename)
  385. with open(filename, 'wb') as fd:
  386. pass
  387. self.cmd('init', self.repository_location)
  388. self.cmd('create', self.repository_location + '::test', 'input')
  389. for filename in filenames:
  390. with changedir('output'):
  391. self.cmd('extract', self.repository_location + '::test', os.path.join('input', filename))
  392. assert os.path.exists(os.path.join('output', 'input', filename))
  393. def test_repository_swap_detection(self):
  394. self.create_test_files()
  395. os.environ['BORG_PASSPHRASE'] = 'passphrase'
  396. self.cmd('init', '--encryption=passphrase', self.repository_location)
  397. repository_id = self._extract_repository_id(self.repository_path)
  398. self.cmd('create', self.repository_location + '::test', 'input')
  399. shutil.rmtree(self.repository_path)
  400. self.cmd('init', '--encryption=none', self.repository_location)
  401. self._set_repository_id(self.repository_path, repository_id)
  402. self.assert_equal(repository_id, self._extract_repository_id(self.repository_path))
  403. if self.FORK_DEFAULT:
  404. self.cmd('create', self.repository_location + '::test.2', 'input', exit_code=EXIT_ERROR)
  405. else:
  406. self.assert_raises(Cache.EncryptionMethodMismatch, lambda: self.cmd('create', self.repository_location + '::test.2', 'input'))
  407. def test_repository_swap_detection2(self):
  408. self.create_test_files()
  409. self.cmd('init', '--encryption=none', self.repository_location + '_unencrypted')
  410. os.environ['BORG_PASSPHRASE'] = 'passphrase'
  411. self.cmd('init', '--encryption=passphrase', self.repository_location + '_encrypted')
  412. self.cmd('create', self.repository_location + '_encrypted::test', 'input')
  413. shutil.rmtree(self.repository_path + '_encrypted')
  414. os.rename(self.repository_path + '_unencrypted', self.repository_path + '_encrypted')
  415. if self.FORK_DEFAULT:
  416. self.cmd('create', self.repository_location + '_encrypted::test.2', 'input', exit_code=EXIT_ERROR)
  417. else:
  418. self.assert_raises(Cache.RepositoryAccessAborted, lambda: self.cmd('create', self.repository_location + '_encrypted::test.2', 'input'))
  419. def test_strip_components(self):
  420. self.cmd('init', self.repository_location)
  421. self.create_regular_file('dir/file')
  422. self.cmd('create', self.repository_location + '::test', 'input')
  423. with changedir('output'):
  424. self.cmd('extract', self.repository_location + '::test', '--strip-components', '3')
  425. self.assert_true(not os.path.exists('file'))
  426. with self.assert_creates_file('file'):
  427. self.cmd('extract', self.repository_location + '::test', '--strip-components', '2')
  428. with self.assert_creates_file('dir/file'):
  429. self.cmd('extract', self.repository_location + '::test', '--strip-components', '1')
  430. with self.assert_creates_file('input/dir/file'):
  431. self.cmd('extract', self.repository_location + '::test', '--strip-components', '0')
  432. def test_extract_include_exclude(self):
  433. self.cmd('init', self.repository_location)
  434. self.create_regular_file('file1', size=1024 * 80)
  435. self.create_regular_file('file2', size=1024 * 80)
  436. self.create_regular_file('file3', size=1024 * 80)
  437. self.create_regular_file('file4', size=1024 * 80)
  438. self.cmd('create', '--exclude=input/file4', self.repository_location + '::test', 'input')
  439. with changedir('output'):
  440. self.cmd('extract', self.repository_location + '::test', 'input/file1', )
  441. self.assert_equal(sorted(os.listdir('output/input')), ['file1'])
  442. with changedir('output'):
  443. self.cmd('extract', '--exclude=input/file2', self.repository_location + '::test')
  444. self.assert_equal(sorted(os.listdir('output/input')), ['file1', 'file3'])
  445. with changedir('output'):
  446. self.cmd('extract', '--exclude-from=' + self.exclude_file_path, self.repository_location + '::test')
  447. self.assert_equal(sorted(os.listdir('output/input')), ['file1', 'file3'])
  448. def test_exclude_caches(self):
  449. self.cmd('init', self.repository_location)
  450. self.create_regular_file('file1', size=1024 * 80)
  451. self.create_regular_file('cache1/CACHEDIR.TAG', contents=b'Signature: 8a477f597d28d172789f06886806bc55 extra stuff')
  452. self.create_regular_file('cache2/CACHEDIR.TAG', contents=b'invalid signature')
  453. self.cmd('create', '--exclude-caches', self.repository_location + '::test', 'input')
  454. with changedir('output'):
  455. self.cmd('extract', self.repository_location + '::test')
  456. self.assert_equal(sorted(os.listdir('output/input')), ['cache2', 'file1'])
  457. self.assert_equal(sorted(os.listdir('output/input/cache2')), ['CACHEDIR.TAG'])
  458. def test_exclude_tagged(self):
  459. self.cmd('init', self.repository_location)
  460. self.create_regular_file('file1', size=1024 * 80)
  461. self.create_regular_file('tagged1/.NOBACKUP')
  462. self.create_regular_file('tagged2/00-NOBACKUP')
  463. self.create_regular_file('tagged3/.NOBACKUP/file2')
  464. self.cmd('create', '--exclude-if-present', '.NOBACKUP', '--exclude-if-present', '00-NOBACKUP', self.repository_location + '::test', 'input')
  465. with changedir('output'):
  466. self.cmd('extract', self.repository_location + '::test')
  467. self.assert_equal(sorted(os.listdir('output/input')), ['file1', 'tagged3'])
  468. def test_exclude_keep_tagged(self):
  469. self.cmd('init', self.repository_location)
  470. self.create_regular_file('file0', size=1024)
  471. self.create_regular_file('tagged1/.NOBACKUP1')
  472. self.create_regular_file('tagged1/file1', size=1024)
  473. self.create_regular_file('tagged2/.NOBACKUP2')
  474. self.create_regular_file('tagged2/file2', size=1024)
  475. self.create_regular_file('tagged3/CACHEDIR.TAG', contents = b'Signature: 8a477f597d28d172789f06886806bc55 extra stuff')
  476. self.create_regular_file('tagged3/file3', size=1024)
  477. self.create_regular_file('taggedall/.NOBACKUP1')
  478. self.create_regular_file('taggedall/.NOBACKUP2')
  479. self.create_regular_file('taggedall/CACHEDIR.TAG', contents = b'Signature: 8a477f597d28d172789f06886806bc55 extra stuff')
  480. self.create_regular_file('taggedall/file4', size=1024)
  481. self.cmd('create', '--exclude-if-present', '.NOBACKUP1', '--exclude-if-present', '.NOBACKUP2',
  482. '--exclude-caches', '--keep-tag-files', self.repository_location + '::test', 'input')
  483. with changedir('output'):
  484. self.cmd('extract', self.repository_location + '::test')
  485. self.assert_equal(sorted(os.listdir('output/input')), ['file0', 'tagged1', 'tagged2', 'tagged3', 'taggedall'])
  486. self.assert_equal(os.listdir('output/input/tagged1'), ['.NOBACKUP1'])
  487. self.assert_equal(os.listdir('output/input/tagged2'), ['.NOBACKUP2'])
  488. self.assert_equal(os.listdir('output/input/tagged3'), ['CACHEDIR.TAG'])
  489. self.assert_equal(sorted(os.listdir('output/input/taggedall')),
  490. ['.NOBACKUP1', '.NOBACKUP2', 'CACHEDIR.TAG', ])
  491. def test_path_normalization(self):
  492. self.cmd('init', self.repository_location)
  493. self.create_regular_file('dir1/dir2/file', size=1024 * 80)
  494. with changedir('input/dir1/dir2'):
  495. self.cmd('create', self.repository_location + '::test', '../../../input/dir1/../dir1/dir2/..')
  496. output = self.cmd('list', self.repository_location + '::test')
  497. self.assert_not_in('..', output)
  498. self.assert_in(' input/dir1/dir2/file', output)
  499. def test_exclude_normalization(self):
  500. self.cmd('init', self.repository_location)
  501. self.create_regular_file('file1', size=1024 * 80)
  502. self.create_regular_file('file2', size=1024 * 80)
  503. with changedir('input'):
  504. self.cmd('create', '--exclude=file1', self.repository_location + '::test1', '.')
  505. with changedir('output'):
  506. self.cmd('extract', self.repository_location + '::test1')
  507. self.assert_equal(sorted(os.listdir('output')), ['file2'])
  508. with changedir('input'):
  509. self.cmd('create', '--exclude=./file1', self.repository_location + '::test2', '.')
  510. with changedir('output'):
  511. self.cmd('extract', self.repository_location + '::test2')
  512. self.assert_equal(sorted(os.listdir('output')), ['file2'])
  513. self.cmd('create', '--exclude=input/./file1', self.repository_location + '::test3', 'input')
  514. with changedir('output'):
  515. self.cmd('extract', self.repository_location + '::test3')
  516. self.assert_equal(sorted(os.listdir('output/input')), ['file2'])
  517. def test_repeated_files(self):
  518. self.create_regular_file('file1', size=1024 * 80)
  519. self.cmd('init', self.repository_location)
  520. self.cmd('create', self.repository_location + '::test', 'input', 'input')
  521. def test_overwrite(self):
  522. self.create_regular_file('file1', size=1024 * 80)
  523. self.create_regular_file('dir2/file2', size=1024 * 80)
  524. self.cmd('init', self.repository_location)
  525. self.cmd('create', self.repository_location + '::test', 'input')
  526. # Overwriting regular files and directories should be supported
  527. os.mkdir('output/input')
  528. os.mkdir('output/input/file1')
  529. os.mkdir('output/input/dir2')
  530. with changedir('output'):
  531. self.cmd('extract', self.repository_location + '::test')
  532. self.assert_dirs_equal('input', 'output/input')
  533. # But non-empty dirs should fail
  534. os.unlink('output/input/file1')
  535. os.mkdir('output/input/file1')
  536. os.mkdir('output/input/file1/dir')
  537. with changedir('output'):
  538. self.cmd('extract', self.repository_location + '::test', exit_code=1)
  539. def test_rename(self):
  540. self.create_regular_file('file1', size=1024 * 80)
  541. self.create_regular_file('dir2/file2', size=1024 * 80)
  542. self.cmd('init', self.repository_location)
  543. self.cmd('create', self.repository_location + '::test', 'input')
  544. self.cmd('create', self.repository_location + '::test.2', 'input')
  545. self.cmd('extract', '--dry-run', self.repository_location + '::test')
  546. self.cmd('extract', '--dry-run', self.repository_location + '::test.2')
  547. self.cmd('rename', self.repository_location + '::test', 'test.3')
  548. self.cmd('extract', '--dry-run', self.repository_location + '::test.2')
  549. self.cmd('rename', self.repository_location + '::test.2', 'test.4')
  550. self.cmd('extract', '--dry-run', self.repository_location + '::test.3')
  551. self.cmd('extract', '--dry-run', self.repository_location + '::test.4')
  552. # Make sure both archives have been renamed
  553. repository = Repository(self.repository_path)
  554. manifest, key = Manifest.load(repository)
  555. self.assert_equal(len(manifest.archives), 2)
  556. self.assert_in('test.3', manifest.archives)
  557. self.assert_in('test.4', manifest.archives)
  558. def test_delete(self):
  559. self.create_regular_file('file1', size=1024 * 80)
  560. self.create_regular_file('dir2/file2', size=1024 * 80)
  561. self.cmd('init', self.repository_location)
  562. self.cmd('create', self.repository_location + '::test', 'input')
  563. self.cmd('create', self.repository_location + '::test.2', 'input')
  564. self.cmd('extract', '--dry-run', self.repository_location + '::test')
  565. self.cmd('extract', '--dry-run', self.repository_location + '::test.2')
  566. self.cmd('delete', self.repository_location + '::test')
  567. self.cmd('extract', '--dry-run', self.repository_location + '::test.2')
  568. self.cmd('delete', '--stats', self.repository_location + '::test.2')
  569. # Make sure all data except the manifest has been deleted
  570. repository = Repository(self.repository_path)
  571. self.assert_equal(len(repository), 1)
  572. def test_delete_repo(self):
  573. self.create_regular_file('file1', size=1024 * 80)
  574. self.create_regular_file('dir2/file2', size=1024 * 80)
  575. self.cmd('init', self.repository_location)
  576. self.cmd('create', self.repository_location + '::test', 'input')
  577. self.cmd('create', self.repository_location + '::test.2', 'input')
  578. self.cmd('delete', self.repository_location)
  579. # Make sure the repo is gone
  580. self.assertFalse(os.path.exists(self.repository_path))
  581. def test_corrupted_repository(self):
  582. self.cmd('init', self.repository_location)
  583. self.create_src_archive('test')
  584. self.cmd('extract', '--dry-run', self.repository_location + '::test')
  585. self.cmd('check', self.repository_location)
  586. name = sorted(os.listdir(os.path.join(self.tmpdir, 'repository', 'data', '0')), reverse=True)[0]
  587. with open(os.path.join(self.tmpdir, 'repository', 'data', '0', name), 'r+b') as fd:
  588. fd.seek(100)
  589. fd.write(b'XXXX')
  590. self.cmd('check', self.repository_location, exit_code=1)
  591. # we currently need to be able to create a lock directory inside the repo:
  592. @pytest.mark.xfail(reason="we need to be able to create the lock directory inside the repo")
  593. def test_readonly_repository(self):
  594. self.cmd('init', self.repository_location)
  595. self.create_src_archive('test')
  596. os.system('chmod -R ugo-w ' + self.repository_path)
  597. try:
  598. self.cmd('extract', '--dry-run', self.repository_location + '::test')
  599. finally:
  600. # Restore permissions so shutil.rmtree is able to delete it
  601. os.system('chmod -R u+w ' + self.repository_path)
  602. def test_umask(self):
  603. self.create_regular_file('file1', size=1024 * 80)
  604. self.cmd('init', self.repository_location)
  605. self.cmd('create', self.repository_location + '::test', 'input')
  606. mode = os.stat(self.repository_path).st_mode
  607. self.assertEqual(stat.S_IMODE(mode), 0o700)
  608. def test_create_dry_run(self):
  609. self.cmd('init', self.repository_location)
  610. self.cmd('create', '--dry-run', self.repository_location + '::test', 'input')
  611. # Make sure no archive has been created
  612. repository = Repository(self.repository_path)
  613. manifest, key = Manifest.load(repository)
  614. self.assert_equal(len(manifest.archives), 0)
  615. def test_progress(self):
  616. self.create_regular_file('file1', size=1024 * 80)
  617. self.cmd('init', self.repository_location)
  618. # progress forced on
  619. output = self.cmd('create', '--progress', self.repository_location + '::test4', 'input')
  620. self.assert_in("\r", output)
  621. # progress forced off
  622. output = self.cmd('create', '--no-progress', self.repository_location + '::test5', 'input')
  623. self.assert_not_in("\r", output)
  624. @unittest.skipUnless(sys.stdout.isatty(), 'need a tty to test auto-detection')
  625. def test_progress_tty(self):
  626. """test that the --progress and --no-progress flags work,
  627. overriding defaults from the terminal auto-detection"""
  628. self.create_regular_file('file1', size=1024 * 80)
  629. self.cmd('init', self.repository_location)
  630. # without a terminal, no progress expected
  631. output = self.cmd('create', self.repository_location + '::test1', 'input', fork=False)
  632. self.assert_not_in("\r", output)
  633. # with a terminal, progress expected
  634. output = self.cmd('create', self.repository_location + '::test2', 'input', fork=True)
  635. self.assert_in("\r", output)
  636. # without a terminal, progress forced on
  637. output = self.cmd('create', '--progress', self.repository_location + '::test3', 'input', fork=False)
  638. self.assert_in("\r", output)
  639. # with a terminal, progress forced on
  640. output = self.cmd('create', '--progress', self.repository_location + '::test4', 'input', fork=True)
  641. self.assert_in("\r", output)
  642. # without a terminal, progress forced off
  643. output = self.cmd('create', '--no-progress', self.repository_location + '::test5', 'input', fork=False)
  644. self.assert_not_in("\r", output)
  645. # with a terminal, progress forced off
  646. output = self.cmd('create', '--no-progress', self.repository_location + '::test6', 'input', fork=True)
  647. self.assert_not_in("\r", output)
  648. def test_file_status(self):
  649. """test that various file status show expected results
  650. clearly incomplete: only tests for the weird "unchanged" status for now"""
  651. now = time.time()
  652. self.create_regular_file('file1', size=1024 * 80)
  653. os.utime('input/file1', (now - 5, now - 5)) # 5 seconds ago
  654. self.create_regular_file('file2', size=1024 * 80)
  655. self.cmd('init', self.repository_location)
  656. output = self.cmd('create', '-v', self.repository_location + '::test', 'input')
  657. self.assert_in("A input/file1", output)
  658. self.assert_in("A input/file2", output)
  659. # should find first file as unmodified
  660. output = self.cmd('create', '-v', self.repository_location + '::test1', 'input')
  661. self.assert_in("U input/file1", output)
  662. # this is expected, although surprising, for why, see:
  663. # http://borgbackup.readthedocs.org/en/latest/faq.html#i-am-seeing-a-added-status-for-a-unchanged-file
  664. self.assert_in("A input/file2", output)
  665. def test_create_topical(self):
  666. now = time.time()
  667. self.create_regular_file('file1', size=1024 * 80)
  668. os.utime('input/file1', (now-5, now-5))
  669. self.create_regular_file('file2', size=1024 * 80)
  670. self.cmd('init', self.repository_location)
  671. # no listing by default
  672. output = self.cmd('create', self.repository_location + '::test', 'input')
  673. self.assert_not_in('file1', output)
  674. # shouldn't be listed even if unchanged
  675. output = self.cmd('create', self.repository_location + '::test0', 'input')
  676. self.assert_not_in('file1', output)
  677. # should list the file as unchanged
  678. output = self.cmd('create', '-v', '--filter=U', self.repository_location + '::test1', 'input')
  679. self.assert_in('file1', output)
  680. # should *not* list the file as changed
  681. output = self.cmd('create', '-v', '--filter=AM', self.repository_location + '::test2', 'input')
  682. self.assert_not_in('file1', output)
  683. # change the file
  684. self.create_regular_file('file1', size=1024 * 100)
  685. # should list the file as changed
  686. output = self.cmd('create', '-v', '--filter=AM', self.repository_location + '::test3', 'input')
  687. self.assert_in('file1', output)
  688. def test_cmdline_compatibility(self):
  689. self.create_regular_file('file1', size=1024 * 80)
  690. self.cmd('init', self.repository_location)
  691. self.cmd('create', self.repository_location + '::test', 'input')
  692. output = self.cmd('verify', '-v', self.repository_location + '::test')
  693. self.assert_in('"borg verify" has been deprecated', output)
  694. output = self.cmd('prune', self.repository_location, '--hourly=1')
  695. self.assert_in('"--hourly" has been deprecated. Use "--keep-hourly" instead', output)
  696. def test_prune_repository(self):
  697. self.cmd('init', self.repository_location)
  698. self.cmd('create', self.repository_location + '::test1', src_dir)
  699. self.cmd('create', self.repository_location + '::test2', src_dir)
  700. output = self.cmd('prune', '-v', '--dry-run', self.repository_location, '--keep-daily=2')
  701. self.assert_in('Keeping archive: test2', output)
  702. self.assert_in('Would prune: test1', output)
  703. output = self.cmd('list', self.repository_location)
  704. self.assert_in('test1', output)
  705. self.assert_in('test2', output)
  706. self.cmd('prune', self.repository_location, '--keep-daily=2')
  707. output = self.cmd('list', self.repository_location)
  708. self.assert_not_in('test1', output)
  709. self.assert_in('test2', output)
  710. def test_prune_repository_save_space(self):
  711. self.cmd('init', self.repository_location)
  712. self.cmd('create', self.repository_location + '::test1', src_dir)
  713. self.cmd('create', self.repository_location + '::test2', src_dir)
  714. output = self.cmd('prune', '-v', '--dry-run', self.repository_location, '--keep-daily=2')
  715. self.assert_in('Keeping archive: test2', output)
  716. self.assert_in('Would prune: test1', output)
  717. output = self.cmd('list', self.repository_location)
  718. self.assert_in('test1', output)
  719. self.assert_in('test2', output)
  720. self.cmd('prune', '--save-space', self.repository_location, '--keep-daily=2')
  721. output = self.cmd('list', self.repository_location)
  722. self.assert_not_in('test1', output)
  723. self.assert_in('test2', output)
  724. def test_prune_repository_prefix(self):
  725. self.cmd('init', self.repository_location)
  726. self.cmd('create', self.repository_location + '::foo-2015-08-12-10:00', src_dir)
  727. self.cmd('create', self.repository_location + '::foo-2015-08-12-20:00', src_dir)
  728. self.cmd('create', self.repository_location + '::bar-2015-08-12-10:00', src_dir)
  729. self.cmd('create', self.repository_location + '::bar-2015-08-12-20:00', src_dir)
  730. output = self.cmd('prune', '-v', '--dry-run', self.repository_location, '--keep-daily=2', '--prefix=foo-')
  731. self.assert_in('Keeping archive: foo-2015-08-12-20:00', output)
  732. self.assert_in('Would prune: foo-2015-08-12-10:00', output)
  733. output = self.cmd('list', self.repository_location)
  734. self.assert_in('foo-2015-08-12-10:00', output)
  735. self.assert_in('foo-2015-08-12-20:00', output)
  736. self.assert_in('bar-2015-08-12-10:00', output)
  737. self.assert_in('bar-2015-08-12-20:00', output)
  738. self.cmd('prune', self.repository_location, '--keep-daily=2', '--prefix=foo-')
  739. output = self.cmd('list', self.repository_location)
  740. self.assert_not_in('foo-2015-08-12-10:00', output)
  741. self.assert_in('foo-2015-08-12-20:00', output)
  742. self.assert_in('bar-2015-08-12-10:00', output)
  743. self.assert_in('bar-2015-08-12-20:00', output)
  744. def test_list_prefix(self):
  745. self.cmd('init', self.repository_location)
  746. self.cmd('create', self.repository_location + '::test-1', src_dir)
  747. self.cmd('create', self.repository_location + '::something-else-than-test-1', src_dir)
  748. self.cmd('create', self.repository_location + '::test-2', src_dir)
  749. output = self.cmd('list', '--prefix=test-', self.repository_location)
  750. self.assert_in('test-1', output)
  751. self.assert_in('test-2', output)
  752. self.assert_not_in('something-else', output)
  753. def test_break_lock(self):
  754. self.cmd('init', self.repository_location)
  755. self.cmd('break-lock', self.repository_location)
  756. def test_usage(self):
  757. if self.FORK_DEFAULT:
  758. self.cmd(exit_code=0)
  759. self.cmd('-h', exit_code=0)
  760. else:
  761. self.assert_raises(SystemExit, lambda: self.cmd())
  762. self.assert_raises(SystemExit, lambda: self.cmd('-h'))
  763. def test_help(self):
  764. assert 'Borg' in self.cmd('help')
  765. assert 'patterns' in self.cmd('help', 'patterns')
  766. assert 'Initialize' in self.cmd('help', 'init')
  767. assert 'positional arguments' not in self.cmd('help', 'init', '--epilog-only')
  768. assert 'This command initializes' not in self.cmd('help', 'init', '--usage-only')
  769. @unittest.skipUnless(has_llfuse, 'llfuse not installed')
  770. def test_fuse_mount_repository(self):
  771. mountpoint = os.path.join(self.tmpdir, 'mountpoint')
  772. os.mkdir(mountpoint)
  773. self.cmd('init', self.repository_location)
  774. self.create_test_files()
  775. self.cmd('create', self.repository_location + '::archive', 'input')
  776. self.cmd('create', self.repository_location + '::archive2', 'input')
  777. try:
  778. self.cmd('mount', self.repository_location, mountpoint, fork=True)
  779. self.wait_for_mount(mountpoint)
  780. self.assert_dirs_equal(self.input_path, os.path.join(mountpoint, 'archive', 'input'))
  781. self.assert_dirs_equal(self.input_path, os.path.join(mountpoint, 'archive2', 'input'))
  782. finally:
  783. if sys.platform.startswith('linux'):
  784. os.system('fusermount -u ' + mountpoint)
  785. else:
  786. os.system('umount ' + mountpoint)
  787. os.rmdir(mountpoint)
  788. # Give the daemon some time to exit
  789. time.sleep(.2)
  790. @unittest.skipUnless(has_llfuse, 'llfuse not installed')
  791. def test_fuse_mount_archive(self):
  792. mountpoint = os.path.join(self.tmpdir, 'mountpoint')
  793. os.mkdir(mountpoint)
  794. self.cmd('init', self.repository_location)
  795. self.create_test_files()
  796. self.cmd('create', self.repository_location + '::archive', 'input')
  797. try:
  798. self.cmd('mount', self.repository_location + '::archive', mountpoint, fork=True)
  799. self.wait_for_mount(mountpoint)
  800. self.assert_dirs_equal(self.input_path, os.path.join(mountpoint, 'input'))
  801. finally:
  802. if sys.platform.startswith('linux'):
  803. os.system('fusermount -u ' + mountpoint)
  804. else:
  805. os.system('umount ' + mountpoint)
  806. os.rmdir(mountpoint)
  807. # Give the daemon some time to exit
  808. time.sleep(.2)
  809. def verify_aes_counter_uniqueness(self, method):
  810. seen = set() # Chunks already seen
  811. used = set() # counter values already used
  812. def verify_uniqueness():
  813. repository = Repository(self.repository_path)
  814. for key, _ in repository.open_index(repository.get_transaction_id()).iteritems():
  815. data = repository.get(key)
  816. hash = sha256(data).digest()
  817. if hash not in seen:
  818. seen.add(hash)
  819. num_blocks = num_aes_blocks(len(data) - 41)
  820. nonce = bytes_to_long(data[33:41])
  821. for counter in range(nonce, nonce + num_blocks):
  822. self.assert_not_in(counter, used)
  823. used.add(counter)
  824. self.create_test_files()
  825. os.environ['BORG_PASSPHRASE'] = 'passphrase'
  826. self.cmd('init', '--encryption=' + method, self.repository_location)
  827. verify_uniqueness()
  828. self.cmd('create', self.repository_location + '::test', 'input')
  829. verify_uniqueness()
  830. self.cmd('create', self.repository_location + '::test.2', 'input')
  831. verify_uniqueness()
  832. self.cmd('delete', self.repository_location + '::test.2')
  833. verify_uniqueness()
  834. self.assert_equal(used, set(range(len(used))))
  835. def test_aes_counter_uniqueness_keyfile(self):
  836. self.verify_aes_counter_uniqueness('keyfile')
  837. def test_aes_counter_uniqueness_passphrase(self):
  838. self.verify_aes_counter_uniqueness('passphrase')
  839. def test_debug_dump_archive_items(self):
  840. self.create_test_files()
  841. self.cmd('init', self.repository_location)
  842. self.cmd('create', self.repository_location + '::test', 'input')
  843. with changedir('output'):
  844. output = self.cmd('debug-dump-archive-items', self.repository_location + '::test')
  845. output_dir = sorted(os.listdir('output'))
  846. assert len(output_dir) > 0 and output_dir[0].startswith('000000_')
  847. assert 'Done.' in output
  848. def test_debug_put_get_delete_obj(self):
  849. self.cmd('init', self.repository_location)
  850. data = b'some data'
  851. hexkey = sha256(data).hexdigest()
  852. self.create_regular_file('file', contents=data)
  853. output = self.cmd('debug-put-obj', self.repository_location, 'input/file')
  854. assert hexkey in output
  855. output = self.cmd('debug-get-obj', self.repository_location, hexkey, 'output/file')
  856. assert hexkey in output
  857. with open('output/file', 'rb') as f:
  858. data_read = f.read()
  859. assert data == data_read
  860. output = self.cmd('debug-delete-obj', self.repository_location, hexkey)
  861. assert "deleted" in output
  862. output = self.cmd('debug-delete-obj', self.repository_location, hexkey)
  863. assert "not found" in output
  864. output = self.cmd('debug-delete-obj', self.repository_location, 'invalid')
  865. assert "is invalid" in output
  866. @unittest.skipUnless('binary' in BORG_EXES, 'no borg.exe available')
  867. class ArchiverTestCaseBinary(ArchiverTestCase):
  868. EXE = 'borg.exe'
  869. FORK_DEFAULT = True
  870. class ArchiverCheckTestCase(ArchiverTestCaseBase):
  871. def setUp(self):
  872. super().setUp()
  873. with patch.object(ChunkBuffer, 'BUFFER_SIZE', 10):
  874. self.cmd('init', self.repository_location)
  875. self.create_src_archive('archive1')
  876. self.create_src_archive('archive2')
  877. def open_archive(self, name):
  878. repository = Repository(self.repository_path)
  879. manifest, key = Manifest.load(repository)
  880. archive = Archive(repository, key, manifest, name)
  881. return archive, repository
  882. def test_check_usage(self):
  883. output = self.cmd('check', '-v', self.repository_location, exit_code=0)
  884. self.assert_in('Starting repository check', output)
  885. self.assert_in('Starting archive consistency check', output)
  886. output = self.cmd('check', '-v', '--repository-only', self.repository_location, exit_code=0)
  887. self.assert_in('Starting repository check', output)
  888. self.assert_not_in('Starting archive consistency check', output)
  889. output = self.cmd('check', '-v', '--archives-only', self.repository_location, exit_code=0)
  890. self.assert_not_in('Starting repository check', output)
  891. self.assert_in('Starting archive consistency check', output)
  892. def test_missing_file_chunk(self):
  893. archive, repository = self.open_archive('archive1')
  894. for item in archive.iter_items():
  895. if item[b'path'].endswith('testsuite/archiver.py'):
  896. repository.delete(item[b'chunks'][-1][0])
  897. break
  898. repository.commit()
  899. self.cmd('check', self.repository_location, exit_code=1)
  900. self.cmd('check', '--repair', self.repository_location, exit_code=0)
  901. self.cmd('check', self.repository_location, exit_code=0)
  902. def test_missing_archive_item_chunk(self):
  903. archive, repository = self.open_archive('archive1')
  904. repository.delete(archive.metadata[b'items'][-5])
  905. repository.commit()
  906. self.cmd('check', self.repository_location, exit_code=1)
  907. self.cmd('check', '--repair', self.repository_location, exit_code=0)
  908. self.cmd('check', self.repository_location, exit_code=0)
  909. def test_missing_archive_metadata(self):
  910. archive, repository = self.open_archive('archive1')
  911. repository.delete(archive.id)
  912. repository.commit()
  913. self.cmd('check', self.repository_location, exit_code=1)
  914. self.cmd('check', '--repair', self.repository_location, exit_code=0)
  915. self.cmd('check', self.repository_location, exit_code=0)
  916. def test_missing_manifest(self):
  917. archive, repository = self.open_archive('archive1')
  918. repository.delete(Manifest.MANIFEST_ID)
  919. repository.commit()
  920. self.cmd('check', self.repository_location, exit_code=1)
  921. output = self.cmd('check', '-v', '--repair', self.repository_location, exit_code=0)
  922. self.assert_in('archive1', output)
  923. self.assert_in('archive2', output)
  924. self.cmd('check', self.repository_location, exit_code=0)
  925. def test_extra_chunks(self):
  926. self.cmd('check', self.repository_location, exit_code=0)
  927. repository = Repository(self.repository_location)
  928. repository.put(b'01234567890123456789012345678901', b'xxxx')
  929. repository.commit()
  930. repository.close()
  931. self.cmd('check', self.repository_location, exit_code=1)
  932. self.cmd('check', self.repository_location, exit_code=1)
  933. self.cmd('check', '--repair', self.repository_location, exit_code=0)
  934. self.cmd('check', self.repository_location, exit_code=0)
  935. self.cmd('extract', '--dry-run', self.repository_location + '::archive1', exit_code=0)
  936. class RemoteArchiverTestCase(ArchiverTestCase):
  937. prefix = '__testsuite__:'
  938. def test_remote_repo_restrict_to_path(self):
  939. self.cmd('init', self.repository_location)
  940. path_prefix = os.path.dirname(self.repository_path)
  941. with patch.object(RemoteRepository, 'extra_test_args', ['--restrict-to-path', '/foo']):
  942. self.assert_raises(PathNotAllowed, lambda: self.cmd('init', self.repository_location + '_1'))
  943. with patch.object(RemoteRepository, 'extra_test_args', ['--restrict-to-path', path_prefix]):
  944. self.cmd('init', self.repository_location + '_2')
  945. with patch.object(RemoteRepository, 'extra_test_args', ['--restrict-to-path', '/foo', '--restrict-to-path', path_prefix]):
  946. self.cmd('init', self.repository_location + '_3')
  947. # skip fuse tests here, they deadlock since this change in exec_cmd:
  948. # -output = subprocess.check_output(borg + args, stderr=None)
  949. # +output = subprocess.check_output(borg + args, stderr=subprocess.STDOUT)
  950. # this was introduced because some tests expect stderr contents to show up
  951. # in "output" also. Also, the non-forking exec_cmd catches both, too.
  952. @unittest.skip('deadlock issues')
  953. def test_fuse_mount_repository(self):
  954. pass
  955. @unittest.skip('deadlock issues')
  956. def test_fuse_mount_archive(self):
  957. pass
  958. @unittest.skip('only works locally')
  959. def test_debug_put_get_delete_obj(self):
  960. pass