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_pwpolicy_success(self): response = self._changepw(testuser, old_password, new_password) assert_equal(response.status, 200) assert_equal(response.getheader('X-IPA-Pwchange-Result'), 'ok') # make sure that password IS changed self._checkpw(testuser, new_password)
def test_invalid_auth(self): response = self._changepw(testuser, 'wrongpassword', 'new_password') assert_equal(response.status, 200) assert_equal(response.getheader('X-IPA-Pwchange-Result'), 'invalid-password') # make sure that password is NOT changed self._checkpw(testuser, old_password)
def test_internal_error(): f = rpcserver.HTTP_Status() t = rpcserver._internal_error_template s = StartResponse() assert_equal(f.internal_error(None, s, 'request failed'), [t % dict(message='request failed')]) assert s.status == '500 Internal Server Error' assert s.headers == [('Content-Type', 'text/html; charset=utf-8')]
def test_bad_request(): f = rpcserver.HTTP_Status() t = rpcserver._bad_request_template s = StartResponse() assert_equal(f.bad_request(None, s, 'illegal request'), [t % dict(message='illegal request')]) assert s.status == '400 Bad Request' assert s.headers == [('Content-Type', 'text/html; charset=utf-8')]
def test_unauthorized_error(): f = rpcserver.HTTP_Status() t = rpcserver._unauthorized_template s = StartResponse() assert_equal(f.unauthorized(None, s, 'unauthorized', 'password-expired'), [t % dict(message='unauthorized')]) assert s.status == '401 Unauthorized' assert s.headers == [('Content-Type', 'text/html; charset=utf-8'), ('X-IPA-Rejection-Reason', 'password-expired')]
def test_bad_request(): f = rpcserver.HTTP_Status() t = rpcserver._bad_request_template s = StartResponse() assert_equal( f.bad_request(None, s, 'illegal request'), [t % dict(message='illegal request')] ) assert s.status == '400 Bad Request' assert s.headers == [('Content-Type', 'text/html; charset=utf-8')]
def test_internal_error(): f = rpcserver.HTTP_Status() t = rpcserver._internal_error_template s = StartResponse() assert_equal( f.internal_error(None, s, 'request failed'), [t % dict(message='request failed')] ) assert s.status == '500 Internal Server Error' assert s.headers == [('Content-Type', 'text/html; charset=utf-8')]
def test_convert(self): """ Test the `ipalib.frontend.Command.convert` method. """ kw = dict( option0=u'1.5', option1=u'7', ) o = self.subcls() o.finalize() for (key, value) in o.convert(**kw).iteritems(): assert_equal(unicode(kw[key]), value)
def test_unauthorized_error(): f = rpcserver.HTTP_Status() t = rpcserver._unauthorized_template s = StartResponse() assert_equal( f.unauthorized(None, s, 'unauthorized', 'password-expired'), [t % dict(message='unauthorized')] ) assert s.status == '401 Unauthorized' assert s.headers == [('Content-Type', 'text/html; charset=utf-8'), ('X-IPA-Rejection-Reason', 'password-expired')]
def test_bad_options(self): for params in (None, # no params {'user': '******'}, # missing options {'user': '******', 'old_password' : 'old'}, # missing option {'user': '******', 'old_password' : 'old', 'new_password' : ''}, # empty option ): response = self.send_request(params=params) assert_equal(response.status, 400) assert_equal(response.reason, 'Bad Request')
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_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_not_found(): f = rpcserver.HTTP_Status() t = rpcserver._not_found_template s = StartResponse() # Test with an innocent URL: url = '/ipa/foo/stuff' assert_equal(f.not_found(None, s, url, None), [t % dict(url='/ipa/foo/stuff')]) assert s.status == '404 Not Found' assert s.headers == [('Content-Type', 'text/html; charset=utf-8')] # Test when URL contains any of '<>&' s.reset() url = ' ' + '<script>do_bad_stuff();</script>' assert_equal(f.not_found(None, s, url, None), [ t % dict(url='&nbsp;<script>do_bad_stuff();</script>') ]) assert s.status == '404 Not Found' assert s.headers == [('Content-Type', 'text/html; charset=utf-8')]
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_not_found(): f = rpcserver.HTTP_Status() t = rpcserver._not_found_template s = StartResponse() # Test with an innocent URL: url = '/ipa/foo/stuff' assert_equal( f.not_found(None, s, url, None), [t % dict(url='/ipa/foo/stuff')] ) assert s.status == '404 Not Found' assert s.headers == [('Content-Type', 'text/html; charset=utf-8')] # Test when URL contains any of '<>&' s.reset() url =' ' + '<script>do_bad_stuff();</script>' assert_equal( f.not_found(None, s, url, None), [t % dict(url='&nbsp;<script>do_bad_stuff();</script>')] ) assert s.status == '404 Not Found' assert s.headers == [('Content-Type', 'text/html; charset=utf-8')]
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_pwpolicy_error(self): response = self._changepw(testuser, old_password, '1') assert_equal(response.status, 200) assert_equal(response.getheader('X-IPA-Pwchange-Result'), 'policy-error') assert_equal(response.getheader('X-IPA-Pwchange-Policy-Error'), 'Constraint violation: Password is too short') # make sure that password is NOT changed self._checkpw(testuser, old_password)
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_round_trip(): """ Test `ipalib.rpc.xml_wrap` and `ipalib.rpc.xml_unwrap`. This tests the two functions together with ``xmlrpclib.dumps()`` and ``xmlrpclib.loads()`` in a full wrap/dumps/loads/unwrap round trip. """ # We first test that our assumptions about xmlrpclib module in the Python # standard library are correct: assert_equal(dump_n_load(utf8_bytes), unicode_str) assert_equal(dump_n_load(unicode_str), unicode_str) assert_equal(dump_n_load(Binary(binary_bytes)).data, binary_bytes) assert isinstance(dump_n_load(Binary(binary_bytes)), Binary) assert type(dump_n_load('hello')) is str assert type(dump_n_load(u'hello')) is str assert_equal(dump_n_load(''), '') assert_equal(dump_n_load(u''), '') assert dump_n_load(None) is None # Now we test our wrap and unwrap methods in combination with dumps, loads: # All str should come back str (because they get wrapped in # xmlrpclib.Binary(). All unicode should come back unicode because str # explicity get decoded by rpc.xml_unwrap() if they weren't already # decoded by xmlrpclib.loads(). assert_equal(round_trip(utf8_bytes), utf8_bytes) assert_equal(round_trip(unicode_str), unicode_str) assert_equal(round_trip(binary_bytes), binary_bytes) assert type(round_trip('hello')) is str assert type(round_trip(u'hello')) is unicode assert_equal(round_trip(''), '') assert_equal(round_trip(u''), u'') assert round_trip(None) is None compound = [utf8_bytes, None, binary_bytes, (None, unicode_str), dict(utf8=utf8_bytes, chars=unicode_str, data=binary_bytes) ] assert round_trip(compound) == tuple(compound)
def test_round_trip(): """ Test `ipalib.rpc.xml_wrap` and `ipalib.rpc.xml_unwrap`. This tests the two functions together with ``xmlrpclib.dumps()`` and ``xmlrpclib.loads()`` in a full wrap/dumps/loads/unwrap round trip. """ # We first test that our assumptions about xmlrpclib module in the Python # standard library are correct: assert_equal(dump_n_load(utf8_bytes), unicode_str) assert_equal(dump_n_load(unicode_str), unicode_str) assert_equal(dump_n_load(Binary(binary_bytes)).data, binary_bytes) assert isinstance(dump_n_load(Binary(binary_bytes)), Binary) assert type(dump_n_load('hello')) is str assert type(dump_n_load(u'hello')) is str assert_equal(dump_n_load(''), '') assert_equal(dump_n_load(u''), '') assert dump_n_load(None) is None # Now we test our wrap and unwrap methods in combination with dumps, loads: # All str should come back str (because they get wrapped in # xmlrpclib.Binary(). All unicode should come back unicode because str # explicity get decoded by rpc.xml_unwrap() if they weren't already # decoded by xmlrpclib.loads(). assert_equal(round_trip(utf8_bytes), utf8_bytes) assert_equal(round_trip(unicode_str), unicode_str) assert_equal(round_trip(binary_bytes), binary_bytes) assert type(round_trip('hello')) is str assert type(round_trip(u'hello')) is unicode assert_equal(round_trip(''), '') assert_equal(round_trip(u''), u'') assert round_trip(None) is None compound = [ utf8_bytes, None, binary_bytes, (None, unicode_str), dict(utf8=utf8_bytes, chars=unicode_str, data=binary_bytes) ] assert round_trip(compound) == tuple(compound)
def test_init(self): """ Test the `ipalib.errors.PublicError.__init__` method. """ message = u'The translated, interpolated message' format = 'key=%(key1)r and key2=%(key2)r' uformat = u'Translated key=%(key1)r and key2=%(key2)r' val1 = 'Value 1' val2 = 'Value 2' kw = dict(key1=val1, key2=val2) # Test with format=str, message=None inst = self.klass(format, **kw) assert inst.format is format assert_equal(inst.message, format % kw) assert inst.forwarded is False assert inst.key1 is val1 assert inst.key2 is val2 # Test with format=None, message=unicode inst = self.klass(message=message, **kw) assert inst.format is None assert inst.message is message assert inst.strerror is message assert inst.forwarded is True assert inst.key1 is val1 assert inst.key2 is val2 # Test with format=None, message=str e = raises(TypeError, self.klass, message='the message', **kw) assert str(e) == TYPE_ERROR % ('message', unicode, 'the message', str) # Test with format=None, message=None e = raises(ValueError, self.klass, **kw) assert str(e) == \ 'PublicError.format is None yet format=None, message=None' ###################################### # Test via PublicExceptionTester.new() # Test with format=str, message=None inst = self.new(format, **kw) assert isinstance(inst, self.klass) assert inst.format is format assert_equal(inst.message, format % kw) assert inst.forwarded is False assert inst.key1 is val1 assert inst.key2 is val2 # Test with format=None, message=unicode inst = self.new(message=message, **kw) assert isinstance(inst, self.klass) assert inst.format is None assert inst.message is message assert inst.strerror is message assert inst.forwarded is True assert inst.key1 is val1 assert inst.key2 is val2 ################## # Test a subclass: class subclass(self.klass): format = '%(true)r %(text)r %(number)r' uformat = u'Translated %(true)r %(text)r %(number)r' kw = dict(true=True, text='Hello!', number=18) # Test with format=str, message=None e = raises(ValueError, subclass, format, **kw) assert str(e) == 'non-generic %r needs format=None; got format=%r' % ( 'subclass', format) # Test with format=None, message=None: inst = subclass(**kw) assert inst.format is subclass.format assert_equal(inst.message, subclass.format % kw) assert inst.forwarded is False assert inst.true is True assert inst.text is kw['text'] assert inst.number is kw['number'] # Test with format=None, message=unicode: inst = subclass(message=message, **kw) assert inst.format is subclass.format assert inst.message is message assert inst.strerror is message assert inst.forwarded is True assert inst.true is True assert inst.text is kw['text'] assert inst.number is kw['number'] # Test with instructions: # first build up "instructions", then get error and search for # lines of instructions appended to the end of the strerror # despite the parameter 'instructions' not existing in the format instructions = u"The quick brown fox jumps over the lazy dog".split() # this expression checks if each word of instructions # exists in a string as a separate line, with right order regexp = re.compile('(?ims).*' + ''.join(map(lambda x: '(%s).*' % (x), instructions)) + '$') inst = subclass(instructions=instructions, **kw) assert inst.format is subclass.format assert_equal(inst.instructions, instructions) inst_match = regexp.match(inst.strerror).groups() assert_equal(list(inst_match),list(instructions))