def test_assertThat_verbose_output(self): matchee = "foo" matcher = Equals("bar") expected = ( "Match failed. Matchee: %r\n" "Matcher: %s\n" "Difference: %s\n" % (matchee, matcher, matcher.match(matchee).describe()) ) self.assertFails(expected, self.assertThat, matchee, matcher, verbose=True)
def test_verbose_description(self): matchee = 2 matcher = Equals(3) mismatch = matcher.match(2) e = MismatchError(matchee, matcher, mismatch, True) expected = ( "Match failed. Matchee: %r\n" "Matcher: %s\n" "Difference: %s\n" % (matchee, matcher, matcher.match(matchee).describe()) ) self.assertEqual(expected, str(e))
def test_assertThat_verbose_output(self): matchee = 'foo' matcher = Equals('bar') expected = ( 'Match failed. Matchee: %r\n' 'Matcher: %s\n' 'Difference: %s\n' % ( matchee, matcher, matcher.match(matchee).describe(), )) self.assertFails( expected, self.assertThat, matchee, matcher, verbose=True)
def test_file_exists_content_mismatch(self, observed, expected): """ If the file exists, the content is matched against the given matcher. If it mismatches, the message includes both the filename and the message from the underlying matcher. """ assume(observed != expected) matcher = Equals(expected) path = self.make_temporary_path() path.setContent(observed) mismatch = file_contents(matcher).match(path) self.assertThat( mismatch.describe(), Equals( '%s has unexpected contents:\n%s' % (path.path, matcher.match(observed).describe())))
def test_assertThat_verbose_unicode(self): # When assertThat is given matchees or matchers that contain non-ASCII # unicode strings, we can still provide a meaningful error. matchee = _u('\xa7') matcher = Equals(_u('a')) expected = ( 'Match failed. Matchee: %s\n' 'Matcher: %s\n' 'Difference: %s\n\n' % ( repr(matchee).replace("\\xa7", matchee), matcher, matcher.match(matchee).describe(), )) e = self.assertRaises( self.failureException, self.assertThat, matchee, matcher, verbose=True) self.assertEqual(expected, self.get_error_string(e))
def test_verbose_unicode(self): # When assertThat is given matchees or matchers that contain non-ASCII # unicode strings, we can still provide a meaningful error. matchee = _u("\xa7") matcher = Equals(_u("a")) mismatch = matcher.match(matchee) expected = ( "Match failed. Matchee: %s\n" "Matcher: %s\n" "Difference: %s\n" % (text_repr(matchee), matcher, mismatch.describe()) ) e = MismatchError(matchee, matcher, mismatch, True) if str_is_unicode: actual = str(e) else: actual = unicode(e) # Using str() should still work, and return ascii only self.assertEqual(expected.replace(matchee, matchee.encode("unicode-escape")), str(e).decode("ascii")) self.assertEqual(expected, actual)
def raise_mismatch_error(): raise MismatchError(2, Equals(3), Equals(3).match(2))
def test_nonexisting_snap_must_raise_exception(self): result = self.run_command(["push-metadata", "test-unexisting-snap"]) self.assertThat(result.exit_code, Equals(2))
def has_digest(digest): return AfterPreprocessing(hexdigest, Equals(digest))
def test__recursively_calls_mapping_keys_and_values(self): mapping = {"key\u1234".encode("utf-8"): ["b", "a", "r"]} expected = (("key\u1234", ("a", "b", "r")), ) self.expectThat(describe_canonical(mapping), Equals(expected))
def test__sorts_sequences(self): self.expectThat(describe_canonical([3, 1, 2]), Equals((1, 2, 3))) self.expectThat(describe_canonical([[1, 2], [1, 1]]), Equals(((1, 1), (1, 2))))
def test__returns_sequences_as_tuples(self): self.expectThat(describe_canonical([1, 2, 3]), Equals((1, 2, 3)))
def test_info_extraction(self): expected = ExtractedMetadata(**self.params) actual = setuppy.extract("setup.py") self.assertThat(str(actual), Equals(str(expected))) self.assertThat(actual, Equals(expected))
def test_round_trip(self): argument = arguments.AmpRequestedMachine() encoded = argument.toString(self.example) self.assertThat(encoded, IsInstance(bytes)) decoded = argument.fromString(encoded) self.assertThat(decoded, Equals(self.example))
def test_round_trip(self): argument = arguments.AmpDiscoveredPodHints() encoded = argument.toString(self.example) self.assertThat(encoded, IsInstance(bytes)) decoded = argument.fromString(encoded) self.assertThat(decoded, Equals(self.example))
def test_set_active_returns_data_and_sets_active(self): node = factory.make_Node() handler = self.make_nodes_handler(fields=["system_id"]) node_data = handler.set_active({"system_id": node.system_id}) self.expectThat(node_data["system_id"], Equals(node.system_id)) self.expectThat(handler.cache["active_pk"], Equals(node.system_id))
def test_clean_nested_dependent_parts(self): result = self.run_command( ["clean", "main", "dependent", "nested-dependent"]) self.assertThat(result.exit_code, Equals(0)) self.assert_clean(["main", "dependent", "nested-dependent"])
def test_unprime_fails(self): self.make_snapcraft_yaml() result = self.run_command(["clean", "--unprime"]) self.assertThat(result.exit_code, Equals(2))
def test_another_conjunction(self): items = ['foo', 'bar', 'baz', 'qux'] output = formatting_utils.humanize_list(items, 'or') self.assertThat(output, Equals("'bar', 'baz', 'foo', or 'qux'"))
def test_four_items(self): items = ['foo', 'bar', 'baz', 'qux'] output = formatting_utils.humanize_list(items, 'and') self.assertThat(output, Equals("'bar', 'baz', 'foo', and 'qux'"))
def test_round_trip(self): argument = arguments.StructureAsJSON() encoded = argument.toString(self.example) self.assertThat(encoded, IsInstance(bytes)) decoded = argument.fromString(encoded) self.assertThat(decoded, Equals(self.example))
def test_two_items(self): items = ['foo', 'bar'] output = formatting_utils.humanize_list(items, 'and') self.assertThat(output, Equals("'bar' and 'foo'"), "Expected 'bar' before 'foo' due to sorting")
def test_service_uses__tryUpdate_as_periodic_function(self): service = external.RackExternalService( StubClusterClientService(), reactor ) self.assertThat(service.call, Equals((service._tryUpdate, (), {})))
def test__decodes_byte_strings(self): string = factory.make_string().encode("utf-8") self.expectThat( describe_canonical(string), MatchesAll(IsInstance(str), Not(Is(string)), Equals(string.decode("utf-8"))))
def test_service_iterates_on_low_interval(self): service = external.RackExternalService( StubClusterClientService(), reactor ) self.assertThat(service.step, Equals(service.INTERVAL_LOW))
def test__recursively_calls_sequence_elements(self): self.expectThat(describe_canonical([1, [2, 3]]), Equals((1, (2, 3))))
def test__get_power_parameters_for_with_empty_list(self): Machines = make_origin().Machines self.assertThat( Machines.get_power_parameters_for(system_ids=[]), Equals({}), )
def test__returns_mappings_as_tuples(self): self.expectThat(describe_canonical({1: 2}), Equals(((1, 2), )))
def test_assertThat_output(self): matchee = 'foo' matcher = Equals('bar') expected = matcher.match(matchee).describe() self.assertFails(expected, self.assert_that_callable, matchee, matcher)
def test__sorts_mappings(self): self.expectThat(describe_canonical({ 2: 1, 1: 1 }), Equals(((1, 1), (2, 1))))
def test_default_description_is_mismatch(self): mismatch = Equals(3).match(2) e = MismatchError(2, Equals(3), mismatch) self.assertEqual(mismatch.describe(), str(e))
async def test_list_tahoe_objects(request, reactor, tahoe_venv, base_dir, introducer_furl, flog_gatherer): """ the 'tahoe-objects' API works concurrently (see also ticket #570) """ yolandi = await util.MagicFolderEnabledNode.create( reactor, tahoe_venv, request, base_dir, introducer_furl, flog_gatherer, name="yolandi", tahoe_web_port="tcp:9983:interface=localhost", magic_folder_web_port="tcp:19983:interface=localhost", storage=True, ) number_of_folders = 20 folder_names = ["workstuff{}".format(n) for n in range(number_of_folders)] # make a bunch of folders for folder_name in folder_names: magic_dir = FilePath(base_dir).child(folder_name) magic_dir.makedirs() await yolandi.client.add_folder( folder_name, author_name="yolandi", local_path=magic_dir, poll_interval=10, scan_interval=10, ) # concurrently put 1 file into each folder and immediately create # a snapshot for it via an API call files = [] for folder_num, folder_name in enumerate(folder_names): magic_dir = FilePath(base_dir).child(folder_name) with magic_dir.child("a_file_name").open("w") as f: f.write("data {:02d}\n".format(folder_num).encode("utf8") * 100) files.append(yolandi.client.add_snapshot( folder_name, "a_file_name", )) # Each folder should produce [416, 800, 190] for the sizes -- this # is (Snapshot-size, content-size and metadata-size) for the one # file we've put in. .. except the first one depends on # Snapshot's implementation and the last one depends on metadata # details, so we only want to assert that they're all the same. # expected_results = [[416, 800, 190]] * number_of_folders # The "if res else None" clauses below are because we use this in # the loop (to potentially succeed early), and some of the results # may be empty for a few iterations / seconds matches_expected_results = MatchesAll( # this says that all the content capabilities (2nd item) # should be size 800 AfterPreprocessing( lambda results: [res[1] if res else None for res in results], AllMatch(Equals(800))), # this says that there should be exactly one thing in the set # of all the pairs of the Snapshot (1st item) and metadata # (3rd item) sizes .. that is, that all the Snapshot sizes are # the same and all the metadata sizes are the same. AfterPreprocessing( lambda results: {(res[0], res[2]) if res else None for res in results}, HasLength(1))) # try for 15 seconds to get what we expect. we're waiting for each # of the magic-folders to upload their single "a_file_name" items # so that they each have one Snapshot in Tahoe-LAFS for _ in range(15): await util.twisted_sleep(reactor, 1) results = await DeferredList([ yolandi.client.tahoe_objects(folder_name) for folder_name in folder_names ]) # if any of the queries fail, we fail the test errors = [fail for ok, fail in results if not ok] assert errors == [], "At least one /tahoe-objects query failed" actual_results = [result for ok, result in results if ok] # exit early if we'll pass the test if matches_expected_results.match(actual_results) is None: break # check the results assert_that(actual_results, matches_expected_results)
def test_ignored_fields(self): """ Ignore any specified fields. """ message = WrittenMessage.from_dict({u'a': 1, u'b': 2}) self.assertThat(message_fields(message, {u'b'}), Equals([(u'a', 1)]))
def test_without_snap_must_raise_exception(self): result = self.run_command(["push-metadata"]) self.assertThat(result.exit_code, Equals(2)) self.assertThat(result.output, Contains("Usage:"))
def test__ip_addresses_are_passed_through(self): address4 = factory.make_ipv4_address() address6 = factory.make_ipv6_address() self.assertThat(config._get_addresses(address4, address6), Equals(([address4], [address6])))
def test_assertThat_output(self): matchee = 'foo' matcher = Equals('bar') expected = matcher.match(matchee).describe() self.assertFails(expected, self.assertThat, matchee, matcher)
def test__ignores_resolution_failures(self): # Some ISPs configure their DNS to resolve to an ads page when a domain # doesn't exist. This ensures resolving fails so the test passes. self.patch(config, '_gen_addresses_where_possible').return_value = [] self.assertThat(config._get_addresses("no-way-this-exists.maas.io"), Equals(([], [])))
def test_assertThat_message_is_annotated(self): matchee = 'foo' matcher = Equals('bar') expected = Annotate('woo', matcher).match(matchee).describe() self.assertFails(expected, self.assert_that_callable, matchee, matcher, 'woo')
def test_default_description_unicode(self): matchee = _u('\xa7') matcher = Equals(_u('a')) mismatch = matcher.match(matchee) e = MismatchError(matchee, matcher, mismatch) self.assertEqual(mismatch.describe(), str(e))