# -*- coding: utf-8 -*-

# Copyright (C) 2020 Avencall
#
# 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 <http://www.gnu.org/licenses/>

import unittest
from mock import Mock, patch

from xivo_agid.modules.get_exten_from_userid import get_exten_from_userid


class TestFwdGetExtenFromUserid(unittest.TestCase):

    def setUp(self):
        self._agi = Mock()
        self._cursor = Mock()

    @patch('xivo_agid.objects.Line')
    def test_get_user_exten_set_billnum_to_user_exten(self, mock_Line):
        args = [42]

        mocked_line = Mock()
        mocked_line.number = 1000
        mock_Line.return_value = mocked_line

        get_exten_from_userid(self._agi, self._cursor, args)

        self._agi.set_variable.assert_called_once_with('XIVO_BILLNUM', 1000)

    @patch('xivo_agid.objects.Line')
    def test_get_user_exten_billnum_set_to_none_for_line_without_exten(self, mock_Line):
        args = [42]
        mocked_line = Mock()
        mocked_line.number = None
        mock_Line.return_value = mocked_line

        get_exten_from_userid(self._agi, self._cursor, args)

        self._agi.set_variable.assert_called_once_with('XIVO_BILLNUM', '')

    @patch('xivo_agid.objects.Line')
    def test_get_user_exten_billnum_set_to_none_when_exception_raised(self, mock_Line):
        args = [42]
        mock_Line.side_effect = Exception()

        get_exten_from_userid(self._agi, self._cursor, args)

        self._agi.set_variable.assert_called_once_with('XIVO_BILLNUM', '')

    def test_get_user_exten_billnum_set_to_none_when_userid_none(self):
        args = None

        get_exten_from_userid(self._agi, self._cursor, args)

        self._agi.set_variable.assert_called_once_with('XIVO_BILLNUM', '')

    def test_get_user_exten_billnum_set_to_none_when_userid_void(self):
        args = ['']

        get_exten_from_userid(self._agi, self._cursor, args)

        self._agi.set_variable.assert_called_once_with('XIVO_BILLNUM', '')