本文整理汇总了Python中meresco.core.Observable.addObserver方法的典型用法代码示例。如果您正苦于以下问题:Python Observable.addObserver方法的具体用法?Python Observable.addObserver怎么用?Python Observable.addObserver使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类meresco.core.Observable
的用法示例。
在下文中一共展示了Observable.addObserver方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: testOne
# 需要导入模块: from meresco.core import Observable [as 别名]
# 或者: from meresco.core.Observable import addObserver [as 别名]
def testOne(self):
observable = Observable()
bitMatrixRow = CallTrace('BitMatrixRow')
multi = MultiLevelDrilldown(
{'date':[('datelevel1', 10, False)]}
)
drilldown = CallTrace('Drilldown')
def dd(*args, **kwargs):
raise StopIteration(iter([('datelevel1', iter([('2008',13),('2007',10)]))]))
yield
drilldown.methods['drilldown'] = dd
multi.addObserver(drilldown)
observable.addObserver(multi)
result = list(compose(observable.call.multiLevelDrilldown(bitMatrixRow, ['date'])))
self.assertEquals(1, len(drilldown.calledMethods))
drilldownMethod = drilldown.calledMethods[0]
self.assertEquals('drilldown', drilldownMethod.name)
self.assertEquals((bitMatrixRow, [('datelevel1', 10, False)]), drilldownMethod.args)
self.assertEquals(1, len(result))
(inputFieldName, realFieldName), termCounts = result[0]
self.assertEquals('date', inputFieldName)
self.assertEquals('datelevel1', realFieldName)
self.assertEquals([('2008',13),('2007',10)], list(termCounts))
示例2: testProvenance
# 需要导入模块: from meresco.core import Observable [as 别名]
# 或者: from meresco.core.Observable import addObserver [as 别名]
def testProvenance(self):
observable = Observable()
provenance = OaiProvenance(
nsMap = {'oai_dc': "http://www.openarchives.org/OAI/2.0/"},
baseURL = ('meta', '/meta/repository/baseurl/text()'),
harvestDate = ('meta', '/meta/repository/harvestDate/text()'),
metadataNamespace = ('meta', '/meta/repository/metadataNamespace/text()'),
identifier = ('header','/oai_dc:header/oai_dc:identifier/text()'),
datestamp = ('header', '/oai_dc:header/oai_dc:datestamp/text()')
)
observable.addObserver(provenance)
observer = MockStorage()
provenance.addObserver(observer)
result = asString(observable.any.provenance("recordId"))
self.assertEqualsWS("""<provenance xmlns="http://www.openarchives.org/OAI/2.0/provenance"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.openarchives.org/OAI/2.0/provenance
http://www.openarchives.org/OAI/2.0/provenance.xsd">
<originDescription harvestDate="HARVESTDATE" altered="true">
<baseURL>BASEURL</baseURL>
<identifier>recordId</identifier>
<datestamp>DATESTAMP</datestamp>
<metadataNamespace>METADATANAMESPACE</metadataNamespace>
</originDescription>
</provenance>""", result)
示例3: testRemoteExecuteQuery
# 需要导入模块: from meresco.core import Observable [as 别名]
# 或者: from meresco.core.Observable import addObserver [as 别名]
def testRemoteExecuteQuery(self):
http = CallTrace('http')
def httppost(*args, **kwargs):
raise StopIteration('HTTP/1.0 200 Ok\r\n\r\n%s' % LuceneResponse(total=5, hits=[Hit("1"), Hit("2"), Hit("3", duplicateCount=2), Hit("4"), Hit("5")]).asJson())
yield
http.methods['httppost'] = httppost
remote = LuceneRemote(host='host', port=1234, path='/path')
observable = Observable()
observable.addObserver(remote)
remote._httppost = http.httppost
cq = ComposedQuery('coreA')
cq.setCoreQuery(
core='coreA',
query=parseString('query AND field=value'),
filterQueries=[parseString('query=fiets')],
facets=[{'fieldname': 'field', 'maxTerms':5}],
)
cq.setCoreQuery(core='coreB', query=parseString('query=test'))
cq.addMatch(dict(core='coreA', uniqueKey='keyA'), dict(core='coreB', key='keyB'))
result = returnValueFromGenerator(observable.any.executeComposedQuery(query=cq))
self.assertEquals(5, result.total)
self.assertEquals([Hit("1"), Hit("2"), Hit("3", duplicateCount=2), Hit("4"), Hit("5")], result.hits)
self.assertEquals(['httppost'], http.calledMethodNames())
m = http.calledMethods[0]
self.assertEquals('host', m.kwargs['host'])
self.assertEquals(1234, m.kwargs['port'])
self.assertEquals('/path/__lucene_remote__', m.kwargs['request'])
self.assertEquals('application/json', m.kwargs['headers']['Content-Type'])
message, kwargs = Conversion().jsonLoadMessage(m.kwargs['body'])
query = kwargs['query']
self.assertEquals('executeComposedQuery', message)
self.assertEquals('coreA', query.resultsFrom)
self.assertEquals([{'fieldname': 'field', 'maxTerms':5}], query.facetsFor('coreA'))
示例4: testXmlPrintLxmlPrettyPrintFalse
# 需要导入模块: from meresco.core import Observable [as 别名]
# 或者: from meresco.core.Observable import addObserver [as 别名]
def testXmlPrintLxmlPrettyPrintFalse(self):
observable = Observable()
xmlprintlxml = XmlPrintLxml(fromKwarg='lxmlNode', toKwarg="data", pretty_print=False)
observer = CallTrace('observer', emptyGeneratorMethods=['someMessage'])
xmlprintlxml.addObserver(observer)
observable.addObserver(xmlprintlxml)
list(compose(observable.all.someMessage(lxmlNode=parse(StringIO('<a><b>“c</b></a>')))))
self.assertEquals(['someMessage'], observer.calledMethodNames())
self.assertEquals(['data'], observer.calledMethods[0].kwargs.keys())
self.assertEquals('''<a><b>“c</b></a>''', observer.calledMethods[0].kwargs['data'])
示例5: testDeclineOtherMessages
# 需要导入模块: from meresco.core import Observable [as 别名]
# 或者: from meresco.core.Observable import addObserver [as 别名]
def testDeclineOtherMessages(self):
class Other(object):
def aMessage(self):
raise StopIteration('Thanks')
yield
remote = LuceneRemote(host='host', port=1234, path='/path')
observable = Observable()
observable.addObserver(remote)
observable.addObserver(Other())
result = returnValueFromGenerator(observable.any.aMessage())
self.assertEquals('Thanks', result)
示例6: testTransparency
# 需要导入模块: from meresco.core import Observable [as 别名]
# 或者: from meresco.core.Observable import addObserver [as 别名]
def testTransparency(self):
observable = Observable()
rename = PathRename(lambda path: '/new'+path)
interceptor = CallTrace('interceptor')
observable.addObserver(rename)
rename.addObserver(interceptor)
observable.do.otherMethod('attribute')
self.assertEquals(1, len(interceptor.calledMethods))
self.assertEquals("otherMethod('attribute')", str(interceptor.calledMethods[0]))
示例7: ValidateTest
# 需要导入模块: from meresco.core import Observable [as 别名]
# 或者: from meresco.core.Observable import addObserver [as 别名]
class ValidateTest(SeecrTestCase):
def setUp(self):
SeecrTestCase.setUp(self)
self.validate = Validate(xsd)
self.interceptor = CallTrace('interceptor', returnValues={
'all_unknown': (x for x in ['done']),
'any_unknown': (x for x in ['done']),
'do_unknown': None,
'call_unknown': 'done',
'logException': None}, onlySpecifiedMethods=True)
self.validate.addObserver(self.interceptor)
self.observable = Observable()
self.observable.addObserver(self.validate)
def testValid(self):
validXml = '<lom xmlns="http://ltsc.ieee.org/xsd/LOM"/>'
self.assertEquals(['done'], list(compose(self.observable.all.someMethod(parse(StringIO(validXml))))))
self.assertEquals(['done'], list(compose(self.observable.any.someMethod(parse(StringIO(validXml))))))
self.interceptor.calledMethods.reset()
self.observable.do.someMethod(parse(StringIO(validXml)))
self.assertEquals(['do_unknown'], [m.name for m in self.interceptor.calledMethods])
self.interceptor.calledMethods.reset()
self.assertEquals('done', self.observable.call.someMethod(parse(StringIO(validXml))))
def testInvalid(self):
invalidXml = '<lom xmlns="http://ltsc.ieee.org/xsd/LOM_this_should_not_work"/>'
try:
list(compose(self.observable.any.someMethod(parse(StringIO(invalidXml)))))
self.fail('must raise exception')
except ValidateException:
pass
self.assertEquals(['logException'], [m.name for m in self.interceptor.calledMethods])
exception = self.interceptor.calledMethods[0].args[0]
self.assertTrue("ERROR:SCHEMASV:SCHEMAV_CVC_ELT_1: Element '{http://ltsc.ieee.org/xsd/LOM_this_should_not_work}lom': No matching global declaration available for the validation root." in str(exception), str(exception))
self.assertTrue("1 %s" % invalidXml in str(exception), str(exception))
self.assertRaises(ValidateException, lambda: list(compose(self.observable.all.someMethod(parse(StringIO(invalidXml))))))
self.assertRaises(ValidateException, lambda: list(compose(self.observable.do.someMethod(parse(StringIO(invalidXml))))))
self.assertRaises(ValidateException, lambda: list(compose(self.observable.call.someMethod(parse(StringIO(invalidXml))))))
def testAssertInvalidString(self):
invalid = '<OAI-PMH/>'
try:
list(compose(self.observable.any.message(parse(StringIO(invalid)))))
self.fail('must raise exception')
except ValidateException, e:
pass
self.assertEquals(['logException'], [m.name for m in self.interceptor.calledMethods])
exception = self.interceptor.calledMethods[0].args[0]
self.assertTrue("ERROR:SCHEMASV:SCHEMAV_CVC_ELT_1: Element 'OAI-PMH': No matching global declaration available for the validation root." in str(exception), str(exception))
self.assertTrue("1 <OAI-PMH/>" in str(exception), str(exception))
示例8: testAllowedInsecurePages
# 需要导入模块: from meresco.core import Observable [as 别名]
# 或者: from meresco.core.Observable import addObserver [as 别名]
def testAllowedInsecurePages(self):
secureZone = SecureZone('/page_with_login', excluding=['/allowed'])
root = Observable()
observer = CallTrace('Observer', returnValues={'handleRequest' :(f for f in ['HTTP/1.0 200 OK\r\n\r\nBody'])})
secureZone.addObserver(observer)
root.addObserver(secureZone)
session={}
response = asString(root.all.handleRequest(path='/allowed_page', query='a=b', session=session, arguments={}))
self.assertEquals('HTTP/1.0 200 OK\r\n\r\nBody', response)
self.assertEquals(['handleRequest'], observer.calledMethodNames())
self.assertEquals({}, session)
示例9: testSecureZone
# 需要导入模块: from meresco.core import Observable [as 别名]
# 或者: from meresco.core.Observable import addObserver [as 别名]
def testSecureZone(self):
secureZone = SecureZone('/page_with_login')
root = Observable()
observer = CallTrace('Observer', emptyGeneratorMethods=['handleRequest'])
secureZone.addObserver(observer)
root.addObserver(secureZone)
session={}
response = ''.join(compose(root.all.handleRequest(path='/secret_page', query='a=b', session=session, arguments={})))
self.assertEquals(redirectHttp % '/page_with_login', response)
self.assertEquals(0, len(observer.calledMethods))
self.assertEquals({'originalPath':'/secret_page?a=b', 'BasicHtmlLoginForm.formValues':{'errorMessage': 'Login required for "/secret_page".'}}, session)
示例10: testXPathReturnsString
# 需要导入模块: from meresco.core import Observable [as 别名]
# 或者: from meresco.core.Observable import addObserver [as 别名]
def testXPathReturnsString(self):
xpath = XmlXPath(['/a/t/text()'], fromKwarg="lxmlNode")
inputNode = parse(StringIO('<a><t>some text & some <entities></t></a>'))
observable = Observable()
observer = CallTrace('observer')
observable.addObserver(xpath)
xpath.addObserver(observer)
observable.do.aMethod(lxmlNode=inputNode)
self.assertEquals(1, len(observer.calledMethods))
result = observer.calledMethods[0].kwargs
self.assertEquals({'lxmlNode': 'some text & some <entities>'}, result)
示例11: testSecureZoneWithoutQuery
# 需要导入模块: from meresco.core import Observable [as 别名]
# 或者: from meresco.core.Observable import addObserver [as 别名]
def testSecureZoneWithoutQuery(self):
secureZone = SecureZone('/page_with_login', defaultLanguage="nl")
root = Observable()
observer = CallTrace('Observer', emptyGeneratorMethods=['handleRequest'])
secureZone.addObserver(observer)
root.addObserver(secureZone)
session={}
response = asString(root.all.handleRequest(path='/secret_page', query='', session=session, arguments={}))
self.assertEquals(redirectHttp % '/page_with_login', response)
self.assertEquals(0, len(observer.calledMethods))
self.assertEquals({'originalPath':'/secret_page', 'BasicHtmlLoginForm.formValues': {'errorMessage': 'Inloggen verplicht voor "/secret_page".'}}, session)
示例12: testObservableCall
# 需要导入模块: from meresco.core import Observable [as 别名]
# 或者: from meresco.core.Observable import addObserver [as 别名]
def testObservableCall(self):
o = Observable()
calltrace = CallTrace('calltrace')
o.addObserver(calltrace)
result = o.call.getSomething()
self.assertEqual(None, result)
self.assertEquals(['getSomething'], calltrace.calledMethodNames())
calltrace.calledMethods.reset()
calltrace.returnValues['getSomething'] = 'RESULT'
result = o.call.getSomething()
self.assertEqual('RESULT', result)
self.assertEquals(['getSomething'], calltrace.calledMethodNames())
示例13: testGetDataPartname
# 需要导入模块: from meresco.core import Observable [as 别名]
# 或者: from meresco.core.Observable import addObserver [as 别名]
def testGetDataPartname(self):
def getData(**kwargs):
return 'data'
observable = Observable()
observer = CallTrace('observer', methods={'getData': getData})
rewrite = RewritePartname('newPartname')
rewrite.addObserver(observer)
observable.addObserver(rewrite)
result = observable.call.getData(identifier='identifier', name='oldPartname')
self.assertEquals(['getData'], [m.name for m in observer.calledMethods])
self.assertEquals({'identifier': 'identifier', 'name': 'newPartname'}, observer.calledMethods[0].kwargs)
self.assertEquals('data', result)
示例14: Xml2FieldsTest
# 需要导入模块: from meresco.core import Observable [as 别名]
# 或者: from meresco.core.Observable import addObserver [as 别名]
class Xml2FieldsTest(TestCase):
def setUp(self):
xml2fields = Xml2Fields()
self.observer = CallTrace('Observer')
xml2fields.addObserver(self.observer)
self.observable = Observable()
self.observable.addObserver(xml2fields)
def testOneField(self):
result = list(compose(self.observable.all.add('id0','partName', parselxml('<fields><tag>value</tag></fields>'))))
self.assertEquals([], result)
self.assertEquals(1, len(self.observer.calledMethods))
self.assertEquals("addField(name='fields.tag', value='value')", str(self.observer.calledMethods[0]))
def testDoNotIncludeNamespaces(self):
list(compose(self.observable.all.add('id0','partName', parselxml('<fields xmlns="aap"><tag>value</tag></fields>'))))
self.assertEquals(1, len(self.observer.calledMethods))
self.assertEquals("addField(name='fields.tag', value='value')", str(self.observer.calledMethods[0]))
def testMultiLevel(self):
node = parselxml("""<lom>
<general>
<title>The title</title>
</general>
</lom>""")
list(compose(self.observable.all.add('id', 'legacy partname', node)))
self.assertEquals("addField(name='lom.general.title', value='The title')", str(self.observer.calledMethods[0]))
def testMultipleValuesForField(self):
node = parselxml("""<tag>
<name>Name One</name>
<name>Name Two</name>
</tag>""")
list(compose(self.observable.all.add('id', 'legacy partname', node)))
self.assertEquals(2, len(self.observer.calledMethods))
self.assertEquals("addField(name='tag.name', value='Name One')", str(self.observer.calledMethods[0]))
self.assertEquals("addField(name='tag.name', value='Name Two')", str(self.observer.calledMethods[1]))
def testIgnoreCommentsAndEmptyTags(self):
node = parselxml("""<tag>
<!-- comment line, ignore me -->
<name>Name One</name>
<name>Name Two</name>
<name>
</name>
</tag>""")
list(compose(self.observable.all.add('id', 'legacy partname', node)))
self.assertEquals(2, len(self.observer.calledMethods))
self.assertEquals("addField(name='tag.name', value='Name One')", str(self.observer.calledMethods[0]))
self.assertEquals("addField(name='tag.name', value='Name Two')", str(self.observer.calledMethods[1]))
示例15: testRetrieveDataPartname
# 需要导入模块: from meresco.core import Observable [as 别名]
# 或者: from meresco.core.Observable import addObserver [as 别名]
def testRetrieveDataPartname(self):
def retrieveData(**kwargs):
raise StopIteration('data')
yield
observable = Observable()
observer = CallTrace('observer', methods={'retrieveData': retrieveData})
rewrite = RewritePartname('newPartname')
rewrite.addObserver(observer)
observable.addObserver(rewrite)
result = retval(observable.any.retrieveData(identifier='identifier', name='oldPartname'))
self.assertEquals(['retrieveData'], [m.name for m in observer.calledMethods])
self.assertEquals({'identifier': 'identifier', 'name': 'newPartname'}, observer.calledMethods[0].kwargs)
self.assertEquals('data', result)