示例#1
0
def test_group_members(users, groups):
    admin = User.find_by_identity('*****@*****.**')
    regular = User.find_by_identity('*****@*****.**')
    grp = Group.find_by_name('test group 1')

    grp.add_members([regular, admin])
    assert grp.is_group_member(regular) is True
    assert grp.members.count() == 2

    grp.remove_members([regular])
    assert grp.is_group_member(regular) is False
    assert grp.members.count() == 1
示例#2
0
def test_remove_group_members(client, users, groups):
    user1 = User.find_by_identity('*****@*****.**')
    user2 = User.find_by_identity('*****@*****.**')
    group = Group.find_by_name('test group 3')
    group.add_members([user2, user1])
    assert len(group.members.all()) == 2

    response = client.delete(
        f'/api/admin/groups/{group.id}/members',
        content_type='application/json',
        data=json.dumps({'users': [user1.id, user2.id]})
    )
    data = json.loads(response.data.decode())
    assert response.status_code == 200
    assert len(data.get('members')) == 0
示例#3
0
def test_add_group_members(client, users, groups):
    user1 = User.find_by_identity('*****@*****.**')
    user2 = User.find_by_identity('*****@*****.**')
    group = Group.find_by_name('test group 1')

    response = client.put(
        f'/api/admin/groups/{group.id}/members',
        content_type='application/json',
        data=json.dumps({'users': [user1.id, user2.id]})
    )
    data = json.loads(response.data.decode())
    assert response.status_code == 200
    assert len(data.get('members')) == 2
    assert data.get('members')[0]['username'] == 'adminuser'
    assert data.get('members')[1]['username'] == 'regularuser'
示例#4
0
def test_delete_user(client, users):
    user = User.find_by_identity('*****@*****.**')
    response = client.delete(
        f'/api/admin/users/{user.id}',)
    data = json.loads(response.data.decode())
    assert response.status_code == 200
    assert 'deleted user' in data.get('message')
示例#5
0
def get_profile(user, username):
    user = User.find_by_identity(username)

    if user:
        return jsonify(UserSchema().dump(user))

    return not_found('User not found.')
示例#6
0
def test_get_user(client, users):
    user = User.find_by_identity('*****@*****.**')
    response = client.get(f'/api/admin/users/{user.id}',)
    data = json.loads(response.data.decode())
    assert response.status_code == 200
    assert data.get('username') == 'adminuser'
    assert data.get('profile')['name'] == 'admin'
示例#7
0
def update_user(id):
    request_data = request.get_json()

    if not request_data:
        return bad_request("No input data provided")

    try:
        data = ProfileSchema().load(request_data)

        user = User.find_by_id(id)
        existing_user = User.find_by_identity(data.get('auth')['username'])

        if existing_user is not None:
            if existing_user.id != user.id:
                return bad_request(f'Username already exists.')

        # update user
        user.profile.name = data.get('name')
        user.profile.bio = data.get('bio')
        user.profile.dob = data.get('dob')
        user.username = data.get('auth')['username']
        user.is_active = data.get('auth')['is_active']
        user.is_admin = data.get('auth')['is_admin']
        user.save()

        return jsonify(UserSchema().dump(user))

    # handle errors
    except ValidationError as err:
        return error_response(422, err.messages)
    except (exc.IntegrityError, ValueError):
        db.session.rollback()
        return server_error('Something went wrong, please try again.')
示例#8
0
def test_follow(client, users, token):
    user = User.find_by_identity('regularuser')
    response = client.post(f'/api/users/follow/{user.id}',
                           headers={'Authorization': f'Bearer {token}'})
    data = json.loads(response.data.decode())
    assert response.status_code == 200
    assert isinstance(data, list) is True
示例#9
0
def token(users):
    """
    Serialize a JWT token.

    :param db: Pytest fixture
    :return: JWT token
    """
    user = User.find_by_identity('*****@*****.**')
    return user.encode_auth_token(user.id).decode()
示例#10
0
def posts(db, session, users):
    """
    Create posts fixtures. They reset per test.

    :param db: Pytest fixture
    :return: SQLAlchemy database session
    """
    db.session.query(Post).delete()

    u1 = User.find_by_identity('*****@*****.**')
    u2 = User.find_by_identity('*****@*****.**')
    u3 = User.find_by_identity('*****@*****.**')

    c1 = add_comment(
        'ullamco laboris nisi ut aliquip ex ea commodo consequat.', u1.id)
    c2 = add_comment(
        'ullamco laboris nisi ut aliquip ex ea commodo consequat.', u1.id)
    c3 = add_comment(
        'Ut enim ad minim veniam, quis nostrud exercitation ',
        u2.id,
        comment_id=c2.id
    )
    c4 = add_comment(
        'ullamco laboris nisi ut aliquip ex ea commodo consequat.', u3.id)

    p1 = add_post(
        'Ut enim ad minim veniam, quis nostrud exercitation ',
        u1.id,
        comments=[c3]
    )
    p2 = add_post(
        'Ut enim ad minim veniam, quis nostrud exercitation ',
        u1.id,
        comments=[c1]
    )
    add_post(
        'Ut enim ad minim veniam, quis nostrud exercitation ',
        u3.id,
        comments=[c4]
    )
    p1.likes.append(u1)
    p2.likes.append(u1)

    return db
示例#11
0
def test_follow(users):
    u1 = User.find_by_identity('*****@*****.**')
    u2 = User.find_by_identity('*****@*****.**')
    assert u1.followed.all() == []
    assert u1.followers.all() == []

    u1.follow(u2)
    db.session.commit()
    assert u1.is_following(u2) is True
    assert u1.followed.count() == 1
    assert u1.followed.first().username == 'commonuser'
    assert u2.followers.count() == 1
    assert u2.followers.first().username == 'regularuser'

    u1.unfollow(u2)
    db.session.commit()
    assert u1.is_following(u2) is False
    assert u1.followed.count() == 0
    assert u2.followers.count() == 0
示例#12
0
def test_update_user_no_data(client, users):
    user = User.find_by_identity('*****@*****.**')
    response = client.put(
        f'/api/admin/users/{user.id}',
        data=json.dumps({}),
        content_type='application/json'
    )
    data = json.loads(response.data.decode())
    assert response.status_code == 400
    assert 'No input data provided' in data.get('message')
示例#13
0
def test_user_perms(users):
    name1 = Permission.set_code_name('can add users')
    name2 = Permission.set_code_name('can edit groups')
    perm1 = Permission.find_by_name(name1)
    perm2 = Permission.find_by_name(name2)
    user = User.find_by_identity('*****@*****.**')

    user.add_permissions([perm1, perm2])
    assert user.permissions.count() == 2
    assert user.user_has_perm(perm2) is True

    user.remove_permissions([perm2])
    assert user.user_has_perm(perm2) is False
    assert user.permissions.count() == 1
示例#14
0
def get_liked_posts(user, username, page=1):
    """Get a users list of liked posts"""
    user = User.find_by_identity(username)
    try:
        liked_posts = user.likes.order_by(Post.created_on.desc()).paginate(
            page, current_app.config['ITEMS_PER_PAGE'])
    except (exc.IntegrityError, ValueError):
        db.session.rollback()
        return server_error('Something went wrong, please try again.')
    else:
        return {
            'likes': PostSchema(many=True).dump(liked_posts.items),
            'hasNext': liked_posts.has_next,
        }
示例#15
0
def get_user_comments(user, username, page=1):
    """Get a users list of comments"""
    user = User.find_by_identity(username)
    try:
        comments = Comment.query.with_parent(user).order_by(
            Comment.created_on.desc()).paginate(
                page, current_app.config['ITEMS_PER_PAGE'])
    except (exc.IntegrityError, ValueError):
        db.session.rollback()
        return server_error('Something went wrong, please try again.')
    else:
        return {
            'comments': CommentSchema(many=True).dump(comments.items),
            'hasNext': comments.has_next,
        }
示例#16
0
def get_followers(user, username, page=1):
    """Get list of users following a user"""
    user = User.find_by_identity(username)
    try:
        followers = user.followers.paginate(
            page, current_app.config['ITEMS_PER_PAGE'], False)
    except (exc.IntegrityError, ValueError):
        db.session.rollback()
        return server_error('Something went wrong, please try again.')
    else:
        return {
            'followers': UserSchema(many=True, only=(
                'id', 'username', 'profile',)).dump(followers.items),
            'count': user.followers.count(),
            'hasNext': followers.has_next,
        }
示例#17
0
def test_user_get_all_perms(users, groups):
    name1 = Permission.set_code_name('can add users')
    name2 = Permission.set_code_name('can edit groups')
    perm1 = Permission.find_by_name(name1)
    perm2 = Permission.find_by_name(name2)
    user = User.find_by_identity('*****@*****.**')
    grp = Group.find_by_name('test group 1')
    grp.add_members([user])

    assert len(user.get_all_perms()) == 0
    user.add_permissions([perm1])
    grp.add_permissions([perm2])

    assert len(user.get_all_perms()) == 2
    assert user.has_permission(perm2.code_name) is True
    assert user.has_permission(perm1.code_name) is True
    assert user.has_permissions([perm1.code_name, perm2.code_name]) is True
示例#18
0
def test_remove_user_perms(client, users):
    name1 = Permission.set_code_name('can view groups')
    name2 = Permission.set_code_name('can delete users')
    perm1 = Permission.find_by_name(name1)
    perm2 = Permission.find_by_name(name2)
    user = User.find_by_identity('*****@*****.**')
    user.add_permissions([perm2, perm1])
    assert len(user.permissions.all()) == 2

    response = client.delete(
        f'/api/admin/users/{user.id}/permissions',
        content_type='application/json',
        data=json.dumps({'perms': [perm1.id, perm2.id]})
    )
    data = json.loads(response.data.decode())
    assert response.status_code == 200
    assert len(data.get('permissions')) == 0
示例#19
0
def test_update_user_duplicate_username(client, users):
    user = User.find_by_identity('*****@*****.**')
    response = client.put(
        f'/api/admin/users/{user.id}',
        data=json.dumps({
            'auth': {
                'username': '******',
                'is_active': True,
                'is_admin': True,
            },
            'name': 'test',
            'bio': 'Another user.'
        }),
        content_type='application/json'
    )
    data = json.loads(response.data.decode())
    assert response.status_code == 400
    assert 'Username already exists.' in data.get('message')
示例#20
0
def test_valid_user_login(client, users):
    user = User.find_by_identity('*****@*****.**')
    old_sign_in_count = user.sign_in_count

    response = client.post(
        '/api/auth/login',
        data=json.dumps({
            'identity': '*****@*****.**',
            'password': '******'
        }),
        content_type='application/json'
    )
    data = json.loads(response.data.decode())
    new_sign_in_count = user.sign_in_count

    assert response.status_code == 200
    assert isinstance(data.get('token'), str) is True
    assert (old_sign_in_count + 1) == new_sign_in_count
示例#21
0
def test_update_user(client, users):
    user = User.find_by_identity('*****@*****.**')
    response = client.put(
        f'/api/admin/users/{user.id}',
        data=json.dumps({
            'bio': 'test user',
            'name': 'test',
            'auth': {
                'username': '******',
                'is_active': True,
                'is_admin': True,
            }
        }),
        content_type='application/json'
    )
    data = json.loads(response.data.decode())
    assert response.status_code == 200
    assert isinstance(data, dict) is True
    assert data.get('username') == 'testuser'
示例#22
0
def test_password_hashing(db):
    user = User.find_by_identity('*****@*****.**')
    assert user.check_password('secret') is False
    assert user.check_password('password') is True
示例#23
0
def test_avatar(users):
    user = User.find_by_identity('*****@*****.**')
    profile = Profile.query.filter_by(user_id=user.id).first()
    assert profile.avatar == (
        'https://www.gravatar.com/avatar/'
        'e6b6b9ec69c4837878505768b621d383?s=128&d=mm&r=pg')