metrics_test.py 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826
  1. #!/usr/bin/env vpython3
  2. # Copyright (c) 2018 The Chromium Authors. All rights reserved.
  3. # Use of this source code is governed by a BSD-style license that can be
  4. # found in the LICENSE file.
  5. import json
  6. import os
  7. import sys
  8. import unittest
  9. from unittest import mock
  10. ROOT_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
  11. sys.path.insert(0, ROOT_DIR)
  12. import metrics
  13. import metrics_utils
  14. import utils
  15. # TODO: Should fix these warnings.
  16. # pylint: disable=line-too-long
  17. class TimeMock(object):
  18. def __init__(self):
  19. self._count = 0
  20. def __call__(self):
  21. self._count += 1
  22. return self._count * 1000
  23. class MetricsCollectorTest(unittest.TestCase):
  24. def setUp(self):
  25. self.config_file = utils.depot_tools_config_path('metrics.cfg')
  26. self.collector = metrics.MetricsCollector()
  27. # Keep track of the URL requests, file reads/writes and subprocess
  28. # spawned.
  29. self.urllib_request = mock.Mock()
  30. self.print_notice = mock.Mock()
  31. self.print_version_change = mock.Mock()
  32. self.Popen = mock.Mock()
  33. self.FileWrite = mock.Mock()
  34. self.FileRead = mock.Mock()
  35. # So that we don't have to update the tests every time we change the
  36. # version.
  37. mock.patch('metrics.metrics_utils.CURRENT_VERSION', 0).start()
  38. mock.patch('metrics.urllib.request', self.urllib_request).start()
  39. mock.patch('metrics.subprocess2.Popen', self.Popen).start()
  40. mock.patch('metrics.gclient_utils.FileWrite', self.FileWrite).start()
  41. mock.patch('metrics.gclient_utils.FileRead', self.FileRead).start()
  42. mock.patch('metrics.metrics_utils.print_notice',
  43. self.print_notice).start()
  44. mock.patch('metrics.metrics_utils.print_version_change',
  45. self.print_version_change).start()
  46. # Patch the methods used to get the system information, so we have a
  47. # known environment.
  48. mock.patch('metrics.time.time', TimeMock()).start()
  49. mock.patch('metrics.metrics_utils.get_python_version',
  50. lambda: '2.7.13').start()
  51. mock.patch('metrics.gclient_utils.GetOperatingSystem',
  52. lambda: 'linux').start()
  53. mock.patch('metrics.detect_host_arch.HostArch', lambda: 'x86').start()
  54. mock.patch('metrics_utils.get_repo_timestamp', lambda _: 1234).start()
  55. mock.patch('metrics_utils.get_git_version', lambda: '2.18.1').start()
  56. mock.patch('newauth.Enabled', lambda: False).start()
  57. mock.patch('newauth.ExplicitlyDisabled', lambda: False).start()
  58. self.maxDiff = None
  59. self.default_metrics = {
  60. "metrics_version": 0,
  61. "python_version": "2.7.13",
  62. "git_version": "2.18.1",
  63. "execution_time": 1000,
  64. "timestamp": 3000,
  65. "exit_code": 0,
  66. "command": "fun",
  67. "depot_tools_age": 1234,
  68. "host_arch": "x86",
  69. "host_os": "linux",
  70. }
  71. self.addCleanup(mock.patch.stopall)
  72. def assert_writes_file(self, expected_filename, expected_content):
  73. self.assertEqual(len(self.FileWrite.mock_calls), 1)
  74. filename, content = self.FileWrite.mock_calls[0][1]
  75. self.assertEqual(filename, expected_filename)
  76. self.assertEqual(json.loads(content), expected_content)
  77. def test_writes_config_if_not_exists(self):
  78. self.FileRead.side_effect = [IOError(2, "No such file or directory")]
  79. mock_response = mock.Mock()
  80. self.urllib_request.urlopen.side_effect = [mock_response]
  81. mock_response.getcode.side_effect = [200]
  82. self.assertTrue(self.collector.config.is_googler)
  83. self.assertIsNone(self.collector.config.opted_in)
  84. self.assertEqual(self.collector.config.countdown, 10)
  85. self.assert_writes_file(self.config_file, {
  86. 'is-googler': True,
  87. 'countdown': 10,
  88. 'opt-in': None,
  89. 'version': 0
  90. })
  91. def test_writes_config_if_not_exists_non_googler(self):
  92. self.FileRead.side_effect = [IOError(2, "No such file or directory")]
  93. mock_response = mock.Mock()
  94. self.urllib_request.urlopen.side_effect = [mock_response]
  95. mock_response.getcode.side_effect = [403]
  96. self.assertFalse(self.collector.config.is_googler)
  97. self.assertIsNone(self.collector.config.opted_in)
  98. self.assertEqual(self.collector.config.countdown, 10)
  99. self.assert_writes_file(self.config_file, {
  100. 'is-googler': False,
  101. 'countdown': 10,
  102. 'opt-in': None,
  103. 'version': 0
  104. })
  105. def test_disables_metrics_if_cant_write_config(self):
  106. self.FileRead.side_effect = [IOError(2, 'No such file or directory')]
  107. mock_response = mock.Mock()
  108. self.urllib_request.urlopen.side_effect = [mock_response]
  109. mock_response.getcode.side_effect = [200]
  110. self.FileWrite.side_effect = [IOError(13, 'Permission denied.')]
  111. self.assertTrue(self.collector.config.is_googler)
  112. self.assertFalse(self.collector.config.opted_in)
  113. self.assertEqual(self.collector.config.countdown, 10)
  114. def assert_collects_metrics(self, update_metrics=None):
  115. expected_metrics = self.default_metrics
  116. self.default_metrics.update(update_metrics or {})
  117. # Assert we invoked the script to upload them.
  118. self.Popen.assert_called_with(['vpython3', metrics.UPLOAD_SCRIPT],
  119. stdin=metrics.subprocess2.PIPE)
  120. # Assert we collected the right metrics.
  121. write_call = self.Popen.return_value.stdin.write.call_args
  122. collected_metrics = json.loads(write_call[0][0])
  123. self.assertTrue(self.collector.collecting_metrics)
  124. self.assertEqual(collected_metrics, expected_metrics)
  125. def test_collects_system_information(self):
  126. """Tests that we collect information about the runtime environment."""
  127. self.FileRead.side_effect = [
  128. '{"is-googler": true, "countdown": 0, "opt-in": null, "version": 0}'
  129. ]
  130. @self.collector.collect_metrics('fun')
  131. def fun():
  132. pass
  133. fun()
  134. self.assert_collects_metrics()
  135. def test_collects_added_metrics(self):
  136. """Tests that we can collect custom metrics."""
  137. self.FileRead.side_effect = [
  138. '{"is-googler": true, "countdown": 0, "opt-in": null, "version": 0}'
  139. ]
  140. @self.collector.collect_metrics('fun')
  141. def fun():
  142. self.collector.add('foo', 'bar')
  143. fun()
  144. self.assert_collects_metrics({'foo': 'bar'})
  145. def test_collects_metrics_when_opted_in(self):
  146. """Tests that metrics are collected when the user opts-in."""
  147. self.FileRead.side_effect = [
  148. '{"is-googler": true, "countdown": 1234, "opt-in": true, "version": 0}'
  149. ]
  150. @self.collector.collect_metrics('fun')
  151. def fun():
  152. pass
  153. fun()
  154. self.assert_collects_metrics()
  155. @mock.patch('metrics_utils.REPORT_BUILD', 'p/b/b/1')
  156. def test_collects_metrics_report_build_set(self):
  157. """Tests that metrics are collected when REPORT_BUILD is set."""
  158. @self.collector.collect_metrics('fun')
  159. def fun():
  160. pass
  161. fun()
  162. self.assert_collects_metrics({
  163. 'bot_metrics': {
  164. 'build_id': 1,
  165. 'builder': {
  166. 'project': 'p',
  167. 'bucket': 'b',
  168. 'builder': 'b',
  169. }
  170. }
  171. })
  172. # We shouldn't have tried to read the config file.
  173. self.assertFalse(self.FileRead.called)
  174. @mock.patch('metrics_utils.COLLECT_METRICS', False)
  175. def test_metrics_collection_disabled(self):
  176. """Tests that metrics collection can be disabled via a global variable."""
  177. @self.collector.collect_metrics('fun')
  178. def fun():
  179. pass
  180. fun()
  181. self.assertFalse(self.collector.collecting_metrics)
  182. # We shouldn't have tried to read the config file.
  183. self.assertFalse(self.FileRead.called)
  184. # Nor tried to upload any metrics.
  185. self.assertFalse(self.Popen.called)
  186. def test_metrics_collection_disabled_not_googler(self):
  187. """Tests that metrics collection is disabled for non googlers."""
  188. self.FileRead.side_effect = [
  189. '{"is-googler": false, "countdown": 0, "opt-in": null, "version": 0}'
  190. ]
  191. @self.collector.collect_metrics('fun')
  192. def fun():
  193. pass
  194. fun()
  195. self.assertFalse(self.collector.collecting_metrics)
  196. self.assertFalse(self.collector.config.is_googler)
  197. self.assertIsNone(self.collector.config.opted_in)
  198. self.assertEqual(self.collector.config.countdown, 0)
  199. # Assert that we did not try to upload any metrics.
  200. self.assertFalse(self.Popen.called)
  201. def test_metrics_collection_disabled_opted_out(self):
  202. """Tests that metrics collection is disabled if the user opts out."""
  203. self.FileRead.side_effect = [
  204. '{"is-googler": true, "countdown": 0, "opt-in": false, "version": 0}'
  205. ]
  206. @self.collector.collect_metrics('fun')
  207. def fun():
  208. pass
  209. fun()
  210. self.assertFalse(self.collector.collecting_metrics)
  211. self.assertTrue(self.collector.config.is_googler)
  212. self.assertFalse(self.collector.config.opted_in)
  213. self.assertEqual(self.collector.config.countdown, 0)
  214. # Assert that we did not try to upload any metrics.
  215. self.assertFalse(self.Popen.called)
  216. def test_metrics_collection_disabled_non_zero_countdown(self):
  217. """Tests that metrics collection is disabled until the countdown expires."""
  218. self.FileRead.side_effect = [
  219. '{"is-googler": true, "countdown": 1, "opt-in": null, "version": 0}'
  220. ]
  221. @self.collector.collect_metrics('fun')
  222. def fun():
  223. pass
  224. fun()
  225. self.assertFalse(self.collector.collecting_metrics)
  226. self.assertTrue(self.collector.config.is_googler)
  227. self.assertFalse(self.collector.config.opted_in)
  228. self.assertEqual(self.collector.config.countdown, 1)
  229. # Assert that we did not try to upload any metrics.
  230. self.assertFalse(self.Popen.called)
  231. def test_handles_exceptions(self):
  232. """Tests that exception are caught and we exit with an appropriate code."""
  233. self.FileRead.side_effect = [
  234. '{"is-googler": true, "countdown": 0, "opt-in": true, "version": 0}'
  235. ]
  236. @self.collector.collect_metrics('fun')
  237. def fun():
  238. raise ValueError
  239. # When an exception is raised, we should catch it, update exit-code,
  240. # collect metrics, and re-raise it.
  241. with self.assertRaises(ValueError):
  242. fun()
  243. self.assert_collects_metrics({'exit_code': 1})
  244. def test_handles_system_exit(self):
  245. """Tests that the sys.exit code is respected and metrics are collected."""
  246. self.FileRead.side_effect = [
  247. '{"is-googler": true, "countdown": 0, "opt-in": true, "version": 0}'
  248. ]
  249. @self.collector.collect_metrics('fun')
  250. def fun():
  251. sys.exit(0)
  252. # When an exception is raised, we should catch it, update exit-code,
  253. # collect metrics, and re-raise it.
  254. with self.assertRaises(SystemExit) as cm:
  255. fun()
  256. self.assertEqual(cm.exception.code, 0)
  257. self.assert_collects_metrics({'exit_code': 0})
  258. def test_handles_keyboard_interrupt(self):
  259. """Tests that KeyboardInterrupt exits with 130 and metrics are collected."""
  260. self.FileRead.side_effect = [
  261. '{"is-googler": true, "countdown": 0, "opt-in": true, "version": 0}'
  262. ]
  263. @self.collector.collect_metrics('fun')
  264. def fun():
  265. raise KeyboardInterrupt
  266. # When an exception is raised, we should catch it, update exit-code,
  267. # collect metrics, and re-raise it.
  268. with self.assertRaises(KeyboardInterrupt):
  269. fun()
  270. self.assert_collects_metrics({'exit_code': 130})
  271. def test_handles_system_exit_non_zero(self):
  272. """Tests that the sys.exit code is respected and metrics are collected."""
  273. self.FileRead.side_effect = [
  274. '{"is-googler": true, "countdown": 0, "opt-in": true, "version": 0}'
  275. ]
  276. @self.collector.collect_metrics('fun')
  277. def fun():
  278. sys.exit(123)
  279. # When an exception is raised, we should catch it, update exit-code,
  280. # collect metrics, and re-raise it.
  281. with self.assertRaises(SystemExit) as cm:
  282. fun()
  283. self.assertEqual(cm.exception.code, 123)
  284. self.assert_collects_metrics({'exit_code': 123})
  285. def test_prints_notice_non_zero_countdown(self):
  286. """Tests that a notice is printed while the countdown is non-zero."""
  287. self.FileRead.side_effect = [
  288. '{"is-googler": true, "countdown": 1234, "opt-in": null, "version": 0}'
  289. ]
  290. with self.assertRaises(SystemExit) as cm:
  291. with self.collector.print_notice_and_exit():
  292. pass
  293. self.assertEqual(cm.exception.code, 0)
  294. self.print_notice.assert_called_once_with(1234)
  295. def test_prints_notice_zero_countdown(self):
  296. """Tests that a notice is printed when the countdown reaches 0."""
  297. self.FileRead.side_effect = [
  298. '{"is-googler": true, "countdown": 0, "opt-in": null, "version": 0}'
  299. ]
  300. with self.assertRaises(SystemExit) as cm:
  301. with self.collector.print_notice_and_exit():
  302. pass
  303. self.assertEqual(cm.exception.code, 0)
  304. self.print_notice.assert_called_once_with(0)
  305. def test_doesnt_print_notice_opted_in(self):
  306. """Tests that a notice is not printed when the user opts-in."""
  307. self.FileRead.side_effect = [
  308. '{"is-googler": true, "countdown": 0, "opt-in": true, "version": 0}'
  309. ]
  310. with self.assertRaises(SystemExit) as cm:
  311. with self.collector.print_notice_and_exit():
  312. pass
  313. self.assertEqual(cm.exception.code, 0)
  314. self.assertFalse(self.print_notice.called)
  315. def test_doesnt_print_notice_opted_out(self):
  316. """Tests that a notice is not printed when the user opts-out."""
  317. self.FileRead.side_effect = [
  318. '{"is-googler": true, "countdown": 0, "opt-in": false, "version": 0}'
  319. ]
  320. with self.assertRaises(SystemExit) as cm:
  321. with self.collector.print_notice_and_exit():
  322. pass
  323. self.assertEqual(cm.exception.code, 0)
  324. self.assertFalse(self.print_notice.called)
  325. @mock.patch('metrics_utils.COLLECT_METRICS', False)
  326. def test_doesnt_print_notice_disable_metrics_collection(self):
  327. with self.assertRaises(SystemExit) as cm:
  328. with self.collector.print_notice_and_exit():
  329. pass
  330. self.assertEqual(cm.exception.code, 0)
  331. self.assertFalse(self.print_notice.called)
  332. # We shouldn't have tried to read the config file.
  333. self.assertFalse(self.FileRead.called)
  334. @mock.patch('metrics_utils.REPORT_BUILD', 'p/b/b/1')
  335. def test_doesnt_print_notice_report_build(self):
  336. with self.assertRaises(SystemExit) as cm:
  337. with self.collector.print_notice_and_exit():
  338. pass
  339. self.assertEqual(cm.exception.code, 0)
  340. self.assertFalse(self.print_notice.called)
  341. # We shouldn't have tried to read the config file.
  342. self.assertFalse(self.FileRead.called)
  343. def test_print_notice_handles_exceptions(self):
  344. """Tests that exception are caught and we exit with an appropriate code."""
  345. self.FileRead.side_effect = [
  346. '{"is-googler": true, "countdown": 0, "opt-in": null, "version": 0}'
  347. ]
  348. # print_notice should catch the exception, print it and invoke
  349. # sys.exit()
  350. with self.assertRaises(SystemExit) as cm:
  351. with self.collector.print_notice_and_exit():
  352. raise ValueError
  353. self.assertEqual(cm.exception.code, 1)
  354. self.assertTrue(self.print_notice.called)
  355. def test_print_notice_handles_system_exit(self):
  356. """Tests that the sys.exit code is respected and a notice is displayed."""
  357. self.FileRead.side_effect = [
  358. '{"is-googler": true, "countdown": 0, "opt-in": null, "version": 0}'
  359. ]
  360. # print_notice should catch the exception, print it and invoke
  361. # sys.exit()
  362. with self.assertRaises(SystemExit) as cm:
  363. with self.collector.print_notice_and_exit():
  364. sys.exit(0)
  365. self.assertEqual(cm.exception.code, 0)
  366. self.assertTrue(self.print_notice.called)
  367. def test_print_notice_handles_system_exit_non_zero(self):
  368. """Tests that the sys.exit code is respected and a notice is displayed."""
  369. self.FileRead.side_effect = [
  370. '{"is-googler": true, "countdown": 0, "opt-in": null, "version": 0}'
  371. ]
  372. # When an exception is raised, we should catch it, update exit-code,
  373. # collect metrics, and re-raise it.
  374. with self.assertRaises(SystemExit) as cm:
  375. with self.collector.print_notice_and_exit():
  376. sys.exit(123)
  377. self.assertEqual(cm.exception.code, 123)
  378. self.assertTrue(self.print_notice.called)
  379. def test_counts_down(self):
  380. """Tests that the countdown works correctly."""
  381. self.FileRead.side_effect = [
  382. '{"is-googler": true, "countdown": 10, "opt-in": null, "version": 0}'
  383. ]
  384. # We define multiple functions to ensure it has no impact on countdown.
  385. @self.collector.collect_metrics('barn')
  386. def _barn():
  387. pass
  388. @self.collector.collect_metrics('fun')
  389. def _fun():
  390. pass
  391. def foo_main():
  392. pass
  393. # Assert that the countdown hasn't decrease yet.
  394. self.assertFalse(self.FileWrite.called)
  395. self.assertEqual(self.collector.config.countdown, 10)
  396. with self.assertRaises(SystemExit) as cm:
  397. with self.collector.print_notice_and_exit():
  398. foo_main()
  399. self.assertEqual(cm.exception.code, 0)
  400. # Assert that the countdown decreased by one, and the config file was
  401. # updated.
  402. self.assertEqual(self.collector.config.countdown, 9)
  403. self.print_notice.assert_called_once_with(10)
  404. self.assert_writes_file(self.config_file, {
  405. 'is-googler': True,
  406. 'countdown': 9,
  407. 'opt-in': None,
  408. 'version': 0
  409. })
  410. def test_nested_functions(self):
  411. """Tests that a function can call another function for which metrics are
  412. collected."""
  413. self.FileRead.side_effect = [
  414. '{"is-googler": true, "countdown": 0, "opt-in": true, "version": 0}'
  415. ]
  416. @self.collector.collect_metrics('barn')
  417. def barn():
  418. self.collector.add('barn-metric', 1)
  419. return 1000
  420. @self.collector.collect_metrics('fun')
  421. def fun():
  422. result = barn()
  423. self.collector.add('fun-metric', result + 1)
  424. fun()
  425. # Assert that we collected metrics for fun, but not for barn.
  426. self.assert_collects_metrics({'fun-metric': 1001})
  427. @mock.patch('metrics.metrics_utils.CURRENT_VERSION', 5)
  428. def test_version_change_from_hasnt_decided(self):
  429. # The user has not decided yet, and the countdown hasn't reached 0, so
  430. # we're not collecting metrics.
  431. self.FileRead.side_effect = [
  432. '{"is-googler": true, "countdown": 9, "opt-in": null, "version": 0}'
  433. ]
  434. with self.assertRaises(SystemExit) as cm:
  435. with self.collector.print_notice_and_exit():
  436. self.collector.add('foo-metric', 1)
  437. self.assertEqual(cm.exception.code, 0)
  438. # We display the notice informing the user of the changes.
  439. self.print_version_change.assert_called_once_with(0)
  440. # But the countdown is not reset.
  441. self.assert_writes_file(self.config_file, {
  442. 'is-googler': True,
  443. 'countdown': 8,
  444. 'opt-in': None,
  445. 'version': 0
  446. })
  447. # And no metrics are uploaded.
  448. self.assertFalse(self.Popen.called)
  449. @mock.patch('metrics.metrics_utils.CURRENT_VERSION', 5)
  450. def test_version_change_from_opted_in_by_default(self):
  451. # The user has not decided yet, but the countdown has reached 0, and
  452. # we're collecting metrics.
  453. self.FileRead.side_effect = [
  454. '{"is-googler": true, "countdown": 0, "opt-in": null, "version": 0}'
  455. ]
  456. with self.assertRaises(SystemExit) as cm:
  457. with self.collector.print_notice_and_exit():
  458. self.collector.add('foo-metric', 1)
  459. self.assertEqual(cm.exception.code, 0)
  460. # We display the notice informing the user of the changes.
  461. self.print_version_change.assert_called_once_with(0)
  462. # We reset the countdown.
  463. self.assert_writes_file(self.config_file, {
  464. 'is-googler': True,
  465. 'countdown': 9,
  466. 'opt-in': None,
  467. 'version': 0
  468. })
  469. # No metrics are uploaded.
  470. self.assertFalse(self.Popen.called)
  471. @mock.patch('metrics.metrics_utils.CURRENT_VERSION', 5)
  472. def test_version_change_from_opted_in(self):
  473. # The user has opted in, and we're collecting metrics.
  474. self.FileRead.side_effect = [
  475. '{"is-googler": true, "countdown": 0, "opt-in": true, "version": 0}'
  476. ]
  477. with self.assertRaises(SystemExit) as cm:
  478. with self.collector.print_notice_and_exit():
  479. self.collector.add('foo-metric', 1)
  480. self.assertEqual(cm.exception.code, 0)
  481. # We display the notice informing the user of the changes.
  482. self.print_version_change.assert_called_once_with(0)
  483. # We reset the countdown.
  484. self.assert_writes_file(self.config_file, {
  485. 'is-googler': True,
  486. 'countdown': 9,
  487. 'opt-in': None,
  488. 'version': 0
  489. })
  490. # No metrics are uploaded.
  491. self.assertFalse(self.Popen.called)
  492. @mock.patch('metrics.metrics_utils.CURRENT_VERSION', 5)
  493. def test_version_change_from_opted_out(self):
  494. # The user has opted out and we're not collecting metrics.
  495. self.FileRead.side_effect = [
  496. '{"is-googler": true, "countdown": 0, "opt-in": false, "version": 0}'
  497. ]
  498. with self.assertRaises(SystemExit) as cm:
  499. with self.collector.print_notice_and_exit():
  500. self.collector.add('foo-metric', 1)
  501. self.assertEqual(cm.exception.code, 0)
  502. # We don't display any notice.
  503. self.assertFalse(self.print_version_change.called)
  504. self.assertFalse(self.print_notice.called)
  505. # We don't upload any metrics.
  506. self.assertFalse(self.Popen.called)
  507. # We don't modify the config.
  508. self.assertFalse(self.FileWrite.called)
  509. @mock.patch('metrics.metrics_utils.CURRENT_VERSION', 5)
  510. def test_version_change_non_googler(self):
  511. # The user is not a googler and we're not collecting metrics.
  512. self.FileRead.side_effect = [
  513. '{"is-googler": false, "countdown": 10, "opt-in": null, "version": 0}'
  514. ]
  515. with self.assertRaises(SystemExit) as cm:
  516. with self.collector.print_notice_and_exit():
  517. self.collector.add('foo-metric', 1)
  518. self.assertEqual(cm.exception.code, 0)
  519. # We don't display any notice.
  520. self.assertFalse(self.print_version_change.called)
  521. self.assertFalse(self.print_notice.called)
  522. # We don't upload any metrics.
  523. self.assertFalse(self.Popen.called)
  524. # We don't modify the config.
  525. self.assertFalse(self.FileWrite.called)
  526. @mock.patch('metrics.metrics_utils.CURRENT_VERSION', 5)
  527. def test_opting_in_updates_version(self):
  528. # The user is seeing the notice telling him of the version changes.
  529. self.FileRead.side_effect = [
  530. '{"is-googler": true, "countdown": 8, "opt-in": null, "version": 0}'
  531. ]
  532. self.collector.config.opted_in = True
  533. # We don't display any notice.
  534. self.assertFalse(self.print_version_change.called)
  535. self.assertFalse(self.print_notice.called)
  536. # We don't upload any metrics.
  537. self.assertFalse(self.Popen.called)
  538. # We update the version and opt-in the user.
  539. self.assert_writes_file(self.config_file, {
  540. 'is-googler': True,
  541. 'countdown': 8,
  542. 'opt-in': True,
  543. 'version': 5
  544. })
  545. @mock.patch('metrics.metrics_utils.CURRENT_VERSION', 5)
  546. def test_opting_in_by_default_updates_version(self):
  547. # The user will be opted in by default on the next execution.
  548. self.FileRead.side_effect = [
  549. '{"is-googler": true, "countdown": 1, "opt-in": null, "version": 0}'
  550. ]
  551. with self.assertRaises(SystemExit) as cm:
  552. with self.collector.print_notice_and_exit():
  553. self.collector.add('foo-metric', 1)
  554. self.assertEqual(cm.exception.code, 0)
  555. # We display the notices.
  556. self.print_notice.assert_called_once_with(1)
  557. self.print_version_change.assert_called_once_with(0)
  558. # We don't upload any metrics.
  559. self.assertFalse(self.Popen.called)
  560. # We update the version and set the countdown to 0. In subsequent runs,
  561. # we'll start collecting metrics.
  562. self.assert_writes_file(self.config_file, {
  563. 'is-googler': True,
  564. 'countdown': 0,
  565. 'opt-in': None,
  566. 'version': 5
  567. })
  568. def test_add_repeated(self):
  569. """Tests that we can add repeated metrics."""
  570. self.FileRead.side_effect = [
  571. '{"is-googler": true, "countdown": 0, "opt-in": true}'
  572. ]
  573. @self.collector.collect_metrics('fun')
  574. def fun():
  575. self.collector.add_repeated('fun', 1)
  576. self.collector.add_repeated('fun', 2)
  577. self.collector.add_repeated('fun', 5)
  578. fun()
  579. # Assert that we collected all metrics for fun.
  580. self.assert_collects_metrics({'fun': [1, 2, 5]})
  581. class MetricsUtilsTest(unittest.TestCase):
  582. def test_extracts_host(self):
  583. """Test that we extract the host from the requested URI."""
  584. # Regular case
  585. http_metrics = metrics_utils.extract_http_metrics(
  586. 'https://chromium-review.googlesource.com/foo/bar?q=baz', '', 0, 0)
  587. self.assertEqual('chromium-review.googlesource.com',
  588. http_metrics['host'])
  589. # Unexpected host
  590. http_metrics = metrics_utils.extract_http_metrics(
  591. 'https://foo-review.googlesource.com/', '', 0, 0)
  592. self.assertNotIn('host', http_metrics)
  593. def test_extracts_path(self):
  594. """Test that we extract the matching path from the requested URI."""
  595. # Regular case
  596. http_metrics = metrics_utils.extract_http_metrics(
  597. 'https://review.example.com/changes/1234/revisions/deadbeef/commit',
  598. '', 0, 0)
  599. self.assertEqual('changes/revisions/commit', http_metrics['path'])
  600. # No matching paths
  601. http_metrics = metrics_utils.extract_http_metrics(
  602. 'https://review.example.com/changes/1234/unexpected/path', '', 0, 0)
  603. self.assertNotIn('path', http_metrics)
  604. def test_extracts_path_changes(self):
  605. """Tests that we extract paths for /changes/."""
  606. # /changes/<change-id>
  607. http_metrics = metrics_utils.extract_http_metrics(
  608. 'https://review.example.com/changes/proj%2Fsrc%7Emain%7EI1234abcd',
  609. '', 0, 0)
  610. self.assertEqual('changes', http_metrics['path'])
  611. # /changes/?q=<something>
  612. http_metrics = metrics_utils.extract_http_metrics(
  613. 'https://review.example.com/changes/?q=owner:me+OR+cc:me', '', 0, 0)
  614. self.assertEqual('changes', http_metrics['path'])
  615. # /changes/#<something>
  616. http_metrics = metrics_utils.extract_http_metrics(
  617. 'https://review.example.com/changes/#something', '', 0, 0)
  618. self.assertEqual('changes', http_metrics['path'])
  619. # /changes/<change-id>/<anything> does not map to changes.
  620. http_metrics = metrics_utils.extract_http_metrics(
  621. 'https://review.example.com/changes/12345678/message', '', 0, 0)
  622. self.assertNotEqual('changes', http_metrics['path'])
  623. def test_extracts_arguments(self):
  624. """Test that we can extract arguments from the requested URI."""
  625. # Regular case
  626. http_metrics = metrics_utils.extract_http_metrics(
  627. 'https://review.example.com/?q=123&foo=bar&o=ALL_REVISIONS', '', 0,
  628. 0)
  629. self.assertEqual(['ALL_REVISIONS'], http_metrics['arguments'])
  630. # Some unexpected arguments are filtered out.
  631. http_metrics = metrics_utils.extract_http_metrics(
  632. 'https://review.example.com/?o=ALL_REVISIONS&o=LABELS&o=UNEXPECTED',
  633. '', 0, 0)
  634. self.assertEqual(['ALL_REVISIONS', 'LABELS'], http_metrics['arguments'])
  635. # No valid arguments, so arguments is not present
  636. http_metrics = metrics_utils.extract_http_metrics(
  637. 'https://review.example.com/?o=bar&baz=1', '', 0, 0)
  638. self.assertNotIn('arguments', http_metrics)
  639. # No valid arguments, so arguments is not present
  640. http_metrics = metrics_utils.extract_http_metrics(
  641. 'https://review.example.com/?foo=bar&baz=1', '', 0, 0)
  642. self.assertNotIn('arguments', http_metrics)
  643. def test_validates_method(self):
  644. """Test that we validate the HTTP method used."""
  645. # Regular case
  646. http_metrics = metrics_utils.extract_http_metrics('', 'POST', 0, 0)
  647. self.assertEqual('POST', http_metrics['method'])
  648. # Unexpected method is not reported
  649. http_metrics = metrics_utils.extract_http_metrics('', 'DEMAND', 0, 0)
  650. self.assertNotIn('method', http_metrics)
  651. def test_status(self):
  652. """Tests that the response status we passed is returned."""
  653. http_metrics = metrics_utils.extract_http_metrics('', '', 123, 0)
  654. self.assertEqual(123, http_metrics['status'])
  655. http_metrics = metrics_utils.extract_http_metrics('', '', 404, 0)
  656. self.assertEqual(404, http_metrics['status'])
  657. def test_response_time(self):
  658. """Tests that the response time we passed is returned."""
  659. http_metrics = metrics_utils.extract_http_metrics('', '', 0, 0.25)
  660. self.assertEqual(0.25, http_metrics['response_time'])
  661. http_metrics = metrics_utils.extract_http_metrics('', '', 0, 12345.25)
  662. self.assertEqual(12345.25, http_metrics['response_time'])
  663. @mock.patch('metrics_utils.subprocess2.Popen')
  664. def test_get_git_version(self, mockPopen):
  665. """Tests that we can get the git version."""
  666. mockProcess = mock.Mock()
  667. mockProcess.communicate.side_effect = [(b'git version 2.18.0.123.foo',
  668. '')]
  669. mockPopen.side_effect = [mockProcess]
  670. self.assertEqual('2.18.0', metrics_utils.get_git_version())
  671. @mock.patch('metrics_utils.subprocess2.Popen')
  672. def test_get_git_version_unrecognized(self, mockPopen):
  673. """Tests that we can get the git version."""
  674. mockProcess = mock.Mock()
  675. mockProcess.communicate.side_effect = [(b'Blah blah blah', 'blah blah')]
  676. mockPopen.side_effect = [mockProcess]
  677. self.assertIsNone(metrics_utils.get_git_version())
  678. def test_extract_known_subcommand_args(self):
  679. """Tests that we can extract known subcommand args."""
  680. result = metrics_utils.extract_known_subcommand_args([
  681. 'm=Fix issue with ccs', 'cc=foo@example.com', 'cc=bar@example.com'
  682. ])
  683. self.assertEqual(['cc', 'cc', 'm'], result)
  684. result = metrics_utils.extract_known_subcommand_args([
  685. 'm=Some title mentioning cc and hashtag', 'notify=NONE', 'private'
  686. ])
  687. self.assertEqual(['m', 'notify=NONE', 'private'], result)
  688. result = metrics_utils.extract_known_subcommand_args(
  689. ['foo=bar', 'another_unkwnon_arg'])
  690. self.assertEqual([], result)
  691. if __name__ == '__main__':
  692. unittest.main()