summaryrefslogtreecommitdiffstats
path: root/deluge/tests/test_ui_entry.py
blob: 130dbe192661bbc22c2d66625c26343555218a80 (plain)
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
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
# -*- coding: utf-8 -*-
#
# Copyright (C) 2016 bendikro <bro.devel+deluge@gmail.com>
#
# This file is part of Deluge and is licensed under GNU General Public License 3.0, or later, with
# the additional special exception to link portions of this program with the OpenSSL library.
# See LICENSE for more details.
#

from __future__ import print_function, unicode_literals

import argparse
import sys
from io import StringIO

import mock
import pytest
from twisted.internet import defer

import deluge
import deluge.component as component
import deluge.ui.console
import deluge.ui.console.cmdline.commands.quit
import deluge.ui.console.main
import deluge.ui.web.server
from deluge.common import get_localhost_auth, utf8_encode_structure
from deluge.ui import ui_entry
from deluge.ui.web.server import DelugeWeb

from . import common
from .basetest import BaseTestCase
from .daemon_base import DaemonBase

DEBUG_COMMAND = False

sys_stdout = sys.stdout
# To catch output to stdout/stderr while running unit tests, we patch
# the file descriptors in sys and argparse._sys with StringFileDescriptor.
# Regular print statements from such tests will therefore write to the
# StringFileDescriptor object instead of the terminal.
# To print to terminal from the tests, use: print('Message...', file=sys_stdout)


class StringFileDescriptor(object):
    """File descriptor that writes to string buffer"""
    def __init__(self, fd):
        self.out = StringIO()
        self.fd = fd
        for a in ['encoding']:
            setattr(self, a, getattr(sys_stdout, a))

    def write(self, *data, **kwargs):
        # io.StringIO requires unicode strings.
        print(unicode(*data), file=self.out, end='')

    def flush(self):
        self.out.flush()


class UIBaseTestCase(object):

    def __init__(self):
        self.var = {}

    def set_up(self):
        common.set_tmp_config_dir()
        common.setup_test_logger(level='info', prefix=self.id())
        return component.start()

    def tear_down(self):
        return component.shutdown()

    def exec_command(self):
        if DEBUG_COMMAND:
            print('Executing: %s\n' % sys.argv, file=sys_stdout)
        return self.var['start_cmd']()


class UIWithDaemonBaseTestCase(UIBaseTestCase, DaemonBase):
    """Subclass for test that require a deluged daemon"""

    def __init__(self):
        UIBaseTestCase.__init__(self)

    def set_up(self):
        d = self.common_set_up()
        common.setup_test_logger(level='info', prefix=self.id())
        d.addCallback(self.start_core)
        return d

    def tear_down(self):
        d = UIBaseTestCase.tear_down(self)
        d.addCallback(self.terminate_core)
        return d


class DelugeEntryTestCase(BaseTestCase):

    def set_up(self):
        common.set_tmp_config_dir()
        return component.start()

    def tear_down(self):
        return component.shutdown()

    def test_deluge_help(self):
        self.patch(sys, 'argv', ['./deluge', '-h'])
        config = deluge.configmanager.ConfigManager('ui.conf', ui_entry.DEFAULT_PREFS)
        config.config['default_ui'] = 'console'
        config.save()

        fd = StringFileDescriptor(sys.stdout)
        self.patch(argparse._sys, 'stdout', fd)

        with mock.patch('deluge.ui.console.main.ConsoleUI'):
            self.assertRaises(SystemExit, ui_entry.start_ui)
            self.assertTrue('usage: deluge' in fd.out.getvalue())
            self.assertTrue('UI Options:' in fd.out.getvalue())
            self.assertTrue('* console' in fd.out.getvalue())

    def test_start_default(self):
        self.patch(sys, 'argv', ['./deluge'])
        config = deluge.configmanager.ConfigManager('ui.conf', ui_entry.DEFAULT_PREFS)
        config.config['default_ui'] = 'console'
        config.save()

        with mock.patch('deluge.ui.console.main.ConsoleUI'):
            # Just test that no exception is raised
            ui_entry.start_ui()

    def test_start_with_log_level(self):
        _level = []

        def setup_logger(level='error', filename=None, filemode='w', logrotate=None, output_stream=sys.stdout):
            _level.append(level)

        self.patch(deluge.log, 'setup_logger', setup_logger)
        self.patch(sys, 'argv', ['./deluge', '-L', 'info'])

        config = deluge.configmanager.ConfigManager('ui.conf', ui_entry.DEFAULT_PREFS)
        config.config['default_ui'] = 'console'
        config.save()

        with mock.patch('deluge.ui.console.main.ConsoleUI'):
            # Just test that no exception is raised
            ui_entry.start_ui()

        self.assertEqual(_level[0], 'info')


class GtkUIBaseTestCase(UIBaseTestCase):
    """Implement all GtkUI tests here"""

    def test_start_gtkui(self):
        self.patch(sys, 'argv', utf8_encode_structure(self.var['sys_arg_cmd']))

        from deluge.ui.gtkui import gtkui
        with mock.patch.object(gtkui.GtkUI, 'start', autospec=True):
            self.exec_command()


@pytest.mark.gtkui
class GtkUIDelugeScriptEntryTestCase(BaseTestCase, GtkUIBaseTestCase):

    def __init__(self, testname):
        super(GtkUIDelugeScriptEntryTestCase, self).__init__(testname)
        GtkUIBaseTestCase.__init__(self)

        self.var['cmd_name'] = 'deluge gtk'
        self.var['start_cmd'] = ui_entry.start_ui
        self.var['sys_arg_cmd'] = ['./deluge', 'gtk']

    def set_up(self):
        return GtkUIBaseTestCase.set_up(self)

    def tear_down(self):
        return GtkUIBaseTestCase.tear_down(self)


@pytest.mark.gtkui
class GtkUIScriptEntryTestCase(BaseTestCase, GtkUIBaseTestCase):

    def __init__(self, testname):
        super(GtkUIScriptEntryTestCase, self).__init__(testname)
        GtkUIBaseTestCase.__init__(self)
        from deluge.ui import gtkui
        self.var['cmd_name'] = 'deluge-gtk'
        self.var['start_cmd'] = gtkui.start
        self.var['sys_arg_cmd'] = ['./deluge-gtk']

    def set_up(self):
        return GtkUIBaseTestCase.set_up(self)

    def tear_down(self):
        return GtkUIBaseTestCase.tear_down(self)


class DelugeWebMock(DelugeWeb):
    def __init__(self, *args, **kwargs):
        kwargs['daemon'] = False
        DelugeWeb.__init__(self, *args, **kwargs)


class WebUIBaseTestCase(UIBaseTestCase):
    """Implement all WebUI tests here"""

    def test_start_webserver(self):
        self.patch(sys, 'argv', self.var['sys_arg_cmd'])
        self.patch(deluge.ui.web.server, 'DelugeWeb', DelugeWebMock)
        self.exec_command()

    def test_start_web_with_log_level(self):
        _level = []

        def setup_logger(level='error', filename=None, filemode='w', logrotate=None, output_stream=sys.stdout):
            _level.append(level)

        self.patch(deluge.log, 'setup_logger', setup_logger)
        self.patch(sys, 'argv', self.var['sys_arg_cmd'] + ['-L', 'info'])

        config = deluge.configmanager.ConfigManager('ui.conf', ui_entry.DEFAULT_PREFS)
        config.config['default_ui'] = 'web'
        config.save()

        self.patch(deluge.ui.web.server, 'DelugeWeb', DelugeWebMock)
        self.exec_command()
        self.assertEqual(_level[0], 'info')


class WebUIScriptEntryTestCase(BaseTestCase, WebUIBaseTestCase):

    def __init__(self, testname):
        super(WebUIScriptEntryTestCase, self).__init__(testname)
        WebUIBaseTestCase.__init__(self)
        self.var['cmd_name'] = 'deluge-web'
        self.var['start_cmd'] = deluge.ui.web.start
        self.var['sys_arg_cmd'] = ['./deluge-web', '--do-not-daemonize']

    def set_up(self):
        return WebUIBaseTestCase.set_up(self)

    def tear_down(self):
        return WebUIBaseTestCase.tear_down(self)


class WebUIDelugeScriptEntryTestCase(BaseTestCase, WebUIBaseTestCase):

    def __init__(self, testname):
        super(WebUIDelugeScriptEntryTestCase, self).__init__(testname)
        WebUIBaseTestCase.__init__(self)
        self.var['cmd_name'] = 'deluge web'
        self.var['start_cmd'] = ui_entry.start_ui
        self.var['sys_arg_cmd'] = ['./deluge', 'web', '--do-not-daemonize']

    def set_up(self):
        return WebUIBaseTestCase.set_up(self)

    def tear_down(self):
        return WebUIBaseTestCase.tear_down(self)


class ConsoleUIBaseTestCase(UIBaseTestCase):
    """Implement Console tests that do not require a running daemon"""

    def test_start_console(self):
        self.patch(sys, 'argv', self.var['sys_arg_cmd'])
        with mock.patch('deluge.ui.console.main.ConsoleUI'):
            self.exec_command()

    def test_start_console_with_log_level(self):
        _level = []

        def setup_logger(level='error', filename=None, filemode='w', logrotate=None, output_stream=sys.stdout):
            _level.append(level)

        self.patch(deluge.log, 'setup_logger', setup_logger)
        self.patch(sys, 'argv', self.var['sys_arg_cmd'] + ['-L', 'info'])

        config = deluge.configmanager.ConfigManager('ui.conf', ui_entry.DEFAULT_PREFS)
        config.config['default_ui'] = 'console'
        config.save()

        with mock.patch('deluge.ui.console.main.ConsoleUI'):
            # Just test that no exception is raised
            self.exec_command()

        self.assertEqual(_level[0], 'info')

    def test_console_help(self):
        self.patch(sys, 'argv', self.var['sys_arg_cmd'] + ['-h'])
        fd = StringFileDescriptor(sys.stdout)
        self.patch(argparse._sys, 'stdout', fd)

        with mock.patch('deluge.ui.console.main.ConsoleUI'):
            self.assertRaises(SystemExit, self.exec_command)
            std_output = fd.out.getvalue()
            self.assertTrue(('usage: %s' % self.var['cmd_name']) in std_output)  # Check command name
            self.assertTrue('Common Options:' in std_output)
            self.assertTrue('Console Options:' in std_output)
            self.assertTrue('Console Commands:\n  The following console commands are available:' in std_output)
            self.assertTrue('The following console commands are available:' in std_output)

    def test_console_command_info(self):
        self.patch(sys, 'argv', self.var['sys_arg_cmd'] + ['info'])
        fd = StringFileDescriptor(sys.stdout)
        self.patch(argparse._sys, 'stdout', fd)

        with mock.patch('deluge.ui.console.main.ConsoleUI'):
            self.exec_command()

    def test_console_command_info_help(self):
        self.patch(sys, 'argv', self.var['sys_arg_cmd'] + ['info', '-h'])
        fd = StringFileDescriptor(sys.stdout)
        self.patch(argparse._sys, 'stdout', fd)

        with mock.patch('deluge.ui.console.main.ConsoleUI'):
            self.assertRaises(SystemExit, self.exec_command)
            std_output = fd.out.getvalue()
            self.assertTrue('usage: info' in std_output)
            self.assertTrue('Show information about the torrents' in std_output)

    def test_console_unrecognized_arguments(self):
        self.patch(sys, 'argv', ['./deluge', '--ui', 'console'])  # --ui is not longer supported
        fd = StringFileDescriptor(sys.stdout)
        self.patch(argparse._sys, 'stderr', fd)
        with mock.patch('deluge.ui.console.main.ConsoleUI'):
            self.assertRaises(SystemExit, self.exec_command)
            self.assertTrue('unrecognized arguments: --ui' in fd.out.getvalue())


class ConsoleUIWithDaemonBaseTestCase(UIWithDaemonBaseTestCase):
    """Implement Console tests that require a running daemon"""

    def set_up(self):
        # Avoid calling reactor.shutdown after commands are executed by main.exec_args()
        deluge.ui.console.main.reactor = common.ReactorOverride()
        return UIWithDaemonBaseTestCase.set_up(self)

    @defer.inlineCallbacks
    def test_console_command_status(self):
        username, password = get_localhost_auth()
        self.patch(
            sys, 'argv', self.var['sys_arg_cmd'] + ['--port'] + ['58900'] + ['--username'] +
            [username] + ['--password'] + [password] + ['status'],
        )
        fd = StringFileDescriptor(sys.stdout)
        self.patch(sys, 'stdout', fd)

        yield self.exec_command()

        std_output = fd.out.getvalue()
        self.assertTrue(std_output.startswith('Total upload: ') and std_output.endswith(' Moving: 0\n'))


class ConsoleScriptEntryWithDaemonTestCase(BaseTestCase, ConsoleUIWithDaemonBaseTestCase):

    def __init__(self, testname):
        super(ConsoleScriptEntryWithDaemonTestCase, self).__init__(testname)
        ConsoleUIWithDaemonBaseTestCase.__init__(self)
        self.var['cmd_name'] = 'deluge-console'
        self.var['sys_arg_cmd'] = ['./deluge-console']

    def set_up(self):
        from deluge.ui.console.console import Console

        def start_console():
            return Console().start()

        self.patch(deluge.ui.console, 'start', start_console)
        self.var['start_cmd'] = deluge.ui.console.start

        return ConsoleUIWithDaemonBaseTestCase.set_up(self)

    def tear_down(self):
        return ConsoleUIWithDaemonBaseTestCase.tear_down(self)


class ConsoleScriptEntryTestCase(BaseTestCase, ConsoleUIBaseTestCase):

    def __init__(self, testname):
        super(ConsoleScriptEntryTestCase, self).__init__(testname)
        ConsoleUIBaseTestCase.__init__(self)
        self.var['cmd_name'] = 'deluge-console'
        self.var['start_cmd'] = deluge.ui.console.start
        self.var['sys_arg_cmd'] = ['./deluge-console']

    def set_up(self):
        return ConsoleUIBaseTestCase.set_up(self)

    def tear_down(self):
        return ConsoleUIBaseTestCase.tear_down(self)


class ConsoleDelugeScriptEntryTestCase(BaseTestCase, ConsoleUIBaseTestCase):

    def __init__(self, testname):
        super(ConsoleDelugeScriptEntryTestCase, self).__init__(testname)
        ConsoleUIBaseTestCase.__init__(self)
        self.var['cmd_name'] = 'deluge console'
        self.var['start_cmd'] = ui_entry.start_ui
        self.var['sys_arg_cmd'] = ['./deluge', 'console']

    def set_up(self):
        return ConsoleUIBaseTestCase.set_up(self)

    def tear_down(self):
        return ConsoleUIBaseTestCase.tear_down(self)