def test_new_requires_all_dhcp_settings_or_none(self): name = factory.make_name('nodegroup') uuid = factory.make_name('uuid') ip = factory.getRandomIPAddress() self.assertRaises( AssertionError, NodeGroup.objects.new, name, uuid, ip, subnet_mask='255.0.0.0')
def test_POST_new_creates_node_with_power_parameters(self): # We're setting power parameters so we disable start_commissioning to # prevent anything from attempting to issue power instructions. self.patch(Node, "start_commissioning") hostname = factory.make_name("hostname") architecture = factory.getRandomChoice(ARCHITECTURE_CHOICES) power_type = POWER_TYPE.IPMI power_parameters = { "power_user": factory.make_name("power-user"), "power_pass": factory.make_name("power-pass"), } response = self.client.post( reverse('nodes_handler'), { 'op': 'new', 'hostname': hostname, 'architecture': architecture, 'mac_addresses': factory.getRandomMACAddress(), 'power_parameters': json.dumps(power_parameters), 'power_type': power_type, }) self.assertEqual(httplib.OK, response.status_code) [node] = Node.objects.filter(hostname=hostname) self.assertEqual(power_parameters, node.power_parameters) self.assertEqual(power_type, node.power_type)
def test_new_stores_dhcp_key_on_nodegroup(self): key = generate_omapi_key() nodegroup = NodeGroup.objects.new( factory.make_name('nodegroup'), factory.make_name('uuid'), factory.getRandomIPAddress(), dhcp_key=key) self.assertEqual(key, nodegroup.dhcp_key)
def test_permanent_error_displayed(self): fault_codes = [ randint(1, 100), randint(101, 200), ] errors = [] for fault in fault_codes: # Create component with getRandomString to be sure # to display all the errors. component = factory.make_name('component') error_message = factory.make_name('error') error = Fault(fault, error_message) errors.append(error) register_persistent_error(component, error_message) links = [ reverse('index'), reverse('node-list'), reverse('prefs'), ] for link in links: response = self.client.get(link) self.assertThat( response.content, ContainsAll( [escape(error.faultString) for error in errors]))
def test_new_assigns_token_and_key_for_worker_user(self): nodegroup = NodeGroup.objects.new( factory.make_name('nodegroup'), factory.make_name('uuid'), factory.getRandomIPAddress()) self.assertIsNotNone(nodegroup.api_token) self.assertIsNotNone(nodegroup.api_key) self.assertEqual(get_worker_user(), nodegroup.api_token.user) self.assertEqual(nodegroup.api_key, nodegroup.api_token.key)
def make_script_name(base_name=None, number=None): """Make up a name for a commissioning script.""" if base_name is None: base_name = 'script' if number is None: number = randint(0, 99) return factory.make_name( '%0.2d-%s' % (number, factory.make_name(base_name)))
def test_ensure_master_returns_oldest_nodegroup(self): first_nodegroup = NodeGroup.objects.new( factory.make_name('nodegroup'), factory.make_name('uuid'), factory.getRandomIPAddress()) NodeGroup.objects.new( factory.make_name('nodegroup'), factory.make_name('uuid'), factory.getRandomIPAddress()) self.assertEqual(first_nodegroup, NodeGroup.objects.ensure_master())
def test_changes_name(self): nodegroup = factory.make_node_group(name=factory.make_name('old-name')) new_name = factory.make_name('new-name') data = self.make_form_data(nodegroup) data['name'] = new_name form = NodeGroupEdit(instance=nodegroup, data=data) self.assertTrue(form.is_valid()) form.save() self.assertEqual(new_name, reload_object(nodegroup).name)
def make_resource(): """ Return a new `OperationsResource` with a `BaseHandler` subclass handler, with a fabricated name and a `resource_uri` class-method. """ name = factory.make_name("handler").encode("ascii") resource_uri = lambda cls: factory.make_name("resource-uri") namespace = {"resource_uri": classmethod(resource_uri)} handler = type(name, (BaseHandler,), namespace) return OperationsResource(handler)
def test_new_creates_nodegroup_with_given_dhcp_settings(self): name = factory.make_name('nodegroup') uuid = factory.make_name('uuid') dhcp_network, dhcp_settings = make_dhcp_settings() ip = factory.getRandomIPInNetwork(dhcp_network) nodegroup = NodeGroup.objects.new(name, uuid, ip, **dhcp_settings) nodegroup = reload_object(nodegroup) interface = get_one(nodegroup.nodegroupinterface_set.all()) self.assertEqual(name, nodegroup.name) self.assertThat( interface, MatchesStructure.byEquality(**dhcp_settings))
def test_pxeconfig_splits_domain_from_node_hostname(self): host = factory.make_name('host') domain = factory.make_name('domain') full_hostname = '.'.join([host, domain]) node = factory.make_node(hostname=full_hostname) mac = factory.make_mac_address(node=node) params = self.get_default_params() params['mac'] = mac.mac_address pxe_config = self.get_pxeconfig(params) self.assertEqual(host, pxe_config.get('hostname')) self.assertNotIn(domain, pxe_config.values())
def test_rejects_invalid_json_interfaces(self): name = factory.make_name('name') uuid = factory.getRandomUUID() invalid_interfaces = factory.make_name('invalid_json_interfaces') form = NodeGroupWithInterfacesForm( data={ 'name': name, 'uuid': uuid, 'interfaces': invalid_interfaces}) self.assertFalse(form.is_valid()) self.assertEquals( {'interfaces': ['Invalid json value.']}, form._errors)
def test_saves_to_db_by_default(self): password = factory.make_name('password') params = { 'email': '*****@*****.**' % factory.getRandomString(), 'username': factory.make_name('user'), 'password1': password, 'password2': password, } form = NewUserCreationForm(params) form.save() self.assertIsNotNone(User.objects.get(username=params['username']))
def test_POST_acquire_sets_agent_name(self): available_status = NODE_STATUS.READY node = factory.make_node( status=available_status, owner=None, agent_name=factory.make_name('agent-name')) agent_name = factory.make_name('agent-name') self.client.post( reverse('nodes_handler'), {'op': 'acquire', 'agent_name': agent_name}) node = Node.objects.get(system_id=node.system_id) self.assertEqual(agent_name, node.agent_name)
def test_does_not_save_to_db_if_commit_is_False(self): password = factory.make_name('password') params = { 'email': '*****@*****.**' % factory.getRandomString(), 'username': factory.make_name('user'), 'password1': password, 'password2': password, } form = NewUserCreationForm(params) form.save(commit=False) self.assertItemsEqual( [], User.objects.filter(username=params['username']))
def test_get_hostname_ip_mapping_strips_out_domain(self): nodegroup = factory.make_node_group() hostname = factory.make_name('hostname') domain = factory.make_name('domain') node = factory.make_node( nodegroup=nodegroup, hostname='%s.%s' % (hostname, domain)) mac = factory.make_mac_address(node=node) lease = factory.make_dhcp_lease( nodegroup=nodegroup, mac=mac.mac_address) mapping = DHCPLease.objects.get_hostname_ip_mapping(nodegroup) self.assertEqual({hostname: lease.ip}, mapping)
def test_fqdn_replaces_hostname_if_dns_is_managed(self): hostname_without_domain = factory.make_name('hostname') hostname_with_domain = '%s.%s' % ( hostname_without_domain, factory.getRandomString()) domain = factory.make_name('domain') nodegroup = factory.make_node_group( status=NODEGROUP_STATUS.ACCEPTED, name=domain, management=NODEGROUPINTERFACE_MANAGEMENT.DHCP_AND_DNS) node = factory.make_node( hostname=hostname_with_domain, nodegroup=nodegroup) expected_hostname = '%s.%s' % (hostname_without_domain, domain) self.assertEqual(expected_hostname, node.fqdn)
def test_can_edit_cluster(self): nodegroup = factory.make_node_group() edit_link = reverse('cluster-edit', args=[nodegroup.uuid]) data = { 'cluster_name': factory.make_name('cluster_name'), 'name': factory.make_name('name'), 'status': factory.getRandomEnum(NODEGROUP_STATUS), } response = self.client.post(edit_link, data) self.assertEqual(httplib.FOUND, response.status_code, response.content) self.assertThat( reload_object(nodegroup), MatchesStructure.byEquality(**data))
def test_get_effective_kernel_options_uses_first_real_tag_value(self): node = factory.make_node() # Intentionally create them in reverse order, so the default 'db' order # doesn't work, and we have asserted that we sort them. tag3 = factory.make_tag(factory.make_name('tag-03-'), kernel_opts=factory.getRandomString()) tag2 = factory.make_tag(factory.make_name('tag-02-'), kernel_opts=factory.getRandomString()) tag1 = factory.make_tag(factory.make_name('tag-01-'), kernel_opts=None) self.assertTrue(tag1.name < tag2.name) self.assertTrue(tag2.name < tag3.name) node.tags.add(tag1, tag2, tag3) self.assertEqual( (tag2, tag2.kernel_opts), node.get_effective_kernel_options())
def test_GET_list_with_agent_name_filters_by_agent_name(self): non_listed_node = factory.make_node( agent_name=factory.make_name('agent_name')) ignore_unused(non_listed_node) agent_name = factory.make_name('agent-name') node = factory.make_node(agent_name=agent_name) response = self.client.get(reverse('nodes_handler'), { 'op': 'list', 'agent_name': agent_name, }) self.assertEqual(httplib.OK, response.status_code) parsed_result = json.loads(response.content) self.assertSequenceEqual( [node.system_id], extract_system_ids(parsed_result))
def test_AdminNodeForm_refuses_to_update_hostname_on_allocated_node(self): old_name = factory.make_name('old-hostname') new_name = factory.make_name('new-hostname') node = factory.make_node( hostname=old_name, status=NODE_STATUS.ALLOCATED) form = AdminNodeForm( data={ 'hostname': new_name, 'architecture': node.architecture, }, instance=node) self.assertFalse(form.is_valid()) self.assertEqual( ["Can't change hostname to %s: node is in use." % new_name], form._errors['hostname'])
def test_accepts_name_change_if_nodegroup_not_accepted(self): nodegroup, node = make_unrenamable_nodegroup_with_node() nodegroup.status = NODEGROUP_STATUS.PENDING data = self.make_form_data(nodegroup) data['name'] = factory.make_name('new-name') form = NodeGroupEdit(instance=nodegroup, data=data) self.assertTrue(form.is_valid())
def test_PUT_reserved_to_admin_users(self): nodegroup = factory.make_node_group() response = self.client_put( reverse('nodegroup_handler', args=[nodegroup.uuid]), {'name': factory.make_name("new-name")}) self.assertEqual(httplib.FORBIDDEN, response.status_code)
def test_sequence_respects_minvalue(self): name = factory.make_name('seq', sep='') minvalue = random.randint(1, 50) seq = Sequence(name, minvalue=minvalue) seq.create() val = self.query_seq(seq.name) self.assertEqual(minvalue, val)
def test_POST_update_nodes_unknown_tag(self): self.become_admin() name = factory.make_name() response = self.client.post( reverse('tag_handler', args=[name]), {'op': 'update_nodes'}) self.assertEqual(httplib.NOT_FOUND, response.status_code)
def test_get_archive_includes_builtin_scripts(self): name = factory.make_name('00-maas') path = os.path.join(ARCHIVE_PREFIX, name) content = factory.getRandomString().encode('ascii') self.patch(cs_module, 'BUILTIN_COMMISSIONING_SCRIPTS', {name: content}) archive = open_tarfile(CommissioningScript.objects.get_archive()) self.assertIn(path, archive.getnames()) self.assertEqual(content, archive.extractfile(path).read())
def test_edit_user_POST_profile_updates_attributes(self): user = factory.make_user() params = make_user_attribute_params(user) params.update({ 'last_name': factory.make_name('Newname'), 'email': '*****@*****.**' % factory.getRandomString(), 'is_superuser': True, 'username': factory.make_name('newname'), }) response = self.client.post( reverse('accounts-edit', args=[user.username]), get_prefixed_form_data('profile', params)) self.assertEqual(httplib.FOUND, response.status_code) self.assertAttributes( reload_object(user), subset_dict(params, user_attributes))
def test_import_boot_images_sent_to_nodegroup_queue(self): recorder = self.patch(nodegroup_module, 'import_boot_images', Mock()) nodegroup = factory.make_node_group() proxy = factory.make_name('proxy') Config.objects.set_config('http_proxy', proxy) nodegroup.import_boot_images() args, kwargs = recorder.apply_async.call_args self.assertEqual(nodegroup.uuid, kwargs['queue'])
def test_pxeconfig_uses_boot_purpose(self): fake_boot_purpose = factory.make_name("purpose") self.patch(api, "get_boot_purpose", lambda node: fake_boot_purpose) response = self.client.get(reverse('pxeconfig'), self.get_default_params()) self.assertEqual( fake_boot_purpose, json.loads(response.content)["purpose"])
def test_created_node_uses_default_nodegroup_if_origin_not_found(self): unknown_host = factory.make_name('host') response = self.client.post( reverse('nodes_handler'), data={ 'op': 'new', 'hostname': factory.make_name('hostname'), 'architecture': factory.getRandomChoice(ARCHITECTURE_CHOICES), 'after_commissioning_action': ( NODE_AFTER_COMMISSIONING_ACTION.DEFAULT), 'mac_addresses': [factory.getRandomMACAddress()], }, HTTP_HOST=unknown_host) self.assertEqual(httplib.OK, response.status_code, response.content) parsed_result = json.loads(response.content) node = Node.objects.get(system_id=parsed_result.get('system_id')) self.assertEqual(NodeGroup.objects.ensure_master(), node.nodegroup)
def test_create_package_repository_requires_url(self): form = PackageRepositoryForm(data={"name": factory.make_name("name")}) self.assertFalse(form.is_valid())
def test_is_default_detects_non_default_space(self): name = factory.make_name('name') space = factory.make_Space(name=name) self.assertFalse(space.is_default())
def test_get_launchpad_crashes_for_user_not_found(self, error): auth_id = factory.make_name("auth_id") mock_requests = self.patch(requests_module, "get") mock_requests.return_value.status_code = error self.assertRaises(ImportSSHKeysError, get_launchpad_ssh_keys, auth_id)
def test_create_does_not_override_name(self): name = factory.make_name() space = factory.make_Space(name=name) self.assertEqual(name, space.name)
def test_add_tag(self): script = factory.make_Script() new_tag = factory.make_name('tag') script.add_tag(new_tag) script.save() self.assertIn(new_tag, reload_object(script).tags)
def test_unregister_raises_error_if_handler_does_not_match(self): listener = PostgresListenerService() channel = factory.make_name("channel") listener.register(channel, sentinel.handler) with ExpectedException(PostgresListenerUnregistrationError): listener.unregister(channel, sentinel.other_handler)
def test_unregister_raises_error_if_channel_not_registered(self): listener = PostgresListenerService() with ExpectedException(PostgresListenerUnregistrationError): listener.unregister(factory.make_name("channel"), sentinel.handler)
def test_register_adds_channel_and_handler(self): listener = PostgresListenerService() channel = factory.make_name("channel") listener.register(channel, sentinel.handler) self.assertEqual([sentinel.handler], listener.listeners[channel])
def test_can_be_modified_from_None_without_crashing(self): Config.objects.set_config(self.name, None) something = [factory.make_name("value")] Config.objects.set_config(self.name, something) self.assertEqual(something, Config.objects.get_config(self.name))
def test_remove_tags_ignores_nonexistant_tag(self): script = factory.make_Script() tag_count = len(script.tags) script.remove_tag(factory.make_name('tag')) script.save() self.assertEquals(tag_count, len(reload_object(script).tags))
def test_can_be_deleted_if_does_not_contain_subnets(self): name = factory.make_name('name') space = factory.make_Space(name=name) space.delete() self.assertItemsEqual([], Space.objects.filter(name=name))
def test_creates_space(self): name = factory.make_name('name') space = Space(name=name) space.save() space_from_db = Space.objects.get(name=name) self.assertThat(space_from_db, MatchesStructure.byEquality(name=name))
def test__uses_maas_internal_domain_config(self): internal_domain = factory.make_name("internal") Config.objects.set_config("maas_internal_domain", internal_domain) domain = get_internal_domain() self.assertEqual(internal_domain, domain.name)
def test_unregister_removes_handler(self): listener = PostgresListenerService() channel = factory.make_name("channel") listener.register(channel, sentinel.handler) listener.unregister(channel, sentinel.handler) self.assertEquals({channel: []}, listener.listeners)
class TestTranslateScriptParallel(MAASServerTestCase): """Test translate_script_parallel.""" scenarios = [ ('numeric disabled', { 'value': SCRIPT_PARALLEL.DISABLED, 'return_value': SCRIPT_PARALLEL.DISABLED, }), ('numeric instance', { 'value': SCRIPT_PARALLEL.INSTANCE, 'return_value': SCRIPT_PARALLEL.INSTANCE, }), ('numeric any', { 'value': SCRIPT_PARALLEL.ANY, 'return_value': SCRIPT_PARALLEL.ANY, }), ('numeric string disabled', { 'value': str(SCRIPT_PARALLEL.DISABLED), 'return_value': SCRIPT_PARALLEL.DISABLED, }), ('numeric string instance', { 'value': str(SCRIPT_PARALLEL.INSTANCE), 'return_value': SCRIPT_PARALLEL.INSTANCE, }), ('numeric string any', { 'value': str(SCRIPT_PARALLEL.ANY), 'return_value': SCRIPT_PARALLEL.ANY, }), ('invalid id', { 'value': random.randint(100, 1000), 'exception': 'Invalid script parallel numeric value.', }), ('disabled', { 'value': 'disabled', 'return_value': SCRIPT_PARALLEL.DISABLED, }), ('none', { 'value': 'none', 'return_value': SCRIPT_PARALLEL.DISABLED, }), ('instance', { 'value': 'instance', 'return_value': SCRIPT_PARALLEL.INSTANCE, }), ('name', { 'value': 'name', 'return_value': SCRIPT_PARALLEL.INSTANCE, }), ('any', { 'value': 'any', 'return_value': SCRIPT_PARALLEL.ANY, }), ('enabled', { 'value': 'enabled', 'return_value': SCRIPT_PARALLEL.ANY, }), ('invalid value', { 'value': factory.make_name('value'), 'exception': 'Script parallel must be disabled, instance, or any.', }), ] def test_translate_script_parallel(self): if hasattr(self, 'exception'): with self.assertRaisesRegex(ValidationError, self.exception): translate_script_parallel(self.value) else: self.assertEquals(self.return_value, translate_script_parallel(self.value))
def test_isSystemChannel_returns_true_for_channel_starting_with_sys(self): channel = factory.make_name("sys_", sep="") listener = PostgresListenerService() self.assertTrue(listener.isSystemChannel(channel))
def test_doesnt_fail_if_interface_missing(self): rack_controller = factory.make_RackController() # No error should be raised. update_foreign_dhcp(rack_controller.system_id, factory.make_name("eth"), None)
def test_isSystemChannel_returns_false_for_channel_not__sys(self): channel = factory.make_name("node_", sep="") listener = PostgresListenerService() self.assertFalse(listener.isSystemChannel(channel))
def test_always_has_current_commissioning_script_set(self): load_builtin_scripts() hostname = factory.make_name("hostname") register(hostname=hostname) rack = RackController.objects.get(hostname=hostname) self.assertIsNotNone(rack.current_commissioning_script_set)
def test_POST_is_forbidden(self): response = self.client.post(self.get_url(), {'name': factory.make_name('script')}) self.assertThat(response, HasStatusCode(http.client.FORBIDDEN))
def test__raises_error_if_system_handler_registered_more_than_once(self): channel = factory.make_name("sys_", sep="") listener = PostgresListenerService() listener.register(channel, lambda *args: None) with ExpectedException(PostgresListenerRegistrationError): listener.register(channel, lambda *args: None)
def test_rejects_names_with_blanks(self): self.assertRaises(ValidationError, factory.make_Space, name=factory.make_name("Space "))
def test_getUserFromSessionId_returns_None_for_invalid_key(self): self.client.login(user=maas_factory.make_User()) session_id = maas_factory.make_name("sessionid") protocol, factory = self.make_protocol() self.assertIs(None, protocol.getUserFromSessionId(session_id))
def test_GET_returns_404_if_user_not_found(self): nonuser = factory.make_name('nonuser') response = self.client.get(reverse('user_handler', args=[nonuser])) self.assertEqual(http.client.NOT_FOUND, response.status_code, response.status_code) self.assertItemsEqual([], User.objects.filter(username=nonuser))
def test_getMessageField_returns_value_in_message(self): protocol, factory = self.make_protocol() key = maas_factory.make_name("key") value = maas_factory.make_name("value") message = {key: value} self.assertEqual(value, protocol.getMessageField(message, key))
def test_DELETE_keeps_quiet_if_user_not_found(self): self.become_admin() nonuser = factory.make_name('nonuser') response = self.client.delete(reverse('user_handler', args=[nonuser])) self.assertEqual(http.client.NO_CONTENT, response.status_code, response.status_code)
def test__validates_unsupported_parameter_types_if_not_required(self): unsupported_type = factory.make_name("unsupported") form = ParametersForm( data={"storage": {"type": unsupported_type, "required": False}} ) self.assertTrue(form.is_valid())
def test__validates_parameters_is_dict(self): form = ParametersForm(data=[factory.make_name() for _ in range(3)]) self.assertFalse(form.is_valid()) self.assertDictEqual( {"parameters": ["Must be a dictionary"]}, form.errors )
def _create_publications(): return [ DNSPublication.objects.create( source=factory.make_name('reason')) for _ in range(3) ]
class TestTranslateHardwareType(MAASServerTestCase): """Test translate_hardware_type.""" scenarios = [ ('numeric node', { 'value': HARDWARE_TYPE.NODE, 'return_value': HARDWARE_TYPE.NODE, }), ('numeric cpu', { 'value': HARDWARE_TYPE.CPU, 'return_value': HARDWARE_TYPE.CPU, }), ('numeric memory', { 'value': HARDWARE_TYPE.MEMORY, 'return_value': HARDWARE_TYPE.MEMORY, }), ('numeric storage', { 'value': HARDWARE_TYPE.STORAGE, 'return_value': HARDWARE_TYPE.STORAGE, }), ('numeric string node', { 'value': str(HARDWARE_TYPE.NODE), 'return_value': HARDWARE_TYPE.NODE, }), ('numeric string cpu', { 'value': str(HARDWARE_TYPE.CPU), 'return_value': HARDWARE_TYPE.CPU, }), ('numeric string memory', { 'value': str(HARDWARE_TYPE.MEMORY), 'return_value': HARDWARE_TYPE.MEMORY, }), ('numeric string storage', { 'value': str(HARDWARE_TYPE.STORAGE), 'return_value': HARDWARE_TYPE.STORAGE, }), ('invalid id', { 'value': random.randint(100, 1000), 'exception': 'Invalid hardware type numeric value.', }), ('node', { 'value': 'node', 'return_value': HARDWARE_TYPE.NODE, }), ('machine', { 'value': 'machine', 'return_value': HARDWARE_TYPE.NODE, }), ('controller', { 'value': 'controller', 'return_value': HARDWARE_TYPE.NODE, }), ('other', { 'value': 'other', 'return_value': HARDWARE_TYPE.NODE, }), ('cpu', { 'value': 'cpu', 'return_value': HARDWARE_TYPE.CPU, }), ('processor', { 'value': 'processor', 'return_value': HARDWARE_TYPE.CPU, }), ('memory', { 'value': 'memory', 'return_value': HARDWARE_TYPE.MEMORY, }), ('ram', { 'value': 'ram', 'return_value': HARDWARE_TYPE.MEMORY, }), ('storage', { 'value': 'storage', 'return_value': HARDWARE_TYPE.STORAGE, }), ('disk', { 'value': 'disk', 'return_value': HARDWARE_TYPE.STORAGE, }), ('ssd', { 'value': 'ssd', 'return_value': HARDWARE_TYPE.STORAGE, }), ('network', { 'value': 'network', 'return_value': HARDWARE_TYPE.NETWORK, }), ('net', { 'value': 'net', 'return_value': HARDWARE_TYPE.NETWORK, }), ('interface', { 'value': 'interface', 'return_value': HARDWARE_TYPE.NETWORK, }), ('invalid value', { 'value': factory.make_name('value'), 'exception': 'Hardware type must be node, cpu, memory, or storage', }), ] def test_translate_hardware_type(self): if hasattr(self, 'exception'): with self.assertRaisesRegex(ValidationError, self.exception): translate_hardware_type(self.value) else: self.assertEquals(self.return_value, translate_hardware_type(self.value))