我正在我的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中检索导致错误的整个参数呢?
暂无答案!
目前还没有任何答案,快来回答吧!