3 # Copyright (C) 2014 Simo Sorce <simo@redhat.com>
5 # see file 'COPYING' for use and warranty information
7 # This program is free software; you can redistribute it and/or modify
8 # it under the terms of the GNU General Public License as published by
9 # the Free Software Foundation, either version 3 of the License, or
10 # (at your option) any later version.
12 # This program is distributed in the hope that it will be useful,
13 # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 # GNU General Public License for more details.
17 # You should have received a copy of the GNU General Public License
18 # along with this program. If not, see <http://www.gnu.org/licenses/>.
22 from datetime import datetime
30 from string import Template
37 parser = argparse.ArgumentParser(description='Ipsilon Tests Environment')
38 parser.add_argument('--path', default='%s/testdir' % os.getcwd(),
39 help="Directory in which tests are run")
40 parser.add_argument('--test', default='test1',
41 help="The test to run")
43 return vars(parser.parse_args())
46 def openlogs(path, test):
47 global logger # pylint: disable=W0603
48 logger = logging.getLogger()
50 datestr = datetime.now().strftime("%Y-%m-%d_%H:%M:%S")
51 filename = '%s/test-%s-%s.log' % (path, test, datestr)
52 lh = logging.FileHandler(filename)
54 print >> sys.stderr, 'Unable to open %s (%s)' % (filename, str(e))
55 lh = logging.StreamHandler(sys.stderr)
56 formatter = logging.Formatter('[%(asctime)s] %(message)s')
57 lh.setFormatter(formatter)
59 logger.setLevel(logging.DEBUG)
62 def force_remove(op, name, info):
67 def setup_http(httpdir, addr, port):
69 os.mkdir(httpdir + '/conf.d')
70 os.mkdir(httpdir + '/html')
71 os.mkdir(httpdir + '/logs')
72 os.symlink('/etc/httpd/modules', httpdir + '/modules')
74 with open('tests/httpd.conf') as f:
75 t = Template(f.read())
76 text = t.substitute({'HTTPROOT': httpdir,
77 'HTTPADDR': addr, 'HTTPPORT': port})
78 with open(httpdir + '/httpd.conf', 'w+') as f:
82 def setup_test(path, test):
83 profile = 'tests/%s.cfg' % test
84 if not os.path.exists(profile):
85 raise ValueError('Unrecognized test name [%s]' % test)
88 config = ConfigParser.ConfigParser()
90 if 'tests' not in config.sections():
91 raise ValueError('Missing [tests] in profile [%s]' % test)
92 T = config.options('tests')
94 opts[t] = config.get('tests', t)
96 base = '%s/%s' % (path, test)
97 if os.path.exists(base):
98 shutil.rmtree(base, onerror=force_remove)
100 shutil.copytree('templates', base + '/templates')
101 os.mkdir(base + '/etc')
102 os.mkdir(base + '/lib')
103 os.mkdir(base + '/lib/' + test)
104 os.mkdir(base + '/log')
106 with open(profile) as f:
107 t = Template(f.read())
108 text = t.substitute({'TESTDIR': base, 'ROOTDIR': os.getcwd(),
109 'TEST_USER': pwd.getpwuid(os.getuid())[0]})
110 with open(base + '/profile.cfg', 'w+') as f:
113 opts['basedir'] = base
117 def generate_profile(profile, name):
118 config = ConfigParser.ConfigParser()
121 global_section = '%s_globals' % name
123 if global_section in config.sections():
124 G = config.options(global_section)
126 global_options[g] = config.get(global_section, g)
128 args_section = '%s_arguments' % name
130 if args_section in config.sections():
131 A = config.options(args_section)
133 args_options[a] = config.get(args_section, a)
135 newconf = ConfigParser.ConfigParser()
136 newconf.add_section('globals')
137 for k in global_options.keys():
138 newconf.set('globals', k, global_options[k])
139 newconf.add_section('arguments')
140 for k in args_options.keys():
141 newconf.set('arguments', k, args_options[k])
143 filename = os.path.join(os.path.dirname(profile), '%s_profile.cfg' % name)
144 with open(filename, 'wb') as f:
150 def fixup_sp_httpd(httpdir):
153 Alias /sp ${HTTPDIR}/sp
155 <Directory ${HTTPDIR}/sp>
161 t = Template(location)
162 text = t.substitute({'HTTPDIR': httpdir})
163 with open(httpdir + '/conf.d/ipsilon-saml.conf', 'a') as f:
166 os.mkdir(httpdir + '/sp')
167 with open(httpdir + '/sp/index.html', 'w') as f:
170 if __name__ == '__main__':
174 if not os.path.exists(args['path']):
175 os.makedirs(args['path'])
176 openlogs(args['path'], args['test'])
178 options = setup_test(args['path'], args['test'])
179 basedir = options['basedir']
181 env={'PYTHONPATH':'./'}
184 for h in options['servers'].split(','):
185 sname, saddr, sport = h.split(':')
186 basehttpdir = '%s/%s' % (basedir, sname)
187 setup_http(basehttpdir, saddr, sport)
189 sprofile = generate_profile('%s/profile.cfg' % basedir, sname)
190 p = subprocess.Popen(['./ipsilon/install/ipsilon-server-install',
191 '--config-profile=%s' % sprofile], env=env,
192 stdout=subprocess.PIPE,
193 stderr=subprocess.PIPE)
194 stdout, stderr = p.communicate()
198 sys.exit(p.returncode)
200 os.symlink('%s/ipsilon' % os.getcwd(),
201 '%s/lib/%s/ipsilon' % (basedir, sname))
203 print "Starting httpd server in %s" % basehttpdir
204 srv = subprocess.Popen(['/usr/sbin/httpd', '-DFOREGROUND',
205 '-f', basehttpdir + '/httpd.conf'],
206 env=env, preexec_fn=os.setsid)
209 for h in options['clients'].split(','):
210 sname, saddr, sport = h.split(':')
211 basehttpdir = '%s/%s' % (basedir, sname)
212 setup_http(basehttpdir, saddr, sport)
214 sprofile = generate_profile('%s/profile.cfg' % basedir, sname)
215 p = subprocess.Popen(['./ipsilon/install/ipsilon-client-install',
216 '--config-profile=%s' % sprofile], env=env,
217 stdout=subprocess.PIPE,
218 stderr=subprocess.PIPE)
219 stdout, stderr = p.communicate()
223 sys.exit(p.returncode)
225 fixup_sp_httpd(basehttpdir)
227 print "Starting httpd server in %s" % basehttpdir
228 srv = subprocess.Popen(['/usr/sbin/httpd', '-DFOREGROUND',
229 '-f', basehttpdir + '/httpd.conf'],
230 env=env, preexec_fn=os.setsid)
233 if os.path.exists('tests/%s.py' % args['test']):
234 code = subprocess.call(['./tests/%s.py' % args['test'], basedir],
238 except Exception: # pylint: disable=broad-except
242 os.killpg(srv.pid, signal.SIGTERM)