How to use append_description_of method in PyHamcrest

Best Python code snippet using PyHamcrest_python

matchers.py

Source:matchers.py Github

copy

Full Screen

...90 return False91 else:92 return True93 def describe_to(self, description):94 description.append_text('object verifiably providing ').append_description_of(self.iface)95 def describe_mismatch(self, item, mismatch_description):96 md = mismatch_description97 try:98 verifyObject(self.iface, item)99 except Invalid as x:100 # Beginning in zope.interface 5, the Invalid exception subclasses101 # like BrokenImplementation, DoesNotImplement, etc, all typically102 # have a much nicer error message than they used to, better than we103 # were producing. This is especially true now that MultipleInvalid104 # is a thing.105 x = str(x).strip()106 md.append_text("Using class ").append_description_of(type(item)).append_text(' ')107 if x.startswith('The object '):108 x = x[len("The object "):]109 x = 'the object ' + x110 x = x.replace('\n ', '\n ')111 md.append_text(x)112def verifiably_provides(*ifaces):113 """114 Matches if the object verifiably provides the correct interface(s),115 as defined by :func:`zope.interface.verify.verifyObject`. This means having the right attributes116 and methods with the right signatures.117 .. note:: This does **not** test schema compliance. For that118 (stricter) test, see :func:`validly_provides`.119 """120 if len(ifaces) == 1:121 return VerifyProvides(ifaces[0])122 return hamcrest.all_of(*[VerifyProvides(x) for x in ifaces])123class VerifyValidSchema(BaseMatcher):124 def __init__(self, iface):125 super(VerifyValidSchema, self).__init__()126 self.iface = iface127 def _matches(self, item):128 errors = getValidationErrors(self.iface, item)129 return not errors130 def describe_to(self, description):131 description.append_text('object validly providing ').append(str(self.iface))132 def describe_mismatch(self, item, mismatch_description):133 x = None134 md = mismatch_description135 md.append_text(str(type(item)))136 errors = getValidationErrors(self.iface, item)137 for attr, exc in errors:138 try:139 raise exc140 except ValidationError:141 md.append_text(' has attribute "')142 md.append_text(attr)143 md.append_text('" with error "')144 md.append_text(repr(exc))145 md.append_text('"\n\t ')146 except Invalid as x: # pragma: no cover147 md.append_text(str(x))148def validly_provides(*ifaces):149 """150 Matches if the object verifiably and validly provides the given151 schema (interface(s)).152 Verification is done with :mod:`zope.interface` and153 :func:`verifiably_provides`, while validation is done with154 :func:`zope.schema.getValidationErrors`.155 """156 if len(ifaces) == 1:157 the_schema = ifaces[0]158 return hamcrest.all_of(verifiably_provides(the_schema), VerifyValidSchema(the_schema))159 prov = verifiably_provides(*ifaces)160 valid = [VerifyValidSchema(x) for x in ifaces]161 return hamcrest.all_of(prov, *valid)162class Implements(BaseMatcher):163 def __init__(self, iface):164 super(Implements, self).__init__()165 self.iface = iface166 def _matches(self, item):167 return self.iface.implementedBy(item)168 def describe_to(self, description):169 description.append_text('object implementing')170 description.append_description_of(self.iface)171def implements(iface):172 """173 Matches if the object implements (is a factory for) the given174 interface.175 .. seealso:: :meth:`zope.interface.interfaces.ISpecification.implementedBy`176 """177 return Implements(iface)178class ValidatedBy(BaseMatcher):179 def __init__(self, field, invalid=Invalid):180 super(ValidatedBy, self).__init__()181 self.field = field182 self.invalid = invalid183 def _matches(self, item):184 try:185 self.field.validate(item)186 except self.invalid:187 return False188 else:189 return True190 def describe_to(self, description):191 description.append_text('data validated by').append_description_of(self.field)192 def describe_mismatch(self, item, mismatch_description):193 ex = None194 try:195 self.field.validate(item)196 except self.invalid as e:197 ex = e198 mismatch_description.append_description_of(self.field)199 mismatch_description.append_text(' failed to validate ')200 mismatch_description.append_description_of(item)201 mismatch_description.append_text(' with ')202 mismatch_description.append_description_of(ex)203def validated_by(field, invalid=Invalid):204 """205 Matches if the data is validated by the given ``IField``.206 :keyword exception invalid: The types of exceptions that are considered207 invalid. Anything other than this is allowed to be raised.208 .. versionchanged:: 2.0.1209 Add ``invalid`` and change it from ``Exception`` to210 :class:`zope.interface.interfaces.Invalid`211 """212 return ValidatedBy(field, invalid=invalid)213def not_validated_by(field, invalid=Invalid):214 """215 Matches if the data is NOT validated by the given IField.216 :keyword exception invalid: The types of exceptions that are considered217 invalid. Anything other than this is allowed to be raised.218 .. versionchanged:: 2.0.1219 Add ``invalid`` and change it from ``Exception`` to220 :class:`zope.interface.interfaces.Invalid`221 """222 return is_not(validated_by(field, invalid=invalid))223def _aq_inContextOf_NotImplemented(child, parent):224 return False225try:226 from Acquisition import aq_inContextOf as _aq_inContextOf227except ImportError: # pragma: no cover228 # acquisition not installed229 _aq_inContextOf = _aq_inContextOf_NotImplemented230class AqInContextOf(BaseMatcher):231 def __init__(self, parent):232 super(AqInContextOf, self).__init__()233 self.parent = parent234 def _matches(self, item):235 if hasattr(item, 'aq_inContextOf'): # wrappers236 return item.aq_inContextOf(self.parent)237 return _aq_inContextOf(item, self.parent) # not wrapped, but maybe __parent__ chain238 def describe_to(self, description):239 description.append_text('object in context of ')240 description.append_description_of(self.parent)241 def describe_mismatch(self, item, mismatch_description):242 if _aq_inContextOf is _aq_inContextOf_NotImplemented:243 mismatch_description.append_text('Acquisition was not installed.')244 return245 mismatch_description.append_description_of(item)246 mismatch_description.append_text(' was not in the context of ')247 mismatch_description.append_description_of(self.parent)248 mismatch_description.append_text('; its lineage is ')249 lineage = []250 while item is not None:251 try:252 item = item.__parent__253 except AttributeError:254 item = None255 if item is not None:256 lineage.append(item)257 mismatch_description.append_description_of(lineage)258def aq_inContextOf(parent):259 """260 Matches if the data is in the acquisition context of261 the given object.262 """263 return AqInContextOf(parent)264# Patch hamcrest for better descriptions of maps (json data)265# and sequences266if six.PY3:267 from io import StringIO268else: # pragma: no cover269 from cStringIO import StringIO # pylint:disable=import-error270_orig_append_description_of = BaseDescription.append_description_of271def _append_description_of_map(self, value):272 if not hasattr(value, 'describe_to'):273 if isinstance(value, (Mapping, Sequence)):274 sio = StringIO()275 pprint.pprint(value, sio)276 self.append(sio.getvalue())277 return self278 return _orig_append_description_of(self, value)279BaseDescription.append_description_of = _append_description_of_map280class TypeCheckedDict(dict):281 "A dictionary that ensures keys and values are of the required type when set"282 def __init__(self, key_class=object, val_class=object, notify=None):283 dict.__init__(self)284 self.key_class = key_class285 self.val_class = val_class286 self.notify = notify287 def __setitem__(self, key, val):288 assert_that(key, is_(self.key_class))289 assert_that(val, is_(self.val_class))290 dict.__setitem__(self, key, val)291 if self.notify:292 self.notify(key, val)

Full Screen

Full Screen

helper.py

Source:helper.py Github

copy

Full Screen

...24 else:25 if mismatch_description:26 mismatch_description.append_text(27 "No item matched "28 ).append_description_of(matcher).append_text(29 "among candidates"30 ).append_description_of(31 sequence[to_match:]32 )33 return False34 return True35 def describe_to(self, description: Description) -> None: # pragma: no cover36 description.append_text("a sequence containing ")37 for matcher in self.matchers[:-1]:38 description.append_description_of(matcher)39 description.append_text(" followed by ")40 description.append_description_of(self.matchers[-1])41def has_items_in_order(*matchers: Any) -> HasItemsInOrder:42 return HasItemsInOrder([wrap_matcher(matcher) for matcher in matchers])43@contextlib.contextmanager44def temp_dir() -> Iterator[str]:45 try:46 dirname = tempfile.mkdtemp()47 yield dirname48 finally:...

Full Screen

Full Screen

status_code_matcher.py

Source:status_code_matcher.py Github

copy

Full Screen

...8 return False9 return item.status_code == self._status_code10 def describe_to(self, description):11 description.append_text("status code ")12 description.append_description_of(self._status_code)13 def describe_mismatch(self, item, mismatch_description):14 mismatch_description.append_text("status code ")15 mismatch_description.append_description_of(item.status_code)16 mismatch_description.append_text(" received with body: \n")17 mismatch_description.append_text(item.text[:1000] + (item.text[1000:] and '..'))18 def describe_match(self, item, match_description):19 match_description.append_text("status code ")20 match_description.append_description_of(item.status_code)21 match_description.append_text(" was received with body: \n")22 match_description.append_text(item.text[:1000] + (item.text[1000:] and '..'))23def returned_status_code(status_code: int):...

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run PyHamcrest automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful