本文整理汇总了Python中mock.Mock.configure_mock方法的典型用法代码示例。如果您正苦于以下问题:Python Mock.configure_mock方法的具体用法?Python Mock.configure_mock怎么用?Python Mock.configure_mock使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类mock.Mock
的用法示例。
在下文中一共展示了Mock.configure_mock方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_location_from_contact
# 需要导入模块: from mock import Mock [as 别名]
# 或者: from mock.Mock import configure_mock [as 别名]
def test_location_from_contact(self):
"""
If location information is input (include address label/name), then
a location should be created along with the contact.
"""
request = Mock()
request.configure_mock(user=self.staff_user, impersonator=None)
data = {
"name": "John Doe",
"partner": self.partner.pk,
"company_id": 1
}
address_info = {
'label': 'Home',
'address_line_one': "123 Fake St",
'address_line_two': "Ste 321",
'city': "Somewhere",
"state": "NM"}
data.update(address_info)
form = ContactForm(data=data)
self.assertTrue(form.is_valid())
form.save(request, self.partner.pk)
self.assertTrue(Location.objects.filter(**address_info).exists())
示例2: test_get_repo_branch
# 需要导入模块: from mock import Mock [as 别名]
# 或者: from mock.Mock import configure_mock [as 别名]
def test_get_repo_branch(self, mock_sub_popen):
process_mock = Mock()
attrs = {'communicate.return_value': ('ouput', 'error')}
process_mock.configure_mock(**attrs)
mock_sub_popen.return_value = process_mock
test.ask(question='What branch is <test/main_test.py>?')
self.assertTrue(mock_sub_popen.called);
示例3: web_request
# 需要导入模块: from mock import Mock [as 别名]
# 或者: from mock.Mock import configure_mock [as 别名]
def web_request():
"""Mock web request for views testing."""
from pyramid_localize.request import LocalizeRequestMixin
from pyramid_localize.request import database_locales
from pyramid_localize.request import locale_id
from pyramid_localize.request import locales
class TestRequest(LocalizeRequestMixin, Request): # pylint:disable=too-many-ancestors
"""Test request object."""
@reify
def _database_locales(self):
return database_locales(self)
@reify
def locale_id(self):
"""Returns a database locale id."""
return locale_id(self)
def locales(self, *args, **kwargs):
"""Return all availablee locales."""
return locales(self, *args, **kwargs)
request = TestRequest({})
config = Mock()
config.configure_mock(
**{'localize.locales.available': ['en', 'pl', 'de', 'cz']}
)
configurator = testing.setUp()
request.registry = configurator.registry # pylint:disable=attribute-defined-outside-init
request.registry['config'] = config
return request
示例4: test_get_repo_url
# 需要导入模块: from mock import Mock [as 别名]
# 或者: from mock.Mock import configure_mock [as 别名]
def test_get_repo_url(self, mock_sub_popen):
process_mock = Mock()
attrs = {'communicate.return_value': ('ouput', 'error')}
process_mock.configure_mock(**attrs)
mock_sub_popen.return_value = process_mock
test.ask(question='Where did <Job_Story_Traces.txt> come from?')
self.assertTrue(mock_sub_popen.called);
示例5: TestModelsUpdateAccount
# 需要导入模块: from mock import Mock [as 别名]
# 或者: from mock.Mock import configure_mock [as 别名]
class TestModelsUpdateAccount(AccountTestCase):
@patch.object(sitewit.models.SitewitService, 'put')
def setUp(self, put_mock):
self.put_mock = put_mock
self._mock_response(put_mock, self.response_brief)
self.site = Mock(id=self.site_id)
self.user = Mock(
location=self.country_code, currency=self.currency,
time_zone=self.time_zone)
self.user.configure_mock(name=self.user_name, email=self.user_email)
self.account = Account.update(
self.token, url=self.url, country_code=self.country_code,
currency=self.currency
)
def test_demands_put_is_called(self):
put_data = {
'url': self.url,
'currency': self.currency,
'countryCode': self.country_code,
}
self.assertDemandsIsCalled(self.put_mock, put_data, self.token)
def test_account_object_is_returned(self):
self.assertAccountIsValid(self.account)
示例6: test_api_base
# 需要导入模块: from mock import Mock [as 别名]
# 或者: from mock.Mock import configure_mock [as 别名]
def test_api_base(self):
app = Mock()
app.configure_mock(**{'record.side_effect': AttributeError})
api = flask_restful.Api(app)
self.assertEquals(api.urls, {})
self.assertEquals(api.prefix, '')
self.assertEquals(api.default_mediatype, 'application/json')
示例7: test_in_repo_changed
# 需要导入模块: from mock import Mock [as 别名]
# 或者: from mock.Mock import configure_mock [as 别名]
def test_in_repo_changed(self, mock_sub_popen):
process_mock = Mock()
attrs = {'communicate.return_value': ('ouput', 'error')}
process_mock.configure_mock(**attrs)
mock_sub_popen.return_value = process_mock
test.ask(question='What is the status of <requirements.txt>?')
self.assertTrue(mock_sub_popen.called);
示例8: test_user_update_view_post
# 需要导入模块: from mock import Mock [as 别名]
# 或者: from mock.Mock import configure_mock [as 别名]
def test_user_update_view_post(self):
self.client.login(username='fred', password='secret')
bob = get_user_model().objects.get(username='bob')
url = reverse('kanisa_manage_users_update', args=[bob.pk, ])
mock_file = Mock(spec=django.core.files.File)
mock_file.configure_mock(name='foo.bar')
mock_file.read.return_value = "Just some data"
resp = self.client.post(url, {'email': '[email protected]',
'first_name': 'Bob',
'last_name': 'Builder',
'image': mock_file},
follow=True)
self.assertEqual(resp.status_code, 200)
self.assertTrue('form' not in resp.context)
self.assertEqual([m.message for m in resp.context['messages']],
['Registered User "Bob" saved.', ])
bob = get_user_model().objects.get(username='bob')
# Clean up after our file
bob.image.delete()
self.assertEqual(bob.email, '[email protected]')
self.client.logout()
示例9: test_start
# 需要导入模块: from mock import Mock [as 别名]
# 或者: from mock.Mock import configure_mock [as 别名]
def test_start(self):
# A large set of mocks required to make sure that this test tests start, not
# any other function
# Does not currently cover exception in the event read loop
resource = {
'resource': {
'SlackBotAccessToken': 'token'
}
}
mock_messenger = MagicMock(return_value="dummy messenger")
mock_event_handler = Mock()
attrs = {'handle.return_value': "dummy return"}
mock_event_handler.configure_mock(**attrs)
mock_rtm = MagicMock(return_value=mock_event_handler)
mock_slack_clients = MagicMock(return_value="dummy clients")
slackbot = SlackBot("token", mock_slack_clients)
slackbot.clients = Mock(rtm=Mock(rtm_connect=None, rtm_read=None, server=Mock(username=None, login_data={'team':{'name': None}}, domain=None)))
slackbot.clients.rtm.rtm_connect = MagicMock(return_value=True)
slackbot.clients.rtm.server.username = "dummy username"
slackbot.clients.rtm.server.login_data['team']['name'] = "dummy team name"
slackbot.clients.rtm.server.domain = "dummy domain"
slackbot.clients.rtm.rtm_read = MagicMock(return_value=['event1', 'event2', 'event3'])
# Ensure that start completes without error
self.assertEqual(slackbot.start(resource, mock_messenger, mock_rtm), None)
示例10: test_layer1
# 需要导入模块: from mock import Mock [as 别名]
# 或者: from mock.Mock import configure_mock [as 别名]
def test_layer1(self):
"""Testing method / function layer1."""
# Initializing key variables
expected_dict = {
199: {'cdpCacheDeviceId': 'byte_string_1',
'cdpCachePlatform': 'byte_string_1',
'cdpCacheDevicePort': 'byte_string_1'},
299: {'cdpCacheDeviceId': 'byte_string_2',
'cdpCachePlatform': 'byte_string_2',
'cdpCacheDevicePort': 'byte_string_2'}
}
# Set the stage for SNMPwalk
snmpobj = Mock(spec=Query)
mock_spec = {'swalk.return_value': self.walk_results_string}
snmpobj.configure_mock(**mock_spec)
# Get results
testobj = testimport.init_query(snmpobj)
results = testobj.layer1()
# Basic testing of results
for primary in results.keys():
for secondary in results[primary].keys():
self.assertEqual(
results[primary][secondary],
expected_dict[primary][secondary])
示例11: createMockSpec
# 需要导入模块: from mock import Mock [as 别名]
# 或者: from mock.Mock import configure_mock [as 别名]
def createMockSpec(self, additional_spec_items={}):
default_server_disk_spec = aws_disk.AwsDiskSpec(
_COMPONENT,
disk_size=5,
disk_type=aws_disk.IO1,
iops=1000)
default_server_vm_spec = virtual_machine.BaseVmSpec(
'NAME', **{'machine_type': 'db.t1.micro',
'zone': 'us-west-2b'})
spec_dict = {
'engine': MYSQL,
'engine_version': '5.7.11',
'run_uri': '123',
'database_name': 'fakedbname',
'database_password': 'fakepassword',
'database_username': 'fakeusername',
'high_availability': False,
'vm_spec': default_server_vm_spec,
'disk_spec': default_server_disk_spec,
}
spec_dict.update(additional_spec_items)
mock_db_spec = Mock(
spec=benchmark_config_spec._ManagedRelationalDbSpec)
mock_db_spec.configure_mock(**spec_dict)
return mock_db_spec
示例12: test_fetch_options
# 需要导入模块: from mock import Mock [as 别名]
# 或者: from mock.Mock import configure_mock [as 别名]
def test_fetch_options(self):
mock = Mock()
mock.configure_mock(**{
"files.return_value.list.return_value.execute.return_value": GDRIVE_LIST_RESPONSE})
with patch("clients.drive.build", return_value=mock):
response = self.client.get(reverse("spreadsheet_list"))
self.assertTrue(response.status_code, 200)
# Only 3 inputs
self.assertTrue(
len([
m.start() for m in re.finditer(
'<input type="radio" name="spreadsheet_id"',
response.content
)
]),
3
)
# Only 3 anchors
self.assertTrue(
len([
m.start() for m in re.finditer(
'<a href="http://example.com/spreadsheet/00[123]" target="_blank">Link</a>',
response.content
)
]),
3
)
self.assertIn("Spreadsheet 001", response.content)
self.assertIn("Spreadsheet 002", response.content)
self.assertIn("Spreadsheet 003", response.content)
示例13: TestFactoryBoyMiddleware
# 需要导入模块: from mock import Mock [as 别名]
# 或者: from mock.Mock import configure_mock [as 别名]
class TestFactoryBoyMiddleware(TestCase):
def setUp(self):
self.middleware = FactoryBoyMiddleware()
self.request = Mock()
self.request.session = {}
def test_process_request_creates_object(self):
self.request.configure_mock(
**{
'GET': {
'FACTORY_BOY_MODEL_PATH': 'mysite.tests.factories.UserFactory', # noqa
'FACTORY_BOY_ARGS': ''
}
}
)
response = self.middleware.process_request(self.request)
self.assertEqual(201, response.status_code)
self.assertEqual(
'johndoe',
json.loads(response.content.decode('utf-8')).get('username')
)
self.assertEqual(1, len(User.objects.values()))
self.assertEqual('johndoe', User.objects.values()[0]['username'])
示例14: test_dispatch_triggers_on_spawn_exit
# 需要导入模块: from mock import Mock [as 别名]
# 或者: from mock.Mock import configure_mock [as 别名]
def test_dispatch_triggers_on_spawn_exit(self):
mock_dispatcher = Mock()
process_container = ProcessSensorContainer(None, poll_interval=0.1,
dispatcher=mock_dispatcher)
sensor = {
'class_name': 'pack.StupidSensor'
}
process = Mock()
process_attrs = {'pid': 1234}
process.configure_mock(**process_attrs)
cmd = 'sensor_wrapper.py --class-name pack.StupidSensor'
process_container._dispatch_trigger_for_sensor_spawn(sensor, process, cmd)
mock_dispatcher.dispatch.assert_called_with(
'core.st2.sensor.process_spawn',
payload={
'timestamp': 1439441533,
'cmd': 'sensor_wrapper.py --class-name pack.StupidSensor',
'pid': 1234,
'id': 'pack.StupidSensor'})
process_container._dispatch_trigger_for_sensor_exit(sensor, 1)
mock_dispatcher.dispatch.assert_called_with(
'core.st2.sensor.process_exit',
payload={
'id': 'pack.StupidSensor',
'timestamp': 1439441533,
'exit_code': 1
})
示例15: test_common_lib_path_not_in_pythonpath_env_var
# 需要导入模块: from mock import Mock [as 别名]
# 或者: from mock.Mock import configure_mock [as 别名]
def test_common_lib_path_not_in_pythonpath_env_var(self, mock_create_token, mock_subproc_popen):
process_mock = Mock()
attrs = {'communicate.return_value': ('output', 'error')}
process_mock.configure_mock(**attrs)
mock_subproc_popen.return_value = process_mock
mock_create_token = Mock()
mock_create_token.return_value = 'WHOLETTHEDOGSOUT'
mock_dispatcher = Mock()
process_container = ProcessSensorContainer(None, poll_interval=0.1,
dispatcher=mock_dispatcher)
sensor = {
'class_name': 'wolfpack.StupidSensor',
'ref': 'wolfpack.StupidSensor',
'id': '567890',
'trigger_types': ['some_trigga'],
'pack': 'wolfpack',
'file_path': '/opt/stackstorm/packs/wolfpack/sensors/stupid_sensor.py',
'poll_interval': 5
}
process_container._enable_common_pack_libs = False
process_container._sensors = {'pack.StupidSensor': sensor}
process_container._spawn_sensor_process(sensor)
_, call_kwargs = mock_subproc_popen.call_args
actual_env = call_kwargs['env']
self.assertTrue('PYTHONPATH' in actual_env)
pack_common_lib_path = '/opt/stackstorm/packs/wolfpack/lib'
self.assertTrue(pack_common_lib_path not in actual_env['PYTHONPATH'])