view tests/test_app.py @ 10:102514eec446

made summitidp package and tests dir
author Atul Varma <avarma@mozilla.com>
date Thu, 24 Jun 2010 17:40:50 -0700
parents test_server.py@06c48ff76ade
children 03c5651a371e
line wrap: on
line source

import simplejson as json
import datetime

from webtest import TestApp

from summitidp.app import Server, gentoken

server = None
app = None

def apptest(func):
    def wrapper():
        g = globals()

        EmailMachine.emails = []
        EntropyMachine.next = []
        TimeMachine.now = datetime.datetime(2010, 6, 17, 0, 32, 33, 985904)

        g['server'] = Server(['bob@foo.com', 'jane@bar.com'],
                             send_email=EmailMachine.send_email,
                             utcnow=TimeMachine.utcnow,
                             gentoken=EntropyMachine.gentoken)
        g['app'] = TestApp(server.wsgi_app)

        func()

    wrapper.__name__ = func.__name__
    return wrapper

class EmailMachine(object):
    emails = []

    @classmethod
    def send_email(klass, email, token):
        klass.emails.append((email, token))

class EntropyMachine(object):
    next = []

    @classmethod
    def gentoken(klass):
        if klass.next:
            return klass.next.pop()
        return gentoken()

class TimeMachine(object):
    now = None

    @classmethod
    def travel(klass, timedelta=None, *args, **kwargs):
        if timedelta is None:
            timedelta = datetime.timedelta(*args, **kwargs)

        klass.now += timedelta

    @classmethod
    def utcnow(klass):
        return klass.now

def post_json(url, obj, **kwargs):
    return app.post(url, json.dumps(obj),
                    {'Content-Type': 'application/json'},
                    **kwargs)

@apptest
def test_request_challenge():
    EntropyMachine.next.append('a token')
    resp = post_json(server.request_challenge_path,
                     {'email': 'bob@foo.com'})
    assert resp.json == {'success': True}
    assert EmailMachine.emails == [('bob@foo.com', 'a token')]

@apptest
def test_request_challenge_with_invalid_email():
    post_json(server.request_challenge_path,
              {'email': 'invalid@foo.com'},
              status=400)

@apptest
def test_request_challenge_with_invalid_body1():
    post_json(server.request_challenge_path,
              [],
              status=400)

@apptest
def test_request_challenge_with_invalid_body2():
    post_json(server.request_challenge_path,
              {'blah': 'narg'},
              status=400)

@apptest
def test_respond_to_challenge():
    token = server.challenge_tokens.create(email='bob@foo.com')
    EntropyMachine.next.append('my auth token')
    resp = post_json(server.respond_to_challenge_path,
                     {'token': token})
    assert resp.json == {'email': 'bob@foo.com',
                         'token': 'my auth token'}
    assert server.auth_tokens.get('my auth token') == {
        'email': 'bob@foo.com',
        'user_id': 0
        }

@apptest
def test_respond_to_expired_challenge():
    token = server.challenge_tokens.create(email='bob@foo.com')
    TimeMachine.travel(server.challenge_tokens.lifetime * 2)
    post_json(server.respond_to_challenge_path,
              {'token': token},
              status=400)

@apptest
def test_respond_to_challenge_only_works_once():
    token = server.challenge_tokens.create(email='bob@foo.com')
    EntropyMachine.next.append('my auth token')
    resp = post_json(server.respond_to_challenge_path,
                     {'token': token})
    assert resp.json == {'email': 'bob@foo.com',
                         'token': 'my auth token'}
    post_json(server.respond_to_challenge_path,
              {'token': token},
              status=400)

@apptest
def test_respond_to_challenge_with_invalid_token():
    post_json(server.respond_to_challenge_path,
              {'token': 'hello there'},
              status=400)

@apptest
def test_respond_to_challenge_with_invalid_body():
    post_json(server.respond_to_challenge_path,
              [],
              status=400)

@apptest
def test_basic_404():
    app.get('/blarg', status=404)

@apptest
def test_set_profile_with_bad_token():
    post_json(server.profile_path,
              {'token': 'blap', 'contents': {}},
              status=400)

@apptest
def test_set_profile_with_no_contents():
    token = server.auth_tokens.create(email='bob@foo.com',
                                      user_id=0)
    post_json(server.profile_path,
              {'token': token},
              status=400)

@apptest
def test_get_profile_with_bad_token():
    app.get('%s?token=%s' % (server.profile_path, 'blap'),
            status=400)

@apptest
def test_get_profile_with_no_token():
    app.get('%s?foo=bar' % server.profile_path,
            status=400)

@apptest
def test_set_and_get_profile():
    token = server.auth_tokens.create(email='bob@foo.com',
                                      user_id=0)
    post_json(server.profile_path,
              {'token': token,
               'contents': {'name': 'bob jones'}})
    resp = app.get('%s?token=%s' % (server.profile_path, token))
    assert resp.json == {"contents": {"0": {"name": "bob jones"}}}

    # Make sure it works twice.

    post_json(server.profile_path,
              {'token': token,
               'contents': {'alias': 'blah'}})
    resp = app.get('%s?token=%s' % (server.profile_path, token))
    assert resp.json == {"contents": {"0": {"alias": "blah"}}}

    # Add another user's profile.

    token2 = server.auth_tokens.create(email='jane@bar.com',
                                       user_id=1)
    post_json(server.profile_path,
              {'token': token2,
               'contents': {'name': 'jane person'}})
    resp = app.get('%s?token=%s' % (server.profile_path, token2))
    assert resp.json == {"contents": {"0": {"alias": "blah"},
                                      "1": {"name": "jane person"}}}