"""Unit tests for blueprint_ingest lambda handler module."""

import json
import logging
import unittest

import mock

from code.justin.tv.dta.rockpaperscissors import event_bus
from code.justin.tv.dta.rockpaperscissors import ingest_queue
from code.justin.tv.dta.rockpaperscissors.testutils import aws_lambda

import blueprint_ingest


logging.basicConfig(level=logging.INFO)


@mock.patch.object(ingest_queue, 'IngestQueue')
class TestCase(unittest.TestCase):

    def testBasic(self, mock_queue):
        invalid_event = event_bus.Event('TestEvent', '')
        invalid_event.ClearField('body')
        events = [
          event_bus.Event('GitHub-push', json.dumps({
            'ref': 'refs/heads/master',
            'commits': [
              {
                'added': [],
                'modified': ['rockpaperscissors.blueprint'],
              },
              {
                'added': ['subdir/bogus.blueprint'],
                'modified': ['some_other_file.txt'],
              }
            ],
            'repository': {
              'full_name': 'dta/rockpaperscissors',
              'url': (
                'https://git-aws.internal.justin.tv/dta/rockpaperscissors'),
              'default_branch': 'master',
            }
          })),
          event_bus.Event('GitHub-push', json.dumps({
            'ref': 'refs/heads/topic-branch',
            'commits': [
              {
                'added': [],
                'modified': ['rockpaperscissors.blueprint'],
              }
            ],
            'repository': {
              'full_name': 'dta/rockpaperscissors',
              'url': (
                'https://git-aws.internal.justin.tv/dta/rockpaperscissors'),
              'default_branch': 'master',
            }
          })),
          event_bus.Event('TestEvent', ''),
          invalid_event,
        ]

        expected_request = ingest_queue.IngestBlueprintRequest(
          github_host='git-aws.internal.justin.tv',
          github_repository='dta/rockpaperscissors',
          blueprint_path='rockpaperscissors.blueprint')

        blueprint_ingest.lambda_handler(
          aws_lambda.KinesisLambdaEvent(
            event.SerializeToString() for event in events),
          aws_lambda.Context('rockpaperscissors-development-lambda'))

        mock_queue_obj = mock_queue.return_value
        self.assertEqual(mock_queue_obj.AddRequests.call_count, 1)
        arg = mock_queue_obj.AddRequests.call_args[0][0]
        self.assertEqual(list(arg), [expected_request])


if __name__ == '__main__':
    unittest.main()
