<commit_before># -*- coding: utf-8 -*-
#
# This file is part of Invenio.
# Copyright (C) 2015 CERN.
#
# Invenio is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any later version.
#
# Invenio is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Invenio; if not, write to the Free Software Foundation, Inc.,
# 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.

"""Test case for ORCID oauth remote app."""

from __future__ import absolute_import

from flask import session, url_for

from flask_email.backends import locmem

import httpretty

from invenio.ext.sqlalchemy import db

from invenio.testsuite import make_test_suite, run_test_suite

from mock import MagicMock

from six.moves.urllib_parse import parse_qs, urlparse

from .helpers import OAuth2ClientTestCase
from ..contrib.orcid import REMOTE_APP, account_info


class OrcidTestCase(OAuth2ClientTestCase):

    """ORCID OAuth remote app test case."""

    example_data = {
        "name": "<NAME>",
        "expires_in": 3599,
        "orcid": "0000-0002-1825-0097",
        "access_token": "test_access_token",
        "refresh_token": "test_refresh_token",
        "scope": "/authenticate",
        "token_type": "bearer"
    }
    example_email = "<EMAIL>"
    existing_email = "<EMAIL>"

    def create_app(self):
        """Create Flask application object."""
        app = super(OrcidTestCase, self).create_app()
        app.testing = True
        app.config.update(dict(
            WTF_CSRF_ENABLED=False,
            OAUTHCLIENT_STATE_ENABLED=False,
            CACHE_TYPE='simple',
            OAUTHCLIENT_REMOTE_APPS=dict(orcid=REMOTE_APP),
            ORCID_APP_CREDENTIALS=dict(
                consumer_key='changeme',
                consumer_secret='changeme',
            ),
            # use local memory mailbox
            EMAIL_BACKEND='flask_email.backends.locmem.Mail',
        ))
        return app

    def setUp(self):
        """Setup test."""
        from invenio.modules.oauthclient.models import RemoteToken, \
            RemoteAccount
        from invenio.modules.accounts.models import UserEXT, User
        RemoteToken.query.delete()
        RemoteAccount.query.delete()
        UserEXT.query.delete()
        User.query.filter_by(email=self.example_email).delete()

        self.u = User(email=self.existing_email, nickname='tester')
        self.u.password = "<PASSWORD>"
        db.session.add(self.u)
        db.session.commit()

    def tearDown(self):
        """Tear down test."""
        from invenio.modules.oauthclient.models import RemoteToken, \
            RemoteAccount
        from invenio.modules.accounts.models import UserEXT, User
        RemoteToken.query.delete()
        RemoteAccount.query.delete()
        UserEXT.query.delete()
        User.query.filter_by(email=self.example_email).delete()
        User.query.filter_by(email=self.existing_email).delete()
        db.session.commit()
        # empty the mailbox
        if hasattr(locmem, 'outbox'):
            del locmem.outbox[:]

    def mock_response(self, app='test', data=None):
        """Mock the oauth response to use the remote."""
        from invenio.modules.oauthclient.client import oauth

        # Mock oauth remote application
        oauth.remote_apps[app].handle_oauth2_response = MagicMock(
            return_value=data or self.example_data
        )

    def _get_state(self):
        from invenio.modules.oauthclient.views.client import serializer
        return serializer.dumps({'app': 'orcid', 'sid': session.sid,
                                 'next': None, })

    def test_account_info(self):
        """Test account info extraction."""
        from invenio.modules.oauthclient.client import oauth
        # Ensure remote apps have been loaded (due to before first
        # request)
        self.client.get(url_for("oauthclient.login", remote_app='orcid'))

        self.assertEqual(
            account_info(oauth.remote_apps['orcid'], self.example_data),
            dict(external_id="0000-0002-1825-0097",
                 external_method="orcid")
        )
        self.assertEqual(
            account_info(oauth.remote_apps['orcid'], {}),
            dict(external_id=None,
                 external_method="orcid")
        )

    def test_login(self):
        """Test ORCID login."""
        resp = self.client.get(
            url_for("oauthclient.login", remote_app='orcid',
                    next='/someurl/')
        )
        self.assertStatus(resp, 302)<commit_msg>oauthclient: hotfix expected results in test<commit_after># -*- coding: utf-8 -*-
#
# This file is part of Invenio.
# Copyright (C) 2015 CERN.
#
# Invenio is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any later version.
#
# Invenio is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Invenio; if not, write to the Free Software Foundation, Inc.,
# 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.

"""Test case for ORCID oauth remote app."""

from __future__ import absolute_import

from flask import session, url_for

from flask_email.backends import locmem

import httpretty

from invenio.ext.sqlalchemy import db

from invenio.testsuite import make_test_suite, run_test_suite

from mock import MagicMock

from six.moves.urllib_parse import parse_qs, urlparse

from .helpers import OAuth2ClientTestCase
from ..contrib.orcid import REMOTE_APP, account_info


class OrcidTestCase(OAuth2ClientTestCase):

    """ORCID OAuth remote app test case."""

    example_data = {
        "name": "<NAME>",
        "expires_in": 3599,
        "orcid": "0000-0002-1825-0097",
        "access_token": "test_access_token",
        "refresh_token": "test_refresh_token",
        "scope": "/authenticate",
        "token_type": "bearer"
    }
    example_email = "<EMAIL>"
    existing_email = "<EMAIL>"

    def create_app(self):
        """Create Flask application object."""
        app = super(OrcidTestCase, self).create_app()
        app.testing = True
        app.config.update(dict(
            WTF_CSRF_ENABLED=False,
            OAUTHCLIENT_STATE_ENABLED=False,
            CACHE_TYPE='simple',
            OAUTHCLIENT_REMOTE_APPS=dict(orcid=REMOTE_APP),
            ORCID_APP_CREDENTIALS=dict(
                consumer_key='changeme',
                consumer_secret='changeme',
            ),
            # use local memory mailbox
            EMAIL_BACKEND='flask_email.backends.locmem.Mail',
        ))
        return app

    def setUp(self):
        """Setup test."""
        from invenio.modules.oauthclient.models import RemoteToken, \
            RemoteAccount
        from invenio.modules.accounts.models import UserEXT, User
        RemoteToken.query.delete()
        RemoteAccount.query.delete()
        UserEXT.query.delete()
        User.query.filter_by(email=self.example_email).delete()

        self.u = User(email=self.existing_email, nickname='tester')
        self.u.password = "<PASSWORD>"
        db.session.add(self.u)
        db.session.commit()

    def tearDown(self):
        """Tear down test."""
        from invenio.modules.oauthclient.models import RemoteToken, \
            RemoteAccount
        from invenio.modules.accounts.models import UserEXT, User
        RemoteToken.query.delete()
        RemoteAccount.query.delete()
        UserEXT.query.delete()
        User.query.filter_by(email=self.example_email).delete()
        User.query.filter_by(email=self.existing_email).delete()
        db.session.commit()
        # empty the mailbox
        if hasattr(locmem, 'outbox'):
            del locmem.outbox[:]

    def mock_response(self, app='test', data=None):
        """Mock the oauth response to use the remote."""
        from invenio.modules.oauthclient.client import oauth

        # Mock oauth remote application
        oauth.remote_apps[app].handle_oauth2_response = MagicMock(
            return_value=data or self.example_data
        )

    def _get_state(self):
        from invenio.modules.oauthclient.views.client import serializer
        return serializer.dumps({'app': 'orcid', 'sid': session.sid,
                                 'next': None, })

    def test_account_info(self):
        """Test account info extraction."""
        from invenio.modules.oauthclient.client import oauth
        # Ensure remote apps have been loaded (due to before first
        # request)
        self.client.get(url_for("oauthclient.login", remote_app='orcid'))

        self.assertEqual(
            account_info(oauth.remote_apps['orcid'], self.example_data),
            dict(external_id="0000-0002-1825-0097",
                 external_method="orcid",
                 nickname="0000-0002-1825-0097")
        )
        self.assertEqual(
            account_info(oauth.remote_apps['orcid'], {}),
            dict(external_id=None,
                 external_method="orcid",
                 nickname=None)
        )

    def test_login(self):
        """Test ORCID login."""
        resp = self.client.get(
            url_for("oauthclient.login", remote_app='orcid',
                    next='/someurl/')
        )
        self.assertStatus(resp, 302)
{'fraction_non_alphanumeric': 0.10128876359242851, 'fraction_numerical': 0.014095851792186871, 'mean_word_length': 2.5768815268275116, 'pattern_counts': {'":': 14, '<': 11, '<?xml version=': 0, '>': 11, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 2, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5393775', 'n_tokens_mistral': 2974, 'n_tokens_neox': 2838, 'n_words': 728}