import os.path

import unittest

from unittest.mock import patch, Mock

from ascend_deployer.downloader.download_util import get_remote_content_length, get_obs_downloader_path





class TestGetRemoteContentLength(unittest.TestCase):



    @patch('urllib.request.Request')

    @patch('urllib.request.urlopen')

    def test_get_remote_content_length_success(self, mock_urlopen, mock_request):

        mock_response = Mock()

        mock_response.getheader.return_value = '"12345"'

        mock_urlopen.return_value.__enter__.return_value = mock_response



        result = get_remote_content_length('http://example.com')

        self.assertEqual(result, 12345)



    @patch('urllib.request.Request')

    @patch('urllib.request.urlopen')

    def test_get_remote_content_length_no_header(self, mock_urlopen, mock_request):

        mock_response = Mock()

        mock_response.getheader.return_value = ''

        mock_urlopen.return_value.__enter__.return_value = mock_response



        result = get_remote_content_length('http://example.com')

        self.assertIsNone(result)



    @patch('urllib.request.Request')

    @patch('urllib.request.urlopen')

    def test_get_remote_content_length_invalid_header(self, mock_urlopen, mock_request):

        mock_response = Mock()

        mock_response.getheader.return_value = '"not_a_number"'

        mock_urlopen.return_value.__enter__.return_value = mock_response



        result = get_remote_content_length('http://example.com')

        self.assertIsNone(result)



    @patch('urllib.request.Request')

    @patch('urllib.request.urlopen')

    def test_get_remote_content_length_exception(self, mock_urlopen, mock_request):

        mock_urlopen.side_effect = Exception('Test exception')



        result = get_remote_content_length('http://example.com')

        self.assertIsNone(result)





class TestGetObsDownloaderPath(unittest.TestCase):



    @patch('os.path.exists')

    def test_get_obs_downloader_path_exists(self, mock_exists):

        mock_exists.return_value = True

        original_path = '/path/to/downloader'

        expected_path = '/path/to/downloader/obs_downloader_config'

        self.assertEqual(get_obs_downloader_path(original_path), os.path.normpath(expected_path))



    @patch('os.path.exists')

    def test_get_obs_downloader_path_not_exists(self, mock_exists):

        mock_exists.return_value = False

        original_path = '/path/to/downloader'

        self.assertEqual(get_obs_downloader_path(original_path), original_path)



    def test_get_obs_downloader_path_no_downloader(self):

        original_path = '/path/to/somewhere'

        self.assertEqual(get_obs_downloader_path(original_path), original_path)





if __name__ == '__main__':

    unittest.main()