def registry(num): try: try: fudge.clear_calls() fudge.clear_expectations() exp_order = ExpectedCallOrder(self.fake) reg.remember_expected_call_order(exp_order) eq_(len(reg.get_expected_call_order().keys()), 1) # registered first time on __init__ : exp = ExpectedCall(self.fake, 'callMe', call_order=exp_order) reg.expect_call(exp) reg.expect_call(exp) reg.expect_call(exp) eq_(len(reg.get_expected_calls()), 4) # actual calls: exp() exp() exp() exp() fudge.verify() fudge.clear_expectations() except Exception, er: thread_run.errors.append(er) raise finally: thread_run.waiting -= 1
def tearDown(self): fudge.clear_expectations() fudge.clear_calls() try: os.remove(self.sqlite_db.dbname) except OSError: pass
def __enter__(self): fudge.clear_expectations() fudge.clear_calls() self.patches = [] all_fakes = [] for path in self.obj_paths: try: target, attr = path.rsplit('.', 1) except (TypeError, ValueError): raise TypeError( "Need a valid target to patch. You supplied: %r" % path) fake = fudge.Fake(path) all_fakes.append(fake) self.patches.append(patch_object(target, attr, fake)) if len(all_fakes) == 1: return all_fakes[0] else: return all_fakes
def registry(num): try: try: fudge.clear_calls() fudge.clear_expectations() exp_order = ExpectedCallOrder(self.fake) reg.remember_expected_call_order(exp_order) eq_(len(reg.get_expected_call_order().keys()), 1) # registered first time on __init__ : exp = ExpectedCall(self.fake, "callMe", call_order=exp_order) reg.expect_call(exp) reg.expect_call(exp) reg.expect_call(exp) eq_(len(reg.get_expected_calls()), 4) # actual calls: exp() exp() exp() exp() fudge.verify() fudge.clear_expectations() except Exception, er: thread_run.errors.append(er) raise finally: thread_run.waiting -= 1
def tearDown(self): fudge.clear_expectations() fudge.clear_calls() self.sqlite_db.close() try: os.remove(SQLITE_DATABASE) except OSError: pass
def tearDown(self): try: os.remove('test_database.db') except OSError: pass fudge.clear_calls() fudge.clear_expectations()
def test_task_will_invoke_provided_class(): def foo(): pass fake = Fake() fake.expects("__init__").with_args(foo) fudge.clear_calls() fudge.clear_expectations() foo = decorators.task(foo, task_class=fake) fudge.verify()
def test_extracts_view_out_of_templatetag_call(self): random_view_name = 'hello_world_%d' % random.randint(100, 200) token = fudge.Fake() token.expects('split_contents').returns(('esi', random_view_name)) fudge.clear_calls() result = esi(Parser([]), token) self.assertEquals(str(result.view_name), random_view_name) fudge.verify()
def test_task_passes_args_to_the_task_class(): random_vars = ("some text", random.randint(100, 200)) def foo(): pass fake = Fake() fake.expects("__init__").with_args(foo, *random_vars) fudge.clear_calls() fudge.clear_expectations() foo = decorators.task(foo, task_class=fake, *random_vars) fudge.verify()
def test_embed_dispatches_kwargs_to_backend(self): kwargs = dict( [("key-%d" % a, a) for a in range(random.randint(1, 10))]) backend = fudge.Fake() backend.provides("prepare") video = EmbeddedVideo("foo/bar", backend=backend) backend.expects("embed").with_args(video, **kwargs) fudge.clear_calls() video.embed(**kwargs) fudge.verify()
def test_embed_dispatches_kwargs_to_backend(self): kwargs = dict([("key-%d" % a, a) for a in range(random.randint(1, 10))]) backend = fudge.Fake() backend.provides("prepare") video = EmbeddedVideo("foo/bar", backend=backend) backend.expects("embed").with_args(video, **kwargs) fudge.clear_calls() video.embed(**kwargs) fudge.verify()
def test_embed_dispatches_to_backend_and_returns_result(self): random_return = random.randint(1000, 2000) backend = fudge.Fake() backend.provides("prepare") video = EmbeddedVideo("foo/bar", backend=backend) backend.expects("embed").with_args(video).returns(random_return) fudge.clear_calls() result = video.embed() self.assertEqual(result, random_return) fudge.verify()
def test_cache_hit(self): response = datasources.pubmed.filter_pmids(gold_pmids, test_data_geo_filter) patched = fudge.patch_object("EUtils.HistoryClient", "HistoryClient", get_a_FakeHistoryClient_hit()) fudge.clear_calls() try: response = datasources.pubmed.filter_pmids(gold_pmids, test_data_geo_filter) fudge.verify() finally: patched.restore() fudge.clear_expectations()
def test_can_be_get_controller(self): fudge.clear_expectations() controller = fudge.Fake().provides("__init__").has_attr(__name__="shouldBeName") controller_intance = controller.returns_fake() dp = dispatcher.TorneiraDispatcher() ctrl = dp.getController(controller) self.assertEqual(controller_intance, ctrl) self.assertEqual(dp._controllers, {"shouldBeName":ctrl}) fudge.clear_calls()
def _disabled_test_cache_miss(self): TimedCache().is_bypass_cache(True) patched = fudge.patch_object("EUtils.HistoryClient", "HistoryClient", get_a_FakeHistoryClient_miss()) fudge.clear_calls() try: response = datasources.pubmed.filter_pmids(gold_pmids, test_data_geo_filter) fudge.verify() finally: patched.restore() fudge.clear_expectations() TimedCache().is_bypass_cache(False)
def test_can_be_get_mapper(self): fudge.clear_expectations() FakeMapper = fudge.Fake("Mapper").expects("__init__") fake_instance = FakeMapper.returns_fake().expects('connect').with_args("url_name", "url_route", controller="controller", action="action") with fudge.patched_context(dispatcher, "Mapper", FakeMapper): dp = dispatcher.TorneiraDispatcher() mapper = dp.getMapper() self.assertEqual(fake_instance, mapper) fudge.clear_calls()
def test_timer_proxy_debug_false(self): settings.DEBUG = False fudge.clear_expectations() fudge.clear_calls() execute_fake = fudge.Fake(callable=True).with_args("shouldBeCursor", "shouldBeStatement", "shouldBeParameters", "shouldBeContext") timerProxy = meta.TimerProxy() timerProxy.cursor_execute(execute_fake, "shouldBeCursor", "shouldBeStatement", "shouldBeParameters", "shouldBeContext", "shouldBeExecutemany") fudge.verify()
def setUp(self): super(BaseDonationFormViewTestCase, self).setUp() # TODO: move this to armstrong.dev self.client = Client() # TODO: make this based off of class name and move into armstrong.dev settings.TEMPLATE_DIRS = (os.path.join(os.path.dirname(__file__), "_templates"), ) self.client self.patches = [ fudge.patch_object(views, "backends", self.get_backend_stub()) ] fudge.clear_calls()
def inner(self): random_text = "Some Random Text (%d)" % random.randint(1000, 2000) backend = self.get_backend_stub(successful=False, reason=random_text) self.patches = [ fudge.patch_object(views, "backends", backend), ] fudge.clear_calls() data = self.random_post_data response = self.client.post(self.url, data) backend_response = backend.get_backend().purchase()["response"] func(self, response, random_text=random_text, backend_response=backend_response)
def test_update_uses_id_if_present(self): twitter = fudge.Fake() twitter.users = (fudge.Fake() .expects("show") .with_args(id=TSWICEGOOD['id']) .returns(TSWICEGOOD)) fudge.clear_calls() user = models.TwitterUser(id=TSWICEGOOD['id']) user.update_from_twitter(twitter=twitter) self.assertEqual(user.screen_name, TSWICEGOOD['screen_name']) self.assertEqual(user.id, TSWICEGOOD['id']) fudge.verify()
def test_can_update_from_twitter(self): twitter = fudge.Fake() twitter.users = (fudge.Fake() .expects("show") .with_args(screen_name="tswicegood") .returns(TSWICEGOOD)) fudge.clear_calls() user = models.TwitterUser(screen_name = 'tswicegood') user.update_from_twitter(twitter = twitter) self.assertEqual(user.screen_name, TSWICEGOOD['screen_name']) self.assertEqual(user.id, TSWICEGOOD['id']) fudge.verify()
def setUp(self): super(BaseDonationFormViewTestCase, self).setUp() # TODO: move this to armstrong.dev self.client = Client() # TODO: make this based off of class name and move into armstrong.dev settings.TEMPLATE_DIRS = ( os.path.join(os.path.dirname(__file__), "_templates"), ) self.client self.patches = [ fudge.patch_object(views, "backends", self.get_backend_stub()) ] fudge.clear_calls()
def test_replaces_relative_url_esi(self, request): rand = random.randint(100, 200) url = './%d/' % rand request.has_attr(path='/hello/') request.provides('build_absolute_uri').returns('http://example.com/') request.has_attr(_esi={'used': True}) response = HttpResponse() esi_tag = '<esi:include src="%s" />' % url response.content = esi_tag fudge.clear_calls() result = full_process_response(request, response) self.assertFalse(re.search(esi_tag, result.content), msg='sanity check') self.assertEquals(result.content, str(rand))
def test_timer_proxy_debug_true(self): settings.DEBUG = True fudge.clear_expectations() fudge.clear_calls() execute_fake = fudge.Fake(callable=True).with_args( "shouldBeCursor", "shouldBeStatement", "shouldBeParameters", "shouldBeContext") timerProxy = meta.TimerProxy() timerProxy.cursor_execute(execute_fake, "shouldBeCursor", "shouldBeStatement", "shouldBeParameters", "shouldBeContext", "shouldBeExecutemany") fudge.verify()
def test_get_recurring_api_instantiates_with_configured_settings(self): random_login = "******" % random.randint(100, 200) random_key = "some random key %d" % random.randint(100, 200) random_return = "some random return %d" % random.randint(100, 200) settings = fudge.Fake().has_attr(AUTHORIZE={ "LOGIN": random_login, "KEY": random_key, }) recurring_api_class = (fudge.Fake().expects_call().with_args( random_login, random_key, is_test=arg.any()).returns(random_return)) fudge.clear_calls() backend = backends.AuthorizeNetBackend( settings=settings, recurring_api_class=recurring_api_class) result = backend.get_recurring_api() self.assertEqual(result, random_return) fudge.verify()
def test_start_stop_resets_stack(self): fudge.clear_expectations() fake = fudge.Fake().provides("something") fake = fake.returns(1) fake = fake.next_call() fake = fake.returns(2) eq_(fake.something(), 1) eq_(fake.something(), 2) fudge.clear_calls() eq_(fake.something(), 1) eq_(fake.something(), 2) fudge.verify() eq_(fake.something(), 1) eq_(fake.something(), 2)
def test_get_recurring_api_instantiates_with_configured_settings(self): random_login = "******" % random.randint(100, 200) random_key = "some random key %d" % random.randint(100, 200) random_return = "some random return %d" % random.randint(100, 200) settings = fudge.Fake().has_attr( AUTHORIZE={ "LOGIN": random_login, "KEY": random_key, }) recurring_api_class = (fudge.Fake().expects_call() .with_args(random_login, random_key) .returns(random_return)) fudge.clear_calls() backend = backends.AuthorizeNetBackend(settings=settings, recurring_api_class=recurring_api_class) result = backend.get_recurring_api() self.assertEqual(result, random_return) fudge.verify()
def test_replaces_relative_url_esi(self, request): rand = random.randint(100, 200) url = './%d/' % rand request.has_attr(path='/hello/') request.provides('build_absolute_uri').returns('http://example.com/') request.has_attr(_esi={'used': True}) response = HttpResponse() esi_tag = '<esi:include src="%s" />' % url response.content = esi_tag fudge.clear_calls() patch_data = patch_settings({'MIDDLEWARE_CLASSES': MIDDLEWARES}) result = full_process_response(request, response) self.assertFalse(re.search(esi_tag, result.content), msg='sanity check') self.assertEquals(result.content, str(rand)) restore_settings(*patch_data)
def check_connection_calls(host_strings, num_calls): # Clear Fudge call stack clear_calls() # Patch connect() with Fake obj set to expect num_calls calls patched_connect = patch_object( 'fabric.network', 'connect', Fake('connect', expect_call=True).times_called(num_calls)) try: # Make new cache object cache = HostConnectionCache() # Connect to all connection strings for host_string in host_strings: # Obtain connection from cache, potentially calling connect() cache[host_string] # Verify expected calls matches up with actual calls verify() finally: # Restore connect() patched_connect.restore() # Clear expectation stack clear_expectations()
def check_connection_calls(host_strings, num_calls): # Clear Fudge call stack clear_calls() # Patch connect() with Fake obj set to expect num_calls calls patched_connect = patch_object('fabric.network', 'connect', Fake('connect', expect_call=True).times_called(num_calls) ) try: # Make new cache object cache = HostConnectionCache() # Connect to all connection strings for host_string in host_strings: # Obtain connection from cache, potentially calling connect() cache[host_string] # Verify expected calls matches up with actual calls verify() finally: # Restore connect() patched_connect.restore() # Clear expectation stack clear_expectations()
def test_can_be_get_session(self): fudge.clear_expectations() fudge.clear_calls() settings.DATABASE_ENGINE = "shouldBeDataBase" settings.DATABASE_POOL_SIZE = "shouldBePoolSize" FakeTimerProxy = fudge.Fake("TimerProxy").expects("__init__") timer_proxy_instance = FakeTimerProxy.returns_fake() create_engine_fake = fudge.Fake(callable=True).with_args("shouldBeDataBase", pool_size="shouldBePoolSize", pool_recycle=300, proxy=timer_proxy_instance ).returns("shouldBeEngine") sessionmaker_fake = fudge.Fake(callable=True).with_args(autocommit=True, autoflush=False, expire_on_commit=False, bind="shouldBeEngine" ).returns("shouldBeScopedSession") scoped_session_fake = fudge.Fake(callable=True).with_args("shouldBeScopedSession").returns("shouldBeSession") patches = [ fudge.patch_object(meta, "TimerProxy", FakeTimerProxy), fudge.patch_object(meta, "create_engine", create_engine_fake), fudge.patch_object(meta, "sessionmaker", sessionmaker_fake), fudge.patch_object(meta, "scoped_session", scoped_session_fake) ] try: session = meta.TorneiraSession() self.assertEqual(session, "shouldBeSession") finally: fudge.verify() for p in patches: p.restore()
def test_api_instantiates_api_class_with_configured_settings(self): random_login = "******" % random.randint(100, 200) random_key = "some random key %d" % random.randint(100, 200) random_return = "some random return %d" % random.randint(100, 200) settings = fudge.Fake() settings.has_attr(AUTHORIZE={ "LOGIN": random_login, "KEY": random_key, }) api_class = fudge.Fake() # Note that delimiter is included here because authorize's code # can't even keep track of what deliminter it wants to use! (api_class.expects_call().with_args( random_login, random_key, delimiter=arg.any(), is_test=arg.any()).returns(random_return)) fudge.clear_calls() backend = backends.AuthorizeNetBackend(api_class=api_class, settings=settings) result = backend.get_api() self.assertEqual(result, random_return) fudge.verify()
def test_api_instantiates_api_class_with_configured_settings(self): random_login = "******" % random.randint(100, 200) random_key = "some random key %d" % random.randint(100, 200) random_return = "some random return %d" % random.randint(100, 200) settings = fudge.Fake() settings.has_attr(AUTHORIZE={ "LOGIN": random_login, "KEY": random_key, }) api_class = fudge.Fake() # Note that delimiter is included here because authorize's code # can't even keep track of what deliminter it wants to use! (api_class.expects_call() .with_args(random_login, random_key, delimiter=u"|") .returns(random_return)) fudge.clear_calls() backend = backends.AuthorizeNetBackend(api_class=api_class, settings=settings) result = backend.get_api() self.assertEqual(result, random_return) fudge.verify()
def test_can_be_run(self): fudge.clear_expectations() fudge.clear_calls() FakeApplication = fudge.Fake("Application").expects("__init__").with_args([ (r"/media/(.*)", tornado.web.StaticFileHandler, {"path": "shouldBeMediaDir"}), (r"/.*", server.TorneiraHandler) ], cookie_secret=settings.COOKIE_SECRET, debug=True) application_instance = FakeApplication.returns_fake() FakeServer = fudge.Fake("HTTPServer").expects("__init__").with_args(application_instance, xheaders="shouldBeXHeaders") server_instance = FakeServer.returns_fake().expects("listen").with_args("shouldBePort") FakeIOLoop = fudge.Fake("IOLoop").expects("instance") FakeIOLoop.returns_fake().expects("start") patches = [ fudge.patch_object(server, "Application", FakeApplication), fudge.patch_object(server, "HTTPServer", FakeServer), fudge.patch_object(server, "IOLoop", FakeIOLoop) ] try: torneira_server = server.TorneiraServer("shouldBePidfile", "shouldBePort", "shouldBeMediaDir", xheaders="shouldBeXHeaders") self.assertEqual(torneira_server.pidfile, "shouldBePidfile") self.assertEqual(torneira_server.media_dir, "shouldBeMediaDir") torneira_server.run() finally: fudge.verify() for p in patches: p.restore()
def setUp(self): fudge.clear_expectations() MOCK_GE = ( fudge.Fake('GameEngine') .expects('__init__') .expects('get_signal_matrix').returns(dict(fakesig=123)) .has_attr(fighters=dict(f1='fighter1', f2='fighter2')) .has_attr(players=dict(p1='player1', p2='player2')) ) MOCK_DD = ( fudge.Fake('DataDriver') .expects('__init__') ) _mock_config = (MOCK_DD.provides('get_config').returns_fake() .has_attr(irc_log_channel='#log', irc_main_channel="#main")) MOCK_LOAD_ALL = fudge.Fake('load_all', expect_call=True) self.fake_dd = fudge.patch_object('urb.db', 'DataDriver', MOCK_DD) self.fake_ge = fudge.patch_object('urb.engine', 'GameEngine', MOCK_GE) self.fake_la = fudge.patch_object('urb.imports', 'load_all', MOCK_LOAD_ALL) fudge.clear_calls()
def setUp(self): super(ArmstrongTestCase, self).setUp() fudge.clear_expectations() fudge.clear_calls()
def setUp(self): fudge.clear_expectations() fudge.clear_calls()
def tearDown(self): fudge.clear_calls()
def setUp(self): fudge.clear_calls() fudge.clear_expectations() self.orig_backend_settings = copy(backends.backend.settings)
def setUp(self): fudge.clear_expectations() fudge.clear_calls() self.application_fake = fudge.Fake().has_attr(ui_methods={}, ui_modules={}) self.request_fake = fudge.Fake().has_attr(uri="shouldBeUri").provides("supports_http_1_1").returns(True)
def setUp(self): fudge.clear_calls() fudge.clear_expectations() super(TestCase, self).setUp()
def setUp(self): self._original_settings = settings fudge.clear_expectations() fudge.clear_calls()
def reset(): """Resets fudge expectations and calls""" fudge.clear_calls() fudge.clear_expectations()