Skip to content

Commit

Permalink
Merge pull request #35 from Capitains/various-issues
Browse files Browse the repository at this point in the history
Various issues
  • Loading branch information
PonteIneptique committed Sep 7, 2015
2 parents 0415326 + fb688bf commit fcc4c2b
Show file tree
Hide file tree
Showing 10 changed files with 124 additions and 30 deletions.
40 changes: 37 additions & 3 deletions MyCapytain/common/metadata.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,10 @@
from collections import defaultdict, OrderedDict
from past.builtins import basestring
from builtins import range, object
from copy import copy


class Metadatum(object):

""" Metadatum object represent a single field of metadata
:param name: Name of the field
Expand All @@ -33,7 +33,6 @@ class Metadatum(object):
.. automethod:: __iter__
"""


def __init__(self, name, children=None):
""" Initiate a Metadatum object
Expand Down Expand Up @@ -96,7 +95,7 @@ def __setitem__(self, key, value):
:raises: `ValueError` if key and value are list and are not the same size
:Example:
>>> a = Metadata(name="label")
>>> a = Metadatum(name="label")
>>> a["eng"] = "Illiad"
>>> print(a["eng"]) # Illiad
Expand Down Expand Up @@ -156,6 +155,18 @@ def __iter__(self):
yield (key, self.children[key])
i += 1

def __len__(self):
""" Get the length of the current Metadatum object
:return: Number of variant of the metadatum
:rtype: int
:Example:
>>> a = Metadata(name="label", [("lat", "Amores"), ("fre", "Les Amours")])
>>> len(a) == 2
"""
return len(self.children)


class Metadata(object):
"""
Expand All @@ -170,6 +181,7 @@ class Metadata(object):
.. automethod:: __setitem__
.. automethod:: __iter__
.. automethod:: __len__
.. automethod:: __add__
"""
def __init__(self, keys=None):
""" Initiate the object
Expand Down Expand Up @@ -268,6 +280,28 @@ def __iter__(self):
yield (key, self.metadata[key])
i += 1

def __add__(self, other):
""" Merge Metadata objects together
:param other: Metadata object to merge with the current one
:type other: Metadata
:returns: The merge result of both metadata object
:rtype: Metadata
:Example:
>>> a = Metadata(name="label")
>>> b = Metadata(name="title")
>>> a + b == Metadata(name=["label", "title"])
"""
result = copy(self)
for metadata_key, metadatum in other:
if metadata_key in self.__keys:
for key, value in metadatum:
result[metadata_key][key] = value
else:
result[metadata_key] = metadatum
return result

def __len__(self):
""" Returns the number of Metadatum registered in the object
Expand Down
41 changes: 24 additions & 17 deletions MyCapytain/resources/inventory.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
"""
from __future__ import unicode_literals

from MyCapytain.resources.proto import inventory
from MyCapytain.resources.proto import inventory, text
from MyCapytain.common.reference import Citation as CitationPrototype
from MyCapytain.common.utils import xmlparser, NS

Expand Down Expand Up @@ -164,15 +164,22 @@ def __str__(self):
strings.append("</ti:{0}>".format(tag_end))
return "".join(strings)

def export(self, format="xml"):
def export(self, output="xml", **kwargs):
""" Create a {format} version of the Work
:param format: Format to be chosen (Only XML for now)
:type param: basestring
:param output: Format to be chosen (Only XML for now)
:type output: basestring, citation
:rtype: lxml.etree._Element
:returns: XML representation of the object
"""
return xmlparser(str(self))
if output == "xml":
return xmlparser(str(self))
elif issubclass(output, text.Text):
complete_metadata = self.metadata
for parent in self.parents:
if isinstance(parent, inventory.Resource):
complete_metadata = complete_metadata + parent.metadata
return output(urn=self.urn, citation=self.citation, metadata=complete_metadata, **kwargs)

def __findCitations(self, xml, element, xpath="ti:citation"):
""" Find citation in current xml. Used as a loop for self.xmlparser()
Expand Down Expand Up @@ -206,7 +213,6 @@ def __findCitations(self, xml, element, xpath="ti:citation"):
element=self.citation
)


def parse(self, resource):
""" Parse a resource to feed the object
Expand Down Expand Up @@ -249,17 +255,18 @@ def parse(self, resource):
return None



def Edition(resource=None, urn=None, parents=None):
""" Create an edition subtyped Text object
"""
return Text(resource=resource, urn=urn, parents=parents, subtype="Edition")


def Translation(resource=None, urn=None, parents=None):
""" Create a translation subtyped Text object
"""
return Text(resource=resource, urn=urn, parents=parents, subtype="Translation")


class Work(inventory.Work):

""" Represents a CTS Textgroup in XML
Expand Down Expand Up @@ -298,11 +305,11 @@ def __str__(self):
strings.append("</ti:work>")
return "".join(strings)

def export(self, format="xml"):
def export(self, output="xml"):
""" Create a {format} version of the Work
:param format: Format to be chosen (Only XML for now)
:type param: basestring
:param output: Format to be chosen (Only XML for now)
:type output: basestring
:rtype: lxml.etree._Element
:returns: XML representation of the object
"""
Expand Down Expand Up @@ -378,11 +385,11 @@ def __str__(self):
strings.append("</ti:textgroup>")
return "".join(strings)

def export(self, format="xml"):
def export(self, output="xml"):
""" Create a {format} version of the TextInventory
:param format: Format to be chosen (Only XML for now)
:type param: basestring
:param output: Format to be chosen (Only XML for now)
:type output: basestring
:rtype: lxml.etree._Element
:returns: XML representation of the object
"""
Expand Down Expand Up @@ -437,11 +444,11 @@ def __str__(self):
strings.append("</ti:TextInventory>")
return "".join(strings)

def export(self, format="xml"):
""" Create a {format} version of the TextInventory
def export(self, output="xml"):
""" Create a {output} version of the TextInventory
:param format: Format to be chosen (Only XML for now)
:type param: basestring
:param output: output to be chosen (Only XML for now)
:type output: basestring
:rtype: lxml.etree._Element
:returns: XML representation of the object
"""
Expand Down
12 changes: 8 additions & 4 deletions MyCapytain/resources/proto/text.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,8 @@
"""
from past.builtins import basestring

from MyCapytain.resources.proto import inventory
import MyCapytain.common.reference
import MyCapytain.common.metadata
from collections import namedtuple

PassagePlus = namedtuple("PassagePlus", ["passage", "prev", "next"])
Expand All @@ -24,7 +24,7 @@ class Resource(object):
:type resource: Any
"""

def __init__(self, urn=None, resource= None):
def __init__(self, urn=None, resource=None):
self.resource = None
self._URN = None

Expand Down Expand Up @@ -129,14 +129,18 @@ def children(self):

class Text(Resource):
""" A CTS Text """
def __init__(self, citation=None, **kwargs):
def __init__(self, citation=None, metadata=None, **kwargs):
super(Text, self).__init__(**kwargs)

self._cRefPattern = MyCapytain.common.reference.Citation()

if citation is not None:
self.citation = citation

if metadata is not None:
self.metadata = metadata
else:
self.metadata = MyCapytain.common.metadata.Metadata()

def getValidReff(self, level=1, reference=None):
""" Given a resource, Text will compute valid reffs
Expand Down
Empty file.
3 changes: 1 addition & 2 deletions MyCapytain/resources/texts/local.py
Original file line number Diff line number Diff line change
Expand Up @@ -341,8 +341,7 @@ def next(self):
self.__next = n.first

return self.__next



@property
def prev(self):
""" Previous passage
Expand Down
25 changes: 25 additions & 0 deletions tests/common/test_metadata.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,13 @@ def test_override_default(self):
with six.assertRaisesRegex(self, ValueError, "Can not set a default to an unknown key"):
a.setDefault(None)

def test_len(self):
a = Metadatum("title", [
("eng", "Epigrams"),
("fre", "Epigrammes")
])
self.assertEqual(len(a), 2)

def test_get_item(self):
a = Metadatum("title", [
("eng", "Epigrams"),
Expand Down Expand Up @@ -185,3 +192,21 @@ def test_len(self):
self.assertEqual(len(a), 2)
a["z"] = 1.5
self.assertEqual(len(a), 2)

def test_add(self):
""" Test sum of two Metadata objects """
a = Metadata()
m1 = Metadatum("desc", [("eng", "desc")])
m2 = Metadatum("label", [("eng", "lbl"), ("fre", "label")])
a["desc"] = m1
a["label"] = m2

b = Metadata()
m3 = Metadatum("desc", [("fre", "Omelette")])
m4 = Metadatum("title", [("eng", "ttl"), ("fre", "titre")])
b[("desc", "title")] = (m3, m4)

c = a + b
self.assertEqual(len(c), 3)
self.assertEqual(len(c["desc"]), 2)

11 changes: 11 additions & 0 deletions tests/resources/proto/test_text.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
from collections import defaultdict
from MyCapytain.resources.proto.text import *
import MyCapytain.common.reference
import MyCapytain.common.metadata

class TestProtoResource(unittest.TestCase):
""" Test for resource, mother class of Text and Passage """
Expand Down Expand Up @@ -42,6 +43,7 @@ def test_urn(self):
b = Text(urn="urn:cts:latinLit:tg.wk.v")
self.assertEqual(str(b.urn), "urn:cts:latinLit:tg.wk.v")


class TestProtoText(unittest.TestCase):
""" Test the text prototype, mainly to ensure consistency """

Expand All @@ -56,6 +58,15 @@ def test_init(self):
a.resource = True
self.assertEqual(a.resource, True)

# Test with metadata
a = Text()
self.assertIsInstance(a.metadata, MyCapytain.common.metadata.Metadata)

m = MyCapytain.common.metadata.Metadata(keys=["title", "author"])
m["title"]["fre"] = "I am a metadata"
a = Text(metadata=m)
self.assertEqual(a.metadata["title"]["fre"], "I am a metadata")

def test_proto_reff(self):
""" Test that getValidReff function are not implemented """
a = Text()
Expand Down
16 changes: 15 additions & 1 deletion tests/resources/test_inventory.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
from six import text_type as str

from MyCapytain.resources.inventory import *
import MyCapytain.resources.proto.text


def compareSTR(one, other):
Expand Down Expand Up @@ -160,7 +161,6 @@ def test_parse_error(self):
resource=5
)


def test_Inventory_metadata(self):
""" Tests TextInventory parses without errors """
TI = TextInventory(resource=self.getCapabilities, id="annotsrc")
Expand Down Expand Up @@ -224,6 +224,20 @@ def test_export(self):
self.assertXmlEquivalentOutputs(*compareXML(ti["urn='urn:cts:latinLit:phi1294.phi002.perseus-eng2"].export(), tr))
self.assertXmlEquivalentOutputs(*compareXML(ti["urn='urn:cts:latinLit:phi1294.phi002.perseus-lat2"].export(), ed))

def test_export_to_text(self):
""" Test export to Text object """
TI = TextInventory(resource=self.getCapabilities, id="annotsrc")
ti_text = TI["urn:cts:latinLit:phi1294.phi002.perseus-lat2"]

txt_text = ti_text.export(output=MyCapytain.resources.proto.text.Text)
self.assertEqual(str(txt_text.urn), "urn:cts:latinLit:phi1294.phi002.perseus-lat2")
self.assertEqual(txt_text.metadata["groupname"]["eng"], "Martial") # Check inheritance of textgroup metadata
self.assertEqual(txt_text.metadata["title"]["eng"], "Epigrammata") # Check inheritance of work metadata
self.assertEqual(txt_text.metadata["title"]["fre"], "Epigrammes") # Check inheritance of work metadata
self.assertEqual(txt_text.metadata["description"]["fre"], "G. Heraeus") # Check inheritance of work metadata
self.assertEqual(txt_text.citation, ti_text.citation)
self.assertEqual(txt_text.citation.scope, "/tei:TEI/tei:text/tei:body/tei:div")

def test_partial_str(self):
ti = TextInventory(resource=self.t, id="annotsrc")

Expand Down
6 changes: 3 additions & 3 deletions tests/testing_data/cts/getCapabilities.xml
Original file line number Diff line number Diff line change
Expand Up @@ -255,9 +255,9 @@
<ti:validate schema="tei-epidoc.rng"/>
<ti:namespaceMapping abbreviation="tei" nsURI="http://www.tei-c.org/ns/1.0"/>
<ti:citationMapping>
<ti:citation label="unknown" xpath="/tei:div[@n='?']" scope="/tei:TEI/tei:text/tei:body/tei:div">
<ti:citation label="unknown" xpath="/tei:div[@n='?']" scope="/tei:TEI/tei:text/tei:body/tei:div/tei:div[@n='?']">
<ti:citation label="unknown" xpath="/tei:l[@n='?']" scope="/tei:TEI/tei:text/tei:body/tei:div/tei:div[@n='?']/tei:div[@n='?']"/>
<ti:citation label="book" xpath="/tei:div[@n='?']" scope="/tei:TEI/tei:text/tei:body/tei:div">
<ti:citation label="poem" xpath="/tei:div[@n='?']" scope="/tei:TEI/tei:text/tei:body/tei:div/tei:div[@n='?']">
<ti:citation label="line" xpath="/tei:l[@n='?']" scope="/tei:TEI/tei:text/tei:body/tei:div/tei:div[@n='?']/tei:div[@n='?']"/>
</ti:citation>
</ti:citation>
</ti:citationMapping>
Expand Down
Empty file.

0 comments on commit fcc4c2b

Please sign in to comment.