本文整理汇总了Python中springpython.context.ApplicationContext类的典型用法代码示例。如果您正苦于以下问题:Python ApplicationContext类的具体用法?Python ApplicationContext怎么用?Python ApplicationContext使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了ApplicationContext类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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)
开发者ID:Cophy08,项目名称:spring-python,代码行数:29,代码来源:securityProviderTestCases.py
示例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())
开发者ID:alanfranz,项目名称:spring-python,代码行数:27,代码来源:databaseCoreTestCases.py
示例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
开发者ID:RaikesSchoolDS,项目名称:HTResearch,代码行数:33,代码来源:middlewares.py
示例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)
开发者ID:heiho1,项目名称:spring-redis,代码行数:28,代码来源:test_connection_pool.py
示例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")
开发者ID:RaikesSchoolDS,项目名称:HTResearch,代码行数:33,代码来源:api_views.py
示例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)
开发者ID:Cophy08,项目名称:spring-python,代码行数:26,代码来源:remotingTestCases.py
示例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')
开发者ID:RaikesSchoolDS,项目名称:HTResearch,代码行数:30,代码来源:scraper_unit_tests.py
示例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
开发者ID:RaikesSchoolDS,项目名称:HTResearch,代码行数:9,代码来源:models.py
示例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")
开发者ID:Cophy08,项目名称:spring-python,代码行数:9,代码来源:securityVoteTestCases.py
示例10: main
def main():
"""
Main function
"""
#TODO: Написать тесты
context = ApplicationContext(XMLConfig(contextFile))
objKernel = context.get_object("Kernel")
objKernel.run()
开发者ID:s200999900,项目名称:ftn-system,代码行数:9,代码来源:main.py
示例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())
开发者ID:alanfranz,项目名称:spring-python,代码行数:11,代码来源:databaseCoreTestCases.py
示例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))
开发者ID:RaikesSchoolDS,项目名称:HTResearch,代码行数:53,代码来源:scraper_unit_tests.py
示例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)
开发者ID:Cophy08,项目名称:spring-python,代码行数:12,代码来源:securityEncodingTestCases.py
示例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))
开发者ID:heiho1,项目名称:spring-redis,代码行数:12,代码来源:tests.py
示例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()
开发者ID:sourav295,项目名称:research_2016,代码行数:12,代码来源:configure.py
示例16: testExportingAServiceThroughIoC
def testExportingAServiceThroughIoC(self):
self.run_jetty()
appContext = ApplicationContext(XMLConfig("support/remotingHessianTestApplicationContext.xml"))
clientSideProxy = appContext.get_object("personService")
results = clientSideProxy.transform("Greg Turnquist a,b,c,x,y,z")
self.assertEquals(results["firstName"], "Greg")
self.assertEquals(results["lastName"], "Turnquist")
self.assertEquals(results["attributes"], ["a", "b", "c", "x", "y", "z"])
time.sleep(self.postdelay)
开发者ID:alanfranz,项目名称:spring-python,代码行数:13,代码来源:remotingTestCases.py
示例17: configure
def configure():
#----- WIRING
GlobalConfiguration.simpyEnv = simpy.Environment()
context = ApplicationContext(GlobalConfiguration.config_xml)
topology = context.get_object("topology")
GlobalConfiguration.topology = topology #reqd for statistic generations
sdn_nfv = context.get_object("nfv_sdn")
sdn_nfv.distribute_information()
topology.wireComponents()
开发者ID:sourav295,项目名称:research_2016,代码行数:14,代码来源:configure.py
示例18: testCachingService
def testCachingService(self):
context = ApplicationContext(WikiProductionAppConfig())
caching_service = context.get_object("caching_service")
self.assertEquals(len(caching_service.keys()), 0)
self.assertEquals(caching_service.keys(), [])
caching_service.store("key", "value")
self.assertEquals(caching_service.keys(), ["key"])
self.assertEquals(caching_service.get("key"), "value")
caching_service.remove("key")
self.assertEquals(caching_service.keys(), [])
开发者ID:jeffshaw,项目名称:spring-python-example,代码行数:14,代码来源:CachedWikiTest.py
示例19: LdapAuthenticationProviderTestCase
class LdapAuthenticationProviderTestCase(unittest.TestCase):
def __init__(self, methodName='runTest'):
unittest.TestCase.__init__(self, methodName)
self.logger = logging.getLogger("springpythontest.securityLdapTestCases.LdapAuthenticationProviderTestCase")
def setUp(self):
SecurityContextHolder.setContext(SecurityContext())
self.appContext = ApplicationContext(XMLConfig("support/ldapApplicationContext.xml"))
def testGoodUsersBindAuthentication(self):
self.auth_manager = self.appContext.get_object("ldapAuthenticationProvider")
authentication = UsernamePasswordAuthenticationToken(username="bob", password="bobspassword")
SecurityContextHolder.getContext().authentication = self.auth_manager.authenticate(authentication)
self.assertTrue("ROLE_DEVELOPERS" in SecurityContextHolder.getContext().authentication.granted_auths)
def testGoodUsersPasswordAuthentication(self):
self.auth_manager = self.appContext.get_object("ldapAuthenticationProvider2")
authentication = UsernamePasswordAuthenticationToken(username="bob", password="bobspassword")
SecurityContextHolder.getContext().authentication = self.auth_manager.authenticate(authentication)
self.assertTrue("ROLE_DEVELOPERS" in SecurityContextHolder.getContext().authentication.granted_auths)
def testGoodUserWithShaEncoding(self):
self.auth_manager = self.appContext.get_object("ldapAuthenticationProvider2")
authentication = UsernamePasswordAuthenticationToken(username="ben", password="benspassword")
SecurityContextHolder.getContext().authentication = self.auth_manager.authenticate(authentication)
self.assertTrue("ROLE_DEVELOPERS" in SecurityContextHolder.getContext().authentication.granted_auths)
def testWrongPasswordBindAuthentication(self):
self.auth_manager = self.appContext.get_object("ldapAuthenticationProvider")
authentication = UsernamePasswordAuthenticationToken(username="bob", password="wrongpassword")
self.assertRaises(BadCredentialsException, self.auth_manager.authenticate, authentication)
def testWrongPasswordAuthentication(self):
self.auth_manager = self.appContext.get_object("ldapAuthenticationProvider2")
authentication = UsernamePasswordAuthenticationToken(username="bob", password="wrongpassword")
self.assertRaises(BadCredentialsException, self.auth_manager.authenticate, authentication)
def testNonexistentUserBindAuthentication(self):
self.auth_manager = self.appContext.get_object("ldapAuthenticationProvider")
authentication = UsernamePasswordAuthenticationToken(username="nonexistentuser", password="password")
self.assertRaises(BadCredentialsException, self.auth_manager.authenticate, authentication)
def testNonexistentUserPasswordAuthentication(self):
self.auth_manager = self.appContext.get_object("ldapAuthenticationProvider2")
authentication = UsernamePasswordAuthenticationToken(username="nonexistentuser", password="password")
self.assertRaises(BadCredentialsException, self.auth_manager.authenticate, authentication)
def testEmptyPassword(self):
self.auth_manager = self.appContext.get_object("ldapAuthenticationProvider")
authentication = UsernamePasswordAuthenticationToken(username="nonexistentuser", password="")
self.assertRaises(BadCredentialsException, self.auth_manager.authenticate, authentication)
开发者ID:Cophy08,项目名称:spring-python,代码行数:59,代码来源:securityLdapTestCases.py
示例20: clean_url
def clean_url(self):
url = self.cleaned_data['url']
ctx = ApplicationContext(DAOContext())
org_dao = ctx.get_object('OrganizationDAO')
url_metadata_dao = ctx.get_object('URLMetadataDAO')
try:
domain = UrlUtility().get_domain(url)
except:
raise ValidationError("Oops! We couldn't find information on that domain.")
if org_dao.find(organization_url=domain) or url_metadata_dao.find(domain=domain):
raise ValidationError("Oops! Looks like we already have information on that organization.")
return url
开发者ID:RaikesSchoolDS,项目名称:HTResearch,代码行数:15,代码来源:models.py
注:本文中的springpython.context.ApplicationContext类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论