# BFH Science Self-Service Portal
# Copyright (C) 2025-2026 IKUS Software
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program 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 General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <https://www.gnu.org/licenses/>.

import tempfile

import cherrypy

from . import WebCase


class LoginPageRateLimitTest(WebCase):
    default_config = {'rate-limit': 5}
    login = False

    def setUp(self):
        cherrypy.tools.ratelimit.reset()
        return super().setUp()

    def test_login_ratelimit(self):
        # Given an unauthenticate
        # When requesting multiple time the login page
        for i in range(0, 5):
            self.getPage('/login/', method='POST', body={'login': 'invalid', 'password': 'invalid'})
            self.assertStatus(200)
        # Then a 429 error (too many request) is return
        self.getPage('/login/', method='POST', body={'login': 'invalid', 'password': 'invalid'})
        self.assertStatus(429)


class FileStorageRateLimitTest(LoginPageRateLimitTest):

    @classmethod
    def setup_class(cls):
        cls.tempdir = tempfile.TemporaryDirectory(prefix='cherrypy-foundation-', suffix='-ratelimit-test')
        cls.default_config['session-dir'] = cls.tempdir.name
        super().setup_class()

    @classmethod
    def teardown_class(cls):
        cls.tempdir.cleanup()
        super().teardown_class()
