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 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 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 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 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 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 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 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 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 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_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 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_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 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_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")
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)
def handle(self, **options): print options name = options['n'] poll_type = options['t'] question = options['q'] if options['r'] in ['', '', 'None']: default_response = None else: default_response = options['r'] print default_response contacts = Contact.objects.filter( Q(pk__in=eval(options['c'][1:-1])) | Q(groups__pk__in=eval(options['g'][1:-1]))).distinct() print contacts user = User.objects.get(pk=int(options['u'])) start_immediately = eval(options['s']) response_type = options['e'] poll = Poll.create_with_bulk( name, poll_type, question, default_response, contacts, user, ) print poll poll.response_type = response_type poll.save() if type == NewPollForm.TYPE_YES_NO: poll.add_yesno_categories() if settings.SITE_ID: poll.sites.add(Site.objects.get_current()) if start_immediately: poll.start()
def handle(self, **options): open = options["open"] close = options["close"] d = datetime.datetime.now() poll_name = "%s Regular Wash Poll" % d.strftime("%Y-%m-%d") user = User.objects.get(username='******') if open: p = Poll.create_with_bulk(\ name=poll_name, \ question='Do you have access to water? Please reply with YES or NO.', \ default_response='Thank you for your report.', \ user=user, \ contacts=Contact.objects.all(), \ type=Poll.TYPE_TEXT, \ ) p.add_yesno_categories() p.start() elif close: polls = Poll.objects.filter(name__endswith='Regular Wash Poll', end_date=None) if polls.count(): p = polls.order_by('-name')[0] p.end()
def handle(self, **options): print options name = options['n'] poll_type = options['t'] question = options['q'] if options['r'] in ['', '', 'None']: default_response = None else: default_response = options['r'] print default_response contacts = Contact.objects.filter(Q(pk__in=eval(options['c'][1:-1])) | Q(groups__pk__in=eval(options['g'][1:-1]))).distinct() print contacts user = User.objects.get(pk=int(options['u'])) start_immediately = eval(options['s']) response_type = options['e'] poll = Poll.create_with_bulk( name, poll_type, question, default_response, contacts, user, ) print poll poll.response_type = response_type poll.save() if type == NewPollForm.TYPE_YES_NO: poll.add_yesno_categories() if settings.SITE_ID: poll.sites.add(Site.objects.get_current()) if start_immediately: poll.start()
def new_poll(req): log.info("[new_poll] TRANSACTION START") if req.method == 'POST': log.info("[new-poll] - request recieved to create a poll") form = NewPollForm(req.POST, request=req) groups_form = GroupsFilter(req.POST, request=req) # form.updateTypes() #Added to form directly already no need to add them again if form.is_valid() and groups_form.is_valid(): # create our XForm question = form.cleaned_data['question_fr'] default_response = form.cleaned_data['default_response_fr'] provinces = form.cleaned_data['provinces'] excluded_groups = groups_form.cleaned_data['group_list'] if hasattr(Contact, 'groups'): groups = form.cleaned_data['groups'] log.info("[new-poll] - finding all contacts for this poll...") if len(provinces): contacts = Contact.objects.filter( reporting_location__in=provinces).filter( groups__in=groups).exclude(groups__in=excluded_groups) else: if -1 in groups or '-1' in groups: contacts = Contact.objects.all().exclude( groups__in=excluded_groups) else: contacts = Contact.objects.filter( groups__in=groups).exclude(groups__in=excluded_groups) log.info("[new-poll] - found all contacts ok.") log.info("[new-poll] - setting up translations...") name = form.cleaned_data['name'] p_type = form.cleaned_data['type'] response_type = form.cleaned_data['response_type'] if not form.cleaned_data['default_response_en'] == '' \ and not form.cleaned_data['default_response_fr'] == '': (translation, created) = \ Translation.objects.get_or_create(language='en', field=form.cleaned_data['default_response_fr'], value=form.cleaned_data['default_response_en']) if not form.cleaned_data['default_response_ki'] == '' \ and not form.cleaned_data['default_response_fr'] == '': (translation, created) = \ Translation.objects.get_or_create(language='ki', field=form.cleaned_data['default_response_fr'], value=form.cleaned_data['default_response_ki']) if not form.cleaned_data['question_en'] == '': (translation, created) = \ Translation.objects.get_or_create(language='en', field=form.cleaned_data['question_fr'], value=form.cleaned_data['question_en']) if not form.cleaned_data['question_ki'] == '': (translation, created) = \ Translation.objects.get_or_create(language='ki', field=form.cleaned_data['question_fr'], value=form.cleaned_data['question_ki']) log.info("[new-poll] - translations ok.") 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) if p_type == NewPollForm.TYPE_YES_NO: log.info("[new-poll] - is Y/N poll so adding categories...") poll.add_yesno_categories() log.info("[new-poll] - categories added ok.") if settings.SITE_ID: log.info( "[new-poll] - SITE_ID is set, so adding the site to the poll" ) poll.sites.add(Site.objects.get_current()) log.info("[new-poll] - site added ok") log.info("[new-poll] - poll created ok.") log.info("[new_poll] TRANSACTION COMMIT") return redirect(reverse('ureport.views.view_poll', args=[poll.pk])) else: form = NewPollForm(request=req) groups_form = GroupsFilter(request=req) # form.updateTypes() #Added to form directly already no need to add them again log.info("[new_poll] TRANSACTION COMMIT") return render_to_response('ureport/new_poll.html', { 'form': form, 'groups_form': groups_form }, context_instance=RequestContext(req))
def new_poll(req): if req.method == 'POST': form = NewPollForm(req.POST) groups_form = GroupsFilter(req.POST) form.updateTypes() if form.is_valid() and groups_form.is_valid(): # create our XForm question = form.cleaned_data['question_en'] default_response = form.cleaned_data['default_response_en'] districts = form.cleaned_data['districts'] excluded_groups = groups_form.cleaned_data['group_list'] if hasattr(Contact, 'groups'): groups = form.cleaned_data['groups'] if len(districts): contacts = Contact.objects.filter(reporting_location__in=districts).filter(groups__in=groups).exclude( groups__in=excluded_groups) else: contacts = Contact.objects.filter(groups__in=groups).exclude(groups__in=excluded_groups) name = form.cleaned_data['name'] p_type = form.cleaned_data['type'] response_type = form.cleaned_data['response_type'] if not form.cleaned_data['default_response_luo'] == '' \ and not form.cleaned_data['default_response_en'] == '': (translation, created) = \ Translation.objects.get_or_create(language='ach', field=form.cleaned_data['default_response_en'], value=form.cleaned_data['default_response_luo']) if not form.cleaned_data['default_response_kdj'] == '' \ and not form.cleaned_data['default_response_en'] == '': (translation, created) = \ Translation.objects.get_or_create(language='kdj', field=form.cleaned_data['default_response_en'], value=form.cleaned_data['default_response_kdj']) if not form.cleaned_data['question_luo'] == '': (translation, created) = \ Translation.objects.get_or_create(language='ach', field=form.cleaned_data['question_en'], value=form.cleaned_data['question_luo']) if not form.cleaned_data['question_kdj'] == '': (translation, created) = \ Translation.objects.get_or_create(language='kdj', field=form.cleaned_data['question_en'], value=form.cleaned_data['question_kdj']) 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) if p_type == NewPollForm.TYPE_YES_NO: poll.add_yesno_categories() if settings.SITE_ID: poll.sites.add(Site.objects.get_current()) return redirect(reverse('ureport.views.view_poll', args=[poll.pk])) else: form = NewPollForm() groups_form = GroupsFilter() form.updateTypes() return render_to_response('ureport/new_poll.html', {'form': form, 'groups_form': groups_form}, context_instance=RequestContext(req))
def mp_dashboard(request): from contact.forms import FilterGroupsForm, \ MultipleDistictFilterForm, GenderFilterForm, AgeFilterForm groupform = AssignResponseGroupForm(request=request) if request.method == 'POST' and request.POST.get('groups', None): g_form = AssignResponseGroupForm(request.POST, request=request) if g_form.is_valid(): request.session['groups'] = g_form.cleaned_data['groups'] if not request.session.get('groups', None): mp_contacts = Contact.objects.filter(groups__name__in=['MP']) else: mp_contacts = \ Contact.objects.filter(groups__in=request.session.get('groups' )) forms = [MultipleDistictFilterForm, FilterGroupsForm, GenderFilterForm, AgeFilterForm] filter_forms = [] mp_conns = Connection.objects.filter(contact__in=mp_contacts) contacts = \ Contact.objects.exclude(connection__in=Blacklist.objects.all()).distinct() message_list = Message.objects.filter(connection__in=mp_conns, direction='I').order_by('-date') if request.GET.get('ajax', None): date = datetime.datetime.now() - datetime.timedelta(seconds=15) msgs = Message.objects.filter(connection__in=mp_conns, direction='I').filter(date__gte=date) msgs_list = [] if msgs: for msg in msgs: m = {} m['text'] = msg.text m['date'] = str(msg.date.date()) m['name'] = msg.connection.contact.name m['number'] = msg.connection.identity if msg.connection.contact.reporting_location: m['district'] = \ msg.connection.contact.reporting_location.name else: m['district'] = 'N/A' m['group'] = msg.connection.contact.groups.all()[0].name msgs_list.append(m) return HttpResponse(mark_safe(simplejson.dumps(msgs_list))) else: return HttpResponse('success') old_contacts = contacts if request.POST and request.GET.get('filter', None): for form_class in forms: form_instance = form_class(request.POST, request=request) if form_instance.is_valid(): contacts = form_instance.filter(request, contacts) if old_contacts.count() == contacts.count(): return HttpResponse('No Contacts Selected') else: request.session['filtered'] = contacts return HttpResponse(str(contacts.count())) for form in forms: filter_forms.append(form(**{'request': request})) paginator = UreportPaginator(message_list, 10, body=6, padding=2) page = request.GET.get('page', 1) try: messages = paginator.page(page) except PageNotAnInteger: # If page is not an integer, deliver first page. messages = paginator.page(1) except EmptyPage: # If page is out of range (e.g. 9999), deliver last page of results. messages = paginator.page(paginator.num_pages) poll_form = NewPollForm() poll_form.updateTypes() if request.method == 'POST' and request.GET.get('poll', None): res_dict = request.POST.copy() res_dict.update({'groups': u'2'}) poll_form = NewPollForm(res_dict) poll_form.updateTypes() # create poll if request.session.get('filtered', None) \ and poll_form.is_valid(): name = poll_form.cleaned_data['name'] p_type = poll_form.cleaned_data['type'] response_type = poll_form.cleaned_data['response_type'] question = poll_form.cleaned_data['question'] default_response = poll_form.cleaned_data['default_response' ] if not poll_form.cleaned_data['default_response_luo'] == '' \ and not poll_form.cleaned_data['default_response'] \ == '': (translation, created) = \ Translation.objects.get_or_create(language='ach', field=poll_form.cleaned_data['default_response' ], value=poll_form.cleaned_data['default_response_luo' ]) if not poll_form.cleaned_data['question_luo'] == '': (translation, created) = \ Translation.objects.get_or_create(language='ach', field=poll_form.cleaned_data['question'], value=poll_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, request.session.get('filtered'), request.user, ) return redirect(reverse('poll.views.view_poll', args=[poll.pk])) context_dict = { 'poll_form': poll_form, 'filter_forms': filter_forms, 'messages': messages, 'groupform': groupform, } return render_to_response('ureport/mp_dashboard.html', context_dict, context_instance=RequestContext(request))
def mp_dashboard(request): from contact.forms import FilterGroupsForm, \ MultipleDistictFilterForm, GenderFilterForm, AgeFilterForm mp_contacts = Contact.objects.filter(groups__name__in=['MP']) forms = [ MultipleDistictFilterForm, FilterGroupsForm, GenderFilterForm, AgeFilterForm ] filter_forms = [] mp_conns = Connection.objects.filter(contact__in=mp_contacts) contacts = \ Contact.objects.exclude(connection__in=Blacklist.objects.all()).distinct() message_list = Message.objects.filter(connection__in=mp_conns, direction='I').order_by('-date') if request.GET.get('ajax', None): date = datetime.datetime.now() - datetime.timedelta(seconds=15) msgs = Message.objects.filter(connection__in=mp_conns, direction='I').filter(date__gte=date) msgs_list = [] if msgs: for msg in msgs: m = {} m['text'] = msg.text m['date'] = str(msg.date.date()) m['name'] = msg.connection.contact.name m['number'] = msg.connection.identity if msg.connection.contact.reporting_location: m['district'] = \ msg.connection.contact.reporting_location.name else: m['district'] = 'N/A' m['group'] = msg.connection.contact.groups.all()[0].name msgs_list.append(m) return HttpResponse(mark_safe(simplejson.dumps(msgs_list))) else: return HttpResponse('success') old_contacts = contacts if request.POST and request.GET.get('filter', None): for form_class in forms: form_instance = form_class(request.POST, request=request) if form_instance.is_valid(): contacts = form_instance.filter(request, contacts) if old_contacts.count() == contacts.count(): return HttpResponse('No Contacts Selected') else: request.session['filtered'] = contacts return HttpResponse(str(contacts.count())) for form in forms: filter_forms.append(form(**{'request': request})) paginator = UreportPaginator(message_list, 10, body=6, padding=2) page = request.GET.get('page', 1) try: messages = paginator.page(page) except PageNotAnInteger: # If page is not an integer, deliver first page. messages = paginator.page(1) except EmptyPage: # If page is out of range (e.g. 9999), deliver last page of results. messages = paginator.page(paginator.num_pages) poll_form = NewPollForm() poll_form.updateTypes() if request.method == 'POST' and request.GET.get('poll', None): res_dict = request.POST.copy() res_dict.update({'groups': u'2'}) poll_form = NewPollForm(res_dict) poll_form.updateTypes() # create poll if request.session.get('filtered', None) \ and poll_form.is_valid(): name = poll_form.cleaned_data['name'] p_type = poll_form.cleaned_data['type'] response_type = poll_form.cleaned_data['response_type'] question = poll_form.cleaned_data['question'] default_response = poll_form.cleaned_data['default_response'] if not poll_form.cleaned_data['default_response_luo'] == '' \ and not poll_form.cleaned_data['default_response'] \ == '': (translation, created) = \ Translation.objects.get_or_create(language='ach', field=poll_form.cleaned_data['default_response' ], value=poll_form.cleaned_data['default_response_luo' ]) if not poll_form.cleaned_data['question_luo'] == '': (translation, created) = \ Translation.objects.get_or_create(language='ach', field=poll_form.cleaned_data['question'], value=poll_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, request.session.get('filtered'), request.user, ) return redirect(reverse('poll.views.view_poll', args=[poll.pk])) context_dict = { 'poll_form': poll_form, 'filter_forms': filter_forms, 'messages': messages, } return render_to_response('ureport/mp_dashboard.html', context_dict, context_instance=RequestContext(request))
def new_poll(req): log.info("[new_poll] TRANSACTION START") if req.method == 'POST': log.info("[new-poll] - request recieved to create a poll") form = NewPollForm(req.POST, request=req) groups_form = GroupsFilter(req.POST, request=req) form.updateTypes() if form.is_valid() and groups_form.is_valid(): # create our XForm is_urgent = form.cleaned_data['is_urgent'] question = form.cleaned_data['question_en'] default_response = form.cleaned_data['default_response_en'] districts = form.cleaned_data['districts'] excluded_groups = groups_form.cleaned_data['group_list'] if hasattr(Contact, 'groups'): groups = form.cleaned_data['groups'] log.info("[new-poll] - finding all contacts for this poll...") if len(districts): contacts = Contact.objects.filter(reporting_location__in=districts).filter(groups__in=groups).exclude( groups__in=excluded_groups) else: contacts = Contact.objects.filter(groups__in=groups).exclude(groups__in=excluded_groups) log.info("[new-poll] - found all contacts ok.") log.info("[new-poll] - setting up translations...") name = form.cleaned_data['name'] p_type = form.cleaned_data['type'] response_type = form.cleaned_data['response_type'] if not form.cleaned_data['default_response_luo'] == '' \ and not form.cleaned_data['default_response_en'] == '': (translation, created) = \ Translation.objects.get_or_create(language='ach', field=form.cleaned_data['default_response_en'] ) translation.value = form.cleaned_data['default_response_luo'] translation.save() if not form.cleaned_data['default_response_kdj'] == '' \ and not form.cleaned_data['default_response_en'] == '': (translation, created) = \ Translation.objects.get_or_create(language='kdj', field=form.cleaned_data['default_response_en'] ) translation.value = form.cleaned_data['default_response_kdj'] translation.save() if not form.cleaned_data['question_luo'] == '': (translation, created) = \ Translation.objects.get_or_create(language='ach', field=form.cleaned_data['question_en'] ) translation.value = form.cleaned_data['question_luo'] translation.save() if not form.cleaned_data['question_kdj'] == '': (translation, created) = \ Translation.objects.get_or_create(language='kdj', field=form.cleaned_data['question_en'] ) translation.value = form.cleaned_data['question_kdj'] translation.save() log.info("[new-poll] - translations ok.") 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, is_urgent=is_urgent) if p_type == NewPollForm.TYPE_YES_NO: log.info("[new-poll] - is Y/N poll so adding categories...") poll.add_yesno_categories() log.info("[new-poll] - categories added ok.") if settings.SITE_ID: log.info("[new-poll] - SITE_ID is set, so adding the site to the poll") poll.sites.add(Site.objects.get_current()) log.info("[new-poll] - site added ok") log.info("[new-poll] - poll created ok.") log.info("[new_poll] TRANSACTION COMMIT") return redirect(reverse('ureport.views.view_poll', args=[poll.pk])) else: form = NewPollForm(request=req) groups_form = GroupsFilter(request=req) form.updateTypes() log.info("[new_poll] TRANSACTION COMMIT") return render_to_response('ureport/new_poll.html', {'form': form, 'groups_form': groups_form}, context_instance=RequestContext(req))
def new_poll(req): if req.method == 'POST': form = NewPollForm(req.POST, request=req) form.updateTypes() if form.is_valid(): # create our XForm question = form.cleaned_data['question'] default_response = form.cleaned_data['default_response'] districts = form.cleaned_data['district'] # contacts = form.cleaned_data['contacts'] if hasattr(Contact, 'groups'): groups = form.cleaned_data['groups'] contacts = get_allowed_poll_contacts(req).filter(groups__in=groups).distinct() else: contacts = get_allowed_poll_contacts(req) # further filter based on district contacts = contacts.filter(reporting_location__in=districts) name = form.cleaned_data['name'] p_type = form.cleaned_data['type'] response_type = form.cleaned_data['response_type'] if getattr(settings, "LANGUAGES", None): langs = dict(settings.LANGUAGES) for language in dict(settings.LANGUAGES).keys(): if not language == "en": int_default_response = 'default_response_%s' % langs[language] int_question = 'question_%s' % langs[language] if not form.cleaned_data[int_default_response] == '' \ and not form.cleaned_data['default_response'] == '': (translation, created) = \ Translation.objects.get_or_create(language=language, field=form.cleaned_data['default_response'], value=form.cleaned_data[int_default_response]) if not form.cleaned_data[int_question] == '': (translation, created) = \ Translation.objects.get_or_create(language=language, field=form.cleaned_data['question'], value=form.cleaned_data[int_question]) poll_type = (Poll.TYPE_TEXT if p_type == NewPollForm.TYPE_YES_NO else p_type) start_immediately = form.cleaned_data['start_immediately'] poll = Poll.create_with_bulk( name, poll_type, question, default_response, contacts, req.user) if 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(request=req) form.updateTypes() return render_to_response('polls/poll_create.html', {'form': form}, context_instance=RequestContext(req))