<commit_before>import unittest
import datetime

from google.appengine.api import users
from google.appengine.api import memcache
from google.appengine.ext import ndb
from google.appengine.ext import testbed

from models import (
    Profile,
    Conference,
    Session,
)

from utils import getUserId


class BaseEndpointAPITestCase(unittest.TestCase):
    """ Base endpoint API unit tests. """

    def setUp(self):
        # First, create an instance of the Testbed class.
        self.testbed = testbed.Testbed()
        # Then activate the testbed, which prepares the service stubs for use.
        self.testbed.activate()
        # Next, declare which service stubs you want to use.
        self.testbed.init_datastore_v3_stub()
        self.testbed.init_memcache_stub()
        self.testbed.init_user_stub()
        # Clear ndb's in-context cache between tests.
        # This prevents data from leaking between tests.
        # Alternatively, you could disable caching by
        # using ndb.get_context().set_cache_policy(False)
        ndb.get_context().clear_cache()

    def tearDown(self):
        self.testbed.deactivate()

    def initDatabase(self):
        """ Adds database fixtures """
        _profiles = [
            {'id': '1', 'displayName': 'Luiz', 'mainEmail': '<EMAIL>', 'teeShirtSize': '1', 'conferenceKeysToAttend': []},
            {'id': '2', 'displayName': 'Batman', 'mainEmail': '<EMAIL>', 'teeShirtSize': '2', 'conferenceKeysToAttend': []},
            {'id': '3', 'displayName': 'Goku', 'mainEmail': '<EMAIL>', 'teeShirtSize': '3', 'conferenceKeysToAttend': []}
        ]
        # add profiles to database
        ndb.put_multi([Profile(**p) for p in _profiles])

        now = datetime.datetime.now()
        # 3 conferences with `<EMAIL>`
        # 1 conference with `<EMAIL>`
        _conferences = [
            {
                'name': 'room #1',
                'organizerUserId': '1',  # <EMAIL>
                'topics': ['programming', 'web design', 'web performance'],
                'city': 'London',
                'startDate': now,
                'endDate': now + datetime.timedelta(days=5),
                'maxAttendees': 100,
                'sessions': [
                    {'name': 'PHP', 'speaker': 'superman', 'typeOfSession': 'educational',
                     'date': (now + datetime.timedelta(days=10)).date(),
                     'startTime': (now + datetime.timedelta(days=1)).time(), 'duration': 60},
                    {'name': 'Python', 'speaker': 'flash', 'typeOfSession': 'educational',
                     'date': (now + datetime.timedelta(days=10)).date(),
                     'startTime': (now + datetime.timedelta(days=1, hours=1)).time(), 'duration': 60}
                ]
            },
            {
                'name': 'room #2',
                'organizerUserId': '1',  # <EMAIL>
                'topics': ['web performance'],
                'city': 'Baton Rouge',
                'startDate': now + datetime.timedelta(days=10),
                'endDate': now + datetime.timedelta(days=20),
                'maxAttendees': 5,
                'sessions': []
            },
            {
                'name': 'room #3',
                'organizerUserId': '1',  # <EMAIL>
                'topics': ['programming', 'misc'],
                'startDate': now + datetime.timedelta(days=8),
                'endDate': now + datetime.timedelta(days=10),
                'maxAttendees': 6,
                'sessions': []
            },
            {
                'name': 'room #4',
                'organizerUserId': '2',  # <EMAIL>
                'topics': ['misc'],
                'startDate': now + datetime.timedelta(days=10),
                'endDate': now + datetime.timedelta(days=20),
                'maxAttendees': 6,
                'sessions': [
                    {'name': 'Intro to Poker', 'speaker': 'joker', 'typeOfSession': 'fun',
                     'date': (now + datetime.timedelta(days=10)).date(),
                     'startTime': (now + datetime.timedelta(days=10)).time(), 'duration': 60},
                    {'name': 'Google App Engine', 'speaker': '<NAME>', 'typeOfSession': 'informative',
                     'date': (now + datetime.timedelta(days=10)).date(),
                     'startTime': (now + datetime.timedelta(days=10, hours=1)).time(), 'duration': 60}
                ]

            }
        ]
        # add conferences to database
        for data in _conferences:
            p_key = ndb.Key(Profile, data['organizerUserId'])
            c_id = Conference.allocate_ids(size=1, parent=p_key)[0]
            data['key'] = ndb.Key(Conference, c_id, parent=p_key)
            # pop the sessions from `data` and add the conference to the database
            sessions = data.pop('sessions')
            conf = Conference(**data)
            conf.put()
            # Now that the conference has been added to the database, we can add the sessions that
            # were previously removed using `pop()`
            for session in sessions:
                c_id = Session.allocate_ids(size=1, parent=conf.key)[0]
                session['key'] = ndb.Key(Session, c_id, parent=conf.key)
                Session(**session).put()

    def login(self, email='<EMAIL>', id='1', is_admin=False):
        """ Logs in user (using simulation). If no arguments are given, logs in using default user `<EMAIL>` """
        self.testbed.setup_env(
            user_email=email,
            user_id=id,
            user_is_admin='1' if is_admin else '0',
            overwrite=True)

    def logout(self):
        """ Logs out user (using simulation) """
        self.login('', '')

    def getUserId(self):
        """ Returns current user's id """
        user = users.get_current_user()
        if not user:
            raise ValueError("User must be logged in to retrieve user id")
        return getUserId(user)

    def testLogin(self):
        """ Ensures login simulation is working properly """
        assert not users.get_current_user()
        self.login()
        assert users.get_current_user().email() == '<EMAIL>'
        self.login(is_admin=True)
        assert users.is_current_user_admin()
<commit_msg>Add support for oauth login simulation<commit_after>import unittest
import datetime

from google.appengine.api import users
from google.appengine.api import memcache
from google.appengine.ext import ndb
from google.appengine.ext import testbed

from models import (
    Profile,
    Conference,
    Session,
)

from utils import getUserId


class BaseEndpointAPITestCase(unittest.TestCase):
    """ Base endpoint API unit tests. """

    def setUp(self):
        # First, create an instance of the Testbed class.
        self.testbed = testbed.Testbed()
        # Then activate the testbed, which prepares the service stubs for use.
        self.testbed.activate()
        # Next, declare which service stubs you want to use.
        self.testbed.init_datastore_v3_stub()
        self.testbed.init_memcache_stub()
        self.testbed.init_user_stub()
        # Clear ndb's in-context cache between tests.
        # This prevents data from leaking between tests.
        # Alternatively, you could disable caching by
        # using ndb.get_context().set_cache_policy(False)
        ndb.get_context().clear_cache()

    def tearDown(self):
        self.testbed.deactivate()

    def initDatabase(self):
        """ Adds database fixtures """
        _profiles = [
            {'displayName': 'Luiz', 'mainEmail': '<EMAIL>', 'teeShirtSize': '1', 'conferenceKeysToAttend': []},
            {'displayName': 'Batman', 'mainEmail': '<EMAIL>', 'teeShirtSize': '2', 'conferenceKeysToAttend': []},
            {'displayName': 'Goku', 'mainEmail': '<EMAIL>', 'teeShirtSize': '3', 'conferenceKeysToAttend': []}
        ]
        # add profiles to database
        ndb.put_multi([Profile(**p) for p in _profiles])

        now = datetime.datetime.now()
        # 3 conferences with `<EMAIL>`
        # 1 conference with `<EMAIL>`
        _conferences = [
            {
                'name': 'room #1',
                'organizerUserId': '<EMAIL>',
                'topics': ['programming', 'web design', 'web performance'],
                'city': 'London',
                'startDate': now,
                'endDate': now + datetime.timedelta(days=5),
                'maxAttendees': 100,
                'sessions': [
                    {'name': 'PHP', 'speaker': 'superman', 'typeOfSession': 'educational',
                     'date': (now + datetime.timedelta(days=10)).date(),
                     'startTime': (now + datetime.timedelta(days=1)).time(), 'duration': 60},
                    {'name': 'Python', 'speaker': 'flash', 'typeOfSession': 'educational',
                     'date': (now + datetime.timedelta(days=10)).date(),
                     'startTime': (now + datetime.timedelta(days=1, hours=1)).time(), 'duration': 60}
                ]
            },
            {
                'name': 'room #2',
                'organizerUserId': '<EMAIL>',
                'topics': ['web performance'],
                'city': 'Baton Rouge',
                'startDate': now + datetime.timedelta(days=10),
                'endDate': now + datetime.timedelta(days=20),
                'maxAttendees': 5,
                'sessions': []
            },
            {
                'name': 'room #3',
                'organizerUserId': '<EMAIL>',
                'topics': ['programming', 'misc'],
                'startDate': now + datetime.timedelta(days=8),
                'endDate': now + datetime.timedelta(days=10),
                'maxAttendees': 6,
                'sessions': []
            },
            {
                'name': 'room #4',
                'organizerUserId': '<EMAIL>',
                'topics': ['misc'],
                'startDate': now + datetime.timedelta(days=10),
                'endDate': now + datetime.timedelta(days=20),
                'maxAttendees': 6,
                'sessions': [
                    {'name': 'Intro to Poker', 'speaker': 'joker', 'typeOfSession': 'fun',
                     'date': (now + datetime.timedelta(days=10)).date(),
                     'startTime': (now + datetime.timedelta(days=10)).time(), 'duration': 60},
                    {'name': 'Google App Engine', 'speaker': '<NAME>', 'typeOfSession': 'informative',
                     'date': (now + datetime.timedelta(days=10)).date(),
                     'startTime': (now + datetime.timedelta(days=10, hours=1)).time(), 'duration': 60}
                ]

            }
        ]
        # add conferences to database
        for data in _conferences:
            p_key = ndb.Key(Profile, data['organizerUserId'])
            c_id = Conference.allocate_ids(size=1, parent=p_key)[0]
            data['key'] = ndb.Key(Conference, c_id, parent=p_key)
            # pop the sessions from `data` and add the conference to the database
            sessions = data.pop('sessions')
            conf = Conference(**data)
            conf.put()
            # Now that the conference has been added to the database, we can add the sessions that
            # were previously removed using `pop()`
            for session in sessions:
                c_id = Session.allocate_ids(size=1, parent=conf.key)[0]
                session['key'] = ndb.Key(Session, c_id, parent=conf.key)
                Session(**session).put()

    def login(self, email='<EMAIL>', is_admin=False):
        """ Logs in user (using simulation). If no arguments are given, logs in using default user `<EMAIL>` """
        self.testbed.setup_env(
            user_email=email,
            user_is_admin='1' if is_admin else '0',
            overwrite=True,
            # support oauth login using `endpoints.get_current_user()`
            ENDPOINTS_AUTH_EMAIL=email,
            ENDPOINTS_AUTH_DOMAIN='testing.com'
        )

    def logout(self):
        """ Logs out user (using simulation) """
        self.login('')

    def getUserId(self):
        """ Returns current user's id """
        user = users.get_current_user()
        if not user:
            raise ValueError("User must be logged in to retrieve user id")
        return getUserId(user)

    def testLogin(self):
        """ Ensures login simulation is working properly """
        assert not users.get_current_user()
        self.login()
        assert users.get_current_user().email() == '<EMAIL>'
        self.login(is_admin=True)
        assert users.is_current_user_admin()
        self.logout()
        assert not users.get_current_user()

{'fraction_non_alphanumeric': 0.1374673732500198, 'fraction_numerical': 0.009807798781934668, 'mean_word_length': 1.9736594543744121, 'pattern_counts': {'":': 0, '<': 29, '<?xml version=': 0, '>': 29, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '563549', 'n_tokens_mistral': 3703, 'n_tokens_neox': 3530, 'n_words': 880}