def test_cannot_set_attributes(self): config = Configuration({}) expected_exception = ExpectedException( AttributeError, "^'Configuration' object has no attribute 'foo'$") with expected_exception: config.foo = "bar"
def test_same_network_not_attached_to_lr(self): logger.debug( "test interface-add gateway-set not allowing" "same network to be attached as both internal and external" "network of logical router") project = self._vnc_lib.project_read( fq_name=['default-domain', 'default-project']) ipam = self._vnc_lib.network_ipam_read(fq_name=[ 'default-domain', 'default-project', 'default-network-ipam' ]) logger.debug('Read network ipam') # Create subnets ipam_sn_v4_vn = IpamSubnetType(subnet=SubnetType('11.1.1.0', 24)) # Create VN my-vn vn = VirtualNetwork('%s-vn' % self.id(), project) vn.add_network_ipam(ipam, VnSubnetsType([ipam_sn_v4_vn])) self._vnc_lib.virtual_network_create(vn) logger.debug('Created Virtual Network object for my-vn: %s', vn.uuid) net_obj = self._vnc_lib.virtual_network_read(id=vn.uuid) ## Create v4 Ip object ip_obj = InstanceIp(name=str(uuid.uuid4()), instance_ip_family='v4') ip_obj.uuid = ip_obj.name logger.debug('Created Instance IP object 1 %s', ip_obj.uuid) # Create Port port_obj = self.create_port(project, net_obj) # Create Logical Router lr = LogicalRouter('router-test-v4-%s' % (self.id()), project) lr_uuid = self._vnc_lib.logical_router_create(lr) logger.debug('Created Logical Router ') # Add Router Interface lr.add_virtual_machine_interface(port_obj) self._vnc_lib.logical_router_update(lr) # set router_external net_obj.set_router_external(True) self._vnc_lib.virtual_network_update(net_obj) logger.debug( "Try adding gateway from same network as of interface to LR object" ) with ExpectedException(cfgm_common.exceptions.BadRequest) as e: lr.add_virtual_network(net_obj) self._vnc_lib.logical_router_update(lr) logger.debug( "Adding gateway from same network as of interface to LR object failed as expected" ) lr.del_virtual_network(net_obj) logger.debug("Removing the interface attached to LR") lr.del_virtual_machine_interface(port_obj) self._vnc_lib.logical_router_update(lr) logger.debug("Adding external gateway to LR") lr.add_virtual_network(net_obj) self._vnc_lib.logical_router_update(lr) # Create Port port_obj = self.create_port(project, net_obj) logger.debug( "Try adding interafce from same network as of gateway to LR object" ) with ExpectedException(cfgm_common.exceptions.BadRequest) as e: lr.add_virtual_machine_interface(port_obj) self._vnc_lib.logical_router_update(lr) logger.debug( "Adding interface from same network as of gateway to LR object failed as expected" ) self._vnc_lib.logical_router_delete(id=lr.uuid)
def test_update_as_non_admin_asserts(self): user = factory.make_User() handler = ConfigHandler(user, {}, None) with ExpectedException(HandlerPermissionError): handler.update({})
def test__duplicate_label_raises(self): with ExpectedException(ConstraintTestException): parse_labeled_constraint_map( "a:b=c;a:d=e", exception_type=ConstraintTestException)
def test__label_with_no_constraints_raises(self): with ExpectedException(ConstraintTestException): parse_labeled_constraint_map( "a:", exception_type=ConstraintTestException)
def test_getRandomClient_empty_raises_NoConnectionsAvailable(self): service = RegionService(sentinel.ipcWorker) service.connections.clear() with ExpectedException(NoConnectionsAvailable): service.getRandomClient()
def test__rejects_bad_names(self): for name in self.EXPECTED_BAD_NAMES: with ExpectedException(ConstraintTestException, msg='name=%s' % name): validate_constraint_label_name( name, exception_type=ConstraintTestException)
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__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_tag_basic_sanity(self): pobj = vnc_api.Project('proj-%s' %(self.id())) self._vnc_lib.project_create(pobj) tag_obj = Tag(parent_obj=pobj) # tag type must be valid tag_obj.set_tag_type('Foobar') with ExpectedException(BadRequest) as e: self._vnc_lib.tag_create(tag_obj) # tag type and value both are required tag_obj.set_tag_type('application') with ExpectedException(BadRequest) as e: self._vnc_lib.tag_create(tag_obj) # tag ID isn't settable by user tag_obj.set_tag_id(0x12345678) with ExpectedException(BadRequest) as e: self._vnc_lib.tag_create(tag_obj) # create a valid project scoped tag tag_obj = Tag(tag_type='application', tag_value='MyTestApp', parent_obj=pobj) self._vnc_lib.tag_create(tag_obj) tag_obj = self._vnc_lib.tag_read(id=tag_obj.uuid) time.sleep(5) # detect duplication of project-scoped tag with ExpectedException(BadRequest) as e: self._vnc_lib.tag_create(Tag(tag_type='application', tag_value='MyTestApp', parent_obj=pobj)) # tag type, value or id can't be updated tag = self._vnc_lib.tag_read(id=tag_obj.uuid) tag_obj.set_tag_value('MyTestApp') with ExpectedException(BadRequest) as e: self._vnc_lib.tag_update(tag_obj) tag = self._vnc_lib.tag_read(id=tag_obj.uuid) tag_obj.set_tag_type('application') with ExpectedException(BadRequest) as e: self._vnc_lib.tag_update(tag_obj) tag = self._vnc_lib.tag_read(id=tag_obj.uuid) tag_obj.set_tag_id(1<<27 | 1) with ExpectedException(BadRequest) as e: self._vnc_lib.tag_update(tag_obj) # create a valid global tag gtag_obj = Tag(tag_type='deployment', tag_value='Production') self._vnc_lib.tag_create(gtag_obj) gtag_obj = self._vnc_lib.tag_read(id=gtag_obj.uuid) time.sleep(5) # detect duplication of globally-scoped tag with ExpectedException(BadRequest) as e: self._vnc_lib.tag_create(Tag(tag_type='deployment', tag_value='Production')) # create a VN and attach project and global tag vn_obj = VirtualNetwork('vn-%s' %(self.id()), parent_obj=pobj) self._vnc_lib.virtual_network_create(vn_obj) self._vnc_lib.set_tag(vn_obj, tag_type='application', tag_value='MyTestApp') self._vnc_lib.set_tag(vn_obj, tag_type='deployment', tag_value='Production', is_global=True) # validate vn->tag ref exists vn = self._vnc_lib.virtual_network_read(id=vn_obj.uuid) tag_refs = vn.get_tag_refs() self.assertEqual(len(tag_refs), 2) received_set = set([ref['uuid'] for ref in tag_refs]) expected_set = set([tag_obj.uuid, gtag_obj.uuid]) self.assertEqual(received_set, expected_set) # validate tag->vn back ref exists tag = self._vnc_lib.tag_read(id=tag_obj.uuid) vn_refs = tag.get_virtual_network_back_refs() self.assertEqual(len(vn_refs), 1) self.assertEqual(vn_refs[0]['uuid'], vn_obj.uuid) tag = self._vnc_lib.tag_read(id=gtag_obj.uuid) vn_refs = tag.get_virtual_network_back_refs() self.assertEqual(len(vn_refs), 1) self.assertEqual(vn_refs[0]['uuid'], vn_obj.uuid) # only one tag of type (latest) can be associated tag2_obj = Tag(tag_type='application', tag_value='MyTestApp2', parent_obj=pobj) self._vnc_lib.tag_create(tag2_obj) tag2_obj = self._vnc_lib.tag_read(id=tag2_obj.uuid) self._vnc_lib.set_tag(vn_obj, tag_type='application', tag_value='MyTestApp2') vn = self._vnc_lib.virtual_network_read(id=vn_obj.uuid) tag_refs = vn.get_tag_refs() self.assertEqual(len(tag_refs), 2) received_set = set([ref['uuid'] for ref in tag_refs]) expected_set = set([tag2_obj.uuid, gtag_obj.uuid]) self.assertEqual(received_set, expected_set)
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_firewall_service(self): pobj = Project('%s-project' %(self.id())) self._vnc_lib.project_create(pobj) rule_obj = FirewallRule(name='rule-%s' % self.id(), parent_obj=pobj) self._vnc_lib.firewall_rule_create(rule_obj) rule_obj = self._vnc_lib.firewall_rule_read(id=rule_obj.uuid) # rule + service (negative test case) rule_obj.set_service(FirewallServiceType(protocol="1234", dst_ports=PortType(8080, 8082))) with ExpectedException(BadRequest) as e: self._vnc_lib.firewall_rule_update(rule_obj) # rule + service (positive test case) rule_obj.set_service(FirewallServiceType(protocol="udp", dst_ports=PortType(8080, 8082))) self._vnc_lib.firewall_rule_update(rule_obj) rule = self._vnc_lib.firewall_rule_read(id=rule_obj.uuid) self.assertEqual(rule.get_service().get_protocol_id(), 17) # service group negative test case fst = FirewallServiceType(protocol="1234", dst_ports=PortType(8080, 8082)) fsgt = FirewallServiceGroupType(firewall_service=[fst]) sg_obj = ServiceGroup(service_group_firewall_service_list=fsgt, parent_obj=pobj) with ExpectedException(BadRequest) as e: self._vnc_lib.service_group_create(sg_obj) # create blank service group fst = FirewallServiceType() fsgt = FirewallServiceGroupType(firewall_service=[fst]) sg_obj = ServiceGroup(name="sg1-%s" % self.id(), service_group_firewall_service_list=fsgt, parent_obj=pobj) self._vnc_lib.service_group_create(sg_obj) sg = self._vnc_lib.service_group_read(id=sg_obj.uuid) fsgt = sg.get_service_group_firewall_service_list() fst = fsgt.get_firewall_service() self.assertEqual(len(fst), 1) # update service group fst = FirewallServiceType(protocol="tcp", dst_ports=PortType(8080, 8082)) fsgt = FirewallServiceGroupType(firewall_service=[fst]) sg.set_service_group_firewall_service_list(fsgt) self._vnc_lib.service_group_update(sg) sg = self._vnc_lib.service_group_read(id=sg_obj.uuid) fsgt = sg.get_service_group_firewall_service_list() fst = fsgt.get_firewall_service() self.assertEqual(len(fst), 1) expected_protocol_id_list = [6] received_list = [service.protocol_id for service in fst] self.assertEqual(received_list, expected_protocol_id_list) # update service group again and verify fsgt.add_firewall_service(FirewallServiceType(protocol="udp", dst_ports=PortType(52, 53))) sg.set_service_group_firewall_service_list(fsgt) self._vnc_lib.service_group_update(sg) sg = self._vnc_lib.service_group_read(id=sg_obj.uuid) fsgt = sg.get_service_group_firewall_service_list() fst = fsgt.get_firewall_service() self.assertEqual(len(fst), 2) expected_protocol_id_list = [6,17] received_list = [service.protocol_id for service in fst] self.assertEqual(received_list, expected_protocol_id_list) # create a new service group fst = FirewallServiceType(protocol="tcp", dst_ports=PortType(80, 80)) fsgt = FirewallServiceGroupType(firewall_service=[fst]) sg_obj = ServiceGroup(name="sg2-%s" % self.id(), service_group_firewall_service_list=fsgt, parent_obj=pobj) self._vnc_lib.service_group_create(sg_obj) sg = self._vnc_lib.service_group_read(id=sg_obj.uuid) fsgt = sg.get_service_group_firewall_service_list() fst = fsgt.get_firewall_service() self.assertEqual(len(fst), 1) expected_protocol_id_list = [6] received_list = [service.protocol_id for service in fst] self.assertEqual(received_list, expected_protocol_id_list) # update service group and verify all items fsgt.add_firewall_service(FirewallServiceType(protocol="udp", dst_ports=PortType(52, 53))) sg.set_service_group_firewall_service_list(fsgt) self._vnc_lib.service_group_update(sg) sg = self._vnc_lib.service_group_read(id=sg_obj.uuid) fsgt = sg.get_service_group_firewall_service_list() fst = fsgt.get_firewall_service() self.assertEqual(len(fst), 2) expected_protocol_id_list = [6,17] received_list = [service.protocol_id for service in fst] self.assertEqual(received_list, expected_protocol_id_list)
def test_set_maas_url_rejects_bare_ipv6_addresses(self): config = ClusterConfiguration({}) example_url = factory.make_simple_http_url( netloc=factory.make_ipv6_address()) with ExpectedException(formencode.api.Invalid): config.maas_url = example_url
def test_setting_something_is_validated(self): config = self.make_config() with ExpectedException(formencode.validators.Invalid): config.something = factory.make_name("not-an-ip-address")
def test__set_current_entry_asserts_for_empty_list(self): region = factory.make_RegionController() with ExpectedException(AssertionError): RDNS.objects.set_current_entry(factory.make_ip_address(), [], region)
def test_insists_on_binary_mode(self): message = "Large objects must be opened in binary mode." with ExpectedException(ValueError, message): large_object = LargeObjectFile() large_object.open('w')
def test__forbids_duplicate_observation_on_single_region(self): region = factory.make_RegionController() factory.make_RDNS("10.0.0.1", "test.maas", region) with ExpectedException(ValidationError, ".*already exists.*"): factory.make_RDNS("10.0.0.1", "test.maasr2", region)
def test__converts_stop_dhcp_server_failure_to_CannotConfigureDHCP(self): self.patch_sudo_write_file() self.patch_sudo_delete_file() self.patch_ensureService().side_effect = ServiceActionError() with ExpectedException(exceptions.CannotConfigureDHCP): yield self.configure(factory.make_name('key'), [], [], [], [], [])
def test__delete_as_non_admin_asserts(self): user = factory.make_User() handler = SpaceHandler(user, {}, None) space = factory.make_Space() with ExpectedException(AssertionError, "Permission denied."): handler.delete({"id": space.id})
def test_get_object_raises_exception_if_owner_by_another_user(self): user = factory.make_User() device = self.make_device_with_ip_address() handler = DeviceHandler(user, {}, None) with ExpectedException(HandlerDoesNotExistError): handler.get_object({"system_id": device.system_id})
def test__missing_key_value_pair_raises(self): with ExpectedException(ConstraintTestException): parse_labeled_constraint_map( "a:bc", exception_type=ConstraintTestException)
def test_missing_action_raises_error(self): user = factory.make_User() device = self.make_device_with_ip_address(owner=user) handler = DeviceHandler(user, {}, None) with ExpectedException(NodeActionError): handler.action({"system_id": device.system_id})
def test__invalid_label_raises(self): with ExpectedException(ConstraintTestException): parse_labeled_constraint_map( "*:b=c", exception_type=ConstraintTestException)
def test_accepts_all_args(self): all_test_arguments = cluster_config_command.all_arguments default_arg_values = { "--region-url": None, "--uuid": None, "--init": False, "--tftp-port": None, "--tftp-root": None, "--debug": None, } failures = {} # Try all cardinalities of combinations of arguments for r in range(len(all_test_arguments) + 1): for test_arg_names in combinations(all_test_arguments, r): test_values = { "--region-url": factory.make_simple_http_url(), "--uuid": str(uuid.uuid4()), "--init": "", "--tftp-port": str(factory.pick_port()), "--tftp-root": factory.make_string(), "--debug": str(factory.pick_bool()), } # Build a query dictionary for the given combination of args args_under_test = [] for param_name in test_arg_names: args_under_test.append(param_name) if param_name != "--init": args_under_test.append(test_values[param_name]) parser = ArgumentParser() cluster_config_command.add_arguments(parser) # If both init and uuid are passed, argparse will generate # a nice ArgumentError exception, which unfortunately, # gets caught and sent to exit. if "--init" in test_arg_names and "--uuid" in test_arg_names: expected_exception = ExpectedException(SystemExit, "2") with expected_exception, patch("sys.stderr"): parser.parse_known_args(args_under_test) else: # Otherwise, parsed args with defaults as usual observed_args = vars(parser.parse_args(args_under_test)) expected_args = {} for param_name in all_test_arguments: parsed_param_name = param_name[2:].replace("-", "_") if param_name not in test_arg_names: expected_args[ parsed_param_name] = default_arg_values[ param_name] else: expected_args[parsed_param_name] = observed_args[ parsed_param_name] if expected_args != observed_args: failures[str(test_arg_names)] = { "expected_args": expected_args, "observed_args": observed_args, } error_message = io.StringIO() error_message.write("One or more key / value argument list(s)" "passed in the query string (expected_args)" "to the API do not match the values in " "the returned query string. This " "means that some arguments were " "dropped / added / changed by the " "the function, which is incorrect " "behavior. The list of incorrect " "arguments is as follows: \n") pp = pprint.PrettyPrinter(depth=3, stream=error_message) pp.pprint(failures) self.assertDictEqual({}, failures, error_message.getvalue())
def test_vm_port_not_added_to_lr(self): logger.debug("test interface-add not allowing vm's port to be" "attached to logical router") project = self._vnc_lib.project_read( fq_name=['default-domain', 'default-project']) ipam = self._vnc_lib.network_ipam_read(fq_name=[ 'default-domain', 'default-project', 'default-network-ipam' ]) logger.debug('Read network ipam') # Create subnets ipam_sn_v4_vn = IpamSubnetType(subnet=SubnetType('11.1.1.0', 24)) # Create VN my-vn vn = VirtualNetwork('%s-vn' % self.id(), project) vn.add_network_ipam(ipam, VnSubnetsType([ipam_sn_v4_vn])) self._vnc_lib.virtual_network_create(vn) logger.debug('Created Virtual Network object for my-vn: %s', vn.uuid) net_obj = self._vnc_lib.virtual_network_read(id=vn.uuid) # Create v4 Ip object ip_obj = InstanceIp(name=str(uuid.uuid4()), instance_ip_family='v4') ip_obj.uuid = ip_obj.name logger.debug('Created Instance IP object 1 %s', ip_obj.uuid) # Create VM vm_inst_obj = VirtualMachine(str(uuid.uuid4())) vm_inst_obj.uuid = vm_inst_obj.name self._vnc_lib.virtual_machine_create(vm_inst_obj) id_perms = IdPermsType(enable=True) vm_port_obj = VirtualMachineInterface(str(uuid.uuid4()), vm_inst_obj, id_perms=id_perms) vm_port_obj.uuid = vm_port_obj.name vm_port_obj.set_virtual_network(vn) ip_obj.set_virtual_machine_interface(vm_port_obj) ip_obj.set_virtual_network(net_obj) port_id = self._vnc_lib.virtual_machine_interface_create(vm_port_obj) logger.debug('Allocating an IP4 address for VM') ip_id = self._vnc_lib.instance_ip_create(ip_obj) # Create Logical Router lr = LogicalRouter('router-test-v4-%s' % (self.id()), project) lr_uuid = self._vnc_lib.logical_router_create(lr) logger.debug('Created Logical Router ') # Add Router Interface lr.add_virtual_machine_interface(vm_port_obj) logger.debug("Trying to Link VM's VMI object and LR object") with ExpectedException(cfgm_common.exceptions.RefsExistError) as e: self._vnc_lib.logical_router_update(lr) logger.debug( "Linking VM's VMI object and LR object failed as expected") lr.del_virtual_machine_interface(vm_port_obj) # Create Port logger.debug("Add internal interface to LR") port_obj = self.create_port(project, net_obj) lr.add_virtual_machine_interface(port_obj) self._vnc_lib.logical_router_update(lr) logger.debug("Link VM to internal interface of a LR") with ExpectedException(cfgm_common.exceptions.BadRequest) as e: port_obj.add_virtual_machine(vm_inst_obj) self._vnc_lib.virtual_machine_interface_update(port_obj) logger.debug( "Linking VM to internal interface of LR failed as expected") self._vnc_lib.logical_router_delete(id=lr.uuid)
def test_create_port_with_port_security_disabled_and_sg(self): proj_obj = self._vnc_lib.project_read( fq_name=['default-domain', 'default-project']) with ExpectedException(webtest.app.AppError): self._create_port_with_sg(proj_obj.uuid, False)
def test_delete_as_non_admin_asserts(self): user = factory.make_User() handler = VLANHandler(user, {}, None) vlan = factory.make_VLAN() with ExpectedException(HandlerPermissionError): handler.delete({"id": vlan.id})
def test_subnet_uuid_heal(self): # 1. create 2 subnets thru vnc_api # 2. mess with useragent-kv index for one # 3. neutron subnet list should report fine # 4. neutron subnet list with uuids where # one is a fake uuid shouldnt cause error in list ipam_obj = vnc_api.NetworkIpam('ipam-%s' % (self.id())) self._vnc_lib.network_ipam_create(ipam_obj) vn1_obj = vnc_api.VirtualNetwork('vn1-%s' % (self.id())) sn1_uuid = str(uuid.uuid4()) vn1_obj.add_network_ipam( ipam_obj, vnc_api.VnSubnetsType([ vnc_api.IpamSubnetType(vnc_api.SubnetType('1.1.1.0', 28), subnet_uuid=sn1_uuid) ])) self._vnc_lib.virtual_network_create(vn1_obj) vn2_obj = vnc_api.VirtualNetwork('vn2-%s' % (self.id())) sn2_uuid = str(uuid.uuid4()) vn2_obj.add_network_ipam( ipam_obj, vnc_api.VnSubnetsType([ vnc_api.IpamSubnetType(vnc_api.SubnetType('2.2.2.0', 28), subnet_uuid=sn2_uuid) ])) self._vnc_lib.virtual_network_create(vn2_obj) # the list primes cfgdb handle(conn to api server) self.list_resource('subnet') neutron_api_obj = FakeExtensionManager.get_extension_objects( 'vnc_cfg_api.neutronApi')[0] neutron_db_obj = neutron_api_obj._npi._cfgdb heal_invoked = [False] def verify_heal_invoked(orig_method, *args, **kwargs): heal_invoked[0] = True return orig_method(*args, **kwargs) with test_common.patch(neutron_db_obj, 'subnet_id_heal', verify_heal_invoked): with CassandraCFs.get_cf("useragent", 'useragent_keyval_table').patch_row( sn2_uuid, None): # verify heal rsp = self.list_resource( 'subnet', req_filters={'id': [sn1_uuid, sn2_uuid]}) self.assertEqual(heal_invoked[0], True) self.assertEqual(len(rsp), 2) self.assertEqual(set([r['id'] for r in rsp]), set([sn1_uuid, sn2_uuid])) # verify wrong/non-existent id doesn't cause # list to have error heal_invoked[0] = False fake_uuid = str(uuid.uuid4()) rsp = self.list_resource( 'subnet', req_filters={'id': [sn1_uuid, sn2_uuid, fake_uuid]}) self.assertEqual(heal_invoked[0], True) self.assertEqual(len(rsp), 2) self.assertEqual(set([r['id'] for r in rsp]), set([sn1_uuid, sn2_uuid])) # verify read of non-existent id throws exception # and valid one doesn't with ExpectedException(webtest.app.AppError): self.read_resource('subnet', fake_uuid) self.read_resource('subnet', sn1_uuid)
def test_contents_immutable(self): textfile = VersionedTextFile(data=SAMPLE_TEXT) textfile.save() textfile.data = "foo" with ExpectedException(ValidationError, ".*immutable.*"): textfile.save()
def test__rejects_unsaved_nodes_on_the_right(self): saved_node, unsaved_node = factory.make_Node(), Node() with ExpectedException(AssertionError, ".* not in the database"): list(find_addresses_between_nodes([saved_node], [unsaved_node]))