#!/usr/bin/python3
# SPDX-FileCopyrightText: 2024-2025 Univention GmbH
# SPDX-License-Identifier: AGPL-3.0-only
"""Unit test for univention.management.console.modules.setup.setup_script"""
import os
# pylint: disable-msg=C0103,E0611,R0904
import unittest
from shutil import rmtree
from tempfile import mkdtemp

import univention.management.console.modules
from univention.config_registry import ConfigRegistry


univention.management.console.modules.__path__.insert(0, os.path.join(os.path.dirname(__file__), os.path.pardir, 'umc/python'))
from univention.management.console.modules.setup.setup_script import TransactionalUcr  # noqa: E402


class TestProfile(unittest.TestCase):
    """Unit test for univention.management.console.modules.setup.setup_script"""

    def setUp(self):
        """Create object."""
        self.temp = mkdtemp()
        os.environ['UNIVENTION_BASECONF'] = os.path.join(self.temp, 'test.conf')
        self.ucr = ConfigRegistry()
        self.ucr.load()
        self.wrap = TransactionalUcr()

    def tearDown(self):
        rmtree(self.temp)

    def test_same(self):
        """Test reading unmodified."""
        assert self.ucr.get("foo") == self.wrap.get("foo")

    def test_uncommited(self):
        """Test reading uncommitted."""
        self.wrap.set('foo', 'bar')
        assert self.ucr.get("foo") != self.wrap.get("foo")

    def test_committed(self):
        """Test reading committed."""
        self.wrap.set('foo', 'bar')
        self.wrap.commit()
        self.ucr.load()
        assert self.ucr.get("foo") == self.wrap.get("foo")

    def test_revert(self):
        """Test reading revert."""
        self.wrap.set('foo', 'bar')
        self.wrap.set('foo', None)
        self.wrap.commit()
        assert self.ucr.get("foo") == self.wrap.get("foo")

    def test_transaction(self):
        """Test transaction commit."""
        with self.wrap:
            self.wrap.set('foo', 'bar')
        self.ucr.load()
        assert self.ucr.get("foo") == "bar"

    def test_transaction_fail(self):
        """Test transaction aborted."""
        self.wrap.set('foo', 'bar')
        try:
            with self.wrap:
                raise ValueError()
        except ValueError:
            pass
        else:
            self.fail('Failed to propagate exception')
        self.ucr.load()
        assert self.ucr.get("foo") != "bar"


if __name__ == '__main__':
    unittest.main()
