#!/usr/bin/python

"""Parses the output of tests from test_output and test_full_output and sends
an email to a list.
Edit this script to change the recipients.
"""

import smtplib
import re
import os
from datetime import date
from email.MIMEText import MIMEText
from email.MIMEBase import MIMEBase
from email.MIMEImage import MIMEImage
from email.MIMEMultipart import MIMEMultipart

# configure this part if needed
from_mail = 'nobody@erp5.org'
to_mail   = [ 'erp5-report@erp5.org' ]
INSTANCE_HOME = os.environ.get('INSTANCE_HOME', '/var/lib/zope')

test_msg = file(
      os.path.join(INSTANCE_HOME, "Products", "test_output"), 'r').read()
test_msg = "Date : %s\n\n" % date.today().isoformat() + test_msg

# minimal parsing 
revision_re = re.compile('Revision: (?P<revision>\d+)')
ran_test_re = re.compile('Ran (?P<tests>\d+) tests')
errors_re = re.compile('FAILED \((failures=(?P<failures>\d+))*[, ]*'\
                       '(errors=(?P<errors>\d+))*\)')
svn_revision = "?"
test_runs = 0
errors = 0
failures = 0
for test_line in test_msg.splitlines():
  revision = revision_re.match(test_line)
  if revision:
    svn_revision = revision.groupdict()['revision']
  ran = ran_test_re.match(test_line)
  if ran:
    test_runs += int(ran.groupdict()['tests'])
  errors_or_failures = errors_re.match(test_line)
  if errors_or_failures:
    failures += int(errors_or_failures.groupdict()['failures'] or 0)
    errors += int(errors_or_failures.groupdict()['errors'] or 0)

subject = "ERP5 r%s: %s Tests, %s Errors, %s Failures" % (
                                  svn_revision, test_runs, errors, failures)

msg = MIMEMultipart()
msg['Subject'] = subject
msg['From']    = from_mail
msg['To']      = ', '.join(to_mail)
# Add custom headers for client side filtering
msg['X-ERP5-Tests'] = 'ERP5'
if not (failures + errors):
  msg['X-ERP5-Tests-Status'] = 'OK'

# Guarantees the message ends in a newline
msg.preamble = subject
msg.epilogue = ''
file_content = file(
    os.path.join(INSTANCE_HOME, "Products", "test_full_output"), 'r').read()

mime_text = MIMEText(test_msg)
mime_text.add_header('Content-Disposition', 'attachment',
                     filename='test_output.txt')
msg.attach(mime_text)
mime_text = MIMEText(file_content)
mime_text.add_header('Content-Disposition', 'attachment',
                     filename='test_full_output.txt')
msg.attach(mime_text)

# Send the email via our own SMTP server.
s = smtplib.SMTP()
s.connect()
s.sendmail(from_mail, to_mail, msg.as_string())
s.close()

