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.

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