def test_verify_deviceid(self, mock_ona_form_submissions, mock_get_form_definition): self.assertEqual('', self.user.deviceid) self.assertFalse(FormSubmission.objects.all()) submission = json.loads(USER_CODE_DATA) mock_ona_form_submissions.return_value = [submission] verify_deviceid.run() self.assertEqual(1, FormSubmission.objects.count()) # Passed minimum as the 'since' parm mock_ona_form_submissions.assert_called_with(ANY, 111, since=minimum_aware_datetime()) # Only add the record once verify_deviceid.run() self.assertEqual(1, FormSubmission.objects.count()) # passed the previous submission time as the 'since' parm when fetching forms subtime = OnaItemBase.parse_form_datetime(submission['_submission_time']) mock_ona_form_submissions.assert_called_with(ANY, 111, since=subtime) self.assertEqual('device_foo', CtsUser.objects.get(pk=self.user.pk).deviceid)
def test_verify_deviceid(self, mock_ona_form_submissions, mock_get_form_definition): self.assertEqual('', self.user.deviceid) self.assertFalse(FormSubmission.objects.all()) submission = json.loads(USER_CODE_DATA) mock_ona_form_submissions.return_value = [submission] verify_deviceid.run() self.assertEqual(1, FormSubmission.objects.count()) # Passed minimum as the 'since' parm mock_ona_form_submissions.assert_called_with( ANY, 111, since=minimum_aware_datetime()) # Only add the record once verify_deviceid.run() self.assertEqual(1, FormSubmission.objects.count()) # passed the previous submission time as the 'since' parm when fetching forms subtime = OnaItemBase.parse_form_datetime( submission['_submission_time']) mock_ona_form_submissions.assert_called_with(ANY, 111, since=subtime) self.assertEqual('device_foo', CtsUser.objects.get(pk=self.user.pk).deviceid)
def update_device_binding(sender, instance, **kwargs): # Only record package locations for package tracking forms form_id = int(settings.ONA_DEVICEID_VERIFICATION_FORM_ID) if kwargs.get('created', False) and int( instance.data['form_id']) == form_id: submission = OnaItemBase(instance.data) try: this_user = CtsUser.objects.get(code=submission.qr_code) except CtsUser.DoesNotExist: logger.error( "Got device ID scan with code that has no matching user (%s)", submission.qr_code) return # Remove this device from any user(s) CtsUser.objects.filter(deviceid=submission.deviceid).update( deviceid='') # Give to the current user this_user.deviceid = submission.deviceid this_user.save()
def verify_deviceid(): """Store the DeviceID and QR code""" last_retrieval = None try: form_id = settings.ONA_DEVICEID_VERIFICATION_FORM_ID if form_id in bad_form_ids: return client = OnaApiClient() # Make sure the form exists before we try to get submissions form_defn = client.get_form_definition(form_id) if not form_defn: # Logging an error should result in an email to the admins so they # know to fix this. logger.error("Bad ONA_DEVICEID_VERIFICATION_FORM_ID: %s" % form_id) # Let's not keep trying for the bad form ID. We'll have to change the # settings and restart to fix it. bad_form_ids.add(form_id) return last_retrieval, unused = LastFormRetrievalTimestamp.objects.get_or_create( form_id=form_id) try: submissions = client.get_form_submissions( form_id, since=last_retrieval.timestamp) except Http404: logger.error( "Got 404 getting submissions for ONA_DEVICEID_VERIFICATION_FORM_ID = %s" % form_id) return except OnaApiClientException as e: if e.status_code != 404: raise logger.error( "Got 404 getting submissions for ONA_DEVICEID_VERIFICATION_FORM_ID = %s" % form_id) return # add the form definition JSON to each submission for data in submissions: data.update({'form_id': form_id}) # create a list of API repr objects and ensure they are sorted by submission date objects = [OnaItemBase(x) for x in submissions] objects.sort(key=lambda x: x._submission_time) for submission in objects: if submission._submission_time > last_retrieval.timestamp: last_retrieval.timestamp = submission._submission_time valid_code = CtsUser.objects.filter( code=submission.qr_code).exists() if valid_code: if not FormSubmission.objects.filter( uuid=submission._uuid).exists(): FormSubmission.from_ona_form_data(submission) else: # Log an invalid QR Code msg = "FormSubmission with form id of %s has invalid User QR Code: %s" \ % (submission._xform_id_string, submission.qr_code) logger.error(msg) except ConnectionError: logger.exception("Error connecting to Ona server") except Exception: logger.exception("Something blew up in verify_deviceid") finally: if last_retrieval: last_retrieval.save()
def test_test_precedence(self): """Normal attribute takes precedence over JSON dictionary key.""" item = OnaItemBase({'json': 'hello'}) self.assertEqual(item.json, {'json': 'hello'})
def test_dictionary_key(self): """JSON dictionary keys should be accessible from the model.""" item = OnaItemBase({'hello': 'world'}) self.assertEqual(item.hello, 'world')
def test_normal_attribute(self): """Normal attributes should be accessible from the model.""" item = OnaItemBase({}) self.assertEqual(item.json, {})
def test_not_a_dict(self): """Ona items must be instantiated with a dictionary.""" with self.assertRaises(ValueError): OnaItemBase([])