Add utils.random_port()

This commit is contained in:
Florian Bruhin 2016-08-03 13:08:55 +02:00
parent dbccb12b49
commit 9851a13981
3 changed files with 21 additions and 9 deletions

View File

@ -28,6 +28,7 @@ import collections
import functools import functools
import contextlib import contextlib
import itertools import itertools
import socket
from PyQt5.QtCore import Qt from PyQt5.QtCore import Qt
from PyQt5.QtGui import QKeySequence, QColor, QClipboard from PyQt5.QtGui import QKeySequence, QColor, QClipboard
@ -783,3 +784,12 @@ def get_clipboard(selection=False):
def supports_selection(): def supports_selection():
"""Check if the OS supports primary selection.""" """Check if the OS supports primary selection."""
return QApplication.clipboard().supportsSelection() 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

View File

@ -31,6 +31,8 @@ from PyQt5.QtCore import pyqtSignal, QUrl
from end2end.fixtures import testprocess from end2end.fixtures import testprocess
from qutebrowser.utils import utils
class Request(testprocess.Line): class Request(testprocess.Line):
@ -127,17 +129,9 @@ class WebserverProcess(testprocess.Process):
def __init__(self, script, parent=None): def __init__(self, script, parent=None):
super().__init__(parent) super().__init__(parent)
self._script = script self._script = script
self.port = self._get_port() self.port = utils.random_port()
self.new_data.connect(self.new_request) 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): def get_requests(self):
"""Get the requests to the server during this test.""" """Get the requests to the server during this test."""
requests = self._get_data() requests = self._get_data()

View File

@ -27,6 +27,7 @@ import io
import logging import logging
import functools import functools
import collections import collections
import socket
from PyQt5.QtCore import Qt from PyQt5.QtCore import Qt
from PyQt5.QtGui import QColor, QClipboard from PyQt5.QtGui import QColor, QClipboard
@ -1000,3 +1001,10 @@ class TestGetSetClipboard:
]) ])
def test_is_special_key(keystr, expected): def test_is_special_key(keystr, expected):
assert utils.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()