test_process_issue_event.py 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939
  1. import os
  2. import shutil
  3. import uuid
  4. from django.urls import reverse
  5. from model_bakery import baker
  6. from apps.issue_events.constants import EventStatus, LogLevel
  7. from apps.issue_events.models import Issue, IssueEvent, IssueHash
  8. from apps.projects.models import IssueEventProjectHourlyStatistic
  9. from apps.releases.models import Release
  10. from ..process_event import process_issue_events
  11. from ..schema import (
  12. CSPIssueEventSchema,
  13. ErrorIssueEventSchema,
  14. InterchangeIssueEvent,
  15. IssueEventSchema,
  16. SecuritySchema,
  17. )
  18. from .utils import EventIngestTestCase
  19. COMPAT_TEST_DATA_DIR = "events/test_data"
  20. def is_exception(v):
  21. return v.get("type") == "exception"
  22. class IssueEventIngestTestCase(EventIngestTestCase):
  23. """
  24. These tests bypass the API and celery. They test the event ingest logic itself.
  25. This file should be large are test the following use cases
  26. - Multiple event saved at the same time
  27. - Sentry API compatibility
  28. - Default, Error, and CSP types
  29. - Graceful failure such as duplicate event ids or invalid data
  30. """
  31. def test_two_events(self):
  32. with self.assertNumQueries(7):
  33. self.process_events([{}, {}])
  34. self.assertEqual(Issue.objects.count(), 1)
  35. self.assertEqual(IssueHash.objects.count(), 1)
  36. self.assertEqual(IssueEvent.objects.count(), 2)
  37. self.assertTrue(
  38. IssueEventProjectHourlyStatistic.objects.filter(
  39. count=2, project=self.project
  40. ).exists()
  41. )
  42. def test_two_issues(self):
  43. self.process_events(
  44. [
  45. {
  46. "message": "a",
  47. },
  48. {
  49. "message": "b",
  50. },
  51. ]
  52. )
  53. self.assertEqual(Issue.objects.count(), 2)
  54. self.assertEqual(IssueHash.objects.count(), 2)
  55. self.assertEqual(IssueEvent.objects.count(), 2)
  56. self.assertTrue(
  57. IssueEventProjectHourlyStatistic.objects.filter(
  58. count=2, project=self.project
  59. ).exists()
  60. )
  61. def test_transaction_truncation(self):
  62. long_string = "x" * 201
  63. truncated_string = "x" * 199 + "…"
  64. data = self.get_json_data("events/test_data/py_hi_event.json")
  65. data["culprit"] = long_string
  66. self.process_events(data)
  67. first_event = IssueEvent.objects.first()
  68. self.assertEqual(first_event.transaction, truncated_string)
  69. data = self.get_json_data("events/test_data/py_hi_event.json")
  70. data["transaction"] = long_string
  71. self.process_events(data)
  72. second_event = IssueEvent.objects.last()
  73. self.assertEqual(second_event.transaction, truncated_string)
  74. def test_message_empty_param_list(self):
  75. self.process_events(
  76. [
  77. {"logentry": {"message": "This is a warning: %s", "params": []}},
  78. ]
  79. )
  80. self.assertEqual(
  81. IssueEvent.objects.first().data["logentry"]["message"],
  82. "This is a warning: %s",
  83. )
  84. def test_query_release_environment_difs(self):
  85. """Test efficiency of existing release/environment/dif"""
  86. project2 = baker.make("projects.Project", organization=self.organization)
  87. release = baker.make("releases.Release", version="r", projects=[self.project])
  88. environment = baker.make(
  89. "environments.Environment", name="e", projects=[self.project]
  90. )
  91. baker.make("difs.DebugInformationFile", project=self.project)
  92. baker.make("releases.Release", projects=[self.project, project2])
  93. baker.make("releases.Release", version="r", projects=[project2])
  94. baker.make("releases.Release", version="r")
  95. baker.make("environments.Environment", projects=[self.project])
  96. baker.make("difs.DebugInformationFile", project=self.project)
  97. event1 = {
  98. "release": release.version,
  99. "environment": environment.name,
  100. }
  101. event2 = {
  102. "release": "newr",
  103. "environment": "newe",
  104. }
  105. with self.assertNumQueries(13):
  106. self.process_events([event1, {}])
  107. self.process_events([event1, event2, {}])
  108. self.assertEqual(self.project.releases.count(), 3)
  109. self.assertEqual(self.project.environment_set.count(), 3)
  110. def test_reopen_resolved_issue(self):
  111. event = self.process_events({})[0]
  112. issue = Issue.objects.first()
  113. issue.status = EventStatus.RESOLVED
  114. issue.save()
  115. event.event_id = uuid.uuid4()
  116. self.process_events(event.dict())
  117. issue.refresh_from_db()
  118. self.assertEqual(issue.status, EventStatus.UNRESOLVED)
  119. def test_fingerprint(self):
  120. data = {
  121. "exception": [
  122. {
  123. "type": "a",
  124. "value": "a",
  125. }
  126. ],
  127. "event_id": uuid.uuid4(),
  128. "fingerprint": ["foo"],
  129. }
  130. self.process_events(data)
  131. data["exception"][0]["type"] = "lol"
  132. data["event_id"] = uuid.uuid4()
  133. self.process_events(data)
  134. self.assertEqual(Issue.objects.count(), 1)
  135. self.assertEqual(IssueEvent.objects.count(), 2)
  136. def test_event_release(self):
  137. data = self.get_json_data("events/test_data/py_hi_event.json")
  138. baker.make("releases.Release", version=data.get("release"))
  139. self.process_events(data)
  140. event = IssueEvent.objects.first()
  141. self.assertTrue(event.release)
  142. self.assertTrue(
  143. Release.objects.filter(
  144. version=data.get("release"), projects=self.project
  145. ).exists()
  146. )
  147. def test_event_release_blank(self):
  148. """In the SDK, it's possible to set a release to a blank string"""
  149. data = self.get_json_data("events/test_data/py_hi_event.json")
  150. data["release"] = ""
  151. self.process_events(data)
  152. self.assertTrue(IssueEvent.objects.first())
  153. def test_event_environment(self):
  154. # Some noise to test queries
  155. baker.make("environments.Environment", organization=self.organization)
  156. baker.make("environments.EnvironmentProject", project=self.project)
  157. data = self.get_json_data("events/test_data/py_hi_event.json")
  158. data["environment"] = "dev"
  159. self.process_events(data)
  160. event = IssueEvent.objects.first()
  161. self.assertTrue(event.issue.project.environment_set.filter(name="dev").exists())
  162. self.assertEqual(event.issue.project.environment_set.count(), 2)
  163. data["event_id"] = uuid.uuid4().hex
  164. self.process_events(data)
  165. self.assertEqual(event.issue.project.environment_set.count(), 2)
  166. def test_multi_org_event_environment_processing(self):
  167. environment = baker.make(
  168. "environments.Environment", organization=self.organization, name="prod"
  169. )
  170. baker.make(
  171. "environments.EnvironmentProject",
  172. environment=environment,
  173. project=self.project,
  174. )
  175. event_list = []
  176. data = self.get_json_data("events/test_data/py_hi_event.json")
  177. data["environment"] = "dev"
  178. event_list.append(
  179. InterchangeIssueEvent(
  180. project_id=self.project.id,
  181. organization_id=self.organization.id,
  182. payload=IssueEventSchema(**data),
  183. )
  184. )
  185. org_b = baker.make("organizations_ext.organization")
  186. org_b_project = baker.make("projects.Project", organization=org_b)
  187. data = self.get_json_data("events/test_data/py_hi_event.json")
  188. data["environment"] = "prod"
  189. event_list.append(
  190. InterchangeIssueEvent(
  191. project_id=org_b_project.id,
  192. organization_id=org_b.id,
  193. payload=IssueEventSchema(**data),
  194. )
  195. )
  196. process_issue_events(event_list)
  197. self.assertTrue(self.project.environment_set.filter(name="dev").exists())
  198. self.assertEqual(self.project.environment_set.count(), 2)
  199. self.assertTrue(org_b_project.environment_set.filter(name="prod").exists())
  200. self.assertEqual(org_b_project.environment_set.count(), 1)
  201. def test_multi_org_event_release_processing(self):
  202. release = baker.make(
  203. "releases.Release", organization=self.organization, version="v1.0"
  204. )
  205. baker.make(
  206. "releases.ReleaseProject",
  207. release=release,
  208. project=self.project,
  209. )
  210. event_list = []
  211. data = self.get_json_data("events/test_data/py_hi_event.json")
  212. data["release"] = "v2.0"
  213. event_list.append(
  214. InterchangeIssueEvent(
  215. project_id=self.project.id,
  216. organization_id=self.organization.id,
  217. payload=IssueEventSchema(**data),
  218. )
  219. )
  220. org_b = baker.make("organizations_ext.organization")
  221. org_b_project = baker.make("projects.Project", organization=org_b)
  222. data = self.get_json_data("events/test_data/py_hi_event.json")
  223. data["release"] = "v1.0"
  224. event_list.append(
  225. InterchangeIssueEvent(
  226. project_id=org_b_project.id,
  227. organization_id=org_b.id,
  228. payload=IssueEventSchema(**data),
  229. )
  230. )
  231. process_issue_events(event_list)
  232. self.assertTrue(self.organization.release_set.filter(version="v2.0").exists())
  233. self.assertEqual(self.organization.release_set.count(), 2)
  234. self.assertTrue(org_b.release_set.filter(version="v1.0").exists())
  235. self.assertEqual(org_b.release_set.count(), 1)
  236. def test_process_sourcemap(self):
  237. sample_event = {
  238. "exception": {
  239. "values": [
  240. {
  241. "type": "Error",
  242. "value": "The error",
  243. "stacktrace": {
  244. "frames": [
  245. {
  246. "filename": "http://localhost:8080/dist/bundle.js",
  247. "function": "?",
  248. "in_app": True,
  249. "lineno": 2,
  250. "colno": 74016,
  251. },
  252. {
  253. "filename": "http://localhost:8080/dist/bundle.js",
  254. "function": "?",
  255. "in_app": True,
  256. "lineno": 2,
  257. "colno": 74012,
  258. },
  259. {
  260. "filename": "http://localhost:8080/dist/bundle.js",
  261. "function": "?",
  262. "in_app": True,
  263. "lineno": 2,
  264. "colno": 73992,
  265. },
  266. ]
  267. },
  268. "mechanism": {"type": "onerror", "handled": False},
  269. }
  270. ]
  271. },
  272. "level": "error",
  273. "platform": "javascript",
  274. "event_id": "0691751a89db419994efac8ac9b00a5d",
  275. "timestamp": 1648414309.82,
  276. "environment": "production",
  277. "request": {
  278. "url": "http://localhost:8080/",
  279. "headers": {
  280. "User-Agent": "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:98.0) Gecko/20100101 Firefox/98.0"
  281. },
  282. },
  283. }
  284. release = baker.make("releases.Release", organization=self.organization)
  285. release.projects.add(self.project)
  286. blob_bundle = baker.make("files.FileBlob", blob="uploads/file_blobs/bundle.js")
  287. blob_bundle_map = baker.make(
  288. "files.FileBlob", blob="uploads/file_blobs/bundle.js.map"
  289. )
  290. baker.make(
  291. "releases.ReleaseFile",
  292. release=release,
  293. file__name="bundle.js",
  294. file__blob=blob_bundle,
  295. )
  296. baker.make(
  297. "releases.ReleaseFile",
  298. release=release,
  299. file__name="bundle.js.map",
  300. file__blob=blob_bundle_map,
  301. )
  302. try:
  303. os.mkdir("./uploads/file_blobs")
  304. except FileExistsError:
  305. pass
  306. shutil.copyfile(
  307. "./apps/event_ingest/tests/test_data/bundle.js",
  308. "./uploads/file_blobs/bundle.js",
  309. )
  310. shutil.copyfile(
  311. "./apps/event_ingest/tests/test_data/bundle.js.map",
  312. "./uploads/file_blobs/bundle.js.map",
  313. )
  314. data = sample_event | {"release": release.version}
  315. self.process_events(data)
  316. # Show that colno changes
  317. self.assertEqual(
  318. IssueEvent.objects.first().data["exception"][0]["stacktrace"]["frames"][0][
  319. "colno"
  320. ],
  321. 13,
  322. )
  323. # Show that pre and post context is included
  324. self.assertEqual(
  325. len(IssueEvent.objects.first().data["exception"][0]["stacktrace"]["frames"][0]["pre_context"]),
  326. 5
  327. )
  328. self.assertEqual(
  329. len(IssueEvent.objects.first().data["exception"][0]["stacktrace"]["frames"][0]["post_context"]),
  330. 1
  331. )
  332. self.assertTrue(IssueEvent.objects.filter(release=release).exists())
  333. def test_search_vector(self):
  334. word = "orange"
  335. for _ in range(2):
  336. self.process_events([{"message": word}])
  337. issue = Issue.objects.filter(search_vector=word).first()
  338. self.assertTrue(issue)
  339. self.assertEqual(len(issue.search_vector.split(" ")), 1)
  340. def test_null_character_event(self):
  341. """
  342. Unicode null characters \u0000 are not supported by Postgres JSONB
  343. NUL \x00 characters are not supported by Postgres string types
  344. They should be filtered out
  345. """
  346. data = self.get_json_data("events/test_data/py_error.json")
  347. data["exception"]["values"][0]["stacktrace"]["frames"][0]["function"] = (
  348. "a\u0000a"
  349. )
  350. data["exception"]["values"][0]["value"] = "\x00\u0000"
  351. self.process_events(data)
  352. def test_csp_event_processing(self):
  353. self.create_logged_in_user()
  354. payload = self.get_json_data(
  355. "apps/event_ingest/tests/test_data/csp/mozilla_example.json"
  356. )
  357. data = SecuritySchema(**payload)
  358. event = CSPIssueEventSchema(csp=data.csp_report.dict(by_alias=True))
  359. process_issue_events(
  360. [
  361. InterchangeIssueEvent(
  362. project_id=self.project.id,
  363. organization_id=self.organization.id,
  364. payload=event.dict(by_alias=True),
  365. )
  366. ]
  367. )
  368. issue = Issue.objects.get()
  369. url = reverse("api:get_latest_issue_event", kwargs={"issue_id": issue.id})
  370. res = self.client.get(url)
  371. self.assertEqual(res.status_code, 200)
  372. self.assertEqual(res.json()["culprit"], "style-src-elem")
  373. class SentryCompatTestCase(EventIngestTestCase):
  374. """
  375. These tests specifically test former open source sentry compatibility
  376. But otherwise are part of issue event ingest testing
  377. """
  378. def setUp(self):
  379. super().setUp()
  380. self.create_logged_in_user()
  381. def get_json_test_data(self, name: str):
  382. """Get incoming event, sentry json, sentry api event"""
  383. event = self.get_json_data(
  384. f"{COMPAT_TEST_DATA_DIR}/incoming_events/{name}.json"
  385. )
  386. sentry_json = self.get_json_data(
  387. f"{COMPAT_TEST_DATA_DIR}/oss_sentry_json/{name}.json"
  388. )
  389. # Force captured test data to match test generated data
  390. sentry_json["project"] = self.project.id
  391. api_sentry_event = self.get_json_data(
  392. f"{COMPAT_TEST_DATA_DIR}/oss_sentry_events/{name}.json"
  393. )
  394. return event, sentry_json, api_sentry_event
  395. def get_event_json(self, event: IssueEvent):
  396. return self.client.get(
  397. reverse(
  398. "api:get_event_json",
  399. kwargs={
  400. "organization_slug": self.organization.slug,
  401. "issue_id": event.issue_id,
  402. "event_id": event.id,
  403. },
  404. )
  405. ).json()
  406. # Upgrade functions handle intentional differences between GlitchTip and Sentry OSS
  407. def upgrade_title(self, value: str):
  408. """Sentry OSS uses ... while GlitchTip uses unicode …"""
  409. if value[-1] == "…":
  410. return value[:-3]
  411. return value.strip("...")
  412. def upgrade_metadata(self, value: dict):
  413. value["title"] = self.upgrade_title(value["title"])
  414. return value
  415. def assertCompareData(self, data1: dict, data2: dict, fields: list[str]):
  416. """Compare data of two dict objects. Compare only provided fields list"""
  417. for field in fields:
  418. field_value1 = data1.get(field)
  419. field_value2 = data2.get(field)
  420. if field == "datetime":
  421. # Check that it's close enough
  422. field_value1 = field_value1[:23]
  423. field_value2 = field_value2[:23]
  424. if field == "title" and isinstance(field_value1, str):
  425. field_value1 = self.upgrade_title(field_value1)
  426. if field_value2:
  427. field_value2 = self.upgrade_title(field_value2)
  428. if (
  429. field == "metadata"
  430. and isinstance(field_value1, dict)
  431. and field_value1.get("title")
  432. ):
  433. field_value1 = self.upgrade_metadata(field_value1)
  434. if field_value2:
  435. field_value2 = self.upgrade_metadata(field_value2)
  436. self.assertEqual(
  437. field_value1,
  438. field_value2,
  439. f"Failed for field '{field}'",
  440. )
  441. def get_project_events_detail(self, event_id: str):
  442. return reverse(
  443. "api:get_project_issue_event",
  444. kwargs={
  445. "organization_slug": self.project.organization.slug,
  446. "project_slug": self.project.slug,
  447. "event_id": event_id,
  448. },
  449. )
  450. def submit_event(self, event_data: dict, event_type="error") -> IssueEvent:
  451. event_class = ErrorIssueEventSchema
  452. if event_type == "default":
  453. event_class = IssueEventSchema
  454. event = InterchangeIssueEvent(
  455. event_id=event_data["event_id"],
  456. organization_id=self.organization.id if self.organization else None,
  457. project_id=self.project.id,
  458. payload=event_class(**event_data),
  459. )
  460. process_issue_events([event])
  461. return IssueEvent.objects.get(pk=event.event_id)
  462. def upgrade_data(self, data):
  463. """A recursive replace function"""
  464. if isinstance(data, dict):
  465. return {k: self.upgrade_data(v) for k, v in data.items()}
  466. elif isinstance(data, list):
  467. return [self.upgrade_data(i) for i in data]
  468. return data
  469. def test_template_error(self):
  470. sdk_error, sentry_json, sentry_data = self.get_json_test_data(
  471. "django_template_error"
  472. )
  473. event = self.submit_event(sdk_error)
  474. url = self.get_project_events_detail(event.id.hex)
  475. res = self.client.get(url)
  476. res_data = res.json()
  477. self.assertEqual(res.status_code, 200)
  478. self.assertCompareData(res_data, sentry_data, ["culprit", "title", "metadata"])
  479. res_frames = res_data["entries"][0]["data"]["values"][0]["stacktrace"]["frames"]
  480. frames = sentry_data["entries"][0]["data"]["values"][0]["stacktrace"]["frames"]
  481. for i in range(6):
  482. # absPath don't always match - needs fixed
  483. self.assertCompareData(res_frames[i], frames[i], ["absPath"])
  484. for res_frame, frame in zip(res_frames, frames):
  485. self.assertCompareData(
  486. res_frame,
  487. frame,
  488. ["lineNo", "function", "filename", "module", "context"],
  489. )
  490. if frame.get("vars"):
  491. self.assertCompareData(
  492. res_frame["vars"], frame["vars"], ["exc", "request"]
  493. )
  494. if frame["vars"].get("get_response"):
  495. # Memory address is different, truncate it
  496. self.assertEqual(
  497. res_frame["vars"]["get_response"][:-16],
  498. frame["vars"]["get_response"][:-16],
  499. )
  500. self.assertCompareData(
  501. res_data["entries"][0]["data"],
  502. sentry_data["entries"][0]["data"],
  503. ["env", "headers", "url", "method", "inferredContentType"],
  504. )
  505. url = reverse("api:get_issue", kwargs={"issue_id": event.issue.pk})
  506. res = self.client.get(url)
  507. self.assertEqual(res.status_code, 200)
  508. res_data = res.json()
  509. data = self.get_json_data("events/test_data/django_template_error_issue.json")
  510. self.assertCompareData(res_data, data, ["title", "metadata"])
  511. def test_js_sdk_with_unix_timestamp(self):
  512. sdk_error, sentry_json, sentry_data = self.get_json_test_data(
  513. "js_event_with_unix_timestamp"
  514. )
  515. event = self.submit_event(sdk_error)
  516. self.assertNotEqual(event.timestamp, sdk_error["timestamp"])
  517. self.assertEqual(event.timestamp.year, 2020)
  518. event_json = self.get_event_json(event)
  519. self.assertCompareData(event_json, sentry_json, ["datetime"])
  520. res = self.client.get(self.get_project_events_detail(event.pk))
  521. res_data = res.json()
  522. self.assertCompareData(res_data, sentry_data, ["timestamp"])
  523. self.assertEqual(res_data["entries"][1].get("type"), "breadcrumbs")
  524. self.maxDiff = None
  525. self.assertEqual(
  526. res_data["entries"][1],
  527. self.upgrade_data(sentry_data["entries"][1]),
  528. )
  529. def test_dotnet_error(self):
  530. sdk_error = self.get_json_data(
  531. "events/test_data/incoming_events/dotnet_error.json"
  532. )
  533. event = self.submit_event(sdk_error)
  534. self.assertEqual(IssueEvent.objects.count(), 1)
  535. sentry_data = self.get_json_data(
  536. "events/test_data/oss_sentry_events/dotnet_error.json"
  537. )
  538. res = self.client.get(self.get_project_events_detail(event.pk))
  539. res_data = res.json()
  540. self.assertCompareData(
  541. res_data,
  542. sentry_data,
  543. ["eventID", "title", "culprit", "platform", "type", "metadata"],
  544. )
  545. res_exception = next(filter(is_exception, res_data["entries"]), None)
  546. sentry_exception = next(filter(is_exception, sentry_data["entries"]), None)
  547. self.assertEqual(
  548. res_exception["data"].get("hasSystemFrames"),
  549. sentry_exception["data"].get("hasSystemFrames"),
  550. )
  551. def test_php_message_event(self):
  552. sdk_error, sentry_json, sentry_data = self.get_json_test_data(
  553. "php_message_event"
  554. )
  555. event = self.submit_event(sdk_error)
  556. res = self.client.get(self.get_project_events_detail(event.pk))
  557. res_data = res.json()
  558. self.assertCompareData(
  559. res_data,
  560. sentry_data,
  561. [
  562. "message",
  563. "title",
  564. ],
  565. )
  566. self.assertEqual(
  567. res_data["entries"][0]["data"]["params"],
  568. sentry_data["entries"][0]["data"]["params"],
  569. )
  570. def test_django_message_params(self):
  571. sdk_error, sentry_json, sentry_data = self.get_json_test_data(
  572. "django_message_params"
  573. )
  574. event = self.submit_event(sdk_error)
  575. res = self.client.get(self.get_project_events_detail(event.pk))
  576. res_data = res.json()
  577. self.assertCompareData(
  578. res_data,
  579. sentry_data,
  580. [
  581. "message",
  582. "title",
  583. ],
  584. )
  585. self.assertEqual(res_data["entries"][0], sentry_data["entries"][0])
  586. def test_message_event(self):
  587. """A generic message made with the Sentry SDK. Generally has less data than exceptions."""
  588. from events.test_data.django_error_factory import message
  589. event = self.submit_event(message, event_type="default")
  590. res = self.client.get(self.get_project_events_detail(event.pk))
  591. res_data = res.json()
  592. data = self.get_json_data("events/test_data/django_message_event.json")
  593. self.assertCompareData(
  594. res_data,
  595. data,
  596. ["title", "culprit", "type", "metadata", "platform", "packages"],
  597. )
  598. def test_python_logging(self):
  599. """Test Sentry SDK logging integration based event"""
  600. sdk_error, sentry_json, sentry_data = self.get_json_test_data("python_logging")
  601. event = self.submit_event(sdk_error, event_type="default")
  602. res = self.client.get(self.get_project_events_detail(event.pk))
  603. res_data = res.json()
  604. self.assertEqual(res.status_code, 200)
  605. self.assertCompareData(
  606. res_data,
  607. sentry_data,
  608. [
  609. "title",
  610. "logentry",
  611. "culprit",
  612. "type",
  613. "metadata",
  614. "platform",
  615. "packages",
  616. ],
  617. )
  618. def test_go_file_not_found(self):
  619. sdk_error = self.get_json_data(
  620. "events/test_data/incoming_events/go_file_not_found.json"
  621. )
  622. event = self.submit_event(sdk_error)
  623. sentry_data = self.get_json_data(
  624. "events/test_data/oss_sentry_events/go_file_not_found.json"
  625. )
  626. res = self.client.get(self.get_project_events_detail(event.pk))
  627. res_data = res.json()
  628. self.assertEqual(res.status_code, 200)
  629. self.assertCompareData(
  630. res_data,
  631. sentry_data,
  632. ["title", "culprit", "type", "metadata", "platform"],
  633. )
  634. def test_very_small_event(self):
  635. """
  636. Shows a very minimalist event example. Good for seeing what data is null
  637. """
  638. sdk_error = self.get_json_data(
  639. "events/test_data/incoming_events/very_small_event.json"
  640. )
  641. event = self.submit_event(sdk_error, event_type="default")
  642. sentry_data = self.get_json_data(
  643. "events/test_data/oss_sentry_events/very_small_event.json"
  644. )
  645. res = self.client.get(self.get_project_events_detail(event.pk))
  646. res_data = res.json()
  647. self.assertEqual(res.status_code, 200)
  648. self.assertCompareData(
  649. res_data,
  650. sentry_data,
  651. ["culprit", "type", "platform", "entries"],
  652. )
  653. def test_python_zero_division(self):
  654. sdk_error, sentry_json, sentry_data = self.get_json_test_data(
  655. "python_zero_division"
  656. )
  657. event = self.submit_event(sdk_error)
  658. event_json = self.get_event_json(event)
  659. self.assertCompareData(
  660. event_json,
  661. sentry_json,
  662. [
  663. "event_id",
  664. "project",
  665. "release",
  666. "dist",
  667. "platform",
  668. "level",
  669. "modules",
  670. "time_spent",
  671. "sdk",
  672. "type",
  673. "title",
  674. "breadcrumbs",
  675. ],
  676. )
  677. self.assertCompareData(
  678. event_json["request"],
  679. sentry_json["request"],
  680. [
  681. "url",
  682. "headers",
  683. "method",
  684. "env",
  685. "query_string",
  686. ],
  687. )
  688. self.assertEqual(
  689. event_json["datetime"][:22],
  690. sentry_json["datetime"][:22],
  691. "Compare if datetime is almost the same",
  692. )
  693. res = self.client.get(self.get_project_events_detail(event.pk))
  694. res_data = res.json()
  695. self.assertEqual(res.status_code, 200)
  696. self.assertCompareData(
  697. res_data,
  698. sentry_data,
  699. ["title", "culprit", "type", "metadata", "platform", "packages"],
  700. )
  701. self.assertCompareData(
  702. res_data["entries"][1]["data"],
  703. sentry_data["entries"][1]["data"],
  704. [
  705. "inferredContentType",
  706. "env",
  707. "headers",
  708. "url",
  709. "query",
  710. "data",
  711. "method",
  712. ],
  713. )
  714. issue = event.issue
  715. issue.refresh_from_db()
  716. self.assertEqual(issue.level, LogLevel.ERROR)
  717. def test_dotnet_zero_division(self):
  718. sdk_error, sentry_json, sentry_data = self.get_json_test_data(
  719. "dotnet_divide_zero"
  720. )
  721. event = self.submit_event(sdk_error)
  722. event_json = self.get_event_json(event)
  723. res = self.client.get(self.get_project_events_detail(event.pk))
  724. res_data = res.json()
  725. self.assertCompareData(event_json, sentry_json, ["environment"])
  726. self.assertCompareData(
  727. res_data,
  728. sentry_data,
  729. [
  730. "eventID",
  731. "title",
  732. "culprit",
  733. "platform",
  734. "type",
  735. "metadata",
  736. ],
  737. )
  738. res_exception = next(filter(is_exception, res_data["entries"]), None)
  739. sentry_exception = next(filter(is_exception, sentry_data["entries"]), None)
  740. self.assertEqual(
  741. res_exception["data"]["values"][0]["stacktrace"]["frames"][4]["context"],
  742. sentry_exception["data"]["values"][0]["stacktrace"]["frames"][4]["context"],
  743. )
  744. tags = res_data.get("tags")
  745. browser_tag = next(filter(lambda tag: tag["key"] == "browser", tags), None)
  746. self.assertEqual(browser_tag["value"], "Firefox 76.0")
  747. environment_tag = next(
  748. filter(lambda tag: tag["key"] == "environment", tags), None
  749. )
  750. self.assertEqual(environment_tag["value"], "Development")
  751. def test_ruby_zero_division(self):
  752. sdk_error, sentry_json, sentry_data = self.get_json_test_data(
  753. "ruby_zero_division"
  754. )
  755. event = self.submit_event(sdk_error)
  756. event_json = self.get_event_json(event)
  757. res = self.client.get(self.get_project_events_detail(event.pk))
  758. res_data = res.json()
  759. res_exception = next(filter(is_exception, res_data["entries"]), None)
  760. sentry_exception = next(filter(is_exception, sentry_data["entries"]), None)
  761. self.assertEqual(
  762. res_exception["data"]["values"][0]["stacktrace"]["frames"][-1]["context"],
  763. sentry_exception["data"]["values"][0]["stacktrace"]["frames"][-1]["context"],
  764. )
  765. self.assertCompareData(event_json, sentry_json, ["environment"])
  766. self.assertCompareData(
  767. res_data,
  768. sentry_data,
  769. [
  770. "eventID",
  771. "title",
  772. "culprit",
  773. "platform",
  774. "type",
  775. "metadata",
  776. ],
  777. )
  778. def test_sentry_cli_send_event_no_level(self):
  779. sdk_error, sentry_json, sentry_data = self.get_json_test_data(
  780. "sentry_cli_send_event_no_level"
  781. )
  782. event = self.submit_event(sdk_error, event_type="default")
  783. event_json = self.get_event_json(event)
  784. self.assertCompareData(event_json, sentry_json, ["title"])
  785. self.assertEqual(event_json["project"], event.issue.project_id)
  786. res = self.client.get(self.get_project_events_detail(event.pk))
  787. res_data = res.json()
  788. self.assertCompareData(
  789. res_data,
  790. sentry_data,
  791. [
  792. "userReport",
  793. "title",
  794. "culprit",
  795. "type",
  796. "metadata",
  797. "message",
  798. "platform",
  799. "previousEventID",
  800. ],
  801. )
  802. self.assertEqual(res_data["projectID"], event.issue.project_id)
  803. def test_js_error_with_context(self):
  804. self.project.scrub_ip_addresses = False
  805. self.project.save()
  806. sdk_error, sentry_json, sentry_data = self.get_json_test_data(
  807. "js_error_with_context"
  808. )
  809. event_store_url = (
  810. reverse("api:event_store", args=[self.project.id])
  811. + "?sentry_key="
  812. + self.project.projectkey_set.first().public_key.hex
  813. )
  814. res = self.client.post(
  815. event_store_url,
  816. sdk_error,
  817. content_type="application/json",
  818. REMOTE_ADDR="142.255.29.14",
  819. )
  820. res_data = res.json()
  821. event = IssueEvent.objects.get(pk=res_data["event_id"])
  822. event_json = self.get_event_json(event)
  823. self.assertCompareData(event_json, sentry_json, ["title", "extra", "user"])
  824. url = self.get_project_events_detail(event.pk)
  825. res = self.client.get(url)
  826. res_json = res.json()
  827. self.assertCompareData(res_json, sentry_data, ["context"])
  828. self.assertCompareData(
  829. res_json["user"], sentry_data["user"], ["id", "email", "ip_address"]
  830. )
  831. def test_small_js_error(self):
  832. """A small example to test stacktraces"""
  833. sdk_error, sentry_json, sentry_data = self.get_json_test_data("small_js_error")
  834. event = self.submit_event(sdk_error, event_type="default")
  835. event_json = self.get_event_json(event)
  836. self.assertCompareData(
  837. event_json["exception"][0],
  838. sentry_json["exception"]["values"][0],
  839. ["type", "values", "exception", "abs_path"],
  840. )