Python PyQt5.QtCore.QUrl() Examples

The following are 30 code examples for showing how to use PyQt5.QtCore.QUrl(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module PyQt5.QtCore , or try the search function .

Example 1
Project: qutebrowser   Author: qutebrowser   File: test_models.py    License: GNU General Public License v3.0 7 votes vote down vote up
def test_tab_completion_not_sorted(qtmodeltester, fake_web_tab, win_registry,
                                   tabbed_browser_stubs):
    """Ensure that the completion row order is the same as tab index order.

    Would be violated for more than 9 tabs if the completion was being
    alphabetically sorted on the first column, or the others.
    """
    expected = []
    for idx in range(1, 11):
        url = "".join(random.sample(string.ascii_letters, 12))
        title = "".join(random.sample(string.ascii_letters, 12))
        expected.append(("0/{}".format(idx), url, title))

    tabbed_browser_stubs[0].widget.tabs = [
        fake_web_tab(QUrl(tab[1]), tab[2], idx)
        for idx, tab in enumerate(expected)
    ]
    model = miscmodels.buffer()
    model.set_pattern('')
    qtmodeltester.check(model)

    _check_completions(model, {
        '0': expected,
        '1': [],
    }) 
Example 2
Project: qutebrowser   Author: qutebrowser   File: stubs.py    License: GNU General Public License v3.0 6 votes vote down vote up
def __init__(self, url=QUrl(), title='', tab_id=0, *,
                 scroll_pos_perc=(0, 0),
                 load_status=usertypes.LoadStatus.success,
                 progress=0, can_go_back=None, can_go_forward=None):
        super().__init__(win_id=0, mode_manager=None, private=False)
        self._load_status = load_status
        self._title = title
        self._url = url
        self._progress = progress
        self.history = FakeWebTabHistory(self, can_go_back=can_go_back,
                                         can_go_forward=can_go_forward)
        self.scroller = FakeWebTabScroller(self, scroll_pos_perc)
        self.audio = FakeWebTabAudio(self)
        self.private_api = FakeWebTabPrivate(tab=self, mode_manager=None)
        wrapped = QWidget()
        self._layout.wrap(self, wrapped) 
Example 3
Project: qutebrowser   Author: qutebrowser   File: test_models.py    License: GNU General Public License v3.0 6 votes vote down vote up
def web_history_populated(web_history):
    """Pre-populate the web-history database."""
    web_history.add_url(
        url=QUrl('http://qutebrowser.org'),
        title='qutebrowser',
        atime=datetime(2015, 9, 5).timestamp()
    )
    web_history.add_url(
        url=QUrl('https://python.org'),
        title='Welcome to Python.org',
        atime=datetime(2016, 3, 8).timestamp()
    )
    web_history.add_url(
        url=QUrl('https://github.com'),
        title='https://github.com',
        atime=datetime(2016, 5, 1).timestamp()
    )
    return web_history 
Example 4
Project: qutebrowser   Author: qutebrowser   File: test_models.py    License: GNU General Public License v3.0 6 votes vote down vote up
def test_tab_completion(qtmodeltester, fake_web_tab, win_registry,
                        tabbed_browser_stubs):
    tabbed_browser_stubs[0].widget.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].widget.tabs = [
        fake_web_tab(QUrl('https://wiki.archlinux.org'), 'ArchWiki', 0),
    ]
    model = miscmodels.buffer()
    model.set_pattern('')
    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'),
        ]
    }) 
Example 5
Project: qutebrowser   Author: qutebrowser   File: test_models.py    License: GNU General Public License v3.0 6 votes vote down vote up
def test_other_buffer_completion(qtmodeltester, fake_web_tab, win_registry,
                                 tabbed_browser_stubs, info):
    tabbed_browser_stubs[0].widget.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].widget.tabs = [
        fake_web_tab(QUrl('https://wiki.archlinux.org'), 'ArchWiki', 0),
    ]
    info.win_id = 1
    model = miscmodels.other_buffer(info=info)
    model.set_pattern('')
    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')
        ],
    }) 
Example 6
Project: qutebrowser   Author: qutebrowser   File: test_models.py    License: GNU General Public License v3.0 6 votes vote down vote up
def test_window_completion(qtmodeltester, fake_web_tab, tabbed_browser_stubs,
                           info):
    tabbed_browser_stubs[0].widget.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].widget.tabs = [
        fake_web_tab(QUrl('https://wiki.archlinux.org'), 'ArchWiki', 0)
    ]

    info.win_id = 1
    model = miscmodels.window(info=info)
    model.set_pattern('')
    qtmodeltester.check(model)

    _check_completions(model, {
        'Windows': [
            ('0', 'window title - qutebrowser',
             'GitHub, Wikipedia, DuckDuckGo'),
        ]
    }) 
Example 7
Project: qutebrowser   Author: qutebrowser   File: test_urlmatch.py    License: GNU General Public License v3.0 6 votes vote down vote up
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)) 
Example 8
Project: qutebrowser   Author: qutebrowser   File: test_jinja.py    License: GNU General Public License v3.0 6 votes vote down vote up
def test_resource_url():
    """Test resource_url() which can be used from templates."""
    data = jinja.render('test2.html')
    print(data)
    url = QUrl(data)
    assert url.isValid()
    assert url.scheme() == 'file'

    path = url.path()

    if utils.is_windows:
        path = path.lstrip('/')
        path = path.replace('/', os.sep)

    with open(path, 'r', encoding='utf-8') as f:
        assert f.read().splitlines()[0] == "Hello World!" 
Example 9
Project: qutebrowser   Author: qutebrowser   File: test_pac.py    License: GNU General Public License v3.0 6 votes vote down vote up
def _pac_common_test(test_str):
    fun_str_f = """
        function FindProxyForURL(domain, host) {{
            {}
            return "DIRECT; PROXY 127.0.0.1:8080; SOCKS 192.168.1.1:4444";
        }}
    """

    fun_str = fun_str_f.format(test_str)
    res = pac.PACResolver(fun_str)
    proxies = res.resolve(QNetworkProxyQuery(QUrl("https://example.com/test")))
    assert len(proxies) == 3
    assert proxies[0].type() == QNetworkProxy.NoProxy
    assert proxies[1].type() == QNetworkProxy.HttpProxy
    assert proxies[1].hostName() == "127.0.0.1"
    assert proxies[1].port() == 8080
    assert proxies[2].type() == QNetworkProxy.Socks5Proxy
    assert proxies[2].hostName() == "192.168.1.1"
    assert proxies[2].port() == 4444 
Example 10
Project: qutebrowser   Author: qutebrowser   File: test_pac.py    License: GNU General Public License v3.0 6 votes vote down vote up
def test_secret_url(url, has_secret, from_file):
    """Make sure secret parts in a URL are stripped correctly.

    The following parts are considered secret:
        - If the PAC info is loaded from a local file, nothing.
        - If the URL to resolve is a HTTP URL, the username/password.
        - If the URL to resolve is a HTTPS URL, the username/password, query
          and path.
    """
    test_str = """
        function FindProxyForURL(domain, host) {{
            has_secret = domain.indexOf("secret") !== -1;
            expected_secret = {};
            if (has_secret !== expected_secret) {{
                throw new Error("Expected secret: " + expected_secret + ", found: " + has_secret + " in " + domain);
            }}
            return "DIRECT";
        }}
    """.format('true' if (has_secret or from_file) else 'false')
    res = pac.PACResolver(test_str)
    res.resolve(QNetworkProxyQuery(QUrl(url)), from_file=from_file) 
Example 11
Project: qutebrowser   Author: qutebrowser   File: test_cache.py    License: GNU General Public License v3.0 6 votes vote down vote up
def test_cache_existing_metadata_file(tmpdir, disk_cache):
    """Test querying existing meta data file from activated cache."""
    url = 'http://qutebrowser.org'
    content = b'foobar'

    metadata = QNetworkCacheMetaData()
    metadata.setUrl(QUrl(url))
    assert metadata.isValid()

    device = disk_cache.prepare(metadata)
    assert device is not None
    device.write(content)
    disk_cache.insert(device)
    disk_cache.updateMetaData(metadata)

    files = list(tmpdir.visit(fil=lambda path: path.isfile()))
    assert len(files) == 1
    assert disk_cache.fileMetaData(str(files[0])) == metadata 
Example 12
Project: qutebrowser   Author: qutebrowser   File: test_cache.py    License: GNU General Public License v3.0 6 votes vote down vote up
def test_cache_full(tmpdir):
    """Do a sanity test involving everything."""
    disk_cache = QNetworkDiskCache()
    disk_cache.setCacheDirectory(str(tmpdir))

    url = 'http://qutebrowser.org'
    content = b'cutebowser'
    preload_cache(disk_cache, url, content)
    url2 = 'https://qutebrowser.org'
    content2 = b'ohmycert'
    preload_cache(disk_cache, url2, content2)

    metadata = QNetworkCacheMetaData()
    metadata.setUrl(QUrl(url))
    soon = QDateTime.currentDateTime().addMonths(4)
    assert soon.isValid()
    metadata.setLastModified(soon)
    assert metadata.isValid()
    disk_cache.updateMetaData(metadata)
    disk_cache.remove(QUrl(url2))

    assert disk_cache.metaData(QUrl(url)).lastModified() == soon
    assert disk_cache.data(QUrl(url)).readAll() == content 
Example 13
Project: qutebrowser   Author: qutebrowser   File: test_hints.py    License: GNU General Public License v3.0 6 votes vote down vote up
def test_show_benchmark(benchmark, tabbed_browser, qtbot, message_bridge,
                        mode_manager):
    """Benchmark showing/drawing of hint labels."""
    tab = tabbed_browser.widget.tabs[0]

    with qtbot.wait_signal(tab.load_finished):
        tab.load_url(QUrl('qute://testdata/data/hints/benchmark.html'))

    manager = qutebrowser.browser.hints.HintManager(win_id=0)

    def bench():
        with qtbot.wait_signal(mode_manager.entered):
            manager.start()

        with qtbot.wait_signal(mode_manager.left):
            mode_manager.leave(usertypes.KeyMode.hint)

    benchmark(bench) 
Example 14
Project: qutebrowser   Author: qutebrowser   File: test_hints.py    License: GNU General Public License v3.0 6 votes vote down vote up
def test_match_benchmark(benchmark, tabbed_browser, qtbot, message_bridge,
                         mode_manager, qapp, config_stub):
    """Benchmark matching of hint labels."""
    tab = tabbed_browser.widget.tabs[0]

    with qtbot.wait_signal(tab.load_finished):
        tab.load_url(QUrl('qute://testdata/data/hints/benchmark.html'))

    config_stub.val.hints.scatter = False
    manager = qutebrowser.browser.hints.HintManager(win_id=0)

    with qtbot.wait_signal(mode_manager.entered):
        manager.start()

    def bench():
        manager.handle_partial_key('a')
        qapp.processEvents()
        manager.handle_partial_key('')
        qapp.processEvents()

    benchmark(bench)

    with qtbot.wait_signal(mode_manager.left):
        mode_manager.leave(usertypes.KeyMode.hint) 
Example 15
Project: qutebrowser   Author: qutebrowser   File: test_navigate.py    License: GNU General Public License v3.0 6 votes vote down vote up
def test_incdec(self, incdec, value, url, config_stub):
        if (value == '{}foo' and
                url == 'http://example.com/path with {} spaces'):
            pytest.xfail("https://github.com/qutebrowser/qutebrowser/issues/4917")

        config_stub.val.url.incdec_segments = ['host', 'path', 'query',
                                               'anchor']

        # The integer used should not affect test output, as long as it's
        # bigger than 1
        # 20 was chosen by dice roll, guaranteed to be random
        base_value = value.format(20)
        if incdec == 'increment':
            expected_value = value.format(21)
        else:
            expected_value = value.format(19)

        base_url = QUrl(url.format(base_value))
        expected_url = QUrl(url.format(expected_value))

        assert navigate.incdec(base_url, 1, incdec) == expected_url 
Example 16
Project: qutebrowser   Author: qutebrowser   File: test_navigate.py    License: GNU General Public License v3.0 6 votes vote down vote up
def test_count(self, inc_or_dec, value, url, count, config_stub):
        config_stub.val.url.incdec_segments = ['host', 'path', 'query',
                                               'anchor']
        base_value = value.format(20)
        if inc_or_dec == 'increment':
            expected_value = value.format(20 + count)
        else:
            if count > 20:
                return
            expected_value = value.format(20 - count)

        base_url = QUrl(url.format(base_value))
        expected_url = QUrl(url.format(expected_value))
        new_url = navigate.incdec(base_url, count, inc_or_dec)

        assert new_url == expected_url 
Example 17
Project: kw_condition   Author: coreanq   File: main.py    License: MIT License 5 votes vote down vote up
def initQmlEngine(self):
        self.qmlEngine.load(QUrl('qrc:///qml/main.qml'))        
        self.rootObject = self.qmlEngine.rootObjects()[0]
        self.rootObject.startClicked.connect(self.onStartClicked)
        self.rootObject.restartClicked.connect(self.onRestartClicked)
        self.rootObject.requestJangoClicked.connect(self.onRequestJangoClicked)
        self.rootObject.chegyeolClicked.connect(self.onChegyeolClicked)
        self.rootObject.testClicked.connect(self.onTestClicked)

        rootContext = self.qmlEngine.rootContext()
        rootContext.setContextProperty("model", self)
        pass 
Example 18
Project: qutebrowser   Author: qutebrowser   File: stubs.py    License: GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, headers=None, url=None):
        if url is None:
            url = QUrl()
        if headers is None:
            self.headers = {}
        else:
            self.headers = headers
        self.url = mock.Mock(return_value=url) 
Example 19
Project: qutebrowser   Author: qutebrowser   File: webserver.py    License: GNU General Public License v3.0 5 votes vote down vote up
def _check_status(self):
        """Check if the http status is what we expected."""
        path_to_statuses = {
            '/favicon.ico': [HTTPStatus.OK, HTTPStatus.PARTIAL_CONTENT],

            '/does-not-exist': [HTTPStatus.NOT_FOUND],
            '/does-not-exist-2': [HTTPStatus.NOT_FOUND],
            '/404': [HTTPStatus.NOT_FOUND],

            '/redirect-later': [HTTPStatus.FOUND],
            '/redirect-self': [HTTPStatus.FOUND],
            '/redirect-to': [HTTPStatus.FOUND],
            '/relative-redirect': [HTTPStatus.FOUND],
            '/absolute-redirect': [HTTPStatus.FOUND],

            '/cookies/set': [HTTPStatus.FOUND],

            '/500-inline': [HTTPStatus.INTERNAL_SERVER_ERROR],
            '/500': [HTTPStatus.INTERNAL_SERVER_ERROR],
        }
        for i in range(15):
            path_to_statuses['/redirect/{}'.format(i)] = [HTTPStatus.FOUND]
        for suffix in ['', '1', '2', '3', '4', '5', '6']:
            key = ('/basic-auth/user{suffix}/password{suffix}'
                   .format(suffix=suffix))
            path_to_statuses[key] = [HTTPStatus.UNAUTHORIZED, HTTPStatus.OK]

        default_statuses = [HTTPStatus.OK, HTTPStatus.NOT_MODIFIED]

        sanitized = QUrl('http://localhost' + self.path).path()  # Remove ?foo
        expected_statuses = path_to_statuses.get(sanitized, default_statuses)
        if self.status not in expected_statuses:
            raise AssertionError(
                "{} loaded with status {} but expected {}".format(
                    sanitized, self.status,
                    ' / '.join(repr(e) for e in expected_statuses))) 
Example 20
Project: qutebrowser   Author: qutebrowser   File: test_argparser.py    License: GNU General Public License v3.0 5 votes vote down vote up
def test_help(self, parser, tabbed_browser_stubs):
        parser.add_argument('--help', action=argparser.HelpAction, nargs=0)

        with pytest.raises(argparser.ArgumentParserExit):
            parser.parse_args(['--help'])

        expected_url = QUrl('qute://help/commands.html#foo')
        assert tabbed_browser_stubs[1].loaded_url == expected_url 
Example 21
Project: qutebrowser   Author: qutebrowser   File: test_models.py    License: GNU General Public License v3.0 5 votes vote down vote up
def test_tab_completion_delete(qtmodeltester, fake_web_tab, win_registry,
                               tabbed_browser_stubs):
    """Verify closing a tab by deleting it from the completion widget."""
    tabbed_browser_stubs[0].widget.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].widget.tabs = [
        fake_web_tab(QUrl('https://wiki.archlinux.org'), 'ArchWiki', 0),
    ]
    model = miscmodels.buffer()
    model.set_pattern('')
    qtmodeltester.check(model)

    parent = model.index(0, 0)
    idx = model.index(1, 0, parent)

    # sanity checks
    assert model.data(parent) == "0"
    assert model.data(idx) == '0/2'

    model.delete_cur_item(idx)
    actual = [tab.url() for tab in tabbed_browser_stubs[0].widget.tabs]
    assert actual == [QUrl('https://github.com'),
                      QUrl('https://duckduckgo.com')] 
Example 22
Project: qutebrowser   Author: qutebrowser   File: test_models.py    License: GNU General Public License v3.0 5 votes vote down vote up
def test_tab_completion_tabs_are_windows(qtmodeltester, fake_web_tab,
                                         win_registry, tabbed_browser_stubs,
                                         config_stub):
    """Verify tabs across all windows are listed under a single category."""
    tabbed_browser_stubs[0].widget.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].widget.tabs = [
        fake_web_tab(QUrl('https://wiki.archlinux.org'), 'ArchWiki', 0),
    ]

    config_stub.val.tabs.tabs_are_windows = True
    model = miscmodels.buffer()
    model.set_pattern('')
    qtmodeltester.check(model)

    _check_completions(model, {
        'Windows': [
            ('0/1', 'https://github.com', 'GitHub'),
            ('0/2', 'https://wikipedia.org', 'Wikipedia'),
            ('0/3', 'https://duckduckgo.com', 'DuckDuckGo'),
            ('1/1', 'https://wiki.archlinux.org', 'ArchWiki'),
        ]
    }) 
Example 23
Project: qutebrowser   Author: qutebrowser   File: test_models.py    License: GNU General Public License v3.0 5 votes vote down vote up
def test_tab_focus_completion(qtmodeltester, fake_web_tab, win_registry,
                              tabbed_browser_stubs, info):
    tabbed_browser_stubs[0].widget.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].widget.tabs = [
        fake_web_tab(QUrl('https://wiki.archlinux.org'), 'ArchWiki', 0),
    ]
    info.win_id = 1
    model = miscmodels.tab_focus(info=info)
    model.set_pattern('')
    qtmodeltester.check(model)

    _check_completions(model, {
        'Tabs': [
            ('1', 'https://wiki.archlinux.org', 'ArchWiki'),
        ],
        'Special': [
            ("last",
             "Focus the last-focused tab",
             None),

            ("stack-next",
             "Go forward through a stack of focused tabs",
             None),

            ("stack-prev",
             "Go backward through a stack of focused tabs",
             None),
        ]
    }) 
Example 24
Project: qutebrowser   Author: qutebrowser   File: test_urlmatch.py    License: GNU General Public License v3.0 5 votes vote down vote up
def test_whitespace_hosts(host):
    """Test that whitespace dot hosts are invalid.

    This is a deviation from Chromium.
    """
    template = 'https://{}/*'
    url = QUrl(template.format(host))
    assert not url.isValid()

    with pytest.raises(urlmatch.ParseError,
                       match='Invalid host|Pattern without host'):
        urlmatch.UrlPattern(template.format(host)) 
Example 25
Project: qutebrowser   Author: qutebrowser   File: test_urlmatch.py    License: GNU General Public License v3.0 5 votes vote down vote up
def test_urls(self, up, url, expected):
        assert up.matches(QUrl(url)) == expected 
Example 26
Project: qutebrowser   Author: qutebrowser   File: test_urlmatch.py    License: GNU General Public License v3.0 5 votes vote down vote up
def test_urls(self, up, url, expected):
        assert up.matches(QUrl(url)) == expected 
Example 27
Project: qutebrowser   Author: qutebrowser   File: test_urlmatch.py    License: GNU General Public License v3.0 5 votes vote down vote up
def test_urls(self, up, url, expected):
        assert up.matches(QUrl(url)) == expected 
Example 28
Project: qutebrowser   Author: qutebrowser   File: test_urlmatch.py    License: GNU General Public License v3.0 5 votes vote down vote up
def test_urls(self, pattern, expected):
        up = urlmatch.UrlPattern(pattern)
        assert up.matches(QUrl("http://127.0.0.1")) == expected


## FIXME Missing TEST(ExtensionURLPatternTest, Match8) (unicode)? 
Example 29
Project: qutebrowser   Author: qutebrowser   File: test_urlmatch.py    License: GNU General Public License v3.0 5 votes vote down vote up
def test_urls(self, up, url, expected):
        assert up.matches(QUrl(url)) == expected 
Example 30
Project: qutebrowser   Author: qutebrowser   File: test_urlmatch.py    License: GNU General Public License v3.0 5 votes vote down vote up
def test_urls(self, up, url):
        assert up.matches(QUrl(url))