metrics_test.py 27 KB

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