Best Python code snippet using yandex-tank
tests.py
Source:tests.py
...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")...
tests_topic_poll.py
Source:tests_topic_poll.py
...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")...
views.py
Source:views.py
...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...
index.js
Source:index.js
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 }...
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.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!