#!/usr/bin/python3
# -*- coding: utf-8 -*-
#
# Copyright 2025 GNOME Foundation, Inc.
#
# SPDX-License-Identifier: GPL-2.0-or-later
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
# MA  02110-1301  USA

"""Integration tests for the malcontent-webd-update process."""

import dbusmock
import os
import subprocess
import sysconfig
import unittest

import taptestrunner


class TestMalcontentWebdUpdate(dbusmock.DBusTestCase):
    """Integration test for running malcontent-webd-update.

    This can be run when installed or uninstalled. When uninstalled, it
    requires G_TEST_BUILDDIR and G_TEST_SRCDIR to be set. It can run as any
    user.

    The idea with this test harness is to simulate simple integration
    situations for malcontent-webd-update, rather than to test any of the core
    code in depth. Unit tests exist for that.
    """

    @classmethod
    def setUpClass(klass):
        klass.start_system_bus()

    def setUp(self):
        if "G_TEST_BUILDDIR" in os.environ:
            self.__malcontent_webd_update = os.path.join(
                os.environ["G_TEST_BUILDDIR"], "..", "malcontent-webd-update"
            )
        else:
            arch = sysconfig.get_config_var("multiarchsubdir").strip("/")
            self.__malcontent_webd_update = os.path.join(
                "/", "lib", arch, "malcontent-webd-update"
            )

        self.__webd_mock_server = dbusmock.SpawnedMock.spawn_with_template(
            os.path.join(os.path.dirname(__file__), "malcontent-webd-template.py"),
            {},
            dbusmock.BusType.SYSTEM,
            stdout=subprocess.PIPE,
            stderr=subprocess.STDOUT,
        )

    def tearDown(self):
        self.__webd_mock_server.terminate()

    def test_successful_update(self):
        """Test the daemon is spawned successfully."""
        out = subprocess.check_output(
            [self.__malcontent_webd_update],
            stderr=subprocess.STDOUT,
        )
        out = out.decode("utf-8").strip()

    def test_error_handling(self):
        """Test that errors from the daemon are reported."""

        # Disable G_DEBUG=fatal-warnings as we want to receive the warnings
        custom_env = os.environ.copy()
        custom_env["G_DEBUG"] = ""

        self.__webd_mock_server.obj.SetUpdateFiltersError(
            "org.freedesktop.MalcontentWeb1.Filtering.Error.Downloading",
            "oh noes, download failed",
        )
        info = subprocess.run(
            [self.__malcontent_webd_update],
            stdout=subprocess.PIPE,
            stderr=subprocess.STDOUT,
            env=custom_env,
        )
        out = info.stdout.decode("utf-8").strip()
        self.assertIn("oh noes, download failed", out)
        self.assertEqual(info.returncode, 69)  # EX_UNAVAILABLE


if __name__ == "__main__":
    unittest.main(testRunner=taptestrunner.TAPTestRunner())
