1#!/usr/bin/env python
2# Copyright 2013 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
6import glob
7import json
8import os
9import subprocess
10import sys
11import unittest
12
13import PRESUBMIT
14
15
16class MockInputApi(object):
17  def __init__(self):
18    self.json = json
19    self.os_path = os.path
20    self.subprocess = subprocess
21    self.python_executable = sys.executable
22
23  def PresubmitLocalPath(self):
24    return os.path.dirname(__file__)
25
26  def ReadFile(self, filename, mode='rU'):
27    with open(filename, mode=mode) as f:
28      return f.read()
29
30
31class JSONParsingTest(unittest.TestCase):
32  def testSuccess(self):
33    input_api = MockInputApi()
34    filename = 'test_presubmit/valid_json.json'
35    self.assertEqual(None,
36                     PRESUBMIT._GetJSONParseError(input_api, filename))
37
38  def testFailure(self):
39    input_api = MockInputApi()
40    expected_errors = [
41      'Expecting property name: line 8 column 3 (char 9)',
42      'Invalid control character at: line 8 column 19 (char 25)',
43      'Expecting property name: line 8 column 23 (char 29)',
44      'Expecting , delimiter: line 8 column 12 (char 18)',
45    ]
46    actual_errors = [
47      str(PRESUBMIT._GetJSONParseError(input_api, filename))
48      for filename in sorted(glob.glob('test_presubmit/invalid_*.json'))
49    ]
50    self.assertEqual(expected_errors, actual_errors)
51
52
53class IDLParsingTest(unittest.TestCase):
54  def testSuccess(self):
55    input_api = MockInputApi()
56    filename = 'test_presubmit/valid_idl_basics.idl'
57    self.assertEqual(None,
58                     PRESUBMIT._GetIDLParseError(input_api, filename))
59
60  def testFailure(self):
61    input_api = MockInputApi()
62    expected_errors = [
63      'Unexpected "{" after keyword "dictionary".',
64      'Unexpected symbol DOMString after symbol a.',
65      'Unexpected symbol name2 after symbol name1.',
66      'Trailing comma in block.',
67      'Unexpected ";" after "(".',
68      'Unexpected ")" after symbol long.',
69      'Unexpected symbol Events after symbol interace.',
70      'Did not process Interface Interface(NotEvent)',
71      'Interface missing name.',
72    ]
73    actual_errors = [
74      PRESUBMIT._GetIDLParseError(input_api, filename)
75      for filename in sorted(glob.glob('test_presubmit/invalid_*.idl'))
76    ]
77    for (expected_error, actual_error) in zip(expected_errors, actual_errors):
78      self.assertTrue(expected_error in actual_error)
79
80
81if __name__ == "__main__":
82  unittest.main()
83