def test_iter_output(self): """ Test the ``ipalib.frontend.Command._iter_output`` instance attribute. """ api = 'the api instance' class Example(self.cls): pass inst = Example(api) 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_02_remove_cert_from_nonexistent_entity(self): """ Tests whether trying to remove certificates from a non-existent entry raises NotFound error. """ raises(errors.NotFound, self.cert_add_cmd, self.non_existent_entity, usercertificate=self.certs)
def test_01_add_cert_to_nonexistent_entity(self): """ Tests whether trying to add certificates to a non-existent entry raises NotFound error. """ raises(errors.NotFound, self.cert_add_cmd, self.non_existent_entity, usercertificate=self.certs)
def test_validate(self): """ Test the `ipalib.frontend.Command.validate` method. """ class api(object): env = config.Env(context='cli') @staticmethod def is_production_mode(): return False sub = self.subcls(api) 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, u'option0') assert_equal(e.error, u"must equal 'option0'") # 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_Registry(): """ Test the `ipalib.plugable.Registry` class """ class Base1(object): pass class Base2(object): pass class Base3(object): pass class plugin1(Base1): pass class plugin2(Base2): pass class plugin3(Base3): pass # Test creation of Registry: r = plugable.Registry() # Check that TypeError is raised trying to register something that isn't # a class: p = plugin1() e = raises(TypeError, r(), p) assert str(e) == 'plugin must be a class; got %r' % p # Check that registration works r()(plugin1) # Check that DuplicateError is raised trying to register exact class # again: e = raises(errors.PluginDuplicateError, r(), plugin1) assert e.plugin is plugin1 # Check that overriding works class base1_extended(Base1): pass class plugin1(base1_extended): # pylint: disable=function-redefined pass r(override=True)(plugin1) # Test that another plugin can be registered: r()(plugin2) # Setup to test more registration: class plugin1a(Base1): pass r()(plugin1a) class plugin1b(Base1): pass r()(plugin1b) class plugin2a(Base2): pass r()(plugin2a) class plugin2b(Base2): pass r()(plugin2b)
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_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_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_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_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_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 in %s arguments ['arg1?', 'arg2']" % (self.get_instance().name) # 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_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) if six.PY2: bad_type = unicode bad_value = unicode(name) else: bad_type = bytes bad_value = name.encode('ascii') e = raises(TypeError, f, bad_value) assert str(e) == TYPE_ERROR % ('name', str, bad_value, bad_type) 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_09_remove_nonexistent_certs_from_entity(self): """ Tests that an attempt to remove certificates that are not present in the entry raises AttrValueNotFound """ raises(errors.AttrValueNotFound, self.remove_certs, self.nonexistent_certs)
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_bind_as_expired_test_user(self, user): """ Try to bind as expired user """ api.Command['user_mod']( user.uid, krbprincipalexpiration=expired_expiration_string) raises(ldap.UNWILLING_TO_PERFORM, self.connection.simple_bind_s, str(get_user_dn(user.uid)), self.password)
def test_validate_output_per_type(self): """ Test `ipalib.frontend.Command.validate_output` per-type validation. """ class api(object): @staticmethod def is_production_mode(): return False class Complex(self.cls): has_output = ( output.Output('foo', int), output.Output('bar', list), ) inst = Complex(api) inst.finalize() wrong = dict(foo=17.9, bar=[18]) e = raises(TypeError, inst.validate_output, wrong) assert str(e) == '%s:\n output[%r]: need %r; got %r: %r' % ( 'Complex.validate_output()', 'foo', int, float, 17.9 ) wrong = dict(foo=18, bar=17) e = raises(TypeError, inst.validate_output, wrong) assert str(e) == '%s:\n output[%r]: need %r; got %r: %r' % ( 'Complex.validate_output()', 'bar', list, int, 17 )
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_validate_output_nested(self): """ Test `ipalib.frontend.Command.validate_output` nested validation. """ class api(object): @staticmethod def is_production_mode(): return False class Subclass(output.ListOfEntries): pass # Test nested validation: class nested(self.cls): has_output = ( output.Output('hello', int), Subclass('world'), ) inst = nested(api) 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_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_validate_output_nested(self): """ Test `ipalib.frontend.Command.validate_output` nested validation. """ class api: @staticmethod def is_production_mode(): return False class Subclass(output.ListOfEntries): pass # Test nested validation: class nested(self.cls): has_output = ( output.Output('hello', int), Subclass('world'), ) inst = nested(api) 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_validate_output_per_type(self): """ Test `ipalib.frontend.Command.validate_output` per-type validation. """ class api: @staticmethod def is_production_mode(): return False class Complex(self.cls): has_output = ( output.Output('foo', int), output.Output('bar', list), ) inst = Complex(api) inst.finalize() wrong = dict(foo=17.9, bar=[18]) e = raises(TypeError, inst.validate_output, wrong) assert str(e) == '%s:\n output[%r]: need (%r,); got %r: %r' % ( 'Complex.validate_output()', 'foo', int, float, 17.9) wrong = dict(foo=18, bar=17) e = raises(TypeError, inst.validate_output, wrong) assert str(e) == '%s:\n output[%r]: need (%r,); got %r: %r' % ( 'Complex.validate_output()', 'bar', list, int, 17)
def test_validate(self): """ Test the `ipalib.frontend.Command.validate` method. """ class api: env = config.Env(context='cli') @staticmethod def is_production_mode(): return False sub = self.subcls(api) 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, u'option0') assert_equal(e.error, u"must equal 'option0'") # 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. """ api = 'the api instance' class Example(self.cls): pass inst = Example(api) 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_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, API_VERSION), {}, rpc.xml_wrap(result, API_VERSION), ), ( 'user_add', rpc.xml_wrap(params, API_VERSION), {}, Fault(3007, u"'four' is required"), # RequirementError ), ( 'user_add', rpc.xml_wrap(params, API_VERSION), {}, Fault(700, u'no such error'), # There is no error 700 ), ) # Create connection for the current thread setattr(context, o.id, Connection(conn, lambda: None)) 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. """ api = 'the api instance' 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(api) # 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(api) 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(api) 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_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_Registry(): """ Test the `ipalib.plugable.Registry` class """ class Base1(object): pass class Base2(object): pass class plugin1(Base1): pass class plugin2(Base2): pass # Test creation of Registry: r = plugable.Registry() # Check that TypeError is raised trying to register something that isn't # a class: p = plugin1() e = raises(TypeError, r(), p) assert str(e) == 'plugin must be callable; got %r' % p # Check that registration works r()(plugin1) # Check that DuplicateError is raised trying to register exact class # again: e = raises(errors.PluginDuplicateError, r(), plugin1) assert e.plugin is plugin1 # Check that overriding works class base1_extended(Base1): pass class plugin1(base1_extended): # pylint: disable=function-redefined pass r(override=True)(plugin1) # Test that another plugin can be registered: r()(plugin2) # Setup to test more registration: class plugin1a(Base1): pass r()(plugin1a) class plugin1b(Base1): pass r()(plugin1b) class plugin2a(Base2): pass r()(plugin2a) class plugin2b(Base2): pass r()(plugin2b)
def test_filter_param_by_context(self): """ Test the `ipalib.frontend.HasParam._filter_param_by_context` method. """ api = 'the api instance' 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(api) # 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(api) 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(api) 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_08_add_already_present_cert_to_entity(self): """ Tests that ExecutionError is raised when attempting to add certificates to the entry that already contains them. """ raises( errors.ExecutionError, self.add_certs, self.certs_subset )
def test_09_remove_nonexistent_certs_from_entity(self): """ Tests that an attempt to remove certificates that are not present in the entry raises AttrValueNotFound """ raises( errors.AttrValueNotFound, self.remove_certs, self.nonexistent_certs )
def test_10_remove_valid_and_nonexistent_certs_from_entity(self): """ Try to remove multiple certificates. Some of them are not present in the entry. This scenario should raise InvocationError. """ raises( errors.AttrValueNotFound, self.remove_certs, self.mixed_certs )
def test_bind_as_expired_test_user(self, user): """ Try to bind as expired user """ api.Command['user_mod']( user.uid, krbprincipalexpiration=expired_expiration_string ) raises(ldap.UNWILLING_TO_PERFORM, self.connection.simple_bind_s, str(get_user_dn(user.uid)), self.password )
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_forward(self): """ Test the `ipalib.rpc.xmlclient.forward` method. """ class user_add(Command): pass 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, API_VERSION), {}, rpc.xml_wrap(result, API_VERSION), ), ( 'user_add', rpc.xml_wrap(params, API_VERSION), {}, Fault(3007, u"'four' is required"), # RequirementError ), ( 'user_add', rpc.xml_wrap(params, API_VERSION), {}, Fault(700, u'no such error'), # There is no error 700 ), ) # Create connection for the current thread setattr(context, o.id, Connection(conn, lambda: None)) 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_only_i18n_serves(self): """ Test if end point doesn't fulfill other RPC commands """ assert api.Command.get('user_find') params = json.dumps(self._prepare_data('user_find/1')) response = self.send_request(params=params) assert_equal(response.status, 403) assert_equal(response.reason, 'Forbidden') response_data = response.read() assert_equal(response_data, b'Invalid RPC command') raises(ValueError, json.loads, response_data)
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 test_only_post_serves(self): """ Test if end point fulfills only POST method """ params = json.dumps(self._prepare_data('i18n_messages')) response = self.send_request(method='GET', params=params) assert_equal(response.status, 405) assert_equal(response.reason, 'Method Not Allowed') assert response.msg assert_equal(response.msg['allow'], 'POST') response_data = response.read() raises(ValueError, json.loads, response_data)
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_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(shared_instance=True) 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_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, API_VERSION, '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,), API_VERSION, 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, API_VERSION, methodresponse=True) e = raises(Fault, loads, data) assert e.faultCode == 69 assert_equal(e.faultString, unicode_str)
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, API_VERSION) # 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 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(Exception, o._finalize_core) assert str(e) == 'Env._finalize_core() already called' return (o, home)