# -*- encoding: UTF8 -*-
# Test harness for CheckSubmitHasReview.py

from __future__ import print_function

import sys
import unittest
import os

from p4testutils import TestCase, P4Server, localDirectory, create_file, append_to_file

parent_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, parent_dir)
from CheckSubmitHasReview import CheckSubmitHasReview

os.environ["LOGS"] = "."
LOGGER_NAME = "TestCheckSubmitHasReview"
LOG_FILE = "log-CheckSubmitHasReview.log"

python3 = sys.version_info[0] >= 3

if python3:
    from unittest.mock import patch, Mock
else:
    from mock import patch, Mock

class TestCheckSubmitHasReview(TestCase):
    def __init__(self, methodName='runTest'):
        super(TestCheckSubmitHasReview, self).__init__(LOGGER_NAME, LOG_FILE, methodName=methodName)

    def setUp(self):
        pass

    def tearDown(self):
        pass

    @patch('CheckSubmitHasReview.requests')
    def testCheckSubmitHasReview(self, requests_mock):
        """trigger fires and sends expected info to Swarm"""
        self.server = P4Server()
        config_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "~test_config.yaml")
        p4 = self.server.p4
        p4.logger = self.logger

        inside = localDirectory(self.server.client_root, "inside")
        outside = localDirectory(self.server.client_root, "outside")
        inside_file1 = os.path.join(inside, "inside_file1")
        outside_file1 = os.path.join(outside, "outside_file1")
        create_file(inside_file1, 'Test content')
        create_file(outside_file1, 'Test content')

        p4.run('add', inside_file1)
        result = p4.run('submit', '-d', 'inside_file1 added')
        self.assertEqual("1", result[-1]['submittedChange'])

        p4.run('add', outside_file1)
        result = p4.run('submit', '-d', 'outside_file1 added')
        self.assertEqual("2", result[-1]['submittedChange'])

        # Test exclusionary mapping
        with open(config_path, "w") as f:
            f.write("""
api: "api/v6"
user: swarmtest
ticket: A123453
submit_without_review_users:
  - jenkins
msg_submit_requires_review:
  - "You are not allowed to submit without a review - please shelve for review first!"
msg_submit_test_must_pass:
  - "You are not allowed to submit without a Jenkins build/test passing successfully!"
projects:
  - name:                       ProjectA
    pre_submit_require_review:  y
    pre_submit_test_must_pass:  y
    post_submit_create_review:  n
    require_job:                y
    update_review:              n
    depot_paths:
    - //depot/inside/...
    default_reviewers:
    - user1
""")

        # For change 2 which is outside, we don't expect trigger to fire

        trig_args = ["-p", p4.port, "-u", p4.user, "-c", config_path, "--test-mode", "2"]
        get_call_count = 0
        post_call_count = 0
        patch_call_count = 0

        trig = CheckSubmitHasReview(*trig_args)
        result = trig.run()
        self.assertEqual(0, result)
        # Hasn't been called
        self.assertEqual(get_call_count, requests_mock.get.call_count)
        self.assertEqual(post_call_count, requests_mock.post.call_count)
        self.assertEqual(patch_call_count, requests_mock.patch.call_count)

        #----------------------------------------
        # For a path config file defines as inside we should call.

        # Return a review or more
        mock_response = Mock()
        review_response = {"lastSeen":813,
                           "reviews":[
                               {"id":815,"author":"perforce","changes":[814,816,817],"comments":[0,0],"commits":[817],
                              "commitStatus":[],"created":1509095267,"deployDetails":[],"deployStatus":None,
                              "description":"asdfasdf","groups":["longlived"],
                              "participants":{"perforce":[]},"pending":False,"projects":[],"state":"approved",
                              "stateLabel":"Approved","testDetails":[],"testStatus":None,"type":"default",
                              "updated":1509096701,"updateDate":"2017-10-27T09:31:41+00:00"}],
                           "totalCount":1}
        mock_response.json.return_value = review_response
        requests_mock.get.return_value = mock_response

        trig_args[-1] = "1"
        trig = CheckSubmitHasReview(*trig_args)
        result = trig.run()
        self.assertEqual(1, result)
        get_call_count += 1    # Expect an update
        self.assertEqual(get_call_count, requests_mock.get.call_count)
        self.assertEqual(post_call_count, requests_mock.post.call_count)
        self.assertEqual(patch_call_count, requests_mock.patch.call_count)

        # Now we make testStatus pass
        review_response = {"lastSeen":813,
                   "reviews":[
                       {"id":815,"author":"perforce","changes":[814,816,817],"comments":[0,0],"commits":[817],
                      "commitStatus":[],"created":1509095267,"deployDetails":[],"deployStatus":None,
                      "description":"asdfasdf","groups":["longlived"],
                      "participants":{"perforce":[]},"pending":False,"projects":[],"state":"approved",
                      "stateLabel":"Approved","testDetails":[],"testStatus":"pass","type":"default",
                      "updated":1509096701,"updateDate":"2017-10-27T09:31:41+00:00"}],
                   "totalCount":1}
        mock_response.json.return_value = review_response
        requests_mock.get.return_value = mock_response

        trig_args[-1] = "1"
        trig = CheckSubmitHasReview(*trig_args)
        result = trig.run()
        self.assertEqual(0, result)
        get_call_count += 1    # Expect an update
        self.assertEqual(get_call_count, requests_mock.get.call_count)
        self.assertEqual(post_call_count, requests_mock.post.call_count)
        self.assertEqual(patch_call_count, requests_mock.patch.call_count)

        
        # If review is blank then still a problem
        # Return a review or more
        mock_response = Mock()
        review_response = {"lastSeen":813,
                           "reviews":[],
                           "totalCount":0}
        mock_response.json.return_value = review_response
        requests_mock.get.return_value = mock_response

        trig_args[-1] = "1"
        trig = CheckSubmitHasReview(*trig_args)
        result = trig.run()
        self.assertEqual(1, result)
        get_call_count += 1    # Expect an update
        self.assertEqual(get_call_count, requests_mock.get.call_count)
        self.assertEqual(post_call_count, requests_mock.post.call_count)
        self.assertEqual(patch_call_count, requests_mock.patch.call_count)

        # ------------------------------
        # Test that some users can submit directly without reviews.

        p4.user = "jenkins"
        p4.run('edit', inside_file1)
        append_to_file(inside_file1, "Extra text")
        result = p4.run('submit', '-d', 'inside_file1 edited')
        self.assertEqual("3", result[-1]['submittedChange'])

        trig_args[-1] = "3"
        trig = CheckSubmitHasReview(*trig_args)
        result = trig.run()
        self.assertEqual(0, result)
        # Mock should not be called in this case
        self.assertEqual(get_call_count, requests_mock.get.call_count)
        self.assertEqual(post_call_count, requests_mock.post.call_count)
        self.assertEqual(patch_call_count, requests_mock.patch.call_count)



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