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
|
import contextlib
import random
import unittest
import ruffus
import ruffus.drmaa_wrapper
import os
import shutil
import glob
import tempfile
try:
import gevent
HAVE_GEVENT = True
except ImportError:
HAVE_GEVENT = False
try:
import drmaa
HAVE_DRMAA = True
DRMAA_SESSION = drmaa.Session()
DRMAA_SESSION.initialize()
except ImportError:
HAVE_DRMAA = False
ROOT = os.path.abspath(os.path.dirname(__file__))
TESTS_TEMPDIR = os.path.abspath(os.path.join(os.path.dirname(__file__), "tmp"))
# number of cores used for testing parallelism
NUM_CORES = 4
@contextlib.contextmanager
def temp_cd(target):
curdir = os.path.curdir
os.chdir(target)
yield
os.chdir(curdir)
def save_pid(outfile):
with open(outfile + ".pid", "w") as outf:
outf.write("{}".format(os.getpid()))
def create_files(outfile):
with open(outfile, "w") as outf:
outf.write("\n".join(map(
str,
random.sample(range(0, 1000), 100))) + "\n")
save_pid(outfile)
def compute_mean(infile, outfile):
"""compute mean"""
with open(infile, "r") as inf:
n = [float(x.strip()) for x in inf.readlines()]
with open(outfile, "w") as outf:
outf.write("{}\n".format(sum(n) / len(n)))
save_pid(outfile)
def run_job(infile, outfile, **kwargs):
if not kwargs.get("run_locally", False):
kwargs["drmaa_session"] = DRMAA_SESSION
stdout, stderr = ruffus.drmaa_wrapper.run_job(
cmd_str="hostname > {}".format(os.path.abspath(outfile)),
verbose=1,
local_echo=False,
**kwargs)
def run_local_job1(*args):
return run_job(*args, run_locally=True)
def run_local_job2(*args):
return run_job(*args, run_locally=True)
def run_remote_job1(*args):
return run_job(*args, run_locally=False)
def run_remote_job2(*args):
return run_job(*args, run_locally=False)
def combine_means(infiles, outfile):
with open(outfile, "w") as outf:
for infile in infiles:
with open(infile) as inf:
outf.write(inf.read())
save_pid(outfile)
class BaseTest(unittest.TestCase):
expected_output_files = ["sample_{:02}.mean".format(x) for x in range(10)] +\
["sample_{:02}.txt".format(x) for x in range(10)]
def setUp(self):
try:
os.makedirs(TESTS_TEMPDIR)
except OSError:
pass
self.work_dir = tempfile.mkdtemp(suffix="",
prefix="ruffus_tmp_{}_".format(
self.id()),
dir=TESTS_TEMPDIR)
def tearDown(self):
# shutil.rmtree(self.work_dir)
pass
def check_files(self, present=[], absent=[]):
for fn in present:
path = os.path.join(self.work_dir, fn)
self.assertTrue(os.path.exists(path),
"file {} does not exist".format(path))
for fn in absent:
path = os.path.join(self.work_dir, fn)
self.assertFalse(os.path.exists(path),
"file {} does exist but not expected".format(path))
def build_pipeline(self, pipeline_name, **kwargs):
# fudge: clear all previous pipelines
ruffus.Pipeline.clear_all()
pipeline = ruffus.Pipeline(pipeline_name)
task_create_files = pipeline.originate(
task_func=create_files,
output=["sample_{:02}.txt".format(x) for x in range(10)])
task_compute_mean = pipeline.transform(
task_func=compute_mean,
input=task_create_files,
filter=ruffus.suffix(".txt"),
output=".mean")
task_combine_means = pipeline.merge(
task_func=combine_means,
input=task_compute_mean,
output="means.txt")
task_run_local_job1 = pipeline.transform(
task_func=run_local_job1,
input=task_create_files,
filter=ruffus.suffix(".txt"),
output=".local1")
# test jobs_limit with local running
task_run_local_job2 = pipeline.transform(
task_func=run_local_job2,
input=task_create_files,
filter=ruffus.suffix(".txt"),
output=".local2").jobs_limit(NUM_CORES // 2)
# multiprocessing and DRMAA do not work at the moment likely
# cause is the shared session object.
if not HAVE_DRMAA or (kwargs.get("multiprocess", 1) > 1):
return
task_run_remote_job1 = pipeline.transform(
task_func=run_remote_job1,
input=task_create_files,
filter=ruffus.suffix(".txt"),
output=".remote1")
# test jobs_limit with remote running
task_run_remote_job2 = pipeline.transform(
task_func=run_remote_job2,
input=task_create_files,
filter=ruffus.suffix(".txt"),
output=".remote2").jobs_limit(NUM_CORES // 2)
def run_pipeline(self, **kwargs):
pipeline = self.build_pipeline(self.id(), **kwargs)
with temp_cd(self.work_dir):
ruffus.pipeline_run(pipeline=pipeline, verbose=5, **kwargs)
self.check_files(self.expected_output_files)
def read_pids(self):
pids = []
for fn in glob.glob(os.path.join(self.work_dir, "*.pid")):
with open(fn) as inf:
pids.append(int(inf.readline().strip()))
return pids
class TestExecutionEngines(BaseTest):
def test_pipeline_runs_with_multiprocessing(self):
self.run_pipeline(multiprocess=NUM_CORES)
pids = self.read_pids()
self.assertEqual(len(set(pids)), NUM_CORES)
def test_pipeline_runs_with_multithreading(self):
self.run_pipeline(multithread=NUM_CORES)
pids = self.read_pids()
self.assertEqual(len(set(pids)), 1)
self.assertEqual(pids[0], os.getpid())
@unittest.skipIf(not HAVE_GEVENT, "no gevent installed")
def test_pipeline_runs_with_gevent_manager(self):
self.run_pipeline(multithread=NUM_CORES, pool_manager="gevent")
pids = self.read_pids()
self.assertEqual(len(set(pids)), 1)
self.assertEqual(pids[0], os.getpid())
def test_pipeline_fails_with_unknown_manager(self):
self.assertRaises(ValueError,
self.run_pipeline,
multithread=NUM_CORES,
pool_manager="mystical_manager")
if __name__ == "__main__":
unittest.main()
|