"""Unit tests for github_stats 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 github_stats


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': [
              {
                'id': 'abcdef',
                'distinct': False,
              },
              {
                'id': 'ghijkl',
                'distinct': True,
              }
            ],
            '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': [
              {
                'id': 'mnopqr',
                'distinct': True,
              }
            ],
            'repository': {
              'full_name': 'dta/rockpaperscissors',
              'url': (
                'https://git-aws.internal.justin.tv/dta/rockpaperscissors'),
              'default_branch': 'master',
            }
          })),
          event_bus.Event('TestEvent', ''),
          invalid_event,
        ]

        expected_requests = [
          ingest_queue.IngestGitHubStatsRequest(
            github_host='git-aws.internal.justin.tv',
            github_repository='dta/rockpaperscissors',
            commit_sha='ghijkl'),
        ]

        github_stats.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_requests)


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