File: client.py

package info (click to toggle)
transmissionrpc 0.8-1
  • links: PTS, VCS
  • area: main
  • in suites: wheezy
  • size: 348 kB
  • sloc: python: 1,778; makefile: 13
file content (235 lines) | stat: -rwxr-xr-x 8,859 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
# -*- coding: utf-8 -*-
# 2008-12, Erik Svensson <erik.public@gmail.com>
# Licensed under the MIT license.

import sys, os, os.path, base64
import unittest
import urlparse

try:
    import json
except ImportError:
    import simplejson as json

import transmissionrpc.constants
from transmissionrpc import TransmissionError, Client, HTTPHandler

def tree_differences(a, b):
    return node_differences(a, b, '.')

def node_differences(a, b, root):
    errors = []
    if isinstance(a, dict) and isinstance(b, dict):
        for k, v in a.iteritems():
            node = root + '.' + k
            if k not in b:
                errors.append('Field %s missing from b at %s' % (k, node))
            else:
                errors.extend(node_differences(a[k], b[k], node))
        for k, v in b.iteritems():
            node = root + '.' + k
            if k not in a:
                errors.append('Field %s missing from a at %s' % (k, node))
    elif isinstance(a, list) and isinstance(b, list):
        for v in a:
            if v not in b:
                errors.append('Value %s missing from b at %s' % (v, root))
        for v in b:
            if v not in a:
                errors.append('Value %s missing from a at %s' % (v, root))
    else:
        if a != b:
            errors.append('Value %s != %s at %s' % (a, b, root))
    return errors

class TestHTTPHandler(HTTPHandler):
    def __init__(self, test_name=None):
        self.url = None
        self.user = None
        self.password = None
        self.tests = None
        self.test_index = 0
        if test_name:
            test_file = test_name + '.json'
            here = os.path.dirname(os.path.abspath(__file__))
            test_path = os.path.join(here, 'data', test_file)
            fd = open(test_path, 'r')
            test_data = json.load(fd)
            fd.close()
            if 'test sequence' in test_data:
                self.tests = test_data['test sequence']
    
    def set_authentication(self, url, user, password):
        urlo = urlparse.urlparse(url)
        if urlo.scheme == '':
            raise ValueError('URL should have a scheme.')
        else:
            self.url = url
        if user and password:
            if isinstance(user, (str, unicode)):
                self.user = user
            else:
                raise TypeError('Invalid type for user.')
            if isinstance(password, (str, unicode)):
                self.password = password
            else:
                raise TypeError('Invalid type for password.')
        elif user or password:
            raise ValueError('User AND password or neither.')
    
    def request(self, url, query, headers, timeout):
        response = {}
        if self.url and self.url != url:
            raise ValueError('New URL?!')
        urlo = urlparse.urlparse(url)
        if urlo.scheme == '':
            raise ValueError('URL should have a scheme.')
        else:
            self.url = url
        q = json.loads(query)
        
        if self.tests:
            test_data = self.tests[self.test_index]
            self.test_index += 1
            errors = tree_differences(test_data['request'], q)
            if len(errors) > 0:
                errors = '\n\t'.join(errors)
                raise Exception('Invalid request\n%s\n%s\n. Errors: %s\n' % (json.dumps(q, indent=2), json.dumps(test_data['request'], indent=2), errors))
            if 'response' in test_data:
                response = test_data['response']
        else:
            response['tag'] = int(q['tag'])
            response['result'] = 'success'
        return json.dumps(response)

def createClient(*args, **kwargs):
    test_name = None
    if 'test_name' in kwargs:
        test_name = kwargs['test_name']
        del kwargs['test_name']
    kwargs['http_handler'] = TestHTTPHandler(test_name)
    return Client(*args, **kwargs)

class ClientTest(unittest.TestCase):

    def testConstruction(self):
        tc = createClient(test_name='construction')
        self.assertEqual(tc.url, 'http://localhost:%d/transmission/rpc' % (transmissionrpc.constants.DEFAULT_PORT))
        tc = createClient('127.0.0.1', 7000, user='user', password='secret', test_name='construction')
        self.assertEqual(tc.url, 'http://127.0.0.1:7000/transmission/rpc')
        tc = createClient('127.0.0.1', 7000, user='user', password='secret', test_name='construction')
        self.assertEqual(tc.url, 'http://127.0.0.1:7000/transmission/rpc')
        tc = createClient('127.0.0.1', 7000, user='user', test_name='construction')
        self.assertEqual(tc.url, 'http://127.0.0.1:7000/transmission/rpc')
        tc = createClient('127.0.0.1', 7000, password='secret', test_name='construction')
        self.assertEqual(tc.url, 'http://127.0.0.1:7000/transmission/rpc')
        tc = createClient('127.0.0.1', 7000, password='secret', timeout=0.1, test_name='construction')
        self.assertEqual(tc.url, 'http://127.0.0.1:7000/transmission/rpc')
        self.assertEqual(tc.timeout, 0.1)
        tc = createClient('127.0.0.1', 7000, password='secret', timeout=10, test_name='construction')
        self.assertEqual(tc.timeout, 10.0)
        tc = createClient('127.0.0.1', 7000, password='secret', timeout=10L, test_name='construction')
        self.assertEqual(tc.timeout, 10.0)

    def testTimeoutProperty(self):
        tc = createClient('127.0.0.1', 12345, timeout=10L, test_name='construction')
        self.assertEqual(tc.timeout, 10.0)
        tc.timeout = 0.1
        self.assertEqual(tc.timeout, 0.1)
        tc.timeout = 100L
        self.assertEqual(tc.timeout, 100.0)
        tc.timeout = 100
        self.assertEqual(tc.timeout, 100.0)
        del tc.timeout
        self.assertEqual(tc.timeout, transmissionrpc.constants.DEFAULT_TIMEOUT)
        tc.timeout = '100.1'
        self.assertEqual(tc.timeout, 100.1)
        self.failUnlessRaises(ValueError, tc._set_timeout, '10 years')
            
    def testAdd(self):
        tc = createClient(test_name='add')
        data = 'data'
        
        r = tc.add(data)[0]
        self.assertEqual(r.id, 0)
        self.assertEqual(r.hashString, 'A000')
        self.assertEqual(r.name, 'testtransfer0')
        
        r = tc.add(data, paused=True)[1]
        self.assertEqual(r.id, 1)
        self.assertEqual(r.hashString, 'A001')
        self.assertEqual(r.name, 'testtransfer1')
        
        r = tc.add(data, download_dir='/tmp')[2]
        self.assertEqual(r.id, 2)
        self.assertEqual(r.hashString, 'A002')
        self.assertEqual(r.name, 'testtransfer2')
        
        r = tc.add(data, peer_limit=10)[3]
        self.assertEqual(r.id, 3)
        self.assertEqual(r.hashString, 'A003')
        self.assertEqual(r.name, 'testtransfer3')
        
        r = tc.add(data, paused=True, download_dir='/tmp', peer_limit=10)[4]
        self.assertEqual(r.id, 4)
        self.assertEqual(r.hashString, 'A004')
        self.assertEqual(r.name, 'testtransfer4')
        
        self.failUnlessRaises(ValueError, tc.add, data, peer_limit='apa')

    def testAddUri(self):
        data_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'data')
        tc = createClient(test_name='adduri')

        r = tc.add_uri('torrent.txt', paused=False, download_dir='/var/downloads', peer_limit=1)[0]
        self.assertEqual(r.id, 0)
        self.assertEqual(r.hashString, 'A000')
        self.assertEqual(r.name, 'testtransfer0')

        r = tc.add_uri('file://' + os.path.join(data_path, 'torrent.txt'), paused=True, download_dir='/tmp', peer_limit=200)[1]
        self.assertEqual(r.id, 1)
        self.assertEqual(r.hashString, 'A001')
        self.assertEqual(r.name, 'testtransfer1')

    def testRemove(self):
        tc = createClient(test_name='remove')
        
        tc.remove(['b000', 2, 3])
        tc.remove(1, delete_data=True)
        tc.remove('b002', delete_data=False)

    def testStart(self):
        tc = createClient(test_name='start')
        
        tc.start(['abcdef', 20, 30])
        tc.start(1)
        tc.start('a0123456789')

    def testStop(self):
        tc = createClient(test_name='stop')
        
        tc.stop(2)
        tc.stop('bad')
        tc.stop(['bad', 'ba5', '30', 20])

    def testVerify(self):
        tc = createClient(test_name='verify')
        
        tc.verify(10000)
        tc.verify('d')
        tc.verify(['a', 'b', 'c'])

    def testInfo(self):
        tc = createClient(test_name='info')
        
        r = tc.info()
        self.assertTrue(2 in r)
        self.assertTrue(3 in r)
        t = r[2]
        self.assertEqual(t.id, 2)
        self.assertEqual(t.name, 'ubuntu-10.04-server-amd64.iso')
        self.assertEqual(t.hashString, 'ab8ea951c022d4745a9b06ab8020b952a52b71ca')

def suite():
    suite = unittest.TestLoader().loadTestsFromTestCase(ClientTest)
    return suite