def _assert_match(actual, matcher, reason): if not matcher.matches(actual): description = StringDescription() # print # print reason # print "-1 <%s>" % description.append_text(reason) # print matcher # print matcher.__class__ # print dir(matcher) # print "-2 <%s>" % description.append_description_of(matcher) # print "-3 <%s>" % matcher.describe_mismatch(actual, description) # print # description.append_text(reason) \ # .append_text('\n Expected: ') \ # .append_description_of(matcher) \ # .append_text('\n But: ') reason = ' (reason: {}) '.format(reason) if reason else '' description.append_text(reason) \ .append_text('expected ') \ .append_description_of(matcher) \ .append_text(', but ') matcher.describe_mismatch(actual, description) raise AssertionError(str(description))
def assert_match_description(expected, matcher, item): result = matcher.matches(item, StringDescription()) assert result, "Precondition: Matcher should match item" description = StringDescription() matcher.describe_match(item, description) assert expected == str(description)
def _matches(self, matcher): ret = True self.match_result = matcher._matches(self.item) if self.result: ret &= self.match_result else: ret &= not self.match_result if self.description: descr = StringDescription() matcher.describe_to(descr) descr = str(descr) descr_is_correct = descr == self.description if not descr_is_correct: self.wrong_description = descr ret = False if self.mismatch_description: descr = StringDescription() matcher.describe_mismatch(self.item, descr) descr = str(descr) descr_is_correct = descr == self.mismatch_description if not descr_is_correct: self.wrong_mismatch_description = descr ret = False return ret
def _matches(self, matcher): ret = True self.match_result = matcher._matches(self.item) if self.expected_match_result: ret &= self.match_result else: ret &= not self.match_result if self.description: descr = StringDescription() matcher.describe_to(descr) descr = str(descr) descr_is_correct = descr == self.description if not descr_is_correct: self.wrong_description = descr ret = False if self.mismatch_description: if ret == self.expected_match_result: self.wrong_mismatch_description = ( "the matcher matched, but a mismatch description was provided" ) return False descr = StringDescription() matcher.describe_mismatch(self.item, descr) descr = str(descr) descr_is_correct = descr == self.mismatch_description if not descr_is_correct: self.wrong_mismatch_description = "the mismatch_description was <{}>".format( descr) ret = False return ret
def test_day_of_week_description(day: int, expected_description: str): matcher = day_of_week(day) description = StringDescription() matcher.describe_to(description) assert str(description).startswith(expected_description) description = StringDescription() matcher.describe_mismatch("2021-05-29", description) assert str(description).startswith("was <")
def _assert_match(actual, matcher, reason): if not matcher.matches(actual): description = StringDescription() description.append_text(reason) \ .append_text('\nExpected: ') \ .append_description_of(matcher) \ .append_text('\n but: ') matcher.describe_mismatch(actual, description) description.append_text('\n') raise AssertionError(description)
def test_day_of_week(day, yesterday, today, tomorrow, expected_name): matcher = day_of_week(day) assert not matcher.matches(yesterday) assert matcher.matches(today) assert not matcher.matches(tomorrow) description = StringDescription() matcher.describe_to(description) assert str(description).startswith(f"is {expected_name}") description = StringDescription() matcher.describe_mismatch(tomorrow, description) assert str(description).startswith("was <")
def testMismatchDescriptionShowsActualArgumentAddress(self): matcher = same_instance('foo') description = StringDescription() expected = re.compile("was 0x[0-9a-fA-F]+ 'hi'") result = matcher.matches('hi', description) self.assertFalse(result, 'Precondition: Matcher should not match item') self.assertTrue(expected.match(str(description)))
def assert_matches(matcher, arg, message): try: assert matcher.matches(arg), message except AssertionError: description = StringDescription() matcher.describe_mismatch(arg, description) log.error(str(description)) raise
def testDescribeMismatch(self): matcher = same_instance('foo') description = StringDescription() expected = re.compile("was 0x[0-9a-fA-F]+ 'hi'") matcher.describe_mismatch('hi', description) expected = re.compile("was 0x[0-9a-fA-F]+ 'hi'") self.assertTrue(expected.match(str(description)))
def testMismatchDescriptionShowsActualArgumentAddress(self): matcher = same_instance("foo") description = StringDescription() expected = re.compile("was " + ADDRESS_FORMAT + " 'hi'") result = matcher.matches("hi", description) self.assertFalse(result, "Precondition: Matcher should not match item") self.assertTrue(expected.match(str(description)))
def assert_matches(self, message, matcher, arg): try: self.assertTrue(matcher.matches(arg), message) except AssertionError: description = StringDescription() matcher.describe_mismatch(arg, description) log.error(str(description)) raise
def assert_deprecated(message, matcher): with warnings.catch_warnings(record=True) as w: warnings.simplefilter("always") matcher(anything()).matches("", StringDescription()) assert_that( w, has_item(has_properties(category=DeprecationWarning, message=has_string(message))) )
def testDescribeMismatch(self): matcher = same_instance('foo') description = StringDescription() expected = re.compile("was " + ADDRESS_FORMAT + " 'hi'") matcher.describe_mismatch('hi', description) expected = re.compile("was " + ADDRESS_FORMAT + " 'hi'") self.assertTrue(expected.match(str(description)), "Expected %s to match %s" % (str(matcher), str(description)))
def match(self, request, stub): """Match request with single stub""" msg = StringDescription() all = all_of(*build_matchers(stub)) result = all.matches(request, msg) if not result: log.debug(u'No match found: {0}'.format(msg.out)) self.trace.warn(msg.out) return result
def test_datetime_matcher(value, item, before_expected, after_expected): matcher = before(ORIGIN) assert matcher.matches(item) == before_expected description = StringDescription() matcher.describe_to(description) assert str(description).startswith("a value before <") description = StringDescription() matcher.describe_mismatch(item, description) assert str(description).startswith("was <") matcher = after(value) assert matcher.matches(item) == after_expected description = StringDescription() matcher.describe_to(description) assert str(description).startswith("a value after <") description = StringDescription() matcher.describe_mismatch(item, description) assert str(description).startswith("was <")
def describe_mismatch(self, matcher_under_test: Matcher[Any], description: Description) -> None: actual_message = StringDescription() if matcher_under_test.matches(self.value_not_to_match, actual_message): description.append_text("matched") return description.append_text("got message ").append_description_of( actual_message) self.append_diff(actual_message, description)
def redirects_to(url_matcher: Union[str, Matcher]) -> Matcher[Response]: """Is a response a redirect to a URL matching the suplplied matcher? Matches :requests.models.Response:. :param url_matcher: Expected URL. """ return described_as( str(StringDescription().append_text( "redirects to ").append_description_of(url_matcher)), is_response().with_status_code(between(300, 399)).and_headers( has_entry("Location", url_matcher)), )
def describe_to(self, description): description.append_text( "An HttpResponse object with status_code <{}>".format(self.status)) header_descr = [] if self.headers_: for key, val in self.headers_.items(): descr = StringDescription() val.describe_to(descr) header_descr.append("{}: {}".format(key, descr)) description.append_list(", with headers: ", ". ", ".", header_descr)
def _describe_failure_of(probe): description = StringDescription() description.append_text('\nTried to look for...\n ') probe.describe_to(description) description.append_text('\nbut...\n ') probe.describe_failure_to(description) return str(description)
def matches(self, item, mismatch_description=None): """Return whether the item is a valid to-one relationship.""" if mismatch_description is None: mismatch_description = StringDescription() if "data" not in item: mismatch_description.append('missing key "data"') return False if item["data"] is None: if self.optional: return True mismatch_description.append("non-optional to-one relationship is ") mismatch_description.append_description_of(item["data"]) return False return super().matches(item["data"], mismatch_description)
def get_mismatch_description(matcher, item): """Get the mismatch description of a matcher with a particular item. :param matcher: :type matcher: BaseMatcher :param item: :type item: Any :return: The string representation of the mismatch description :rtype: str """ descr = StringDescription() matcher.describe_mismatch(item, descr) return str(descr)
def _assert_match(actual: T, matcher: Matcher[T], reason: str) -> None: if not matcher.matches(actual): description = StringDescription() description.append_text(reason).append_text( "\nExpected: ").append_description_of(matcher).append_text( "\n but: ") matcher.describe_mismatch(actual, description) description.append_text("\n") raise AssertionError(description)
class StringDescriptionTest(unittest.TestCase): def setUp(self): self.description = StringDescription() def testLetsSelfDescribingObjectDescribeItself(self): self.description.append_description_of(FakeSelfDescribing()) self.assertEqual("DESCRIPTION", str(self.description)) def testDescribesStringInQuotes(self): self.description.append_description_of("FOO") self.assertEqual("'FOO'", str(self.description)) def testWrapsNonSelfDescribingObjectInAngleBrackets(self): self.description.append_description_of(42) self.assertEqual("<42>", str(self.description)) def testShouldNotAddAngleBracketsIfObjectDescriptionAlreadyHasThem(self): self.description.append_description_of(object()) expected = re.compile("<object object at 0x[0-9a-fA-F]+>") self.assertTrue(expected.match(str(self.description))) def testDescribeUnicodeStringAsUnicode(self): self.description.append_description_of("\u05d0") self.assertEqual("'\u05d0'", str(self.description))
def matches(self, item, mismatch_description=None): """Return whether the item is a json:api document.""" if mismatch_description is None: mismatch_description = StringDescription() if "data" not in item: mismatch_description.append('missing key "data"') return False if not self.optional and not item["data"]: mismatch_description.append('non-optional "data" is ') mismatch_description.append_description_of(item["data"]) return False if self.many: if not isinstance(item["data"], list): mismatch_description.append( f'"data" is not a `list`\n got: `{item.__class__.__name__}`' ) return False for index, data in enumerate(item["data"]): if not self._match_resource( data, mismatch_description, index=index): return False elif not self._match_resource(item["data"], mismatch_description): return False return self._matches_includes(item, mismatch_description)
def _assert_match(actual, matcher, reason): if not matcher.matches(actual): description = StringDescription() description.append_text(reason) \ .append_text('\nExpected: ') \ .append_description_of(matcher) \ .append_text('\n but: ') matcher.describe_mismatch(actual, description) description.append_text('\n') raise AssertionError(description)
def test_failure_error(self): desc = StringDescription() matcher = is_counter('foo', '1', 0.1) matcher.describe_to(desc) desc = str(desc) assert_that( desc, all_of( contains_string("(an instance of Observation and "), contains_string( "an object with a property 'kind' matching 'c'"), contains_string( "an object with a property 'name' matching 'foo'"), contains_string( "an object with a property 'value' matching '1'"), contains_string( "an object with a property 'sampling_rate' matching <0.1>") ))
def wait_for(self, refresh_fn, matcher, timeout): matched = False counter = 0 failure_message = StringDescription() while not matched and counter <= timeout: new_value = refresh_fn() match = matcher.matches(new_value) if not match: sleep(1) counter += 1 else: matched = True if matched: return else: matcher.describe_mismatch(new_value, failure_message) raise AssertionError("After {} seconds test failed: {}".format( timeout, failure_message))
def _matches(self, item): if not (isinstance(item, list) or isinstance(item, tuple)): self.messages.append( f'Can\'t perform ListSorted matcher on {type(item)} object.') pairs = [(item[i], item[i + 1]) for i in range(len(item) - 1)] for i, (left, right) in enumerate(pairs): matcher = self.pair_matcher(self.criteria(right)) if not matcher.matches(self.criteria(left)): description = StringDescription() matcher.describe_to(description) description.append_text(' expected, but ') matcher.describe_mismatch(self.criteria(left), description) description.append(f'. items indexes are {i}, and {i + 1}') self.messages.append(str(description)) return False return True
def matches(self, item, mismatch_description=None): """Return whether the item is a resource object.""" if mismatch_description is None: mismatch_description = StringDescription() match_result = super().matches(item, mismatch_description) if not match_result: return match_result if not self._match_dict( item, mismatch_description, attr_name="attributes", attr_description="attribute", matcher_dict=self.attributes, ): return False if not self._match_dict( item, mismatch_description, attr_name="relationships", attr_description="relationship", matcher_dict=self.relationships, ): return False return True
def _matches(self, item): if not isinstance(item, HttpResponse): self.errors.append("Not an HttpResponse object") return False matches = True if item.status_code != self.status: matches = False self.errors.append("Status code was: <{}>".format( item.status_code)) if self.headers_: for header, matcher in self.headers_.items(): if not item.has_header(header): matches = False self.errors.append( "Does not contain header <{}>".format(header)) elif not matcher._matches(item[header]): matches = False descr = StringDescription() matcher.describe_mismatch(item[header], descr) self.errors.append("The value for header <{}> {}".format( header, str(descr))) return matches
def assert_description(expected, matcher): description = StringDescription() description.append_description_of(matcher) assert expected == str(description)
def testDescriptionIncludesMemoryAddress(self): description = StringDescription() expected = re.compile("same instance as " + ADDRESS_FORMAT + " 'abc'") description.append_description_of(same_instance('abc')); self.assertTrue(expected.match(str(description)))
def assert_description(self, expected, matcher): description = StringDescription() description.append_description_of(matcher) self.assertEqual(expected, str(description))