def test_database_note_id_increte_automatically_without_declaration(self): note1 = Note() note1.save() note2 = Note() note2.save() self.assertEqual(note2.id - note1.id, 1)
def post(self): user = users.get_current_user() jsonNotes = self.request.get('notes') if user and jsonNotes: notes = simplejson.loads(jsonNotes) for note in notes: # TODO: Validate the note pk = None if note.has_key('pk'): pk = note['pk'] if pk is not None: logging.error("Has primary key: %s" % pk) n = Note().get_by_id(int(pk)) else: logging.error("New note") # This is a new note. n = Note() n.user = user n.text = note['text'] n.left = int(note['left']) n.top = int(note['top']) n.width = int(note['width']) n.height = int(note['height']) n.put()
def setUp(self): welcomeNote = Note() welcomeNote.name = "Welcome to Note Space!" welcomeNote.desc = "Introduction and Quick guide" welcomeNote.owner = "Note Space Team" welcomeNote.save() econNote = Note() econNote.name = "Basic Economics" econNote.subject = "Economics" econNote.desc = "This note is about demands, suplies and how market works." econNote.owner = "Susan" econNote.save() img1 = Image() img1.index = 1 img1.note = econNote img1.image = SimpleUploadedFile( name='IMG_0809.JPG', content=open( "C:/Users/B/Desktop/NoteSpace/static/TestNotes/Econ/IMG_0809.JPG", 'rb').read(), content_type='image/jpeg') img1.save() img2 = Image() img2.index = 2 img2.note = econNote img2.image = SimpleUploadedFile( name='IMG_0810.JPG', content=open( "C:/Users/B/Desktop/NoteSpace/static/TestNotes/Econ/IMG_0810.JPG", 'rb').read(), content_type='image/jpeg') img2.save() img3 = Image() img3.index = 3 img3.note = econNote img3.image = SimpleUploadedFile( name='IMG_0811.JPG', content=open( "C:/Users/B/Desktop/NoteSpace/static/TestNotes/Econ/IMG_0811.JPG", 'rb').read(), content_type='image/jpeg') img3.save() img4 = Image() img4.index = 4 img4.note = econNote img4.image = SimpleUploadedFile( name='IMG_0812.JPG', content=open( "C:/Users/B/Desktop/NoteSpace/static/TestNotes/Econ/IMG_0812.JPG", 'rb').read(), content_type='image/jpeg') img4.save() User.objects.create_user("smith", "*****@*****.**", "1234") self.browser = webdriver.Firefox()
def create(request): list_of_notes = Note.objects.all().order_by('-last_update_date') template = 'notes/create.html' if len(list_of_notes) == 0: note = Note(title='', content='') note.save() elif not list_of_notes[0].title == '': note = Note(title='', content='') note.save() form = NotesForm() list_of_notes = Note.objects.all().order_by('-last_update_date') noteid = list_of_notes[0].id context = {'list_of_notes': list_of_notes, 'form': form, 'noteid': noteid} return render(request, template, context)
def test_loose_tags_removed_when_note_deleted(self): """ Tests 'loose' tags (i.e. Tags associated with no notes) are removed when Note is deleted. """ note = Note(title='My first note', content='Noteworthy content for #pyladies') note.save() note = Note(title='My second note', content='Noteworthy content for #workshop') note.save() Note.objects.all().delete() self.assertEqual(Tag.objects.count(), 0)
def test_create(note_session): note = Note(time_scope_id="2020-ww20.4", short_desc="status update") assert note.note_id is None note_session.add(note) note_session.commit() assert note.note_id is not None
def save_note(message, note, element, story): if DiscordUser.objects.filter(user_id=message.author.id).exists(): user = DiscordUser.objects.get(user_id=message.author.id) if Story.objects.filter(owner=user, name=story).exists(): story = Story.objects.get(owner=user, name=story) if StoryElement.objects.filter(story=story, name=element).exists(): try: element = StoryElement.objects.get(story=story, name=element) note = Note(element=element, note=note) note.save() except MultipleObjectsReturned: elements = StoryElement.objects.filter( story=story, name=element) type_list = [ element.get_type_display() for element in elements ] raise MultipleObjectsReturned(type_list) else: raise ElementNotFoundError else: raise StoryNotFoundError else: raise UserNotCreatedError return element.name
def post(self, request, *args, **kwargs): content = request.data.get('content') note = Note() note.content = content note.title = request.data.get('title') note.save() return Response(note)
def notes(request): if request.method == 'GET': notes = Note.objects.all() for i in range(len(notes)): if notes[i].title is None or len(notes[i].title) == 0: notes[i].title = notes[i].content[:MAX_SYMBOLS] title = request.query_params.get('string', None) if title is not None: notes_title = [ notes.filter(title__icontains=title), notes.filter(content__icontains=title) ] res = [] for i in notes_title: for j in i: if j not in res: res.append(j) notes = res note_serializer = NoteSerializer(notes, many=True) return JsonResponse(note_serializer.data, safe=False) elif request.method == 'POST': content = request.data.get('content') note = Note() note.content = content note.title = request.data.get('title') note.save() note_serializer = NoteSerializer(note) return JsonResponse(note_serializer, safe=False, status=status.HTTP_201_CREATED)
def test_a_user_opens_an_existing_note_for_printing_or_sharing(self): """ An existing note can be open in a tab for printing or sharing via url. Viewing does not require login and the url contains a slug instead of the note id. """ note = Note( title="Pisos termicos", summary= "Los pisos termicos permiten distintos tipos de cultivo segun la temperatura" ) note.save() Paragraph( description="Distintos tipos de cultivos", content= "se clasifican segun la altura sobre el nivel del mar editados", note=note).save() visit(self, reverse("show", kwargs={'slug': note.slug})) body = self.selenium.find_element_by_tag_name('body') self.assertTrue(has_content(body, "Pisos termicos")) self.assertTrue(has_content(body, "Distintos tipos de cultivos")) self.assertTrue( has_content( body, "se clasifican segun la altura sobre el nivel del mar editados" )) self.assertTrue( has_content( body, "Los pisos termicos permiten distintos tipos de cultivo segun la temperatura" ))
def test_database_can_save_and_get_one_Note_multiple_images(self): n = Note() n.name = "test note" n.desc = "this is note for ..." n.save() n_id = n.id img1 = Image() img1.index = 1 img1.note = n img1.image = SimpleUploadedFile( name='1.jpg', content=open( "C:/Users/B/OneDrive/Documents/61FC8C1A-D1FE-4D09-ABE4-BE1689D03C8E.jpg", 'rb').read(), content_type='image/jpeg') img1.save() img2 = Image() img2.index = 2 img2.note = n img2.image = SimpleUploadedFile( name='1.jpg', content=open( "C:/Users/B/OneDrive/Documents/61FC8C1A-D1FE-4D09-ABE4-BE1689D03C8E.jpg", 'rb').read(), content_type='image/jpeg') img2.save() n = Note.objects.get(pk=n_id) images = Image.objects.filter(note=n) self.assertEqual(images.count(), 2)
def test_note_updates_tags(self): """ Tests Tags are automatically updated based on Note content. """ note = Note(title='My first note', content='Noteworthy content for #pyladies') note.save() for i in range(3): if i == 0: note.content = '... but it can be improved. #workshop #python' elif i == 1: note.content = '... but it can be improved some more. #workshop #python' else: pass # test saving twice note.save() self.assertTrue(Tag.objects.get(keyword='workshop')) self.assertTrue(Tag.objects.get(keyword='python')) self.assertEqual(Tag.objects.filter(keyword='pyladies').count(), 0) self.assertEqual(Tag.objects.count(), 2) self.assertEqual(note.tags.count(), 2) self.assertEqual(Note.objects.get().tags.count(), 2)
def test_note_with_multiple_location(self): country = Country(name='A') City = City(name='A', country=country) divesite = DiveSite(name='A', City=City) note_country = Note(country=country) note_country.clean() note_City = Note(City=City) note_City.clean() note_divesite = Note(divesite=divesite) note_divesite.clean() note_multi = Note(divesite=divesite, country=country) with self.assertRaises(ValidationError): note_multi.clean()
def test_was_published_recently_with_future_note(self): """ was_published_recently() returns False for notes whose pub_date is in the future. """ time = timezone.now() + datetime.timedelta(days=30) future_note = Note(pub_date=time) self.assertIs(future_note.was_published_recently(), False)
def test_was_published_recently_with_old_note(self): """ was_published_recently() returns False for notes whose pub_date is older than 1 day. """ time = timezone.now() - datetime.timedelta(days=1, seconds=1) old_note = Note(pub_date=time) self.assertIs(old_note.was_published_recently(), False)
def test_database_canbe_query(self): note1 = Note() note1.id = 5 note1.name = "for testing" note1.save() n = Note.objects.filter(id=5)[0] self.assertEqual(n.name, "for testing")
def add_new_note(request): if request.method == 'POST': noteform = NoteForm(request.POST) if noteform.is_valid(): title = request.POST['title'] description = request.POST['description'] note = Note(user=request.user, title=title, description=description) note.save() return redirect('notes:index')
def create_note(self, user): new_note = Note(date=self.cleaned_data['date'], venue=self.cleaned_data['venue'], note=self.cleaned_data['note'], note_type=self.cleaned_data['note_type'], creator=user, customer=user.userprofile.customer) new_note.save() return new_note
def run(): n = Note(title='example', content='This is a test.') n.save() # def run(): # print("Test")
def test_was_published_recently_with_recent_note(self): """ was_published_recently() returns True for notes whose pub_date is within the last day. """ time = timezone.now() - datetime.timedelta( hours=23, minutes=59, seconds=59) recent_note = Note(pub_date=time) self.assertIs(recent_note.was_published_recently(), True)
def gen_random_notes(note_count): """Puts a set of random notes of given length into the db.""" user_count = User.objects.all().count() Note.objects.bulk_create([ Note(title=randomdata.random_title(), content=randomdata.random_text(), owner_id=random.randrange(1, user_count + 1)) for _ in xrange(note_count) ])
def test_database_can_search_by_similar(self): from django.db.models import Q note1_namesearch = Note() note1_namesearch.name = "django" note1_namesearch.save() note2_descsearch = Note() note2_descsearch.name = "writing unit test" note2_descsearch.desc = "for django" note2_descsearch.save() Tag_django = Tag() Tag_django.title = "django" Tag_django.save() note3_tagsearch = Note() note3_tagsearch.name = "Html Template Tags" note3_tagsearch.save() note3_tagsearch.tags.add(Tag_django) note3_tagsearch.save() note4_ownersearch = Note() note4_ownersearch.name = "FAQ" note4_ownersearch.owner = "Django official" note4_ownersearch.save() search_result = list( Note.objects.filter( Q(name__icontains="django") | Q(desc__icontains="django") | Q(tags__title__icontains="django") | Q(owner__icontains="django"))) print(search_result) self.assertGreaterEqual(len(search_result), 4) self.assertIn(note1_namesearch, search_result) self.assertIn(note2_descsearch, search_result) self.assertIn(note3_tagsearch, search_result) self.assertIn(note4_ownersearch, search_result) search_result = Note.objects.filter( name__trigram_similar="django").filter( desc__trigram_similar="django")
def save_data(request): if 'name' in request.GET and request.GET[ 'name'] and 'content' in request.GET and request.GET['content']: name = request.GET['name'] content = request.GET['content'] note = Note(name=name, content=content) note.save() return HttpResponse('Successful') else: return HttpResponse('Failed')
def new_note(request): if request.method == 'POST': if request.POST.get('title') and request.POST.get('body'): note = Note() note.user = request.user note.title = request.POST.get('title') note.body = request.POST.get('body') note.save() return HttpResponseRedirect(reverse(note_list)) else: return render(request, 'notes.html') else: return render(request, 'notes.html')
def notes(request, id): if request.method == 'POST': data = request.data user = User.objects.get(pk=id) note = Note(user=user, title=data["title"], note=data["note"]) note.save() return JsonResponse({"message": "Data saved"}, status=200) else: note = Note.objects.filter(user=id) serialize = NoteDisplaySerializer(note, many=True) return Response(serialize.data)
def test_list(self): days_ago_1 = datetime.datetime.now() - datetime.timedelta(days=1) days_ago_7 = datetime.datetime.now() - datetime.timedelta(days=7) days_ago_16 = datetime.datetime.now() - datetime.timedelta(days=16) title1 = 'note1' title2 = 'note2' title3 = 'note3' note1 = Note(user=self.user, title=title1, written_at=days_ago_1) note2 = Note(user=self.user, title=title2, written_at=days_ago_7) note3 = Note(user=self.user, title=title3, written_at=days_ago_16) note1.save() note2.save() note3.save() url = self.public_url + '{}/'.format(self.user.username) res = self.rest_client.get(url) content = json.loads(res.content) self.assertEqual(content['days_1'][0]['title'], title1) self.assertEqual(content['days_7'][0]['title'], title2) self.assertEqual(content['days_16'][0]['title'], title3) self.assertEqual(content['days_35'], []) self.assertEqual(content['days_62'], [])
def test_note_creates_tags(self): """ Tests Tags are automatically created based on Note content. """ # check that tags are associated with saved object in database note = Note(title='My first note', content='Noteworthy content for #pyladies') note.save() self.assertEqual(Tag.objects.count(), 1) self.assertTrue(Tag.objects.get(keyword='pyladies')) self.assertEqual(Note.objects.get(pk=note.pk).tags.count(), 1) self.assertEqual(Tag.objects.get(keyword='pyladies').notes.count(), 1) # check tags are not duplicated and are grouped note = Note( title='My second note', content='Noteworthy content for #pyladies with the same hashtag.') note.save() self.assertEqual(Tag.objects.count(), 1) self.assertTrue(Tag.objects.get(keyword='pyladies')) self.assertEqual(Note.objects.get(pk=note.pk).tags.count(), 1) self.assertEqual(Tag.objects.get(keyword='pyladies').notes.count(), 2)
def test_can_get_review_mean_score(self): n = Note() n.save() review1 = Review() review1.note = n review1.score = 5 review1.save() review2 = Review() review2.note = n review2.score = 4 review2.save() self.assertEqual(round(n.mean_score, ndigits=2), 4.5)
def create_daterange_notes(self, user): end_date = self.cleaned_data['end_date'] date = self.cleaned_data['date'] if date == end_date: return self.create_note(user) else: for x in rrule(DAILY, dtstart=date, until=end_date): new_note = Note(date=x, venue=self.cleaned_data['venue'], note=self.cleaned_data['note'], note_type=self.cleaned_data['note_type'], creator=user, customer=user.userprofile.customer) new_note.save() return True
def __init__(self, *args, **kwargs): """ If it's a form for a new note, a `noted_object` argument must be in kwargs """ # get or create a note, to have content_type filled in the form if 'instance' not in 'kwargs' and 'noted_object' in kwargs: kwargs['instance'] = Note(content_object=kwargs.pop('noted_object')) super(NoteForm, self).__init__(*args, **kwargs) ## change the help text for markup #self.fields['markup'].help_text = self.fields['markup'].help_text\ # .replace('are using with this model', 'want to use') self.fields['content'].label = 'Your private note'