示例#1
0
def test_set_user_by_instance(session_scope_function):
    add_user(session_scope_function, name='test_user', password='******',
             lastname='lastname', firstname='firstname',
             email='*****@*****.**', access_level='asked')
    add_user(session_scope_function, name='test_user_2',
             password='******', lastname='lastname',
             firstname='firstname', email='*****@*****.**',
             access_level='asked')
    user = get_user_by_name(session_scope_function, 'test_user')
    set_user_by_instance(session_scope_function, user, lastname='a',
                         firstname='b', email='c', linkedin_url='d',
                         twitter_url='e', facebook_url='f', google_url='g',
                         github_url='h', website_url='i', bio='j',
                         is_want_news=False)
    user = get_user_by_name(session_scope_function, 'test_user')
    assert user.lastname == 'a'
    assert user.firstname == 'b'
    assert user.email == 'c'
    assert user.linkedin_url == 'd'
    assert user.twitter_url == 'e'
    assert user.facebook_url == 'f'
    assert user.google_url == 'g'
    assert user.github_url == 'h'
    assert user.website_url == 'i'
    assert user.bio == 'j'
    assert user.is_want_news is False
示例#2
0
def test_reset_password(client_session):
    client, session = client_session

    # GET method
    rv = client.get('/reset_password')
    assert rv.status_code == 200
    assert b'If you are a registered user, we are going to send' in rv.data

    # POST method
    # check that we raise an error if the email does not exist
    rv = client.post('/reset_password', data={'email': '*****@*****.**'})
    assert rv.status_code == 200
    assert b'You can sign-up instead.' in rv.data

    # set a user to "asked" access level
    user = get_user_by_name(session, 'test_user')
    user.access_level = 'asked'
    session.commit()
    rv = client.post('/reset_password', data={'email': user.email})
    assert rv.status_code == 200
    assert b'Your account has not been yet approved.' in rv.data

    # set back the account to 'user' access level
    user.access_level = 'user'
    session.commit()
    rv = client.post('/reset_password', data={'email': user.email})
    with client.session_transaction() as cs:
        flash_message = dict(cs['_flashes'])
    assert flash_message['message'] == ('An email to reset your password has '
                                        'been sent')
    assert rv.status_code == 302
    assert rv.location == 'http://localhost/login'

    with client.application.app_context():
        with mail.record_messages() as outbox:
            rv = client.post('/reset_password', data={'email': user.email})
            assert len(outbox) == 1
            assert 'click on the link to reset your password' in outbox[0].body
            # get the link to reset the password
            reg_exp = re.search("http://localhost/reset/.*", outbox[0].body)
            reset_password_link = reg_exp.group()
            # remove the part with 'localhost' for the next query
            reset_password_link = reset_password_link[reset_password_link.
                                                      find('/reset'):]

    # check that we can reset the password using the previous link
    # GET method
    rv = client.get(reset_password_link)
    assert rv.status_code == 200
    assert b'Change my password' in rv.data

    # POST method
    new_password = '******'
    rv = client.post(reset_password_link, data={'password': new_password})
    assert rv.status_code == 302
    assert rv.location == 'http://localhost/login'
    # make a commit to be sure that the update has been done
    session.commit()
    user = get_user_by_name(session, 'test_user')
    assert check_password(new_password, user.hashed_password)
示例#3
0
def test_reset_token_error(client_session):
    client, session = client_session

    # POST method
    new_password = '******'
    rv = client.post('/reset/xxx', data={'password': new_password})
    assert rv.status_code == 404

    # Get get the link to a real token but remove the user in between
    user = get_user_by_name(session, 'test_user')
    with client.application.app_context():
        with mail.record_messages() as outbox:
            rv = client.post('/reset_password', data={'email': user.email})
            assert len(outbox) == 1
            assert 'click on the link to reset your password' in outbox[0].body
            # get the link to reset the password
            reg_exp = re.search("http://localhost/reset/.*", outbox[0].body)
            reset_password_link = reg_exp.group()
            # remove the part with 'localhost' for the next query
            reset_password_link = reset_password_link[reset_password_link.
                                                      find('/reset'):]

    user = get_user_by_name(session, 'test_user')
    session.delete(user)
    session.commit()
    new_password = '******'
    rv = client.post(reset_password_link, data={'password': new_password})
    assert rv.status_code == 404
示例#4
0
def test_add_user(session_scope_function):
    name = 'test_user'
    password = '******'
    lastname = 'Test'
    firstname = 'User'
    email = '*****@*****.**'
    access_level = 'asked'
    add_user(session_scope_function,
             name=name,
             password=password,
             lastname=lastname,
             firstname=firstname,
             email=email,
             access_level=access_level)
    user = get_user_by_name(session_scope_function, name)
    assert user.name == name
    assert check_password(password, user.hashed_password)
    assert user.lastname == lastname
    assert user.firstname == firstname
    assert user.email == email
    assert user.access_level == access_level
    # check that a team was automatically added with the new user
    team = get_team_by_name(session_scope_function, name)
    assert team.name == name
    assert team.admin_id == user.id
    # check that we get an error if we try to add the same user
    with pytest.raises(NameClashError, match='email is already in use'):
        add_user(session_scope_function,
                 name=name,
                 password=password,
                 lastname=lastname,
                 firstname=firstname,
                 email=email,
                 access_level=access_level)
    # check that the checking is case insensitive
    with pytest.raises(NameClashError, match='email is already in use'):
        add_user(session_scope_function,
                 name=name,
                 password=password,
                 lastname=lastname,
                 firstname=firstname,
                 email=email.capitalize(),
                 access_level=access_level)
    # add a user email with some capital letters and check that only lower case
    # are stored in the database
    name = 'new_user_name'
    email = '*****@*****.**'
    add_user(session_scope_function,
             name=name,
             password=password,
             lastname=lastname,
             firstname=firstname,
             email=email,
             access_level=access_level)
    user = get_user_by_name(session_scope_function, name)
    assert user.email == '*****@*****.**'
示例#5
0
def test_approve_user(session_scope_function):
    add_user(session_scope_function, name='test_user', password='******',
             lastname='Test', firstname='User', email='*****@*****.**',
             access_level='asked')
    user = get_user_by_name(session_scope_function, 'test_user')
    assert user.access_level == 'asked'
    assert user.is_authenticated is False
    approve_user(session_scope_function, 'test_user')
    user = get_user_by_name(session_scope_function, 'test_user')
    assert user.access_level == 'user'
    assert user.is_authenticated is True
示例#6
0
def test_sign_up(client_session):
    client, session = client_session

    # GET on sign-up
    rv = client.get('/sign_up')
    assert rv.status_code == 200
    assert b'Sign Up' in rv.data

    # POST on sign-up
    user_profile = {'user_name': 'xx', 'password': '******', 'firstname': 'xx',
                    'lastname': 'xx', 'email': 'xx'}
    rv = client.post('/sign_up', data=user_profile)
    assert rv.status_code == 200
    user = get_user_by_name(session, 'xx')
    assert user.name == 'xx'
    user_profile = {'user_name': 'yy', 'password': '******', 'firstname': 'yy',
                    'lastname': 'yy', 'email': 'yy'}
    rv = client.post('/sign_up', data=user_profile, follow_redirects=True)
    assert rv.status_code == 200

    # check that we catch a flash error if we try to sign-up with an identical
    # username or email
    user_profile = {'user_name': 'test_user', 'password': '******',
                    'firstname': 'xx', 'lastname': 'xx',
                    'email': '*****@*****.**'}
    rv = client.post('/sign_up', data=user_profile)
    with client.session_transaction() as cs:
        flash_message = dict(cs['_flashes'])
    assert (flash_message['message'] ==
            'username is already in use and email is already in use')
    assert rv.status_code == 200
示例#7
0
def test_approve_single_user(client_session):
    client, session = client_session

    add_user(session, 'aa', 'aa', 'aa', 'aa', 'aa', access_level='asked')
    with login_scope(client, 'test_iris_admin', 'test') as client:
        rv = client.get('/sign_up/aa')
        assert rv.status_code == 302
        assert rv.location == 'http://localhost/problems'
        with client.session_transaction() as cs:
            flash_message = dict(cs['_flashes'])
        assert re.match("User(.*aa.*) is signed up",
                        flash_message['Successful sign-up'])

        # ensure that the previous change have been committed within our
        # session
        session.commit()
        user = get_user_by_name(session, 'aa')
        assert user.access_level == 'user'

        rv = client.get("/sign_up/unknown_user")
        session.commit()
        assert rv.status_code == 302
        assert rv.location == "http://localhost/problems"
        with client.session_transaction() as cs:
            flash_message = dict(cs['_flashes'])
        assert flash_message['message'] == 'No user unknown_user'
示例#8
0
def test_update_profile(client_session):
    client, session = client_session

    # try to change the profile without being logged-in
    rv = client.get('/update_profile')
    assert rv.status_code == 302
    assert rv.location == 'http://localhost/login?next=%2Fupdate_profile'
    rv = client.get('/update_profile', follow_redirects=True)
    assert rv.status_code == 200

    with login_scope(client, 'test_user', 'test') as client:
        # GET function once logged-in
        rv = client.get('/update_profile')
        assert rv.status_code == 200
        for attr in [b'Username', b'First name', b'Last name', b'Email',
                     b'User', b'Test', b'*****@*****.**']:
            assert attr in rv.data

        # POST function once logged-in
        user_profile = {'lastname': 'XXX', 'firstname': 'YYY',
                        'email': '*****@*****.**'}
        rv = client.post('/update_profile', data=user_profile)
        assert rv.status_code == 302
        assert rv.location == 'http://localhost/problems'
        user = get_user_by_name(session, 'test_user')
        assert user.lastname == 'XXX'
        assert user.firstname == 'YYY'
        assert user.email == '*****@*****.**'
        user_profile = {'lastname': 'Test', 'firstname': 'User',
                        'email': '*****@*****.**'}
        rv = client.post('/update_profile', data=user_profile,
                         follow_redirects=True)
        assert rv.status_code == 200
示例#9
0
def test_user_model_backref(session_scope_module, backref, expected_type):
    user = get_user_by_name(session_scope_module, 'test_user')
    backref_attr = getattr(user, backref)
    assert isinstance(backref_attr, list)
    # only check if the list is not empty
    if backref_attr:
        assert isinstance(backref_attr[0], expected_type)
示例#10
0
def test_check_user_interactions(session_scope_function, output_format,
                                 expected_format):
    add_user(session_scope_function,
             name='test_user',
             password='******',
             lastname='lastname',
             firstname='firstname',
             email='*****@*****.**',
             access_level='asked')
    params = {'interaction': 'landing'}
    add_user_interaction(session_scope_function, **params)
    params = {
        'interaction': 'landing',
        'user': get_user_by_name(session_scope_function, 'test_user')
    }
    add_user_interaction(session_scope_function, **params)
    user_interaction = get_user_interactions_by_name(
        session_scope_function, output_format=output_format)
    if isinstance(user_interaction, pd.DataFrame):
        assert user_interaction.shape[0] == 2
    assert isinstance(user_interaction, expected_format)
    user_interaction = get_user_interactions_by_name(
        session_scope_function, name='test_user', output_format=output_format)
    if isinstance(user_interaction, pd.DataFrame):
        assert user_interaction.shape[0] == 1
示例#11
0
def test_sign_up(client_session):
    client, session = client_session

    # GET on sign-up
    rv = client.get('/sign_up')
    assert rv.status_code == 200
    assert b'Sign Up' in rv.data

    # POST on sign-up
    user_profile = {
        'user_name': 'xx',
        'password': '******',
        'firstname': 'xx',
        'lastname': 'xx',
        'email': 'xx'
    }
    rv = client.post('/sign_up', data=user_profile)
    assert rv.status_code == 302
    assert rv.location == 'http://localhost/login'
    user = get_user_by_name(session, 'xx')
    assert user.name == 'xx'
    user_profile = {
        'user_name': 'yy',
        'password': '******',
        'firstname': 'yy',
        'lastname': 'yy',
        'email': 'yy'
    }
    rv = client.post('/sign_up', data=user_profile, follow_redirects=True)
    assert rv.status_code == 200
示例#12
0
def test_add_user(session_scope_function):
    name = 'test_user'
    password = '******'
    lastname = 'Test'
    firstname = 'User'
    email = '*****@*****.**'
    access_level = 'asked'
    add_user(session_scope_function,
             name=name,
             password=password,
             lastname=lastname,
             firstname=firstname,
             email=email,
             access_level=access_level)
    user = get_user_by_name(session_scope_function, name)
    assert user.name == name
    assert check_password(password, user.hashed_password)
    assert user.lastname == lastname
    assert user.firstname == firstname
    assert user.email == email
    assert user.access_level == access_level
    # check that a team was automatically added with the new user
    team = get_team_by_name(session_scope_function, name)
    assert team.name == name
    assert team.admin_id == user.id
示例#13
0
def test_user_model_properties(session_scope_module):
    user = get_user_by_name(session_scope_module, 'test_user')

    assert user.is_active is True
    assert user.is_anonymous is False
    assert user.get_id() == '1'
    assert re.match(r'User\(.*test_user.*\)', str(user))
    assert re.match(r'User\(name=.*test_user.*, lastname.*\)', repr(user))
示例#14
0
def test_body_formatter_user(client_session):
    _, session = client_session
    user = get_user_by_name(session, 'test_user')
    for word in [
            'test_user', 'User', 'Test', 'linkedin', 'twitter', 'facebook',
            'github', 'notes', 'bio'
    ]:
        assert word in body_formatter_user(user)
示例#15
0
def test_add_users(session_scope_function):
    add_users(session_scope_function)
    users = get_user_by_name(session_scope_function, None)
    for user in users:
        assert user.name in ('test_user', 'test_user_2', 'test_iris_admin')
    err_msg = 'username is already in use'
    with pytest.raises(NameClashError, match=err_msg):
        add_users(session_scope_function)
示例#16
0
def test_is_accessible_code(session_toy_db):
    event_name = 'iris_test'
    # simulate a user which is not authenticated
    user = get_user_by_name(session_toy_db, 'test_user_2')
    user.is_authenticated = False
    assert not is_accessible_code(session_toy_db, event_name, user.name)
    # simulate a user which authenticated and author of the submission to a
    # public event
    user.is_authenticated = True
    assert is_accessible_code(session_toy_db, event_name, user.name)
    # simulate an admin user
    user = get_user_by_name(session_toy_db, 'test_iris_admin')
    user.is_authenticated = True
    assert is_accessible_code(session_toy_db, event_name, 'test_iris_admin')
    # simulate a user which is not signed up to the event
    user = add_user(session_toy_db, 'xx', 'xx', 'xx', 'xx', 'xx', 'user')
    user.is_authenticated = True
    assert not is_accessible_code(session_toy_db, event_name, user.name)
示例#17
0
def test_get_user_by_name(session_scope_function, name, query_type):
    add_user(session_scope_function, name='test_user', password='******',
             lastname='lastname', firstname='firstname',
             email='*****@*****.**', access_level='asked')
    add_user(session_scope_function, name='test_user_2',
             password='******', lastname='lastname',
             firstname='firstname', email='*****@*****.**',
             access_level='asked')
    user = get_user_by_name(session_scope_function, name)
    assert isinstance(user, query_type)
示例#18
0
def test_is_accessible_leaderboard(session_toy_db):
    event_name = 'iris_test'
    # simulate a user which is not authenticated
    user = get_user_by_name(session_toy_db, 'test_user_2')
    user.is_authenticated = False
    assert not is_accessible_leaderboard(session_toy_db, event_name, user.name)
    # simulate a user which authenticated and author of the submission to a
    # public event
    user.is_authenticated = True
    assert not is_accessible_leaderboard(session_toy_db, event_name, user.name)
    # simulate an admin user
    user = get_user_by_name(session_toy_db, 'test_iris_admin')
    user.is_authenticated = True
    assert is_accessible_leaderboard(session_toy_db, event_name,
                                     'test_iris_admin')
    # simulate a close event
    event = get_event(session_toy_db, event_name)
    event.closing_timestamp = datetime.datetime.utcnow()
    assert not is_accessible_leaderboard(session_toy_db, event_name,
                                         'test_user_2')
示例#19
0
def test_is_accessible_event(session_toy_db, event_name, user_name,
                             is_accessible):
    # force one of the user to not be approved
    if user_name == 'test_user':
        user = get_user_by_name(session_toy_db, user_name)
        user.access_level = 'asked'
        session_toy_db.commit()
    # force an event to be private
    if event_name == 'boston_housing_test':
        event = get_event(session_toy_db, event_name)
        event.is_public = False
        session_toy_db.commit()
    assert is_accessible_event(session_toy_db, event_name,
                               user_name) is is_accessible
示例#20
0
def test_set_user_access_level(session_scope_function, access_level):
    username = '******'
    user = add_user(session_scope_function,
                    name=username,
                    password='******',
                    lastname='lastname',
                    firstname='firstname',
                    email='*****@*****.**',
                    access_level='asked')
    assert user.access_level == 'asked'
    assert user.is_authenticated is False
    set_user_access_level(session_scope_function, username, access_level)
    user = get_user_by_name(session_scope_function, username)
    assert user.access_level == access_level
    assert user.is_authenticated is True
示例#21
0
def test_add_submission_similarity(session_scope_module):
    user = get_user_by_name(session_scope_module, 'test_user')
    source_submission = get_submission_by_id(session_scope_module, 1)
    target_submission = get_submission_by_id(session_scope_module, 2)
    add_submission_similarity(session_scope_module, 'target_credit', user,
                              source_submission, target_submission, 0.5,
                              datetime.datetime.utcnow())
    similarity = session_scope_module.query(SubmissionSimilarity).all()
    assert len(similarity) == 1
    similarity = similarity[0]
    assert similarity.type == 'target_credit'
    assert similarity.user == user
    assert similarity.source_submission == source_submission
    assert similarity.target_submission == target_submission
    assert similarity.similarity == pytest.approx(0.5)
    assert isinstance(similarity.timestamp, datetime.datetime)
示例#22
0
def test_approve_users_remove(client_session):
    client, session = client_session

    # create 2 new users
    add_user(session, 'xx', 'xx', 'xx', 'xx', 'xx', access_level='user')
    add_user(session, 'yy', 'yy', 'yy', 'yy', 'yy', access_level='asked')
    # ask for sign up for an event for the first user
    _, _, event_team = ask_sign_up_team(session, 'iris_test', 'xx')

    with login_scope(client, 'test_iris_admin', 'test') as client:

        # GET check that we get all new user to be approved
        rv = client.get('/approve_users')
        assert rv.status_code == 200
        # line for user approval
        assert b'yy: yy yy - yy' in rv.data
        # line for the event approval
        assert b'iris_test - xx'

        # POST check that we are able to approve a user and event
        data = ImmutableMultiDict([('submit_button', 'Remove!'),
                                   ('approve_users', 'yy'),
                                   ('approve_event_teams', str(event_team.id))
                                   ])
        rv = client.post('/approve_users', data=data)
        assert rv.status_code == 302
        assert rv.location == 'http://localhost/problems'

        # ensure that the previous change have been committed within our
        # session
        session.commit()
        user = get_user_by_name(session, 'yy')
        assert user is None
        event_team = get_event_team_by_name(session, 'iris_test', 'xx')
        assert event_team is None
        with client.session_transaction() as cs:
            flash_message = dict(cs['_flashes'])
            print(flash_message)
        assert re.match(
            r"Removed users:\nyy\nRemoved event_team:\n"
            r"Event\(iris_test\)/Team\(.*xx.*\)\n",
            flash_message['Removed users'])
示例#23
0
def test_logout(client_session):
    client, session = client_session

    # logout without previous login
    rv = client.get('/logout')
    assert rv.status_code == 302
    assert rv.location == 'http://localhost/login?next=%2Flogout'
    rv = client.get('/logout', follow_redirects=True)
    assert rv.status_code == 200

    # logout from a previous login
    login(client, 'test_user', 'test')
    rv = client.get('/logout')
    assert rv.status_code == 302
    assert rv.location == 'http://localhost/login'
    user = get_user_by_name(session, 'test_user')
    assert not user.is_authenticated
    login(client, 'test_user', 'test')
    rv = client.get('/logout', follow_redirects=True)
    assert rv.status_code == 200
示例#24
0
def login():
    """Login request."""
    if app.config['TRACK_USER_INTERACTION']:
        add_user_interaction(db.session, interaction='landing')

    if flask_login.current_user.is_authenticated:
        logger.info('User already logged-in')
        session['logged_in'] = True
        return redirect(url_for('ramp.problems'))

    form = LoginForm()
    if form.validate_on_submit():
        try:
            user = get_user_by_name(db.session, name=form.user_name.data)
        except NoResultFound:
            msg = u'User "{}" does not exist'.format(form.user_name.data)
            flash(msg)
            logger.info(msg)
            return redirect(url_for('auth.login'))
        if not check_password(form.password.data, user.hashed_password):
            msg = 'Wrong password'
            flash(msg)
            logger.info(msg)
            return redirect(url_for('auth.login'))
        flask_login.login_user(user, remember=True)
        session['logged_in'] = True
        user.is_authenticated = True
        db.session.commit()
        logger.info(u'User "{}" is logged in'.format(
            flask_login.current_user.name))
        if app.config['TRACK_USER_INTERACTION']:
            add_user_interaction(db.session,
                                 interaction='login',
                                 user=flask_login.current_user)
        next_ = request.args.get('next')
        if next_ is None:
            next_ = url_for('ramp.problems')
        return redirect(next_)

    return render_template('login.html', form=form)
示例#25
0
def test_login(client_session):
    client, session = client_session

    # GET without any previous login
    rv = client.get('/login')
    assert rv.status_code == 200
    assert b'Login' in rv.data
    assert b'Username' in rv.data
    assert b'Password' in rv.data

    # GET with a previous login
    with login_scope(client, 'test_user', 'test') as client:
        rv = client.get('/login')
        assert rv.status_code == 302
        assert rv.location == 'http://localhost/problems'
        rv = client.get('/login', follow_redirects=True)
        assert rv.status_code == 200

    # POST with unknown username
    login_info = {'user_name': 'unknown', 'password': '******'}
    rv = client.post('/login', data=login_info)
    with client.session_transaction() as cs:
        flash_message = dict(cs['_flashes'])
    assert flash_message['message'] == 'User "unknown" does not exist'
    assert rv.status_code == 302
    assert rv.location == 'http://localhost/login'
    rv = client.post('/login', data=login_info, follow_redirects=True)
    assert rv.status_code == 200

    # POST with wrong password
    login_info = {'user_name': 'test_user', 'password': '******'}
    rv = client.post('/login', data=login_info)
    with client.session_transaction() as cs:
        flash_message = dict(cs['_flashes'])
    assert flash_message['message'] == 'Wrong password'
    assert rv.status_code == 302
    assert rv.location == 'http://localhost/login'
    rv = client.post('/login', data=login_info, follow_redirects=True)
    assert rv.status_code == 200

    # POST with a right login and password
    login_info = {'user_name': 'test_user', 'password': '******'}
    rv = client.post('/login', data=login_info)
    assert rv.status_code == 302
    assert rv.location == 'http://localhost/problems'
    user = get_user_by_name(session, login_info['user_name'])
    assert user.is_authenticated
    logout(client)
    rv = client.post('/login', data=login_info, follow_redirects=True)
    assert rv.status_code == 200
    logout(client)

    # POST with right login and password from a different location webpage
    login_info = {'user_name': 'test_user', 'password': '******'}
    landing_page = {'next': 'http://localhost/events/iris_test'}
    rv = client.post('/login', data=login_info, query_string=landing_page)
    assert rv.status_code == 302
    assert rv.location == landing_page['next']
    logout(client)
    rv = client.post('/login',
                     data=login_info,
                     query_string=landing_page,
                     follow_redirects=True)
    assert rv.status_code == 200
    logout(client)
示例#26
0
def test_is_accessible_code(session_toy_db):
    # create a third user
    add_user(
        session_toy_db, name='test_user_3', password='******',
        lastname='Test_3', firstname='User_3',
        email='*****@*****.**', access_level='user')
    approve_user(session_toy_db, 'test_user_3')
    event_name = 'iris_test'
    sign_up_team(session_toy_db, event_name, 'test_user_3')
    # simulate a user which is not authenticated
    user = get_user_by_name(session_toy_db, 'test_user_2')
    user.is_authenticated = False
    assert not is_accessible_code(session_toy_db, event_name, user.name)
    # simulate a user which authenticated and author of the submission to a
    # public event
    user.is_authenticated = True
    assert is_accessible_code(session_toy_db, event_name, user.name)
    # simulate an admin user
    user = get_user_by_name(session_toy_db, 'test_iris_admin')
    user.is_authenticated = True
    assert is_accessible_code(session_toy_db, event_name, 'test_iris_admin')
    # simulate a user which is not signed up to the event
    user = add_user(session_toy_db, 'xx', 'xx', 'xx', 'xx', 'xx', 'user')
    user.is_authenticated = True
    assert not is_accessible_code(session_toy_db, event_name, user.name)
    # simulate that the event is not publicly opened
    event = get_event(session_toy_db, event_name)
    past_public_opening = event.public_opening_timestamp
    tomorrow = datetime.datetime.utcnow() + datetime.timedelta(days=1)
    event.public_opening_timestamp = tomorrow
    session_toy_db.commit()
    assert is_accessible_code(session_toy_db, event_name, 'test_user_3')
    # Make a submission
    submission_name = 'random_forest_10_10'
    ramp_config = generate_ramp_config(read_config(ramp_config_template()))
    path_submission = os.path.join(
        os.path.dirname(ramp_config['ramp_sandbox_dir']), submission_name
    )
    sub = add_submission(
        session_toy_db, event_name, 'test_user_3', submission_name,
        path_submission
    )
    # check that the user submitting the submission could access it
    assert is_accessible_code(
        session_toy_db, event_name, 'test_user_3', sub.id
    )
    # change the admin of the team
    from ramp_database.model import Team, User
    team = (session_toy_db.query(Team)
                          .filter(Team.name == 'test_user_3')
                          .first())
    user = (session_toy_db.query(User)
                          .filter(User.name == 'test_user_2')
                          .first())
    team.admin_id = user.id
    team.admin = user
    session_toy_db.commit()
    # check that the admin can access the submission
    assert is_accessible_code(
        session_toy_db, event_name, 'test_user_2', sub.id
    )
    # but others cannot
    assert not is_accessible_code(
        session_toy_db, event_name, 'test_user_3', sub.id
    )
    event.public_opening_timestamp = past_public_opening
    session_toy_db.commit()
示例#27
0
def test_sign_up_with_approval(client_session):
    # check the sign-up and email confirmation framework
    client, session = client_session

    with client.application.app_context():
        with mail.record_messages() as outbox:
            user_profile = {
                'user_name': 'new_user_1',
                'password': '******',
                'firstname': 'xx',
                'lastname': 'xx',
                'email': '*****@*****.**'
            }
            rv = client.post('/sign_up', data=user_profile)
            # check the flash box to inform the user about the mail
            with client.session_transaction() as cs:
                flash_message = dict(cs['_flashes'])
            assert 'We sent a confirmation email.' in flash_message['message']
            # check that the email has been sent
            assert len(outbox) == 1
            assert ('click on the following link to confirm your email'
                    in outbox[0].body)
            # get the link to reset the password
            reg_exp = re.search("http://localhost/confirm_email/.*",
                                outbox[0].body)
            confirm_email_link = reg_exp.group()
            # remove the part with 'localhost' for the next query
            confirm_email_link = confirm_email_link[confirm_email_link.
                                                    find('/confirm_email'):]
            # check the redirection
            assert rv.status_code == 200
            user = get_user_by_name(session, 'new_user_1')
            assert user is not None
            assert user.access_level == 'not_confirmed'

    # POST method of the email confirmation
    with client.application.app_context():
        with mail.record_messages() as outbox:
            rv = client.post(confirm_email_link)
            # check the flash box to inform the user to wait for admin's
            # approval
            with client.session_transaction() as cs:
                flash_message = dict(cs['_flashes'])
            assert ('An email has been sent to the RAMP administrator'
                    in flash_message['message'])
            # check that we send an email to the administrator
            assert len(outbox) == 1
            assert "Approve registration of new_user_1" in outbox[0].subject
            # ensure that we have the last changes
            session.commit()
            user = get_user_by_name(session, 'new_user_1')
            assert user.access_level == 'asked'
            assert rv.status_code == 302
            assert rv.location == 'http://localhost/login'

    # POST to check that we raise the right errors
    # resend the confirmation for a user which already confirmed
    rv = client.post(confirm_email_link)
    with client.session_transaction() as cs:
        flash_message = dict(cs['_flashes'])
    assert ('Your email address already has been confirmed'
            in flash_message['error'])
    assert rv.status_code == 302
    assert rv.location == 'http://localhost/'
    # check when the user was already approved
    for status in ('user', 'admin'):
        user = get_user_by_name(session, 'new_user_1')
        user.access_level = status
        session.commit()
        rv = client.post(confirm_email_link)
        with client.session_transaction() as cs:
            flash_message = dict(cs['_flashes'])
        assert 'Your account is already approved.' in flash_message['error']
        assert rv.status_code == 302
        assert rv.location == 'http://localhost/login'
    # delete the user in the middle
    session.delete(user)
    session.commit()
    rv = client.post(confirm_email_link)
    with client.session_transaction() as cs:
        flash_message = dict(cs['_flashes'])
    assert 'You did not sign-up yet to RAMP.' in flash_message['error']
    assert rv.status_code == 302
    assert rv.location == 'http://localhost/sign_up'
    # access a token which does not exist
    rv = client.post('/confirm_email/xxx')
    assert rv.status_code == 404