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)
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="******", password="******") 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="******", password="") self.assertRaises(UsernameNotFoundException, self.auth_manager.authenticate, authentication)
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)
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")
def setupContext(self, username, password): applicationContext = ApplicationContext(XMLConfig("support/labelBasedAclVoterApplicationContext.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.blueblock = SampleBlockOfData("blue") self.orangeblock = SampleBlockOfData("orange") self.sharedblock = SampleBlockOfData("blue-orange")
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")
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)
def setupContext(self, username, password): applicationContext = ApplicationContext( XMLConfig("support/labelBasedAclVoterApplicationContext.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.blueblock = SampleBlockOfData("blue") self.orangeblock = SampleBlockOfData("orange") self.sharedblock = SampleBlockOfData("blue-orange")
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()
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="******", password="******") 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="******", password="******") 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="******", password="******") 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="******", password="******") self.assertRaises(BadCredentialsException, self.auth_manager.authenticate, authentication) def testWrongPasswordAuthentication(self): self.auth_manager = self.appContext.get_object("ldapAuthenticationProvider2") authentication = UsernamePasswordAuthenticationToken(username="******", password="******") self.assertRaises(BadCredentialsException, self.auth_manager.authenticate, authentication) def testNonexistentUserBindAuthentication(self): self.auth_manager = self.appContext.get_object("ldapAuthenticationProvider") authentication = UsernamePasswordAuthenticationToken(username="******", password="******") self.assertRaises(BadCredentialsException, self.auth_manager.authenticate, authentication) def testNonexistentUserPasswordAuthentication(self): self.auth_manager = self.appContext.get_object("ldapAuthenticationProvider2") authentication = UsernamePasswordAuthenticationToken(username="******", password="******") self.assertRaises(BadCredentialsException, self.auth_manager.authenticate, authentication) def testEmptyPassword(self): self.auth_manager = self.appContext.get_object("ldapAuthenticationProvider") authentication = UsernamePasswordAuthenticationToken(username="******", password="") self.assertRaises(BadCredentialsException, self.auth_manager.authenticate, authentication)
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
def testWikiServiceWithCaching(self): context = ApplicationContext(WikiProductionAppConfig()) caching_service = context.get_object("caching_service") wiki_service = context.get_object("wiki_service") self.assertEquals(len(caching_service.keys()), 0) wiki_service.statistics(None) self.assertEquals(len(caching_service.keys()), 0) wiki_service.get_article("jeff article") self.assertEquals(len(caching_service.keys()), 1) wiki_service.store_article("jeff article") self.assertEquals(len(caching_service.keys()), 0)
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)
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
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')
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())
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())
def main(): container = ApplicationContext(ExampleApplicationContext()) weather_service = WeatherService() geo_place = 'Maceio, AL' wind = weather_service.check_wind(geo_place) condition = weather_service.check_condition(geo_place) sunset = weather_service.check_sunset(geo_place) print('Direction: %s' % wind['wind']['direction']) print('Speed: %s' % wind['wind']['speed']) print('Condition: %s' % condition['item']['condition']['text']) print('Sunset: %s' % sunset['astronomy']['sunset']) weather_service = container.get_object('weather_service') geo_place = 'Maceio, AL' wind = weather_service.check_wind(geo_place) condition = weather_service.check_condition(geo_place) sunset = weather_service.check_sunset(geo_place) print('====== AOP ======') print('Direction: %s' % wind['wind']['direction']) print('Speed: %s' % wind['wind']['speed']) print('Condition: %s' % condition['item']['condition']['text']) print('Sunset: %s' % sunset['astronomy']['sunset'])
class InMemoryDaoAuthenticationProviderTestCase(unittest.TestCase): def setUp(self): SecurityContextHolder.setContext(SecurityContext()) self.appContext = ApplicationContext(XMLConfig("support/providerApplicationContext.xml")) self.auth_manager = self.appContext.get_object("inMemoryDaoAuthenticationManager") def __init__(self, methodName='runTest'): unittest.TestCase.__init__(self, methodName) self.logger = logging.getLogger("springpythontest.providerTestCases.InMemoryDaoAuthenticationProviderTestCase") def testIoCDaoAuthenticationGoodUsers(self): authentication = UsernamePasswordAuthenticationToken(username="******", password="******") SecurityContextHolder.getContext().authentication = self.auth_manager.authenticate(authentication) self.assertTrue("role1" in SecurityContextHolder.getContext().authentication.granted_auths) self.assertTrue("blue" in SecurityContextHolder.getContext().authentication.granted_auths) authentication = UsernamePasswordAuthenticationToken(username="******", password="******") SecurityContextHolder.getContext().authentication = self.auth_manager.authenticate(authentication) self.assertTrue("role1" in SecurityContextHolder.getContext().authentication.granted_auths) self.assertTrue("orange" in SecurityContextHolder.getContext().authentication.granted_auths) authentication = UsernamePasswordAuthenticationToken(username="******", password="******") SecurityContextHolder.getContext().authentication = self.auth_manager.authenticate(authentication) self.assertTrue("role1" in SecurityContextHolder.getContext().authentication.granted_auths) self.assertTrue("admin" in SecurityContextHolder.getContext().authentication.granted_auths) def testIocDaoAuthenticationBadUsersWithHiddenExceptions(self): authentication = UsernamePasswordAuthenticationToken(username="******", password="******") self.assertRaises(BadCredentialsException, self.auth_manager.authenticate, authentication) authentication = UsernamePasswordAuthenticationToken(username="******", password="******") self.assertRaises(DisabledException, self.auth_manager.authenticate, authentication) authentication = UsernamePasswordAuthenticationToken(username="******", password="") self.assertRaises(BadCredentialsException, self.auth_manager.authenticate, authentication)
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")
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")
def ttestExportingAServiceUsingNonStandardPortsWithValueElement(self): appContext = ApplicationContext(XMLConfig("support/remotingPyro4TestApplicationContext.xml")) time.sleep(0.01) remoteService1 = appContext.get_object("remoteServiceServer1") serviceExporter3 = appContext.get_object("serviceExporter3") clientSideProxy3 = appContext.get_object("accountServiceClient3") time.sleep(0.01) argument = ['a', 1, 'b'] self.assertEquals(remoteService1.getData(argument), "You got remote data => %s" % argument) self.assertEquals(remoteService1.getMoreData(argument), "You got more remote data => %s" % argument) self.assertEquals(clientSideProxy3.getData(argument), "You got remote data => %s" % argument) self.assertEquals(clientSideProxy3.getMoreData(argument), "You got more remote data => %s" % argument)
def test_item_converter(self): ctx = ApplicationContext(TestableDAOContext()) print 'Creating organization and contact item.' org = ctx.get_object('OrganizationDAO') org_dto = OrganizationDTO(name="Univerisityee of Nyeebraska-Lincoln") org.create_update(org_dto) org_model = DTOConverter.from_dto(Organization, org_dto) contact_item = ScrapedContact(first_name='Bee', last_name='Yee', organization={'name': "Univerisityee of Nyeebraska-Lincoln"} ) print 'Converting contact to model.' converter = ctx.get_object('ModelConverter') model_contact = converter.to_model(Contact, contact_item) self.assertEqual(model_contact.organization.name, org_model.name)
def testExportingAServiceUsingNonStandardPortsWithConstructorArgsByAttribute(self): appContext = ApplicationContext(XMLConfig("support/remotingPyroTestApplicationContext.xml")) time.sleep(0.01) remoteService1 = appContext.get_object("remoteServiceServer1") serviceExporter5 = appContext.get_object("serviceExporter5") clientSideProxy5 = appContext.get_object("accountServiceClient5") time.sleep(0.01) argument = ['a', 1, 'b'] self.assertEquals(remoteService1.getData(argument), "You got remote data => %s" % argument) self.assertEquals(remoteService1.getMoreData(argument), "You got more remote data => %s" % argument) self.assertEquals(clientSideProxy5.getData(argument), "You got remote data => %s" % argument) self.assertEquals(clientSideProxy5.getMoreData(argument), "You got more remote data => %s" % argument)
def test_item_converter(self): ctx = ApplicationContext(TestableDAOContext()) print 'Creating organization and contact item.' org = ctx.get_object('OrganizationDAO') org_dto = OrganizationDTO(name="Univerisityee of Nyeebraska-Lincoln") org.create_update(org_dto) org_model = DTOConverter.from_dto(Organization, org_dto) contact_item = ScrapedContact( first_name='Bee', last_name='Yee', organization={'name': "Univerisityee of Nyeebraska-Lincoln"}) print 'Converting contact to model.' converter = ctx.get_object('ModelConverter') model_contact = converter.to_model(Contact, contact_item) self.assertEqual(model_contact.organization.name, org_model.name)
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
def main(): """ Main function """ #TODO: Написать тесты context = ApplicationContext(XMLConfig(contextFile)) objKernel = context.get_object("Kernel") objKernel.run()
def main(): """ Main function """ #TODO: Написать тесты context = ApplicationContext(XMLConfig(contextFile)) objKernel = context.get_object("Kernel") objKernel.run()
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
def run(self): try: context = ApplicationContext(YamlConfig(self.ctx_yaml)) service = context.get_object('XmZoomeyeUpgradeClient') service.start() except Exception as e: self.logger.error( 'resolve yaml context with exception, exp={0}'.format(e)) self.logger.error(traceback.format_exc())
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
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())
def GetObject(id, **kwargs): try: config_path = os.path.join(GloalConfig().config, 'config.xml') context = ApplicationContext(XMLConfig(config_path)) obj = context.get_object(id) logger.info(obj) return obj except: logger.error("", exc_info=1) return None
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())
class ShaPasswordEncodingTestCase(unittest.TestCase): def setUp(self): self.appContext = ApplicationContext(XMLConfig("support/encodingApplicationContext.xml")) self.user = SaltedUser("user1", "testPassword", True) self.encoder = self.appContext.get_object("shaEncoder") def testEncodingWithNoPasswordAndNoSaltSource(self): encodedPassword = self.encoder.encodePassword(None, None) self.assertTrue(self.encoder.isPasswordValid(encodedPassword, "", None)) def testEncodingWithMixedCaseAndNoSaltSource(self): self.encoder.ignorePasswordCase = True encodedPassword = self.encoder.encodePassword("TESTPASSWORD", None) self.assertTrue(self.encoder.isPasswordValid(encodedPassword, "testpassword", None)) self.encoder.ignorePasswordCase = False def testEncodingWithNoSaltSource(self): encodedPassword = self.encoder.encodePassword(self.user.password, None) self.assertTrue(self.encoder.isPasswordValid(encodedPassword, self.user.password, None)) def testEncodingWithSystemWideSaltSourceLeftEmpty(self): saltSource = self.appContext.get_object("systemWideSaltSource") salt = saltSource.get_salt(self.user) encodedPassword = self.encoder.encodePassword(self.user.password, salt) self.assertTrue(self.encoder.isPasswordValid(encodedPassword, self.user.password, salt)) def testEncodingWithSystemWideSaltSourceConfigured(self): saltSource = self.appContext.get_object("systemWideSaltSource2") salt = saltSource.get_salt(self.user) encodedPassword = self.encoder.encodePassword(self.user.password, salt) self.assertTrue(self.encoder.isPasswordValid(encodedPassword, self.user.password, salt)) def testEncodingWithSystemWideSaltSourceInvalidLeftBrace(self): saltSource = self.appContext.get_object("systemWideSaltSource3") salt = saltSource.get_salt(self.user) encodedPassword = self.encoder.encodePassword(self.user.password, salt) self.assertTrue(self.encoder.isPasswordValid(encodedPassword, self.user.password, salt)) def testEncodingWithSystemWideSaltSourceInvalidRightBrace(self): saltSource = self.appContext.get_object("systemWideSaltSource4") salt = saltSource.get_salt(self.user) encodedPassword = self.encoder.encodePassword(self.user.password, salt) self.assertTrue(self.encoder.isPasswordValid(encodedPassword, self.user.password, salt)) def testEncodingWithSystemWideSaltSourceInvalidBothBraces(self): saltSource = self.appContext.get_object("systemWideSaltSource5") salt = saltSource.get_salt(self.user) encodedPassword = self.encoder.encodePassword(self.user.password, salt) self.assertTrue(self.encoder.isPasswordValid(encodedPassword, self.user.password, salt)) def testEncodingWithReflectionSaltSourceConfigured(self): saltSource = self.appContext.get_object("reflectionSaltSource") salt = saltSource.get_salt(self.user) encodedPassword = self.encoder.encodePassword(self.user.password, salt) self.assertTrue(self.encoder.isPasswordValid(encodedPassword, self.user.password, salt))
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()
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))
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))
def ttestExportingAServiceThroughIoC(self): import logging logger = logging.getLogger("springpython.test") logger.info("Creating appContext") appContext = ApplicationContext(XMLConfig("support/remotingPyro4TestApplicationContext.xml")) logger.info("Fetching server 1 stuff...") remoteService1 = appContext.get_object("remoteServiceServer1") logger.info("remoteService1 = %s" % remoteService1) serviceExporter1 = appContext.get_object("serviceExporter1") clientSideProxy1 = appContext.get_object("accountServiceClient1") remoteService2 = appContext.get_object("remoteServiceServer2") serviceExporter2 = appContext.get_object("serviceExporter2") clientSideProxy2 = appContext.get_object("accountServiceClient2") time.sleep(10.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) serviceExporter1.__del__() serviceExporter2 = None
def testExportingAServiceUsingNonStandardPortsWithValueAttribute(self): appContext = ApplicationContext( XMLConfig("support/remotingPyroTestApplicationContext.xml")) time.sleep(0.01) remoteService1 = appContext.get_object("remoteServiceServer1") serviceExporter4 = appContext.get_object("serviceExporter4") clientSideProxy4 = appContext.get_object("accountServiceClient4") time.sleep(0.01) argument = ['a', 1, 'b'] self.assertEquals(remoteService1.getData(argument), "You got remote data => %s" % argument) self.assertEquals(remoteService1.getMoreData(argument), "You got more remote data => %s" % argument) self.assertEquals(clientSideProxy4.getData(argument), "You got remote data => %s" % argument) self.assertEquals(clientSideProxy4.getMoreData(argument), "You got more remote data => %s" % argument)
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)
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)
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(), [])
def ttestExportingAServiceUsingNonStandardPortsWithConstructorArgsByElement( self): appContext = ApplicationContext( XMLConfig("support/remotingPyro4TestApplicationContext.xml")) time.sleep(0.01) remoteService1 = appContext.get_object("remoteServiceServer1") serviceExporter6 = appContext.get_object("serviceExporter6") clientSideProxy6 = appContext.get_object("accountServiceClient6") time.sleep(0.01) argument = ['a', 1, 'b'] self.assertEquals(remoteService1.getData(argument), "You got remote data => %s" % argument) self.assertEquals(remoteService1.getMoreData(argument), "You got more remote data => %s" % argument) self.assertEquals(clientSideProxy6.getData(argument), "You got remote data => %s" % argument) self.assertEquals(clientSideProxy6.getMoreData(argument), "You got more remote data => %s" % argument)
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)
def user_info(request): info = {'username': '', 'user_id': ''} if hasattr(request, 'session'): if 'name' in request.session and 'user_id' in request.session: info['username'] = request.session['name'] info['user_id'] = request.session['user_id'] elif 'user_id' in request.session: uid = request.session['user_id'] ctx = ApplicationContext(DAOContext()) dao = ctx.get_object('UserDAO') user_dto = dao.find(id=uid) info['username'] = user_dto.first_name + ' ' + user_dto.last_name info['user_id'] = uid return info
def testDecoratorBasedTransactionsWithLotsOfArguments(self): appContext = ApplicationContext(DatabaseTxTestDecorativeTransactionsWithLotsOfArguments(self.factory)) bank = appContext.get_object("bank") bank.open("Checking") bank.open("Savings") bank.deposit(125.00, "Checking") self.assertEquals(bank.balance("Checking"), 125.00) bank.deposit(250.00, "Savings") self.assertEquals(bank.balance("Savings"), 250.00) bank.transfer(25.00, "Savings", "Checking") self.assertEquals(bank.balance("Savings"), 225.00) self.assertEquals(bank.balance("Checking"), 150.00) bank.withdraw(10.00, "Checking") self.assertEquals(bank.balance("Checking"), 140.00) amount = 0.0 try: amount = bank.withdraw(1000, "Nowhere") self.fail("Expected a BankException!") except BankException: pass self.assertEquals(amount, 0.0) self.assertEquals(bank.balance("Savings"), 225.00) self.assertEquals(bank.balance("Checking"), 140.00) try: bank.transfer(200, "Checking", "Nowhere") self.fail("Expected a BankException!") except BankException: pass self.assertEquals(bank.balance("Savings"), 225.00, "Bad transfer did NOT fail atomically!") logging.getLogger("springpythontest.databaseTransactionTestCases").debug(bank.balance("Checking")) self.assertEquals(bank.balance("Checking"), 140.00, "Bad transfer did NOT fail atomically!")
def testDecoratorBasedTransactionsWithLotsOfArguments(self): appContext = ApplicationContext(DatabaseTxTestDecorativeTransactionsWithLotsOfArguments(self.factory)) bank = appContext.get_object("bank") bank.open("Checking") bank.open("Savings") bank.deposit(125.00, "Checking") self.assertEquals(bank.balance("Checking"), 125.00) bank.deposit(250.00, "Savings") self.assertEquals(bank.balance("Savings"), 250.00) bank.transfer(25.00, "Savings", "Checking") self.assertEquals(bank.balance("Savings"), 225.00) self.assertEquals(bank.balance("Checking"), 150.00) bank.withdraw(10.00, "Checking") self.assertEquals(bank.balance("Checking"), 140.00) amount = 0.0 try: amount = bank.withdraw(1000, "Nowhere") self.fail("Expected a BankException!") except BankException: pass self.assertEquals(amount, 0.0) self.assertEquals(bank.balance("Savings"), 225.00) self.assertEquals(bank.balance("Checking"), 140.00) try: bank.transfer(200, "Checking", "Nowhere") self.fail("Expected a BankException!") except BankException: pass self.assertEquals(bank.balance("Savings"), 225.00, "Bad transfer did NOT fail atomically!") logging.getLogger("springpythontest.databaseTransactionTestCases").debug(bank.balance("Checking")) self.assertEquals(bank.balance("Checking"), 140.00, "Bad transfer did NOT fail atomically!")
def testTransactionalBankWithNoAutoTransactionalObject(self): appContext = ApplicationContext(DatabaseTxTestAppContextWithNoAutoTransactionalObject(self.factory)) bank = appContext.get_object("bank") bank.open("Checking") bank.open("Savings") bank.deposit(125.00, "Checking") self.assertEquals(bank.balance("Checking"), 125.00) bank.deposit(250.00, "Savings") self.assertEquals(bank.balance("Savings"), 250.00) bank.transfer(25.00, "Savings", "Checking") self.assertEquals(bank.balance("Savings"), 225.00) self.assertEquals(bank.balance("Checking"), 150.00) bank.withdraw(10.00, "Checking") self.assertEquals(bank.balance("Checking"), 140.00) amount = 0.0 try: amount = bank.withdraw(1000, "Nowhere") self.fail("Expected a BankException!") except BankException: pass self.assertEquals(amount, 0.0) self.assertEquals(bank.balance("Savings"), 225.00) self.assertEquals(bank.balance("Checking"), 140.00) try: bank.transfer(200, "Checking", "Nowhere") self.fail("Expected a BankException!") except BankException: pass self.assertEquals(bank.balance("Savings"), 225.00, "Bad transfer did NOT fail atomically!") self.assertEquals(bank.balance("Checking"), -60.00, "Bad transfer did NOT fail as expected (not atomically due to lack of AutoTransactionalObject)")
def ttestExportingAServiceThroughIoC(self): import logging logger = logging.getLogger("springpython.test") logger.info("Creating appContext") appContext = ApplicationContext( XMLConfig("support/remotingPyro4TestApplicationContext.xml")) logger.info("Fetching server 1 stuff...") remoteService1 = appContext.get_object("remoteServiceServer1") logger.info("remoteService1 = %s" % remoteService1) serviceExporter1 = appContext.get_object("serviceExporter1") clientSideProxy1 = appContext.get_object("accountServiceClient1") remoteService2 = appContext.get_object("remoteServiceServer2") serviceExporter2 = appContext.get_object("serviceExporter2") clientSideProxy2 = appContext.get_object("accountServiceClient2") time.sleep(10.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) serviceExporter1.__del__() serviceExporter2 = None
def testOtherPropagationLevels(self): appContext = ApplicationContext(DatabaseTxTestDecorativeTransactionsWithLotsOfArguments(self.factory)) bank = appContext.get_object("bank") # Call a mandatory operation outside a transaction, and verify it fails. try: bank.mandatoryOperation() self.fail("Expected a TransactionPropagationException!") except TransactionPropagationException: pass # Call a mandatory operation from within a transactional routine, and verify it works. bank.mandatoryOperationTransactionalWrapper() # Call a non-transactional operation from outside a transaction, and verify it works. bank.nonTransactionalOperation() # Call a non-tranactional operation from within a transaction, and verify it fails. try: bank.nonTransactionalOperationTransactionalWrapper() self.fail("Expected a TransactionPropagationException!") except TransactionPropagationException: pass
from springpython.context import ApplicationContext from HTResearch.Utilities.context import DAOContext from HTResearch.Utilities.geocoder import geocode # Helper script to fix broken database by adding latlongs if __name__ == '__main__': ctx = ApplicationContext(DAOContext()) dao = ctx.get_object('OrganizationDAO') empty_latlngs = dao.findmany(latlng=[]) null_latlngs = dao.findmany(latlng__exists=False) for dto in empty_latlngs: if not dto.address: continue dto.latlng = geocode(dto.address) dao.create_update(dto) for dto in null_latlngs: if not dto.address: continue dto.latlng = geocode(dto.address) dao.create_update(dto)
# This turns on debugging, so you can see everything Spring Python is doing in the background # while executing the sample application. logger = logging.getLogger("springpython") loggingLevel = logging.DEBUG logger.setLevel(loggingLevel) ch = logging.StreamHandler() ch.setLevel(loggingLevel) formatter = logging.Formatter( "%(asctime)s - %(name)s - %(levelname)s - %(message)s") ch.setFormatter(formatter) logger.addHandler(ch) applicationContext = ApplicationContext(noxml.PetClinicClientOnly()) applicationContext.get_object("filterChainProxy") SecurityContextHolder.setStrategy(SecurityContextHolder.MODE_GLOBAL) SecurityContextHolder.getContext() conf = { '/': { "tools.staticdir.root": os.getcwd(), "tools.sessions.on": True, "tools.filterChainProxy.on": True }, "/images": { "tools.staticdir.on": True, "tools.staticdir.dir": "images" }, "/html": {
class AopProxyTestCase(unittest.TestCase): """Tests creating and using AOP proxies including unconditional interceptors.""" def setUp(self): self.appContext = ApplicationContext( XMLConfig("support/aopApplicationContext.xml")) def testCreatingAProxyFactoryAndAddingAnInterceptorProgrammatically(self): factory = ProxyFactory() factory.target = SampleService() factory.interceptors.append(WrappingInterceptor()) service = factory.getProxy() self.assertEquals("<Wrapped>Alright!</Wrapped>", service.doSomething()) self.assertEquals("<Wrapped>You made it! => test</Wrapped>", service.method("test")) self.assertEquals("sample", service.attribute) def testCreatingAopProxyFactoryAndAddingInterceptorToNewStyleClassProgammatically( self): factory = ProxyFactory() factory.target = NewStyleSampleService() factory.interceptors.append(WrappingInterceptor()) service = factory.getProxy() self.assertEquals("<Wrapped>Even better!</Wrapped>", service.doSomething()) self.assertEquals( "<Wrapped>You made it to a new style class! => test</Wrapped>", service.method("test")) self.assertEquals("new_sample", service.attribute) def testCreatingAProxyFactoryAndAddingAnInterceptorIoC(self): factory = self.appContext.get_object("factory") service = factory.getProxy() self.assertEquals("<Wrapped>Alright!</Wrapped>", service.doSomething()) self.assertEquals("<Wrapped>You made it! => test</Wrapped>", service.method("test")) self.assertEquals("sample", service.attribute) def testWrappingStringFunctionWithInterceptor(self): service = ProxyFactoryObject() service.target = SampleService() service.interceptors = [WrappingInterceptor()] self.assertEquals("This is a sample service.", service.target.__str__()) self.assertEquals("This is a sample service.", str(service.target)) self.assertEquals("<Wrapped>This is a sample service.</Wrapped>", str(service)) self.assertEquals("<Wrapped>This is a sample service.</Wrapped>", service.__str__()) def testCreatingAProxyFactoryObjectAndAddingAnInterceptorProgrammatically( self): service = ProxyFactoryObject() service.target = SampleService() service.interceptors = [WrappingInterceptor()] self.assertEquals("<Wrapped>Alright!</Wrapped>", service.doSomething()) self.assertEquals("<Wrapped>You made it! => test</Wrapped>", service.method("test")) self.assertEquals("sample", service.attribute) def testCreatingAProxyFactoryObjectWithAnInterceptorIoC(self): service = self.appContext.get_object("sampleService4") self.assertEquals("<Wrapped>Alright!</Wrapped>", service.doSomething()) self.assertEquals("<Wrapped>You made it! => test</Wrapped>", service.method("test")) self.assertEquals("sample", service.attribute) def testApplyingASingleConditionalPointcutIoC(self): sampleService = self.appContext.get_object("sampleService1") self.assertEquals(sampleService.doSomething(), "<Wrapped>Alright!</Wrapped>") self.assertEquals(sampleService.method("testdata"), "You made it! => testdata") def testApplyingTwoConditionalPointcutsIoC(self): sampleService = self.appContext.get_object("sampleService2") self.assertEquals(sampleService.doSomething(), "BEFORE => <Wrapped>Alright!</Wrapped> <= AFTER") self.assertEquals(sampleService.method("testdata"), "You made it! => testdata") def testApplyingASingleConditionalPointcutProgrammatically(self): wrappingAdvice = WrappingInterceptor() pointcutAdvisor = RegexpMethodPointcutAdvisor() pointcutAdvisor.advice = wrappingAdvice pointcutAdvisor.patterns = [".*do.*"] targetService = SampleService() sampleService = ProxyFactoryObject(interceptors=pointcutAdvisor) sampleService.target = targetService self.assertEquals(sampleService.doSomething(), "<Wrapped>Alright!</Wrapped>") self.assertEquals(sampleService.method("testdata"), "You made it! => testdata") def testApplyingTwoConditionalPointcutsProgrammatically(self): beginEndAdvice = BeforeAndAfterInterceptor() wrappingAdvice = WrappingInterceptor() pointcutAdvisor = RegexpMethodPointcutAdvisor() pointcutAdvisor.advice = [beginEndAdvice, wrappingAdvice] pointcutAdvisor.patterns = [".*do.*"] targetService = SampleService() sampleService = ProxyFactoryObject(interceptors=pointcutAdvisor) sampleService.target = targetService self.assertEquals(sampleService.doSomething(), "BEFORE => <Wrapped>Alright!</Wrapped> <= AFTER") self.assertEquals(sampleService.method("testdata"), "You made it! => testdata") def testCreatingAProxyFactoryObjectWithAnInterceptorByClassNameInsteadOfInstanceIoC( self): service = self.appContext.get_object("sampleService5") self.assertEquals("<Wrapped>Alright!</Wrapped>", service.doSomething()) self.assertEquals("<Wrapped>You made it! => test</Wrapped>", service.method("test")) self.assertEquals("sample", service.attribute) def testProxyFactoryObjectInterceptorsNotWrappedInAList(self): service = ProxyFactoryObject() service.target = SampleService() # Note that it isn't wrapped in a list. service.interceptors = WrappingInterceptor() self.assertEquals("This is a sample service.", service.target.__str__()) self.assertEquals("This is a sample service.", str(service.target)) self.assertEquals("<Wrapped>This is a sample service.</Wrapped>", str(service)) self.assertEquals("<Wrapped>This is a sample service.</Wrapped>", service.__str__()) # sampleService6 has an interceptor which isn't wrapped in a list # inside its XMLConfig. service = self.appContext.get_object("sampleService6") self.assertEquals("<Wrapped>Alright!</Wrapped>", service.doSomething()) self.assertEquals("<Wrapped>You made it! => test</Wrapped>", service.method("test")) self.assertEquals("sample", service.attribute)
class PageRankMergeTest(unittest.TestCase): def setUp(self): print "New PageRankMergeTest running" self.organization = Organization( name="Yee University", organization_url="www.yee.com", email_key="*****@*****.**", emails=["*****@*****.**", "*****@*****.**"], phone_numbers=[5555555555, "(555)555-5555"], facebook="http://www.facebook.com/yee", twitter="http://www.twitter.com/yee", address="5124 Yeesy Street Omaha, NE 68024", keywords="intj enfp entp isfp enfj istj", types=[ OrgTypesEnum.RELIGIOUS, OrgTypesEnum.GOVERNMENT, OrgTypesEnum.PROSECUTION, ], page_rank_info=PageRankInfoDTO( total_with_self=10, total=8, references=[ PageRankVectorDTO(org_domain='yee.com', count=2, pages=[ UrlCountPairDTO( url='http://www.yee.com/', count=2) ]), PageRankVectorDTO( org_domain='trystero.org', count=4, pages=[ UrlCountPairDTO(url='http://www.yee.com/', count=3), UrlCountPairDTO( url='http://www.yee.com/contacts.php', count=1) ]), PageRankVectorDTO(org_domain='thurnandtaxis.info', count=4, pages=[ UrlCountPairDTO( url='http://www.yee.com/', count=4) ]) ])) self.ctx = ApplicationContext(TestableDAOContext()) def tearDown(self): with MockDBConnection() as db: db.dropall() def test_page_rank_merge(self): org_dto = DTOConverter.to_dto(OrganizationDTO, self.organization) org_dao = self.ctx.get_object("OrganizationDAO") print 'Putting initial data in database' org_dao.create_update(org_dto) new_organization = OrganizationDTO( name="Yee University", organization_url="www.yee.com", page_rank_info=PageRankInfoDTO( total_with_self=18, total=16, references=[ PageRankVectorDTO( org_domain='yee.com', count=2, pages=[ UrlCountPairDTO(url='http://www.yee.com/test.php', count=2) ]), PageRankVectorDTO( org_domain='trystero.org', count=12, pages=[ UrlCountPairDTO(url='http://www.yee.com/', count=2), UrlCountPairDTO( url='http://www.yee.com/contacts.php', count=10) ]), PageRankVectorDTO( org_domain='philately.com', count=4, pages=[ UrlCountPairDTO(url='http://www.yee.com/test.php', count=4) ]) ])) test_org = Organization( name="Yee University", organization_url="www.yee.com", email_key="*****@*****.**", emails=["*****@*****.**", "*****@*****.**"], phone_numbers=[5555555555, "(555)555-5555"], facebook="http://www.facebook.com/yee", twitter="http://www.twitter.com/yee", address="5124 Yeesy Street Omaha, NE 68024", keywords="intj enfp entp isfp enfj istj", types=[ OrgTypesEnum.RELIGIOUS, OrgTypesEnum.GOVERNMENT, OrgTypesEnum.PROSECUTION, ], page_rank_info=PageRankInfoDTO( total_with_self=24, total=20, references=[ PageRankVectorDTO( org_domain='yee.com', count=4, pages=[ UrlCountPairDTO(url='http://www.yee.com/', count=2), UrlCountPairDTO(url='http://www.yee.com/test.php', count=2) ]), PageRankVectorDTO( org_domain='trystero.org', count=12, pages=[ UrlCountPairDTO(url='http://www.yee.com/', count=2), UrlCountPairDTO( url='http://www.yee.com/contacts.php', count=10) ]), PageRankVectorDTO(org_domain='thurnandtaxis.info', count=4, pages=[ UrlCountPairDTO( url='http://www.yee.com/', count=4) ]), PageRankVectorDTO( org_domain='philately.com', count=4, pages=[ UrlCountPairDTO(url='http://www.yee.com/test.php', count=4) ]) ])) print 'Merging new data' org_dao.create_update(new_organization) assert_org = org_dao.find(id=org_dto.id) self.assertEqual(assert_org.name, test_org.name) self.assertEqual(assert_org.organization_url, test_org.organization_url) self.assertEqual(assert_org.email_key, test_org.email_key) self.assertEqual(assert_org.emails, test_org.emails) self.assertEqual(assert_org.phone_numbers, test_org.phone_numbers) self.assertEqual(assert_org.facebook, test_org.facebook) self.assertEqual(assert_org.twitter, test_org.twitter) self._compare_page_rank_info(assert_org, test_org) print 'OrganizationDAO tests passed' def _compare_page_rank_info(self, org1, org2): page_rank_info1 = org1.page_rank_info page_rank_info2 = org2.page_rank_info self.assertEqual(page_rank_info1.total_with_self, page_rank_info2.total_with_self) self.assertEqual(page_rank_info1.total, page_rank_info2.total) self.assertEqual(len(page_rank_info2.references), len(page_rank_info1.references)) for i in range(len(page_rank_info1.references)): ref1 = page_rank_info1.references[i] ref2 = page_rank_info2.references[i] self.assertEqual(ref1.org_domain, ref2.org_domain) self.assertEqual(ref1.count, ref2.count) self.assertEqual(len(ref1.pages), len(ref2.pages)) for j in range(len(ref1.pages)): pair1 = ref1.pages[j] pair2 = ref2.pages[j] self.assertEqual(pair1.url, pair2.url) self.assertEqual(pair1.count, pair2.count)