def test_poll_answer_new(app, authed_client):
    ForumPollChoice.from_pk(6).answers  # cache it
    answer = ForumPollAnswer.new(poll_id=3, user_id=2, choice_id=6)
    assert answer.poll_id == 3
    assert answer.user_id == 2
    assert answer.choice_id == 6
    assert ForumPollChoice.from_pk(6).answers == 1
Esempio n. 2
0
def vote_on_poll(choice_id: int) -> flask.Response:
    """
    This is the endpoint for forum poll voting. The ``forums_polls_vote``
    permission is required to access this endpoint.

    .. :quickref: ForumPollChoice; Vote on a forum poll choice.

    **Example response**:

    .. parsed-literal::

       {
         "status": "success",
         "response": "You have successfully voted for choice 1032."
       }

    :>json str response: The result message

    :statuscode 200: Voting successful
    :statuscode 400: Voting unsuccessful
    :statuscode 404: Poll or poll choice
    """
    choice = ForumPollChoice.from_pk(choice_id, _404=True)
    if ForumPollAnswer.from_attrs(poll_id=choice.poll.id,
                                  user_id=flask.g.user.id):
        raise APIException('You have already voted on this poll.')
    ForumPollAnswer.new(poll_id=choice.poll.id,
                        user_id=flask.g.user.id,
                        choice_id=choice.id)
    return flask.jsonify(
        f'You have successfully voted for choice {choice.id}.')
Esempio n. 3
0
def change_poll_choices(poll: ForumPoll, add: List[str],
                        delete: List[int]) -> None:
    """
    Change the choices to a poll. Create new choices or delete existing ones.
    The choices parameter should contain a dictionary of answer name keys and
    their status as booleans. True = Add, False = Delete.

    :param poll:    The forum poll to alter
    :param choices: The choices to edit
    """
    poll_choice_choices = {c.choice for c in poll.choices}
    poll_choice_ids = {c.id for c in poll.choices}
    errors = {
        'add': {choice
                for choice in add if choice in poll_choice_choices},
        'delete':
        {choice
         for choice in delete if choice not in poll_choice_ids},
    }

    error_message = []
    if errors['add']:
        error_message.append(
            f'The following poll choices could not be added: '  # type: ignore
            f'{", ".join(errors["add"])}.')
    if errors['delete']:
        error_message.append(
            f'The following poll choices could not be deleted: '  # type: ignore
            f'{", ".join([str(d) for d in errors["delete"]])}.')
    if error_message:
        raise APIException(' '.join(error_message))

    for choice in delete:
        choice = ForumPollChoice.from_pk(choice)
        choice.delete_answers()  # type: ignore
        db.session.delete(choice)
    for choice_new in add:
        db.session.add(ForumPollChoice(poll_id=poll.id, choice=choice_new))
    cache.delete(ForumPollChoice.__cache_key_of_poll__.format(poll_id=poll.id))
    poll.del_property_cache('choices')
    db.session.commit()
def test_modify_poll_choices(app, authed_client):
    add_permissions(app, 'forums_view', 'modify_forum_polls')
    response = authed_client.put(
        '/polls/1',
        data=json.dumps(
            {'choices': {
                'add': ['a', 'b', 'c'],
                'delete': [1, 2]
            }}),
    )
    choices = response.get_json()['response']['choices']
    assert len(choices) == 4
    assert {'Choice C', 'a', 'b',
            'c'} == {choice['choice']
                     for choice in choices}
    choices = ForumPollChoice.from_poll(1)
    assert {'Choice C', 'a', 'b', 'c'} == {choice.choice for choice in choices}
def test_vote_poll(app, authed_client):
    add_permissions(app, 'forums_view', 'forums_polls_vote')
    response = authed_client.post('/polls/votes/6')
    check_json_response(response, 'You have successfully voted for choice 6.')
    assert ForumPollChoice.from_pk(6).answers == 1
def test_poll_answers(app, authed_client):
    assert ForumPollChoice.from_pk(1).answers == 2
    assert ForumPollChoice.from_pk(3).answers == 0
def test_poll_new_choice_nonexistent_poll(app, authed_client):
    with pytest.raises(APIException):
        ForumPollChoice.new(poll_id=99, choice='user_three!')
def test_poll_new_choice(app, authed_client):
    choice = ForumPollChoice.new(poll_id=3, choice='user_three!')
    assert choice.id == 7
    assert choice.poll_id == 3
    assert choice.choice == 'user_three!'
    assert {6, 7} == set(c.id for c in ForumPoll.from_pk(3).choices)
def test_poll_choice_from_poll_nonexistent(app, authed_client):
    choices = ForumPollChoice.from_poll(4)
    assert choices == []