runner 9.86 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
#! /usr/bin/env python
#
# Copyright (C) 2009  Nexedi SA
# 
# 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., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.

import unittest
import logging
import time

23 24 25 26 27
# TODO: 
# - include failed imports in the report
# - group tests by kind (unit, functionnal...)
# - import each test case instead of modules to reduce import errors

28 29
# list of test modules
# each of them have to import its TestCase classes
30
UNIT_TEST_MODULES = [ 
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
    # generic parts
    'neo.tests.testBootstrap',
    'neo.tests.testConfig',
    'neo.tests.testConnection',
    'neo.tests.testEvent',
    'neo.tests.testHandler',
    'neo.tests.testNodes',
    'neo.tests.testProtocol',
    'neo.tests.testPT',
    # master application
    'neo.tests.master.connector',
    'neo.tests.master.testClientHandler',
    'neo.tests.master.testElectionHandler',
    'neo.tests.master.testMasterApp',
    'neo.tests.master.testMasterPT',
    'neo.tests.master.testRecoveryHandler',
    'neo.tests.master.testStorageHandler',
    'neo.tests.master.testVerificationHandler',
    # storage application
    'neo.tests.storage.testClientHandler',
    'neo.tests.storage.testInitializationHandler',
    'neo.tests.storage.testMasterHandler',
    'neo.tests.storage.testStorageApp',
    'neo.tests.storage.testStorageHandler',
    'neo.tests.storage.testStorageMySQLdb',
    'neo.tests.storage.testVerificationHandler',
    # client application
    'neo.tests.client.testClientApp',
    'neo.tests.client.testClientHandler',
    'neo.tests.client.testConnectionPool',
    'neo.tests.client.testDispatcher',
    'neo.tests.client.testZODB',
63 64
]

65 66 67 68
FUNC_TEST_MODULES = [
    'neo.client.tests.testZODB',
]

69
# configuration 
70
WITH_ZODB_TESTS = False
71
SEND_REPORT = False
72 73 74
CONSOLE_LOG = False
ATTACH_LOG = False # for ZODB test, only the client side is logged
LOG_FILE = 'neo.log' 
75
SENDER = 'gregory@nexedi.com'
76
RECIPIENTS = ['gregory@nexedi.com'] #['neo-report@erp5.org']
77 78 79 80 81 82 83 84 85 86
SMTP_SERVER = ( "mail.nexedi.com", "25")

# override logging configuration to send all messages to a file
logger = logging.getLogger()
logger.setLevel(logging.INFO)
handler = logging.FileHandler(LOG_FILE, 'w+')
format='[%(module)12s:%(levelname)s:%(lineno)3d] %(message)s'
formatter = logging.Formatter(format)
handler.setFormatter(formatter)
logger.addHandler(handler)
87
# enabled console logging if desired
88 89 90 91 92
if CONSOLE_LOG:
    handler = logging.StreamHandler()
    handler.setFormatter(formatter)
    logger.addHandler(handler)

93
class NeoTestRunner(unittest.TestResult):
94 95
    """ Custom result class to build report with statistics per module """

96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113
    def __init__(self):
        unittest.TestResult.__init__(self)
        self.modulesStats = {}
        self.lastStart = None

    def run(self, name, modules, prefix='test'):
        suite = unittest.TestSuite()
        loader = unittest.defaultTestLoader
        loader.testMethodPrefix = prefix
        for test_module in modules:
            try:
                test_module = __import__(test_module, globals(), locals(), ['*'])
            except ImportError, err:
                print "Import of %s failed : %s" % (test_module, err)
                continue
            suite.addTests(loader.loadTestsFromModule(test_module))
        suite.run(self)

114
    class ModuleStats(object):
115
        run = 0
116 117 118 119 120 121
        errors = 0
        success = 0
        failures = 0
        time = 0.0

    def _getModuleStats(self, test):
122 123
        module = test.__class__.__module__
        module = tuple(module.split('.'))
124 125 126 127 128 129 130 131 132 133
        try:
            return self.modulesStats[module] 
        except KeyError:
            self.modulesStats[module] = self.ModuleStats()
            return self.modulesStats[module]

    def _updateTimer(self, stats):
        stats.time += time.time() - self.lastStart

    def startTest(self, test):
134
        print test.__class__.__module__, test._TestCase__testMethodName
135 136 137 138
        unittest.TestResult.startTest(self, test)
        module = test.__class__.__name__
        method = test._TestCase__testMethodName
        logging.info(" * TEST %s" % test)
139 140
        stats = self._getModuleStats(test)
        stats.run += 1
141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160
        self.lastStart = time.time()

    def addSuccess(self, test):
        unittest.TestResult.addSuccess(self, test)
        stats = self._getModuleStats(test)
        stats.success += 1
        self._updateTimer(stats)

    def addError(self, test, err):
        unittest.TestResult.addError(self, test, err)
        stats = self._getModuleStats(test)
        stats.errors += 1
        self._updateTimer(stats)

    def addFailure(self, test, err):
        unittest.TestResult.addFailure(self, test, err)
        stats = self._getModuleStats(test)
        stats.failures += 1
        self._updateTimer(stats)

161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178
    def _buildSystemInfo(self):
        import platform
        import datetime
        s = """
    Date        : %s
    Node        : %s
    Processor   : %s (%s)
    System      : %s (%s)
        """ % (
            datetime.date.today().isoformat(),
            platform.node(),
            platform.processor(),
            platform.architecture()[0],
            platform.system(),
            platform.release(),
        )
        return s

179
    def _buildSummary(self):
180 181 182 183 184 185
        # visual 
        header       = "%25s |   run   | success |  errors |  fails  |   time   \n" % 'Test Module'
        separator    = "%25s-+---------+---------+---------+---------+----------\n" % ('-' * 25)
        format       = "%25s |   %3s   |   %3s   |   %3s   |   %3s   | %6.2fs   \n"
        group_f      = "%25s |         |         |         |         |          \n" 
        # header
186
        s = ' ' * 30 + ' NEO TESTS REPORT'
187
        s += '\n\n'
188
        s += self._buildSystemInfo()
189 190 191 192 193 194 195 196
        s += '\n' + header + separator
        group = None
        t_success = 0
        # for each test case
        for k, v in sorted(self.modulesStats.items()):
            # test case stats
            t_success += v.success
            run, success = v.run or '.', v.success or '.'
197
            errors, failures = v.errors or '.', v.failures or '.'
198 199
            name = k[-1].lstrip('test')
            args = (name, run, success, errors, failures, v.time)
200
            s += format % args
201 202 203 204 205 206 207 208 209 210
            # display group below its content
            _group = '.'.join(k[:-1])
            if group is None:
                group = _group
            if _group != group:
                s += separator + group_f % group + separator
                group = _group
        # the last group
        s += separator  + group_f % group + separator
        # the final summary
211
        errors, failures = len(self.errors) or '.', len(self.failures) or '.'
212 213
        args = ("Summary", self.testsRun, t_success, errors, failures, self.time)
        s += format % args + separator + '\n'
214 215 216 217 218 219 220 221
        return s

    def _buildErrors(self):
        s = '\n'
        if len(self.errors):
            s += '\nERRORS:\n'
            for test, trace in self.errors:
                s += "%s\n" % test
222
                s += "-------------------------------------------------------------\n"
223
                s += trace
224
                s += "-------------------------------------------------------------\n"
225 226 227 228 229
                s += '\n'
        if len(self.failures):
            s += '\nFAILURES:\n'
            for test, trace in self.failures:
                s += "%s\n" % test
230
                s += "-------------------------------------------------------------\n"
231
                s += trace
232
                s += "-------------------------------------------------------------\n"
233 234 235 236 237 238 239 240 241 242
                s += '\n'
        return s

    def build(self):
        self.time = sum([s.time for s in self.modulesStats.values()])
        args = (self.testsRun, len(self.errors), len(self.failures))
        self.subject = "Neo : %s Tests, %s Errors, %s Failures" % args
        self.summary = self._buildSummary()
        self.errors = self._buildErrors()

243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279
    def sendReport(self):
        """ Send a mail with the report summary """

        import smtplib
        from email.MIMEMultipart import MIMEMultipart
        from email.MIMEText import MIMEText

        # build the email
        msg = MIMEMultipart()
        msg['Subject'] = self.subject
        msg['From']    = SENDER
        msg['To']      = ', '.join(RECIPIENTS)
        #msg.preamble = self.subject
        msg.epilogue = ''

        # Add custom headers for client side filtering
        msg['X-ERP5-Tests'] = 'NEO'
        if self.wasSuccessful():
          msg['X-ERP5-Tests-Status'] = 'OK'

        # write the body
        body = MIMEText(self.summary + self.errors, 'text')
        msg.attach(body)

        # attach the log file
        if ATTACH_LOG:
            log = MIMEText(file(LOG_FILE, 'r').read())
            log.add_header('Content-Disposition', 'attachment', filename=LOG_FILE)
            msg.attach(log)

        # Send the email via our own SMTP server.
        s = smtplib.SMTP()
        s.connect(*SMTP_SERVER)
        mail = msg.as_string()
        for recipient in RECIPIENTS:
            s.sendmail(SENDER, recipient, mail)
        s.close()
280 281

if __name__ == "__main__":
282
    
283
    # run and build the report
284 285 286 287 288
    runner = NeoTestRunner()
    runner.run('Unit tests', UNIT_TEST_MODULES)
    if WITH_ZODB_TESTS:
        runner.run('Functional tests', FUNC_TEST_MODULES, prefix='check')
    runner.build()
289 290
    # send a mail
    if SEND_REPORT:
291 292 293
        runner.sendReport()
    print runner.errors
    print runner.summary