def match(self, thing): if not isinstance(thing, defer.Deferred): return Mismatch("%r is not a Deferred" % (thing,)) if thing.called: return Mismatch( "%r has been called (result=%r)" % (thing, thing.result)) return None
def match(self, other): expected_type = type(self.expected) if type(other) is not expected_type: return Mismatch("{} is not a {}".format(other, expected_type)) if other.args != self.expected.args: return Mismatch("{} has different arguments: {}.".format( other.args, self.expected.args))
def match(self, call_tuple): for k, v in self._filters.items(): try: pos = self._position_lookup[k] if call_tuple[pos] != v: return Mismatch("Value for key is %r, not %r" % (call_tuple[pos], v)) except IndexError: return Mismatch("Key %s is not present." % k)
def match(self, candidate): """Return Mismatch if candidate is not in a subdirectory of path.""" if not candidate: return Mismatch("""None passed to match""") path = self._path if os.path.commonprefix([os.path.realpath(path).lower(), os.path.realpath(candidate).lower()]): return None else: return Mismatch("{0} is not in a subdir of {1}".format(candidate, path))
def match(self, log): """ Return None if log is bound with given args/kwargs. Otherwise return Mismatch """ if not isinstance(log, BoundLog): return Mismatch('log is not a BoundLog') kwargs = bound_log_kwargs(log) if self.kwargs == kwargs: return None else: return Mismatch('Expected kwargs {} but got {} instead'.format( self.kwargs, kwargs))
def match(self, something): try: getattr(something, self.attribute) except AttributeError: return Mismatch( "%r does not have a %r attribute" % ( something, self.attribute))
def match(self, other): if type(other) != tuple: return Mismatch('{!r} is not an exc_info tuple'.format(other)) expected_class = self.expected etype, evalue, etb = other if not issubclass(etype, expected_class): return Mismatch( "{!r} is an instance of {}, expected an instance of {}.".format( evalue, etype, expected_class, ), dict( traceback=TracebackContent(other, None), ), )
def match(self, observed): if observed != self.expected: diff = self._diff(self.expected, observed) return Mismatch( "Observed text does not match expectations; see diff.", {"diff": Content(UTF8_TEXT, lambda: map(str.encode, diff))}, )
def match(self, mock): try: mock.assert_any_call(*self.args, **self.kwargs) except AssertionError as e: return Mismatch(*e.args) return None
def _got_failure(deferred, failure): deferred.addErrback(lambda _: None) return Mismatch( _u('Success result expected on %r, found failure result ' 'instead: %r' % (deferred, failure)), {'traceback': failure_content(failure)}, )
def match(self, mock): mismatch = IsCallableMock().match(mock) if mismatch is not None: return mismatch elif mock.call_count == 1: return None else: return Mismatch("Expected to be called once. Called %d times." % mock.call_count)
def match(self, actual): for phase, ops in self.expected.items(): if phase not in actual: # missing the phase return Mismatch( "Phase %d does not exist in %s" % (phase, actual)) for op, pkgs in ops.items(): if op not in actual[phase]: # missing op (install/uninstall) return Mismatch( "Operation %s does not exist in %s" % (op, ops)) # on py2 these can be out of order, we just want a match expected_phase_ops = sorted(self.expected[phase][op]) actual_phase_ops = sorted(actual[phase][op]) if expected_phase_ops != actual_phase_ops: return Mismatch( "Operation list %s does not match expected %s" % (actual[phase][op], self.expected[phase][op]))
def match(self, response): # Maybe the c-t should be more specific, but this is probably good for # making sure it gets saved without the client trying to decompress it # or anything. if (response.header('Content-Type') == self.expect_mimetype and response.header('Content-Disposition') == "attachment; filename*=utf-8''" + self.expect_filename): pass else: return Mismatch("wrong response headers: %r" % response.headers)
def match(self, obj): missing = set() for iface in self.interfaces: if not iface.providedBy(obj): missing.add(iface) if missing: return Mismatch("{} does not provide expected {}".format( obj, ", ".join(str(iface) for iface in missing), ))
def match(self, response): actual_code = response.code mismatch = self.match_expected_code.match(actual_code) if mismatch is None: return None return Mismatch( u"Response {} code: {}".format( response, mismatch.describe(), ), mismatch.get_details(), )
def match(self, macaroons): mismatch = Contains("root").match(macaroons) if mismatch is not None: return mismatch root_macaroon = Macaroon.deserialize(macaroons["root"]) if "discharge" in macaroons: discharge_macaroons = [ Macaroon.deserialize(macaroons["discharge"])] else: discharge_macaroons = [] try: Verifier().verify(root_macaroon, self.key, discharge_macaroons) except Exception as e: return Mismatch("Macaroons do not verify: %s" % e)
def match(self, other): # "other" is the RemoteSnapshot's signature public_key = self.snapshot.author.verify_key alleged_sig = base64.b64decode(self.remote_snapshot.signature) signed_data = (u"{content_capability}\n" u"{name}\n").format( content_capability=self.remote_snapshot.content_cap, name=self.remote_snapshot.metadata['name'], ).encode("utf8") try: public_key.verify(signed_data, alleged_sig) except BadSignatureError: return Mismatch("The signature did not verify.")
def match(self, headers): """ :param twisted.web.http_headers.Headers headers: The response or request headers object. """ if not headers.hasHeader(self.key): headers_content = text_content( repr(dict(headers.getAllRawHeaders()))) return Mismatch('The response does not have a "%s" header' % (self.key, ), details={'raw headers': headers_content}) raw_values = headers.getRawHeaders(self.key) return super(HasHeader, self).match(raw_values)
def match(self, o): serialized = o.encode_base64() deserialized = type(o).decode_base64(serialized) reserialized = deserialized.encode_base64() if serialized != reserialized: return Mismatch( "failed to round-trip unmodified", dict( o=text_content("{}".format(o)), serialized=text_content("{!r}".format(serialized)), deserialized=text_content("{}".format(deserialized)), reserialized=text_content("{!r}".format(reserialized)), ), ) return None
def match(self, value): if callable(value): wait_fun = partial(_callable_wait_for, value) else: wait_fun = getattr(value, 'wait_for', None) if wait_fun is None or not callable(wait_fun): raise TypeError( "Eventually is only usable with attributes that have a " "wait_for function or callable objects.") try: wait_fun(self.matcher, self.timeout) except AssertionError as e: return Mismatch(str(e)) return None
def match(self, base): content = [] for root, dirs, files in scandir.walk(base): content.extend( [os.path.relpath(os.path.join(root, f), base) for f in files]) left_over = sorted(set(content) - set(self.expected)) missing = sorted(set(self.expected) - set(content)) if left_over != [] or missing != []: mismatch = '' if left_over: mismatch += " unexpected files: " + str(left_over) if missing: mismatch += " missing files: " + str(missing) return Mismatch("SignedMatches:" + mismatch) return None
def match(self, value): # This is somewhat terrible. Probably can be better after # pyca/service_identity#14 is resolved. target_ids = [ DNSPattern(target_name.encode('utf-8')) for target_name in (value.extensions.get_extension_for_oid( ExtensionOID.SUBJECT_ALTERNATIVE_NAME).value. get_values_for_type(x509.DNSName)) ] ids = [DNS_ID(self.name)] try: verify_service_identity(cert_patterns=target_ids, obligatory_ids=ids, optional_ids=[]) except VerificationError: return Mismatch('{!r} is not valid for {!r}'.format( value, self.name))
def match(self, response): if response.status_code != self.status_code: response_dump = response.serialize() if response.charset.lower() not in {"utf-8", "utf_8", "utf8"}: response_dump = response_dump.decode(response.charset) response_dump = response_dump.encode("utf-8", "replace") description = "Expected %s, got %s" % ( describe_http_status(self.status_code), describe_http_status(response.status_code), ) details = { "Unexpected HTTP response": Content(UTF8_TEXT, lambda: [response_dump]) } return Mismatch(description, details)
def match(self, other): """ Match a private key which is the same as the private key in the node at ``self.basedir``. :param other: A signing key (aka "private key") from ``allmydata.crypto.ed25519``. This is the key to check against the node's key. :return Mismatch: If the keys don't match. """ config = read_config(self.basedir, u"tub.port") privkey_bytes = config.get_private_config("node.privkey") private_key = ed25519.signing_keypair_from_string(privkey_bytes)[0] signature = ed25519.sign_data(private_key, b"") other_public_key = ed25519.verifying_key_from_signing_key(other) try: ed25519.verify_signature(other_public_key, signature, b"") except error.BadSignature: return Mismatch("The signature did not verify.")
def match(self, matchee): try: result = matchee() return Mismatch('%r returned %r' % (matchee, result)) # Catch all exceptions: Raises() should be able to match a # KeyboardInterrupt or SystemExit. except: exc_info = sys.exc_info() mismatch = self.exception_matcher.match(exc_info) exc_type = exc_info[1] # It's safer not to keep the traceback around. del exc_info if mismatch: # The exception did not match, or no explicit matching logic was # performed. If the exception is a non-user exception then # propagate it. if _is_exception(exc_type) and not _is_user_exception(exc_type): raise return mismatch return None
def _got_result(deferred, result): return Mismatch( _u('No result expected on %r, found %r instead' % (deferred, result)))
def _got_no_result(deferred): return Mismatch( _u('Failure result expected on %r, found no result instead' % (deferred,)))
def _got_success(deferred, success): return Mismatch( _u('Failure result expected on %r, found success ' 'result (%r) instead' % (deferred, success)))
def match(self, actual): if round(actual - self.expected, 3) == 0: return None else: msg = "{} is not almost equal to {}" return Mismatch(msg.format(actual, self.expected))
def test_forwards_details(self): x = Mismatch("description", {'foo': 'bar'}) decorated = MismatchDecorator(x) self.assertEqual(x.get_details(), decorated.get_details())
def test_constructor_no_arguments(self): mismatch = Mismatch() self.assertThat(mismatch.describe, Raises(MatchesException(NotImplementedError))) self.assertEqual({}, mismatch.get_details())
def test_constructor_arguments(self): mismatch = Mismatch("some description", {'detail': "things"}) self.assertEqual("some description", mismatch.describe()) self.assertEqual({'detail': "things"}, mismatch.get_details())
def test_forwards_details(self): x = Mismatch('description', {'foo': 'bar'}) annotated = AnnotatedMismatch("annotation", x) self.assertEqual(x.get_details(), annotated.get_details())
def test_forwards_description(self): x = Mismatch("description", {"foo": "bar"}) decorated = MismatchDecorator(x) self.assertEqual(x.describe(), decorated.describe())
def _got_no_result(deferred): return Mismatch( _u('Success result expected on %r, found no result ' 'instead' % (deferred,)))
def test_forwards_details(self): x = Mismatch("description", {"foo": "bar"}) annotated = AnnotatedMismatch("annotation", x) self.assertEqual(x.get_details(), annotated.get_details())