#!/usr/bin/python
# -*- coding: UTF-8 -*-
#
# Copyright (c) 2007 Tarek Ziadé
#
# Authors:
#   Tarek Ziadé <tarek@ziade.org>
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
import os
import sys
import re
from glob import glob

header = 'Products/'
catcher = r'Ran .*? with (\d*?) failures and (\d*?) errors'
catcher = re.compile(catcher)
omit = ('bundle.conf', 'CookieCrumbler')

products = [element[len(header):] for element in glob('%s*' % header)]
products.sort()

command = 'bin/zopectl test --dir Products/%s'

for product in products:
    if product in omit:
        continue
    sys.stdout.write('Testing %s\n' % product)
    test_in, test_out, test_err = os.popen3(command % product)
    test_out = test_out.read()
    sys.stdout.write(test_out)

    sys.stdout.write('%s\n' % ('*' * 80))
    sys.stdout.flush()

    # error ?
    errors = test_err.read()
    if errors != '':
        sys.stdout.write(errors)
        sys.stdout.flush()
        sys.exit(1)

    # failed ?
    catched = catcher.findall(test_out)

    if len(catched) == 0:
        continue

    try:
        errors = int(catched[0][1])
        failures = int(catched[0][0])
        if errors > 0 or failures > 0:
            sys.exit(1)
    except ValueError:
        sys.exit(1)

sys.exit(0)

