def test_must_have_fields_create(self): for field in ['user', 'usage_id', 'course_id', 'ranges']: payload = self.note_dict.copy() payload.pop(field) with self.assertRaises(ValidationError): note = Note.create(payload) note.full_clean()
def test_default_tags_value(self): """ Test that a note without explicit tags has an empty list for the tags value """ payload = self.note_dict.copy() payload.pop("tags") note = Note.create(payload) note.full_clean() note.save() self.assertEqual("[]", note.tags) self.assertEqual([], note.as_dict()["tags"])
def test_create_valid_note(self): note = Note.create(self.note_dict.copy()) note.save() result_note = note.as_dict() del result_note['id'] del result_note['created'] del result_note['updated'] self.assertEqual(result_note, self.note_dict)
def test_default_tags_value(self): """ Test that a note without explicit tags has an empty list for the tags value """ payload = self.note_dict.copy() payload.pop("tags") note = Note.create(payload) note.full_clean() note.save() self.assertEqual("[]", note.tags) self.assertEqual([], NoteSerializer(note).data["tags"])
def test_create_valid_note(self): note = Note.create(self.note_dict.copy()) note.save() serializer = NoteSerializer(note) result_note = serializer.data del result_note['id'] del result_note['created'] del result_note['updated'] self.assertEqual(result_note, self.note_dict)
def note_iter(total_notes, notes_per_user, course_ids): """ Return an iterable of random notes data of length `total_notes`. Arguments: total_notes (int): total number of notes models to yield notes_per_user (int): number of notes to attribute to any one user course_ids (list): list of course_id strings to which notes will be randomly attributed Returns: generator: An iterable of note models. """ DATA_DIRECTORY = os.path.join(os.path.dirname(__file__), "data/") with open(os.path.join(DATA_DIRECTORY, 'basic_words.txt')) as f: notes_text = [word for line in f for word in line.split()] def weighted_get_words(weighted_num_words): """ Return random words of of a length of weighted probability. `weighted_num_words` should look like [(word_count, weight), (word_count, weight) ...] """ return random.sample( notes_text, random.choice([ word_count for word_count, weight in weighted_num_words for i in range(weight) ])) get_new_user_id = lambda: uuid.uuid4().hex user_id = get_new_user_id() for note_count in range(total_notes): if note_count % notes_per_user == 0: user_id = get_new_user_id() # Notice that quote and ranges are arbitrary yield Note(user_id=user_id, course_id=random.choice(course_ids), usage_id=uuid.uuid4().hex, quote='foo bar baz', text=' '.join( weighted_get_words([(10, 5), (25, 3), (100, 2)])), ranges=json.dumps([{ "start": "/div[1]/p[1]", "end": "/div[1]/p[1]", "startOffset": 0, "endOffset": 6 }]), tags=json.dumps( weighted_get_words([(1, 40), (2, 30), (5, 15), (10, 10), (15, 5)])))
def post(self, *args, **kwargs): # pylint: disable=unused-argument """ Create a new annotation. Returns 400 request if bad payload is sent or it was empty object. """ if not self.request.data or 'id' in self.request.data: return Response(status=status.HTTP_400_BAD_REQUEST) try: total_notes = Note.objects.filter( user_id=self.request.data['user'], course_id=self.request.data['course_id']).count() if total_notes >= settings.MAX_NOTES_PER_COURSE: raise AnnotationsLimitReachedError note = Note.create(self.request.data) note.full_clean() # Gather metrics for New Relic so we can slice data in New Relic Insights newrelic.agent.add_custom_parameter('notes.count', total_notes) except ValidationError as error: log.debug(error, exc_info=True) return Response(status=status.HTTP_400_BAD_REQUEST) except AnnotationsLimitReachedError: error_message = _( u'You can create up to {max_num_annotations_per_course} notes.' u' You must remove some notes before you can add new ones.' ).format( max_num_annotations_per_course=settings.MAX_NOTES_PER_COURSE) log.info(u'Attempted to create more than %s annotations', settings.MAX_NOTES_PER_COURSE) return Response({'error_msg': error_message}, status=status.HTTP_400_BAD_REQUEST) note.save() location = reverse('api:v1:annotations_detail', kwargs={'annotation_id': note.id}) serializer = NoteSerializer(note) return Response(serializer.data, status=status.HTTP_201_CREATED, headers={'Location': location})
def post(self, *args, **kwargs): # pylint: disable=unused-argument """ Create a new annotation. Returns 400 request if bad payload is sent or it was empty object. """ if not self.request.data or 'id' in self.request.data: return Response(status=status.HTTP_400_BAD_REQUEST) try: total_notes = Note.objects.filter( user_id=self.request.data['user'], course_id=self.request.data['course_id'] ).count() if total_notes >= settings.MAX_NOTES_PER_COURSE: raise AnnotationsLimitReachedError note = Note.create(self.request.data) note.full_clean() # Gather metrics for New Relic so we can slice data in New Relic Insights newrelic.agent.add_custom_parameter('notes.count', total_notes) except ValidationError as error: log.debug(error, exc_info=True) return Response(status=status.HTTP_400_BAD_REQUEST) except AnnotationsLimitReachedError: error_message = _( u'You can create up to {max_num_annotations_per_course} notes.' u' You must remove some notes before you can add new ones.' ).format(max_num_annotations_per_course=settings.MAX_NOTES_PER_COURSE) log.info( u'Attempted to create more than %s annotations', settings.MAX_NOTES_PER_COURSE ) return Response({ 'error_msg': error_message }, status=status.HTTP_400_BAD_REQUEST) note.save() location = reverse('api:v1:annotations_detail', kwargs={'annotation_id': note.id}) serializer = NoteSerializer(note) return Response(serializer.data, status=status.HTTP_201_CREATED, headers={'Location': location})
def post(self, *args, **kwargs): # pylint: disable=unused-argument """ Create a new annotation. Returns 400 request if bad payload is sent or it was empty object. """ if 'id' in self.request.DATA: return Response(status=status.HTTP_400_BAD_REQUEST) try: note = Note.create(self.request.DATA) note.full_clean() except ValidationError as error: log.debug(error, exc_info=True) return Response(status=status.HTTP_400_BAD_REQUEST) note.save() location = reverse('api:v1:annotations_detail', kwargs={'annotation_id': note.id}) return Response(note.as_dict(), status=status.HTTP_201_CREATED, headers={'Location': location})
def test_create_invalid_note(self): note = Note() for empty_type in (None, '', []): with self.assertRaises(ValidationError): note.create(empty_type)