# SPDX-FileCopyrightText: Freya Bruhin (The Compiler) <mail@qutebrowser.org>
#
# SPDX-License-Identifier: GPL-3.0-or-later

"""Tests for qutebrowser.misc.crashdialog."""

import os
import pytest
from qutebrowser.misc import crashdialog


VALID_CRASH_TEXT = """
Fatal Python error: Segmentation fault
_
Current thread 0x00007f09b538d700 (most recent call first):
  File "", line 1 in testfunc
  File "filename", line 88 in func
"""

VALID_CRASH_TEXT_EMPTY = """
Fatal Python error: Aborted
_
Current thread 0x00007f09b538d700 (most recent call first):
  File "", line 1 in_
  File "filename", line 88 in func
"""

VALID_CRASH_TEXT_THREAD = """
Fatal Python error: Segmentation fault
_
Thread 0x00007fa135ac7700 (most recent call first):
  File "", line 1 in testfunc
"""

VALID_CRASH_TEXT_PY314 = """
Fatal Python error: Segmentation fault
_
Current thread 0x00000001fe53e140 [CrBrowserMain] (most recent call first):
  File "qutebrowser/app.py", line 126 in qt_mainloop
  File "qutebrowser/app.py", line 116 in run
  File "qutebrowser/qutebrowser.py", line 234 in main
  File "__main__.py", line 15 in <module>
_
Current thread's C stack trace (most recent call first):
  Binary file "...", at _Py_DumpStack+0x48 [0x10227cc9c]
  <truncated rest of calls>
"""

VALID_CRASH_TEXT_PY314_NO_PY = """
Fatal Python error: Segmentation fault
_
Current thread 0x00007f0dc805cbc0 [qutebrowser] (most recent call first):
  <no Python frame>
_
Current thread's C stack trace (most recent call first):
  Binary file "/lib64/libpython3.14.so.1.0", at _Py_DumpStack+0x4c [0x7f0dc7b2127b]
  <truncated rest of calls>
"""

WINDOWS_CRASH_TEXT = r"""
Windows fatal exception: access violation
_
Current thread 0x000014bc (most recent call first):
  File "qutebrowser\mainwindow\tabbedbrowser.py", line 468 in tabopen
  File "qutebrowser\browser\shared.py", line 247 in get_tab
"""

INVALID_CRASH_TEXT = """
Hello world!
"""


@pytest.mark.parametrize(
    "text, typ, func",
    [
        pytest.param(VALID_CRASH_TEXT, "Segmentation fault", "testfunc", id="valid"),
        pytest.param(
            VALID_CRASH_TEXT_THREAD, "Segmentation fault", "testfunc", id="valid-thread"
        ),
        pytest.param(
            VALID_CRASH_TEXT_PY314,
            "Segmentation fault",
            "qt mainloop",
            id="valid-py314",
        ),
        pytest.param(
            VALID_CRASH_TEXT_PY314_NO_PY,
            "Segmentation fault",
            "",
            id="valid-py314-no-py",
        ),
        pytest.param(VALID_CRASH_TEXT_EMPTY, "Aborted", "", id="valid-empty"),
        pytest.param(
            WINDOWS_CRASH_TEXT, "Windows access violation", "tabopen", id="windows"
        ),
        pytest.param(INVALID_CRASH_TEXT, "", "", id="invalid"),
    ],
)
def test_parse_fatal_stacktrace(text, typ, func):
    text = text.strip().replace('_', ' ')
    assert crashdialog.parse_fatal_stacktrace(text) == (typ, func)


@pytest.mark.parametrize('env, expected', [
    ({'FOO': 'bar'}, ""),
    ({'FOO': 'bar', 'LC_ALL': 'baz'}, "LC_ALL = baz"),
    ({'LC_ALL': 'baz', 'PYTHONFOO': 'fish'}, "LC_ALL = baz\nPYTHONFOO = fish"),
    (
        {'DE': 'KDE', 'DESKTOP_SESSION': 'plasma'},
        "DE = KDE\nDESKTOP_SESSION = plasma"
    ),
    (
        {'QT5_IM_MODULE': 'fcitx', 'QT_IM_MODULE': 'fcitx'},
        "QT_IM_MODULE = fcitx"
    ),
    ({'LANGUAGE': 'foo', 'LANG': 'en_US.UTF-8'}, "LANG = en_US.UTF-8"),
    ({'FOO': 'bar', 'QUTE_BLAH': '1'}, "QUTE_BLAH = 1"),
])
def test_get_environment_vars(monkeypatch, env, expected):
    """Test for crashdialog._get_environment_vars."""
    for key in os.environ.copy():
        monkeypatch.delenv(key)
    for k, v in env.items():
        monkeypatch.setenv(k, v)
    assert crashdialog._get_environment_vars() == expected
