def test_args(self): """ Test the ``ipalib.frontend.Command.args`` instance attribute. """ assert self.cls().args is None o = self.cls() o.finalize() assert type(o.args) is plugable.NameSpace assert len(o.args) == 0 args = ('destination', 'source?') ns = self.get_instance(args=args).args assert type(ns) is plugable.NameSpace assert len(ns) == len(args) assert list(ns) == ['destination', 'source'] assert type(ns.destination) is parameters.Str assert type(ns.source) is parameters.Str assert ns.destination.required is True assert ns.destination.multivalue is False assert ns.source.required is False assert ns.source.multivalue is False # Test TypeError: e = raises(TypeError, self.get_instance, args=(u'whatever',)) assert str(e) == TYPE_ERROR % ( 'spec', (str, parameters.Param), u'whatever', unicode) # Test ValueError, required after optional: e = raises(ValueError, self.get_instance, args=('arg1?', 'arg2')) assert str(e) == 'arg2: required argument after optional' # Test ValueError, scalar after multivalue: e = raises(ValueError, self.get_instance, args=('arg1+', 'arg2')) assert str(e) == 'arg2: only final argument can be multivalue'
def test_iter_output(self): """ Test the ``ipalib.frontend.Command._iter_output`` instance attribute. """ class Example(self.cls): pass inst = Example() inst.has_output = tuple() assert list(inst._iter_output()) == [] wrong = ['hello', 'world'] inst.has_output = wrong e = raises(TypeError, list, inst._iter_output()) assert str(e) == 'Example.has_output: need a %r; got a %r: %r' % ( tuple, list, wrong ) wrong = ('hello', 17) inst.has_output = wrong e = raises(TypeError, list, inst._iter_output()) assert str(e) == 'Example.has_output[1]: need a %r; got a %r: %r' % ( (str, output.Output), int, 17 ) okay = ('foo', output.Output('bar'), 'baz') inst.has_output = okay items = list(inst._iter_output()) assert len(items) == 3 assert list(o.name for o in items) == ['foo', 'bar', 'baz'] for o in items: assert type(o) is output.Output
def test_init(self): """ Test the `ipalib.base.NameSpace.__init__` method. """ o = self.cls([]) assert len(o) == 0 assert list(o) == [] assert list(o()) == [] # Test members as attribute and item: for cnt in (3, 42): for sort in (True, False): (o, members) = self.new(cnt, sort=sort) assert len(members) == cnt for m in members: assert getattr(o, m.name) is m assert o[m.name] is m # Test that TypeError is raised if sort is not a bool: e = raises(TypeError, self.cls, [], sort=None) assert str(e) == TYPE_ERROR % ('sort', bool, None, type(None)) # Test that AttributeError is raised with duplicate member name: members = gen_members(0, 1, 2, 1, 3) e = raises(AttributeError, self.cls, members) assert str(e) == OVERRIDE_ERROR % ( 'NameSpace', membername(1), members[1], members[3] )
def test_check_name(): """ Test the `ipalib.base.check_name` function. """ f = base.check_name okay = [ 'user_add', 'stuff2junk', 'sixty9', ] nope = [ '_user_add', '__user_add', 'user_add_', 'user_add__', '_user_add_', '__user_add__', '60nine', ] for name in okay: assert name is f(name) e = raises(TypeError, f, unicode(name)) assert str(e) == TYPE_ERROR % ('name', str, unicode(name), unicode) for name in nope: e = raises(ValueError, f, name) assert str(e) == NAME_ERROR % (NAME_REGEX, name) for name in okay: e = raises(ValueError, f, name.upper()) assert str(e) == NAME_ERROR % (NAME_REGEX, name.upper())
def test_validate(self): """ Test the `ipalib.frontend.Command.validate` method. """ sub = self.subcls() sub.env = config.Env(context='cli') sub.finalize() # Check with valid values okay = dict( option0=u'option0', option1=u'option1', another_option='some value', version=API_VERSION, ) sub.validate(**okay) # Check with an invalid value fail = dict(okay) fail['option0'] = u'whatever' e = raises(errors.ValidationError, sub.validate, **fail) assert_equal(e.name, 'option0') assert_equal(e.value, u'whatever') assert_equal(e.error, u"must equal 'option0'") assert e.rule.__class__.__name__ == 'Rule' assert e.index is None # Check with a missing required arg fail = dict(okay) fail.pop('option1') e = raises(errors.RequirementError, sub.validate, **fail) assert e.name == 'option1'
def test_iter_output(self): """ Test the ``ipalib.frontend.Command._iter_output`` instance attribute. """ class Example(self.cls): pass inst = Example() inst.has_output = tuple() assert list(inst._iter_output()) == [] wrong = ['hello', 'world'] inst.has_output = wrong e = raises(TypeError, list, inst._iter_output()) assert str(e) == 'Example.has_output: need a %r; got a %r: %r' % ( tuple, list, wrong) wrong = ('hello', 17) inst.has_output = wrong e = raises(TypeError, list, inst._iter_output()) assert str(e) == 'Example.has_output[1]: need a %r; got a %r: %r' % ( (str, output.Output), int, 17) okay = ('foo', output.Output('bar'), 'baz') inst.has_output = okay items = list(inst._iter_output()) assert len(items) == 3 assert list(o.name for o in items) == ['foo', 'bar', 'baz'] for o in items: assert type(o) is output.Output
def test_setitem(self): """ Test the `ipalib.config.Env.__setitem__` method. """ o = self.cls() for (key, raw, value) in good_vars: # Test setting the value: o[key] = raw result = o[key] assert type(result) is type(value) assert result == value assert result is getattr(o, key) # Test that value cannot be overridden once set: e = raises(AttributeError, o.__setitem__, key, raw) assert str(e) == OVERRIDE_ERROR % ('Env', key, value, raw) # Test that values cannot be set once locked: o = self.cls() o.__lock__() for (key, raw, value) in good_vars: e = raises(AttributeError, o.__setitem__, key, raw) assert str(e) == SET_ERROR % ('Env', key, raw) # Test that name is tested with check_name(): o = self.cls() for (key, value) in bad_names: e = raises(ValueError, o.__setitem__, key, value) assert str(e) == NAME_ERROR % (NAME_REGEX, key)
def test_class(self): """ Test the `ipalib.plugable.MagicDict` class. """ assert self.cls.__bases__ == (plugable.DictProxy,) for non_dict in ('hello', 69, object): raises(TypeError, self.cls, non_dict)
def test_args(self): """ Test the ``ipalib.frontend.Command.args`` instance attribute. """ assert self.cls().args is None o = self.cls() o.finalize() assert type(o.args) is plugable.NameSpace assert len(o.args) == 0 args = ('destination', 'source?') ns = self.get_instance(args=args).args assert type(ns) is plugable.NameSpace assert len(ns) == len(args) assert list(ns) == ['destination', 'source'] assert type(ns.destination) is parameters.Str assert type(ns.source) is parameters.Str assert ns.destination.required is True assert ns.destination.multivalue is False assert ns.source.required is False assert ns.source.multivalue is False # Test TypeError: e = raises(TypeError, self.get_instance, args=(u'whatever', )) assert str(e) == TYPE_ERROR % ('spec', (str, parameters.Param), u'whatever', unicode) # Test ValueError, required after optional: e = raises(ValueError, self.get_instance, args=('arg1?', 'arg2')) assert str(e) == 'arg2: required argument after optional' # Test ValueError, scalar after multivalue: e = raises(ValueError, self.get_instance, args=('arg1+', 'arg2')) assert str(e) == 'arg2: only final argument can be multivalue'
def test_create_complex(self): for prefix in range(12, 17): self.r.ipblock_create('%d.0.0.0/8' % prefix, status='Container') self.r.ipblock_create('2001::/16', status='Container') self.r.ippool_create("pool1", vlan=4) self.check_ippool_add_subnet('pool1', '12.0.0.0/24', gateway='12.0.0.1') self.check_ippool_add_subnet('pool1', '13.0.0.0/24', gateway='12.0.0.1') self.check_ippool_add_subnet('pool1', '14.0.0.0/23') self.check_ippool_add_subnet('pool1', '15.0.0.0/24', attributes={'country': 'ro', 'team': 'IP Operations'}) with raises(AlreadyExistsError): self.r.ippool_add_subnet('pool1', '12.0.0.0/24') with raises(InvalidIPError): self.r.ippool_add_subnet('pool1', '2001:db8::/32') self.r.ipblock_create('17.0.0.0/24', status='Container') with raises(InvalidStatusError): self.r.ippool_add_subnet('pool1', '17.0.0.0/24') self.r.ippool_create("pool2", vlan=4) self.check_ippool_add_subnet('pool2', '16.0.0.0/24') with raises(AlreadyExistsError): self.r.ippool_add_subnet('pool1', '16.0.0.0/24') assert self.r.ipblock_remove('16.0.0.0/24', pool='pool2') == 1 self.r.ippool_add_subnet('pool1', '16.0.0.0/24') with raises(NotInPoolError): self.r.ipblock_remove('16.0.0.0/24', pool='pool2', status='Subnet') assert self.r.ipblock_remove('16.0.0.0/24', pool='pool1') == 1 self.r.ippool_set_vlan('pool2', 5) self.check_ippool_add_subnet('pool2', '16.0.0.0/24') assert self.r.ippool_delete('pool1', force=True, delete_subnets=True) assert self.r.ippool_delete('pool2', force=True, delete_subnets=True)
def test_init(self): """ Test the `ipalib.base.NameSpace.__init__` method. """ o = self.cls([]) assert len(o) == 0 assert list(o) == [] assert list(o()) == [] # Test members as attribute and item: for cnt in (3, 42): for sort in (True, False): (o, members) = self.new(cnt, sort=sort) assert len(members) == cnt for m in members: assert getattr(o, m.name) is m assert o[m.name] is m # Test that TypeError is raised if sort is not a bool: e = raises(TypeError, self.cls, [], sort=None) assert str(e) == TYPE_ERROR % ('sort', bool, None, type(None)) # Test that AttributeError is raised with duplicate member name: members = gen_members(0, 1, 2, 1, 3) e = raises(AttributeError, self.cls, members) assert str(e) == OVERRIDE_ERROR % ('NameSpace', membername(1), members[1], members[3])
def check_method(self, name, *args): o = self.cls() e = raises(NotImplementedError, getattr(o, name), *args) assert str(e) == 'CrudBackend.%s()' % name sub = self.subcls() e = raises(NotImplementedError, getattr(sub, name), *args) assert str(e) == 'ldap.%s()' % name
def test_validate_output_nested(self): """ Test `ipalib.frontend.Command.validate_output` nested validation. """ class Subclass(output.ListOfEntries): pass # Test nested validation: class nested(self.cls): has_output = ( output.Output('hello', int), Subclass('world'), ) inst = nested() inst.finalize() okay = dict(foo='bar') nope = ('aye', 'bee') wrong = dict(hello=18, world=[okay, nope, okay]) e = raises(TypeError, inst.validate_output, wrong) assert str(e) == output.emsg % ('nested', 'Subclass', 'world', 1, dict, tuple, nope) wrong = dict(hello=18, world=[okay, okay, okay, okay, nope]) e = raises(TypeError, inst.validate_output, wrong) assert str(e) == output.emsg % ('nested', 'Subclass', 'world', 4, dict, tuple, nope)
def test_allocate(self): with raises(PermissionDeniedError): self.user.ippool_create('pool') self.net.ippool_create('pool') self.net.ipblock_create('12.0.0.0/8', status='Container') self.net.ippool_add_subnet('pool', '12.0.0.0/24') self.net.ippool_get_ip('pool') self.user.ippool_list(pool='pool') self.net.group_create('usergroup') self.net.group_add_user('usergroup', 'user') self.net.group_grant_access('usergroup', 'allocate', 'pool') self.user.ippool_get_ip('pool') self.user.ipblock_set_attrs('12.0.0.0', {'key': 'value'}) assert self.user.ipblock_get_attrs('12.0.0.0')['key'] == 'value' self.user.ipblock_delete_attrs('12.0.0.0', ['key']) self.user.ip_free('12.0.0.1') delegation = self.user.ippool_get_delegation('pool', 27) self.user.ipblock_remove(delegation[0]['ip']) self.net.group_revoke_access('usergroup', 'allocate', 'pool') with raises(PermissionDeniedError): self.user.ippool_get_ip('pool') self.net.group_grant_access('usergroup', 'allocate', 'pool') self.net.group_remove_user('usergroup', 'user') with raises(PermissionDeniedError): self.user.ippool_get_ip('pool')
def test_validate_output_basic(self): """ Test the `ipalib.frontend.Command.validate_output` method. """ class Example(self.cls): has_output = ('foo', 'bar', 'baz') inst = Example() inst.finalize() # Test with wrong type: wrong = ('foo', 'bar', 'baz') e = raises(TypeError, inst.validate_output, wrong) assert str(e) == '%s.validate_output(): need a %r; got a %r: %r' % ( 'Example', dict, tuple, wrong) # Test with a missing keys: wrong = dict(bar='hello') e = raises(ValueError, inst.validate_output, wrong) assert str(e) == '%s.validate_output(): missing keys %r in %r' % ( 'Example', ['baz', 'foo'], wrong) # Test with extra keys: wrong = dict(foo=1, bar=2, baz=3, fee=4, azz=5) e = raises(ValueError, inst.validate_output, wrong) assert str(e) == '%s.validate_output(): unexpected keys %r in %r' % ( 'Example', ['azz', 'fee'], wrong) # Test with different keys: wrong = dict(baz=1, xyzzy=2, quux=3) e = raises(ValueError, inst.validate_output, wrong) assert str(e) == '%s.validate_output(): missing keys %r in %r' % ( 'Example', ['bar', 'foo'], wrong), str(e)
def test_validate_output_nested(self): """ Test `ipalib.frontend.Command.validate_output` nested validation. """ class Subclass(output.ListOfEntries): pass # Test nested validation: class nested(self.cls): has_output = ( output.Output('hello', int), Subclass('world'), ) inst = nested() inst.finalize() okay = dict(foo='bar') nope = ('aye', 'bee') wrong = dict(hello=18, world=[okay, nope, okay]) e = raises(TypeError, inst.validate_output, wrong) assert str(e) == output.emsg % ( 'nested', 'Subclass', 'world', 1, dict, tuple, nope ) wrong = dict(hello=18, world=[okay, okay, okay, okay, nope]) e = raises(TypeError, inst.validate_output, wrong) assert str(e) == output.emsg % ( 'nested', 'Subclass', 'world', 4, dict, tuple, nope )
def test_args_options_2_params(self): """ Test the `ipalib.frontend.Command.args_options_2_params` method. """ # Test that ZeroArgumentError is raised: o = self.get_instance() e = raises(errors.ZeroArgumentError, o.args_options_2_params, 1) assert e.name == 'example' # Test that MaxArgumentError is raised (count=1) o = self.get_instance(args=('one?', )) e = raises(errors.MaxArgumentError, o.args_options_2_params, 1, 2) assert e.name == 'example' assert e.count == 1 assert str(e) == "command 'example' takes at most 1 argument" # Test that MaxArgumentError is raised (count=2) o = self.get_instance(args=('one', 'two?')) e = raises(errors.MaxArgumentError, o.args_options_2_params, 1, 2, 3) assert e.name == 'example' assert e.count == 2 assert str(e) == "command 'example' takes at most 2 arguments" # Test that OptionError is raised when an extra option is given: o = self.get_instance() e = raises(errors.OptionError, o.args_options_2_params, bad_option=True) assert e.option == 'bad_option' # Test that OverlapError is raised: o = self.get_instance(args=('one', 'two'), options=('three', 'four')) e = raises(errors.OverlapError, o.args_options_2_params, 1, 2, three=3, two=2, four=4, one=1) assert e.names == ['one', 'two'] # Test the permutations: o = self.get_instance(args=('one', 'two*'), options=('three', 'four')) mthd = o.args_options_2_params assert mthd() == dict() assert mthd(1) == dict(one=1) assert mthd(1, 2) == dict(one=1, two=(2, )) assert mthd(1, 21, 22, 23) == dict(one=1, two=(21, 22, 23)) assert mthd(1, (21, 22, 23)) == dict(one=1, two=(21, 22, 23)) assert mthd(three=3, four=4) == dict(three=3, four=4) assert mthd(three=3, four=4, one=1, two=2) == \ dict(one=1, two=2, three=3, four=4) assert mthd(1, 21, 22, 23, three=3, four=4) == \ dict(one=1, two=(21, 22, 23), three=3, four=4) assert mthd(1, (21, 22, 23), three=3, four=4) == \ dict(one=1, two=(21, 22, 23), three=3, four=4)
def test_create_add(self): with raises(PermissionDeniedError): self.user.group_create('usergroup') self.net.group_create('usergroup') with raises(PermissionDeniedError): self.user.group_add_user('usergroup', 'user') self.net.group_add_user('usergroup', 'user') with raises(PermissionDeniedError): self.user.group_delete('usergroup')
def test_group_rename(self): self.net.group_create('usergroup1') self.net.group_rename('usergroup1', 'usergroup') assert 'usergroup' in set(self.user.group_list()) assert 'usergroup1' not in set(self.user.group_list()) with raises(PermissionDeniedError): self.net.group_rename('networkgroup', 'test') with raises(PermissionDeniedError): self.user.group_rename('networkgroup', 'test')
def test_filter_param_by_context(self): """ Test the `ipalib.frontend.HasParam._filter_param_by_context` method. """ class Example(self.cls): def get_stuff(self): return ( 'one', # Make sure create_param() is called for each spec 'two', parameters.Str('three', include='cli'), parameters.Str('four', exclude='server'), parameters.Str('five', exclude=['whatever', 'cli']), ) o = Example() # Test when env is None: params = list(o._filter_param_by_context('stuff')) assert list( p.name for p in params) == ['one', 'two', 'three', 'four', 'five'] for p in params: assert type(p) is parameters.Str # Test when env.context == 'cli': cli = config.Env(context='cli') assert cli.context == 'cli' params = list(o._filter_param_by_context('stuff', cli)) assert list(p.name for p in params) == ['one', 'two', 'three', 'four'] for p in params: assert type(p) is parameters.Str # Test when env.context == 'server' server = config.Env(context='server') assert server.context == 'server' params = list(o._filter_param_by_context('stuff', server)) assert list(p.name for p in params) == ['one', 'two', 'five'] for p in params: assert type(p) is parameters.Str # Test with no get_stuff: class Missing(self.cls): pass o = Missing() gen = o._filter_param_by_context('stuff') e = raises(NotImplementedError, list, gen) assert str(e) == 'Missing.get_stuff()' # Test when get_stuff is not callable: class NotCallable(self.cls): get_stuff = ('one', 'two') o = NotCallable() gen = o._filter_param_by_context('stuff') e = raises(TypeError, list, gen) assert str(e) == '%s.%s must be a callable; got %r' % ( 'NotCallable', 'get_stuff', NotCallable.get_stuff)
def test_list_containers_edge(self): assert self.r.container_list() == [] with raises(InvalidIPError): self.r.container_list('12.0.0.0/24') self.r.ipblock_create('12.0.0.0/8', status='Container') self.r.ippool_create('pool') self.r.ippool_add_subnet('pool', '12.0.0.0/24') with raises(InvalidStatusError): self.r.container_list('12.0.0.0/24')
def test_forward(self): """ Test the `ipalib.rpc.xmlclient.forward` method. """ class user_add(Command): pass # Test that ValueError is raised when forwarding a command that is not # in api.Command: (o, api, home) = self.instance('Backend', in_server=False) e = raises(ValueError, o.forward, 'user_add') assert str(e) == '%s.forward(): %r not in api.Command' % ( 'xmlclient', 'user_add' ) (o, api, home) = self.instance('Backend', user_add, in_server=False) args = (binary_bytes, utf8_bytes, unicode_str) kw = dict(one=binary_bytes, two=utf8_bytes, three=unicode_str) params = [args, kw] result = (unicode_str, binary_bytes, utf8_bytes) conn = DummyClass( ( 'user_add', rpc.xml_wrap(params), {}, rpc.xml_wrap(result), ), ( 'user_add', rpc.xml_wrap(params), {}, Fault(3007, u"'four' is required"), # RequirementError ), ( 'user_add', rpc.xml_wrap(params), {}, Fault(700, u'no such error'), # There is no error 700 ), ) context.xmlclient = Connection(conn, lambda: None) # Test with a successful return value: assert o.forward('user_add', *args, **kw) == result # Test with an errno the client knows: e = raises(errors.RequirementError, o.forward, 'user_add', *args, **kw) assert_equal(e.args[0], u"'four' is required") # Test with an errno the client doesn't know e = raises(errors.UnknownError, o.forward, 'user_add', *args, **kw) assert_equal(e.code, 700) assert_equal(e.error, u'no such error') assert context.xmlclient.conn._calledall() is True
def test_filter_param_by_context(self): """ Test the `ipalib.frontend.HasParam._filter_param_by_context` method. """ class Example(self.cls): def get_stuff(self): return ( 'one', # Make sure create_param() is called for each spec 'two', parameters.Str('three', include='cli'), parameters.Str('four', exclude='server'), parameters.Str('five', exclude=['whatever', 'cli']), ) o = Example() # Test when env is None: params = list(o._filter_param_by_context('stuff')) assert list(p.name for p in params) == [ 'one', 'two', 'three', 'four', 'five' ] for p in params: assert type(p) is parameters.Str # Test when env.context == 'cli': cli = config.Env(context='cli') assert cli.context == 'cli' params = list(o._filter_param_by_context('stuff', cli)) assert list(p.name for p in params) == ['one', 'two', 'three', 'four'] for p in params: assert type(p) is parameters.Str # Test when env.context == 'server' server = config.Env(context='server') assert server.context == 'server' params = list(o._filter_param_by_context('stuff', server)) assert list(p.name for p in params) == ['one', 'two', 'five'] for p in params: assert type(p) is parameters.Str # Test with no get_stuff: class Missing(self.cls): pass o = Missing() gen = o._filter_param_by_context('stuff') e = raises(NotImplementedError, list, gen) assert str(e) == 'Missing.get_stuff()' # Test when get_stuff is not callable: class NotCallable(self.cls): get_stuff = ('one', 'two') o = NotCallable() gen = o._filter_param_by_context('stuff') e = raises(TypeError, list, gen) assert str(e) == '%s.%s must be a callable; got %r' % ( 'NotCallable', 'get_stuff', NotCallable.get_stuff )
def test_forward(self): """ Test the `ipalib.rpc.xmlclient.forward` method. """ class user_add(Command): pass # Test that ValueError is raised when forwarding a command that is not # in api.Command: (o, api, home) = self.instance('Backend', in_server=False) e = raises(ValueError, o.forward, 'user_add') assert str(e) == '%s.forward(): %r not in api.Command' % ('xmlclient', 'user_add') (o, api, home) = self.instance('Backend', user_add, in_server=False) args = (binary_bytes, utf8_bytes, unicode_str) kw = dict(one=binary_bytes, two=utf8_bytes, three=unicode_str) params = [args, kw] result = (unicode_str, binary_bytes, utf8_bytes) conn = DummyClass( ( 'user_add', rpc.xml_wrap(params), {}, rpc.xml_wrap(result), ), ( 'user_add', rpc.xml_wrap(params), {}, Fault(3007, u"'four' is required"), # RequirementError ), ( 'user_add', rpc.xml_wrap(params), {}, Fault(700, u'no such error'), # There is no error 700 ), ) context.xmlclient = Connection(conn, lambda: None) # Test with a successful return value: assert o.forward('user_add', *args, **kw) == result # Test with an errno the client knows: e = raises(errors.RequirementError, o.forward, 'user_add', *args, **kw) assert_equal(e.args[0], u"'four' is required") # Test with an errno the client doesn't know e = raises(errors.UnknownError, o.forward, 'user_add', *args, **kw) assert_equal(e.code, 700) assert_equal(e.error, u'no such error') assert context.xmlclient.conn._calledall() is True
def test_get_dn(self): """ Test the `ipalib.frontend.Object.get_dn` method. """ o = self.cls() e = raises(NotImplementedError, o.get_dn, 'primary key') assert str(e) == 'Object.get_dn()' class user(self.cls): pass o = user() e = raises(NotImplementedError, o.get_dn, 'primary key') assert str(e) == 'user.get_dn()'
def test_set_api(self): """ Test the `ipalib.plugable.Plugin.set_api` method. """ api = 'the api instance' o = self.cls() assert o.api is None e = raises(AssertionError, o.set_api, None) assert str(e) == 'set_api() argument cannot be None' o.set_api(api) assert o.api is api e = raises(AssertionError, o.set_api, api) assert str(e) == 'set_api() can only be called once'
def test_delete_group(self): assert set(self.user.group_list()) == set( ['networkgroup', 'all_users']) assert set(self.user.user_get_groups('net')) == set( ['networkgroup', 'all_users']) assert self.user.group_get_users('networkgroup') == ['net'] self.admin.group_delete('networkgroup') assert self.user.group_list() == ['all_users'] assert self.user.user_get_groups('net') == ['all_users'] with raises(InvalidGroupError): assert self.user.group_get_users('networkgroup') with raises(InvalidGroupError): self.admin.group_delete('networkgroup')
def test_priority(self): self.r.ipblock_create('20.0.0.0/8', status='Container') self.r.ipblock_create('13.0.0.0/8', status='Container') self.r.ippool_create("pool") self.r.ippool_add_subnet("pool", '20.0.0.0/24', gateway='20.0.0.1') self.r.ippool_add_subnet("pool", '20.0.1.0/24') self.r.ippool_add_subnet("pool", '20.0.2.0/24') l = self.r.ippool_get_subnets('pool') self.assertDictSubset(l[0], {'subnet': '20.0.0.0/24', 'priority': 1, 'gateway': '20.0.0.1'}) self.assertDictSubset(l[1], {'subnet': '20.0.1.0/24', 'priority': 2}) self.assertDictSubset(l[2], {'subnet': '20.0.2.0/24', 'priority': 3}) self.r.ipblock_remove('20.0.1.0/24', pool='pool', status='Subnet') self.r.ippool_add_subnet('pool', '20.0.3.0/24') l = self.r.ippool_get_subnets('pool') self.assertDictSubset(l[0], {'subnet': '20.0.0.0/24', 'priority': 1}) self.assertDictSubset(l[1], {'subnet': '20.0.2.0/24', 'priority': 3}) self.assertDictSubset(l[2], {'subnet': '20.0.3.0/24', 'priority': 4}) self.r.ipblock_create('12.0.0.0/24', status='Container') with raises(InvalidStatusError): self.r.subnet_set_priority('12.0.0.0/24', 1) with raises(InvalidPriorityError): self.r.subnet_set_priority('20.0.0.0/24', 'g') with raises(InvalidPriorityError): self.r.subnet_set_priority('20.0.0.0/24', 0) self.r.subnet_set_priority('20.0.0.0/24', '1') self.r.subnet_set_priority('20.0.2.0/24', 1, pool='pool') l = self.r.ippool_get_subnets('pool') self.assertDictSubset(l[0], {'subnet': '20.0.2.0/24', 'priority': 1}) self.assertDictSubset(l[1], {'subnet': '20.0.0.0/24', 'priority': 2}) self.assertDictSubset(l[2], {'subnet': '20.0.3.0/24', 'priority': 4}) self.r.ippool_add_subnet('pool', '20.0.1.0/24') self.r.ippool_add_subnet('pool', '20.0.4.0/24') self.r.subnet_set_priority('20.0.4.0/24', 3, pool='pool') l = self.r.ippool_get_subnets('pool') self.assertDictSubset(l[0], {'subnet': '20.0.2.0/24', 'priority': 1}) self.assertDictSubset(l[1], {'subnet': '20.0.0.0/24', 'priority': 2}) self.assertDictSubset(l[2], {'subnet': '20.0.4.0/24', 'priority': 3}) self.assertDictSubset(l[3], {'subnet': '20.0.3.0/24', 'priority': 4}) self.assertDictSubset(l[4], {'subnet': '20.0.1.0/24', 'priority': 5}) self.r.subnet_set_priority('20.0.4.0/24', 1, pool='pool') l = self.r.ippool_get_subnets('pool') self.assertDictSubset(l[0], {'subnet': '20.0.4.0/24', 'priority': 1}) self.assertDictSubset(l[1], {'subnet': '20.0.2.0/24', 'priority': 2}) self.assertDictSubset(l[2], {'subnet': '20.0.0.0/24', 'priority': 3}) self.assertDictSubset(l[3], {'subnet': '20.0.3.0/24', 'priority': 4}) self.assertDictSubset(l[4], {'subnet': '20.0.1.0/24', 'priority': 5})
def test_create_remove(self): with raises(InvalidVLANError): self.r.ippool_create('invalid', vlan=0) with raises(InvalidVLANError): self.r.ippool_create('invalid', vlan=4095) with raises(InvalidVLANError): self.r.ippool_create('invalid', vlan='test') self.r.ippool_create('valid', vlan='22') self.r.ippool_create('test') with raises(AlreadyExistsError): self.r.ippool_create('test') assert get_pool('test') assert self.r.ippool_delete('test') assert not get_pool('test')
def test_delattr(self): """ Test the `ipalib.config.Env.__delattr__` method. This also tests that ``__delitem__`` is not implemented. """ o = self.cls() o.one = 1 assert o.one == 1 for key in ('one', 'two'): e = raises(AttributeError, delattr, o, key) assert str(e) == DEL_ERROR % ('Env', key) e = raises(AttributeError, delitem, o, key) assert str(e) == '__delitem__'
def test_args_options_2_params(self): """ Test the `ipalib.frontend.Command.args_options_2_params` method. """ # Test that ZeroArgumentError is raised: o = self.get_instance() e = raises(errors.ZeroArgumentError, o.args_options_2_params, 1) assert e.name == 'example' # Test that MaxArgumentError is raised (count=1) o = self.get_instance(args=('one?',)) e = raises(errors.MaxArgumentError, o.args_options_2_params, 1, 2) assert e.name == 'example' assert e.count == 1 assert str(e) == "command 'example' takes at most 1 argument" # Test that MaxArgumentError is raised (count=2) o = self.get_instance(args=('one', 'two?')) e = raises(errors.MaxArgumentError, o.args_options_2_params, 1, 2, 3) assert e.name == 'example' assert e.count == 2 assert str(e) == "command 'example' takes at most 2 arguments" # Test that OptionError is raised when an extra option is given: o = self.get_instance() e = raises(errors.OptionError, o.args_options_2_params, bad_option=True) assert e.option == 'bad_option' # Test that OverlapError is raised: o = self.get_instance(args=('one', 'two'), options=('three', 'four')) e = raises(errors.OverlapError, o.args_options_2_params, 1, 2, three=3, two=2, four=4, one=1) assert e.names == ['one', 'two'] # Test the permutations: o = self.get_instance(args=('one', 'two*'), options=('three', 'four')) mthd = o.args_options_2_params assert mthd() == dict() assert mthd(1) == dict(one=1) assert mthd(1, 2) == dict(one=1, two=(2,)) assert mthd(1, 21, 22, 23) == dict(one=1, two=(21, 22, 23)) assert mthd(1, (21, 22, 23)) == dict(one=1, two=(21, 22, 23)) assert mthd(three=3, four=4) == dict(three=3, four=4) assert mthd(three=3, four=4, one=1, two=2) == \ dict(one=1, two=2, three=3, four=4) assert mthd(1, 21, 22, 23, three=3, four=4) == \ dict(one=1, two=(21, 22, 23), three=3, four=4) assert mthd(1, (21, 22, 23), three=3, four=4) == \ dict(one=1, two=(21, 22, 23), three=3, four=4)
def finalize_core(self, ctx, **defaults): """ Helper method used in testing `Env._finalize_core`. """ # We must force in_tree=True so we don't load possible config files in # /etc/ipa/, whose contents could break this test: (o, home) = self.new(in_tree=True) if ctx: o.context = ctx # Check that calls cascade down the chain: set_here = ('in_server', 'logdir', 'log') assert o._isdone('_bootstrap') is False assert o._isdone('_finalize_core') is False assert o._isdone('_finalize') is False for key in set_here: assert key not in o o._finalize_core(**defaults) assert o._isdone('_bootstrap') is True assert o._isdone('_finalize_core') is True assert o._isdone('_finalize') is False # Should not cascade for key in set_here: assert key in o # Check that it can't be called twice: e = raises(StandardError, o._finalize_core) assert str(e) == 'Env._finalize_core() already called' return (o, home)
def test_rename(self): self.r.ippool_create('old') self.r.ippool_rename('old', 'new') assert not get_pool('old') assert get_pool('new') with raises(InvalidParameterError): self.r.ippool_rename('new', 'a' * 300)
def test_islocked(): """ Test the `ipalib.base.islocked` function. """ f = base.islocked # Test with ReadOnly instance: o = base.ReadOnly() assert f(o) is False o.__lock__() assert f(o) is True # Test with another class implemented locking protocol: class Lockable(object): __locked = False def __lock__(self): self.__locked = True def __islocked__(self): return self.__locked o = Lockable() assert f(o) is False o.__lock__() assert f(o) is True # Test with a class incorrectly implementing the locking protocol: class Broken(object): __lock__ = False def __islocked__(self): return False o = Broken() e = raises(AssertionError, f, o) assert str(e) == 'no __lock__() method: %r' % o
def test_execute(self): """ Test the `ipalib.frontend.Command.execute` method. """ o = self.cls() e = raises(NotImplementedError, o.execute) assert str(e) == 'Command.execute()'
def test_xml_loads(): """ Test the `ipalib.rpc.xml_loads` function. """ f = rpc.xml_loads params = (binary_bytes, utf8_bytes, unicode_str, None) wrapped = rpc.xml_wrap(params) # Test un-serializing an RPC request: data = dumps(wrapped, 'the_method', allow_none=True) (p, m) = f(data) assert_equal(m, u'the_method') assert_equal(p, params) # Test un-serializing an RPC response: data = dumps((wrapped, ), methodresponse=True, allow_none=True) (tup, m) = f(data) assert m is None assert len(tup) == 1 assert type(tup) is tuple assert_equal(tup[0], params) # Test un-serializing an RPC response containing a Fault: for error in (unicode_str, u'hello'): fault = Fault(69, error) data = dumps(fault, methodresponse=True, allow_none=True, encoding='UTF-8') e = raises(Fault, f, data) assert e.faultCode == 69 assert_equal(e.faultString, error) assert type(e.faultString) is unicode
def test_get_param_iterable(self): """ Test the `ipalib.frontend.HasParam._get_param_iterable` method. """ class WithTuple(self.cls): takes_stuff = ('one', 'two') o = WithTuple() assert o._get_param_iterable('stuff') is WithTuple.takes_stuff junk = ('three', 'four') class WithCallable(self.cls): def takes_stuff(self): return junk o = WithCallable() assert o._get_param_iterable('stuff') is junk class WithParam(self.cls): takes_stuff = parameters.Str('five') o = WithParam() assert o._get_param_iterable('stuff') == (WithParam.takes_stuff,) class WithStr(self.cls): takes_stuff = 'six' o = WithStr() assert o._get_param_iterable('stuff') == ('six',) class Wrong(self.cls): takes_stuff = ['seven', 'eight'] o = Wrong() e = raises(TypeError, o._get_param_iterable, 'stuff') assert str(e) == '%s.%s must be a tuple, callable, or spec; got %r' % ( 'Wrong', 'takes_stuff', Wrong.takes_stuff )
def test_connect(self): """ Test the `ipalib.backend.Connectible.connect` method. """ # Test that connection is created: class example(self.cls): def create_connection(self, *args, **kw): object.__setattr__(self, 'args', args) object.__setattr__(self, 'kw', kw) return 'The connection.' o = example() args = ('Arg1', 'Arg2', 'Arg3') kw = dict(key1='Val1', key2='Val2', key3='Val3') assert not hasattr(context, 'example') assert o.connect(*args, **kw) is None conn = context.example assert type(conn) is Connection assert o.args == args assert o.kw == kw assert conn.conn == 'The connection.' assert conn.disconnect == o.disconnect # Test that StandardError is raised if already connected: m = "connect: 'context.%s' already exists in thread %r" e = raises(StandardError, o.connect, *args, **kw) assert str(e) == m % ('example', threading.currentThread().getName()) # Double check that it works after deleting context.example: del context.example assert o.connect(*args, **kw) is None
def test_xml_loads(): """ Test the `ipalib.rpc.xml_loads` function. """ f = rpc.xml_loads params = (binary_bytes, utf8_bytes, unicode_str, None) wrapped = rpc.xml_wrap(params) # Test un-serializing an RPC request: data = dumps(wrapped, 'the_method', allow_none=True) (p, m) = f(data) assert_equal(m, u'the_method') assert_equal(p, params) # Test un-serializing an RPC response: data = dumps((wrapped,), methodresponse=True, allow_none=True) (tup, m) = f(data) assert m is None assert len(tup) == 1 assert type(tup) is tuple assert_equal(tup[0], params) # Test un-serializing an RPC response containing a Fault: for error in (unicode_str, u'hello'): fault = Fault(69, error) data = dumps(fault, methodresponse=True, allow_none=True, encoding='UTF-8') e = raises(Fault, f, data) assert e.faultCode == 69 assert_equal(e.faultString, error) assert type(e.faultString) is unicode
def test_xml_dumps(): """ Test the `ipalib.rpc.xml_dumps` function. """ f = rpc.xml_dumps params = (binary_bytes, utf8_bytes, unicode_str, None) # Test serializing an RPC request: data = f(params, 'the_method') (p, m) = loads(data) assert_equal(m, u'the_method') assert type(p) is tuple assert rpc.xml_unwrap(p) == params # Test serializing an RPC response: data = f((params,), methodresponse=True) (tup, m) = loads(data) assert m is None assert len(tup) == 1 assert type(tup) is tuple assert rpc.xml_unwrap(tup[0]) == params # Test serializing an RPC response containing a Fault: fault = Fault(69, unicode_str) data = f(fault, methodresponse=True) e = raises(Fault, loads, data) assert e.faultCode == 69 assert_equal(e.faultString, unicode_str)
def test_xml_dumps(): """ Test the `ipalib.rpc.xml_dumps` function. """ f = rpc.xml_dumps params = (binary_bytes, utf8_bytes, unicode_str, None) # Test serializing an RPC request: data = f(params, 'the_method') (p, m) = loads(data) assert_equal(m, u'the_method') assert type(p) is tuple assert rpc.xml_unwrap(p) == params # Test serializing an RPC response: data = f((params, ), methodresponse=True) (tup, m) = loads(data) assert m is None assert len(tup) == 1 assert type(tup) is tuple assert rpc.xml_unwrap(tup[0]) == params # Test serializing an RPC response containing a Fault: fault = Fault(69, unicode_str) data = f(fault, methodresponse=True) e = raises(Fault, loads, data) assert e.faultCode == 69 assert_equal(e.faultString, unicode_str)
def test_lock(self): """ Test the `ipalib.config.Env.__lock__` method. """ o = self.cls() assert o.__islocked__() is False o.__lock__() assert o.__islocked__() is True e = raises(StandardError, o.__lock__) assert str(e) == 'Env.__lock__() already called' # Also test with base.lock() function: o = self.cls() assert o.__islocked__() is False assert base.lock(o) is o assert o.__islocked__() is True e = raises(AssertionError, base.lock, o) assert str(e) == 'already locked: %r' % o
def test_call(self): """ Test the `ipalib.plugable.Plugin.call` method. """ o = self.cls() o.call('/bin/true') is None e = raises(errors.SubprocessError, o.call, '/bin/false') assert e.returncode == 1 assert e.argv == ('/bin/false',)
def test_unmarshal(self): """ Test the `ipaserver.rpcserver.jsonserver.unmarshal` method. """ (o, api, home) = self.instance('Backend', in_server=True) # Test with invalid JSON-data: e = raises(errors.JSONError, o.unmarshal, 'this wont work') assert isinstance(e.error, ValueError) assert unicode(e.error) == 'No JSON object could be decoded' # Test with non-dict type: e = raises(errors.JSONError, o.unmarshal, json.dumps([1, 2, 3])) assert unicode(e.error) == 'Request must be a dict' params = [[1, 2], dict(three=3, four=4)] # Test with missing method: d = dict(params=params, id=18) e = raises(errors.JSONError, o.unmarshal, json.dumps(d)) assert unicode(e.error) == 'Request is missing "method"' # Test with missing params: d = dict(method='echo', id=18) e = raises(errors.JSONError, o.unmarshal, json.dumps(d)) assert unicode(e.error) == 'Request is missing "params"' # Test with non-list params: for p in ('hello', dict(args=tuple(), options=dict())): d = dict(method='echo', id=18, params=p) e = raises(errors.JSONError, o.unmarshal, json.dumps(d)) assert unicode(e.error) == 'params must be a list' # Test with other than 2 params: for p in ([], [tuple()], [None, dict(), tuple()]): d = dict(method='echo', id=18, params=p) e = raises(errors.JSONError, o.unmarshal, json.dumps(d)) assert unicode(e.error) == 'params must contain [args, options]' # Test when args is not a list: d = dict(method='echo', id=18, params=['args', dict()]) e = raises(errors.JSONError, o.unmarshal, json.dumps(d)) assert unicode(e.error) == 'params[0] (aka args) must be a list' # Test when options is not a dict: d = dict(method='echo', id=18, params=[('hello', 'world'), 'options']) e = raises(errors.JSONError, o.unmarshal, json.dumps(d)) assert unicode(e.error) == 'params[1] (aka options) must be a dict' # Test with valid values: args = [u'jdoe'] options = dict(givenname=u'John', sn='Doe') d = dict(method=u'user_add', params=[args, options], id=18) assert o.unmarshal(json.dumps(d)) == (u'user_add', args, options, 18)
def test_create_connection(self): """ Test the `ipalib.backend.Connectible.create_connection` method. """ class example(self.cls): pass for klass in (self.cls, example): o = klass() e = raises(NotImplementedError, o.create_connection) assert str(e) == '%s.create_connection()' % klass.__name__
def bootstrap(self, **overrides): """ Helper method used in testing bootstrap related methods below. """ (o, home) = self.new() assert o._isdone('_bootstrap') is False o._bootstrap(**overrides) assert o._isdone('_bootstrap') is True e = raises(StandardError, o._bootstrap) assert str(e) == 'Env._bootstrap() already called' return (o, home)
def test_lock(self): """ Test the `ipalib.base.ReadOnly.__lock__` method. """ o = self.cls() assert o._ReadOnly__locked is False o.__lock__() assert o._ReadOnly__locked is True e = raises(AssertionError, o.__lock__) # Can only be locked once assert str(e) == '__lock__() can only be called once' assert o._ReadOnly__locked is True # This should still be True
def test_validate(self): """ Test the `ipalib.output.ListOfEntries.validate` method. """ class example(Command): pass cmd = example() inst = self.cls('stuff') okay = dict(foo='bar') nope = ('aye', 'bee') e = raises(TypeError, inst.validate, cmd, [okay, okay, nope]) assert str(e) == output.emsg % ( 'example', 'ListOfEntries', 'stuff', 2, dict, tuple, nope ) e = raises(TypeError, inst.validate, cmd, [nope, okay, nope]) assert str(e) == output.emsg % ( 'example', 'ListOfEntries', 'stuff', 0, dict, tuple, nope )
def test_setattr(self): """ Test the `ipalib.base.ReadOnly.__setattr__` method. """ o = self.cls() o.attr1 = 'Hello, world!' assert o.attr1 == 'Hello, world!' o.__lock__() for name in ('attr1', 'attr2'): e = raises(AttributeError, setattr, o, name, 'whatever') assert str(e) == SET_ERROR % ('ReadOnly', name, 'whatever') assert o.attr1 == 'Hello, world!'