How to use poll method in wpt

Best JavaScript code snippet using wpt

tests.py

Source:tests.py Github

copy

Full Screen

...186 self.user2 = utils.create_user()187 self.category = utils.create_category()188 self.topic = utils.create_topic(self.category, user=self.user)189 self.topic2 = utils.create_topic(self.category, user=self.user2)190 def test_create_poll(self):191 """192 TopicPollForm193 """194 form_data = {'choice_limit': 1, }195 form = TopicPollForm(topic=self.topic, data=form_data)196 self.assertTrue(form.is_valid())197 form.save()198 self.assertEqual(len(TopicPoll.objects.filter(topic=self.topic)), 1)199 def test_create_poll_invalid(self):200 """201 TopicPollForm202 """203 form_data = {'choice_limit': 0, }204 form = TopicPollForm(topic=self.topic, data=form_data)205 self.assertFalse(form.is_valid())206 def test_poll_choices_can_delete(self):207 """208 TopicPollChoiceFormSet209 """210 form = TopicPollChoiceFormSet(can_delete=True)211 self.assertIn('DELETE', [f.fields for f in form.forms][0])212 form = TopicPollChoiceFormSet(can_delete=False)213 self.assertNotIn('DELETE', [f.fields for f in form.forms][0])214 def test_create_poll_choices(self):215 """216 TopicPollChoiceFormSet217 Check it's valid and is filled218 """219 form_data = {'choices-TOTAL_FORMS': 2, 'choices-INITIAL_FORMS': 0,220 'choices-0-description': 'op1',221 'choices-1-description': 'op2'}222 form = TopicPollChoiceFormSet(data=form_data)223 self.assertTrue(form.is_valid())224 self.assertTrue(form.is_filled())225 def test_create_poll_choices_unfilled(self):226 """227 TopicPollChoiceFormSet228 """229 form_data = {'choices-TOTAL_FORMS': 2, 'choices-INITIAL_FORMS': 0,230 'choices-0-description': '',231 'choices-1-description': ''}232 form = TopicPollChoiceFormSet(data=form_data)233 self.assertTrue(form.is_valid())234 self.assertFalse(form.is_filled())235 def test_create_poll_choices_filled_but_deleted(self):236 """237 TopicPollChoiceFormSet, create238 """239 form_data = {'choices-TOTAL_FORMS': 2, 'choices-INITIAL_FORMS': 0,240 'choices-0-description': 'op1', 'choices-0-DELETE': "on",241 'choices-1-description': 'op2', 'choices-1-DELETE': "on"}242 form = TopicPollChoiceFormSet(can_delete=True, data=form_data)243 self.assertTrue(form.is_valid()) # not enough choices, but since we are NOT updating this is valid244 self.assertFalse(form.is_filled())245 def test_update_poll_choices_filled_but_deleted(self):246 """247 TopicPollChoiceFormSet, update248 is_filled should not be called when updating (coz form is always filled), but whatever249 """250 poll = TopicPoll.objects.create(topic=self.topic)251 form_data = {'choices-TOTAL_FORMS': 2, 'choices-INITIAL_FORMS': 0,252 'choices-0-description': 'op1', 'choices-0-DELETE': "on",253 'choices-1-description': 'op2', 'choices-1-DELETE': "on"}254 form = TopicPollChoiceFormSet(can_delete=True, data=form_data, instance=poll)255 self.assertFalse(form.is_valid()) # not enough choices256 self.assertTrue(form.is_filled())257class TopicPollVoteManyFormTest(TestCase):258 def setUp(self):259 cache.clear()260 self.user = utils.create_user()261 self.user2 = utils.create_user()262 self.category = utils.create_category()263 self.topic = utils.create_topic(self.category, user=self.user)264 self.topic2 = utils.create_topic(self.category, user=self.user2)265 self.topic3 = utils.create_topic(self.category, user=self.user2)266 self.poll = TopicPoll.objects.create(topic=self.topic, choice_limit=1)267 self.poll_multi = TopicPoll.objects.create(topic=self.topic2, choice_limit=2)268 self.poll_choice = TopicPollChoice.objects.create(poll=self.poll, description="op1")269 self.poll_choice2 = TopicPollChoice.objects.create(poll=self.poll, description="op2")270 self.poll_vote = TopicPollVote.objects.create(user=self.user, choice=self.poll_choice)271 self.poll_vote2 = TopicPollVote.objects.create(user=self.user2, choice=self.poll_choice)272 self.poll_multi_choice = TopicPollChoice.objects.create(poll=self.poll_multi, description="op1")273 self.poll_multi_choice2 = TopicPollChoice.objects.create(poll=self.poll_multi, description="op2")274 self.poll_multi_choice3 = TopicPollChoice.objects.create(poll=self.poll_multi, description="op3")275 self.poll_multi_vote = TopicPollVote.objects.create(user=self.user, choice=self.poll_multi_choice)276 self.poll_multi_vote2 = TopicPollVote.objects.create(user=self.user, choice=self.poll_multi_choice2)277 self.poll_multi_vote3 = TopicPollVote.objects.create(user=self.user2, choice=self.poll_multi_choice)278 def test_vote_load_initial_single(self):279 """280 TopicPollVoteManyForm281 """282 form = TopicPollVoteManyForm(user=self.user, poll=self.poll)283 form.load_initial()284 self.assertDictEqual(form.initial, {'choices': self.poll_choice, })285 def test_vote_load_initial_multi(self):286 """287 TopicPollVoteManyForm288 """289 form = TopicPollVoteManyForm(user=self.user, poll=self.poll_multi)290 form.load_initial()291 self.assertDictEqual(form.initial, {'choices': [self.poll_multi_choice, self.poll_multi_choice2], })292 def test_vote_load_initial_empty(self):293 """294 TopicPollVoteManyForm295 """296 TopicPollVote.objects.all().delete()297 form = TopicPollVoteManyForm(user=self.user, poll=self.poll)298 form.load_initial()299 self.assertEqual(form.initial, {})300 def test_vote_load_initial_choice_limit(self):301 """302 Load initial for a single choice poll that was previously a multi choice poll303 """304 # multi to single305 self.poll_multi.choice_limit = 1306 form = TopicPollVoteManyForm(user=self.user, poll=self.poll_multi)307 form.load_initial()308 self.assertDictEqual(form.initial, {'choices': self.poll_multi_choice, })309 # single to multi310 self.poll.choice_limit = 2311 form = TopicPollVoteManyForm(user=self.user, poll=self.poll)312 form.load_initial()313 self.assertDictEqual(form.initial, {'choices': [self.poll_choice, ], })314 def test_vote_poll_closed(self):315 """316 Cant vote on closed poll317 """318 self.poll.is_closed = True319 self.poll.save()320 form_data = {'choices': self.poll_choice.pk, }321 form = TopicPollVoteManyForm(user=self.user, poll=self.poll, data=form_data)322 self.assertFalse(form.is_valid())323 def test_create_vote_single(self):324 """325 TopicPollVoteManyForm326 """327 TopicPollVote.objects.all().delete()328 form_data = {'choices': self.poll_choice.pk, }329 form = TopicPollVoteManyForm(user=self.user, poll=self.poll, data=form_data)330 self.assertTrue(form.is_valid())331 form.save_m2m()332 self.assertEqual(len(TopicPollVote.objects.filter(choice=self.poll_choice)), 1)333 def test_create_vote_multi(self):334 """335 TopicPollVoteManyForm336 """337 TopicPollVote.objects.all().delete()338 form_data = {'choices': [self.poll_multi_choice.pk, self.poll_multi_choice2.pk], }339 form = TopicPollVoteManyForm(user=self.user, poll=self.poll_multi, data=form_data)340 self.assertTrue(form.is_valid())341 def test_create_vote_multi_invalid(self):342 """343 Limit selected choices to choice_limit344 """345 TopicPollVote.objects.all().delete()346 form_data = {'choices': [self.poll_multi_choice.pk,347 self.poll_multi_choice2.pk,348 self.poll_multi_choice3.pk], }349 form = TopicPollVoteManyForm(user=self.user, poll=self.poll_multi, data=form_data)350 self.assertFalse(form.is_valid())351 def test_update_vote_single(self):352 """353 TopicPollVoteManyForm354 """355 self.assertEqual(len(TopicPollVote.objects.filter(choice=self.poll_choice2)), 0)356 self.assertEqual(len(TopicPollVote.objects.filter(choice=self.poll_choice)), 2)357 form_data = {'choices': self.poll_choice2.pk, }358 form = TopicPollVoteManyForm(user=self.user, poll=self.poll, data=form_data)359 self.assertTrue(form.is_valid())360 form.save_m2m()361 self.assertEqual(len(TopicPollVote.objects.filter(choice=self.poll_choice2)), 1)362 self.assertEqual(len(TopicPollVote.objects.filter(choice=self.poll_choice)), 1)363class TopicPollSignalTest(TestCase):364 def setUp(self):365 cache.clear()366 self.user = utils.create_user()367 self.category = utils.create_category()368 self.topic = utils.create_topic(category=self.category, user=self.user)369 self.topic2 = utils.create_topic(category=self.category, user=self.user)370 self.poll = TopicPoll.objects.create(topic=self.topic)371 self.poll_other = TopicPoll.objects.create(topic=self.topic2)372 self.poll_choice = TopicPollChoice.objects.create(poll=self.poll, description="op1")373 self.poll_choice2 = TopicPollChoice.objects.create(poll=self.poll, description="op2")374 self.poll_other_choice = TopicPollChoice.objects.create(poll=self.poll_other, description="op2")375 self.poll_vote = TopicPollVote.objects.create(user=self.user, choice=self.poll_choice)376 self.poll_other_vote = TopicPollVote.objects.create(user=self.user, choice=self.poll_other_choice)377 def test_topic_poll_pre_vote_handler(self):378 """379 topic_poll_pre_vote_handler signal380 """381 self.poll_choice.vote_count = 2382 self.poll_choice.save()383 topic_poll_pre_vote.send(sender=self.poll.__class__, poll=self.poll, user=self.user)384 self.assertEqual(TopicPollChoice.objects.get(pk=self.poll_choice.pk).vote_count, 1)385 self.assertEqual(TopicPollChoice.objects.get(pk=self.poll_other_choice.pk).vote_count, 0)386 def test_topic_poll_post_vote_handler(self):387 """388 topic_poll_post_vote_handler signal389 """390 topic_poll_post_vote.send(sender=self.poll.__class__, poll=self.poll, user=self.user)391 self.assertEqual(TopicPollChoice.objects.get(pk=self.poll_choice.pk).vote_count, 1)392 self.assertEqual(TopicPollChoice.objects.get(pk=self.poll_other_choice.pk).vote_count, 0)393class TopicPollTemplateTagsTest(TestCase):394 def setUp(self):395 cache.clear()396 self.user = utils.create_user()397 self.category = utils.create_category()398 self.topic = utils.create_topic(category=self.category, user=self.user)399 self.poll = TopicPoll.objects.create(topic=self.topic)400 def test_render_poll_form(self):401 """402 should display poll vote form403 """404 out = Template(405 "{% load spirit_tags %}"406 "{% render_poll_form topic=topic user=user %}"407 ).render(Context({'topic': self.topic, 'user': self.user}))408 self.assertNotEqual(out.strip(), "")409 context = render_poll_form(self.topic, self.user)410 self.assertEqual(context['next'], None)411 self.assertIsInstance(context['form'], TopicPollVoteManyForm)412 self.assertEqual(context['poll'], self.poll)413 def test_render_poll_form_no_poll(self):414 """415 should display nothing416 """417 topic = utils.create_topic(category=self.category, user=self.user)418 out = Template(419 "{% load spirit_tags %}"420 "{% render_poll_form topic=topic user=user %}"421 ).render(Context({'topic': topic, 'user': self.user}))422 self.assertEqual(out.strip(), "")423 def test_render_poll_form_user(self):424 """425 should load initial or not426 """427 poll_choice = TopicPollChoice.objects.create(poll=self.poll, description="op2")...

Full Screen

Full Screen

tests_topic_poll.py

Source:tests_topic_poll.py Github

copy

Full Screen

...186 self.user2 = utils.create_user()187 self.category = utils.create_category()188 self.topic = utils.create_topic(self.category, user=self.user)189 self.topic2 = utils.create_topic(self.category, user=self.user2)190 def test_create_poll(self):191 """192 TopicPollForm193 """194 form_data = {'choice_limit': 1, }195 form = TopicPollForm(topic=self.topic, data=form_data)196 self.assertTrue(form.is_valid())197 form.save()198 self.assertEqual(len(TopicPoll.objects.filter(topic=self.topic)), 1)199 def test_create_poll_invalid(self):200 """201 TopicPollForm202 """203 form_data = {'choice_limit': 0, }204 form = TopicPollForm(topic=self.topic, data=form_data)205 self.assertFalse(form.is_valid())206 def test_poll_choices_can_delete(self):207 """208 TopicPollChoiceFormSet209 """210 form = TopicPollChoiceFormSet(can_delete=True)211 self.assertIn('DELETE', [f.fields for f in form.forms][0])212 form = TopicPollChoiceFormSet(can_delete=False)213 self.assertNotIn('DELETE', [f.fields for f in form.forms][0])214 def test_create_poll_choices(self):215 """216 TopicPollChoiceFormSet217 Check it's valid and is filled218 """219 form_data = {'choices-TOTAL_FORMS': 2, 'choices-INITIAL_FORMS': 0,220 'choices-0-description': 'op1',221 'choices-1-description': 'op2'}222 form = TopicPollChoiceFormSet(data=form_data)223 self.assertTrue(form.is_valid())224 self.assertTrue(form.is_filled())225 def test_create_poll_choices_unfilled(self):226 """227 TopicPollChoiceFormSet228 """229 form_data = {'choices-TOTAL_FORMS': 2, 'choices-INITIAL_FORMS': 0,230 'choices-0-description': '',231 'choices-1-description': ''}232 form = TopicPollChoiceFormSet(data=form_data)233 self.assertTrue(form.is_valid())234 self.assertFalse(form.is_filled())235 def test_create_poll_choices_filled_but_deleted(self):236 """237 TopicPollChoiceFormSet, create238 """239 form_data = {'choices-TOTAL_FORMS': 2, 'choices-INITIAL_FORMS': 0,240 'choices-0-description': 'op1', 'choices-0-DELETE': "on",241 'choices-1-description': 'op2', 'choices-1-DELETE': "on"}242 form = TopicPollChoiceFormSet(can_delete=True, data=form_data)243 self.assertTrue(form.is_valid())244 self.assertFalse(form.is_filled())245 def test_update_poll_choices_filled_but_deleted(self):246 """247 TopicPollChoiceFormSet, update248 is_filled should not be called when updating (coz form is always filled), but whatever249 """250 poll = TopicPoll.objects.create(topic=self.topic)251 form_data = {'choices-TOTAL_FORMS': 2, 'choices-INITIAL_FORMS': 0,252 'choices-0-description': 'op1', 'choices-0-DELETE': "on",253 'choices-1-description': 'op2', 'choices-1-DELETE': "on"}254 form = TopicPollChoiceFormSet(can_delete=True, data=form_data, instance=poll)255 self.assertTrue(form.is_valid())256 self.assertTrue(form.is_filled())257class TopicPollVoteManyFormTest(TestCase):258 def setUp(self):259 cache.clear()260 self.user = utils.create_user()261 self.user2 = utils.create_user()262 self.category = utils.create_category()263 self.topic = utils.create_topic(self.category, user=self.user)264 self.topic2 = utils.create_topic(self.category, user=self.user2)265 self.topic3 = utils.create_topic(self.category, user=self.user2)266 self.poll = TopicPoll.objects.create(topic=self.topic, choice_limit=1)267 self.poll_multi = TopicPoll.objects.create(topic=self.topic2, choice_limit=2)268 self.poll_choice = TopicPollChoice.objects.create(poll=self.poll, description="op1")269 self.poll_choice2 = TopicPollChoice.objects.create(poll=self.poll, description="op2")270 self.poll_vote = TopicPollVote.objects.create(user=self.user, choice=self.poll_choice)271 self.poll_vote2 = TopicPollVote.objects.create(user=self.user2, choice=self.poll_choice)272 self.poll_multi_choice = TopicPollChoice.objects.create(poll=self.poll_multi, description="op1")273 self.poll_multi_choice2 = TopicPollChoice.objects.create(poll=self.poll_multi, description="op2")274 self.poll_multi_choice3 = TopicPollChoice.objects.create(poll=self.poll_multi, description="op3")275 self.poll_multi_vote = TopicPollVote.objects.create(user=self.user, choice=self.poll_multi_choice)276 self.poll_multi_vote2 = TopicPollVote.objects.create(user=self.user, choice=self.poll_multi_choice2)277 self.poll_multi_vote3 = TopicPollVote.objects.create(user=self.user2, choice=self.poll_multi_choice)278 def test_vote_load_initial_single(self):279 """280 TopicPollVoteManyForm281 """282 form = TopicPollVoteManyForm(user=self.user, poll=self.poll)283 form.load_initial()284 self.assertDictEqual(form.initial, {'choices': self.poll_choice, })285 def test_vote_load_initial_multi(self):286 """287 TopicPollVoteManyForm288 """289 form = TopicPollVoteManyForm(user=self.user, poll=self.poll_multi)290 form.load_initial()291 self.assertDictEqual(form.initial, {'choices': [self.poll_multi_choice, self.poll_multi_choice2], })292 def test_vote_load_initial_empty(self):293 """294 TopicPollVoteManyForm295 """296 TopicPollVote.objects.all().delete()297 form = TopicPollVoteManyForm(user=self.user, poll=self.poll)298 form.load_initial()299 self.assertEqual(form.initial, {})300 def test_vote_load_initial_choice_limit(self):301 """302 Load initial for a single choice poll that was previously a multi choice poll303 """304 # multi to single305 self.poll_multi.choice_limit = 1306 form = TopicPollVoteManyForm(user=self.user, poll=self.poll_multi)307 form.load_initial()308 self.assertDictEqual(form.initial, {'choices': self.poll_multi_choice, })309 # single to multi310 self.poll.choice_limit = 2311 form = TopicPollVoteManyForm(user=self.user, poll=self.poll)312 form.load_initial()313 self.assertDictEqual(form.initial, {'choices': [self.poll_choice, ], })314 def test_vote_poll_closed(self):315 """316 Cant vote on closed poll317 """318 self.poll.is_closed = True319 self.poll.save()320 form_data = {'choices': self.poll_choice.pk, }321 form = TopicPollVoteManyForm(user=self.user, poll=self.poll, data=form_data)322 self.assertFalse(form.is_valid())323 def test_create_vote_single(self):324 """325 TopicPollVoteManyForm326 """327 TopicPollVote.objects.all().delete()328 form_data = {'choices': self.poll_choice.pk, }329 form = TopicPollVoteManyForm(user=self.user, poll=self.poll, data=form_data)330 self.assertTrue(form.is_valid())331 form.save_m2m()332 self.assertEqual(len(TopicPollVote.objects.filter(choice=self.poll_choice)), 1)333 def test_create_vote_multi(self):334 """335 TopicPollVoteManyForm336 """337 TopicPollVote.objects.all().delete()338 form_data = {'choices': [self.poll_multi_choice.pk, self.poll_multi_choice2.pk], }339 form = TopicPollVoteManyForm(user=self.user, poll=self.poll_multi, data=form_data)340 self.assertTrue(form.is_valid())341 def test_create_vote_multi_invalid(self):342 """343 Limit selected choices to choice_limit344 """345 TopicPollVote.objects.all().delete()346 form_data = {'choices': [self.poll_multi_choice.pk,347 self.poll_multi_choice2.pk,348 self.poll_multi_choice3.pk], }349 form = TopicPollVoteManyForm(user=self.user, poll=self.poll_multi, data=form_data)350 self.assertFalse(form.is_valid())351 def test_update_vote_single(self):352 """353 TopicPollVoteManyForm354 """355 self.assertEqual(len(TopicPollVote.objects.filter(choice=self.poll_choice2)), 0)356 self.assertEqual(len(TopicPollVote.objects.filter(choice=self.poll_choice)), 2)357 form_data = {'choices': self.poll_choice2.pk, }358 form = TopicPollVoteManyForm(user=self.user, poll=self.poll, data=form_data)359 self.assertTrue(form.is_valid())360 form.save_m2m()361 self.assertEqual(len(TopicPollVote.objects.filter(choice=self.poll_choice2)), 1)362 self.assertEqual(len(TopicPollVote.objects.filter(choice=self.poll_choice)), 1)363class TopicPollSignalTest(TestCase):364 def setUp(self):365 cache.clear()366 self.user = utils.create_user()367 self.category = utils.create_category()368 self.topic = utils.create_topic(category=self.category, user=self.user)369 self.topic2 = utils.create_topic(category=self.category, user=self.user)370 self.poll = TopicPoll.objects.create(topic=self.topic)371 self.poll_other = TopicPoll.objects.create(topic=self.topic2)372 self.poll_choice = TopicPollChoice.objects.create(poll=self.poll, description="op1")373 self.poll_choice2 = TopicPollChoice.objects.create(poll=self.poll, description="op2")374 self.poll_other_choice = TopicPollChoice.objects.create(poll=self.poll_other, description="op2")375 self.poll_vote = TopicPollVote.objects.create(user=self.user, choice=self.poll_choice)376 self.poll_other_vote = TopicPollVote.objects.create(user=self.user, choice=self.poll_other_choice)377 def test_topic_poll_pre_vote_handler(self):378 """379 topic_poll_pre_vote_handler signal380 """381 self.poll_choice.vote_count = 2382 self.poll_choice.save()383 topic_poll_pre_vote.send(sender=self.poll.__class__, poll=self.poll, user=self.user)384 self.assertEqual(TopicPollChoice.objects.get(pk=self.poll_choice.pk).vote_count, 1)385 self.assertEqual(TopicPollChoice.objects.get(pk=self.poll_other_choice.pk).vote_count, 0)386 def test_topic_poll_post_vote_handler(self):387 """388 topic_poll_post_vote_handler signal389 """390 topic_poll_post_vote.send(sender=self.poll.__class__, poll=self.poll, user=self.user)391 self.assertEqual(TopicPollChoice.objects.get(pk=self.poll_choice.pk).vote_count, 1)392 self.assertEqual(TopicPollChoice.objects.get(pk=self.poll_other_choice.pk).vote_count, 0)393class TopicPollTemplateTagsTest(TestCase):394 def setUp(self):395 cache.clear()396 self.user = utils.create_user()397 self.category = utils.create_category()398 self.topic = utils.create_topic(category=self.category, user=self.user)399 self.poll = TopicPoll.objects.create(topic=self.topic)400 def test_render_poll_form(self):401 """402 should display poll vote form403 """404 out = Template(405 "{% load foro_tags %}"406 "{% render_poll_form topic=topic user=user %}"407 ).render(Context({'topic': self.topic, 'user': self.user}))408 self.assertNotEqual(out.strip(), "")409 context = render_poll_form(self.topic, self.user)410 self.assertEqual(context['next'], None)411 self.assertIsInstance(context['form'], TopicPollVoteManyForm)412 self.assertEqual(context['poll'], self.poll)413 def test_render_poll_form_no_poll(self):414 """415 should display nothing416 """417 topic = utils.create_topic(category=self.category, user=self.user)418 out = Template(419 "{% load foro_tags %}"420 "{% render_poll_form topic=topic user=user %}"421 ).render(Context({'topic': topic, 'user': self.user}))422 self.assertEqual(out.strip(), "")423 def test_render_poll_form_user(self):424 """425 should load initial or not426 """427 poll_choice = TopicPollChoice.objects.create(poll=self.poll, description="op2")...

Full Screen

Full Screen

views.py

Source:views.py Github

copy

Full Screen

...173 return redirect("poll:detail", poll_id)174 175 return render(request, 'poll/poll_result.html', {'poll': poll})176@login_required177def endpoll(request, poll_id):178 poll = get_object_or_404(Poll, pk=poll_id)179 if request.user != poll.owner:180 return redirect('home')181 if poll.active is True:182 poll.active = False183 poll.save()184 return render(request, 'poll/poll_result.html', {'poll': poll})185 else:186 return render(request, 'poll/poll_result.html', {'poll': poll})187@login_required188def poll_result(request):189 polls = Poll.objects.all()190 context = {191 "polls":polls...

Full Screen

Full Screen

index.js

Source:index.js Github

copy

Full Screen

1const errors = require("../../helpers/mainErrors");2const {3 User,4 Thread,5 PollQuestion,6 PollVote,7 PollResponse8} = require("../../models");9const attributes = require("../../helpers/getModelAttributes");10const validate = require("../../helpers/validation");11const moment = require("moment");12// /:pollId13exports.getAPoll = async (req, res, next) => {14 try {15 const pollQuestion = await PollQuestion.findById(req.params.pollId);16 if (!pollQuestion) {17 next(errors.pollError);18 } else {19 const pollQuestionReq = attributes.convert(pollQuestion);20 // check if the polls active21 if (pollQuestionReq.active === false) {22 next(errors.pollEndedError);23 } else {24 // check if the polls been open for 7 days25 const days = moment(pollQuestionReq.createdAt).fromNow();26 if (days >= 7) {27 await PollQuestion.update(28 { active: true },29 { where: { id: pollQuestionReq.id } }30 );31 }32 // get the questiosn responses33 const pollResponses = await PollResponse.findAll({34 where: { PollQuestionId: pollQuestionReq.id }35 });36 const result = pollResponses.map(f => {37 return f.response;38 });39 Promise.all(result).then(complete => {40 res.json({41 poll: {42 question: pollQuestionReq.question,43 responses: complete,44 results: pollQuestionReq.PollVotes45 }46 });47 });48 }49 }50 } catch (error) {51 next(error);52 }53};54// /all55exports.getAllPolls = async (req, res, next) => {56 try {57 const polls = await PollQuestion.findAndCountAll();58 res.json(polls);59 } catch (error) {60 next(error);61 }62};63// /:pollId/result64exports.generatePollResults = async (req, res, next) => {65 try {66 const results = await PollVote.findAndCountAll({67 where: { PollQuestionId: req.params.pollId }68 });69 const question = await PollQuestion.findById(req.params.pollId);70 const questionReq = attributes.convert(question);71 const count = results.rows.reduce((sum, row) => {72 sum[row.PollResponseId] = (sum[row.PollResponseId] || 0) + 1;73 return sum;74 }, {});75 const resultObj = {76 total: results.count,77 questionId: questionReq.id,78 results: count79 };80 res.json(resultObj);81 } catch (error) {82 next(error);83 }84};85// /:threadId/new86exports.newPoll = async (req, res, next) => {87 try {88 const thread = await Thread.findOne({89 where: { id: req.params.threadId }90 });91 if (!thread) {92 next(errors.threadError);93 } else {94 const question = req.body.question;95 const responses = req.body.responses;96 // response validation97 if (responses.length < 2) {98 next(errors.pollResponseError);99 } else if (responses.length !== new Set(responses).size) {100 next(errors.pollResponseDuplicates);101 } else if (validate.isEmpty(question)) {102 next(errors.pollQuestionError);103 } else {104 // lets create a new poll105 // create the poll question106 const pollQuestion = await PollQuestion.create({107 question,108 UserId: req.session.userId,109 duration: req.body.duration110 });111 const questionReq = attributes.convert(pollQuestion);112 // add the polls responses113 await Promise.all(114 responses.map(r =>115 PollResponse.create({116 response: r,117 PollQuestionId: questionReq.id118 })119 )120 );121 // add the poll to the thread122 const threadReq = attributes.convert(thread);123 await Thread.update(124 { PollQuestionId: questionReq.id },125 {126 where: {127 id: threadReq.id128 }129 }130 );131 const user = await User.findById(req.session.userId);132 await user.increment("points", {133 by: req.app.locals.pointsPerPollVote134 });135 res.json({ success: true });136 }137 }138 } catch (error) {139 next(error);140 }141};142// /:pollId/:responseId/vote143exports.voteOnPoll = async (req, res, next) => {144 try {145 // get the poll question146 const poll = await PollQuestion.findById(req.params.pollId);147 if (!poll) {148 next(errors.pollError);149 } else {150 const pollReq = attributes.convert(poll);151 // check if the user has already voted152 const votes = await PollVote.findAll({153 where: { UserId: req.session.userId }154 });155 let error = false;156 votes.map(v => {157 if (v.UserId === req.session.userId) {158 error = true;159 }160 });161 if (error) {162 next(errors.pollAlreadyVotedError);163 } else {164 // record the users vote165 await PollVote.create({166 UserId: req.session.userId,167 PollQuestionId: pollReq.id,168 PollResponseId: req.params.responseId169 });170 const user = await User.findById(req.session.userId);171 await user.increment("points", {172 by: req.app.locals.pointsPerPollVote173 });174 // return response message175 res.json({ success: true });176 }177 }178 } catch (error) {179 next(error);180 }181};182// /:pollId183exports.editPoll = async (req, res, next) => {184 try {185 const poll = await PollQuestion.findOne({186 where: { id: req.params.pollId }187 });188 if (!poll) {189 next(errors.pollError);190 } else {191 const question = req.body.question;192 const responses = req.body.responses;193 // response validation194 if (responses.length < 2) {195 next(errors.pollResponseError);196 } else if (responses.length !== new Set(responses).size) {197 next(errors.pollResponseDuplicates);198 } else if (validate.isEmpty(question)) {199 next(errors.pollQuestionError);200 } else {201 // update a poll202 // update the poll's question203 const pollQuestion = await PollQuestion.update(204 {205 question,206 UserId: req.session.userId207 },208 { where: { id: req.params.pollId } }209 );210 const questionReq = attributes.convert(pollQuestion);211 // update the polls responses212 await Promise.all(213 responses.map((r, i) => {214 return PollResponse.update(215 {216 response: r,217 PollQuestionId: questionReq.id218 },219 { where: { id: ++i } }220 );221 })222 );223 res.json({ success: true });224 }225 }226 } catch (error) {227 next(error);228 }229};230// /:pollId/remove231exports.removePoll = async (req, res, next) => {232 try {233 // find poll234 const poll = await PollQuestion.findById(req.params.pollId);235 const pollReq = attributes.convert(poll);236 // remove votes237 await PollVote.destroy({238 where: { PollQuestionId: pollReq.id }239 });240 // remove responses241 await PollResponse.destroy({242 where: { PollQuestionId: pollReq.id }243 });244 // remove question245 await PollQuestion.destroy({246 where: { id: pollReq.id }247 });248 // return response249 res.json({ success: true });250 } catch (error) {251 next(error);252 }...

Full Screen

Full Screen

test_poll.py

Source:test_poll.py Github

copy

Full Screen

...64 assert poll_answer_dict['poll_id'] == poll_answer.poll_id65 assert poll_answer_dict['user'] == poll_answer.user.to_dict()66 assert poll_answer_dict['option_ids'] == poll_answer.option_ids67@pytest.fixture(scope='class')68def poll():69 return Poll(TestPoll.id_,70 TestPoll.question,71 TestPoll.options,72 TestPoll.total_voter_count,73 TestPoll.is_closed,74 TestPoll.is_anonymous,75 TestPoll.type,76 TestPoll.allows_multiple_answers,77 explanation=TestPoll.explanation,78 explanation_entities=TestPoll.explanation_entities,79 open_period=TestPoll.open_period,80 close_date=TestPoll.close_date,81 )82class TestPoll:...

Full Screen

Full Screen

poll-ui-builder.js.es6

Source:poll-ui-builder.js.es6 Github

copy

Full Screen

...134 let pollHeader = "[poll";135 let output = "";136 const match = this.get("toolbarEvent")137 .getText()138 .match(/\[poll(\s+name=[^\s\]]+)*.*\]/gim);139 if (match) {140 pollHeader += ` name=poll${match.length + 1}`;141 }142 let step = pollStep;143 if (step < 1) {144 step = 1;145 }146 if (pollType) pollHeader += ` type=${pollType}`;147 if (pollMin && showMinMax) pollHeader += ` min=${pollMin}`;148 if (pollMax) pollHeader += ` max=${pollMax}`;149 if (isNumber) pollHeader += ` step=${step}`;150 if (publicPoll) pollHeader += ` public=true`;151 if (autoClose) {152 let closeDate = moment(...

Full Screen

Full Screen

polls-js.dev.js

Source:polls-js.dev.js Github

copy

Full Screen

1// Variables2var poll_id = 0;3var poll_answer_id = '';4var is_being_voted = false;5pollsL10n.show_loading = parseInt(pollsL10n.show_loading);6pollsL10n.show_fading = parseInt(pollsL10n.show_fading);7// When User Vote For Poll8function poll_vote(current_poll_id) {9 jQuery(document).ready(function($) {10 if(!is_being_voted) {11 set_is_being_voted(true);12 poll_id = current_poll_id;13 poll_answer_id = '';14 poll_multiple_ans = 0;15 poll_multiple_ans_count = 0;16 if($('#poll_multiple_ans_' + poll_id).length) {17 poll_multiple_ans = parseInt($('#poll_multiple_ans_' + poll_id).val());18 }19 $('#polls_form_' + poll_id + ' input:checkbox, #polls_form_' + poll_id + ' input:radio, #polls_form_' + poll_id + ' option').each(function(i){20 if ($(this).is(':checked') || $(this).is(':selected')) {21 if(poll_multiple_ans > 0) {22 poll_answer_id = $(this).val() + ',' + poll_answer_id;23 poll_multiple_ans_count++;24 } else {25 poll_answer_id = parseInt($(this).val());26 }27 }28 });29 if(poll_multiple_ans > 0) {30 if(poll_multiple_ans_count > 0 && poll_multiple_ans_count <= poll_multiple_ans) {31 poll_answer_id = poll_answer_id.substring(0, (poll_answer_id.length-1));32 poll_process();33 } else if(poll_multiple_ans_count == 0) {34 set_is_being_voted(false);35 alert(pollsL10n.text_valid);36 } else {37 set_is_being_voted(false);38 alert(pollsL10n.text_multiple + ' ' + poll_multiple_ans);39 }40 } else {41 if(poll_answer_id > 0) {42 poll_process();43 } else {44 set_is_being_voted(false);45 alert(pollsL10n.text_valid);46 }47 }48 } else {49 alert(pollsL10n.text_wait);50 }51 });52}53// Process Poll (User Click "Vote" Button)54function poll_process() {55 jQuery(document).ready(function($) {56 poll_nonce = $('#poll_' + poll_id + '_nonce').val();57 if(pollsL10n.show_fading) {58 $('#polls-' + poll_id).fadeTo('def', 0);59 if(pollsL10n.show_loading) {60 $('#polls-' + poll_id + '-loading').show();61 }62 $.ajax({type: 'POST', xhrFields: {withCredentials: true}, url: pollsL10n.ajax_url, data: 'action=polls&view=process&poll_id=' + poll_id + '&poll_' + poll_id + '=' + poll_answer_id + '&poll_' + poll_id + '_nonce=' + poll_nonce, cache: false, success: poll_process_success});63 } else {64 if(pollsL10n.show_loading) {65 $('#polls-' + poll_id + '-loading').show();66 }67 $.ajax({type: 'POST', xhrFields: {withCredentials: true}, url: pollsL10n.ajax_url, data: 'action=polls&view=process&poll_id=' + poll_id + '&poll_' + poll_id + '=' + poll_answer_id + '&poll_' + poll_id + '_nonce=' + poll_nonce, cache: false, success: poll_process_success});68 }69 });70}71// Poll's Result (User Click "View Results" Link)72function poll_result(current_poll_id) {73 jQuery(document).ready(function($) {74 if(!is_being_voted) {75 set_is_being_voted(true);76 poll_id = current_poll_id;77 poll_nonce = $('#poll_' + poll_id + '_nonce').val();78 if(pollsL10n.show_fading) {79 $('#polls-' + poll_id).fadeTo('def', 0);80 if(pollsL10n.show_loading) {81 $('#polls-' + poll_id + '-loading').show();82 }83 $.ajax({type: 'POST', xhrFields: {withCredentials: true}, url: pollsL10n.ajax_url, data: 'action=polls&view=result&poll_id=' + poll_id + '&poll_' + poll_id + '_nonce=' + poll_nonce, cache: false, success: poll_process_success});84 } else {85 if(pollsL10n.show_loading) {86 $('#polls-' + poll_id + '-loading').show();87 }88 $.ajax({type: 'POST', xhrFields: {withCredentials: true}, url: pollsL10n.ajax_url, data: 'action=polls&view=result&poll_id=' + poll_id + '&poll_' + poll_id + '_nonce=' + poll_nonce, cache: false, success: poll_process_success});89 }90 } else {91 alert(pollsL10n.text_wait);92 }93 });94}95// Poll's Voting Booth (User Click "Vote" Link)96function poll_booth(current_poll_id) {97 jQuery(document).ready(function($) {98 if(!is_being_voted) {99 set_is_being_voted(true);100 poll_id = current_poll_id;101 poll_nonce = $('#poll_' + poll_id + '_nonce').val();102 if(pollsL10n.show_fading) {103 $('#polls-' + poll_id).fadeTo('def', 0);104 if(pollsL10n.show_loading) {105 $('#polls-' + poll_id + '-loading').show();106 }107 $.ajax({type: 'POST', xhrFields: {withCredentials: true}, url: pollsL10n.ajax_url, data: 'action=polls&view=booth&poll_id=' + poll_id + '&poll_' + poll_id + '_nonce=' + poll_nonce, cache: false, success: poll_process_success});108 } else {109 if(pollsL10n.show_loading) {110 $('#polls-' + poll_id + '-loading').show();111 }112 $.ajax({type: 'POST', xhrFields: {withCredentials: true}, url: pollsL10n.ajax_url, data: 'action=polls&view=booth&poll_id=' + poll_id + '&poll_' + poll_id + '_nonce=' + poll_nonce, cache: false, success: poll_process_success});113 }114 } else {115 alert(pollsL10n.text_wait);116 }117 });118}119// Poll Process Successfully120function poll_process_success(data) {121 jQuery(document).ready(function($) {122 $('#polls-' + poll_id).replaceWith(data);123 if(pollsL10n.show_loading) {124 $('#polls-' + poll_id + '-loading').hide();125 }126 if(pollsL10n.show_fading) {127 $('#polls-' + poll_id).fadeTo('def', 1);128 set_is_being_voted(false);129 } else {130 set_is_being_voted(false);131 }132 });133}134// Set is_being_voted Status135function set_is_being_voted(voted_status) {136 is_being_voted = voted_status;...

Full Screen

Full Screen

topic_poll.py

Source:topic_poll.py Github

copy

Full Screen

1# -*- coding: utf-8 -*-2from __future__ import unicode_literals3from django.contrib.auth.decorators import login_required4from django.shortcuts import render, redirect, get_object_or_4045from django.views.decorators.http import require_POST6from django.contrib import messages7from django.contrib.auth.views import redirect_to_login8from django.conf import settings9from foro import utils10from foro.models.topic_poll import TopicPoll11from foro.forms.topic_poll import TopicPollChoiceFormSet, TopicPollForm, TopicPollVoteManyForm12from foro.signals.topic_poll import topic_poll_pre_vote, topic_poll_post_vote13@login_required14def poll_update(request, pk):15 poll = get_object_or_404(TopicPoll, pk=pk, topic__user=request.user)16 if request.method == 'POST':17 form = TopicPollForm(data=request.POST, instance=poll)18 formset = TopicPollChoiceFormSet(data=request.POST, instance=poll)19 if form.is_valid() and formset.is_valid():20 poll = form.save()21 choices = formset.save()22 return redirect(request.POST.get('next', poll.get_absolute_url()))23 else:24 form = TopicPollForm(instance=poll)25 formset = TopicPollChoiceFormSet(instance=poll)26 return render(request, 'foro/topic_poll/poll_update.html', {'form': form, 'formset': formset})27@login_required28def poll_close(request, pk):29 poll = get_object_or_404(TopicPoll, pk=pk, topic__user=request.user)30 if request.method == 'POST':31 not_is_closed = not poll.is_closed32 TopicPoll.objects.filter(pk=poll.pk)\33 .update(is_closed=not_is_closed)34 return redirect(request.GET.get('next', poll.get_absolute_url()))35 return render(request, 'foro/topic_poll/poll_close.html', {'poll': poll, })36@require_POST37def poll_vote(request, pk):38 # TODO: check if user has access to this topic/poll39 poll = get_object_or_404(TopicPoll, pk=pk)40 if not request.user.is_authenticated():41 return redirect_to_login(next=poll.get_absolute_url(),42 login_url=settings.LOGIN_URL)43 form = TopicPollVoteManyForm(user=request.user, poll=poll, data=request.POST)44 if form.is_valid():45 topic_poll_pre_vote.send(sender=poll.__class__, poll=poll, user=request.user)46 form.save_m2m()47 topic_poll_post_vote.send(sender=poll.__class__, poll=poll, user=request.user)48 return redirect(request.POST.get('next', poll.get_absolute_url()))49 else:50 messages.error(request, utils.render_form_errors(form))...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1var wpt = require('wpt');2var wptPoll = new wpt('API_KEY');3wptPoll.poll('TEST_ID', function(err, data) {4 if (err) {5 console.log(err);6 } else {7 console.log(data);8 }9});10var wpt = require('wpt');11var wptGetLocations = new wpt('API_KEY');12wptGetLocations.getLocations(function(err, data) {13 if (err) {14 console.log(err);15 } else {16 console.log(data);17 }18});19var wpt = require('wpt');20var wptGetTesters = new wpt('API_KEY');21wptGetTesters.getTesters(function(err, data) {22 if (err) {23 console.log(err);24 } else {25 console.log(data);26 }27});28var wpt = require('wpt');29var wptGetTesters = new wpt('API_KEY');30wptGetTesters.getTesters(function(err, data) {31 if (err) {32 console.log(err);33 } else {34 console.log(data);35 }36});37var wpt = require('wpt');38var wptGetTesters = new wpt('API_KEY');39wptGetTesters.getTesters(function(err, data) {40 if (err) {41 console.log(err);42 } else {43 console.log(data);44 }45});46var wpt = require('wpt');47var wptGetLocations = new wpt('API_KEY');48wptGetLocations.getLocations(function(err, data) {49 if (err) {50 console.log(err);51 } else {52 console.log(data);53 }54});55var wpt = require('wpt');56var wptGetTesters = new wpt('API_KEY');57wptGetTesters.getTesters(function(err

Full Screen

Using AI Code Generation

copy

Full Screen

1var wpt = require('webpagetest');2var fs = require('fs');3var path = require('path');4var test = new wpt('www.webpagetest.org', 'A.9e8c6b0e6a3d6e2a2d8e1d1f6c3d6b9c');5var options = {6};7test.runTest(url, options, function(err, data) {8 if (err) return console.error(err);9 console.log('Test status:', data.statusText);10 if (data.statusCode === 200) {11 var testId = data.data.testId;12 console.log('Test ID:', testId);13 test.getTestResults(testId, function(err, data) {14 if (err) return console.error(err);15 console.log('Test results:', data.data.median.firstView);16 var json = JSON.stringify(data.data.median.firstView);17 fs.writeFile('test.json', json, 'utf8', function() {18 console.log('file saved');19 });20 });21 }22});23var wpt = require('webpagetest');24var fs = require('fs');25var path = require('path');26var test = new wpt('www.webpagetest.org', 'A.9e8c6b0e6a3d6e2a2d8e1d1f6c3d6b9c');27var options = {28};29test.runTest(url, options, function(err, data) {30 if (err) return console.error(err);31 console.log('Test status:', data.statusText);32 if (data.statusCode === 200) {33 var testId = data.data.testId;34 console.log('Test ID:', testId);

Full Screen

Using AI Code Generation

copy

Full Screen

1var wpt = require('webpagetest');2var options = {3};4var test = new wpt(options);5var params = {6};7test.runTest(testURL, params, function(err, data) {8 if (err) {9 console.log('Error: ' + err);10 } else {11 console.log('Test Status: ' + data.statusCode);12 test.getTestResults(data.data.testId, function(err, data) {13 if (err) {14 console.log('Error: ' + err);15 } else {16 console.log('Test Status: ' + data.statusCode);17 console.log('Test Results: ' + JSON.stringify(data.data));18 }19 });20 }21});22var wpt = require('webpagetest');23var options = {24};25var test = new wpt(options);26var params = {27};28test.runTest(testURL, params, function(err, data) {29 if (err) {30 console.log('Error: ' + err);31 } else {32 console.log('Test Status: ' + data.statusCode);33 test.getTestResults(data.data.testId, function(err, data) {34 if (err) {35 console.log('Error: ' + err);36 } else {37 console.log('Test Status: ' + data.statusCode);38 console.log('Test Results: ' +

Full Screen

Using AI Code Generation

copy

Full Screen

1var wpt = require('webpagetest');2var wpt = new WebPageTest('www.webpagetest.org', 'A.8f6b2d6b1e6f7f6c2c5e5a5f7c5a5e5');3 wpt.pollTest(data.data.testId, function(err, data) {4 console.log(data);5 });6});7{ statusCode: 200,8 { testId: '140418_7X_9c3e3c2d2d8e2c7e4e1b1c7e1b1c7e1',

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run wpt automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful