def test_view_can_handle_votes_via_POST(self): # set up a poll with choices poll1 = Poll(question='6 times 7', pub_date=timezone.now()) poll1.save() choice1 = Choice(poll=poll1, choice='42', votes=1) choice1.save() choice2 = Choice(poll=poll1, choice='The Ultimate Answer', votes=3) choice2.save() # set up our POST data - keys and values are strings post_data = {'vote': str(choice2.id)} # make our request to the view poll_url = '/poll/polls/%d/' % (poll1.id,) response = self.client.post(poll_url, data=post_data) # retrieve the updated choice from the database choice_in_db = Choice.objects.get(pk=choice2.id) # check it's votes have gone up by 1 self.assertEquals(choice_in_db.votes, 4) self.assertEquals(choice_in_db.percentage(), 80) # always redirect after a POST - even if, in this case, we go back # to the same page. self.assertRedirects(response, poll_url)
def test_simple_poll_responses(self): p = Poll.create_with_bulk( 'test poll1', Poll.TYPE_TEXT, 'test?', 'test!', Contact.objects.filter(pk__in=[self.contact1.pk]), self.user) p.start() # starting a poll should send out a message self.assertEquals(Message.objects.count(), 1) self.assertEquals(Message.objects.all()[0].text, 'test?') self.assertInteraction(self.connection1, "test poll response", "test!") self.assertEqual(Response.objects.count(), 1) self.assertEqual(Response.objects.all()[0].eav.poll_text_value, 'test poll response') p2 = Poll.create_with_bulk( 'test poll2', Poll.TYPE_NUMERIC, 'test?', '#test!', Contact.objects.filter(pk__in=[self.contact2.pk]), self.user) p2.start() self.assertInteraction(self.connection2, '3.1415', '#test!') self.assertEqual(Response.objects.count(), 2) # There should only be one response for a numeric type poll, # and it should have the value # we just sent in self.assertEqual( Response.objects.filter( poll__type=Poll.TYPE_NUMERIC)[0].eav.poll_number_value, 3.1415)
def get_mocked_step_with_poll_question(self, question, script_slug='registration_script'): mocked_poll = Poll() mocked_poll.question = question poll_step = ScriptStep() poll_step.poll = mocked_poll poll_step.script = Script(slug=script_slug) return poll_step
def pollSave(request): # if request.method == 'POST': # if not request.POST.get('subject', ''): # errors.append('Enter a subject.') # if not request.POST.get('message', ''): # errors.append('Enter a message.') # if request.POST.get('email') and '@' not in request.POST['email']: # errors.append('Enter a valid e-mail address.') # if not errors: # send_mail( # request.POST['subject'], # request.POST['message'], # request.POST.get('email', '*****@*****.**'), # ['*****@*****.**'], # ) # return HttpResponseRedirect('/contact/thanks/') title = request.POST.get('title', '') remark = request.POST.get('remark', '') poll = Poll(title=title, remark=remark, createTime=datetime.now()) poll.save() itemIds = request.POST.get('item_ids', '') ids = itemIds.split(',') for id in ids: pollItem = PollItem(title=request.POST.get('item_title' + id, ''), poll=poll) pollItem.save() return render_to_response('pollSave.html')
def test_simple_poll_responses(self): p = Poll.create_with_bulk( 'test poll1', Poll.TYPE_TEXT, 'test?', 'test!', Contact.objects.filter(pk__in=[self.contact1.pk]), self.user) p.start() # starting a poll should send out a message self.assertEquals(Message.objects.count(), 1) self.assertEquals(Message.objects.all()[0].text, 'test?') self.assertInteraction(self.connection1, "test poll response", "test!") self.assertEqual(Response.objects.count(), 1) self.assertEqual(Response.objects.all()[0].eav.poll_text_value, 'test poll response') p2 = Poll.create_with_bulk( 'test poll2', Poll.TYPE_NUMERIC, 'test?', '#test!', Contact.objects.filter(pk__in=[self.contact2.pk]), self.user) p2.start() self.assertInteraction(self.connection2, '3.1415', '#test!') self.assertEqual(Response.objects.count(), 2) # There should only be one response for a numeric type poll, # and it should have the value # we just sent in self.assertEqual(Response.objects.filter(poll__type=Poll.TYPE_NUMERIC)[0].eav.poll_number_value, 3.1415)
def seed_polls(num_entries=10, choice_min=2, choice_max=5, overwrite = False): """ Seeds num_entries poll with random users as owners Each poll will be seeded with # choices from choice_min to choice_max """ if overwrite: print("over writing poll") Poll.objects.all().delete() users = list(User.objects.all()) count = 0 for _ in range(num_entries): p = Poll( owner = random.choice(users), text=fake.paragraph(), pub_date=datetime.datetime.now() ) p.save() num_choices = random.randrange(choice_min,choice_max+1) for _ in range(num_choices): c = Choice( poll=p, choice_text=fake.sentence() ) c.save() count += 1 perecent_complete = count / num_entries * 100 print( "Addind {} new poll: {:.2f}%".format( num_entries, perecent_complete ), end='\r', flush=True ) print()
def post(self, request): title = request.data.get('title') text = request.data.get('text') link = request.data.get('link', 'No link') user = request.user close_date = request.data.get('closeDate', '2424-2-2') if not close_date: close_date = '2424-2-2' participants = request.data.get('participants', []) selects = request.data.get('selects') meeting = Meeting(title=title, text=text, owner=user) meeting.save() poll = Poll(title=title, text=text, meeting=meeting) if close_date: poll.date_close = datetime.datetime.strptime( close_date, '%Y-%m-%d') poll.save() meetingParticipant = MeetingParticipant(meeting=meeting, participant=user) meetingParticipant.save() link += str(poll.id) self.create_participants(meeting, participants, user) self.createOptions(poll, selects) check_poll_close(poll) poll_json = serializers.serialize('json', [poll]) send_email_create_poll(user, title, link, participants) try: return HttpResponse(poll_json, content_type='application/json') except Exception as e: print(e) return HttpResponse404Error("This poll doesn\'t exist.")
def test_response_type_handling(self): #test allow all poll1 = Poll.create_with_bulk( 'test response type handling', Poll.TYPE_TEXT, 'ureport is bored.what would u like it 2 do?', 'yikes :(', Contact.objects.all(), self.user) poll1.start() self.assertInteraction(self.connection1, 'get me a kindle :)', 'yikes :(') self.assertInteraction(self.connection1, 'get me a kindle :)', 'yikes :(') self.assertInteraction(self.connection1, 'get me an ipad :)', 'yikes :(') self.assertInteraction(self.connection1, 'Arrest Bush :)', 'yikes :(') self.assertEqual(Response.objects.filter(contact=self.contact1).count(), 4) poll1.end() #test ignore dups poll2 = Poll.create_with_bulk( 'test response type handling', Poll.TYPE_TEXT, 'ureport is bored.what would u like it 2 do?', 'yikes :(', Contact.objects.all(), self.user) poll2.response_type=Poll.RESPONSE_TYPE_NO_DUPS poll2.save() poll2.start() self.assertInteraction(self.connection1, 'get me a kindle :)', 'yikes :(') self.fake_incoming(self.connection1, 'get me a kindle :)') self.assertInteraction(self.connection1, 'get me an ipad :)', 'yikes :(') self.assertInteraction(self.connection1, 'Arrest Bush :)', 'yikes :(') self.assertEqual(Response.objects.filter(contact=self.contact1,poll=poll2).count(), 3) poll2.end() #test allow one poll3 = Poll.create_with_bulk( 'test response type handling', Poll.TYPE_TEXT, 'Are u cool?', 'yikes :(', Contact.objects.all(), self.user) poll3.response_type=Poll.RESPONSE_TYPE_ONE poll3.add_yesno_categories() poll3.save() poll3.start() self.fake_incoming(self.connection1, 'what?') self.assertEqual(Response.objects.filter(contact=self.contact1,poll=poll3).count(), 1) self.assertInteraction(self.connection1, 'yes', 'yikes :(') self.assertEqual(Response.objects.filter(contact=self.contact1,poll=poll3).count(), 1) self.fake_incoming(self.connection1, 'get me a kindle :)') self.fake_incoming(self.connection1, 'get me an ipad :)') self.fake_incoming(self.connection1, 'Arrest Bush :)') self.assertEqual(Response.objects.filter(contact=self.contact1,poll=poll3).count(), 1) self.assertEqual(Response.objects.filter(contact=self.contact1,poll=poll3)[0].message.text, 'yes')
def if_it_exists_delete_poll_called(poll_name): try: poll = Poll.objects.get(name=poll_name) Poll.delete(poll) except Poll.DoesNotExist: pass if_exists_delete_group() if_exists_delete_user()
def test_index(self, app, client): with app.app_context(): now = datetime.now() p = Poll(id=None, name="Mon premier sondage", date=now) p.save() response = client.get("/") assert response.status_code == 200 assert b"Aucuns sondages actifs" not in response.data assert b"Mon premier sondage" in response.data
def test_get_poll_by_id(self, app): with app.app_context(): now = datetime.now() p = Poll(id=None, name="Nom", date=now) p.save() new_poll = Poll.get_poll_by_id(1) assert new_poll.id == 1 assert new_poll.name == "Nom" assert new_poll.date == str(now)
def gen_poll(self): from poll.models import Poll poll = Poll() candidates = list(self.profile.all()) for elected in self.elected.all(): try: candidates.remove(elected) except ValueError: pass # Option A: candidates <= available posts -> yes/no/abstention if len(candidates) <= self.posts - self.elected.count(): poll.optiondecision = True else: poll.optiondecision = False # Option B: candidates == 1 -> yes/no/abstention #if self.profile.count() == 1: # poll.optiondecision = True #else: # poll.optiondecision = False poll.assignment = self poll.description = self.polldescription poll.save() for candidate in candidates: poll.add_option(candidate) return poll
def gen_poll(self, user=None): """ Generates a poll object for the application """ from poll.models import Poll poll = Poll(optiondecision=True, \ application=self) poll.save() poll.add_option(self) self.writelog(_("Poll created"), user) return poll
def test_save_inserts_row(self, app): with app.app_context(): now = datetime.now() p = Poll(id=None, name="Nom", date=now) p.save() new_poll = get_db().execute( "SELECT id, name, date FROM polls WHERE id = ?", [1]).fetchone() assert new_poll[0] == 1 assert new_poll[1] == "Nom" assert new_poll[2] == str(now)
def test_should_choose_batch_status_based_on_feature_flag(self): p = Poll() self.assertEqual(p.get_start_poll_batch_status(), "Q") settings.FEATURE_PREPARE_SEND_POLL = True self.assertEqual(p.get_start_poll_batch_status(), "P") settings.FEATURE_PREPARE_SEND_POLL = False self.assertEqual(p.get_start_poll_batch_status(), "Q")
def setUp(self): self.queue = Queue(title='TestQueue', auth=False) self.queue.save() self.poll = Poll(title='TestPoll', queue=self.queue, polltype=0, startdate=datetime.now()) self.poll.save() self.item = self.poll.item_set.create(userbox=False, value='One', index=0) self.client = Client()
def choice_create(poll_id): poll = Poll.get_or_none(Poll.id == poll_id) if not poll: return abort(404) choice = PollServices.create_new_choice_for_poll_from_post_data(poll, request.form) return redirect(url_for('poll', poll_id=poll.id))
def test_that_data_from_poll_should_have_all_the_neccessary_fields(self): question = "is this really a poll ? or a pool ? or a loop?" name = "this is a poll" an_hour_ago = datetime.datetime.now() - datetime.timedelta(hours=1) default_response = "thanks" poll = Poll(name=name, question=question, id=12, type="t", start_date=an_hour_ago, default_response=default_response, response_type="a") expected_poll_data = { "id": "12", "question": question, "name": name, "language": None, "question_voice": None, "start_date": an_hour_ago.strftime(self.view.get_datetime_format()), "end_date": None, "is_registration": False, "type": "t", "is_registration_end": False, "default_response": default_response, "default_response_voice": None, "response_type": "allow_all" } self.assertDictEqual(expected_poll_data, self.view.get_data_from_poll(poll))
def create_new_poll_from_post_data(cls, post_data, date): poll = Poll.create( name=post_data['name'], date=date ) return poll
def test_poll_translation(self): t1=Translation.objects.create(field="How did you hear about Ureport?", language="ach", value="I winyo pi U-report ki kwene?") t2=Translation.objects.create(field="Ureport gives you a chance to speak out on issues in your community & share opinions with youth around Uganda Best responses & results shared through the media", language="ach", value="Ureport mini kare me lok ikum jami matime i kama in ibedo iyee. Lagam mabejo kibiketo ne I karatac me ngec.") self.contact1.language = "en" self.contact1.save() self.contact2.language = "ach" self.contact2.save() t_poll = Poll.create_with_bulk( 'test translation', Poll.TYPE_TEXT, "How did you hear about Ureport?" , "Ureport gives you a chance to speak out on issues in your community & share opinions with youth around Uganda Best responses & results shared through the media", Contact.objects.all(), self.user) t_poll.add_yesno_categories() t_poll.save() t_poll.start() self.assertEquals(Message.objects.count(), 2) self.assertInteraction(self.connection1, 'yes', 'Ureport gives you a chance to speak out on issues in your community & share opinions with youth around Uganda Best responses & results shared through the media') self.assertInteraction(self.connection2, 'no', 'Ureport mini kare me lok ikum jami matime i kama in ibedo iyee. Lagam mabejo kibiketo ne I karatac me ngec.')
def test_numeric_polls(self): p = Poll.create_with_bulk('test poll numeric', Poll.TYPE_NUMERIC, 'how old are you?', ':) go yo age!', Contact.objects.all(), self.user) p.start() self.assertInteraction(self.connection2, '19years', ':) go yo age!') self.assertEqual(Response.objects.filter(poll=p).count(), 1)
def setUp(self): self.user, created = User.objects.get_or_create(username='******') self.backend = Backend.objects.create(name='test') self.user2 = User.objects.create_user('foo', '*****@*****.**', 'barbar') # self.location = Location.objects.create(name='Kampala') self.contact1 = Contact.objects.create(name='John Jonny') self.connection1 = Connection.objects.create(backend=self.backend, identity='8675309', contact=self.contact1) self.u_contact = UreportContact.objects.create(name='John Jonny', autoreg_join_date=self.connection1.created_on, quit_date=datetime.datetime.now(), age=23, responses=2, questions=2, incoming=1, is_caregiver=True, connection_pk=self.connection1.pk, reporting_location_id=-1, user_id=self.user.pk) self.contact2 = Contact.objects.create(name='gowl') self.connection2 = Connection.objects.create(backend=self.backend, identity='5555555', contact=self.contact2) self.test_msg = Message.objects.create(text="hello", direction="I", connection=self.connection1) self.poll = Poll.create_with_bulk( 'test poll1', Poll.TYPE_TEXT, 'test?', 'test!', Contact.objects.filter(pk__in=[self.contact1.pk]), self.user) self.poll.start_date = datetime.datetime.now() self.cat1 = self.poll.categories.create(name="cat1") self.cat2 = self.poll.categories.create(name="cat2") self.cat3 = self.poll.categories.create(name="cat3") self.resp = Response.objects.create(poll=self.poll, message=self.test_msg, contact=self.contact1, date=self.test_msg.date) self.flag = Flag.objects.create(name="jedi", words="luke,sky,walker,jedi", rule=2)
def setUp(self): self.user,created = User.objects.get_or_create(username='******') self.backend = Backend.objects.create(name='test') self.user2=User.objects.create_user('foo', '*****@*****.**', 'barbar') self.contact1 = Contact.objects.create(name='John Jonny') self.connection1 = Connection.objects.create(backend=self.backend, identity='8675309', contact=self.contact1) self.contact2 = Contact.objects.create(name='gowl') self.connection2 = Connection.objects.create(backend=self.backend, identity='5555555', contact=self.contact2) self.test_msg=Message.objects.create(text="hello",direction="I",connection=self.connection1) self.poll = Poll.create_with_bulk( 'test poll1', Poll.TYPE_TEXT, 'test?', 'test!', Contact.objects.filter(pk__in=[self.contact1.pk]), self.user) self.poll.start_date=datetime.datetime.now() self.cat1=self.poll.categories.create(name="cat1") self.cat2=self.poll.categories.create(name="cat2") self.cat3=self.poll.categories.create(name="cat3") self.resp = Response.objects.create(poll=self.poll, message=self.test_msg, contact=self.contact1, date=self.test_msg.date) self.flag=Flag.objects.create(name="jedi",words="luke,sky,walker,jedi",rule=2)
def perform(self, request, results): if not len(results): return (_('No contacts selected'), 'error') name = self.cleaned_data['poll_name'] poll_type = self.cleaned_data['poll_type'] poll_type = self.cleaned_data['poll_type'] if poll_type == NewPollForm.TYPE_YES_NO: poll_type = Poll.TYPE_TEXT question = self.cleaned_data.get('question').replace('%', u'\u0025') default_response = self.cleaned_data['default_response'] response_type = self.cleaned_data['response_type'] contacts = Contact.objects.filter(pk__in=results) poll = Poll.create_with_bulk(name=name, type=poll_type, question=question, default_response=default_response, contacts=contacts, user=request.user) poll.response_type = response_type if self.cleaned_data['poll_type'] == NewPollForm.TYPE_YES_NO: poll.add_yesno_categories() poll.save() if settings.SITE_ID: poll.sites.add(Site.objects.get_current()) return (_('%(results)d participants added to %(poll)s poll') % { "results": len(results), "poll": poll.name }, 'success')
def perform(self, request, results): if not len(results): return ('No contacts selected', 'error') name = self.cleaned_data['poll_name'] poll_type = self.cleaned_data['poll_type'] poll_type = self.cleaned_data['poll_type'] if poll_type == NewPollForm.TYPE_YES_NO: poll_type = Poll.TYPE_TEXT question = self.cleaned_data.get('question').replace('%', u'\u0025') default_response = self.cleaned_data['default_response'] response_type = self.cleaned_data['response_type'] contacts=Contact.objects.filter(pk__in=results) poll = Poll.create_with_bulk( name=name, type=poll_type, question=question, default_response=default_response, contacts=contacts, user=request.user ) poll.response_type = response_type if self.cleaned_data['poll_type'] == NewPollForm.TYPE_YES_NO: poll.add_yesno_categories() poll.save() if settings.SITE_ID: poll.sites.add(Site.objects.get_current()) return ('%d participants added to %s poll' % (len(results), poll.name), 'success')
def poll(poll_id): poll = Poll.get_poll_by_id(poll_id) if not poll: return abort(404) choices = Choice.get_choices_for_poll(poll) return views.view_poll(poll, choices)
def test_nothing_happens_if_you_start_a_started_poll(self): p = Poll.create_with_bulk('test poll1', Poll.TYPE_TEXT, 'are you there?', 'glad to know where you are!', Contact.objects.all(), self.user) p.start() p.start() #no exceptions should be thrown...
def poll(poll_id): poll = Poll.get_poll_by_id(poll_id) if not poll: return abort(404) choices = Choice.get_choices_for_poll(poll) #csrf_token = generate_csrf() return views.view_poll(poll, choices, csrf_token=None)
def test_that_if_the_response_is_not_accepted_the_script_steps_are_not_checked( self): self.view.get_poll = Mock(return_value=Poll()) self.view.get_incoming_response = Mock() self.view.process_poll_response = Mock(return_value=(False, "")) self.view.create_json_response = Mock() fake_process_registration = Mock() self.view.process_registration_steps = fake_process_registration self.view.post(self, None, **{'poll_id': "12"}) assert not fake_process_registration.called
def test_recategorization(self): p = Poll.create_with_bulk('test poll1', Poll.TYPE_TEXT, 'whats your favorite food?', 'thanks!', Contact.objects.all(), self.user) p.start() self.assertInteraction(self.connection1, 'apples', 'thanks!') r1 = Response.objects.all()[0] self.assertInteraction(self.connection2, 'oranges', 'thanks!') r2 = Response.objects.order_by('-pk')[0] self.assertInteraction(self.connection1, 'pizza', 'thanks!', TestScript.SHOULD_NOT_HAVE_RESPONSE) r3 = Response.objects.order_by('-pk')[0] self.assertInteraction(self.connection2, 'pringles', 'thanks!', TestScript.SHOULD_NOT_HAVE_RESPONSE) r4 = Response.objects.order_by('-pk')[0] self.assertInteraction(self.connection1, 'steak', 'thanks!', TestScript.SHOULD_NOT_HAVE_RESPONSE) r5 = Response.objects.order_by('-pk')[0] self.assertInteraction(self.connection2, 'pork chop', 'thanks!', TestScript.SHOULD_NOT_HAVE_RESPONSE) r6 = Response.objects.order_by('-pk')[0] self.assertInteraction(self.connection2, 'moldy bread', 'thanks!', TestScript.SHOULD_NOT_HAVE_RESPONSE) r7 = Response.objects.order_by('-pk')[0] for r in Response.objects.all(): self.assertEqual(r.categories.count(), 0, "number of response categories should be 0") for name, keywords in [('healthy', ['apples', 'oranges']), ('junk', ['pizza', 'pringles']), ('meaty', ['steak', 'pork'])]: category = Category.objects.create(name=name, poll=p) for keyword in keywords: r = Rule.objects.create(category=category, rule_type=Rule.TYPE_CONTAINS, rule_string=keyword) r.update_regex() r.save() p.reprocess_responses() for r, c in [(r1, 'healthy'), (r2, 'healthy'), (r3, 'junk'), (r4, 'junk'), (r5, 'meaty'), (r6, 'meaty')]: self.assertEqual(r.categories.count(), 1) self.assertEqual(r.categories.all()[0].category.name, c) self.assertEquals(r7.categories.count(), 0, "number of r7 response categories should be 0")
def test_null_responses(self): no_response_poll = Poll.create_with_bulk( 'test response type handling', Poll.TYPE_TEXT, 'Can we defeat Sauron?', None, Contact.objects.all(), self.user) no_response_poll.start() self.fake_incoming(self.connection1, 'my precious :)') self.assertEqual( Message.objects.filter(connection=self.connection1, direction="O").count(), 1)
def test_response_type_handling(self): # test allow all poll1 = Poll.create_with_bulk( "test response type handling", Poll.TYPE_TEXT, "ureport is bored.what would u like it 2 do?", "yikes :(", Contact.objects.all(), self.user, ) poll1.start() self.fake_incoming(self.connection1, "get me a kindle :)") self.fake_incoming(self.connection1, "get me a kindle :)") self.fake_incoming(self.connection1, "get me a kindle :)") self.fake_incoming(self.connection1, "get me a kindle :)") self.fake_incoming(self.connection1, "get me a kindle :)") self.fake_incoming(self.connection1, "get me a kindle :)") self.fake_incoming(self.connection1, "get me a kindle :)") self.assertEqual(Response.objects.filter(contact=self.contact1).count(), 7) self.assertEqual(Message.objects.filter(connection=self.connection1, direction="O").count(), 2) poll1.end() # allow one poll3 = Poll.create_with_bulk( "test response type handling", Poll.TYPE_TEXT, "Are u cool?", "yikes :(", Contact.objects.all(), self.user ) poll3.response_type = Poll.RESPONSE_TYPE_ONE poll3.add_yesno_categories() poll3.save() poll3.start() self.assertInteraction(self.connection2, "yes", "yikes :(") self.assertEqual(Response.objects.filter(contact=self.contact2, poll=poll3).count(), 1) self.fake_incoming(self.connection2, "get me a kindle :)") self.fake_incoming(self.connection2, "get me an ipad :)") self.fake_incoming(self.connection2, "Arrest Bush :)") self.assertEqual(Response.objects.filter(contact=self.contact2, poll=poll3).count(), 1) self.assertEqual(Response.objects.filter(contact=self.contact2, poll=poll3)[0].message.text, "yes")
def poll_creation_form(request): if request.method == "POST": poll_form = PollForm(request.POST) content = {"form": poll_form} if poll_form.is_valid(): poll = Poll(poll_name=poll_form.cleaned_data["poll_name"], start_date=poll_form.cleaned_data["start_date"], manager=request.user.email, end_date=poll_form.cleaned_data["end_date"]) poll.save() poll.member.add(request.user) return redirect("pollhome.page") else: return render(request, "poll/poll_form.html", content) else: poll_form = PollForm() content = {"form": poll_form} return render(request, "poll/poll_form.html", content)
def test_numeric_polls(self): p = Poll.create_with_bulk( "test poll numeric", Poll.TYPE_NUMERIC, "how old are you?", ":) go yo age!", Contact.objects.all(), self.user, ) p.start() self.assertInteraction(self.connection2, "19years", ":) go yo age!") self.assertEqual(Response.objects.filter(poll=p).count(), 1)
def test_batch_status_is_Q_when_start_poll(self): p = Poll.create_with_bulk('test poll1', Poll.TYPE_TEXT, 'are you there?', 'glad to know where you are!', Contact.objects.all(), self.user) p.start() batchName = p.get_outgoing_message_batch_name() batches = MessageBatch.objects.filter(name=batchName).all() for batch in batches: self.assertEqual(batch.status, "Q")
def test_nothing_happens_if_you_start_a_started_poll(self): p = Poll.create_with_bulk( "test poll1", Poll.TYPE_TEXT, "are you there?", "glad to know where you are!", Contact.objects.all(), self.user, ) p.start() p.start() # no exceptions should be thrown...
def test_form_renders_poll_choices_as_radio_inputs(self): # set up a poll with a couple of choices poll1 = Poll(question="6 times 7", pub_date=timezone.now()) poll1.save() choice1 = Choice(poll=poll1, choice="42", votes=0) choice1.save() choice2 = Choice(poll=poll1, choice="The Ultimate Answer", votes=0) choice2.save() # set up another poll to make sure we only see the right choices poll2 = Poll(question="time", pub_date=timezone.now()) poll2.save() choice3 = Choice(poll=poll2, choice="PM", votes=0) choice3.save() # build a voting form for poll1 form = PollVoteForm(poll=poll1) # check it has a single field called 'vote', which has right choices: self.assertEquals(form.fields.keys(), ["vote"]) # choices are tuples in the format (choice_number, choice_text): self.assertEquals(form.fields["vote"].choices, [(choice1.id, choice1.choice), (choice2.id, choice2.choice)]) # check it uses radio inputs to render self.assertIn('input type="radio"', form.as_p())
def test_get_polls(self, app): with app.app_context(): now = datetime.now() p = Poll(id=None, name="Nom", date=now) p.save() p = Poll(id=None, name="Nom #2", date=now) p.save() new_poll = Poll.get_polls() assert new_poll[0].id == 1 assert new_poll[0].name == "Nom" assert new_poll[0].date == str(now) assert new_poll[1].id == 2 assert new_poll[1].name == "Nom #2" assert new_poll[1].date == str(now)
def new_poll(req): if req.method == 'POST': form = NewPollForm(req.POST) form.updateTypes() if form.is_valid(): # create our XForm question = form.cleaned_data['question'] default_response = form.cleaned_data['default_response'] contacts = form.cleaned_data['contacts'] if hasattr(Contact, 'groups'): groups = form.cleaned_data['groups'] contacts = Contact.objects.filter(Q(pk__in=contacts) | Q(groups__in=groups)).distinct() name = form.cleaned_data['name'] p_type = form.cleaned_data['poll_type'] response_type = form.cleaned_data['response_type'] if not form.cleaned_data['default_response_luo'] == '' and not form.cleaned_data['default_response'] == '': Translation.objects.create(language='ach', field=form.cleaned_data['default_response'], value=form.cleaned_data['default_response_luo']) if not form.cleaned_data['question_luo'] == '': Translation.objects.create(language='ach', field=form.cleaned_data['question'], value=form.cleaned_data['question_luo']) poll_type = Poll.TYPE_TEXT if p_type == NewPollForm.TYPE_YES_NO else p_type poll = Poll.create_with_bulk(\ name, poll_type, question, default_response, contacts, req.user) poll.contacts = contacts # for some reason this wasn't being saved in the create_with_bulk call poll.response_type = response_type poll.save() if p_type == NewPollForm.TYPE_YES_NO: poll.add_yesno_categories() if settings.SITE_ID: poll.sites.add(Site.objects.get_current()) if form.cleaned_data['start_immediately']: poll.start() return redirect(reverse('poll.views.view_poll', args=[poll.pk])) else: form = NewPollForm() form.updateTypes() return render_to_response( "polls/poll_create.html", {'form': form}, context_instance=RequestContext(req))
def test_page_shows_choices_using_form(self): # set up a poll with choices poll1 = Poll(question='time', pub_date=timezone.now()) poll1.save() choice1 = Choice(poll=poll1, choice="PM", votes=0) choice1.save() choice2 = Choice(poll=poll1, choice="Gardener's", votes=0) choice2.save() response = self.client.get('/poll/polls/%d/' % (poll1.id, )) # check we've passed in a form of the right type self.assertTrue(isinstance(response.context['form'], PollVoteForm)) self.assertTrue(response.context['poll'], poll1) self.assertTemplateUsed(response, 'poll.html') # and check the check the form is being used in the template, # by checking for the choice text self.assertIn(choice1.choice, response.content.replace(''', "'")) self.assertIn(choice2.choice, response.content.replace(''', "'")) self.assertIn('csrf', response.content) self.assertIn('0 %', response.content)
def poll_vote(poll_id): poll = Poll.get_poll_by_id(poll_id) if not poll: return abort(404) choice_id = request.form['choice_id'] choice = Choice.get_by_id_for_poll(poll, choice_id) if not choice: return abort(404) choice.cast_vote() return redirect(url_for('poll', poll_id=poll.id))
def test_null_responses(self): no_response_poll = Poll.create_with_bulk('test response type handling', Poll.TYPE_TEXT, 'Can we defeat Sauron?', None, Contact.objects.all(), self.user) no_response_poll.start() self.fake_incoming(self.connection1, 'my precious :)') self.assertEqual( Message.objects.filter(connection=self.connection1, direction="O").count(), 1)
def test_yes_no_polls(self): p = Poll.create_with_bulk( 'test poll1', Poll.TYPE_TEXT, 'are you there?', 'glad to know where you are!', Contact.objects.all(), self.user) p.add_yesno_categories() p.start() self.assertInteraction(self.connection2, 'yes', 'glad to know where you are!') self.assertEqual(Response.objects.filter(poll=p).count(), 1) self.assertEqual(Response.objects.get(poll=p).categories.all()[0].category.name, 'yes')
def test_yes_no_polls(self): p = Poll.create_with_bulk('test poll1', Poll.TYPE_TEXT, 'are you there?', 'glad to know where you are!', Contact.objects.all(), self.user) p.add_yesno_categories() p.start() self.assertInteraction(self.connection2, 'yes', 'glad to know where you are!') self.assertEqual(Response.objects.filter(poll=p).count(), 1) self.assertEqual( Response.objects.get(poll=p).categories.all()[0].category.name, 'yes')
def perform(self, request, results): #TODO: Deal with languages languages = ["fr"] question_fr = self.cleaned_data.get('question_fr', "") question_fr = question_fr.replace('%', u'\u0025') if not self.cleaned_data['question_en'] == '': languages.append('en') (translation, created) = \ Translation.objects.get_or_create(language='en', field=self.cleaned_data['question_fr'], value=self.cleaned_data['question_en']) if not self.cleaned_data['question_ki'] == '': languages.append('ki') (translation, created) = \ Translation.objects.get_or_create(language='ki', field=self.cleaned_data['question_fr'], value=self.cleaned_data['question_ki']) if not len(results): return ('No contacts selected', 'error') name = self.cleaned_data['poll_name'] poll_type = self.cleaned_data['poll_type'] poll_type = self.cleaned_data['poll_type'] if poll_type == NewPollForm.TYPE_YES_NO: poll_type = Poll.TYPE_TEXT # question = self.cleaned_data.get('question').replace('%', u'\u0025') default_response = self.cleaned_data['default_response'] response_type = self.cleaned_data['response_type'] contacts = Contact.objects.filter(pk__in=results) poll = Poll.create_with_bulk( name=name, type=poll_type, question=question_fr, default_response=default_response, contacts=contacts, user=request.user ) poll.response_type = response_type if self.cleaned_data['poll_type'] == NewPollForm.TYPE_YES_NO: poll.add_yesno_categories() poll.save() if settings.SITE_ID: poll.sites.add(Site.objects.get_current()) return ('%d participants added to %s poll' % (len(results), poll.name), 'success')
def test_yes_no_polls(self): p = Poll.create_with_bulk( "test poll1", Poll.TYPE_TEXT, "are you there?", "glad to know where you are!", Contact.objects.all(), self.user, ) p.add_yesno_categories() p.start() self.assertInteraction(self.connection2, "yes", "glad to know where you are!") self.assertEqual(Response.objects.filter(poll=p).count(), 1) self.assertEqual(Response.objects.get(poll=p).categories.all()[0].category.name, "yes")
class PollTest(TestCase): def setUp(self): self.queue = Queue(title='TestQueue', auth=False) self.queue.save() self.poll = Poll(title='TestPoll', queue=self.queue, polltype=0, startdate=datetime.now()) self.poll.save() self.item = self.poll.item_set.create(userbox=False, value='One', index=0) self.client = Client() def test_voting(self): request = self.client.post( reverse('poll_ajax_vote', args=(self.poll.pk,)), {'chosen_items': '{"%s": "radio"}'\ % (self.item.id,)}, HTTP_X_REQUESTED_WITH='XMLHttpRequest') self.assertEqual(request.status_code, 200) self.assertEqual(Vote.objects.count(), 1)
def new_poll(req): if req.method == "POST": form = NewPollForm(req.POST) form.updateTypes() if form.is_valid(): # create our XForm question = form.cleaned_data["question"] default_response = form.cleaned_data["default_response"] contacts = form.cleaned_data["contacts"] if hasattr(Contact, "groups"): groups = form.cleaned_data["groups"] contacts = Contact.objects.filter(Q(pk__in=contacts) | Q(groups__in=groups)).distinct() name = form.cleaned_data["name"] p_type = form.cleaned_data["poll_type"] response_type = form.cleaned_data["response_type"] if not form.cleaned_data["default_response_luo"] == "" and not form.cleaned_data["default_response"] == "": Translation.objects.create( language="ach", field=form.cleaned_data["default_response"], value=form.cleaned_data["default_response_luo"], ) if not form.cleaned_data["question_luo"] == "": Translation.objects.create( language="ach", field=form.cleaned_data["question"], value=form.cleaned_data["question_luo"] ) poll_type = Poll.TYPE_TEXT if p_type == NewPollForm.TYPE_YES_NO else p_type poll = Poll.create_with_bulk(name, poll_type, question, default_response, contacts, req.user) poll.contacts = contacts # for some reason this wasn't being saved in the create_with_bulk call poll.response_type = response_type poll.save() if p_type == NewPollForm.TYPE_YES_NO: poll.add_yesno_categories() if settings.SITE_ID: poll.sites.add(Site.objects.get_current()) if form.cleaned_data["start_immediately"]: poll.start() return redirect(reverse("poll.views.view_poll", args=[poll.pk])) else: form = NewPollForm() form.updateTypes() return render_to_response("polls/poll_create.html", {"form": form}, context_instance=RequestContext(req))
def test_batch_status_is_Q_when_start_poll(self): p = Poll.create_with_bulk( "test poll1", Poll.TYPE_TEXT, "are you there?", "glad to know where you are!", Contact.objects.all(), self.user, ) p.start() batchName = p.get_outgoing_message_batch_name() batches = MessageBatch.objects.filter(name=batchName).all() for batch in batches: self.assertEqual(batch.status, "Q")
def test_recategorization(self): p = Poll.create_with_bulk( "test poll1", Poll.TYPE_TEXT, "whats your favorite food?", "thanks!", Contact.objects.all(), self.user ) p.start() self.assertInteraction(self.connection1, "apples", "thanks!") r1 = Response.objects.all()[0] self.assertInteraction(self.connection2, "oranges", "thanks!") r2 = Response.objects.order_by("-pk")[0] self.assertInteraction(self.connection1, "pizza", "thanks!", TestScript.SHOULD_NOT_HAVE_RESPONSE) r3 = Response.objects.order_by("-pk")[0] self.assertInteraction(self.connection2, "pringles", "thanks!", TestScript.SHOULD_NOT_HAVE_RESPONSE) r4 = Response.objects.order_by("-pk")[0] self.assertInteraction(self.connection1, "steak", "thanks!", TestScript.SHOULD_NOT_HAVE_RESPONSE) r5 = Response.objects.order_by("-pk")[0] self.assertInteraction(self.connection2, "pork chop", "thanks!", TestScript.SHOULD_NOT_HAVE_RESPONSE) r6 = Response.objects.order_by("-pk")[0] self.assertInteraction(self.connection2, "moldy bread", "thanks!", TestScript.SHOULD_NOT_HAVE_RESPONSE) r7 = Response.objects.order_by("-pk")[0] for r in Response.objects.all(): self.assertEqual(r.categories.count(), 0, "number of response categories should be 0") for name, keywords in [ ("healthy", ["apples", "oranges"]), ("junk", ["pizza", "pringles"]), ("meaty", ["steak", "pork"]), ]: category = Category.objects.create(name=name, poll=p) for keyword in keywords: r = Rule.objects.create(category=category, rule_type=Rule.TYPE_CONTAINS, rule_string=keyword) r.update_regex() r.save() p.reprocess_responses() for r, c in [(r1, "healthy"), (r2, "healthy"), (r3, "junk"), (r4, "junk"), (r5, "meaty"), (r6, "meaty")]: self.assertEqual(r.categories.count(), 1) self.assertEqual(r.categories.all()[0].category.name, c) self.assertEquals(r7.categories.count(), 0, "number of r7 response categories should be 0")
def test_recategorization(self): p = Poll.create_with_bulk( 'test poll1', Poll.TYPE_TEXT, 'whats your favorite food?', 'thanks!', Contact.objects.all(), self.user) p.start() self.assertInteraction(self.connection1, 'apples', 'thanks!') r1 = Response.objects.all()[0] self.assertInteraction(self.connection2, 'oranges', 'thanks!') r2 = Response.objects.order_by('-pk')[0] self.assertInteraction(self.connection1, 'pizza', 'thanks!') r3 = Response.objects.order_by('-pk')[0] self.assertInteraction(self.connection2, 'pringles', 'thanks!') r4 = Response.objects.order_by('-pk')[0] self.assertInteraction(self.connection1, 'steak', 'thanks!') r5 = Response.objects.order_by('-pk')[0] self.assertInteraction(self.connection2, 'pork chop', 'thanks!') r6 = Response.objects.order_by('-pk')[0] self.assertInteraction(self.connection2, 'moldy bread', 'thanks!') r7 = Response.objects.order_by('-pk')[0] for r in Response.objects.all(): self.assertEqual(r.categories.count(), 0) for name, keywords in [('healthy', ['apples', 'oranges']), ('junk', ['pizza', 'pringles']), ('meaty', ['steak', 'pork'])]: category = Category.objects.create(name=name, poll=p) for keyword in keywords: r = Rule.objects.create(category=category, rule_type=Rule.TYPE_CONTAINS, rule_string=keyword) r.update_regex() r.save() p.reprocess_responses() for r, c in [(r1, 'healthy'), (r2, 'healthy'), (r3, 'junk'), (r4, 'junk'), (r5, 'meaty'), (r6, 'meaty')]: self.assertEqual(r.categories.count(), 1) self.assertEqual(r.categories.all()[0].category.name, c) self.assertEquals(r7.categories.count(), 0)