forked from scylladb/scylladb
-
Notifications
You must be signed in to change notification settings - Fork 0
/
test.py
executable file
·2184 lines (1900 loc) · 98 KB
/
test.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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Copyright (C) 2015-present ScyllaDB
#
#
# SPDX-License-Identifier: AGPL-3.0-or-later
#
import argparse
import asyncio
import collections
import colorama
import difflib
import filecmp
import glob
import itertools
import logging
import multiprocessing
import os
import pathlib
import re
import resource
import shlex
import shutil
import signal
import subprocess
import sys
import time
import traceback
import xml.etree.ElementTree as ET
import yaml
from abc import ABC, abstractmethod
from io import StringIO
from scripts import coverage # type: ignore
from test.pylib.artifact_registry import ArtifactRegistry
from test.pylib.host_registry import HostRegistry
from test.pylib.pool import Pool
from test.pylib.s3_proxy import S3ProxyServer
from test.pylib.s3_server_mock import MockS3Server
from test.pylib.resource_gather import setup_cgroup, run_resource_watcher, get_resource_gather
from test.pylib.util import LogPrefixAdapter
from test.pylib.scylla_cluster import ScyllaServer, ScyllaCluster, get_cluster_manager, merge_cmdline_options
from test.pylib.minio_server import MinioServer
from typing import Dict, List, Callable, Any, Iterable, Optional, Awaitable, Union
import logging
from test.pylib import coverage_utils
import humanfriendly
import treelib
launch_time = time.monotonic()
output_is_a_tty = sys.stdout.isatty()
all_modes = {'debug': 'Debug',
'release': 'RelWithDebInfo',
'dev': 'Dev',
'sanitize': 'Sanitize',
'coverage': 'Coverage'}
debug_modes = {'debug', 'sanitize'}
def create_formatter(*decorators) -> Callable[[Any], str]:
"""Return a function which decorates its argument with the given
color/style if stdout is a tty, and leaves intact otherwise."""
def color(arg: Any) -> str:
return "".join(decorators) + str(arg) + colorama.Style.RESET_ALL
def nocolor(arg: Any) -> str:
return str(arg)
return color if output_is_a_tty else nocolor
class palette:
"""Color palette for formatting terminal output"""
ok = create_formatter(colorama.Fore.GREEN, colorama.Style.BRIGHT)
fail = create_formatter(colorama.Fore.RED, colorama.Style.BRIGHT)
new = create_formatter(colorama.Fore.BLUE)
skip = create_formatter(colorama.Style.DIM)
path = create_formatter(colorama.Style.BRIGHT)
diff_in = create_formatter(colorama.Fore.GREEN)
diff_out = create_formatter(colorama.Fore.RED)
diff_mark = create_formatter(colorama.Fore.MAGENTA)
warn = create_formatter(colorama.Fore.YELLOW)
crit = create_formatter(colorama.Fore.RED, colorama.Style.BRIGHT)
ansi_escape = re.compile(r'\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])')
@staticmethod
def nocolor(text: str) -> str:
return palette.ansi_escape.sub('', text)
def path_to(mode, *components):
"""Resolve path to built executable"""
build_dir = 'build'
if os.path.exists(os.path.join(build_dir, 'build.ninja')):
*dir_components, basename = components
exe_path = os.path.join(build_dir, *dir_components, all_modes[mode], basename)
else:
exe_path = os.path.join(build_dir, mode, *components)
if not os.access(exe_path, os.F_OK):
raise FileNotFoundError(f"{exe_path} does not exist.")
elif not os.access(exe_path, os.X_OK):
raise PermissionError(f"{exe_path} is not executable.")
return exe_path
def ninja(target):
"""Build specified target using ninja"""
build_dir = 'build'
args = ['ninja', target]
if os.path.exists(os.path.join(build_dir, 'build.ninja')):
args = ['ninja', '-C', build_dir, target]
return subprocess.Popen(args, stdout=subprocess.PIPE).communicate()[0].decode()
class TestSuite(ABC):
"""A test suite is a folder with tests of the same type.
E.g. it can be unit tests, boost tests, or CQL tests."""
# All existing test suites, one suite per path/mode.
suites: Dict[str, 'TestSuite'] = dict()
artifacts = ArtifactRegistry()
hosts = HostRegistry()
FLAKY_RETRIES = 5
_next_id = collections.defaultdict(int) # (test_key -> id)
def __init__(self, path: str, cfg: dict, options: argparse.Namespace, mode: str) -> None:
self.suite_path = pathlib.Path(path)
self.name = str(self.suite_path.name)
self.cfg = cfg
self.options = options
self.mode = mode
self.suite_key = os.path.join(path, mode)
self.tests: List['Test'] = []
self.pending_test_count = 0
# The number of failed tests
self.n_failed = 0
self.run_first_tests = set(cfg.get("run_first", []))
self.no_parallel_cases = set(cfg.get("no_parallel_cases", []))
# Skip tests disabled in suite.yaml
self.disabled_tests = set(self.cfg.get("disable", []))
# Skip tests disabled in specific mode.
self.disabled_tests.update(self.cfg.get("skip_in_" + mode, []))
self.flaky_tests = set(self.cfg.get("flaky", []))
# If this mode is one of the debug modes, and there are
# tests disabled in a debug mode, add these tests to the skip list.
if mode in debug_modes:
self.disabled_tests.update(self.cfg.get("skip_in_debug_modes", []))
# If a test is listed in run_in_<mode>, it should only be enabled in
# this mode. Tests not listed in any run_in_<mode> directive should
# run in all modes. Inversing this, we should disable all tests
# which are listed explicitly in some run_in_<m> where m != mode
# This of course may create ambiguity with skip_* settings,
# since the priority of the two is undefined, but oh well.
run_in_m = set(self.cfg.get("run_in_" + mode, []))
for a in all_modes:
if a == mode:
continue
skip_in_m = set(self.cfg.get("run_in_" + a, []))
self.disabled_tests.update(skip_in_m - run_in_m)
# environment variables that should be the base of all processes running in this suit
self.base_env = {}
if self.need_coverage():
# Set the coverage data from each instrumented object to use the same file (and merged into it with locking)
# as long as we don't need test specific coverage data, this looks sufficient. The benefit of doing this in
# this way is that the storage will not be bloated with coverage files (each can weigh 10s of MBs so for several
# thousands of tests it can easily reach 10 of GBs)
# ref: https://clang.llvm.org/docs/SourceBasedCodeCoverage.html#running-the-instrumented-program
self.base_env["LLVM_PROFILE_FILE"] = os.path.join(options.tmpdir,self.mode, "coverage", self.name, "%m.profraw")
# Generate a unique ID for `--repeat`ed tests
# We want these tests to have different XML IDs so test result
# processors (Jenkins) don't merge results for different iterations of
# the same test. We also don't want the ids to be too random, because then
# there is no correlation between test identifiers across multiple
# runs of test.py, and so it's hard to understand failure trends. The
# compromise is for next_id() results to be unique only within a particular
# test case. That is, we'll have a.1, a.2, a.3, b.1, b.2, b.3 rather than
# a.1 a.2 a.3 b.4 b.5 b.6.
def next_id(self, test_key) -> int:
TestSuite._next_id[test_key] += 1
return TestSuite._next_id[test_key]
@staticmethod
def test_count() -> int:
return sum(TestSuite._next_id.values())
@staticmethod
def load_cfg(path: str) -> dict:
with open(os.path.join(path, "suite.yaml"), "r") as cfg_file:
cfg = yaml.safe_load(cfg_file.read())
if not isinstance(cfg, dict):
raise RuntimeError("Failed to load tests in {}: suite.yaml is empty".format(path))
return cfg
@staticmethod
def opt_create(path: str, options: argparse.Namespace, mode: str) -> 'TestSuite':
"""Return a subclass of TestSuite with name cfg["type"].title + TestSuite.
Ensures there is only one suite instance per path."""
suite_key = os.path.join(path, mode)
suite = TestSuite.suites.get(suite_key)
if not suite:
cfg = TestSuite.load_cfg(path)
kind = cfg.get("type")
if kind is None:
raise RuntimeError("Failed to load tests in {}: suite.yaml has no suite type".format(path))
def suite_type_to_class_name(suite_type: str) -> str:
if suite_type.casefold() == "Approval".casefold():
suite_type = "CQLApproval"
else:
suite_type = suite_type.title()
return suite_type + "TestSuite"
SpecificTestSuite = globals().get(suite_type_to_class_name(kind))
if not SpecificTestSuite:
raise RuntimeError("Failed to load tests in {}: suite type '{}' not found".format(path, kind))
suite = SpecificTestSuite(path, cfg, options, mode)
assert suite is not None
TestSuite.suites[suite_key] = suite
return suite
@staticmethod
def all_tests() -> Iterable['Test']:
return itertools.chain(*(suite.tests for suite in
TestSuite.suites.values()))
@property
@abstractmethod
def pattern(self) -> str:
pass
@abstractmethod
async def add_test(self, shortname: str, casename: str) -> None:
pass
async def run(self, test: 'Test', options: argparse.Namespace):
try:
test.started = True
for i in range(1, self.FLAKY_RETRIES):
if i > 1:
test.is_flaky_failure = True
logging.info("Retrying test %s after a flaky fail, retry %d", test.uname, i)
test.reset()
await test.run(options)
if test.success or not test.is_flaky or test.is_cancelled:
break
except asyncio.CancelledError:
test.is_cancelled = True
finally:
self.pending_test_count -= 1
self.n_failed += int(test.failed)
if self.pending_test_count == 0:
await TestSuite.artifacts.cleanup_after_suite(self, self.n_failed > 0)
return test
def junit_tests(self):
"""Tests which participate in a consolidated junit report"""
return self.tests
def boost_tests(self):
return []
def build_test_list(self) -> List[str]:
return [os.path.splitext(t.relative_to(self.suite_path))[0] for t in
self.suite_path.glob(self.pattern)]
async def add_test_list(self) -> None:
options = self.options
lst = self.build_test_list()
if lst:
# Some tests are long and are better to be started earlier,
# so pop them up while sorting the list
lst.sort(key=lambda x: (x not in self.run_first_tests, x))
pending = set()
for shortname in lst:
testname = os.path.join(self.name, shortname)
casename = None
# Check opt-out lists
if shortname in self.disabled_tests:
continue
if options.skip_patterns:
if any(skip_pattern in testname for skip_pattern in options.skip_patterns):
continue
# Check opt-in list
if options.name:
for p in options.name:
pn = p.split('::', 2)
if len(pn) == 1 and p in testname:
break
if len(pn) == 2 and pn[0] == testname:
if pn[1] != "*":
casename = pn[1]
break
else:
continue
async def add_test(shortname, casename) -> None:
# Add variants of the same test sequentially
# so that case cache has a chance to populate
for i in range(options.repeat):
await self.add_test(shortname, casename)
self.pending_test_count += 1
pending.add(asyncio.create_task(add_test(shortname, casename)))
if len(pending) == 0:
return
try:
await asyncio.gather(*pending)
except asyncio.CancelledError:
for task in pending:
task.cancel()
await asyncio.gather(*pending, return_exceptions=True)
raise
def need_coverage(self):
return self.options.coverage and (self.mode in self.options.coverage_modes) and bool(self.cfg.get("coverage",True))
class UnitTestSuite(TestSuite):
"""TestSuite instantiation for non-boost unit tests"""
def __init__(self, path: str, cfg: dict, options: argparse.Namespace, mode: str) -> None:
super().__init__(path, cfg, options, mode)
# Map of custom test command line arguments, if configured
self.custom_args = cfg.get("custom_args", {})
# Map of tests that cannot run with compaction groups
self.all_can_run_compaction_groups_except = cfg.get("all_can_run_compaction_groups_except")
async def create_test(self, shortname, casename, suite, args):
exe = path_to(suite.mode, "test", suite.name, shortname)
if not os.access(exe, os.X_OK):
print(palette.warn(f"Unit test executable {exe} not found."))
return
test = UnitTest(self.next_id((shortname, self.suite_key)), shortname, suite, args)
self.tests.append(test)
async def add_test(self, shortname, casename) -> None:
"""Create a UnitTest class with possibly custom command line
arguments and add it to the list of tests"""
# Skip tests which are not configured, and hence are not built
if os.path.join("test", self.name, shortname) not in self.options.tests:
return
# Default seastar arguments, if not provided in custom test options,
# are two cores and 2G of RAM
args = self.custom_args.get(shortname, ["-c2 -m2G"])
args = merge_cmdline_options(args, self.options.extra_scylla_cmdline_options)
for a in args:
await self.create_test(shortname, casename, self, a)
@property
def pattern(self) -> str:
return "*_test.cc"
class BoostTestSuite(UnitTestSuite):
"""TestSuite for boost unit tests"""
# A cache of individual test cases, for which we have called
# --list_content. Static to share across all modes.
_case_cache: Dict[str, List[str]] = dict()
def __init__(self, path, cfg: dict, options: argparse.Namespace, mode) -> None:
super().__init__(path, cfg, options, mode)
async def create_test(self, shortname: str, casename: str, suite, args) -> None:
exe = path_to(suite.mode, "test", suite.name, shortname)
if not os.access(exe, os.X_OK):
print(palette.warn(f"Boost test executable {exe} not found."))
return
options = self.options
allows_compaction_groups = self.all_can_run_compaction_groups_except != None and shortname not in self.all_can_run_compaction_groups_except
if options.parallel_cases and (shortname not in self.no_parallel_cases) and casename is None:
fqname = os.path.join(self.mode, self.name, shortname)
if fqname not in self._case_cache:
process = await asyncio.create_subprocess_exec(
exe, *['--list_content'],
stderr=asyncio.subprocess.PIPE,
stdout=asyncio.subprocess.PIPE,
env=dict(os.environ,
**{"ASAN_OPTIONS": "halt_on_error=0"}),
preexec_fn=os.setsid,
)
_, stderr = await asyncio.wait_for(process.communicate(), options.timeout)
# --list_content produces the list of all test cases in the file. When BOOST_DATA_TEST_CASE is used it
# will additionally produce the lines with numbers for each case preserving the function name like this:
# test_singular_tree_ptr_sz*
# _0*
# _1*
# _2*
# however, it's only possible to run test_singular_tree_ptr_sz that will execute all test cases
# this line catches only test function name ignoring unrelated lines like '_0'
# Note: this will ignore any test case starting with a '_' symbol
case_list = [case[:-1] for case in stderr.decode().splitlines() if case.endswith('*') and not case.strip().startswith('_')]
self._case_cache[fqname] = case_list
case_list = self._case_cache[fqname]
if len(case_list) == 1:
test = BoostTest(self.next_id((shortname, self.suite_key)), shortname, suite, args, None, allows_compaction_groups)
self.tests.append(test)
else:
for case in case_list:
test = BoostTest(self.next_id((shortname, self.suite_key, case)), shortname, suite, args, case, allows_compaction_groups)
self.tests.append(test)
else:
test = BoostTest(self.next_id((shortname, self.suite_key)), shortname, suite, args, casename, allows_compaction_groups)
self.tests.append(test)
def junit_tests(self) -> Iterable['Test']:
"""Boost tests produce an own XML output, so are not included in a junit report"""
return []
def boost_tests(self) -> Iterable['Tests']:
return self.tests
class PythonTestSuite(TestSuite):
"""A collection of Python pytests against a single Scylla instance"""
def __init__(self, path, cfg: dict, options: argparse.Namespace, mode: str) -> None:
super().__init__(path, cfg, options, mode)
self.scylla_exe = path_to(self.mode, "scylla")
self.scylla_env = dict(self.base_env)
if self.mode == "coverage":
self.scylla_env.update(coverage.env(self.scylla_exe, distinct_id=self.name))
self.scylla_env['SCYLLA'] = self.scylla_exe
cluster_cfg = self.cfg.get("cluster", {"initial_size": 1})
cluster_size = cluster_cfg["initial_size"]
env_pool_size = os.getenv("CLUSTER_POOL_SIZE")
if options.cluster_pool_size is not None:
pool_size = options.cluster_pool_size
elif env_pool_size is not None:
pool_size = int(env_pool_size)
else:
pool_size = cfg.get("pool_size", 2)
self.dirties_cluster = set(cfg.get("dirties_cluster", []))
self.create_cluster = self.get_cluster_factory(cluster_size, options)
async def recycle_cluster(cluster: ScyllaCluster) -> None:
"""When a dirty cluster is returned to the cluster pool,
stop it and release the used IPs. We don't necessarily uninstall() it yet,
which would delete the log file and directory - we might want to preserve
these if it came from a failed test.
"""
for srv in cluster.running.values():
srv.log_file.close()
srv.maintenance_socket_dir.cleanup()
await cluster.stop()
await cluster.release_ips()
self.clusters = Pool(pool_size, self.create_cluster, recycle_cluster)
def get_cluster_factory(self, cluster_size: int, options: argparse.Namespace) -> Callable[..., Awaitable]:
def create_server(create_cfg: ScyllaCluster.CreateServerParams):
cmdline_options = self.cfg.get("extra_scylla_cmdline_options", [])
if type(cmdline_options) == str:
cmdline_options = [cmdline_options]
cmdline_options = merge_cmdline_options(cmdline_options, create_cfg.cmdline_from_test)
cmdline_options = merge_cmdline_options(cmdline_options, options.extra_scylla_cmdline_options)
# There are multiple sources of config options, with increasing priority
# (if two sources provide the same config option, the higher priority one wins):
# 1. the defaults
# 2. suite-specific config options (in "extra_scylla_config_options")
# 3. config options from tests (when servers are added during a test)
default_config_options = \
{"authenticator": "PasswordAuthenticator",
"authorizer": "CassandraAuthorizer"}
config_options = default_config_options | \
self.cfg.get("extra_scylla_config_options", {}) | \
create_cfg.config_from_test
server = ScyllaServer(
mode=self.mode,
exe=self.scylla_exe,
vardir=os.path.join(self.options.tmpdir, self.mode),
logger=create_cfg.logger,
cluster_name=create_cfg.cluster_name,
ip_addr=create_cfg.ip_addr,
seeds=create_cfg.seeds,
cmdline_options=cmdline_options,
config_options=config_options,
property_file=create_cfg.property_file,
append_env=self.base_env,
server_encryption=create_cfg.server_encryption)
return server
async def create_cluster(logger: Union[logging.Logger, logging.LoggerAdapter]) -> ScyllaCluster:
cluster = ScyllaCluster(logger, self.hosts, cluster_size, create_server)
async def stop() -> None:
await cluster.stop()
# Suite artifacts are removed when
# the entire suite ends successfully.
self.artifacts.add_suite_artifact(self, stop)
if not self.options.save_log_on_success:
# If a test fails, we might want to keep the data dirs.
async def uninstall() -> None:
await cluster.uninstall()
self.artifacts.add_suite_artifact(self, uninstall)
self.artifacts.add_exit_artifact(self, stop)
await cluster.install_and_start()
return cluster
return create_cluster
def build_test_list(self) -> List[str]:
"""For pytest, search for directories recursively"""
path = self.suite_path
pytests = itertools.chain(path.rglob("*_test.py"), path.rglob("test_*.py"))
return [os.path.splitext(t.relative_to(self.suite_path))[0] for t in pytests]
@property
def pattern(self) -> str:
assert False
async def add_test(self, shortname, casename) -> None:
test = PythonTest(self.next_id((shortname, self.suite_key)), shortname, casename, self)
self.tests.append(test)
class CQLApprovalTestSuite(PythonTestSuite):
"""Run CQL commands against a single Scylla instance"""
def __init__(self, path, cfg, options: argparse.Namespace, mode) -> None:
super().__init__(path, cfg, options, mode)
def build_test_list(self) -> List[str]:
return TestSuite.build_test_list(self)
async def add_test(self, shortname: str, casename: str) -> None:
test = CQLApprovalTest(self.next_id((shortname, self.suite_key)), shortname, self)
self.tests.append(test)
@property
def pattern(self) -> str:
return "*test.cql"
class TopologyTestSuite(PythonTestSuite):
"""A collection of Python pytests against Scylla instances dealing with topology changes.
Instead of using a single Scylla cluster directly, there is a cluster manager handling
the lifecycle of clusters and bringing up new ones as needed. The cluster health checks
are done per test case.
"""
def build_test_list(self) -> List[str]:
"""Build list of Topology python tests"""
return TestSuite.build_test_list(self)
async def add_test(self, shortname: str, casename: str) -> None:
"""Add test to suite"""
test = TopologyTest(self.next_id((shortname, 'topology', self.mode)), shortname, casename, self)
self.tests.append(test)
@property
def pattern(self) -> str:
"""Python pattern"""
return "test_*.py"
def junit_tests(self):
"""Return an empty list, since topology tests are excluded from an aggregated Junit report to prevent double
count in the CI report"""
return []
class RunTestSuite(TestSuite):
"""TestSuite for test directory with a 'run' script """
def __init__(self, path: str, cfg, options: argparse.Namespace, mode: str) -> None:
super().__init__(path, cfg, options, mode)
self.scylla_exe = path_to(self.mode, "scylla")
self.scylla_env = dict(self.base_env)
if self.mode == "coverage":
self.scylla_env = coverage.env(self.scylla_exe, distinct_id=self.name)
self.scylla_env['SCYLLA'] = self.scylla_exe
async def add_test(self, shortname, casename) -> None:
test = RunTest(self.next_id((shortname, self.suite_key)), shortname, self)
self.tests.append(test)
@property
def pattern(self) -> str:
return "run"
class ToolTestSuite(TestSuite):
"""A collection of Python pytests that test tools
These tests do not need an cluster setup for them. They invoke scylla
manually, in tool mode.
"""
def __init__(self, path, cfg: dict, options: argparse.Namespace, mode: str) -> None:
super().__init__(path, cfg, options, mode)
def build_test_list(self) -> List[str]:
"""For pytest, search for directories recursively"""
path = self.suite_path
pytests = itertools.chain(path.rglob("*_test.py"), path.rglob("test_*.py"))
return [os.path.splitext(t.relative_to(self.suite_path))[0] for t in pytests]
@property
def pattern(self) -> str:
assert False
async def add_test(self, shortname, casename) -> None:
test = ToolTest(self.next_id((shortname, self.suite_key)), shortname, self)
self.tests.append(test)
class Test:
"""Base class for CQL, Unit and Boost tests"""
def __init__(self, test_no: int, shortname: str, suite) -> None:
self.id = test_no
self.path = ""
self.args: List[str] = []
# Arguments which are required by a program regardless of additional test specific arguments
self.core_args : List[str] = []
self.valid_exit_codes = [0]
# Name with test suite name
self.name = os.path.join(suite.name, shortname.split('.')[0])
# Name within the suite
self.shortname = shortname
self.mode = suite.mode
self.suite = suite
self.allure_dir = pathlib.Path(suite.options.tmpdir) / self.mode / 'allure'
# Unique file name, which is also readable by human, as filename prefix
self.uname = "{}.{}.{}".format(self.suite.name, self.shortname, self.id)
self.log_filename = pathlib.Path(suite.options.tmpdir) / self.mode / (self.uname + ".log")
self.log_filename.parent.mkdir(parents=True, exist_ok=True)
self.is_flaky = self.shortname in suite.flaky_tests
# True if the test was retried after it failed
self.is_flaky_failure = False
# True if the test was cancelled by a ctrl-c or timeout, so
# shouldn't be retried, even if it is flaky
self.is_cancelled = False
self.env = dict(self.suite.base_env)
self.started = False
self.success = False
self.time_start: float = 0
self.time_end: float = 0
def reset(self) -> None:
"""Reset the test before a retry, if it is retried as flaky"""
self.success = False
self.time_start = 0
self.time_end = 0
@property
def failed(self):
"""Returns True, if this test Failed"""
return self.started and not self.success and not self.is_cancelled
@property
def did_not_run(self):
"""Returns True, if this test did not run correctly, i.e. was canceled either during or before execution"""
return not self.started or self.is_cancelled
@abstractmethod
async def run(self, options: argparse.Namespace) -> 'Test':
pass
@abstractmethod
def print_summary(self) -> None:
pass
def check_log(self, trim: bool) -> None:
"""Check and trim logs and xml output for tests which have it"""
if trim:
self.log_filename.unlink()
pass
def write_junit_failure_report(self, xml_res: ET.Element) -> None:
assert not self.success
xml_fail = ET.SubElement(xml_res, 'failure')
xml_fail.text = "Test {} {} failed, check the log at {}".format(
self.path,
" ".join(self.args),
self.log_filename)
if self.log_filename.exists():
system_out = ET.SubElement(xml_res, 'system-out')
system_out.text = read_log(self.log_filename)
class UnitTest(Test):
standard_args = shlex.split("--overprovisioned --unsafe-bypass-fsync 1 "
"--kernel-page-cache 1 "
"--blocked-reactor-notify-ms 2000000 --collectd 0 "
"--max-networking-io-control-blocks=100 ")
def __init__(self, test_no: int, shortname: str, suite, args: str) -> None:
super().__init__(test_no, shortname, suite)
self.path = path_to(self.mode, "test", suite.name, shortname.split('.')[0])
self.args = shlex.split(args) + UnitTest.standard_args
if self.mode == "coverage":
self.env.update(coverage.env(self.path))
def print_summary(self) -> None:
print("Output of {} {}:".format(self.path, " ".join(self.args)))
print(read_log(self.log_filename))
async def run(self, options) -> Test:
self.success = await run_test(self, options, env=self.env)
logging.info("Test %s %s", self.uname, "succeeded" if self.success else "failed ")
return self
TestPath = collections.namedtuple('TestPath', ['suite_name', 'test_name', 'case_name'])
class BoostTest(UnitTest):
"""A unit test which can produce its own XML output"""
def __init__(self, test_no: int, shortname: str, suite, args: str,
casename: Optional[str], allows_compaction_groups : bool) -> None:
boost_args = []
if casename:
shortname += '.' + casename
boost_args += ['--run_test=' + casename]
super().__init__(test_no, shortname, suite, args)
self.xmlout = os.path.join(suite.options.tmpdir, self.mode, "xml", self.uname + ".xunit.xml")
boost_args += ['--report_level=no',
'--logger=HRF,test_suite:XML,test_suite,' + self.xmlout]
boost_args += ['--catch_system_errors=no'] # causes undebuggable cores
boost_args += ['--color_output=false']
boost_args += ['--']
self.args = boost_args + self.args
self.casename = casename
self.__test_case_elements: list[ET.Element] = []
self.allows_compaction_groups = allows_compaction_groups
def reset(self) -> None:
"""Reset the test before a retry, if it is retried as flaky"""
super().reset()
self.__test_case_elements = []
def get_test_cases(self) -> list[ET.Element]:
if not self.__test_case_elements:
self.__parse_logger()
return self.__test_case_elements
@staticmethod
def test_path_of_element(test: ET.Element) -> TestPath:
path = test.attrib['path']
prefix, case_name = path.rsplit('::', 1)
suite_name, test_name = prefix.split('.', 1)
return TestPath(suite_name, test_name, case_name)
def __parse_logger(self) -> None:
def attach_path_and_mode(test):
# attach the "path" to the test so we can group the tests by this string
test_name = test.attrib['name']
prefix = self.name.replace(os.path.sep, '.')
test.attrib['path'] = f'{prefix}::{test_name}'
test.attrib['mode'] = self.mode
return test
try:
root = ET.parse(self.xmlout).getroot()
# only keep the tests which actually ran, the skipped ones do not have
# TestingTime tag in the corresponding TestCase tag.
self.__test_case_elements = map(attach_path_and_mode,
root.findall(".//TestCase[TestingTime]"))
os.unlink(self.xmlout)
except ET.ParseError as e:
message = palette.crit(f"failed to parse XML output '{self.xmlout}': {e}")
if e.msg.__contains__("no element found"):
message = palette.crit(f"Empty testcase XML output, possibly caused by a crash in the cql_test_env.cc, "
f"details: '{self.xmlout}': {e}")
print(f"error: {self.name}: {message}")
def check_log(self, trim: bool) -> None:
self.__parse_logger()
super().check_log(trim)
async def run(self, options):
if options.random_seed:
self.args += ['--random-seed', options.random_seed]
if self.allows_compaction_groups and options.x_log2_compaction_groups:
self.args += [ "--x-log2-compaction-groups", str(options.x_log2_compaction_groups) ]
return await super().run(options)
def write_junit_failure_report(self, xml_res: ET.Element) -> None:
"""Does not write junit report for Jenkins legacy reasons"""
assert False
class CQLApprovalTest(Test):
"""Run a sequence of CQL commands against a standalone Scylla"""
def __init__(self, test_no: int, shortname: str, suite) -> None:
super().__init__(test_no, shortname, suite)
# Path to cql_repl driver, in the given build mode
self.path = "pytest"
self.cql = suite.suite_path / (self.shortname + ".cql")
self.result = suite.suite_path / (self.shortname + ".result")
self.tmpfile = os.path.join(suite.options.tmpdir, self.mode, self.uname + ".reject")
self.reject = suite.suite_path / (self.shortname + ".reject")
self.server_log: Optional[str] = None
self.server_log_filename: Optional[pathlib.Path] = None
self.is_before_test_ok = False
self.is_executed_ok = False
self.is_new = False
self.is_after_test_ok = False
self.is_equal_result = False
self.summary = "not run"
self.unidiff: Optional[str] = None
self.server_log = None
self.server_log_filename = None
self.env: Dict[str, str] = dict()
self._prepare_args(suite.options)
def reset(self) -> None:
"""Reset the test before a retry, if it is retried as flaky"""
super().reset()
self.is_before_test_ok = False
self.is_executed_ok = False
self.is_new = False
self.is_after_test_ok = False
self.is_equal_result = False
self.summary = "not run"
self.unidiff = None
self.server_log = None
self.server_log_filename = None
self.env = dict()
old_tmpfile = pathlib.Path(self.tmpfile)
if old_tmpfile.exists():
old_tmpfile.unlink()
def _prepare_args(self, options: argparse.Namespace):
self.args = [
"-s", # don't capture print() inside pytest
"test/pylib/cql_repl/cql_repl.py",
"--input={}".format(self.cql),
"--output={}".format(self.tmpfile),
"--run_id={}".format(self.id),
"--mode={}".format(self.mode),
]
self.args.append(f"--alluredir={self.allure_dir}")
if not options.save_log_on_success:
self.args.append("--allure-no-capture")
async def run(self, options: argparse.Namespace) -> Test:
self.success = False
self.summary = "failed"
loggerPrefix = self.mode + '/' + self.uname
logger = LogPrefixAdapter(logging.getLogger(loggerPrefix), {'prefix': loggerPrefix})
def set_summary(summary):
self.summary = summary
log_func = logger.info if self.success else logger.error
log_func("Test %s %s", self.uname, summary)
if self.server_log is not None:
logger.info("Server log:\n%s", self.server_log)
# TODO: consider dirty_on_exception=True
async with (cm := self.suite.clusters.instance(False, logger)) as cluster:
try:
cluster.before_test(self.uname)
logger.info("Leasing Scylla cluster %s for test %s", cluster, self.uname)
self.args.insert(1, "--host={}".format(cluster.endpoint()))
# If pre-check fails, e.g. because Scylla failed to start
# or crashed between two tests, fail entire test.py
self.is_before_test_ok = True
cluster.take_log_savepoint()
self.is_executed_ok = await run_test(self, options, env=self.env)
cluster.after_test(self.uname, self.is_executed_ok)
cm.dirty = cluster.is_dirty
self.is_after_test_ok = True
if not self.is_executed_ok:
set_summary("""returned non-zero return status.\n
Check test log at {}.""".format(self.log_filename))
elif not os.path.isfile(self.tmpfile):
set_summary("failed: no output file")
elif not os.path.isfile(self.result):
set_summary("failed: no result file")
self.is_new = True
else:
self.is_equal_result = filecmp.cmp(self.result, self.tmpfile)
if not self.is_equal_result:
self.unidiff = format_unidiff(str(self.result), self.tmpfile)
set_summary("failed: test output does not match expected result")
assert self.unidiff is not None
logger.info("\n{}".format(palette.nocolor(self.unidiff)))
else:
self.success = True
set_summary("succeeded")
except Exception as e:
# Server log bloats the output if we produce it in all
# cases. So only grab it when it's relevant:
# 1) failed pre-check, e.g. start failure
# 2) failed test execution.
if not self.is_executed_ok:
self.server_log = cluster.read_server_log()
self.server_log_filename = cluster.server_log_filename()
if not self.is_before_test_ok:
set_summary("pre-check failed: {}".format(e))
print("Test {} {}".format(self.name, self.summary))
print("Server log of the first server:\n{}".format(self.server_log))
# Don't try to continue if the cluster is broken
raise
set_summary("failed: {}".format(e))
finally:
if os.path.exists(self.tmpfile):
if self.is_executed_ok and (self.is_new or not self.is_equal_result):
# Move the .reject file close to the .result file
# so that it's easy to analyze the diff or overwrite .result
# with .reject.
shutil.move(self.tmpfile, self.reject)
else:
pathlib.Path(self.tmpfile).unlink()
return self
def print_summary(self) -> None:
print("Test {} ({}) {}".format(palette.path(self.name), self.mode,
self.summary))
if not self.is_executed_ok:
print(read_log(self.log_filename))
if self.server_log is not None:
print("Server log of the first server:")
print(self.server_log)
elif not self.is_equal_result and self.unidiff:
print(self.unidiff)
def write_junit_failure_report(self, xml_res: ET.Element) -> None:
assert not self.success
xml_fail = ET.SubElement(xml_res, 'failure')
xml_fail.text = self.summary
if not self.is_executed_ok:
if self.log_filename.exists():
system_out = ET.SubElement(xml_res, 'system-out')
system_out.text = read_log(self.log_filename)
if self.server_log_filename:
system_err = ET.SubElement(xml_res, 'system-err')
system_err.text = read_log(self.server_log_filename)
elif self.unidiff:
system_out = ET.SubElement(xml_res, 'system-out')
system_out.text = palette.nocolor(self.unidiff)
class RunTest(Test):
"""Run tests in a directory started by a run script"""
def __init__(self, test_no: int, shortname: str, suite) -> None:
super().__init__(test_no, shortname, suite)
self.path = suite.suite_path / shortname
self.xmlout = os.path.join(suite.options.tmpdir, self.mode, "xml", self.uname + ".xunit.xml")
self.args = [
"--junit-xml={}".format(self.xmlout),
"-o",
"junit_suite_name={}".format(self.suite.name)
]
self.args.append(f"--alluredir={self.allure_dir}")
if not suite.options.save_log_on_success:
self.args.append("--allure-no-capture")
def print_summary(self) -> None:
print("Output of {} {}:".format(self.path, " ".join(self.args)))
print(read_log(self.log_filename))
async def run(self, options: argparse.Namespace) -> Test:
# This test can and should be killed gently, with SIGTERM, not with SIGKILL
self.success = await run_test(self, options, gentle_kill=True, env=self.suite.scylla_env)
logging.info("Test %s %s", self.uname, "succeeded" if self.success else "failed ")
return self
class PythonTest(Test):
"""Run a pytest collection of cases against a standalone Scylla"""
def __init__(self, test_no: int, shortname: str, casename: str, suite) -> None:
super().__init__(test_no, shortname, suite)
self.path = "python"
self.core_args = ["-m", "pytest"]
self.casename = casename
self.xmlout = os.path.join(self.suite.options.tmpdir, self.mode, "xml", self.uname + ".xunit.xml")
self.server_log: Optional[str] = None
self.server_log_filename: Optional[pathlib.Path] = None
self.is_before_test_ok = False
self.is_after_test_ok = False
def _prepare_pytest_params(self, options: argparse.Namespace):
self.args = [
"-s", # don't capture print() output inside pytest
"--log-level=DEBUG", # Capture logs
"-o",
"junit_family=xunit2",
"-o",
"junit_suite_name={}".format(self.suite.name),
"--junit-xml={}".format(self.xmlout),
"-rs",