本文整理汇总了Python中attr.Factory方法的典型用法代码示例。如果您正苦于以下问题:Python attr.Factory方法的具体用法?Python attr.Factory怎么用?Python attr.Factory使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类attr
的用法示例。
在下文中一共展示了attr.Factory方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_startedListeningLogMessage
# 需要导入模块: import attr [as 别名]
# 或者: from attr import Factory [as 别名]
def test_startedListeningLogMessage(self):
"""
When a port starts, a message including a description of the associated
factory is logged.
"""
loggedMessages = self.observe()
reactor = self.buildReactor()
@implementer(ILoggingContext)
class SomeFactory(ServerFactory):
def logPrefix(self):
return "Crazy Factory"
factory = SomeFactory()
p = self.getListeningPort(reactor, factory)
expectedMessage = self.getExpectedStartListeningLogMessage(
p, "Crazy Factory")
self.assertEqual((expectedMessage,), loggedMessages[0]['message'])
示例2: test_adds_keyword_only_arguments
# 需要导入模块: import attr [as 别名]
# 或者: from attr import Factory [as 别名]
def test_adds_keyword_only_arguments(self):
"""
Attributes can be added as keyword-only.
"""
@attr.s
class C:
a = attr.ib()
b = attr.ib(default=2, kw_only=True)
c = attr.ib(kw_only=True)
d = attr.ib(default=attr.Factory(lambda: 4), kw_only=True)
c = C(1, c=3)
assert c.a == 1
assert c.b == 2
assert c.c == 3
assert c.d == 4
示例3: test_factory_takes_self
# 需要导入模块: import attr [as 别名]
# 或者: from attr import Factory [as 别名]
def test_factory_takes_self(self):
"""
If takes_self on factories is True, self is passed.
"""
C = make_class(
"C",
{
"x": attr.ib(
default=Factory((lambda self: self), takes_self=True)
)
},
)
i = C()
assert i is i.x
示例4: test_annotations_strings
# 需要导入模块: import attr [as 别名]
# 或者: from attr import Factory [as 别名]
def test_annotations_strings(self, slots, classvar):
"""
String annotations are passed into __init__ as is.
"""
@attr.s(auto_attribs=True, slots=slots)
class C:
cls_var: classvar + "[int]" = 23
a: "int"
x: "typing.List[int]" = attr.Factory(list)
y: "int" = 2
z: "int" = attr.ib(default=3)
foo: "typing.Any" = None
assert C.__init__.__annotations__ == {
"a": "int",
"x": "typing.List[int]",
"y": "int",
"z": "int",
"foo": "typing.Any",
"return": None,
}
示例5: _get
# 需要导入模块: import attr [as 别名]
# 或者: from attr import Factory [as 别名]
def _get(self, environ, metadata, prefix, name):
# Delayed loading.
if self._cfg is None and self._env_name is not None:
log.debug("looking for env var '%s'." % (self._env_name,))
self._cfg = _load_ini(
environ.get(self._env_name, self._env_default)
)
ce = metadata[CNF_KEY]
ic = metadata[CNF_INI_SECRET_KEY]
section = ic.section
if ce.name is not None:
var = ce.name
else:
var = "_".join((prefix + (name,)))
try:
log.debug("looking for '%s' in section '%s'." % (var, section))
return _SecretStr(self._cfg.get(section, var))
except NoOptionError:
if isinstance(ce.default, attr.Factory):
return attr.NOTHING
elif ce.default is not RAISE:
return ce.default
raise MissingSecretError(var)
示例6: test_default_factory
# 需要导入模块: import attr [as 别名]
# 或者: from attr import Factory [as 别名]
def test_default_factory(self, ini):
"""
Defaults are used iff the key is missing.
"""
def getpass():
return "thesecret"
@environ.config
class Cfg(object):
password = ini.secret(default=attr.Factory(getpass))
secret = ini.secret(default=attr.Factory(getpass))
cfg = environ.to_config(Cfg, {})
assert Cfg("foobar", "thesecret") == cfg
示例7: test_structure_simple_from_dict_default
# 需要导入模块: import attr [as 别名]
# 或者: from attr import Factory [as 别名]
def test_structure_simple_from_dict_default(converter, cl_and_vals, data):
"""Test structuring non-nested attrs classes with default value."""
cl, vals = cl_and_vals
obj = cl(*vals)
attrs_with_defaults = [a for a in fields(cl) if a.default is not NOTHING]
to_remove = data.draw(
lists(elements=sampled_from(attrs_with_defaults), unique=True)
)
for a in to_remove:
if isinstance(a.default, Factory):
setattr(obj, a.name, a.default.factory())
else:
setattr(obj, a.name, a.default)
dumped = asdict(obj)
for a in to_remove:
del dumped[a.name]
assert obj == converter.structure(dumped, cl)
示例8: _connectDone
# 需要导入模块: import attr [as 别名]
# 或者: from attr import Factory [as 别名]
def _connectDone(self):
"""
This is a hook for when a connection attempt has succeeded.
Here, we build the protocol from the
L{twisted.internet.protocol.ClientFactory} that was passed in, compute
a log string, begin reading so as to send traffic to the newly built
protocol, and finally hook up the protocol itself.
This hook is overridden by L{ssl.Client} to initiate the TLS protocol.
"""
self.protocol = self.connector.buildProtocol(self.getPeer())
self.connected = 1
logPrefix = self._getLogPrefix(self.protocol)
self.logstr = "%s,client" % logPrefix
if self.protocol is None:
# Factory.buildProtocol is allowed to return None. In that case,
# make up a protocol to satisfy the rest of the implementation;
# connectionLost is going to be called on something, for example.
# This is easier than adding special case support for a None
# protocol throughout the rest of the transport implementation.
self.protocol = Protocol()
# But dispose of the connection quickly.
self.loseConnection()
else:
self.startReading()
self.protocol.makeConnection(self)
示例9: test_userFail
# 需要导入模块: import attr [as 别名]
# 或者: from attr import Factory [as 别名]
def test_userFail(self):
"""
Calling L{IConnector.stopConnecting} in C{Factory.startedConnecting}
results in C{Factory.clientConnectionFailed} being called with
L{error.UserError} as the reason.
"""
serverFactory = MyServerFactory()
reactor = self.buildReactor()
tcpPort = reactor.listenTCP(0, serverFactory, interface=self.interface)
portNumber = tcpPort.getHost().port
fatalErrors = []
def startedConnecting(connector):
try:
connector.stopConnecting()
except Exception:
fatalErrors.append(Failure())
reactor.stop()
clientFactory = ClientStartStopFactory()
clientFactory.startedConnecting = startedConnecting
clientFactory.whenStopped.addBoth(lambda _: reactor.stop())
reactor.callWhenRunning(lambda: reactor.connectTCP(self.interface,
portNumber,
clientFactory))
self.runReactor(reactor)
if fatalErrors:
self.fail(fatalErrors[0].getTraceback())
clientFactory.reason.trap(UserError)
self.assertEqual(clientFactory.failed, 1)
示例10: test_reconnect
# 需要导入模块: import attr [as 别名]
# 或者: from attr import Factory [as 别名]
def test_reconnect(self):
"""
Calling L{IConnector.connect} in C{Factory.clientConnectionLost} causes
a new connection attempt to be made.
"""
serverFactory = ClosingFactory()
reactor = self.buildReactor()
tcpPort = reactor.listenTCP(0, serverFactory, interface=self.interface)
serverFactory.port = tcpPort
portNumber = tcpPort.getHost().port
clientFactory = MyClientFactory()
def clientConnectionLost(connector, reason):
connector.connect()
clientFactory.clientConnectionLost = clientConnectionLost
reactor.connectTCP(self.interface, portNumber, clientFactory)
protocolMadeAndClosed = []
def reconnectFailed(ignored):
p = clientFactory.protocol
protocolMadeAndClosed.append((p.made, p.closed))
reactor.stop()
clientFactory.failDeferred.addCallback(reconnectFailed)
self.runReactor(reactor)
clientFactory.reason.trap(ConnectionRefusedError)
self.assertEqual(protocolMadeAndClosed, [(1, 1)])
示例11: make
# 需要导入模块: import attr [as 别名]
# 或者: from attr import Factory [as 别名]
def make(cls, **kwargs):
"""Create a container.
Reports extra keys as well as missing ones.
Thanks to habnabit for the idea!
"""
cls_attrs = {f.name: f for f in attr.fields(cls)}
unknown = {k: v for k, v in kwargs.items() if k not in cls_attrs}
if len(unknown) > 0:
_LOGGER.debug(
"Got unknowns for %s: %s - please create an issue!", cls.__name__, unknown
)
missing = [k for k in cls_attrs if k not in kwargs]
data = {k: v for k, v in kwargs.items() if k in cls_attrs}
# initialize missing values to avoid passing default=None
# for the attrs attribute definitions
for m in missing:
default = cls_attrs[m].default
if isinstance(default, attr.Factory):
if not default.takes_self:
data[m] = default.factory()
else:
raise NotImplementedError
else:
_LOGGER.debug("Missing key %s with no default for %s", m, cls.__name__)
data[m] = None
# initialize and store raw data for debug purposes
inst = cls(**data)
setattr(inst, "raw", kwargs)
return inst
示例12: Field
# 需要导入模块: import attr [as 别名]
# 或者: from attr import Factory [as 别名]
def Field(*args, default=attr.NOTHING, **kwargs):
if callable(default):
default = attr.Factory(default)
return attr.ib(*args, default=default, **kwargs)
示例13: test_default_decorator_sets
# 需要导入模块: import attr [as 别名]
# 或者: from attr import Factory [as 别名]
def test_default_decorator_sets(self):
"""
Decorator wraps the method in a Factory with pass_self=True and sets
the default.
"""
a = attr.ib()
@a.default
def f(self):
pass
assert Factory(f, True) == a._default
示例14: test_factory_sugar
# 需要导入模块: import attr [as 别名]
# 或者: from attr import Factory [as 别名]
def test_factory_sugar(self):
"""
Passing factory=f is syntactic sugar for passing default=Factory(f).
"""
@attr.s
class C(object):
x = attr.ib(factory=list)
assert Factory(list) == attr.fields(C).x.default
示例15: test_sugar_factory_mutex
# 需要导入模块: import attr [as 别名]
# 或者: from attr import Factory [as 别名]
def test_sugar_factory_mutex(self):
"""
Passing both default and factory raises ValueError.
"""
with pytest.raises(ValueError, match="mutually exclusive"):
@attr.s
class C(object):
x = attr.ib(factory=list, default=Factory(list))