def test_should_auto_close_polls(self, mock_send_bulk_sms): self.poll_to_post['question'] = 'Will you comply, yes or no?' self.poll_to_post['ptype'] = 'yesno' second_poll = self.poll_to_post.copy() second_poll['question'] = 'Please say, yes or no?' second_poll['keyword'] = 'anotherkey' # self.poll_to_send['text'] = 'Will you comply, yes or no? Reply With: NECOCPoll YES/NO' response = self.client.post(self.POLL_ENDPOINT, data=json.dumps(self.poll_to_post), content_type="application/json") self.assertEqual(201, response.status_code) retrieved_poll = Poll.objects(**self.poll_to_post) self.assertEqual(1, retrieved_poll.count()) self.assertEqual(True, retrieved_poll[0].open) response = self.client.post(self.POLL_ENDPOINT, data=json.dumps(second_poll), content_type="application/json") self.assertEqual(201, response.status_code) retrieved_poll = Poll.objects(**self.poll_to_post) self.assertEqual(1, retrieved_poll.count()) self.assertEqual(False, retrieved_poll[0].open) retrieved_poll = Poll.objects(**second_poll) self.assertEqual(1, retrieved_poll.count()) self.assertEqual(True, retrieved_poll[0].open)
def get_queryset(self): query_params = {key: value or None for key, value in self.request.GET.items()} user_group = self.request.user.group.name if user_group in getattr(settings, 'DISTRICT_GROUPS', []): target_locations = get_user_district_locations(self.request.user) query_params.update({'target_locations__in': target_locations}) if 'ordering' in query_params: ordering_params = query_params['ordering'] del query_params['ordering'] query_set = Poll.objects(**query_params).order_by('%s' % ordering_params) else: query_set = Poll.objects(**query_params).order_by('-created_at') return query_set
def setUp(self): date_time = datetime.datetime(2014, 9, 17, 16, 0, 49, 807000) phone_number = "256775019449" self.district = Location( **dict(name='Kampala', parent=None, type='district')).save() self.village = Location(**dict( name='Bukoto', parent=self.district, type='village')).save() self.mobile_user = UserProfile(**dict(name='timothy', phone=phone_number, location=self.village, email=None)).save() self.poll_attr = dict(name="Disaster", question="How many disasters are in your area?", keyword="some_word", target_locations=[str(self.village.id)]) self.poll = Poll(**self.poll_attr).save() self.text_format = "NECOCPoll %s there are 4 or 5" text = self.text_format % self.poll_attr['keyword'] self.poll_response = dict(phone_no=phone_number, text=text, received_at=date_time, relayer_id=234, run_id=23243) self.serialized_data = dict(phone=phone_number, time=date_time, relayer=234, run=23243, text=text)
def setUp(self): date_time = datetime.datetime(2014, 9, 17, 16, 0, 49, 807000) phone_number = "+256775019449" self.district = Location( **dict(name='Kampala', parent=None, type='district')).save() self.village = Location(**dict( name='Bukoto', parent=self.district, type='village')).save() self.mobile_user = UserProfile(**dict(name='timothy', phone=phone_number, location=self.village, email=None)).save() self.mobile_user2 = UserProfile(**dict( name='timothy2', phone='12344', location=self.village, email=None)).save() poll_attr = dict(name="Disaster", question="How many disasters are in your area?", keyword="some_word", target_locations=[str(self.village.id)]) self.poll = Poll(**poll_attr).save() self.poll_response_attr = dict(phone_no=phone_number, text="NECOCPoll %s whatever" % self.poll['keyword'], received_at=date_time, relayer_id=234, run_id=23243, poll=self.poll) self.delimiter_line = 'sep=;' self.headings = "Respondent;Answer;Location;Responded on"
def test_should_serialize_poll_object(self): poll = Poll(**self.poll).save() serialized_object = PollSerializer(poll) self.assertDictContainsSubset(self.serialized_poll, serialized_object.data) self.assertIsNotNone(serialized_object.data['id']) self.assertIsNotNone(serialized_object.data['created_at'])
def test_ddmc_should_get_a_list_of_polls_of_his_district(self): self.client.logout() user = self.login_user_with_group(self.ddmc_group) user_attr = dict(name='sam', phone='+256775019441', location=self.ludara_subcounty, email=None, user=user) UserProfile(**(user_attr)).save() poll = Poll(**self.poll_to_post).save() poll2 = Poll(**self.poll_to_post2).save() poll3 = Poll(**self.poll_to_post3).save() response = self.client.get(self.POLL_ENDPOINT, format='json') self.assertEqual(200, response.status_code) self.assertEqual(2, len(response.data))
def test_should_process_and_categorise_yesno_poll_responses(self): self.poll_attr['ptype'] = 'yesno' self.poll_attr['keyword'] = 'akeyword' poll = Poll(**self.poll_attr).save() self.poll_response['text'] = 'yes' PollResponse(**self.poll_response).save() poll_response = PollResponse.objects(**self.poll_response) self.assertEqual(1, poll_response.count()) yes_category = ResponseCategory.objects(**dict(poll=poll, name='yes')).first() self.assertEqual(1, PollResponseCategory.objects.count()) self.assertEqual(1, PollResponseCategory.objects(**dict(response_category=yes_category, poll_response=poll_response.first())).count()) #a 'NO' Response self.poll_response['text'] = 'nah' PollResponse(**self.poll_response).save() poll_response = PollResponse.objects(**self.poll_response) self.assertEqual(1, poll_response.count()) no_category = ResponseCategory.objects(**dict(poll=poll, name='no')).first() self.assertEqual(2, PollResponseCategory.objects.count()) self.assertEqual(1, PollResponseCategory.objects(**dict(response_category=no_category, poll_response=poll_response.first())).count()) #a 'unknown' Response self.poll_response['text'] = 'very wiered response' PollResponse(**self.poll_response).save() poll_response = PollResponse.objects(**self.poll_response) self.assertEqual(1, poll_response.count()) unknown_category = ResponseCategory.objects(**dict(poll=poll, name='unknown')).first() self.assertEqual(3, PollResponseCategory.objects.count()) #bad response not associated with poll self.assertEqual(1, PollResponseCategory.objects(**dict(response_category=unknown_category, poll_response=poll_response.first())).count()) #should count results results_count = poll.yesno_poll_stats() self.assertEqual(1, results_count['yes']) self.assertEqual(1, results_count['unknown']) self.assertEqual(1, results_count['no'])
def get_queryset(self): query_params = { key: value or None for key, value in self.request.GET.items() } user_group = self.request.user.group.name if user_group in getattr(settings, 'DISTRICT_GROUPS', []): target_locations = get_user_district_locations(self.request.user) query_params.update({'target_locations__in': target_locations}) if 'ordering' in query_params: ordering_params = query_params['ordering'] del query_params['ordering'] query_set = Poll.objects(**query_params).order_by('%s' % ordering_params) else: query_set = Poll.objects(**query_params).order_by('-created_at') return query_set
def test_should_post_a_yesno_poll_and_resend_appropriate_outgoing_message(self, mock_send_bulk_sms): self.poll_to_post['question'] = 'Will you comply, yes or no?' self.poll_to_post['ptype'] = 'yesno' self.poll_to_send['text'] = 'Will you comply, yes or no? Reply With: NECOCPoll YES/NO' response = self.client.post(self.POLL_ENDPOINT, data=json.dumps(self.poll_to_post), content_type="application/json") self.assertEqual(201, response.status_code) # mock_send_bulk_sms.delay.assert_called_once_with(ANY, ANY, self.poll_to_send['text']) self.assertTrue(mock_send_bulk_sms.delay.called_once_with(ANY, ANY, self.poll_to_send['text'])) retrieved_poll = Poll.objects(**self.poll_to_post) self.assertEqual(1, retrieved_poll.count()) self.assertTrue(retrieved_poll[0].is_yesno_poll())
class PollListCreateView(ListCreateAPIView): model = Poll serializer_class = PollSerializer queryset = Poll.objects() permission_classes = [ Or(build_permission_class('dms.can_manage_polls'), And(build_permission_class('dms.can_view_polls'), IsGetRequest)) ] def get_queryset(self): query_params = { key: value or None for key, value in self.request.GET.items() } user_group = self.request.user.group.name if user_group in getattr(settings, 'DISTRICT_GROUPS', []): target_locations = get_user_district_locations(self.request.user) query_params.update({'target_locations__in': target_locations}) if 'ordering' in query_params: ordering_params = query_params['ordering'] del query_params['ordering'] query_set = Poll.objects(**query_params).order_by('%s' % ordering_params) else: query_set = Poll.objects(**query_params).order_by('-created_at') return query_set def post_save(self, obj, created=True): locations = self.get_location(obj) phone_numbers = list( UserProfile.objects(location__in=locations).values_list('phone')) if obj.ptype == 'yesno': text = '%s Reply With: NECOCPoll YES/NO' % obj.question else: text = '%s Reply With: NECOCPoll %s ...' % (obj.question, obj.keyword) send_bulk_sms.delay(obj, phone_numbers, text) def get_location(self, obj): locations = Location.objects(id__in=obj.target_locations) if locations.filter(type='subcounty'): return locations districts_children = [district.children() for district in locations] return flatten(districts_children) def get_location_id(self, user): profile = UserProfile.objects(user=user).first() return profile.location.id if profile else ''
def test_should_post_a_poll_and_save_logs(self, mock_requests): some_id = 1234 mock_response = MagicMock() mock_response.status_code = 201 mock_response.json.return_value = {"messages": [some_id], "sms": [some_id]} mock_requests.post.return_value = mock_response response = self.client.post(self.POLL_ENDPOINT, data=json.dumps(self.poll_to_post), content_type="application/json") self.assertEqual(201, response.status_code) self.assertTrue(mock_requests.post.called_once_with(API_URL, json.dumps(self.poll_to_send), self.headers)) retrieved_poll = Poll.objects(**self.poll_to_post) self.assertEqual(1, retrieved_poll.count())
def test_should_process_and_categorise_yesno_poll_responses_when_yesno_is_misplaced(self): self.poll_attr['ptype'] = 'yesno' self.poll_attr['keyword'] = 'akeyword' poll = Poll(**self.poll_attr).save() self.poll_response['text'] = 'NECOCPoll a very bad yes answer' PollResponse(**self.poll_response).save() poll_response = PollResponse.objects(**self.poll_response) self.assertEqual(1, poll_response.count()) yes_category = ResponseCategory.objects(**dict(poll=poll, name='yes')).first() self.assertEqual(1, PollResponseCategory.objects.count()) self.assertEqual(1, PollResponseCategory.objects(**dict(response_category=yes_category, poll_response=poll_response.first())).count())
def test_should_create_yesno_poll_response(self): self.poll_attr['ptype'] = 'yesno' self.poll_attr['keyword'] = 'weiredkey' self.poll_attr[ 'question'] = 'Are there any disasters in your area? YES or NO' self.poll = Poll(**self.poll_attr).save() self.expected_poll_response['text'] = 'NECOCPoll.yes' self.poll_response['text'] = 'NECOCPoll.yes' response = self.client.post(self.API_ENDPOINT, data=self.expected_poll_response) self.assertEqual(201, response.status_code) retrieved_poll_response = PollResponse.objects(**self.poll_response) self.assertEqual(1, retrieved_poll_response.count()) self.assertTrue(retrieved_poll_response[0].is_categorized())
def test_should_get_a_list_of_polls(self): poll = Poll(**self.poll_to_post).save() poll_response_attr = dict(phone_no='123455', text="NECOC There is a fire", relayer_id=234, run_id=23243, poll=poll) PollResponse(**poll_response_attr).save() response = self.client.get(self.POLL_ENDPOINT, format='json') self.assertEqual(200, response.status_code) self.assertEqual(1, len(response.data)) expected_poll = self.poll_to_post.copy() expected_poll['number_of_responses'] = 1 self.assertDictContainsSubset(expected_poll, response.data[0])
def test_should_post_a_yesno_poll_and_resend_appropriate_outgoing_message( self, mock_send_bulk_sms): self.poll_to_post['question'] = 'Will you comply, yes or no?' self.poll_to_post['ptype'] = 'yesno' self.poll_to_send[ 'text'] = 'Will you comply, yes or no? Reply With: NECOCPoll YES/NO' response = self.client.post(self.POLL_ENDPOINT, data=json.dumps(self.poll_to_post), content_type="application/json") self.assertEqual(201, response.status_code) # mock_send_bulk_sms.delay.assert_called_once_with(ANY, ANY, self.poll_to_send['text']) self.assertTrue( mock_send_bulk_sms.delay.called_once_with( ANY, ANY, self.poll_to_send['text'])) retrieved_poll = Poll.objects(**self.poll_to_post) self.assertEqual(1, retrieved_poll.count()) self.assertTrue(retrieved_poll[0].is_yesno_poll())
def test_should_post_a_poll_and_save_logs(self, mock_requests): some_id = 1234 mock_response = MagicMock() mock_response.status_code = 201 mock_response.json.return_value = { "messages": [some_id], "sms": [some_id] } mock_requests.post.return_value = mock_response response = self.client.post(self.POLL_ENDPOINT, data=json.dumps(self.poll_to_post), content_type="application/json") self.assertEqual(201, response.status_code) self.assertTrue( mock_requests.post.called_once_with(API_URL, json.dumps(self.poll_to_send), self.headers)) retrieved_poll = Poll.objects(**self.poll_to_post) self.assertEqual(1, retrieved_poll.count())
def setUp(self): self.date_time = datetime.datetime(2014, 9, 17, 16, 0, 49, 807000) self.district = Location( **dict(name='Kampala', parent=None, type='district')).save() self.village = Location(**dict( name='Bukoto', parent=self.district, type='village')).save() self.mobile_user = UserProfile(**dict(name='timothy', phone="256775019449", location=self.village, email=None)).save() self.poll_attr = dict(name="Disaster", question="How many disasters are in your area?", keyword="some_word", target_locations=[str(self.village.id)]) self.poll = Poll(**self.poll_attr).save() self.text_format = "NECOCPoll %s there are 4 or 5" self.dotted_text_format = "NECOCPoll.%s.there.are.4.or.5" self.no_keyword = '' text = self.text_format % self.poll_attr['keyword'] dotted_text = self.dotted_text_format % self.poll_attr['keyword'] self.expected_poll_response = dict(phone="256775019449", text=text, time=self.date_time, relayer=234, run=23243) self.poll_response = dict(phone_no="256775019449", text=text, received_at=self.date_time, relayer_id=234, run_id=23243) self.no_keyword_response = dict(phone="256775019449", text=(self.text_format % self.no_keyword), time=self.date_time, relayer=234, run=23243) self.no_keyword_message = dict(phone_no="256775019449", text=(self.text_format % self.no_keyword), received_at=self.date_time, relayer_id=234, run_id=23243) self.wrong_format_response = dict(phone="256775019449", text="there are 4 or 5", time=self.date_time, relayer=234, run=23243) self.wrong_format_message = dict(phone_no="256775019449", text="there are 4 or 5", received_at=self.date_time, relayer_id=234, run_id=23243) self.no_text_response = dict(phone="256775019449", text="NECOCPoll ", time=self.date_time, relayer=234, run=23243) self.no_text_message = dict(phone_no="256775019449", text="NECOCPoll ", received_at=self.date_time, relayer_id=234, run_id=23243) self.special_response_for_rapidtester = dict(phone="256775019449", text=None, time=self.date_time, relayer=234, run=23243) self.special_response = dict(phone_no="256775019449", text=None, received_at=self.date_time, relayer_id=234, run_id=23243) self.dotted_response = dict(phone="256775019449", text=dotted_text, time=self.date_time, relayer=234, run=23243) self.dotted_message = dict(phone_no="256775019449", text=dotted_text, received_at=self.date_time, relayer_id=234, run_id=23243) self.client.logout()
def validate_keyword(self, attrs, source): if len(Poll.objects(keyword=attrs[source])): raise rest_serializers.ValidationError('Keyword must be unique') return attrs