#  Copyright 2022 The Debusine developers
#  See the AUTHORS file at the top-level directory of this distribution
#
#  This file is part of Debusine. It is subject to the license terms
#  in the LICENSE file found in the top-level directory of this
#  distribution. No part of Debusine, including this file, may be copied,
#  modified, propagated, or distributed except according to the terms
#  contained in the LICENSE file.
"""Unit tests for functions in debusine.utils."""
import os
import tempfile
from pathlib import Path

from django.core.exceptions import ImproperlyConfigured
from django.test import TestCase

from debusine.project import utils


class UtilsTests(TestCase):
    """Tests for functions in defaults.py."""

    SECRET_KEY = "this-is-a-secret-key"

    def create_secret_key_file(self, permissions):
        """Create a secret key file, schedules deletion after test."""
        file = tempfile.NamedTemporaryFile(
            mode="w", delete=False, prefix="debusine-test-settings-secret-key"
        )
        self.addCleanup(os.unlink, file.name)
        file.write(self.SECRET_KEY)
        file.close()
        Path(file.name).chmod(permissions)
        return file.name

    def test_read_secret_key_reads_key(self):
        """read_secret_key return the key in the file."""
        secret_key_file = self.create_secret_key_file(0o600)
        self.assertEqual(
            self.SECRET_KEY, utils.read_secret_key(secret_key_file)
        )

    def test_read_secret_key_cannot_read_file(self):
        """read_secret_key cannot read the file, raises ImproperlyConfigured."""
        with self.assertRaisesRegex(ImproperlyConfigured, "Cannot read"):
            utils.read_secret_key("/tmp/a-file-that-does-not-exist-24241")

    def test_read_secret_key_file_permissions_too_open(self):
        """read_secret_key file permissions too open, raises exception."""
        secret_key_file = self.create_secret_key_file(0o640)

        with self.assertRaisesRegex(ImproperlyConfigured, "too open"):
            utils.read_secret_key(secret_key_file)
