You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

419 lines
17 KiB

  1. # -*- coding: utf-8 -*-
  2. # Copyright 2016 Tecnativa - Antonio Espinosa
  3. # Copyright 2017 Tecnativa - David Vidal
  4. # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
  5. from odoo.tools import mute_logger
  6. from odoo.tests.common import TransactionCase
  7. from odoo.exceptions import UserError, ValidationError
  8. import mock
  9. import json
  10. _packagepath = 'odoo.addons.mail_tracking_mailgun'
  11. class TestMailgun(TransactionCase):
  12. def mail_send(self):
  13. mail = self.env['mail.mail'].create({
  14. 'subject': 'Test subject',
  15. 'email_from': 'from@example.com',
  16. 'email_to': self.recipient,
  17. 'body_html': '<p>This is a test message</p>',
  18. })
  19. mail.send()
  20. # Search tracking created
  21. tracking_email = self.env['mail.tracking.email'].search([
  22. ('mail_id', '=', mail.id),
  23. ])
  24. return mail, tracking_email
  25. def setUp(self):
  26. super(TestMailgun, self).setUp()
  27. self.recipient = u'to@example.com'
  28. self.mail, self.tracking_email = self.mail_send()
  29. self.api_key = u'key-12345678901234567890123456789012'
  30. self.domain = u'example.com'
  31. self.token = u'f1349299097a51b9a7d886fcb5c2735b426ba200ada6e9e149'
  32. self.timestamp = u'1471021089'
  33. self.signature = ('4fb6d4dbbe10ce5d620265dcd7a3c0b8'
  34. 'ca0dede1433103891bc1ae4086e9d5b2')
  35. self.env['ir.config_parameter'].set_param(
  36. 'mailgun.apikey', self.api_key)
  37. self.env['ir.config_parameter'].set_param(
  38. 'mail.catchall.domain', self.domain)
  39. self.env['ir.config_parameter'].set_param(
  40. 'mailgun.validation_key', self.api_key)
  41. self.event = {
  42. 'Message-Id': u'<xxx.xxx.xxx-openerp-xxx-res.partner@test_db>',
  43. 'X-Mailgun-Sid': u'WyIwNjgxZSIsICJ0b0BleGFtcGxlLmNvbSIsICI3MG'
  44. 'I0MWYiXQ==',
  45. 'token': self.token,
  46. 'timestamp': self.timestamp,
  47. 'signature': self.signature,
  48. 'domain': u'example.com',
  49. 'message-headers': u'[]',
  50. 'recipient': self.recipient,
  51. 'odoo_db': self.env.cr.dbname,
  52. 'tracking_email_id': u'%s' % self.tracking_email.id
  53. }
  54. self.metadata = {
  55. 'ip': '127.0.0.1',
  56. 'user_agent': False,
  57. 'os_family': False,
  58. 'ua_family': False,
  59. }
  60. self.partner = self.env['res.partner'].create({
  61. 'name': 'Mr. Odoo',
  62. 'email': 'mrodoo@example.com',
  63. })
  64. self.response = {
  65. "items": [{
  66. "log-level": "info",
  67. "id": "oXAVv5URCF-dKv8c6Sa7T",
  68. "timestamp": 1509119329.0,
  69. "message": {
  70. "headers": {
  71. "to": "test@test.com",
  72. "message-id": "test-id@f187c54734e8",
  73. "from": "Mr. Odoo <mrodoo@odoo.com>",
  74. "subject": "This is a test"
  75. },
  76. },
  77. "event": "delivered"
  78. }]
  79. }
  80. def event_search(self, event_type):
  81. event = self.env['mail.tracking.event'].search([
  82. ('tracking_email_id', '=', self.tracking_email.id),
  83. ('event_type', '=', event_type),
  84. ])
  85. self.assertTrue(event)
  86. return event
  87. def test_no_api_key(self):
  88. self.env['ir.config_parameter'].set_param('mailgun.apikey', '')
  89. self.test_event_delivered()
  90. with self.assertRaises(ValidationError):
  91. self.env['mail.tracking.email']._mailgun_values()
  92. def test_no_domain(self):
  93. self.env['ir.config_parameter'].set_param('mail.catchall.domain', '')
  94. self.test_event_delivered()
  95. with self.assertRaises(ValidationError):
  96. self.env['mail.tracking.email']._mailgun_values()
  97. @mute_logger('odoo.addons.mail_tracking_mailgun.models'
  98. '.mail_tracking_email')
  99. def test_bad_signature(self):
  100. self.event.update({
  101. 'event': u'delivered',
  102. 'signature': u'bad_signature',
  103. })
  104. response = self.env['mail.tracking.email'].event_process(
  105. None, self.event, self.metadata)
  106. self.assertEqual('ERROR: Signature', response)
  107. @mute_logger('odoo.addons.mail_tracking_mailgun.models'
  108. '.mail_tracking_email')
  109. def test_bad_event_type(self):
  110. self.event.update({
  111. 'event': u'bad_event',
  112. })
  113. response = self.env['mail.tracking.email'].event_process(
  114. None, self.event, self.metadata)
  115. self.assertEqual('ERROR: Event type not supported', response)
  116. @mute_logger('odoo.addons.mail_tracking_mailgun.models'
  117. '.mail_tracking_email')
  118. def test_bad_db(self):
  119. self.event.update({
  120. 'event': u'delivered',
  121. 'odoo_db': u'bad_db',
  122. })
  123. response = self.env['mail.tracking.email'].event_process(
  124. None, self.event, self.metadata)
  125. self.assertEqual('ERROR: Invalid DB', response)
  126. def test_bad_ts(self):
  127. timestamp = u'7a' # Now time will be used instead
  128. signature = ('06cc05680f6e8110e59b41152b2d1c0f'
  129. '1045d755ef2880ff922344325c89a6d4')
  130. self.event.update({
  131. 'event': u'delivered',
  132. 'timestamp': timestamp,
  133. 'signature': signature,
  134. })
  135. response = self.env['mail.tracking.email'].event_process(
  136. None, self.event, self.metadata)
  137. self.assertEqual('OK', response)
  138. @mute_logger('odoo.addons.mail_tracking_mailgun.models'
  139. '.mail_tracking_email')
  140. def test_tracking_not_found(self):
  141. self.event.update({
  142. 'event': u'delivered',
  143. 'tracking_email_id': u'bad_id',
  144. })
  145. response = self.env['mail.tracking.email'].event_process(
  146. None, self.event, self.metadata)
  147. self.assertEqual('ERROR: Tracking not found', response)
  148. # https://documentation.mailgun.com/user_manual.html#tracking-deliveries
  149. def test_event_delivered(self):
  150. self.event.update({
  151. 'event': u'delivered',
  152. })
  153. response = self.env['mail.tracking.email'].event_process(
  154. None, self.event, self.metadata)
  155. self.assertEqual('OK', response)
  156. event = self.event_search('delivered')
  157. self.assertEqual(event.timestamp, float(self.timestamp))
  158. self.assertEqual(event.recipient, self.recipient)
  159. # https://documentation.mailgun.com/user_manual.html#tracking-opens
  160. def test_event_opened(self):
  161. ip = u'127.0.0.1'
  162. user_agent = u'Odoo Test/8.0 Gecko Firefox/11.0'
  163. os_family = u'Linux'
  164. ua_family = u'Firefox'
  165. ua_type = u'browser'
  166. self.event.update({
  167. 'event': u'opened',
  168. 'city': u'Mountain View',
  169. 'country': u'US',
  170. 'region': u'CA',
  171. 'client-name': ua_family,
  172. 'client-os': os_family,
  173. 'client-type': ua_type,
  174. 'device-type': u'desktop',
  175. 'ip': ip,
  176. 'user-agent': user_agent,
  177. })
  178. response = self.env['mail.tracking.email'].event_process(
  179. None, self.event, self.metadata)
  180. self.assertEqual('OK', response)
  181. event = self.event_search('open')
  182. self.assertEqual(event.timestamp, float(self.timestamp))
  183. self.assertEqual(event.recipient, self.recipient)
  184. self.assertEqual(event.ip, ip)
  185. self.assertEqual(event.user_agent, user_agent)
  186. self.assertEqual(event.os_family, os_family)
  187. self.assertEqual(event.ua_family, ua_family)
  188. self.assertEqual(event.ua_type, ua_type)
  189. self.assertEqual(event.mobile, False)
  190. self.assertEqual(event.user_country_id.code, 'US')
  191. # https://documentation.mailgun.com/user_manual.html#tracking-clicks
  192. def test_event_clicked(self):
  193. ip = u'127.0.0.1'
  194. user_agent = u'Odoo Test/8.0 Gecko Firefox/11.0'
  195. os_family = u'Linux'
  196. ua_family = u'Firefox'
  197. ua_type = u'browser'
  198. url = u'https://odoo-community.org'
  199. self.event.update({
  200. 'event': u'clicked',
  201. 'city': u'Mountain View',
  202. 'country': u'US',
  203. 'region': u'CA',
  204. 'client-name': ua_family,
  205. 'client-os': os_family,
  206. 'client-type': ua_type,
  207. 'device-type': u'tablet',
  208. 'ip': ip,
  209. 'user-agent': user_agent,
  210. 'url': url,
  211. })
  212. response = self.env['mail.tracking.email'].event_process(
  213. None, self.event, self.metadata, event_type='click')
  214. self.assertEqual('OK', response)
  215. event = self.event_search('click')
  216. self.assertEqual(event.timestamp, float(self.timestamp))
  217. self.assertEqual(event.recipient, self.recipient)
  218. self.assertEqual(event.ip, ip)
  219. self.assertEqual(event.user_agent, user_agent)
  220. self.assertEqual(event.os_family, os_family)
  221. self.assertEqual(event.ua_family, ua_family)
  222. self.assertEqual(event.ua_type, ua_type)
  223. self.assertEqual(event.mobile, True)
  224. self.assertEqual(event.url, url)
  225. # https://documentation.mailgun.com/user_manual.html#tracking-unsubscribes
  226. def test_event_unsubscribed(self):
  227. ip = u'127.0.0.1'
  228. user_agent = u'Odoo Test/8.0 Gecko Firefox/11.0'
  229. os_family = u'Linux'
  230. ua_family = u'Firefox'
  231. ua_type = u'browser'
  232. self.event.update({
  233. 'event': u'unsubscribed',
  234. 'city': u'Mountain View',
  235. 'country': u'US',
  236. 'region': u'CA',
  237. 'client-name': ua_family,
  238. 'client-os': os_family,
  239. 'client-type': ua_type,
  240. 'device-type': u'mobile',
  241. 'ip': ip,
  242. 'user-agent': user_agent,
  243. })
  244. response = self.env['mail.tracking.email'].event_process(
  245. None, self.event, self.metadata)
  246. self.assertEqual('OK', response)
  247. event = self.event_search('unsub')
  248. self.assertEqual(event.timestamp, float(self.timestamp))
  249. self.assertEqual(event.recipient, self.recipient)
  250. self.assertEqual(event.ip, ip)
  251. self.assertEqual(event.user_agent, user_agent)
  252. self.assertEqual(event.os_family, os_family)
  253. self.assertEqual(event.ua_family, ua_family)
  254. self.assertEqual(event.ua_type, ua_type)
  255. self.assertEqual(event.mobile, True)
  256. # https://documentation.mailgun.com/
  257. # user_manual.html#tracking-spam-complaints
  258. def test_event_complained(self):
  259. self.event.update({
  260. 'event': u'complained',
  261. })
  262. response = self.env['mail.tracking.email'].event_process(
  263. None, self.event, self.metadata)
  264. self.assertEqual('OK', response)
  265. event = self.event_search('spam')
  266. self.assertEqual(event.timestamp, float(self.timestamp))
  267. self.assertEqual(event.recipient, self.recipient)
  268. self.assertEqual(event.error_type, 'spam')
  269. # https://documentation.mailgun.com/user_manual.html#tracking-bounces
  270. def test_event_bounced(self):
  271. code = u'550'
  272. error = (u"5.1.1 The email account does not exist.\n"
  273. "5.1.1 double-checking the recipient's email address")
  274. notification = u"Please, check recipient's email address"
  275. self.event.update({
  276. 'event': u'bounced',
  277. 'code': code,
  278. 'error': error,
  279. 'notification': notification,
  280. })
  281. response = self.env['mail.tracking.email'].event_process(
  282. None, self.event, self.metadata)
  283. self.assertEqual('OK', response)
  284. event = self.event_search('hard_bounce')
  285. self.assertEqual(event.timestamp, float(self.timestamp))
  286. self.assertEqual(event.recipient, self.recipient)
  287. self.assertEqual(event.error_type, code)
  288. self.assertEqual(event.error_description, error)
  289. self.assertEqual(event.error_details, notification)
  290. # https://documentation.mailgun.com/user_manual.html#tracking-failures
  291. def test_event_dropped(self):
  292. reason = u'hardfail'
  293. code = u'605'
  294. description = u'Not delivering to previously bounced address'
  295. self.event.update({
  296. 'event': u'dropped',
  297. 'reason': reason,
  298. 'code': code,
  299. 'description': description,
  300. })
  301. response = self.env['mail.tracking.email'].event_process(
  302. None, self.event, self.metadata)
  303. self.assertEqual('OK', response)
  304. event = self.event_search('reject')
  305. self.assertEqual(event.timestamp, float(self.timestamp))
  306. self.assertEqual(event.recipient, self.recipient)
  307. self.assertEqual(event.error_type, reason)
  308. self.assertEqual(event.error_description, code)
  309. self.assertEqual(event.error_details, description)
  310. @mock.patch(_packagepath + '.models.res_partner.requests')
  311. def test_email_validity(self, mock_request):
  312. self.partner.email_bounced = False
  313. self.partner.email = 'info@tecnativa.com'
  314. mock_request.get.return_value.apparent_encoding = 'ascii'
  315. mock_request.get.return_value.status_code = 200
  316. mock_request.get.return_value.content = json.dumps({
  317. 'is_valid': True,
  318. 'mailbox_verification': 'true',
  319. }, ensure_ascii=True)
  320. self.partner.check_email_validity()
  321. self.assertFalse(self.partner.email_bounced)
  322. self.partner.email = 'xoxoxoxo@tecnativa.com'
  323. # Not a valid mailbox
  324. mock_request.get.return_value.content = json.dumps({
  325. 'is_valid': True,
  326. 'mailbox_verification': 'false',
  327. }, ensure_ascii=True)
  328. with self.assertRaises(UserError):
  329. self.partner.check_email_validity()
  330. # Not a valid mail address
  331. mock_request.get.return_value.content = json.dumps({
  332. 'is_valid': False,
  333. 'mailbox_verification': 'false',
  334. }, ensure_ascii=True)
  335. with self.assertRaises(UserError):
  336. self.partner.check_email_validity()
  337. # Unable to fully validate
  338. mock_request.get.return_value.content = json.dumps({
  339. 'is_valid': True,
  340. 'mailbox_verification': 'unknown',
  341. }, ensure_ascii=True)
  342. with self.assertRaises(UserError):
  343. self.partner.check_email_validity()
  344. self.assertTrue(self.partner.email_bounced)
  345. @mock.patch(_packagepath + '.models.res_partner.requests')
  346. def test_email_validity_exceptions(self, mock_request):
  347. mock_request.get.return_value.status_code = 404
  348. with self.assertRaises(UserError):
  349. self.partner.check_email_validity()
  350. self.env['ir.config_parameter'].set_param('mailgun.validation_key', '')
  351. with self.assertRaises(UserError):
  352. self.partner.check_email_validity()
  353. @mock.patch(_packagepath + '.models.res_partner.requests')
  354. def test_bounced(self, mock_request):
  355. self.partner.email_bounced = True
  356. mock_request.get.return_value.status_code = 404
  357. self.partner.check_email_bounced()
  358. self.assertFalse(self.partner.email_bounced)
  359. mock_request.get.return_value.status_code = 200
  360. self.partner.force_set_bounced()
  361. self.partner.check_email_bounced()
  362. self.assertTrue(self.partner.email_bounced)
  363. mock_request.delete.return_value.status_code = 200
  364. self.partner.force_unset_bounced()
  365. self.assertFalse(self.partner.email_bounced)
  366. def test_email_bounced_set(self):
  367. message_number = len(self.partner.message_ids) + 1
  368. self.partner._email_bounced_set('test_error', self.event)
  369. self.assertEqual(len(self.partner.message_ids), message_number)
  370. self.partner.email = ""
  371. self.partner._email_bounced_set('test_error', self.event)
  372. self.assertEqual(len(self.partner.message_ids), message_number)
  373. @mock.patch(_packagepath + '.models.mail_tracking_email.requests')
  374. def test_manual_check(self, mock_request):
  375. mock_request.get.return_value.content = json.dumps(self.response,
  376. ensure_ascii=True)
  377. mock_request.get.return_value.apparent_encoding = 'ascii'
  378. mock_request.get.return_value.status_code = 200
  379. self.tracking_email.action_manual_check_mailgun()
  380. event = self.env['mail.tracking.event'].search(
  381. [('mailgun_id', '=', self.response['items'][0]['id'])])
  382. self.assertEqual(event.event_type, self.response['items'][0]['event'])
  383. @mock.patch(_packagepath + '.models.mail_tracking_email.requests')
  384. def test_manual_check_exceptions(self, mock_request):
  385. mock_request.get.return_value.status_code = 404
  386. with self.assertRaises(ValidationError):
  387. self.tracking_email.action_manual_check_mailgun()
  388. mock_request.get.return_value.status_code = 200
  389. mock_request.get.return_value.content = json.dumps('{}',
  390. ensure_ascii=True)
  391. mock_request.get.return_value.apparent_encoding = 'ascii'
  392. with self.assertRaises(ValidationError):
  393. self.tracking_email.action_manual_check_mailgun()