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 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144
|
# SPDX-FileCopyrightText: Florian Bruhin (The Compiler) <mail@qutebrowser.org>
#
# SPDX-License-Identifier: GPL-3.0-or-later
"""Tests for qutebrowser.utils.qtutils."""
import io
import os
import pathlib
import dataclasses
import unittest
import unittest.mock
import pytest
from qutebrowser.qt.core import (QDataStream, QPoint, QUrl, QByteArray, QIODevice,
QTimer, QBuffer, QFile, QProcess, QFileDevice, QLibraryInfo, Qt, QObject)
from qutebrowser.qt.gui import QColor
from qutebrowser.qt import sip
from qutebrowser.utils import qtutils, utils, usertypes
import overflow_test_cases
from helpers import testutils
if utils.is_linux:
# Those are not run on macOS because that seems to cause a hang sometimes.
# On Windows, we don't run them either because of
# https://github.com/pytest-dev/pytest/issues/3650
try:
# pylint: disable=no-name-in-module,useless-suppression
from test import test_file
# pylint: enable=no-name-in-module,useless-suppression
except ImportError:
# Debian patches Python to remove the tests...
test_file = None
else:
test_file = None
@pytest.mark.parametrize('qversion, compiled, pyqt, version, exact, expected', [
# equal versions
('5.14.0', None, None, '5.14.0', False, True),
('5.14.0', None, None, '5.14.0', True, True), # exact=True
('5.14.0', None, None, '5.14', True, True), # without trailing 0
# newer version installed
('5.14.1', None, None, '5.14', False, True),
('5.14.1', None, None, '5.14', True, False), # exact=True
# older version installed
('5.13.2', None, None, '5.14', False, False),
('5.13.0', None, None, '5.13.2', False, False),
('5.13.0', None, None, '5.13.2', True, False), # exact=True
# compiled=True
# new Qt runtime, but compiled against older version
('5.14.0', '5.13.0', '5.14.0', '5.14.0', False, False),
# new Qt runtime, compiled against new version, but old PyQt
('5.14.0', '5.14.0', '5.13.0', '5.14.0', False, False),
# all up-to-date
('5.14.0', '5.14.0', '5.14.0', '5.14.0', False, True),
# dev suffix
('5.15.1', '5.15.1', '5.15.2.dev2009281246', '5.15.0', False, True),
])
def test_version_check(monkeypatch, qversion, compiled, pyqt, version, exact,
expected):
"""Test for version_check().
Args:
monkeypatch: The pytest monkeypatch fixture.
qversion: The version to set as fake qVersion().
compiled: The value for QT_VERSION_STR (set compiled=False)
pyqt: The value for PYQT_VERSION_STR (set compiled=False)
version: The version to compare with.
exact: Use exact comparing (==)
expected: The expected result.
"""
monkeypatch.setattr(qtutils, 'qVersion', lambda: qversion)
if compiled is not None:
monkeypatch.setattr(qtutils, 'QT_VERSION_STR', compiled)
monkeypatch.setattr(qtutils, 'PYQT_VERSION_STR', pyqt)
compiled_arg = True
else:
compiled_arg = False
actual = qtutils.version_check(version, exact, compiled=compiled_arg)
assert actual == expected
def test_version_check_compiled_and_exact():
with pytest.raises(ValueError):
qtutils.version_check('1.2.3', exact=True, compiled=True)
@pytest.mark.parametrize('version, is_new', [
('537.21', False), # QtWebKit 5.1
('538.1', False), # Qt 5.8
('602.1', True) # new QtWebKit TP5, 5.212 Alpha
])
def test_is_new_qtwebkit(monkeypatch, version, is_new):
monkeypatch.setattr(qtutils, 'qWebKitVersion', lambda: version)
assert qtutils.is_new_qtwebkit() == is_new
@pytest.mark.parametrize('backend, arguments, single_process', [
(usertypes.Backend.QtWebKit, ['--single-process'], False),
(usertypes.Backend.QtWebEngine, ['--single-process'], True),
(usertypes.Backend.QtWebEngine, [], False),
])
def test_is_single_process(monkeypatch, stubs, backend, arguments, single_process):
qapp = stubs.FakeQApplication(arguments=arguments)
monkeypatch.setattr(qtutils.objects, 'qapp', qapp)
monkeypatch.setattr(qtutils.objects, 'backend', backend)
assert qtutils.is_single_process() == single_process
@pytest.mark.parametrize('platform, is_wayland', [
("wayland", True),
("wayland-egl", True),
("xcb", False),
])
def test_is_wayland(monkeypatch, stubs, platform, is_wayland):
qapp = stubs.FakeQApplication(platform_name=platform)
monkeypatch.setattr(qtutils.objects, 'qapp', qapp)
assert qtutils.is_wayland() == is_wayland
class TestCheckOverflow:
"""Test check_overflow."""
@pytest.mark.parametrize('ctype, val',
overflow_test_cases.good_values())
def test_good_values(self, ctype, val):
"""Test values which are inside bounds."""
qtutils.check_overflow(val, ctype)
@pytest.mark.parametrize('ctype, val',
[(ctype, val) for (ctype, val, _) in
overflow_test_cases.bad_values()])
def test_bad_values_fatal(self, ctype, val):
"""Test values which are outside bounds with fatal=True."""
with pytest.raises(OverflowError):
qtutils.check_overflow(val, ctype)
@pytest.mark.parametrize('ctype, val, repl',
overflow_test_cases.bad_values())
def test_bad_values_nonfatal(self, ctype, val, repl):
"""Test values which are outside bounds with fatal=False."""
newval = qtutils.check_overflow(val, ctype, fatal=False)
assert newval == repl
class QtObject:
"""Fake Qt object for test_ensure."""
def __init__(self, valid=True, null=False, error=None):
self._valid = valid
self._null = null
self._error = error
def __repr__(self):
return '<QtObject>'
def errorString(self):
"""Get the fake error, or raise AttributeError if set to None."""
if self._error is None:
raise AttributeError
return self._error
def isValid(self):
return self._valid
def isNull(self):
return self._null
@pytest.mark.parametrize('obj, raising, exc_reason, exc_str', [
# good examples
(QtObject(valid=True, null=True), False, None, None),
(QtObject(valid=True, null=False), False, None, None),
# bad examples
(QtObject(valid=False, null=True), True, None, '<QtObject> is not valid'),
(QtObject(valid=False, null=False), True, None, '<QtObject> is not valid'),
(QtObject(valid=False, null=True, error='Test'), True, 'Test',
'<QtObject> is not valid: Test'),
])
def test_ensure_valid(obj, raising, exc_reason, exc_str):
"""Test ensure_valid.
Args:
obj: The object to test with.
raising: Whether QtValueError is expected to be raised.
exc_reason: The expected .reason attribute of the exception.
exc_str: The expected string of the exception.
"""
if raising:
with pytest.raises(qtutils.QtValueError) as excinfo:
qtutils.ensure_valid(obj)
assert excinfo.value.reason == exc_reason
assert str(excinfo.value) == exc_str
else:
qtutils.ensure_valid(obj)
@pytest.mark.parametrize('status, raising, message', [
(QDataStream.Status.Ok, False, None),
(QDataStream.Status.ReadPastEnd, True,
"The data stream has read past the end of the data in the underlying device."),
(QDataStream.Status.ReadCorruptData, True,
"The data stream has read corrupt data."),
(QDataStream.Status.WriteFailed, True,
"The data stream cannot write to the underlying device."),
pytest.param(
getattr(QDataStream.Status, "SizeLimitExceeded", None),
True,
(
"The data stream cannot read or write the data because its size is larger "
"than supported by the current platform."
),
marks=pytest.mark.skipif(
not hasattr(QDataStream.Status, "SizeLimitExceeded"),
reason="Added in Qt 6.7"
)
),
])
def test_check_qdatastream(status, raising, message):
"""Test check_qdatastream.
Args:
status: The status to set on the QDataStream we test with.
raising: Whether check_qdatastream is expected to raise OSError.
message: The expected exception string.
"""
stream = QDataStream()
stream.setStatus(status)
if raising:
with pytest.raises(OSError, match=message):
qtutils.check_qdatastream(stream)
else:
qtutils.check_qdatastream(stream)
def test_qdatastream_status_members():
"""Make sure no new members are added to QDataStream.Status.
If this fails, qtutils.check_qdatastream will need to be updated with the
respective error documentation.
"""
status_vals = set(testutils.enum_members(QDataStream, QDataStream.Status).values())
expected = {
QDataStream.Status.Ok,
QDataStream.Status.ReadPastEnd,
QDataStream.Status.ReadCorruptData,
QDataStream.Status.WriteFailed,
}
try:
expected.add(QDataStream.Status.SizeLimitExceeded)
except AttributeError:
# Added in Qt 6.7
pass
assert status_vals == expected
@pytest.mark.parametrize('color, expected', [
(QColor('red'), 'rgba(255, 0, 0, 255)'),
(QColor('blue'), 'rgba(0, 0, 255, 255)'),
(QColor(1, 3, 5, 7), 'rgba(1, 3, 5, 7)'),
])
def test_qcolor_to_qsscolor(color, expected):
assert qtutils.qcolor_to_qsscolor(color) == expected
def test_qcolor_to_qsscolor_invalid():
with pytest.raises(qtutils.QtValueError):
qtutils.qcolor_to_qsscolor(QColor())
@pytest.mark.parametrize('obj', [
QPoint(23, 42),
QUrl('http://www.qutebrowser.org/'),
])
def test_serialize(obj):
"""Test a serialize/deserialize round trip.
Args:
obj: The object to test with.
"""
new_obj = type(obj)()
qtutils.deserialize(qtutils.serialize(obj), new_obj)
assert new_obj == obj
class TestSerializeStream:
"""Tests for serialize_stream and deserialize_stream."""
def _set_status(self, stream, status):
"""Helper function so mocks can set an error status when used."""
stream.status.return_value = status
@pytest.fixture
def stream_mock(self):
"""Fixture providing a QDataStream-like mock."""
m = unittest.mock.MagicMock(spec=QDataStream)
m.status.return_value = QDataStream.Status.Ok
return m
def test_serialize_pre_error_mock(self, stream_mock):
"""Test serialize_stream with an error already set."""
stream_mock.status.return_value = QDataStream.Status.ReadCorruptData
with pytest.raises(OSError, match="The data stream has read corrupt "
"data."):
qtutils.serialize_stream(stream_mock, QPoint())
assert not stream_mock.__lshift__.called
def test_serialize_post_error_mock(self, stream_mock):
"""Test serialize_stream with an error while serializing."""
obj = QPoint()
stream_mock.__lshift__.side_effect = lambda _other: self._set_status(
stream_mock, QDataStream.Status.ReadCorruptData)
with pytest.raises(OSError, match="The data stream has read corrupt "
"data."):
qtutils.serialize_stream(stream_mock, obj)
stream_mock.__lshift__.assert_called_once_with(obj)
def test_deserialize_pre_error_mock(self, stream_mock):
"""Test deserialize_stream with an error already set."""
stream_mock.status.return_value = QDataStream.Status.ReadCorruptData
with pytest.raises(OSError, match="The data stream has read corrupt "
"data."):
qtutils.deserialize_stream(stream_mock, QPoint())
assert not stream_mock.__rshift__.called
def test_deserialize_post_error_mock(self, stream_mock):
"""Test deserialize_stream with an error while deserializing."""
obj = QPoint()
stream_mock.__rshift__.side_effect = lambda _other: self._set_status(
stream_mock, QDataStream.Status.ReadCorruptData)
with pytest.raises(OSError, match="The data stream has read corrupt "
"data."):
qtutils.deserialize_stream(stream_mock, obj)
stream_mock.__rshift__.assert_called_once_with(obj)
def test_round_trip_real_stream(self):
"""Test a round trip with a real QDataStream."""
src_obj = QPoint(23, 42)
dest_obj = QPoint()
data = QByteArray()
write_stream = QDataStream(data, QIODevice.OpenModeFlag.WriteOnly)
qtutils.serialize_stream(write_stream, src_obj)
read_stream = QDataStream(data, QIODevice.OpenModeFlag.ReadOnly)
qtutils.deserialize_stream(read_stream, dest_obj)
assert src_obj == dest_obj
@pytest.mark.qt_log_ignore('^QIODevice::write.*: ReadOnly device')
def test_serialize_readonly_stream(self):
"""Test serialize_stream with a read-only stream."""
data = QByteArray()
stream = QDataStream(data, QIODevice.OpenModeFlag.ReadOnly)
with pytest.raises(OSError, match="The data stream cannot write to "
"the underlying device."):
qtutils.serialize_stream(stream, QPoint())
@pytest.mark.qt_log_ignore('QIODevice::read.*: WriteOnly device')
def test_deserialize_writeonly_stream(self):
"""Test deserialize_stream with a write-only stream."""
data = QByteArray()
obj = QPoint()
stream = QDataStream(data, QIODevice.OpenModeFlag.WriteOnly)
with pytest.raises(OSError, match="The data stream has read past the "
"end of the data in the underlying device."):
qtutils.deserialize_stream(stream, obj)
class SavefileTestException(Exception):
"""Exception raised in TestSavefileOpen for testing."""
@pytest.mark.usefixtures('qapp')
class TestSavefileOpen:
"""Tests for savefile_open."""
## Tests with a mock testing that the needed methods are called.
@pytest.fixture
def qsavefile_mock(self, mocker):
"""Mock for QSaveFile."""
m = mocker.patch('qutebrowser.utils.qtutils.QSaveFile')
instance = m()
yield instance
instance.commit.assert_called_once_with()
def test_mock_open_error(self, qsavefile_mock):
"""Test with a mock and a failing open()."""
qsavefile_mock.open.return_value = False
qsavefile_mock.errorString.return_value = "Hello World"
with pytest.raises(OSError, match="Hello World"):
with qtutils.savefile_open('filename'):
pass
qsavefile_mock.open.assert_called_once_with(QIODevice.OpenModeFlag.WriteOnly)
qsavefile_mock.cancelWriting.assert_called_once_with()
def test_mock_exception(self, qsavefile_mock):
"""Test with a mock and an exception in the block."""
qsavefile_mock.open.return_value = True
with pytest.raises(SavefileTestException):
with qtutils.savefile_open('filename'):
raise SavefileTestException
qsavefile_mock.open.assert_called_once_with(QIODevice.OpenModeFlag.WriteOnly)
qsavefile_mock.cancelWriting.assert_called_once_with()
def test_mock_commit_failed(self, qsavefile_mock):
"""Test with a mock and an exception in the block."""
qsavefile_mock.open.return_value = True
qsavefile_mock.commit.return_value = False
with pytest.raises(OSError, match="Commit failed!"):
with qtutils.savefile_open('filename'):
pass
qsavefile_mock.open.assert_called_once_with(QIODevice.OpenModeFlag.WriteOnly)
assert not qsavefile_mock.cancelWriting.called
assert not qsavefile_mock.errorString.called
def test_mock_successful(self, qsavefile_mock):
"""Test with a mock and a successful write."""
qsavefile_mock.open.return_value = True
qsavefile_mock.errorString.return_value = "Hello World"
qsavefile_mock.commit.return_value = True
qsavefile_mock.write.side_effect = len
qsavefile_mock.isOpen.return_value = True
with qtutils.savefile_open('filename') as f:
f.write("Hello World")
qsavefile_mock.open.assert_called_once_with(QIODevice.OpenModeFlag.WriteOnly)
assert not qsavefile_mock.cancelWriting.called
qsavefile_mock.write.assert_called_once_with(b"Hello World")
## Tests with real files
@pytest.mark.parametrize('data', ["Hello World", "Snowman! ☃"])
def test_utf8(self, data, tmp_path):
"""Test with UTF8 data."""
filename = tmp_path / 'foo'
filename.write_text("Old data", encoding="utf-8")
with qtutils.savefile_open(str(filename)) as f:
f.write(data)
assert list(tmp_path.iterdir()) == [filename]
assert filename.read_text(encoding='utf-8') == data
def test_binary(self, tmp_path):
"""Test with binary data."""
filename = tmp_path / 'foo'
with qtutils.savefile_open(str(filename), binary=True) as f:
f.write(b'\xde\xad\xbe\xef')
assert list(tmp_path.iterdir()) == [filename]
assert filename.read_bytes() == b'\xde\xad\xbe\xef'
def test_exception(self, tmp_path):
"""Test with an exception in the block."""
filename = tmp_path / 'foo'
filename.write_text("Old content", encoding="utf-8")
with pytest.raises(SavefileTestException):
with qtutils.savefile_open(str(filename)) as f:
f.write("Hello World!")
raise SavefileTestException
assert list(tmp_path.iterdir()) == [filename]
assert filename.read_text(encoding='utf-8') == "Old content"
def test_existing_dir(self, tmp_path):
"""Test with the filename already occupied by a directory."""
filename = tmp_path / 'foo'
filename.mkdir()
with pytest.raises(OSError) as excinfo:
with qtutils.savefile_open(str(filename)):
pass
msg = "Filename refers to a directory: {!r}".format(str(filename))
assert str(excinfo.value) == msg
assert list(tmp_path.iterdir()) == [filename]
def test_failing_flush(self, tmp_path):
"""Test with the file being closed before flushing."""
filename = tmp_path / 'foo'
with pytest.raises(ValueError, match="IO operation on closed device!"):
with qtutils.savefile_open(str(filename), binary=True) as f:
f.write(b'Hello')
f.dev.commit() # provoke failing flush
assert list(tmp_path.iterdir()) == [filename]
def test_failing_commit(self, tmp_path):
"""Test with the file being closed before committing."""
filename = tmp_path / 'foo'
with pytest.raises(OSError, match='Commit failed!'):
with qtutils.savefile_open(str(filename), binary=True) as f:
f.write(b'Hello')
f.dev.cancelWriting() # provoke failing commit
assert list(tmp_path.iterdir()) == []
def test_line_endings(self, tmp_path):
"""Make sure line endings are translated correctly.
See https://github.com/qutebrowser/qutebrowser/issues/309
"""
filename = tmp_path / 'foo'
with qtutils.savefile_open(str(filename)) as f:
f.write('foo\nbar\nbaz')
data = filename.read_bytes()
if utils.is_windows:
assert data == b'foo\r\nbar\r\nbaz'
else:
assert data == b'foo\nbar\nbaz'
if test_file is not None: # noqa: C901
# If we were able to import Python's test_file module, we run some code
# here which defines unittest TestCases to run the python tests over
# PyQIODevice.
@pytest.fixture(scope='session', autouse=True)
def clean_up_python_testfile():
"""Clean up the python testfile after tests if tests didn't."""
yield
try:
pathlib.Path(test_file.TESTFN).unlink()
except FileNotFoundError:
pass
class PyIODeviceTestMixin:
"""Some helper code to run Python's tests with PyQIODevice.
Attributes:
_data: A QByteArray containing the data in memory.
f: The opened PyQIODevice.
"""
def setUp(self):
"""Set up self.f using a PyQIODevice instead of a real file."""
self._data = QByteArray()
self.f = self.open(test_file.TESTFN, 'wb')
def open(self, _fname, mode):
"""Open an in-memory PyQIODevice instead of a real file."""
modes = {
'wb': QIODevice.OpenModeFlag.WriteOnly | QIODevice.OpenModeFlag.Truncate,
'w': QIODevice.OpenModeFlag.WriteOnly | QIODevice.OpenModeFlag.Text | QIODevice.OpenModeFlag.Truncate,
'rb': QIODevice.OpenModeFlag.ReadOnly,
'r': QIODevice.OpenModeFlag.ReadOnly | QIODevice.OpenModeFlag.Text,
}
try:
qt_mode = modes[mode]
except KeyError:
raise ValueError("Invalid mode {}!".format(mode))
f = QBuffer(self._data)
f.open(qt_mode)
qiodev = qtutils.PyQIODevice(f)
# Make sure tests using name/mode don't blow up.
qiodev.name = test_file.TESTFN
qiodev.mode = mode
# Create empty TESTFN file because the Python tests try to unlink
# it after the test.
with open(test_file.TESTFN, 'w', encoding='utf-8'):
pass
return qiodev
class PyAutoFileTests(PyIODeviceTestMixin, test_file.AutoFileTests,
unittest.TestCase):
"""Unittest testcase to run Python's AutoFileTests."""
def testReadinto_text(self):
"""Skip this test as BufferedIOBase seems to fail it."""
class PyOtherFileTests(PyIODeviceTestMixin, test_file.OtherFileTests,
unittest.TestCase):
"""Unittest testcase to run Python's OtherFileTests."""
def testSetBufferSize(self):
"""Skip this test as setting buffer size is unsupported."""
def testDefaultBufferSize(self):
"""Skip this test as getting buffer size is unsupported."""
def testTruncateOnWindows(self):
"""Skip this test truncating is unsupported."""
class FailingQIODevice(QIODevice):
"""A fake QIODevice where reads/writes fail."""
def isOpen(self):
return True
def isReadable(self):
return True
def isWritable(self):
return True
def write(self, _data):
"""Simulate failed write."""
self.setErrorString("Writing failed")
return -1
def read(self, _maxsize): # pylint: disable=useless-return
"""Simulate failed read."""
self.setErrorString("Reading failed")
return None
def readAll(self):
return self.read(0)
def readLine(self, maxsize):
return self.read(maxsize)
class TestPyQIODevice:
"""Tests for PyQIODevice."""
@pytest.fixture
def pyqiodev(self):
"""Fixture providing a PyQIODevice with a QByteArray to test."""
data = QByteArray()
f = QBuffer(data)
qiodev = qtutils.PyQIODevice(f)
yield qiodev
qiodev.close()
@pytest.fixture
def pyqiodev_failing(self):
"""Fixture providing a PyQIODevice with a FailingQIODevice to test."""
failing = FailingQIODevice()
return qtutils.PyQIODevice(failing)
@pytest.mark.parametrize('method, args', [
('seek', [0]),
('flush', []),
('isatty', []),
('readline', []),
('tell', []),
('write', [b'']),
('read', []),
])
def test_closed_device(self, pyqiodev, method, args):
"""Test various methods with a closed device.
Args:
method: The name of the method to call.
args: The arguments to pass.
"""
func = getattr(pyqiodev, method)
with pytest.raises(ValueError, match="IO operation on closed device!"):
func(*args)
@pytest.mark.parametrize('method', ['readline', 'read'])
def test_unreadable(self, pyqiodev, method):
"""Test methods with an unreadable device.
Args:
method: The name of the method to call.
"""
pyqiodev.open(QIODevice.OpenModeFlag.WriteOnly)
func = getattr(pyqiodev, method)
with pytest.raises(OSError, match="Trying to read unreadable file!"):
func()
def test_unwritable(self, pyqiodev):
"""Test writing with a read-only device."""
pyqiodev.open(QIODevice.OpenModeFlag.ReadOnly)
with pytest.raises(OSError, match="Trying to write to unwritable "
"file!"):
pyqiodev.write(b'')
@pytest.mark.parametrize('data', [b'12345', b''])
def test_len(self, pyqiodev, data):
"""Test len()/__len__.
Args:
data: The data to write before checking if the length equals
len(data).
"""
pyqiodev.open(QIODevice.OpenModeFlag.WriteOnly)
pyqiodev.write(data)
assert len(pyqiodev) == len(data)
def test_failing_open(self, tmp_path):
"""Test open() which fails (because it's an existent directory)."""
qf = QFile(str(tmp_path))
dev = qtutils.PyQIODevice(qf)
with pytest.raises(qtutils.QtOSError) as excinfo:
dev.open(QIODevice.OpenModeFlag.WriteOnly)
assert excinfo.value.qt_errno == QFileDevice.FileError.OpenError
assert dev.closed
def test_fileno(self, pyqiodev):
with pytest.raises(io.UnsupportedOperation):
pyqiodev.fileno()
@pytest.mark.qt_log_ignore('^QBuffer::seek: Invalid pos:')
@pytest.mark.parametrize('offset, whence, pos, data, raising', [
(0, io.SEEK_SET, 0, b'1234567890', False),
(42, io.SEEK_SET, 0, b'1234567890', True),
(8, io.SEEK_CUR, 8, b'90', False),
(-5, io.SEEK_CUR, 0, b'1234567890', True),
(-2, io.SEEK_END, 8, b'90', False),
(2, io.SEEK_END, 0, b'1234567890', True),
(0, io.SEEK_END, 10, b'', False),
])
def test_seek_tell(self, pyqiodev, offset, whence, pos, data, raising):
"""Test seek() and tell().
The initial position when these tests run is 0.
Args:
offset: The offset to pass to .seek().
whence: The whence argument to pass to .seek().
pos: The expected position after seeking.
data: The expected data to read after seeking.
raising: Whether seeking should raise OSError.
"""
with pyqiodev.open(QIODevice.OpenModeFlag.WriteOnly) as f:
f.write(b'1234567890')
pyqiodev.open(QIODevice.OpenModeFlag.ReadOnly)
if raising:
with pytest.raises(OSError, match="seek failed!"):
pyqiodev.seek(offset, whence)
else:
pyqiodev.seek(offset, whence)
assert pyqiodev.tell() == pos
assert pyqiodev.read() == data
def test_seek_unsupported(self, pyqiodev):
"""Test seeking with unsupported whence arguments."""
# pylint: disable=no-member,useless-suppression
if hasattr(os, 'SEEK_HOLE'):
whence = os.SEEK_HOLE
elif hasattr(os, 'SEEK_DATA'):
whence = os.SEEK_DATA
# pylint: enable=no-member,useless-suppression
else:
pytest.skip("Needs os.SEEK_HOLE or os.SEEK_DATA available.")
pyqiodev.open(QIODevice.OpenModeFlag.ReadOnly)
with pytest.raises(io.UnsupportedOperation):
# pylint: disable=possibly-used-before-assignment
pyqiodev.seek(0, whence)
@pytest.mark.flaky
def test_qprocess(self, py_proc):
"""Test PyQIODevice with a QProcess which is non-sequential.
This also verifies seek() and tell() behave as expected.
"""
proc = QProcess()
proc.start(*py_proc('print("Hello World")'))
dev = qtutils.PyQIODevice(proc)
assert not dev.closed
with pytest.raises(OSError, match='Random access not allowed!'):
dev.seek(0)
with pytest.raises(OSError, match='Random access not allowed!'):
dev.tell()
proc.waitForFinished(1000)
proc.kill()
assert bytes(dev.read()).rstrip() == b'Hello World'
def test_truncate(self, pyqiodev):
with pytest.raises(io.UnsupportedOperation):
pyqiodev.truncate()
def test_closed(self, pyqiodev):
"""Test the closed attribute."""
assert pyqiodev.closed
pyqiodev.open(QIODevice.OpenModeFlag.ReadOnly)
assert not pyqiodev.closed
pyqiodev.close()
assert pyqiodev.closed
def test_contextmanager(self, pyqiodev):
"""Make sure using the PyQIODevice as context manager works."""
assert pyqiodev.closed
with pyqiodev.open(QIODevice.OpenModeFlag.ReadOnly) as f:
assert not f.closed
assert f is pyqiodev
assert pyqiodev.closed
def test_flush(self, pyqiodev):
"""Make sure flushing doesn't raise an exception."""
pyqiodev.open(QIODevice.OpenModeFlag.WriteOnly)
pyqiodev.write(b'test')
pyqiodev.flush()
@pytest.mark.parametrize('method, ret', [
('isatty', False),
('seekable', True),
])
def test_bools(self, method, ret, pyqiodev):
"""Make sure simple bool arguments return the right thing.
Args:
method: The name of the method to call.
ret: The return value we expect.
"""
pyqiodev.open(QIODevice.OpenModeFlag.WriteOnly)
func = getattr(pyqiodev, method)
assert func() == ret
@pytest.mark.parametrize('mode, readable, writable', [
(QIODevice.OpenModeFlag.ReadOnly, True, False),
(QIODevice.OpenModeFlag.ReadWrite, True, True),
(QIODevice.OpenModeFlag.WriteOnly, False, True),
])
def test_readable_writable(self, mode, readable, writable, pyqiodev):
"""Test readable() and writable().
Args:
mode: The mode to open the PyQIODevice in.
readable: Whether the device should be readable.
writable: Whether the device should be writable.
"""
assert not pyqiodev.readable()
assert not pyqiodev.writable()
pyqiodev.open(mode)
assert pyqiodev.readable() == readable
assert pyqiodev.writable() == writable
@pytest.mark.parametrize('size, chunks', [
(-1, [b'one\n', b'two\n', b'three', b'']),
(0, [b'', b'', b'', b'']),
(2, [b'on', b'e\n', b'tw', b'o\n', b'th', b're', b'e']),
(10, [b'one\n', b'two\n', b'three', b'']),
])
def test_readline(self, size, chunks, pyqiodev):
"""Test readline() with different sizes.
Args:
size: The size to pass to readline()
chunks: A list of expected chunks to read.
"""
with pyqiodev.open(QIODevice.OpenModeFlag.WriteOnly) as f:
f.write(b'one\ntwo\nthree')
pyqiodev.open(QIODevice.OpenModeFlag.ReadOnly)
for i, chunk in enumerate(chunks, start=1):
print("Expecting chunk {}: {!r}".format(i, chunk))
assert pyqiodev.readline(size) == chunk
def test_write(self, pyqiodev):
"""Make sure writing and re-reading works."""
with pyqiodev.open(QIODevice.OpenModeFlag.WriteOnly) as f:
f.write(b'foo\n')
f.write(b'bar\n')
pyqiodev.open(QIODevice.OpenModeFlag.ReadOnly)
assert pyqiodev.read() == b'foo\nbar\n'
def test_write_error(self, pyqiodev_failing):
"""Test writing with FailingQIODevice."""
with pytest.raises(OSError, match="Writing failed"):
pyqiodev_failing.write(b'x')
@pytest.mark.posix
@pytest.mark.skipif(not pathlib.Path('/dev/full').exists(),
reason="Needs /dev/full.")
def test_write_error_real(self):
"""Test a real write error with /dev/full on supported systems."""
qf = QFile('/dev/full')
qf.open(QIODevice.OpenModeFlag.WriteOnly | QIODevice.OpenModeFlag.Unbuffered)
dev = qtutils.PyQIODevice(qf)
with pytest.raises(OSError, match='No space left on device'):
dev.write(b'foo')
qf.close()
@pytest.mark.parametrize('size, chunks', [
(-1, [b'1234567890']),
(0, [b'']),
(3, [b'123', b'456', b'789', b'0']),
(20, [b'1234567890'])
])
def test_read(self, size, chunks, pyqiodev):
"""Test reading with different sizes.
Args:
size: The size to pass to read()
chunks: A list of expected data chunks.
"""
with pyqiodev.open(QIODevice.OpenModeFlag.WriteOnly) as f:
f.write(b'1234567890')
pyqiodev.open(QIODevice.OpenModeFlag.ReadOnly)
for i, chunk in enumerate(chunks):
print("Expecting chunk {}: {!r}".format(i, chunk))
assert pyqiodev.read(size) == chunk
@pytest.mark.parametrize('method, args', [
('read', []),
('read', [5]),
('readline', []),
('readline', [5]),
])
def test_failing_reads(self, method, args, pyqiodev_failing):
"""Test reading with a FailingQIODevice.
Args:
method: The name of the method to call.
args: A list of arguments to pass.
"""
func = getattr(pyqiodev_failing, method)
with pytest.raises(OSError, match='Reading failed'):
func(*args)
@pytest.mark.usefixtures('qapp')
class TestEventLoop:
"""Tests for EventLoop.
Attributes:
loop: The EventLoop we're testing.
"""
# pylint: disable=attribute-defined-outside-init
def _assert_executing(self):
"""Slot which gets called from timers to be sure the loop runs."""
assert self.loop._executing
def _double_exec(self):
"""Slot which gets called from timers to assert double-exec fails."""
with pytest.raises(AssertionError):
self.loop.exec()
def test_normal_exec(self):
"""Test exec_ without double-executing."""
self.loop = qtutils.EventLoop()
QTimer.singleShot(100, self._assert_executing)
QTimer.singleShot(200, self.loop.quit)
self.loop.exec()
assert not self.loop._executing
def test_double_exec(self):
"""Test double-executing."""
self.loop = qtutils.EventLoop()
QTimer.singleShot(100, self._assert_executing)
QTimer.singleShot(200, self._double_exec)
QTimer.singleShot(300, self._assert_executing)
QTimer.singleShot(400, self.loop.quit)
self.loop.exec()
assert not self.loop._executing
class TestInterpolateColor:
@dataclasses.dataclass
class Colors:
white: testutils.Color
black: testutils.Color
@pytest.fixture
def colors(self):
"""Example colors to be used."""
return self.Colors(testutils.Color('white'), testutils.Color('black'))
def test_invalid_start(self, colors):
"""Test an invalid start color."""
with pytest.raises(qtutils.QtValueError):
qtutils.interpolate_color(testutils.Color(), colors.white, 0)
def test_invalid_end(self, colors):
"""Test an invalid end color."""
with pytest.raises(qtutils.QtValueError):
qtutils.interpolate_color(colors.white, testutils.Color(), 0)
@pytest.mark.parametrize('perc', [-1, 101])
def test_invalid_percentage(self, colors, perc):
"""Test an invalid percentage."""
with pytest.raises(ValueError):
qtutils.interpolate_color(colors.white, colors.white, perc)
def test_invalid_colorspace(self, colors):
"""Test an invalid colorspace."""
with pytest.raises(ValueError):
qtutils.interpolate_color(colors.white, colors.black, 10, QColor.Spec.Cmyk)
@pytest.mark.parametrize('colorspace', [QColor.Spec.Rgb, QColor.Spec.Hsv, QColor.Spec.Hsl])
def test_0_100(self, colors, colorspace):
"""Test 0% and 100% in different colorspaces."""
white = qtutils.interpolate_color(colors.white, colors.black, 0, colorspace)
black = qtutils.interpolate_color(colors.white, colors.black, 100, colorspace)
assert testutils.Color(white) == colors.white
assert testutils.Color(black) == colors.black
def test_interpolation_rgb(self):
"""Test an interpolation in the RGB colorspace."""
color = qtutils.interpolate_color(
testutils.Color(0, 40, 100), testutils.Color(0, 20, 200), 50, QColor.Spec.Rgb)
assert testutils.Color(color) == testutils.Color(0, 30, 150)
def test_interpolation_hsv(self):
"""Test an interpolation in the HSV colorspace."""
start = testutils.Color()
stop = testutils.Color()
start.setHsv(0, 40, 100)
stop.setHsv(0, 20, 200)
color = qtutils.interpolate_color(start, stop, 50, QColor.Spec.Hsv)
expected = testutils.Color()
expected.setHsv(0, 30, 150)
assert testutils.Color(color) == expected
def test_interpolation_hsl(self):
"""Test an interpolation in the HSL colorspace."""
start = testutils.Color()
stop = testutils.Color()
start.setHsl(0, 40, 100)
stop.setHsl(0, 20, 200)
color = qtutils.interpolate_color(start, stop, 50, QColor.Spec.Hsl)
expected = testutils.Color()
expected.setHsl(0, 30, 150)
assert testutils.Color(color) == expected
@pytest.mark.parametrize('colorspace', [QColor.Spec.Rgb, QColor.Spec.Hsv, QColor.Spec.Hsl])
def test_interpolation_alpha(self, colorspace):
"""Test interpolation of colorspace's alpha."""
start = testutils.Color(0, 0, 0, 30)
stop = testutils.Color(0, 0, 0, 100)
color = qtutils.interpolate_color(start, stop, 50, colorspace)
expected = testutils.Color(0, 0, 0, 65)
assert testutils.Color(color) == expected
@pytest.mark.parametrize('percentage, expected', [
(0, (0, 0, 0)),
(99, (0, 0, 0)),
(100, (255, 255, 255)),
])
def test_interpolation_none(self, percentage, expected):
"""Test an interpolation with a gradient turned off."""
color = qtutils.interpolate_color(
testutils.Color(0, 0, 0), testutils.Color(255, 255, 255), percentage, None)
assert isinstance(color, QColor)
assert testutils.Color(color) == testutils.Color(*expected)
class TestLibraryPath:
def test_simple(self):
try:
# Qt 6
path = QLibraryInfo.path(QLibraryInfo.LibraryPath.DataPath)
except AttributeError:
# Qt 5
path = QLibraryInfo.location(QLibraryInfo.LibraryLocation.DataPath)
assert path
assert qtutils.library_path(qtutils.LibraryPath.data).as_posix() == path
@pytest.mark.parametrize("which", list(qtutils.LibraryPath))
def test_all(self, which):
if utils.is_windows and which == qtutils.LibraryPath.settings:
pytest.skip("Settings path not supported on Windows")
qtutils.library_path(which)
# The returned path doesn't necessarily exist.
def test_values_match_qt(self):
try:
# Qt 6
enumtype = QLibraryInfo.LibraryPath
except AttributeError:
enumtype = QLibraryInfo.LibraryLocation
our_names = {member.value for member in qtutils.LibraryPath}
qt_names = set(testutils.enum_members(QLibraryInfo, enumtype))
qt_names.discard("ImportsPath") # Moved to QmlImportsPath in Qt 6
assert qt_names == our_names
def test_extract_enum_val():
value = qtutils.extract_enum_val(Qt.KeyboardModifier.ShiftModifier)
assert value == 0x02000000
class TestQObjRepr:
@pytest.mark.parametrize("obj", [QObject(), object(), None])
def test_simple(self, obj):
assert qtutils.qobj_repr(obj) == repr(obj)
def _py_repr(self, obj):
"""Get the original repr of an object, with <> stripped off.
We do this in code instead of recreating it in tests because of output
differences between PyQt5/PyQt6 and between operating systems.
"""
r = repr(obj)
if r.startswith("<") and r.endswith(">"):
return r[1:-1]
return r
def test_object_name(self):
obj = QObject()
obj.setObjectName("Tux")
expected = f"<{self._py_repr(obj)}, objectName='Tux'>"
assert qtutils.qobj_repr(obj) == expected
def test_class_name(self):
obj = QTimer() # misc: ignore
hidden = sip.cast(obj, QObject)
expected = f"<{self._py_repr(hidden)}, className='QTimer'>"
assert qtutils.qobj_repr(hidden) == expected
def test_both(self):
obj = QTimer() # misc: ignore
obj.setObjectName("Pomodoro")
hidden = sip.cast(obj, QObject)
expected = f"<{self._py_repr(hidden)}, objectName='Pomodoro', className='QTimer'>"
assert qtutils.qobj_repr(hidden) == expected
def test_rich_repr(self):
class RichRepr(QObject):
def __repr__(self):
return "RichRepr()"
obj = RichRepr()
assert repr(obj) == "RichRepr()" # sanity check
expected = "<RichRepr(), className='RichRepr'>"
assert qtutils.qobj_repr(obj) == expected
|