forked from perforce/p4transfer
-
Notifications
You must be signed in to change notification settings - Fork 3
/
TestP4Transfer.py
executable file
·5184 lines (4189 loc) · 219 KB
/
TestP4Transfer.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
# -*- encoding: UTF8 -*-
# Tests for the P4Transfer.py module.
from __future__ import print_function
import sys
import time
import P4
import subprocess
import inspect
import platform
from textwrap import dedent
import unittest
import os
import shutil
import stat
import re
import glob
import argparse
import datetime
from ruamel.yaml import YAML
# Bring in module to be tested
sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), '..'))
import logutils # noqa: E402
import P4Transfer # noqa: E402
yaml = YAML()
python3 = sys.version_info[0] >= 3
if sys.hexversion < 0x02070000 or (0x0300000 < sys.hexversion < 0x0303000):
sys.exit("Python 2.7 or 3.3 or newer is required to run this program.")
if python3:
from io import StringIO
else:
from StringIO import StringIO
P4D = "p4d" # This can be overridden via command line stuff
P4USER = "testuser"
P4CLIENT = "test_ws"
TEST_ROOT = '_testrun_transfer'
TRANSFER_CLIENT = "transfer"
TRANSFER_CONFIG = "transfer.yaml"
TEST_COUNTER_NAME = "P4Transfer"
INTEG_ENGINE = 3
saved_stdoutput = StringIO()
test_logger = None
def onRmTreeError(function, path, exc_info):
os.chmod(path, stat.S_IWRITE)
os.remove(path)
def ensureDirectory(directory):
if not os.path.isdir(directory):
os.makedirs(directory)
def localDirectory(root, *dirs):
"Create and ensure it exists"
dir_path = os.path.join(root, *dirs)
ensureDirectory(dir_path)
return dir_path
def create_file(file_name, contents):
"Create file with specified contents"
ensureDirectory(os.path.dirname(file_name))
if python3:
contents = bytes(contents.encode())
with open(file_name, 'wb') as f:
f.write(contents)
def append_to_file(file_name, contents):
"Append contents to file"
if python3:
contents = bytes(contents.encode())
with open(file_name, 'ab+') as f:
f.write(contents)
def getP4ConfigFilename():
"Returns os specific filename"
if 'P4CONFIG' in os.environ:
return os.environ['P4CONFIG']
if os.name == "nt":
return "p4config.txt"
return ".p4config"
class P4Server:
def __init__(self, root, logger, caseInsensitive=False):
self.root = root
self.logger = logger
self.server_root = os.path.join(root, "server")
self.client_root = os.path.join(root, "client")
ensureDirectory(self.root)
ensureDirectory(self.server_root)
ensureDirectory(self.client_root)
caseFlag = ""
if caseInsensitive:
caseFlag = "-C1 "
self.p4d = P4D
self.port = "rsh:%s -r \"%s\" -L log %s -i" % (self.p4d, self.server_root, caseFlag)
self.p4 = P4.P4()
self.p4.port = self.port
self.p4.user = P4USER
self.p4.client = P4CLIENT
self.p4.connect()
self.p4cmd('depots') # triggers creation of the user
self.p4cmd('configure', 'set', 'dm.integ.engine=%d' % INTEG_ENGINE)
self.p4.disconnect() # required to pick up the configure changes
self.p4.connect()
self.client_name = P4CLIENT
client = self.p4.fetch_client(self.client_name)
client._root = self.client_root
client._lineend = 'unix'
self.p4.save_client(client)
def shutDown(self):
if self.p4.connected():
self.p4.disconnect()
def createTransferClient(self, name, root):
pass
def run_cmd(self, cmd, dir=".", get_output=True, timeout=35, stop_on_error=True):
"Run cmd logging input and output"
output = ""
try:
self.logger.debug("Running: %s" % cmd)
if get_output:
p = subprocess.Popen(cmd, cwd=dir, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, universal_newlines=True, shell=True)
if python3:
output, _ = p.communicate(timeout=timeout)
else:
output, _ = p.communicate()
# rc = p.returncode
self.logger.debug("Output:\n%s" % output)
else:
result = subprocess.check_call(cmd, stderr=subprocess.STDOUT, shell=True, timeout=timeout)
self.logger.debug('Result: %d' % result)
except subprocess.CalledProcessError as e:
self.logger.debug("Output: %s" % e.output)
if stop_on_error:
msg = 'Failed run_cmd: %d %s' % (e.returncode, str(e))
self.logger.debug(msg)
raise e
except Exception as e:
self.logger.debug("Output: %s" % output)
if stop_on_error:
msg = 'Failed run_cmd: %s' % str(e)
self.logger.debug(msg)
raise e
return output
def enableUnicode(self):
cmd = '%s -r "%s" -L log -vserver=3 -xi' % (self.p4d, self.server_root)
output = self.run_cmd(cmd, dir=self.server_root, get_output=True, stop_on_error=True)
self.logger.debug(output)
def getCounter(self):
"Returns value of counter as integer"
result = self.p4.run('counter', TEST_COUNTER_NAME)
if result and 'counter' in result[0]:
return int(result[0]['value'])
return 0
def p4cmd(self, *args):
"Execute p4 cmd while logging arguments and results"
if not self.logger:
self.logger = logutils.getLogger(P4Transfer.LOGGER_NAME)
self.logger.debug('testp4:', args)
output = self.p4.run(args)
self.logger.debug('testp4r:', output)
return output
class TestP4TransferBase(unittest.TestCase):
"""Base class for tests"""
def __init__(self, methodName='runTest'):
global saved_stdoutput, test_logger
saved_stdoutput.truncate(0)
if test_logger is None:
test_logger = logutils.getLogger(P4Transfer.LOGGER_NAME, stream=saved_stdoutput)
else:
logutils.resetLogger(P4Transfer.LOGGER_NAME)
self.logger = test_logger
super(TestP4TransferBase, self).__init__(methodName=methodName)
def assertRegex(self, *args, **kwargs):
if python3:
return super(TestP4TransferBase, self).assertRegex(*args, **kwargs)
else:
return super(TestP4TransferBase, self).assertRegexpMatches(*args, **kwargs)
def assertContentsEqual(self, expected, content):
if python3:
content = content.decode()
self.assertEqual(expected, content)
def setUp(self):
self.setDirectories()
def tearDown(self):
self.source.shutDown()
self.target.shutDown()
time.sleep(0.1)
# self.cleanupTestTree()
def setDirectories(self, caseInsensitive=False):
self.startdir = os.getcwd()
self.transfer_root = os.path.join(self.startdir, TEST_ROOT)
self.cleanupTestTree()
ensureDirectory(self.transfer_root)
self.source = P4Server(os.path.join(self.transfer_root, 'source'), self.logger, caseInsensitive=caseInsensitive)
self.target = P4Server(os.path.join(self.transfer_root, 'target'), self.logger, caseInsensitive=caseInsensitive)
self.transfer_client_root = localDirectory(self.transfer_root, 'transfer_client')
self.writeP4Config()
def writeP4Config(self):
"Write appropriate files - useful for occasional manual debugging"
p4config_filename = getP4ConfigFilename()
srcP4Config = os.path.join(self.transfer_root, 'source', p4config_filename)
targP4Config = os.path.join(self.transfer_root, 'target', p4config_filename)
transferP4Config = os.path.join(self.transfer_client_root, p4config_filename)
with open(srcP4Config, "w") as fh:
fh.write('P4PORT=%s\n' % self.source.port)
fh.write('P4USER=%s\n' % self.source.p4.user)
fh.write('P4CLIENT=%s\n' % self.source.p4.client)
with open(targP4Config, "w") as fh:
fh.write('P4PORT=%s\n' % self.target.port)
fh.write('P4USER=%s\n' % self.target.p4.user)
fh.write('P4CLIENT=%s\n' % self.target.p4.client)
with open(transferP4Config, "w") as fh:
fh.write('P4PORT=%s\n' % self.target.port)
fh.write('P4USER=%s\n' % self.target.p4.user)
fh.write('P4CLIENT=%s\n' % TRANSFER_CLIENT)
def cleanupTestTree(self):
os.chdir(self.startdir)
if os.path.isdir(self.transfer_root):
shutil.rmtree(self.transfer_root, False, onRmTreeError)
def getDefaultOptions(self):
config = {}
config['transfer_client'] = TRANSFER_CLIENT
config['workspace_root'] = self.transfer_client_root
config['views'] = [{'src': '//depot/inside/...',
'targ': '//depot/import/...'}]
return config
def setupTransfer(self):
"""Creates a config file with default mappings"""
msg = "Test: %s ======================" % inspect.stack()[1][3]
self.logger.debug(msg)
config = self.getDefaultOptions()
self.createConfigFile(options=config)
def createConfigFile(self, srcOptions=None, targOptions=None, options=None):
"Creates config file with extras if appropriate"
if options is None:
options = {}
if srcOptions is None:
srcOptions = {}
if targOptions is None:
targOptions = {}
config = {}
config['source'] = {}
config['source']['p4port'] = self.source.port
config['source']['p4user'] = P4USER
config['source']['p4client'] = TRANSFER_CLIENT
for opt in srcOptions.keys():
config['source'][opt] = srcOptions[opt]
config['target'] = {}
config['target']['p4port'] = self.target.port
config['target']['p4user'] = P4USER
config['target']['p4client'] = TRANSFER_CLIENT
for opt in targOptions.keys():
config['target'][opt] = targOptions[opt]
config['logfile'] = os.path.join(self.transfer_root, 'temp', 'test.log')
if not os.path.exists(os.path.join(self.transfer_root, 'temp')):
os.mkdir(os.path.join(self.transfer_root, 'temp'))
config['counter_name'] = TEST_COUNTER_NAME
for opt in options.keys():
config[opt] = options[opt]
# write the config file
self.transfer_cfg = os.path.join(self.transfer_root, TRANSFER_CONFIG)
with open(self.transfer_cfg, 'w') as f:
yaml.dump(config, f)
def run_P4Transfer(self, *args):
self.logger.debug("-----------------------------Starting P4Transfer")
base_args = ['-c', self.transfer_cfg, '-s']
if args:
base_args.extend(args)
pt = P4Transfer.P4Transfer(*base_args)
result = pt.replicate()
return result
def setTargetCounter(self, value):
"Set's the target counter to specified value"
self.target.p4.run('counter', TEST_COUNTER_NAME, str(value))
def assertCounters(self, sourceValue, targetValue):
sourceCounter = self.target.getCounter()
targetCounter = len(self.target.p4.run("changes"))
self.assertEqual(sourceCounter, sourceValue, "Source counter is not {} but {}".format(sourceValue, sourceCounter))
self.assertEqual(targetCounter, targetValue, "Target counter is not {} but {}".format(targetValue, targetCounter))
def applyJournalPatch(self, jnl_rec):
"Apply journal patch"
jnl_fix = os.path.join(self.source.server_root, "jnl_fix")
create_file(jnl_fix, jnl_rec)
cmd = '%s -r "%s" -jr "%s"' % (self.source.p4d, self.source.server_root, jnl_fix)
self.logger.debug("Cmd: %s" % cmd)
subprocess.check_output(cmd, shell=True)
def dumpDBFiles(self, tables):
"Extract journal records"
all_output = []
for table in tables.split(","):
cmd = '%s -r "%s" -jd - %s' % (self.source.p4d, self.source.server_root, table)
self.logger.debug("Cmd: %s" % cmd)
output = subprocess.check_output(cmd, shell=True, universal_newlines=True)
self.logger.debug("Output: %s" % output)
all_output.append(output)
results = [r for r in "\n".join(all_output).split("\n") if re.search("^@pv@", r)]
return results
class TestP4TransferCaseInsensitive(TestP4TransferBase):
"""Case insensitive version"""
def __init__(self, methodName='runTest'):
global saved_stdoutput, test_logger
saved_stdoutput.truncate(0)
if test_logger is None:
test_logger = logutils.getLogger(P4Transfer.LOGGER_NAME, stream=saved_stdoutput)
else:
logutils.resetLogger(P4Transfer.LOGGER_NAME)
self.logger = test_logger
super(TestP4TransferCaseInsensitive, self).__init__(methodName=methodName)
def setUp(self):
self.setDirectories(caseInsensitive=True)
def testWildcardCharsAndCaseInsensitive(self):
"Test filenames containing Perforce wildcards when required to be case insensitive"
self.setupTransfer()
options = self.getDefaultOptions()
options["case_sensitive"] = "False"
self.createConfigFile(options=options)
inside = localDirectory(self.source.client_root, "inside")
outside = localDirectory(self.source.client_root, "outside")
inside_file1 = os.path.join(inside, "@inside_file1")
inside_file2 = os.path.join(inside, "%inside_file2")
inside_file3 = os.path.join(inside, "#inside_file3")
inside_file4 = os.path.join(inside, "C#", "inside_file4")
outside_file1 = os.path.join(outside, "%outside_file")
inside_file1Fixed = inside_file1.replace("@", "%40")
inside_file2Fixed = inside_file2.replace("%", "%25")
inside_file3Fixed = inside_file3.replace("#", "%23")
inside_file4Fixed = inside_file4.replace("#", "%23")
outside_file1Fixed = outside_file1.replace("%", "%25")
create_file(inside_file1, 'Test content')
create_file(inside_file3, 'Test content')
create_file(inside_file4, 'Test content')
create_file(outside_file1, 'Test content')
self.source.p4cmd('add', '-f', inside_file1)
self.source.p4cmd('add', '-f', inside_file3)
self.source.p4cmd('add', '-f', inside_file4)
self.source.p4cmd('add', '-f', outside_file1)
self.source.p4cmd('submit', '-d', 'files added')
self.source.p4cmd('integrate', outside_file1Fixed, inside_file2Fixed)
self.source.p4cmd('submit', '-d', 'files integrated')
self.source.p4cmd('edit', inside_file1Fixed)
self.source.p4cmd('edit', inside_file3Fixed)
self.source.p4cmd('edit', inside_file4Fixed)
append_to_file(inside_file1, 'Different stuff')
append_to_file(inside_file3, 'Different stuff')
append_to_file(inside_file4, 'Different stuff')
self.source.p4cmd('submit', '-d', 'files modified')
self.source.p4cmd('integrate', "//depot/inside/*", "//depot/inside/new/*")
self.source.p4cmd('submit', '-d', 'files branched')
self.run_P4Transfer()
self.assertCounters(4, 4)
files = self.target.p4cmd('files', '//depot/...')
self.assertEqual(len(files), 7)
self.assertEqual(files[0]['depotFile'], '//depot/import/%23inside_file3')
self.assertEqual(files[1]['depotFile'], '//depot/import/%25inside_file2')
self.assertEqual(files[2]['depotFile'], '//depot/import/%40inside_file1')
self.assertEqual(files[3]['depotFile'], '//depot/import/C%23/inside_file4')
class TestP4Transfer(TestP4TransferBase):
def __init__(self, methodName='runTest'):
global saved_stdoutput, test_logger
saved_stdoutput.truncate(0)
if test_logger is None:
test_logger = logutils.getLogger(P4Transfer.LOGGER_NAME, stream=saved_stdoutput)
else:
logutils.resetLogger(P4Transfer.LOGGER_NAME)
self.logger = test_logger
super(TestP4Transfer, self).__init__(methodName=methodName)
def testArgParsing(self):
"Basic argparsing for the module"
self.setupTransfer()
args = ['-c', self.transfer_cfg, '-s']
pt = P4Transfer.P4Transfer(*args)
self.assertEqual(pt.options.config, self.transfer_cfg)
self.assertTrue(pt.options.stoponerror)
args = ['-c', self.transfer_cfg]
pt = P4Transfer.P4Transfer(*args)
def testArgParsingErrors(self):
"Basic argparsing for the module"
self.setupTransfer()
# args = ['-c', self.transfer_cfg, '--end-datetime', '2020/1/1']
# try:
# self.assertTrue(False, "Failed to get expected exception")
# except Exception as e:
# pass
args = ['-c', self.transfer_cfg, '--end-datetime', '2020/1/1 13:01']
pt = P4Transfer.P4Transfer(*args)
self.assertEqual(pt.options.config, self.transfer_cfg)
self.assertFalse(pt.options.stoponerror)
self.assertEqual(datetime.datetime(2020, 1, 1, 13, 1), pt.options.end_datetime)
self.assertTrue(pt.endDatetimeExceeded())
args = ['-c', self.transfer_cfg, '--end-datetime', '2040/1/1 13:01']
pt = P4Transfer.P4Transfer(*args)
self.assertEqual(pt.options.config, self.transfer_cfg)
self.assertFalse(pt.options.stoponerror)
self.assertEqual(datetime.datetime(2040, 1, 1, 13, 1), pt.options.end_datetime)
self.assertFalse(pt.endDatetimeExceeded())
def testMaximum(self):
"Test only max number of changes are transferred"
self.setupTransfer()
args = ['-c', self.transfer_cfg, '-m1']
pt = P4Transfer.P4Transfer(*args)
self.assertEqual(pt.options.config, self.transfer_cfg)
inside = localDirectory(self.source.client_root, "inside")
inside_file1 = os.path.join(inside, "inside_file1")
create_file(inside_file1, 'Test content')
self.source.p4cmd('add', inside_file1)
desc = 'inside_file1 added'
self.source.p4cmd('submit', '-d', desc)
self.source.p4cmd('edit', inside_file1)
append_to_file(inside_file1, "New line")
desc = 'file edited'
self.source.p4cmd('submit', '-d', desc)
pt.replicate()
self.assertCounters(1, 1)
pt.replicate()
self.assertCounters(2, 2)
def testKTextDigests(self):
"Calculate filesizes and digests for files which might contain keywords"
self.setupTransfer()
filename = os.path.join(self.transfer_root, 'test_file')
create_file(filename, "line1\n")
fileSize, digest = P4Transfer.getKTextDigest(filename)
self.assertEqual(fileSize, 6)
self.assertEqual(digest, "1ddab9058a07abc0db2605ab02a61a00")
create_file(filename, "line1\nline2\n")
fileSize, digest = P4Transfer.getKTextDigest(filename)
self.assertEqual(fileSize, 12)
self.assertEqual(digest, "4fcc82a88ee38e0aa16c17f512c685c9")
create_file(filename, "line1\nsome $Id: //depot/fred.txt#2 $\nline2\n")
fileSize, digest = P4Transfer.getKTextDigest(filename)
self.assertEqual(fileSize, 10)
self.assertEqual(digest, "ce8bc0316bdd8ad1f716f48e5c968854")
create_file(filename, "line1\nsome $Id: //depot/fred.txt#2 $\nanother $Date: somedate$\nline2\n")
fileSize, digest = P4Transfer.getKTextDigest(filename)
self.assertEqual(fileSize, 10)
self.assertEqual(digest, "ce8bc0316bdd8ad1f716f48e5c968854")
create_file(filename, dedent("""\
line1
some $Id: //depot/fred.txt#2 $
another $Date: somedate$
line2
"""))
fileSize, digest = P4Transfer.getKTextDigest(filename)
self.assertEqual(fileSize, 10)
self.assertEqual(digest, "ce8bc0316bdd8ad1f716f48e5c968854")
create_file(filename, dedent("""\
line1
some $Id: //depot/fred.txt#2 $
another $Date: somedata $
another $DateTime: somedata $
another $DateTime: somedata $
$Change: 1234 $
var = "$File: //depot/some/file.txt $";
var = "$Revision: 45 $";
var = "$Author: fred $";
line2
"""))
fileSize, digest = P4Transfer.getKTextDigest(filename)
self.assertEqual(fileSize, 10)
self.assertEqual(digest, "ce8bc0316bdd8ad1f716f48e5c968854")
def testConfigValidation(self):
"Make sure specified config options such as client views are valid"
msg = "Test: %s ======================" % inspect.stack()[0][3]
self.logger.debug(msg)
self.createConfigFile()
msg = ""
try:
base_args = ['-c', self.transfer_cfg, '-s']
pt = P4Transfer.P4Transfer(*base_args)
pt.setupReplicate()
except Exception as e:
msg = str(e)
self.assertRegex(msg, "One of options views/stream_views must be specified")
self.assertRegex(msg, "Option workspace_root must not be blank")
# Integer config related options
config = self.getDefaultOptions()
config['poll_interval'] = 5
config['report_interval'] = "10 * 5"
self.createConfigFile(options=config)
base_args = ['-c', self.transfer_cfg, '-s']
pt = P4Transfer.P4Transfer(*base_args)
pt.setupReplicate()
self.assertEqual(5, pt.options.poll_interval)
self.assertEqual(50, pt.options.report_interval)
# Other streams related validation
config = self.getDefaultOptions()
config['views'] = []
config['stream_views'] = [{'src': '//src_streams/rel*',
'targ': '//targ_streams/rel*',
'type': 'release',
'parent': '//targ_streams/main'}]
self.createConfigFile(options=config)
msg = ""
try:
base_args = ['-c', self.transfer_cfg, '-s']
pt = P4Transfer.P4Transfer(*base_args)
pt.setupReplicate()
except Exception as e:
msg = str(e)
self.assertRegex(msg, "Option transfer_target_stream must be specified if streams are being used")
# Other streams related validation
config = self.getDefaultOptions()
config['views'] = []
config['transfer_target_stream'] = ['//targ_streams/transfer_target_stream']
config['stream_views'] = [{'fred': 'joe'}]
self.createConfigFile(options=config)
msg = ""
try:
base_args = ['-c', self.transfer_cfg, '-s']
pt = P4Transfer.P4Transfer(*base_args)
pt.setupReplicate()
except Exception as e:
msg = str(e)
self.assertRegex(msg, "Missing required field 'src'")
self.assertRegex(msg, "Missing required field 'targ'")
self.assertRegex(msg, "Missing required field 'type'")
self.assertRegex(msg, "Missing required field 'parent'")
# Other streams related validation
config = self.getDefaultOptions()
config['views'] = []
config['transfer_target_stream'] = ['//targ_streams/transfer_target_stream']
config['stream_views'] = [{'src': '//src_streams/*rel*',
'targ': '//targ_streams/rel*',
'type': 'new',
'parent': '//targ_streams/main'}]
self.createConfigFile(options=config)
msg = ""
try:
base_args = ['-c', self.transfer_cfg, '-s']
pt = P4Transfer.P4Transfer(*base_args)
pt.setupReplicate()
except Exception as e:
msg = str(e)
self.assertRegex(msg, "Wildcards need to match")
self.assertRegex(msg, "Stream type 'new' is not one of allowed values")
def testChangeFormatting(self):
"Formatting options for change descriptions"
self.setupTransfer()
inside = localDirectory(self.source.client_root, "inside")
inside_file1 = os.path.join(inside, "inside_file1")
create_file(inside_file1, 'Test content')
self.source.p4cmd('add', inside_file1)
desc = 'inside_file1 added'
self.source.p4cmd('submit', '-d', desc)
self.run_P4Transfer()
self.assertCounters(1, 1)
changes = self.target.p4cmd('changes', '-l', '-m1')
self.assertRegex(changes[0]['desc'], "%s\n\nTransferred from p4://rsh:.*@1\n$" % desc)
options = self.getDefaultOptions()
options["change_description_format"] = "Originally $sourceChange by $sourceUser"
self.createConfigFile(options=options)
self.source.p4cmd('edit', inside_file1)
desc = 'inside_file1 edited'
self.source.p4cmd('submit', '-d', desc)
self.run_P4Transfer()
self.assertCounters(2, 2)
changes = self.target.p4cmd('changes', '-l', '-m1')
self.assertRegex(changes[0]['desc'], "Originally 2 by %s" % P4USER)
options = self.getDefaultOptions()
options["change_description_format"] = "Was $sourceChange by $sourceUser $fred\n$sourceDescription"
self.createConfigFile(options=options)
self.source.p4cmd('edit', inside_file1)
desc = 'inside_file1 edited again'
self.source.p4cmd('submit', '-d', desc)
self.run_P4Transfer()
self.assertCounters(3, 3)
changes = self.target.p4cmd('changes', '-l', '-m1')
self.assertEqual(changes[0]['desc'], "Was 3 by %s $fred\n%s\n" % (P4USER, desc))
def testBatchSize(self):
"Set batch size appropriately - make sure logging switches"
self.setupTransfer()
inside = localDirectory(self.source.client_root, "inside")
inside_file1 = os.path.join(inside, "inside_file1")
create_file(inside_file1, 'Test content')
self.source.p4cmd('add', inside_file1)
self.source.p4cmd('submit', '-d', 'file added')
for _ in range(1, 10):
self.source.p4cmd('edit', inside_file1)
append_to_file(inside_file1, "more")
self.source.p4cmd('submit', '-d', 'edited')
changes = self.source.p4cmd('changes', '-l', '-m1')
self.assertEqual(changes[0]['change'], '10')
options = self.getDefaultOptions()
options["change_batch_size"] = "4"
self.createConfigFile(options=options)
self.run_P4Transfer()
self.assertCounters(10, 10)
logoutput = saved_stdoutput.getvalue()
matches = re.findall("INFO: Logging to file:", logoutput)
self.assertEqual(len(matches), 3)
def testChangeMapFile(self):
"How a change map file is written"
self.setupTransfer()
inside = localDirectory(self.source.client_root, "inside")
inside_file1 = os.path.join(inside, "inside_file1")
create_file(inside_file1, 'Test content')
self.source.p4cmd('add', inside_file1)
self.source.p4cmd('submit', '-d', 'file added')
self.run_P4Transfer()
self.assertCounters(1, 1)
options = self.getDefaultOptions()
options["change_map_file"] = "depot/inside/change_map.csv"
change_map_file = '//depot/import/change_map.csv'
self.createConfigFile(options=options)
self.source.p4cmd('edit', inside_file1)
self.source.p4cmd('submit', '-d', 'edited')
self.run_P4Transfer()
self.assertCounters(2, 3)
change = self.target.p4.run_describe('4')[0]
self.assertEqual(len(change['depotFile']), 1)
self.assertEqual(change['depotFile'][0], change_map_file)
content = self.target.p4.run_print('-q', change_map_file)[1]
if python3:
content = content.decode()
content = content.split("\n")
self.logger.debug("content:", content)
self.assertRegex(content[0], "sourceP4Port,sourceChangeNo,targetChangeNo")
self.assertRegex(content[1], "rsh.*,2,3")
self.source.p4cmd('edit', inside_file1)
self.source.p4cmd('submit', '-d', 'edited again')
self.source.p4cmd('edit', inside_file1)
self.source.p4cmd('submit', '-d', 'and again')
self.run_P4Transfer()
self.assertCounters(4, 6)
change = self.target.p4.run_describe('8')[0]
self.assertEqual(len(change['depotFile']), 1)
self.assertEqual(change['depotFile'][0], change_map_file)
content = self.target.p4.run_print('-q', change_map_file)[1]
if python3:
content = content.decode()
content = content.split("\n")
self.logger.debug("content:", content)
self.assertRegex(content[1], "rsh.*,2,3")
self.assertRegex(content[2], "rsh.*,3,6")
self.assertRegex(content[3], "rsh.*,4,7")
def testChangeMapFileNotRoot(self):
"How a change map file is written - when not at root"
self.setupTransfer()
inside = localDirectory(self.source.client_root, "inside")
inside_file1 = os.path.join(inside, "inside_file1")
create_file(inside_file1, 'Test content')
self.source.p4cmd('add', inside_file1)
self.source.p4cmd('submit', '-d', 'file added')
self.run_P4Transfer()
self.assertCounters(1, 1)
options = self.getDefaultOptions()
options["change_map_file"] = "depot/inside/changes/change_map.csv"
change_map_file = '//depot/import/changes/change_map.csv'
self.createConfigFile(options=options)
self.source.p4cmd('edit', inside_file1)
self.source.p4cmd('submit', '-d', 'edited')
self.run_P4Transfer()
self.assertCounters(2, 3)
change = self.target.p4.run_describe('4')[0]
self.assertEqual(len(change['depotFile']), 1)
self.assertEqual(change['depotFile'][0], change_map_file)
content = self.target.p4.run_print('-q', change_map_file)[1]
if python3:
content = content.decode()
content = content.split("\n")
self.logger.debug("content:", content)
self.assertRegex(content[0], "sourceP4Port,sourceChangeNo,targetChangeNo")
self.assertRegex(content[1], "rsh.*,2,3")
self.source.p4cmd('edit', inside_file1)
self.source.p4cmd('submit', '-d', 'edited again')
self.source.p4cmd('edit', inside_file1)
self.source.p4cmd('submit', '-d', 'and again')
self.run_P4Transfer()
self.assertCounters(4, 6)
change = self.target.p4.run_describe('8')[0]
self.assertEqual(len(change['depotFile']), 1)
self.assertEqual(change['depotFile'][0], change_map_file)
content = self.target.p4.run_print('-q', change_map_file)[1]
if python3:
content = content.decode()
content = content.split("\n")
self.logger.debug("content:", content)
self.assertRegex(content[1], "rsh.*,2,3")
self.assertRegex(content[2], "rsh.*,3,6")
self.assertRegex(content[3], "rsh.*,4,7")
def testArchive(self):
"Archive a file"
self.setupTransfer()
d = self.source.p4.fetch_depot('archive')
d['Type'] = 'archive'
self.source.p4.save_depot(d)
inside = localDirectory(self.source.client_root, "inside")
inside_file1 = os.path.join(inside, "inside_file1")
inside_file2 = os.path.join(inside, "inside_file2")
inside_file3 = os.path.join(inside, "inside_file3")
create_file(inside_file1, 'Test content')
create_file(inside_file2, 'Test content')
create_file(inside_file3, 'Test content')
self.source.p4cmd('add', '-tbinary', inside_file1)
self.source.p4cmd('add', inside_file2)
self.source.p4cmd('add', '-tbinary', inside_file3)
self.source.p4cmd('submit', '-d', 'files added')
self.source.p4cmd('edit', inside_file1)
self.source.p4cmd('edit', inside_file2)
self.source.p4cmd('edit', inside_file3)
append_to_file(inside_file1, "Some text")
append_to_file(inside_file2, "More text")
append_to_file(inside_file3, "More text")
self.source.p4cmd('submit', '-d', 'files edited')
self.source.p4cmd('archive', '-D', 'archive', inside_file1)
filelog = self.source.p4.run_filelog('//depot/inside/inside_file1')
self.assertEqual(filelog[0].revisions[0].action, 'archive')
self.assertEqual(filelog[0].revisions[1].action, 'archive')
self.source.p4cmd('archive', '-D', 'archive', inside_file3 + "#1")
filelog = self.source.p4.run_filelog('//depot/inside/inside_file3')
self.assertEqual(filelog[0].revisions[0].action, 'edit')
self.assertEqual(filelog[0].revisions[1].action, 'archive')
self.run_P4Transfer()
self.assertCounters(2, 2)
change = self.target.p4.run_describe('1')[0]
self.assertEqual(len(change['depotFile']), 1)
self.assertEqual(change['depotFile'][0], '//depot/import/inside_file2')
change = self.target.p4.run_describe('2')[0]
self.assertEqual(len(change['depotFile']), 2)
self.assertEqual(change['depotFile'][0], '//depot/import/inside_file2')
self.assertEqual(change['depotFile'][1], '//depot/import/inside_file3')
def testAdd(self):
"Basic file add"
self.setupTransfer()
inside = localDirectory(self.source.client_root, "inside")
inside_file1 = os.path.join(inside, "inside_file1")
create_file(inside_file1, 'Test content')
self.source.p4cmd('add', inside_file1)
self.source.p4cmd('submit', '-d', 'inside_file1 added')
self.run_P4Transfer()
changes = self.target.p4cmd('changes')
self.assertEqual(len(changes), 1, "Target does not have exactly one change")
self.assertEqual(changes[0]['change'], "1")
files = self.target.p4cmd('files', '//depot/...')
self.assertEqual(len(files), 1)
self.assertEqual(files[0]['depotFile'], '//depot/import/inside_file1')
self.assertCounters(1, 1)
def testNonSuperUser(self):
"Test when not a superuser - who can't update"
self.setupTransfer()
# Setup default transfer user as super user
# All other users will just have write access
username = "newuser"
p = self.target.p4.fetch_protect()
p['Protections'].append("review user %s * //..." % username)
self.target.p4.save_protect(p)
options = self.getDefaultOptions()
options["superuser"] = "n"
targOptions = {"p4user": username}
self.createConfigFile(options=options, targOptions=targOptions)
inside = localDirectory(self.source.client_root, "inside")
inside_file1 = os.path.join(inside, "inside_file1")
create_file(inside_file1, 'Test content')
self.source.p4cmd('add', inside_file1)
self.source.p4cmd('submit', '-d', 'inside_file1 added')
self.run_P4Transfer()
changes = self.target.p4cmd('changes')
self.assertEqual(len(changes), 1, "Target does not have exactly one change")
self.assertEqual(changes[0]['change'], "1")
files = self.target.p4cmd('files', '//depot/...')
self.assertEqual(len(files), 1)
self.assertEqual(files[0]['depotFile'], '//depot/import/inside_file1')
self.assertCounters(1, 1)
def testObliterate(self):
"What happens to obliterated changes"
self.setupTransfer()
inside = localDirectory(self.source.client_root, "inside")
inside_file1 = os.path.join(inside, "inside_file1")
inside_file2 = os.path.join(inside, "inside_file2")
create_file(inside_file1, 'Test content')
create_file(inside_file2, 'Test content')
self.source.p4cmd('add', inside_file1)
self.source.p4cmd('submit', '-d', 'inside_file1 added')
self.source.p4cmd('edit', inside_file1)
append_to_file(inside_file1, "more stuff")
self.source.p4cmd('add', inside_file2)
self.source.p4cmd('submit', '-d', 'inside_file1 edited and 2 added')
self.source.p4cmd('edit', inside_file1)
append_to_file(inside_file1, "yet more stuff")
self.source.p4cmd('submit', '-d', 'inside_file1 edited again')
self.source.p4cmd('obliterate', '-y', "%s#2,2" % inside_file1)
self.run_P4Transfer()
self.assertCounters(3, 3)
changes = self.target.p4cmd('changes')
self.assertEqual(3, len(changes))
# self.assertEqual(changes[0]['change'], "1")
# files = self.target.p4cmd('files', '//depot/...')
# self.assertEqual(len(files), 1)
# self.assertEqual(files[0]['depotFile'], '//depot/import/inside_file1')
def testSymlinks(self):
"Various symlink actions"
self.setupTransfer()
inside = localDirectory(self.source.client_root, "inside")
inside_file1 = os.path.join(inside, "inside_file1")
file_link1 = os.path.join(inside, "link1")
file_link2 = os.path.join(inside, "link2")
file_link3 = os.path.join(inside, "link3")
file_link4 = os.path.join(inside, "link4")
file_link5 = os.path.join(inside, "link5")
file_link6 = os.path.join(inside, "link6")
inside_file2 = os.path.join(inside, "subdir", "inside_file2")
create_file(inside_file1, '01234567890123456789012345678901234567890123456789')
create_file(inside_file2, '01234567890123456789012345678901234567890123456789more')
if os.name == "nt":
create_file(file_link1, "inside_file1\n")
create_file(file_link2, "subdir\n")
else:
os.symlink("inside_file1", file_link1)
os.symlink("subdir", file_link2)
self.source.p4cmd('add', inside_file1, inside_file2)
self.source.p4cmd('add', "-t", "symlink", file_link1, file_link2)
self.source.p4cmd('submit', '-d', 'files added')
self.run_P4Transfer()
self.assertCounters(1, 1)
changes = self.target.p4cmd('changes')
self.assertEqual(len(changes), 1, "Target does not have exactly one change")
self.assertEqual(changes[0]['change'], "1")
files = self.target.p4cmd('files', '//depot/...')
self.assertEqual(len(files), 4)
self.assertEqual(files[0]['depotFile'], '//depot/import/inside_file1')
self.source.p4cmd('edit', file_link1, file_link2)
self.source.p4cmd('move', file_link1, file_link3)
self.source.p4cmd('move', file_link2, file_link4)
self.source.p4cmd('submit', '-d', 'links moved')
self.run_P4Transfer()
self.assertCounters(2, 2)
self.source.p4cmd('edit', file_link3, file_link4)
self.source.p4cmd('move', file_link3, file_link5)
self.source.p4cmd('move', file_link4, file_link6)
self.source.p4cmd('submit', '-d', 'links moved')
self.run_P4Transfer()
self.assertCounters(3, 3)
def testUTF16FaultyBOM(self):
"UTF 16 file with faulty BOM"
self.setupTransfer()
inside = localDirectory(self.source.client_root, "inside")
fname = "data-file-utf16"
rcs_fname = fname + ",v"
inside_file1 = os.path.join(inside, fname)
create_file(inside_file1, 'Test content')
self.source.p4cmd('add', '-t', 'utf16', inside_file1)
self.source.p4cmd('submit', '-d', 'inside_file1 added')