This repository has been archived by the owner on Nov 3, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
tests.py
1438 lines (1171 loc) · 43.4 KB
/
tests.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import unittest
import os
import tempfile
import shutil
import datetime
import subprocess
import psycopg2
import bz2
import pwd
import grp
import sys
import multiprocessing
import re
from io import StringIO
import btw_backup.__main__ as main
from btw_backup.sync import SyncState, S3
from btw_backup.errors import ImproperlyConfigured
backup_env = dict(os.environ)
class Backup(object):
def __init__(self, args):
self.args = args
full_args = ["python", "-m", "btw_backup",
"--config-dir=" + config_dir] + args
proc = subprocess.Popen(full_args, stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
env=backup_env)
self.proc = proc
self.stdout = proc.stdout
self.stderr = proc.stderr
@property
def outstr(self):
return self.stdout.read().strip()
@property
def errstr(self):
return self.stderr.read().strip()
@property
def exitcode(self):
return self.proc.returncode
def join(self):
return self.proc.wait()
tmpdir = None
root_dir = None
config_dir = None
server = None
server_dir = None
s3cmd_config_path = None
preserve = os.environ.get("NOCLEANUP")
def check_aws_profile(profile):
args = ["aws", "configure", "list"]
if profile is not None:
args += ["--profile", profile]
failed = False
if profile is None:
stdout = subprocess.check_output(args,
env=backup_env)
# This is crude but it works.
failed = (stdout.decode("utf8") != """\
Name Value Type Location
---- ----- ---- --------
profile <not set> None None
access_key <not set> None None
secret_key <not set> None None
region <not set> None None
""")
else:
child = subprocess.Popen(args, stdout=subprocess.PIPE,
stderr=subprocess.PIPE, env=backup_env)
child.wait()
failed = child.returncode == 0
stdout = child.stdout.read()
if failed:
print(stdout, file=sys.stderr)
raise ValueError("there is a {0} aws profile!"
.format(profile or "default"))
def setUp():
# pylint: disable=global-statement
global tmpdir
global root_dir
global config_dir
global server
global server_dir
global s3cmd_config_path
tmpdir = tempfile.mkdtemp()
backup_env["HOME"] = tmpdir
# We do a double check to make sure we are not going to interfere
# with the configuration of the user running the tests.
check_aws_profile(None)
check_aws_profile("btw-backup-test")
root_dir = os.path.join(tmpdir, "root")
config_dir = os.path.join(tmpdir, "config_dir")
server_dir = os.path.join(tmpdir, "server")
os.mkdir(server_dir)
os.mkdir(root_dir)
# Start a fake aws server
server_host = "localhost"
server_port = 4999
server_endpoint = "http://{0}:{1}".format(server_host, server_port)
server = subprocess.Popen(["./node_modules/.bin/s3rver", "-p",
str(server_port),
"-s", # Silent
"-d", server_dir])
# Make btw-backup connect to our server.
backup_env["BTW_BACKUP_S3_SERVER"] = server_endpoint
# Create a test profile for awscli
aws_dir = os.path.join(tmpdir, ".aws")
os.mkdir(aws_dir)
with open(os.path.join(aws_dir, "config"), 'w') as config:
# Yes, the config file needs [profile <profile name>] whereas
# the credential files needs [<profile name>]. Go figure!
config.write("""
[profile btw-backup-test]
region=us-east-1
output=json
""")
with open(os.path.join(aws_dir, "credentials"), 'w') as config:
config.write("""
[btw-backup-test]
aws_access_key_id=S3RVER
aws_secret_access_key=S3RVER
""")
subprocess.check_call(["aws", "s3",
"--endpoint=" + server_endpoint,
"--profile=btw-backup-test", "mb", "s3://foo"],
env=backup_env)
s3cmd_config_path = os.path.join(tmpdir, "s3cmd")
backup_env["S3CMD_CONFIG"] = s3cmd_config_path
with open(s3cmd_config_path, 'w') as config:
config.write("""
[default]
access_key = S3RVER
# access_token = x
add_encoding_exts =
add_headers =
bucket_location = US
ca_certs_file =
cache_file =
check_ssl_certificate = True
check_ssl_hostname = True
cloudfront_host = cloudfront.amazonaws.com
default_mime_type = binary/octet-stream
delay_updates = False
delete_after = False
delete_after_fetch = False
delete_removed = False
dry_run = False
enable_multipart = True
encoding = UTF-8
encrypt = False
expiry_date =
expiry_days =
expiry_prefix =
follow_symlinks = False
force = False
get_continue = False
gpg_command = /usr/bin/gpg
gpg_decrypt = %(gpg_command)s -d --verbose --no-use-agent --batch --yes --passphrase-fd %(passphrase_fd)s -o %(output_file)s %(input_file)s
gpg_encrypt = %(gpg_command)s -c --verbose --no-use-agent --batch --yes --passphrase-fd %(passphrase_fd)s -o %(output_file)s %(input_file)s
gpg_passphrase =
guess_mime_type = True
host_base = {host}:{port}
host_bucket = {host}:{port}
human_readable_sizes = False
invalidate_default_index_on_cf = False
invalidate_default_index_root_on_cf = True
invalidate_on_cf = False
kms_key =
limitrate = 0
list_md5 = False
log_target_prefix =
long_listing = False
max_delete = -1
mime_type =
multipart_chunk_size_mb = 15
multipart_max_chunks = 10000
preserve_attrs = True
progress_meter = True
proxy_host =
proxy_port = 0
put_continue = False
recursive = False
recv_chunk = 65536
reduced_redundancy = False
requester_pays = False
restore_days = 1
secret_key = S3RVER
send_chunk = 65536
server_side_encryption = False
signature_v2 = False
simpledb_host = sdb.amazonaws.com
skip_existing = False
socket_timeout = 300
stats = False
stop_on_error = False
storage_class =
urlencoding_mode = normal
use_https = False
use_mime_magic = True
verbosity = WARNING
website_endpoint = http://%(bucket)s.s3-website-%(location)s.amazonaws.com/
website_error =
website_index = index.html
""".format(host=server_host, port=server_port))
subprocess.check_call(["s3cmd", "ls", "s3://foo"], env=backup_env)
reset_config()
def tearDown():
server.kill()
if tmpdir:
if preserve:
print("TMPDIR:", tmpdir)
else:
shutil.rmtree(tmpdir)
def clean_dir(to_clean):
for entry in os.listdir(to_clean):
path = os.path.join(to_clean, entry)
if os.path.isdir(path):
shutil.rmtree(path)
else:
os.unlink(path)
def reset_config():
if not os.path.exists(config_dir):
os.mkdir(config_dir)
clean_dir(config_dir)
with open(os.path.join(config_dir, "config.py"), 'w') as config:
config.write("""
ROOT_PATH={0}
AWSCLI_PROFILE="btw-backup-test"
S3_URI_PREFIX="s3://foo/backups/"
S3CMD_CONFIG={1}
""".format(repr(root_dir), repr(s3cmd_config_path)))
def reset_tmpdir():
reset_config()
clean_dir(root_dir)
def reset_server():
if not preserve:
clean_dir(server_dir)
# Create the bucket "foo". Yes, we are cheating.
os.mkdir(os.path.join(server_dir, "foo"))
def diff_against_server(path, server_relative_path):
diff_dir = os.path.join(tmpdir, "diff")
done = False
while not done:
os.mkdir(diff_dir)
try:
subprocess.check_call(["aws", "s3", "sync",
"--only-show-errors",
"--profile=btw-backup-test",
"--endpoint=http://localhost:4999",
os.path.join("s3://foo/backups",
server_relative_path),
diff_dir],
env=backup_env)
try:
subprocess.check_call(["diff", "-rN", path, diff_dir])
done = True
except subprocess.CalledProcessError:
import time
time.sleep(2)
print("Trying again")
finally:
shutil.rmtree(diff_dir)
def exists_on_server(file_path):
# s3rver used to just store files with the same name as how they appear to
# s3 clients. But it now stores files as 3 different files on dist. To
# check for the existence of a file we check that one of the internally
# named files exists.
return os.path.exists(os.path.join(server_dir,
"{}._S3rver_object".format(file_path)))
class BackupTestMixin(object):
def __init__(self, *args, **kwargs):
self.tmp_src = None
self.maxDiff = None
super(BackupTestMixin, self).__init__(*args, **kwargs)
def tearDown(self):
if self.tmp_src is not None and os.path.exists(self.tmp_src):
shutil.rmtree(self.tmp_src)
super(BackupTestMixin, self).tearDown()
def assertNoError(self, backup, expected_output="", regexp=False,
dont_compare=False):
backup.join()
ret = backup.outstr.decode("utf8")
self.assertEqual(backup.errstr.decode("utf8"), "")
if not regexp:
self.assertEqual(ret, expected_output)
else:
self.assertRegex(ret, expected_output)
self.assertEqual(backup.exitcode, 0)
if not dont_compare and \
(backup.args[0] in ("db", "fs") or
(backup.args[0] == "sync" and backup.args[1] != "--list")):
self.check_off_site_sync()
return ret
def assertRdiffListOutput(self, backup, expected):
backup.join()
outstr = backup.outstr.decode("utf8")
self.assertEqual(backup.errstr.decode("utf8"), "")
lines = outstr.split("\n")
now = datetime.datetime.utcnow()
max_delta = datetime.timedelta(minutes=1)
parse = lambda x: datetime.datetime.strptime(x, "%Y-%m-%dT%H:%M:%S")
prev_date = None
ret = []
for x in expected:
line = lines.pop(0)
if x == "f":
date = parse(line)
ret.append({"date": date, "incrementals": []})
elif x == "i":
date = parse(line[1:])
ret[-1]["incrementals"].append(date)
else:
raise ValueError("unknown specification: " + x)
self.assertTrue(abs(now - date) <= max_delta,
"the date should be relatively close to "
"our current time")
if prev_date:
self.assertTrue(date > prev_date,
"the dates should be in ascending order")
prev_date = date
self.assertEqual(backup.exitcode, 0)
self.assertEqual(
len(lines), 0, "all lines should be accounted for\n" + outstr)
return ret
def assertTarListOutput(self, backup, expected):
backup.join()
outstr = backup.outstr.decode("utf8")
self.assertEqual(backup.errstr.decode("utf8"), "")
lines = outstr.split("\n")
now = datetime.datetime.utcnow()
max_delta = datetime.timedelta(minutes=1)
parse = lambda x: datetime.datetime.strptime(
x, "%Y-%m-%dT%H:%M:%S.tbz")
prev_date = None
ret = []
for _ in range(0, expected):
line = lines.pop(0)
date = parse(line)
ret.append(date)
self.assertTrue(abs(now - date) <= max_delta,
"the date should be relatively close to "
"our current time")
if prev_date:
self.assertTrue(date > prev_date,
"the dates should be in ascending order")
prev_date = date
self.assertEqual(backup.exitcode, 0)
self.assertEqual(
len(lines), 0, "all lines should be accounted for\n" + outstr)
return ret
def assertError(self, backup, expected_error, expected_status):
backup.join()
self.assertEqual(backup.errstr.decode("utf8"), expected_error)
self.assertEqual(backup.outstr, b"")
self.assertEqual(backup.exitcode, expected_status)
def createSrc(self):
"""
This method requires that the host object have a
``orig_src`` field pointing to the initial source.
"""
new_path = self.tmp_src = os.path.join(tmpdir, "src")
shutil.copytree(self.src, new_path)
return new_path
def modify(self, src):
with open(os.path.join(src, "modified"), "a") as f:
f.write("mod\n")
def init(self, src, name="test"):
backup = Backup(["fs-init", "--type=rdiff", src, name])
out = self.assertNoError(
backup,
r"^btw_backup: created /tmp/.*?/test\..*?$",
regexp=True)
return out[len("btw_backup: created "):]
def list(self, expected):
self.assertRdiffListOutput(Backup(["list", self.dst]), expected)
def check_off_site_sync(self):
diff_against_server(self.dst_full, self.dst)
time_re = re.compile(r"^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}",
re.MULTILINE)
def clean_times(src):
return time_re.sub("2016-01-01T12:00:00", src)
class BaseStateTest(unittest.TestCase):
def setUp(self):
self.maxDiff = None
self.state_path = os.path.join(tmpdir, "test_state")
def tearDown(self):
if os.path.exists(self.state_path):
os.unlink(self.state_path)
reset_tmpdir()
def assertStateFile(self, expected, raw=False):
with open(self.state_path, 'r') as state_file:
actual = state_file.read()
if not raw:
actual = clean_times(actual)
self.assertEqual(actual, expected)
def storeToState(self, store):
with open(self.state_path, 'w') as state_file:
state_file.write(store)
class SyncStateTest(BaseStateTest):
def test_is_mutually_exclusive(self):
state = SyncState(self.state_path)
# We have to do this in a different process because our own process
# can reopen the same file multiple times.
def target():
with self.assertRaises(IOError):
SyncState(self.state_path)
p = multiprocessing.Process(target=target)
p.start()
p.join()
def test_records_state_in_memory(self):
state = SyncState(self.state_path)
state.push_path("a")
state.push_path("b")
state.sync_path("c")
state.sync_path("d")
self.assertEqual(state.current_state, {
"push": ["a", "b"],
"sync": ["c", "d"],
})
state.push_done("a")
state.sync_done("d")
self.assertEqual(state.current_state, {
"push": ["b"],
"sync": ["c"],
})
def test_saves_to_file(self):
state = SyncState(self.state_path)
state.push_path("a")
state.push_path("b")
state.sync_path("c")
state.sync_path("d")
self.assertStateFile("""\
2016-01-01T12:00:00 +push a
2016-01-01T12:00:00 +push b
2016-01-01T12:00:00 +sync c
2016-01-01T12:00:00 +sync d
""")
state.push_done("a")
state.sync_done("d")
self.assertStateFile("""\
2016-01-01T12:00:00 +push a
2016-01-01T12:00:00 +push b
2016-01-01T12:00:00 +sync c
2016-01-01T12:00:00 +sync d
2016-01-01T12:00:00 -push a
2016-01-01T12:00:00 -sync d
""")
def test_does_not_modify_a_file_if_nothing_changes(self):
self.storeToState("""\
2016-01-01T12:00:00 +push a
2016-01-01T12:00:00 +push b
2016-01-01T12:00:00 +sync c
2016-01-01T12:00:00 +sync d
""")
state = SyncState(self.state_path)
state.current_state
self.assertStateFile("""\
2016-01-01T12:00:00 +push a
2016-01-01T12:00:00 +push b
2016-01-01T12:00:00 +sync c
2016-01-01T12:00:00 +sync d
""", raw=True)
def test_reads_from_file(self):
self.storeToState("""\
2016-01-01T12:00:00 +push a
2016-01-01T12:00:00 +push b
2016-01-01T12:00:00 +sync c
2016-01-01T12:00:00 +sync d
""")
state = SyncState(self.state_path).current_state
self.assertEqual(state, {
"push": ["a", "b"],
"sync": ["c", "d"],
})
self.storeToState("""\
2016-01-01T12:00:00 +push a
2016-01-01T12:00:00 +push b
2016-01-01T12:00:00 +sync c
2016-01-01T12:00:00 +sync d
2016-01-01T12:00:00 -push a
2016-01-01T12:00:00 -sync d
""")
state = SyncState(self.state_path).current_state
self.assertEqual(state, {
"push": ["b"],
"sync": ["c"],
})
# This simulates a push that happened on the path "", which is
# a valid path. It is equivalent to ROOT_PATH.
self.storeToState("""\
2016-01-01T12:00:00 +sync \n\
""")
state = SyncState(self.state_path).current_state
self.assertEqual(state, {
"push": [],
"sync": [""],
})
def test_emits_on_push_path(self):
state = SyncState(self.state_path)
paths = []
state.ee.on('push', lambda x: paths.append(x))
state.push_path("a")
self.assertEqual(paths, ["a"])
def test_emits_on_sync_path(self):
state = SyncState(self.state_path)
paths = []
state.ee.on('sync', lambda x: paths.append(x))
state.sync_path("a")
self.assertEqual(paths, ["a"])
class S3Null(S3):
def __init__(self, *args, **kwargs):
super(S3Null, self).__init__(*args, **kwargs)
self._pushed = set()
self._synced = set()
self._fail_on = set()
def _do_push(self, path):
if path in self._fail_on:
raise Exception("faked error: " + path)
self._pushed.add(path)
def _do_sync(self, path):
if path in self._fail_on:
raise Exception("faked error: " + path)
self._synced.add(path)
class S3Test(BaseStateTest):
def test_raises_if_s3_uri_prefix_missing(self):
state = SyncState(self.state_path)
with self.assertRaisesRegex(
ImproperlyConfigured,
r"^you must specify S3_URI_PREFIX in the general "
r"configuration$"):
S3Null({}, state)
def test_raises_if_roo_path_missing(self):
state = SyncState(self.state_path)
with self.assertRaisesRegex(
ImproperlyConfigured,
r"^you must specify ROOT_PATH in the general "
r"configuration$"):
S3Null({
"S3_URI_PREFIX": "foo"
}, state)
def test_raises_error_if_syncing_nonexistent_path(self):
state = SyncState(self.state_path)
s3 = S3Null({
"S3_URI_PREFIX": "s3://foo",
"ROOT_PATH": root_dir,
}, state)
with self.assertRaisesRegex(
ValueError,
r"^trying to sync a non-existent path: nonexistent"):
state.sync_path("nonexistent")
def test_raises_error_if_syncing_a_non_directory(self):
state = SyncState(self.state_path)
s3 = S3Null({
"S3_URI_PREFIX": "s3://foo",
"ROOT_PATH": root_dir,
}, state)
with open(os.path.join(root_dir, "foo"), 'w') as foo:
pass
with self.assertRaisesRegex(
ValueError,
r"^trying to sync a path which is not a directory: foo"):
state.sync_path("foo")
def test_pushes_and_syncs(self):
state = SyncState(self.state_path)
s3 = S3Null({
"S3_URI_PREFIX": "s3://foo",
"ROOT_PATH": root_dir,
}, state)
os.mkdir(os.path.join(root_dir, "server"))
state.sync_path("server")
state.sync_path("")
# We can abuse push_path because pushed paths are not checked.
state.push_path("a")
state.push_path("b")
s3.run()
self.assertEqual(s3._pushed, set(("a", "b")))
self.assertEqual(s3._synced, set(("server", "")))
def test_survives_fatal_errors(self):
state = SyncState(self.state_path)
s3 = S3Null({
"S3_URI_PREFIX": "s3://foo",
"ROOT_PATH": root_dir,
}, state)
os.mkdir(os.path.join(root_dir, "server"))
state.sync_path("server")
state.sync_path("")
# We can abuse push_path because pushed paths are not checked.
state.push_path("a")
state.push_path("b")
stderr = StringIO()
s3._cached_stderr = stderr
s3._fail_on = set(("a", ""))
s3.run()
# Some went through.
self.assertEqual(s3._pushed, set(("b", )))
self.assertEqual(s3._synced, set(("server",)))
# Some failed.
self.assertRegex(
stderr.getvalue(),
re.compile(r"^Error while processing: a$", re.MULTILINE))
self.assertRegex(
stderr.getvalue(),
re.compile(r"^Error while processing: $", re.MULTILINE))
# Those that failed still need to be done.
self.assertEqual(state.current_state, {
"push": ["a"],
"sync": [""],
})
# The state on disk does not show the failures as done.
# The funky "\n\" in what follows is to prevent git from swallowing
# the space at the end of the line.
self.assertStateFile("""\
2016-01-01T12:00:00 +sync server
2016-01-01T12:00:00 +sync \n\
2016-01-01T12:00:00 +push a
2016-01-01T12:00:00 +push b
2016-01-01T12:00:00 -push b
2016-01-01T12:00:00 -sync server
""")
class CommonTests(BackupTestMixin, unittest.TestCase):
def tearDown(self):
reset_tmpdir()
super(CommonTests, self).tearDown()
def test_no_root(self):
open(os.path.join(config_dir, "config.py"), 'w').close()
self.assertError(
Backup(["fs-init", "--type=rdiff", "/tmp", "test"]),
"btw_backup: you must specify ROOT_PATH in the general "
"configuration", 1)
def test_no_s3cmd_config(self):
with open(os.path.join(config_dir, "config.py"), 'w') as config:
config.write("""
ROOT_PATH={0}
S3_URI_PREFIX="q"
""".format(repr(root_dir)))
self.assertError(
Backup(["db", "-g", "test"]),
"btw_backup: you must specify S3CMD_CONFIG in the general "
"configuration", 1)
def test_no_s3_uri_prefix(self):
with open(os.path.join(config_dir, "config.py"), 'w') as config:
config.write("""
ROOT_PATH={0}
S3CMD_CONFIG="q"
""".format(repr(root_dir)))
self.assertError(
Backup(["db", "-g", "test"]),
"btw_backup: you must specify S3_URI_PREFIX in the general "
"configuration", 1)
class FSInitTest(BackupTestMixin, unittest.TestCase):
src = os.path.join(os.getcwd(), "test-data/src")
def tearDown(self):
reset_tmpdir()
super(FSInitTest, self).tearDown()
def test_lacking_all_params(self):
self.assertError(
Backup(["fs-init"]),
"usage: btw_backup fs-init [-h] --type {rdiff,tar} src name\n"
"btw_backup fs-init: error: the following arguments are "
"required: --type, src, name",
2)
def test_lacking_name(self):
self.assertError(
Backup(["fs-init", "."]),
"usage: btw_backup fs-init [-h] --type {rdiff,tar} src name\n"
"btw_backup fs-init: error: the following arguments are "
"required: --type, name",
2)
def test_lacking_type(self):
self.assertError(
Backup(["fs-init", "/", "test"]),
"usage: btw_backup fs-init [-h] --type {rdiff,tar} src name\n"
"btw_backup fs-init: error: the following arguments are "
"required: --type",
2)
def test_not_absolute(self):
self.assertError(Backup(["fs-init", "--type=rdiff", ".", "test"]),
"btw_backup: the source path must be absolute",
1)
def test_new_setup(self):
out = self.assertNoError(
Backup(["fs-init", "--type=rdiff", self.src, "test"]),
r"^btw_backup: created /tmp/.*?/test.uqsE0Q",
regexp=True)
workdir_path = out[len("btw_backup: created "):]
src = os.readlink(os.path.join(workdir_path, "src"))
self.assertEqual(src, self.src)
shutil.rmtree(workdir_path)
def test_duplicate_setup(self):
out = self.assertNoError(
Backup(["fs-init", "--type=rdiff", self.src, "test"]),
r"^btw_backup: created /tmp/.*?/test.uqsE0Q",
regexp=True)
workdir_path = out[len("btw_backup: created "):]
self.assertError(
Backup(["fs-init", "--type=rdiff", self.src, "test2"]),
"btw_backup: there is already a directory for this path",
1)
shutil.rmtree(workdir_path)
class FSRdiffTest(BackupTestMixin, unittest.TestCase):
src = os.path.join(os.getcwd(), "test-data/src")
def setUp(self):
self.dst = "dst"
self.dst_full = os.path.join(root_dir, self.dst)
os.mkdir(self.dst_full)
self.assertNoError(
Backup(["fs-init", "--type=rdiff", self.src, "test"]),
r"^btw_backup: created /tmp/.*?/test.uqsE0Q",
regexp=True)
def tearDown(self):
if os.path.exists(self.dst_full):
shutil.rmtree(self.dst_full)
reset_tmpdir()
reset_server()
super(FSRdiffTest, self).tearDown()
def test_no_setup(self):
reset_tmpdir()
self.assertError(
Backup(["fs", self.src, self.dst]),
"btw_backup: no working directory for: "
"/home/ldd/src/git-repos/btw-backup/test-data/src",
1)
def test_no_params(self):
self.assertError(
Backup(["fs"]),
"usage: btw_backup fs [-h] [-u UID[:GID]] src dst\n"
"btw_backup fs: error: the following arguments are required: src, "
"dst",
2)
def test_no_dst(self):
self.assertError(
Backup(["fs", self.src]),
"usage: btw_backup fs [-h] [-u UID[:GID]] src dst\n"
"btw_backup fs: error: the following arguments are required: dst",
2)
def test_new_backup(self):
self.assertNoError(Backup(["fs", self.src, self.dst]))
backups = self.assertRdiffListOutput(
Backup(["list", self.dst]), "f")
# Check that something was saved!
restore_path = tempfile.mkdtemp(dir=tmpdir)
last_date = backups[-1]["date"].isoformat()
subprocess.check_output(
["rdiff-backup", "-r",
last_date,
os.path.join(self.dst_full, last_date), restore_path])
paths = os.listdir(restore_path)
self.assertEqual(paths, ["backup.tar"])
t_path = os.path.join(restore_path, "t")
os.mkdir(t_path)
subprocess.check_call(["tar", "-C", t_path, "-xf",
os.path.join(restore_path, "backup.tar")])
# Check the files.
subprocess.check_call(["diff", "-rN", t_path, self.src])
def test_incremental_backup(self):
src = self.createSrc()
self.init(src)
self.assertNoError(Backup(["fs", src, self.dst]))
self.modify(src)
self.assertNoError(Backup(["fs", src, self.dst]))
self.assertRdiffListOutput(Backup(["list", self.dst]), "fi")
def test_two_incremental_backups_no_change(self):
src = self.createSrc()
self.init(src)
self.assertNoError(Backup(["fs", src, self.dst]))
self.modify(src)
self.assertNoError(Backup(["fs", src, self.dst]))
self.assertNoError(Backup(["fs", src, self.dst]))
# The second incremental backup did nothing.
self.assertRdiffListOutput(Backup(["list", self.dst]), "fi")
def test_max_incremental_count(self):
src = self.createSrc()
workdir_path = self.init(src)
config_path = os.path.join(workdir_path, "config.py")
with open(config_path, "a") as f:
f.write("MAX_INCREMENTAL_COUNT=1\n")
self.assertNoError(Backup(["fs", src, self.dst]))
self.modify(src)
self.assertNoError(Backup(["fs", src, self.dst]))
self.assertRdiffListOutput(Backup(["list", self.dst]), "fi")
self.modify(src)
self.assertNoError(Backup(["fs", src, self.dst]))
self.assertRdiffListOutput(Backup(["list", self.dst]), "fif")
def test_max_incremental_span(self):
src = self.createSrc()
workdir_path = self.init(src)
config_path = os.path.join(workdir_path, "config.py")
with open(config_path, "a") as f:
f.write("MAX_INCREMENTAL_SPAN='0s'\n")
self.assertNoError(Backup(["fs", src, self.dst]))
self.modify(src)
self.assertNoError(Backup(["fs", src, self.dst]))
self.assertRdiffListOutput(Backup(["list", self.dst]), "ff")
def test_identical_full_backup(self):
src = self.createSrc()
workdir_path = self.init(src)
config_path = os.path.join(workdir_path, "config.py")
with open(config_path, "a") as f:
f.write("MAX_INCREMENTAL_SPAN='0s'\n")
self.assertNoError(Backup(["fs", src, self.dst]))
self.assertNoError(Backup(["fs", src, self.dst]))
# Only one backup.
self.assertRdiffListOutput(Backup(["list", self.dst]), "f")
# Check the log
self.assertRegex(
open(os.path.join(self.dst_full, "log.txt"), 'r').read(),
r"^.*: no change in the data to be backed up: "
"skipping creation of new full backup\n$")
class FSTarTest(BackupTestMixin, unittest.TestCase):
src = os.path.join(os.getcwd(), "test-data/src")
def setUp(self):
self.dst = "dst"
self.dst_full = os.path.join(root_dir, self.dst)
os.mkdir(self.dst_full)
self.assertNoError(
Backup(["fs-init", "--type=tar", self.src, "test"]),
r"^btw_backup: created /tmp/.*?/test.uqsE0Q",
regexp=True)
def tearDown(self):
if os.path.exists(self.dst_full):
shutil.rmtree(self.dst_full)
reset_tmpdir()
reset_server()
super(FSTarTest, self).tearDown()
def init(self, src, name="test"):
backup = Backup(["fs-init", "--type=tar", src, name])
out = self.assertNoError(
backup,
r"^btw_backup: created /tmp/.*?/test\..*?$",
regexp=True)
return out[len("btw_backup: created "):]
def test_no_setup(self):
reset_tmpdir()
self.assertError(
Backup(["fs", self.src, self.dst]),