Beispiel #1
0
def test_admin_can_ban_email_domain(client, user_info):
    register_user(client, user_info)
    promote_user_to_admin(client, user_info)

    rv = client.get(url_for('admin.domains', domain_type='email'))
    rv = client.post(url_for('do.ban_domain', domain_type='email'),
                     data=dict(csrf_token=csrf_token(rv.data),
                               domain='spam4u.com'),
                     follow_redirects=True)
    reply = json.loads(rv.data.decode('utf-8'))
    assert reply['status'] == 'ok'

    log_out_current_user(client)
    rv = client.get(url_for('auth.register'))
    with mail.record_messages() as outbox:
        data = dict(csrf_token=csrf_token(rv.data),
                    username='******',
                    password='******',
                    confirm='Safe123#$@lolnot',
                    email_required='*****@*****.**',
                    invitecode='',
                    accept_tos=True,
                    captcha='xyzzy')
        rv = client.post(url_for('auth.register'),
                         data=data,
                         follow_redirects=True)
        assert len(outbox) == 0
        assert b'do not accept emails' in rv.data
        assert b'Register' in rv.data
        assert b'Log out' not in rv.data
Beispiel #2
0
def test_reset_password(client, user_info):
    """A user can reset their password using a link sent to their email."""
    new_password = '******'
    assert new_password != user_info['password']
    register_user(client, user_info)
    log_out_current_user(client)

    with mail.record_messages() as outbox:
        rv = client.get(url_for('user.password_recovery'))
        rv = client.post(url_for('user.password_recovery'),
                         data=dict(csrf_token=csrf_token(rv.data),
                                   email=user_info['email'],
                                   captcha='xyzzy'))
        message = outbox.pop()
        assert message.send_to == {user_info['email']}
        soup = BeautifulSoup(message.html, 'html.parser')
        token = soup.a['href'].split('/')[-1]
        rv = client.get(url_for('user.password_reset', token=token),
                        follow_redirects=True)
        rv = client.post(url_for('do.reset'),
                         data=dict(csrf_token=csrf_token(rv.data),
                                   user=get_value(rv.data, 'user'),
                                   key=get_value(rv.data, 'key'),
                                   password=new_password,
                                   confirm=new_password))

        log_out_current_user(client)
        user_info['password'] = new_password
        log_in_user(client, user_info, expect_success=True)
def test_post_existing(client):
    """Can we POST a new resource properly?"""
    client.post('/artist/',
                data=json.dumps({
                    'Name': 'Jeff Knupp',
                }),
                headers={'Content-type': 'application/json'})
    response = client.post('/artist/',
                           data=json.dumps({
                               'Name': 'Jeff Knupp',
                           }),
                           headers={'Content-type': 'application/json'})

    assert response.status_code == 204
Beispiel #4
0
def test_post_existing(client):
    """Can we POST a new resource properly?"""
    client.post(
        '/artist/',
        data=json.dumps({
            'Name': 'Jeff Knupp',
            }),
        headers={'Content-type': 'application/json'})
    response = client.post(
        '/artist/',
        data=json.dumps({
            'Name': 'Jeff Knupp',
            }),
        headers={'Content-type': 'application/json'})

    assert response.status_code == 204
Beispiel #5
0
def test_post_create_user(client):
    user = {'name': 'User Name', 'type': 'email', 'contact': '*****@*****.**'}
    response = client.post('user',
                           data=json.dumps(user),
                           content_type='application/json')
    assert re.compile('[0-9]+').match(str(response.json))
    assert response.status_code == 200
Beispiel #6
0
def test_post_send_message(client):
    message = {'uid': '123456', 'message': 'test'}
    response = client.post('send',
                           data=json.dumps(message),
                           content_type='application/json')
    assert re.compile('[0-9]+').match(str(response.json))
    assert response.status_code == 200
Beispiel #7
0
def test_registration_login(client):
    """The registration page logs a user in if they register correctly."""
    rv = client.get(url_for('auth.register'))
    with mail.record_messages() as outbox:
        data = dict(csrf_token=csrf_token(rv.data),
                    username='******',
                    password='******',
                    confirm='Safe123#$@lolnot',
                    invitecode='',
                    accept_tos=True,
                    captcha='xyzzy')
        if email_validation_is_required():
            data['email_required'] = '*****@*****.**'
        else:
            data['email_optional'] = '*****@*****.**'
        rv = client.post(url_for('auth.register'),
                         data=data,
                         follow_redirects=True)

        if email_validation_is_required():
            assert b'spam' in rv.data  # Telling user to go check it.
            message = outbox[-1]
            soup = BeautifulSoup(message.html, 'html.parser')
            token = soup.a['href'].split('/')[-1]
            rv = client.get(url_for('auth.login_with_token', token=token),
                            follow_redirects=True)

        assert auth_provider.get_user_by_email(
            '*****@*****.**').name == 'supertester'
        assert b'Log out' in rv.data
Beispiel #8
0
def test_reregister(client, user_info, user2_info):
    "A user account which is unconfirmed after two days can be re-registered."
    rv = client.get(url_for('auth.register'))
    data = dict(csrf_token=csrf_token(rv.data),
                username=user_info['username'],
                password=user_info['password'],
                confirm=user_info['password'],
                invitecode='',
                accept_tos=True,
                email_required=user_info['email'],
                captcha='xyzzy')
    rv = client.post(url_for('auth.register'),
                     data=data,
                     follow_redirects=True)

    new_user = User.get(User.name == user_info['username'])
    assert new_user.status == UserStatus.PROBATION
    new_user.joindate -= timedelta(days=3)
    new_user.save()

    rv = client.get(url_for('auth.register'))
    with mail.record_messages() as outbox:
        data = dict(
            csrf_token=csrf_token(rv.data),
            username=user_info['username'],
            password=user_info['password'],
            confirm=user_info['password'],
            invitecode='',
            email_required=user2_info['email'],
            accept_tos=True,
        )
        rv = client.post(url_for('auth.register'),
                         data=data,
                         follow_redirects=True)

        assert b'spam' in rv.data  # Telling user to go check it.
        message = outbox[-1]
        assert message.send_to == {user2_info['email']}
        soup = BeautifulSoup(message.html, 'html.parser')
        token = soup.a['href'].split('/')[-1]
        rv = client.get(url_for('auth.login_with_token', token=token),
                        follow_redirects=True)
        assert b'Log out' in rv.data

    assert auth_provider.get_user_by_email(user_info['email']) == None
    assert (auth_provider.get_user_by_email(
        user2_info['email']).name == user_info['username'])
def test_post_missing_field(client):
    """Do we reject a POST with a missing required field?"""
    response = client.post('/album/',
                           data=json.dumps({
                               'ArtistId': 1,
                           }),
                           headers={'Content-type': 'application/json'})
    assert response.status_code == 400
Beispiel #10
0
def test_post_missing_field(client):
    """Do we reject a POST with a missing required field?"""
    response = client.post(
        '/album/',
        data=json.dumps({
            'ArtistId': 1,
            }),
        headers={'Content-type': 'application/json'})
    assert response.status_code == 400
Beispiel #11
0
def test_post_unknown_field(client):
    """Do we properly reject a POST with an unknown field?"""
    response = client.post(
        '/artist/',
        data=json.dumps({'foo': 'bar', 'Name': 'Jeff Knupp'}),
        headers={'Content-type': 'application/json'}
    )
    assert response.status_code == 400
    json_response = json.loads(response.get_data(as_text=True))
    assert json_response == {'message': 'Unknown field [foo]'}
def test_post(client):
    """Can we POST a new resource properly?"""
    response = client.post('/album/',
                           data=json.dumps({
                               'Title': 'Some Title',
                               'ArtistId': 1,
                           }),
                           headers={'Content-type': 'application/json'})
    assert response.status_code == 201
    assert json.loads(response.get_data(as_text=True)) == NEW_ALBUM
Beispiel #13
0
def test_post_unknown_field(client):
    """Do we properly reject a POST with an unknown field?"""
    response = client.post(
        '/artist/',
        data=json.dumps({'foo': 'bar', 'Name': 'Jeff Knupp'}),
        headers={'Content-type': 'application/json'}
    )
    assert response.status_code == 400
    json_response = json.loads(response.get_data(as_text=True))
    assert json_response == {'message': 'Unknown field [foo]'}
Beispiel #14
0
def test_validate_post_existing_resource(client):
    """Do we get back an error message when making a POST request on a resource that already exists?"""
    response = client.post('/user/',
                           data=json.dumps({
                               'name': 'Jeff Knupp',
                               'email': '*****@*****.**',
                           }),
                           headers={'Content-Type': 'application/json'})
    assert response.status_code == 400
    assert response.json['message'] == INVALID_ACTION_MESSAGE
Beispiel #15
0
def test_post(client):
    """Can we POST a new resource properly?"""
    response = client.post(
        '/album/',
        data=json.dumps({
            'Title': 'Some Title',
            'ArtistId': 1,
            }),
        headers={'Content-type': 'application/json'})
    assert response.status_code == 201
    assert json.loads(response.get_data(as_text=True)) == NEW_ALBUM
Beispiel #16
0
def test_validate_post(client):
    """Do we get back an error message when making a POST request that fails
    validation?"""
    response = client.post('/user',
                           data=json.dumps({
                               'name': 'Jeff Knupp',
                               'email': '*****@*****.**',
                           }),
                           headers={'Content-Type': 'application/json'})
    assert response.status_code == 400
    assert response.json['message'] == INVALID_ACTION_MESSAGE
Beispiel #17
0
def test_flask_app(client):
    """Does Emily run successfully as a Flask web server?"""
    response = client.get('/get_session')
    assert response.status_code == 200
    session_id = response.get_data(as_text=True)
    response = client.post('/chat',
                           data={
                               'message': 'hello',
                               'session_id': session_id
                           })
    assert response.status_code == 200
    json_response = json.loads(response.get_data(as_text=True))
    assert json_response['response'] == 'world'
    response = client.post('/chat',
                           data={
                               'message': 'quit',
                               'session_id': session_id
                           })
    # The Emily thread closes if no more sessions are left, but pytest runs through these tests too quickly for Emily to make that check in time.
    time.sleep(0.1)
Beispiel #18
0
def test_validate_post_existing_resource(client):
    """Do we get back an error message when making a POST request on a resource that already exists?"""
    response = client.post(
        '/user/',
        data=json.dumps({
            'name': 'Jeff Knupp',
            'email': '*****@*****.**',
            }),
        headers={'Content-Type': 'application/json'}
    )
    assert response.status_code == 400
    assert response.json['message'] == INVALID_ACTION_MESSAGE
Beispiel #19
0
def test_validate_post(client):
    """Do we get back an error message when making a POST request that fails
    validation?"""
    response = client.post(
        '/user',
        data=json.dumps({
            'name': 'Jeff Knupp',
            'email': '*****@*****.**',
            }),
        headers={'Content-Type': 'application/json'}
    )
    assert response.status_code == 400
    assert response.json['message'] == INVALID_ACTION_MESSAGE
Beispiel #20
0
def test_delete_account(client, user_info):
    """A user can delete their account."""
    register_user(client, user_info)

    # The password has to be right.
    rv = client.get(url_for('user.delete_account'))
    rv = client.post(url_for('do.delete_user'),
                     data=dict(csrf_token=csrf_token(rv.data),
                               password='******',
                               consent='YES'),
                     follow_redirects=True)
    reply = json.loads(rv.data.decode('utf-8'))
    assert reply['status'] == 'error'

    # The consent must be given.
    rv = client.get(url_for('user.delete_account'))
    rv = client.post(url_for('do.delete_user'),
                     data=dict(csrf_token=csrf_token(rv.data),
                               password='******',
                               consent='NO'),
                     follow_redirects=True)
    reply = json.loads(rv.data.decode('utf-8'))
    assert reply['status'] == 'error'

    rv = client.get(url_for('user.delete_account'))
    rv = client.post(url_for('do.delete_user'),
                     data=dict(csrf_token=csrf_token(rv.data),
                               password=user_info['password'],
                               consent='YES'),
                     follow_redirects=True)
    reply = json.loads(rv.data.decode('utf-8'))
    assert reply['status'] == 'ok'

    # Deleting your account should log you out.
    rv = client.get(url_for('home.index'))
    assert b'Log in' in rv.data

    # Try to log in to the deleted account.
    log_in_user(client, user_info, expect_success=False)
Beispiel #21
0
def test_login_before_confirming_email(client, user_info):
    """Registered users with unconfirmed emails can't log in."""
    rv = client.get(url_for('auth.register'))
    with mail.record_messages() as outbox:
        data = dict(csrf_token=csrf_token(rv.data),
                    username=user_info['username'],
                    password=user_info['password'],
                    confirm=user_info['password'],
                    email_required=user_info['email'],
                    invitecode='',
                    accept_tos=True,
                    captcha='xyzzy')
        rv = client.post(url_for('auth.register'),
                         data=data,
                         follow_redirects=True)
        assert b'spam' in rv.data  # Telling user to go check it.

        message = outbox.pop()

        rv = client.get(url_for('auth.login'))
        rv = client.post(url_for('auth.login'),
                         data=dict(csrf_token=csrf_token(rv.data),
                                   username=user_info['username'],
                                   password=user_info['password']),
                         follow_redirects=True)
        assert b'Resend account confirmation instructions' in rv.data
        rv = client.post(url_for('auth.resend_confirmation_email'),
                         data=dict(csrf_token=csrf_token(rv.data),
                                   email=user_info['email']),
                         follow_redirects=True)

        assert b'spam' in rv.data  # Telling user to go check it.
        message = outbox.pop()
        soup = BeautifulSoup(message.html, 'html.parser')
        token = soup.a['href'].split('/')[-1]
        rv = client.get(url_for('auth.login_with_token', token=token),
                        follow_redirects=True)

        assert b'Log out' in rv.data
Beispiel #22
0
def test_password_required_to_change_recovery_email(client, user_info):
    """Changing the password recovery requires the correct password."""
    register_user(client, user_info)
    wrong_password = '******'
    new_email = '*****@*****.**'
    assert wrong_password != user_info['password']
    assert new_email != user_info['email']

    rv = client.get(url_for('user.edit_account'))
    data = dict(csrf_token=csrf_token(rv.data),
                email_required=new_email,
                oldpassword=wrong_password,
                password='',
                confirm='')

    # No confirmation email should be sent.
    with mail.record_messages() as outbox:
        rv = client.post(url_for('do.edit_account'),
                         data=data,
                         follow_redirects=True)
        assert len(outbox) == 0

    log_out_current_user(client)

    # Verify password recovery email goes to the right place.
    with mail.record_messages() as outbox:
        rv = client.get(url_for('user.password_recovery'))
        rv = client.post(url_for('user.password_recovery'),
                         data=dict(csrf_token=csrf_token(rv.data),
                                   email=new_email,
                                   captcha='xyzzy'))
        assert len(outbox) == 0
        rv = client.get(url_for('user.password_recovery'))
        rv = client.post(url_for('user.password_recovery'),
                         data=dict(csrf_token=csrf_token(rv.data),
                                   email=user_info['email'],
                                   captcha='xyzzy'))
        assert len(outbox) == 1
Beispiel #23
0
def test_admin_can_ban_and_unban_user(client, user_info, user2_info):
    register_user(client, user_info)
    register_user(client, user2_info)
    promote_user_to_admin(client, user2_info)

    username = user_info['username']

    rv = client.get(url_for('user.view', user=username))
    rv = client.post(url_for('do.ban_user', username=username),
                     data=dict(csrf_token=csrf_token(rv.data)),
                     follow_redirects=True)

    # For now, banning makes you unable to log in.
    log_out_current_user(client)
    log_in_user(client, user_info, expect_success=False)
    log_in_user(client, user2_info, expect_success=True)

    rv = client.get(url_for('user.view', user=username))
    rv = client.post(url_for('do.unban_user', username=username),
                     data=dict(csrf_token=csrf_token(rv.data)),
                     follow_redirects=True)

    log_out_current_user(client)
    log_in_user(client, user_info, expect_success=True)
    def test_post(self, client, mdm_group):
        res = client.put(url_for('api_app.mdmgroupresource'), data=mdm_group)
        data = json.loads(res.data)

        mdm_group['group_name'] = 'something else'
        res = client.post(url_for('api_app.mdmgroupresource', id=data['id']), data=mdm_group)

        assert self.assert_success(res)

        res = client.get(url_for('api_app.mdmgroupresource', id=data['id']))

        assert self.assert_json(res.headers)
        assert self.assert_success(res)
        data = json.loads(res.data)

        mdm_group['id'] = data['id']
        assert data == mdm_group
    def test_post(self, client, device):
        res = client.put(url_for('api_app.deviceresource'), data=device)
        data = json.loads(res.data)

        device['udid'] = str(uuid.uuid4())
        device['serial_number'] = '12131415'
        res = client.post(url_for('api_app.deviceresource', id=data['id']), data=device)

        assert self.assert_success(res)

        res = client.get(url_for('api_app.deviceresource', id=data['id']))

        assert self.assert_json(res.headers)
        assert self.assert_success(res)
        data = json.loads(res.data)

        device['id'] = data['id']
        assert data == device
Beispiel #26
0
    def test_post(self, client, profile):
        res = client.put(url_for('api_app.profileresource'), data=profile)
        data = json.loads(res.data)

        profile['profile_data'] = 'something else'
        res = client.post(url_for('api_app.profileresource', id=data['id']), data=profile)

        assert self.assert_success(res)

        res = client.get(url_for('api_app.profileresource', id=data['id']))

        assert self.assert_json(res.headers)
        assert self.assert_success(res)
        data = json.loads(res.data)

        assert data['identifier'] == profile['identifier']
        assert data['uuid'] == profile['uuid']
        assert data['status'] == profile['status'].value
Beispiel #27
0
def test_email_required_for_registration(client, user_info):
    "If emails are required, trying to register without one will fail."
    rv = client.get(url_for('auth.register'))
    with mail.record_messages() as outbox:
        data = dict(csrf_token=csrf_token(rv.data),
                    username='******',
                    password='******',
                    confirm='Safe123#$@lolnot',
                    email_required='',
                    invitecode='',
                    accept_tos=True,
                    captcha='xyzzy')
        rv = client.post(url_for('auth.register'),
                         data=data,
                         follow_redirects=True)
        assert len(outbox) == 0
        assert b'Error' in rv.data
        assert b'Register' in rv.data
        assert b'Log out' not in rv.data
Beispiel #28
0
def test_change_password(client, user_info):
    """A user can change their password and log in with the new password."""
    register_user(client, user_info)
    new_password = '******' + '\N{PARTIAL DIFFERENTIAL}'
    assert new_password != user_info['password']
    rv = client.get(url_for('user.edit_account'))
    rv = client.post(url_for('do.edit_account'),
                     data=dict(csrf_token=csrf_token(rv.data),
                               oldpassword=user_info['password'],
                               password=new_password,
                               confirm=new_password),
                     follow_redirects=True)
    reply = json.loads(rv.data.decode('utf-8'))
    assert reply['status'] == 'ok'

    log_out_current_user(client)

    # Try to log in with the old password
    log_in_user(client, user_info, expect_success=False)

    new_info = dict(user_info)
    new_info.update(password=new_password)
    log_in_user(client, new_info, expect_success=True)
Beispiel #29
0
def test_change_password_recovery_email(client, user_info):
    """The user can change their password recovery email."""
    register_user(client, user_info)
    new_email = '*****@*****.**'
    assert new_email != user_info['email']

    rv = client.get(url_for('user.edit_account'))
    data = dict(csrf_token=csrf_token(rv.data),
                oldpassword=user_info['password'],
                password='',
                confirm='')
    if email_validation_is_required():
        data['email_required'] = new_email
    else:
        data['email_optional'] = new_email

    with mail.record_messages() as outbox:
        rv = client.post(url_for('do.edit_account'),
                         data=data,
                         follow_redirects=True)
        log_out_current_user(client)

        if email_validation_is_required():
            message = outbox.pop()

            # Make sure that password recovery emails go to the former address
            # if the new one has not yet been confirmed.
            rv = client.get(url_for('user.password_recovery'))
            rv = client.post(url_for('user.password_recovery'),
                             data=dict(csrf_token=csrf_token(rv.data),
                                       email=new_email,
                                       captcha='xyzzy'))
            assert len(outbox) == 0

            rv = client.get(url_for('user.password_recovery'))
            rv = client.post(url_for('user.password_recovery'),
                             data=dict(csrf_token=csrf_token(rv.data),
                                       email=user_info['email'],
                                       captcha='xyzzy'))
            assert outbox.pop().send_to == {user_info['email']}

            # Now click the confirm link.
            assert message.send_to == {new_email}
            soup = BeautifulSoup(message.html, 'html.parser')
            token = soup.a['href'].split('/')[-1]
            rv = client.get(url_for('user.confirm_email_change', token=token),
                            follow_redirects=True)
        else:
            assert len(outbox) == 0

    # Verify password recovery email goes to the right place.
    with mail.record_messages() as outbox:
        rv = client.get(url_for('user.password_recovery'))
        rv = client.post(url_for('user.password_recovery'),
                         data=dict(csrf_token=csrf_token(rv.data),
                                   email=user_info['email'],
                                   captcha='xyzzy'))
        assert len(outbox) == 0
        rv = client.get(url_for('user.password_recovery'))
        rv = client.post(url_for('user.password_recovery'),
                         data=dict(csrf_token=csrf_token(rv.data),
                                   email=new_email,
                                   captcha='xyzzy'))
        assert outbox.pop().send_to == {new_email}
def test_post_no_data(client):
    """Do we properly reject a POST with no JSON data?"""
    response = client.post('/artist/')
    json_response = json.loads(response.get_data(as_text=True))
    assert json_response == {'message': 'No data received from request'}
Beispiel #31
0
def test_invite_code_required_for_registration(client, user_info, user2_info):
    "If invite codes are required, trying to register without one will fail."
    register_user(client, user_info)
    promote_user_to_admin(client, user_info)

    # Enable invite codes.
    rv = client.get(url_for('admin.invitecodes'))
    data = dict(csrf_token=csrf_token(rv.data),
                enableinvitecode=True,
                minlevel=3,
                maxcodes=10)

    rv = client.post(url_for('do.use_invite_code'),
                     data=data,
                     follow_redirects=True)
    reply = json.loads(rv.data.decode('utf-8'))
    assert reply['status'] == 'ok'

    # Create an invite code.
    rv = client.get(url_for('admin.invitecodes'))
    data = dict(csrf_token=csrf_token(rv.data),
                code="abcde",
                uses=10,
                expires='')
    rv = client.post(url_for('admin.invitecodes'),
                     data=data,
                     follow_redirects=True)

    log_out_current_user(client)

    # Now try to register a new user without an invite code.
    rv = client.get(url_for('auth.register'))
    data = dict(csrf_token=csrf_token(rv.data),
                username=user2_info['username'],
                password=user2_info['password'],
                confirm=user2_info['password'],
                invitecode='',
                email_optional=user2_info['email'],
                accept_tos=True,
                captcha='xyzzy')

    rv = client.post(url_for('auth.register'),
                     data=data,
                     follow_redirects=True)
    assert b'Invalid invite code' in rv.data

    # Now try to register a new user with an incorrect invite code.
    rv = client.get(url_for('auth.register'))
    data = dict(csrf_token=csrf_token(rv.data),
                username=user2_info['username'],
                password=user2_info['password'],
                confirm=user2_info['password'],
                invitecode='xyzzy',
                email_optional=user2_info['email'],
                accept_tos=True,
                captcha='xyzzy')

    rv = client.post(url_for('auth.register'),
                     data=data,
                     follow_redirects=True)
    assert b'Invalid invite code' in rv.data

    # Now try to register a new user with a valid invite code.
    rv = client.get(url_for('auth.register'))
    data = dict(csrf_token=csrf_token(rv.data),
                username=user2_info['username'],
                password=user2_info['password'],
                confirm=user2_info['password'],
                invitecode='abcde',
                email_optional=user2_info['email'],
                accept_tos=True,
                captcha='xyzzy')

    rv = client.post(url_for('auth.register'),
                     data=data,
                     follow_redirects=True)
    assert b'Log out' in rv.data
Beispiel #32
0
def test_post_no_data(client):
    """Do we properly reject a POST with no JSON data?"""
    response = client.post('/artist/')
    json_response = json.loads(response.get_data(as_text=True))
    assert json_response == {'message': 'No data received from request'}