# HG changeset patch # User ndurand # Date 1427988594 -7200 # Node ID 5087560b51b64bde2e695b6a99982f9531b10859 # Parent f69b5d8ba4b9c2da10ef70ab77de031703985442 Upgrade to Django 1.6: reworked and fixed tests and deprecations diff -r f69b5d8ba4b9 -r 5087560b51b6 src/ldt/ldt/api/ldt/serializers/cinelabserializer.py --- a/src/ldt/ldt/api/ldt/serializers/cinelabserializer.py Fri Mar 27 18:07:56 2015 +0100 +++ b/src/ldt/ldt/api/ldt/serializers/cinelabserializer.py Thu Apr 02 17:29:54 2015 +0200 @@ -1,5 +1,4 @@ from django.conf import settings -from django.utils import simplejson from ldt.ldt_utils.models import Content, Project from ldt.ldt_utils.projectserializer import ProjectJsonSerializer from ldt.ldt_utils.utils import generate_uuid @@ -59,7 +58,7 @@ "owner*": "user_id" """ - cinelab = simplejson.loads(content) + cinelab = json.loads(content) # We validate the json self.validate_cinelab_json(cinelab) # We search if the id is set @@ -82,7 +81,7 @@ #s = '{"description": "", "ldt": "", "000ldt_id": "gen_by_tc","title": "aaa GEN BY TC"}' #s = '{"description": "", "ldt": "", "title": "aaaGEN BY TC"}' - #return simplejson.loads(simplejson.dumps(s)) + #return json.loads(json.dumps(s)) return s diff -r f69b5d8ba4b9 -r 5087560b51b6 src/ldt/ldt/ldt_utils/fixtures/testing_sites_data.json --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/ldt/ldt/ldt_utils/fixtures/testing_sites_data.json Thu Apr 02 17:29:54 2015 +0200 @@ -0,0 +1,10 @@ +[ + { + "model": "sites.site", + "pk": 1, + "fields": { + "domain": "127.0.0.1:8000", + "name": "localhost" + } + } +] \ No newline at end of file diff -r f69b5d8ba4b9 -r 5087560b51b6 src/ldt/ldt/ldt_utils/fixtures/user_data.json --- a/src/ldt/ldt/ldt_utils/fixtures/user_data.json Fri Mar 27 18:07:56 2015 +0100 +++ b/src/ldt/ldt/ldt_utils/fixtures/user_data.json Thu Apr 02 17:29:54 2015 +0200 @@ -1,7 +1,7 @@ [ { "pk": 2, - "model": "auth.user", + "model": "user.ldtuser", "fields": { "username": "admin", "first_name": "", diff -r f69b5d8ba4b9 -r 5087560b51b6 src/ldt/ldt/ldt_utils/models.py --- a/src/ldt/ldt/ldt_utils/models.py Fri Mar 27 18:07:56 2015 +0100 +++ b/src/ldt/ldt/ldt_utils/models.py Thu Apr 02 17:29:54 2015 +0200 @@ -29,9 +29,6 @@ from .events import post_project_save - -User = get_user_model() - logger = logging.getLogger(__name__); class Author(SafeModel): @@ -45,6 +42,7 @@ return unicode(self.id) + " - " + self.handle + ", " + self.email + ", " + self.firstname + " " + self.lastname class Meta: + app_label="ldt_utils" permissions = ( ('view_author', 'Can view author'), ) @@ -78,6 +76,7 @@ mimetype_field = models.CharField(max_length=512, null=True, blank=True, verbose_name=_('media.mimetype')) class Meta: + app_label="ldt_utils" permissions = ( ('view_media', 'Can view media'), ) @@ -175,15 +174,16 @@ update_date = models.DateTimeField(auto_now=True, verbose_name=_('content.update_date')) title = models.CharField(max_length=1024, null=True, blank=True, verbose_name=_('content.title')) description = models.TextField(null=True, blank=True, verbose_name=_('content.description')) - authors = models.ManyToManyField(Author, blank=True, verbose_name=_('content.authors')) + authors = models.ManyToManyField("Author", blank=True, verbose_name=_('content.authors')) duration = models.IntegerField(null=True, blank=True, verbose_name=_('content.duration')) content_creation_date = models.DateTimeField(null=True, blank=True, verbose_name=_('content.content_creation_date')) tags = TaggableManager() - media_obj = models.ForeignKey('Media', blank=True, null=True) + media_obj = models.ForeignKey("Media", blank=True, null=True) image = ImageField(upload_to="thumbnails/contents/", default=settings.DEFAULT_CONTENT_ICON, max_length=200) - front_project = models.ForeignKey('Project', null=True, blank=True) + front_project = models.ForeignKey("Project", null=True, blank=True) class Meta: + app_label="ldt_utils" ordering = ["title"] permissions = ( ('view_content', 'Can view content'), @@ -459,7 +459,7 @@ if old_user.is_superuser: admin = old_user else: - admin = User.objects.filter(is_superuser=True)[0] + admin = get_user_model().objects.filter(is_superuser=True)[0] set_current_user(admin) self.front_project = Project.create_project(admin, 'front project : %s' % self.title, [self], cuttings=['chapitrage', 'contributions'] ) @@ -545,7 +545,7 @@ if self.annotation_volume_str is None and self.polemics_volume_str is None: self.__init_empty_stat() - content = models.OneToOneField(Content, blank=False, null=False, related_name='stat_annotation', verbose_name=_("content_stat.content"), unique=True, db_index=True) + content = models.OneToOneField("Content", blank=False, null=False, related_name='stat_annotation', verbose_name=_("content_stat.content"), unique=True, db_index=True) annotation_volume_str = models.CommaSeparatedIntegerField(max_length=1024, null=True, blank=True, verbose_name=_("content_stat.annotations_volume")) polemics_volume_str = models.CommaSeparatedIntegerField(max_length=1024, null=True, blank=True, verbose_name=_("content_stat.polemics_volume")) nb_annotations = models.IntegerField(null=False, blank=False, verbose_name=_('content.nb_annotation'), default=0, db_index=True) @@ -587,6 +587,9 @@ polemics_volume = property(**polemics_volume()) + class Meta: + app_label="ldt_utils" + class Project(Document, SafeModel): @@ -606,7 +609,7 @@ ldt_id = models.CharField(max_length=255, unique=True) ldt = models.TextField(null=True) title = models.CharField(max_length=1024) - contents = models.ManyToManyField(Content) + contents = models.ManyToManyField("Content") creation_date = models.DateTimeField(auto_now_add=True) modification_date = models.DateTimeField(auto_now=True) created_by = models.CharField(_("created by"), max_length=70) @@ -616,6 +619,7 @@ image = ImageField(upload_to="thumbnails/projects/", default=settings.DEFAULT_PROJECT_ICON, max_length=200) class Meta: + app_label="ldt_utils" ordering = ["title"] permissions = ( ('view_project', 'Can view project'), @@ -791,8 +795,8 @@ class Segment(SafeModel): - project_obj = models.ForeignKey(Project, null=True) - content = models.ForeignKey(Content) + project_obj = models.ForeignKey("Project", null=True) + content = models.ForeignKey("Content") project_id = models.CharField(max_length=255, unique=False, blank=True, null=True, db_index=True) iri_id = models.CharField(max_length=255, unique=False, db_index=True) ensemble_id = models.CharField(max_length=512, unique=False, db_index=True) @@ -864,6 +868,7 @@ class Meta: + app_label="ldt_utils" permissions = ( ('view_segment', 'Can view segment'), ) diff -r f69b5d8ba4b9 -r 5087560b51b6 src/ldt/ldt/ldt_utils/projectserializer.py --- a/src/ldt/ldt/ldt_utils/projectserializer.py Fri Mar 27 18:07:56 2015 +0100 +++ b/src/ldt/ldt/ldt_utils/projectserializer.py Thu Apr 02 17:29:54 2015 +0200 @@ -7,7 +7,7 @@ from ldt.ldt_utils.stat import get_string_from_buckets from ldt.ldt_utils.utils import reduce_text_node import lxml.etree -import md5 +import hashlib import uuid User = get_user_model() @@ -231,8 +231,8 @@ tag_date = datetime.utcnow().isoformat() for tag_title in tags_list: if tag_title not in self.tags: - # md5 instead of uuid to get an almost unicity - tag_id = unicode(md5.new(tag_title.encode('utf-8')).hexdigest()) + # hashlib instead of uuid to get an almost unicity + tag_id = unicode(hashlib.new(tag_title.encode('utf-8')).hexdigest()) new_tag = { "id":tag_id, "meta" : { diff -r f69b5d8ba4b9 -r 5087560b51b6 src/ldt/ldt/ldt_utils/tests/__init__.py --- a/src/ldt/ldt/ldt_utils/tests/__init__.py Fri Mar 27 18:07:56 2015 +0100 +++ b/src/ldt/ldt/ldt_utils/tests/__init__.py Thu Apr 02 17:29:54 2015 +0200 @@ -1,4 +1,4 @@ -from content_tests import * -from ldt_tests import * -from media_tests import * -from project_tests import * +from tests_content import * +from tests_ldt import * +from tests_media import * +from tests_project import * diff -r f69b5d8ba4b9 -r 5087560b51b6 src/ldt/ldt/ldt_utils/tests/content_tests.py --- a/src/ldt/ldt/ldt_utils/tests/content_tests.py Fri Mar 27 18:07:56 2015 +0100 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,120 +0,0 @@ -""" -This file demonstrates two different styles of tests (one doctest and one -unittest). These will both pass when you run "manage.py test". - -Replace these with more appropriate tests for your application. -""" - -from django.conf import settings -from django.contrib.auth import get_user_model, create_superuser -from django.utils._os import WindowsError -from ldt.ldt_utils.models import Content, Media -from ldt.test.client import Client -from ldt.test.testcases import TestCase -import logging -import os - -User = get_user_model() - -class ContentTest(TestCase): - - fixtures = ['base_data.json', 'user_data.json'] - - def setUp(self): - self.client = Client() - create_superuser('blop', 'blop@blop.com', 'blop') - - _ = self.client.login(username='blop', password='blop') - - self.user = User() - self.user.username = 'blop' - - #test the creation of a content without media - def test_create_content_v1(self): - self.cont12 = Content(iriurl="id12/iriurl12", duration = 100) - self.cont12.iri_id = "id112" - self.cont12.save() - - self.assertEqual(Content.objects.get(iri_id=self.cont12.iri_id), self.cont12) - - #test the creation of a content with a media - def test_create_content_v2(self): - self.media13 = Media() - self.cont13 = Content(iriurl="id13/iriurl13", duration = 100, media_obj = self.media13) - self.cont13 = Content(iriurl="id13/iriurl13", duration = 100) - self.cont13.iri_id = "id113" - self.cont13.save() - - self.assertEqual(Content.objects.get(iri_id=self.cont13.iri_id), self.cont13) - - #test the creation of content without reading permission - def test_create_content_v3(self): - import sys - ldt_dir = os.path.join(settings.MEDIA_ROOT, "ldt") - if sys.platform == 'win32': - logging.debug("windows 3") - else: - logging.debug("linux") - os.chmod(ldt_dir, 0577) - - self.cont17 = Content(iriurl="id17/iriurl17", duration = 100) - self.cont17.iri_id = 'id117' - with self.assertRaises(WindowsError): - self.cont17.save() - with self.assertRaises(Content.DoesNotExist): - Content.objects.get(iri_id=self.cont17.iri_id) - - if sys.platform == 'win32': - logging.debug("windows 4") - else: - logging.debug("linux") - os.chmod(ldt_dir, 0700) - - #test the creation of content without reading permission - def test_create_content_v4(self): - import sys - ldt_dir = os.path.join(settings.MEDIA_ROOT, "ldt") - if sys.platform == 'win32': - logging.debug("windows 3") - else: - logging.debug("linux") - os.chmod(ldt_dir, 0377) - - self.cont18 = Content(iriurl="id18/iriurl18", duration = 100) - self.cont18.iri_id = 'id118' - with self.assertRaises(WindowsError): - self.cont18.save() - with self.assertRaises(Content.DoesNotExist): - Content.objects.get(iri_id=self.cont18.iri_id) - - if sys.platform == 'win32': - logging.debug("windows 4") - else: - logging.debug("linux") - os.chmod(ldt_dir, 0700) - - #test the deletion of a content without media - def test_del_content_v1(self): - self.cont14 = Content(iriurl="id14/iriurl14", duration = 100) - self.cont14.iri_id = "id114" - self.cont14.save() - - self.cont14.delete() - self.cont14.commit() - - with self.assertRaises(Content.DoesNotExist): - Content.objects.get(iri_id=self.cont14.iri_id) - - #test the deletion of a content with media - def test_del_content_v2(self): - self.media15 = Media() - self.cont15 = Content(iriurl="id15/iriurl15", duration = 100, media_obj = self.media15) - self.cont15.iri_id = "id115" - self.cont15.save() - - self.cont15.delete() - self.cont15.commit() - - with self.assertRaises(Content.DoesNotExist): - Content.objects.get(iri_id=self.cont15.iri_id) - \ No newline at end of file diff -r f69b5d8ba4b9 -r 5087560b51b6 src/ldt/ldt/ldt_utils/tests/ldt_tests.py --- a/src/ldt/ldt/ldt_utils/tests/ldt_tests.py Fri Mar 27 18:07:56 2015 +0100 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,167 +0,0 @@ -""" -This file demonstrates two different styles of tests (one doctest and one -unittest). These will both pass when you run "manage.py test". - -Replace these with more appropriate tests for your application. -""" - -from django.contrib.auth import get_user_model -from ldt.ldt_utils.models import Project, Content -from ldt.ldt_utils.utils import (LdtUtils, LdtAnnotation, create_ldt, - create_empty_iri, copy_ldt) -from ldt.test.client import Client -from ldt.test.testcases import TestCase -import base64 -import lxml.etree -import tempfile -import uuid - -User = get_user_model() - -class UtilsTest(TestCase): - - fixtures = ['base_data.json', 'user_data.json'] - - def setUp(self): - self.client = Client() - User.objects.create_superuser('blop', 'blop@blop.com', 'blop') - - _ = self.client.login(username='blop', password='blop') - - self.user = User() - self.user.username = 'blop' - - self.LU = LdtUtils() - self.project = Project(title="titleproj1", owner=self.user) - self.project.ldt = ' CA: prof et admin <abstract/> <audio source=""/> <tags/> </element> <element id="s_0050F043-3AD2-0A7C-6699-D2A03A1EBA02" begin="5052858" dur="124407" author="" date="2010/09/02" color="10053375" src=""> <title>conseil de classe Reprise de la figure precedente TC: prof et admin Conseil de classe conseil de classe Reprise de la figure precedente Bout a bout 1 ' - self.project.id = "11321" - self.project.ldt_id = str(uuid.uuid1()) - self.project.description = "proj1description" - self.project.save() - - self.projectcopy = Project(title="the2ndproject") - self.projectcopy.id = "21" - - def tearDown(self): - self.project.delete() - self.projectcopy.delete() - - def test_generate_ldt(self): - self.cont1 = Content(iriurl="cont1_id/iriurl1", duration=123) - self.cont1.iri_id = "cont1_id" - self.cont1.save() - - self.cont2 = Content(iriurl="cont2_id/iriurl2", duration=100) - self.cont2.iri_id = "cont2_id" - self.cont2.save() - - self.project.contents.add(self.cont1, self.cont2) - - f = tempfile.TemporaryFile(mode='r+') - doc = self.LU.generate_ldt(Content.objects.all()) - doc.write(f, pretty_print=True) - f.seek(0) - ldoc = lxml.etree.parse(f) - self.assertEqual(ldoc.xpath("/iri/displays/display/content")[0].get("id"), self.cont1.iri_id) - self.assertEqual(ldoc.xpath("/iri/medias/media")[0].get("id"), self.cont1.iri_id) - - self.assertEqual(ldoc.xpath("/iri/displays/display/content")[1].get("id"), self.cont2.iri_id) - self.assertEqual(ldoc.xpath("/iri/medias/media")[1].get("id"), self.cont2.iri_id) - f.close() - - def test_generate_init(self): - self.cont3 = Content(iriurl="id3/iriurl3", duration=111) - self.cont3.iri_id = "id3" - self.cont3.save() - - self.cont4 = Content(iriurl="id4/iriurl4", duration=111) - self.cont4.iri_id = "id4" - self.cont4.save() - - search='' - field='all' - query = base64.urlsafe_b64encode(search.encode('utf8')) - - self.project.contents.add(self.cont3, self.cont4) - ldoc = self.LU.generate_init({'field':field, 'query':query}, 'ldt.ldt_utils.views.lignesdetemps.search_ldt', 'ldt.ldt_utils.views.lignesdetemps.search_segments') - self.assertEqual(ldoc.xpath("/iri/files/init")[0].tag, "init") - self.assertEqual(ldoc.xpath("/iri/files/library")[0].tag, "library") - def test_create_ldt(self): - self.cont5 = Content(iriurl="id5/iriurl5", duration=111) - self.cont5.iri_id = "id5" - self.cont5.save() - - self.cont6 = Content(iriurl="id6/iriurl6", duration=111) - self.cont6.iri_id = "id6" - self.cont6.save() - - self.project.contents.add(self.cont5, self.cont6) - self.project.ldt = "" - create_ldt(self.project, self.user) - ldt = lxml.etree.fromstring(self.project.ldt_encoded) - self.assertEqual(ldt.xpath("/iri")[0].tag, "iri") - self.assertEqual(ldt.xpath("/iri/project")[0].get("title"), self.project.title) - self.assertEqual(ldt.xpath("/iri/medias/media")[0].get("src"), self.cont5.relative_iri_url()) - self.assertEqual(ldt.xpath("/iri/medias/media")[1].get("id"), self.cont6.iri_id) - - def test_copy_ldt(self): - self.cont7 = Content(iriurl="id7/iriurl7", duration=111) - self.cont7.iri_id = "id7" - self.cont7.save() - - self.cont8 = Content(iriurl="id8/iriurl8", duration=111) - self.cont8.iri_id = "id8" - self.cont8.save() - - self.project.contents.add(self.cont7, self.cont8) - copy_ldt(self.project, self.projectcopy, self.user) - ldt1 = lxml.etree.fromstring(self.project.ldt_encoded) - ldt2 = lxml.etree.fromstring(self.projectcopy.ldt_encoded) - self.assertTrue(ldt1.xpath("/iri/project")[0].get("id") != ldt2.xpath("/iri/project")[0].get("id")) - self.assertEqual(ldt1.xpath("/iri/medias/media")[0].get("id"), ldt2.xpath("/iri/medias/media")[0].get("id")) - self.assertEqual(ldt1.xpath("/iri/annotations/content/ensemble")[0].get("title"), ldt2.xpath("/iri/annotations/content/ensemble")[0].get("title")) - self.assertEqual(ldt1.xpath("/iri/annotations/content/ensemble/decoupage")[0].get("id"), ldt2.xpath("/iri/annotations/content/ensemble/decoupage")[0].get("id")) - self.assertEqual(ldt1.xpath("/iri/annotations/content/ensemble/decoupage/title")[1].text, ldt2.xpath("/iri/annotations/content/ensemble/decoupage/title")[1].text.strip("\n\t")) - - def test_create_empty_iri(self): - self.cont9 = Content(iriurl="id9/iriurl9", duration=111) - self.cont9.iri_id = "id9" - self.cont9.save() - - self.cont10 = Content(iriurl="id10/iriurl10", duration=111) - self.cont10.iri_id = "id10" - self.cont10.save() - - self.project.contents.add(self.cont9, self.cont10) - tmp = tempfile.TemporaryFile(mode='r+') - create_empty_iri(tmp, self.cont9, "admin") - tmp.seek(0) - ldoc = lxml.etree.parse(tmp) - self.assertEqual(ldoc.xpath("/iri/head/meta")[0].get("content"), self.cont9.iri_id) - self.assertEqual(ldoc.xpath("/iri/body/medias/media/video")[0].get("id"), self.cont9.iri_id) - tmp.close() - - def test_add_annotation(self): - - self.cont11 = Content(iriurl="id11/iriurl11", duration=111) - self.cont11.iri_id = "id11" - self.cont11.save() - - self.project.contents.add(self.cont11) - self.project.ldt = "" - create_ldt(self.project, self.user) - - self.LA = LdtAnnotation(self.project) - - self.LA.add("id11", "cutting_id", "cutting_title", "title", "text", ["tag1", "tag2"], "800", - "10000", "jdoe", "2011-09-10T09:12:58") - self.LA.save() - ldt = lxml.etree.fromstring(self.project.ldt) - ann = ldt.xpath('/iri/annotations/content[@id="id11"]/ensemble/decoupage/elements/element')[0] - title = ann.xpath('title')[0].text - abstract = ann.xpath('abstract')[0].text - - self.assertEqual(ann.get("author"), "jdoe") - self.assertEqual(title, "title") - self.assertEqual(abstract, "text") - \ No newline at end of file diff -r f69b5d8ba4b9 -r 5087560b51b6 src/ldt/ldt/ldt_utils/tests/media_tests.py --- a/src/ldt/ldt/ldt_utils/tests/media_tests.py Fri Mar 27 18:07:56 2015 +0100 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,44 +0,0 @@ -""" -This file demonstrates two different styles of tests (one doctest and one -unittest). These will both pass when you run "manage.py test". - -Replace these with more appropriate tests for your application. -""" - -from django.contrib.auth import get_user_model -from ldt.ldt_utils.models import Media -from ldt.test.client import Client -from ldt.test.testcases import TestCase - -User = get_user_model() - -class MediaTest(TestCase): - - fixtures = ['base_data.json', 'user_data.json'] - - def setUp(self): - self.client = Client() - User.objects.create_superuser('blop', 'blop@blop.com', 'blop') - - _ = self.client.login(username='blop', password='blop') - - self.user = User() - self.user.username = 'blop' - - def test_create_media(self): - self.media1, _ = Media.objects.get_or_create(src = "http://www.youtube.com/watch?v=O2G-PEtyKSY") - self.media1.id = 1 - self.media1.save() - - self.assertEqual(Media.objects.get(id=self.media1.id), self.media1) - - def test_del_media(self): - self.media2 = Media() - self.media2.id = 2 - self.media2.save() - - self.media2.delete() - - with self.assertRaises(Media.DoesNotExist): - Media.objects.get(id=self.media2.id) - \ No newline at end of file diff -r f69b5d8ba4b9 -r 5087560b51b6 src/ldt/ldt/ldt_utils/tests/project_tests.py --- a/src/ldt/ldt/ldt_utils/tests/project_tests.py Fri Mar 27 18:07:56 2015 +0100 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,170 +0,0 @@ -""" -This file demonstrates two different styles of tests (one doctest and one -unittest). These will both pass when you run "manage.py test". - -Replace these with more appropriate tests for your application. -""" - -from django.contrib.auth import get_user_model -from django.core.management import call_command -from ldt.ldt_utils.models import Project, Content -from ldt.ldt_utils.utils import LdtUtils, LdtAnnotation, create_ldt -from ldt.test.client import Client -from ldt.test.testcases import TestCase -import lxml.etree -import uuid - -User = get_user_model() - -class ProjectTest(TestCase): - - fixtures = ['base_data.json', 'user_data.json'] - - def setUp(self): - self.client = Client() - User.objects.create_superuser('blop', 'blop@blop.com', 'blop') - - _ = self.client.login(username='blop', password='blop') - self.user = User() - self.user.username = 'blop' - self.LU = LdtUtils() - self.project = Project(title="titleproj1", owner=self.user) - self.project.ldt = ' CA: prof et admin <abstract/> <audio source=""/> <tags/> </element> <element id="s_0050F043-3AD2-0A7C-6699-D2A03A1EBA02" begin="5052858" dur="124407" author="" date="2010/09/02" color="10053375" src=""> <title>conseil de classe Reprise de la figure precedente TC: prof et admin Conseil de classe conseil de classe Reprise de la figure precedente Bout a bout 1 ' - self.project.id = "11321" - self.project.ldt_id = str(uuid.uuid1()) - self.project.description = "proj1description" - self.project.save() - - def test_create_project(self): - self.cont1 = Content(iriurl="cont1_id/iriurl1", duration=123) - self.cont1.iri_id = "cont1_id" - self.cont1.save() - - self.cont2 = Content(iriurl="cont2_id/iriurl2", duration=100) - self.cont2.iri_id = "cont2_id" - self.cont2.save() - - self.project2 = Project(title="titleproj2", owner=self.user) - - self.project2.ldt = self.LU.generate_ldt(Content.objects.all()) - self.project2.ldt_id = str(uuid.uuid1()) - self.project2.description = "proj2description" - self.project2.save() - - self.assertEqual(Project.objects.get(ldt_id=self.project2.ldt_id), self.project2) - - #test deletion of project without annotation - def test_del_project_v1(self): - self.cont3 = Content(iriurl="cont3_id/iriurl3", duration=100) - self.cont3.iri_id = "cont3_id" - self.cont3.save() - - self.project3 = Project(title="titleproj3", owner=self.user) - self.project3.ldt = self.LU.generate_ldt(Content.objects.all()) - self.project3.id = "333" - self.project3.ldt_id = str(uuid.uuid1()) - self.project3.description = "proj3description" - self.project3.save() - - self.project3.delete() - - with self.assertRaises(Project.DoesNotExist): - Project.objects.get(ldt_id=self.project3.ldt_id) - - #test deletion of project with annotations - def test_del_project_v2(self): - self.cont4 = Content(iriurl="cont4_id/iriurl4", duration=100) - self.cont4.iri_id = "cont4_id" - self.cont4.save() - - self.project4 = Project(title="titleproj4", owner=self.user) - self.project4.ldt=self.LU.generate_ldt(Content.objects.all()) - self.project4.id = "444" - self.project4.ldt_id = str(uuid.uuid1()) - self.project4.description = "proj4description" - self.project4.save() - - create_ldt(self.project4, self.user) - - self.LA = LdtAnnotation(self.project4) - - self.LA.add("id11", "cutting_id", "cutting_title", "title", "text", ["tag1", "tag2"], "800", - "10000", "jdoe", "2011-09-10T09:12:58") - self.LA.save() - - self.project4.delete() - - with self.assertRaises(Project.DoesNotExist): - Project.objects.get(ldt_id=self.project4.ldt_id) - - def test_clean_database_project(self) : - self.cont5 = Content(iriurl="cont5_id/iriurl5", duration=123) - self.cont5.iri_id = "cont5_id" - self.cont5.save() - - self.cont6 = Content(iriurl="cont6_id/iriurl6", duration=100) - self.cont6.iri_id = "cont6_id" - self.cont6.save() - - self.cont7 = Content(iriurl="cont7_id/iriurl7", duration=100) - self.cont7.iri_id = "cont7_id" - self.cont7.save() - - self.project.contents.add(self.cont5, self.cont6) - - doc = self.LU.generate_ldt(Content.objects.all()) - - #project5 : valid project - self.project5 = Project(title="titleproj5", owner=self.user) - ldt = lxml.etree.tostring(doc, pretty_print = False) - self.project5.ldt = ldt - self.project5.id = "555" - self.project5.ldt_id = str(uuid.uuid1()) - self.project5.description = "proj5description" - self.project5.save() - - #project6 : project with empty ldt - self.project6 = Project(title="titleproj5", owner=self.user) - self.project6.id = "666" - self.project6.ldt_id = str(uuid.uuid1()) - self.project6.description = "proj6description" - self.project6.save() - - #project7 : project with a non-existing media - - self.project7 = Project(title="titleproj7", owner=self.user) - self.project7.id = "777" - self.project7.ldt_id = str(uuid.uuid1()) - self.project7.ldt = '' - self.project7.description = "proj7description" - self.project7.save() - - #project8 : project with multiple medias some valid and some that don't exist - self.project8 = Project(title="titleproj8", owner=self.user) - self.project8.id = "888" - self.project8.ldt_id = str(uuid.uuid1()) - self.project8.ldt = '' - self.project8.description = "proj8description" - self.project8.save() - - #project9 : project without any media - self.project9 = Project(title="titleproj9", owner=self.user) - self.project9.id = "999" - self.project9.ldt_id = str(uuid.uuid1()) - self.project9.ldt = '' - self.project9.description = "proj9description" - self.project9.save() - - call_command('set_projectldtiri') - - with self.assertRaises(Project.DoesNotExist): - Project.objects.get(ldt_id=self.project6.ldt_id) - - with self.assertRaises(Project.DoesNotExist): - Project.objects.get(ldt_id=self.project7.ldt_id) - - with self.assertRaises(Project.DoesNotExist): - Project.objects.get(ldt_id=self.project9.ldt_id) - - self.assertEqual(ldt, self.project5.ldt) - \ No newline at end of file diff -r f69b5d8ba4b9 -r 5087560b51b6 src/ldt/ldt/ldt_utils/tests/tests_content.py --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/ldt/ldt/ldt_utils/tests/tests_content.py Thu Apr 02 17:29:54 2015 +0200 @@ -0,0 +1,122 @@ +""" +This file demonstrates two different styles of tests (one doctest and one +unittest). These will both pass when you run "manage.py test". + +Replace these with more appropriate tests for your application. +""" + +import logging +import os + +from django.conf import settings +from django.contrib.auth import get_user_model +from django.contrib.auth.models import User +from django.utils._os import WindowsError + +from ldt.ldt_utils.models import Content, Media +from ldt.test.client import Client +from ldt.test.testcases import TestCase + + +logger = logging.getLogger(__name__) + +User = get_user_model() + +class ContentTest(TestCase): + + fixtures = ['testing_sites_data.json', 'user_data.json'] + + def setUp(self): + self.client = Client() + + self.user = User.objects.create_superuser('blop', 'blop@blop.com', 'blop') + self.user.username = 'blop' + + _ = self.client.login(username='blop', password='blop') + + #test the creation of a content without media + def test_create_content_v1(self): + self.cont12 = Content(iriurl="id12/iriurl12", duration = 100) + self.cont12.iri_id = "id12" + self.cont12.save() + self.assertEqual(Content.objects.get(iri_id=self.cont12.iri_id), self.cont12) + + #test the creation of a content with a media + def test_create_content_v2(self): + self.media13 = Media() + self.cont13 = Content(iriurl="id13/iriurl13", duration = 100, media_obj = self.media13) + self.cont13 = Content(iriurl="id13/iriurl13", duration = 100) + self.cont13.iri_id = "id13" + self.cont13.save() + + self.assertEqual(Content.objects.get(iri_id=self.cont13.iri_id), self.cont13) + + #test the creation of content without writing permission, should fail + def test_create_content_v3(self): + import sys + ldt_dir = os.path.join(settings.MEDIA_ROOT, "ldt") + if sys.platform == 'win32': + logging.debug("windows 3") + else: + logging.debug("linux") + os.chmod(ldt_dir, 0577) + + self.cont17 = Content(iriurl="id17/iriurl17", duration = 100) + self.cont17.iri_id = 'id17' + with self.assertRaises(OSError): + self.cont17.save() + with self.assertRaises(Content.DoesNotExist): + Content.objects.get(iri_id=self.cont17.iri_id) + + if sys.platform == 'win32': + logging.debug("windows 4") + else: + logging.debug("linux") + os.chmod(ldt_dir, 0700) + + #test the creation of content without reading permission on the directory where the content file is created, should pass + def test_create_content_v4(self): + import sys + ldt_dir = os.path.join(settings.MEDIA_ROOT, "ldt") + if sys.platform == 'win32': + logging.debug("windows 3") + else: + logging.debug("linux") + os.chmod(ldt_dir, 0377) + + self.cont18 = Content(iriurl="id18/iriurl18", duration = 100) + self.cont18.iri_id = 'id18' + self.cont18.save() + self.assertEqual(Content.objects.get(iri_id=self.cont18.iri_id), self.cont18) + + if sys.platform == 'win32': + logging.debug("windows 4") + else: + logging.debug("linux") + os.chmod(ldt_dir, 0700) + + #test the deletion of a content without media + def test_del_content_v1(self): + self.cont14 = Content(iriurl="id14/iriurl14", duration = 100) + self.cont14.iri_id = "id14" + self.cont14.save() + + self.cont14.delete() + self.cont14.commit() + + with self.assertRaises(Content.DoesNotExist): + Content.objects.get(iri_id=self.cont14.iri_id) + + #test the deletion of a content with media + def test_del_content_v2(self): + self.media15 = Media() + self.cont15 = Content(iriurl="id15/iriurl15", duration = 100, media_obj = self.media15) + self.cont15.iri_id = "id15" + self.cont15.save() + + self.cont15.delete() + self.cont15.commit() + + with self.assertRaises(Content.DoesNotExist): + Content.objects.get(iri_id=self.cont15.iri_id) + \ No newline at end of file diff -r f69b5d8ba4b9 -r 5087560b51b6 src/ldt/ldt/ldt_utils/tests/tests_ldt.py --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/ldt/ldt/ldt_utils/tests/tests_ldt.py Thu Apr 02 17:29:54 2015 +0200 @@ -0,0 +1,170 @@ +""" +This file demonstrates two different styles of tests (one doctest and one +unittest). These will both pass when you run "manage.py test". + +Replace these with more appropriate tests for your application. +""" + +import base64 +import lxml.etree +import tempfile +import uuid + +from django.contrib.auth import get_user_model + +from ldt.ldt_utils.models import Project, Content +from ldt.ldt_utils.utils import (LdtUtils, LdtAnnotation, create_ldt, + create_empty_iri, copy_ldt) +from ldt.test.client import Client +from ldt.test.testcases import TestCase + + +User = get_user_model() + +class UtilsTest(TestCase): + + fixtures = ['testing_sites_data.json', 'user_data.json'] + + def setUp(self): + self.client = Client() + User.objects.create_superuser('blop', 'blop@blop.com', 'blop') + + _ = self.client.login(username='blop', password='blop') + + self.user = User() + self.user.username = 'blop' + + self.LU = LdtUtils() + self.project = Project(title="titleproj1", owner=self.user) + self.project.ldt = ' CA: prof et admin <abstract/> <audio source=""/> <tags/> </element> <element id="s_0050F043-3AD2-0A7C-6699-D2A03A1EBA02" begin="5052858" dur="124407" author="" date="2010/09/02" color="10053375" src=""> <title>conseil de classe Reprise de la figure precedente TC: prof et admin Conseil de classe conseil de classe Reprise de la figure precedente Bout a bout 1 ' + self.project.id = "11321" + self.project.ldt_id = str(uuid.uuid1()) + self.project.description = "proj1description" + self.project.save() + + self.projectcopy = Project(title="the2ndproject") + self.projectcopy.id = "21" + + def tearDown(self): + self.project.delete() + self.projectcopy.delete() + + def test_generate_ldt(self): + self.cont1 = Content(iriurl="cont1_id/iriurl1", duration=123) + self.cont1.iri_id = "cont1_id" + self.cont1.save() + + self.cont2 = Content(iriurl="cont2_id/iriurl2", duration=100) + self.cont2.iri_id = "cont2_id" + self.cont2.save() + + self.project.contents.add(self.cont1, self.cont2) + + f = tempfile.TemporaryFile(mode='r+') + doc = self.LU.generate_ldt(Content.objects.all()) + doc.write(f, pretty_print=True) + f.seek(0) + ldoc = lxml.etree.parse(f) + self.assertEqual(ldoc.xpath("/iri/displays/display/content")[0].get("id"), self.cont1.iri_id) + self.assertEqual(ldoc.xpath("/iri/medias/media")[0].get("id"), self.cont1.iri_id) + + self.assertEqual(ldoc.xpath("/iri/displays/display/content")[1].get("id"), self.cont2.iri_id) + self.assertEqual(ldoc.xpath("/iri/medias/media")[1].get("id"), self.cont2.iri_id) + f.close() + + def test_generate_init(self): + self.cont3 = Content(iriurl="id3/iriurl3", duration=111) + self.cont3.iri_id = "id3" + self.cont3.save() + + self.cont4 = Content(iriurl="id4/iriurl4", duration=111) + self.cont4.iri_id = "id4" + self.cont4.save() + + search='' + field='all' + query = base64.urlsafe_b64encode(search.encode('utf8')) + + self.project.contents.add(self.cont3, self.cont4) + ldoc = self.LU.generate_init({'field':field, 'query':query}, 'ldt.ldt_utils.views.lignesdetemps.search_ldt', 'ldt.ldt_utils.views.lignesdetemps.search_segments') + self.assertEqual(ldoc.xpath("/iri/files/init")[0].tag, "init") + self.assertEqual(ldoc.xpath("/iri/files/library")[0].tag, "library") + def test_create_ldt(self): + self.cont5 = Content(iriurl="id5/iriurl5", duration=111) + self.cont5.iri_id = "id5" + self.cont5.save() + + self.cont6 = Content(iriurl="id6/iriurl6", duration=111) + self.cont6.iri_id = "id6" + self.cont6.save() + + self.project.contents.add(self.cont5, self.cont6) + self.project.ldt = "" + create_ldt(self.project, self.user) + ldt = lxml.etree.fromstring(self.project.ldt_encoded) + self.assertEqual(ldt.xpath("/iri")[0].tag, "iri") + self.assertEqual(ldt.xpath("/iri/project")[0].get("title"), self.project.title) + self.assertEqual(ldt.xpath("/iri/medias/media")[0].get("src"), self.cont5.relative_iri_url()) + self.assertEqual(ldt.xpath("/iri/medias/media")[1].get("id"), self.cont6.iri_id) + + def test_copy_ldt(self): + self.cont7 = Content(iriurl="id7/iriurl7", duration=111) + self.cont7.iri_id = "id7" + self.cont7.save() + + self.cont8 = Content(iriurl="id8/iriurl8", duration=111) + self.cont8.iri_id = "id8" + self.cont8.save() + + self.project.contents.add(self.cont7, self.cont8) + copy_ldt(self.project, self.projectcopy, self.user) + ldt1 = lxml.etree.fromstring(self.project.ldt_encoded) + ldt2 = lxml.etree.fromstring(self.projectcopy.ldt_encoded) + self.assertTrue(ldt1.xpath("/iri/project")[0].get("id") != ldt2.xpath("/iri/project")[0].get("id")) + self.assertEqual(ldt1.xpath("/iri/medias/media")[0].get("id"), ldt2.xpath("/iri/medias/media")[0].get("id")) + self.assertEqual(ldt1.xpath("/iri/annotations/content/ensemble")[0].get("title"), ldt2.xpath("/iri/annotations/content/ensemble")[0].get("title")) + self.assertEqual(ldt1.xpath("/iri/annotations/content/ensemble/decoupage")[0].get("id"), ldt2.xpath("/iri/annotations/content/ensemble/decoupage")[0].get("id")) + self.assertEqual(ldt1.xpath("/iri/annotations/content/ensemble/decoupage/title")[1].text, ldt2.xpath("/iri/annotations/content/ensemble/decoupage/title")[1].text.strip("\n\t")) + + def test_create_empty_iri(self): + self.cont9 = Content(iriurl="id9/iriurl9", duration=111) + self.cont9.iri_id = "id9" + self.cont9.save() + + self.cont10 = Content(iriurl="id10/iriurl10", duration=111) + self.cont10.iri_id = "id10" + self.cont10.save() + + self.project.contents.add(self.cont9, self.cont10) + tmp = tempfile.TemporaryFile(mode='r+') + create_empty_iri(tmp, self.cont9, "admin") + tmp.seek(0) + ldoc = lxml.etree.parse(tmp) + self.assertEqual(ldoc.xpath("/iri/head/meta")[0].get("content"), self.cont9.iri_id) + self.assertEqual(ldoc.xpath("/iri/body/medias/media/video")[0].get("id"), self.cont9.iri_id) + tmp.close() + + def test_add_annotation(self): + + self.cont11 = Content(iriurl="id11/iriurl11", duration=111) + self.cont11.iri_id = "id11" + self.cont11.save() + + self.project.contents.add(self.cont11) + self.project.ldt = "" + create_ldt(self.project, self.user) + + self.LA = LdtAnnotation(self.project) + + self.LA.add("id11", "cutting_id", "cutting_title", "title", "text", ["tag1", "tag2"], "800", + "10000", "jdoe", "2011-09-10T09:12:58") + self.LA.save() + ldt = lxml.etree.fromstring(self.project.ldt) + ann = ldt.xpath('/iri/annotations/content[@id="id11"]/ensemble/decoupage/elements/element')[0] + title = ann.xpath('title')[0].text + abstract = ann.xpath('abstract')[0].text + + self.assertEqual(ann.get("author"), "jdoe") + self.assertEqual(title, "title") + self.assertEqual(abstract, "text") + \ No newline at end of file diff -r f69b5d8ba4b9 -r 5087560b51b6 src/ldt/ldt/ldt_utils/tests/tests_media.py --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/ldt/ldt/ldt_utils/tests/tests_media.py Thu Apr 02 17:29:54 2015 +0200 @@ -0,0 +1,43 @@ +""" +This file demonstrates two different styles of tests (one doctest and one +unittest). These will both pass when you run "manage.py test". + +Replace these with more appropriate tests for your application. +""" + +from django.contrib.auth import get_user_model + +from ldt.ldt_utils.models import Media +from ldt.test.client import Client +from ldt.test.testcases import TestCase + + +User = get_user_model() + +class MediaTest(TestCase): + + fixtures = ['testing_sites_data.json', 'user_data.json'] + + def setUp(self): + self.client = Client() + User.objects.create_superuser('blop', 'blop@blop.com', 'blop') + + _ = self.client.login(username='blop', password='blop') + + self.user = User() + self.user.username = 'blop' + + def test_create_media(self): + self.media1, created = Media.objects.get_or_create(src = "http://www.youtube.com/watch?v=O2G-PEtyKSY", id = 1) + self.assertEqual(Media.objects.get(id=self.media1.id), self.media1) + + def test_del_media(self): + self.media2 = Media() + self.media2.id = 2 + self.media2.save() + + self.media2.delete() + + with self.assertRaises(Media.DoesNotExist): + Media.objects.get(id=self.media2.id) + \ No newline at end of file diff -r f69b5d8ba4b9 -r 5087560b51b6 src/ldt/ldt/ldt_utils/tests/tests_project.py --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/ldt/ldt/ldt_utils/tests/tests_project.py Thu Apr 02 17:29:54 2015 +0200 @@ -0,0 +1,173 @@ +""" +This file demonstrates two different styles of tests (one doctest and one +unittest). These will both pass when you run "manage.py test". + +Replace these with more appropriate tests for your application. +""" + +import lxml.etree +import uuid + +from django.contrib.auth import get_user_model +from django.core.management import call_command + +from ldt.ldt_utils.models import Project, Content +from ldt.ldt_utils.utils import LdtUtils, LdtAnnotation, create_ldt +from ldt.test.client import Client +from ldt.test.testcases import TestCase + + +User = get_user_model() + +class ProjectTest(TestCase): + + fixtures = ['testing_sites_data.json', 'user_data.json'] + + def setUp(self): + self.client = Client() + User.objects.create_superuser('blop', 'blop@blop.com', 'blop') + + _ = self.client.login(username='blop', password='blop') + self.user = User() + self.user.username = 'blop' + self.LU = LdtUtils() + self.project = Project(title="titleproj1", owner=self.user) + self.project.ldt = ' CA: prof et admin <abstract/> <audio source=""/> <tags/> </element> <element id="s_0050F043-3AD2-0A7C-6699-D2A03A1EBA02" begin="5052858" dur="124407" author="" date="2010/09/02" color="10053375" src=""> <title>conseil de classe Reprise de la figure precedente TC: prof et admin Conseil de classe conseil de classe Reprise de la figure precedente Bout a bout 1 ' + self.project.id = "11321" + self.project.ldt_id = str(uuid.uuid1()) + self.project.description = "proj1description" + self.project.save() + + def test_create_project(self): + self.cont1 = Content(iriurl="cont1_id/iriurl1", duration=123) + self.cont1.iri_id = "cont1_id" + self.cont1.save() + + self.cont2 = Content(iriurl="cont2_id/iriurl2", duration=100) + self.cont2.iri_id = "cont2_id" + self.cont2.save() + + self.project2 = Project(title="titleproj2", owner=self.user) + + self.project2.ldt = self.LU.generate_ldt(Content.objects.all()) + self.project2.ldt_id = str(uuid.uuid1()) + self.project2.description = "proj2description" + self.project2.save() + + self.assertEqual(Project.objects.get(ldt_id=self.project2.ldt_id), self.project2) + + #test deletion of project without annotation + def test_del_project_v1(self): + self.cont3 = Content(iriurl="cont3_id/iriurl3", duration=100) + self.cont3.iri_id = "cont3_id" + self.cont3.save() + + self.project3 = Project(title="titleproj3", owner=self.user) + self.project3.ldt = self.LU.generate_ldt(Content.objects.all()) + self.project3.id = "333" + self.project3.ldt_id = str(uuid.uuid1()) + self.project3.description = "proj3description" + self.project3.save() + + self.project3.delete() + + with self.assertRaises(Project.DoesNotExist): + Project.objects.get(ldt_id=self.project3.ldt_id) + + #test deletion of project with annotations + def test_del_project_v2(self): + self.cont4 = Content(iriurl="cont4_id/iriurl4", duration=100) + self.cont4.iri_id = "cont4_id" + self.cont4.save() + + self.project4 = Project(title="titleproj4", owner=self.user) + self.project4.ldt=self.LU.generate_ldt(Content.objects.all()) + self.project4.id = "444" + self.project4.ldt_id = str(uuid.uuid1()) + self.project4.description = "proj4description" + self.project4.save() + + create_ldt(self.project4, self.user) + + self.LA = LdtAnnotation(self.project4) + + self.LA.add("id11", "cutting_id", "cutting_title", "title", "text", ["tag1", "tag2"], "800", + "10000", "jdoe", "2011-09-10T09:12:58") + self.LA.save() + + self.project4.delete() + + with self.assertRaises(Project.DoesNotExist): + Project.objects.get(ldt_id=self.project4.ldt_id) + + def test_clean_database_project(self) : + self.cont5 = Content(iriurl="cont5_id/iriurl5", duration=123) + self.cont5.iri_id = "cont5_id" + self.cont5.save() + + self.cont6 = Content(iriurl="cont6_id/iriurl6", duration=100) + self.cont6.iri_id = "cont6_id" + self.cont6.save() + + self.cont7 = Content(iriurl="cont7_id/iriurl7", duration=100) + self.cont7.iri_id = "cont7_id" + self.cont7.save() + + self.project.contents.add(self.cont5, self.cont6) + + doc = self.LU.generate_ldt(Content.objects.all()) + + #project5 : valid project + self.project5 = Project(title="titleproj5", owner=self.user) + ldt = lxml.etree.tostring(doc, pretty_print = False) + self.project5.ldt = ldt + self.project5.id = "555" + self.project5.ldt_id = str(uuid.uuid1()) + self.project5.description = "proj5description" + self.project5.save() + + #project6 : project with empty ldt + self.project6 = Project(title="titleproj5", owner=self.user) + self.project6.id = "666" + self.project6.ldt_id = str(uuid.uuid1()) + self.project6.description = "proj6description" + self.project6.save() + + #project7 : project with a non-existing media + + self.project7 = Project(title="titleproj7", owner=self.user) + self.project7.id = "777" + self.project7.ldt_id = str(uuid.uuid1()) + self.project7.ldt = '' + self.project7.description = "proj7description" + self.project7.save() + + #project8 : project with multiple medias some valid and some that don't exist + self.project8 = Project(title="titleproj8", owner=self.user) + self.project8.id = "888" + self.project8.ldt_id = str(uuid.uuid1()) + self.project8.ldt = '' + self.project8.description = "proj8description" + self.project8.save() + + #project9 : project without any media + self.project9 = Project(title="titleproj9", owner=self.user) + self.project9.id = "999" + self.project9.ldt_id = str(uuid.uuid1()) + self.project9.ldt = '' + self.project9.description = "proj9description" + self.project9.save() + + call_command('setprojectldtiri') + + with self.assertRaises(Project.DoesNotExist): + Project.objects.get(ldt_id=self.project6.ldt_id) + + with self.assertRaises(Project.DoesNotExist): + Project.objects.get(ldt_id=self.project7.ldt_id) + + with self.assertRaises(Project.DoesNotExist): + Project.objects.get(ldt_id=self.project9.ldt_id) + + self.assertEqual(ldt, self.project5.ldt) + \ No newline at end of file diff -r f69b5d8ba4b9 -r 5087560b51b6 src/ldt/ldt/ldt_utils/tests/tests_view.py --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/ldt/ldt/ldt_utils/tests/tests_view.py Thu Apr 02 17:29:54 2015 +0200 @@ -0,0 +1,31 @@ +""" +This file demonstrates two different styles of tests (one doctest and one +unittest). These will both pass when you run "manage.py test". + +Replace these with more appropriate tests for your application. +""" + +import unittest + +from ldt.ldt_utils.models import Project, Content + + +class ViewsTest(unittest.TestCase): + def setUp(self): + self.project = Project() + self.project.id = "121" + self.project.save() + self.project.ldt = ' CA: prof et admin <abstract/> <audio source=""/> <tags/> </element> <element id="s_0050F043-3AD2-0A7C-6699-D2A03A1EBA02" begin="5052858" dur="124407" author="" date="2010/09/02" color="10053375" src=""> <title>conseil de classe Reprise de la figure precedente TC: prof et admin Conseil de classe conseil de classe Reprise de la figure precedente Bout a bout 1 ' + + self.cont1 = Content(iriurl="/laurentcantet_entrelesmurs/iriurl1") + self.cont1.iri_id = 'laurentcantet_entrelesmurs' + self.cont1.save() + + self.cont2 = Content(iriurl="/content_notinldt/iriurl2") + self.cont2.iri_id = 'content_notinldt' + self.cont2.save() + + self.project.contents.add(self.cont1, self.cont2) + + def tearDown(self): + self.project.delete() diff -r f69b5d8ba4b9 -r 5087560b51b6 src/ldt/ldt/ldt_utils/tests/view_tests.py --- a/src/ldt/ldt/ldt_utils/tests/view_tests.py Fri Mar 27 18:07:56 2015 +0100 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,29 +0,0 @@ -""" -This file demonstrates two different styles of tests (one doctest and one -unittest). These will both pass when you run "manage.py test". - -Replace these with more appropriate tests for your application. -""" - -from ldt.ldt_utils.models import Project, Content -import unittest - -class ViewsTest(unittest.TestCase): - def setUp(self): - self.project = Project() - self.project.id = "121" - self.project.save() - self.project.ldt = ' CA: prof et admin <abstract/> <audio source=""/> <tags/> </element> <element id="s_0050F043-3AD2-0A7C-6699-D2A03A1EBA02" begin="5052858" dur="124407" author="" date="2010/09/02" color="10053375" src=""> <title>conseil de classe Reprise de la figure precedente TC: prof et admin Conseil de classe conseil de classe Reprise de la figure precedente Bout a bout 1 ' - - self.cont1 = Content(iriurl="/laurentcantet_entrelesmurs/iriurl1") - self.cont1.iri_id = 'laurentcantet_entrelesmurs' - self.cont1.save() - - self.cont2 = Content(iriurl="/content_notinldt/iriurl2") - self.cont2.iri_id = 'content_notinldt' - self.cont2.save() - - self.project.contents.add(self.cont1, self.cont2) - - def tearDown(self): - self.project.delete() diff -r f69b5d8ba4b9 -r 5087560b51b6 src/ldt/ldt/ldt_utils/utils.py --- a/src/ldt/ldt/ldt_utils/utils.py Fri Mar 27 18:07:56 2015 +0100 +++ b/src/ldt/ldt/ldt_utils/utils.py Thu Apr 02 17:29:54 2015 +0200 @@ -8,6 +8,9 @@ from ldt.utils.url import request_with_auth from ldt.utils.url import absurl_norequest +import logging +logger = logging.getLogger(__name__) + __BOOLEAN_DICT = { 'false':False, 'true':True, @@ -350,13 +353,14 @@ for content in contentList: elementContent = lxml.etree.SubElement(elementDisplay, 'content') elementContent.set('id', content.iri_id) - if not 'http' in content.iriurl: #eg: "iiiielizabethrosse/ENMI08-III_elizabethrosse.iri" url = content.iri_url() else: url = content.iriurl + __, content = request_with_auth(url) + #logger.debug(content) doc = lxml.etree.parse(StringIO(content)) res = doc.xpath("/iri/body/ensembles/ensemble/decoupage") diff -r f69b5d8ba4b9 -r 5087560b51b6 src/ldt/ldt/ldt_utils/views/json.py --- a/src/ldt/ldt/ldt_utils/views/json.py Fri Mar 27 18:07:56 2015 +0100 +++ b/src/ldt/ldt/ldt_utils/views/json.py Thu Apr 02 17:29:54 2015 +0200 @@ -1,18 +1,21 @@ # -*- coding: utf-8 -*- +from datetime import datetime +import json +import logging +import lxml.etree +from operator import itemgetter + from django.conf import settings from django.http import HttpResponse, HttpResponseForbidden from django.shortcuts import get_object_or_404, get_list_or_404 -from django.utils import simplejson from django.utils.html import escape from django.utils.translation import ugettext as _ + +import ldt.auth as ldt_auth from ldt.ldt_utils.models import Project from ldt.ldt_utils.projectserializer import ProjectJsonSerializer from ldt.ldt_utils.searchutils import search_generate_ldt -from operator import itemgetter -from datetime import datetime -import ldt.auth as ldt_auth -import lxml.etree -import logging + logger = logging.getLogger(__name__) @@ -74,7 +77,7 @@ ps = ProjectJsonSerializer(project, serialize_contents, first_cutting=first_cutting) project_dict = ps.serialize_to_cinelab(one_content_bool) - json_str = simplejson.dumps(project_dict, ensure_ascii=False, indent=indent) + json_str = json.dumps(project_dict, ensure_ascii=False, indent=indent) if callback is not None: json_str = "%s(%s)" % (callback, json_str) @@ -209,7 +212,7 @@ mashup_dict["annotations"].remove(a) - json_str = simplejson.dumps(mashup_dict, ensure_ascii=False, indent=indent) + json_str = json.dumps(mashup_dict, ensure_ascii=False, indent=indent) if escape_bool: json_str = escape(json_str) diff -r f69b5d8ba4b9 -r 5087560b51b6 src/ldt/ldt/ldt_utils/views/project.py --- a/src/ldt/ldt/ldt_utils/views/project.py Fri Mar 27 18:07:56 2015 +0100 +++ b/src/ldt/ldt/ldt_utils/views/project.py Thu Apr 02 17:29:54 2015 +0200 @@ -1,23 +1,25 @@ +import json +import lxml.etree +import math + from django.conf import settings from django.contrib.auth.decorators import login_required from django.contrib.auth.models import Group from django.core.urlresolvers import reverse from django.db.models import Q -from django.http import (HttpResponse, HttpResponseRedirect, +from django.http import (HttpResponse, HttpResponseRedirect, HttpResponseServerError) from django.shortcuts import render_to_response, get_object_or_404 from django.template import RequestContext -from django.utils import simplejson from django.utils.translation import ugettext as _ from guardian.shortcuts import get_objects_for_group, get_objects_for_user + from ldt.ldt_utils.forms import LdtAddForm, AddProjectForm, CopyProjectForm from ldt.ldt_utils.models import Content, Project from ldt.ldt_utils.utils import boolean_convert -from ldt.security.utils import (assign_perm_to_obj, add_change_attr, get_userlist, +from ldt.security.utils import (assign_perm_to_obj, add_change_attr, get_userlist, get_userlist_model) from ldt.user.forms import PictureForm -import lxml.etree -import math @login_required @@ -266,13 +268,13 @@ def publish(request, id): # @ReservedAssignment ldt = get_object_or_404(Project.safe_objects, ldt_id=id) ldt.publish() - return HttpResponse(simplejson.dumps({'res':True, 'ldt': {'id': ldt.id, 'state':ldt.state, 'ldt_id': ldt.ldt_id}}, ensure_ascii=False), mimetype='application/json') + return HttpResponse(json.dumps({'res':True, 'ldt': {'id': ldt.id, 'state':ldt.state, 'ldt_id': ldt.ldt_id}}, ensure_ascii=False), mimetype='application/json') @login_required def unpublish(request, id): # @ReservedAssignment ldt = get_object_or_404(Project.safe_objects, ldt_id=id) ldt.unpublish() - return HttpResponse(simplejson.dumps({'res':True, 'ldt': {'id': ldt.id, 'state':ldt.state, 'ldt_id': ldt.ldt_id}}, ensure_ascii=False), mimetype='application/json') + return HttpResponse(json.dumps({'res':True, 'ldt': {'id': ldt.id, 'state':ldt.state, 'ldt_id': ldt.ldt_id}}, ensure_ascii=False), mimetype='application/json') def created_ldt(request): diff -r f69b5d8ba4b9 -r 5087560b51b6 src/ldt/ldt/settings.py --- a/src/ldt/ldt/settings.py Fri Mar 27 18:07:56 2015 +0100 +++ b/src/ldt/ldt/settings.py Thu Apr 02 17:29:54 2015 +0200 @@ -32,7 +32,7 @@ #'django_openid_consumer', 'corsheaders', 'social.apps.django_app.default', - 'south', + #'south', 'guardian', 'sorl.thumbnail', 'tastypie', diff -r f69b5d8ba4b9 -r 5087560b51b6 src/ldt/ldt/text/tests/__init__.py --- a/src/ldt/ldt/text/tests/__init__.py Fri Mar 27 18:07:56 2015 +0100 +++ b/src/ldt/ldt/text/tests/__init__.py Thu Apr 02 17:29:54 2015 +0200 @@ -1,3 +1,3 @@ -from base_tests import * -from oauth_tests import * -from server_tests import * +from tests_base import * +from tests_oauth import * +from tests_server import * diff -r f69b5d8ba4b9 -r 5087560b51b6 src/ldt/ldt/text/tests/base_tests.py --- a/src/ldt/ldt/text/tests/base_tests.py Fri Mar 27 18:07:56 2015 +0100 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,206 +0,0 @@ -#encoding:UTF-8 - -""" Run these tests with 'python manage.py test text' """ - -from ldt.test.testcases import OAuthTestCase, TestCase -from ldt.text import VERSION_STR -from ldt.text.models import Annotation -import datetime -import lxml.etree - - -CONSUMER_KEY = 'dpf43f3p2l4k3l03' -CONSUMER_SECRET = 'kd94hf93k423kf44' - - -# This test creates an annotation and checks that: -# 1. the annotation was created in the database (by trying to access it through a Django object) -# 2. the returned xml contains correct data -class CreateTest(OAuthTestCase): - - fixtures = ['base_data', 'oauth_data'] - - def setUp(self): - - self.id = 'f2c1d1fa-629d-4520-a3d2-955b4f2582c0' - self.text = "texte selectionne lors de la creation de l\'annotation" - self.content = str('' + self.id + 'http://www.leezam.com/pub/epub/123456!/OPS/chapter2.xhtml#pos=56,168tag1tag2#AAAAAA<![CDATA[titre de l\'annotation]]>' + self.text + 'oaubert79cd0532-1dda-4130-b351-6a181130a7c92010-09-06 12:33:53.417550oaubert79cd0532-1dda-4130-b351-6a181130a7c92010-09-06 12:33:53.420459') - self.error_content = 'z2c1d1fa-629d-4520-a3d2-955b4f2582c0http://www.leezam.com/pub/epub/123456!/OPS/chapter2.xhtml#pos=56,168tag1tag2#AAAAAA<![CDATA[titre de l\'annotation]]>oaubert79cd0532-1dda-4130-b351-6a181130a7c92010-09-06 12:33:53.417550oaubert79cd0532-1dda-4130-b351-6a181130a7c92010-09-06 12:33:53.420459' - - self.set_consumer(CONSUMER_KEY, CONSUMER_SECRET) - self.client.login(username='jane', password='toto') - - def test_create_annotation(self): - - response = self.client.post('/api/' + VERSION_STR + '/text/create/', {'content':self.content}) - self.assertEqual(response.status_code, 200) - annot1 = lxml.etree.fromstring(response.content) - self.assertEqual(annot1.xpath("/iri/text-annotation/id/text()")[0], self.id) - self.assertEqual(annot1.xpath("/iri/text-annotation/content/text/text()")[0], self.text) - self.assertEqual(len(annot1.xpath("/iri/text-annotation/tags/tag")), 2) - self.assertEqual(annot1.xpath("/iri/text-annotation/meta/created/text()")[0][:11], str(datetime.datetime.now())[:11]) - - annot2 = Annotation.objects.get(external_id=self.id) - self.assertEqual(annot2.text, self.text) - self.assertEqual(len(annot2.tags.split(",")), 2) - self.assertEqual(str(annot2.creation_date)[:11], str(datetime.datetime.now())[:11]) - - def test_error_create(self): - - response = self.client.post('/api/' + VERSION_STR + '/text/create/', {'content':self.error_content}) - self.assertEqual(response.status_code, 409) - - -# This test creates an annotation, then gets it, and checks that the returned xml contains correct data -class GetTest(TestCase): - - fixtures = ['base_data'] - - def setUp(self): - - self.id = 'z2c1d1fa-629d-4520-a3d2-955b4f2582c0' - self.color = '#DDDDDD' - self.creation_date = '2010-11-16 17:01:41' - self.title = "titre de l'annotation" - - def test_get_annotation(self): - - response = self.client.get('http://127.0.0.1:8000/api/' + VERSION_STR + '/text/get/' + self.id + '') - self.assertEqual(response.status_code, 200) - annot1 = lxml.etree.fromstring(response.content) - self.assertEqual(annot1.xpath("/iri/text-annotation/id/text()")[0], self.id) - self.assertTrue('tag3', 'tag1' in annot1.xpath("/iri/text-annotation/tags/tag/text()")) - self.assertTrue('mytag', 'tag2new' in annot1.xpath("/iri/text-annotation/tags/tag/text()")) - self.assertEqual(annot1.xpath("/iri/text-annotation/content/color/text()")[0], self.color) - self.assertEqual(annot1.xpath("/iri/text-annotation/content/title/text()")[0], self.title) - self.assertEqual(annot1.xpath("/iri/text-annotation/meta/created/text()")[0], self.creation_date) - - def test_error_get(self): - - response = self.client.get('http://127.0.0.1:8000/api/' + VERSION_STR + '/text/get/2') - self.assertEqual(response.status_code, 404) - - -class FilterTest(TestCase): - - fixtures = ['filter_data'] - - def setUp(self): - - self.user = 'wakimd' - self.uri = "http://www.leezam.com/pub/epub/123456!/OPS/chapter2.xhtml#pos=56,168" - self.limit = "2,1" - self.filter = 'lors' - - def test_filter_all(self): - - response = self.client.get('/api/' + VERSION_STR + '/text/filter/', {'uri':self.uri, 'creator':self.user, 'limit':"1,1", 'filter':self.filter}) - self.assertEqual(response.status_code, 200) - doc = lxml.etree.fromstring(response.content) - self.assertEqual(len(doc.xpath("/iri/text-annotation")), 1) - for elem in doc.xpath("/iri/text-annotation/meta/creator/text()"): - self.assertEqual(elem, self.user) - for elem in doc.xpath("/iri/text-annotation/uri/text()"): - self.assertEqual(elem, self.uri) - for elem in doc.xpath("/iri/text-annotation/content/text/text()"): - self.assertTrue(self.filter in elem) - - def test_filter_creator_limit(self): - - response = self.client.get('/api/' + VERSION_STR + '/text/filter/', {'creator':self.user, 'limit':self.limit}) - self.assertEqual(response.status_code, 200) - doc = lxml.etree.fromstring(response.content) - if self.limit is not None: - self.assertEqual(str(len(doc.xpath("/iri/text-annotation"))), self.limit[0]) - for elem in doc.xpath("/iri/text-annotation/meta/creator/text()"): - self.assertEqual(elem, self.user) - - def test_filter_uri(self): - - response = self.client.get('/api/' + VERSION_STR + '/text/filter/', {'uri':self.uri}) - self.assertEqual(response.status_code, 200) - doc = lxml.etree.fromstring(response.content) - for elem in doc.xpath("/iri/text-annotation/uri/text()"): - self.assertEqual(elem, self.uri) - - def test_filter_annotation_filter(self): - - response = self.client.get('/api/' + VERSION_STR + '/text/filter/', {'uri':self.uri, 'filter':self.filter}) - self.assertEqual(response.status_code, 200) - doc = lxml.etree.fromstring(response.content) - for elem in doc.xpath("/iri/text-annotation/content/text/text()"): - self.assertTrue(self.filter in elem) - for elem in doc.xpath("/iri/text-annotation/uri/text()"): - self.assertEqual(elem, self.uri) - - def test_filter_none(self): - - response = self.client.get('/api/' + VERSION_STR + '/text/filter/', {'uri':'uri', 'creator':'creator', 'filter':'filter'}) - self.assertEqual(response.status_code, 200) - self.assertEqual(response.content, '\n') - - - -# This test deletes an annotation, and checks that: -# 1. the annotation doesn't exist anymore in the database (by trying to access it through Django objects) -# 2. the returned xml contains an empty string -class DeleteTest(OAuthTestCase): - - fixtures = ['base_data', 'oauth_data'] - - def setUp(self): - - self.id = 'z2c1d1fa-629d-4520-a3d2-955b4f2582c0' - - self.set_consumer(CONSUMER_KEY, CONSUMER_SECRET) - self.client.login(username='jane', password='toto') - - def test_delete_annotation(self): - - response = self.client.delete('/api/' + VERSION_STR + '/text/delete/' + self.id + '') - self.assertEqual(response.content, "") - self.assertEqual(response.status_code, 200) - - self.assertRaises(Annotation.DoesNotExist, Annotation.objects.get, external_id=self.id) - - def test_error_delete(self): - - response = self.client.delete('/api/' + VERSION_STR + '/text/ldt/delete/1') - self.assertEqual(response.status_code, 404) - - -# This test creates an annotation, then updates it with new content, and checks that the returned xml contains the updated data -class UpdateTest(OAuthTestCase): - - fixtures = ['oauth_data', 'base_data'] - - def setUp(self): - - self.id = 'z2c1d1fa-629d-4520-a3d2-955b4f2582c0' - self.color = '#DDDDDD' - self.description = "texte de description update" - self.text = "texte selectionne a nouveau lors de la creation de l\'annotation" - self.contributor = "oaubert" - self.content = 'tag2newmytag' + self.color + '' + self.description + '' + self.text + '' + self.contributor + '80cd0532-1dda-4130-b351-6a181130a7c92010-11-06 12:33:53.420459' - - self.set_consumer(CONSUMER_KEY, CONSUMER_SECRET) - self.client.login(username='jane', password='toto') - - def test_update_annotation(self): - - response = self.client.put('/api/' + VERSION_STR + '/text/update/' + self.id + '', {'content':self.content}) - self.assertEqual(response.status_code, 200) - annot = Annotation.objects.get(external_id=self.id) - self.assertEqual(str(annot.update_date)[:11], str(datetime.datetime.now())[:11]) - self.assertEqual(annot.external_id, self.id) - self.assertTrue('tag3', 'tag1' not in annot.tags) - self.assertTrue('mytag', 'tag2new' in annot.tags) - self.assertEqual(annot.color, self.color) - self.assertEqual(annot.description, self.description) - self.assertEqual(annot.text, self.text) - self.assertEqual(annot.contributor, self.contributor) - - def test_error_update(self): - - response = self.client.put('/api/' + VERSION_STR + '/text/update/1', {'content':self.content}) - self.assertEqual(response.status_code, 404) diff -r f69b5d8ba4b9 -r 5087560b51b6 src/ldt/ldt/text/tests/oauth_tests.py --- a/src/ldt/ldt/text/tests/oauth_tests.py Fri Mar 27 18:07:56 2015 +0100 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,259 +0,0 @@ -#encoding:UTF-8 - -""" Run these tests with 'python manage.py test text' """ - -from ldt.test.testcases import TestCase -from ldt.text import VERSION_STR -from oauth2 import Request, SignatureMethod_HMAC_SHA1, generate_nonce -from oauth_provider.consts import OUT_OF_BAND -from oauth_provider.models import Consumer, Token -import datetime -import lxml.etree -import time -import urlparse - -CONSUMER_KEY = 'dpf43f3p2l4k3l03' -CONSUMER_SECRET = 'kd94hf93k423kf44' - - -class OAuthTestDelete(TestCase): - - fixtures = ['oauth_data', 'base_data'] - - def setUp(self): - - self.nonce = generate_nonce(8) - - self.parameters_request = { - 'oauth_consumer_key': CONSUMER_KEY, - 'oauth_signature_method': 'PLAINTEXT', - 'oauth_signature': '%s&' % CONSUMER_SECRET, - 'oauth_timestamp': str(int(time.time())), - 'oauth_nonce': self.nonce, - 'oauth_version': '1.0', - 'oauth_callback': OUT_OF_BAND, - } - - self.parameters_access = { - 'oauth_consumer_key': CONSUMER_KEY, - 'oauth_signature_method': 'PLAINTEXT', - 'oauth_nonce': self.nonce, - 'oauth_version': '1.0', - } - - self.parameters_protected = { - 'oauth_consumer_key': CONSUMER_KEY, - 'oauth_signature_method': 'HMAC-SHA1', - 'oauth_nonce': self.nonce, - 'oauth_version': '1.0', - } - - - def test_auth_access_delete(self): - - ## REQUEST TOKEN - self.parameters_request['scope'] = 'delete' - - response = self.client.get("http://127.0.0.1:8000/oauth/request_token/", self.parameters_request) - self.assertEqual(response.status_code, 200) - - token = list(Token.objects.all())[-1] - data = urlparse.parse_qs(response.content) - - self.assertEqual(token.key, data["oauth_token"][0]) - self.assertEqual(token.secret, data['oauth_token_secret'][0]) - self.assertTrue(data['oauth_callback_confirmed'][0]) - self.assertEqual(token.callback, None) - - ## USER AUTHORIZATION - parameters = { - 'oauth_token': token.key, - } - - response = self.client.get("/oauth/authorize/", parameters) - self.assertEqual(response.status_code, 302) - self.assertTrue(token.key in response['Location']) - - self.client.login(username='jane', password='toto') - - response = self.client.get("/oauth/authorize/", parameters) - self.assertEqual(response.status_code, 200) - self.assertEqual(response.content, 'Fake authorize view for example.com.') - - # fake authorization by the user - parameters['authorize_access'] = 1 - response = self.client.post("/oauth/authorize/", parameters) - self.assertEqual(response.status_code, 200) - - token = list(Token.objects.all())[-1] - self.assertTrue(token.is_approved) - - ## ACCESS TOKEN - self.parameters_access['oauth_token'] = token.key - self.parameters_access['oauth_signature'] = '%s&%s' % (CONSUMER_SECRET, token.secret) - self.parameters_access['oauth_timestamp'] = str(int(time.time())) - self.parameters_access['oauth_verifier'] = token.verifier - self.parameters_access['scope'] = 'delete' - - response = self.client.get("/oauth/access_token/", self.parameters_access) - - access_token = list(Token.objects.filter(token_type=Token.ACCESS))[-1] - self.assertTrue(access_token.key in response.content) - self.assertTrue(access_token.secret in response.content) - self.assertEqual(access_token.user.username, u'jane') - - ## ACCESSING PROTECTED VIEW - self.parameters_protected['oauth_token'] = access_token.key - self.parameters_protected['oauth_timestamp'] = str(int(time.time())) - - oauth_request = Request.from_token_and_callback(access_token, http_url='http://testserver/api/' + VERSION_STR + '/text/delete/z2c1d1fa-629d-4520-a3d2-955b4f2582c0', parameters=self.parameters_protected, http_method="DELETE") - signature_method = SignatureMethod_HMAC_SHA1() - signature = signature_method.sign(oauth_request, Consumer.objects.get(name="example.com"), access_token) - - self.parameters_protected['oauth_signature'] = signature - response = self.client.delete("/api/" + VERSION_STR + "/text/delete/z2c1d1fa-629d-4520-a3d2-955b4f2582c0", self.parameters_protected) - self.assertEqual(response.content, "") - self.assertEqual(response.status_code, 200) - - self.client.logout() - access_token.delete() - - - def test_auth_access_create(self): - - ## REQUEST TOKEN - self.parameters_request['scope'] = 'create' - response = self.client.get("/oauth/request_token/", self.parameters_request) - self.assertEqual(response.status_code, 200) - token = list(Token.objects.all())[-1] - data = urlparse.parse_qs(response.content) - self.assertEqual(token.key, data["oauth_token"][0]) - self.assertEqual(token.secret, data['oauth_token_secret'][0]) - self.assertTrue(data['oauth_callback_confirmed'][0]) - self.assertEqual(token.callback, None) - - ## USER AUTHORIZATION - parameters = { - 'oauth_token': token.key, - } - - response = self.client.get("/oauth/authorize/", parameters) - self.assertEqual(response.status_code, 302) - self.assertTrue(token.key in response['Location']) - - self.client.login(username='jane', password='toto') - - response = self.client.get("/oauth/authorize/", parameters) - self.assertEqual(response.status_code, 200) - self.assertEqual(response.content, 'Fake authorize view for example.com.') - - # fake authorization by the user - parameters['authorize_access'] = 1 - response = self.client.post("/oauth/authorize/", parameters) - self.assertEqual(response.status_code, 200) - token = list(Token.objects.all())[-1] - self.assertTrue(token.is_approved) - - ## ACCESS TOKEN - self.parameters_access['oauth_token'] = token.key - self.parameters_access['oauth_signature'] = '%s&%s' % (CONSUMER_SECRET, token.secret) - self.parameters_access['oauth_timestamp'] = str(int(time.time())) - self.parameters_access['oauth_verifier'] = token.verifier - self.parameters_access['scope'] = 'create' - - response = self.client.get("/oauth/access_token/", self.parameters_access) - - access_token = list(Token.objects.filter(token_type=Token.ACCESS))[-1] - self.assertTrue(access_token.key in response.content) - self.assertTrue(access_token.secret in response.content) - self.assertEqual(access_token.user.username, u'jane') - - ## ACCESSING PROTECTED VIEW - self.parameters_protected['oauth_token'] = access_token.key - self.parameters_protected['oauth_timestamp'] = str(int(time.time())) - self.parameters_protected['content'] = 'f2c1d1fa-629d-4520-a3d2-955b4f2582c0http://www.leezam.com/pub/epub/123456!/OPS/chapter2.xhtml#pos=56,168tag1tag2#AAAAAA<![CDATA[titre de l\'annotation]]>oaubert79cd0532-1dda-4130-b351-6a181130a7c92010-09-06 12:33:53.417550oaubert79cd0532-1dda-4130-b351-6a181130a7c92010-09-06 12:33:53.420459' - - oauth_request = Request.from_token_and_callback(access_token, http_url='http://testserver/api/' + VERSION_STR + '/text/create/', parameters=self.parameters_protected, http_method="POST") - signature_method = SignatureMethod_HMAC_SHA1() - signature = signature_method.sign(oauth_request, Consumer.objects.get(name="example.com"), access_token) - - self.parameters_protected['oauth_signature'] = signature - response = self.client.post("/api/" + VERSION_STR + "/text/create/", self.parameters_protected) - annot1 = lxml.etree.fromstring(response.content) - self.assertEqual(annot1.xpath("/iri/text-annotation/meta/created/text()")[0][:11], str(datetime.datetime.now())[:11]) - self.assertEqual(response.status_code, 200) - - self.client.logout() - access_token.delete() - - def test_auth_access_update(self): - - ## REQUEST TOKEN - self.parameters_request['scope'] = 'update' - - response = self.client.get("/oauth/request_token/", self.parameters_request) - self.assertEqual(response.status_code, 200) - - token = list(Token.objects.all())[-1] - data = urlparse.parse_qs(response.content) - self.assertEqual(token.key, data["oauth_token"][0]) - self.assertEqual(token.secret, data['oauth_token_secret'][0]) - self.assertTrue(data['oauth_callback_confirmed'][0]) - self.assertEqual(token.callback, None) - - ## USER AUTHORIZATION - parameters = { - 'oauth_token': token.key, - } - - response = self.client.get("/oauth/authorize/", parameters) - self.assertEqual(response.status_code, 302) - self.assertTrue(token.key in response['Location']) - - self.client.login(username='jane', password='toto') - - response = self.client.get("/oauth/authorize/", parameters) - self.assertEqual(response.status_code, 200) - self.assertEqual(response.content, 'Fake authorize view for example.com.') - - # fake authorization by the user - parameters['authorize_access'] = 1 - response = self.client.post("/oauth/authorize/", parameters) - self.assertEqual(response.status_code, 200) - token = list(Token.objects.all())[-1] - self.assertTrue(token.is_approved) - - ## ACCESS TOKEN - self.parameters_access['oauth_token'] = token.key - self.parameters_access['oauth_signature'] = '%s&%s' % (CONSUMER_SECRET, token.secret) - self.parameters_access['oauth_timestamp'] = str(int(time.time())) - self.parameters_access['oauth_verifier'] = token.verifier - self.parameters_access['scope'] = 'update' - - response = self.client.get("/oauth/access_token/", self.parameters_access) - - access_token = list(Token.objects.filter(token_type=Token.ACCESS))[-1] - self.assertTrue(access_token.key in response.content) - self.assertTrue(access_token.secret in response.content) - self.assertEqual(access_token.user.username, u'jane') - - ## ACCESSING PROTECTED VIEW - self.parameters_protected['oauth_token'] = access_token.key - self.parameters_protected['oauth_timestamp'] = str(int(time.time())) - self.parameters_protected['content'] = 'tag2newmytag#DDDDDDoaubert80cd0532-1dda-4130-b351-6a181130a7c92010-11-06 12:33:53.420459' - - oauth_request = Request.from_token_and_callback(access_token, http_url='http://testserver/api/' + VERSION_STR + '/text/update/z2c1d1fa-629d-4520-a3d2-955b4f2582c0', parameters=self.parameters_protected, http_method="PUT") - signature_method = SignatureMethod_HMAC_SHA1() - signature = signature_method.sign(oauth_request, Consumer.objects.get(name="example.com"), access_token) - - self.parameters_protected['oauth_signature'] = signature - response = self.client.put("/api/" + VERSION_STR + "/text/update/z2c1d1fa-629d-4520-a3d2-955b4f2582c0", self.parameters_protected) - doc = lxml.etree.fromstring(response.content) - self.assertEqual(doc.xpath("/iri/text-annotation/id/text()")[0], "z2c1d1fa-629d-4520-a3d2-955b4f2582c0") - self.assertTrue('tag3', 'tag1' not in doc.xpath("/iri/text-annotation/tags/tag/text()")) - self.assertTrue('mytag', 'tag2new' in doc.xpath("/iri/text-annotation/tags/tag/text()")) - self.assertEqual(doc.xpath("/iri/text-annotation/meta/modified/text()")[0][:11], str(datetime.datetime.now())[:11]) - self.assertEqual(response.status_code, 200) - - self.client.logout() - access_token.delete() diff -r f69b5d8ba4b9 -r 5087560b51b6 src/ldt/ldt/text/tests/server_tests.py --- a/src/ldt/ldt/text/tests/server_tests.py Fri Mar 27 18:07:56 2015 +0100 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,149 +0,0 @@ -#encoding:UTF-8 - -""" Run these tests with 'python manage.py test text' """ - -from ldt.test.testcases import OAuthWebTestCase, WebTestCase -from ldt.text import VERSION_STR -from ldt.text.models import Annotation -import datetime -import lxml.etree - -CONSUMER_KEY = 'dpf43f3p2l4k3l03' -CONSUMER_SECRET = 'kd94hf93k423kf44' - - -class OnServerGlobalTest(OAuthWebTestCase): - - fixtures = ['oauth_data', 'base_data'] - - def setUp(self): - - self.id = "mypersonnalid" - self.title = "titre de l\'annotation" - self.text = "texte selectionne lors de la creation de l\'annotation" - self.textupdate = "texte selectionne a nouveau lors de la creation de l\'annotation" - self.descupdate = "texte de description update" - self.contributor = "oaubert" - self.creator = "wakimd" - self.uri = "http://www.leezam.com/pub/epub/123456!/OPS/chapter2.xhtml#pos=56,168" - self.content1 = '' + self.id + '' + self.uri + 'tag1tag2#AAAAAA' + self.title + '' + self.text + 'oaubert79cd0532-1dda-4130-b351-6a181130a7c92010-09-06 12:33:53.417550' + self.creator + '79cd0532-1dda-4130-b351-6a181130a7c92010-09-06 12:33:53.420459' - self.contentupdate = 'tag1tag2newtag3#DDDDDD' + self.descupdate + '' + self.textupdate + '' + self.contributor + '80cd0532-1dda-4130-b351-6a181130a7c92010-11-06 12:33:53.420459' - - self.set_login_url("/auth_accounts/login/") - self.set_consumer(CONSUMER_KEY, CONSUMER_SECRET) - - - def test_everything(self): - - self.assertTrue(self.client.login(username='jane', password='toto')) - - #test POST - creation = self.client.post("/api/" + VERSION_STR + "/text/create/", data={'content': self.content1}) - self.assertEqual(creation.status_code, 200) - annot = Annotation.objects.get(external_id=self.id) - self.assertEqual(str(annot.creation_date)[:11], str(datetime.datetime.now())[:11]) - self.assertEqual(annot.text, self.text) - self.assertEqual(len(annot.tags.split(",")), 2) - - #test GET - get = self.client.get("/api/" + VERSION_STR + "/text/get/" + self.id + "") - self.assertEqual(get.status_code, 200) - annot = lxml.etree.fromstring(get.content) - self.assertTrue('tag1', 'tag2' in annot.xpath("/iri/text-annotation/tags/tag/text()")) - self.assertEqual(annot.xpath("/iri/text-annotation/content/title/text()")[0], self.title) - - #test OPTIONS - options = self.client.options("/api/" + VERSION_STR + "/text/get/" + self.id + "") - self.assertEqual(options.status_code, 200) - self.assertEqual(options.content, get.content) - - #test HEAD - head = self.client.head("/api/" + VERSION_STR + "/text/get/" + self.id + "") - self.assertEqual(head.status_code, 200) - self.assertEqual(head['content-type'], 'text/xml;charset=utf-8') - self.assertEqual(head['content-language'], 'fr-fr') - self.assertEqual(head.content, '') - - #test LOGOUT - self.client.logout() - - creation = self.client.post("/api/" + VERSION_STR + "/text/create/", data={'content': self.content1}) - self.assertEqual(creation.status_code, 401) - - self.assertTrue(self.client.login(username='jane', password='toto')) - - # filter - filt1 = self.client.get("/api/" + VERSION_STR + "/text/filter/", data={"uri":self.uri}) - self.assertEqual(filt1.status_code, 200) - doc = lxml.etree.fromstring(filt1.content) - self.assertEqual(len(doc.xpath("/iri/text-annotation")), 2) - for elem in doc.xpath("/iri/text-annotation/uri/text()"): - self.assertEqual(elem, self.uri) - - filt2 = self.client.get("/api/" + VERSION_STR + "/text/filter/", data={"creator":self.contributor}) - self.assertEqual(filt2.status_code, 200) - self.assertEqual(filt2.content, '\n') - - #test PUT - update = self.client.put("/api/" + VERSION_STR + "/text/update/" + self.id + "", data={'content':self.contentupdate}) - self.assertEqual(update.status_code, 200) - annot = Annotation.objects.get(external_id=self.id) - self.assertEqual(str(annot.creation_date)[:11], str(datetime.datetime.now())[:11]) - self.assertEqual(annot.external_id, self.id) - self.assertTrue('tag1', 'tag2' not in annot.tags) - self.assertTrue('mytag', 'tag2new' in annot.tags) - self.assertEqual(annot.description, self.descupdate) - self.assertEqual(annot.text, self.textupdate) - self.assertEqual(annot.contributor, self.contributor) - - #test DELETE - delete = self.client.delete("/api/" + VERSION_STR + "/text/delete/" + self.id + "") - self.assertEqual(delete.content, "") - self.assertEqual(delete.status_code, 200) - self.assertRaises(Annotation.DoesNotExist, Annotation.objects.get, external_id=self.id) - - self.client.logout() - - - def test_errors(self): - - self.assertTrue(self.client.login(username='jane', password='toto')) - - creation = self.client.post("/api/" + VERSION_STR + "/text/create/", data={'content': self.content1}) - self.assertEqual(creation.status_code, 200) - - creation = self.client.post("/api/" + VERSION_STR + "/text/create/", data={'content': self.content1}) - self.assertEqual(creation.status_code, 409) - - get = self.client.get("/api/" + VERSION_STR + "/text/get/1") - self.assertEqual(get.status_code, 404) - - update = self.client.put('/api/' + VERSION_STR + '/text/update/1', {'content':self.contentupdate}) - self.assertEqual(update.status_code, 404) - - delete = self.client.delete("/api/" + VERSION_STR + "/text/delete/1") - self.assertEqual(delete.status_code, 404) - - delete = self.client.delete("/api/" + VERSION_STR + "/text/delete/" + self.id + "") - self.assertEqual(delete.status_code, 200) - self.assertEqual(delete.content, "") - - self.client.logout() - - -class WebClientTest(WebTestCase): - - fixtures = ['oauth_data', 'base_data'] - - def setUp(self): - self.set_login_url("/auth_accounts/login/") - - def test_get(self): - self.assertTrue(self.client.login(username='jane', password='toto')) - - get = self.client.get("/api/" + VERSION_STR + "/text/get/z2c1d1fa-629d-4520-a3d2-955b4f2582c0") - self.assertEqual(get.status_code, 200) - annot = lxml.etree.fromstring(get.content) - self.assertTrue('tag1', 'tag2' in annot.xpath("/iri/text-annotation/tags/tag/text()")) - - diff -r f69b5d8ba4b9 -r 5087560b51b6 src/ldt/ldt/text/tests/tests_base.py --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/ldt/ldt/text/tests/tests_base.py Thu Apr 02 17:29:54 2015 +0200 @@ -0,0 +1,206 @@ +#encoding:UTF-8 + +""" Run these tests with 'python manage.py test text' """ + +from ldt.test.testcases import OAuthTestCase, TestCase +from ldt.text import VERSION_STR +from ldt.text.models import Annotation +import datetime +import lxml.etree + + +CONSUMER_KEY = 'dpf43f3p2l4k3l03' +CONSUMER_SECRET = 'kd94hf93k423kf44' + + +# This test creates an annotation and checks that: +# 1. the annotation was created in the database (by trying to access it through a Django object) +# 2. the returned xml contains correct data +class CreateTest(OAuthTestCase): + + fixtures = ['base_data', 'oauth_data'] + + def setUp(self): + + self.id = 'f2c1d1fa-629d-4520-a3d2-955b4f2582c0' + self.text = "texte selectionne lors de la creation de l\'annotation" + self.content = str('' + self.id + 'http://www.leezam.com/pub/epub/123456!/OPS/chapter2.xhtml#pos=56,168tag1tag2#AAAAAA<![CDATA[titre de l\'annotation]]>' + self.text + 'oaubert79cd0532-1dda-4130-b351-6a181130a7c92010-09-06 12:33:53.417550oaubert79cd0532-1dda-4130-b351-6a181130a7c92010-09-06 12:33:53.420459') + self.error_content = 'z2c1d1fa-629d-4520-a3d2-955b4f2582c0http://www.leezam.com/pub/epub/123456!/OPS/chapter2.xhtml#pos=56,168tag1tag2#AAAAAA<![CDATA[titre de l\'annotation]]>oaubert79cd0532-1dda-4130-b351-6a181130a7c92010-09-06 12:33:53.417550oaubert79cd0532-1dda-4130-b351-6a181130a7c92010-09-06 12:33:53.420459' + + self.set_consumer(CONSUMER_KEY, CONSUMER_SECRET) + self.client.login(username='jane', password='toto') + + def test_create_annotation(self): + + response = self.client.post('/api/' + VERSION_STR + '/text/create/', {'content':self.content}) + self.assertEqual(response.status_code, 200) + annot1 = lxml.etree.fromstring(response.content) + self.assertEqual(annot1.xpath("/iri/text-annotation/id/text()")[0], self.id) + self.assertEqual(annot1.xpath("/iri/text-annotation/content/text/text()")[0], self.text) + self.assertEqual(len(annot1.xpath("/iri/text-annotation/tags/tag")), 2) + self.assertEqual(annot1.xpath("/iri/text-annotation/meta/created/text()")[0][:11], str(datetime.datetime.now())[:11]) + + annot2 = Annotation.objects.get(external_id=self.id) + self.assertEqual(annot2.text, self.text) + self.assertEqual(len(annot2.tags.split(",")), 2) + self.assertEqual(str(annot2.creation_date)[:11], str(datetime.datetime.now())[:11]) + + def test_error_create(self): + + response = self.client.post('/api/' + VERSION_STR + '/text/create/', {'content':self.error_content}) + self.assertEqual(response.status_code, 409) + + +# This test creates an annotation, then gets it, and checks that the returned xml contains correct data +class GetTest(TestCase): + + fixtures = ['base_data'] + + def setUp(self): + + self.id = 'z2c1d1fa-629d-4520-a3d2-955b4f2582c0' + self.color = '#DDDDDD' + self.creation_date = '2010-11-16 17:01:41' + self.title = "titre de l'annotation" + + def test_get_annotation(self): + + response = self.client.get('http://127.0.0.1:8000/api/' + VERSION_STR + '/text/get/' + self.id + '') + self.assertEqual(response.status_code, 200) + annot1 = lxml.etree.fromstring(response.content) + self.assertEqual(annot1.xpath("/iri/text-annotation/id/text()")[0], self.id) + self.assertTrue('tag3', 'tag1' in annot1.xpath("/iri/text-annotation/tags/tag/text()")) + self.assertTrue('mytag', 'tag2new' in annot1.xpath("/iri/text-annotation/tags/tag/text()")) + self.assertEqual(annot1.xpath("/iri/text-annotation/content/color/text()")[0], self.color) + self.assertEqual(annot1.xpath("/iri/text-annotation/content/title/text()")[0], self.title) + self.assertEqual(annot1.xpath("/iri/text-annotation/meta/created/text()")[0], self.creation_date) + + def test_error_get(self): + + response = self.client.get('http://127.0.0.1:8000/api/' + VERSION_STR + '/text/get/2') + self.assertEqual(response.status_code, 404) + + +class FilterTest(TestCase): + + fixtures = ['filter_data'] + + def setUp(self): + + self.user = 'wakimd' + self.uri = "http://www.leezam.com/pub/epub/123456!/OPS/chapter2.xhtml#pos=56,168" + self.limit = "2,1" + self.filter = 'lors' + + def test_filter_all(self): + + response = self.client.get('/api/' + VERSION_STR + '/text/filter/', {'uri':self.uri, 'creator':self.user, 'limit':"1,1", 'filter':self.filter}) + self.assertEqual(response.status_code, 200) + doc = lxml.etree.fromstring(response.content) + self.assertEqual(len(doc.xpath("/iri/text-annotation")), 1) + for elem in doc.xpath("/iri/text-annotation/meta/creator/text()"): + self.assertEqual(elem, self.user) + for elem in doc.xpath("/iri/text-annotation/uri/text()"): + self.assertEqual(elem, self.uri) + for elem in doc.xpath("/iri/text-annotation/content/text/text()"): + self.assertTrue(self.filter in elem) + + def test_filter_creator_limit(self): + + response = self.client.get('/api/' + VERSION_STR + '/text/filter/', {'creator':self.user, 'limit':self.limit}) + self.assertEqual(response.status_code, 200) + doc = lxml.etree.fromstring(response.content) + if self.limit is not None: + self.assertEqual(str(len(doc.xpath("/iri/text-annotation"))), self.limit[0]) + for elem in doc.xpath("/iri/text-annotation/meta/creator/text()"): + self.assertEqual(elem, self.user) + + def test_filter_uri(self): + + response = self.client.get('/api/' + VERSION_STR + '/text/filter/', {'uri':self.uri}) + self.assertEqual(response.status_code, 200) + doc = lxml.etree.fromstring(response.content) + for elem in doc.xpath("/iri/text-annotation/uri/text()"): + self.assertEqual(elem, self.uri) + + def test_filter_annotation_filter(self): + + response = self.client.get('/api/' + VERSION_STR + '/text/filter/', {'uri':self.uri, 'filter':self.filter}) + self.assertEqual(response.status_code, 200) + doc = lxml.etree.fromstring(response.content) + for elem in doc.xpath("/iri/text-annotation/content/text/text()"): + self.assertTrue(self.filter in elem) + for elem in doc.xpath("/iri/text-annotation/uri/text()"): + self.assertEqual(elem, self.uri) + + def test_filter_none(self): + + response = self.client.get('/api/' + VERSION_STR + '/text/filter/', {'uri':'uri', 'creator':'creator', 'filter':'filter'}) + self.assertEqual(response.status_code, 200) + self.assertEqual(response.content, '\n') + + + +# This test deletes an annotation, and checks that: +# 1. the annotation doesn't exist anymore in the database (by trying to access it through Django objects) +# 2. the returned xml contains an empty string +class DeleteTest(OAuthTestCase): + + fixtures = ['base_data', 'oauth_data'] + + def setUp(self): + + self.id = 'z2c1d1fa-629d-4520-a3d2-955b4f2582c0' + + self.set_consumer(CONSUMER_KEY, CONSUMER_SECRET) + self.client.login(username='jane', password='toto') + + def test_delete_annotation(self): + + response = self.client.delete('/api/' + VERSION_STR + '/text/delete/' + self.id + '') + self.assertEqual(response.content, "") + self.assertEqual(response.status_code, 200) + + self.assertRaises(Annotation.DoesNotExist, Annotation.objects.get, external_id=self.id) + + def test_error_delete(self): + + response = self.client.delete('/api/' + VERSION_STR + '/text/ldt/delete/1') + self.assertEqual(response.status_code, 404) + + +# This test creates an annotation, then updates it with new content, and checks that the returned xml contains the updated data +class UpdateTest(OAuthTestCase): + + fixtures = ['oauth_data', 'base_data'] + + def setUp(self): + + self.id = 'z2c1d1fa-629d-4520-a3d2-955b4f2582c0' + self.color = '#DDDDDD' + self.description = "texte de description update" + self.text = "texte selectionne a nouveau lors de la creation de l\'annotation" + self.contributor = "oaubert" + self.content = 'tag2newmytag' + self.color + '' + self.description + '' + self.text + '' + self.contributor + '80cd0532-1dda-4130-b351-6a181130a7c92010-11-06 12:33:53.420459' + + self.set_consumer(CONSUMER_KEY, CONSUMER_SECRET) + self.client.login(username='jane', password='toto') + + def test_update_annotation(self): + + response = self.client.put('/api/' + VERSION_STR + '/text/update/' + self.id + '', {'content':self.content}) + self.assertEqual(response.status_code, 200) + annot = Annotation.objects.get(external_id=self.id) + self.assertEqual(str(annot.update_date)[:11], str(datetime.datetime.now())[:11]) + self.assertEqual(annot.external_id, self.id) + self.assertTrue('tag3', 'tag1' not in annot.tags) + self.assertTrue('mytag', 'tag2new' in annot.tags) + self.assertEqual(annot.color, self.color) + self.assertEqual(annot.description, self.description) + self.assertEqual(annot.text, self.text) + self.assertEqual(annot.contributor, self.contributor) + + def test_error_update(self): + + response = self.client.put('/api/' + VERSION_STR + '/text/update/1', {'content':self.content}) + self.assertEqual(response.status_code, 404) diff -r f69b5d8ba4b9 -r 5087560b51b6 src/ldt/ldt/text/tests/tests_oauth.py --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/ldt/ldt/text/tests/tests_oauth.py Thu Apr 02 17:29:54 2015 +0200 @@ -0,0 +1,259 @@ +#encoding:UTF-8 + +""" Run these tests with 'python manage.py test text' """ + +from ldt.test.testcases import TestCase +from ldt.text import VERSION_STR +from oauth2 import Request, SignatureMethod_HMAC_SHA1, generate_nonce +from oauth_provider.consts import OUT_OF_BAND +from oauth_provider.models import Consumer, Token +import datetime +import lxml.etree +import time +import urlparse + +CONSUMER_KEY = 'dpf43f3p2l4k3l03' +CONSUMER_SECRET = 'kd94hf93k423kf44' + + +class OAuthTestDelete(TestCase): + + fixtures = ['oauth_data', 'base_data'] + + def setUp(self): + + self.nonce = generate_nonce(8) + + self.parameters_request = { + 'oauth_consumer_key': CONSUMER_KEY, + 'oauth_signature_method': 'PLAINTEXT', + 'oauth_signature': '%s&' % CONSUMER_SECRET, + 'oauth_timestamp': str(int(time.time())), + 'oauth_nonce': self.nonce, + 'oauth_version': '1.0', + 'oauth_callback': OUT_OF_BAND, + } + + self.parameters_access = { + 'oauth_consumer_key': CONSUMER_KEY, + 'oauth_signature_method': 'PLAINTEXT', + 'oauth_nonce': self.nonce, + 'oauth_version': '1.0', + } + + self.parameters_protected = { + 'oauth_consumer_key': CONSUMER_KEY, + 'oauth_signature_method': 'HMAC-SHA1', + 'oauth_nonce': self.nonce, + 'oauth_version': '1.0', + } + + + def test_auth_access_delete(self): + + ## REQUEST TOKEN + self.parameters_request['scope'] = 'delete' + + response = self.client.get("http://127.0.0.1:8000/oauth/request_token/", self.parameters_request) + self.assertEqual(response.status_code, 200) + + token = list(Token.objects.all())[-1] + data = urlparse.parse_qs(response.content) + + self.assertEqual(token.key, data["oauth_token"][0]) + self.assertEqual(token.secret, data['oauth_token_secret'][0]) + self.assertTrue(data['oauth_callback_confirmed'][0]) + self.assertEqual(token.callback, None) + + ## USER AUTHORIZATION + parameters = { + 'oauth_token': token.key, + } + + response = self.client.get("/oauth/authorize/", parameters) + self.assertEqual(response.status_code, 302) + self.assertTrue(token.key in response['Location']) + + self.client.login(username='jane', password='toto') + + response = self.client.get("/oauth/authorize/", parameters) + self.assertEqual(response.status_code, 200) + self.assertEqual(response.content, 'Fake authorize view for example.com.') + + # fake authorization by the user + parameters['authorize_access'] = 1 + response = self.client.post("/oauth/authorize/", parameters) + self.assertEqual(response.status_code, 200) + + token = list(Token.objects.all())[-1] + self.assertTrue(token.is_approved) + + ## ACCESS TOKEN + self.parameters_access['oauth_token'] = token.key + self.parameters_access['oauth_signature'] = '%s&%s' % (CONSUMER_SECRET, token.secret) + self.parameters_access['oauth_timestamp'] = str(int(time.time())) + self.parameters_access['oauth_verifier'] = token.verifier + self.parameters_access['scope'] = 'delete' + + response = self.client.get("/oauth/access_token/", self.parameters_access) + + access_token = list(Token.objects.filter(token_type=Token.ACCESS))[-1] + self.assertTrue(access_token.key in response.content) + self.assertTrue(access_token.secret in response.content) + self.assertEqual(access_token.user.username, u'jane') + + ## ACCESSING PROTECTED VIEW + self.parameters_protected['oauth_token'] = access_token.key + self.parameters_protected['oauth_timestamp'] = str(int(time.time())) + + oauth_request = Request.from_token_and_callback(access_token, http_url='http://testserver/api/' + VERSION_STR + '/text/delete/z2c1d1fa-629d-4520-a3d2-955b4f2582c0', parameters=self.parameters_protected, http_method="DELETE") + signature_method = SignatureMethod_HMAC_SHA1() + signature = signature_method.sign(oauth_request, Consumer.objects.get(name="example.com"), access_token) + + self.parameters_protected['oauth_signature'] = signature + response = self.client.delete("/api/" + VERSION_STR + "/text/delete/z2c1d1fa-629d-4520-a3d2-955b4f2582c0", self.parameters_protected) + self.assertEqual(response.content, "") + self.assertEqual(response.status_code, 200) + + self.client.logout() + access_token.delete() + + + def test_auth_access_create(self): + + ## REQUEST TOKEN + self.parameters_request['scope'] = 'create' + response = self.client.get("/oauth/request_token/", self.parameters_request) + self.assertEqual(response.status_code, 200) + token = list(Token.objects.all())[-1] + data = urlparse.parse_qs(response.content) + self.assertEqual(token.key, data["oauth_token"][0]) + self.assertEqual(token.secret, data['oauth_token_secret'][0]) + self.assertTrue(data['oauth_callback_confirmed'][0]) + self.assertEqual(token.callback, None) + + ## USER AUTHORIZATION + parameters = { + 'oauth_token': token.key, + } + + response = self.client.get("/oauth/authorize/", parameters) + self.assertEqual(response.status_code, 302) + self.assertTrue(token.key in response['Location']) + + self.client.login(username='jane', password='toto') + + response = self.client.get("/oauth/authorize/", parameters) + self.assertEqual(response.status_code, 200) + self.assertEqual(response.content, 'Fake authorize view for example.com.') + + # fake authorization by the user + parameters['authorize_access'] = 1 + response = self.client.post("/oauth/authorize/", parameters) + self.assertEqual(response.status_code, 200) + token = list(Token.objects.all())[-1] + self.assertTrue(token.is_approved) + + ## ACCESS TOKEN + self.parameters_access['oauth_token'] = token.key + self.parameters_access['oauth_signature'] = '%s&%s' % (CONSUMER_SECRET, token.secret) + self.parameters_access['oauth_timestamp'] = str(int(time.time())) + self.parameters_access['oauth_verifier'] = token.verifier + self.parameters_access['scope'] = 'create' + + response = self.client.get("/oauth/access_token/", self.parameters_access) + + access_token = list(Token.objects.filter(token_type=Token.ACCESS))[-1] + self.assertTrue(access_token.key in response.content) + self.assertTrue(access_token.secret in response.content) + self.assertEqual(access_token.user.username, u'jane') + + ## ACCESSING PROTECTED VIEW + self.parameters_protected['oauth_token'] = access_token.key + self.parameters_protected['oauth_timestamp'] = str(int(time.time())) + self.parameters_protected['content'] = 'f2c1d1fa-629d-4520-a3d2-955b4f2582c0http://www.leezam.com/pub/epub/123456!/OPS/chapter2.xhtml#pos=56,168tag1tag2#AAAAAA<![CDATA[titre de l\'annotation]]>oaubert79cd0532-1dda-4130-b351-6a181130a7c92010-09-06 12:33:53.417550oaubert79cd0532-1dda-4130-b351-6a181130a7c92010-09-06 12:33:53.420459' + + oauth_request = Request.from_token_and_callback(access_token, http_url='http://testserver/api/' + VERSION_STR + '/text/create/', parameters=self.parameters_protected, http_method="POST") + signature_method = SignatureMethod_HMAC_SHA1() + signature = signature_method.sign(oauth_request, Consumer.objects.get(name="example.com"), access_token) + + self.parameters_protected['oauth_signature'] = signature + response = self.client.post("/api/" + VERSION_STR + "/text/create/", self.parameters_protected) + annot1 = lxml.etree.fromstring(response.content) + self.assertEqual(annot1.xpath("/iri/text-annotation/meta/created/text()")[0][:11], str(datetime.datetime.now())[:11]) + self.assertEqual(response.status_code, 200) + + self.client.logout() + access_token.delete() + + def test_auth_access_update(self): + + ## REQUEST TOKEN + self.parameters_request['scope'] = 'update' + + response = self.client.get("/oauth/request_token/", self.parameters_request) + self.assertEqual(response.status_code, 200) + + token = list(Token.objects.all())[-1] + data = urlparse.parse_qs(response.content) + self.assertEqual(token.key, data["oauth_token"][0]) + self.assertEqual(token.secret, data['oauth_token_secret'][0]) + self.assertTrue(data['oauth_callback_confirmed'][0]) + self.assertEqual(token.callback, None) + + ## USER AUTHORIZATION + parameters = { + 'oauth_token': token.key, + } + + response = self.client.get("/oauth/authorize/", parameters) + self.assertEqual(response.status_code, 302) + self.assertTrue(token.key in response['Location']) + + self.client.login(username='jane', password='toto') + + response = self.client.get("/oauth/authorize/", parameters) + self.assertEqual(response.status_code, 200) + self.assertEqual(response.content, 'Fake authorize view for example.com.') + + # fake authorization by the user + parameters['authorize_access'] = 1 + response = self.client.post("/oauth/authorize/", parameters) + self.assertEqual(response.status_code, 200) + token = list(Token.objects.all())[-1] + self.assertTrue(token.is_approved) + + ## ACCESS TOKEN + self.parameters_access['oauth_token'] = token.key + self.parameters_access['oauth_signature'] = '%s&%s' % (CONSUMER_SECRET, token.secret) + self.parameters_access['oauth_timestamp'] = str(int(time.time())) + self.parameters_access['oauth_verifier'] = token.verifier + self.parameters_access['scope'] = 'update' + + response = self.client.get("/oauth/access_token/", self.parameters_access) + + access_token = list(Token.objects.filter(token_type=Token.ACCESS))[-1] + self.assertTrue(access_token.key in response.content) + self.assertTrue(access_token.secret in response.content) + self.assertEqual(access_token.user.username, u'jane') + + ## ACCESSING PROTECTED VIEW + self.parameters_protected['oauth_token'] = access_token.key + self.parameters_protected['oauth_timestamp'] = str(int(time.time())) + self.parameters_protected['content'] = 'tag2newmytag#DDDDDDoaubert80cd0532-1dda-4130-b351-6a181130a7c92010-11-06 12:33:53.420459' + + oauth_request = Request.from_token_and_callback(access_token, http_url='http://testserver/api/' + VERSION_STR + '/text/update/z2c1d1fa-629d-4520-a3d2-955b4f2582c0', parameters=self.parameters_protected, http_method="PUT") + signature_method = SignatureMethod_HMAC_SHA1() + signature = signature_method.sign(oauth_request, Consumer.objects.get(name="example.com"), access_token) + + self.parameters_protected['oauth_signature'] = signature + response = self.client.put("/api/" + VERSION_STR + "/text/update/z2c1d1fa-629d-4520-a3d2-955b4f2582c0", self.parameters_protected) + doc = lxml.etree.fromstring(response.content) + self.assertEqual(doc.xpath("/iri/text-annotation/id/text()")[0], "z2c1d1fa-629d-4520-a3d2-955b4f2582c0") + self.assertTrue('tag3', 'tag1' not in doc.xpath("/iri/text-annotation/tags/tag/text()")) + self.assertTrue('mytag', 'tag2new' in doc.xpath("/iri/text-annotation/tags/tag/text()")) + self.assertEqual(doc.xpath("/iri/text-annotation/meta/modified/text()")[0][:11], str(datetime.datetime.now())[:11]) + self.assertEqual(response.status_code, 200) + + self.client.logout() + access_token.delete() diff -r f69b5d8ba4b9 -r 5087560b51b6 src/ldt/ldt/text/tests/tests_server.py --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/ldt/ldt/text/tests/tests_server.py Thu Apr 02 17:29:54 2015 +0200 @@ -0,0 +1,149 @@ +#encoding:UTF-8 + +""" Run these tests with 'python manage.py test text' """ + +from ldt.test.testcases import OAuthWebTestCase, WebTestCase +from ldt.text import VERSION_STR +from ldt.text.models import Annotation +import datetime +import lxml.etree + +CONSUMER_KEY = 'dpf43f3p2l4k3l03' +CONSUMER_SECRET = 'kd94hf93k423kf44' + + +class OnServerGlobalTest(OAuthWebTestCase): + + fixtures = ['oauth_data', 'base_data'] + + def setUp(self): + + self.id = "mypersonnalid" + self.title = "titre de l\'annotation" + self.text = "texte selectionne lors de la creation de l\'annotation" + self.textupdate = "texte selectionne a nouveau lors de la creation de l\'annotation" + self.descupdate = "texte de description update" + self.contributor = "oaubert" + self.creator = "wakimd" + self.uri = "http://www.leezam.com/pub/epub/123456!/OPS/chapter2.xhtml#pos=56,168" + self.content1 = '' + self.id + '' + self.uri + 'tag1tag2#AAAAAA' + self.title + '' + self.text + 'oaubert79cd0532-1dda-4130-b351-6a181130a7c92010-09-06 12:33:53.417550' + self.creator + '79cd0532-1dda-4130-b351-6a181130a7c92010-09-06 12:33:53.420459' + self.contentupdate = 'tag1tag2newtag3#DDDDDD' + self.descupdate + '' + self.textupdate + '' + self.contributor + '80cd0532-1dda-4130-b351-6a181130a7c92010-11-06 12:33:53.420459' + + self.set_login_url("/auth_accounts/login/") + self.set_consumer(CONSUMER_KEY, CONSUMER_SECRET) + + + def test_everything(self): + + self.assertTrue(self.client.login(username='jane', password='toto')) + + #test POST + creation = self.client.post("/api/" + VERSION_STR + "/text/create/", data={'content': self.content1}) + self.assertEqual(creation.status_code, 200) + annot = Annotation.objects.get(external_id=self.id) + self.assertEqual(str(annot.creation_date)[:11], str(datetime.datetime.now())[:11]) + self.assertEqual(annot.text, self.text) + self.assertEqual(len(annot.tags.split(",")), 2) + + #test GET + get = self.client.get("/api/" + VERSION_STR + "/text/get/" + self.id + "") + self.assertEqual(get.status_code, 200) + annot = lxml.etree.fromstring(get.content) + self.assertTrue('tag1', 'tag2' in annot.xpath("/iri/text-annotation/tags/tag/text()")) + self.assertEqual(annot.xpath("/iri/text-annotation/content/title/text()")[0], self.title) + + #test OPTIONS + options = self.client.options("/api/" + VERSION_STR + "/text/get/" + self.id + "") + self.assertEqual(options.status_code, 200) + self.assertEqual(options.content, get.content) + + #test HEAD + head = self.client.head("/api/" + VERSION_STR + "/text/get/" + self.id + "") + self.assertEqual(head.status_code, 200) + self.assertEqual(head['content-type'], 'text/xml;charset=utf-8') + self.assertEqual(head['content-language'], 'fr-fr') + self.assertEqual(head.content, '') + + #test LOGOUT + self.client.logout() + + creation = self.client.post("/api/" + VERSION_STR + "/text/create/", data={'content': self.content1}) + self.assertEqual(creation.status_code, 401) + + self.assertTrue(self.client.login(username='jane', password='toto')) + + # filter + filt1 = self.client.get("/api/" + VERSION_STR + "/text/filter/", data={"uri":self.uri}) + self.assertEqual(filt1.status_code, 200) + doc = lxml.etree.fromstring(filt1.content) + self.assertEqual(len(doc.xpath("/iri/text-annotation")), 2) + for elem in doc.xpath("/iri/text-annotation/uri/text()"): + self.assertEqual(elem, self.uri) + + filt2 = self.client.get("/api/" + VERSION_STR + "/text/filter/", data={"creator":self.contributor}) + self.assertEqual(filt2.status_code, 200) + self.assertEqual(filt2.content, '\n') + + #test PUT + update = self.client.put("/api/" + VERSION_STR + "/text/update/" + self.id + "", data={'content':self.contentupdate}) + self.assertEqual(update.status_code, 200) + annot = Annotation.objects.get(external_id=self.id) + self.assertEqual(str(annot.creation_date)[:11], str(datetime.datetime.now())[:11]) + self.assertEqual(annot.external_id, self.id) + self.assertTrue('tag1', 'tag2' not in annot.tags) + self.assertTrue('mytag', 'tag2new' in annot.tags) + self.assertEqual(annot.description, self.descupdate) + self.assertEqual(annot.text, self.textupdate) + self.assertEqual(annot.contributor, self.contributor) + + #test DELETE + delete = self.client.delete("/api/" + VERSION_STR + "/text/delete/" + self.id + "") + self.assertEqual(delete.content, "") + self.assertEqual(delete.status_code, 200) + self.assertRaises(Annotation.DoesNotExist, Annotation.objects.get, external_id=self.id) + + self.client.logout() + + + def test_errors(self): + + self.assertTrue(self.client.login(username='jane', password='toto')) + + creation = self.client.post("/api/" + VERSION_STR + "/text/create/", data={'content': self.content1}) + self.assertEqual(creation.status_code, 200) + + creation = self.client.post("/api/" + VERSION_STR + "/text/create/", data={'content': self.content1}) + self.assertEqual(creation.status_code, 409) + + get = self.client.get("/api/" + VERSION_STR + "/text/get/1") + self.assertEqual(get.status_code, 404) + + update = self.client.put('/api/' + VERSION_STR + '/text/update/1', {'content':self.contentupdate}) + self.assertEqual(update.status_code, 404) + + delete = self.client.delete("/api/" + VERSION_STR + "/text/delete/1") + self.assertEqual(delete.status_code, 404) + + delete = self.client.delete("/api/" + VERSION_STR + "/text/delete/" + self.id + "") + self.assertEqual(delete.status_code, 200) + self.assertEqual(delete.content, "") + + self.client.logout() + + +class WebClientTest(WebTestCase): + + fixtures = ['oauth_data', 'base_data'] + + def setUp(self): + self.set_login_url("/auth_accounts/login/") + + def test_get(self): + self.assertTrue(self.client.login(username='jane', password='toto')) + + get = self.client.get("/api/" + VERSION_STR + "/text/get/z2c1d1fa-629d-4520-a3d2-955b4f2582c0") + self.assertEqual(get.status_code, 200) + annot = lxml.etree.fromstring(get.content) + self.assertTrue('tag1', 'tag2' in annot.xpath("/iri/text-annotation/tags/tag/text()")) + + diff -r f69b5d8ba4b9 -r 5087560b51b6 src/ldt/ldt/user/views.py --- a/src/ldt/ldt/user/views.py Fri Mar 27 18:07:56 2015 +0100 +++ b/src/ldt/ldt/user/views.py Thu Apr 02 17:29:54 2015 +0200 @@ -1,14 +1,17 @@ +import json + from django.contrib.auth import authenticate, login, logout from django.contrib.auth.decorators import login_required from django.contrib.auth.forms import PasswordChangeForm from django.http import HttpResponse, HttpResponseRedirect from django.shortcuts import render_to_response from django.template import RequestContext, loader -from django.utils import simplejson from django.utils.translation import ugettext as _ from django.views.i18n import set_language + from ldt.user.forms import ProfileForm, LanguageChangeForm, PictureForm - + + @login_required def profile(request): msg = '' @@ -97,11 +100,11 @@ context = RequestContext(request, { 'username': user.username, }) template = loader.get_template(loginstate_template_name) html = template.render(context) - return HttpResponse(simplejson.dumps({'message': u'successful', 'username': user.username, 'html': html, 'reload': request.POST["reload"], })) + return HttpResponse(json.dumps({'message': u'successful', 'username': user.username, 'html': html, 'reload': request.POST["reload"], })) else: - return HttpResponse(simplejson.dumps({'message': error_message, })) + return HttpResponse(json.dumps({'message': error_message, })) else: - return HttpResponse(simplejson.dumps({'message': error_message, })) + return HttpResponse(json.dumps({'message': error_message, })) return render_to_response('ldt/user/login_ajax.html', context_instance=RequestContext(request))