~cosmin.lupu/+junk/penguintv

« back to all changes in this revision

Viewing changes to penguintv/ptvbittorrent/testtest.py

  • Committer: cosmin.lupu at gmail
  • Date: 2010-04-27 16:47:43 UTC
  • Revision ID: cosmin.lupu@gmail.com-20100427164743-ds8xrqonipp5ovdf
initial packaging

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
"""
 
2
A much simpler testing framework than PyUnit
 
3
 
 
4
tests a module by running all functions in it whose name starts with 'test'
 
5
 
 
6
a test fails if it raises an exception, otherwise it passes
 
7
 
 
8
functions are try_all and try_single
 
9
"""
 
10
 
 
11
# Written by Bram Cohen
 
12
# see LICENSE.txt for license information
 
13
 
 
14
from traceback import print_exc
 
15
from sys import modules
 
16
 
 
17
def try_all(excludes = [], excluded_paths=[]):
 
18
    """
 
19
    tests all imported modules
 
20
 
 
21
    takes an optional list of module names and/or module objects to skip over.
 
22
    modules from files under under any of excluded_paths are also skipped.
 
23
    """
 
24
    failed = []
 
25
    for modulename, module in modules.items():
 
26
        # skip builtins
 
27
        if not hasattr(module, '__file__'):
 
28
            continue
 
29
        # skip modules under any of excluded_paths
 
30
        if [p for p in excluded_paths if module.__file__.startswith(p)]:
 
31
            continue
 
32
        if modulename not in excludes and module not in excludes:
 
33
            try_module(module, modulename, failed)
 
34
    print_failed(failed)
 
35
 
 
36
def try_single(m):
 
37
    """
 
38
    tests a single module
 
39
    
 
40
    accepts either a module object or a module name in string form
 
41
    """
 
42
    if type(m) is str:
 
43
        modulename = m
 
44
        module = __import__(m)
 
45
    else:
 
46
        modulename = str(m)
 
47
        module = m
 
48
    failed = []
 
49
    try_module(module, modulename, failed)
 
50
    print_failed(failed)
 
51
 
 
52
def try_module(module, modulename, failed):
 
53
    if not hasattr(module, '__dict__'):
 
54
        return
 
55
    for n, func in module.__dict__.items():
 
56
        if not callable(func) or n[:4] != 'test':
 
57
            continue
 
58
        name = modulename + '.' + n
 
59
        try:
 
60
            print 'trying ' + name
 
61
            func()
 
62
            print 'passed ' + name
 
63
        except:
 
64
            print_exc()
 
65
            failed.append(name)
 
66
            print 'failed ' + name
 
67
 
 
68
def print_failed(failed):
 
69
    print
 
70
    if len(failed) == 0:
 
71
        print 'everything passed'
 
72
    else:
 
73
        print 'the following tests failed:'
 
74
        for i in failed:
 
75
            print i
 
76
 
 
77
 
 
78