<commit_before>import datetime
from unittest import mock

import pytest

from aiohttp import helpers

def test_parse_mimetype_1():
    assert helpers.parse_mimetype('') == ('', '', '', {})

def test_parse_mimetype_2():
    assert helpers.parse_mimetype('*') == ('*', '*', '', {})

def test_parse_mimetype_3():
    assert (helpers.parse_mimetype('application/json') ==
            ('application', 'json', '', {}))

def test_parse_mimetype_4():
    assert (
        helpers.parse_mimetype('application/json;  charset=utf-8') ==
        ('application', 'json', '', {'charset': 'utf-8'}))

def test_parse_mimetype_5():
    assert (
        helpers.parse_mimetype('''application/json; charset=utf-8;''') ==
        ('application', 'json', '', {'charset': 'utf-8'}))

def test_parse_mimetype_6():
    assert(
        helpers.parse_mimetype('ApPlIcAtIoN/JSON;ChaRseT="UTF-8"') ==
        ('application', 'json', '', {'charset': 'UTF-8'}))

def test_parse_mimetype_7():
    assert (
        helpers.parse_mimetype('application/rss+xml') ==
        ('application', 'rss', 'xml', {}))

def test_parse_mimetype_8():
    assert (
        helpers.parse_mimetype('text/plain;base64') ==
        ('text', 'plain', '', {'base64': ''}))

def test_basic_auth1():
    # missing password here
    with pytest.raises(ValueError):
        helpers.BasicAuth(None)

def test_basic_auth2():
    with pytest.raises(ValueError):
        helpers.BasicAuth('nkim', None)

def test_basic_auth3():
    auth = helpers.BasicAuth('nkim')
    assert auth.login == 'nkim'
    assert auth.password == ''

def test_basic_auth4():
    auth = helpers.BasicAuth('nkim', 'pwd')
    assert auth.login == 'nkim'
    assert auth.password == 'pwd'
    assert auth.encode() == 'Basic bmtpbTpwd2Q='

def test_basic_auth_decode():
    auth = helpers.BasicAuth.decode('Basic bmtpbTpwd2Q=')
    assert auth.login == 'nkim'
    assert auth.password == 'pwd'

def test_basic_auth_invalid():
    with pytest.raises(ValueError):
        helpers.BasicAuth.decode('bmtpbTpwd2Q=')

def test_basic_auth_decode_not_basic():
    with pytest.raises(ValueError):
        helpers.BasicAuth.decode('Complex bmtpbTpwd2Q=')

def test_basic_auth_decode_bad_base64():
    with pytest.raises(ValueError):
        helpers.BasicAuth.decode('Basic bmtpbTpwd2Q')

def test_invalid_formdata_params():
    with pytest.raises(TypeError):
        helpers.FormData('asdasf')

def test_invalid_formdata_params2():
    with pytest.raises(TypeError):
        helpers.FormData('as')  # 2-char str is not allowed

def test_invalid_formdata_content_type():
    form = helpers.FormData()
    invalid_vals = [0, 0.1, {}, [], b'foo']
    for invalid_val in invalid_vals:
        with pytest.raises(TypeError):
            form.add_field('foo', 'bar', content_type=invalid_val)

def test_invalid_formdata_filename():
    form = helpers.FormData()
    invalid_vals = [0, 0.1, {}, [], b'foo']
    for invalid_val in invalid_vals:
        with pytest.raises(TypeError):
            form.add_field('foo', 'bar', filename=invalid_val)

def test_invalid_formdata_content_transfer_encoding():
    form = helpers.FormData()
    invalid_vals = [0, 0.1, {}, [], b'foo']
    for invalid_val in invalid_vals:
        with pytest.raises(TypeError):
            form.add_field('foo',
                           'bar',
                           content_transfer_encoding=invalid_val)

def test_access_logger_format():
    log_format = '%T {%{SPAM}e} "%{ETag}o" %X {X} %%P %{FOO_TEST}e %{FOO1}e'
    mock_logger = mock.Mock()
    access_logger = helpers.AccessLogger(mock_logger, log_format)
    expected = '%s {%s} "%s" %%X {X} %%%s %s %s'
    assert expected == access_logger._log_format

def test_access_logger_atoms(mocker):
    mock_datetime = mocker.patch("aiohttp.helpers.datetime")
    mock_getpid = mocker.patch("os.getpid")
    utcnow = datetime.datetime(1843, 1, 1, 0, 0)
    mock_datetime.datetime.utcnow.return_value = utcnow
    mock_getpid.return_value = 42
    log_format = '%a %t %P %l %u %r %s %b %O %T %Tf %D'
    mock_logger = mock.Mock()
    access_logger = helpers.AccessLogger(mock_logger, log_format)
    message = mock.Mock(headers={}, method="GET", path="/path", version=(1, 1))
    environ = {}
    response = mock.Mock(headers={}, output_length=123,
                         body_length=42, status=200)
    transport = mock.Mock()
    transport.get_extra_info.return_value = ("127.0.0.2", 1234)
    access_logger.log(message, environ, response, transport, 3.1415926)
    assert not mock_logger.exception.called
    expected = ('127.0.0.2 [01/Jan/1843:00:00:00 +0000] <42> - - '
                'GET /path HTTP/1.1 200 42 123 3 3.141593 3141593')
    mock_logger.info.assert_called_with(expected)

def test_access_logger_dicts():
    log_format = '%{User-Agent}i %{Content-Length}o %{SPAM}e %{None}i'
    mock_logger = mock.Mock()
    access_logger = helpers.AccessLogger(mock_logger, log_format)
    message = mock.Mock(headers={"User-Agent": "Mock/1.0"}, version=(1, 1))
    environ = {"SPAM": "EGGS"}
    response = mock.Mock(headers={"Content-Length": 123})
    transport = mock.Mock()
    transport.get_extra_info.return_value = ("127.0.0.2", 1234)
    access_logger.log(message, environ, response, transport, 0.0)
    assert not mock_logger.error.called
    expected = 'Mock/1.0 123 EGGS -'
    mock_logger.info.assert_called_with(expected)

def test_access_logger_unix_socket():
    log_format = '|%a|'
    mock_logger = mock.Mock()
    access_logger = helpers.AccessLogger(mock_logger, log_format)
    message = mock.Mock(headers={"User-Agent": "Mock/1.0"}, version=(1, 1))
    environ = {}
    response = mock.Mock()
    transport = mock.Mock()
    transport.get_extra_info.return_value = ""
    access_logger.log(message, environ, response, transport, 0.0)
    assert not mock_logger.error.called
    expected = '||'
    mock_logger.info.assert_called_with(expected)

def test_logger_no_message_and_environ():
    mock_logger = mock.Mock()
    mock_transport = mock.Mock()
    mock_transport.get_extra_info.return_value = ("127.0.0.3", 0)
    access_logger = helpers.AccessLogger(mock_logger,
                                         "%r %{FOOBAR}e %{content-type}i")
    access_logger.log(None, None, None, mock_transport, 0.0)
    mock_logger.info.assert_called_with("- - (no headers)")

def test_reify():
    class A:
        @helpers.reify
        def prop(self):
            return 1

    a = A()
    assert 1 == a.prop

def test_reify_class():
    class A:
        @helpers.reify
        def prop(self):
            """Docstring."""
            return 1

    assert isinstance(A.prop, helpers.reify)
    assert 'Docstring.' == A.prop.__doc__

def test_reify_assignment():
    class A:
        @helpers.reify
        def prop(self):
            return 1

    a = A()

    with pytest.raises(AttributeError):
        a.prop = 123

def test_create_future_with_new_loop():
    # We should use the new create_future() if it's available.
    mock_loop = mock.Mock()
    expected = 'hello'
    mock_loop.create_future.return_value = expected
    assert expected == helpers.create_future(mock_loop)

def test_create_future_with_old_loop(mocker):
    MockFuture = mocker.patch('asyncio.Future')
    # The old loop (without create_future()) should just have a Future object
    # wrapped around it.
    mock_loop = mock.Mock()
    del mock_loop.create_future

    expected = 'hello'
    MockFuture.return_value = expected

    future = helpers.create_future(mock_loop)
    MockFuture.assert_called_with(loop=mock_loop)
    assert expected == future

def test_is_ip_address():
    assert helpers.is_ip_address("127.0.0.1")
    assert helpers.is_ip_address("::1")
    assert helpers.is_ip_address("FE80:0000:0000:0000:0202:B3FF:FE1E:8329")

    # Hostnames
    assert not helpers.is_ip_address("localhost")
    assert not helpers.is_ip_address("www.example.com")

    # Out of range
    assert not helpers.is_ip_address("999.999.999.999")
    # Contain a port
    assert not helpers.is_ip_address("127.0.0.1:80")
    assert not helpers.is_ip_address("[2001:db8:0:1]:80")
    # Too many "::"
    assert not helpers.is_ip_address("1200::AB00:1234::2552:7777:1313")

def test_is_ip_address_bytes():
    assert helpers.is_ip_address(b"127.0.0.1")
    assert helpers.is_ip_address(b"::1")
    assert helpers.is_ip_address(b"FE80:0000:0000:0000:0202:B3FF:FE1E:8329")

    # Hostnames
    assert not helpers.is_ip_address(b"localhost")
    assert not helpers.is_ip_address(b"www.example.com")

    # Out of range
    assert not helpers.is_ip_address(b"999.999.999.999")
    # Contain a port
    assert not helpers.is_ip_address(b"127.0.0.1:80")
    assert not helpers.is_ip_address(b"[2001:db8:0:1]:80")
    # Too many "::"
    assert not helpers.is_ip_address(b"1200::AB00:1234::2552:7777:1313")

def test_ip_addresses():
    ip_addresses = [
        '0.0.0.0',
        '127.0.0.1',
        '255.255.255.255',
        '0:0:0:0:0:0:0:0',
        'FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF',
        '00AB:0002:3008:8CFD:00AB:0002:3008:8CFD',
        '00ab:0002:3008:8cfd:00ab:0002:3008:8cfd',
        'AB:02:3008:8CFD:AB:02:3008:8CFD',
        'AB:02:3008:8CFD::02:3008:8CFD',
        '::',
        '1::1',
    ]
    for address in ip_addresses:
        assert helpers.is_ip_address(address)

def test_host_addresses():
    hosts = [
        'www.four.part.host'
        'www.python.org',
        'foo.bar',
        'localhost',
    ]
    for host in hosts:
        assert not helpers.is_ip_address(host)

def test_is_ip_address_invalid_type():
    with pytest.raises(TypeError):
        helpers.is_ip_address(123)

    with pytest.raises(TypeError):
        helpers.is_ip_address(object())
<commit_msg>Improve coverage<commit_after>import datetime
from unittest import mock

import pytest

from aiohttp import helpers

def test_parse_mimetype_1():
    assert helpers.parse_mimetype('') == ('', '', '', {})

def test_parse_mimetype_2():
    assert helpers.parse_mimetype('*') == ('*', '*', '', {})

def test_parse_mimetype_3():
    assert (helpers.parse_mimetype('application/json') ==
            ('application', 'json', '', {}))

def test_parse_mimetype_4():
    assert (
        helpers.parse_mimetype('application/json;  charset=utf-8') ==
        ('application', 'json', '', {'charset': 'utf-8'}))

def test_parse_mimetype_5():
    assert (
        helpers.parse_mimetype('''application/json; charset=utf-8;''') ==
        ('application', 'json', '', {'charset': 'utf-8'}))

def test_parse_mimetype_6():
    assert(
        helpers.parse_mimetype('ApPlIcAtIoN/JSON;ChaRseT="UTF-8"') ==
        ('application', 'json', '', {'charset': 'UTF-8'}))

def test_parse_mimetype_7():
    assert (
        helpers.parse_mimetype('application/rss+xml') ==
        ('application', 'rss', 'xml', {}))

def test_parse_mimetype_8():
    assert (
        helpers.parse_mimetype('text/plain;base64') ==
        ('text', 'plain', '', {'base64': ''}))

def test_basic_auth1():
    # missing password here
    with pytest.raises(ValueError):
        helpers.BasicAuth(None)

def test_basic_auth2():
    with pytest.raises(ValueError):
        helpers.BasicAuth('nkim', None)

def test_basic_auth3():
    auth = helpers.BasicAuth('nkim')
    assert auth.login == 'nkim'
    assert auth.password == ''

def test_basic_auth4():
    auth = helpers.BasicAuth('nkim', 'pwd')
    assert auth.login == 'nkim'
    assert auth.password == 'pwd'
    assert auth.encode() == 'Basic bmtpbTpwd2Q='

def test_basic_auth_decode():
    auth = helpers.BasicAuth.decode('Basic bmtpbTpwd2Q=')
    assert auth.login == 'nkim'
    assert auth.password == 'pwd'

def test_basic_auth_invalid():
    with pytest.raises(ValueError):
        helpers.BasicAuth.decode('bmtpbTpwd2Q=')

def test_basic_auth_decode_not_basic():
    with pytest.raises(ValueError):
        helpers.BasicAuth.decode('Complex bmtpbTpwd2Q=')

def test_basic_auth_decode_bad_base64():
    with pytest.raises(ValueError):
        helpers.BasicAuth.decode('Basic bmtpbTpwd2Q')

def test_invalid_formdata_params():
    with pytest.raises(TypeError):
        helpers.FormData('asdasf')

def test_invalid_formdata_params2():
    with pytest.raises(TypeError):
        helpers.FormData('as')  # 2-char str is not allowed

def test_invalid_formdata_content_type():
    form = helpers.FormData()
    invalid_vals = [0, 0.1, {}, [], b'foo']
    for invalid_val in invalid_vals:
        with pytest.raises(TypeError):
            form.add_field('foo', 'bar', content_type=invalid_val)

def test_invalid_formdata_filename():
    form = helpers.FormData()
    invalid_vals = [0, 0.1, {}, [], b'foo']
    for invalid_val in invalid_vals:
        with pytest.raises(TypeError):
            form.add_field('foo', 'bar', filename=invalid_val)

def test_invalid_formdata_content_transfer_encoding():
    form = helpers.FormData()
    invalid_vals = [0, 0.1, {}, [], b'foo']
    for invalid_val in invalid_vals:
        with pytest.raises(TypeError):
            form.add_field('foo',
                           'bar',
                           content_transfer_encoding=invalid_val)

# ------------- access logger -------------------------

def test_access_logger_format():
    log_format = '%T {%{SPAM}e} "%{ETag}o" %X {X} %%P %{FOO_TEST}e %{FOO1}e'
    mock_logger = mock.Mock()
    access_logger = helpers.AccessLogger(mock_logger, log_format)
    expected = '%s {%s} "%s" %%X {X} %%%s %s %s'
    assert expected == access_logger._log_format

def test_access_logger_atoms(mocker):
    mock_datetime = mocker.patch("aiohttp.helpers.datetime")
    mock_getpid = mocker.patch("os.getpid")
    utcnow = datetime.datetime(1843, 1, 1, 0, 0)
    mock_datetime.datetime.utcnow.return_value = utcnow
    mock_getpid.return_value = 42
    log_format = '%a %t %P %l %u %r %s %b %O %T %Tf %D'
    mock_logger = mock.Mock()
    access_logger = helpers.AccessLogger(mock_logger, log_format)
    message = mock.Mock(headers={}, method="GET", path="/path", version=(1, 1))
    environ = {}
    response = mock.Mock(headers={}, output_length=123,
                         body_length=42, status=200)
    transport = mock.Mock()
    transport.get_extra_info.return_value = ("127.0.0.2", 1234)
    access_logger.log(message, environ, response, transport, 3.1415926)
    assert not mock_logger.exception.called
    expected = ('127.0.0.2 [01/Jan/1843:00:00:00 +0000] <42> - - '
                'GET /path HTTP/1.1 200 42 123 3 3.141593 3141593')
    mock_logger.info.assert_called_with(expected)

def test_access_logger_dicts():
    log_format = '%{User-Agent}i %{Content-Length}o %{SPAM}e %{None}i'
    mock_logger = mock.Mock()
    access_logger = helpers.AccessLogger(mock_logger, log_format)
    message = mock.Mock(headers={"User-Agent": "Mock/1.0"}, version=(1, 1))
    environ = {"SPAM": "EGGS"}
    response = mock.Mock(headers={"Content-Length": 123})
    transport = mock.Mock()
    transport.get_extra_info.return_value = ("127.0.0.2", 1234)
    access_logger.log(message, environ, response, transport, 0.0)
    assert not mock_logger.error.called
    expected = 'Mock/1.0 123 EGGS -'
    mock_logger.info.assert_called_with(expected)

def test_access_logger_unix_socket():
    log_format = '|%a|'
    mock_logger = mock.Mock()
    access_logger = helpers.AccessLogger(mock_logger, log_format)
    message = mock.Mock(headers={"User-Agent": "Mock/1.0"}, version=(1, 1))
    environ = {}
    response = mock.Mock()
    transport = mock.Mock()
    transport.get_extra_info.return_value = ""
    access_logger.log(message, environ, response, transport, 0.0)
    assert not mock_logger.error.called
    expected = '||'
    mock_logger.info.assert_called_with(expected)

def test_logger_no_message_and_environ():
    mock_logger = mock.Mock()
    mock_transport = mock.Mock()
    mock_transport.get_extra_info.return_value = ("127.0.0.3", 0)
    access_logger = helpers.AccessLogger(mock_logger,
                                         "%r %{FOOBAR}e %{content-type}i")
    access_logger.log(None, None, None, mock_transport, 0.0)
    mock_logger.info.assert_called_with("- - (no headers)")

def test_logger_internal_error():
    mock_logger = mock.Mock()
    mock_transport = mock.Mock()
    mock_transport.get_extra_info.return_value = ("127.0.0.3", 0)
    access_logger = helpers.AccessLogger(mock_logger, "%D")
    access_logger.log(None, None, None, mock_transport, 'invalid')
    mock_logger.exception.assert_called_with("Error in logging")

# ----------------------------------------------------------

def test_reify():
    class A:
        @helpers.reify
        def prop(self):
            return 1

    a = A()
    assert 1 == a.prop

def test_reify_class():
    class A:
        @helpers.reify
        def prop(self):
            """Docstring."""
            return 1

    assert isinstance(A.prop, helpers.reify)
    assert 'Docstring.' == A.prop.__doc__

def test_reify_assignment():
    class A:
        @helpers.reify
        def prop(self):
            return 1

    a = A()

    with pytest.raises(AttributeError):
        a.prop = 123

def test_create_future_with_new_loop():
    # We should use the new create_future() if it's available.
    mock_loop = mock.Mock()
    expected = 'hello'
    mock_loop.create_future.return_value = expected
    assert expected == helpers.create_future(mock_loop)

def test_create_future_with_old_loop(mocker):
    MockFuture = mocker.patch('asyncio.Future')
    # The old loop (without create_future()) should just have a Future object
    # wrapped around it.
    mock_loop = mock.Mock()
    del mock_loop.create_future

    expected = 'hello'
    MockFuture.return_value = expected

    future = helpers.create_future(mock_loop)
    MockFuture.assert_called_with(loop=mock_loop)
    assert expected == future

# ----------------------------------- is_ip_address() ----------------------

def test_is_ip_address():
    assert helpers.is_ip_address("127.0.0.1")
    assert helpers.is_ip_address("::1")
    assert helpers.is_ip_address("FE80:0000:0000:0000:0202:B3FF:FE1E:8329")

    # Hostnames
    assert not helpers.is_ip_address("localhost")
    assert not helpers.is_ip_address("www.example.com")

    # Out of range
    assert not helpers.is_ip_address("999.999.999.999")
    # Contain a port
    assert not helpers.is_ip_address("127.0.0.1:80")
    assert not helpers.is_ip_address("[2001:db8:0:1]:80")
    # Too many "::"
    assert not helpers.is_ip_address("1200::AB00:1234::2552:7777:1313")

def test_is_ip_address_bytes():
    assert helpers.is_ip_address(b"127.0.0.1")
    assert helpers.is_ip_address(b"::1")
    assert helpers.is_ip_address(b"FE80:0000:0000:0000:0202:B3FF:FE1E:8329")

    # Hostnames
    assert not helpers.is_ip_address(b"localhost")
    assert not helpers.is_ip_address(b"www.example.com")

    # Out of range
    assert not helpers.is_ip_address(b"999.999.999.999")
    # Contain a port
    assert not helpers.is_ip_address(b"127.0.0.1:80")
    assert not helpers.is_ip_address(b"[2001:db8:0:1]:80")
    # Too many "::"
    assert not helpers.is_ip_address(b"1200::AB00:1234::2552:7777:1313")

def test_ip_addresses():
    ip_addresses = [
        '0.0.0.0',
        '127.0.0.1',
        '255.255.255.255',
        '0:0:0:0:0:0:0:0',
        'FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF',
        '00AB:0002:3008:8CFD:00AB:0002:3008:8CFD',
        '00ab:0002:3008:8cfd:00ab:0002:3008:8cfd',
        'AB:02:3008:8CFD:AB:02:3008:8CFD',
        'AB:02:3008:8CFD::02:3008:8CFD',
        '::',
        '1::1',
    ]
    for address in ip_addresses:
        assert helpers.is_ip_address(address)

def test_host_addresses():
    hosts = [
        'www.four.part.host'
        'www.python.org',
        'foo.bar',
        'localhost',
    ]
    for host in hosts:
        assert not helpers.is_ip_address(host)

def test_is_ip_address_invalid_type():
    with pytest.raises(TypeError):
        helpers.is_ip_address(123)

    with pytest.raises(TypeError):
        helpers.is_ip_address(object())
<|endoftext|>


<commit_before>import io
import sys

import pytest

from rich import inspect
from rich.console import Console

skip_py36 = pytest.mark.skipif(
    sys.version_info.minor == 6 and sys.version_info.major == 3,
    reason="rendered differently on py3.6",
)

class InspectError(Exception):
    def __str__(self) -> str:
        return "INSPECT ERROR"

class Foo:
    """Foo test

    Second line
    """

    def __init__(self, foo: int) -> None:
        """constructor docs."""
        self.foo = foo

    @property
    def broken(self):
        raise InspectError()

    def method(self, a, b) -> str:
        """Multi line

        docs.
        """
        return "test"

    def __dir__(self):
        return ["__init__", "broken", "method"]

@skip_py36
def test_render():
    console = Console(width=100, file=io.StringIO(), legacy_windows=False)

    foo = Foo("hello")
    inspect(foo, console=console, all=True)
    result = console.file.getvalue()
    print(repr(result))
    expected = "╭────────────── <class 'tests.test_inspect.Foo'> ──────────────╮\n│ Foo test                                                     │\n│                                                              │\n│   broken = InspectError()                                    │\n│ __init__ = def __init__(foo: int) -> None: constructor docs. │\n│   method = def method(a, b) -> str: Multi line               │\n╰──────────────────────────────────────────────────────────────╯\n"
    assert expected == result
<commit_msg>added tests for inspect<commit_after>import io
import sys

import pytest

from rich import inspect
from rich.console import Console

skip_py36 = pytest.mark.skipif(
    sys.version_info.minor == 6 and sys.version_info.major == 3,
    reason="rendered differently on py3.6",
)

def render(obj, methods=False) -> str:
    console = Console(file=io.StringIO(), width=50, legacy_windows=False)
    inspect(obj, console=console, methods=methods)
    return console.file.getvalue()

class InspectError(Exception):
    def __str__(self) -> str:
        return "INSPECT ERROR"

class Foo:
    """Foo test

    Second line
    """

    def __init__(self, foo: int) -> None:
        """constructor docs."""
        self.foo = foo

    @property
    def broken(self):
        raise InspectError()

    def method(self, a, b) -> str:
        """Multi line

        docs.
        """
        return "test"

    def __dir__(self):
        return ["__init__", "broken", "method"]

@skip_py36
def test_render():
    console = Console(width=100, file=io.StringIO(), legacy_windows=False)

    foo = Foo("hello")
    inspect(foo, console=console, all=True)
    result = console.file.getvalue()
    print(repr(result))
    expected = "╭────────────── <class 'tests.test_inspect.Foo'> ──────────────╮\n│ Foo test                                                     │\n│                                                              │\n│   broken = InspectError()                                    │\n│ __init__ = def __init__(foo: int) -> None: constructor docs. │\n│   method = def method(a, b) -> str: Multi line               │\n╰──────────────────────────────────────────────────────────────╯\n"
    assert expected == result

def test_inspect_text():
    from rich.text import Text

    t = Text("Hello, World")

    expected = (
        "╭─ <class 'rich.text.Text'> ─╮\n"
        "│ Text with color / style.   │\n"
        "│                            │\n"
        "│ cell_len = 12              │\n"
        "│      end = '\\n'            │\n"
        "│  justify = None            │\n"
        "│  no_wrap = None            │\n"
        "│ overflow = None            │\n"
        "│    plain = 'Hello, World'  │\n"
        "│    spans = []              │\n"
        "│    style = ''              │\n"
        "│ tab_size = 8               │\n"
        "╰────────────────────────────╯\n"
    )

    assert expected == render(t)

def test_inspect_empty_dict():

    expected = (
        "╭──────────────── <class 'dict'> ────────────────╮\n"
        "│ dict() -> new empty dictionary                 │\n"
        "│ dict(mapping) -> new dictionary initialized    │\n"
        "│ from a mapping object's                        │\n"
        "│     (key, value) pairs                         │\n"
        "│ dict(iterable) -> new dictionary initialized   │\n"
        "│ as if via:                                     │\n"
        "│     d = {}                                     │\n"
        "│     for k, v in iterable:                      │\n"
        "│         d[k] = v                               │\n"
        "│ dict(**kwargs) -> new dictionary initialized   │\n"
        "│ with the name=value pairs                      │\n"
        "│     in the keyword argument list.  For         │\n"
        "│ example:  dict(one=1, two=2)                   │\n"
        "│                                                │\n"
        "│ 30 attribute(s) not shown. Use                 │\n"
        "│ inspect(<OBJECT>, all=True) to see all         │\n"
        "│ attributes.                                    │\n"
        "╰────────────────────────────────────────────────╯\n"
    )
    assert expected == render({})

def test_inspect_builtin_function():

    expected = (
        "╭────────── <built-in function print> ───────────╮\n"
        "│ def print(...)                                 │\n"
        "│                                                │\n"
        "│ print(value, ..., sep=' ', end='\\n',           │\n"
        "│ file=sys.stdout, flush=False)                  │\n"
        "│                                                │\n"
        "│ 29 attribute(s) not shown. Use                 │\n"
        "│ inspect(<OBJECT>, all=True) to see all         │\n"
        "│ attributes.                                    │\n"
        "╰────────────────────────────────────────────────╯\n"
    )
    assert expected == render(print)

def test_inspect_integer():

    expected = (
        "╭────── <class 'int'> ───────╮\n"
        "│ int([x]) -> integer        │\n"
        "│ int(x, base=10) -> integer │\n"
        "│                            │\n"
        "│ denominator = 1            │\n"
        "│        imag = 0            │\n"
        "│   numerator = 1            │\n"
        "│        real = 1            │\n"
        "╰────────────────────────────╯\n"
    )
    assert expected == render(1)

def test_inspect_integer_with_methods():

    expected = (
        "╭──────────────── <class 'int'> ─────────────────╮\n"
        "│ int([x]) -> integer                            │\n"
        "│ int(x, base=10) -> integer                     │\n"
        "│                                                │\n"
        "│      denominator = 1                           │\n"
        "│             imag = 0                           │\n"
        "│        numerator = 1                           │\n"
        "│             real = 1                           │\n"
        "│ as_integer_ratio = def as_integer_ratio():     │\n"
        "│                    Return integer ratio.       │\n"
        "│       bit_length = def bit_length(): Number of │\n"
        "│                    bits necessary to represent │\n"
        "│                    self in binary.             │\n"
        "│        conjugate = def conjugate(...) Returns  │\n"
        "│                    self, the complex conjugate │\n"
        "│                    of any int.                 │\n"
        "│       from_bytes = def from_bytes(bytes,       │\n"
        "│                    byteorder, *,               │\n"
        "│                    signed=False): Return the   │\n"
        "│                    integer represented by the  │\n"
        "│                    given array of bytes.       │\n"
        "│         to_bytes = def to_bytes(length,        │\n"
        "│                    byteorder, *,               │\n"
        "│                    signed=False): Return an    │\n"
        "│                    array of bytes representing │\n"
        "│                    an integer.                 │\n"
        "╰────────────────────────────────────────────────╯\n"
    )
    assert expected == render(1, methods=True)
<|endoftext|>


<commit_before>#!/usr/bin/env python
"""
Test installation
"""
import os
import subprocess
import tempfile

GITURL = "https://github.com/DarkEnergySurvey/ugali"
GITURL = "https://github.com/kadrlica/ugali"

def call_cmd(cmd):
    print(cmd)
    subprocess.check_call(cmd,shell=True)

def call_chdir(path):
    if not os.path.isdir(path):
        raise Exception("Directory does not exist: %s"%path)
    print('os.chdir(%s)'%path)
    os.chdir(path)

def setup_env():
    path='./lib/python2.7/site-packages/'
    call_cmd("mkdir -p %s"%path)
    env = 'HOME=.; PYTHONPATH=$PYTHONPATH:%s;'%path
    return path, env

def call_setup_py():
    path,env = setup_env()
    #cmd = env +' python setup.py -q install -f --prefix=.'
    #cmd = env +' python setup.py -v install -f --user'
    call_cmd(cmd)
    #call_cmd(cmd + ' --isochrones')
    #call_cmd(cmd + ' --isochrones --isochrones-path=./tmp')

def call_pip():
    path,env = setup_env()
    cmd = env + 'pip install --user --no-deps -I  ugali'
    call_cmd(cmd)
    #call_cmd(cmd +' --install-option "--isochrones"')
    #call_cmd(cmd +' --install-option "--isochrones" --install-option="--isochrones-path=./tmp" ')
    #call_cmd('pip uninstall ugali')

def test_git_install():
    cwd = os.getcwd()
    tempdir = tempfile.mkdtemp()
    call_chdir(tempdir)
    call_cmd('git clone %s.git'%GITURL)
    call_chdir('ugali')
    call_setup_py()
    call_cmd('rm -rf %s'%tempdir)
    call_chdir(cwd)

#def test_zip_install():
#    tempdir = tempfile.mkdtemp()
#    call_chdir(tempdir)
#    call_cmd('wget %s/archive/master.zip'%GITURL)
#    call_cmd('unzip -q master.zip')
#    call_chdir('ugali-master')
#    call_setup_py()
#    call_cmd('rm -rf %s'%tempdir)
#
#def test_pip_install():
#    tempdir = tempfile.mkdtemp()
#    call_chdir(tempdir)
#    call_pip()
#    call_cmd('rm -rf %s'%tempdir)

if __name__ == "__main__":
    import argparse
    parser = argparse.ArgumentParser(description=__doc__)
    args = parser.parse_args()

    #test_git_install()
    #test_zip_install()
    #test_pip_install()
<commit_msg>playing with test_install<commit_after>#!/usr/bin/env python
"""
Test installation
"""
import os
import subprocess
import tempfile

GITURL = "https://github.com/DarkEnergySurvey/ugali"
GITURL = "https://github.com/kadrlica/ugali"

def call_cmd(cmd):
    print(cmd)
    subprocess.check_call(cmd,shell=True)

def call_chdir(path):
    if not os.path.isdir(path):
        raise Exception("Directory does not exist: %s"%path)
    print('os.chdir(%s)'%path)
    os.chdir(path)

def setup_env():
    path='./lib/python2.7/site-packages/'
    call_cmd("mkdir -p %s"%path)
    env = 'HOME=.; PYTHONPATH=$PYTHONPATH:%s;'%path
    return path, env

def call_setup_py():
    path,env = setup_env()
    cmd = env +' python setup.py -v install -f --prefix=.'
    call_cmd(cmd)
    #call_cmd(cmd + ' --isochrones')
    #call_cmd(cmd + ' --isochrones --isochrones-path=./tmp')

def call_pip():
    path,env = setup_env()
    cmd = env + 'pip install --user --no-deps -I ugali'
    call_cmd(cmd)
    #call_cmd(cmd +' --install-option "--isochrones"')
    #call_cmd(cmd +' --install-option "--isochrones" --install-option="--isochrones-path=./tmp" ')
    #call_cmd('pip uninstall ugali')

def test_git_install():
    cwd = os.getcwd()
    tempdir = tempfile.mkdtemp()
    call_chdir(tempdir)
    call_cmd('git clone %s.git'%GITURL)
    call_chdir('ugali')
    call_setup_py()
    call_chdir(cwd)
    call_cmd('rm -rf %s'%tempdir)
    call_cmd('echo $HOME')
    call_cmd('echo $PYTHONPATH')

#def test_zip_install():
#    tempdir = tempfile.mkdtemp()
#    call_chdir(tempdir)
#    call_cmd('wget %s/archive/master.zip'%GITURL)
#    call_cmd('unzip -q master.zip')
#    call_chdir('ugali-master')
#    call_setup_py()
#    call_cmd('rm -rf %s'%tempdir)
#
#def test_pip_install():
#    tempdir = tempfile.mkdtemp()
#    call_chdir(tempdir)
#    call_pip()
#    call_cmd('rm -rf %s'%tempdir)

if __name__ == "__main__":
    import argparse
    parser = argparse.ArgumentParser(description=__doc__)
    args = parser.parse_args()

    #test_git_install()
    #test_zip_install()
    #test_pip_install()
<|endoftext|>


<commit_before>"""Test listing a datasource's layers."""

from pathlib import Path

import logging
import sys
import os

import pytest

import fiona
import fiona.ogrext
from fiona.errors import DriverError

def test_single_file_private(path_coutwildrnp_shp):
    with fiona.Env():
        assert fiona.ogrext._listlayers(
            path_coutwildrnp_shp) == ['coutwildrnp']

def test_single_file(path_coutwildrnp_shp):
    assert fiona.listlayers(path_coutwildrnp_shp) == ['coutwildrnp']

def test_directory(data_dir):
    assert sorted(fiona.listlayers(data_dir)) == ['coutwildrnp', 'gre', 'test_tin']

def test_directory_trailing_slash(data_dir):
    assert sorted(fiona.listlayers(data_dir)) == ['coutwildrnp', 'gre', 'test_tin']

def test_zip_path(path_coutwildrnp_zip):
    assert fiona.listlayers(
        'zip://{}'.format(path_coutwildrnp_zip)) == ['coutwildrnp']

def test_zip_path_arch(path_coutwildrnp_zip):
    vfs = 'zip://{}'.format(path_coutwildrnp_zip)
    assert fiona.listlayers('/coutwildrnp.shp', vfs=vfs) == ['coutwildrnp']

def test_list_not_existing(data_dir):
    """Test underlying Cython function correctly raises"""
    path = os.path.join(data_dir, "does_not_exist.geojson")
    with pytest.raises(DriverError):
        fiona.ogrext._listlayers(path)

def test_invalid_path():
    with pytest.raises(TypeError):
        fiona.listlayers(1)

def test_invalid_vfs():
    with pytest.raises(TypeError):
        fiona.listlayers("/", vfs=1)

def test_invalid_path_ioerror():
    with pytest.raises(DriverError):
        fiona.listlayers("foobar")

def test_path_object(path_coutwildrnp_shp):
    path_obj = Path(path_coutwildrnp_shp)
    assert fiona.listlayers(path_obj) == ['coutwildrnp']

def test_zip_path_arch(path_coutwildrnp_zip):
    vfs = Path('zip://{}'.format(path_coutwildrnp_zip))
    assert fiona.listlayers('/coutwildrnp.shp', vfs=vfs) == ['coutwildrnp']<commit_msg>Skip Path test for zip files on Windows (#772)<commit_after>"""Test listing a datasource's layers."""

from pathlib import Path

import logging
import sys
import os

import pytest

import fiona
import fiona.ogrext
from fiona.errors import DriverError

def test_single_file_private(path_coutwildrnp_shp):
    with fiona.Env():
        assert fiona.ogrext._listlayers(
            path_coutwildrnp_shp) == ['coutwildrnp']

def test_single_file(path_coutwildrnp_shp):
    assert fiona.listlayers(path_coutwildrnp_shp) == ['coutwildrnp']

def test_directory(data_dir):
    assert sorted(fiona.listlayers(data_dir)) == ['coutwildrnp', 'gre', 'test_tin']

def test_directory_trailing_slash(data_dir):
    assert sorted(fiona.listlayers(data_dir)) == ['coutwildrnp', 'gre', 'test_tin']

def test_zip_path(path_coutwildrnp_zip):
    assert fiona.listlayers(
        'zip://{}'.format(path_coutwildrnp_zip)) == ['coutwildrnp']

def test_zip_path_arch(path_coutwildrnp_zip):
    vfs = 'zip://{}'.format(path_coutwildrnp_zip)
    assert fiona.listlayers('/coutwildrnp.shp', vfs=vfs) == ['coutwildrnp']

def test_list_not_existing(data_dir):
    """Test underlying Cython function correctly raises"""
    path = os.path.join(data_dir, "does_not_exist.geojson")
    with pytest.raises(DriverError):
        fiona.ogrext._listlayers(path)

def test_invalid_path():
    with pytest.raises(TypeError):
        fiona.listlayers(1)

def test_invalid_vfs():
    with pytest.raises(TypeError):
        fiona.listlayers("/", vfs=1)

def test_invalid_path_ioerror():
    with pytest.raises(DriverError):
        fiona.listlayers("foobar")

def test_path_object(path_coutwildrnp_shp):
    path_obj = Path(path_coutwildrnp_shp)
    assert fiona.listlayers(path_obj) == ['coutwildrnp']

@pytest.mark.skipif(sys.platform == "win32", reason="Path doesn't support URI-style locations on Windows")
def test_zip_path_arch(path_coutwildrnp_zip):
    vfs = Path('zip://{}'.format(path_coutwildrnp_zip))
    assert fiona.listlayers('/coutwildrnp.shp', vfs=vfs) == ['coutwildrnp']<|endoftext|>


<commit_before>import logging
import sys

import pytest

from flask._compat import StringIO
from flask.logging import default_handler, has_level_handler, \
    wsgi_errors_stream

@pytest.fixture(autouse=True)
def reset_logging(monkeypatch):
    root_handlers = logging.root.handlers[:]
    root_level = logging.root.level

    logger = logging.getLogger('flask.app')
    logger.handlers = []
    logger.setLevel(logging.NOTSET)

    yield

    logging.root.handlers[:] = root_handlers
    logging.root.setLevel(root_level)

    logger.handlers = []
    logger.setLevel(logging.NOTSET)

def test_logger(app):
    assert app.logger.name == 'flask.app'
    assert app.logger.level == logging.NOTSET
    assert app.logger.handlers == [default_handler]

def test_logger_debug(app):
    app.debug = True
    assert app.logger.level == logging.DEBUG
    assert app.logger.handlers == [default_handler]

def test_existing_handler(app):
    logging.root.addHandler(logging.StreamHandler())
    assert app.logger.level == logging.NOTSET
    assert not app.logger.handlers

def test_wsgi_errors_stream(app, client):
    @app.route('/')
    def index():
        app.logger.error('test')
        return ''

    stream = StringIO()
    client.get('/', errors_stream=stream)
    assert 'ERROR in test_logging: test' in stream.getvalue()

    assert wsgi_errors_stream._get_current_object() is sys.stderr

    with app.test_request_context(errors_stream=stream):
        assert wsgi_errors_stream._get_current_object() is stream

def test_has_level_handler():
    logger = logging.getLogger('flask.app')
    assert not has_level_handler(logger)

    handler = logging.StreamHandler()
    logging.root.addHandler(handler)
    assert has_level_handler(logger)

    logger.propagate = False
    assert not has_level_handler(logger)
    logger.propagate = True

    handler.setLevel(logging.ERROR)
    assert not has_level_handler(logger)

def test_log_view_exception(app, client):
    @app.route('/')
    def index():
        raise Exception('test')

    app.testing = False
    stream = StringIO()
    rv = client.get('/', errors_stream=stream)
    assert rv.status_code == 500
    assert rv.data
    err = stream.getvalue()
    assert 'Exception on / [GET]' in err
    assert 'Exception: test' in err
<commit_msg>fix non-passing tests for logging on pytest > 3.3.0<commit_after>import logging
import sys

import pytest

from flask._compat import StringIO
from flask.logging import default_handler, has_level_handler, \
    wsgi_errors_stream

@pytest.fixture(autouse=True)
def reset_logging(monkeypatch):
    root_handlers = logging.root.handlers[:]
    root_level = logging.root.level

    logger = logging.getLogger('flask.app')
    logger.handlers = []
    logger.setLevel(logging.NOTSET)

    logging_plugin = pytest.config.pluginmanager.getplugin('logging-plugin')
    pytest.config.pluginmanager.unregister(name='logging-plugin')
    logging.root.handlers = []

    yield

    logging.root.handlers[:] = root_handlers
    logging.root.setLevel(root_level)

    logger.handlers = []
    logger.setLevel(logging.NOTSET)

    pytest.config.pluginmanager.register(logging_plugin, 'logging-plugin')

def test_logger(app):
    assert app.logger.name == 'flask.app'
    assert app.logger.level == logging.NOTSET
    assert app.logger.handlers == [default_handler]

def test_logger_debug(app):
    app.debug = True
    assert app.logger.level == logging.DEBUG
    assert app.logger.handlers == [default_handler]

def test_existing_handler(app):
    logging.root.addHandler(logging.StreamHandler())
    assert app.logger.level == logging.NOTSET
    assert not app.logger.handlers

def test_wsgi_errors_stream(app, client):
    @app.route('/')
    def index():
        app.logger.error('test')
        return ''

    stream = StringIO()
    client.get('/', errors_stream=stream)
    assert 'ERROR in test_logging: test' in stream.getvalue()

    assert wsgi_errors_stream._get_current_object() is sys.stderr

    with app.test_request_context(errors_stream=stream):
        assert wsgi_errors_stream._get_current_object() is stream

def test_has_level_handler():
    logger = logging.getLogger('flask.app')
    assert not has_level_handler(logger)

    handler = logging.StreamHandler()
    logging.root.addHandler(handler)
    assert has_level_handler(logger)

    logger.propagate = False
    assert not has_level_handler(logger)
    logger.propagate = True

    handler.setLevel(logging.ERROR)
    assert not has_level_handler(logger)

def test_log_view_exception(app, client):
    @app.route('/')
    def index():
        raise Exception('test')

    app.testing = False
    stream = StringIO()
    rv = client.get('/', errors_stream=stream)
    assert rv.status_code == 500
    assert rv.data
    err = stream.getvalue()
    assert 'Exception on / [GET]' in err
    assert 'Exception: test' in err
<|endoftext|>


<commit_before>import datetime

import pytest

from pytestqt.qt_compat import qt_api

pytestmark = pytest.mark.skipif(qt_api.pytest_qt_api == 'pyside2', reason="https://bugreports.qt.io/browse/PYSIDE-435")

@pytest.mark.parametrize('test_succeeds', [True, False])
@pytest.mark.parametrize('qt_log', [True, False])
def test_basic_logging(testdir, test_succeeds, qt_log):
    """
    Test Qt logging capture output.

    :type testdir: _pytest.pytester.TmpTestdir
    """
    testdir.makepyfile(
        """
        import sys
        from pytestqt.qt_compat import qt_api

        def to_unicode(s):
            return s.decode('utf-8', 'replace') if isinstance(s, bytes) else s

        if qt_api.qInstallMessageHandler:
            def print_msg(msg_type, context, message):
                sys.stderr.write(to_unicode(message) + '\\n')
            qt_api.qInstallMessageHandler(print_msg)
        else:
            def print_msg(msg_type, message):
                sys.stderr.write(to_unicode(message) + '\\n')
            qt_api.qInstallMsgHandler(print_msg)

        def test_types():
            qt_api.qDebug('this is a DEBUG message')
            qt_api.qWarning('this is a WARNING message')
            qt_api.qCritical('this is a CRITICAL message')
            assert {0}
        """.format(test_succeeds)
    )
    res = testdir.runpytest(*(['--no-qt-log'] if not qt_log else []))
    if test_succeeds:
        assert 'Captured Qt messages' not in res.stdout.str()
        assert 'Captured stderr call' not in res.stdout.str()
    else:
        if qt_log:
            res.stdout.fnmatch_lines([
                '*-- Captured Qt messages --*',
                '*QtDebugMsg: this is a DEBUG message*',
                '*QtWarningMsg: this is a WARNING message*',
                '*QtCriticalMsg: this is a CRITICAL message*',
            ])
        else:
            res.stdout.fnmatch_lines([
                '*-- Captured stderr call --*',
                'this is a DEBUG message*',
                'this is a WARNING message*',
                'this is a CRITICAL message*',
            ])

def test_qtlog_fixture(qtlog):
    """
    Test qtlog fixture.
    """
    qt_api.qDebug('this is a DEBUG message')
    qt_api.qWarning('this is a WARNING message')
    qt_api.qCritical('this is a CRITICAL message')
    records = [(m.type, m.message.strip()) for m in qtlog.records]
    assert records == [
        (qt_api.QtDebugMsg, 'this is a DEBUG message'),
        (qt_api.QtWarningMsg, 'this is a WARNING message'),
        (qt_api.QtCriticalMsg, 'this is a CRITICAL message'),
    ]
    # `records` attribute is read-only
    with pytest.raises(AttributeError):
        qtlog.records = []

def test_fixture_with_logging_disabled(testdir):
    """
    Test that qtlog fixture doesn't capture anything if logging is disabled
    in the command line.

    :type testdir: _pytest.pytester.TmpTestdir
    """
    testdir.makepyfile(
        """
        from pytestqt.qt_compat import qt_api

        def test_types(qtlog):
            qt_api.qWarning('message')
            assert qtlog.records == []
        """
    )
    res = testdir.runpytest('--no-qt-log')
    res.stdout.fnmatch_lines('*1 passed*')

@pytest.mark.parametrize('use_context_manager', [True, False])
def test_disable_qtlog_context_manager(testdir, use_context_manager):
    """
    Test qtlog.disabled() context manager.

    :type testdir: _pytest.pytester.TmpTestdir
    """
    testdir.makeini(
        """
        [pytest]
        qt_log_level_fail = CRITICAL
        """
    )

    if use_context_manager:
        code = 'with qtlog.disabled():'
    else:
        code = 'if 1:'

    testdir.makepyfile(
        """
        from pytestqt.qt_compat import qt_api
        def test_1(qtlog):
            {code}
                qt_api.qCritical('message')
        """.format(code=code)
    )
    res = testdir.inline_run()
    passed = 1 if use_context_manager else 0
    res.assertoutcome(passed=passed, failed=int(not passed))

@pytest.mark.parametrize('use_mark', [True, False])
def test_disable_qtlog_mark(testdir, use_mark):
    """
    Test mark which disables logging capture for a test.

    :type testdir: _pytest.pytester.TmpTestdir
    """
    testdir.makeini(
        """
        [pytest]
        qt_log_level_fail = CRITICAL
        """
    )
    mark = '@pytest.mark.no_qt_log' if use_mark else ''

    testdir.makepyfile(
        """
        from pytestqt.qt_compat import qt_api
        import pytest
        {mark}
        def test_1():
            qt_api.qCritical('message')
        """.format(mark=mark)
    )
    res = testdir.inline_run()
    passed = 1 if use_mark else 0
    res.assertoutcome(passed=passed, failed=int(not passed))

def test_logging_formatting(testdir):
    """
    Test custom formatting for logging messages.

    :type testdir: _pytest.pytester.TmpTestdir
    """
    testdir.makepyfile(
        """
        from pytestqt.qt_compat import qt_api
        def test_types():
            qt_api.qWarning('this is a WARNING message')
            assert 0
        """
    )
    f = '{rec.type_name} {rec.log_type_name} {rec.when:%Y-%m-%d}: {rec.message}'
    res = testdir.runpytest('--qt-log-format={0}'.format(f))
    today = '{0:%Y-%m-%d}'.format(datetime.datetime.now())
    res.stdout.fnmatch_lines([
        '*-- Captured Qt messages --*',
        'QtWarningMsg WARNING {0}: this is a WARNING message*'.format(today),
    ])

@pytest.mark.parametrize('level, expect_passes',
                         [('DEBUG', 1), ('WARNING', 2), ('CRITICAL', 3),
                          ('NO', 4)],
                         )
def test_logging_fails_tests(testdir, level, expect_passes):
    """
    Test qt_log_level_fail ini option.

    :type testdir: _pytest.pytester.TmpTestdir
    """
    testdir.makeini(
        """
        [pytest]
        qt_log_level_fail = {level}
        """.format(level=level)
    )
    testdir.makepyfile(
        """
        from pytestqt.qt_compat import qt_api
        def test_1():
            qt_api.qDebug('this is a DEBUG message')
        def test_2():
            qt_api.qWarning('this is a WARNING message')
        def test_3():
            qt_api.qCritical('this is a CRITICAL message')
        def test_4():
            assert 1
        """
    )
    res = testdir.runpytest()
    lines = []
    if level != 'NO':
        lines.extend([
            '*Failure: Qt messages with level {0} or above emitted*'.format(
                level.upper()),
            '*-- Captured Qt messages --*',
        ])
    lines.append('*{0} passed*'.format(expect_passes))
    res.stdout.fnmatch_lines(lines)

def test_logging_fails_tests_mark(testdir):
    """
    Test mark overrides what's configured in the ini file.

    :type testdir: _pytest.pytester.TmpTestdir
    """
    testdir.makeini(
        """
        [pytest]
        qt_log_level_fail = CRITICAL
        """
    )
    testdir.makepyfile(
        """
        from pytestqt.qt_compat import qWarning
        import pytest
        @pytest.mark.qt_log_level_fail('WARNING')
        def test_1():
            qWarning('message')
        """
    )
    res = testdir.inline_run()
    res.assertoutcome(failed=1)

def test_logging_fails_ignore(testdir):
    """
    Test qt_log_ignore config option.

    :type testdir: _pytest.pytester.TmpTestdir
    """
    testdir.makeini(
        """
        [pytest]
        qt_log_level_fail = CRITICAL
        qt_log_ignore =
            WM_DESTROY.*sent
            WM_PAINT not handled
        """
    )
    testdir.makepyfile(
        """
        from pytestqt.qt_compat import qt_api
        import pytest

        def test1():
            qt_api.qCritical('a critical message')
        def test2():
            qt_api.qCritical('WM_DESTROY was sent')
        def test3():
            qt_api.qCritical('WM_DESTROY was sent')
            assert 0
        def test4():
            qt_api.qCritical('WM_PAINT not handled')
            qt_api.qCritical('another critical message')
        """
    )
    res = testdir.runpytest()
    lines = [
        # test1 fails because it has emitted a CRITICAL message and that message
        # does not match any regex in qt_log_ignore
        '*_ test1 _*',
        '*Failure: Qt messages with level CRITICAL or above emitted*',
        '*QtCriticalMsg: a critical message*',

        # test2 succeeds because its message matches qt_log_ignore

        # test3 fails because of an assert, but the ignored message should
        # still appear in the failure message
        '*_ test3 _*',
        '*AssertionError*',
        '*QtCriticalMsg: WM_DESTROY was sent*(IGNORED)*',

        # test4 fails because one message is ignored but the other isn't
        '*_ test4 _*',
        '*Failure: Qt messages with level CRITICAL or above emitted*',
        '*QtCriticalMsg: WM_PAINT not handled*(IGNORED)*',
        '*QtCriticalMsg: another critical message*',

        # summary
        '*3 failed, 1 passed*',
    ]
    res.stdout.fnmatch_lines(lines)

@pytest.mark.parametrize('message', ['match-global', 'match-mark'])
@pytest.mark.parametrize('marker_args', [
    "'match-mark', extend=True",
    "'match-mark'"
])
def test_logging_mark_with_extend(testdir, message, marker_args):
    """
    Test qt_log_ignore mark with extend=True.

    :type testdir: _pytest.pytester.TmpTestdir
    """
    testdir.makeini(
        """
        [pytest]
        qt_log_level_fail = CRITICAL
        qt_log_ignore = match-global
        """
    )
    testdir.makepyfile(
        """
        from pytestqt.qt_compat import qt_api
        import pytest

        @pytest.mark.qt_log_ignore({marker_args})
        def test1():
            qt_api.qCritical('{message}')
        """.format(message=message, marker_args=marker_args)
    )
    res = testdir.inline_run()
    res.assertoutcome(passed=1, failed=0)

@pytest.mark.parametrize('message, error_expected', [
    ('match-global', True),
    ('match-mark', False),
])
def test_logging_mark_without_extend(testdir, message, error_expected):
    """
    Test qt_log_ignore mark with extend=False.

    :type testdir: _pytest.pytester.TmpTestdir
    """
    testdir.makeini(
        """
        [pytest]
        qt_log_level_fail = CRITICAL
        qt_log_ignore = match-global
        """
    )
    testdir.makepyfile(
        """
        from pytestqt.qt_compat import qt_api
        import pytest

        @pytest.mark.qt_log_ignore('match-mark', extend=False)
        def test1():
            qt_api.qCritical('{message}')
        """.format(message=message)
    )
    res = testdir.inline_run()

    if error_expected:
        res.assertoutcome(passed=0, failed=1)
    else:
        res.assertoutcome(passed=1, failed=0)

def test_logging_mark_with_invalid_argument(testdir):
    """
    Test qt_log_ignore mark with invalid keyword argument.

    :type testdir: _pytest.pytester.TmpTestdir
    """
    testdir.makepyfile(
        """
        import pytest

        @pytest.mark.qt_log_ignore('match-mark', does_not_exist=True)
        def test1():
            pass
        """
    )
    res = testdir.runpytest()
    lines = [
        '*= ERRORS =*',
        '*_ ERROR at setup of test1 _*',
        "*ValueError: Invalid keyword arguments in {'does_not_exist': True} "
            "for qt_log_ignore mark.",

        # summary
        '*= 1 error in*',
    ]
    res.stdout.fnmatch_lines(lines)

@pytest.mark.parametrize('apply_mark', [True, False])
def test_logging_fails_ignore_mark_multiple(testdir, apply_mark):
    """
    Make sure qt_log_ignore mark supports multiple arguments.

    :type testdir: _pytest.pytester.TmpTestdir
    """
    if apply_mark:
        mark = '@pytest.mark.qt_log_ignore("WM_DESTROY", "WM_PAINT")'
    else:
        mark = ''
    testdir.makepyfile(
        """
        from pytestqt.qt_compat import qt_api
        import pytest
        @pytest.mark.qt_log_level_fail('CRITICAL')
        {mark}
        def test1():
            qt_api.qCritical('WM_PAINT was sent')
        """.format(mark=mark)
    )
    res = testdir.inline_run()
    passed = 1 if apply_mark else 0
    res.assertoutcome(passed=passed, failed=int(not passed))

def test_lineno_failure(testdir):
    """
    Test that tests when failing because log messages were emitted report
    the correct line number.

    :type testdir: _pytest.pytester.TmpTestdir
    """
    testdir.makeini(
        """
        [pytest]
        qt_log_level_fail = WARNING
        """
    )
    testdir.makepyfile(
        """
        from pytestqt.qt_compat import qt_api
        def test_foo():
            assert foo() == 10
        def foo():
            qt_api.qWarning('this is a WARNING message')
            return 10
        """
    )
    res = testdir.runpytest()
    if qt_api.pytest_qt_api == 'pyqt5':
        res.stdout.fnmatch_lines([
            '*test_lineno_failure.py:2: Failure*',
            '*test_lineno_failure.py:foo:5:*',
            '    QtWarningMsg: this is a WARNING message',
        ])
    else:
        res.stdout.fnmatch_lines('*test_lineno_failure.py:2: Failure*')

def test_context_none(testdir):
    """
    Sometimes PyQt5 will emit a context with some/all attributes set as None
    instead of appropriate file, function and line number.

    Test that when this happens the plugin doesn't break.

    :type testdir: _pytest.pytester.TmpTestdir
    """
    if qt_api.pytest_qt_api != 'pyqt5':
        pytest.skip('Context information only available in PyQt5')
    testdir.makepyfile(
        """
        from pytestqt.qt_compat import qt_api

        def test_foo(request):
            log_capture = request.node.qt_log_capture
            context = log_capture._Context(None, None, None)
            log_capture._handle_with_context(qt_api.QtWarningMsg,
                                             context, "WARNING message")
            assert 0
        """
    )
    res = testdir.runpytest()
    res.stdout.fnmatch_lines([
        '*None:None:None:*',
        '* QtWarningMsg: WARNING message*',
    ])

def test_logging_broken_makereport(testdir):
    """
    Make sure logging's makereport hookwrapper doesn't hide exceptions.

    See https://github.com/pytest-dev/pytest-qt/issues/98

    :type testdir: _pytest.pytester.TmpTestdir
    """
    testdir.makepyfile(conftest="""
        import pytest

        @pytest.mark.hookwrapper(tryfirst=True)
        def pytest_runtest_makereport(call):
            if call.when == 'call':
                raise Exception("This should not be hidden")
            yield
    """)
    p = testdir.makepyfile(
        """
        def test_foo():
            pass
        """
    )
    res = testdir.runpytest_subprocess(p)
    res.stdout.fnmatch_lines([
        '*This should not be hidden*',
    ])
<commit_msg>Remove skip mark for PYSIDE-435 as it seems this has been fixed<commit_after>import datetime

import pytest

from pytestqt.qt_compat import qt_api

@pytest.mark.parametrize('test_succeeds', [True, False])
@pytest.mark.parametrize('qt_log', [True, False])
def test_basic_logging(testdir, test_succeeds, qt_log):
    """
    Test Qt logging capture output.

    :type testdir: _pytest.pytester.TmpTestdir
    """
    testdir.makepyfile(
        """
        import sys
        from pytestqt.qt_compat import qt_api

        def to_unicode(s):
            return s.decode('utf-8', 'replace') if isinstance(s, bytes) else s

        if qt_api.qInstallMessageHandler:
            def print_msg(msg_type, context, message):
                sys.stderr.write(to_unicode(message) + '\\n')
            qt_api.qInstallMessageHandler(print_msg)
        else:
            def print_msg(msg_type, message):
                sys.stderr.write(to_unicode(message) + '\\n')
            qt_api.qInstallMsgHandler(print_msg)

        def test_types():
            qt_api.qDebug('this is a DEBUG message')
            qt_api.qWarning('this is a WARNING message')
            qt_api.qCritical('this is a CRITICAL message')
            assert {0}
        """.format(test_succeeds)
    )
    res = testdir.runpytest(*(['--no-qt-log'] if not qt_log else []))
    if test_succeeds:
        assert 'Captured Qt messages' not in res.stdout.str()
        assert 'Captured stderr call' not in res.stdout.str()
    else:
        if qt_log:
            res.stdout.fnmatch_lines([
                '*-- Captured Qt messages --*',
                '*QtDebugMsg: this is a DEBUG message*',
                '*QtWarningMsg: this is a WARNING message*',
                '*QtCriticalMsg: this is a CRITICAL message*',
            ])
        else:
            res.stdout.fnmatch_lines([
                '*-- Captured stderr call --*',
                'this is a DEBUG message*',
                'this is a WARNING message*',
                'this is a CRITICAL message*',
            ])

def test_qtlog_fixture(qtlog):
    """
    Test qtlog fixture.
    """
    qt_api.qDebug('this is a DEBUG message')
    qt_api.qWarning('this is a WARNING message')
    qt_api.qCritical('this is a CRITICAL message')
    records = [(m.type, m.message.strip()) for m in qtlog.records]
    assert records == [
        (qt_api.QtDebugMsg, 'this is a DEBUG message'),
        (qt_api.QtWarningMsg, 'this is a WARNING message'),
        (qt_api.QtCriticalMsg, 'this is a CRITICAL message'),
    ]
    # `records` attribute is read-only
    with pytest.raises(AttributeError):
        qtlog.records = []

def test_fixture_with_logging_disabled(testdir):
    """
    Test that qtlog fixture doesn't capture anything if logging is disabled
    in the command line.

    :type testdir: _pytest.pytester.TmpTestdir
    """
    testdir.makepyfile(
        """
        from pytestqt.qt_compat import qt_api

        def test_types(qtlog):
            qt_api.qWarning('message')
            assert qtlog.records == []
        """
    )
    res = testdir.runpytest('--no-qt-log')
    res.stdout.fnmatch_lines('*1 passed*')

@pytest.mark.parametrize('use_context_manager', [True, False])
def test_disable_qtlog_context_manager(testdir, use_context_manager):
    """
    Test qtlog.disabled() context manager.

    :type testdir: _pytest.pytester.TmpTestdir
    """
    testdir.makeini(
        """
        [pytest]
        qt_log_level_fail = CRITICAL
        """
    )

    if use_context_manager:
        code = 'with qtlog.disabled():'
    else:
        code = 'if 1:'

    testdir.makepyfile(
        """
        from pytestqt.qt_compat import qt_api
        def test_1(qtlog):
            {code}
                qt_api.qCritical('message')
        """.format(code=code)
    )
    res = testdir.inline_run()
    passed = 1 if use_context_manager else 0
    res.assertoutcome(passed=passed, failed=int(not passed))

@pytest.mark.parametrize('use_mark', [True, False])
def test_disable_qtlog_mark(testdir, use_mark):
    """
    Test mark which disables logging capture for a test.

    :type testdir: _pytest.pytester.TmpTestdir
    """
    testdir.makeini(
        """
        [pytest]
        qt_log_level_fail = CRITICAL
        """
    )
    mark = '@pytest.mark.no_qt_log' if use_mark else ''

    testdir.makepyfile(
        """
        from pytestqt.qt_compat import qt_api
        import pytest
        {mark}
        def test_1():
            qt_api.qCritical('message')
        """.format(mark=mark)
    )
    res = testdir.inline_run()
    passed = 1 if use_mark else 0
    res.assertoutcome(passed=passed, failed=int(not passed))

def test_logging_formatting(testdir):
    """
    Test custom formatting for logging messages.

    :type testdir: _pytest.pytester.TmpTestdir
    """
    testdir.makepyfile(
        """
        from pytestqt.qt_compat import qt_api
        def test_types():
            qt_api.qWarning('this is a WARNING message')
            assert 0
        """
    )
    f = '{rec.type_name} {rec.log_type_name} {rec.when:%Y-%m-%d}: {rec.message}'
    res = testdir.runpytest('--qt-log-format={0}'.format(f))
    today = '{0:%Y-%m-%d}'.format(datetime.datetime.now())
    res.stdout.fnmatch_lines([
        '*-- Captured Qt messages --*',
        'QtWarningMsg WARNING {0}: this is a WARNING message*'.format(today),
    ])

@pytest.mark.parametrize('level, expect_passes',
                         [('DEBUG', 1), ('WARNING', 2), ('CRITICAL', 3),
                          ('NO', 4)],
                         )
def test_logging_fails_tests(testdir, level, expect_passes):
    """
    Test qt_log_level_fail ini option.

    :type testdir: _pytest.pytester.TmpTestdir
    """
    testdir.makeini(
        """
        [pytest]
        qt_log_level_fail = {level}
        """.format(level=level)
    )
    testdir.makepyfile(
        """
        from pytestqt.qt_compat import qt_api
        def test_1():
            qt_api.qDebug('this is a DEBUG message')
        def test_2():
            qt_api.qWarning('this is a WARNING message')
        def test_3():
            qt_api.qCritical('this is a CRITICAL message')
        def test_4():
            assert 1
        """
    )
    res = testdir.runpytest()
    lines = []
    if level != 'NO':
        lines.extend([
            '*Failure: Qt messages with level {0} or above emitted*'.format(
                level.upper()),
            '*-- Captured Qt messages --*',
        ])
    lines.append('*{0} passed*'.format(expect_passes))
    res.stdout.fnmatch_lines(lines)

def test_logging_fails_tests_mark(testdir):
    """
    Test mark overrides what's configured in the ini file.

    :type testdir: _pytest.pytester.TmpTestdir
    """
    testdir.makeini(
        """
        [pytest]
        qt_log_level_fail = CRITICAL
        """
    )
    testdir.makepyfile(
        """
        from pytestqt.qt_compat import qWarning
        import pytest
        @pytest.mark.qt_log_level_fail('WARNING')
        def test_1():
            qWarning('message')
        """
    )
    res = testdir.inline_run()
    res.assertoutcome(failed=1)

def test_logging_fails_ignore(testdir):
    """
    Test qt_log_ignore config option.

    :type testdir: _pytest.pytester.TmpTestdir
    """
    testdir.makeini(
        """
        [pytest]
        qt_log_level_fail = CRITICAL
        qt_log_ignore =
            WM_DESTROY.*sent
            WM_PAINT not handled
        """
    )
    testdir.makepyfile(
        """
        from pytestqt.qt_compat import qt_api
        import pytest

        def test1():
            qt_api.qCritical('a critical message')
        def test2():
            qt_api.qCritical('WM_DESTROY was sent')
        def test3():
            qt_api.qCritical('WM_DESTROY was sent')
            assert 0
        def test4():
            qt_api.qCritical('WM_PAINT not handled')
            qt_api.qCritical('another critical message')
        """
    )
    res = testdir.runpytest()
    lines = [
        # test1 fails because it has emitted a CRITICAL message and that message
        # does not match any regex in qt_log_ignore
        '*_ test1 _*',
        '*Failure: Qt messages with level CRITICAL or above emitted*',
        '*QtCriticalMsg: a critical message*',

        # test2 succeeds because its message matches qt_log_ignore

        # test3 fails because of an assert, but the ignored message should
        # still appear in the failure message
        '*_ test3 _*',
        '*AssertionError*',
        '*QtCriticalMsg: WM_DESTROY was sent*(IGNORED)*',

        # test4 fails because one message is ignored but the other isn't
        '*_ test4 _*',
        '*Failure: Qt messages with level CRITICAL or above emitted*',
        '*QtCriticalMsg: WM_PAINT not handled*(IGNORED)*',
        '*QtCriticalMsg: another critical message*',

        # summary
        '*3 failed, 1 passed*',
    ]
    res.stdout.fnmatch_lines(lines)

@pytest.mark.parametrize('message', ['match-global', 'match-mark'])
@pytest.mark.parametrize('marker_args', [
    "'match-mark', extend=True",
    "'match-mark'"
])
def test_logging_mark_with_extend(testdir, message, marker_args):
    """
    Test qt_log_ignore mark with extend=True.

    :type testdir: _pytest.pytester.TmpTestdir
    """
    testdir.makeini(
        """
        [pytest]
        qt_log_level_fail = CRITICAL
        qt_log_ignore = match-global
        """
    )
    testdir.makepyfile(
        """
        from pytestqt.qt_compat import qt_api
        import pytest

        @pytest.mark.qt_log_ignore({marker_args})
        def test1():
            qt_api.qCritical('{message}')
        """.format(message=message, marker_args=marker_args)
    )
    res = testdir.inline_run()
    res.assertoutcome(passed=1, failed=0)

@pytest.mark.parametrize('message, error_expected', [
    ('match-global', True),
    ('match-mark', False),
])
def test_logging_mark_without_extend(testdir, message, error_expected):
    """
    Test qt_log_ignore mark with extend=False.

    :type testdir: _pytest.pytester.TmpTestdir
    """
    testdir.makeini(
        """
        [pytest]
        qt_log_level_fail = CRITICAL
        qt_log_ignore = match-global
        """
    )
    testdir.makepyfile(
        """
        from pytestqt.qt_compat import qt_api
        import pytest

        @pytest.mark.qt_log_ignore('match-mark', extend=False)
        def test1():
            qt_api.qCritical('{message}')
        """.format(message=message)
    )
    res = testdir.inline_run()

    if error_expected:
        res.assertoutcome(passed=0, failed=1)
    else:
        res.assertoutcome(passed=1, failed=0)

def test_logging_mark_with_invalid_argument(testdir):
    """
    Test qt_log_ignore mark with invalid keyword argument.

    :type testdir: _pytest.pytester.TmpTestdir
    """
    testdir.makepyfile(
        """
        import pytest

        @pytest.mark.qt_log_ignore('match-mark', does_not_exist=True)
        def test1():
            pass
        """
    )
    res = testdir.runpytest()
    lines = [
        '*= ERRORS =*',
        '*_ ERROR at setup of test1 _*',
        "*ValueError: Invalid keyword arguments in {'does_not_exist': True} "
            "for qt_log_ignore mark.",

        # summary
        '*= 1 error in*',
    ]
    res.stdout.fnmatch_lines(lines)

@pytest.mark.parametrize('apply_mark', [True, False])
def test_logging_fails_ignore_mark_multiple(testdir, apply_mark):
    """
    Make sure qt_log_ignore mark supports multiple arguments.

    :type testdir: _pytest.pytester.TmpTestdir
    """
    if apply_mark:
        mark = '@pytest.mark.qt_log_ignore("WM_DESTROY", "WM_PAINT")'
    else:
        mark = ''
    testdir.makepyfile(
        """
        from pytestqt.qt_compat import qt_api
        import pytest
        @pytest.mark.qt_log_level_fail('CRITICAL')
        {mark}
        def test1():
            qt_api.qCritical('WM_PAINT was sent')
        """.format(mark=mark)
    )
    res = testdir.inline_run()
    passed = 1 if apply_mark else 0
    res.assertoutcome(passed=passed, failed=int(not passed))

def test_lineno_failure(testdir):
    """
    Test that tests when failing because log messages were emitted report
    the correct line number.

    :type testdir: _pytest.pytester.TmpTestdir
    """
    testdir.makeini(
        """
        [pytest]
        qt_log_level_fail = WARNING
        """
    )
    testdir.makepyfile(
        """
        from pytestqt.qt_compat import qt_api
        def test_foo():
            assert foo() == 10
        def foo():
            qt_api.qWarning('this is a WARNING message')
            return 10
        """
    )
    res = testdir.runpytest()
    if qt_api.pytest_qt_api == 'pyqt5':
        res.stdout.fnmatch_lines([
            '*test_lineno_failure.py:2: Failure*',
            '*test_lineno_failure.py:foo:5:*',
            '    QtWarningMsg: this is a WARNING message',
        ])
    else:
        res.stdout.fnmatch_lines('*test_lineno_failure.py:2: Failure*')

def test_context_none(testdir):
    """
    Sometimes PyQt5 will emit a context with some/all attributes set as None
    instead of appropriate file, function and line number.

    Test that when this happens the plugin doesn't break.

    :type testdir: _pytest.pytester.TmpTestdir
    """
    if qt_api.pytest_qt_api != 'pyqt5':
        pytest.skip('Context information only available in PyQt5')
    testdir.makepyfile(
        """
        from pytestqt.qt_compat import qt_api

        def test_foo(request):
            log_capture = request.node.qt_log_capture
            context = log_capture._Context(None, None, None)
            log_capture._handle_with_context(qt_api.QtWarningMsg,
                                             context, "WARNING message")
            assert 0
        """
    )
    res = testdir.runpytest()
    res.stdout.fnmatch_lines([
        '*None:None:None:*',
        '* QtWarningMsg: WARNING message*',
    ])

def test_logging_broken_makereport(testdir):
    """
    Make sure logging's makereport hookwrapper doesn't hide exceptions.

    See https://github.com/pytest-dev/pytest-qt/issues/98

    :type testdir: _pytest.pytester.TmpTestdir
    """
    testdir.makepyfile(conftest="""
        import pytest

        @pytest.mark.hookwrapper(tryfirst=True)
        def pytest_runtest_makereport(call):
            if call.when == 'call':
                raise Exception("This should not be hidden")
            yield
    """)
    p = testdir.makepyfile(
        """
        def test_foo():
            pass
        """
    )
    res = testdir.runpytest_subprocess(p)
    res.stdout.fnmatch_lines([
        '*This should not be hidden*',
    ])
<|endoftext|>


<commit_before>import io
import os
import logging
import pytest

from rich.console import Console
from rich.logging import RichHandler

handler = RichHandler(
    console=Console(
        file=io.StringIO(),
        force_terminal=True,
        width=80,
        color_system="truecolor",
        _environ={},
    ),
    enable_link_path=False,
)

logging.basicConfig(
    level="NOTSET", format="%(message)s", datefmt="[DATE]", handlers=[handler]
)
log = logging.getLogger("rich")

skip_win = pytest.mark.skipif(
    os.name == "nt",
    reason="rendered differently on windows",
)

@skip_win
def test_exception():
    console = Console(
        file=io.StringIO(),
        force_terminal=True,
        width=140,
        color_system=None,
        _environ={},
    )
    handler_with_tracebacks = RichHandler(
        console=console, enable_link_path=False, rich_tracebacks=True
    )
    formatter = logging.Formatter("FORMATTER %(message)s %(asctime)s")
    handler_with_tracebacks.setFormatter(formatter)
    log.addHandler(handler_with_tracebacks)
    log.error("foo")
    try:
        1 / 0
    except ZeroDivisionError:
        log.exception("message")

    render = handler_with_tracebacks.console.file.getvalue()
    print(render)

    assert "FORMATTER foo" in render
    assert "ZeroDivisionError" in render
    assert "message" in render
    assert "division by zero" in render

def test_exception_with_extra_lines():
    console = Console(
        file=io.StringIO(),
        force_terminal=True,
        width=140,
        color_system=None,
        _environ={},
    )
    handler_extra_lines = RichHandler(
        console=console,
        enable_link_path=False,
        markup=True,
        rich_tracebacks=True,
        tracebacks_extra_lines=5,
    )
    log.addHandler(handler_extra_lines)

    try:
        1 / 0
    except ZeroDivisionError:
        log.exception("message")

    render = handler_extra_lines.console.file.getvalue()
    print(render)

    assert "ZeroDivisionError" in render
    assert "message" in render
    assert "division by zero" in render

if __name__ == "__main__":
    render = make_log()
    print(render)
    print(repr(render))
<commit_msg>Add a test case to simulate pythonw related to issue #1619<commit_after>import io
import os
import logging
from typing import Optional

import pytest

from rich.console import Console
from rich.logging import RichHandler

handler = RichHandler(
    console=Console(
        file=io.StringIO(),
        force_terminal=True,
        width=80,
        color_system="truecolor",
        _environ={},
    ),
    enable_link_path=False,
)

logging.basicConfig(
    level="NOTSET", format="%(message)s", datefmt="[DATE]", handlers=[handler]
)
log = logging.getLogger("rich")

skip_win = pytest.mark.skipif(
    os.name == "nt",
    reason="rendered differently on windows",
)

@skip_win
def test_exception():
    console = Console(
        file=io.StringIO(),
        force_terminal=True,
        width=140,
        color_system=None,
        _environ={},
    )
    handler_with_tracebacks = RichHandler(
        console=console, enable_link_path=False, rich_tracebacks=True
    )
    formatter = logging.Formatter("FORMATTER %(message)s %(asctime)s")
    handler_with_tracebacks.setFormatter(formatter)
    log.addHandler(handler_with_tracebacks)
    log.error("foo")
    try:
        1 / 0
    except ZeroDivisionError:
        log.exception("message")

    render = handler_with_tracebacks.console.file.getvalue()
    print(render)

    assert "FORMATTER foo" in render
    assert "ZeroDivisionError" in render
    assert "message" in render
    assert "division by zero" in render

def test_exception_with_extra_lines():
    console = Console(
        file=io.StringIO(),
        force_terminal=True,
        width=140,
        color_system=None,
        _environ={},
    )
    handler_extra_lines = RichHandler(
        console=console,
        enable_link_path=False,
        markup=True,
        rich_tracebacks=True,
        tracebacks_extra_lines=5,
    )
    log.addHandler(handler_extra_lines)

    try:
        1 / 0
    except ZeroDivisionError:
        log.exception("message")

    render = handler_extra_lines.console.file.getvalue()
    print(render)

    assert "ZeroDivisionError" in render
    assert "message" in render
    assert "division by zero" in render

def test_stderr_and_stdout_are_none(monkeypatch):
    # This test is specifically to handle cases when using pythonw on
    # windows an stderr and stdout are set to None.
    # See https://bugs.python.org/issue13807

    monkeypatch.setattr("sys.stdout", None)
    monkeypatch.setattr("sys.stderr", None)

    console = Console(_environ={})
    target_handler = RichHandler(console=console)
    actual_record: Optional[logging.LogRecord] = None

    def mock_handle_error(record):
        nonlocal actual_record
        actual_record = record

    target_handler.handleError = mock_handle_error
    log.addHandler(target_handler)

    try:
        1 / 0
    except ZeroDivisionError:
        log.exception("message")

    finally:
        log.removeHandler(target_handler)

    assert actual_record is not None
    assert "message" in actual_record.msg

if __name__ == "__main__":
    render = make_log()
    print(render)
    print(repr(render))
<|endoftext|>


<commit_before>import math
import unittest

from robot.markers import Metres, Radians, SphericalCoord

class SphericalCoordTest(unittest.TestCase):
    def test_conversion_to_degrees(self):
        coords = SphericalCoord(
            rot_x_radians=Radians(math.pi / 2),
            rot_y_radians=Radians(-math.pi / 4),
            dist=Metres(1),
        )

        self.assertEqual(
            90,
            coords.rot_x_degrees,
            "Wrong x rotation",
        )

        self.assertEqual(
            -45,
            coords.rot_y_degrees,
            "Wrong y rotation",
        )
<commit_msg>Also update attribute name in test<commit_after>import math
import unittest

from robot.markers import Metres, Radians, SphericalCoord

class SphericalCoordTest(unittest.TestCase):
    def test_conversion_to_degrees(self):
        coords = SphericalCoord(
            rot_x_radians=Radians(math.pi / 2),
            rot_y_radians=Radians(-math.pi / 4),
            distance_metres=Metres(1),
        )

        self.assertEqual(
            90,
            coords.rot_x_degrees,
            "Wrong x rotation",
        )

        self.assertEqual(
            -45,
            coords.rot_y_degrees,
            "Wrong y rotation",
        )
<|endoftext|>


<commit_before>import os
import tempfile
from datetime import datetime
from unittest import mock

from bottery.message import Message, render

@mock.patch('bottery.message.settings')
def test_render(mocked_settings):
    '''
    Test if a message template is rendered with a
    specified context.
    '''
    message = Message(123, 'Telegram', 'Bottery', 'text', 1506191745, 'raw')
    with tempfile.TemporaryDirectory() as tempdir:
        path = os.path.join(tempdir, 'templates')
        os.mkdir(path)

        template_path = os.path.join(path, 'template.md')
        with open(template_path, 'w') as template:
            template.write('{{ user }} {{ text }}!')

        mocked_settings.TEMPLATES = [path]
        rendered = render(message, 'template.md', {'text': 'rocks'})
        assert rendered == 'Bottery rocks!'
<commit_msg>Fixed test_message flake8 errors<commit_after>import os
import tempfile
from unittest import mock

from bottery.message import Message, render

@mock.patch('bottery.message.settings')
def test_render(mocked_settings):
    '''
    Test if a message template is rendered with a
    specified context.
    '''
    message = Message(123, 'Telegram', 'Bottery', 'text', 1506191745, 'raw')
    with tempfile.TemporaryDirectory() as tempdir:
        path = os.path.join(tempdir, 'templates')
        os.mkdir(path)

        template_path = os.path.join(path, 'template.md')
        with open(template_path, 'w') as template:
            template.write('{{ user }} {{ text }}!')

        mocked_settings.TEMPLATES = [path]
        rendered = render(message, 'template.md', {'text': 'rocks'})
        assert rendered == 'Bottery rocks!'
<|endoftext|>