Edgewall Software

Version 1 (modified by Franz Mayer <franz.mayer@…>, 10 years ago) ( diff )

Very first wiki page for Writing unit tests

Writing unit tests

This wiki page should show how to write your own unit tests for Trac or Trac plugin.

Start writing TestCases

Any unit test should derive from class unittest.TestCase in order to be called from unittest.makeSuite. Thus you can make a set of test cases, which are called test suite.

Usually you need to setup your Environment in order to have any access to your Trac environment. This can be done using EnvironmentStub.

This test suite can be executed as a normal python code.

Here's a simple Test case (from trac plugin LogWatcherPlugin) to explain the above:

import unittest
from logwatcher import api
from trac.test import EnvironmentStub
import tempfile
import os


class TestApi(unittest.TestCase):

    def setUp(self, port=None):
        self.env = EnvironmentStub(enable=[
            'trac.*', 'logwatcher.api'
        ])
        self.env.path = tempfile.mkdtemp()
        os.mkdir('%s/log' % self.env.path)

        self.env.config.set('logging', 'log_type', 'file')
        self.env.setup_log()
        print 'successfully set up with env path: %s' % self.env.path

    def test_get_logfile_name(self):
        test_api = api.LogViewerApi(self.env)
        logfile_name = test_api.get_logfile_name()
        print "log file name: %s" % logfile_name
        self.assertIsNotNone(logfile_name, "log file name is None")


def suite():
    print "Starting **API** test suite"
    suite = unittest.TestSuite()
    suite.addTest(unittest.makeSuite(TestApi, 'test'))
    return suite

if __name__ == '__main__':
    unittest.main(defaultTest='suite')
Note: See TracWiki for help on using the wiki.