From 9851a13981306fd97bbf98840b1ab01d0089fd97 Mon Sep 17 00:00:00 2001 From: Florian Bruhin Date: Wed, 3 Aug 2016 13:08:55 +0200 Subject: [PATCH] Add utils.random_port() --- qutebrowser/utils/utils.py | 10 ++++++++++ tests/end2end/fixtures/webserver.py | 12 +++--------- tests/unit/utils/test_utils.py | 8 ++++++++ 3 files changed, 21 insertions(+), 9 deletions(-) diff --git a/qutebrowser/utils/utils.py b/qutebrowser/utils/utils.py index 87ee9d901..f24365ce2 100644 --- a/qutebrowser/utils/utils.py +++ b/qutebrowser/utils/utils.py @@ -28,6 +28,7 @@ import collections import functools import contextlib import itertools +import socket from PyQt5.QtCore import Qt from PyQt5.QtGui import QKeySequence, QColor, QClipboard @@ -783,3 +784,12 @@ def get_clipboard(selection=False): def supports_selection(): """Check if the OS supports primary selection.""" return QApplication.clipboard().supportsSelection() + + +def random_port(): + """Get a random free port.""" + sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + sock.bind(('localhost', 0)) + port = sock.getsockname()[1] + sock.close() + return port diff --git a/tests/end2end/fixtures/webserver.py b/tests/end2end/fixtures/webserver.py index 79ba7b55f..c009be4b1 100644 --- a/tests/end2end/fixtures/webserver.py +++ b/tests/end2end/fixtures/webserver.py @@ -31,6 +31,8 @@ from PyQt5.QtCore import pyqtSignal, QUrl from end2end.fixtures import testprocess +from qutebrowser.utils import utils + class Request(testprocess.Line): @@ -127,17 +129,9 @@ class WebserverProcess(testprocess.Process): def __init__(self, script, parent=None): super().__init__(parent) self._script = script - self.port = self._get_port() + self.port = utils.random_port() self.new_data.connect(self.new_request) - def _get_port(self): - """Get a random free port to use for the server.""" - sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) - sock.bind(('localhost', 0)) - port = sock.getsockname()[1] - sock.close() - return port - def get_requests(self): """Get the requests to the server during this test.""" requests = self._get_data() diff --git a/tests/unit/utils/test_utils.py b/tests/unit/utils/test_utils.py index 52c36eee3..49d20ebaf 100644 --- a/tests/unit/utils/test_utils.py +++ b/tests/unit/utils/test_utils.py @@ -27,6 +27,7 @@ import io import logging import functools import collections +import socket from PyQt5.QtCore import Qt from PyQt5.QtGui import QColor, QClipboard @@ -1000,3 +1001,10 @@ class TestGetSetClipboard: ]) def test_is_special_key(keystr, expected): assert utils.is_special_key(keystr) == expected + + +def test_random_port(): + port = utils.random_port() + sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + sock.bind(('localhost', port)) + sock.close()