コード例 #1
0
ファイル: test_avahi.py プロジェクト: sydneypdx/maas
 def test_returns_none_for_malformed_input(self):
     self.assertThat(parse_avahi_event(b";;;"), Equals(None))
コード例 #2
0
 def test_too_many_values(self):
     self.assertMismatchWithDescriptionMatching(
         [1, 2, 3], MatchesSetwise(Equals(1), Equals(2)),
         Equals('There was 1 value left over: [3]'))
コード例 #3
0
 def test_two_too_many_values(self):
     self.assertMismatchWithDescriptionMatching(
         [1, 2, 3, 4], MatchesSetwise(Equals(1), Equals(2)),
         MatchesRegex(r'There were 2 values left over: \[[34], [34]\]'))
コード例 #4
0
 def test_update_none(self):
     self.assertThat(
         self.SimpleClass(1, 2),
         MatchesStructure(x=Equals(1), z=NotEquals(42)).update(z=None))
コード例 #5
0
 def test_mismatches(self):
     self.assertMismatchWithDescriptionMatching(
         [2, 3], MatchesSetwise(Equals(1), Equals(2)),
         MatchesRegex('.*There was 1 mismatch$', re.S))
コード例 #6
0
    def test_happy(self):
        """
        Test printing of some well-known state
        """

        author = create_local_author("zara")
        magic_path = FilePath(self.mktemp())
        magic_path.makedirs()
        config = self.global_config.create_magic_folder(
            name="test",
            magic_path=magic_path,
            author=author,
            collective_dircap=Capability.from_string("URI:DIR2:hz46fi2e7gy6i3h4zveznrdr5q:i7yc4dp33y4jzvpe5jlaqyjxq7ee7qj2scouolumrfa6c7prgkvq"),
            upload_dircap=Capability.from_string("URI:DIR2:hnua3xva2meb46dqm3ndmiqxhe:h7l2qnydoztv7gruwd65xtdhsvd3cm2kk2544knp5fhmzxoyckba"),
            poll_interval=1,
            scan_interval=1,
        )
        config.store_local_snapshot(
            LocalSnapshot(
                "foo",
                author,
                {},
                config.magic_path.child("foo"),
                parents_local=[],
                parents_remote=[],
            ),
            get_pathinfo(config.magic_path.child("foo")).state,
        )
        config.store_downloaded_snapshot(
            "bar",
            RemoteSnapshot(
                "bar",
                author,
                {"modification_time": 0},
                capability=Capability.from_string("URI:DIR2-CHK:l7b3rn6pha6c2ipbbo4yxvunvy:c6ppejrkip4cdfo3kmyju36qbb6bbptzhh3pno7jb5b5myzoxkja:1:5:329"),
                parents_raw=[],
                content_cap=random_immutable(),
                metadata_cap=random_immutable(),
            ),
            PathState(
                0,
                0,
                0,
            ),
        )

        # we've set up some particular, well-known state in our
        # configuration; now we exercise the dump-state subcommand and
        # ensure the output matches
        options = MagicFolderApiCommand()
        options.stdout = StringIO()
        options.stderr = StringIO()
        options.parseOptions([
            "--config", self.magic_config.path,
            "dump-state",
            "--folder", "test",
        ])
        options._config = self.global_config
        yield run_magic_folder_api_options(options)

        self.assertThat(
            options.stderr.getvalue(),
            Equals("")
        )
        stdout_lines_no_whitespace = [
            line.strip()
            for line in options.stdout.getvalue().splitlines()
        ]

        local_uuid = config.get_local_snapshot("foo").identifier

        self.assertThat(
            stdout_lines_no_whitespace,
            Equals([
                config.name,
                "author: zara {}".format(author.signing_key.verify_key.encode(encoder=HexEncoder).decode("utf8")),
                "stash_path: {}".format(config.stash_path.path),
                "magic_path: {}".format(config.magic_path.path),
                "collective: URI:DIR2:hz46fi2e7gy6i3h4zveznrdr5q:i7yc4dp33y4jzvpe5jlaqyjxq7ee7qj2scouolumrfa6c7prgkvq",
                "local snapshots:",
                "foo: {}".format(local_uuid),
                "remote snapshots:",
                "bar:",
                "cap: URI:DIR2-CHK:l7b3rn6pha6c2ipbbo4yxvunvy:c6ppejrkip4cdfo3kmyju36qbb6bbptzhh3pno7jb5b5myzoxkja:1:5:329",
                "mtime: 0",
                "size: 0",
            ])
        )
コード例 #7
0
 def test_maps_and_sets_differ(self):
     """
     Mappings hash to different values than frozensets of their iteritems().
     """
     self.assertThat(generation_hash(frozenset([('a', 1), ('b', 2)])),
                     Not(Equals(generation_hash(dict(a=1, b=2)))))
コード例 #8
0
ファイル: test_lbsh.py プロジェクト: stephamon/otter
    def test_only_autoscale_nodes_are_modified(self):
        """
        Autoscale only self-heals the nodes that it added, without touching
        any other nodes.  Assuming 1 CLB:
        1. Create two non-autoscaled servers and add them to the CLB.
        2. Wait for all servers to be on the CLB
        3. Create a scaling group with said CLB and 1 server
        4. Wait for AS server to be active and on the CLB.
        4. Delete autoscaled server and 1 non-autoscaled server from the CLB
        5. Converge
        6. Assert that the autoscaled server is put back on the CLB, the
           non-autoscaled server is left off the CLB, and the untouched
           non-autoscaled server is left on the CLB.
        """
        clb = self.helper.clbs[0]

        nodes = yield clb.list_nodes(self.rcs)
        self.assertEqual(len(nodes['nodes']), 0,
                         "There should be no nodes on the CLB yet.")

        # create the other two non-autoscaled servers - just wait until they
        # have servicenet addresses - don't bother waiting for them to be
        # active, which will take too long
        other_servers = yield self.helper.create_servers(
            self.rcs,
            2,
            wait_for=ContainsDict({
                "addresses":
                ContainsDict({
                    'private':
                    MatchesSetwise(
                        ContainsDict({"addr": MatchesRegex("(\d+\.){3}\d+")}))
                })
            }))
        # add non-autoscaled servers to the CLB
        clb_response = yield clb.add_nodes(
            self.rcs, [{
                'address': server['addresses']['private'][0]['addr'],
                'port': 8080,
                'condition': "ENABLED"
            } for server in other_servers])
        remove_non_as_node, untouch_non_as_node = clb_response['nodes']

        # set up the group and get the group's server's CLB node
        group, _ = self.helper.create_group(min_entities=1)
        yield self.helper.start_group_and_wait(group, self.rcs)

        # Should be 3 nodes now that all servers are added
        nodes = yield clb.wait_for_nodes(self.rcs,
                                         HasLength(3),
                                         timeout=timeout_default)
        as_node = [
            node for node in nodes
            if node not in (remove_non_as_node, untouch_non_as_node)
        ][0]

        # delete 1 autoscale node and 1 non-autoscale node
        yield clb.delete_nodes(self.rcs,
                               [as_node['id'], remove_non_as_node['id']])
        # There should be 1 node left
        yield clb.wait_for_nodes(self.rcs,
                                 HasLength(1),
                                 timeout=timeout_default)

        yield group.trigger_convergence(self.rcs)

        yield clb.wait_for_nodes(
            self.rcs,
            MatchesSetwise(  # means there are only these two nodes and no more
                # the untouched node should remain exactly the same
                Equals(untouch_non_as_node),
                # the AS node should have the same paramters, but not the same
                # ID since it was re-added
                ContainsDict({
                    k: Equals(v)
                    for k, v in as_node.items()
                    if k in ('address', 'port', 'weight'
                             'type', 'condition')
                })),
            timeout=timeout_default)
コード例 #9
0
ファイル: test_lbsh.py プロジェクト: stephamon/otter
    def test_convergence_heals_two_groups_on_same_clb(self):
        """
        Autoscale puts a server back on the desired CLB, not touching any other
        autoscale servers on the same CLB.

        1. Create 2 AS groups on the same CLB, both with min 1 server,
           each group mapped to different ports
        2. Add group1's server to the CLB on group2's port and remove it from
           group1's port.
        3. Converge both groups.
        4. Group1's servers will be put back in group1's port but not removed
           from group2's port. group2 and its clb port will not be touched
        """
        clb = self.helper.clbs[0]
        group1, _ = self.helper.create_group(
            min_entities=1, use_lbs=[clb.scaling_group_spec(80)])
        group2, _ = self.helper.create_group(
            min_entities=1, use_lbs=[clb.scaling_group_spec(8080)])

        yield gatherResults([
            self.helper.start_group_and_wait(group, self.rcs)
            for group in (group1, group2)
        ])

        # assert that they're both on the CLB on the right ports
        groups = yield gatherResults(
            [group.get_servicenet_ips(self.rcs) for group in (group1, group2)])
        group1_ip, group2_ip = [g.values()[0] for g in groups]
        expected_nodes = [
            ContainsDict({
                'port': Equals(80),
                'address': Equals(group1_ip)
            }),
            ContainsDict({
                'port': Equals(8080),
                'address': Equals(group1_ip)
            }),
            ContainsDict({
                'port': Equals(8080),
                'address': Equals(group2_ip)
            })
        ]
        nodes = yield clb.wait_for_nodes(self.rcs,
                                         MatchesSetwise(
                                             expected_nodes[0],
                                             expected_nodes[2]),
                                         timeout=timeout_default)

        # add/remove another node
        perturb = [
            clb.add_nodes(self.rcs, [{
                'address': group1_ip,
                'port': 8080,
                'condition': 'ENABLED',
                'type': 'PRIMARY'
            }]),
            clb.delete_nodes(
                self.rcs,
                [n['id'] for n in nodes if n['address'] == group1_ip])
        ]
        yield gatherResults(perturb)
        yield clb.wait_for_nodes(self.rcs,
                                 MatchesSetwise(*expected_nodes[1:]),
                                 timeout=timeout_default)

        # Trigger convergence on both groups
        yield gatherResults([
            group.trigger_convergence(self.rcs) for group in (group1, group2)
        ])

        # Group1 server be back and group2 will have both
        yield clb.wait_for_nodes(self.rcs,
                                 MatchesSetwise(*expected_nodes),
                                 timeout=timeout_default)
コード例 #10
0
ファイル: test_collaborators.py プロジェクト: snshn/snapcraft
    def test_collaborators_without_snap_name_must_error(self):
        result = self.run_command([self.command_name])

        self.assertThat(result.exit_code, Equals(2))
        self.assertThat(result.output, Contains("Usage:"))
コード例 #11
0
ファイル: test_parallel.py プロジェクト: casual-lemon/maas
 def test_subprocess_per_core_can_be_specified(self):
     sysexit = self.assertRaises(SystemExit, parallel.main,
                                 ["--subprocess-per-core"])
     self.assertThat(sysexit.code, Equals(0))
     self.assertThat(parallel.test,
                     MockCalledOnceWith(ANY, ANY, os.cpu_count()))
コード例 #12
0
ファイル: test_avahi.py プロジェクト: sydneypdx/maas
 def test_converts_escaped_dot(self):
     result = unescape_avahi_service_name("example\\.com")
     self.assertThat(result, Equals("example.com"))
コード例 #13
0
ファイル: test_avahi.py プロジェクト: sydneypdx/maas
 def test_converts_escaped_backslash(self):
     result = unescape_avahi_service_name("\\\\\\\\samba\\\\share")
     self.assertThat(result, Equals("\\\\samba\\share"))
コード例 #14
0
ファイル: test_avahi.py プロジェクト: sydneypdx/maas
 def test_converts_escaped_decimal_characters(self):
     result = unescape_avahi_service_name(
         "HP\\032Color\\032LaserJet\\032CP2025dn\\032\\040test\\041")
     self.assertThat(result, Equals("HP Color LaserJet CP2025dn (test)"))
コード例 #15
0
 def test_list_users(self):
     dbaas.MySqlAdmin.list_users = MagicMock(return_value=['user1'])
     users = self.manager.list_users(self.context)
     self.assertThat(users, Equals(['user1']))
     dbaas.MySqlAdmin.list_users.assert_any_call(None, None, False)
コード例 #16
0
 def assert_time_difference(earlier_inst_index, later_inst_index):
     td = instances_and_visit_times[later_inst_index][1] - \
         instances_and_visit_times[earlier_inst_index][1]
     self.assertThat(td, MatchesAny(Equals(1), GreaterThan(1)))
コード例 #17
0
    def test_api_error(self):
        """
        An error is reported if the API reports an error
        """
        stdout = StringIO()
        stderr = StringIO()

        basedir = FilePath(self.mktemp())
        global_config = create_global_configuration(
            basedir,
            "tcp:-1",
            FilePath(u"/no/tahoe/node-directory"),
            "tcp:127.0.0.1:-1",
        )

        # 2-tuples of "expected request" and the corresponding reply
        request_sequence = RequestSequence([
            # ((method, url, params, headers, data), (code, headers, body)),
            (
                (b"post",
                 self.url.child("magic-folder", "default", "snapshot").to_text(),
                 {b"path": [b"foo"]},
                 {
                     b'Host': [b'invalid.'],
                     b'Content-Length': [b'0'],
                     b'Connection': [b'close'],
                     b'Authorization': [b'Bearer ' + global_config.api_token],
                     b'Accept-Encoding': [b'gzip']
                 },
                 b""),
                (406, {}, b'{"reason": "an explanation"}')
            ),
        ])
        http_client = StubTreq(
            StringStubbingResource(
                request_sequence,
            )
        )
        client = create_magic_folder_client(
            Clock(),
            global_config,
            http_client,
        )

        with self.assertRaises(SystemExit):
            with request_sequence.consume(self.fail):
                yield dispatch_magic_folder_api_command(
                    ["--config", basedir.path, "add-snapshot",
                     "--file", "foo",
                     "--folder", "default"],
                    stdout=stdout,
                    stderr=stderr,
                    client=client,
                )
        self.assertThat(
            stdout.getvalue().strip(),
            Equals("")
        )
        self.assertThat(
            json.loads(stderr.getvalue()),
            Equals({"reason": "an explanation"})
        )
コード例 #18
0
    def test_user_agent_darwin(self):
        arch = ProjectOptions().deb_arch
        expected = f"snapcraft/{snapcraft_version} Darwin ({arch})"

        self.expectThat(agent.get_user_agent(platform="darwin"),
                        Equals(expected))
コード例 #19
0
    def XXXtest_add_participant(self):
        """
        A new participant is added to a magic-folder
        """
        stdout = StringIO()
        stderr = StringIO()

        # 2-tuples of "expected request" and the corresponding reply
        request_sequence = RequestSequence([
            # ((method, url, params, headers, data), (code, headers, body)),
            (
                # expected request
                (b"post",
                 self.url.child("magic-folder", "default", "participants").to_text(),
                 {},
                 {
                     b'Host': [b'invalid.'],
                     b'Content-Length': [b'149'],
                     b'Connection': [b'close'],
                     b'Authorization': [b'Bearer ' + self.global_config.api_token],
                     b'Accept-Encoding': [b'gzip']
                 },
                 # XXX args, this fails because of different sorting of keys in body serialization
                 json.dumps({
                     "personal_dmd": "URI:DIR2-CHK:lq34kr5sp7mnvkhce4ahl2nw4m:dpujdl7sol6xih5gzil525tormolzaucq4re7snn5belv7wzsdha:1:5:328",
                     "author": {
                         "name": "amaya",
                     }
                 }).encode("utf8"),
                ),
                # expected response
                (200, {}, b"{}"),
            ),
        ])
        http_client = StubTreq(
            StringStubbingResource(
                request_sequence,
            )
        )
        client = create_magic_folder_client(
            Clock(),
            self.global_config,
            http_client,
        )
        with request_sequence.consume(self.fail):
            yield dispatch_magic_folder_api_command(
                ["--config", self.magic_config.path, "add-participant",
                 "--folder", "default",
                 "--author-name", "amaya",
                 "--personal-dmd", 'URI:DIR2-CHK:lq34kr5sp7mnvkhce4ahl2nw4m:dpujdl7sol6xih5gzil525tormolzaucq4re7snn5belv7wzsdha:1:5:328',
                ],
                stdout=stdout,
                stderr=stderr,
                client=client,
            )
        self.assertThat(
            stdout.getvalue().strip(),
            Equals("{}")
        )
        self.assertThat(
            stderr.getvalue().strip(),
            Equals("")
        )
コード例 #20
0
ファイル: test_python.py プロジェクト: hsbt/snapcraft
    def test_plugin_stage_packages_python3(self):
        self.options.python_version = "python3"

        plugin = python.PythonPlugin("test-part", self.options, self.project)
        self.assertThat(plugin.plugin_stage_packages, Equals(["python3"]))
コード例 #21
0
 def test_strings_and_jsonable_types_differ(self):
     """
     Strings and integers hash to different values.
     """
     self.assertThat(generation_hash(5), Not(Equals(generation_hash('5'))))
コード例 #22
0
ファイル: test_upload.py プロジェクト: ycheng/snapcraft
    def test_upload_nonexisting_snap_must_raise_exception(self):
        result = self.run_command(["upload", "test-unexisting-snap"])

        self.assertThat(result.exit_code, Equals(2))
コード例 #23
0
 def test_matches(self):
     self.assertIs(None, MatchesSetwise(Equals(1), Equals(2)).match([2, 1]))
コード例 #24
0
ファイル: test_upload.py プロジェクト: ycheng/snapcraft
    def test_upload_without_snap_must_raise_exception(self):
        result = self.run_command(["upload"])

        self.assertThat(result.exit_code, Equals(2))
        self.assertThat(result.output, Contains("Usage:"))
コード例 #25
0
 def test_too_many_matchers(self):
     self.assertMismatchWithDescriptionMatching(
         [2, 3], MatchesSetwise(Equals(1), Equals(2), Equals(3)),
         Equals('There was 1 matcher left over: Equals(1)'))
コード例 #26
0
 def test_error_formatting(self):
     self.assertThat(str(self.exception(**self.kwargs)),
                     Equals(self.expected_message))
コード例 #27
0
 def test_two_too_many_matchers(self):
     self.assertMismatchWithDescriptionMatching(
         [3], MatchesSetwise(Equals(1), Equals(2), Equals(3)),
         MatchesRegex(r'There were 2 matchers left over: Equals\([12]\), '
                      r'Equals\([12]\)'))
コード例 #28
0
 def test_list_databases(self):
     dbaas.MySqlAdmin.list_databases = MagicMock(return_value=['database1'])
     databases = self.manager.list_databases(self.context)
     self.assertThat(databases, Not(Is(None)))
     self.assertThat(databases, Equals(['database1']))
     dbaas.MySqlAdmin.list_databases.assert_any_call(None, None, False)
コード例 #29
0
 def test_mismatch_and_too_many_matchers(self):
     self.assertMismatchWithDescriptionMatching(
         [2, 3], MatchesSetwise(Equals(0), Equals(1), Equals(2)),
         MatchesRegex(
             r'.*There was 1 mismatch and 1 extra matcher: Equals\([01]\)',
             re.S))
コード例 #30
0
ファイル: __init__.py プロジェクト: rickspencer3/GetThereDC
    def setUp(self):
        super(ClickAppTestCase, self).setUp()
        self.pointing_device = input.Pointer(self.input_device_class.create())
        self.launch_application()

        self.assertThat(self.main_view.visible, Eventually(Equals(True)))