本文整理汇总了Python中unittest.mock.PropertyMock方法的典型用法代码示例。如果您正苦于以下问题:Python mock.PropertyMock方法的具体用法?Python mock.PropertyMock怎么用?Python mock.PropertyMock使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类unittest.mock
的用法示例。
在下文中一共展示了mock.PropertyMock方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_list
# 需要导入模块: from unittest import mock [as 别名]
# 或者: from unittest.mock import PropertyMock [as 别名]
def test_list(self, os_mock, path_mock):
data = self.create_data(path_mock, self.contributor, self.process)
stat_mock = MagicMock()
type(stat_mock).st_size = PropertyMock(side_effect=[34, 42000, 42])
path_mock.return_value = MagicMock(
is_file=lambda: True,
stat=lambda: stat_mock,
__fspath__=lambda: "my_mocked_file_name",
)
data.output = {
"file_list": [
{"file": "test_01.tmp",},
{"file": "test_02.tmp", "refs": ["ref_file1.tmp"]},
]
}
hydrate_size(data)
self.assertEqual(data.output["file_list"][0]["size"], 34)
self.assertEqual(data.output["file_list"][0]["total_size"], 34)
self.assertEqual(data.output["file_list"][1]["size"], 42000)
self.assertEqual(data.output["file_list"][1]["total_size"], 42042)
self.assertEqual(data.size, 34 + 42042)
示例2: forced_piece_size
# 需要导入模块: from unittest import mock [as 别名]
# 或者: from unittest.mock import PropertyMock [as 别名]
def forced_piece_size(pytestconfig):
@contextlib.contextmanager
def _forced_piece_size(piece_size):
orig_piece_size_min = torf.Torrent.piece_size_min
torf.Torrent.piece_size_min = piece_size
with mock.patch('torf.Torrent.piece_size', new_callable=mock.PropertyMock) as mock_piece_size:
def piece_size_setter(prop, torrent, value):
torrent.metainfo['info']['piece length'] = piece_size
mock_piece_size.return_value = piece_size
mock_piece_size.__set__ = piece_size_setter
yield piece_size
torf.Torrent.piece_size_min = orig_piece_size_min
return _forced_piece_size
# https://stackoverflow.com/a/45690594
示例3: test_sinkProcessorProcess
# 需要导入模块: from unittest import mock [as 别名]
# 或者: from unittest.mock import PropertyMock [as 别名]
def test_sinkProcessorProcess():
with mock.patch('winton_kafka_streams.processor.ProcessorContext.timestamp', new_callable=mock.PropertyMock) as mock_timestamp:
mock_timestamp.return_value = _expected_timestamp
mock_task = mock.Mock()
mock_task.application_id = 'test_id'
mock_task_id = TaskId('test_group', 0)
processor_context = wks_processor.ProcessorContext(mock_task_id, mock_task, None, None, {})
processor_context.record_collector = mock.MagicMock()
sink = wks_processor.SinkProcessor('topic1')
sink.initialise('test-sink', processor_context)
assert sink.name == 'test-sink'
test_key, test_value = 'test-key', 'test-value'
sink.process(test_key, test_value)
assert processor_context.record_collector.called_with(test_key, test_value, _expected_timestamp)
示例4: test_get_cost_export_for_key
# 需要导入模块: from unittest import mock [as 别名]
# 或者: from unittest.mock import PropertyMock [as 别名]
def test_get_cost_export_for_key(self):
"""Test that a cost export is retrieved by a key."""
today = self.current_date_time
yesterday = today - relativedelta(days=1)
test_matrix = [
{"key": "{}_{}_day_{}".format(self.container_name, "blob", today.day), "expected_date": today.date()},
{
"key": "{}_{}_day_{}".format(self.container_name, "blob", yesterday.day),
"expected_date": yesterday.date(),
},
]
for test in test_matrix:
key = test.get("key")
expected_modified_date = test.get("expected_date")
mock_blob = Mock(last_modified=Mock(date=Mock(return_value=expected_modified_date)))
name_attr = PropertyMock(return_value=key)
type(mock_blob).name = name_attr # kludge to set name attribute on Mock
svc = self.get_mock_client(blob_list=[mock_blob])
cost_export = svc.get_cost_export_for_key(key, self.container_name)
self.assertIsNotNone(cost_export)
self.assertEquals(cost_export.name, key)
self.assertEquals(cost_export.last_modified.date(), expected_modified_date)
示例5: test_describe_cost_management_exports_wrong_account
# 需要导入模块: from unittest import mock [as 别名]
# 或者: from unittest.mock import PropertyMock [as 别名]
def test_describe_cost_management_exports_wrong_account(self):
"""Test that cost management exports are not returned from incorrect account."""
resource_id = (
f"/subscriptions/{FAKE.uuid4()}/resourceGroups/"
f"{self.resource_group_name}/providers/Microsoft.Storage/"
f"storageAccounts/{self.storage_account_name}"
)
mock_export = Mock(
delivery_info=Mock(
destination=Mock(
container=self.container_name, root_folder_path=self.export_directory, resource_id=resource_id
)
)
)
name_attr = PropertyMock(return_value=f"{self.container_name}_blob")
type(mock_export).name = name_attr # kludge to set name attribute on Mock
svc = self.get_mock_client(cost_exports=[mock_export])
exports = svc.describe_cost_management_exports()
self.assertEquals(exports, [])
示例6: test_download_cost_report_exception
# 需要导入模块: from unittest import mock [as 别名]
# 或者: from unittest.mock import PropertyMock [as 别名]
def test_download_cost_report_exception(self, mock_factory):
"""Test that function handles a raised exception."""
key = FAKE.word()
mock_blob = Mock(last_modified=Mock(date=Mock(return_value=datetime.now())))
name_attr = PropertyMock(return_value=key)
type(mock_blob).name = name_attr # kludge to set name attribute on Mock
mock_factory.return_value = Mock(
spec=AzureClientFactory,
cloud_storage_account=Mock(
return_value=Mock(
spec=BlobServiceClient,
get_blob_client=Mock(side_effect=AdalError("test error")),
get_container_client=Mock(
return_value=Mock(spec=ContainerClient, list_blobs=Mock(return_value=[mock_blob]))
),
)
),
)
with self.assertRaises(AzureServiceError):
service = AzureService(
self.tenant_id, self.client_id, self.client_secret, self.resource_group_name, self.storage_account_name
)
service.download_cost_export(key=key, container_name=FAKE.word())
示例7: test_check_for_lb_vip_deallocate
# 需要导入模块: from unittest import mock [as 别名]
# 或者: from unittest.mock import PropertyMock [as 别名]
def test_check_for_lb_vip_deallocate(self, mock_get_net_drvr):
mock_repo = mock.MagicMock()
mock_lb = mock.MagicMock()
mock_vip = mock.MagicMock()
mock_octavia_owned = mock.PropertyMock(side_effect=[True, False])
type(mock_vip).octavia_owned = mock_octavia_owned
mock_lb.vip = mock_vip
mock_repo.get.return_value = mock_lb
mock_net_drvr = mock.MagicMock()
mock_get_net_drvr.return_value = mock_net_drvr
self.driver_updater._check_for_lb_vip_deallocate(mock_repo, 'bogus_id')
mock_net_drvr.deallocate_vip.assert_called_once_with(mock_vip)
mock_net_drvr.reset_mock()
self.driver_updater._check_for_lb_vip_deallocate(mock_repo, 'bogus_id')
mock_net_drvr.deallocate_vip.assert_not_called()
示例8: test_get_cert_no_registration_raise_on_secret_access_failure
# 需要导入模块: from unittest import mock [as 别名]
# 或者: from unittest.mock import PropertyMock [as 别名]
def test_get_cert_no_registration_raise_on_secret_access_failure(self):
self.bc.containers.get.return_value = self.container
with mock.patch('barbicanclient.v1.secrets.Secret.payload',
new_callable=mock.PropertyMock) as mock_payload:
mock_payload.side_effect = ValueError
# Get the container data
self.assertRaises(
ValueError, self.cert_manager.get_cert,
context=self.context,
cert_ref=self.container_ref, check_only=True
)
# 'get' should be called once with the container_ref
self.bc.containers.get.assert_called_once_with(
container_ref=self.container_ref
)
示例9: test_find_payments
# 需要导入模块: from unittest import mock [as 别名]
# 或者: from unittest.mock import PropertyMock [as 别名]
def test_find_payments(self):
cls = LowestBalanceFirstMethod(Decimal('100.00'))
s1 = Mock(spec_set=CCStatement)
type(s1).minimum_payment = PropertyMock(return_value=Decimal('2.00'))
type(s1).principal = PropertyMock(return_value=Decimal('10.00'))
s2 = Mock(spec_set=CCStatement)
type(s2).minimum_payment = PropertyMock(return_value=Decimal('5.00'))
type(s2).principal = PropertyMock(return_value=Decimal('25.00'))
s3 = Mock(spec_set=CCStatement)
type(s3).minimum_payment = PropertyMock(return_value=Decimal('2.00'))
type(s3).principal = PropertyMock(return_value=Decimal('1234.56'))
s4 = Mock(spec_set=CCStatement)
type(s4).minimum_payment = PropertyMock(return_value=Decimal('7.00'))
type(s4).principal = PropertyMock(return_value=Decimal('3.00'))
assert cls.find_payments([s1, s2, s3, s4]) == [
Decimal('2.00'),
Decimal('5.00'),
Decimal('2.00'),
Decimal('91.00')
]
示例10: test_find_payments_total_too_low
# 需要导入模块: from unittest import mock [as 别名]
# 或者: from unittest.mock import PropertyMock [as 别名]
def test_find_payments_total_too_low(self):
cls = LowestBalanceFirstMethod(Decimal('3.00'))
s1 = Mock(spec_set=CCStatement)
type(s1).minimum_payment = PropertyMock(return_value=Decimal('2.00'))
type(s1).principal = PropertyMock(return_value=Decimal('10.00'))
s2 = Mock(spec_set=CCStatement)
type(s2).minimum_payment = PropertyMock(return_value=Decimal('5.00'))
type(s2).principal = PropertyMock(return_value=Decimal('25.00'))
s3 = Mock(spec_set=CCStatement)
type(s3).minimum_payment = PropertyMock(return_value=Decimal('2.00'))
type(s3).principal = PropertyMock(return_value=Decimal('1234.56'))
s4 = Mock(spec_set=CCStatement)
type(s4).minimum_payment = PropertyMock(return_value=Decimal('7.00'))
type(s4).principal = PropertyMock(return_value=Decimal('3.00'))
with pytest.raises(TypeError):
cls.find_payments([s1, s2, s3, s4])
示例11: test_next_with_transactions
# 需要导入模块: from unittest import mock [as 别名]
# 或者: from unittest.mock import PropertyMock [as 别名]
def test_next_with_transactions(self):
b = Mock(spec_set=_BillingPeriod)
b_next = Mock(spec_set=_BillingPeriod)
type(b).next_period = PropertyMock(return_value=b_next)
i = Mock(spec_set=_InterestCalculation)
p = Mock(spec_set=_MinPaymentFormula)
cls = CCStatement(
i, Decimal('1.23'), p, b,
end_balance=Decimal('1.50'), interest_amt=Decimal('0.27')
)
mock_stmt = Mock(spec_set=CCStatement)
with patch('biweeklybudget.interest.CCStatement', autospec=True) as m:
m.return_value = mock_stmt
res = cls.next_with_transactions({'foo': 'bar'})
assert res == mock_stmt
assert m.mock_calls == [
call(
i, Decimal('1.50'), p, b_next, transactions={'foo': 'bar'}
)
]
示例12: test_pay
# 需要导入模块: from unittest import mock [as 别名]
# 或者: from unittest.mock import PropertyMock [as 别名]
def test_pay(self):
b = Mock(spec_set=_BillingPeriod)
b_next = Mock(spec_set=_BillingPeriod)
type(b_next).payment_date = PropertyMock(return_value=date(2017, 1, 15))
type(b).next_period = PropertyMock(return_value=b_next)
i = Mock(spec_set=_InterestCalculation)
p = Mock(spec_set=_MinPaymentFormula)
cls = CCStatement(
i, Decimal('1.23'), p, b,
end_balance=Decimal('1.50'), interest_amt=Decimal('0.27')
)
mock_stmt = Mock(spec_set=CCStatement)
with patch(
'biweeklybudget.interest.CCStatement.next_with_transactions',
autospec=True
) as m:
m.return_value = mock_stmt
res = cls.pay(Decimal('98.76'))
assert res == mock_stmt
assert m.mock_calls == [
call(cls, {date(2017, 1, 15): Decimal('98.76')})
]
示例13: _test_migrate_vm
# 需要导入模块: from unittest import mock [as 别名]
# 或者: from unittest.mock import PropertyMock [as 别名]
def _test_migrate_vm(self, mock_get_by_uuid,
mock_wait_for_instance_pending_task,
instance_uuid=None, vm_state='active'):
self._hostops._vmutils.get_instance_uuid.return_value = instance_uuid
instance = mock_get_by_uuid.return_value
type(instance).vm_state = mock.PropertyMock(
side_effect=[vm_state])
self._hostops._migrate_vm(ctxt=mock.sentinel.CONTEXT,
vm_name=mock.sentinel.VM_NAME,
host=mock.sentinel.HOST)
if not instance_uuid:
self.assertFalse(self._hostops._api.live_migrate.called)
return
if vm_state == 'active':
self._hostops._api.live_migrate.assert_called_once_with(
mock.sentinel.CONTEXT, instance, block_migration=False,
disk_over_commit=False, host_name=None)
else:
self._hostops._api.resize.assert_called_once_with(
mock.sentinel.CONTEXT, instance, flavor_id=None,
clean_shutdown=True)
mock_wait_for_instance_pending_task.assert_called_once_with(
mock.sentinel.CONTEXT, instance_uuid)
示例14: test_discoveredPrinters
# 需要导入模块: from unittest import mock [as 别名]
# 或者: from unittest.mock import PropertyMock [as 别名]
def test_discoveredPrinters(discovered_printer_model):
mocked_device = MagicMock()
cluster_size = PropertyMock(return_value = 1)
type(mocked_device).clusterSize = cluster_size
mocked_callback = MagicMock()
discovered_printer_model.addDiscoveredPrinter("ip", "key", "name", mocked_callback, "machine_type", mocked_device)
device = discovered_printer_model.discoveredPrinters[0]
discovered_printer_model.createMachineFromDiscoveredPrinter(device)
mocked_callback.assert_called_with("key")
assert len(discovered_printer_model.discoveredPrinters) == 1
discovered_printer_model.discoveredPrintersChanged = MagicMock()
# Test if removing it works
discovered_printer_model.removeDiscoveredPrinter("ip")
assert len(discovered_printer_model.discoveredPrinters) == 0
assert discovered_printer_model.discoveredPrintersChanged.emit.call_count == 1
# Removing it again shouldn't cause another signal emit
discovered_printer_model.removeDiscoveredPrinter("ip")
assert discovered_printer_model.discoveredPrintersChanged.emit.call_count == 1
示例15: test_get_logs_for_handler_without_read_method
# 需要导入模块: from unittest import mock [as 别名]
# 或者: from unittest.mock import PropertyMock [as 别名]
def test_get_logs_for_handler_without_read_method(self, mock_log_reader):
type(mock_log_reader.return_value).supports_read = PropertyMock(return_value=False)
url_template = "get_logs_with_metadata?dag_id={}&" \
"task_id={}&execution_date={}&" \
"try_number={}&metadata={}&format=json"
try_number = 1
url = url_template.format(self.DAG_ID,
self.TASK_ID,
quote_plus(self.DEFAULT_DATE.isoformat()),
try_number,
json.dumps({}))
response = self.client.get(url)
self.assertEqual(200, response.status_code)
self.assertIn('message', response.json)
self.assertIn('metadata', response.json)
self.assertIn(
'Task log handler does not support read logs.',
response.json['message'])