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 __Consumer_start__(self): path = os.path.dirname(__file__) self.serviceContext = ApplicationContext(XMLConfig(path+"/dataValidator.xml")) self.mqConnection = self.serviceContext.get_object("mqConnection") try: # Open the channel channel = self.mqConnection.channel() # Declare the exchange exchange = channel.exchange_declare(exchange='rawdata', type='fanout', passive=False, durable=True, auto_delete=False, internal=False, nowait=False, arguments={}) # Declare the queue #channel.queue_declare(queue="test", durable=True, exclusive=False, auto_delete=False) result = channel.queue_declare(durable=False, exclusive=True, auto_delete=False) queue_name = result.method.queue channel.queue_bind(exchange='rawdata', queue=queue_name) # We're stuck looping here since this is a blocking adapter channel.basic_consume(self.__Consumer_handler__, queue=queue_name, no_ack=True) self.debug("Raw Data Writer STARTED") self.debug("amqp connection : %s" % self.mqConnection) self.debug("amqp channel : %s" % channel) self.debug("amqp exchange : %s" % exchange) self.debug("amqp queue : %s" % result) channel.start_consuming() except Exception as ex: # Gracefully close the connection self.mqConnection.close() # Loop until we're fully closed, will stop on its own #connection.ioloop.start() self.error(ex)
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')
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 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_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 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 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 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'])
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 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 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 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())
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 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 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 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()
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 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 __init__(self, *args, **kwargs): super(OrgSpider, self).__init__(*args, **kwargs) # Define our Scrapers self.scrapers = [] self.org_scraper = OrganizationScraper() self.meta_data_scraper = UrlMetadataScraper() self.scrapers.append(ContactScraper()) self.scrapers.append(LinkScraper()) self.url_frontier_rules = URLFrontierRules(blocked_domains=OrgSpider._get_blocked_domains()) self.ctx = ApplicationContext(URLFrontierContext()) self.url_frontier = self.ctx.get_object("URLFrontier") self.next_url_timeout = 10
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 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 __init__(self, configFile): self.allow_reuse_address = True self.serviceContext = ApplicationContext(XMLConfig(configFile)) self.config = self.serviceContext.get_object("mainConfiguration") SocketServer.TCPServer.__init__(self, (self.config.host, self.config.port), self.RequestHandler) self.poll_interval = 0.5 self.mainProcess = multiprocessing.current_process() self.mainThread = threading.current_thread() self.adminThread = None '''
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)
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)
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 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())
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 setUp(self): self.app_ctx = ApplicationContext(app_context.SecWallContext()) self.test_dir = tempfile.mkdtemp(prefix='tmp-sec-wall-') cli.Init(self.test_dir, self.app_ctx, False).run() log_config = """ [loggers] keys=root [handlers] keys=consoleHandler [formatters] keys=simpleFormatter [logger_root] level=DEBUG handlers=consoleHandler [handler_consoleHandler] class=StreamHandler level=DEBUG formatter=simpleFormatter args=(sys.stdout,) """ self.log_file_config = os.path.join(self.test_dir, uuid.uuid4().hex) open(self.log_file_config, 'w').write(log_config)
def run(): # Special-case the --fork option so that it doesn't get exposed to users. # The idea is that --fork is an internal detail which shouldn't be visible # anywhere. if '--fork' in sys.argv: command, config_info = handle_fork(sys.argv) else: parser = get_parser() args = parser.parse_args() # Using a mutually exclusive group in 'get_parser' gurantees that we'll have # exactly one option to pick here. command, config_info = [(k, v) for k, v in args._get_kwargs() if v][0] if command == 'fork': config_dir, is_https = config_info else: config_dir = config_info is_https = None config_dir = os.path.abspath(config_dir) app_ctx = ApplicationContext(app_context.SecWallContext()) handler_class = getattr(cli, command.capitalize()) handler_class(config_dir, app_ctx, is_https).run()
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 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 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 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 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 get_app_context(config): """ Returns the Zato's Inversion of Control application context. """ ctx_class_path = config['spring']['context_class'] ctx_class_path = ctx_class_path.split('.') mod_name, class_name = '.'.join(ctx_class_path[:-1]), ctx_class_path[-1:][0] mod = import_module(mod_name) class_ = getattr(mod, class_name)() return ApplicationContext(class_)
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
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 setUp(self): with MockDBConnection() as db: db.dropall() self.ctx = ApplicationContext(TestablePageRankContext()) with open(os.path.join(RESOURCES_DIRECTORY, 'organizations'), mode='r') as to_read: org_models = pickle.load(to_read) # freeze these out b/c we didn't store them for model in org_models: del model.contacts org_dtos = [DTOConverter.to_dto(OrganizationDTO, o) for o in org_models] org_dao = self.ctx.get_object('OrganizationDAO') for dto in org_dtos: org_dao.create_update(dto) with open(os.path.join(RESOURCES_DIRECTORY, 'ranked_organizations'), mode='r') as to_read: self.assert_models = pickle.load(to_read)
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 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 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)")