def testOne(self):
        server = ResolveServer()
        observer = CallTrace(emptyGeneratorMethods=['add'])
        dna = be(
            (Observable(),
                (server,
                    (observer,)
                )
            )
        )
        server.listResolvables = lambda: [{'items': [{'filter': filterFoafAgents, 'partname': 'foafAgent', 'urls': ['some:url']}], 'identifier': 'urn:some:identifier'}]
        server._urlopen = lambda url: StringIO("""<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:foaf="http://xmlns.com/foaf/0.1/" xmlns:dc="http://purl.org/dc/elements/1.1/">
<rdf:Description rdf:about="http://oas.dev.seecr.nl:8000/static/dummy_foaf_agent">
<rdf:type rdf:resource="http://xmlns.com/foaf/0.1/Agent"/>
<foaf:name>Pietje Puk</foaf:name>
<dc:title>Gewillig slachtoffer</dc:title>
</rdf:Description>
</rdf:RDF>""")
        
        lico(dna.all.process())
        addCall, injectCall = observer.calledMethods
        self.assertEqualsWS("""<rdf:Description xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:foaf="http://xmlns.com/foaf/0.1/" xmlns:dc="http://purl.org/dc/elements/1.1/" rdf:about="http://oas.dev.seecr.nl:8000/static/dummy_foaf_agent">
        <rdf:type rdf:resource="http://xmlns.com/foaf/0.1/Agent"/>
        <foaf:name>Pietje Puk</foaf:name>
        <dc:title>Gewillig slachtoffer</dc:title>
        </rdf:Description>""", tostring(addCall.kwargs['lxmlNode']))
    def assertConvert(self, expected, source):
        lico(self.dna.all.process(lxmlNode=parse(StringIO(source))))

        resultNode = self.observer.calledMethods[0].kwargs['lxmlNode']
        self.assertEqualsWS(
            expected, 
            tostring(resultNode, pretty_print=True))
    def testPublishChecksForBodyInStorage(self):
        xml = """<rdf:RDF
    xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
    xmlns:oa="http://www.w3.org/ns/openannotation/core/">
    <oa:Annotation rdf:about="urn:id:1">
        <oa:hasBody rdf:resource="urn:id:2"/>
    </oa:Annotation>
</rdf:RDF>"""
        expectedXml = """<rdf:RDF
    xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
    xmlns:oa="http://www.w3.org/ns/openannotation/core/">
    <oa:Annotation rdf:about="http://some.where/here/urn%3Aid%3A1">
        <oa:hasBody>
            <xml/> 
        </oa:hasBody>
        <dc:identifier xmlns:dc="http://purl.org/dc/elements/1.1/">urn:id:1</dc:identifier>
    </oa:Annotation>
</rdf:RDF>"""
        self.store.returnValues["isAvailable"] = (False, False)

        lico(self.dna.all.process(parse(StringIO(xml))))
        self.assertEquals("isAvailable", self.store.calledMethods[0].name)
        self.assertEquals("http://some.where/here/urn%3Aid%3A2", self.store.calledMethods[0].args[0])
        self.assertEquals("oacBody", self.store.calledMethods[0].args[1])
        self.assertEquals(1, len(self.store.calledMethods))

        self.store.returnValues["isAvailable"] = (True, True)
        self.store.returnValues["getStream"] = StringIO("<xml/>")
        lico(self.dna.all.process(parse(StringIO(xml))))

        self.assertEquals("getStream", self.store.calledMethods[2].name)
        self.assertEquals(("http://some.where/here/urn%3Aid%3A2", "oacBody"), self.store.calledMethods[2].args)

        self.assertEquals("add", self.observer.calledMethods[1].name)
        self.assertEqualsWS(expectedXml, tostring(self.observer.calledMethods[1].kwargs["lxmlNode"]))
    def testPublishBodyToo(self):
        xml = """<rdf:RDF
    xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
    xmlns:oa="http://www.w3.org/ns/openannotation/core/">
    <oa:Annotation rdf:about="urn:id:1">
        <oa:hasBody>
            <oa:Body rdf:about="urn:id:2"/>
        </oa:hasBody>
    </oa:Annotation>
</rdf:RDF>"""
        lico(self.dna.all.process(parse(StringIO(xml))))
        self.assertEqualsWS(
            """<rdf:RDF
    xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
    xmlns:oa="http://www.w3.org/ns/openannotation/core/">
    <oa:Annotation rdf:about="http://some.where/here/urn%3Aid%3A1">
        <oa:hasBody>
            <oa:Body rdf:about="http://some.where/here/urn%3Aid%3A2">
                <dc:identifier xmlns:dc="http://purl.org/dc/elements/1.1/">urn:id:2</dc:identifier>
            </oa:Body>
        </oa:hasBody>
        <dc:identifier xmlns:dc="http://purl.org/dc/elements/1.1/">urn:id:1</dc:identifier>
    </oa:Annotation>
</rdf:RDF>""",
            tostring(self.observer.calledMethods[0].kwargs["lxmlNode"]),
        )
        self.assertEquals("http://some.where/here/urn%3Aid%3A2", self.store.calledMethods[0].kwargs["identifier"])
        self.assertEquals("http://some.where/here/urn%3Aid%3A1", self.observer.calledMethods[0].kwargs["identifier"])
    def testInlineSpecificResources(self):
        self.storageObserver.returnValues['isAvailable'] = (False, False)
        xml = """<rdf:RDF
            xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
            xmlns:dc="http://purl.org/dc/elements/1.1/"
            xmlns:oa="http://www.w3.org/ns/openannotation/core/">
            <oa:Annotation rdf:about="identifier:1">
                <oa:hasTarget rdf:resource="urn:id:ct:1"/>
            </oa:Annotation>

            <oa:SpecificResource rdf:about="urn:id:ct:1">
                <dc:title>Constrained Target</dc:title>    
            </oa:SpecificResource>
        </rdf:RDF>"""
        lico(self.dna.all.add(identifier="IDENTIFIER", partname="rdf", lxmlNode=parse(StringIO(xml))))
        resultNode = self.observer.calledMethods[0].kwargs['lxmlNode']
        self.assertEqualsWS("""<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">
    <oa:Annotation xmlns:oa="http://www.w3.org/ns/openannotation/core/" rdf:about="identifier:1">
                <oa:hasTarget><oa:SpecificResource xmlns:dc="http://purl.org/dc/elements/1.1/" rdf:about="urn:id:ct:1">
                <dc:title>Constrained Target</dc:title>    
            </oa:SpecificResource>
        </oa:hasTarget>
            </oa:Annotation>

            </rdf:RDF>""", tostring(resultNode))
 def testNoRdf(self):
     inputText = """<oai_dc:dc xmlns:oai_dc="http://example.org"/>"""
     try:
         lico(self.dna.all.add(identifier="IDENTIFIER", partname="rdf", lxmlNode=parse(StringIO(inputText))))
         self.fail()
     except ValidateException, e:
         self.assertEquals('No annotations found.', str(e))
    def testLogError(self):
        env = Environment(root=self.tempdir)
        repository = env.addRepository(name="test", active=True)

        self.harvest._urlopen = lambda url: StringIO(OAIPMH_ERROR_OUTPUT)

        lico(self.dna.all.process(repository))
        self.assertEquals('errorCode: error text', repository.readErrorLog())
 def testApiKeyRetrieves(self):
     self.observer.returnValues['getForApiKey'] = {'username': '******'}
     self.observer.emptyGeneratorMethods.append('add')
     __callstack_var_authorization__ = {'apiKey': 'MonkeyWrench'}
     lico(self.retrieve.add(identifier='identifier', partname='rdf', data='RDF'))
     self.assertEquals(['getForApiKey', 'add'], [m.name for m in self.observer.calledMethods])
     self.assertEquals({'apiKey':'MonkeyWrench'}, self.observer.calledMethods[0].kwargs)
     self.assertEquals(dict(identifier='identifier', partname='user', data='User Name'), self.observer.calledMethods[1].kwargs)
    def testTwo(self):
        observer = CallTrace(emptyGeneratorMethods=["add"])
        dna = be((Observable(), (IdentifierFromXPath("/a/@b"), (observer,))))

        try:
            lico(dna.all.add(identifier="wrong", partname="xxx", lxmlNode=parse(StringIO("<a x='right'/>"))))
            self.fail()
        except ValueError, e:
            self.assertEquals("Identifier not found", str(e))
    def testDontPublishIfAlreadyAnURL(self):
        xml = """<rdf:RDF
    xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
    xmlns:oa="http://www.w3.org/ns/openannotation/core/">
    <oa:Annotation rdf:about="http://some.where.else/1"/>
</rdf:RDF>"""
        lico(self.dna.all.process(parse(StringIO(xml))))
        self.assertEqualsWS(xml, tostring(self.observer.calledMethods[0].kwargs["lxmlNode"]))
        self.assertEquals("http://some.where.else/1", self.observer.calledMethods[0].kwargs["identifier"])
    def testPassThroughResource(self):
        xml = """<rdf:RDF 
        xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
        xmlns:oa="http://www.w3.org/ns/openannotation/core/"> 
    <oa:Annotation rdf:resource="urn:id:1"/>
</rdf:RDF>"""

        lico(self.dna.all.process(lxmlNode=parse(StringIO(xml))))
        self.assertEquals(1, len(self.observer.calledMethods))
        self.assertEqualsWS(xml, tostring(self.observer.calledMethods[0].kwargs['lxmlNode']))
    def testAddDeleteWithoutResumption(self):
        env = Environment(root=self.tempdir)
        repository = env.addRepository(name="test", active=True)

        self.harvest._urlopen = lambda url: StringIO(OAIPMH_OUTPUT)

        lico(self.dna.all.process(repository))
        self.assertEquals(['add', 'delete'], [m.name for m in self.observer.calledMethods])
        self.assertEquals('', repository.resumptionToken)
        self.assertFalse(repository.active)
 def testWithSubTypes(self):
     lico(self.dna.all.add(identifier="identifier", partname="partname", lxmlNode=parse(StringIO("""<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:oa="%(oa)s">
         <oa:Annotation rdf:about="urn:uuid:10482225-56e3-4a5c-801b-690379aff7ac">
             <rdf:type rdf:resource="http://this.is.my/type"/>
             <rdf:type rdf:resource="http://this.is.my/type/to"/>
         </oa:Annotation>
     </rdf:RDF>""" % namespaces))))
     self.assertEquals(3*['addField'], [m.name for m in self.observer.calledMethods])
     self.assertEquals(dict(name="rdf:type", value="%(oa)sAnnotation" % namespaces), self.observer.calledMethods[0].kwargs)
     self.assertEquals(dict(name="rdf:type", value="http://this.is.my/type"), self.observer.calledMethods[1].kwargs)
     self.assertEquals(dict(name="rdf:type", value="http://this.is.my/type/to"), self.observer.calledMethods[2].kwargs)
    def testAddUrn(self):
        xml = """<rdf:RDF 
        xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
        xmlns:oa="http://www.w3.org/ns/openannotation/core/"> 
    <oa:Annotation%s/>
</rdf:RDF>"""

        newIdentifier = 'urn:some:form:of:identifier'
        self.deanonymize._urnGen = lambda: newIdentifier
        lico(self.dna.all.process(lxmlNode=parse(StringIO(xml % ""))))
        self.assertEquals(1, len(self.observer.calledMethods))
        self.assertEqualsWS(xml % ' rdf:about="%s"' % newIdentifier, tostring(self.observer.calledMethods[0].kwargs['lxmlNode']))
 def testHasBodyInRdfType(self):
     lico(self.dna.all.add(identifier="identifier", partname="partname", lxmlNode=parse(StringIO("""<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:oa="%(oa)s">
         <oa:Annotation rdf:about="urn:uuid:10482225-56e3-4a5c-801b-690379aff7ac">
             <oa:hasBody>
                 <oa:SpecificResource rdf:about="urn:nr:1">
                     <rdf:type rdf:resource="http://www.catchplus.nl/annotation/MonkTranscription"/>
                 </oa:SpecificResource>
             </oa:hasBody>
         </oa:Annotation>
     </rdf:RDF>""" % namespaces))))
     self.assertEquals(2*['addField'], [m.name for m in self.observer.calledMethods])
     self.assertEquals(dict(name="rdf:type", value="%(oa)sAnnotation" % namespaces), self.observer.calledMethods[0].kwargs)
     self.assertEquals(dict(name="rdf:type", value='http://www.catchplus.nl/annotation/MonkTranscription'), self.observer.calledMethods[1].kwargs)
    def testPublishChecksForSpecificResourceInStorage(self):
        xml = """<rdf:RDF 
    xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" 
    xmlns:oa="http://www.w3.org/ns/openannotation/core/"
    xmlns:dc="http://purl.org/dc/elements/1.1/"
    xmlns:foaf="http://xmlns.com/foaf/0.1/">

    <oa:Annotation rdf:about="urn:uuid:1505e7d8-6462-4536-a3ae-944a08ce540c">
        <oa:hasTarget rdf:resource="urn:id:ct:1"/>
    </oa:Annotation>
</rdf:RDF>"""
        specificResource = """<oa:SpecificResource 
        xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" 
        xmlns:oa="http://www.w3.org/ns/openannotation/core/" 
        rdf:about="urn:id:ct:1">
    </oa:SpecificResource>"""
        expectedXml = """<rdf:RDF 
    xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" 
    xmlns:oa="http://www.w3.org/ns/openannotation/core/"
    xmlns:dc="http://purl.org/dc/elements/1.1/"
    xmlns:foaf="http://xmlns.com/foaf/0.1/">

    <oa:Annotation rdf:about="http://some.where/here/urn%3Auuid%3A1505e7d8-6462-4536-a3ae-944a08ce540c">
        <oa:hasTarget>
            <oa:SpecificResource rdf:about="http://some.where/here/urn%3Aid%3Act%3A1">
                <dc:identifier>urn:id:ct:1</dc:identifier>
            </oa:SpecificResource>
        </oa:hasTarget>
        <dc:identifier>urn:uuid:1505e7d8-6462-4536-a3ae-944a08ce540c</dc:identifier>
    </oa:Annotation>
</rdf:RDF>"""

        self.store.returnValues["isAvailable"] = (False, False)

        lico(self.dna.all.process(parse(StringIO(xml))))
        self.assertEquals("isAvailable", self.store.calledMethods[0].name)
        self.assertEquals("http://some.where/here/urn%3Aid%3Act%3A1", self.store.calledMethods[0].args[0])
        self.assertEquals("oacConstrainedTarget", self.store.calledMethods[0].args[1])
        self.assertEquals(1, len(self.store.calledMethods))

        self.store.returnValues["isAvailable"] = (True, True)
        self.store.returnValues["getStream"] = StringIO(specificResource)
        lico(self.dna.all.process(parse(StringIO(xml))))

        self.assertEquals("getStream", self.store.calledMethods[2].name)
        self.assertEquals(
            ("http://some.where/here/urn%3Aid%3Act%3A1", "oacConstrainedTarget"), self.store.calledMethods[2].args
        )

        self.assertEquals("add", self.observer.calledMethods[1].name)
        self.assertEqualsWS(expectedXml, tostring(self.observer.calledMethods[1].kwargs["lxmlNode"]))
 def testNoIdentifier(self):
     inputText = """
     <rdf:RDF
         xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
         xmlns:some="http://www.example.org/ns/">
         <rdf:Description rdf:about="identifier:1">
             <some:tag/>
         </rdf:Description>
     </rdf:RDF>"""
     try:
         lico(self.dna.all.add(identifier="IDENTIFIER", partname="rdf", lxmlNode=parse(StringIO(inputText))))
         self.fail()
     except ValidateException, e:
         self.assertEquals('No annotations found.', str(e))
    def testUrnNotInSelfAndNotInStorage(self):
        self.storageObserver.returnValues['isAvailable'] = (False, False)
        xml = """<rdf:RDF
            xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
            xmlns:foaf="http://xmlns.com/foaf/0.1/"
            xmlns:oa="http://www.w3.org/ns/openannotation/core/">
            <oa:Annotation rdf:about="identifier:1">
                <oa:annotatedBy rdf:resource="urn:othercreator"/>
            </oa:Annotation>
        </rdf:RDF>"""
        lico(self.dna.all.add(identifier="IDENTIFIER", partname="rdf", lxmlNode=parse(StringIO(xml))))
        resultNode = self.observer.calledMethods[0].kwargs['lxmlNode']
        self.assertEqualsWS("""<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">
    <oa:Annotation xmlns:oa="http://www.w3.org/ns/openannotation/core/" rdf:about="identifier:1">
        <oa:annotatedBy rdf:resource="urn:othercreator"/>
    </oa:Annotation>
</rdf:RDF>""", tostring(resultNode))
    def testOne(self):
        XML = """
        <rdf:RDF 
            xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
            xmlns:oa="http://www.w3.org/ns/openannotation/core/">
            <rdf:Description rdf:about="identifier:1">
                <rdf:type rdf:resource="http://www.w3.org/ns/openannotation/core/Annotation"/>
            </rdf:Description>
            <oa:Annotation rdf:about="identifier:2"/>
            <rdf:Description rdf:about="identifier:3">
                <rdf:type rdf:resource="http://www.w3.org/ns/openannotation/core/Annotation"/>
            </rdf:Description>
        </rdf:RDF>
        """

        lico(self.dna.all.add(identifier="IDENTIFIER", partname="rdf", lxmlNode=parse(StringIO(XML))))
        self.assertEquals(3, len(self.observer.calledMethods))
    def testOne(self):
        dna = be(
            (Observable(),
                (ApiKeyCheck(),)
            )
        )

        response = lico(dna.all.handleRequest())
        self.assertEquals([unauthorizedHtml], response)
    def testInlineURNFromStorage(self):
        xml = """<rdf:RDF
            xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
            xmlns:foaf="http://xmlns.com/foaf/0.1/"
            xmlns:oa="http://www.w3.org/ns/openannotation/core/">
            <oa:Annotation rdf:about="identifier:1">
                <oa:annotatedBy rdf:resource="urn:creator"/>
            </oa:Annotation>
        </rdf:RDF>"""
        lico(self.dna.all.add(identifier="IDENTIFIER", partname="rdf", lxmlNode=parse(StringIO(xml))))
        resultNode = self.observer.calledMethods[0].kwargs['lxmlNode']
        self.assertEqualsWS("""<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">
    <oa:Annotation xmlns:oa="http://www.w3.org/ns/openannotation/core/" rdf:about="identifier:1">
        <oa:annotatedBy>
            <foaf:Agent xmlns:foaf="http://xmlns.com/foaf/0.1/" rdf:about="urn:creator">
                <foaf:mbox>[email protected]</foaf:mbox>
            </foaf:Agent>
        </oa:annotatedBy>
    </oa:Annotation>
</rdf:RDF>""", tostring(resultNode))
    def testInlineURNs(self):
        xml = """<rdf:RDF
            xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
            xmlns:foaf="http://xmlns.com/foaf/0.1/"
            xmlns:oa="http://www.w3.org/ns/openannotation/core/"
            xmlns:dc="http://purl.org/dc/elements/1.1/">
            <oa:Annotation rdf:about="identifier:1">
                <oa:annotatedBy rdf:resource="urn:creator"/>
                <oa:hasBody rdf:resource="urn:body"/>
            </oa:Annotation>
            <rdf:Description rdf:about="urn:creator">
               <rdf:type rdf:resource="http://xmlns.com/foaf/0.1/Agent"/>
               <foaf:mbox>[email protected]</foaf:mbox>
            </rdf:Description>
            <rdf:Description rdf:about="urn:body">
               <rdf:type rdf:resource="http://www.w3.org/ns/openannotation/core/Body"/>
               <dc:title>This is the body</dc:title>
            </rdf:Description>
        </rdf:RDF>"""
        lico(self.dna.all.add(identifier="IDENTIFIER", partname="rdf", lxmlNode=parse(StringIO(xml))))
        resultNode = self.observer.calledMethods[0].kwargs['lxmlNode']
        self.assertEqualsWS("""<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">
    <oa:Annotation xmlns:oa="http://www.w3.org/ns/openannotation/core/" rdf:about="identifier:1">
        <oa:annotatedBy>
            <rdf:Description xmlns:foaf="http://xmlns.com/foaf/0.1/" rdf:about="urn:creator">
                <rdf:type rdf:resource="http://xmlns.com/foaf/0.1/Agent"/>
                <foaf:mbox>[email protected]</foaf:mbox>
            </rdf:Description>
        </oa:annotatedBy>
        <oa:hasBody>
            <rdf:Description xmlns:dc="http://purl.org/dc/elements/1.1/" rdf:about="urn:body">
                <rdf:type rdf:resource="http://www.w3.org/ns/openannotation/core/Body"/>
                <dc:title>This is the body</dc:title>
            </rdf:Description>
        </oa:hasBody>
    </oa:Annotation>
</rdf:RDF>""", tostring(resultNode))
    def testAdd(self):
        sruUpload = SruUpload(apiKey="apiKey")
        socket = CallTrace()

        answers = ["""HTTP/1.0 200 OK\r\n\r\n""", SUCCESS_SRU_UPLOAD_RESPONSE, ""]
        def recv(size):
            return answers.pop(0)
            
        socket.methods['recv'] = recv
        sruUpload._socket = lambda: socket

        lico(sruUpload.add(identifier="IDENTIFIER", lxmlNode=parse(StringIO("""<oai:record xmlns:oai="%(oai)s"><oai:metadata><xml/></oai:metadata></oai:record>""" % namespaces))))
        self.assertEquals([
            "connect(('localhost', 8000))", 
            "send('POST /update HTTP/1.0\r\n')", 
            "send('Content-Type: text/xml\r\n')", 
            "send('Content-Length: 609\r\n')", 
            "send('Authorization: apiKey\r\n')", 
            "send('\r\n')", 
            'sendall(\'<ucp:updateRequest xmlns:ucp="info:lc/xmlns/update-v1">\n            <srw:version xmlns:srw="http://www.loc.gov/zing/srw/">1.0</srw:version>\n            <ucp:action>info:srw/action/1/replace</ucp:action>\n            <ucp:recordIdentifier>IGNORED</ucp:recordIdentifier>\n            <srw:record xmlns:srw="http://www.loc.gov/zing/srw/">\n                <srw:recordPacking>xml</srw:recordPacking>\n                <srw:recordSchema>rdf</srw:recordSchema>\n                <srw:recordData><xml xmlns:oai="http://www.openarchives.org/OAI/2.0/"/></srw:recordData>\n            </srw:record>\n        </ucp:updateRequest>\')', 
            'recv(1024)', 
            'recv(1024)', 
            'recv(1024)', 
            'close()'], [str(m) for m in socket.calledMethods])
    def testDelete(self):
        sruUpload = SruUpload(apiKey="apiKey")
        socket = CallTrace()

        answers = ["""HTTP/1.0 200 OK\r\n\r\n""", SUCCESS_SRU_UPLOAD_RESPONSE, ""]
        def recv(size):
            return answers.pop(0)
            
        socket.methods['recv'] = recv
        sruUpload._socket = lambda: socket

        lico(sruUpload.delete(identifier="IDENTIFIER"))
        self.assertEquals([
            "connect(('localhost', 8000))", 
            "send('POST /update HTTP/1.0\r\n')", 
            "send('Content-Type: text/xml\r\n')", 
            "send('Content-Length: 298\r\n')", 
            "send('Authorization: apiKey\r\n')", 
            "send('\r\n')", 
            'sendall(\'<ucp:updateRequest xmlns:ucp="info:lc/xmlns/update-v1">\n            <srw:version xmlns:srw="http://www.loc.gov/zing/srw/">1.0</srw:version>\n            <ucp:action>info:srw/action/1/delete</ucp:action>\n            <ucp:recordIdentifier>IDENTIFIER</ucp:recordIdentifier>\n        </ucp:updateRequest>\')', 
            'recv(1024)', 
            'recv(1024)', 
            'recv(1024)', 
            'close()'], [str(m) for m in socket.calledMethods])
    def testUnknownApiKeyForAdd(self):
        def getForApiKey(apiKey):
            return None
        observer = CallTrace(
            methods={'getForApiKey': getForApiKey}, 
            emptyGeneratorMethods=['add'])

        __callstack_var_authorization__ = {'apiKey': "APIKEY"}

        dna = be(
            (Observable(),
                (ApiKeyCheck(),
                    (observer, )
                )
            )
        )
        self.assertRaises(ValueError, lambda: lico(dna.all.add(identifier='bla')))
        self.assertEquals(['getForApiKey'], [m.name for m in observer.calledMethods])
    def testUnknownApiKey(self):
        def getForApiKey(apiKey):
            return None
        observer = CallTrace(
            methods={'getForApiKey': getForApiKey}, 
            emptyGeneratorMethods=['handleRequest'])

        __callstack_var_authorization__ = {'apiKey': "APIKEY"}

        dna = be(
            (Observable(),
                (ApiKeyCheck(),
                    (observer, )
                )
            )
        )
        response = lico(dna.all.handleRequest())
        self.assertEquals([unauthorizedHtml], response)
        self.assertEquals(['getForApiKey'], [m.name for m in observer.calledMethods])
 def testAdd(self):
     lico(self.data2field.add(identifier='identifier', partname='part', data='somedata'))
     self.assertEquals(['addField'], [m.name for m in self.observer.calledMethods])
     self.assertEquals(dict(name='field', value='somedata'), self.observer.calledMethods[0].kwargs)
    def testOne(self):
        observer = CallTrace(emptyGeneratorMethods=["add"])
        dna = be((Observable(), (IdentifierFromXPath("/a/@b"), (observer,))))

        lico(dna.all.add(identifier="wrong", partname="xxx", lxmlNode=parse(StringIO("<a b='right'/>"))))
        self.assertEquals("right", observer.calledMethods[0].kwargs["identifier"])
 def testNoApiKey(self):
     self.assertRaises(AttributeError, lambda: lico(self.retrieve.add(identifier='identifier', partname='rdf', data='RDF')))
 def testFailedUpload(self):
     sruUpload = SruUpload(apiKey="apiKey")
     sruUpload._send = lambda data: "HTTP/1.0 200 Ok\r\n\r\n" + FAILED_SRU_UPLOAD_RESPONSE
     self.assertRaises(SruUploadException, lambda: lico(sruUpload.add(identifier="IDENTIFIER", lxmlNode=parse(StringIO("""<oai:record xmlns:oai="%(oai)s"><oai:metadata><xml/></oai:metadata></oai:record>""" % namespaces)))))