本文整理汇总了Python中unittest.mock.create_autospec函数的典型用法代码示例。如果您正苦于以下问题:Python create_autospec函数的具体用法?Python create_autospec怎么用?Python create_autospec使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了create_autospec函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_pool_update
def test_pool_update(self):
"""Test delete"""
api = mock.create_autospec(BatchAppsApi)
pool = Pool(api)
api.get_pool.return_value = mock.create_autospec(Response)
api.get_pool.return_value.success = True
api.get_pool.return_value.result = {
'targetDedicated':'5',
'currentDedicated':'4',
'state':'active',
'allocationState':'test',
}
self.assertEqual(pool.target_size, 0)
self.assertEqual(pool.current_size, 0)
self.assertEqual(pool.state, None)
self.assertEqual(pool.allocation_state, None)
self.assertEqual(pool.resize_error, '')
pool.update()
api.get_pool.assert_called_with(pool_id=None)
self.assertEqual(pool.target_size, 5)
self.assertEqual(pool.current_size, 4)
self.assertEqual(pool.state, 'active')
self.assertEqual(pool.allocation_state, 'test')
self.assertEqual(pool.resize_error, '')
api.get_pool.return_value.success = False
api.get_pool.return_value.result = RestCallException(None, "Test", None)
with self.assertRaises(RestCallException):
pool.update()
示例2: test_run_implementations_parallel_output_enabled_slow_implementations
def test_run_implementations_parallel_output_enabled_slow_implementations(self, mock_loadImplementation):
"""Coverage case for the display_progress option where the future is still not done after the timer expires."""
test_implementation_mapping = {"foo": "bar", "baz": "bog"}
test_command = CommandUnderTest()
# create dummy imps where the side_effect of calling run is to sleep.
mock_imp1 = create_autospec(spec = Implementation, spec_set = True, instance = True)
mock_imp1.run.side_effect = lambda args: time.sleep(4)
mock_imp2 = create_autospec(spec = Implementation, spec_set = True, instance = True)
mock_imp2.run.side_effect = lambda args: time.sleep(5)
gen = (impl for impl in (mock_imp1, mock_imp2))
test_command.impl_list = {
key: next(gen) for key in test_implementation_mapping
}
result = test_command.run_implementations_parallel(
implementation_mapping = test_implementation_mapping,
display_progress = True
)
assert result == {
key: namedtuple("_", ("result", "exception"))(
result = None,
exception = None,
)
for key in test_implementation_mapping
}
示例3: test_copy_target
def test_copy_target():
src = create_autospec(Path, spec_set=True)
dest = create_autospec(Path, spec_set=True)
ct = CopyTarget(src, dest)
assert ct.dest == dest
ct.dest.exists.return_value = False
with patch("shutil.copy2") as copy2, patch("filecmp.cmp") as cmp:
cmp.return_value = False
cres1 = ct.create()
cres1.is_success
assert copy2.call_count == 1
assert cmp.call_count == 0
ct.dest.exists.return_value = True
with patch("shutil.copy2") as copy2, patch("filecmp.cmp") as cmp:
cmp.return_value = False
cres2 = ct.create()
cres2.is_success
assert copy2.call_count == 1
assert cmp.call_count == 1
ct.dest.exists.return_value = True
with patch("shutil.copy2") as copy2, patch("filecmp.cmp") as cmp:
cmp.return_value = True
cres3 = ct.create()
cres3.is_success
assert copy2.call_count == 0
assert cmp.call_count == 1
示例4: __init__
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.randomizer_mock = create_autospec(Randomizer)
self.configuration = EvolutionConfiguration()
self.configuration.operators = EvolutionOperatorsConfiguration()
self.configuration.operators.inversion = EvolutionOperatorConfiguration()
self.configuration.operators.inversion.chance = 0.5
self.configuration.operators.mutation = EvolutionOperatorConfiguration()
self.configuration.operators.mutation.chance = 0.2
self.configuration.operators.crossover = EvolutionOperatorConfiguration()
self.configuration.operators.crossover.chance = 0.3
self.rule_population_mock = create_autospec(RulePopulation)
self.service_mock = create_autospec(EvolutionService)
self.service_mock.configure_mock(randomizer=self.randomizer_mock,
configuration=self.configuration)
self.rule_1 = Rule(Symbol('A'), Symbol('B'), Symbol('C'))
self.rule_2 = Rule(Symbol('D'), Symbol('E'), Symbol('F'))
self.sut = None
示例5: build_mock_player
def build_mock_player(position, pid):
player = create_autospec(Player)
pose = create_autospec(Pose)
pose.position = position
player.pose = pose
player.id = pid
return player
示例6: test_filecoll_extend
def test_filecoll_extend(self, mock_api):
"""Test extend"""
col = FileCollection(mock_api)
col2 = FileCollection(mock_api)
test_file = mock.create_autospec(UserFile)
test_file2 = mock.create_autospec(UserFile)
col._collection = [test_file]
col2._collection = [test_file2, test_file]
with self.assertRaises(AttributeError):
col.extend(None)
with self.assertRaises(AttributeError):
col.extend("test")
with self.assertRaises(AttributeError):
col.extend([])
col.extend(col2)
self.assertEqual(len(col._collection), 2)
self.assertTrue(all(i in [test_file, test_file2]
for i in col._collection))
col2.extend(col)
self.assertEqual(len(col._collection), 2)
self.assertTrue(all(i in [test_file, test_file2]
for i in col._collection))
示例7: test_filecoll_remove
def test_filecoll_remove(self, mock_api):
"""Test remove"""
col = FileCollection(mock_api)
test_file = mock.create_autospec(UserFile)
test_file.name = "test"
col._collection = [test_file, 1, "2", None, []]
with self.assertRaises(TypeError):
col.remove(None)
with self.assertRaises(TypeError):
col.remove(10)
col.remove(1)
col.remove(-1)
col.remove(slice(1))
self.assertEqual(col._collection, ["2", None])
test_file2 = mock.create_autospec(UserFile)
test_file2.name = "test2"
test_file3 = mock.create_autospec(UserFile)
test_file3.name = "test3"
col._collection = [test_file, test_file2, test_file3]
col.remove("test")
self.assertEqual(col._collection, [test_file2, test_file3])
col.remove(["test2", "test3"])
self.assertEqual(col._collection, [])
示例8: test_engine_logger
def test_engine_logger(self, mocked_application, mocked_adapter):
logger = ema_logging.get_logger()
mocked_logger = mock.Mock(spec=logger)
mocked_logger.handlers = []
mocked_logger.manager = mock.Mock(spec=logging.Manager)
mocked_logger.manager.disable = 0
ema_logging._logger = mocked_logger
mocked_application.instance.return_value = mocked_application
mocked_application.log = mocked_logger
# no handlers
ema.set_engine_logger()
logger = ema_logging._logger
# self.assertTrue(type(logger) == type(mocked_adapter))
mocked_logger.setLevel.assert_called_once_with(ema_logging.DEBUG)
mocked_adapter.assert_called_with(mocked_logger, ema.SUBTOPIC)
# with handlers
mocked_logger = mock.create_autospec(logging.Logger)
mock_engine_handler = mock.create_autospec(ipykernel.log.EnginePUBHandler)
mocked_logger.handlers = [mock_engine_handler]
mocked_application.instance.return_value = mocked_application
mocked_application.log = mocked_logger
ema.set_engine_logger()
logger = ema_logging._logger
# self.assertTrue(type(logger) == ema.EngingeLoggerAdapter)
mocked_logger.setLevel.assert_called_once_with(ema_logging.DEBUG)
mocked_adapter.assert_called_with(mocked_logger, ema.SUBTOPIC)
mock_engine_handler.setLevel.assert_called_once_with(ema_logging.DEBUG)
示例9: test_spec_inheritance_for_classes
def test_spec_inheritance_for_classes(self):
class Foo(object):
def a(self):
pass
class Bar(object):
def f(self):
pass
class_mock = create_autospec(Foo)
self.assertIsNot(class_mock, class_mock())
for this_mock in class_mock, class_mock():
this_mock.a()
this_mock.a.assert_called_with()
self.assertRaises(TypeError, this_mock.a, 'foo')
self.assertRaises(AttributeError, getattr, this_mock, 'b')
instance_mock = create_autospec(Foo())
instance_mock.a()
instance_mock.a.assert_called_with()
self.assertRaises(TypeError, instance_mock.a, 'foo')
self.assertRaises(AttributeError, getattr, instance_mock, 'b')
# The return value isn't isn't callable
self.assertRaises(TypeError, instance_mock)
instance_mock.Bar.f()
instance_mock.Bar.f.assert_called_with()
self.assertRaises(AttributeError, getattr, instance_mock.Bar, 'g')
instance_mock.Bar().f()
instance_mock.Bar().f.assert_called_with()
self.assertRaises(AttributeError, getattr, instance_mock.Bar(), 'g')
示例10: test_credentials_get_token
def test_credentials_get_token(self):
creds = mock.create_autospec(InteractiveCredentials)
session = mock.create_autospec(OAuth2Session)
creds._setup_session.return_value = session
session.fetch_token.return_value = {
'expires_at':'1',
'expires_in':'2',
'refresh_token':"test"}
creds.redirect = "//my_service.com"
creds.token_uri = "token_uri"
creds._check_state.return_value = True
creds.verify = True
InteractiveCredentials.set_token(creds, "response")
self.assertEqual(creds.token, session.fetch_token.return_value)
session.fetch_token.assert_called_with(
"token_uri",
authorization_response="https://my_service.com/response",
verify=True)
creds._check_state.side_effect = ValueError("failed")
with self.assertRaises(ValueError):
InteractiveCredentials.set_token(creds, "response")
creds._check_state.side_effect = None
session.fetch_token.side_effect = oauthlib.oauth2.OAuth2Error
with self.assertRaises(AuthenticationError):
InteractiveCredentials.set_token(creds, "response")
示例11: test_signature_callable
def test_signature_callable(self):
class Callable(object):
def __init__(self):
pass
def __call__(self, a):
pass
mock = create_autospec(Callable)
mock()
mock.assert_called_once_with()
self.assertRaises(TypeError, mock, 'a')
instance = mock()
self.assertRaises(TypeError, instance)
instance(a='a')
instance.assert_called_once_with(a='a')
instance('a')
instance.assert_called_with('a')
mock = create_autospec(Callable())
mock(a='a')
mock.assert_called_once_with(a='a')
self.assertRaises(TypeError, mock)
mock('a')
mock.assert_called_with('a')
示例12: test_spec_inheritance_for_classes
def test_spec_inheritance_for_classes(self):
class Foo(object):
__qualname__ = 'SpecSignatureTest.test_spec_inheritance_for_classes.<locals>.Foo'
def a(self):
pass
class Bar(object):
__qualname__ = 'SpecSignatureTest.test_spec_inheritance_for_classes.<locals>.Foo.Bar'
def f(self):
pass
class_mock = create_autospec(Foo)
self.assertIsNot(class_mock, class_mock())
for this_mock in (class_mock, class_mock()):
this_mock.a()
this_mock.a.assert_called_with()
self.assertRaises(TypeError, this_mock.a, 'foo')
self.assertRaises(AttributeError, getattr, this_mock, 'b')
instance_mock = create_autospec(Foo())
instance_mock.a()
instance_mock.a.assert_called_with()
self.assertRaises(TypeError, instance_mock.a, 'foo')
self.assertRaises(AttributeError, getattr, instance_mock, 'b')
self.assertRaises(TypeError, instance_mock)
instance_mock.Bar.f()
instance_mock.Bar.f.assert_called_with()
self.assertRaises(AttributeError, getattr, instance_mock.Bar, 'g')
instance_mock.Bar().f()
instance_mock.Bar().f.assert_called_with()
self.assertRaises(AttributeError, getattr, instance_mock.Bar(), 'g')
示例13: test_create_autopsec
def test_create_autopsec(self):
mock = create_autospec(X)
instance = mock()
self.assertRaises(TypeError, instance)
mock = create_autospec(X())
self.assertRaises(TypeError, mock)
示例14: test_submittedjob_get_thumbnail
def test_submittedjob_get_thumbnail(self, mock_prev):
"""Test get_thumbnail"""
resp = mock.create_autospec(Response)
resp.success = False
resp.result = RestCallException(None, "test", None)
mock_prev.return_value = resp
api = mock.create_autospec(BatchAppsApi)
job = SubmittedJob(api, "abc", None, None)
with self.assertRaises(FileDownloadException):
job.get_thumbnail()
self.assertFalse(mock_prev.called)
job = SubmittedJob(api,
"abc",
None,
None,
previewLink={'href':'http://'})
with self.assertRaises(RestCallException):
job.get_thumbnail()
self.assertTrue(mock_prev.called)
resp.success = True
thumb = job.get_thumbnail(filename="thumb.png")
mock_prev.assert_called_with(tempfile.gettempdir(), "thumb.png", True)
thumb = job.get_thumbnail(download_dir="dir",
filename="thumb.png",
overwrite=False)
mock_prev.assert_called_with("dir", "thumb.png", False)
self.assertEqual(thumb, "dir\\thumb.png")
示例15: mock_update
def mock_update(url, headers=None):
response = mock.create_autospec(Response)
response.request = mock.create_autospec(Request)
response.request.method = 'GET'
if url == ASYNC_URL:
response.request.url = url
response.status_code = POLLING_STATUS
response.content = ASYNC_BODY
response.randomFieldFromPollAsyncOpHeader = None
elif url == LOCATION_URL:
response.request.url = url
response.status_code = POLLING_STATUS
response.content = LOCATION_BODY
response.randomFieldFromPollLocationHeader = None
elif url == ERROR:
raise BadEndpointError("boom")
elif url == RESOURCE_URL:
response.request.url = url
response.status_code = POLLING_STATUS
response.content = RESOURCE_BODY
else:
raise Exception('URL does not match')
response.json = lambda: json.loads(response.content)
return response