def test_help(): with mock.patch_object(_shell.parser, 'print_help') as m: shell('help') m.assert_called() with mock.patch_object(_shell.subcommands['delete'], 'print_help') as m: shell('help delete') m.assert_called() assert_raises(CommandError, shell, 'help foofoo')
def test_auth_automatic(): client = cloudservers.CloudServers("username", "apikey").client client.management_url = '' mock_request = mock.Mock(return_value=(None, None)) with mock.patch_object(client, 'request', mock_request): with mock.patch_object(client, 'authenticate') as mock_authenticate: client.get('/') mock_authenticate.assert_called() mock_request.assert_called()
def process_report(self, report): # don't really save the report, since that would try to upload the csv # file to S3 with mock.patch_object(report, 'save') as mock_save: report.process() self.assertEquals(mock_save.call_count, 1) return report.csv_file.read()
def test_reply_without_post_permission(self): """Posting without post_in_forum permission should 403.""" self.client.login(username='******', password='******') with patch_object(Forum, 'allows_viewing_by', Mock(return_value=True)): response = post(self.client, 'forums.reply', {'content': 'Blahs'}, args=['restricted-forum', 6]) eq_(403, response.status_code)
def test_new_thread_without_post_permission(self): """Making a new thread without post permission should 403.""" self.client.login(username='******', password='******') with patch_object(Forum, 'allows_viewing_by', Mock(return_value=True)): response = post(self.client, 'forums.new_thread', {'title': 'Blahs', 'content': 'Blahs'}, args=['restricted-forum']) eq_(403, response.status_code)
def test_get(): cl = client() with mock.patch_object(httplib2.Http, "request", mock_request): resp, body = cl.get("/hi") mock_request.assert_called_with("http://example.com/hi", "GET", headers={"X-Auth-Token": "token", "User-Agent": cl.USER_AGENT}) # Automatic JSON parsing assert_equal(body, {"hi":"there"})
def test_client_call(self): """ Tests ``__call__`` method. """ mock_get_json = mock.Mock(return_value={}) with mock.patch_object(utils, 'get_json', mock_get_json) as mocked: c = FlickrClient('apikey') res = c.foo.bar(a=1, b=2) self.assert_(mocked.called)
def test_client_call_fail(self): """ Tests ``__call__`` method which fails. """ failure = {'stat': 'fail', 'code': 1, 'message': 'fail'} mock_get_json = mock.Mock(return_value=failure) with mock.patch_object(utils, 'get_json', mock_get_json): c = FlickrClient('apikey') self.assertRaises(FlickrError, c.foo)
def test_done_in_range_feeds_card_info(self): start_date = datetime(2012, 1, 1) end_date = datetime(2012, 12, 31) with mock.patch('kardboard.services.teams.Kard') as mock_Kard: with mock.patch_object(self.service, '_card_info') as mock_card_info: return_value = [mock.Mock(), mock.Mock()] mock_Kard.objects.filter.return_value = return_value self.service.done_in_range(start_date, end_date) mock_card_info.assert_called_with(return_value)
def test_post(): cl = client() with mock.patch_object(httplib2.Http, "request", mock_request): cl.post("/hi", body=[1, 2, 3]) mock_request.assert_called_with("http://example.com/hi", "POST", headers = { "X-Auth-Token": "token", "Content-Type": "application/json", "User-Agent": cl.USER_AGENT}, body = '[1, 2, 3]' )
def test_new_thread_without_post_permission(self): """Making a new thread without post permission should 403.""" self.client.login(username='******', password='******') with patch_object(Forum, 'allows_viewing_by', Mock(return_value=True)): response = post(self.client, 'forums.new_thread', { 'title': 'Blahs', 'content': 'Blahs' }, args=['restricted-forum']) eq_(403, response.status_code)
def patch_object(*args, **kwargs): """Unified patch_object for various versions of Python Mock. Different Python Mock versions provide incompatible versions of patching an object. More recent versions use _patch_object, older ones used patch_object. This function unifies the different variations. """ import mock try: return mock._patch_object(*args, **kwargs) except AttributeError: return mock.patch_object(*args, **kwargs)
def test_list_devices_passthrough(self, context): with mock.patch_object(Enumerator, 'match') as match: context.list_devices(subsystem=mock.sentinel.subsystem, sys_name=mock.sentinel.sys_name, tag=mock.sentinel.tag, prop1=mock.sentinel.prop1, prop2=mock.sentinel.prop2) match.assert_called_with( subsystem=mock.sentinel.subsystem, sys_name=mock.sentinel.sys_name, tag=mock.sentinel.tag, prop1=mock.sentinel.prop1, prop2=mock.sentinel.prop2)
def test_init_logs_amqp_send_with_no_amqp_handler(self): """ init_logs_amqp_send() will add an `AMQPHandler` instance to the root logger if none is present. """ mm = mock.MagicMock(spec=kombu.messaging.Producer) with mock.patch_object(logs.AMQPHandler, "_initialize") as minit: minit.return_value = mm with helpers.patch("logging.root.addHandler") as mah: logs.init_logs_amqp_send("info", 321) self.assertEqual(1, mah.call_count) (single_arg,) = mah.call_args[0] self.assertTrue(isinstance(single_arg, logs.AMQPHandler)) self.assertEqual(logging.root.level, logging.INFO)
def patch_object(*args, **kwargs): """Unified patch_object for various versions of Python Mock. Different Python Mock versions provide incompatible versions of patching an object. More recent versions use _patch_object, older ones used patch_object. This function unifies the different variations. """ import mock try: # pylint: disable=W0212 return mock._patch_object(*args, **kwargs) except AttributeError: # pylint: disable=E1101 return mock.patch_object(*args, **kwargs)
def test_init_logs_amqp_send_with_existing_amqp_handler(self): """ init_logs_amqp_send() will not add more than one `AMQPHandler` instance to the root logger. """ mm = mock.MagicMock(spec=kombu.messaging.Producer) with mock.patch_object(logs.AMQPHandler, "_initialize") as minit: minit.return_value = mm handler = logs.AMQPHandler() handler.set_job_id = mock.Mock() logging.root.handlers.append(handler) with helpers.patch("logging.root.addHandler") as mah: logs.init_logs_amqp_send("info", 322) self.assertEqual(0, mah.call_count) self.assertEqual(1, handler.set_job_id.call_count) self.assertEqual((322,), handler.set_job_id.call_args[0])
def test_authenticate_success(): cs = cloudservers.CloudServers("username", "apikey") auth_response = httplib2.Response({ 'status': 204, 'x-server-management-url': 'https://servers.api.rackspacecloud.com/v1.0/443470', 'x-auth-token': '1b751d74-de0c-46ae-84f0-915744b582d1', }) mock_request = mock.Mock(return_value=(auth_response, None)) with mock.patch_object(httplib2.Http, "request", mock_request): cs.client.authenticate() mock_request.assert_called_with(cs.client.AUTH_URL, 'GET', headers = { 'X-Auth-User': '******', 'X-Auth-Key': 'apikey', 'User-Agent': cs.client.USER_AGENT }) assert_equal(cs.client.management_url, auth_response['x-server-management-url']) assert_equal(cs.client.auth_token, auth_response['x-auth-token'])
def test_init_logs_amqp_send_changes_logging_level(self): """ init_logs_amqp_send() will change the root level logger anyway. """ mm = mock.MagicMock(spec=kombu.messaging.Producer) with mock.patch_object(logs.AMQPHandler, "_initialize") as minit: minit.return_value = mm handler = logs.AMQPHandler() logging.root.handlers.append(handler) handler.set_job_id = mock.Mock() logging.root.setLevel(logging.INFO) logs.init_logs_amqp_send("warning", 322) self.assertEqual(logging.root.level, logging.WARNING) logs.init_logs_amqp_send("debug", 323) self.assertEqual(logging.root.level, logging.DEBUG) logs.init_logs_amqp_send("error", 324) self.assertEqual(logging.root.level, logging.ERROR)
def test_response_processing(self, *mocks): from flaskext.gae_mini_profiler import GAEMiniProfiler app = mock.Mock() rendering = "GAEMiniProfiler" class Response(object): """Mock response""" status_code = 200 is_sequence = True charset = "utf-8" data = u"<body>Hello World!</body>" with mock.patch_object(GAEMiniProfiler, '_render') as render_mock: render_mock.return_value = rendering ext = GAEMiniProfiler(app) new_response = ext._process_response(Response()) self.assertEquals([u"<body>Hello World!GAEMiniProfiler</body>"], new_response.response)
def test_client_call(self): mock_getjson = mock.Mock(return_value={}) with mock.patch_object(utils, "getjson", mock_getjson) as mocked: c = netflix.NetflixClient("aaaa", "bbbb", None) res = c.foo.bar(a=1, b=2) self.assert_(mocked.called)
def _examine_warnings(ws): patch_object(SomeClass, 'class_attribute', spec=SomeClass) warning = ws[0] self.assertIs(warning.category, DeprecationWarning)
def test_auth_manual(): cs = cloudservers.CloudServers("username", "password") with mock.patch_object(cs.client, 'authenticate') as mocked: cs.authenticate() mocked.assert_called()
def test_client_call(self): mock_getjson = mock.Mock(return_value={}) with mock.patch_object(utils, 'getjson', mock_getjson) as mocked: c = flickr.FlickrClient('apikey') res = c.foo.bar(a=1, b=2) self.assert_(mocked.called)
def test_authenticate_failure(): cs = cloudservers.CloudServers("username", "apikey") auth_response = httplib2.Response({'status': 401}) mock_request = mock.Mock(return_value=(auth_response, None)) with mock.patch_object(httplib2.Http, "request", mock_request): assert_raises(cloudservers.Unauthorized, cs.client.authenticate)
def test_client_call_fail(self): failure = {'stat': 'fail', 'code': 1, 'message': 'fail'} mock_getjson = mock.Mock(return_value=failure) with mock.patch_object(utils, 'getjson', mock_getjson): c = flickr.FlickrClient('apikey') self.assertRaises(flickr.FlickrError, c.foo)