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_bad_params(self): """ Test against bad (missing, empty) params """ for params in ( None, # no params { 'username': '******' }, # missing password { 'password': '******' }, # missing username { 'username': '', 'password': '' }, # empty options { 'username': '', 'password': '******' }, # empty username { 'username': '******', 'password': '' }, # empty password ): response = self.send_request(params=params) assert_equal(response.status, 400) assert_equal(response.reason, 'Bad Request')
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_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_not_found(): api = 'the api instance' f = rpcserver.HTTP_Status(api) 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')).encode('utf-8')] ) 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>') ).encode('utf-8')] ) assert s.status == '404 Not Found' assert s.headers == [('Content-Type', 'text/html; charset=utf-8')]
def test_migration_success(self): """ Test successful migration scenario """ response = self._migratepw(testuser, password) assert_equal(response.status, 200) assert_equal(response.getheader('X-IPA-Migrate-Result'), 'ok')
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_not_post_method(self): """ Test redirection of non POST request """ response = self._migratepw(testuser, password, method='GET') assert_equal(response.status, 302) assert response.msg assert_equal(response.msg['Location'], 'index.html')
def test_invalid_password(self): """ Test invalid password """ response = self._migratepw(testuser, 'wrongpassword') assert_equal(response.status, 200) assert_equal(response.getheader('X-IPA-Migrate-Result'), 'invalid-password')
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_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_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_i18n_consequence_receive(self): """ Test if consequence translations requests for different languages are successful. Every request's result have to contain messages in it's locale. """ prev_i18n_msgs = self._fetch_i18n_msgs_http('en-us') cur_i18n_msgs = self._fetch_i18n_msgs_http('fr-fr') try: assert_equal(prev_i18n_msgs['texts']['true'], u'True') assert_equal(cur_i18n_msgs['texts']['true'], u'Vrai') except KeyError: assert_not_equal(prev_i18n_msgs, cur_i18n_msgs)
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 test_jsplugins(self): empty_response = "define([],function(){return[];});" # Step 1: make sure default response has no additional plugins response = self.send_request(method='GET') assert_equal(response.status, 200) response_data = response.read().decode(encoding='utf-8') assert_equal(response_data, empty_response) # Step 2: add fake plugins try: for (d, f) in self.jsplugins: dir = os.path.join(paths.IPA_JS_PLUGINS_DIR, d) if not os.path.exists(dir): os.mkdir(dir, 0o755) if f: with open(os.path.join(dir, f), 'w') as js: js.write("/* test js plugin */") except OSError as e: pytest.skip('Cannot set up test JS plugin: %s' % e) # Step 3: query plugins to see if our plugins exist response = self.send_request(method='GET') assert_equal(response.status, 200) response_data = response.read().decode(encoding='utf-8') assert_not_equal(response_data, empty_response) for (d, f) in self.jsplugins: if f: assert "'" + d + "'" in response_data else: assert "'" + d + "'" not in response_data # Step 4: remove fake plugins try: for (d, f) in self.jsplugins: dir = os.path.join(paths.IPA_JS_PLUGINS_DIR, d) file = os.path.join(dir, f) if f and os.path.exists(file): os.unlink(file) if os.path.exists(dir): os.rmdir(dir) except OSError: pass # Step 5: make sure default response has no additional plugins response = self.send_request(method='GET') assert_equal(response.status, 200) response_data = response.read().decode(encoding='utf-8') assert_equal(response_data, empty_response)
def test_convert(self): """ Test the `ipalib.frontend.Command.convert` method. """ class api(object): @staticmethod def is_production_mode(): return False kw = dict( option0=u'1.5', option1=u'7', ) o = self.subcls(api) o.finalize() for (key, value) in o.convert(**kw).items(): assert_equal(unicode(kw[key]), value)
def _fetch_i18n_msgs_http(self, accept_lang): """ Fetch translations via http request """ self.accept_language = accept_lang params = json.dumps(self._prepare_data('i18n_messages')) response = self.send_request(params=params) assert_equal(response.status, 200) response_data = response.read() jsondata = json.loads(response_data) assert_equal(jsondata['error'], None) assert jsondata['result'] assert jsondata['result']['texts'] return jsondata['result']
def test_convert(self): """ Test the `ipalib.frontend.Command.convert` method. """ class api: @staticmethod def is_production_mode(): return False kw = dict( option0=u'1.5', option1=u'7', ) o = self.subcls(api) o.finalize() for (key, value) in o.convert(**kw).items(): assert_equal(unicode(kw[key]), value)
def test_bad_options(self): for params in ( None, # no params { 'user': '******' }, # missing options { 'user': '******', 'old_password': '******' }, # missing option { 'user': '******', 'old_password': '******', 'new_password': '' }, # empty option ): response = self.send_request(params=params) assert_equal(response.status, 400) assert_equal(response.reason, 'Bad Request')
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_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_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 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_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_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_ping(self): """Ping the server.""" result = self.tracker.run_command('ping') exp = {'summary': Fuzzy('IPA server version .*. API version .*')} assert_equal(result, exp)
def upg_check(response): """Check that the user was assigned to the corresponding private group.""" assert_equal(response['result']['uidnumber'], response['result']['gidnumber']) return 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 ``xmlrpc.client.dumps()`` and ``xmlrpc.client.loads()`` in a full wrap/dumps/loads/unwrap round trip. """ # We first test that our assumptions about xmlrpc.client module in the Python # standard library are correct: if six.PY2: output_binary_type = bytes else: output_binary_type = Binary if six.PY2: assert_equal(dump_n_load(utf8_bytes), unicode_str) assert_equal(dump_n_load(unicode_str), unicode_str) # "Binary" is not "str". pylint: disable=no-member 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(b'hello')) is output_binary_type assert type(dump_n_load(u'hello')) is str assert_equal(dump_n_load(b''), output_binary_type(b'')) assert_equal(dump_n_load(u''), str()) assert dump_n_load(None) is None # Now we test our wrap and unwrap methods in combination with dumps, loads: # All bytes should come back bytes (because they get wrapped in # xmlrpc.client.Binary(). All unicode should come back unicode because str # explicity get decoded by rpc.xml_unwrap() if they weren't already # decoded by xmlrpc.client.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(b'hello')) is bytes assert type(round_trip(u'hello')) is unicode assert_equal(round_trip(b''), b'') 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_context_request_url(self): """ Test that request_url is set in `ipalib.rpc.rpcclient.connect` """ request_url = getattr(context, 'request_url', None) assert_equal(request_url, 'https://%s/ipa/session/json' % api.env.host)
def test_context_principal(self): """ Test that principal is set in `ipalib.rpc.rpcclient.connect` """ principal = getattr(context, 'principal', None) assert_equal(principal, 'admin@%s' % api.env.realm)
def test_context_cafile(self): """ Test that ca_certfile is set in `ipalib.rpc.rpcclient.connect` """ ca_certfile = getattr(context, 'ca_certfile', None) assert_equal(ca_certfile, 'foo')
def test_init(self): message = u'The translated, interpolated message' format = 'key=%(key1)r and key2=%(key2)r' val1 = u'Value 1' val2 = u'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(str(inst), 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 str(inst) == 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=bytes e = raises(TypeError, self.klass, message=b'the message', **kw) assert str(e) == TYPE_ERROR % ('message', unicode, b'the message', bytes) # Test with format=None, message=None e = raises(ValueError, self.klass, **kw) assert (str(e) == '%s.format is None yet format=None, message=None' % self.klass.__name__) ###################################### # 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(str(inst), 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 str(inst) == 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' kw = dict(true=True, text=u'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(str(inst), 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 str(inst) == 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('(%s).*' % (x) for x in instructions) + '$') inst = subclass(instructions=instructions, **kw) assert inst.format is subclass.format assert_equal(inst.instructions, unicode(instructions)) inst_match = regexp.match(inst.strerror).groups() assert_equal(list(inst_match), list(instructions))
def test_init(self): message = u'The translated, interpolated message' format = 'key=%(key1)r and key2=%(key2)r' val1 = u'Value 1' val2 = u'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(str(inst), 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 str(inst) == 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=bytes e = raises(TypeError, self.klass, message=b'the message', **kw) assert str(e) == TYPE_ERROR % ('message', unicode, b'the message', bytes) # Test with format=None, message=None e = raises(ValueError, self.klass, **kw) assert (str(e) == '%s.format is None yet format=None, message=None' % self.klass.__name__) ###################################### # 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(str(inst), 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 str(inst) == 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' kw = dict(true=True, text=u'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(str(inst), 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 str(inst) == 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('(%s).*' % (x) for x in instructions) + '$') inst = subclass(instructions=instructions, **kw) assert inst.format is subclass.format assert_equal(inst.instructions, unicode(instructions)) inst_match = regexp.match(inst.strerror).groups() assert_equal(list(inst_match),list(instructions))