test_organization_events_v2.py 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748
  1. import copy
  2. from datetime import timedelta
  3. from unittest.mock import patch
  4. from urllib.parse import urlencode
  5. import pytest
  6. import pytz
  7. from selenium.webdriver.common.by import By
  8. from selenium.webdriver.common.keys import Keys
  9. from sentry.discover.models import DiscoverSavedQuery
  10. from sentry.testutils import AcceptanceTestCase, SnubaTestCase
  11. from sentry.testutils.helpers.datetime import before_now, iso_format, timestamp_format
  12. from sentry.testutils.silo import region_silo_test
  13. from sentry.utils.samples import load_data
  14. FEATURE_NAMES = [
  15. "organizations:discover-basic",
  16. "organizations:discover-query",
  17. "organizations:performance-view",
  18. ]
  19. def all_events_query(**kwargs):
  20. options = {
  21. "sort": ["-timestamp"],
  22. "field": ["title", "event.type", "project", "user.display", "timestamp"],
  23. "name": ["All Events"],
  24. }
  25. options.update(kwargs)
  26. return urlencode(options, doseq=True)
  27. def errors_query(**kwargs):
  28. options = {
  29. "sort": ["-title"],
  30. "name": ["Errors"],
  31. "field": ["title", "count(id)", "count_unique(user)", "project"],
  32. "query": ["event.type:error"],
  33. }
  34. options.update(kwargs)
  35. return urlencode(options, doseq=True)
  36. def transactions_query(**kwargs):
  37. options = {
  38. "sort": ["-count"],
  39. "name": ["Transactions"],
  40. "field": ["transaction", "project", "count()"],
  41. "statsPeriod": ["14d"],
  42. "query": ["event.type:transaction"],
  43. }
  44. options.update(kwargs)
  45. return urlencode(options, doseq=True)
  46. # Sorted by transactions to avoid sorting issues caused by storing events
  47. def transactions_sorted_query(**kwargs):
  48. options = {
  49. "sort": ["transaction"],
  50. "name": ["Transactions"],
  51. "field": ["transaction", "project", "count()"],
  52. "statsPeriod": ["14d"],
  53. "query": ["event.type:transaction"],
  54. }
  55. options.update(kwargs)
  56. return urlencode(options, doseq=True)
  57. def generate_transaction(trace=None, span=None):
  58. end_datetime = before_now(minutes=10)
  59. start_datetime = end_datetime - timedelta(milliseconds=500)
  60. event_data = load_data(
  61. "transaction",
  62. timestamp=end_datetime,
  63. start_timestamp=start_datetime,
  64. trace=trace,
  65. span_id=span,
  66. )
  67. event_data.update({"event_id": "a" * 32})
  68. # generate and build up span tree
  69. reference_span = event_data["spans"][0]
  70. parent_span_id = reference_span["parent_span_id"]
  71. span_tree_blueprint = {
  72. "a": {},
  73. "b": {"bb": {"bbb": {"bbbb": "bbbbb"}}},
  74. "c": {},
  75. "d": {},
  76. "e": {},
  77. }
  78. time_offsets = {
  79. "a": (timedelta(), timedelta(milliseconds=10)),
  80. "b": (timedelta(milliseconds=120), timedelta(milliseconds=250)),
  81. "bb": (timedelta(milliseconds=130), timedelta(milliseconds=10)),
  82. "bbb": (timedelta(milliseconds=140), timedelta(milliseconds=10)),
  83. "bbbb": (timedelta(milliseconds=150), timedelta(milliseconds=10)),
  84. "bbbbb": (timedelta(milliseconds=160), timedelta(milliseconds=90)),
  85. "c": (timedelta(milliseconds=260), timedelta(milliseconds=100)),
  86. "d": (timedelta(milliseconds=375), timedelta(milliseconds=50)),
  87. "e": (timedelta(milliseconds=400), timedelta(milliseconds=100)),
  88. }
  89. def build_span_tree(span_tree, spans, parent_span_id):
  90. for span_id, child in sorted(span_tree.items(), key=lambda item: item[0]):
  91. span = copy.deepcopy(reference_span)
  92. # non-leaf node span
  93. span["parent_span_id"] = parent_span_id.ljust(16, "0")
  94. span["span_id"] = span_id.ljust(16, "0")
  95. (start_delta, span_length) = time_offsets.get(span_id, (timedelta(), timedelta()))
  96. span_start_time = start_datetime + start_delta
  97. span["start_timestamp"] = timestamp_format(span_start_time)
  98. span["timestamp"] = timestamp_format(span_start_time + span_length)
  99. spans.append(span)
  100. if isinstance(child, dict):
  101. spans = build_span_tree(child, spans, span_id)
  102. elif isinstance(child, str):
  103. parent_span_id = span_id
  104. span_id = child
  105. span = copy.deepcopy(reference_span)
  106. # leaf node span
  107. span["parent_span_id"] = parent_span_id.ljust(16, "0")
  108. span["span_id"] = span_id.ljust(16, "0")
  109. (start_delta, span_length) = time_offsets.get(span_id, (timedelta(), timedelta()))
  110. span_start_time = start_datetime + start_delta
  111. span["start_timestamp"] = timestamp_format(span_start_time)
  112. span["timestamp"] = timestamp_format(span_start_time + span_length)
  113. spans.append(span)
  114. return spans
  115. event_data["spans"] = build_span_tree(span_tree_blueprint, [], parent_span_id)
  116. return event_data
  117. @region_silo_test
  118. class OrganizationEventsV2Test(AcceptanceTestCase, SnubaTestCase):
  119. def setUp(self):
  120. super().setUp()
  121. self.user = self.create_user("foo@example.com", is_superuser=True)
  122. self.org = self.create_organization(name="Rowdy Tiger")
  123. self.team = self.create_team(organization=self.org, name="Mariachi Band")
  124. self.project = self.create_project(organization=self.org, teams=[self.team], name="Bengal")
  125. self.create_member(user=self.user, organization=self.org, role="owner", teams=[self.team])
  126. self.login_as(self.user)
  127. self.landing_path = f"/organizations/{self.org.slug}/discover/queries/"
  128. self.result_path = f"/organizations/{self.org.slug}/discover/results/"
  129. def wait_until_loaded(self):
  130. self.browser.wait_until_not('[data-test-id="loading-indicator"]')
  131. self.browser.wait_until_not('[data-test-id="loading-placeholder"]')
  132. def test_events_default_landing(self):
  133. with self.feature(FEATURE_NAMES):
  134. self.browser.get(self.landing_path)
  135. self.wait_until_loaded()
  136. self.browser.snapshot("events-v2 - default landing")
  137. def test_all_events_query_empty_state(self):
  138. with self.feature(FEATURE_NAMES):
  139. self.browser.get(self.result_path + "?" + all_events_query())
  140. self.wait_until_loaded()
  141. self.browser.snapshot("events-v2 - all events query - empty state")
  142. with self.feature(FEATURE_NAMES):
  143. # expect table to expand to the right when no tags are provided
  144. self.browser.get(self.result_path + "?" + all_events_query(tag=[]))
  145. self.wait_until_loaded()
  146. self.browser.snapshot("events-v2 - all events query - empty state - no tags")
  147. @patch("django.utils.timezone.now")
  148. def test_all_events_query(self, mock_now):
  149. now = before_now().replace(tzinfo=pytz.utc)
  150. mock_now.return_value = now
  151. five_mins_ago = iso_format(now - timedelta(minutes=5))
  152. ten_mins_ago = iso_format(now - timedelta(minutes=10))
  153. self.store_event(
  154. data={
  155. "event_id": "a" * 32,
  156. "message": "oh no",
  157. "timestamp": five_mins_ago,
  158. "fingerprint": ["group-1"],
  159. },
  160. project_id=self.project.id,
  161. assert_no_errors=False,
  162. )
  163. self.store_event(
  164. data={
  165. "event_id": "b" * 32,
  166. "message": "this is bad.",
  167. "timestamp": ten_mins_ago,
  168. "fingerprint": ["group-2"],
  169. "user": {
  170. "id": "123",
  171. "email": "someone@example.com",
  172. "username": "haveibeenpwned",
  173. "ip_address": "8.8.8.8",
  174. "name": "Someone",
  175. },
  176. },
  177. project_id=self.project.id,
  178. assert_no_errors=False,
  179. )
  180. self.wait_for_event_count(self.project.id, 2)
  181. with self.feature(FEATURE_NAMES):
  182. self.browser.get(self.result_path + "?" + all_events_query())
  183. self.wait_until_loaded()
  184. # This test is flakey in that we sometimes load this page before the event is processed
  185. # depend on pytest-retry to reload the page
  186. self.browser.wait_until('[data-test-id="grid-editable"] > tbody > tr:nth-child(2)')
  187. self.browser.snapshot("events-v2 - all events query - list")
  188. with self.feature(FEATURE_NAMES):
  189. # expect table to expand to the right when no tags are provided
  190. self.browser.get(self.result_path + "?" + all_events_query(tag=[]))
  191. self.wait_until_loaded()
  192. self.browser.wait_until('[data-test-id="grid-editable"] > tbody > tr:nth-child(2)')
  193. self.browser.snapshot("events-v2 - all events query - list - no tags")
  194. def test_errors_query_empty_state(self):
  195. with self.feature(FEATURE_NAMES):
  196. self.browser.get(self.result_path + "?" + errors_query())
  197. self.wait_until_loaded()
  198. self.browser.snapshot("events-v2 - errors query - empty state")
  199. self.browser.click_when_visible('[data-test-id="grid-edit-enable"]')
  200. self.browser.snapshot(
  201. "events-v2 - errors query - empty state - querybuilder - column edit state"
  202. )
  203. @patch("django.utils.timezone.now")
  204. def test_errors_query(self, mock_now):
  205. now = before_now().replace(tzinfo=pytz.utc)
  206. mock_now.return_value = now
  207. ten_mins_ago = iso_format(now - timedelta(minutes=10))
  208. self.store_event(
  209. data={
  210. "event_id": "a" * 32,
  211. "message": "oh no",
  212. "timestamp": ten_mins_ago,
  213. "fingerprint": ["group-1"],
  214. "type": "error",
  215. },
  216. project_id=self.project.id,
  217. assert_no_errors=False,
  218. )
  219. self.store_event(
  220. data={
  221. "event_id": "b" * 32,
  222. "message": "oh no",
  223. "timestamp": ten_mins_ago,
  224. "fingerprint": ["group-1"],
  225. "type": "error",
  226. },
  227. project_id=self.project.id,
  228. assert_no_errors=False,
  229. )
  230. self.store_event(
  231. data={
  232. "event_id": "c" * 32,
  233. "message": "this is bad.",
  234. "timestamp": ten_mins_ago,
  235. "fingerprint": ["group-2"],
  236. "type": "error",
  237. },
  238. project_id=self.project.id,
  239. assert_no_errors=False,
  240. )
  241. with self.feature(FEATURE_NAMES):
  242. self.browser.get(self.result_path + "?" + errors_query())
  243. self.wait_until_loaded()
  244. self.browser.snapshot("events-v2 - errors")
  245. def test_transactions_query_empty_state(self):
  246. with self.feature(FEATURE_NAMES):
  247. self.browser.get(self.result_path + "?" + transactions_query())
  248. self.wait_until_loaded()
  249. self.browser.snapshot("events-v2 - transactions query - empty state")
  250. with self.feature(FEATURE_NAMES):
  251. # expect table to expand to the right when no tags are provided
  252. self.browser.get(self.result_path + "?" + transactions_query(tag=[]))
  253. self.wait_until_loaded()
  254. self.browser.snapshot("events-v2 - transactions query - empty state - no tags")
  255. @patch("django.utils.timezone.now")
  256. def test_transactions_query(self, mock_now):
  257. mock_now.return_value = before_now().replace(tzinfo=pytz.utc)
  258. event_data = generate_transaction()
  259. self.store_event(data=event_data, project_id=self.project.id, assert_no_errors=True)
  260. with self.feature(FEATURE_NAMES):
  261. self.browser.get(self.result_path + "?" + transactions_query())
  262. self.wait_until_loaded()
  263. self.browser.wait_until_not(
  264. '[data-test-id="grid-editable"] [data-test-id="empty-state"]', timeout=2
  265. )
  266. self.browser.snapshot("events-v2 - transactions query - list")
  267. @patch("django.utils.timezone.now")
  268. def test_event_detail_view_from_all_events(self, mock_now):
  269. now = before_now().replace(tzinfo=pytz.utc)
  270. mock_now.return_value = now
  271. ten_mins_ago = iso_format(now - timedelta(minutes=10))
  272. event_data = load_data("python")
  273. event_data.update(
  274. {
  275. "event_id": "a" * 32,
  276. "timestamp": ten_mins_ago,
  277. "received": ten_mins_ago,
  278. "fingerprint": ["group-1"],
  279. }
  280. )
  281. if "contexts" not in event_data:
  282. event_data["contexts"] = {}
  283. event_data["contexts"]["trace"] = {
  284. "type": "trace",
  285. "trace_id": "a" * 32,
  286. "span_id": "b" * 16,
  287. }
  288. self.store_event(data=event_data, project_id=self.project.id, assert_no_errors=False)
  289. with self.feature(FEATURE_NAMES):
  290. # Get the list page.
  291. self.browser.get(self.result_path + "?" + all_events_query())
  292. self.wait_until_loaded()
  293. # View Event
  294. self.browser.elements('[data-test-id="view-event"]')[0].click()
  295. self.wait_until_loaded()
  296. # header = self.browser.element('[data-test-id="event-header"] div div span')
  297. # assert event_data["message"] in header.text
  298. self.browser.snapshot("events-v2 - single error details view")
  299. @patch("django.utils.timezone.now")
  300. def test_event_detail_view_from_errors_view(self, mock_now):
  301. now = before_now().replace(tzinfo=pytz.utc)
  302. mock_now.return_value = now
  303. event_data = load_data("javascript")
  304. event_data.update(
  305. {
  306. "timestamp": iso_format(now - timedelta(minutes=5)),
  307. "event_id": "d" * 32,
  308. "fingerprint": ["group-1"],
  309. }
  310. )
  311. event_data["contexts"]["trace"] = {
  312. "type": "trace",
  313. "trace_id": "a" * 32,
  314. "span_id": "b" * 16,
  315. }
  316. self.store_event(data=event_data, project_id=self.project.id)
  317. self.wait_for_event_count(self.project.id, 1)
  318. with self.feature(FEATURE_NAMES):
  319. # Get the list page
  320. self.browser.get(self.result_path + "?" + errors_query() + "&statsPeriod=24h")
  321. self.wait_until_loaded()
  322. # Open the stack
  323. self.browser.element('[data-test-id="open-group"]').click()
  324. self.wait_until_loaded()
  325. # View Event
  326. self.browser.elements('[data-test-id="view-event"]')[0].click()
  327. self.wait_until_loaded()
  328. self.browser.snapshot("events-v2 - error event detail view")
  329. @patch("django.utils.timezone.now")
  330. def test_event_detail_view_from_transactions_query(self, mock_now):
  331. mock_now.return_value = before_now().replace(tzinfo=pytz.utc)
  332. event_data = generate_transaction(trace="a" * 32, span="ab" * 8)
  333. self.store_event(data=event_data, project_id=self.project.id, assert_no_errors=True)
  334. # Create a child event that is linked to the parent so we have coverage
  335. # of traversal buttons.
  336. child_event = generate_transaction(
  337. trace=event_data["contexts"]["trace"]["trace_id"], span="bc" * 8
  338. )
  339. child_event["event_id"] = "b" * 32
  340. child_event["contexts"]["trace"]["parent_span_id"] = event_data["spans"][4]["span_id"]
  341. child_event["transaction"] = "z-child-transaction"
  342. child_event["spans"] = child_event["spans"][0:3]
  343. self.store_event(data=child_event, project_id=self.project.id, assert_no_errors=True)
  344. with self.feature(FEATURE_NAMES):
  345. # Get the list page
  346. self.browser.get(self.result_path + "?" + transactions_sorted_query())
  347. self.wait_until_loaded()
  348. # Open the stack
  349. self.browser.elements('[data-test-id="open-group"]')[0].click()
  350. self.wait_until_loaded()
  351. # View Event
  352. self.browser.elements('[data-test-id="view-event"]')[0].click()
  353. self.wait_until_loaded()
  354. self.browser.snapshot("events-v2 - transactions event with auto-grouped spans")
  355. # Expand auto-grouped spans
  356. self.browser.element('[data-test-id="span-row-5"]').click()
  357. # Open a span detail so we can check the search by trace link.
  358. # Click on the 6th one as a missing instrumentation span is inserted.
  359. self.browser.element('[data-test-id="span-row-7"]').click()
  360. # Wait until the child event loads.
  361. child_button = '[data-test-id="view-child-transaction"]'
  362. self.browser.wait_until(child_button)
  363. self.browser.snapshot("events-v2 - transactions event detail view")
  364. # Click on the child transaction.
  365. self.browser.click(child_button)
  366. self.wait_until_loaded()
  367. @patch("django.utils.timezone.now")
  368. def test_event_detail_view_from_transactions_query_siblings(self, mock_now):
  369. mock_now.return_value = before_now().replace(tzinfo=pytz.utc)
  370. event_data = generate_transaction(trace="a" * 32, span="ab" * 8)
  371. # Arranges sibling spans to be autogrouped in a way that will cover many edgecases
  372. last_span = copy.deepcopy(event_data["spans"][-1])
  373. for i in range(5):
  374. clone = copy.deepcopy(last_span)
  375. # If range > 9 this might no longer work because of constraints on span_id (hex 16)
  376. clone["span_id"] = (str("ac" * 6) + str(i)).ljust(16, "0")
  377. event_data["spans"].append(clone)
  378. combo_breaker_span = copy.deepcopy(last_span)
  379. combo_breaker_span["span_id"] = (str("af" * 6)).ljust(16, "0")
  380. combo_breaker_span["op"] = "combo.breaker"
  381. event_data["spans"].append(combo_breaker_span)
  382. for i in range(5):
  383. clone = copy.deepcopy(last_span)
  384. clone["op"] = "django.middleware"
  385. clone["span_id"] = (str("de" * 6) + str(i)).ljust(16, "0")
  386. event_data["spans"].append(clone)
  387. for i in range(5):
  388. clone = copy.deepcopy(last_span)
  389. clone["op"] = "http"
  390. clone["description"] = "test"
  391. clone["span_id"] = (str("bd" * 6) + str(i)).ljust(16, "0")
  392. event_data["spans"].append(clone)
  393. self.store_event(data=event_data, project_id=self.project.id, assert_no_errors=True)
  394. # Create a child event that is linked to the parent so we have coverage
  395. # of traversal buttons.
  396. child_event = generate_transaction(
  397. trace=event_data["contexts"]["trace"]["trace_id"], span="bc" * 8
  398. )
  399. child_event["event_id"] = "b" * 32
  400. child_event["contexts"]["trace"]["parent_span_id"] = event_data["spans"][4]["span_id"]
  401. child_event["transaction"] = "z-child-transaction"
  402. child_event["spans"] = child_event["spans"][0:3]
  403. self.store_event(data=child_event, project_id=self.project.id, assert_no_errors=True)
  404. with self.feature(FEATURE_NAMES + ["organizations:performance-autogroup-sibling-spans"]):
  405. # Get the list page
  406. self.browser.get(self.result_path + "?" + transactions_sorted_query())
  407. self.wait_until_loaded()
  408. # Open the stack
  409. self.browser.elements('[data-test-id="open-group"]')[0].click()
  410. self.wait_until_loaded()
  411. # View Event
  412. self.browser.elements('[data-test-id="view-event"]')[0].click()
  413. self.wait_until_loaded()
  414. self.browser.snapshot(
  415. "events-v2 - transactions event with descendant and sibling auto-grouped spans"
  416. )
  417. # Expand auto-grouped descendant spans
  418. self.browser.element('[data-test-id="span-row-5"]').click()
  419. # Expand all autogrouped rows
  420. self.browser.element('[data-test-id="span-row-9"]').click()
  421. self.browser.element('[data-test-id="span-row-18"]').click()
  422. self.browser.element('[data-test-id="span-row-23"]').click()
  423. self.browser.snapshot(
  424. "events-v2 - transactions event with expanded descendant and sibling auto-grouped spans"
  425. )
  426. # Click to collapse all of these spans back into autogroups, we expect the span tree to look like it did initially
  427. first_row = self.browser.element('[data-test-id="span-row-23"]')
  428. first_row.find_element(By.CSS_SELECTOR, "a").click()
  429. second_row = self.browser.element('[data-test-id="span-row-18"]')
  430. second_row.find_element(By.CSS_SELECTOR, "a").click()
  431. third_row = self.browser.element('[data-test-id="span-row-9"]')
  432. third_row.find_element(By.CSS_SELECTOR, "a").click()
  433. self.browser.snapshot(
  434. "events-v2 - transactions event after regrouping expanded sibling auto-grouped spans"
  435. )
  436. @patch("django.utils.timezone.now")
  437. def test_transaction_event_detail_view_ops_filtering(self, mock_now):
  438. mock_now.return_value = before_now().replace(tzinfo=pytz.utc)
  439. event_data = generate_transaction(trace="a" * 32, span="ab" * 8)
  440. self.store_event(data=event_data, project_id=self.project.id, assert_no_errors=True)
  441. with self.feature(FEATURE_NAMES):
  442. # Get the list page
  443. self.browser.get(self.result_path + "?" + transactions_query())
  444. self.wait_until_loaded()
  445. # Open the stack
  446. self.browser.elements('[data-test-id="open-group"]')[0].click()
  447. self.wait_until_loaded()
  448. # View Event
  449. self.browser.elements('[data-test-id="view-event"]')[0].click()
  450. self.wait_until_loaded()
  451. # Interact with ops filter dropdown
  452. self.browser.elements('[data-test-id="operation-filter-dropdown-trigger"]')[0].click()
  453. # select django.middleware
  454. self.browser.elements('[data-test-id="django.middleware"]')[0].click()
  455. self.browser.snapshot("events-v2 - transactions event detail view - ops filtering")
  456. def test_create_saved_query(self):
  457. # Simulate a custom query
  458. query = {"field": ["project.id", "count()"], "query": "event.type:error"}
  459. query_name = "A new custom query"
  460. with self.feature(FEATURE_NAMES):
  461. # Go directly to the query builder view
  462. self.browser.get(self.result_path + "?" + urlencode(query, doseq=True))
  463. self.wait_until_loaded()
  464. # Open the save as drawer
  465. self.browser.element('[aria-label="Save as"]').click()
  466. # Fill out name and submit form.
  467. self.browser.element('input[name="query_name"]').send_keys(query_name)
  468. self.browser.element('[aria-label="Save for Org"]').click()
  469. self.browser.wait_until(f'[data-test-id="discover2-query-name-{query_name}"]')
  470. # Page title should update.
  471. editable_text_label = self.browser.element('[data-test-id="editable-text-label"]').text
  472. assert editable_text_label == query_name
  473. # Saved query should exist.
  474. assert DiscoverSavedQuery.objects.filter(name=query_name).exists()
  475. def test_view_and_rename_saved_query(self):
  476. # Create saved query to rename
  477. query = DiscoverSavedQuery.objects.create(
  478. name="Custom query",
  479. organization=self.org,
  480. version=2,
  481. query={"fields": ["title", "project.id", "count()"], "query": "event.type:error"},
  482. )
  483. with self.feature(FEATURE_NAMES):
  484. # View the query list
  485. self.browser.get(self.landing_path)
  486. self.wait_until_loaded()
  487. # Look at the results for our query.
  488. self.browser.element(f'[data-test-id="card-{query.name}"]').click()
  489. self.wait_until_loaded()
  490. self.browser.element('[data-test-id="editable-text-label"]').click()
  491. self.browser.wait_until('[data-test-id="editable-text-input"]')
  492. editable_text_input = self.browser.element('[data-test-id="editable-text-input"] input')
  493. editable_text_input.click()
  494. editable_text_input.send_keys(Keys.END + "updated!")
  495. # Move focus somewhere else to trigger a blur and update the query
  496. self.browser.element("table").click()
  497. self.browser.wait_until('[data-test-id="editable-text-label"]')
  498. new_name = "Custom queryupdated!"
  499. # new_card_selector = f'div[name="discover2-query-name"][value="{new_name}"]'
  500. # self.browser.wait_until(new_card_selector)
  501. self.browser.wait_until(f'[data-test-id="discover2-query-name-{new_name}"]')
  502. # Assert the name was updated.
  503. assert DiscoverSavedQuery.objects.filter(name=new_name).exists()
  504. def test_delete_saved_query(self):
  505. # Create saved query with ORM
  506. query = DiscoverSavedQuery.objects.create(
  507. name="Custom query",
  508. organization=self.org,
  509. version=2,
  510. query={"fields": ["title", "project.id", "count()"], "query": "event.type:error"},
  511. )
  512. with self.feature(FEATURE_NAMES):
  513. # View the query list
  514. self.browser.get(self.landing_path)
  515. self.wait_until_loaded()
  516. # Get the card with the new query
  517. card_selector = f'[data-test-id="card-{query.name}"]'
  518. card = self.browser.element(card_selector)
  519. # Open the context menu
  520. card.find_element(by=By.CSS_SELECTOR, value='[data-test-id="menu-trigger"]').click()
  521. # Delete the query
  522. card.find_element(by=By.CSS_SELECTOR, value='[data-test-id="delete"]').click()
  523. # Wait for card to clear
  524. self.browser.wait_until_not(card_selector)
  525. assert DiscoverSavedQuery.objects.filter(name=query.name).exists() is False
  526. def test_duplicate_query(self):
  527. # Create saved query with ORM
  528. query = DiscoverSavedQuery.objects.create(
  529. name="Custom query",
  530. organization=self.org,
  531. version=2,
  532. query={"fields": ["title", "project.id", "count()"], "query": "event.type:error"},
  533. )
  534. with self.feature(FEATURE_NAMES):
  535. # View the query list
  536. self.browser.get(self.landing_path)
  537. self.wait_until_loaded()
  538. # Get the card with the new query
  539. card_selector = f'[data-test-id="card-{query.name}"]'
  540. card = self.browser.element(card_selector)
  541. # Open the context menu, and duplicate
  542. card.find_element(by=By.CSS_SELECTOR, value='[data-test-id="menu-trigger"]').click()
  543. card.find_element(by=By.CSS_SELECTOR, value='[data-test-id="duplicate"]').click()
  544. duplicate_name = f"{query.name} copy"
  545. # Reload the page
  546. self.browser.get(self.landing_path)
  547. # Wait for new element to show up.
  548. self.browser.element(f'[data-test-id="card-{duplicate_name}"]')
  549. # Assert the new query exists and has 'copy' added to the name.
  550. assert DiscoverSavedQuery.objects.filter(name=duplicate_name).exists()
  551. @pytest.mark.skip(reason="causing timeouts in github actions and travis")
  552. @patch("django.utils.timezone.now")
  553. def test_drilldown_result(self, mock_now):
  554. now = before_now().replace(tzinfo=pytz.utc)
  555. mock_now.return_value = now
  556. ten_mins_ago = iso_format(now - timedelta(minutes=10))
  557. events = (
  558. ("a" * 32, "oh no", "group-1"),
  559. ("b" * 32, "oh no", "group-1"),
  560. ("c" * 32, "this is bad", "group-2"),
  561. )
  562. for event in events:
  563. self.store_event(
  564. data={
  565. "event_id": event[0],
  566. "message": event[1],
  567. "timestamp": ten_mins_ago,
  568. "fingerprint": [event[2]],
  569. "type": "error",
  570. },
  571. project_id=self.project.id,
  572. )
  573. query = {"field": ["message", "project", "count()"], "query": "event.type:error"}
  574. with self.feature(FEATURE_NAMES):
  575. # Go directly to the query builder view
  576. self.browser.get(self.result_path + "?" + urlencode(query, doseq=True))
  577. self.wait_until_loaded()
  578. # Click the first drilldown
  579. self.browser.element('[data-test-id="expand-count"]').click()
  580. self.wait_until_loaded()
  581. assert self.browser.element_exists_by_test_id("grid-editable"), "table should exist."
  582. headers = self.browser.elements('[data-test-id="grid-editable"] thead th')
  583. expected = ["", "MESSAGE", "PROJECT", "ID"]
  584. actual = [header.text for header in headers]
  585. assert expected == actual
  586. @pytest.mark.skip(reason="not done")
  587. @patch("django.utils.timezone.now")
  588. def test_usage(self, mock_now):
  589. mock_now.return_value = before_now().replace(tzinfo=pytz.utc)
  590. # TODO: load events
  591. # go to landing
  592. # go to a precanned query
  593. # save query 1
  594. # add environment column
  595. # update query
  596. # add condition from facet map
  597. # delete a column
  598. # click and drag a column
  599. # save as query 2
  600. # load save query 1
  601. # sort column
  602. # update query
  603. # delete save query 1