-
Notifications
You must be signed in to change notification settings - Fork 1.6k
Expand file tree
/
Copy pathother_test.py
More file actions
4429 lines (3593 loc) · 131 KB
/
other_test.py
File metadata and controls
4429 lines (3593 loc) · 131 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
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
# python -m pytest test-other.py
import os
import sys
import pytest
import glob
import json
import subprocess
import shutil
from testutils import cppcheck, assert_cppcheck, cppcheck_ex, __lookup_cppcheck_exe
from xml.etree import ElementTree
def __remove_verbose_log(l : list):
l.remove('Defines:')
l.remove('Undefines:')
l.remove('Includes:')
l.remove('Platform:native')
return l
def test_missing_include(tmpdir): # #11283
test_file = os.path.join(tmpdir, 'test.c')
with open(test_file, 'wt') as f:
f.write("""
#include "test.h"
""")
args = ['--enable=missingInclude', '--template=simple', test_file]
_, _, stderr = cppcheck(args)
assert stderr == '{}:2:2: information: Include file: "test.h" not found. [missingInclude]\n'.format(test_file)
def __test_missing_include_check_config(tmpdir, use_j):
test_file = os.path.join(tmpdir, 'test.c')
with open(test_file, 'wt') as f:
f.write("""
#include "test.h"
""")
# TODO: -rp is not working requiring the full path in the assert
args = '--check-config -rp={} {}'.format(tmpdir, test_file)
if use_j:
args = '-j2 ' + args
_, _, stderr = cppcheck(args.split())
assert stderr == '' # --check-config no longer reports the missing includes
def test_missing_include_check_config(tmpdir):
__test_missing_include_check_config(tmpdir, False)
def test_missing_include_check_config_j(tmpdir):
__test_missing_include_check_config(tmpdir, True)
def test_missing_include_inline_suppr(tmpdir):
test_file = os.path.join(tmpdir, 'test.c')
with open(test_file, 'wt') as f:
f.write("""
// cppcheck-suppress missingInclude
#include "missing.h"
// cppcheck-suppress missingIncludeSystem
#include <missing2.h>
""")
args = ['--enable=missingInclude', '--inline-suppr', test_file]
_, _, stderr = cppcheck(args)
assert stderr == ''
def test_preprocessor_error(tmpdir):
test_file = os.path.join(tmpdir, '10866.c')
with open(test_file, 'wt') as f:
f.write('#error test\nx=1;\n')
exitcode, _, stderr = cppcheck(['--error-exitcode=1', test_file])
assert 'preprocessorErrorDirective' in stderr
assert exitcode != 0
__ANSI_BOLD = "\x1b[1m"
__ANSI_FG_RED = "\x1b[31m"
__ANSI_FG_DEFAULT = "\x1b[39m"
__ANSI_FG_RESET = "\x1b[0m"
@pytest.mark.parametrize("env,color_expected", [({"CLICOLOR_FORCE":"1"}, True), ({"NO_COLOR": "1", "CLICOLOR_FORCE":"1"}, False)])
def test_color_non_tty(tmpdir, env, color_expected):
test_file = os.path.join(tmpdir, 'test.c')
with open(test_file, 'wt') as f:
f.write('#error test\nx=1;\n')
exitcode, stdout, stderr = cppcheck([test_file], env=env)
assert exitcode == 0, stdout if stdout else stderr
assert stderr
assert (__ANSI_BOLD in stderr) == color_expected
assert (__ANSI_FG_RED in stderr) == color_expected
assert (__ANSI_FG_DEFAULT in stderr) == color_expected
assert (__ANSI_FG_RESET in stderr) == color_expected
@pytest.mark.skipif(sys.platform == "win32", reason="TTY not supported in Windows")
@pytest.mark.parametrize("env,color_expected", [({}, True), ({"NO_COLOR": "1"}, False)])
def test_color_tty(tmpdir, env, color_expected):
test_file = os.path.join(tmpdir, 'test.c')
with open(test_file, 'wt') as f:
f.write('#error test\nx=1;\n')
exitcode, stdout, stderr = cppcheck([test_file], env=env, tty=True)
assert exitcode == 0, stdout if stdout else stderr
assert stderr
assert (__ANSI_BOLD in stderr) == color_expected
assert (__ANSI_FG_RED in stderr) == color_expected
assert (__ANSI_FG_DEFAULT in stderr) == color_expected
assert (__ANSI_FG_RESET in stderr) == color_expected
def test_invalid_library(tmpdir):
args = ['--library=none', '--library=posix', '--library=none2', 'file.c']
exitcode, stdout, stderr = cppcheck(args)
assert exitcode == 1
assert (stdout == "cppcheck: Failed to load library configuration file 'none'. File not found\n"
"cppcheck: Failed to load library configuration file 'none2'. File not found\n")
assert stderr == ""
def test_message_j(tmpdir):
test_file = os.path.join(tmpdir, 'test.c')
with open(test_file, 'wt') as f:
f.write("")
args = ['-j2', test_file]
_, stdout, _ = cppcheck(args)
assert stdout == "Checking {} ...\n".format(test_file) # we were adding stray \0 characters at the end
# TODO: test missing std.cfg
def test_progress(tmpdir):
test_file = os.path.join(tmpdir, 'test.c')
with open(test_file, 'wt') as f:
f.write("""
int main(int argc)
{
}
""")
args = ['--report-progress=0', '--enable=all', '--inconclusive', '-j1', test_file]
exitcode, stdout, stderr = cppcheck(args)
assert exitcode == 0, stdout if stdout else stderr
pos = stdout.find('\n')
assert(pos != -1)
pos += 1
assert stdout[:pos] == "Checking {} ...\n".format(test_file)
assert (stdout[pos:] ==
"progress: Tokenize (typedef) 0%\n"
"progress: Tokenize (typedef) 12%\n"
"progress: Tokenize (typedef) 25%\n"
"progress: Tokenize (typedef) 37%\n"
"progress: Tokenize (typedef) 50%\n"
"progress: Tokenize (typedef) 62%\n"
"progress: Tokenize (typedef) 75%\n"
"progress: Tokenize (typedef) 87%\n"
"progress: Tokenize (typedef) 100%\n"
"progress: SymbolDatabase (find all scopes) 0%\n"
"progress: SymbolDatabase (find all scopes) 12%\n"
"progress: SymbolDatabase (find all scopes) 87%\n"
"progress: SymbolDatabase (find all scopes) 100%\n"
"progress: ValueFlow 0%\n"
"progress: ValueFlow::valueFlowImpossibleValues(tokenlist, settings) 1 0%\n"
"progress: ValueFlow::valueFlowImpossibleValues(tokenlist, settings) 1 100%\n"
"progress: ValueFlow::valueFlowSymbolicOperators(symboldatabase, settings) 1 0%\n"
"progress: ValueFlow::valueFlowSymbolicOperators(symboldatabase, settings) 1 100%\n"
"progress: ValueFlow::valueFlowCondition(SymbolicConditionHandler{}, tokenlist, symboldatabase, errorLogger, settings, skippedFunctions) 1 0%\n"
"progress: ValueFlow::valueFlowCondition(SymbolicConditionHandler{}, tokenlist, symboldatabase, errorLogger, settings, skippedFunctions) 1 100%\n"
"progress: ValueFlow::valueFlowSymbolicInfer(symboldatabase, settings) 1 0%\n"
"progress: ValueFlow::valueFlowSymbolicInfer(symboldatabase, settings) 1 100%\n"
"progress: ValueFlow::valueFlowArrayBool(tokenlist, settings) 1 0%\n"
"progress: ValueFlow::valueFlowArrayBool(tokenlist, settings) 1 100%\n"
"progress: ValueFlow::valueFlowArrayElement(tokenlist, settings) 1 0%\n"
"progress: ValueFlow::valueFlowArrayElement(tokenlist, settings) 1 100%\n"
"progress: ValueFlow::valueFlowRightShift(tokenlist, settings) 1 0%\n"
"progress: ValueFlow::valueFlowRightShift(tokenlist, settings) 1 100%\n"
"progress: ValueFlow::valueFlowCondition(ContainerConditionHandler{}, tokenlist, symboldatabase, errorLogger, settings, skippedFunctions) 1 0%\n"
"progress: ValueFlow::valueFlowCondition(ContainerConditionHandler{}, tokenlist, symboldatabase, errorLogger, settings, skippedFunctions) 1 100%\n"
"progress: ValueFlow::valueFlowAfterAssign(tokenlist, symboldatabase, errorLogger, settings, skippedFunctions) 1 0%\n"
"progress: ValueFlow::valueFlowAfterAssign(tokenlist, symboldatabase, errorLogger, settings, skippedFunctions) 1 100%\n"
"progress: ValueFlow::valueFlowAfterSwap(tokenlist, symboldatabase, errorLogger, settings) 1 0%\n"
"progress: ValueFlow::valueFlowAfterSwap(tokenlist, symboldatabase, errorLogger, settings) 1 100%\n"
"progress: ValueFlow::valueFlowCondition(SimpleConditionHandler{}, tokenlist, symboldatabase, errorLogger, settings, skippedFunctions) 1 0%\n"
"progress: ValueFlow::valueFlowCondition(SimpleConditionHandler{}, tokenlist, symboldatabase, errorLogger, settings, skippedFunctions) 1 100%\n"
"progress: ValueFlow::valueFlowInferCondition(tokenlist, settings) 1 0%\n"
"progress: ValueFlow::valueFlowInferCondition(tokenlist, settings) 1 100%\n"
"progress: ValueFlow::valueFlowSwitchVariable(tokenlist, symboldatabase, errorLogger, settings) 1 0%\n"
"progress: ValueFlow::valueFlowSwitchVariable(tokenlist, symboldatabase, errorLogger, settings) 1 100%\n"
"progress: ValueFlow::valueFlowForLoop(tokenlist, symboldatabase, errorLogger, settings) 1 0%\n"
"progress: ValueFlow::valueFlowForLoop(tokenlist, symboldatabase, errorLogger, settings) 1 100%\n"
"progress: ValueFlow::valueFlowSubFunction(tokenlist, symboldatabase, errorLogger, settings) 1 0%\n"
"progress: ValueFlow::valueFlowSubFunction(tokenlist, symboldatabase, errorLogger, settings) 1 100%\n"
"progress: ValueFlow::valueFlowFunctionReturn(tokenlist, errorLogger, settings) 1 0%\n"
"progress: ValueFlow::valueFlowFunctionReturn(tokenlist, errorLogger, settings) 1 100%\n"
"progress: ValueFlow::valueFlowLifetime(tokenlist, errorLogger, settings) 1 0%\n"
"progress: ValueFlow::valueFlowLifetime(tokenlist, errorLogger, settings) 1 100%\n"
"progress: ValueFlow::valueFlowFunctionDefaultParameter(tokenlist, symboldatabase, errorLogger, settings) 1 0%\n"
"progress: ValueFlow::valueFlowFunctionDefaultParameter(tokenlist, symboldatabase, errorLogger, settings) 1 100%\n"
"progress: ValueFlow::valueFlowUninit(tokenlist, errorLogger, settings) 1 0%\n"
"progress: ValueFlow::valueFlowUninit(tokenlist, errorLogger, settings) 1 100%\n"
"progress: ValueFlow::valueFlowAfterMove(tokenlist, symboldatabase, errorLogger, settings) 1 0%\n"
"progress: ValueFlow::valueFlowAfterMove(tokenlist, symboldatabase, errorLogger, settings) 1 100%\n"
"progress: ValueFlow::valueFlowSmartPointer(tokenlist, errorLogger, settings) 1 0%\n"
"progress: ValueFlow::valueFlowSmartPointer(tokenlist, errorLogger, settings) 1 100%\n"
"progress: ValueFlow::valueFlowIterators(tokenlist, settings) 1 0%\n"
"progress: ValueFlow::valueFlowIterators(tokenlist, settings) 1 100%\n"
"progress: ValueFlow::valueFlowCondition(IteratorConditionHandler{}, tokenlist, symboldatabase, errorLogger, settings, skippedFunctions) 1 0%\n"
"progress: ValueFlow::valueFlowCondition(IteratorConditionHandler{}, tokenlist, symboldatabase, errorLogger, settings, skippedFunctions) 1 100%\n"
"progress: ValueFlow::valueFlowIteratorInfer(tokenlist, settings) 1 0%\n"
"progress: ValueFlow::valueFlowIteratorInfer(tokenlist, settings) 1 100%\n"
"progress: ValueFlow::valueFlowContainerSize(tokenlist, symboldatabase, errorLogger, settings, skippedFunctions) 1 0%\n"
"progress: ValueFlow::valueFlowContainerSize(tokenlist, symboldatabase, errorLogger, settings, skippedFunctions) 1 100%\n"
"progress: ValueFlow::valueFlowSafeFunctions(tokenlist, symboldatabase, errorLogger, settings) 1 0%\n"
"progress: ValueFlow::valueFlowSafeFunctions(tokenlist, symboldatabase, errorLogger, settings) 1 100%\n"
"progress: ValueFlow 100%\n"
"progress: Run checkers 0%\n"
"progress: Run checkers 100%\n"
)
assert stderr == ""
def test_progress_j(tmpdir):
test_file = os.path.join(tmpdir, 'test.c')
with open(test_file, 'wt') as f:
f.write("""
int main(int argc)
{
}
""")
args = ['--report-progress=0', '--enable=all', '--inconclusive', '-j2', '--disable=unusedFunction', test_file]
exitcode, stdout, stderr = cppcheck(args)
assert exitcode == 0, stdout if stdout else stderr
assert stdout == "Checking {} ...\n".format(test_file)
assert stderr == ""
def test_execute_addon_failure_py_auto(tmpdir):
test_file = os.path.join(tmpdir, 'test.cpp')
with open(test_file, 'wt') as f:
f.write("""
void f();
""")
args = ['--addon=naming', test_file]
# provide empty PATH environment variable so python is not found and execution of addon fails
env = {'PATH': ''}
_, _, stderr = cppcheck(args, env)
assert stderr == '{}:0:0: error: Bailing out from analysis: Checking file failed: Failed to auto detect python [internalError]\n\n^\n'.format(test_file)
def test_execute_addon_failure_py_notexist(tmpdir):
test_file = os.path.join(tmpdir, 'test.cpp')
with open(test_file, 'wt') as f:
f.write("""
void f();
""")
# specify non-existent python executable so execution of addon fails
args = ['--addon=naming', '--addon-python=python5.x', test_file]
_, _, stderr = cppcheck(args)
ec = 1 if os.name == 'nt' else 127
assert stderr == "{}:0:0: error: Bailing out from analysis: Checking file failed: Failed to execute addon 'naming' - exitcode is {} [internalError]\n\n^\n".format(test_file, ec)
def test_execute_addon_failure_json_notexist(tmpdir):
# specify non-existent python executable so execution of addon fails
addon_json = os.path.join(tmpdir, 'addon.json')
with open(addon_json, 'wt') as f:
f.write(json.dumps({'executable': 'notexist'}))
test_file = os.path.join(tmpdir, 'test.cpp')
with open(test_file, 'wt') as f:
f.write("""
void f();
""")
args = [
'--addon={}'.format(addon_json),
test_file
]
_, _, stderr = cppcheck(args)
ec = 1 if os.name == 'nt' else 127
assert stderr == "{}:0:0: error: Bailing out from analysis: Checking file failed: Failed to execute addon 'addon.json' - exitcode is {} [internalError]\n\n^\n".format(test_file, ec)
@pytest.mark.skipif(sys.platform != "win32", reason="Windows specific issue")
def test_execute_addon_path_with_spaces(tmpdir):
addon_json = os.path.join(tmpdir, 'addon.json')
addon_dir = os.path.join(tmpdir, 'A Folder')
addon_script = os.path.join(addon_dir, 'addon.bat')
with open(addon_json, 'wt') as f:
f.write(json.dumps({'executable': addon_script }))
os.makedirs(addon_dir, exist_ok=True)
with open(addon_script, 'wt') as f:
f.write('@echo {"file":"1.c","linenr":1,"column":1,"severity":"error","message":"hello world","errorId":"hello","addon":"test"}')
test_file = os.path.join(tmpdir, 'test.cpp')
with open(test_file, 'wt') as f:
pass
args = [
'--addon={}'.format(addon_json),
test_file,
]
_, _, stderr = cppcheck(args)
# Make sure the full command is used
assert '1.c:1:1: error: hello world [test-hello]\n' in stderr
def test_execute_addon_failure_json_ctu_notexist(tmpdir):
# specify non-existent python executable so execution of addon fails
addon_json = os.path.join(tmpdir, 'addon.json')
with open(addon_json, 'wt') as f:
f.write(json.dumps({
'executable': 'notexist',
'ctu': True
}))
test_file = os.path.join(tmpdir, 'test.cpp')
with open(test_file, 'wt') as f:
f.write("""
void f(); """)
args = [
'--template=simple',
'--addon={}'.format(addon_json),
test_file
]
_, _, stderr = cppcheck(args)
ec = 1 if os.name == 'nt' else 127
assert stderr.splitlines() == [
"{}:0:0: error: Bailing out from analysis: Checking file failed: Failed to execute addon 'addon.json' - exitcode is {} [internalError]".format(test_file, ec),
":0:0: error: Bailing out from analysis: Whole program analysis failed: Failed to execute addon 'addon.json' - exitcode is {} [internalError]".format(ec)
]
def test_execute_addon_file0(tmpdir):
test_file = os.path.join(tmpdir, 'test.c')
with open(test_file, 'wt') as f:
f.write('void foo() {}\n')
args = ['--xml', '--addon=misra', '--enable=style', test_file]
_, _, stderr = cppcheck(args)
assert 'misra-c2012-8.2' in stderr
assert '.dump' not in stderr
# TODO: find a test case which always fails
@pytest.mark.skip
def test_internal_error(tmpdir):
test_file = os.path.join(tmpdir, 'test.cpp')
with open(test_file, 'wt') as f:
f.write("""
#include <cstdio>
void f() {
double gc = 3333.3333;
char stat[80];
sprintf(stat,"'%2.1f'",gc);
}
""")
args = [test_file]
_, _, stderr = cppcheck(args)
assert stderr == '{}:0:0: error: Bailing from out analysis: Checking file failed: converting \'1f\' to integer failed - not an integer [internalError]\n\n^\n'.format(test_file)
def test_addon_ctu_exitcode(tmpdir):
""" #12440 - Misra ctu violations found => exit code should be non-zero """
test_file = os.path.join(tmpdir, 'test.c')
with open(test_file, 'wt') as f:
f.write("""typedef enum { BLOCK = 0x80U, } E;""")
args = ['--addon=misra', '--enable=style', '--error-exitcode=1', test_file]
exitcode, _, stderr = cppcheck(args)
assert '2.3' in stderr, stderr
assert exitcode == 1
# TODO: test with -j2
def test_addon_misra(tmpdir):
test_file = os.path.join(tmpdir, 'test.cpp')
with open(test_file, 'wt') as f:
f.write("""
typedef int MISRA_5_6_VIOLATION;
""")
args = ['--addon=misra', '--enable=all', '--disable=unusedFunction', '-j1', test_file]
exitcode, stdout, stderr = cppcheck(args)
assert exitcode == 0, stdout if stdout else stderr
lines = stdout.splitlines()
assert lines == [
'Checking {} ...'.format(test_file)
]
assert stderr == '{}:2:1: style: misra violation (use --rule-texts=<file> to get proper output) [misra-c2012-2.3]\ntypedef int MISRA_5_6_VIOLATION;\n^\n'.format(test_file)
def test_addon_y2038(tmpdir):
test_file = os.path.join(tmpdir, 'test.cpp')
# TODO: trigger warning
with open(test_file, 'wt') as f:
f.write("""
extern void f()
{
time_t t = std::time(nullptr);
(void)t;
}
""")
args = ['--addon=y2038', '--enable=all', '--disable=unusedFunction', '--template=simple', test_file]
exitcode, stdout, stderr = cppcheck(args)
assert exitcode == 0, stdout if stdout else stderr
lines = stdout.splitlines()
assert lines == [
'Checking {} ...'.format(test_file)
]
assert stderr == '{}:4:21: warning: time is Y2038-unsafe [y2038-unsafe-call]\n'.format(test_file)
def test_addon_threadsafety(tmpdir):
test_file = os.path.join(tmpdir, 'test.cpp')
with open(test_file, 'wt') as f:
f.write("""
extern const char* f()
{
return strerror(1);
}
""")
args = ['--addon=threadsafety', '--enable=all', '--disable=unusedFunction', '--template=simple', test_file]
exitcode, stdout, stderr = cppcheck(args)
assert exitcode == 0, stdout if stdout else stderr
lines = stdout.splitlines()
assert lines == [
'Checking {} ...'.format(test_file)
]
assert stderr == '{}:4:12: warning: strerror is MT-unsafe [threadsafety-unsafe-call]\n'.format(test_file)
def test_addon_naming(tmpdir):
# the addon does nothing without a config
addon_file = os.path.join(tmpdir, 'naming1.json')
with open(addon_file, 'wt') as f:
f.write("""
{
"script": "addons/naming.py",
"args": [
"--var=[_a-z].*"
]
}
""")
test_file = os.path.join(tmpdir, 'test.cpp')
with open(test_file, 'wt') as f:
f.write("""
int Var;
""")
args = ['--addon={}'.format(addon_file), '--enable=all', '--disable=unusedFunction', '--template=simple', test_file]
exitcode, stdout, stderr = cppcheck(args)
assert exitcode == 0, stdout if stdout else stderr
lines = stdout.splitlines()
assert lines == [
'Checking {} ...'.format(test_file)
]
assert stderr == '{}:2:1: style: Variable Var violates naming convention [naming-varname]\n'.format(test_file)
def test_addon_namingng(tmpdir):
addon_file = os.path.join(tmpdir, 'namingng.json')
addon_config_file = os.path.join(tmpdir, 'namingng.config.json')
with open(addon_file, 'wt') as f:
f.write("""
{
"script": "addons/namingng.py",
"args": [
"--configfile=%s"
]
}
"""%(addon_config_file).replace('\\','\\\\'))
with open(addon_config_file, 'wt') as f:
f.write("""
{
"RE_FILE": [
"[^/]*[a-z][a-z0-9_]*[a-z0-9]\\.c\\Z"
],
"RE_CLASS_NAME": ["[a-z][a-z0-9_]*[a-z0-9]\\Z"],
"RE_NAMESPACE": ["[a-z][a-z0-9_]*[a-z0-9]\\Z"],
"RE_VARNAME": ["[a-z][a-z0-9_]*[a-z0-9]\\Z"],
"RE_PUBLIC_MEMBER_VARIABLE": ["[a-z][a-z0-9_]*[a-z0-9]\\Z"],
"RE_PRIVATE_MEMBER_VARIABLE": {
".*_tmp\\Z":[true,"illegal suffix _tmp"],
"priv_.*\\Z":[false,"required prefix priv_ missing"]
},
"RE_GLOBAL_VARNAME": ["[a-z][a-z0-9_]*[a-z0-9]\\Z"],
"RE_FUNCTIONNAME": ["[a-z][a-z0-9_]*[a-z0-9]\\Z"],
"include_guard": {
"input": "basename",
"prefix": "_",
"suffix": "",
"case": "upper",
"max_linenr": 5,
"RE_HEADERFILE": ".*\\.h\\Z",
"required": true
},
"var_prefixes": {"uint32_t": "ui32"},
"function_prefixes": {"uint16_t": "ui16",
"uint32_t": "ui32"},
"skip_one_char_variables": false
}
""".replace('\\','\\\\'))
test_unguarded_include_file_basename = 'test_unguarded.h'
test_unguarded_include_file = os.path.join(tmpdir, test_unguarded_include_file_basename)
with open(test_unguarded_include_file, 'wt') as f:
f.write("""
void InvalidFunctionUnguarded();
""")
test_include_file_basename = '_test.h'
test_include_file = os.path.join(tmpdir, test_include_file_basename)
with open(test_include_file, 'wt') as f:
f.write("""
#ifndef TEST_H
#define TEST_H
void InvalidFunction();
extern int _invalid_extern_global;
#include "{}"
#endif
""".format(test_unguarded_include_file))
test_file_basename = 'test_.cpp'
test_file = os.path.join(tmpdir, test_file_basename)
with open(test_file, 'wt') as f:
f.write("""
#include "%s"
void invalid_function_();
void _invalid_function();
void valid_function1();
void valid_function2(int _invalid_arg);
void valid_function3(int invalid_arg_);
void valid_function4(int valid_arg32);
void valid_function5(uint32_t invalid_arg32);
void valid_function6(uint32_t ui32_valid_arg);
uint16_t invalid_function7(int valid_arg);
uint16_t ui16_valid_function8(int valid_arg);
int _invalid_global;
static int _invalid_static_global;
class _clz {
public:
_clz() : _invalid_public(0), _invalid_private(0), priv_good(0), priv_bad_tmp(0) { }
int _invalid_public;
private:
char _invalid_private;
int priv_good;
int priv_bad_tmp;
};
namespace _invalid_namespace { }
"""%(test_include_file_basename))
args = ['--addon='+addon_file, '--verbose', '--enable=all', '--disable=unusedFunction', test_file]
exitcode, stdout, stderr = cppcheck(args)
assert exitcode == 0, stdout if stdout else stderr
lines = __remove_verbose_log(stdout.splitlines())
assert lines == [
'Checking {} ...'.format(test_file)
]
lines = [line for line in stderr.splitlines() if line != '']
expect = [
'{}:0:0: style: File name {} violates naming convention [namingng-namingConvention]'.format(test_include_file,test_include_file_basename),
'^',
'{}:2:9: style: include guard naming violation; TEST_H != _TEST_H [namingng-includeGuardName]'.format(test_include_file),
'#ifndef TEST_H',
' ^',
'{}:5:6: style: Function InvalidFunction violates naming convention [namingng-namingConvention]'.format(test_include_file),
'void InvalidFunction();',
' ^',
'{}:6:12: style: Global variable _invalid_extern_global violates naming convention [namingng-namingConvention]'.format(test_include_file),
'extern int _invalid_extern_global;',
' ^',
'{}:0:0: style: File name {} violates naming convention [namingng-namingConvention]'.format(test_unguarded_include_file,test_unguarded_include_file_basename),
'^',
'{}:0:0: style: Missing include guard [namingng-includeGuardMissing]'.format(test_unguarded_include_file),
'^',
'{}:2:6: style: Function InvalidFunctionUnguarded violates naming convention [namingng-namingConvention]'.format(test_unguarded_include_file),
'void InvalidFunctionUnguarded();',
' ^',
'{}:0:0: style: File name {} violates naming convention [namingng-namingConvention]'.format(test_file,test_file_basename),
'^',
'{}:7:26: style: Variable _invalid_arg violates naming convention [namingng-namingConvention]'.format(test_file),
'void valid_function2(int _invalid_arg);',
' ^',
'{}:8:26: style: Variable invalid_arg_ violates naming convention [namingng-namingConvention]'.format(test_file),
'void valid_function3(int invalid_arg_);',
' ^',
'{}:10:31: style: Variable invalid_arg32 violates naming convention [namingng-namingConvention]'.format(test_file),
'void valid_function5(uint32_t invalid_arg32);',
' ^',
'{}:4:6: style: Function invalid_function_ violates naming convention [namingng-namingConvention]'.format(test_file),
'void invalid_function_();',
' ^',
'{}:5:6: style: Function _invalid_function violates naming convention [namingng-namingConvention]'.format(test_file),
'void _invalid_function();',
' ^',
'{}:12:10: style: Function invalid_function7 violates naming convention [namingng-namingConvention]'.format(test_file),
'uint16_t invalid_function7(int valid_arg);',
' ^',
'{}:15:5: style: Global variable _invalid_global violates naming convention [namingng-namingConvention]'.format(test_file),
'int _invalid_global;',
' ^',
'{}:16:12: style: Global variable _invalid_static_global violates naming convention [namingng-namingConvention]'.format(test_file),
'static int _invalid_static_global;',
' ^',
'{}:20:5: style: Class Constructor _clz violates naming convention [namingng-namingConvention]'.format(test_file),
' _clz() : _invalid_public(0), _invalid_private(0), priv_good(0), priv_bad_tmp(0) { }',
' ^',
'{}:21:9: style: Public member variable _invalid_public violates naming convention [namingng-namingConvention]'.format(test_file),
' int _invalid_public;',
' ^',
'{}:23:10: style: Private member variable _invalid_private violates naming convention: required prefix priv_ missing [namingng-namingConvention]'.format(test_file),
' char _invalid_private;',
' ^',
'{}:25:9: style: Private member variable priv_bad_tmp violates naming convention: illegal suffix _tmp [namingng-namingConvention]'.format(test_file),
' int priv_bad_tmp;',
' ^',
'{}:28:11: style: Namespace _invalid_namespace violates naming convention [namingng-namingConvention]'.format(test_file),
'namespace _invalid_namespace { }',
' ^',
]
# test sorted lines; the order of messages may vary and is not of importance
lines.sort()
expect.sort()
assert lines == expect
# TODO: test with -j2
def test_addon_namingng_config(tmpdir):
addon_file = os.path.join(tmpdir, 'namingng.json')
addon_config_file = os.path.join(tmpdir, 'namingng.config.json')
with open(addon_file, 'wt') as f:
f.write("""
{
"script": "addons/namingng.py",
"args": [
"--configfile=%s"
]
}
"""%(addon_config_file).replace('\\','\\\\'))
with open(addon_config_file, 'wt') as f:
f.write("""
{
"RE_FILE": "[^/]*[a-z][a-z0-9_]*[a-z0-9]\\.c\\Z",
"RE_NAMESPACE": false,
"RE_VARNAME": ["+bad pattern","[a-z]_good_pattern\\Z","(parentheses?"],
"RE_PRIVATE_MEMBER_VARIABLE": "[a-z][a-z0-9_]*[a-z0-9]\\Z",
"RE_PUBLIC_MEMBER_VARIABLE": {
"tmp_.*\\Z":[true,"illegal prefix tmp_"],
"bad_.*\\Z":true,
"public_.*\\Z":[false],
"pub_.*\\Z":[0,"required prefix pub_ missing"]
},
"RE_GLOBAL_VARNAME": "[a-z][a-z0-9_]*[a-z0-9]\\Z",
"RE_FUNCTIONNAME": "[a-z][a-z0-9_]*[a-z0-9]\\Z",
"RE_CLASS_NAME": "[a-z][a-z0-9_]*[a-z0-9]\\Z",
"_comment1": "these should all be arrays, or null, or not set",
"include_guard": true,
"var_prefixes": ["bad"],
"function_prefixes": false,
"_comment2": "these should all be dict",
"skip_one_char_variables": "false",
"_comment3": "this should be bool",
"RE_VAR_NAME": "typo"
}
""".replace('\\','\\\\'))
test_file_basename = 'test.c'
test_file = os.path.join(tmpdir, test_file_basename)
with open(test_file, 'a'):
# only create the file
pass
args = ['--addon='+addon_file, '--verbose', '--enable=all', '-j1', test_file]
exitcode, stdout, stderr = cppcheck(args)
assert exitcode == 0, stdout if stdout else stderr
lines = __remove_verbose_log(stdout.splitlines())
assert lines == [
'Checking {} ...'.format(test_file)
]
lines = stderr.splitlines()
# ignore the first line, stating that the addon failed to run properly
lines.pop(0)
assert lines == [
"Output:",
"config error: RE_FILE must be list (not str), or not set",
"config error: RE_NAMESPACE must be list or dict (not bool), or not set",
"config error: include_guard must be dict (not bool), or not set",
"config error: item '+bad pattern' of 'RE_VARNAME' is not a valid regular expression: nothing to repeat at position 0",
"config error: item '(parentheses?' of 'RE_VARNAME' is not a valid regular expression: missing ), unterminated subpattern at position 0",
"config error: var_prefixes must be dict (not list), or not set",
"config error: RE_PRIVATE_MEMBER_VARIABLE must be list or dict (not str), or not set",
"config error: item 'bad_.*\\Z' of 'RE_PUBLIC_MEMBER_VARIABLE' must be an array [bool,string]",
"config error: item 'public_.*\\Z' of 'RE_PUBLIC_MEMBER_VARIABLE' must be an array [bool,string]",
"config error: item 'pub_.*\\Z' of 'RE_PUBLIC_MEMBER_VARIABLE' must be an array [bool,string]",
"config error: RE_GLOBAL_VARNAME must be list or dict (not str), or not set",
"config error: RE_FUNCTIONNAME must be list or dict (not str), or not set",
"config error: function_prefixes must be dict (not bool), or not set",
"config error: RE_CLASS_NAME must be list or dict (not str), or not set",
"config error: skip_one_char_variables must be bool (not str), or not set",
"config error: unknown config key 'RE_VAR_NAME' [internalError]",
"",
"^",
]
def test_addon_findcasts(tmpdir):
test_file = os.path.join(tmpdir, 'test.cpp')
with open(test_file, 'wt') as f:
f.write("""
extern void f(char c)
{
int i = (int)c;
(void)i;
}
""")
args = ['--addon=findcasts', '--enable=all', '--disable=unusedFunction', '--template=simple', test_file]
exitcode, stdout, stderr = cppcheck(args)
assert exitcode == 0, stdout if stdout else stderr
lines = stdout.splitlines()
assert lines == [
'Checking {} ...'.format(test_file)
]
assert stderr == '{}:4:21: information: found a cast [findcasts-cast]\n'.format(test_file)
def test_addon_misc(tmpdir):
test_file = os.path.join(tmpdir, 'test.cpp')
with open(test_file, 'wt') as f:
f.write("""
extern void f()
{
const char* c[] = {"a" "b"};
}
""")
args = ['--addon=misc', '--enable=all', '--disable=unusedFunction', '--template=simple', test_file]
exitcode, stdout, stderr = cppcheck(args)
assert exitcode == 0, stdout if stdout else stderr
lines = stdout.splitlines()
assert lines == [
'Checking {} ...'.format(test_file)
]
assert stderr == '{}:4:28: style: String concatenation in array initialization, missing comma? [misc-stringConcatInArrayInit]\n'.format(test_file)
def test_invalid_addon_json(tmpdir):
addon_file = os.path.join(tmpdir, 'addon1.json')
with open(addon_file, 'wt') as f:
f.write("""
""")
test_file = os.path.join(tmpdir, 'file.cpp')
with open(test_file, 'wt'):
pass
args = ['--addon={}'.format(addon_file), test_file]
exitcode, stdout, stderr = cppcheck(args)
assert exitcode == 1
lines = stdout.splitlines()
assert lines == [
'Loading {} failed. syntax error at line 2 near: '.format(addon_file)
]
assert stderr == ''
def test_invalid_addon_py(tmpdir):
addon_file = os.path.join(tmpdir, 'addon1.py')
with open(addon_file, 'wt') as f:
f.write("""
raise Exception()
""")
test_file = os.path.join(tmpdir, 'file.cpp')
with open(test_file, 'wt') as f:
f.write("""
typedef int MISRA_5_6_VIOLATION;
""")
args = ['--addon={}'.format(addon_file), '--enable=all', '--disable=unusedFunction', test_file]
exitcode, stdout, stderr = cppcheck(args)
assert exitcode == 0 # TODO: needs to be 1
lines = stdout.splitlines()
assert lines == [
'Checking {} ...'.format(test_file)
]
assert stderr == "{}:0:0: error: Bailing out from analysis: Checking file failed: Failed to execute addon 'addon1' - exitcode is 1 [internalError]\n\n^\n".format(test_file)
# TODO: test with -j2
def test_invalid_addon_py_verbose(tmpdir):
addon_file = os.path.join(tmpdir, 'addon1.py')
with open(addon_file, 'wt') as f:
f.write("""
raise Exception()
""")
test_file = os.path.join(tmpdir, 'file.cpp')
with open(test_file, 'wt') as f:
f.write("""
typedef int MISRA_5_6_VIOLATION;
""")
args = ['--addon={}'.format(addon_file), '--enable=all', '--disable=unusedFunction', '--verbose', '-j1', test_file]
exitcode, stdout, stderr = cppcheck(args)
assert exitcode == 0 # TODO: needs to be 1
lines = __remove_verbose_log(stdout.splitlines())
assert lines == [
'Checking {} ...'.format(test_file)
]
"""
/tmp/pytest-of-user/pytest-11/test_invalid_addon_py_20/file.cpp:0:0: error: Bailing out from analysis: Checking file failed: Failed to execute addon 'addon1' - exitcode is 1: python3 /home/user/CLionProjects/cppcheck/addons/runaddon.py /tmp/pytest-of-user/pytest-11/test_invalid_addon_py_20/addon1.py --cli /tmp/pytest-of-user/pytest-11/test_invalid_addon_py_20/file.cpp.24762.dump
Output:
Traceback (most recent call last):
File "/home/user/CLionProjects/cppcheck/addons/runaddon.py", line 8, in <module>
runpy.run_path(addon, run_name='__main__')
File "<frozen runpy>", line 291, in run_path
File "<frozen runpy>", line 98, in _run_module_code
File "<frozen runpy>", line 88, in _run_code
File "/tmp/pytest-of-user/pytest-11/test_invalid_addon_py_20/addon1.py", line 2, in <module>
raise Exception()
Exceptio [internalError]
"""
# /tmp/pytest-of-user/pytest-10/test_invalid_addon_py_20/file.cpp:0:0: error: Bailing out from analysis: Checking file failed: Failed to execute addon 'addon1' - exitcode is 256.: python3 /home/user/CLionProjects/cppcheck/addons/runaddon.py /tmp/pytest-of-user/pytest-10/test_invalid_addon_py_20/addon1.py --cli /tmp/pytest-of-user/pytest-10/test_invalid_addon_py_20/file.cpp.24637.dump
assert stderr.startswith("{}:0:0: error: Bailing out from analysis: Checking file failed: Failed to execute addon 'addon1' - exitcode is 1: ".format(test_file))
assert stderr.count('Output:\nTraceback')
assert stderr.endswith('raise Exception()\nException [internalError]\n\n^\n')
def test_addon_result(tmpdir):
addon_file = os.path.join(tmpdir, 'addon1.py')
with open(addon_file, 'wt') as f:
f.write("""
print("Checking ...")
print("")
print('{"file": "test.cpp", "linenr": 1, "column": 1, "severity": "style", "message": "msg", "addon": "addon1", "errorId": "id", "extra": ""}')
print('{"loc": [{"file": "test.cpp", "linenr": 1, "column": 1, "info": ""}], "severity": "style", "message": "msg", "addon": "addon1", "errorId": "id", "extra": ""}')
""")
test_file = os.path.join(tmpdir, 'file.cpp')
with open(test_file, 'wt') as f:
f.write("""
typedef int MISRA_5_6_VIOLATION;
""")
args = ['--addon={}'.format(addon_file), '--enable=all', '--disable=unusedFunction', test_file]
exitcode, stdout, stderr = cppcheck(args)
assert exitcode == 0 # TODO: needs to be 1
lines = stdout.splitlines()
assert lines == [
'Checking {} ...'.format(test_file)
]
assert stderr == 'test.cpp:1:1: style: msg [addon1-id]\n\n^\n'
# TODO: test with -j2
# #11483
def __test_unused_function_include(tmpdir, extra_args):
test_cpp_file = os.path.join(tmpdir, 'test.cpp')
with open(test_cpp_file, 'wt') as f:
f.write("""
#include "test.h"
""")
test_h_file = os.path.join(tmpdir, 'test.h')
with open(test_h_file, 'wt') as f:
f.write("""
class A {
public:
void f() {}
// cppcheck-suppress unusedFunction
void f2() {}
};
""")
args = [
'--enable=unusedFunction',
'--inline-suppr',
'--template=simple',
'-j1',
test_cpp_file
]
args += extra_args
_, _, stderr = cppcheck(args)
assert stderr == "{}:4:26: style: The function 'f' is never used. [unusedFunction]\n".format(test_h_file)
def test_unused_function_include(tmpdir):
__test_unused_function_include(tmpdir, [])
# TODO: test with clang-tidy
# TODO: test with --addon
# TODO: test with FileSettings
# TODO: test with multiple files
def __test_showtime(tmp_path, showtime, exp_res, exp_last, extra_args=None):
test_file = tmp_path / 'test.cpp'
with open(test_file, 'wt') as f:
f.write(
"""
void f()
{
(void)(*((int*)0)); // cppcheck-suppress nullPointer
}
""")
args = [
f'--showtime={showtime}',
'--quiet',
'--inline-suppr',
str(test_file)
]
if extra_args:
args += extra_args
exitcode, stdout, stderr = cppcheck(args)
assert exitcode == 0
lines = stdout.splitlines()
exp_len = exp_res
if 'cppcheck internal API usage' in stdout:
exp_len += 1
exp_len += 1 # last line
assert len(lines) == exp_len
for i in range(1, exp_res):
assert 'avg.' in lines[i]
assert lines[exp_len-1].startswith(exp_last)
assert not 'avg.' in lines[exp_len-1]
assert stderr == ''
def test_showtime_top5_file(tmp_path):
__test_showtime(tmp_path, 'top5_file', 5, 'Check time: ')