<commit_before>import os
import sys
import math
from io import StringIO

import pytest

from msl.qt import application, QtWidgets, QtCore, QtGui, Qt, convert

app = application()


def has_pythonnet():
    try:
        import clr
    except ImportError:
        return False
    else:
        return True


def test_to_qicon():

    assert isinstance(convert.to_qicon(QtGui.QIcon()), QtGui.QIcon)
    assert isinstance(convert.to_qicon(QtGui.QPixmap()), QtGui.QIcon)
    assert isinstance(convert.to_qicon(QtGui.QImage()), QtGui.QIcon)
    assert isinstance(convert.to_qicon(QtWidgets.QStyle.SP_TitleBarMenuButton), QtGui.QIcon)
    assert isinstance(convert.to_qicon(14), QtGui.QIcon)

    base64 = 'iVBORw0KGgoAAAANSUhEUgAAACgAAABCCAYAAAAlkZRRAAAACXBIWXMAAAsTAAALEwEAmpwYAAABpElEQVR' \
             '<KEY>' \
             '<KEY>/<KEY>' \
             'kGXc9824iMYBG0JgrZ4X0lMWe+KtKKkdTcvQgT3sRy2Y6URr6+bo3laV/cogpUcX28VpbV1vdtY4iyCYcsv' \
             'lSBoi7j94G474iMoXjDMg7YEQVvEC4rPDxq/xctBdH7CuAGA0/vSOBlkivk0o+iMNcfuVWq6+6uOfot4wdo' \
             'h/riKcqbqYOMrMfQTxEdQvKC4/eAu4iMYBG0RL9gAthd6yg4lco6B+AiKFzSfB1erBVQj8+CyF2PB1sPrAg' \
             'fyea4RP8TiBb+GmDIA0ArF5h/CLUCPx5AKuISAsJJYIV4w8O8hAOj2O9VbTJRNn6YpAHT6nZxQnYun49nmQ' \
             'NTrXcSaKN8t37RRU85AMRvPEgDoXnZT8Pe3un31FXMymTzL/xwrXlA8n2MHdwPYAbB5AAAAAElFTkSuQmCC'

    assert isinstance(convert.to_qicon(QtCore.QByteArray(base64.encode())), QtGui.QIcon)
    assert isinstance(convert.to_qicon(bytearray(base64.encode())), QtGui.QIcon)

    default_size = convert.to_qicon(QtWidgets.QStyle.SP_TitleBarMenuButton).availableSizes()[-1]
    assert isinstance(default_size, QtCore.QSize)

    with pytest.raises(TypeError):
        convert.to_qicon(None)

    with pytest.raises(OSError):
        convert.to_qicon(99999)  # not a valid QStyle.StandardPixmap enum value

    with pytest.raises(OSError):
        convert.to_qicon('this is not an icon')

    assert isinstance(convert.to_qicon(os.path.join(os.path.dirname(__file__), 'gamma.png')), QtGui.QIcon)

    # insert this directory into sys.path and check again
    sys.path.insert(0, os.path.dirname(__file__))
    assert isinstance(convert.to_qicon('gamma.png'), QtGui.QIcon)

    icon_1 = convert.to_qicon('gamma.png').availableSizes()[0]
    icon_2 = convert.to_qicon('gamma.png', size=0.5).availableSizes()[0]
    assert int(icon_1.width() * 0.5) == icon_2.width()
    assert int(icon_1.height() * 0.5) == icon_2.height()


@pytest.mark.skipif(not (has_pythonnet() and sys.platform == 'win32'), reason='requires pythonnet and win32')
def test_to_qicon_dll_exe():
    assert isinstance(convert.to_qicon('C:/Windows/System32/shell32.dll|0'), QtGui.QIcon)
    assert isinstance(convert.to_qicon('shell32.dll|0'), QtGui.QIcon)
    assert isinstance(convert.to_qicon('shell32|0'), QtGui.QIcon)
    with pytest.raises(OSError):
        convert.to_qicon('/shell32|0')  # fails because it appears as though a full path is being specified
    assert isinstance(convert.to_qicon('C:/Windows/explorer.exe|0'), QtGui.QIcon)
    assert isinstance(convert.to_qicon('explorer.exe|0'), QtGui.QIcon)
    assert isinstance(convert.to_qicon('explorer|0'), QtGui.QIcon)
    if sys.maxsize > 2**32:
        # the exe is located at 'C:/Windows/explorer.exe'
        with pytest.raises(OSError):
            convert.to_qicon('C:/Windows/System32/explorer.exe|0')
    else:
        assert isinstance(convert.to_qicon('C:/Windows/System32/explorer.exe|0'), QtGui.QIcon)
    with pytest.raises(OSError, match=r'Requested icon 9999'):
        convert.to_qicon('shell32|9999')  # the maximum icon index should be much less than 9999


@pytest.mark.skipif(not (has_pythonnet() and sys.platform == 'win32'), reason='requires pythonnet and win32')
def test_icon_to_base64_exe():
    assert isinstance(convert.icon_to_base64('explorer|0'), QtCore.QByteArray)

    # index number is < 0
    with pytest.raises(OSError):
        convert.icon_to_base64('explorer|-1')

    # the filename not a DLL in C:/Windows/System32/ nor an EXE in C:/Windows/
    with pytest.raises(OSError):
        convert.icon_to_base64('unknown_default|1')


def test_icon_to_base64():
    # reading from a standard Qt icon does not raise any errors
    assert isinstance(convert.icon_to_base64(QtWidgets.QStyle.SP_TitleBarMenuButton), QtCore.QByteArray)

    # reading from a file does not raise any errors
    icon = convert.to_qicon('gamma.png')
    assert isinstance(convert.icon_to_base64(icon), QtCore.QByteArray)
    assert convert.icon_to_base64(icon).startsWith(b'iVBORw0KGgoAAAA')
    assert convert.icon_to_base64(icon, fmt='PNG').startsWith(b'iVBORw0KGgoAAAA')
    assert convert.icon_to_base64(icon, fmt='BMP').startsWith(b'Qk32jgIAAAAAADY')
    assert convert.icon_to_base64(icon, fmt='JPG').startsWith(b'/9j/4AAQSkZJRgA')
    assert convert.icon_to_base64(icon, fmt='JPEG').startsWith(b'/9j/4AAQSkZJRgA')

    # GIF is not supported
    with pytest.raises(ValueError):
        convert.icon_to_base64(icon, fmt='GIF')

    # the size of 'gamma.png'
    size = QtCore.QSize(191, 291)

    # convert back to a QIcon and check each pixel
    original = icon.pixmap(size).toImage()
    converted = convert.to_qicon(convert.icon_to_base64(icon)).pixmap(size).toImage()
    for x in range(0, size.width()):
        for y in range(0, size.height()):
            rgb_original = original.pixel(x, y)
            rgb_converted = converted.pixel(x, y)
            assert QtGui.QColor(rgb_original).getRgb() == QtGui.QColor(rgb_converted).getRgb()


def test_rescale_icon():
    # the actual size of 'gamma.png'
    size = QtCore.QSize(191, 291)

    icon = convert.to_qicon('gamma.png')
    sizes = icon.availableSizes()
    assert len(sizes) == 1
    assert sizes[0].width() == size.width()
    assert sizes[0].height() == size.height()

    new_size = convert.rescale_icon(icon, 2.6).size()
    assert new_size.width() == int(size.width() * 2.6)
    assert new_size.height() == int(size.height() * 2.6)

    new_size = convert.rescale_icon(icon, 150).size()
    assert new_size.width() == int((150. / float(size.height())) * size.width())
    assert new_size.height() == 150

    new_size = convert.rescale_icon(icon, 300, aspect_mode=Qt.KeepAspectRatioByExpanding).size()
    assert new_size.width() == 300
    assert new_size.height() == int((300. / float(size.width())) * size.height())

    size2 = (150, 200)
    new_size = convert.rescale_icon(icon, size2, aspect_mode=Qt.IgnoreAspectRatio).size()
    assert new_size.width() == size2[0]
    assert new_size.height() == size2[1]
    new_size = convert.rescale_icon(icon, size2).size()
    assert new_size.width() == int(size2[1] * size.width() / float(size.height()))
    assert new_size.height() == size2[1]

    # passing different objects does not raise an error
    if sys.platform == 'win32' and has_pythonnet():
        assert isinstance(convert.rescale_icon('explorer|0', 1.0), QtGui.QPixmap)
    assert isinstance(convert.rescale_icon(QtWidgets.QStyle.SP_TitleBarMenuButton, 1.0), QtGui.QPixmap)
    assert isinstance(convert.rescale_icon(25, 1.0), QtGui.QPixmap)
    assert isinstance(convert.rescale_icon(icon.pixmap(size), 1.0), QtGui.QPixmap)
    assert isinstance(convert.rescale_icon(icon.pixmap(size).toImage(), 1.0), QtGui.QPixmap)

    if sys.platform == 'win32' and has_pythonnet():
        with pytest.raises(TypeError, match=r'Unsupported "size"'):
            convert.rescale_icon('explorer|0', None)

    # if a list/tuple then must contain 2 elements
    for item in [(), [], (256,), [256, ], (256, 256, 256), [256, 256, 256]]:
        with pytest.raises(ValueError, match=r'The size must be in the form (width, height)'):
            convert.rescale_icon(icon, item)


def test_to_qfont():

    assert isinstance(convert.to_qfont(), QtGui.QFont)

    font = QtGui.QFont()
    assert convert.to_qfont(font) is not font
    assert convert.to_qfont(font).isCopyOf(font)

    assert convert.to_qfont(100).pointSize() == 100

    assert convert.to_qfont(12.3).pointSize() == 12
    assert convert.to_qfont(12.3).pointSizeF() == 12.3

    assert convert.to_qfont('Papyrus').family() == 'Papyrus'

    f = convert.to_qfont('Ariel')
    assert f.family() == 'Ariel'
    assert f.weight() == QtGui.QFont.Normal
    assert not f.italic()
<commit_msg>escape brackets in regex<commit_after>import os
import sys
import math
from io import StringIO

import pytest

from msl.qt import application, QtWidgets, QtCore, QtGui, Qt, convert

app = application()


def has_pythonnet():
    try:
        import clr
    except ImportError:
        return False
    else:
        return True


def test_to_qicon():

    assert isinstance(convert.to_qicon(QtGui.QIcon()), QtGui.QIcon)
    assert isinstance(convert.to_qicon(QtGui.QPixmap()), QtGui.QIcon)
    assert isinstance(convert.to_qicon(QtGui.QImage()), QtGui.QIcon)
    assert isinstance(convert.to_qicon(QtWidgets.QStyle.SP_TitleBarMenuButton), QtGui.QIcon)
    assert isinstance(convert.to_qicon(14), QtGui.QIcon)

    base64 = 'iVBORw0KGgoAAAANSUhEUgAAACgAAABCCAYAAAAlkZRRAAAACXBIWXMAAAsTAAALEwEAmpwYAAABpElEQVR' \
             'oge2ZT07CQBSHf29kLXKOsnApBEx7DAl3sT2BZzAx6C1ahYBLFzRxyQ1Q12SeiwoSQonjzMiLmW9Fh+nMlz' \
             '<KEY>' \
             '<KEY>' \
             '<KEY>iMNcfuVWq6+6uOfot4wdo' \
             '<KEY>' \
             'fyea4RP8TiBb+GmDIA0ArF5h/CLUCPx5AKuISAsJJYIV4w8O8hAOj2O9VbTJRNn6YpAHT6nZxQnYun49nmQ' \
             'NTrXcSaKN8t37RRU85AMRvPEgDoXnZT8Pe3un31FXMymTzL/xwrXlA8n2MHdwPYAbB5AAAAAElFTkSuQmCC'

    assert isinstance(convert.to_qicon(QtCore.QByteArray(base64.encode())), QtGui.QIcon)
    assert isinstance(convert.to_qicon(bytearray(base64.encode())), QtGui.QIcon)

    default_size = convert.to_qicon(QtWidgets.QStyle.SP_TitleBarMenuButton).availableSizes()[-1]
    assert isinstance(default_size, QtCore.QSize)

    with pytest.raises(TypeError):
        convert.to_qicon(None)

    with pytest.raises(OSError):
        convert.to_qicon(99999)  # not a valid QStyle.StandardPixmap enum value

    with pytest.raises(OSError):
        convert.to_qicon('this is not an icon')

    assert isinstance(convert.to_qicon(os.path.join(os.path.dirname(__file__), 'gamma.png')), QtGui.QIcon)

    # insert this directory into sys.path and check again
    sys.path.insert(0, os.path.dirname(__file__))
    assert isinstance(convert.to_qicon('gamma.png'), QtGui.QIcon)

    icon_1 = convert.to_qicon('gamma.png').availableSizes()[0]
    icon_2 = convert.to_qicon('gamma.png', size=0.5).availableSizes()[0]
    assert int(icon_1.width() * 0.5) == icon_2.width()
    assert int(icon_1.height() * 0.5) == icon_2.height()


@pytest.mark.skipif(not (has_pythonnet() and sys.platform == 'win32'), reason='requires pythonnet and win32')
def test_to_qicon_dll_exe():
    assert isinstance(convert.to_qicon('C:/Windows/System32/shell32.dll|0'), QtGui.QIcon)
    assert isinstance(convert.to_qicon('shell32.dll|0'), QtGui.QIcon)
    assert isinstance(convert.to_qicon('shell32|0'), QtGui.QIcon)
    with pytest.raises(OSError):
        convert.to_qicon('/shell32|0')  # fails because it appears as though a full path is being specified
    assert isinstance(convert.to_qicon('C:/Windows/explorer.exe|0'), QtGui.QIcon)
    assert isinstance(convert.to_qicon('explorer.exe|0'), QtGui.QIcon)
    assert isinstance(convert.to_qicon('explorer|0'), QtGui.QIcon)
    if sys.maxsize > 2**32:
        # the exe is located at 'C:/Windows/explorer.exe'
        with pytest.raises(OSError):
            convert.to_qicon('C:/Windows/System32/explorer.exe|0')
    else:
        assert isinstance(convert.to_qicon('C:/Windows/System32/explorer.exe|0'), QtGui.QIcon)
    with pytest.raises(OSError, match=r'Requested icon 9999'):
        convert.to_qicon('shell32|9999')  # the maximum icon index should be much less than 9999


@pytest.mark.skipif(not (has_pythonnet() and sys.platform == 'win32'), reason='requires pythonnet and win32')
def test_icon_to_base64_exe():
    assert isinstance(convert.icon_to_base64('explorer|0'), QtCore.QByteArray)

    # index number is < 0
    with pytest.raises(OSError):
        convert.icon_to_base64('explorer|-1')

    # the filename not a DLL in C:/Windows/System32/ nor an EXE in C:/Windows/
    with pytest.raises(OSError):
        convert.icon_to_base64('unknown_default|1')


def test_icon_to_base64():
    # reading from a standard Qt icon does not raise any errors
    assert isinstance(convert.icon_to_base64(QtWidgets.QStyle.SP_TitleBarMenuButton), QtCore.QByteArray)

    # reading from a file does not raise any errors
    icon = convert.to_qicon('gamma.png')
    assert isinstance(convert.icon_to_base64(icon), QtCore.QByteArray)
    assert convert.icon_to_base64(icon).startsWith(b'iVBORw0KGgoAAAA')
    assert convert.icon_to_base64(icon, fmt='PNG').startsWith(b'iVBORw0KGgoAAAA')
    assert convert.icon_to_base64(icon, fmt='BMP').startsWith(b'Qk32jgIAAAAAADY')
    assert convert.icon_to_base64(icon, fmt='JPG').startsWith(b'/9j/4AAQSkZJRgA')
    assert convert.icon_to_base64(icon, fmt='JPEG').startsWith(b'/9j/4AAQSkZJRgA')

    # GIF is not supported
    with pytest.raises(ValueError):
        convert.icon_to_base64(icon, fmt='GIF')

    # the size of 'gamma.png'
    size = QtCore.QSize(191, 291)

    # convert back to a QIcon and check each pixel
    original = icon.pixmap(size).toImage()
    converted = convert.to_qicon(convert.icon_to_base64(icon)).pixmap(size).toImage()
    for x in range(0, size.width()):
        for y in range(0, size.height()):
            rgb_original = original.pixel(x, y)
            rgb_converted = converted.pixel(x, y)
            assert QtGui.QColor(rgb_original).getRgb() == QtGui.QColor(rgb_converted).getRgb()


def test_rescale_icon():
    # the actual size of 'gamma.png'
    size = QtCore.QSize(191, 291)

    icon = convert.to_qicon('gamma.png')
    sizes = icon.availableSizes()
    assert len(sizes) == 1
    assert sizes[0].width() == size.width()
    assert sizes[0].height() == size.height()

    new_size = convert.rescale_icon(icon, 2.6).size()
    assert new_size.width() == int(size.width() * 2.6)
    assert new_size.height() == int(size.height() * 2.6)

    new_size = convert.rescale_icon(icon, 150).size()
    assert new_size.width() == int((150. / float(size.height())) * size.width())
    assert new_size.height() == 150

    new_size = convert.rescale_icon(icon, 300, aspect_mode=Qt.KeepAspectRatioByExpanding).size()
    assert new_size.width() == 300
    assert new_size.height() == int((300. / float(size.width())) * size.height())

    size2 = (150, 200)
    new_size = convert.rescale_icon(icon, size2, aspect_mode=Qt.IgnoreAspectRatio).size()
    assert new_size.width() == size2[0]
    assert new_size.height() == size2[1]
    new_size = convert.rescale_icon(icon, size2).size()
    assert new_size.width() == int(size2[1] * size.width() / float(size.height()))
    assert new_size.height() == size2[1]

    # passing different objects does not raise an error
    if sys.platform == 'win32' and has_pythonnet():
        assert isinstance(convert.rescale_icon('explorer|0', 1.0), QtGui.QPixmap)
    assert isinstance(convert.rescale_icon(QtWidgets.QStyle.SP_TitleBarMenuButton, 1.0), QtGui.QPixmap)
    assert isinstance(convert.rescale_icon(25, 1.0), QtGui.QPixmap)
    assert isinstance(convert.rescale_icon(icon.pixmap(size), 1.0), QtGui.QPixmap)
    assert isinstance(convert.rescale_icon(icon.pixmap(size).toImage(), 1.0), QtGui.QPixmap)

    if sys.platform == 'win32' and has_pythonnet():
        with pytest.raises(TypeError, match=r'Unsupported "size"'):
            convert.rescale_icon('explorer|0', None)

    # if a list/tuple then must contain 2 elements
    for item in [(), [], (256,), [256, ], (256, 256, 256), [256, 256, 256]]:
        with pytest.raises(ValueError, match=r'The size must be in the form \(width, height\)'):
            convert.rescale_icon(icon, item)


def test_to_qfont():

    assert isinstance(convert.to_qfont(), QtGui.QFont)

    font = QtGui.QFont()
    assert convert.to_qfont(font) is not font
    assert convert.to_qfont(font).isCopyOf(font)

    assert convert.to_qfont(100).pointSize() == 100

    assert convert.to_qfont(12.3).pointSize() == 12
    assert convert.to_qfont(12.3).pointSizeF() == 12.3

    assert convert.to_qfont('Papyrus').family() == 'Papyrus'

    f = convert.to_qfont('Ariel')
    assert f.family() == 'Ariel'
    assert f.weight() == QtGui.QFont.Normal
    assert not f.italic()

{'fraction_non_alphanumeric': 0.13245113512201043, 'fraction_numerical': 0.03557120310792764, 'mean_word_length': 4.022865853658536, 'pattern_counts': {'":': 0, '<': 12, '<?xml version=': 0, '>': 12, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '474930', 'n_tokens_mistral': 6396, 'n_tokens_neox': 5970, 'n_words': 1039}