Example #1
0
def test_default_config(app):
    """make sure we're casting things that make sense to cast"""
    github_app = GitHubApp(app)
    with app.app_context():
        assert github_app.id == 1
        assert github_app.key == b'key'
        assert github_app.secret == b'secret'
Example #2
0
def test_github_enterprise_client(app):
    enterprise_url = 'https://enterprise.github.com'
    app.config['GITHUBAPP_URL'] = enterprise_url
    github_app = GitHubApp(app)
    with app.app_context():
        assert isinstance(github_app.client, GitHubEnterprise)
        assert github_app.client.url == enterprise_url
Example #3
0
def test_event_and_action_functions_called(app, mocker):
    github_app = GitHubApp(app)
    event_function = MagicMock()
    event_action_function = MagicMock()
    other_event_function = MagicMock()
    github_app._hook_mappings = {
        'foo': [event_function],
        'foo.bar': [event_action_function],
        'bar': [other_event_function]
    }
    mocker.patch('flask_githubapp.core.GitHubApp._verify_webhook')
    with app.test_client() as client:
        resp = client.post('/',
                           data=json.dumps({
                               'installation': {
                                   'id': 2
                               },
                               'action': 'bar'
                           }),
                           headers={
                               'X-GitHub-Event': 'foo',
                               'Content-Type': 'application/json'
                           })
        assert resp.status_code == 200
        event_function.assert_called_once_with()
        event_action_function.assert_called_once_with()
        other_event_function.assert_not_called()
Example #4
0
def test_hook_mapping(app):
    github_app = GitHubApp(app)

    @github_app.on('foo')
    def bar():
        pass

    assert github_app._hook_mappings['foo'] == [bar]
Example #5
0
def test_github_app_client(app, mocker):
    github_app = GitHubApp(app)
    mocker.patch('flask_githubapp.core.GitHubApp._verify_webhook')
    mock_client = mocker.patch('flask_githubapp.core.GitHubApp.client')
    with app.app_context():
        github_app.app_client
        mock_client.login_as_app.assert_called_once_with(
            github_app.key, github_app.id)
Example #6
0
def test_multiple_function_on_same_event(app):
    github_app = GitHubApp(app)

    @github_app.on('foo')
    def bar():
        pass

    @github_app.on('foo')
    def baz():
        pass

    assert github_app._hook_mappings['foo'] == [bar, baz]
def test_issues_hook_invalid_signature(app):
    with open(os.path.join(FIXURES_DIR, 'issues_hook.json'), 'rb') as hook:
        issues_data = hook.read()

    GitHubApp(app)

    with app.test_client() as client:
        resp = client.post('/',
                           data=issues_data,
                           headers={
                               'Content-Type': 'application/json',
                               'X-GitHub-Event': 'issues',
                               'X-Hub-Signature': 'sha1=badhash'
                           })
        assert resp.status_code == 400
Example #8
0
def test_events_mapped_to_functions(app, mocker):
    github_app = GitHubApp(app)
    function_to_call = MagicMock()
    github_app._hook_mappings['foo'] = [function_to_call]
    mocker.patch('flask_githubapp.core.GitHubApp._verify_webhook')
    with app.test_client() as client:
        resp = client.post('/',
                           data=json.dumps({'installation': {
                               'id': 2
                           }}),
                           headers={
                               'X-GitHub-Event': 'foo',
                               'Content-Type': 'application/json'
                           })
        assert resp.status_code == 200
        function_to_call.assert_called_once_with()
Example #9
0
def test_github_installation_client_is_lazy(app, mocker):
    github_app = GitHubApp(app)
    installation_id = 2
    mocker.patch('flask_githubapp.core.GitHubApp._verify_webhook')
    mock_client = mocker.patch('flask_githubapp.core.GitHubApp.client')
    with app.test_client() as client:
        resp = client.post('/',
                           data=json.dumps(
                               {'installation': {
                                   'id': installation_id
                               }}),
                           headers={
                               'X-GitHub-Event': 'foo',
                               'Content-Type': 'application/json'
                           })
        assert resp.status_code == 200
        mock_client.login_as_app_installation.assert_not_called()
def test_issues_hook_valid_signature(app):
    with open(os.path.join(FIXURES_DIR, 'issues_hook.json'), 'rb') as hook:
        issues_data = hook.read()

    GitHubApp(app)

    with app.test_client() as client:
        resp = client.post('/',
                           data=issues_data,
                           headers={
                               'Content-Type':
                               'application/json',
                               'X-GitHub-Event':
                               'issues',
                               'X-Hub-Signature':
                               'sha1=85d20eda7a4e518f956b99f432b1225de8516e56'
                           })
        assert resp.status_code == 200
Example #11
0
def test_function_exception_raise_500_error(app, mocker):
    github_app = GitHubApp(app)

    function_to_call = MagicMock()
    function_to_call.__name__ = 'foo'  # used to generate response
    function_to_call.side_effect = Exception('foo exception')

    github_app._hook_mappings['foo'] = [function_to_call]
    mocker.patch('flask_githubapp.core.GitHubApp._verify_webhook')
    with app.test_client() as client:
        resp = client.post('/',
                           data=json.dumps({'installation': {
                               'id': 2
                           }}),
                           headers={
                               'X-GitHub-Event': 'foo',
                               'Content-Type': 'application/json'
                           })
        assert resp.status_code == 500
        function_to_call.assert_called_once_with()
Example #12
0
def test_no_target_functions(app, mocker):
    github_app = GitHubApp(app)

    function_to_miss = MagicMock()
    function_to_miss.__name__ = 'foo'  # used to generate response

    github_app._hook_mappings['foo'] = [function_to_miss]
    mocker.patch('flask_githubapp.core.GitHubApp._verify_webhook')
    with app.test_client() as client:
        resp = client.post('/',
                           data=json.dumps({'installation': {
                               'id': 2
                           }}),
                           headers={
                               'X-GitHub-Event': 'bar',
                               'Content-Type': 'application/json'
                           })
        assert resp.status_code == 200
        function_to_miss.assert_not_called()
        assert resp.json['status'] == STATUS_NO_FUNC_CALLED
        assert resp.json['calls'] == {}
Example #13
0
def test_view_returns_map_of_called_functions_and_returned_data(app, mocker):
    github_app = GitHubApp(app)

    def event_function():
        return 'foo'

    def event_action_function():
        return 'bar'

    def other_event_function():
        return 'baz'

    github_app._hook_mappings = {
        'foo': [event_function],
        'foo.bar': [event_action_function],
        'bar': [other_event_function]
    }
    mocker.patch('flask_githubapp.core.GitHubApp._verify_webhook')
    with app.test_client() as client:
        resp = client.post('/',
                           data=json.dumps({
                               'installation': {
                                   'id': 2
                               },
                               'action': 'bar'
                           }),
                           headers={
                               'X-GitHub-Event': 'foo',
                               'Content-Type': 'application/json'
                           })
        assert resp.status_code == 200
        assert resp.json == {
            'status': 'HIT',
            'calls': {
                'event_function': 'foo',
                'event_action_function': 'bar',
            }
        }
Example #14
0
def test_events_with_actions_mapped_to_functions(app, mocker):
    github_app = GitHubApp(app)

    function_to_call = MagicMock()
    function_to_call.__name__ = 'foo'  # used to generate response
    function_to_call.return_value = 'foo'  # return data must be serializable

    github_app._hook_mappings['foo.bar'] = [function_to_call]
    mocker.patch('flask_githubapp.core.GitHubApp._verify_webhook')
    with app.test_client() as client:
        resp = client.post('/',
                           data=json.dumps({
                               'installation': {
                                   'id': 2
                               },
                               'action': 'bar'
                           }),
                           headers={
                               'X-GitHub-Event': 'foo',
                               'Content-Type': 'application/json'
                           })
        assert resp.status_code == 200
        function_to_call.assert_called_once_with()
Example #15
0
def test_github_client(app):
    github_app = GitHubApp(app)
    with app.app_context():
        assert isinstance(github_app.client, GitHub)
Example #16
0
from flask_githubapp import GitHubApp  # type: ignore

from ..common import github_utils
from ..common.typ import AppInstallationTokenAuth, CorregirJob, Repo
from ..corrector.tasks import corregir_entrega
from .queue import task_queue
from .reposdb import make_reposdb
from .settings import load_config

__all__ = [
    "repos_hook",
]

reposdb = make_reposdb()
repos_hook = GitHubApp()


def app_installation_token_auth() -> AppInstallationTokenAuth:
    """Obtiene el token de autenticación del objeto GitHubApp.
    """
    client = repos_hook.installation_client
    session_auth = client.session.auth
    # Para poder usar github3.py en el worker, se necesita tanto el token
    # como su fecha de expiración. Para PyGithub haría falta solamente el
    # token.
    return AppInstallationTokenAuth(
        token=session_auth.token,
        expires_at=session_auth.expires_at_str,
    )
Example #17
0
	# 3rd party
	from werkzeug.wrappers import Response

app = Flask(__name__)

GITHUBAPP_ID = app.config["GITHUBAPP_ID"] = int(os.environ["GITHUBAPP_ID"])
GITHUBAPP_SECRET = app.config["GITHUBAPP_SECRET"] = os.environ["GITHUBAPP_SECRET"]
GITHUBAPP_KEY: bytes

if "GITHUBAPP_KEY" in os.environ:
	GITHUBAPP_KEY = app.config["GITHUBAPP_KEY"] = os.environ["GITHUBAPP_KEY"].encode("UTF-8")
else:
	with open(os.environ["GITHUBAPP_KEY_PATH"], "rb") as key_file:
		GITHUBAPP_KEY = app.config["GITHUBAPP_KEY"] = key_file.read()

github_app = GitHubApp(app)

client: GitHub = GitHub()

context_switcher = ContextSwitcher(
		client=client,
		private_key_pem=GITHUBAPP_KEY,
		app_id=GITHUBAPP_ID,
		)

context_switcher.login_as_app()


def https_redirect() -> Optional["Response"]:
	# Based on https://stackoverflow.com/a/59771351
	# By Maximilian Burszley <https://stackoverflow.com/users/8188846/maximilian-burszley>
Example #18
0
def test_init_app(app):
    github_app = GitHubApp()
    github_app.init_app(app)
    assert 'GITHUBAPP_URL' not in app.config