forked from frerich/clcache
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathintegrationtests.py
More file actions
789 lines (626 loc) · 31.3 KB
/
integrationtests.py
File metadata and controls
789 lines (626 loc) · 31.3 KB
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
#!/usr/bin/env python
#
# This file is part of the clcache project.
#
# The contents of this file are subject to the BSD 3-Clause License, the
# full text of which is available in the accompanying LICENSE file at the
# root directory of this project.
#
# In Python unittests are always members, not functions. Silence lint in this file.
# pylint: disable=no-self-use
#
from contextlib import contextmanager
import copy
import glob
import os
import shutil
import subprocess
import sys
import tempfile
import unittest
import clcache
PYTHON_BINARY = sys.executable
CLCACHE_SCRIPT = os.path.join(os.path.dirname(os.path.realpath(__file__)), "clcache.py")
ASSETS_DIR = os.path.join("tests", "integrationtests")
# pytest-cov note: subprocesses are coverage tested by default with some limitations
# "For subprocess measurement environment variables must make it from the main process to the
# subprocess. The python used by the subprocess must have pytest-cov installed. The subprocess
# must do normal site initialisation so that the environment variables can be detected and
# coverage started."
CLCACHE_CMD = [PYTHON_BINARY, CLCACHE_SCRIPT]
@contextmanager
def cd(targetDirectory):
oldDirectory = os.getcwd()
os.chdir(os.path.expanduser(targetDirectory))
try:
yield
finally:
os.chdir(oldDirectory)
class TestCommandLineArguments(unittest.TestCase):
def testValidMaxSize(self):
with tempfile.TemporaryDirectory() as tempDir:
customEnv = dict(os.environ, CLCACHE_DIR=tempDir)
validValues = ["1", " 10", "42 ", "22222222"]
for value in validValues:
cmd = CLCACHE_CMD + ["-M", value]
self.assertEqual(
subprocess.call(cmd, env=customEnv),
0,
"Command must not fail for max size: '" + value + "'")
def testInvalidMaxSize(self):
invalidValues = ["ababa", "-1", "0", "1000.0"]
for value in invalidValues:
cmd = CLCACHE_CMD + ["-M", value]
self.assertNotEqual(subprocess.call(cmd), 0, "Command must fail for max size: '" + value + "'")
class TestCompileRuns(unittest.TestCase):
def testBasicCompileCc(self):
cmd = CLCACHE_CMD + ["/nologo", "/c", os.path.join(ASSETS_DIR, "fibonacci.c")]
subprocess.check_call(cmd)
def testBasicCompileCpp(self):
cmd = CLCACHE_CMD + ["/nologo", "/EHsc", "/c", os.path.join(ASSETS_DIR, "fibonacci.cpp")]
subprocess.check_call(cmd)
def testCompileLinkRunCc(self):
with cd(ASSETS_DIR):
cmd = CLCACHE_CMD + ["/nologo", "/c", "fibonacci.c", "/Fofibonacci_c.obj"]
subprocess.check_call(cmd)
cmd = ["link", "/nologo", "/OUT:fibonacci_c.exe", "fibonacci_c.obj"]
subprocess.check_call(cmd)
cmd = ["fibonacci_c.exe"]
output = subprocess.check_output(cmd).decode("ascii").strip()
self.assertEqual(output, "0 1 1 2 3 5 8 13 21 34 55 89 144 233 377")
def testCompileLinkRunCpp(self):
with cd(ASSETS_DIR):
cmd = CLCACHE_CMD + ["/nologo", "/EHsc", "/c", "fibonacci.cpp", "/Fofibonacci_cpp.obj"]
subprocess.check_call(cmd)
cmd = ["link", "/nologo", "/OUT:fibonacci_cpp.exe", "fibonacci_cpp.obj"]
subprocess.check_call(cmd)
cmd = ["fibonacci_cpp.exe"]
output = subprocess.check_output(cmd).decode("ascii").strip()
self.assertEqual(output, "0 1 1 2 3 5 8 13 21 34 55 89 144 233 377")
def testRecompile(self):
cmd = CLCACHE_CMD + [
"/nologo",
"/EHsc",
"/c",
os.path.join(ASSETS_DIR, "recompile1.cpp")
]
subprocess.check_call(cmd) # Compile once
subprocess.check_call(cmd) # Compile again
def testRecompileObjectSetSameDir(self):
cmd = CLCACHE_CMD + [
"/nologo",
"/EHsc",
"/c",
os.path.join(ASSETS_DIR, "recompile2.cpp"),
"/Forecompile2_custom_object_name.obj"
]
subprocess.check_call(cmd) # Compile once
subprocess.check_call(cmd) # Compile again
def testRecompileObjectSetOtherDir(self):
cmd = CLCACHE_CMD + [
"/nologo",
"/EHsc",
"/c",
os.path.join(ASSETS_DIR, "recompile3.cpp"),
"/Fotests\\output\\recompile2_custom_object_name.obj"
]
subprocess.check_call(cmd) # Compile once
subprocess.check_call(cmd) # Compile again
def testPipedOutput(self):
def debugLinebreaks(text):
out = []
lines = text.splitlines(True)
for line in lines:
out.append(line.replace("\r", "<CR>").replace("\n", "<LN>"))
return "\n".join(out)
commands = [
# just show cl.exe version
{
'directMode': True,
'compileFails': False,
'cmd': CLCACHE_CMD
},
# passed to real compiler
{
'directMode': True,
'compileFails': False,
'cmd': CLCACHE_CMD + ['/E', 'fibonacci.c']
},
# Unique parameters ensure this was not cached yet (at least in CI)
{
'directMode': True,
'compileFails': False,
'cmd': CLCACHE_CMD + ['/wd4267', '/wo4018', '/c', 'fibonacci.c']
},
# Cache hit
{
'directMode': True,
'compileFails': False,
'cmd': CLCACHE_CMD + ['/wd4267', '/wo4018', '/c', 'fibonacci.c']
},
# Unique parameters ensure this was not cached yet (at least in CI)
{
'directMode': False,
'compileFails': False,
'cmd': CLCACHE_CMD + ['/wd4269', '/wo4019', '/c', 'fibonacci.c']
},
# Cache hit
{
'directMode': False,
'compileFails': False,
'cmd': CLCACHE_CMD + ['/wd4269', '/wo4019', '/c', 'fibonacci.c']
},
# Compile fails in NODIRECT mode. This will trigger a preprocessor fail via
# cl.exe /EP /w1NONNUMERIC fibonacci.c
{
'directMode': False,
'compileFails': True,
'cmd': CLCACHE_CMD + ['/w1NONNUMERIC', '/c', 'fibonacci.c']
},
]
for command in commands:
with cd(ASSETS_DIR):
if command['directMode']:
testEnvironment = dict(os.environ)
else:
testEnvironment = dict(os.environ, CLCACHE_NODIRECT="1")
proc = subprocess.Popen(command['cmd'], env=testEnvironment,
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdoutBinary, stderrBinary = proc.communicate()
stdout = stdoutBinary.decode(clcache.CL_DEFAULT_CODEC)
stderr = stderrBinary.decode(clcache.CL_DEFAULT_CODEC)
if not command['compileFails'] and proc.returncode != 0:
self.fail(
'Compile failed with return code {}.\n'.format(proc.returncode) +
'Command: {}\nEnvironment: {}\nStdout: {}\nStderr: {}'.format(
command['cmd'], testEnvironment, stdout, stderr))
if command['compileFails'] and proc.returncode == 0:
self.fail('Compile was expected to fail but did not. {}'.format(command['cmd']))
for output in [stdout, stderr]:
if output:
self.assertTrue('\r\r\n' not in output,
'Output has duplicated CR.\nCommand: {}\nOutput: {}'.format(
command['cmd'], debugLinebreaks(output)))
# Just to be sure we have newlines
self.assertTrue('\r\n' in output,
'Output has no CRLF.\nCommand: {}\nOutput: {}'.format(
command['cmd'], debugLinebreaks(output)))
class TestCompilerEncoding(unittest.TestCase):
def testNonAsciiMessage(self):
with cd(os.path.join(ASSETS_DIR, "compiler-encoding")):
for filename in ['non-ascii-message-ansi.c', 'non-ascii-message-utf16.c']:
cmd = CLCACHE_CMD + ["/nologo", "/c", filename]
subprocess.check_call(cmd)
class TestHits(unittest.TestCase):
def testHitsSimple(self):
with cd(os.path.join(ASSETS_DIR, "hits-and-misses")):
cmd = CLCACHE_CMD + ["/nologo", "/EHsc", "/c", 'hit.cpp']
subprocess.check_call(cmd) # Ensure it has been compiled before
cache = clcache.Cache()
with cache.statistics as stats:
oldHits = stats.numCacheHits()
subprocess.check_call(cmd) # This must hit now
with cache.statistics as stats:
newHits = stats.numCacheHits()
self.assertEqual(newHits, oldHits + 1)
class TestPrecompiledHeaders(unittest.TestCase):
def testSampleproject(self):
with cd(os.path.join(ASSETS_DIR, "precompiled-headers")):
cpp = ' '.join(CLCACHE_CMD)
testEnvironment = dict(os.environ, CPP=cpp)
cmd = ["nmake", "/nologo"]
subprocess.check_call(cmd, env=testEnvironment)
cmd = ["myapp.exe"]
subprocess.check_call(cmd)
cmd = ["nmake", "/nologo", "clean"]
subprocess.check_call(cmd, env=testEnvironment)
cmd = ["nmake", "/nologo"]
subprocess.check_call(cmd, env=testEnvironment)
class TestHeaderChange(unittest.TestCase):
def _clean(self):
if os.path.isfile("main.obj"):
os.remove("main.obj")
if os.path.isfile("main.exe"):
os.remove("main.exe")
def _compileAndLink(self, environment=None):
cmdCompile = CLCACHE_CMD + ["/nologo", "/EHsc", "/c", "main.cpp"]
cmdLink = ["link", "/nologo", "/OUT:main.exe", "main.obj"]
subprocess.check_call(cmdCompile, env=environment or os.environ)
subprocess.check_call(cmdLink, env=environment or os.environ)
def testDirect(self):
with cd(os.path.join(ASSETS_DIR, "header-change")):
self._clean()
with open("version.h", "w") as header:
header.write("#define VERSION 1")
self._compileAndLink()
cmdRun = [os.path.abspath("main.exe")]
output = subprocess.check_output(cmdRun).decode("ascii").strip()
self.assertEqual(output, "1")
self._clean()
with open("version.h", "w") as header:
header.write("#define VERSION 2")
self._compileAndLink()
cmdRun = [os.path.abspath("main.exe")]
output = subprocess.check_output(cmdRun).decode("ascii").strip()
self.assertEqual(output, "2")
def testNoDirect(self):
with cd(os.path.join(ASSETS_DIR, "header-change")):
self._clean()
with open("version.h", "w") as header:
header.write("#define VERSION 1")
testEnvironment = dict(os.environ, CLCACHE_NODIRECT="1")
self._compileAndLink(testEnvironment)
cmdRun = [os.path.abspath("main.exe")]
output = subprocess.check_output(cmdRun).decode("ascii").strip()
self.assertEqual(output, "1")
self._clean()
with open("version.h", "w") as header:
header.write("#define VERSION 2")
self._compileAndLink(testEnvironment)
cmdRun = [os.path.abspath("main.exe")]
output = subprocess.check_output(cmdRun).decode("ascii").strip()
self.assertEqual(output, "2")
class TestHeaderMiss(unittest.TestCase):
# When a required header disappears, we must fall back to real compiler
# complaining about the miss
def testRequiredHeaderDisappears(self):
with cd(os.path.join(ASSETS_DIR, "header-miss")):
compileCmd = CLCACHE_CMD + ["/nologo", "/EHsc", "/c", "main.cpp"]
with open("info.h", "w") as header:
header.write("#define INFO 1337\n")
subprocess.check_call(compileCmd)
os.remove("info.h")
# real compiler fails
process = subprocess.Popen(compileCmd, stdout=subprocess.PIPE)
stdout, _ = process.communicate()
self.assertEqual(process.returncode, 2)
self.assertTrue("C1083" in stdout.decode(clcache.CL_DEFAULT_CODEC))
# When a header included by another header becomes obsolete and disappers,
# we must fall back to real compiler.
def testObsoleteHeaderDisappears(self):
# A includes B
with cd(os.path.join(ASSETS_DIR, "header-miss-obsolete")):
compileCmd = CLCACHE_CMD + ["/I.", "/nologo", "/EHsc", "/c", "main.cpp"]
cache = clcache.Cache()
with open("A.h", "w") as header:
header.write('#define INFO 1337\n')
header.write('#include "B.h"\n')
with open("B.h", "w") as header:
header.write('#define SOMETHING 1\n')
subprocess.check_call(compileCmd)
with cache.statistics as stats:
headerChangedMisses1 = stats.numHeaderChangedMisses()
hits1 = stats.numCacheHits()
misses1 = stats.numCacheMisses()
# Make include B.h obsolete
with open("A.h", "w") as header:
header.write('#define INFO 1337\n')
header.write('\n')
os.remove("B.h")
subprocess.check_call(compileCmd)
with cache.statistics as stats:
headerChangedMisses2 = stats.numHeaderChangedMisses()
hits2 = stats.numCacheHits()
misses2 = stats.numCacheMisses()
self.assertEqual(headerChangedMisses2, headerChangedMisses1+1)
self.assertEqual(misses2, misses1+1)
self.assertEqual(hits2, hits1)
# Ensure the new manifest was stored
subprocess.check_call(compileCmd)
with cache.statistics as stats:
headerChangedMisses3 = stats.numHeaderChangedMisses()
hits3 = stats.numCacheHits()
misses3 = stats.numCacheMisses()
self.assertEqual(headerChangedMisses3, headerChangedMisses2)
self.assertEqual(misses3, misses2)
self.assertEqual(hits3, hits2+1)
class TestRunParallel(unittest.TestCase):
def _zeroStats(self):
subprocess.check_call(CLCACHE_CMD + ["-z"])
def _buildAll(self):
processes = []
for sourceFile in glob.glob('*.cpp'):
print("Starting compilation of {}".format(sourceFile))
cxxflags = ["/c", "/nologo", "/EHsc"]
cmd = CLCACHE_CMD + cxxflags + [sourceFile]
processes.append(subprocess.Popen(cmd))
for p in processes:
p.wait()
# Test counting of misses and hits in a parallel environment
def testParallel(self):
with cd(os.path.join(ASSETS_DIR, "parallel")):
self._zeroStats()
# Compile first time
self._buildAll()
cache = clcache.Cache()
with cache.statistics as stats:
hits = stats.numCacheHits()
misses = stats.numCacheMisses()
self.assertEqual(hits + misses, 10)
# Compile second time
self._buildAll()
cache = clcache.Cache()
with cache.statistics as stats:
hits = stats.numCacheHits()
misses = stats.numCacheMisses()
self.assertEqual(hits + misses, 20)
def testHitViaMpSequential(self):
with cd(os.path.join(ASSETS_DIR, "parallel")), tempfile.TemporaryDirectory() as tempDir:
cache = clcache.Cache(tempDir)
customEnv = dict(os.environ, CLCACHE_DIR=tempDir)
with cache.statistics as stats:
self.assertEqual(stats.numCacheHits(), 0)
self.assertEqual(stats.numCacheMisses(), 0)
self.assertEqual(stats.numCacheEntries(), 0)
cmd = CLCACHE_CMD + ["/nologo", "/EHsc", "/c"]
# Compile random file, filling cache
subprocess.check_call(cmd + ["fibonacci01.cpp"], env=customEnv)
with cache.statistics as stats:
self.assertEqual(stats.numCacheHits(), 0)
self.assertEqual(stats.numCacheMisses(), 1)
self.assertEqual(stats.numCacheEntries(), 1)
# Compile same files with specifying /MP, this should hit
subprocess.check_call(cmd + ["/MP", "fibonacci01.cpp"], env=customEnv)
with cache.statistics as stats:
self.assertEqual(stats.numCacheHits(), 1)
self.assertEqual(stats.numCacheMisses(), 1)
self.assertEqual(stats.numCacheEntries(), 1)
def testHitsViaMpConcurrent(self):
with cd(os.path.join(ASSETS_DIR, "parallel")), tempfile.TemporaryDirectory() as tempDir:
cache = clcache.Cache(tempDir)
customEnv = dict(os.environ, CLCACHE_DIR=tempDir)
with cache.statistics as stats:
self.assertEqual(stats.numCacheHits(), 0)
self.assertEqual(stats.numCacheMisses(), 0)
self.assertEqual(stats.numCacheEntries(), 0)
cmd = CLCACHE_CMD + ["/nologo", "/EHsc", "/c"]
# Compile two random files
subprocess.check_call(cmd + ["fibonacci01.cpp"], env=customEnv)
subprocess.check_call(cmd + ["fibonacci02.cpp"], env=customEnv)
with cache.statistics as stats:
self.assertEqual(stats.numCacheHits(), 0)
self.assertEqual(stats.numCacheMisses(), 2)
self.assertEqual(stats.numCacheEntries(), 2)
# Compile same two files concurrently, this should hit twice.
subprocess.check_call(cmd + ["/MP2", "fibonacci01.cpp", "fibonacci02.cpp"], env=customEnv)
with cache.statistics as stats:
self.assertEqual(stats.numCacheHits(), 2)
self.assertEqual(stats.numCacheMisses(), 2)
self.assertEqual(stats.numCacheEntries(), 2)
# Compiler calls with multiple sources files at once, e.g.
# cl file1.c file2.c
class TestMultipleSources(unittest.TestCase):
def testTwo(self):
with cd(os.path.join(ASSETS_DIR, "mutiple-sources")), tempfile.TemporaryDirectory() as tempDir:
cache = clcache.Cache(tempDir)
customEnv = dict(os.environ, CLCACHE_DIR=tempDir)
baseCmd = CLCACHE_CMD + ["/nologo", "/EHsc", "/c"]
with cache.statistics as stats:
self.assertEqual(stats.numCacheHits(), 0)
self.assertEqual(stats.numCacheMisses(), 0)
self.assertEqual(stats.numCacheEntries(), 0)
subprocess.check_call(baseCmd + ["fibonacci01.cpp", "fibonacci02.cpp"], env=customEnv)
with cache.statistics as stats:
self.assertEqual(stats.numCacheHits(), 0)
self.assertEqual(stats.numCacheMisses(), 2)
self.assertEqual(stats.numCacheEntries(), 2)
subprocess.check_call(baseCmd + ["fibonacci01.cpp", "fibonacci02.cpp"], env=customEnv)
with cache.statistics as stats:
self.assertEqual(stats.numCacheHits(), 2)
self.assertEqual(stats.numCacheMisses(), 2)
self.assertEqual(stats.numCacheEntries(), 2)
def testFive(self):
with cd(os.path.join(ASSETS_DIR, "mutiple-sources")), tempfile.TemporaryDirectory() as tempDir:
cache = clcache.Cache(tempDir)
customEnv = dict(os.environ, CLCACHE_DIR=tempDir)
baseCmd = CLCACHE_CMD + ["/nologo", "/EHsc", "/c"]
with cache.statistics as stats:
self.assertEqual(stats.numCacheHits(), 0)
self.assertEqual(stats.numCacheMisses(), 0)
self.assertEqual(stats.numCacheEntries(), 0)
subprocess.check_call(baseCmd + [
"fibonacci01.cpp",
"fibonacci02.cpp",
"fibonacci03.cpp",
"fibonacci04.cpp",
"fibonacci05.cpp",
], env=customEnv)
with cache.statistics as stats:
self.assertEqual(stats.numCacheHits(), 0)
self.assertEqual(stats.numCacheMisses(), 5)
self.assertEqual(stats.numCacheEntries(), 5)
subprocess.check_call(baseCmd + [
"fibonacci01.cpp",
"fibonacci02.cpp",
"fibonacci03.cpp",
"fibonacci04.cpp",
"fibonacci05.cpp",
], env=customEnv)
with cache.statistics as stats:
self.assertEqual(stats.numCacheHits(), 5)
self.assertEqual(stats.numCacheMisses(), 5)
self.assertEqual(stats.numCacheEntries(), 5)
class TestMultipleSourceWithClEnv(unittest.TestCase):
def testAppend(self):
with cd(os.path.join(ASSETS_DIR)):
customEnv = dict(os.environ, _CL_="minimal.cpp")
cmd = CLCACHE_CMD + ["/nologo", "/EHsc", "/c"]
subprocess.check_call(cmd + ["fibonacci.cpp"], env=customEnv)
class TestClearing(unittest.TestCase):
def _clearCache(self):
subprocess.check_call(CLCACHE_CMD + ["-C"])
def testClearIdempotency(self):
cache = clcache.Cache()
self._clearCache()
with cache.statistics as stats:
self.assertEqual(stats.currentCacheSize(), 0)
self.assertEqual(stats.numCacheEntries(), 0)
# Clearing should be idempotent
self._clearCache()
with cache.statistics as stats:
self.assertEqual(stats.currentCacheSize(), 0)
self.assertEqual(stats.numCacheEntries(), 0)
def testClearPostcondition(self):
cache = clcache.Cache()
# Compile a random file to populate cache
cmd = CLCACHE_CMD + ["/nologo", "/EHsc", "/c", os.path.join(ASSETS_DIR, "fibonacci.cpp")]
subprocess.check_call(cmd)
# Now there should be something in the cache
with cache.statistics as stats:
self.assertTrue(stats.currentCacheSize() > 0)
self.assertTrue(stats.numCacheEntries() > 0)
# Now, clear the cache: the stats should remain unchanged except for
# the cache size and number of cache entries.
oldStats = copy.copy(cache.statistics)
self._clearCache()
with cache.statistics as stats:
self.assertEqual(stats.currentCacheSize(), 0)
self.assertEqual(stats.numCacheEntries(), 0)
self.assertEqual(stats.numCallsWithoutSourceFile(), oldStats.numCallsWithoutSourceFile())
self.assertEqual(stats.numCallsWithMultipleSourceFiles(), oldStats.numCallsWithMultipleSourceFiles())
self.assertEqual(stats.numCallsWithPch(), oldStats.numCallsWithPch())
self.assertEqual(stats.numCallsForLinking(), oldStats.numCallsForLinking())
self.assertEqual(stats.numCallsForPreprocessing(), oldStats.numCallsForPreprocessing())
self.assertEqual(stats.numCallsForExternalDebugInfo(), oldStats.numCallsForExternalDebugInfo())
self.assertEqual(stats.numEvictedMisses(), oldStats.numEvictedMisses())
self.assertEqual(stats.numHeaderChangedMisses(), oldStats.numHeaderChangedMisses())
self.assertEqual(stats.numSourceChangedMisses(), oldStats.numSourceChangedMisses())
self.assertEqual(stats.numCacheHits(), oldStats.numCacheHits())
self.assertEqual(stats.numCacheMisses(), oldStats.numCacheMisses())
class TestAnalysisErrorsCalls(unittest.TestCase):
def testAllKnownAnalysisErrors(self):
# This ensures all AnalysisError cases are run once without crashes
with cd(os.path.join(ASSETS_DIR)):
baseCmd = CLCACHE_CMD + ['/nologo']
# NoSourceFileError
# This must fail because cl.exe: "cl : Command line error D8003 : missing source filename"
# Make sure it was cl.exe that failed and not clcache
process = subprocess.Popen(baseCmd + [], stderr=subprocess.PIPE)
_, stderr = process.communicate()
self.assertEqual(process.returncode, 2)
self.assertTrue("D8003" in stderr.decode(clcache.CL_DEFAULT_CODEC))
# InvalidArgumentError
# This must fail because cl.exe: "cl : Command line error D8004 : '/Zm' requires an argument"
# Make sure it was cl.exe that failed and not clcache
process = subprocess.Popen(baseCmd + ['/c', '/Zm', 'bar', "minimal.cpp"], stderr=subprocess.PIPE)
_, stderr = process.communicate()
self.assertEqual(process.returncode, 2)
self.assertTrue("D8004" in stderr.decode(clcache.CL_DEFAULT_CODEC))
# MultipleSourceFilesComplexError
subprocess.check_call(baseCmd + ['/c', '/Tcfibonacci.c', "minimal.cpp"])
# CalledForLinkError
subprocess.check_call(baseCmd + ["fibonacci.cpp"])
# CalledWithPchError
subprocess.check_call(baseCmd + ['/c', '/Yc', "minimal.cpp"])
# ExternalDebugInfoError
subprocess.check_call(baseCmd + ['/c', '/Zi', "minimal.cpp"])
# CalledForPreprocessingError
subprocess.check_call(baseCmd + ['/E', "minimal.cpp"])
class TestPreprocessorCalls(unittest.TestCase):
def testHitsSimple(self):
invocations = [
["/nologo", "/E"],
["/nologo", "/EP", "/c"],
["/nologo", "/P", "/c"],
["/nologo", "/E", "/EP"],
]
cache = clcache.Cache()
with cache.statistics as stats:
oldPreprocessorCalls = stats.numCallsForPreprocessing()
for i, invocation in enumerate(invocations, 1):
cmd = CLCACHE_CMD + invocation + [os.path.join(ASSETS_DIR, "minimal.cpp")]
subprocess.check_call(cmd)
with cache.statistics as stats:
newPreprocessorCalls = stats.numCallsForPreprocessing()
self.assertEqual(newPreprocessorCalls, oldPreprocessorCalls + i, str(cmd))
class TestNoDirectCalls(unittest.TestCase):
def testPreprocessorFailure(self):
cache = clcache.Cache()
oldStats = copy.copy(cache.statistics)
cmd = CLCACHE_CMD + ["/nologo", "/c", "doesnotexist.cpp"]
env = dict(os.environ, CLCACHE_NODIRECT="1")
self.assertNotEqual(subprocess.call(cmd, env=env), 0)
self.assertEqual(cache.statistics, oldStats)
def testHit(self):
with cd(os.path.join(ASSETS_DIR, "hits-and-misses")):
cmd = CLCACHE_CMD + ["/nologo", "/EHsc", "/c", "hit.cpp"]
env = dict(os.environ, CLCACHE_NODIRECT="1")
self.assertEqual(subprocess.call(cmd, env=env), 0)
cache = clcache.Cache()
with cache.statistics as stats:
oldHits = stats.numCacheHits()
self.assertEqual(subprocess.call(cmd, env=env), 0) # This should hit now
with cache.statistics as stats:
self.assertEqual(stats.numCacheHits(), oldHits + 1)
def testHitViaMpSequential(self):
with cd(os.path.join(ASSETS_DIR, "parallel")), tempfile.TemporaryDirectory() as tempDir:
cache = clcache.Cache(tempDir)
customEnv = dict(os.environ, CLCACHE_DIR=tempDir, CLCACHE_NODIRECT="1")
with cache.statistics as stats:
self.assertEqual(stats.numCacheHits(), 0)
self.assertEqual(stats.numCacheMisses(), 0)
self.assertEqual(stats.numCacheEntries(), 0)
cmd = CLCACHE_CMD + ["/nologo", "/EHsc", "/c"]
# Compile random file, filling cache
subprocess.check_call(cmd + ["fibonacci01.cpp"], env=customEnv)
with cache.statistics as stats:
self.assertEqual(stats.numCacheHits(), 0)
self.assertEqual(stats.numCacheMisses(), 1)
self.assertEqual(stats.numCacheEntries(), 1)
# Compile same files with specifying /MP, this should hit
subprocess.check_call(cmd + ["/MP", "fibonacci01.cpp"], env=customEnv)
with cache.statistics as stats:
self.assertEqual(stats.numCacheHits(), 1)
self.assertEqual(stats.numCacheMisses(), 1)
self.assertEqual(stats.numCacheEntries(), 1)
def testHitsViaMpConcurrent(self):
with cd(os.path.join(ASSETS_DIR, "parallel")), tempfile.TemporaryDirectory() as tempDir:
cache = clcache.Cache(tempDir)
customEnv = dict(os.environ, CLCACHE_DIR=tempDir, CLCACHE_NODIRECT="1")
with cache.statistics as stats:
self.assertEqual(stats.numCacheHits(), 0)
self.assertEqual(stats.numCacheMisses(), 0)
self.assertEqual(stats.numCacheEntries(), 0)
cmd = CLCACHE_CMD + ["/nologo", "/EHsc", "/c"]
# Compile two random files
subprocess.check_call(cmd + ["fibonacci01.cpp"], env=customEnv)
subprocess.check_call(cmd + ["fibonacci02.cpp"], env=customEnv)
with cache.statistics as stats:
self.assertEqual(stats.numCacheHits(), 0)
self.assertEqual(stats.numCacheMisses(), 2)
self.assertEqual(stats.numCacheEntries(), 2)
# Compile same two files concurrently, this should hit twice.
subprocess.check_call(cmd + ["/MP2", "fibonacci01.cpp", "fibonacci02.cpp"], env=customEnv)
with cache.statistics as stats:
self.assertEqual(stats.numCacheHits(), 2)
self.assertEqual(stats.numCacheMisses(), 2)
self.assertEqual(stats.numCacheEntries(), 2)
class TestBasedir(unittest.TestCase):
def testBasedir(self):
with cd(os.path.join(ASSETS_DIR, "basedir")), tempfile.TemporaryDirectory() as tempDir:
# First, create two separate build directories with the same sources
for buildDir in ["builddir_a", "builddir_b"]:
shutil.rmtree(buildDir, ignore_errors=True)
os.mkdir(buildDir)
shutil.copy("main.cpp", buildDir)
shutil.copy("constants.h", buildDir)
cache = clcache.Cache(tempDir)
cmd = CLCACHE_CMD + ["/nologo", "/EHsc", "/c", "main.cpp"]
# Build once in one directory
with cd("builddir_a"):
env = dict(os.environ, CLCACHE_DIR=tempDir, CLCACHE_BASEDIR=os.getcwd())
self.assertEqual(subprocess.call(cmd, env=env), 0)
with cache.statistics as stats:
self.assertEqual(stats.numCacheMisses(), 1)
self.assertEqual(stats.numCacheHits(), 0)
shutil.rmtree("builddir_a", ignore_errors=True)
# Build again in a different directory, this should hit now because of CLCACHE_BASEDIR
with cd("builddir_b"):
env = dict(os.environ, CLCACHE_DIR=tempDir, CLCACHE_BASEDIR=os.getcwd())
self.assertEqual(subprocess.call(cmd, env=env), 0)
with cache.statistics as stats:
self.assertEqual(stats.numCacheMisses(), 1)
self.assertEqual(stats.numCacheHits(), 1)
if __name__ == '__main__':
unittest.TestCase.longMessage = True
unittest.main()