示例#1
0
def test_get_equivalent_patterns(empty_values):
    """With multiple matching pattern, the last added should win."""
    pat1 = urlmatch.UrlPattern('https://www.example.com/')
    pat2 = urlmatch.UrlPattern('*://www.example.com/')
    empty_values.add('pat1 value', pat1)
    empty_values.add('pat2 value', pat2)

    assert empty_values.get_for_pattern(pat1) == 'pat1 value'
    assert empty_values.get_for_pattern(pat2) == 'pat2 value'
def test_ignore_missing_slashes():
    pattern1 = urlmatch.UrlPattern("http://www.example.com/example")
    pattern2 = urlmatch.UrlPattern("http://www.example.com/example/*")
    url1 = QUrl('http://www.example.com/example')
    url2 = QUrl('http://www.example.com/example/')

    # Same patterns should match same URLs.
    assert pattern1.matches(url1)
    assert pattern2.matches(url1)
    # The not terminated path should match the terminated pattern.
    assert pattern2.matches(url1)
    # The terminated path however should not match the unterminated pattern.
    assert not pattern1.matches(url2)
 def test_attrs(self, pattern, host, match_subdomains):
     up = urlmatch.UrlPattern(pattern)
     assert up._scheme == 'http'
     assert up._host == host
     assert up._match_subdomains == match_subdomains
     assert not up._match_all
     assert up._path is None
示例#4
0
    def accept(self, value=None, save=False):
        self._check_save_support(save)

        if value is None:
            if self.question.default is None:
                raise Error("No default value was set for this question!")
            self.question.answer = self.question.default
        elif value == 'yes':
            self.question.answer = True
        elif value == 'no':
            self.question.answer = False
        else:
            raise Error("Invalid value {} - expected yes/no!".format(value))

        if save:
            opt = config.instance.get_opt(self.question.option)
            assert isinstance(opt.typ, configtypes.Bool)
            pattern = urlmatch.UrlPattern(self.question.url)

            try:
                config.instance.set_obj(opt.name,
                                        self.question.answer,
                                        pattern=pattern,
                                        save_yaml=True)
            except configexc.Error as e:
                raise Error(str(e))

        return True
示例#5
0
 def pattern(self, pattern: str) -> typing.Iterator[config.ConfigContainer]:
     """Get a ConfigContainer for the given pattern."""
     # We need to propagate the exception so we don't need to return
     # something.
     urlpattern = urlmatch.UrlPattern(pattern)
     container = config.ConfigContainer(config=self._config,
                                        configapi=self,
                                        pattern=urlpattern)
     yield container
    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_lightweight_patterns(pattern, scheme, host, path):
    """Make sure we can leave off parts of a URL.

    This is a deviation from Chromium to make patterns more user-friendly.
    """
    up = urlmatch.UrlPattern(pattern)
    assert up._scheme == scheme
    assert up._host == host
    assert up._path == path
示例#8
0
    def test_set_with_pattern(self, confpy, template):
        option = 'content.javascript.enabled'
        pattern = 'https://www.example.com/'

        confpy.write(template.format(opt=option, pattern=pattern))
        confpy.read()

        assert config.instance.get_obj(option)
        assert not config.instance.get_obj_for_pattern(
            option, pattern=urlmatch.UrlPattern(pattern))
示例#9
0
 def matches(self, script):
     """Check whether the URL matches filtering rules of the script."""
     assert self.is_greaseable
     matching_includes = any(
         self._match_pattern(pat) for pat in script.includes)
     matching_match = any(
         urlmatch.UrlPattern(pat).matches(self._url)
         for pat in script.matches)
     matching_excludes = any(
         self._match_pattern(pat) for pat in script.excludes)
     return (matching_includes or matching_match) and not matching_excludes
示例#10
0
    def _parse_pattern(
            self, pattern: typing.Optional[str]
    ) -> typing.Optional[urlmatch.UrlPattern]:
        """Parse a pattern string argument to a pattern."""
        if pattern is None:
            return None

        try:
            return urlmatch.UrlPattern(pattern)
        except urlmatch.ParseError as e:
            raise cmdutils.CommandError("Error while parsing {}: {}".format(
                pattern, str(e)))
示例#11
0
 def test_get_with_pattern(self, confpy):
     """Test whether we get a matching value with a pattern."""
     option = 'content.javascript.enabled'
     pattern = 'https://www.example.com/'
     config.instance.set_obj(option,
                             False,
                             pattern=urlmatch.UrlPattern(pattern))
     confpy.write(
         'assert config.get({!r})'.format(option),
         'assert not config.get({!r}, pattern={!r})'.format(
             option, pattern))
     confpy.read()
示例#12
0
def init(args: argparse.Namespace) -> None:
    """Initialize all QWeb(Engine)Settings."""
    if objects.backend == usertypes.Backend.QtWebEngine:
        from glimpsebrowser.browser.webengine import webenginesettings
        webenginesettings.init(args)
    else:
        from glimpsebrowser.browser.webkit import webkitsettings
        webkitsettings.init(args)

    # Make sure special URLs always get JS support
    for pattern in ['file://*', 'chrome://*/*', 'glimpse://*/*']:
        config.instance.set_obj('content.javascript.enabled', True,
                                pattern=urlmatch.UrlPattern(pattern))
示例#13
0
 def test_pattern(self):
     opt = configdata.Option(name='opt',
                             typ=configtypes.BoolAsk(),
                             default='ask',
                             backends=[usertypes.Backend.QtWebEngine],
                             raw_backends=None,
                             description='Hello World')
     options = [
         (urlmatch.UrlPattern('https://www.example.com/'), opt, 'ask'),
     ]
     writer = configfiles.ConfigPyWriter(options=options,
                                         bindings={},
                                         commented=False)
     text = '\n'.join(writer._gen_lines())
     expected = "config.set('opt', 'ask', 'https://www.example.com/')"
     assert expected in text
示例#14
0
def test_trailing_dot_domain(pattern, url):
    """Both patterns should match trailing dot and non trailing dot domains.

    More information about this not obvious behavior can be found in [1].

    RFC 1738 [2] specifies clearly that the <host> part of a URL is supposed to
    contain a fully qualified domain name:

    3.1. Common Internet Scheme Syntax
         //<user>:<password>@<host>:<port>/<url-path>

     host
         The fully qualified domain name of a network host

    [1] http://www.dns-sd.org./TrailingDotsInDomainNames.html
    [2] http://www.ietf.org/rfc/rfc1738.txt
    """
    assert urlmatch.UrlPattern(pattern).matches(QUrl(url))
    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
示例#16
0
    def _build_values(self, settings: typing.Mapping) -> None:
        """Build up self._values from the values in the given dict."""
        errors = []
        for name, yaml_values in settings.items():
            if not isinstance(yaml_values, dict):
                errors.append(
                    configexc.ConfigErrorDesc(
                        "While parsing {!r}".format(name),
                        "value is not a dict"))
                continue

            values = configutils.Values(configdata.DATA[name])
            if 'global' in yaml_values:
                values.add(yaml_values.pop('global'))

            for pattern, value in yaml_values.items():
                if not isinstance(pattern, str):
                    errors.append(
                        configexc.ConfigErrorDesc(
                            "While parsing {!r}".format(name),
                            "pattern is not of type string"))
                    continue
                try:
                    urlpattern = urlmatch.UrlPattern(pattern)
                except urlmatch.ParseError as e:
                    errors.append(
                        configexc.ConfigErrorDesc(
                            "While parsing pattern {!r} for {!r}".format(
                                pattern, name), e))
                    continue
                values.add(value, urlpattern)

            self._values[name] = values

        if errors:
            raise configexc.ConfigFileErrors('autoconfig.yml', errors)
示例#17
0
 def set(self, name: str, value: typing.Any, pattern: str = None) -> None:
     """Set a setting value in the config, optionally with a pattern."""
     with self._handle_error('setting', name):
         urlpattern = urlmatch.UrlPattern(pattern) if pattern else None
         self._config.set_obj(name, value, pattern=urlpattern)
示例#18
0
 def get(self, name: str, pattern: str = None) -> typing.Any:
     """Get a setting value from the config, optionally with a pattern."""
     with self._handle_error('getting', name):
         urlpattern = urlmatch.UrlPattern(pattern) if pattern else None
         return self._config.get_mutable_obj(name, pattern=urlpattern)
示例#19
0
def test_equal(text1, text2, equal):
    pat1 = urlmatch.UrlPattern(text1)
    pat2 = urlmatch.UrlPattern(text2)

    assert (pat1 == pat2) == equal
    assert (hash(pat1) == hash(pat2)) == equal
示例#20
0
def test_equal_string():
    assert urlmatch.UrlPattern("<all_urls>") != '<all_urls>'
示例#21
0
def pattern():
    return urlmatch.UrlPattern('*://www.example.com/')
示例#22
0
def test_repr():
    pat = urlmatch.UrlPattern('https://www.example.com/')
    expected = ("glimpsebrowser.utils.urlmatch.UrlPattern("
                "pattern='https://www.example.com/')")
    assert repr(pat) == expected
示例#23
0
 def test_pattern_no_configapi(self, config_stub):
     pattern = urlmatch.UrlPattern('https://example.com/')
     with pytest.raises(TypeError,
                        match="Can't use pattern without configapi!"):
         config.ConfigContainer(config_stub, pattern=pattern)
示例#24
0
 def test_set_no_pattern(self, conf, method, qtbot):
     meth = getattr(conf, method)
     pattern = urlmatch.UrlPattern('https://www.example.com/')
     with pytest.raises(configexc.NoPatternError):
         with qtbot.assert_not_emitted(conf.changed):
             meth('colors.statusbar.normal.bg', '#abcdef', pattern=pattern)
示例#25
0
 def test_get_obj_for_pattern_no_match(self, conf):
     pattern = urlmatch.UrlPattern('*://example.com')
     name = 'content.javascript.enabled'
     value = conf.get_obj_for_pattern(name, pattern=pattern)
     assert value is configutils.UNSET
示例#26
0
def test_str():
    text = 'https://www.example.com/'
    pat = urlmatch.UrlPattern(text)
    assert str(pat) == text
示例#27
0
 def test_get_for_url(self, conf):
     """Test conf.get() with a URL/pattern."""
     pattern = urlmatch.UrlPattern('*://example.com/')
     name = 'content.javascript.enabled'
     conf.set_obj(name, False, pattern=pattern)
     assert conf.get(name, url=QUrl('https://example.com/')) is False
示例#28
0
def other_pattern():
    return urlmatch.UrlPattern('https://www.example.org/')
示例#29
0
 def test_get_obj_for_pattern(self, conf):
     pattern = urlmatch.UrlPattern('*://example.com')
     name = 'content.javascript.enabled'
     conf.set_obj(name, False, pattern=pattern)
     assert conf.get_obj_for_pattern(name, pattern=pattern) is False
示例#30
0
def test_get_multiple_matches(values):
    """With multiple matching pattern, the last added should win."""
    all_pattern = urlmatch.UrlPattern('*://*/')
    values.add('new value', all_pattern)
    url = QUrl('https://www.example.com/')
    assert values.get_for_url(url) == 'new value'