def test_github_api_create_webhook_when_webhook_already_exist_raises_GitIntegrationError(
        m_get_repo, app):
    app.config['DEBUG'] = False

    class MockProject:
        def get_branch(self, name):
            return Mock()

        def create_hook(self, name, config, events, active):
            raise GithubException(
                422,
                data={
                    'message':
                    'Validation Failed',
                    'errors': [{
                        'resource':
                        'Hook',
                        'code':
                        'custom',
                        'message':
                        'Hook already exists on this repository'
                    }],
                })

    m_get_repo.return_value = MockProject()

    api = GithubAPI('github.com', 'owner', 'repository', 'my-branch')

    with raises(GitIntegrationError):
        api.create_webhook()
def test_github_api_create_webhook_when_no_permissions_to_create_a_webhook_raises_GitIntegrationError(
        m_get_repo, app):
    app.config['DEBUG'] = False

    class MockProject:
        def get_branch(self, name):
            mock = Mock()
            mock.name = name
            mock.commit.sha = 'mybranchsha'
            return mock

        def create_hook(self, name, config, events, active):
            raise UnknownObjectException(404, data={'message': 'Not Found'})

    m_get_repo.return_value = MockProject()

    api = GithubAPI('github.com', 'owner', 'repository', 'my-branch')

    with raises(GitIntegrationError):
        api.create_webhook()
def test_github_api_create_webhook(m_get_repo, app):
    class MockProject:
        def get_branch(self, name):
            return Mock()

        def create_hook(self, name, config, events, active):
            assert name == 'web'
            assert config == {
                'url': 'http://analysispreservation.cern.ch/api/repos/event',
                'content_type': 'json',
                'secret': 'mysecret'
            }
            assert events == ['release']
            assert active is True
            return Mock(
                url="https://api.github.com/repos/owner/repo/hooks/186091239",
                id=186091239)

    m_get_repo.return_value = MockProject()

    api = GithubAPI('github.com', 'owner', 'repository', 'my-branch')

    assert api.create_webhook() == (186091239, 'mysecret')