本文整理汇总了Python中pyrsistent.field方法的典型用法代码示例。如果您正苦于以下问题:Python pyrsistent.field方法的具体用法?Python pyrsistent.field怎么用?Python pyrsistent.field使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类pyrsistent
的用法示例。
在下文中一共展示了pyrsistent.field方法的13个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_backend_selection
# 需要导入模块: import pyrsistent [as 别名]
# 或者: from pyrsistent import field [as 别名]
def test_backend_selection(self):
"""
``AgentService.get_api`` returns an object constructed by the
factory corresponding to the agent's ``backend_description``,
supplying ``api_args``.
"""
class API(PClass):
a = field()
b = field()
agent_service = self.agent_service.set(
"backend_description",
BackendDescription(
name=u"foo", needs_reactor=False, needs_cluster_id=False,
api_factory=API, deployer_type=DeployerType.p2p,
),
).set(
"api_args", {"a": "x", "b": "y"},
)
api = agent_service.get_api()
self.assertEqual(
API(a="x", b="y"),
api,
)
示例2: test_needs_cluster_id
# 需要导入模块: import pyrsistent [as 别名]
# 或者: from pyrsistent import field [as 别名]
def test_needs_cluster_id(self):
"""
If the flag for needing a cluster id as an extra argument is set in the
backend_description, the ``AgentService`` passes the cluster id
extracted from the node certificate when ``AgentService.get_api`` calls
the backend factory.
"""
class API(PClass):
cluster_id = field()
agent_service = self.agent_service.set(
"backend_description",
BackendDescription(
name=u"foo",
needs_reactor=False, needs_cluster_id=True,
api_factory=API, deployer_type=DeployerType.p2p,
),
)
api = agent_service.get_api()
self.assertEqual(
API(cluster_id=self.ca_set.node.cluster_uuid),
api,
)
示例3: new_record_type
# 需要导入模块: import pyrsistent [as 别名]
# 或者: from pyrsistent import field [as 别名]
def new_record_type(name, headings):
return type(
name,
(PClass,),
{heading: field(type=unicode, mandatory=True) for heading in headings}
)
示例4: filter_for_pclass
# 需要导入模块: import pyrsistent [as 别名]
# 或者: from pyrsistent import field [as 别名]
def filter_for_pclass(pclass_type, pclass_kwargs):
pclass_fields = pclass_type._pclass_fields
# Does the pclass support all the proposed kwargs
unexpected_keys = set(
pclass_kwargs.keys()
).difference(
set(pclass_fields.keys())
)
if unexpected_keys:
raise ValueError(
"Unexpected keyword arguments for '{}'. "
"Found: {}. "
"Expected: {}.".format(
pclass_type.__name__,
list(unexpected_keys),
pclass_fields.keys(),
)
)
fields_to_validate = {
key: field
for key, field
in pclass_fields.items()
if key in pclass_kwargs
}
filter_type = type(
"Filter_{}".format(pclass_type.__name__),
(PClass,),
fields_to_validate
)
return filter_type(**pclass_kwargs)
示例5: test_needs_reactor
# 需要导入模块: import pyrsistent [as 别名]
# 或者: from pyrsistent import field [as 别名]
def test_needs_reactor(self):
"""
If the flag for needing a reactor as an extra argument is set in the
backend_description, the ``AgentService`` passes its own reactor when
``AgentService.get_api`` calls the backend factory.
"""
reactor = MemoryCoreReactor()
class API(PClass):
reactor = field()
agent_service = self.agent_service.set(
"backend_description",
BackendDescription(
name=u"foo",
needs_reactor=True, needs_cluster_id=False,
api_factory=API, deployer_type=DeployerType.p2p,
),
).set(
"reactor", reactor,
)
api = agent_service.get_api()
self.assertEqual(
API(reactor=reactor),
api,
)
示例6: _volume_field
# 需要导入模块: import pyrsistent [as 别名]
# 或者: from pyrsistent import field [as 别名]
def _volume_field():
"""
Create and return a ``PClass`` ``field`` to hold a ``BlockDeviceVolume``.
"""
return field(
type=BlockDeviceVolume, mandatory=True,
# Disable the automatic PClass.create factory. Callers can just
# supply the right type, we don't need the magic coercion behavior
# supplied by default.
factory=lambda x: x
)
示例7: interface_field
# 需要导入模块: import pyrsistent [as 别名]
# 或者: from pyrsistent import field [as 别名]
def interface_field(interfaces, **field_kwargs):
"""
A ``PClass`` field which checks that the assigned value provides all the
``interfaces``.
:param tuple interfaces: The ``Interface`` that a value must provide.
"""
if not isinstance(interfaces, tuple):
raise TypeError(
"The ``interfaces`` argument must be a tuple. "
"Got: {!r}".format(interfaces)
)
original_invariant = field_kwargs.pop("invariant", None)
def invariant(value):
error_messages = []
if original_invariant is not None:
(original_invariant_result,
_original_invariant_message) = original_invariant(value)
if original_invariant_result:
error_messages.append(original_invariant_result)
missing_interfaces = []
for interface in interfaces:
if not interface.providedBy(value):
missing_interfaces.append(interface.getName())
if missing_interfaces:
error_messages.append(
"The value {!r} "
"did not provide these required interfaces: {}".format(
value,
", ".join(missing_interfaces)
)
)
if error_messages:
return (False, "\n".join(error_messages))
else:
return (True, "")
field_kwargs["invariant"] = invariant
return field(**field_kwargs)
示例8: _disk_resource_description
# 需要导入模块: import pyrsistent [as 别名]
# 或者: from pyrsistent import field [as 别名]
def _disk_resource_description(self):
"""
Returns the value to be used in the description field of the disk
resources for this cluster.
:returns unicode: The value for the description.
"""
return u"flocker-v1-cluster-id: " + unicode(self._cluster_id)
示例9: finish
# 需要导入模块: import pyrsistent [as 别名]
# 或者: from pyrsistent import field [as 别名]
def finish(self, exception=None):
"""
Log the finish message.
The action identification fields, and any additional given fields,
will be logged.
In general you shouldn't call this yourself, instead using a C{with}
block or L{Action.finish}.
@param exception: C{None}, in which case the fields added with
L{Action.addSuccessFields} are used. Or an L{Exception}, in
which case an C{"exception"} field is added with the given
L{Exception} type and C{"reason"} with its contents.
"""
if self._finished:
return
self._finished = True
serializer = None
if exception is None:
fields = self._successFields
fields[ACTION_STATUS_FIELD] = SUCCEEDED_STATUS
if self._serializers is not None:
serializer = self._serializers.success
else:
fields = _error_extraction.get_fields_for_exception(self._logger, exception)
fields[EXCEPTION_FIELD] = "%s.%s" % (
exception.__class__.__module__,
exception.__class__.__name__,
)
fields[REASON_FIELD] = safeunicode(exception)
fields[ACTION_STATUS_FIELD] = FAILED_STATUS
if self._serializers is not None:
serializer = self._serializers.failure
fields[TIMESTAMP_FIELD] = time.time()
fields.update(self._identification)
fields[TASK_LEVEL_FIELD] = self._nextTaskLevel().as_list()
self._logger.write(fields, serializer)
示例10: assertHasMessage
# 需要导入模块: import pyrsistent [as 别名]
# 或者: from pyrsistent import field [as 别名]
def assertHasMessage(testCase, logger, messageType, fields=None):
"""
Assert that the given logger has a message of the given type, and the first
message found of this type has the given fields.
This can be used as the assertion function passed to L{validateLogging} or
as part of a unit test.
@param testCase: L{unittest.TestCase} instance.
@param logger: L{eliot.MemoryLogger} whose messages will be checked.
@param messageType: L{eliot.MessageType} indicating which message we're
looking for.
@param fields: The first message of the given type found must have a
superset of the given C{dict} as its fields. If C{None} then fields are
not checked.
@return: The first found L{LoggedMessage} of the given type, if field
validation succeeded.
@raises AssertionError: No message was found, or the fields were not
superset of given fields.
"""
if fields is None:
fields = {}
messages = LoggedMessage.ofType(logger.messages, messageType)
testCase.assertTrue(messages, "No messages of type %s" % (messageType,))
loggedMessage = messages[0]
assertContainsFields(testCase, loggedMessage.message, fields)
return loggedMessage
示例11: addGlobalFields
# 需要导入模块: import pyrsistent [as 别名]
# 或者: from pyrsistent import field [as 别名]
def addGlobalFields(self, **fields):
"""
Add fields that will be included in all messages sent through this
destination.
@param fields: Keyword arguments mapping field names to values.
"""
self._globalFields.update(fields)
示例12: _validate_message
# 需要导入模块: import pyrsistent [as 别名]
# 或者: from pyrsistent import field [as 别名]
def _validate_message(self, dictionary, serializer):
"""Validate an individual message.
As a side-effect, the message is replaced with its serialized contents.
@param dictionary: A message C{dict} to be validated. Might be mutated
by the serializer!
@param serializer: C{None} or a serializer.
@raises TypeError: If a field name is not unicode, or the dictionary
fails to serialize to JSON.
@raises eliot.ValidationError: If serializer was given and validation
failed.
"""
if serializer is not None:
serializer.validate(dictionary)
for key in dictionary:
if not isinstance(key, str):
if isinstance(key, bytes):
key.decode("utf-8")
else:
raise TypeError(dictionary, "%r is not unicode" % (key,))
if serializer is not None:
serializer.serialize(dictionary)
try:
bytesjson.dumps(dictionary)
pyjson.dumps(dictionary)
except Exception as e:
raise TypeError("Message %s doesn't encode to JSON: %s" % (dictionary, e))
示例13: assertHasAction
# 需要导入模块: import pyrsistent [as 别名]
# 或者: from pyrsistent import field [as 别名]
def assertHasAction(
testCase, logger, actionType, succeeded, startFields=None, endFields=None
):
"""
Assert that the given logger has an action of the given type, and the first
action found of this type has the given fields and success status.
This can be used as the assertion function passed to L{validateLogging} or
as part of a unit test.
@param testCase: L{unittest.TestCase} instance.
@param logger: L{eliot.MemoryLogger} whose messages will be checked.
@param actionType: L{eliot.ActionType} or C{str} indicating which message
we're looking for.
@param succeeded: Expected success status of the action, a C{bool}.
@param startFields: The first action of the given type found must have a
superset of the given C{dict} as its start fields. If C{None} then
fields are not checked.
@param endFields: The first action of the given type found must have a
superset of the given C{dict} as its end fields. If C{None} then
fields are not checked.
@return: The first found L{LoggedAction} of the given type, if field
validation succeeded.
@raises AssertionError: No action was found, or the fields were not
superset of given fields.
"""
if startFields is None:
startFields = {}
if endFields is None:
endFields = {}
actions = LoggedAction.ofType(logger.messages, actionType)
testCase.assertTrue(actions, "No actions of type %s" % (actionType,))
action = actions[0]
testCase.assertEqual(action.succeeded, succeeded)
assertContainsFields(testCase, action.startMessage, startFields)
assertContainsFields(testCase, action.endMessage, endFields)
return action