js_checker_eslint_test.py 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. #!/usr/bin/env python3
  2. # Copyright 2017 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. from . import js_checker
  6. import json
  7. import os
  8. import sys
  9. import unittest
  10. import tempfile
  11. _HERE_PATH = os.path.dirname(__file__)
  12. sys.path.append(os.path.join(_HERE_PATH, '..', '..'))
  13. from PRESUBMIT_test_mocks import MockInputApi, MockOutputApi, MockFile
  14. class JsCheckerEsLintTest(unittest.TestCase):
  15. def setUp(self):
  16. self._tmp_files = []
  17. def tearDown(self):
  18. for file in self._tmp_files:
  19. os.remove(file)
  20. def _runChecks(self, file_contents, file_type):
  21. tmp_args = {'suffix': '.' + file_type, 'dir': _HERE_PATH, 'delete': False}
  22. with tempfile.NamedTemporaryFile(**tmp_args) as f:
  23. tmp_file = f.name
  24. self._tmp_files.append(tmp_file)
  25. f.write(file_contents.encode('utf-8'))
  26. input_api = MockInputApi()
  27. input_api.files = [MockFile(os.path.abspath(tmp_file), '')]
  28. input_api.presubmit_local_path = _HERE_PATH
  29. checker = js_checker.JSChecker(input_api, MockOutputApi())
  30. output = checker.RunEsLintChecks(input_api.AffectedFiles(),
  31. format='json')[0]
  32. # Extract ESLint's error from the PresubmitError. This is added in
  33. # third_party/node/node.py.
  34. search_token = '\' failed\n'
  35. json_start_index = output.message.index(search_token)
  36. json_error_str = output.message[json_start_index + len(search_token):]
  37. # ESLint's errors are in JSON format.
  38. return json.loads(json_error_str)[0].get('messages')
  39. def _assertError(self, results, rule_id, line):
  40. self.assertEqual(1, len(results))
  41. message = results[0]
  42. self.assertEqual(rule_id, message.get('ruleId'))
  43. self.assertEqual(line, message.get('line'))
  44. def testPrimitiveWrappersCheck(self):
  45. results = self._runChecks('const a = new Number(1);', 'js')
  46. self._assertError(results, 'no-new-wrappers', 1)
  47. results = self._runChecks(
  48. '''
  49. // eslint-disable-next-line @typescript-eslint/no-unused-vars
  50. const a: number = new Number(1);
  51. ''', 'ts')
  52. self._assertError(results, 'no-new-wrappers', 3)
  53. def testTypeScriptEslintPluginCheck(self):
  54. results = self._runChecks('const a: number = 1;', 'ts')
  55. self._assertError(results, '@typescript-eslint/no-unused-vars', 1)
  56. if __name__ == '__main__':
  57. unittest.main()