summaryrefslogtreecommitdiff
path: root/tests/unit/completion/test_models.py
blob: ff00a11a99678907754dace183fb6c5af812df85 (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
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
# vim: ft=python fileencoding=utf-8 sts=4 sw=4 et:

# Copyright 2016-2017 Ryan Roden-Corrent (rcorre) <ryan@rcorre.net>
#
# This file is part of qutebrowser.
#
# qutebrowser is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# qutebrowser is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with qutebrowser.  If not, see <http://www.gnu.org/licenses/>.

"""Tests for completion models."""

import collections
from datetime import datetime

import pytest
from PyQt5.QtCore import QUrl
from PyQt5.QtWidgets import QTreeView

from qutebrowser.completion.models import (miscmodels, urlmodel, configmodel,
                                           sortfilter)
from qutebrowser.browser import history
from qutebrowser.config import sections, value


def _check_completions(model, expected):
    """Check that a model contains the expected items in any order.

    Args:
        expected: A dict of form
            {
                CategoryName: [(name, desc, misc), ...],
                CategoryName: [(name, desc, misc), ...],
                ...
            }
    """
    assert model.rowCount() == len(expected)
    for i in range(0, model.rowCount()):
        actual_cat = model.item(i)
        catname = actual_cat.text()
        assert catname in expected
        expected_cat = expected[catname]
        assert actual_cat.rowCount() == len(expected_cat)
        for j in range(0, actual_cat.rowCount()):
            name = actual_cat.child(j, 0)
            desc = actual_cat.child(j, 1)
            misc = actual_cat.child(j, 2)
            actual_item = (name.text(), desc.text(), misc.text())
            assert actual_item in expected_cat


def _patch_cmdutils(monkeypatch, stubs, symbol):
    """Patch the cmdutils module to provide fake commands."""
    cmd_utils = stubs.FakeCmdUtils({
        'stop': stubs.FakeCommand(name='stop', desc='stop qutebrowser'),
        'drop': stubs.FakeCommand(name='drop', desc='drop all user data'),
        'roll': stubs.FakeCommand(name='roll', desc='never gonna give you up'),
        'hide': stubs.FakeCommand(name='hide', hide=True),
        'depr': stubs.FakeCommand(name='depr', deprecated=True),
    })
    monkeypatch.setattr(symbol, cmd_utils)


def _patch_configdata(monkeypatch, stubs, symbol):
    """Patch the configdata module to provide fake data."""
    data = collections.OrderedDict([
        ('general', sections.KeyValue(
            ('time',
                value.SettingValue(stubs.FakeConfigType('fast', 'slow'),
                                   default='slow'),
                'Is an illusion.\n\nLunchtime doubly so.'),
            ('volume',
                value.SettingValue(stubs.FakeConfigType('0', '11'),
                                   default='11'),
                'Goes to 11'))),
        ('ui', sections.KeyValue(
            ('gesture',
                value.SettingValue(stubs.FakeConfigType(('on', 'off')),
                                   default='off'),
                'Waggle your hands to control qutebrowser'),
            ('mind',
                value.SettingValue(stubs.FakeConfigType(('on', 'off')),
                                   default='off'),
                'Enable mind-control ui (experimental)'),
            ('voice',
                value.SettingValue(stubs.FakeConfigType(('on', 'off')),
                                   default='off'),
                'Whether to respond to voice commands'))),
        ('searchengines', sections.ValueList(
            stubs.FakeConfigType(), stubs.FakeConfigType(),
            ('DEFAULT', 'https://duckduckgo.com/?q={}'),
        )),
    ])
    monkeypatch.setattr(symbol, data)


def _patch_config_section_desc(monkeypatch, stubs, symbol):
    """Patch the configdata module to provide fake SECTION_DESC."""
    section_desc = {
        'general': 'General/miscellaneous options.',
        'ui': 'General options related to the user interface.',
        'searchengines': 'Definitions of search engines ...',
    }
    monkeypatch.setattr(symbol, section_desc)


def _mock_view_index(model, category_idx, child_idx, qtbot):
    """Create a tree view from a model and set the current index.

    Args:
        model: model to create a fake view for.
        category_idx: index of the category to select.
        child_idx: index of the child item under that category to select.
    """
    view = QTreeView()
    qtbot.add_widget(view)
    view.setModel(model)
    idx = model.indexFromItem(model.item(category_idx).child(child_idx))
    view.setCurrentIndex(idx)
    return view


@pytest.fixture
def quickmarks(quickmark_manager_stub):
    """Pre-populate the quickmark-manager stub with some quickmarks."""
    quickmark_manager_stub.marks = collections.OrderedDict([
        ('aw', 'https://wiki.archlinux.org'),
        ('ddg', 'https://duckduckgo.com'),
        ('wiki', 'https://wikipedia.org'),
    ])
    return quickmark_manager_stub


@pytest.fixture
def bookmarks(bookmark_manager_stub):
    """Pre-populate the bookmark-manager stub with some quickmarks."""
    bookmark_manager_stub.marks = collections.OrderedDict([
        ('https://github.com', 'GitHub'),
        ('https://python.org', 'Welcome to Python.org'),
        ('http://qutebrowser.org', 'qutebrowser | qutebrowser'),
    ])
    return bookmark_manager_stub


@pytest.fixture
def web_history(stubs, web_history_stub):
    """Pre-populate the web-history stub with some history entries."""
    web_history_stub.history_dict = collections.OrderedDict([
        ('http://qutebrowser.org', history.Entry(
            datetime(2015, 9, 5).timestamp(),
            QUrl('http://qutebrowser.org'), 'qutebrowser | qutebrowser')),
        ('https://python.org', history.Entry(
            datetime(2016, 3, 8).timestamp(),
            QUrl('https://python.org'), 'Welcome to Python.org')),
        ('https://github.com', history.Entry(
            datetime(2016, 5, 1).timestamp(),
            QUrl('https://github.com'), 'GitHub')),
    ])
    return web_history_stub


def test_command_completion(qtmodeltester, monkeypatch, stubs, config_stub,
                            key_config_stub):
    """Test the results of command completion.

    Validates that:
        - only non-hidden and non-deprecated commands are included
        - the command description is shown in the desc column
        - the binding (if any) is shown in the misc column
        - aliases are included
    """
    _patch_cmdutils(monkeypatch, stubs,
                    'qutebrowser.completion.models.miscmodels.cmdutils')
    config_stub.data['aliases'] = {'rock': 'roll'}
    key_config_stub.set_bindings_for('normal', {'s': 'stop',
                                                'rr': 'roll',
                                                'ro': 'rock'})
    model = miscmodels.CommandCompletionModel()
    qtmodeltester.data_display_may_return_none = True
    qtmodeltester.check(model)

    _check_completions(model, {
        "Commands": [
            ('stop', 'stop qutebrowser', 's'),
            ('drop', 'drop all user data', ''),
            ('roll', 'never gonna give you up', 'rr'),
            ('rock', "Alias for 'roll'", 'ro'),
        ]
    })


def test_help_completion(qtmodeltester, monkeypatch, stubs, key_config_stub):
    """Test the results of command completion.

    Validates that:
        - only non-deprecated commands are included
        - the command description is shown in the desc column
        - the binding (if any) is shown in the misc column
        - aliases are included
        - only the first line of a multiline description is shown
    """
    module = 'qutebrowser.completion.models.miscmodels'
    key_config_stub.set_bindings_for('normal', {'s': 'stop', 'rr': 'roll'})
    _patch_cmdutils(monkeypatch, stubs, module + '.cmdutils')
    _patch_configdata(monkeypatch, stubs, module + '.configdata.DATA')
    model = miscmodels.HelpCompletionModel()
    qtmodeltester.data_display_may_return_none = True
    qtmodeltester.check(model)

    _check_completions(model, {
        "Commands": [
            (':stop', 'stop qutebrowser', 's'),
            (':drop', 'drop all user data', ''),
            (':roll', 'never gonna give you up', 'rr'),
            (':hide', '', ''),
        ],
        "Settings": [
            ('general->time', 'Is an illusion.', ''),
            ('general->volume', 'Goes to 11', ''),
            ('ui->gesture', 'Waggle your hands to control qutebrowser', ''),
            ('ui->mind', 'Enable mind-control ui (experimental)', ''),
            ('ui->voice', 'Whether to respond to voice commands', ''),
            ('searchengines->DEFAULT', '', ''),
        ]
    })


def test_quickmark_completion(qtmodeltester, quickmarks):
    """Test the results of quickmark completion."""
    model = miscmodels.QuickmarkCompletionModel()
    qtmodeltester.data_display_may_return_none = True
    qtmodeltester.check(model)

    _check_completions(model, {
        "Quickmarks": [
            ('aw', 'https://wiki.archlinux.org', ''),
            ('ddg', 'https://duckduckgo.com', ''),
            ('wiki', 'https://wikipedia.org', ''),
        ]
    })


def test_bookmark_completion(qtmodeltester, bookmarks):
    """Test the results of bookmark completion."""
    model = miscmodels.BookmarkCompletionModel()
    qtmodeltester.data_display_may_return_none = True
    qtmodeltester.check(model)

    _check_completions(model, {
        "Bookmarks": [
            ('https://github.com', 'GitHub', ''),
            ('https://python.org', 'Welcome to Python.org', ''),
            ('http://qutebrowser.org', 'qutebrowser | qutebrowser', ''),
        ]
    })


def test_url_completion(qtmodeltester, config_stub, web_history, quickmarks,
                        bookmarks):
    """Test the results of url completion.

    Verify that:
        - quickmarks, bookmarks, and urls are included
        - no more than 'web-history-max-items' history entries are included
        - the most recent entries are included
    """
    config_stub.data['completion'] = {'timestamp-format': '%Y-%m-%d',
                                      'web-history-max-items': 2}
    model = urlmodel.UrlCompletionModel()
    qtmodeltester.data_display_may_return_none = True
    qtmodeltester.check(model)

    _check_completions(model, {
        "Quickmarks": [
            ('https://wiki.archlinux.org', 'aw', ''),
            ('https://duckduckgo.com', 'ddg', ''),
            ('https://wikipedia.org', 'wiki', ''),
        ],
        "Bookmarks": [
            ('https://github.com', 'GitHub', ''),
            ('https://python.org', 'Welcome to Python.org', ''),
            ('http://qutebrowser.org', 'qutebrowser | qutebrowser', ''),
        ],
        "History": [
            ('https://python.org', 'Welcome to Python.org', '2016-03-08'),
            ('https://github.com', 'GitHub', '2016-05-01'),
        ],
    })


def test_url_completion_delete_bookmark(qtmodeltester, config_stub,
                                        web_history, quickmarks, bookmarks,
                                        qtbot):
    """Test deleting a bookmark from the url completion model."""
    config_stub.data['completion'] = {'timestamp-format': '%Y-%m-%d',
                                      'web-history-max-items': 2}
    model = urlmodel.UrlCompletionModel()
    qtmodeltester.data_display_may_return_none = True
    qtmodeltester.check(model)

    # delete item (1, 0) -> (bookmarks, 'https://github.com' )
    view = _mock_view_index(model, 1, 0, qtbot)
    model.delete_cur_item(view)
    assert 'https://github.com' not in bookmarks.marks
    assert 'https://python.org' in bookmarks.marks
    assert 'http://qutebrowser.org' in bookmarks.marks


def test_url_completion_delete_quickmark(qtmodeltester, config_stub,
                                         web_history, quickmarks, bookmarks,
                                         qtbot):
    """Test deleting a bookmark from the url completion model."""
    config_stub.data['completion'] = {'timestamp-format': '%Y-%m-%d',
                                      'web-history-max-items': 2}
    model = urlmodel.UrlCompletionModel()
    qtmodeltester.data_display_may_return_none = True
    qtmodeltester.check(model)

    # delete item (0, 1) -> (quickmarks, 'ddg' )
    view = _mock_view_index(model, 0, 1, qtbot)
    model.delete_cur_item(view)
    assert 'aw' in quickmarks.marks
    assert 'ddg' not in quickmarks.marks
    assert 'wiki' in quickmarks.marks


def test_session_completion(qtmodeltester, session_manager_stub):
    session_manager_stub.sessions = ['default', '1', '2']
    model = miscmodels.SessionCompletionModel()
    qtmodeltester.data_display_may_return_none = True
    qtmodeltester.check(model)

    _check_completions(model, {
        "Sessions": [('default', '', ''), ('1', '', ''), ('2', '', '')]
    })


def test_tab_completion(qtmodeltester, fake_web_tab, app_stub, win_registry,
                        tabbed_browser_stubs):
    tabbed_browser_stubs[0].tabs = [
        fake_web_tab(QUrl('https://github.com'), 'GitHub', 0),
        fake_web_tab(QUrl('https://wikipedia.org'), 'Wikipedia', 1),
        fake_web_tab(QUrl('https://duckduckgo.com'), 'DuckDuckGo', 2),
    ]
    tabbed_browser_stubs[1].tabs = [
        fake_web_tab(QUrl('https://wiki.archlinux.org'), 'ArchWiki', 0),
    ]
    model = miscmodels.TabCompletionModel()
    qtmodeltester.data_display_may_return_none = True
    qtmodeltester.check(model)

    _check_completions(model, {
        '0': [
            ('0/1', 'https://github.com', 'GitHub'),
            ('0/2', 'https://wikipedia.org', 'Wikipedia'),
            ('0/3', 'https://duckduckgo.com', 'DuckDuckGo')
        ],
        '1': [
            ('1/1', 'https://wiki.archlinux.org', 'ArchWiki'),
        ]
    })


def test_tab_completion_delete(qtmodeltester, fake_web_tab, qtbot, app_stub,
                               win_registry, tabbed_browser_stubs):
    """Verify closing a tab by deleting it from the completion widget."""
    tabbed_browser_stubs[0].tabs = [
        fake_web_tab(QUrl('https://github.com'), 'GitHub', 0),
        fake_web_tab(QUrl('https://wikipedia.org'), 'Wikipedia', 1),
        fake_web_tab(QUrl('https://duckduckgo.com'), 'DuckDuckGo', 2)
    ]
    tabbed_browser_stubs[1].tabs = [
        fake_web_tab(QUrl('https://wiki.archlinux.org'), 'ArchWiki', 0),
    ]
    model = miscmodels.TabCompletionModel()
    qtmodeltester.data_display_may_return_none = True
    qtmodeltester.check(model)

    view = _mock_view_index(model, 0, 1, qtbot)
    qtbot.add_widget(view)
    model.delete_cur_item(view)
    actual = [tab.url() for tab in tabbed_browser_stubs[0].tabs]
    assert actual == [QUrl('https://github.com'),
                      QUrl('https://duckduckgo.com')]


def test_setting_section_completion(qtmodeltester, monkeypatch, stubs):
    module = 'qutebrowser.completion.models.configmodel'
    _patch_configdata(monkeypatch, stubs, module + '.configdata.DATA')
    _patch_config_section_desc(monkeypatch, stubs,
                               module + '.configdata.SECTION_DESC')
    model = configmodel.SettingSectionCompletionModel()
    qtmodeltester.data_display_may_return_none = True
    qtmodeltester.check(model)

    _check_completions(model, {
        "Sections": [
            ('general', 'General/miscellaneous options.', ''),
            ('ui', 'General options related to the user interface.', ''),
            ('searchengines', 'Definitions of search engines ...', ''),
        ]
    })


def test_setting_option_completion(qtmodeltester, monkeypatch, stubs,
                                   config_stub):
    module = 'qutebrowser.completion.models.configmodel'
    _patch_configdata(monkeypatch, stubs, module + '.configdata.DATA')
    config_stub.data = {'ui': {'gesture': 'off',
                               'mind': 'on',
                               'voice': 'sometimes'}}
    model = configmodel.SettingOptionCompletionModel('ui')
    qtmodeltester.data_display_may_return_none = True
    qtmodeltester.check(model)

    _check_completions(model, {
        "ui": [
            ('gesture', 'Waggle your hands to control qutebrowser', 'off'),
            ('mind', 'Enable mind-control ui (experimental)', 'on'),
            ('voice', 'Whether to respond to voice commands', 'sometimes'),
        ]
    })


def test_setting_option_completion_valuelist(qtmodeltester, monkeypatch, stubs,
                                             config_stub):
    module = 'qutebrowser.completion.models.configmodel'
    _patch_configdata(monkeypatch, stubs, module + '.configdata.DATA')
    config_stub.data = {
        'searchengines': {
            'DEFAULT': 'https://duckduckgo.com/?q={}'
        }
    }
    model = configmodel.SettingOptionCompletionModel('searchengines')
    qtmodeltester.data_display_may_return_none = True
    qtmodeltester.check(model)

    _check_completions(model, {
        'searchengines': [('DEFAULT', '', 'https://duckduckgo.com/?q={}')]
    })


def test_setting_value_completion(qtmodeltester, monkeypatch, stubs,
                                  config_stub):
    module = 'qutebrowser.completion.models.configmodel'
    _patch_configdata(monkeypatch, stubs, module + '.configdata.DATA')
    config_stub.data = {'general': {'volume': '0'}}
    model = configmodel.SettingValueCompletionModel('general', 'volume')
    qtmodeltester.data_display_may_return_none = True
    qtmodeltester.check(model)

    _check_completions(model, {
        "Current/Default": [
            ('0', 'Current value', ''),
            ('11', 'Default value', ''),
        ],
        "Completions": [
            ('0', '', ''),
            ('11', '', ''),
        ]
    })


def test_bind_completion(qtmodeltester, monkeypatch, stubs, config_stub,
                         key_config_stub):
    """Test the results of keybinding command completion.

    Validates that:
        - only non-hidden and non-deprecated commands are included
        - the command description is shown in the desc column
        - the binding (if any) is shown in the misc column
        - aliases are included
    """
    _patch_cmdutils(monkeypatch, stubs,
                    'qutebrowser.completion.models.miscmodels.cmdutils')
    config_stub.data['aliases'] = {'rock': 'roll'}
    key_config_stub.set_bindings_for('normal', {'s': 'stop',
                                                'rr': 'roll',
                                                'ro': 'rock'})
    model = miscmodels.BindCompletionModel()
    qtmodeltester.data_display_may_return_none = True
    qtmodeltester.check(model)

    _check_completions(model, {
        "Commands": [
            ('stop', 'stop qutebrowser', 's'),
            ('drop', 'drop all user data', ''),
            ('hide', '', ''),
            ('roll', 'never gonna give you up', 'rr'),
            ('rock', "Alias for 'roll'", 'ro'),
        ]
    })


def test_url_completion_benchmark(benchmark, config_stub,
                                  quickmark_manager_stub,
                                  bookmark_manager_stub,
                                  web_history_stub):
    """Benchmark url completion."""
    config_stub.data['completion'] = {'timestamp-format': '%Y-%m-%d',
                                      'web-history-max-items': 1000}

    entries = [history.Entry(
        atime=i,
        url=QUrl('http://example.com/{}'.format(i)),
        title='title{}'.format(i))
        for i in range(100000)]

    web_history_stub.history_dict = collections.OrderedDict(
        ((e.url_str(), e) for e in entries))

    quickmark_manager_stub.marks = collections.OrderedDict(
        (e.title, e.url_str())
        for e in entries[0:1000])

    bookmark_manager_stub.marks = collections.OrderedDict(
        (e.url_str(), e.title)
        for e in entries[0:1000])

    def bench():
        model = urlmodel.UrlCompletionModel()
        filtermodel = sortfilter.CompletionFilterModel(model)
        filtermodel.set_pattern('')
        filtermodel.set_pattern('e')
        filtermodel.set_pattern('ex')
        filtermodel.set_pattern('ex ')
        filtermodel.set_pattern('ex 1')
        filtermodel.set_pattern('ex 12')
        filtermodel.set_pattern('ex 123')

    benchmark(bench)