本文整理汇总了Python中springpython.context.ApplicationContext类的典型用法代码示例。如果您正苦于以下问题:Python ApplicationContext类的具体用法?Python ApplicationContext怎么用?Python ApplicationContext使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了ApplicationContext类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: DaoAuthenticationProviderNotHidingUserNotFoundExceptionsTestCase
class DaoAuthenticationProviderNotHidingUserNotFoundExceptionsTestCase(MockTestCase):
def __init__(self, methodName='runTest'):
MockTestCase.__init__(self, methodName)
self.logger = logging.getLogger("springpythontest.providerTestCases.DaoAuthenticationProviderNotHidingUserNotFoundExceptionsTestCase")
def setUp(self):
SecurityContextHolder.setContext(SecurityContext())
self.appContext = ApplicationContext(XMLConfig("support/providerApplicationContext.xml"))
self.auth_manager = self.appContext.get_object("dao_mgr_not_hiding_exceptions")
self.mock = self.mock()
self.appContext.get_object("dataSource").stubConnection.mockCursor = self.mock
def testIocDaoAuthenticationBadUsersDontHideBadCredentialsDisabledUser(self):
self.mock.expects(once()).method("execute").id("#1")
self.mock.expects(once()).method("fetchall").will(return_value([('disableduser', 'password4', False)])).id("#2").after("#1")
self.mock.expects(once()).method("execute").id("#3").after("#2")
self.mock.expects(once()).method("fetchall").will(return_value([('disableduser', 'role1'), ('disableduser', 'blue')])).id("#4").after("#3")
authentication = UsernamePasswordAuthenticationToken(username="disableduser", password="password4")
self.assertRaises(DisabledException, self.auth_manager.authenticate, authentication)
def testIocDaoAuthenticationBadUsersDontHideBadCredentialsEmptyUser(self):
self.mock.expects(once()).method("execute").id("#1")
self.mock.expects(once()).method("fetchall").will(return_value([('emptyuser', '', True)])).id("#2").after("#1")
self.mock.expects(once()).method("execute").id("#3").after("#2")
self.mock.expects(once()).method("fetchall").will(return_value([])).id("#4").after("#3")
authentication = UsernamePasswordAuthenticationToken(username="emptyuser", password="")
self.assertRaises(UsernameNotFoundException, self.auth_manager.authenticate, authentication)
示例2: testIoCGeneralQueryWithDictionaryRowMapper
def testIoCGeneralQueryWithDictionaryRowMapper(self):
appContext = ApplicationContext(XMLConfig("support/databaseTestSqliteApplicationContext.xml"))
factory = appContext.get_object("connection_factory")
databaseTemplate = DatabaseTemplate(factory)
databaseTemplate.execute("DROP TABLE IF EXISTS animal")
databaseTemplate.execute("""
CREATE TABLE animal (
id serial PRIMARY KEY,
name VARCHAR(11),
category VARCHAR(20),
population integer
)
""")
factory.commit()
databaseTemplate.execute("DELETE FROM animal")
factory.commit()
self.assertEquals(len(databaseTemplate.query_for_list("SELECT * FROM animal")), 0)
databaseTemplate.execute("INSERT INTO animal (name, category, population) VALUES ('snake', 'reptile', 1)")
databaseTemplate.execute("INSERT INTO animal (name, category, population) VALUES ('racoon', 'mammal', 0)")
databaseTemplate.execute ("INSERT INTO animal (name, category, population) VALUES ('black mamba', 'kill_bill_viper', 1)")
databaseTemplate.execute ("INSERT INTO animal (name, category, population) VALUES ('cottonmouth', 'kill_bill_viper', 1)")
factory.commit()
self.assertEquals(len(databaseTemplate.query_for_list("SELECT * FROM animal")), 4)
results = databaseTemplate.query("select * from animal", rowhandler=DictionaryRowMapper())
示例3: process_exception
def process_exception(self, request, exception, spider):
"""
An exception occurred while trying to get a response from the requested URL,
so we need to do cleanup. This means updating the URLMetadata to reflect that
this URL has been checked and queuing a new URL request from the URLFrontier.
"""
# log error
_middleware_logger.error(exception.message)
# update last_visited for failed request
try:
url_dao = URLMetadataDAO()
url_dto = url_dao.find(url=request.url)
if url_dto is not None:
url_dto.last_visited = datetime.utcnow()
url_dao.create_update(url_dto)
except Exception as e:
_middleware_logger.error(e.message)
# queue next url
ctx = ApplicationContext(URLFrontierContext())
url_frontier = ctx.get_object("URLFrontier")
try:
url_frontier_rules = spider.url_frontier_rules
except Exception as e:
_middleware_logger.error('ERROR: Spider without url_frontier_rules defined')
return None
next_url = url_frontier.next_url(url_frontier_rules)
if next_url is not None:
return Request(next_url.url, dont_filter=True)
return None
示例4: test_multiple_connections
def test_multiple_connections(self):
# 2 clients to the same host/port/db/pool should use the same
# connection
appctx = ApplicationContext(RedisAppConfig())
pool = redis.ConnectionPool()
# NOTE: it is fragile to reference connection_pool property directly
r1 = appctx.get_object('redis_service')
r1.connection_pool=pool
r2 = appctx.get_object('redis_service')
r2.connection_pool=pool
self.assertEquals(r1.connection, r2.connection)
# if one of them switches, they should have
# separate conncetion objects
r2.select(db=10, host='localhost', port=6379)
self.assertNotEqual(r1.connection, r2.connection)
conns = [r1.connection, r2.connection]
conns.sort()
# but returning to the original state shares the object again
r2.select(db=9, host='localhost', port=6379)
self.assertEquals(r1.connection, r2.connection)
# the connection manager should still have just 2 connections
mgr_conns = pool.get_all_connections()
mgr_conns.sort()
self.assertEquals(conns, mgr_conns)
示例5: heatmap_coordinates
def heatmap_coordinates(request):
"""
Gets all the lat/long values for all organizations.
Returns:
List of lat/long coordinates encoded in JSON.
"""
if request.method != 'GET':
return HttpResponseNotAllowed(request)
coords = cache.get('organization_coords_list')
last_update = cache.get('organization_coords_list_last_update')
if not coords or not last_update or (datetime.utcnow() - last_update > REFRESH_COORDS_LIST):
new_coords = []
cache.set('organization_address_list_last_update', datetime.utcnow())
ctx = ApplicationContext(DAOContext())
org_dao = ctx.get_object('OrganizationDAO')
try:
organizations = org_dao.findmany(latlng__exists=True, latlng__ne=[])
except:
logger.error('Error occurred on organization lookup')
return HttpResponseServerError(request)
for org in organizations:
new_coords.append(org.latlng)
coords = MongoJSONEncoder().encode(new_coords)
if len(coords) > 0:
cache.set('organization_coords_list', coords)
return HttpResponse(coords, content_type="application/json")
示例6: ttestExportingAServiceThroughIoCWithoutPullingTheIntermediateComponent
def ttestExportingAServiceThroughIoCWithoutPullingTheIntermediateComponent(self):
appContext = ApplicationContext(XMLConfig("support/remotingPyro4TestApplicationContext.xml"))
remoteService1 = appContext.get_object("remoteServiceServer1")
clientSideProxy1 = appContext.get_object("accountServiceClient1")
remoteService2 = appContext.get_object("remoteServiceServer2")
clientSideProxy2 = appContext.get_object("accountServiceClient2")
time.sleep(0.01)
argument1 = ['a', 1, 'b']
self.assertEquals(remoteService1.getData(argument1), "You got remote data => %s" % argument1)
self.assertEquals(remoteService1.getMoreData(argument1), "You got more remote data => %s" % argument1)
self.assertEquals(clientSideProxy1.getData(argument1), "You got remote data => %s" % argument1)
self.assertEquals(clientSideProxy1.getMoreData(argument1), "You got more remote data => %s" % argument1)
routineToRun = "testit"
self.assertEquals(remoteService2.executeOperation(routineToRun), "Operation %s has been carried out" % routineToRun)
self.assertEquals(remoteService2.executeOtherOperation(routineToRun), "Other operation %s has been carried out" % routineToRun)
self.assertEquals(clientSideProxy2.executeOperation(routineToRun), "Operation %s has been carried out" % routineToRun)
self.assertEquals(clientSideProxy2.executeOtherOperation(routineToRun), "Other operation %s has been carried out" % routineToRun)
del(appContext)
示例7: test_contact_scraper
def test_contact_scraper(self):
ctx = ApplicationContext(TestableDocumentScraperContext())
test_files = [
"httpwwwprajwalaindiacomcontactushtml",
]
contact_scraper = ctx.get_object('ContactScraper')
contacts = []
for input_file in test_files:
response = file_to_response(input_file)
if response is not None:
ret = contact_scraper.parse(response)
if isinstance(ret, type([])):
contacts = contacts + ret
else:
contacts.append(ret)
assert_list = [{
'email': 'test',
'first_name': 'test',
'last_name': 'test',
'organization': {'name': 'test'},
'position': 'test',
'phones': ['test'],
}]
for test in assert_list:
self.assertIn(test, contacts, 'Contact \'' + str(test) + '\' not found')
示例8: clean_email
def clean_email(self):
email = self.cleaned_data['email']
ctx = ApplicationContext(DAOContext())
dao = ctx.get_object('UserDAO')
if dao.find(email=email):
raise ValidationError('An account with that email already exists.')
return email
示例9: setupContext
def setupContext(self, username, password):
applicationContext = ApplicationContext(XMLConfig("support/unanimousBasedApplicationContext.xml"))
token = UsernamePasswordAuthenticationToken(username, password)
auth_manager = applicationContext.get_object("auth_manager")
SecurityContextHolder.setContext(SecurityContext())
SecurityContextHolder.getContext().authentication = auth_manager.authenticate(token)
self.sampleService = applicationContext.get_object("sampleService")
self.block1 = SampleBlockOfData("block1")
self.block2 = SampleBlockOfData("block2")
示例10: main
def main():
"""
Main function
"""
#TODO: Написать тесты
context = ApplicationContext(XMLConfig(contextFile))
objKernel = context.get_object("Kernel")
objKernel.run()
示例11: testIoCGeneralQuery
def testIoCGeneralQuery(self):
appContext = ApplicationContext(XMLConfig("support/databaseTestApplicationContext.xml"))
mockConnectionFactory = appContext.get_object("mockConnectionFactory")
mockConnectionFactory.stubConnection.mockCursor = self.mock
self.mock.expects(once()).method("execute")
self.mock.expects(once()).method("fetchall").will(return_value([("me", "myphone")]))
databaseTemplate = DatabaseTemplate(connection_factory = mockConnectionFactory)
results = databaseTemplate.query("select * from foobar", rowhandler=testSupportClasses.SampleRowMapper())
示例12: test_urlmetadata_scraper
def test_urlmetadata_scraper(self):
ctx = ApplicationContext(TestableUrlMetadataScraperContext())
self.set_up_url_metadata_scraper_test()
test_files = [
"httpbombayteenchallengeorg",
"httpwwwgooglecom",
"httpwwwhalftheskymovementorgpartners",
]
url_mds = ctx.get_object("UrlMetadataScraper")
scraped_urls = []
for input_file in test_files:
response = file_to_response(input_file)
if response is not None:
ret = url_mds.parse(response)
if isinstance(ret, type([])):
scraped_urls = scraped_urls + ret
else:
scraped_urls.append(ret)
# We can't possibly get the last_visited time exactly right, so set to date
for scraped_url in scraped_urls:
scraped_url['last_visited'] = scraped_url['last_visited'].date()
assert_list = [
{
'checksum': Binary('154916369406075238760605425088915003118'),
'last_visited': datetime.utcnow().date(),
'update_freq': 0,
'url': 'http://bombayteenchallenge.org/'
},
{
'checksum': Binary('94565939257467841022060717122642335157'),
'last_visited': datetime.utcnow().date(),
'update_freq': 6, # incremented one from setup b/c diff checksum
'url': 'http://www.google.com'
},
{
'checksum': Binary('199553381546012383114562002951261892300'),
'last_visited': datetime.utcnow().date(),
'update_freq': 1, # not incremented b/c checksum is same
'url': 'http://www.halftheskymovement.org/partners'
},
]
# do teardown now in case of failure
self.tear_down_url_metadata_scraper_test()
for test in assert_list:
self.assertIn(test, scraped_urls, 'Invalid URL Metadata Didn\'t Find: %s' % str(test))
示例13: ReflectionSaltSourceErrorTestCase
class ReflectionSaltSourceErrorTestCase(unittest.TestCase):
def setUp(self):
self.appContext = ApplicationContext(XMLConfig("support/encodingApplicationContext.xml"))
self.user = SaltedUser("user1", "testPassword", True)
def testEncodingWithReflectionSaltSourceNoSuchMethod(self):
saltSource = self.appContext.get_object("reflectionSaltSource2")
self.assertRaises(AuthenticationServiceException, saltSource.get_salt, self.user)
def testEncodingWithReflectionSaltSourceLeftEmpty(self):
saltSource = self.appContext.get_object("reflectionSaltSource3")
self.assertRaises(AuthenticationServiceException, saltSource.get_salt, self.user)
示例14: test_container
def test_container(self):
"""
Validates that the redis service is accessible and functioning
"""
appctx = ApplicationContext(RedisAppConfig())
rdssvc = appctx.get_object('redis_service')
tstky = 'foo'
tstval = 'bar'
self.assertTrue(rdssvc.set(tstky, tstval))
self.assertEquals(rdssvc.get(tstky), tstval)
self.assertTrue(rdssvc.delete(tstky))
self.assertFalse(rdssvc.exists(tstky))
示例15: configure
def configure(configs):
context = ApplicationContext(configs)
'''
x3 = context.get_object("x3")
x2 = context.get_object("x2")
print x2.a
print x3.a
'''
topology = context.get_object("topology")
topology.wireComponents()