summaryrefslogtreecommitdiff
path: root/tests/unit/config/test_configcommands.py
blob: 6dd09cee386e61f09a7f9ff15d6041a96c3cf214 (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
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
# vim: ft=python fileencoding=utf-8 sts=4 sw=4 et:
# Copyright 2014-2021 Florian Bruhin (The Compiler) <mail@qutebrowser.org>

# 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 <https://www.gnu.org/licenses/>.

"""Tests for qutebrowser.config.configcommands."""

import logging
import functools
import unittest.mock

import pytest
from PyQt5.QtCore import QUrl

from qutebrowser.config import configcommands
from qutebrowser.api import cmdutils
from qutebrowser.utils import usertypes, urlmatch, utils
from qutebrowser.keyinput import keyutils
from qutebrowser.misc import objects


# Alias because we need this a lot in here.
def keyseq(s):
    return keyutils.KeySequence.parse(s)


@pytest.fixture
def commands(config_stub, key_config_stub):
    return configcommands.ConfigCommands(config_stub, key_config_stub)


@pytest.fixture
def yaml_value(config_stub):
    """Fixture which provides a getter for a YAML value."""
    def getter(option):
        return config_stub._yaml._values[option].get_for_url(fallback=False)
    return getter


class TestSet:

    """Tests for :set."""

    def test_set_no_args(self, commands, tabbed_browser_stubs):
        """Run ':set'.

        Should open qute://settings."""
        commands.set(win_id=0)
        assert tabbed_browser_stubs[0].loaded_url == QUrl('qute://settings')

    @pytest.mark.parametrize('option', ['url.auto_search?', 'url.auto_search'])
    def test_get(self, config_stub, commands, message_mock, option):
        """Run ':set url.auto_search?' / ':set url.auto_search'.

        Should show the value.
        """
        config_stub.val.url.auto_search = 'never'
        commands.set(win_id=0, option=option)
        msg = message_mock.getmsg(usertypes.MessageLevel.info)
        assert msg.text == 'url.auto_search = never'

    @pytest.mark.parametrize('temp', [True, False])
    @pytest.mark.parametrize('option, old_value, inp, new_value', [
        ('url.auto_search', 'naive', 'dns', 'dns'),
        # https://github.com/qutebrowser/qutebrowser/issues/2962
        ('editor.command',
         ['gvim', '-f', '{file}', '-c', 'normal {line}G{column0}l'],
         '[emacs, "{}"]', ['emacs', '{}']),
    ])
    def test_set_simple(self, monkeypatch, commands, config_stub, yaml_value,
                        temp, option, old_value, inp, new_value):
        """Run ':set [-t] option value'.

        Should set the setting accordingly.
        """
        monkeypatch.setattr(objects, 'backend', usertypes.Backend.QtWebKit)
        assert config_stub.get(option) == old_value

        commands.set(0, option, inp, temp=temp)

        assert config_stub.get(option) == new_value
        assert yaml_value(option) == (usertypes.UNSET if temp else new_value)

    def test_set_with_pattern(self, monkeypatch, commands, config_stub):
        monkeypatch.setattr(objects, 'backend', usertypes.Backend.QtWebKit)
        option = 'content.javascript.enabled'

        commands.set(0, option, 'false', pattern='*://example.com')
        pattern = urlmatch.UrlPattern('*://example.com')

        assert config_stub.get(option)
        assert not config_stub.get_obj_for_pattern(option, pattern=pattern)

    def test_set_invalid_pattern(self, monkeypatch, commands):
        monkeypatch.setattr(objects, 'backend', usertypes.Backend.QtWebKit)
        option = 'content.javascript.enabled'

        with pytest.raises(cmdutils.CommandError,
                           match=('Error while parsing http://: Pattern '
                                  'without host')):
            commands.set(0, option, 'false', pattern='http://')

    def test_set_no_pattern(self, monkeypatch, commands):
        """Run ':set --pattern=*://* colors.statusbar.normal.bg #abcdef.

        Should show an error as patterns are unsupported.
        """
        with pytest.raises(cmdutils.CommandError,
                           match='does not support URL patterns'):
            commands.set(0, 'colors.statusbar.normal.bg', '#abcdef',
                         pattern='*://*')

    @pytest.mark.parametrize('temp', [True, False])
    def test_set_temp_override(self, commands, config_stub, yaml_value, temp):
        """Invoking :set twice.

        :set url.auto_search dns
        :set -t url.auto_search never

        Should set the setting accordingly.
        """
        assert config_stub.val.url.auto_search == 'naive'
        commands.set(0, 'url.auto_search', 'dns')
        commands.set(0, 'url.auto_search', 'never', temp=True)

        assert config_stub.val.url.auto_search == 'never'
        assert yaml_value('url.auto_search') == 'dns'

    @pytest.mark.parametrize('pattern', [None, '*://example.com'])
    def test_set_print(self, config_stub, commands, message_mock, pattern):
        """Run ':set -p [-u *://example.com] content.javascript.enabled false'.

        Should set show the value.
        """
        assert config_stub.val.content.javascript.enabled
        commands.set(0, 'content.javascript.enabled', 'false', print_=True,
                     pattern=pattern)

        value = config_stub.get_obj_for_pattern(
            'content.javascript.enabled',
            pattern=None if pattern is None else urlmatch.UrlPattern(pattern))
        assert not value

        expected = 'content.javascript.enabled = false'
        if pattern is not None:
            expected += ' for {}'.format(pattern)
        msg = message_mock.getmsg(usertypes.MessageLevel.info)
        assert msg.text == expected

    def test_set_invalid_option(self, commands):
        """Run ':set foo bar'.

        Should show an error.
        """
        with pytest.raises(cmdutils.CommandError, match="No option 'foo'"):
            commands.set(0, 'foo', 'bar')

    def test_set_invalid_value(self, commands):
        """Run ':set auto_save.session blah'.

        Should show an error.
        """
        with pytest.raises(cmdutils.CommandError,
                           match="Invalid value 'blah' - must be a boolean!"):
            commands.set(0, 'auto_save.session', 'blah')

    def test_set_wrong_backend(self, commands, monkeypatch):
        monkeypatch.setattr(objects, 'backend', usertypes.Backend.QtWebEngine)
        with pytest.raises(cmdutils.CommandError,
                           match="The hints.find_implementation setting is "
                           "not available with the QtWebEngine backend!"):
            commands.set(0, 'hints.find_implementation', 'javascript')

    def test_empty(self, commands):
        """Run ':set ?'.

        Should show an error.
        See https://github.com/qutebrowser/qutebrowser/issues/1109
        """
        with pytest.raises(cmdutils.CommandError, match="No option '?'"):
            commands.set(win_id=0, option='?')

    def test_toggle(self, commands):
        """Try toggling a value.

        Should show an nicer error.
        """
        with pytest.raises(cmdutils.CommandError,
                           match="Toggling values was moved to the "
                                 ":config-cycle command"):
            commands.set(win_id=0, option='javascript.enabled!')

    def test_invalid(self, commands):
        """Run ':set foo?'.

        Should show an error.
        """
        with pytest.raises(cmdutils.CommandError, match="No option 'foo'"):
            commands.set(win_id=0, option='foo?')


def test_diff(commands, tabbed_browser_stubs):
    """Run ':config-diff'.

    Should open qute://configdiff."""
    commands.config_diff(win_id=0)
    assert tabbed_browser_stubs[0].loaded_url == QUrl('qute://configdiff')


class TestCycle:

    """Test :config-cycle."""

    @pytest.mark.parametrize('initial, expected', [
        # Normal cycling
        ('magenta', 'blue'),
        # Through the end of the list
        ('yellow', 'green'),
        # Value which is not in the list
        ('red', 'green'),
    ])
    def test_cycling(self, commands, config_stub, yaml_value,
                     initial, expected):
        """Run ':set' with multiple values."""
        opt = 'colors.statusbar.normal.bg'
        config_stub.set_obj(opt, initial)
        commands.config_cycle(opt, 'green', 'magenta', 'blue', 'yellow')
        assert config_stub.get(opt) == expected
        assert yaml_value(opt) == expected

    def test_different_representation(self, commands, config_stub):
        """When using a different representation, cycling should work.

        For example, we use [foo] which is represented as ["foo"].
        """
        opt = 'qt.args'
        config_stub.set_obj(opt, ['foo'])
        commands.config_cycle(opt, '[foo]', '[bar]')
        assert config_stub.get(opt) == ['bar']
        commands.config_cycle(opt, '[foo]', '[bar]')
        assert config_stub.get(opt) == ['foo']

    def test_toggle(self, commands, config_stub, yaml_value):
        """Run ':config-cycle auto_save.session'.

        Should toggle the value.
        """
        assert not config_stub.val.auto_save.session
        commands.config_cycle('auto_save.session')
        assert config_stub.val.auto_save.session
        assert yaml_value('auto_save.session')

    @pytest.mark.parametrize('args', [
        ['url.auto_search'], ['url.auto_search', 'foo']
    ])
    def test_toggle_nonbool(self, commands, config_stub, args):
        """Run :config-cycle without a bool and 0/1 value.

        :config-cycle url.auto_search
        :config-cycle url.auto_search foo

        Should show an error.
        """
        assert config_stub.val.url.auto_search == 'naive'
        with pytest.raises(cmdutils.CommandError, match="Need at least "
                           "two values for non-boolean settings."):
            commands.config_cycle(*args)
        assert config_stub.val.url.auto_search == 'naive'

    def test_set_toggle_print(self, commands, config_stub, message_mock):
        """Run ':config-cycle -p auto_save.session'.

        Should toggle the value and show the new value.
        """
        commands.config_cycle('auto_save.session', print_=True)
        msg = message_mock.getmsg(usertypes.MessageLevel.info)
        assert msg.text == 'auto_save.session = true'


class TestAdd:

    """Test :config-list-add and :config-dict-add."""

    @pytest.mark.parametrize('temp', [True, False])
    @pytest.mark.parametrize('value', ['test1', 'test2'])
    def test_list_add(self, commands, config_stub, yaml_value, temp, value):
        name = 'content.blocking.whitelist'

        commands.config_list_add(name, value, temp=temp)

        assert str(config_stub.get(name)[-1]) == value
        if temp:
            assert yaml_value(name) == usertypes.UNSET
        else:
            assert yaml_value(name)[-1] == value

    def test_list_add_invalid_option(self, commands):
        with pytest.raises(
                cmdutils.CommandError,
                match="No option 'nonexistent'"):
            commands.config_list_add('nonexistent', 'value')

    def test_list_add_non_list(self, commands):
        with pytest.raises(
                cmdutils.CommandError,
                match=":config-list-add can only be used for lists"):
            commands.config_list_add('history_gap_interval', 'value')

    @pytest.mark.parametrize('value', ['', None, 42])
    def test_list_add_invalid_values(self, commands, value):
        with pytest.raises(
                cmdutils.CommandError,
                match="Invalid value '{}'".format(value)):
            commands.config_list_add('content.blocking.whitelist', value)

    @pytest.mark.parametrize('value', ['test1', 'test2'])
    @pytest.mark.parametrize('temp', [True, False])
    def test_dict_add(self, commands, config_stub, yaml_value, value, temp):
        name = 'aliases'
        key = 'missingkey'

        commands.config_dict_add(name, key, value, temp=temp)

        assert str(config_stub.get(name)[key]) == value
        if temp:
            assert yaml_value(name) == usertypes.UNSET
        else:
            assert yaml_value(name)[key] == value

    @pytest.mark.parametrize('replace', [True, False])
    def test_dict_add_replace(self, commands, config_stub, replace):
        name = 'aliases'
        key = 'w'
        value = 'anything'

        if replace:
            commands.config_dict_add(name, key, value, replace=True)
            assert str(config_stub.get(name)[key]) == value
        else:
            with pytest.raises(
                    cmdutils.CommandError,
                    match="w already exists in aliases - use --replace to "
                          "overwrite!"):
                commands.config_dict_add(name, key, value, replace=False)

    def test_dict_add_invalid_option(self, commands):
        with pytest.raises(
                cmdutils.CommandError,
                match="No option 'nonexistent'"):
            commands.config_dict_add('nonexistent', 'key', 'value')

    def test_dict_add_non_dict(self, commands):
        with pytest.raises(
                cmdutils.CommandError,
                match=":config-dict-add can only be used for dicts"):
            commands.config_dict_add('history_gap_interval', 'key', 'value')

    @pytest.mark.parametrize('value', ['', None, 42])
    def test_dict_add_invalid_values(self, commands, value):
        with pytest.raises(cmdutils.CommandError,
                           match="Invalid value '{}'".format(value)):
            commands.config_dict_add('aliases', 'missingkey', value)


class TestRemove:

    """Test :config-list-remove and :config-dict-remove."""

    @pytest.mark.parametrize('value', ['25%', '50%'])
    @pytest.mark.parametrize('temp', [True, False])
    def test_list_remove(self, commands, config_stub, yaml_value, value, temp):
        name = 'zoom.levels'
        commands.config_list_remove(name, value, temp=temp)

        assert value not in config_stub.get(name)
        if temp:
            assert yaml_value(name) == usertypes.UNSET
        else:
            assert value not in yaml_value(name)

    def test_list_remove_invalid_option(self, commands):
        with pytest.raises(
                cmdutils.CommandError,
                match="No option 'nonexistent'"):
            commands.config_list_remove('nonexistent', 'value')

    def test_list_remove_non_list(self, commands):
        with pytest.raises(
                cmdutils.CommandError,
                match=":config-list-remove can only be used for lists"):
            commands.config_list_remove('content.javascript.enabled',
                                        'never')

    def test_list_remove_no_value(self, commands):
        with pytest.raises(
                cmdutils.CommandError,
                match="never is not in colors.completion.fg!"):
            commands.config_list_remove('colors.completion.fg', 'never')

    @pytest.mark.parametrize('key', ['w', 'q'])
    @pytest.mark.parametrize('temp', [True, False])
    def test_dict_remove(self, commands, config_stub, yaml_value, key, temp):
        name = 'aliases'
        commands.config_dict_remove(name, key, temp=temp)

        assert key not in config_stub.get(name)
        if temp:
            assert yaml_value(name) == usertypes.UNSET
        else:
            assert key not in yaml_value(name)

    def test_dict_remove_invalid_option(self, commands):
        with pytest.raises(
                cmdutils.CommandError,
                match="No option 'nonexistent'"):
            commands.config_dict_remove('nonexistent', 'key')

    def test_dict_remove_non_dict(self, commands):
        with pytest.raises(
                cmdutils.CommandError,
                match=":config-dict-remove can only be used for dicts"):
            commands.config_dict_remove('content.javascript.enabled',
                                        'never')

    def test_dict_remove_no_value(self, commands):
        with pytest.raises(
                cmdutils.CommandError,
                match="never is not in aliases!"):
            commands.config_dict_remove('aliases', 'never')


class TestUnsetAndClear:

    """Test :config-unset and :config-clear."""

    @pytest.mark.parametrize('temp', [True, False])
    def test_unset(self, commands, config_stub, yaml_value, temp):
        name = 'tabs.show'
        config_stub.set_obj(name, 'never', save_yaml=True)

        commands.config_unset(name, temp=temp)

        assert config_stub.get(name) == 'always'
        assert yaml_value(name) == ('never' if temp else usertypes.UNSET)

    def test_unset_unknown_option(self, commands):
        with pytest.raises(cmdutils.CommandError, match="No option 'tabs'"):
            commands.config_unset('tabs')

    def test_unset_uncustomized(self, commands):
        with pytest.raises(cmdutils.CommandError, match="tabs.show is not customized"):
            commands.config_unset('tabs.show')

    @pytest.mark.parametrize('set_global', [True, False])
    def test_unset_pattern(self, commands, config_stub, set_global):
        name = 'content.javascript.enabled'
        pattern = urlmatch.UrlPattern('*://example.com')
        url = QUrl('https://example.com')

        if set_global:
            config_stub.set_obj(name, False)
            global_value = False
            local_value = True
        else:
            global_value = True
            local_value = False

        config_stub.set_obj(name, local_value, pattern=pattern)
        commands.config_unset(name, pattern=str(pattern))
        assert config_stub.get_obj(name, url=url) == global_value
        assert config_stub.get_obj(name, url=url, fallback=False) == usertypes.UNSET

    def test_unset_uncustomized_pattern(self, commands, config_stub):
        name = 'content.javascript.enabled'
        pattern = 'example.com'

        config_stub.set_obj(name, False)
        with pytest.raises(
            cmdutils.CommandError,
            match=f"{name} is not customized for {pattern}",
        ):
            commands.config_unset(name, pattern=pattern)

    @pytest.mark.parametrize('save', [True, False])
    def test_clear(self, commands, config_stub, yaml_value, save):
        name = 'tabs.show'
        config_stub.set_obj(name, 'never', save_yaml=True)

        commands.config_clear(save=save)

        assert config_stub.get(name) == 'always'
        assert yaml_value(name) == (usertypes.UNSET if save else 'never')


class TestSource:

    """Test :config-source."""

    pytestmark = pytest.mark.usefixtures('config_tmpdir', 'data_tmpdir',
                                         'config_stub', 'key_config_stub')

    @pytest.mark.parametrize('location', ['default', 'absolute', 'relative'])
    @pytest.mark.parametrize('clear', [True, False])
    def test_config_source(self, tmp_path, commands, config_stub, config_tmpdir,
                           location, clear):
        assert config_stub.val.content.javascript.enabled
        config_stub.val.search.ignore_case = 'always'

        if location == 'default':
            pyfile = config_tmpdir / 'config.py'
            arg = None
        elif location == 'absolute':
            pyfile = tmp_path / 'sourced.py'
            arg = str(pyfile)
        elif location == 'relative':
            pyfile = config_tmpdir / 'sourced.py'
            arg = 'sourced.py'
        else:
            raise utils.Unreachable(location)

        pyfile.write_text('\n'.join(['config.load_autoconfig(False)',
                                     'c.content.javascript.enabled = False']),
                          encoding='utf-8')

        commands.config_source(arg, clear=clear)

        assert not config_stub.val.content.javascript.enabled
        ignore_case = config_stub.val.search.ignore_case
        assert ignore_case == (usertypes.IgnoreCase.smart if clear
                               else usertypes.IgnoreCase.always)

    def test_config_py_arg_source(self, commands, config_py_arg, config_stub):
        assert config_stub.val.content.javascript.enabled
        config_py_arg.write_text('\n'.join(['config.load_autoconfig(False)',
                                            'c.content.javascript.enabled = False']),
                                 encoding='utf-8')
        commands.config_source()
        assert not config_stub.val.content.javascript.enabled

    def test_errors(self, commands, config_tmpdir):
        pyfile = config_tmpdir / 'config.py'
        pyfile.write_text('\n'.join(['config.load_autoconfig(False)',
                                     'c.foo = 42']), encoding='utf-8')

        with pytest.raises(cmdutils.CommandError) as excinfo:
            commands.config_source()

        expected = ("Errors occurred while reading config.py:\n"
                    "  While setting 'foo': No option 'foo'")
        assert str(excinfo.value) == expected

    def test_invalid_source(self, commands, config_tmpdir):
        pyfile = config_tmpdir / 'config.py'
        pyfile.write_text('\n'.join(['config.load_autoconfig(False)',
                                     '1/0']), encoding='utf-8')

        with pytest.raises(cmdutils.CommandError) as excinfo:
            commands.config_source()

        expected = ("Errors occurred while reading config.py:\n"
                    "  Unhandled exception - ZeroDivisionError:"
                    " division by zero")
        assert str(excinfo.value) == expected


class TestEdit:

    """Tests for :config-edit."""

    pytestmark = pytest.mark.usefixtures('config_tmpdir', 'data_tmpdir',
                                         'config_stub', 'key_config_stub',
                                         'qapp')

    def test_no_source(self, commands, mocker):
        mock = mocker.patch('qutebrowser.config.configcommands.editor.'
                            'ExternalEditor._start_editor', autospec=True)
        commands.config_edit(no_source=True)
        mock.assert_called_once_with(unittest.mock.ANY)

    @pytest.fixture
    def patch_editor(self, mocker):
        """Write a config.py file."""
        def do_patch(text):
            def _write_file(editor_self):
                with open(editor_self._filename, 'w', encoding='utf-8') as f:
                    f.write(text)
                editor_self.file_updated.emit(text)

            return mocker.patch('qutebrowser.config.configcommands.editor.'
                                'ExternalEditor._start_editor', autospec=True,
                                side_effect=_write_file)

        return do_patch

    def test_with_sourcing(self, commands, config_stub, patch_editor):
        assert config_stub.val.content.javascript.enabled
        mock = patch_editor('\n'.join(['config.load_autoconfig(False)',
                                       'c.content.javascript.enabled = False']))

        commands.config_edit()

        mock.assert_called_once_with(unittest.mock.ANY)
        assert not config_stub.val.content.javascript.enabled

    def test_config_py_with_sourcing(self, commands, config_stub, patch_editor, config_py_arg):
        assert config_stub.val.content.javascript.enabled
        conf = ['config.load_autoconfig(False)', 'c.content.javascript.enabled = False']
        mock = patch_editor("\n".join(conf))
        commands.config_edit()
        mock.assert_called_once_with(unittest.mock.ANY)
        assert not config_stub.val.content.javascript.enabled
        assert config_py_arg.read_text('utf-8').splitlines() == conf

    def test_error(self, commands, config_stub, patch_editor, message_mock,
                   caplog):
        patch_editor('\n'.join(['config.load_autoconfig(False)', 'c.foo = 42']))

        with caplog.at_level(logging.ERROR):
            commands.config_edit()

        msg = message_mock.getmsg()
        expected = ("Errors occurred while reading config.py:\n"
                    "  While setting 'foo': No option 'foo'")
        assert msg.text == expected


class TestWritePy:

    """Tests for :config-write-py."""

    def test_custom(self, commands, config_stub, key_config_stub, tmp_path):
        confpy = tmp_path / 'config.py'
        config_stub.val.content.javascript.enabled = True
        key_config_stub.bind(keyseq(',x'), 'message-info foo', mode='normal')

        commands.config_write_py(str(confpy))

        lines = confpy.read_text('utf-8').splitlines()
        assert "c.content.javascript.enabled = True" in lines
        assert "config.bind(',x', 'message-info foo')" in lines

    def test_defaults(self, commands, tmp_path):
        confpy = tmp_path / 'config.py'
        commands.config_write_py(str(confpy), defaults=True)

        lines = confpy.read_text('utf-8').splitlines()
        assert "# c.content.javascript.enabled = True" in lines
        assert "# config.bind('H', 'back')" in lines

    def test_default_location(self, commands, config_tmpdir):
        confpy = config_tmpdir / 'config.py'
        commands.config_write_py()
        lines = confpy.read_text('utf-8').splitlines()
        assert '# Autogenerated config.py' in lines

    def test_relative_path(self, commands, config_tmpdir):
        confpy = config_tmpdir / 'config2.py'
        commands.config_write_py('config2.py')
        lines = confpy.read_text('utf-8').splitlines()
        assert '# Autogenerated config.py' in lines

    @pytest.mark.posix
    def test_expanduser(self, commands, monkeypatch, tmp_path):
        """Make sure that using a path with ~/... works correctly."""
        home = tmp_path / 'home'
        home.mkdir()
        monkeypatch.setenv('HOME', str(home))

        commands.config_write_py('~/config.py')

        confpy = home / 'config.py'
        lines = confpy.read_text('utf-8').splitlines()
        assert '# Autogenerated config.py' in lines

    def test_existing_file(self, commands, tmp_path):
        confpy = tmp_path / 'config.py'
        confpy.touch()

        with pytest.raises(cmdutils.CommandError) as excinfo:
            commands.config_write_py(str(confpy))

        expected = " already exists - use --force to overwrite!"
        assert str(excinfo.value).endswith(expected)

    def test_existing_file_force(self, commands, tmp_path):
        confpy = tmp_path / 'config.py'
        confpy.touch()

        commands.config_write_py(str(confpy), force=True)

        lines = confpy.read_text('utf-8').splitlines()
        assert '# Autogenerated config.py' in lines

    def test_oserror(self, commands, tmp_path):
        """Test writing to a directory which does not exist."""
        with pytest.raises(cmdutils.CommandError):
            commands.config_write_py(str(tmp_path / 'foo' / 'config.py'))

    def test_config_py_arg(self, commands, config_py_arg):
        config_py_arg.ensure()
        commands.config_write_py(str(config_py_arg), force=True)
        lines = config_py_arg.read_text('utf-8').splitlines()
        assert '# Autogenerated config.py' in lines


class TestBind:

    """Tests for :bind and :unbind."""

    @pytest.fixture
    def no_bindings(self):
        """Get a dict with no bindings."""
        return {'normal': {}}

    @pytest.mark.parametrize("mode, url", [
        ("normal", QUrl("qute://bindings")),
        ("passthrough", QUrl("qute://bindings#passthrough")),
    ])
    def test_bind_no_args(self, commands, config_stub, no_bindings,
                          tabbed_browser_stubs, mode, url):
        """Run ':bind'.

        Should open qute://bindings."""
        config_stub.val.bindings.default = no_bindings
        config_stub.val.bindings.commands = no_bindings
        commands.bind(win_id=0, mode=mode)
        assert tabbed_browser_stubs[0].loaded_url == url

    @pytest.mark.parametrize('command', ['nop', 'nope'])
    def test_bind(self, commands, config_stub, no_bindings, key_config_stub,
                  yaml_value, command):
        """Simple :bind test (and aliases)."""
        config_stub.val.aliases = {'nope': 'nop'}
        config_stub.val.bindings.default = no_bindings
        config_stub.val.bindings.commands = no_bindings

        commands.bind(0, 'a', command)
        assert key_config_stub.get_command(keyseq('a'), 'normal') == command
        yaml_bindings = yaml_value('bindings.commands')['normal']
        assert yaml_bindings['a'] == command

    @pytest.mark.parametrize('key, mode, expected', [
        # Simple
        ('a', 'normal', "a is bound to 'message-info a' in normal mode"),
        # Alias
        ('b', 'normal', "b is bound to 'mib' in normal mode"),
        # Custom binding
        ('c', 'normal', "c is bound to 'message-info c' in normal mode"),
        # Special key
        ('<Ctrl-X>', 'normal',
         "<Ctrl+x> is bound to 'message-info C-x' in normal mode"),
        # unbound
        ('x', 'normal', "x is unbound in normal mode"),
        # non-default mode
        ('x', 'caret', "x is bound to 'nop' in caret mode"),
    ])
    def test_bind_print(self, commands, config_stub, message_mock,
                        key, mode, expected):
        """Run ':bind key'.

        Should print the binding.
        """
        config_stub.val.aliases = {'mib': 'message-info b'}
        config_stub.val.bindings.default = {
            'normal': {'a': 'message-info a',
                       'b': 'mib',
                       '<Ctrl+x>': 'message-info C-x'},
            'caret': {'x': 'nop'}
        }
        config_stub.val.bindings.commands = {
            'normal': {'c': 'message-info c'}
        }

        commands.bind(0, key, mode=mode)

        msg = message_mock.getmsg(usertypes.MessageLevel.info)
        assert msg.text == expected

    @pytest.mark.parametrize('command, args, kwargs, expected', [
        # :bind --mode=wrongmode a nop
        ('bind', ['a', 'nop'], {'mode': 'wrongmode'},
         'Invalid mode wrongmode!'),
        # :bind --mode=wrongmode a
        ('bind', ['a'], {'mode': 'wrongmode'},
         'Invalid mode wrongmode!'),
        # :bind --default --mode=wrongmode a
        ('bind', ['a'], {'mode': 'wrongmode', 'default': True},
         'Invalid mode wrongmode!'),
        # :bind --default foobar
        ('bind', ['foobar'], {'default': True},
         "Can't find binding 'foobar' in normal mode"),
        # :bind <blub> nop
        ('bind', ['<blub>', 'nop'], {},
         "Could not parse '<blub>': Got invalid key!"),
        # :unbind foobar
        ('unbind', ['foobar'], {},
         "Can't find binding 'foobar' in normal mode"),
        # :unbind --mode=wrongmode x
        ('unbind', ['x'], {'mode': 'wrongmode'},
         'Invalid mode wrongmode!'),
        # :unbind <blub>
        ('unbind', ['<blub>'], {},
         "Could not parse '<blub>': Got invalid key!"),
    ])
    def test_bind_invalid(self, commands,
                          command, args, kwargs, expected):
        """Run various wrong :bind/:unbind invocations.

        Should show an error.
        """
        if command == 'bind':
            func = functools.partial(commands.bind, 0)
        elif command == 'unbind':
            func = commands.unbind

        with pytest.raises(cmdutils.CommandError, match=expected):
            func(*args, **kwargs)

    @pytest.mark.parametrize('key', ['a', 'b', '<Ctrl-X>'])
    def test_bind_duplicate(self, commands, config_stub, key_config_stub, key):
        """Run ':bind' with a key which already has been bound.'.

        Also tests for https://github.com/qutebrowser/qutebrowser/issues/1544
        """
        config_stub.val.bindings.default = {
            'normal': {'a': 'nop', '<Ctrl+x>': 'nop'}
        }
        config_stub.val.bindings.commands = {
            'normal': {'b': 'nop'},
        }

        commands.bind(0, key, 'message-info foo', mode='normal')
        command = key_config_stub.get_command(keyseq(key), 'normal')
        assert command == 'message-info foo'

    def test_bind_none(self, commands, config_stub):
        config_stub.val.bindings.commands = None
        commands.bind(0, ',x', 'nop')

    def test_bind_default(self, commands, key_config_stub, config_stub):
        """Bind a key to its default."""
        default_cmd = 'message-info default'
        bound_cmd = 'message-info bound'
        config_stub.val.bindings.default = {'normal': {'a': default_cmd}}
        config_stub.val.bindings.commands = {'normal': {'a': bound_cmd}}
        command = key_config_stub.get_command(keyseq('a'), mode='normal')
        assert command == bound_cmd

        commands.bind(0, 'a', mode='normal', default=True)

        command = key_config_stub.get_command(keyseq('a'), mode='normal')
        assert command == default_cmd

    def test_unbind_none(self, commands, config_stub):
        config_stub.val.bindings.commands = None
        commands.unbind('H')

    @pytest.mark.parametrize('key, normalized', [
        ('a', 'a'),  # default bindings
        ('b', 'b'),  # custom bindings
        ('c', 'c'),  # :bind then :unbind
        ('<Ctrl-X>', '<Ctrl+x>')  # normalized special binding
    ])
    def test_unbind(self, commands, key_config_stub, config_stub, yaml_value,
                    key, normalized):
        config_stub.val.bindings.default = {
            'normal': {'a': 'nop', '<ctrl+x>': 'nop'},
            'caret': {'a': 'nop', '<ctrl+x>': 'nop'},
        }
        config_stub.val.bindings.commands = {
            'normal': {'b': 'nop'},
            'caret': {'b': 'nop'},
        }
        if key == 'c':
            # Test :bind and :unbind
            commands.bind(0, key, 'nop')

        commands.unbind(key)
        assert key_config_stub.get_command(keyseq(key), 'normal') is None

        yaml_bindings = yaml_value('bindings.commands')['normal']
        if key in 'bc':
            # Custom binding
            assert normalized not in yaml_bindings
        else:
            assert yaml_bindings[normalized] is None