我正在Web应用程序中实现一些错误处理:
import parse
try:
cursor.execute("INSERT INTO User (email, name, hash) VALUES ('%s', '%s', '%s');" % (email, name, pw_hash))
except MySQLdb.IntegrityError as e:
msg = e.args[1]
print(email)
print(e)
if "Duplicate entry" in msg:
fields = parse("Duplicate entry '{}' for key '{}'", msg)
msg = "%s %s already exists." % (fields[1], fields[0])
raise ConflictException(msg) //sends response to client with status code 409
问题在于异常不包括导致错误的输入的整个字符串。
当我测试重复的电子邮件时,会生成一个合理有效的电子邮件,当mysql尝试插入已经存在的电子邮件时,将引发IntegrityError
。
当我打印错误而不是输入电子邮件时,错误中的电子邮件已被截断:
实际输入的电子邮件:
a+EMCayiy_O+xGVcYZxvZqHZTMv9-6aE2qSElp7LHQIdcmLMKbvlXo89nrUNsIFbplm36lVmQRvjzABDhGVab_LLvWQLDkyoMJakzb8FcacHnNgj642jLhbu5imT+ENxR01W-DcWTJdZPRo0V155UW@PakZ7hfY2I953-4ackKNoNrJbcHkcwNGruEvprdAFgz2xpVvTbzt0LMxHZEgNYuA641Uj9AA1zC39B6C.VzCgqPzPj09bSqDyPNjDuZR
数据库抛出的错误:
(1062, "Duplicate entry 'a+EMCayiy_O+xGVcYZxvZqHZTMv9-6aE2qSElp7LHQIdcmLMKbvlXo89nrUNsIFb' for key 'email'")
因此,我的测试失败了:
def assert_register_fail(self, email, name, password, confirmed_password, expected_msg, expected_code):
response = self.register(email, name, password, confirmed_password)
res = json.loads(response.data.decode())
self.assertEqual(response.status_code, expected_code)
self.assertEqual(res["message"], expected_msg)
def test_email_taken(self):
email = self.gen_email()
password = self.gen_pass()
expected_msg = "email %s already exists." % email
self.assert_register_success(email, self.gen_name(), password, password)
self.assert_register_fail(email, self.gen_name(), password, password, expected_msg, 409)
测试显然希望错误消息中包含整个无效电子邮件:
AssertionError: 'emai[61 chars]5YD.q already exists.' != 'emai[61 chars]5YD.qq5Po.OYDxtaL-UcMDYx4Uw5aEth-+GWeMJrSat_fH[162 chars]sts.'
- email Jf5QbVi+l1x3VOrYYc5c-wlgg+s7b4TOHVQqHwtIT+rouTe1CQShWlX384d5YD.q already exists.
+ email Jf5QbVi+l1x3VOrYYc5c-wlgg+s7b4TOHVQqHwtIT+rouTe1CQShWlX384d5YD.qq5Po.OYDxtaL-UcMDYx4Uw5aEth-+GWeMJrSat_fHF6THMOwBOawCZo1Vu8.hJoWvH.l.LUYNwANrtgAy+vM.h@W884ZKLYhgknKSeDSCQxC9lLUYa3KSVXNKPUWxIyNXyK9De-FN-t935GBb3ma6b2wWel-L4xL2zM3Y6M.Qy5g3O-i2SMiE7PpsdALSUs already exists.
我可以一起破解一些完全使用另一种方法的东西,但我认为这不会更好。
此外,我可以将生成的电子邮件长度限制为大约60个字符,这时mysql不会截断。测试将通过,但它们可能无法反映实际情况。
那么,如何从mysql检索导致错误的整个参数呢?