Edgewall Software

Version 2 (modified by Jun Omae, 10 years ago) ( diff )

added encoding comment, sorted import statements, added tearDown, setUp has no arguments.

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:

# -*- coding: utf-8 -*-

import os
import shutil
import tempfile
import unittest

from trac.test import EnvironmentStub

from logwatcher import api


class TestApi(unittest.TestCase):

    def setUp(self):
        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 tearDown(self):
        shutil.rmtree(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.