Python testtools.matchers.Contains() Examples

The following are 30 code examples of testtools.matchers.Contains(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module testtools.matchers , or try the search function .
Example #1
Source File: test_leases.py    From maas with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_skips_dns_record_for_coerced_hostname_from_existing_node(self):
        subnet = factory.make_ipv4_Subnet_with_IPRanges(
            with_static_range=False, dhcp_on=True
        )
        dynamic_range = subnet.get_dynamic_ranges()[0]
        ip = factory.pick_ip_in_IPRange(dynamic_range)
        hostname = "gaming device"
        factory.make_Node(hostname="gaming-device")
        kwargs = self.make_kwargs(action="commit", ip=ip, hostname=hostname)
        update_lease(**kwargs)
        unknown_interface = UnknownInterface.objects.filter(
            mac_address=kwargs["mac"]
        ).first()
        self.assertIsNotNone(unknown_interface)
        self.assertEquals(subnet.vlan, unknown_interface.vlan)
        sip = unknown_interface.ip_addresses.first()
        self.assertIsNotNone(sip)
        self.assertThat(sip.dnsresource_set.all(), Not(Contains(sip))) 
Example #2
Source File: test_actions.py    From maas with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_bind_write_configuration_writes_file_with_acl(self):
        trusted_networks = [
            factory.make_ipv4_network(),
            factory.make_ipv6_network(),
        ]
        actions.bind_write_configuration(
            zones=[], trusted_networks=trusted_networks
        )
        expected_file = os.path.join(self.dns_conf_dir, MAAS_NAMED_CONF_NAME)
        self.assertThat(expected_file, FileExists())
        expected_content = dedent(
            """\
        acl "trusted" {
            %s;
            %s;
            localnets;
            localhost;
        };
        """
        )
        expected_content %= tuple(trusted_networks)
        self.assertThat(
            expected_file, FileContains(matcher=Contains(expected_content))
        ) 
Example #3
Source File: test_edit_named_options.py    From maas with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_normal_operation(self):
        options_file = self.make_file(contents=OPTIONS_FILE)
        self.run_command("--config-path", options_file)
        expected_path = os.path.join(
            os.path.dirname(options_file),
            "maas",
            MAAS_NAMED_CONF_OPTIONS_INSIDE_NAME,
        )

        # Check that the file was re-written with the include statement.
        options = read_isc_file(options_file)
        self.assertThat(
            make_isc_string(options), Contains('include "%s";' % expected_path)
        )

        # Check that the backup was made.
        options_file_base = os.path.dirname(options_file)
        files = os.listdir(options_file_base)
        self.assertEqual(2, len(files))
        files.remove(os.path.basename(options_file))
        [backup_file] = files
        backup_file = os.path.join(options_file_base, backup_file)
        self.assertThat(backup_file, FileContains(OPTIONS_FILE)) 
Example #4
Source File: test_views.py    From maas with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_handle_uncaught_exception_does_not_note_other_failure(self):
        handler = views.WebApplicationHandler()
        request = make_request()
        request.path = factory.make_name("path")
        failure_type = factory.make_exception_type()
        failure = failure_type, failure_type(), None
        response = handler.handle_uncaught_exception(
            request=request,
            resolver=get_resolver(None),
            exc_info=failure,
            reraise=False,
        )
        # HTTP 500 is returned...
        self.expectThat(
            response.status_code, Equals(http.client.INTERNAL_SERVER_ERROR)
        )
        # ... but the response is NOT recorded as needing a retry.
        self.expectThat(
            handler._WebApplicationHandler__retry, Not(Contains(response))
        ) 
Example #5
Source File: test_views.py    From maas with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_handle_uncaught_exception_notes_serialization_failure(self):
        handler = views.WebApplicationHandler()
        request = make_request()
        request.path = factory.make_name("path")
        failure = self.capture_serialization_failure()
        response = handler.handle_uncaught_exception(
            request=request,
            resolver=get_resolver(None),
            exc_info=failure,
            reraise=False,
        )
        # HTTP 409 is returned...
        self.expectThat(response.status_code, Equals(http.client.CONFLICT))
        # ... and the response is recorded as needing a retry.
        self.expectThat(
            handler._WebApplicationHandler__retry, Contains(response)
        ) 
Example #6
Source File: test_config.py    From maas with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_no_write_local(self):
        config.write_config(False)
        matcher_one = Not(
            Contains(':fromhost-ip, !isequal, "127.0.0.1" ?MAASenlist')
        )
        matcher_two = Not(
            Contains(':fromhost-ip, !isequal, "127.0.0.1" ?MAASboot')
        )
        # maas.log is still local when no write local.
        matcher_three = Contains(':syslogtag, contains, "maas"')
        self.assertThat(
            "%s/%s" % (self.tmpdir, config.MAAS_SYSLOG_CONF_NAME),
            FileContains(
                matcher=MatchesAll(matcher_one, matcher_two, matcher_three)
            ),
        ) 
Example #7
Source File: test_bindfixture.py    From maas with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_setUp_creates_config_files(self):
        with BINDServerResources() as resources:
            self.assertThat(
                resources.conf_file,
                FileContains(
                    matcher=Contains(b"listen-on port %d" % resources.port)
                ),
            )
            self.assertThat(
                resources.rndcconf_file,
                FileContains(
                    matcher=Contains(
                        b"default-port %d" % (resources.rndc_port)
                    )
                ),
            )
            # This should ideally be in its own test but it's here to cut
            # test run time. See test_setUp_honours_include_in_options()
            # as its counterpart.
            self.assertThat(
                resources.conf_file,
                Not(FileContains(matcher=Contains("forwarders"))),
            ) 
Example #8
Source File: test_ipmi.py    From maas with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_finds_power_address_from_mac_address(self):
        context = make_context()
        driver = IPMIPowerDriver()
        ip_address = factory.make_ipv4_address()
        find_ip_via_arp = self.patch(ipmi_module, "find_ip_via_arp")
        find_ip_via_arp.return_value = ip_address
        power_change = random.choice(("on", "off"))

        context["mac_address"] = factory.make_mac_address()
        context["power_address"] = random.choice((None, "", "   "))

        self.patch_autospec(driver, "_issue_ipmipower_command")
        driver._issue_ipmi_command(power_change, **context)

        # The IP address is passed to _issue_ipmipower_command.
        self.assertThat(
            driver._issue_ipmipower_command,
            MockCalledOnceWith(ANY, power_change, ip_address),
        )
        # The IP address is also within the command passed to
        # _issue_ipmipower_command.
        self.assertThat(
            driver._issue_ipmipower_command.call_args[0], Contains(ip_address)
        ) 
Example #9
Source File: test_leases.py    From maas with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_creates_dns_record_for_hostname(self):
        subnet = factory.make_ipv4_Subnet_with_IPRanges(
            with_static_range=False, dhcp_on=True
        )
        dynamic_range = subnet.get_dynamic_ranges()[0]
        ip = factory.pick_ip_in_IPRange(dynamic_range)
        hostname = factory.make_name().lower()
        kwargs = self.make_kwargs(action="commit", ip=ip, hostname=hostname)
        update_lease(**kwargs)
        unknown_interface = UnknownInterface.objects.filter(
            mac_address=kwargs["mac"]
        ).first()
        self.assertIsNotNone(unknown_interface)
        self.assertEquals(subnet.vlan, unknown_interface.vlan)
        sip = unknown_interface.ip_addresses.first()
        self.assertIsNotNone(sip)
        dnsrr = get_one(DNSResource.objects.filter(name=hostname))
        self.assertThat(sip.dnsresource_set.all(), Contains(dnsrr)) 
Example #10
Source File: test_leases.py    From maas with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_skips_dns_record_for_hostname_from_existing_node(self):
        subnet = factory.make_ipv4_Subnet_with_IPRanges(
            with_static_range=False, dhcp_on=True
        )
        dynamic_range = subnet.get_dynamic_ranges()[0]
        ip = factory.pick_ip_in_IPRange(dynamic_range)
        hostname = factory.make_name().lower()
        factory.make_Node(hostname=hostname)
        kwargs = self.make_kwargs(action="commit", ip=ip, hostname=hostname)
        update_lease(**kwargs)
        unknown_interface = UnknownInterface.objects.filter(
            mac_address=kwargs["mac"]
        ).first()
        self.assertIsNotNone(unknown_interface)
        self.assertEquals(subnet.vlan, unknown_interface.vlan)
        sip = unknown_interface.ip_addresses.first()
        self.assertIsNotNone(sip)
        self.assertThat(sip.dnsresource_set.all(), Not(Contains(sip))) 
Example #11
Source File: test_commands_edit_named_options.py    From maas with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_normal_operation(self):
        options_file = self.make_file(contents=OPTIONS_FILE)
        call_command(
            "edit_named_options", config_path=options_file, stdout=self.stdout
        )
        expected_path = os.path.join(
            os.path.dirname(options_file),
            "maas",
            MAAS_NAMED_CONF_OPTIONS_INSIDE_NAME,
        )

        # Check that the file was re-written with the include statement.
        options = read_isc_file(options_file)
        self.assertThat(
            make_isc_string(options), Contains('include "%s";' % expected_path)
        )

        # Check that the backup was made.
        options_file_base = os.path.dirname(options_file)
        files = os.listdir(options_file_base)
        self.assertEqual(2, len(files))
        files.remove(os.path.basename(options_file))
        [backup_file] = files
        backup_file = os.path.join(options_file_base, backup_file)
        self.assertThat(backup_file, FileContains(OPTIONS_FILE)) 
Example #12
Source File: test_role_assignment.py    From shade with Apache License 2.0 6 votes vote down vote up
def _build_role_assignment_response(self, role_id, scope_type, scope_id,
                                        entity_type, entity_id):
        self.assertThat(['group', 'user'], matchers.Contains(entity_type))
        self.assertThat(['project', 'domain'], matchers.Contains(scope_type))
        # NOTE(notmorgan): Links are thrown out by shade, but we construct them
        # for corectness.
        link_str = ('https://identity.example.com/identity/v3/{scope_t}s'
                    '/{scopeid}/{entity_t}s/{entityid}/roles/{roleid}')
        return [{
            'links': {'assignment': link_str.format(
                scope_t=scope_type, scopeid=scope_id, entity_t=entity_type,
                entityid=entity_id, roleid=role_id)},
            'role': {'id': role_id},
            'scope': {scope_type: {'id': scope_id}},
            entity_type: {'id': entity_id}
        }] 
Example #13
Source File: test_role_assignment.py    From openstacksdk with Apache License 2.0 6 votes vote down vote up
def _build_role_assignment_response(self, role_id, scope_type, scope_id,
                                        entity_type, entity_id):
        self.assertThat(['group', 'user'], matchers.Contains(entity_type))
        self.assertThat(['project', 'domain'], matchers.Contains(scope_type))
        # NOTE(notmorgan): Links are thrown out by shade, but we construct them
        # for corectness.
        link_str = ('https://identity.example.com/identity/v3/{scope_t}s'
                    '/{scopeid}/{entity_t}s/{entityid}/roles/{roleid}')
        return [{
            'links': {'assignment': link_str.format(
                scope_t=scope_type, scopeid=scope_id, entity_t=entity_type,
                entityid=entity_id, roleid=role_id)},
            'role': {'id': role_id},
            'scope': {scope_type: {'id': scope_id}},
            entity_type: {'id': entity_id}
        }] 
Example #14
Source File: test_release.py    From flocker with Apache License 2.0 6 votes vote down vote up
def test_run(self):
        """
        The script creates a new release version branch in a new working
        directory and prints some shell commands to ``stdout``.
        """
        expected_version = "9.9.9"
        script_path = self.make_temporary_directory()
        repo_path = script_path.sibling(
            'flocker-release-{}'.format(expected_version)
        )
        result = run_process(
            [INITIALIZE_RELEASE_PATH.path,
             '--flocker-version={}'.format(expected_version)],
            cwd=script_path.path
        )
        self.expectThat(result.status, Equals(0))
        self.expectThat(
            result.output,
            Contains('export VERSION={}'.format(expected_version))
        )
        self.expectThat(
            Repo(path=repo_path.path).active_branch.name,
            Equals('release/flocker-{}'.format(expected_version))
        ) 
Example #15
Source File: test_proxyconfig.py    From maas with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_only_enabled_subnets_are_present(self):
        self.patch(settings, "PROXY_CONNECT", True)
        disabled = yield deferToDatabase(self.make_subnet, allow_proxy=False)
        enabled = yield deferToDatabase(self.make_subnet)
        yield proxyconfig.proxy_update_config(reload_proxy=False)
        # enabled's cidr must be present
        matcher = Contains("acl localnet src %s" % enabled.cidr)
        self.assertThat(
            "%s/%s" % (self.tmpdir, config.MAAS_PROXY_CONF_NAME),
            FileContains(matcher=matcher),
        )
        # disabled's cidr must not be present
        matcher = Not(Contains("acl localnet src %s" % disabled.cidr))
        self.assertThat(
            "%s/%s" % (self.tmpdir, config.MAAS_PROXY_CONF_NAME),
            FileContains(matcher=matcher),
        ) 
Example #16
Source File: test_machines.py    From maas with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_POST_allocate_allocates_machine_by_interfaces(self):
        """Interface label is returned alongside machine data"""
        fabric = factory.make_Fabric("ubuntu")
        # The ID may always be '1', which won't be interesting for testing.
        for _ in range(1, random.choice([1, 3, 5])):
            factory.make_Interface()
        machine = factory.make_Node_with_Interface_on_Subnet(
            status=NODE_STATUS.READY, fabric=fabric
        )
        iface = machine.get_boot_interface()
        response = self.client.post(
            reverse("machines_handler"),
            {"op": "allocate", "interfaces": "needed:fabric=ubuntu"},
        )
        self.assertThat(response, HasStatusCode(http.client.OK))
        response_json = json.loads(
            response.content.decode(settings.DEFAULT_CHARSET)
        )
        self.expectThat(response_json["status"], Equals(NODE_STATUS.ALLOCATED))
        constraints = response_json["constraints_by_type"]
        self.expectThat(constraints, Contains("interfaces"))
        interfaces = constraints.get("interfaces")
        self.expectThat(interfaces, Contains("needed"))
        self.expectThat(interfaces["needed"], Contains(iface.id))
        self.expectThat(constraints, Not(Contains("verbose_interfaces"))) 
Example #17
Source File: test_machines.py    From maas with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_POST_allocate_allocates_machine_by_storage(self):
        """Storage label is returned alongside machine data"""
        machine = factory.make_Node(
            status=NODE_STATUS.READY, with_boot_disk=False
        )
        factory.make_PhysicalBlockDevice(
            node=machine,
            size=11 * (1000 ** 3),
            tags=["ssd"],
            formatted_root=True,
        )
        response = self.client.post(
            reverse("machines_handler"),
            {"op": "allocate", "storage": "needed:10(ssd)"},
        )
        self.assertThat(response, HasStatusCode(http.client.OK))
        response_json = json.loads(
            response.content.decode(settings.DEFAULT_CHARSET)
        )
        device_id = response_json["physicalblockdevice_set"][0]["id"]
        constraints = response_json["constraints_by_type"]
        self.expectThat(constraints, Contains("storage"))
        self.expectThat(constraints["storage"], Contains("needed"))
        self.expectThat(constraints["storage"]["needed"], Contains(device_id))
        self.expectThat(constraints, Not(Contains("verbose_storage"))) 
Example #18
Source File: test_vlan.py    From maas with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_configure_dhcp_optionally_creates_iprange(self):
        user = factory.make_admin()
        handler = VLANHandler(user, {}, None)
        vlan = factory.make_VLAN()
        rack = factory.make_RackController()
        factory.make_Interface(INTERFACE_TYPE.PHYSICAL, node=rack, vlan=vlan)
        subnet = factory.make_Subnet(
            vlan=vlan, cidr="10.0.0.0/24", gateway_ip=""
        )
        self.assertThat(subnet.get_dynamic_ranges().count(), Equals(0))
        handler.configure_dhcp(
            {
                "id": vlan.id,
                "controllers": [rack.system_id],
                "extra": {
                    "subnet": subnet.id,
                    "start": "10.0.0.2",
                    "end": "10.0.0.99",
                },
            }
        )
        vlan = reload_object(vlan)
        subnet = reload_object(subnet)
        self.assertThat(vlan.dhcp_on, Equals(True))
        self.assertThat(vlan.primary_rack, Equals(rack))
        self.assertThat(subnet.get_dynamic_ranges().count(), Equals(1))
        dynamic_range = subnet.get_dynamic_ranges().first()
        self.assertThat(dynamic_range.start_ip, Equals("10.0.0.2"))
        self.assertThat(dynamic_range.end_ip, Equals("10.0.0.99"))
        self.assertThat(dynamic_range.type, Equals("dynamic"))
        self.assertThat(dynamic_range.user_id, Equals(user.id))
        self.assertThat(dynamic_range.comment, Contains("Web UI")) 
Example #19
Source File: test_commands_edit_named_options.py    From maas with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_remove_existing_forwarders_config(self):
        options_file = self.make_file(contents=OPTIONS_FILE_WITH_FORWARDERS)
        call_command(
            "edit_named_options", config_path=options_file, stdout=self.stdout
        )

        options = read_isc_file(options_file)
        self.assertThat(make_isc_string(options), Not(Contains("forwarders"))) 
Example #20
Source File: test_commands_edit_named_options.py    From maas with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_removes_existing_dnssec_validation_config_if_migration_set(self):
        options_file = self.make_file(contents=OPTIONS_FILE_WITH_DNSSEC)
        call_command(
            "edit_named_options",
            config_path=options_file,
            migrate_conflicting_options=True,
            stdout=self.stdout,
        )

        # Check that the file was re-written without dnssec-validation (since
        # that's now in the included file).
        options = read_isc_file(options_file)
        self.assertThat(
            make_isc_string(options), Not(Contains("dnssec-validation"))
        ) 
Example #21
Source File: test_commands_edit_named_options.py    From maas with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_removes_existing_forwarders_config_if_migrate_set(self):
        options_file = self.make_file(contents=OPTIONS_FILE_WITH_FORWARDERS)
        call_command(
            "edit_named_options",
            config_path=options_file,
            migrate_conflicting_options=True,
            stdout=self.stdout,
        )

        # Check that the file was re-written without forwarders (since
        # that's now in the included file).
        options = read_isc_file(options_file)
        self.assertThat(make_isc_string(options), Not(Contains("forwarders"))) 
Example #22
Source File: test_dnsresource.py    From maas with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_adds_new_hostname(self):
        sip = factory.make_StaticIPAddress(
            ip="10.0.0.1", alloc_type=IPADDRESS_TYPE.DISCOVERED
        )
        hostname = factory.make_name().lower()
        DNSResource.objects.update_dynamic_hostname(sip, hostname)
        dnsrr = DNSResource.objects.get(name=hostname)
        self.assertThat(dnsrr.ip_addresses.all(), Contains(sip)) 
Example #23
Source File: test_dnsresource.py    From maas with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_update_releases_obsolete_hostnames(self):
        sip = factory.make_StaticIPAddress(
            ip="10.0.0.1", alloc_type=IPADDRESS_TYPE.DISCOVERED
        )
        hostname_old = factory.make_name().lower()
        DNSResource.objects.update_dynamic_hostname(sip, hostname_old)
        hostname_new = factory.make_name().lower()
        DNSResource.objects.update_dynamic_hostname(sip, hostname_new)
        dnsrr = DNSResource.objects.get(name=hostname_new)
        self.assertThat(dnsrr.ip_addresses.all(), Contains(sip))
        self.assertThat(
            DNSResource.objects.filter(name=hostname_old).first(), Equals(None)
        ) 
Example #24
Source File: test_interfaces.py    From maas with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_visited_set_is_thread_local(self):
        thread_local = update_parents_thread_local
        thread_local.visiting.add("a")

        def check_a_does_not_exist():
            self.assertThat(thread_local.visiting, Not(Contains("a")))

        thread = threading.Thread(target=check_a_does_not_exist)
        thread.start()
        thread.join()
        self.assertThat(thread_local.visiting, Contains("a"))
        thread_local.visiting.discard("a") 
Example #25
Source File: test_utils.py    From maas with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_get_maas_user_agent_without_uuid(self):
        user_agent = get_maas_user_agent()
        uuid = Config.objects.get_config("uuid")
        self.assertEqual(uuid, None)
        self.assertThat(user_agent, IsNonEmptyString)
        self.assertThat(user_agent, Not(Contains(uuid))) 
Example #26
Source File: test_subnets.py    From maas with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_accounts_for_reserved_ip_address(self):
        subnet = factory.make_Subnet(dns_servers=[], gateway_ip="")
        ip = factory.pick_ip_in_network(subnet.get_ipnetwork())
        factory.make_StaticIPAddress(
            ip=ip, alloc_type=IPADDRESS_TYPE.AUTO, subnet=subnet
        )
        response = self.client.get(
            get_subnet_uri(subnet), {"op": "reserved_ip_ranges"}
        )
        self.assertEqual(
            http.client.OK,
            response.status_code,
            explain_unexpected_response(http.client.OK, response),
        )
        result = json.loads(response.content.decode(settings.DEFAULT_CHARSET))
        self.assertThat(
            result,
            Contains(
                {
                    "start": ip,
                    "end": ip,
                    "purpose": ["assigned-ip"],
                    "num_addresses": 1,
                }
            ),
        ) 
Example #27
Source File: test_machines.py    From maas with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_POST_allocate_allocates_machine_by_interfaces_with_verbose(self):
        """Interface label is returned alongside machine data"""
        fabric = factory.make_Fabric("ubuntu")
        # The ID may always be '1', which won't be interesting for testing.
        for _ in range(1, random.choice([1, 3, 5])):
            factory.make_Interface()
        factory.make_Node()
        machine = factory.make_Node_with_Interface_on_Subnet(
            status=NODE_STATUS.READY, fabric=fabric
        )
        iface = machine.get_boot_interface()
        response = self.client.post(
            reverse("machines_handler"),
            {
                "op": "allocate",
                "interfaces": "needed:fabric=ubuntu",
                "verbose": "true",
            },
        )
        self.assertThat(response, HasStatusCode(http.client.OK))
        response_json = json.loads(
            response.content.decode(settings.DEFAULT_CHARSET)
        )
        constraints = response_json["constraints_by_type"]
        self.expectThat(constraints, Contains("interfaces"))
        interfaces = constraints.get("interfaces")
        self.expectThat(interfaces, Contains("needed"))
        self.expectThat(interfaces["needed"], Equals([iface.id]))
        verbose_interfaces = constraints.get("verbose_interfaces")
        self.expectThat(
            verbose_interfaces["needed"], Contains(str(machine.id))
        )
        self.expectThat(
            verbose_interfaces["needed"][str(machine.id)], Contains(iface.id)
        ) 
Example #28
Source File: test_machines.py    From maas with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_POST_allocate_machine_by_interfaces_dry_run_with_verbose(self):
        """Interface label is returned alongside machine data"""
        fabric = factory.make_Fabric("ubuntu")
        # The ID may always be '1', which won't be interesting for testing.
        for _ in range(1, random.choice([1, 3, 5])):
            factory.make_Interface()
        machine = factory.make_Node_with_Interface_on_Subnet(
            status=NODE_STATUS.READY, fabric=fabric
        )
        iface = machine.get_boot_interface()
        response = self.client.post(
            reverse("machines_handler"),
            {
                "op": "allocate",
                "interfaces": "needed:fabric=ubuntu",
                "verbose": "true",
                "dry_run": "true",
            },
        )
        self.assertThat(response, HasStatusCode(http.client.OK))
        response_json = json.loads(
            response.content.decode(settings.DEFAULT_CHARSET)
        )
        self.expectThat(response_json["status"], Equals(NODE_STATUS.READY))
        # Check that we still got the verbose constraints output even if
        # it was a dry run.
        constraints = response_json["constraints_by_type"]
        self.expectThat(constraints, Contains("interfaces"))
        interfaces = constraints.get("interfaces")
        self.expectThat(interfaces, Contains("needed"))
        self.expectThat(interfaces["needed"], Contains(iface.id))
        verbose_interfaces = constraints.get("verbose_interfaces")
        self.expectThat(
            verbose_interfaces["needed"], Contains(str(machine.id))
        )
        self.expectThat(
            verbose_interfaces["needed"][str(machine.id)], Contains(iface.id)
        ) 
Example #29
Source File: test_machines.py    From maas with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_POST_allocate_allocates_machine_by_storage_with_verbose(self):
        """Storage label is returned alongside machine data"""
        machine = factory.make_Node(
            status=NODE_STATUS.READY, with_boot_disk=False
        )
        factory.make_PhysicalBlockDevice(
            node=machine,
            size=11 * (1000 ** 3),
            tags=["ssd"],
            formatted_root=True,
        )
        response = self.client.post(
            reverse("machines_handler"),
            {"op": "allocate", "storage": "needed:10(ssd)", "verbose": "true"},
        )
        self.assertThat(response, HasStatusCode(http.client.OK))
        response_json = json.loads(
            response.content.decode(settings.DEFAULT_CHARSET)
        )
        device_id = response_json["physicalblockdevice_set"][0]["id"]
        constraints = response_json["constraints_by_type"]
        self.expectThat(constraints, Contains("storage"))
        self.expectThat(constraints["storage"], Contains("needed"))
        self.expectThat(constraints["storage"]["needed"], Contains(device_id))
        verbose_storage = constraints.get("verbose_storage")
        self.expectThat(verbose_storage, Contains(str(machine.id))) 
Example #30
Source File: test_boot_sources.py    From maas with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_GET_returns_boot_source(self):
        self.become_admin()
        boot_source = factory.make_BootSource()
        response = self.client.get(get_boot_source_uri(boot_source))
        self.assertEqual(http.client.OK, response.status_code)
        returned_boot_source = json_load_bytes(response.content)
        # The returned object contains a 'resource_uri' field.
        self.assertEqual(
            reverse("boot_source_handler", args=[boot_source.id]),
            returned_boot_source["resource_uri"],
        )
        # The other fields are the boot source's fields.
        del returned_boot_source["resource_uri"]
        # JSON loads the keyring_data as a str, but it needs to be bytes.
        returned_boot_source["keyring_data"] = returned_boot_source[
            "keyring_data"
        ].encode("utf-8")
        # All the fields are present.
        self.assertItemsEqual(
            DISPLAYED_BOOTSOURCE_FIELDS, returned_boot_source.keys()
        )
        # Remove created and updated that is handled by django.
        del returned_boot_source["created"]
        del returned_boot_source["updated"]
        self.assertThat(
            boot_source, MatchesStructure.byEquality(**returned_boot_source)
        )
        self.assertThat(
            returned_boot_source["keyring_data"], Not(Contains("<memory at"))
        )