def test_unextractable_schema(extractor):
""" test an attrs class which we can't extract schema from. """
@attr.s
class NoBueno(object):
foo = attr.ib()
with pytest.raises(UnextractableSchema):
extractor.extract(NoBueno)
python类ib()的实例源码
def Field(*args, default=attr.NOTHING, **kwargs):
if callable(default):
default = attr.Factory(default)
return attr.ib(*args, default=default, **kwargs)
def ForeignKey(cls, *args, **kwargs):
metadata = {
'related': {
'target': cls,
'type': 'ForeignKey',
}
}
return attr.ib(*args, metadata=metadata, **kwargs)
def __init_subclass__(cls, soft, reply_code, **kwargs):
super().__init_subclass__(**kwargs)
cls.soft = attr.ib(default=soft)
cls.reply_code = attr.ib(default=reply_code)
cls.BY_ID[reply_code] = cls
def __init_subclass__(cls, class_id, **kwargs):
super().__init_subclass__(**kwargs)
cls.class_id = attr.ib(default=class_id, init=False)
cls.struct = make_struct(
cls, exclude_attrs={'class_id'}, struct=PropertiesStruct
)
cls.BY_ID[class_id] = cls
def attr_init(factory_or_default=attr.NOTHING, **attr_kws):
if callable(factory_or_default): factory_or_default = attr.Factory(factory_or_default)
return attr.ib(default=factory_or_default, **attr_kws)
def log(name):
"""Returns a logger attr.ib
:param name: name to pass to logging.getLogger()
:rtype: attr.ib
"""
return attr.ib(default=logging.getLogger(name),
repr=False,
hash=False,
cmp=False)
def attrib(*args, **kwargs):
"""
Extend the attr.ib to include our metadata elements.
ATM we support additional keyword args which are then stored within
`metadata`:
- `doc` for documentation to describe the attribute (e.g. in --help)
"""
doc = kwargs.pop('doc', None)
metadata = kwargs.get('metadata', {})
if doc:
metadata['doc'] = doc
if metadata:
kwargs['metadata'] = metadata
return attr.ib(*args, **kwargs)
def __init__(self, path, session):
"""Representation for a repository
Parameters
----------
path: str
Path to the top of the repository
"""
self.path = path.rstrip(os.sep) # TODO: might be done as some rg to attr.ib
self._session = session
self._all_files = None
self._branch = None
def TypedList(type_):
"""A helper to generate an attribute which would be with list factory
but also defining a type in its metadata
"""
return attr.ib(default=Factory(list), metadata={'type': type_})
#
# Models
#
def __setattr__(self, name, value):
"""Mimic attr.s(frozen=True) behaviour but allow for attributes
to be initialized after class instantiation.
Useful when you would like a class to be immutable after a
certain action, such as a save to a database.
Any attributes created with ``attr.ib(init=False)`` or are
initially set to ``None`` in ``__init__()`` are allowed to have
their values be set once after initialization. Any other
attributes with initial values set are immediately frozen upon
initialization.
**Note**: Obviously, this doesn't stop anyone from setting the
uninitialized attributes before you've set it yourself.
Hopefully, you've got responsibile users.
Raises:
:class:`attr.exceptions.FronzenInstanceError`: if a frozen
attribute is set
"""
current_value = getattr(self, name, None)
if current_value is None or isinstance(current_value, attr.Attribute):
super().__setattr__(name, value)
else:
raise attr.exceptions.FrozenInstanceError()
def test_is_callable_cls():
from coalaip.model_validators import is_callable
@attr.s
class TestCallable:
fn = attr.ib(validator=is_callable)
return TestCallable
def test_use_model_attr_cls():
from coalaip.model_validators import use_model_attr
@attr.s
class TestUseModelAttr:
validator = attr.ib()
test = attr.ib(validator=use_model_attr('validator'))
return TestUseModelAttr
def create_test_does_not_contain_cls():
from coalaip.model_validators import does_not_contain
def create_cls(*avoid_keys):
@does_not_contain(*avoid_keys)
def validator(*args, **kwargs):
pass
@attr.s
class TestDoesNotContain:
data = attr.ib(validator=validator)
return TestDoesNotContain
return create_cls
def create_reactor():
"""
Twisted 17.1.0 and higher requires a reactor which implements
``IReactorPluggableNameResolver``.
"""
@implementer(IHostResolution)
@attr.s
class Resolution(object):
name = attr.ib()
class _FakeResolver(object):
def resolveHostName(self, resolutionReceiver, hostName, *args, **kwargs):
portNumber = kwargs.pop('portNumber')
r = Resolution(name=hostName)
resolutionReceiver.resolutionBegan(r)
if hostName in HOST_MAP:
resolutionReceiver.addressResolved(
IPv4Address('TCP', HOST_MAP[hostName], portNumber))
resolutionReceiver.resolutionComplete()
return r
@implementer(IReactorPluggableNameResolver)
class _ResolvingMemoryClockReactor(MemoryReactorClock):
nameResolver = _FakeResolver()
return _ResolvingMemoryClockReactor()
test_hgvs_variantmapper_cp_altseqbuilder.py 文件源码
项目:hgvs
作者: biocommons
项目源码
文件源码
阅读 14
收藏 0
点赞 0
评论 0
def _run_comparison(self, hgvsc, expected_sequence):
# test replicates the internal class of p_to_c
@attr.s(slots=True)
class RefTranscriptData(object):
transcript_sequence = attr.ib()
aa_sequence = attr.ib()
cds_start = attr.ib()
cds_stop = attr.ib()
protein_accession = attr.ib()
@classmethod
def setup_transcript_data(cls, ac, ac_p, db, ref="GRCh37.p10"):
"""helper for generating RefTranscriptData from for c_to_p"""
tx_info = db.get_tx_info(ac)
tx_seq = db.get_tx_seq(ac)
if tx_info is None or tx_seq is None:
raise hgvs.exceptions.HGVSError("Missing transcript data for accession: {}".format(ac))
# use 1-based hgvs coords
cds_start = tx_info["cds_start_i"] + 1
cds_stop = tx_info["cds_end_i"]
# padding list so biopython won't complain during the conversion
tx_seq_to_translate = tx_seq[cds_start - 1:cds_stop]
if len(tx_seq_to_translate) % 3 != 0:
"".join(list(tx_seq_to_translate).extend(["N"] * ((3 - len(tx_seq_to_translate) % 3) % 3)))
tx_seq_cds = Seq(tx_seq_to_translate)
protein_seq = str(tx_seq_cds.translate())
transcript_data = RefTranscriptData(tx_seq, protein_seq, cds_start, cds_stop, ac_p)
return transcript_data
ac_p = "DUMMY"
var = self._parser.parse_hgvs_variant(hgvsc)
transcript_data = RefTranscriptData.setup_transcript_data(var.ac, ac_p, self._datasource)
builder = altseqbuilder.AltSeqBuilder(var, transcript_data)
insert_result = builder.build_altseq()
actual_sequence = insert_result[0].transcript_sequence
msg = "expected: {}\nactual : {}".format(expected_sequence, actual_sequence)
self.assertEqual(expected_sequence, actual_sequence, msg)
def test_comparison(self):
"""
The binary comparison operations work on ``KubernetesError`` as expected.
"""
model = v1_5_model
a1 = KubernetesError(200, model.v1.Status(status=u"A"))
a2 = KubernetesError(200, model.v1.Status(status=u"A"))
b = KubernetesError(201, model.v1.Status(status=u"A"))
c = KubernetesError(200, model.v1.Status(status=u"B"))
# a1 == a2
self.expectThat(a1, Equals(a2))
# not (a1 != a2)
self.expectThat(a1, Not(NotEquals(a2)))
# not (a1 > a2)
self.expectThat(a1, Not(GreaterThan(a2)))
# not (a1 < a2)
self.expectThat(a1, Not(LessThan(a2)))
# not (a1 == b)
self.expectThat(a1, Not(Equals(b)))
# a1 != b
self.expectThat(a1, NotEquals(b))
# a1 < b
self.expectThat(a1, LessThan(b))
# not (a1 > b)
self.expectThat(a1, Not(GreaterThan(b)))
# not (a1 == c)
self.expectThat(a1, Not(Equals(b)))
# a1 != c
self.expectThat(a1, NotEquals(b))
# a1 < c
self.expectThat(a1, LessThan(c))
# not (a1 > c)
self.expectThat(a1, Not(GreaterThan(c)))
@attr.s
class Comparator(object):
result = attr.ib()
def __cmp__(self, other):
return self.result
largest = Comparator(1)
equalest = Comparator(0)
smallest = Comparator(-1)
# a1 < largest
self.expectThat(a1, LessThan(largest))
# a1 == equalest
self.expectThat(a1, Equals(equalest))
# a1 > smallest
self.expectThat(a1, GreaterThan(smallest))