def test_get_release(self, mock): # The get_release method fecthes a release tarball and # extracts it. We have setup a mock so that it won't actually # download the release. Let's call the code. class FakeFile(object): def read(self): return 'Django tarball' def close(self): self.closed = True tmp = tempfile.mkdtemp() filename = os.path.join(tmp, 'django-0.96.2.tar.gz') mock.return_value = FakeFile() try: self.assertEqual( self.recipe.get_release('0.96.2', tmp), filename) # It tried to download the release through our mock mock.assert_called_with( 'http://www.djangoproject.com/download/0.96.2/tarball/') # The file should have been filled with the contents from the # handle it got. self.assertEqual(open(filename).read(), 'Django tarball') finally: shutil.rmtree(tmp)
def test__thread_main_alive_on_emit_failed(self, mock): class Exporter(object): def __init__(self): self.exported = [] def emit(self, span): if len(self.exported) < 2: self.exported.extend(span) else: raise Exception("This exporter is broken !") exporter = Exporter() worker = async_._Worker(exporter, max_batch_size=2, wait_period=0) span_data0 = [mock.Mock()] span_data1 = [mock.Mock()] span_data2 = [mock.Mock()] worker.enqueue(span_data0) worker.enqueue(span_data1) worker.enqueue(span_data2) worker.enqueue(async_._WORKER_TERMINATOR) worker._thread_main() # Span 2 should throw an exception, only span 0 and 1 are left self.assertEqual(exporter.exported, span_data0 + span_data1) # Logging exception should have been called on the exporter exception expected = '%s failed to emit data.Dropping %s objects from queue.' mock.assert_called_with(expected, 'Exporter', 1) # Nothing should be left in the queue because worker is terminated # and the data was dropped. self.assertEqual(worker._queue.qsize(), 0)
def testMainHandlerGetMocked(self, mock): # Arrange: Make a fake web request that will be routed to MainHandler's get(). request = webapp2.Request.blank('/home') # Act: Give the request to the app. response = request.get_response(main.app) # Assert mock.assert_called_with('home-page.html')
def test_side_effect(self): mock = Mock() def effect(*args, **kwargs): raise SystemError('kablooie') mock.side_effect = effect self.assertRaises(SystemError, mock, 1, 2, fish=3) mock.assert_called_with(1, 2, fish=3) results = [1, 2, 3] def effect(): return results.pop() mock.side_effect = effect self.assertEqual([mock(), mock(), mock()], [3, 2, 1], "side effect not used correctly") mock = Mock(side_effect=sentinel.SideEffect) self.assertEqual(mock.side_effect, sentinel.SideEffect, "side effect in constructor not used") def side_effect(): return DEFAULT mock = Mock(side_effect=side_effect, return_value=sentinel.RETURN) self.assertEqual(mock(), sentinel.RETURN)
def test_get_one_or_else_multiple_results(self, mock): journo_1, _ = db_helper.init_journalist() journo_2, _ = db_helper.init_journalist() with mock.patch('logger') as mock_logger: get_one_or_else(Journalist.query, mock_logger, mock) mock_logger.error.assert_called() # Not specifying very long log line mock.assert_called_with(500)
def test_get_is_called(): # check that JobResult.is_done() calls .get() on QPU prior to # returning result qpu_connect = QPUConnection('test') job_result = JobResult(qpu_connect, False, result={'result': 0}) with patch.object(job_result, 'get') as mock: job_result.is_done() mock.assert_called_with()
def testSuccessHandler(self, mock): # Arrange. request = webapp2.Request.blank('/success') # Act. response = request.get_response(main.app) # Assert. self.assertEqual(main.error, "") mock.assert_called_with('success.html')
def test_toggle_scene(given_that, scene_switch, assert_that, time_travel): given_that.state_of('light.some_light_group') \ .is_set_to('off') with patch('appdaemon.plugins.hass.hassapi.Hass.select_option') as mock: scene_switch.toggle_scene({"scene": "Scene Name"}) mock.assert_called_with("input_select.some_scene_toggle_input_select", "Scene Name") scene_switch.scene_utils.turn_on_current_scene.assert_not_called()
def test_get_one_or_else_no_result_found(self, mock): query = Journalist.query.filter(Journalist.username == "alice") with mock.patch('logger') as mock_logger: selected_journos = get_one_or_else(query, mock_logger, mock) log_line = 'Found none when one was expected: No row was found for one()' mock_logger.error.assert_called_with(log_line) mock.assert_called_with(404)
def test_get_one_or_else_no_result_found(self, mock): query = Journalist.query.filter(Journalist.username == "alice") with mock.patch('logger') as mock_logger: get_one_or_else(query, mock_logger, mock) log_line = ('Found none when one was expected: ' 'No row was found for one()') mock_logger.error.assert_called_with(log_line) mock.assert_called_with(404)
def _check(mock): mock(1, b=2, c=3) mock.assert_called_with(1, 2, 3) mock.assert_called_with(a=1, b=2, c=3) self.assertRaises(AssertionError, mock.assert_called_with, 1, b=3, c=2)
def run(args): args.pre_kill_hook = 'myhook' old_app = {'id': 'oldApp'} new_app = {'id': 'newApp'} tasks_to_kill = ['task1', 'task2'] zdd.execute_pre_kill_hook(args, old_app, tasks_to_kill, new_app) mock.assert_called_with([ args.pre_kill_hook, '{"id": "oldApp"}', '["task1", "task2"]', '{"id": "newApp"}' ])
def test_setting_call(self): mock = Mock() def __call__(self, a): return self._mock_call(a) type(mock).__call__ = __call__ mock('one') mock.assert_called_with('one') self.assertRaises(TypeError, mock, 'one', 'two')
def run(args): new_app = { 'instances': 10, 'labels': { 'HAPROXY_DEPLOYMENT_TARGET_INSTANCES': 30 } } old_app = {'instances': 8} args.initial_instances = 5 zdd.scale_new_app_instances(args, new_app, old_app) mock.assert_called_with(args, new_app, 30)
def test_setting_call(self): mock = Mock() def __call__(self, a): return self._mock_call(a) type(mock).__call__ = __call__ mock("one") mock.assert_called_with("one") self.assertRaises(TypeError, mock, "one", "two")
def run(args): new_app = { 'instances': 10, 'labels': { 'HAPROXY_DEPLOYMENT_TARGET_INSTANCES': 30 } } old_app = {'instances': 8} args.initial_instances = 5 zdd.scale_new_app_instances(args, new_app, old_app) mock.assert_called_with( args, new_app, 30)
def test_canot_parse_items(self, mock): from pypi_updates.bot import RSS_URL target_obj = self._make_one() update_status = target_obj.funcs[0]['options']['callback'] with logbook.TestHandler() as log_handler: update_status(target_obj) assert log_handler.formatted_records == [ '[WARNING] [kuroko user]: Cannot parse RSS: {}'.format(RSS_URL) ] mock.assert_called_with(RSS_URL)
def test_java_exception_side_effect(self): import java mock = Mock(side_effect=java.lang.RuntimeException("Boom!")) # can't use assertRaises with java exceptions try: mock(1, 2, fish=3) except java.lang.RuntimeException: pass else: self.fail('java exception not raised') mock.assert_called_with(1,2, fish=3)
def testLoginHandlerCookieFaculty(self, mock): user = User() user.Fname = "Matt" user.Lname = "K" user.email = "*****@*****.**" user.password = "******" user.isInstructor = True main.u = user user.put() request = webapp2.Request.blank('/login') request.cookies['uname'] = "*****@*****.**" response = request.get_response(main.app) mock.assert_called_with('Faculty_landing.html')
def test_assert_called_with(self): mock = Mock() mock() # Will raise an exception if it fails mock.assert_called_with() self.assertRaises(AssertionError, mock.assert_called_with, 1) mock.reset_mock() self.assertRaises(AssertionError, mock.assert_called_with) mock(1, 2, 3, a='fish', b='nothing') mock.assert_called_with(1, 2, 3, a='fish', b='nothing')
def test_git_clone(self, mock): res = resource.GitResource( {'git': {'url': 'url', 'ref': 'ref'}}) res.copy('dir') mock.assert_called_with(['git', 'clone', '--depth', '1', 'url', 'dir/url-ref', '-b', 'ref'], stderr=-2)
def test_pre_kill_hook(self, mock): # TODO(BM): This test is naive. An end-to-end test would be nice. args = Arguments() args.pre_kill_hook = 'myhook' old_app = {'id': 'oldApp'} new_app = {'id': 'newApp'} tasks_to_kill = ['task1', 'task2'] zdd.execute_pre_kill_hook(args, old_app, tasks_to_kill, new_app) mock.assert_called_with([ args.pre_kill_hook, '{"id": "oldApp"}', '["task1", "task2"]', '{"id": "newApp"}' ])
def test_list_with_pagination(self, mock): self.call(execution_cmd.List) mock.assert_called_once_with(limit=None, marker='', sort_dirs='asc', sort_keys='created_at') self.call(execution_cmd.List, app_args=['--limit', '5', '--sort_dirs', 'id, Workflow', '--sort_keys', 'desc', '--marker', 'abc']) mock.assert_called_with(limit=5, marker='abc', sort_dirs='id, Workflow', sort_keys='desc')
def test_scale_new_app_instances_to_target(self, mock): """When scaling new instances up, if we have met or surpassed the amount of instances deployed for old_app, go right to our deployment target amount of instances for new_app """ new_app = { 'instances': 10, 'labels': { 'HAPROXY_DEPLOYMENT_TARGET_INSTANCES': 30 } } old_app = {'instances': 8} args = Arguments() args.initial_instances = 5 zdd.scale_new_app_instances(args, new_app, old_app) mock.assert_called_with(args, new_app, 30)
def test_scale_new_app_instances_up_50_percent(self, mock): """When scaling new_app instances, increase instances by 50% of existing instances if we have not yet met or surpassed the amount of instances deployed by old_app """ new_app = { 'instances': 10, 'labels': { 'HAPROXY_DEPLOYMENT_TARGET_INSTANCES': 30 } } old_app = {'instances': 30} args = Arguments() args.initial_instances = 5 zdd.scale_new_app_instances(args, new_app, old_app) mock.assert_called_with(args, new_app, 15)
def test_scale_new_app_instances_up_50_percent(self, mock): """When scaling new_app instances, increase instances by 50% of existing instances if we have not yet met or surpassed the amount of instances deployed by old_app """ new_app = { 'instances': 10, 'labels': { 'HAPROXY_DEPLOYMENT_TARGET_INSTANCES': 30 } } old_app = {'instances': 30} args = Arguments() args.initial_instances = 5 zdd.scale_new_app_instances(args, new_app, old_app) mock.assert_called_with( args, new_app, 15)
def test_scale_new_app_instances_to_target(self, mock): """When scaling new instances up, if we have met or surpassed the amount of instances deployed for old_app, go right to our deployment target amount of instances for new_app """ new_app = { 'instances': 10, 'labels': { 'HAPROXY_DEPLOYMENT_TARGET_INSTANCES': 30 } } old_app = {'instances': 8} args = Arguments() args.initial_instances = 5 zdd.scale_new_app_instances(args, new_app, old_app) mock.assert_called_with( args, new_app, 30)
def run(args): args.pre_kill_hook = 'myhook' old_app = { 'id': 'oldApp' } new_app = { 'id': 'newApp' } tasks_to_kill = ['task1', 'task2'] zdd.execute_pre_kill_hook(args, old_app, tasks_to_kill, new_app) mock.assert_called_with([args.pre_kill_hook, '{"id": "oldApp"}', '["task1", "task2"]', '{"id": "newApp"}'])
def testMainHandlerPostEmailError(self, mock): # Arrange: If there's not exactly one user, an error occurs. # POST is a dictionary; it adds this data to a request object...or something. I think this is unnecessary. test_request = webapp2.Request.blank('/home', POST={ "user_email": "*****@*****.**", "pass_word": "FAKEPASSWORD" }) test_request.method = 'POST' # I have no idea why this line is necessary. mock.return_value = None # Act: Give the request to the app. response = test_request.get_response(main.app) # Assert: Inspect the response mock.assert_called_with('/home') self.assertEqual(main.error, "Invalid email!")
def test_refresh_listeners_check_that_scene_switch_timer_are_set_check_current_scene_activated( given_that, scene_switch, assert_that, time_travel): given_that.time_is(time(hour=20)) given_that.state_of('light.some_light_group') \ .is_set_to('on') given_that.state_of('input_datetime.work_light_start_time') \ .is_set_to('08:30:00') given_that.state_of('input_select.work_light_input_select') \ .is_set_to('Work Light') given_that.state_of('input_datetime.night_light_start_time') \ .is_set_to('22:45:00') given_that.state_of('input_select.night_light_input_select') \ .is_set_to('Night Light') given_that.state_of('input_select.some_time_based_scenes') \ .is_set_to('work_light_start_time/Work Light', {'options': ['work_light_start_time/work_light_input_select', 'night_light_start_time/night_light_input_select']}) with patch('appdaemon.plugins.hass.hassapi.Hass.select_option') as mock: scene_switch.refresh_listeners(None, None, None, None, None) assert_that(scene_switch) \ .registered.run_daily(time(hour=8, minute=30), scene="Work Light") \ .with_callback(scene_switch.toggle_scene) assert_that(scene_switch) \ .listens_to.state("input_datetime.work_light_start_time") \ .with_callback(scene_switch.refresh_listeners) assert_that(scene_switch) \ .listens_to.state("input_select.work_light_input_select") \ .with_callback(scene_switch.refresh_listeners) assert_that(scene_switch) \ .registered.run_daily(time(hour=22, minute=45), scene="Night Light") \ .with_callback(scene_switch.toggle_scene) assert_that(scene_switch) \ .listens_to.state("input_datetime.night_light_start_time") \ .with_callback(scene_switch.refresh_listeners) assert_that(scene_switch) \ .listens_to.state("input_select.night_light_input_select") \ .with_callback(scene_switch.refresh_listeners) mock.assert_called_with("input_select.some_scene_toggle_input_select", "Work Light") scene_switch.scene_utils.turn_on_current_scene.assert_called_once_with( "some_room", "input_select.some_scene_toggle_input_select")
def testMainHandlerPostPWError(self, mock): # Arrange: Put a User in the datastore stub; POST the wrong password. test_User = User() test_User.email = "*****@*****.**" test_User.password = "******" test_User.put() test_request = webapp2.Request.blank('/home', POST={ "user_email": "*****@*****.**", "pass_word": "WRONGPASSWORD" }) test_request.method = 'POST' mock.return_value = None # Act: Give the request to the app. response = test_request.get_response(main.app) # Assert: Inspect the response. mock.assert_called_with('/home') self.assertEqual(main.error, "Incorrect password!")
def test_pre_kill_hook(self, mock): # TODO(BM): This test is naive. An end-to-end test would be nice. args = Arguments() args.pre_kill_hook = 'myhook' old_app = { 'id': 'oldApp' } new_app = { 'id': 'newApp' } tasks_to_kill = ['task1', 'task2'] zdd.execute_pre_kill_hook(args, old_app, tasks_to_kill, new_app) mock.assert_called_with([args.pre_kill_hook, '{"id": "oldApp"}', '["task1", "task2"]', '{"id": "newApp"}'])
def test_assert_called_with_function_spec(self): def f(a, b, c, d=None): pass mock = Mock(spec=f) mock(1, b=2, c=3) mock.assert_called_with(1, 2, 3) mock.assert_called_with(a=1, b=2, c=3) self.assertRaises(AssertionError, mock.assert_called_with, 1, b=3, c=2) # Expected call doesn't match the spec's signature with self.assertRaises(AssertionError) as cm: mock.assert_called_with(e=8) if hasattr(cm.exception, '__cause__'): self.assertIsInstance(cm.exception.__cause__, TypeError)
def test_class_fullname(self, mock): target = self._makeOne(self._getDummyModel(), 'connection') self.assertEqual('dummy', target.class_fullname) mock.assert_called_with('TestModel')
def test_test_vnf_unimplemented(self, mock): self.assertEqual(self.test.test_vnf(), testcase_base.TestcaseBase.EX_TESTCASE_FAILED) mock.assert_called_with('VNF must be tested')
def test_null_blank(self, mock): target = self._makeOne('dummy_field', 'dummy', 'dummy', 'dummy') self.assertEqual('dummy_field', target.null_blank) mock.assert_called_with('dummy_field')
def test_resource_verify(self, mock): res = resource.Resource.__new__(resource.Resource) res.checksums = {'sha256': 'justamocksum'} res._Resource__verify('dummy') mock.assert_called_with('dummy', 'sha256', 'justamocksum')
def test_select2_modelform_attrs_argument(mock): utils.select2_modelform(m.TestFieldsModel) mock.assert_called_with(m.TestFieldsModel, attrs=None) attrs = {'attr': False} utils.select2_modelform(m.TestFieldsModel, attrs=attrs) mock.assert_called_with(m.TestFieldsModel, attrs=attrs)
def test_refresh_listeners_listeners_updated_on_next_call( given_that, scene_switch, assert_that, time_travel): given_that.state_of('light.some_light_group') \ .is_set_to('off') given_that.time_is(time(hour=8)) given_that.state_of('input_select.some_time_based_scenes') \ .is_set_to('work_light_start_time/work_light_input_select', {'options': ['work_light_start_time/work_light_input_select']}) given_that.state_of('input_datetime.work_light_start_time') \ .is_set_to('08:30:00') given_that.state_of('input_select.work_light_input_select') \ .is_set_to('Work Light') with patch('appdaemon.plugins.hass.hassapi.Hass.select_option') as mock: scene_switch.refresh_listeners(None, None, None, None, None) assert_that(scene_switch) \ .listens_to.state("input_datetime.work_light_start_time") \ .with_callback(scene_switch.refresh_listeners) assert_that(scene_switch) \ .listens_to.state("input_select.work_light_input_select") \ .with_callback(scene_switch.refresh_listeners) mock.assert_called_with("input_select.some_scene_toggle_input_select", "Work Light") given_that.mock_functions_are_cleared() given_that.state_of('input_select.some_time_based_scenes') \ .is_set_to('night_light_start_time/night_light_input_select', {'options': ['night_light_start_time/night_light_input_select']}) given_that.state_of('input_datetime.night_light_start_time') \ .is_set_to('10:30:00') given_that.state_of('input_select.night_light_input_select') \ .is_set_to('Night Light') with patch('appdaemon.plugins.hass.hassapi.Hass.select_option' ) as select_option_mock: with patch('appdaemon.plugins.hass.hassapi.Hass.cancel_listen_state'): scene_switch.refresh_listeners(None, None, None, None, None) assert_that(scene_switch) \ .registered.run_daily(time(hour=10, minute=30), scene="Night Light") \ .with_callback(scene_switch.toggle_scene) select_option_mock.assert_called_with( "input_select.some_scene_toggle_input_select", "Night Light") assert_that(scene_switch) \ .listens_to.state("input_datetime.night_light_start_time") \ .with_callback(scene_switch.refresh_listeners) assert_that(scene_switch) \ .listens_to.state("input_select.night_light_input_select") \ .with_callback(scene_switch.refresh_listeners) scene_switch.scene_utils.turn_on_current_scene.assert_not_called() with pytest.raises(AssertionError): assert_that(scene_switch) \ .listens_to.state("input_datetime.work_light_start_time") \ .with_callback(scene_switch.refresh_listeners) with pytest.raises(AssertionError): assert_that(scene_switch) \ .listens_to.state("input_select.work_light_input_select") \ .with_callback(scene_switch.refresh_listeners) with pytest.raises(AssertionError): assert_that(scene_switch) \ .registered.run_daily(time(hour=8, minute=30), scene="Work Light") \ .with_callback(scene_switch.toggle_scene)