Passed
Push — master ( 694e2f...150a8e )
by Dean
09:10 queued 06:18
created

setup()   A

Complexity

Conditions 4

Size

Total Lines 19

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 20

Importance

Changes 1
Bugs 0 Features 0
Metric Value
dl 0
loc 19
ccs 0
cts 11
cp 0
rs 9.2
c 1
b 0
f 0
cc 4
crap 20
1
from argparse import ArgumentParser
2
import importlib
3
import inspect
4
import json
5
import logging
6
import os
7
import sys
8
import traceback
9
10
log = logging.getLogger(__name__)
11
12
PLUGIN_IDENTIFIER = 'trakttv.bundle'
13
14
15
def get_bundle_path():
16
    bundle_path = os.path.dirname(os.path.abspath(__file__))
17
18
    # Find plugin identifier
19
    pos = bundle_path.lower().find(PLUGIN_IDENTIFIER)
20
21
    if pos < 0:
22
        return None
23
24
    # Return bundle path
25
    return bundle_path[:pos + len(PLUGIN_IDENTIFIER)]
26
27
28
def setup(search_paths):
29
    # Find bundle path
30
    bundle_path = get_bundle_path()
31
32
    if not bundle_path:
33
        raise Exception("Unable to find bundle path")
34
35
    log.debug("bundle_path: %r", bundle_path)
36
37
    # Setup library search paths
38
    for path in (search_paths or []):
39
        if not os.path.exists(path):
40
            continue
41
42
        sys.path.insert(0, path)
43
44
    # Set environment variable (to disable plugin fixes)
45
    os.environ['TFP_TEST_HOST'] = 'true'
46
    return True
47
48
49
def import_module(name):
50
    log.info("Importing module %r", name)
51
52
    module = importlib.import_module(name)
53
54
    if not module:
55
        raise Exception('Unable to import module %r' % name)
56
57
    log.info('Imported module: %r', module)
58
    return module
59
60
61
def find_test(module):
62
    for key in dir(module):
63
        value = getattr(module, key, None)
64
65
        if not value:
66
            continue
67
68
        if not inspect.isclass(value):
69
            continue
70
71
        if value.__module__ != module.__name__:
72
            continue
73
74
        return value
75
76
    return None
77
78
79
def run():
80
    # Parse arguments
81
    parser = ArgumentParser()
82
    parser.add_argument('--debug', action='store_true')
83
    parser.add_argument('--module', required=True)
84
    parser.add_argument('--name', required=True)
85
    parser.add_argument('--search-paths', required=True)
86
87
    args = parser.parse_args()
88
89
    search_paths = args.search_paths.strip('"').split(';')
90
91
    log.debug('module: %r', args.module)
92
    log.debug('name: %r', args.name)
93
    log.debug('search_paths: %r', search_paths)
94
95
    # Setup logging
96
    logging.basicConfig(level=logging.DEBUG if args.debug else logging.WARN)
97
98
    # Setup test host
99
    if not setup(search_paths):
100
        raise Exception("Unable to setup test host")
101
102
    # Import test module
103
    module = import_module(args.module)
104
105
    if not module:
106
        raise Exception("Unable to import test module: %r" % args.module)
107
108
    # Find test class
109
    cls = find_test(module)
110
111
    if not cls:
112
        raise Exception('Unable to find test class in %r' % args.module)
113
114
    # Find test method
115
    func = getattr(cls, args.name)
116
117
    if not func:
118
        raise Exception('Unable to find test method %r in %r' % (args.name, cls))
119
120
    # Run test
121
    return func()
122
123
124
if __name__ == '__main__':
125
    success = True
126
127
    try:
128
        result = run()
129
    except Exception, ex:
130
        tb = traceback.format_exc()
131
132
        result = {
133
            'message': ex.message,
134
            'traceback': tb
135
        }
136
        success = False
137
138
    sys.stdout.write(json.dumps(result))
139
    sys.stdout.flush()
140
141
    if not success:
142
        exit(1)
143