Skip to content

Commit b040243

Browse files
committed
[tests] improve tmpdir structure
1 parent 96c850c commit b040243

File tree

2 files changed

+27
-15
lines changed

2 files changed

+27
-15
lines changed

test/functional/test_framework/test_framework.py

Lines changed: 5 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -109,8 +109,7 @@ def main(self):
109109
help="Source directory containing bitcoind/bitcoin-cli (default: %default)")
110110
parser.add_option("--cachedir", dest="cachedir", default=os.path.normpath(os.path.dirname(os.path.realpath(__file__))+"/../../cache"),
111111
help="Directory for caching pregenerated datadirs")
112-
parser.add_option("--tmpdir", dest="tmpdir", default=tempfile.mkdtemp(prefix="test"),
113-
help="Root directory for datadirs")
112+
parser.add_option("--tmpdir", dest="tmpdir", help="Root directory for datadirs")
114113
parser.add_option("-l", "--loglevel", dest="loglevel", default="INFO",
115114
help="log events at this level and higher to the console. Can be set to DEBUG, INFO, WARNING, ERROR or CRITICAL. Passing --loglevel DEBUG will output all logs to console. Note that logs at all levels are always written to the test_framework.log file in the temporary test directory.")
116115
parser.add_option("--tracerpc", dest="trace_rpc", default=False, action="store_true",
@@ -124,9 +123,6 @@ def main(self):
124123
self.add_options(parser)
125124
(self.options, self.args) = parser.parse_args()
126125

127-
# backup dir variable for removal at cleanup
128-
self.options.root, self.options.tmpdir = self.options.tmpdir, self.options.tmpdir + '/' + str(self.options.port_seed)
129-
130126
if self.options.coveragedir:
131127
enable_coverage(self.options.coveragedir)
132128

@@ -137,7 +133,10 @@ def main(self):
137133
check_json_precision()
138134

139135
# Set up temp directory and start logging
140-
os.makedirs(self.options.tmpdir, exist_ok=False)
136+
if self.options.tmpdir:
137+
os.makedirs(self.options.tmpdir, exist_ok=False)
138+
else:
139+
self.options.tmpdir = tempfile.mkdtemp(prefix="test")
141140
self._start_logging()
142141

143142
success = False
@@ -167,8 +166,6 @@ def main(self):
167166
if not self.options.nocleanup and not self.options.noshutdown and success:
168167
self.log.info("Cleaning up")
169168
shutil.rmtree(self.options.tmpdir)
170-
if not os.listdir(self.options.root):
171-
os.rmdir(self.options.root)
172169
else:
173170
self.log.warning("Not cleaning up dir %s" % self.options.tmpdir)
174171
if os.getenv("PYTHON_DEBUG", ""):

test/functional/test_runner.py

Lines changed: 22 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@
1616

1717
import argparse
1818
import configparser
19+
import datetime
1920
import os
2021
import time
2122
import shutil
@@ -170,6 +171,7 @@ def main():
170171
parser.add_argument('--jobs', '-j', type=int, default=4, help='how many test scripts to run in parallel. Default=4.')
171172
parser.add_argument('--keepcache', '-k', action='store_true', help='the default behavior is to flush the cache directory on startup. --keepcache retains the cache from the previous testrun.')
172173
parser.add_argument('--quiet', '-q', action='store_true', help='only print results summary and failure logs')
174+
parser.add_argument('--tmpdirprefix', '-t', default=tempfile.gettempdir(), help="Root directory for datadirs")
173175
args, unknown_args = parser.parse_known_args()
174176

175177
# Create a set to store arguments and create the passon string
@@ -187,6 +189,12 @@ def main():
187189
logging_level = logging.INFO if args.quiet else logging.DEBUG
188190
logging.basicConfig(format='%(message)s', level=logging_level)
189191

192+
# Create base test directory
193+
tmpdir = "%s/bitcoin_test_runner_%s" % (args.tmpdirprefix, datetime.datetime.now().strftime("%Y%m%d_%H%M%S"))
194+
os.makedirs(tmpdir)
195+
196+
logging.debug("Temporary test directory at %s" % tmpdir)
197+
190198
enable_wallet = config["components"].getboolean("ENABLE_WALLET")
191199
enable_utils = config["components"].getboolean("ENABLE_UTILS")
192200
enable_bitcoind = config["components"].getboolean("ENABLE_BITCOIND")
@@ -239,9 +247,9 @@ def main():
239247
if not args.keepcache:
240248
shutil.rmtree("%s/test/cache" % config["environment"]["BUILDDIR"], ignore_errors=True)
241249

242-
run_tests(test_list, config["environment"]["SRCDIR"], config["environment"]["BUILDDIR"], config["environment"]["EXEEXT"], args.jobs, args.coverage, passon_args)
250+
run_tests(test_list, config["environment"]["SRCDIR"], config["environment"]["BUILDDIR"], config["environment"]["EXEEXT"], tmpdir, args.jobs, args.coverage, passon_args)
243251

244-
def run_tests(test_list, src_dir, build_dir, exeext, jobs=1, enable_coverage=False, args=[]):
252+
def run_tests(test_list, src_dir, build_dir, exeext, tmpdir, jobs=1, enable_coverage=False, args=[]):
245253
# Warn if bitcoind is already running (unix only)
246254
try:
247255
if subprocess.check_output(["pidof", "bitcoind"]) is not None:
@@ -272,10 +280,10 @@ def run_tests(test_list, src_dir, build_dir, exeext, jobs=1, enable_coverage=Fal
272280

273281
if len(test_list) > 1 and jobs > 1:
274282
# Populate cache
275-
subprocess.check_output([tests_dir + 'create_cache.py'] + flags)
283+
subprocess.check_output([tests_dir + 'create_cache.py'] + flags + ["--tmpdir=%s/cache" % tmpdir])
276284

277285
#Run Tests
278-
job_queue = TestHandler(jobs, tests_dir, test_list, flags)
286+
job_queue = TestHandler(jobs, tests_dir, tmpdir, test_list, flags)
279287
time0 = time.time()
280288
test_results = []
281289

@@ -302,6 +310,10 @@ def run_tests(test_list, src_dir, build_dir, exeext, jobs=1, enable_coverage=Fal
302310
logging.debug("Cleaning up coverage data")
303311
coverage.cleanup()
304312

313+
# Clear up the temp directory if all subdirectories are gone
314+
if not os.listdir(tmpdir):
315+
os.rmdir(tmpdir)
316+
305317
all_passed = all(map(lambda test_result: test_result.was_successful, test_results))
306318

307319
sys.exit(not all_passed)
@@ -329,10 +341,11 @@ class TestHandler:
329341
Trigger the testscrips passed in via the list.
330342
"""
331343

332-
def __init__(self, num_tests_parallel, tests_dir, test_list=None, flags=None):
344+
def __init__(self, num_tests_parallel, tests_dir, tmpdir, test_list=None, flags=None):
333345
assert(num_tests_parallel >= 1)
334346
self.num_jobs = num_tests_parallel
335347
self.tests_dir = tests_dir
348+
self.tmpdir = tmpdir
336349
self.test_list = test_list
337350
self.flags = flags
338351
self.num_running = 0
@@ -347,13 +360,15 @@ def get_next(self):
347360
# Add tests
348361
self.num_running += 1
349362
t = self.test_list.pop(0)
350-
port_seed = ["--portseed={}".format(len(self.test_list) + self.portseed_offset)]
363+
portseed = len(self.test_list) + self.portseed_offset
364+
portseed_arg = ["--portseed={}".format(portseed)]
351365
log_stdout = tempfile.SpooledTemporaryFile(max_size=2**16)
352366
log_stderr = tempfile.SpooledTemporaryFile(max_size=2**16)
353367
test_argv = t.split()
368+
tmpdir = ["--tmpdir=%s/%s_%s" % (self.tmpdir, re.sub(".py$", "", test_argv[0]), portseed)]
354369
self.jobs.append((t,
355370
time.time(),
356-
subprocess.Popen([self.tests_dir + test_argv[0]] + test_argv[1:] + self.flags + port_seed,
371+
subprocess.Popen([self.tests_dir + test_argv[0]] + test_argv[1:] + self.flags + portseed_arg + tmpdir,
357372
universal_newlines=True,
358373
stdout=log_stdout,
359374
stderr=log_stderr),

0 commit comments

Comments
 (0)