from nose.tools import *
from tests.base import OsfTestCase

import json
import hmac
import hashlib

from website.addons.base.exceptions import HookError

from website.addons.github.model import AddonGitHubNodeSettings
from website.addons.github import utils


def make_signature(secret, data):
    return hmac.new(secret, data, hashlib.sha1).hexdigest()

HOOK_PAYLOAD = json.dumps({
    'files': [],
    'message': 'fake commit',
})


class TestHookVerify(OsfTestCase):

    def setUp(self):
        super(TestHookVerify, self).setUp()
        self.node_settings = AddonGitHubNodeSettings(
            hook_secret='speakfriend',
        )

    def test_verify_no_secret(self):
        self.node_settings.hook_secret = None
        with assert_raises(HookError):
            utils.verify_hook_signature(self.node_settings, {}, {})

    def test_verify_valid(self):
        try:
            utils.verify_hook_signature(
                self.node_settings,
                HOOK_PAYLOAD,
                {
                    'X-Hub-Signature': make_signature(
                        self.node_settings.hook_secret,
                        HOOK_PAYLOAD,
                    )
                }
            )
        except HookError:
            assert 0

    def test_verify_invalid(self):
        with assert_raises(HookError):
            utils.verify_hook_signature(
                self.node_settings,
                HOOK_PAYLOAD,
                {'X-Hub-Signature': 'invalid'}
            )

@@ -1,12 +1,81 @@
+import json%0Aimport hmac%0Aimport hashlib%0Aimport unittest%0A%0Aimport mock%0A%0A
 from nose.to
@@ -87,16 +87,17 @@
 mport *%0A
+%0A
 from tes
@@ -128,47 +128,92 @@
 se%0A%0A
-import json%0Aimport hmac%0Aimport hashlib%0A
+from website.addons.github import utils%0Afrom website.addons.github.api import GitHub
 %0Afro
@@ -262,17 +262,16 @@
 okError%0A
-%0A
 from web
@@ -293,44 +293,40 @@
 hub.
-model import AddonGitHubNodeSettings
+exceptions import EmptyRepoError
 %0Afro
@@ -344,32 +344,38 @@
 ddons.github
+.model
  import 
 utils%0A%0A%0Adef 
@@ -362,20 +362,38 @@
  import 
-util
+AddonGitHubNodeSetting
 s%0A%0A%0Adef 
@@ -1607,24 +1607,385 @@
 invalid'%7D%0A            )%0A
+%0A%0Aclass TestHookVerify(unittest.TestCase):%0A    @mock.patch('website.addons.github.api.GitHub.repo')%0A    def tests_none_trees_raise_empty_repo(self, mack_repo):%0A        mock_tree = mock.Mock()%0A        mock_tree.tree.return_value = None%0A        mack_repo.return_value = mock_tree%0A%0A        with assert_raises(EmptyRepoError):%0A            GitHub().tree('', '', '')%0A

Add a test for the case that calling tree returns None