~jtv/storm/profile-fetches

« back to all changes in this revision

Viewing changes to tests/helpers.py

  • Committer: Gustavo Niemeyer
  • Date: 2006-05-13 04:42:42 UTC
  • Revision ID: gustavo@niemeyer.net-20060513044242-39457d29f0849be3
Adding initial infrastructure.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
from cStringIO import StringIO
 
2
import unittest
 
3
import tempfile
 
4
import logging
 
5
import shutil
 
6
import sys
 
7
 
 
8
 
 
9
class TestHelper(unittest.TestCase):
 
10
 
 
11
    helpers = []
 
12
 
 
13
    def setUp(self):
 
14
        self._helper_instances = []
 
15
        for helper_factory in self.helpers:
 
16
            helper = helper_factory()
 
17
            helper.set_up(self)
 
18
            self._helper_instances.append(helper)
 
19
 
 
20
    def tearDown(self):
 
21
        for helper in reversed(self._helper_instances):
 
22
            helper.tear_down(self)
 
23
 
 
24
 
 
25
class MakePath(object):
 
26
 
 
27
    def set_up(self, test_case):
 
28
        self.dirname = tempfile.mkdtemp()
 
29
        self.dirs = []
 
30
        self.counter = 0
 
31
        test_case.make_dir = self.make_dir
 
32
        test_case.make_path = self.make_path
 
33
 
 
34
    def tear_down(self, test_case):
 
35
        shutil.rmtree(self.dirname)
 
36
        [shutil.rmtree(dir) for dir in self.dirs]
 
37
 
 
38
    def make_dir(self):
 
39
        path = tempfile.mkdtemp()
 
40
        self.dirs.append(path)
 
41
        return path
 
42
 
 
43
    def make_path(self, content=None, path=None):
 
44
        if path is None:
 
45
            self.counter += 1
 
46
            path = "%s/%03d" % (self.dirname, self.counter)
 
47
        if content is not None:
 
48
            file = open(path, "w")
 
49
            try:
 
50
                file.write(content)
 
51
            finally:
 
52
                file.close()
 
53
        return path
 
54
 
 
55
 
 
56
class LogKeeper(object):
 
57
    """Record logging information.
 
58
 
 
59
    Puts a 'logfile' attribute on your test case, which is a StringIO
 
60
    containing all log output.
 
61
    """
 
62
 
 
63
    def set_up(self, test_case):
 
64
        logger = logging.getLogger()
 
65
        test_case.logfile = StringIO()
 
66
        handler = logging.StreamHandler(test_case.logfile)
 
67
        self.old_handlers = logger.handlers
 
68
        # Sanity check; this might not be 100% what we want
 
69
        if self.old_handlers:
 
70
            test_case.assertEquals(len(self.old_handlers), 1)
 
71
            test_case.assertEquals(self.old_handlers[0].stream, sys.stderr)
 
72
        logger.handlers = [handler]
 
73
 
 
74
    def tear_down(self, test_case):
 
75
        logging.getLogger().handlers = self.old_handlers