def test_format_poll_bars_absolute_url(mocker): mocker.patch('formatters.resolve_usernames', new=lambda user_ids: user_ids) img_url = 'http://example.org/images/red_bar.png' with force_settings(BAR_IMG_URL=img_url): poll = Poll.create( creator_id='user0', message='# Spam? **:tada:**', vote_options=['Sure', 'Maybe', 'No'], bars=True, ) poll.vote('user0', 0) poll.vote('user1', 1) poll.vote('user2', 2) poll.vote('user3', 2) poll.end() with app.app.test_request_context(base_url='http://localhost:5005'): poll_dict = frmts.format_poll(poll) assert 'response_type' in poll_dict assert 'attachments' in poll_dict attachments = poll_dict['attachments'] fields = attachments[0]['fields'] for field in fields[1:]: assert img_url in field['value'] assert 'localhost' not in field['value']
def test_vote(self): poll = Poll.create('user0123', 'Spam?', ['Yes', 'Maybe', 'No']) self.assertEqual(poll.num_votes(), 0) self.assertEqual(poll.count_votes(0), 0) self.assertEqual(poll.count_votes(1), 0) self.assertEqual(poll.count_votes(2), 0) self.assertEqual(poll.count_votes(3), 0) poll.vote('user0', 0) poll.vote('user1', 2) poll.vote('user2', 2) self.assertEqual(poll.num_votes(), 3) self.assertEqual(poll.count_votes(0), 1) self.assertEqual(poll.count_votes(1), 0) self.assertEqual(poll.count_votes(2), 2) self.assertEqual(poll.count_votes(3), 0) poll.vote('user0', 0) poll.vote('user0', 0) self.assertEqual(poll.num_votes(), 3) self.assertEqual(poll.count_votes(0), 1) self.assertEqual(poll.count_votes(1), 0) self.assertEqual(poll.count_votes(2), 2) self.assertEqual(poll.count_votes(3), 0) poll.vote('user2', 1) self.assertEqual(poll.num_votes(), 3) self.assertEqual(poll.count_votes(0), 1) self.assertEqual(poll.count_votes(1), 1) self.assertEqual(poll.count_votes(2), 1) self.assertEqual(poll.count_votes(3), 0)
def test_vote(): poll = Poll.create('user0123', 'Spam?', ['Yes', 'Maybe', 'No']) assert poll.num_votes() == 0 assert poll.count_votes(0) == 0 assert poll.count_votes(1) == 0 assert poll.count_votes(2) == 0 assert poll.count_votes(3) == 0 poll.vote('user0', 0) poll.vote('user1', 2) poll.vote('user2', 2) assert poll.num_votes() == 3 assert poll.count_votes(0) == 1 assert poll.count_votes(1) == 0 assert poll.count_votes(2) == 2 assert poll.count_votes(3) == 0 poll.vote('user0', 0) poll.vote('user0', 0) assert poll.num_votes() == 3 assert poll.count_votes(0) == 1 assert poll.count_votes(1) == 0 assert poll.count_votes(2) == 2 assert poll.count_votes(3) == 0 poll.vote('user2', 1) assert poll.num_votes() == 3 assert poll.count_votes(0) == 1 assert poll.count_votes(1) == 1 assert poll.count_votes(2) == 1 assert poll.count_votes(3) == 0
def test_format_poll_running(mocker): mocker.patch('formatters.resolve_usernames', new=lambda user_ids: user_ids) poll = Poll.create(creator_id='user0', message='# Spam? **:tada:**', vote_options=['Sure', 'Maybe', 'No'], secret=False) poll.vote('user0', 0) poll.vote('user1', 1) poll.vote('user2', 2) poll.vote('user3', 2) with app.app.test_request_context(base_url='http://localhost:5005'): poll_dict = frmts.format_poll(poll) assert 'response_type' in poll_dict assert 'attachments' in poll_dict assert poll_dict['response_type'] == 'in_channel' attachments = poll_dict['attachments'] assert len(attachments) == 1 assert 'text' in attachments[0] assert 'actions' in attachments[0] assert 'fields' in attachments[0] assert attachments[0]['text'] == poll.message assert len(attachments[0]['actions']) == 4 fields = attachments[0]['fields'] assert len(fields) == 1 assert 'short' in fields[0] assert 'title' in fields[0] assert 'value' in fields[0] assert not fields[0]['short'] assert not fields[0]['title'] assert fields[0]['value'] == '*Number of voters: 4*'
def test_init_defaults(self): creator_id = 'user01234' message = '## Markdown message<br>Test **bla**' poll = Poll.create(creator_id, message) self.assertEqual(poll.creator_id, creator_id) self.assertEqual(poll.message, message) self.assertEqual(poll.vote_options, ['Yes', 'No']) self.assertEqual(poll.secret, False)
def test_load_invalid(): with pytest.raises(InvalidPollError): Poll.load('bla') with pytest.raises(InvalidPollError): poll = Poll.create('user0123', 'Spam?', 'en', ['Yes', 'Maybe', 'No'], secret=True, public=True, max_votes=2) Poll(poll.connection, 'user3210')
def test_init_defaults(): creator_id = 'user01234' message = '## Markdown message<br>Test **bla**' poll = Poll.create(creator_id, message) assert poll.creator_id == creator_id assert poll.message == message assert poll.vote_options == ['Yes', 'No'] assert not poll.secret
def test_init(self): creator_id = 'user01234' message = '## Markdown message<br>Test **bla**' vote_options = ['Option 1', 'Another option', 'Spam!'] poll = Poll.create(creator_id, message, vote_options, True) self.assertEqual(poll.creator_id, creator_id) self.assertEqual(poll.message, message) self.assertEqual(poll.vote_options, vote_options) self.assertEqual(poll.secret, True)
def test_format_poll_finished_public_bars(mocker): mocker.patch('formatters.resolve_usernames', new=lambda user_ids: user_ids) poll = Poll.create( creator_id='user0', message='# Spam? **:tada:**', vote_options=['Sure', 'Maybe', 'No'], bars=True, public=True, ) poll.vote('user0', 0) poll.vote('user1', 1) poll.vote('user2', 2) poll.vote('user3', 2) poll.end() with app.app.test_request_context(base_url='http://localhost:5005'): poll_dict = frmts.format_poll(poll) assert 'response_type' in poll_dict assert 'attachments' in poll_dict assert poll_dict['response_type'] == 'in_channel' attachments = poll_dict['attachments'] assert len(attachments) == 1 assert 'text' in attachments[0] assert 'actions' not in attachments[0] assert 'fields' in attachments[0] assert attachments[0]['text'] == poll.message fields = attachments[0]['fields'] assert len(fields) == 4 assert 'short' in fields[0] assert 'title' in fields[0] assert 'value' in fields[0] assert not fields[0]['short'] assert not fields[0]['title'] assert fields[0]['value'] == '*Number of voters: 4*' img_url = 'http://localhost:5005/img/bar.png' expected = [ (poll.vote_options[0], '1 Vote (25.0%)', 0.25, ['user0']), (poll.vote_options[1], '1 Vote (25.0%)', 0.25, ['user1']), (poll.vote_options[2], '2 Votes (50.0%)', 0.5, ['user2', 'user3']), ] for field, (title, value, bar_length, users) in zip(fields[1:], expected): assert 'short' in field assert 'title' in field assert 'value' in field assert not field['short'] assert title == field['title'] assert value in field['value'] image = '![Bar]({} ={}x25)'.format(img_url, bar_length * 450 + 2) assert image in field['value'] for user in users: assert user in field['value']
def test_init(): creator_id = 'user01234' message = '## Markdown message<br>Test **bla**' vote_options = ['Option 1', 'Another option', 'Spam!'] poll = Poll.create(creator_id, message, vote_options, True) assert poll.creator_id == creator_id assert poll.message == message assert poll.vote_options == vote_options assert poll.secret
def test_vote_to_string_single(): poll = Poll.create(creator_id='user0', message='Message', vote_options=['Sure', 'Maybe', 'No']) poll.vote('user0', 0) poll.vote('user1', 2) assert app.vote_to_string(poll, 'user0') == ('Sure ✓, Maybe ✗, No ✗') assert app.vote_to_string(poll, 'user1') == ('Sure ✗, Maybe ✗, No ✓') assert app.vote_to_string(poll, 'user2') == ('Sure ✗, Maybe ✗, No ✗')
def make_variant_poll(self, variant, user): from poll import Poll key = self.variant_key(variant) for poll in self.polls: if poll.subject == key: return poll poll = Poll.create(self.page, user, Poll.SELECT, subject=key) if self._polls is not None: self._polls.append(poll) return poll
def test_vote_to_string_multi(): poll = Poll.create(creator_id='user0', message='Message', vote_options=['Sure', 'Maybe', 'No'], max_votes=2) poll.vote('user0', 0) poll.vote('user0', 2) poll.vote('user1', 2) assert frmts.format_user_vote(poll, 'user0') == ('Sure ✓, Maybe ✗, No ✓') assert frmts.format_user_vote(poll, 'user1') == ('Sure ✗, Maybe ✗, No ✓') assert frmts.format_user_vote(poll, 'user2') == ('Sure ✗, Maybe ✗, No ✗')
def test_format_poll_finished(mocker): mocker.patch('formatters.resolve_usernames', new=lambda user_ids: user_ids) poll = Poll.create(creator_id='user0', message='# Spam? **:tada:**', vote_options=['Sure', 'Maybe', 'No'], secret=False) poll.vote('user0', 0) poll.vote('user1', 1) poll.vote('user2', 2) poll.vote('user3', 2) poll.end() with app.app.test_request_context(base_url='http://localhost:5005'): poll_dict = frmts.format_poll(poll) assert 'response_type' in poll_dict assert 'attachments' in poll_dict assert poll_dict['response_type'] == 'in_channel' attachments = poll_dict['attachments'] assert len(attachments) == 1 assert 'text' in attachments[0] assert 'actions' not in attachments[0] assert 'fields' in attachments[0] assert attachments[0]['text'] == poll.message fields = attachments[0]['fields'] assert len(fields) == 4 assert 'short' in fields[0] assert 'title' in fields[0] assert 'value' in fields[0] assert not fields[0]['short'] assert not fields[0]['title'] assert fields[0]['value'] == '*Number of voters: 4*' users = ['user0', 'user1', 'user2', 'user3'] expected = [ (poll.vote_options[0], '1 Vote (25.0%)'), (poll.vote_options[1], '1 Vote (25.0%)'), (poll.vote_options[2], '2 Votes (50.0%)'), ] for field, (title, value) in zip(fields[1:], expected): assert 'short' in field assert 'title' in field assert 'value' in field assert field['short'] assert title == field['title'] assert value == field['value'] for user in users: assert user not in field['value']
def test_num_voters(max_votes, expected): poll = Poll.create('user0123', 'Spam?', 'en', ['Yes', 'Maybe', 'No'], max_votes=max_votes) assert poll.num_voters() == 0 poll.vote('user0', 0) assert poll.num_voters() == expected[0] poll.vote('user1', 2) assert poll.num_voters() == expected[1] poll.vote('user0', 0) # unvote assert poll.num_voters() == expected[2] poll.vote('user1', 1) assert poll.num_voters() == expected[3]
def test_load(): poll = Poll.create('user0123', 'Spam?', 'en', ['Yes', 'Maybe', 'No'], secret=True, public=True, max_votes=2, bars=True) # because of :memory: database, load() cannot be used directly poll2 = Poll(poll.connection, poll.id) assert poll.creator_id == poll2.creator_id assert poll.message == poll2.message assert poll.secret == poll2.secret assert poll.public == poll2.public assert poll.max_votes == poll2.max_votes assert poll.vote_options == poll2.vote_options assert poll.bars == poll2.bars
def create(cls, instance, label, user, with_vote=False, tags=None): from poll import Poll from tagging import Tagging proposal = Proposal(instance, label, user) meta.Session.add(proposal) meta.Session.flush() poll = Poll.create(proposal, user, Poll.RATE, with_vote=with_vote) proposal.rate_poll = poll if tags is not None: proposal.taggings = Tagging.create_all(proposal, tags, user) meta.Session.flush() return proposal
def test_votes(max_votes, expected_votes): poll = Poll.create('user0123', 'Spam?', 'en', ['Yes', 'Maybe', 'No'], max_votes=max_votes) poll.vote('user0', 0) poll.vote('user1', 2) assert poll.votes('user0') == [0] assert poll.votes('user1') == [2] assert poll.votes('user2') == [] poll.vote('user0', 1) assert poll.votes('user0') == expected_votes[0] assert poll.votes('user1') == expected_votes[1] assert poll.votes('user2') == expected_votes[2]
def test_init(): creator_id = 'user01234' message = '## Markdown message<br>Test **bla**' vote_options = ['Option 1', 'Another option', 'Spam!'] poll = Poll.create(creator_id, message, 'de', vote_options, True, True, 2, True) assert poll.creator_id == creator_id assert poll.message == message assert poll.locale == 'de' assert poll.vote_options == vote_options assert poll.secret assert poll.public assert poll.max_votes == 2 assert poll.bars
def test_get_actions(self): poll = Poll.create(creator_id='user0', message='Message', vote_options=['Yes', 'No'], secret=False) with self.subTest('Fresh poll'): expected = [ ('Yes (0)', 0), ('No (0)', 1), ] self.__test_get_actions(poll, expected) with self.subTest('With votes'): poll.vote('user0', 0) poll.vote('user1', 0) poll.vote('user2', 0) poll.vote('user3', 1) poll.vote('user4', 1) expected = [ ('Yes (3)', 0), ('No (2)', 1), ] self.__test_get_actions(poll, expected) poll = Poll.create(creator_id='user0', message='Message', vote_options=['Yes', 'No'], secret=True) with self.subTest('Secret vote'): poll.vote('user0', 0) poll.vote('user1', 0) poll.vote('user2', 0) poll.vote('user3', 1) poll.vote('user4', 1) expected = [ ('Yes', 0), ('No', 1), ] self.__test_get_actions(poll, expected)
def create(cls, text, user, topic, reply=None, wiki=True, variant=None, sentiment=0, with_vote=False): from poll import Poll comment = Comment(topic, user, variant) comment.wiki = wiki comment.reply = reply meta.Session.add(comment) meta.Session.flush() poll = Poll.create(topic, user, Poll.RATE, comment, with_vote=with_vote) comment.poll = poll comment.latest = comment.create_revision( text, user, sentiment=sentiment, create_time=comment.create_time) return comment
def test_format_actions(votes, secret, exp_actions): poll = Poll.create( creator_id='user0', message='Message', vote_options=['Yes', 'No'], secret=secret, bars=False, ) for voter, vote in enumerate(votes): poll.vote('user{}'.format(voter), vote) with app.app.test_request_context(base_url='http://localhost:5005'): actions = frmts.format_actions(poll) assert len(actions) == 3 for action, (vote_id, name) in zip(actions[:-1], enumerate(exp_actions)): assert 'name' in action assert 'integration' in action assert action['name'] == name integration = action['integration'] assert 'context' in integration assert 'url' in integration assert integration['url'] == 'http://localhost:5005/vote' context = integration['context'] assert 'vote' in context assert 'poll_id' in context assert context['vote'] == vote_id assert context['poll_id'] == poll.id # the last action is always 'End Poll' action = actions[-1] assert 'name' in action assert 'integration' in action assert action['name'] == 'End Poll' integration = action['integration'] assert 'context' in integration assert 'url' in integration assert integration['url'] == 'http://localhost:5005/end' context = integration['context'] assert 'poll_id' in context assert context['poll_id'] == poll.id
def test_end(): poll = Poll.create('user0123', 'Spam?', 'en', ['Yes', 'Maybe', 'No'], max_votes=2) poll.vote('user0', 0) poll.vote('user1', 2) poll.vote('user2', 2) assert poll.num_votes() == 3 assert poll.count_votes(0) == 1 assert poll.count_votes(1) == 0 assert poll.count_votes(2) == 2 poll.end() poll.vote('user3', 0) poll.vote('user4', 1) assert poll.num_votes() == 3 assert poll.count_votes(0) == 1 assert poll.count_votes(1) == 0 assert poll.count_votes(2) == 2
def test_multiple_votes(): poll = Poll.create('user0123', 'Spam?', ['Yes', 'Maybe', 'No'], max_votes=2) assert poll.num_votes() == 0 assert poll.count_votes(0) == 0 assert poll.count_votes(1) == 0 assert poll.count_votes(2) == 0 assert poll.count_votes(3) == 0 poll.vote('user0', 0) poll.vote('user1', 2) poll.vote('user2', 2) assert poll.num_votes() == 3 assert poll.count_votes(0) == 1 assert poll.count_votes(1) == 0 assert poll.count_votes(2) == 2 assert poll.count_votes(3) == 0 poll.vote('user0', 1) poll.vote('user1', 0) assert poll.num_votes() == 5 assert poll.count_votes(0) == 2 assert poll.count_votes(1) == 1 assert poll.count_votes(2) == 2 assert poll.count_votes(3) == 0 # user has exhausted her votes with pytest.raises(NoMoreVotesError): poll.vote('user0', 2) assert poll.num_votes() == 5 assert poll.count_votes(0) == 2 assert poll.count_votes(1) == 1 assert poll.count_votes(2) == 2 assert poll.count_votes(3) == 0 # voting for the same again is removes the vote poll.vote('user0', 1) assert poll.num_votes() == 4 assert poll.count_votes(0) == 2 assert poll.count_votes(1) == 0 assert poll.count_votes(2) == 2 assert poll.count_votes(3) == 0
def create(cls, text, user, topic, reply=None, wiki=True, variant=None, sentiment=0, with_vote=False): from poll import Poll from text import Text if variant is None: variant = Text.HEAD comment = Comment(topic, user, variant) comment.wiki = wiki comment.reply = reply meta.Session.add(comment) meta.Session.flush() poll = Poll.create(topic, user, Poll.RATE, comment, with_vote=with_vote) comment.poll = poll comment.latest = comment.create_revision( text, user, sentiment=sentiment, create_time=comment.create_time) return comment
class Model: def __init__(self): self.poll = None # self.polls = [] # polls list for each model def create_poll(self, message): self.poll = Poll() return self.poll.create(message) def roll_dice(self, message): sides = message.content[6:] if sides.isdigit and int(sides) > 0: val = Dice.roll(int(sides)) return "Wyrzucono: " + str(val) def vote_poll(self, message): if self.poll is None: return "Obecnie nie trwa żadna ankieta" return self.poll.vote(message) def get_poll_message(self): if self.poll is None: return "Obecnie nie trwa żadna ankieta" return self.poll.get_results() def end_poll(self): if self.poll is None: return "Obecnie nie trwa żadna ankieta" msg = "@everyone Ankieta zakończona!\n\n" + self.poll.get_results()[9:] self.poll = None return msg def get_help_message(self): msg = "Dostępne komendy:\n" msg += "!help - wyświetla tę pomoc\n" msg += "!pollc pytanie;odp1;odp2;... - stworzenie ankiety\n" msg += "!poll - wyświetlenie obecnie trwającej ankiety\n" msg += "!pollend - zakończenie obecnej ankiety\n" msg += "!roll n - rzut n-ścienną kostką\n" msg += "!vote abc - oddanie głosu na opcje abc w obecnej ankiecie\n" return msg
def test_vote(): poll = Poll.create('user0123', 'Spam?', 'en', ['Yes', 'Maybe', 'No']) assert poll.num_votes() == 0 assert poll.count_votes(0) == 0 assert poll.count_votes(1) == 0 assert poll.count_votes(2) == 0 assert poll.count_votes(3) == 0 poll.vote('user0', 0) poll.vote('user1', 2) poll.vote('user2', 2) assert poll.num_votes() == 3 assert poll.count_votes(0) == 1 assert poll.count_votes(1) == 0 assert poll.count_votes(2) == 2 assert poll.count_votes(3) == 0 poll.vote('user0', 0) poll.vote('user0', 0) assert poll.num_votes() == 3 assert poll.count_votes(0) == 1 assert poll.count_votes(1) == 0 assert poll.count_votes(2) == 2 assert poll.count_votes(3) == 0 poll.vote('user2', 1) assert poll.num_votes() == 3 assert poll.count_votes(0) == 1 assert poll.count_votes(1) == 1 assert poll.count_votes(2) == 1 assert poll.count_votes(3) == 0 with pytest.raises(IndexError): poll.vote('user2', 3) with pytest.raises(IndexError): poll.vote('user2', -2) assert poll.num_votes() == 3 assert poll.count_votes(0) == 1 assert poll.count_votes(1) == 1 assert poll.count_votes(2) == 1 assert poll.count_votes(3) == 0
def poll(): """Creates a new poll. Directly called by Mattermost. Example response data: ``` { "response_type": "in_channel", "attachments": [{ "text": "<Poll message>", "actions": [ { "name": "<First Option> (0)", "integration": { "context": { "poll_id": "<unique_id>", "vote": 0 }, "url": "http://<hostname:port>/vote" } }, ... additional entries for all poll options ... { "name": "End Poll", "integration": { "url": "http://<hostname:port>/end", "context": { "poll_id": "<unique_id>" } } }], "fields": [ { "short": false, "title": "", "value": "Number of Votes: 1" }] }] } ``` """ if hasattr(settings, 'MATTERMOST_TOKEN'): warnings.warn("MATTERMOST_TOKEN is deprecated, use MATTERMOST_TOKENS \ instead", category=DeprecationWarning) settings.MATTERMOST_TOKENS = [settings.MATTERMOST_TOKEN] settings.MATTERMOST_TOKEN = None if settings.MATTERMOST_TOKENS: token = request.form['token'] if token not in settings.MATTERMOST_TOKENS: return jsonify({ 'response_type': 'ephemeral', 'text': tr("The integration is not correctly set up: " "Invalid token.") }) if 'user_id' not in request.form: abort(400) if 'text' not in request.form: abort(400) user_id = request.form['user_id'] request.user_id = user_id app.logger.debug('Received command: %s', request.form['text']) # the poll should have a fixed locale, otherwise it # changes for everyone every time someone votes locale = flask_babel.get_locale().language if request.form['text'].strip() == 'help': return jsonify({ 'response_type': 'ephemeral', 'text': format_help(request.form['command'], locale) }) args = parse_slash_command(request.form['text']) if not args.message: text = tr("**Please provide a message.**\n\n" "**Usage:**\n{help}").format( help=format_help(request.form['command'], locale)) return jsonify({'response_type': 'ephemeral', 'text': text}) if args.public: if not settings.MATTERMOST_URL or not settings.MATTERMOST_PA_TOKEN: return jsonify({ 'response_type': 'ephemeral', 'text': tr("Public polls are not available with the " "current setup. Please check with you " "system administrator.") }) if args.locale: locale = args.locale poll = Poll.create(user_id, message=args.message, locale=locale, vote_options=args.vote_options, secret=not args.progress, public=args.public, max_votes=args.max_votes, bars=args.bars) app.logger.info('Creating Poll: %s', poll.id) return jsonify(format_poll(poll))
def poll(): """Creates a new poll. Directly called by Mattermost. Example response data: ``` { "response_type": "in_channel", "attachments": [{ "text": "<Poll message>", "actions": [ { "name": "<First Option> (0)", "integration": { "context": { "poll_id": "<unique_id>", "vote": 0 }, "url": "http://<hostname:port>/vote" } }, ... additional entries for all poll options ... { "name": "End Poll", "integration": { "url": "http://<hostname:port>/end", "context": { "poll_id": "<unique_id>" } } }], "fields": [ { "short": false, "title": "", "value": "Number of Votes: 1" }] }] } ``` """ if hasattr(settings, 'MATTERMOST_TOKEN'): warnings.warn("MATTERMOST_TOKEN is deprecated, use MATTERMOST_TOKENS \ instead", category=DeprecationWarning) settings.MATTERMOST_TOKENS = [settings.MATTERMOST_TOKEN] settings.MATTERMOST_TOKEN = None if settings.MATTERMOST_TOKENS: token = request.form['token'] if token not in settings.MATTERMOST_TOKENS: return jsonify({ 'response_type': 'ephemeral', 'text': tr("The integration is not correctly set up: " "Invalid token.") }) if 'user_id' not in request.form: abort(400) if 'text' not in request.form: abort(400) user_id = request.form['user_id'] request.user_id = user_id app.logger.debug('Received command: %s', request.form['text']) # the poll should have a fixed locale, otherwise it # changes for everyone every time someone votes locale = flask_babel.get_locale().language if request.form['text'].strip() == 'help': return jsonify({ 'response_type': 'ephemeral', 'text': format_help(request.form['command'], locale) }) args = parse_slash_command(request.form['text']) #debug #return jsonify({'response_type': 'ephemeral', 'text': str(args.progress)+str(args.lunch)+str(args.message)}) # lunch # built new message and vote_options if args.lunch: lunch = Lunch() restaurants = lunch.read_restaurant() try: num_restaurant = int(args.message) except: num_restaurant = len( restaurants ) # if no number is provider as a message, just list all restautrant in the db #return jsonify({'ephemeral_text':tr("Please provide a number.")}) restaurants_subset = random.sample(restaurants, num_restaurant) new_vote_options = restaurants_subset args_dict = args._asdict() args_dict['message'] = "Let's vote for lunch!" args_dict['vote_options'] = new_vote_options # copy from parse_slash_command Arguments = namedtuple('Arguments', [ 'message', 'vote_options', 'progress', 'public', 'max_votes', 'bars', 'locale', 'lunch', 'lunchadd', 'lunchrm', 'lunchls' ]) args = Arguments(**args_dict) if args.lunchadd: lunch = Lunch() flag = lunch.add_restaurant(author_id=user_id, restaurant=args.message) if flag: return jsonify({ 'response_type': 'ephemeral', 'text': tr("Successfully added restaurant.") }) else: return jsonify({ 'response_type': 'ephemeral', 'text': tr("Error in adding restaurant.") }) if args.lunchrm: lunch = Lunch() flag = lunch.rm_restaurant(args.message) if flag: return jsonify({ 'response_type': 'ephemeral', 'text': tr("Successfully removed restaurant.") }) else: return jsonify({ 'response_type': 'ephemeral', 'text': tr("Error in removing restaurant.") }) if args.lunchls: lunch = Lunch() restaurants = lunch.read_restaurant() restaurants_str = ",".join(restaurants) return jsonify({'response_type': 'ephemeral', 'text': restaurants_str}) if not args.message: text = tr("**Please provide a message.**\n\n" "**Usage:**\n{help}").format( help=format_help(request.form['command'], locale)) return jsonify({'response_type': 'ephemeral', 'text': text}) if args.public: if not settings.MATTERMOST_URL or not settings.MATTERMOST_PA_TOKEN: return jsonify({ 'response_type': 'ephemeral', 'text': tr("Public polls are not available with the " "current setup. Please check with you " "system administrator.") }) if args.locale: locale = args.locale poll = Poll.create(user_id, message=args.message, locale=locale, vote_options=args.vote_options, secret=not args.progress, public=args.public, max_votes=args.max_votes, bars=args.bars) app.logger.info('Creating Poll: %s', poll.id) return jsonify(format_poll(poll))
def test_get_poll(self): poll = Poll.create(creator_id='user0', message='# Spam? **:tada:**', vote_options=['Sure', 'Maybe', 'No'], secret=False) poll.vote('user0', 0) poll.vote('user1', 1) poll.vote('user2', 2) poll.vote('user3', 2) with self.subTest('Running poll'): with app.app.test_request_context(base_url='http://localhost:5005'): poll_dict = app.get_poll(poll) self.assertIn('response_type', poll_dict) self.assertIn('attachments', poll_dict) self.assertEqual(poll_dict['response_type'], 'in_channel') attachments = poll_dict['attachments'] self.assertEqual(len(attachments), 1) self.assertIn('text', attachments[0]) self.assertIn('actions', attachments[0]) self.assertIn('fields', attachments[0]) self.assertEqual(attachments[0]['text'], poll.message) self.assertEqual(len(attachments[0]['actions']), 4) fields = attachments[0]['fields'] self.assertEqual(len(fields), 1) self.assertIn('short', fields[0]) self.assertIn('title', fields[0]) self.assertIn('value', fields[0]) self.assertEqual(False, fields[0]['short']) self.assertEqual("", fields[0]['title']) self.assertEqual('*Number of Votes: 4*', fields[0]['value']) poll.end() with self.subTest('Finished poll'): with app.app.test_request_context(base_url='http://localhost:5005'): poll_dict = app.get_poll(poll) self.assertIn('response_type', poll_dict) self.assertIn('attachments', poll_dict) self.assertEqual(poll_dict['response_type'], 'in_channel') attachments = poll_dict['attachments'] self.assertEqual(len(attachments), 1) self.assertIn('text', attachments[0]) self.assertNotIn('actions', attachments[0]) self.assertIn('fields', attachments[0]) self.assertEqual(attachments[0]['text'], poll.message) fields = attachments[0]['fields'] self.assertEqual(len(fields), 4) self.assertIn('short', fields[0]) self.assertIn('title', fields[0]) self.assertIn('value', fields[0]) self.assertEqual(False, fields[0]['short']) self.assertEqual("", fields[0]['title']) self.assertEqual('*Number of Votes: 4*', fields[0]['value']) expected = [ (poll.vote_options[0], '1 (25.0%)'), (poll.vote_options[1], '1 (25.0%)'), (poll.vote_options[2], '2 (50.0%)'), ] for field, (title, value) in zip(fields[1:], expected): self.assertIn('short', field) self.assertIn('title', field) self.assertIn('value', field) self.assertEqual(True, field['short']) self.assertEqual(title, field['title']) self.assertEqual(value, field['value'])
def poll(): """Creates a new poll. Directly called by Mattermost. Example response data: ``` { "response_type": "in_channel", "attachments": [{ "text": "<Poll message>", "actions": [ { "name": "<First Option> (0)", "integration": { "context": { "poll_id": "<unique_id>", "vote": 0 }, "url": "http://<hostname:port>/vote" } }, ... additional entries for all poll options ... { "name": "End Poll", "integration": { "url": "http://<hostname:port>/end", "context": { "poll_id": "<unique_id>" } } }], "fields": [ { "short": false, "title": "", "value": "Number of Votes: 1" }] }] } ``` """ if hasattr(settings, 'MATTERMOST_TOKEN'): warnings.warn("MATTERMOST_TOKEN is deprecated, use MATTERMOST_TOKENS \ instead", category=DeprecationWarning) settings.MATTERMOST_TOKENS = [settings.MATTERMOST_TOKEN] settings.MATTERMOST_TOKEN = None if settings.MATTERMOST_TOKENS: token = request.form['token'] if token not in settings.MATTERMOST_TOKENS: return jsonify({ 'response_type': 'ephemeral', 'text': "The integration is not correctly set up: Invalid token." }) if 'user_id' not in request.form: abort(400) if 'text' not in request.form: abort(400) user_id = request.form['user_id'] app.logger.debug('Received command: %s', request.form['text']) if request.form['text'].strip() == 'help': return jsonify({ 'response_type': 'ephemeral', 'text': get_help(request.form['command']) }) args = parse_slash_command(request.form['text']) if not args.message: return jsonify({ 'response_type': 'ephemeral', 'text': "Please provide a message" }) if args.public: if not settings.MATTERMOST_URL or not settings.MATTERMOST_PA_TOKEN: return jsonify({ 'response_type': 'ephemeral', 'text': "Public polls are not available with the " "current setup. Please check with you " "system administrator." }) poll = Poll.create(user_id, message=args.message, vote_options=args.vote_options, secret=args.secret, public=args.public, max_votes=args.max_votes) app.logger.info('Creating Poll: %s', poll.id) return jsonify(get_poll(poll))