import datetime
import mock
import tests
import unittest2
from st2common.persistence.reactor import Trigger, TriggerInstance
from st2common.models.db.reactor import TriggerDB, TriggerInstanceDB
from st2reactor.container import utils

MOCK_TRIGGER = TriggerDB()
MOCK_TRIGGER.id = 'trigger-test.id'
MOCK_TRIGGER.name = 'trigger-test.name'

MOCK_TRIGGER_INSTANCE = TriggerInstanceDB()
MOCK_TRIGGER_INSTANCE.id = 'triggerinstance-test'
MOCK_TRIGGER_INSTANCE.name = 'triggerinstance-test.name'
MOCK_TRIGGER_INSTANCE.trigger = MOCK_TRIGGER
MOCK_TRIGGER_INSTANCE.payload = {}
MOCK_TRIGGER_INSTANCE.occurrence_time = datetime.datetime.now()


class ContainerServiceTest(unittest2.TestCase):
    def setUp(self):
        tests.parse_args()

    @mock.patch.object(Trigger, 'query', mock.MagicMock(
        return_value=[MOCK_TRIGGER]))
    @mock.patch.object(TriggerInstance, 'add_or_update', mock.MagicMock(
        return_value=MOCK_TRIGGER_INSTANCE))
    @mock.patch('st2reactor.container.utils.DISPATCH_HANDLER')
    def test_validate_dispatch(self, mock_dispatch_handler):
        utils.dispatch_trigger(MOCK_TRIGGER_INSTANCE)
        mock_dispatch_handler.assert_called_once_with([MOCK_TRIGGER_INSTANCE])

    @mock.patch.object(Trigger, 'query', mock.MagicMock(
        return_value=[MOCK_TRIGGER]))
    @mock.patch.object(Trigger, 'add_or_update')
    def test_add_trigger(self, mock_add_handler):
        mock_add_handler.return_value = MOCK_TRIGGER
        utils.add_trigger_type(MOCK_TRIGGER)
        self.assertTrue(mock_add_handler.called, 'trigger not added.')

@@ -1559,8 +1559,729 @@
 dded.')%0A
+%0A    def test_add_trigger_type(self):%0A        %22%22%22%0A        This sensor has misconfigured trigger type. We shouldn't explode.%0A        %22%22%22%0A        class FailTestSensor(object):%0A            started = False%0A%0A            def start(self):%0A                FailTestSensor.started = True%0A%0A            def stop(self):%0A                pass%0A%0A            def get_trigger_type(self):%0A                return %7B%0A                    'description': 'Ain%5C't got no name'%0A                %7D%0A%0A        try:%0A            st2reactor.container.utils.add_trigger_type(FailTestSensor())%0A            self.assertTrue(False, 'Trigger type doesn%5C't have %5C'name%5C' field. Should have thrown.')%0A        except Exception, e:%0A            self.assertTrue(True)%0A%0A

Test case for trigger type validation