blob: 0e7ae32f392534dfdfe5a96977848385a7000f0c [file] [log] [blame]
#!/usr/bin/env python3
# Copyright 2012 The Chromium Authors
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import io
import os.path
import subprocess
import textwrap
import unittest
import PRESUBMIT
from PRESUBMIT_test_mocks import MockFile, MockAffectedFile
from PRESUBMIT_test_mocks import MockInputApi, MockOutputApi
_TEST_DATA_DIR = 'base/test/data/presubmit'
class VersionControlConflictsTest(unittest.TestCase):
def testTypicalConflict(self):
lines = [
'<<<<<<< HEAD', ' base::ScopedTempDir temp_dir_;', '=======',
' ScopedTempDir temp_dir_;', '>>>>>>> master'
]
errors = PRESUBMIT._CheckForVersionControlConflictsInFile(
MockInputApi(), MockFile('some/path/foo_platform.cc', lines))
self.assertEqual(3, len(errors))
self.assertTrue('1' in errors[0])
self.assertTrue('3' in errors[1])
self.assertTrue('5' in errors[2])
def testIgnoresReadmes(self):
lines = [
'A First Level Header', '====================', '',
'A Second Level Header', '---------------------'
]
errors = PRESUBMIT._CheckForVersionControlConflictsInFile(
MockInputApi(), MockFile('some/polymer/README.md', lines))
self.assertEqual(0, len(errors))
class BadExtensionsTest(unittest.TestCase):
def testBadRejFile(self):
mock_input_api = MockInputApi()
mock_input_api.files = [
MockFile('some/path/foo.cc', ''),
MockFile('some/path/foo.cc.rej', ''),
MockFile('some/path2/bar.h.rej', ''),
]
results = PRESUBMIT.CheckPatchFiles(mock_input_api, MockOutputApi())
self.assertEqual(1, len(results))
self.assertEqual(2, len(results[0].items))
self.assertTrue('foo.cc.rej' in results[0].items[0])
self.assertTrue('bar.h.rej' in results[0].items[1])
def testBadOrigFile(self):
mock_input_api = MockInputApi()
mock_input_api.files = [
MockFile('other/path/qux.h.orig', ''),
MockFile('other/path/qux.h', ''),
MockFile('other/path/qux.cc', ''),
]
results = PRESUBMIT.CheckPatchFiles(mock_input_api, MockOutputApi())
self.assertEqual(1, len(results))
self.assertEqual(1, len(results[0].items))
self.assertTrue('qux.h.orig' in results[0].items[0])
def testGoodFiles(self):
mock_input_api = MockInputApi()
mock_input_api.files = [
MockFile('other/path/qux.h', ''),
MockFile('other/path/qux.cc', ''),
]
results = PRESUBMIT.CheckPatchFiles(mock_input_api, MockOutputApi())
self.assertEqual(0, len(results))
class CheckForSuperfluousStlIncludesInHeadersTest(unittest.TestCase):
def testGoodFiles(self):
mock_input_api = MockInputApi()
mock_input_api.files = [
# The check is not smart enough to figure out which definitions correspond
# to which header.
MockFile('other/path/foo.h', ['#include <string>', 'std::vector']),
# The check is not smart enough to do IWYU.
MockFile('other/path/bar.h',
['#include "base/check.h"', 'std::vector']),
MockFile('other/path/qux.h',
['#include "base/stl_util.h"', 'foobar']),
MockFile('other/path/baz.h',
['#include "set/vector.h"', 'bazzab']),
# The check is only for header files.
MockFile('other/path/not_checked.cc',
['#include <vector>', 'bazbaz']),
]
results = PRESUBMIT.CheckForSuperfluousStlIncludesInHeaders(
mock_input_api, MockOutputApi())
self.assertEqual(0, len(results))
def testBadFiles(self):
mock_input_api = MockInputApi()
mock_input_api.files = [
MockFile('other/path/foo.h', ['#include <vector>', 'vector']),
MockFile(
'other/path/bar.h',
['#include <limits>', '#include <set>', 'no_std_namespace']),
]
results = PRESUBMIT.CheckForSuperfluousStlIncludesInHeaders(
mock_input_api, MockOutputApi())
self.assertEqual(1, len(results))
self.assertTrue('foo.h: Includes STL' in results[0].message)
self.assertTrue('bar.h: Includes STL' in results[0].message)
class CheckSingletonInHeadersTest(unittest.TestCase):
def testSingletonInArbitraryHeader(self):
diff_singleton_h = [
'base::subtle::AtomicWord '
'base::Singleton<Type, Traits, DifferentiatingType>::'
]
diff_foo_h = [
'// base::Singleton<Foo> in comment.',
'friend class base::Singleton<Foo>'
]
diff_foo2_h = [' //Foo* bar = base::Singleton<Foo>::get();']
diff_bad_h = ['Foo* foo = base::Singleton<Foo>::get();']
mock_input_api = MockInputApi()
mock_input_api.files = [
MockAffectedFile('base/memory/singleton.h', diff_singleton_h),
MockAffectedFile('foo.h', diff_foo_h),
MockAffectedFile('foo2.h', diff_foo2_h),
MockAffectedFile('bad.h', diff_bad_h)
]
warnings = PRESUBMIT.CheckSingletonInHeaders(mock_input_api,
MockOutputApi())
self.assertEqual(1, len(warnings))
self.assertEqual(1, len(warnings[0].items))
self.assertEqual('error', warnings[0].type)
self.assertTrue('Found base::Singleton<T>' in warnings[0].message)
def testSingletonInCC(self):
diff_cc = ['Foo* foo = base::Singleton<Foo>::get();']
mock_input_api = MockInputApi()
mock_input_api.files = [MockAffectedFile('some/path/foo.cc', diff_cc)]
warnings = PRESUBMIT.CheckSingletonInHeaders(mock_input_api,
MockOutputApi())
self.assertEqual(0, len(warnings))
class DeprecatedOSMacroNamesTest(unittest.TestCase):
def testDeprecatedOSMacroNames(self):
lines = [
'#if defined(OS_WIN)', ' #elif defined(OS_WINDOW)',
' # if defined(OS_MAC) || defined(OS_CHROME)'
]
errors = PRESUBMIT._CheckForDeprecatedOSMacrosInFile(
MockInputApi(), MockFile('some/path/foo_platform.cc', lines))
self.assertEqual(len(lines) + 1, len(errors))
self.assertTrue(
':1: defined(OS_WIN) -> BUILDFLAG(IS_WIN)' in errors[0])
class InvalidIfDefinedMacroNamesTest(unittest.TestCase):
def testInvalidIfDefinedMacroNames(self):
lines = [
'#if defined(TARGET_IPHONE_SIMULATOR)',
'#if !defined(TARGET_IPHONE_SIMULATOR)',
'#elif defined(TARGET_IPHONE_SIMULATOR)',
'#ifdef TARGET_IPHONE_SIMULATOR',
' # ifdef TARGET_IPHONE_SIMULATOR',
'# if defined(VALID) || defined(TARGET_IPHONE_SIMULATOR)',
'# else // defined(TARGET_IPHONE_SIMULATOR)',
'#endif // defined(TARGET_IPHONE_SIMULATOR)'
]
errors = PRESUBMIT._CheckForInvalidIfDefinedMacrosInFile(
MockInputApi(), MockFile('some/path/source.mm', lines))
self.assertEqual(len(lines), len(errors))
def testValidIfDefinedMacroNames(self):
lines = [
'#if defined(FOO)', '#ifdef BAR', '#if TARGET_IPHONE_SIMULATOR'
]
errors = PRESUBMIT._CheckForInvalidIfDefinedMacrosInFile(
MockInputApi(), MockFile('some/path/source.cc', lines))
self.assertEqual(0, len(errors))
class CheckNoUNIT_TESTInSourceFilesTest(unittest.TestCase):
def testUnitTestMacros(self):
lines = [
'#if defined(UNIT_TEST)', '#if defined UNIT_TEST',
'#if !defined(UNIT_TEST)', '#elif defined(UNIT_TEST)',
'#ifdef UNIT_TEST', ' # ifdef UNIT_TEST', '#ifndef UNIT_TEST',
'# if defined(VALID) || defined(UNIT_TEST)',
'# if defined(UNIT_TEST) && defined(VALID)',
'# else // defined(UNIT_TEST)', '#endif // defined(UNIT_TEST)'
]
errors = PRESUBMIT._CheckNoUNIT_TESTInSourceFiles(
MockInputApi(), MockFile('some/path/source.cc', lines))
self.assertEqual(len(lines), len(errors))
def testNotUnitTestMacros(self):
lines = [
'// Comment about "#if defined(UNIT_TEST)"',
'/* Comment about #if defined(UNIT_TEST)" */',
'#ifndef UNIT_TEST_H', '#define UNIT_TEST_H',
'#ifndef TEST_UNIT_TEST', '#define TEST_UNIT_TEST',
'#if defined(_UNIT_TEST)', '#if defined(UNIT_TEST_)',
'#ifdef _UNIT_TEST', '#ifdef UNIT_TEST_', '#ifndef _UNIT_TEST',
'#ifndef UNIT_TEST_'
]
errors = PRESUBMIT._CheckNoUNIT_TESTInSourceFiles(
MockInputApi(), MockFile('some/path/source.cc', lines))
self.assertEqual(0, len(errors))
class CheckEachPerfettoTestDataFileHasDepsEntry(unittest.TestCase):
def testNewSha256FileNoDEPS(self):
input_api = MockInputApi()
input_api.files = [
MockFile('base/tracing/test/data_sha256/new.pftrace.sha256', []),
]
results = PRESUBMIT.CheckEachPerfettoTestDataFileHasDepsEntry(
input_api, MockOutputApi())
self.assertEqual(
('You must update the DEPS file when you update a .sha256 file '
'in base/tracing/test/data_sha256'), results[0].message)
def testNewSha256FileSuccess(self):
input_api = MockInputApi()
new_deps = """deps = {
'src/base/tracing/test/data': {
'bucket': 'perfetto',
'objects': [
{
'object_name': 'test_data/new.pftrace-a1b2c3f4',
'sha256sum': 'a1b2c3f4',
'size_bytes': 1,
'generation': 1,
'output_file': 'new.pftrace'
},
],
'dep_type': 'gcs'
},
}""".splitlines()
input_api.files = [
MockFile('base/tracing/test/data_sha256/new.pftrace.sha256',
['a1b2c3f4']),
MockFile('DEPS', new_deps,
["deps={'src/base/tracing/test/data':{}}"]),
]
results = PRESUBMIT.CheckEachPerfettoTestDataFileHasDepsEntry(
input_api, MockOutputApi())
self.assertEqual(0, len(results))
def testNewSha256FileWrongSha256(self):
input_api = MockInputApi()
new_deps = """deps = {
'src/base/tracing/test/data': {
'bucket': 'perfetto',
'objects': [
{
'object_name': 'test_data/new.pftrace-a1b2c3f4',
'sha256sum': 'wrong_hash',
'size_bytes': 1,
'generation': 1,
'output_file': 'new.pftrace'
},
],
'dep_type': 'gcs'
},
}""".splitlines()
f = MockFile('base/tracing/test/data_sha256/new.pftrace.sha256',
['a1b2c3f4'])
input_api.files = [
f,
MockFile('DEPS', new_deps,
["deps={'src/base/tracing/test/data':{}}"]),
]
results = PRESUBMIT.CheckEachPerfettoTestDataFileHasDepsEntry(
input_api, MockOutputApi())
self.assertEqual(
('No corresponding DEPS entry found for %s. '
'Run `base/tracing/test/test_data.py get_deps --filepath %s` '
'to generate the DEPS entry.' % (f.LocalPath(), f.LocalPath())),
results[0].message)
def testDeleteSha256File(self):
input_api = MockInputApi()
old_deps = """deps = {
'src/base/tracing/test/data': {
'bucket': 'perfetto',
'objects': [
{
'object_name': 'test_data/new.pftrace-a1b2c3f4',
'sha256sum': 'a1b2c3f4',
'size_bytes': 1,
'generation': 1,
'output_file': 'new.pftrace'
},
],
'dep_type': 'gcs'
},
}""".splitlines()
f = MockFile('base/tracing/test/data_sha256/new.pftrace.sha256', [],
['a1b2c3f4'],
action='D')
input_api.files = [
f,
MockFile('DEPS', old_deps, old_deps),
]
results = PRESUBMIT.CheckEachPerfettoTestDataFileHasDepsEntry(
input_api, MockOutputApi())
self.assertEqual((
'You deleted %s so you must also remove the corresponding DEPS entry.'
% f.LocalPath()), results[0].message)
def testDeleteSha256Success(self):
input_api = MockInputApi()
new_deps = """deps = {
'src/base/tracing/test/data': {
'bucket': 'perfetto',
'objects': [],
'dep_type': 'gcs'
},
}""".splitlines()
old_deps = """deps = {
'src/base/tracing/test/data': {
'bucket': 'perfetto',
'objects': [
{
'object_name': 'test_data/new.pftrace-a1b2c3f4',
'sha256sum': 'a1b2c3f4',
'size_bytes': 1,
'generation': 1,
'output_file': 'new.pftrace'
},
],
'dep_type': 'gcs'
},
}""".splitlines()
f = MockFile('base/tracing/test/data_sha256/new.pftrace.sha256', [],
['a1b2c3f4'],
action='D')
input_api.files = [
f,
MockFile('DEPS', new_deps, old_deps),
]
results = PRESUBMIT.CheckEachPerfettoTestDataFileHasDepsEntry(
input_api, MockOutputApi())
self.assertEqual(0, len(results))
class CheckAddedDepsHaveTestApprovalsTest(unittest.TestCase):
def calculate(self, old_include_rules, old_specific_include_rules,
new_include_rules, new_specific_include_rules):
return PRESUBMIT._CalculateAddedDeps(
os.path, 'include_rules = %r\nspecific_include_rules = %r' %
(old_include_rules, old_specific_include_rules),
'include_rules = %r\nspecific_include_rules = %r' %
(new_include_rules, new_specific_include_rules))
def testCalculateAddedDeps(self):
old_include_rules = [
'+base',
'-chrome',
'+content',
'-grit',
'-grit/",',
'+jni/fooblat.h',
'!sandbox',
]
old_specific_include_rules = {
'compositor\.*': {
'+cc',
},
}
new_include_rules = [
'-ash',
'+base',
'+chrome',
'+components',
'+content',
'+grit',
'+grit/generated_resources.h",',
'+grit/",',
'+jni/fooblat.h',
'+policy',
'+' + os.path.join('third_party', 'WebKit'),
]
new_specific_include_rules = {
'compositor\.*': {
'+cc',
},
'widget\.*': {
'+gpu',
},
}
expected = set([
os.path.join('chrome', 'DEPS'),
os.path.join('gpu', 'DEPS'),
os.path.join('components', 'DEPS'),
os.path.join('policy', 'DEPS'),
os.path.join('third_party', 'WebKit', 'DEPS'),
])
self.assertEqual(
expected,
self.calculate(old_include_rules, old_specific_include_rules,
new_include_rules, new_specific_include_rules))
def testCalculateAddedDepsIgnoresPermutations(self):
old_include_rules = [
'+base',
'+chrome',
]
new_include_rules = [
'+chrome',
'+base',
]
self.assertEqual(
set(), self.calculate(old_include_rules, {}, new_include_rules,
{}))
class FakeOwnersClient(object):
APPROVED = "APPROVED"
PENDING = "PENDING"
returns = {}
def ListOwners(self, *args, **kwargs):
return self.returns.get(self.ListOwners.__name__, "")
def mockListOwners(self, owners):
self.returns[self.ListOwners.__name__] = owners
def GetFilesApprovalStatus(self, *args, **kwargs):
return self.returns.get(self.GetFilesApprovalStatus.__name__, {})
def mockGetFilesApprovalStatus(self, status):
self.returns[self.GetFilesApprovalStatus.__name__] = status
def SuggestOwners(self, *args, **kwargs):
return ["eng1", "eng2", "eng3"]
class fakeGerrit(object):
def IsOwnersOverrideApproved(self, issue):
return False
def setUp(self):
self.input_api = input_api = MockInputApi()
input_api.environ = {}
input_api.owners_client = self.FakeOwnersClient()
input_api.gerrit = self.fakeGerrit()
input_api.change.issue = 123
self.mockOwnersAndReviewers("owner", set(["reviewer"]))
self.mockListSubmodules([])
def mockOwnersAndReviewers(self, owner, reviewers):
def mock(*args, **kwargs):
return [owner, reviewers]
self.input_api.canned_checks.GetCodereviewOwnerAndReviewers = mock
def mockListSubmodules(self, paths):
def mock(*args, **kwargs):
return paths
self.input_api.ListSubmodules = mock
def testApprovedAdditionalDep(self):
old_deps = """include_rules = []""".splitlines()
new_deps = """include_rules = ["+v8/123"]""".splitlines()
self.input_api.files = [
MockAffectedFile("pdf/DEPS", new_deps, old_deps)
]
# mark the additional dep as approved.
os_path = self.input_api.os_path
self.input_api.owners_client.mockGetFilesApprovalStatus(
{os_path.join('v8/123', 'DEPS'): self.FakeOwnersClient.APPROVED})
results = PRESUBMIT.CheckAddedDepsHaveTargetApprovals(
self.input_api, MockOutputApi())
# Then, the check should pass.
self.assertEqual([], results)
def testUnapprovedAdditionalDep(self):
old_deps = """include_rules = []""".splitlines()
new_deps = """include_rules = ["+v8/123"]""".splitlines()
self.input_api.files = [
MockAffectedFile('pdf/DEPS', new_deps, old_deps),
]
# pending.
os_path = self.input_api.os_path
self.input_api.owners_client.mockGetFilesApprovalStatus(
{os_path.join('v8/123', 'DEPS'): self.FakeOwnersClient.PENDING})
results = PRESUBMIT.CheckAddedDepsHaveTargetApprovals(
self.input_api, MockOutputApi())
# the check should fail
self.assertIn('You need LGTM', results[0].message)
self.assertIn('+v8/123', results[0].message)
# unless the added dep is from a submodule.
self.mockListSubmodules(['v8'])
results = PRESUBMIT.CheckAddedDepsHaveTargetApprovals(
self.input_api, MockOutputApi())
self.assertEqual([], results)
class JSONParsingTest(unittest.TestCase):
def testSuccess(self):
input_api = MockInputApi()
filename = 'valid_json.json'
contents = [
'// This is a comment.', '{', ' "key1": ["value1", "value2"],',
' "key2": 3 // This is an inline comment.', '}'
]
input_api.files = [MockFile(filename, contents)]
self.assertEqual(None,
PRESUBMIT._GetJSONParseError(input_api, filename))
def testFailure(self):
input_api = MockInputApi()
test_data = [
('invalid_json_1.json', ['{ x }'], 'Expecting property name'),
('invalid_json_2.json', ['// Hello world!', '{ "hello": "world }'],
'Unterminated string starting at:'),
('invalid_json_3.json', ['{ "a": "b", "c": "d", }'],
'Expecting property name'),
('invalid_json_4.json', ['{ "a": "b" "c": "d" }'],
"Expecting ',' delimiter:"),
]
input_api.files = [
MockFile(filename, contents)
for (filename, contents, _) in test_data
]
for (filename, _, expected_error) in test_data:
actual_error = PRESUBMIT._GetJSONParseError(input_api, filename)
self.assertTrue(
expected_error in str(actual_error),
"'%s' not found in '%s'" % (expected_error, actual_error))
def testNoEatComments(self):
input_api = MockInputApi()
file_with_comments = 'file_with_comments.json'
contents_with_comments = [
'// This is a comment.', '{', ' "key1": ["value1", "value2"],',
' "key2": 3 // This is an inline comment.', '}'
]
file_without_comments = 'file_without_comments.json'
contents_without_comments = [
'{', ' "key1": ["value1", "value2"],', ' "key2": 3', '}'
]
input_api.files = [
MockFile(file_with_comments, contents_with_comments),
MockFile(file_without_comments, contents_without_comments)
]
self.assertNotEqual(
None,
str(
PRESUBMIT._GetJSONParseError(input_api,
file_with_comments,
eat_comments=False)))
self.assertEqual(
None,
PRESUBMIT._GetJSONParseError(input_api,
file_without_comments,
eat_comments=False))
class IDLParsingTest(unittest.TestCase):
def testSuccess(self):
input_api = MockInputApi()
filename = 'valid_idl_basics.idl'
contents = [
'// Tests a valid IDL file.', 'namespace idl_basics {',
' enum EnumType {', ' name1,', ' name2', ' };', '',
' dictionary MyType1 {', ' DOMString a;', ' };', '',
' callback Callback1 = void();',
' callback Callback2 = void(long x);',
' callback Callback3 = void(MyType1 arg);',
' callback Callback4 = void(EnumType type);', '',
' interface Functions {', ' static void function1();',
' static void function2(long x);',
' static void function3(MyType1 arg);',
' static void function4(Callback1 cb);',
' static void function5(Callback2 cb);',
' static void function6(Callback3 cb);',
' static void function7(Callback4 cb);', ' };', '',
' interface Events {', ' static void onFoo1();',
' static void onFoo2(long x);',
' static void onFoo2(MyType1 arg);',
' static void onFoo3(EnumType type);', ' };', '};'
]
input_api.files = [MockFile(filename, contents)]
self.assertEqual(None,
PRESUBMIT._GetIDLParseError(input_api, filename))
def testFailure(self):
input_api = MockInputApi()
test_data = [
('invalid_idl_1.idl', [
'//', 'namespace test {', ' dictionary {', ' DOMString s;',
' };', '};'
], 'Unexpected "{" after keyword "dictionary".\n'),
# TODO(yoz): Disabled because it causes the IDL parser to hang.
# See crbug.com/363830.
# ('invalid_idl_2.idl',
# (['namespace test {',
# ' dictionary MissingSemicolon {',
# ' DOMString a',
# ' DOMString b;',
# ' };',
# '};'],
# 'Unexpected symbol DOMString after symbol a.'),
('invalid_idl_3.idl', [
'//', 'namespace test {', ' enum MissingComma {', ' name1',
' name2', ' };', '};'
], 'Unexpected symbol name2 after symbol name1.'),
('invalid_idl_4.idl', [
'//', 'namespace test {', ' enum TrailingComma {',
' name1,', ' name2,', ' };', '};'
], 'Trailing comma in block.'),
('invalid_idl_5.idl',
['//', 'namespace test {', ' callback Callback1 = void(;',
'};'], 'Unexpected ";" after "(".'),
('invalid_idl_6.idl', [
'//', 'namespace test {',
' callback Callback1 = void(long );', '};'
], 'Unexpected ")" after symbol long.'),
('invalid_idl_7.idl', [
'//', 'namespace test {', ' interace Events {',
' static void onFoo1();', ' };', '};'
], 'Unexpected symbol Events after symbol interace.'),
('invalid_idl_8.idl', [
'//', 'namespace test {', ' interface NotEvent {',
' static void onFoo1();', ' };', '};'
], 'Did not process Interface Interface(NotEvent)'),
('invalid_idl_9.idl', [
'//', 'namespace test {', ' interface {',
' static void function1();', ' };', '};'
], 'Interface missing name.'),
]
input_api.files = [
MockFile(filename, contents)
for (filename, contents, _) in test_data
]
for (filename, _, expected_error) in test_data:
actual_error = PRESUBMIT._GetIDLParseError(input_api, filename)
self.assertTrue(
expected_error in str(actual_error),
"'%s' not found in '%s'" % (expected_error, actual_error))
class UserMetricsActionTest(unittest.TestCase):
def testUserMetricsActionInActions(self):
input_api = MockInputApi()
file_with_user_action = 'file_with_user_action.cc'
contents_with_user_action = ['base::UserMetricsAction("AboutChrome")']
input_api.files = [
MockFile(file_with_user_action, contents_with_user_action)
]
self.assertEqual([],
PRESUBMIT.CheckUserActionUpdate(
input_api, MockOutputApi()))
def testUserMetricsActionNotAddedToActions(self):
input_api = MockInputApi()
file_with_user_action = 'file_with_user_action.cc'
contents_with_user_action = [
'base::UserMetricsAction("NotInActionsXml")'
]
input_api.files = [
MockFile(file_with_user_action, contents_with_user_action)
]
output = PRESUBMIT.CheckUserActionUpdate(input_api, MockOutputApi())
self.assertEqual(
('File %s line %d: %s is missing in '
'tools/metrics/actions/actions.xml. Please run '
'tools/metrics/actions/extract_actions.py to update.' %
(file_with_user_action, 1, 'NotInActionsXml')), output[0].message)
def testUserMetricsActionInTestFile(self):
input_api = MockInputApi()
file_with_user_action = 'file_with_user_action_unittest.cc'
contents_with_user_action = [
'base::UserMetricsAction("NotInActionsXml")'
]
input_api.files = [
MockFile(file_with_user_action, contents_with_user_action)
]
self.assertEqual([],
PRESUBMIT.CheckUserActionUpdate(
input_api, MockOutputApi()))
class PydepsNeedsUpdatingTest(unittest.TestCase):
class MockPopen:
def __init__(self, stdout):
self.stdout = io.StringIO(stdout)
def wait(self):
return 0
class MockSubprocess:
CalledProcessError = subprocess.CalledProcessError
PIPE = 0
def __init__(self):
self._popen_func = None
def SetPopenCallback(self, func):
self._popen_func = func
def Popen(self, cmd, *args, **kwargs):
return PydepsNeedsUpdatingTest.MockPopen(self._popen_func(cmd))
def _MockParseGclientArgs(self, is_android=True):
return lambda: {'checkout_android': 'true' if is_android else 'false'}
def setUp(self):
mock_all_pydeps = ['A.pydeps', 'B.pydeps', 'D.pydeps']
self.old_ALL_PYDEPS_FILES = PRESUBMIT._ALL_PYDEPS_FILES
PRESUBMIT._ALL_PYDEPS_FILES = mock_all_pydeps
mock_android_pydeps = ['D.pydeps']
self.old_ANDROID_SPECIFIC_PYDEPS_FILES = (
PRESUBMIT._ANDROID_SPECIFIC_PYDEPS_FILES)
PRESUBMIT._ANDROID_SPECIFIC_PYDEPS_FILES = mock_android_pydeps
self.old_ParseGclientArgs = PRESUBMIT._ParseGclientArgs
PRESUBMIT._ParseGclientArgs = self._MockParseGclientArgs()
self.mock_input_api = MockInputApi()
self.mock_output_api = MockOutputApi()
self.mock_input_api.subprocess = PydepsNeedsUpdatingTest.MockSubprocess(
)
self.checker = PRESUBMIT.PydepsChecker(self.mock_input_api,
mock_all_pydeps)
self.checker._file_cache = {
'A.pydeps':
'# Generated by:\n# CMD --output A.pydeps A\nA.py\nC.py\n',
'B.pydeps':
'# Generated by:\n# CMD --output B.pydeps B\nB.py\nC.py\n',
'D.pydeps': '# Generated by:\n# CMD --output D.pydeps D\nD.py\n',
}
def tearDown(self):
PRESUBMIT._ALL_PYDEPS_FILES = self.old_ALL_PYDEPS_FILES
PRESUBMIT._ANDROID_SPECIFIC_PYDEPS_FILES = (
self.old_ANDROID_SPECIFIC_PYDEPS_FILES)
PRESUBMIT._ParseGclientArgs = self.old_ParseGclientArgs
def _RunCheck(self):
return PRESUBMIT.CheckPydepsNeedsUpdating(
self.mock_input_api,
self.mock_output_api,
checker_for_tests=self.checker)
def testAddedPydep(self):
# PRESUBMIT.CheckPydepsNeedsUpdating is only implemented for Linux.
if not self.mock_input_api.platform.startswith('linux'):
return []
self.mock_input_api.files = [
MockAffectedFile('new.pydeps', [], action='A'),
]
self.mock_input_api.CreateMockFileInPath([
x.LocalPath()
for x in self.mock_input_api.AffectedFiles(include_deletes=True)
])
results = self._RunCheck()
self.assertEqual(1, len(results))
self.assertIn('PYDEPS_FILES', str(results[0]))
def testPydepNotInSrc(self):
self.mock_input_api.files = [
MockAffectedFile('new.pydeps', [], action='A'),
]
self.mock_input_api.CreateMockFileInPath([])
results = self._RunCheck()
self.assertEqual(0, len(results))
def testRemovedPydep(self):
# PRESUBMIT.CheckPydepsNeedsUpdating is only implemented for Linux.
if not self.mock_input_api.platform.startswith('linux'):
return []
self.mock_input_api.files = [
MockAffectedFile(PRESUBMIT._ALL_PYDEPS_FILES[0], [], action='D'),
]
self.mock_input_api.CreateMockFileInPath([
x.LocalPath()
for x in self.mock_input_api.AffectedFiles(include_deletes=True)
])
results = self._RunCheck()
self.assertEqual(1, len(results))
self.assertIn('PYDEPS_FILES', str(results[0]))
def testRandomPyIgnored(self):
# PRESUBMIT.CheckPydepsNeedsUpdating is only implemented for Linux.
if not self.mock_input_api.platform.startswith('linux'):
return []
self.mock_input_api.files = [
MockAffectedFile('random.py', []),
]
results = self._RunCheck()
self.assertEqual(0, len(results), 'Unexpected results: %r' % results)
def testRelevantPyNoChange(self):
# PRESUBMIT.CheckPydepsNeedsUpdating is only implemented for Linux.
if not self.mock_input_api.platform.startswith('linux'):
return []
self.mock_input_api.files = [
MockAffectedFile('A.py', []),
]
def popen_callback(cmd):
self.assertEqual('CMD --output A.pydeps A --output ""', cmd)
return self.checker._file_cache['A.pydeps']
self.mock_input_api.subprocess.SetPopenCallback(popen_callback)
results = self._RunCheck()
self.assertEqual(0, len(results), 'Unexpected results: %r' % results)
def testRelevantPyOneChange(self):
# PRESUBMIT.CheckPydepsNeedsUpdating is only implemented for Linux.
if not self.mock_input_api.platform.startswith('linux'):
return []
self.mock_input_api.files = [
MockAffectedFile('A.py', []),
]
def popen_callback(cmd):
self.assertEqual('CMD --output A.pydeps A --output ""', cmd)
return 'changed data'
self.mock_input_api.subprocess.SetPopenCallback(popen_callback)
results = self._RunCheck()
self.assertEqual(1, len(results))
# Check that --output "" is not included.
self.assertNotIn('""', str(results[0]))
self.assertIn('File is stale', str(results[0]))
def testRelevantPyTwoChanges(self):
# PRESUBMIT.CheckPydepsNeedsUpdating is only implemented for Linux.
if not self.mock_input_api.platform.startswith('linux'):
return []
self.mock_input_api.files = [
MockAffectedFile('C.py', []),
]
def popen_callback(cmd):
return 'changed data'
self.mock_input_api.subprocess.SetPopenCallback(popen_callback)
results = self._RunCheck()
self.assertEqual(2, len(results))
self.assertIn('File is stale', str(results[0]))
self.assertIn('File is stale', str(results[1]))
def testRelevantAndroidPyInNonAndroidCheckout(self):
# PRESUBMIT.CheckPydepsNeedsUpdating is only implemented for Linux.
if not self.mock_input_api.platform.startswith('linux'):
return []
self.mock_input_api.files = [
MockAffectedFile('D.py', []),
]
def popen_callback(cmd):
self.assertEqual('CMD --output D.pydeps D --output ""', cmd)
return 'changed data'
self.mock_input_api.subprocess.SetPopenCallback(popen_callback)
PRESUBMIT._ParseGclientArgs = self._MockParseGclientArgs(
is_android=False)
results = self._RunCheck()
self.assertEqual(1, len(results))
self.assertIn('Android', str(results[0]))
self.assertIn('D.pydeps', str(results[0]))
def testGnPathsAndMissingOutputFlag(self):
# PRESUBMIT.CheckPydepsNeedsUpdating is only implemented for Linux.
if not self.mock_input_api.platform.startswith('linux'):
return []
self.checker._file_cache = {
'A.pydeps':
'# Generated by:\n# CMD --gn-paths A\n//A.py\n//C.py\n',
'B.pydeps':
'# Generated by:\n# CMD --gn-paths B\n//B.py\n//C.py\n',
'D.pydeps': '# Generated by:\n# CMD --gn-paths D\n//D.py\n',
}
self.mock_input_api.files = [
MockAffectedFile('A.py', []),
]
def popen_callback(cmd):
self.assertEqual('CMD --gn-paths A --output A.pydeps --output ""',
cmd)
return 'changed data'
self.mock_input_api.subprocess.SetPopenCallback(popen_callback)
results = self._RunCheck()
self.assertEqual(1, len(results))
self.assertIn('File is stale', str(results[0]))
class IncludeGuardTest(unittest.TestCase):
def testIncludeGuardChecks(self):
mock_input_api = MockInputApi()
mock_output_api = MockOutputApi()
mock_input_api.files = [
MockAffectedFile('content/browser/thing/foo.h', [
'// Comment',
'#ifndef CONTENT_BROWSER_THING_FOO_H_',
'#define CONTENT_BROWSER_THING_FOO_H_',
'struct McBoatFace;',
'#endif // CONTENT_BROWSER_THING_FOO_H_',
]),
MockAffectedFile('content/browser/thing/bar.h', [
'#ifndef CONTENT_BROWSER_THING_BAR_H_',
'#define CONTENT_BROWSER_THING_BAR_H_',
'namespace content {',
'#endif // CONTENT_BROWSER_THING_BAR_H_',
'} // namespace content',
]),
MockAffectedFile('content/browser/test1.h', [
'namespace content {',
'} // namespace content',
]),
MockAffectedFile('content\\browser\\win.h', [
'#ifndef CONTENT_BROWSER_WIN_H_',
'#define CONTENT_BROWSER_WIN_H_',
'struct McBoatFace;',
'#endif // CONTENT_BROWSER_WIN_H_',
]),
MockAffectedFile('content/browser/test2.h', [
'// Comment',
'#ifndef CONTENT_BROWSER_TEST2_H_',
'struct McBoatFace;',
'#endif // CONTENT_BROWSER_TEST2_H_',
]),
MockAffectedFile('content/browser/internal.h', [
'// Comment',
'#ifndef CONTENT_BROWSER_INTERNAL_H_',
'#define CONTENT_BROWSER_INTERNAL_H_',
'// Comment',
'#ifndef INTERNAL_CONTENT_BROWSER_INTERNAL_H_',
'#define INTERNAL_CONTENT_BROWSER_INTERNAL_H_',
'namespace internal {',
'} // namespace internal',
'#endif // INTERNAL_CONTENT_BROWSER_THING_BAR_H_',
'namespace content {',
'} // namespace content',
'#endif // CONTENT_BROWSER_THING_BAR_H_',
]),
MockAffectedFile('content/browser/thing/foo.cc', [
'// This is a non-header.',
]),
MockAffectedFile('content/browser/disabled.h', [
'// no-include-guard-because-multiply-included',
'struct McBoatFace;',
]),
# New files don't allow misspelled include guards.
MockAffectedFile('content/browser/spleling.h', [
'#ifndef CONTENT_BROWSER_SPLLEING_H_',
'#define CONTENT_BROWSER_SPLLEING_H_',
'struct McBoatFace;',
'#endif // CONTENT_BROWSER_SPLLEING_H_',
]),
# New files don't allow + in include guards.
MockAffectedFile('content/browser/foo+bar.h', [
'#ifndef CONTENT_BROWSER_FOO+BAR_H_',
'#define CONTENT_BROWSER_FOO+BAR_H_',
'struct McBoatFace;',
'#endif // CONTENT_BROWSER_FOO+BAR_H_',
]),
# Old files allow misspelled include guards (for now).
MockAffectedFile('chrome/old.h', [
'// New contents',
'#ifndef CHROME_ODL_H_',
'#define CHROME_ODL_H_',
'#endif // CHROME_ODL_H_',
], [
'// Old contents',
'#ifndef CHROME_ODL_H_',
'#define CHROME_ODL_H_',
'#endif // CHROME_ODL_H_',
],
action='M'),
# Using a Blink style include guard outside Blink is wrong.
MockAffectedFile('content/NotInBlink.h', [
'#ifndef NotInBlink_h',
'#define NotInBlink_h',
'struct McBoatFace;',
'#endif // NotInBlink_h',
]),
# Using a Blink style include guard in Blink is no longer ok.
MockAffectedFile('third_party/blink/InBlink.h', [
'#ifndef InBlink_h',
'#define InBlink_h',
'struct McBoatFace;',
'#endif // InBlink_h',
]),
# Using a bad include guard in Blink is not ok.
MockAffectedFile('third_party/blink/AlsoInBlink.h', [
'#ifndef WrongInBlink_h',
'#define WrongInBlink_h',
'struct McBoatFace;',
'#endif // WrongInBlink_h',
]),
# Using a bad include guard in Blink is not supposed to be accepted even
# if it's an old file. However the current presubmit has accepted this
# for a while.
MockAffectedFile('third_party/blink/StillInBlink.h', [
'// New contents',
'#ifndef AcceptedInBlink_h',
'#define AcceptedInBlink_h',
'struct McBoatFace;',
'#endif // AcceptedInBlink_h',
], [
'// Old contents',
'#ifndef AcceptedInBlink_h',
'#define AcceptedInBlink_h',
'struct McBoatFace;',
'#endif // AcceptedInBlink_h',
],
action='M'),
# Using a non-Chromium include guard in third_party
# (outside blink) is accepted.
MockAffectedFile('third_party/foo/some_file.h', [
'#ifndef REQUIRED_RPCNDR_H_',
'#define REQUIRED_RPCNDR_H_',
'struct SomeFileFoo;',
'#endif // REQUIRED_RPCNDR_H_',
]),
# Not having proper include guard in *_message_generator.h
# for old IPC messages is allowed.
MockAffectedFile('content/common/content_message_generator.h', [
'#undef CONTENT_COMMON_FOO_MESSAGES_H_',
'#include "content/common/foo_messages.h"',
'#ifndef CONTENT_COMMON_FOO_MESSAGES_H_',
'#error "Failed to include content/common/foo_messages.h"',
'#endif',
]),
MockAffectedFile('chrome/renderer/thing/qux.h', [
'// Comment',
'#ifndef CHROME_RENDERER_THING_QUX_H_',
'#define CHROME_RENDERER_THING_QUX_H_',
'struct Boaty;',
'#endif',
]),
]
msgs = PRESUBMIT.CheckForIncludeGuards(mock_input_api, mock_output_api)
expected_fail_count = 10
self.assertEqual(
expected_fail_count, len(msgs), 'Expected %d items, found %d: %s' %
(expected_fail_count, len(msgs), msgs))
self.assertEqual(msgs[0].items, ['content/browser/thing/bar.h'])
self.assertEqual(
msgs[0].message, 'Include guard CONTENT_BROWSER_THING_BAR_H_ '
'not covering the whole file')
self.assertIn('content/browser/test1.h', msgs[1].message)
self.assertIn('Recommended name: CONTENT_BROWSER_TEST1_H_',
msgs[1].message)
self.assertEqual(msgs[2].items, ['content/browser/test2.h:3'])
self.assertEqual(
msgs[2].message, 'Missing "#define CONTENT_BROWSER_TEST2_H_" for '
'include guard')
self.assertIn('content/browser/internal.h', msgs[3].message)
self.assertIn(
'Recommended #endif comment: // CONTENT_BROWSER_INTERNAL_H_',
msgs[3].message)
self.assertEqual(msgs[4].items, ['content/browser/spleling.h:1'])
self.assertEqual(
msgs[4].message, 'Header using the wrong include guard name '
'CONTENT_BROWSER_SPLLEING_H_')
self.assertIn('content/browser/foo+bar.h', msgs[5].message)
self.assertIn('Recommended name: CONTENT_BROWSER_FOO_BAR_H_',
msgs[5].message)
self.assertEqual(msgs[6].items, ['content/NotInBlink.h:1'])
self.assertEqual(
msgs[6].message, 'Header using the wrong include guard name '
'NotInBlink_h')
self.assertEqual(msgs[7].items, ['third_party/blink/InBlink.h:1'])
self.assertEqual(
msgs[7].message, 'Header using the wrong include guard name '
'InBlink_h')
self.assertEqual(msgs[8].items, ['third_party/blink/AlsoInBlink.h:1'])
self.assertEqual(
msgs[8].message, 'Header using the wrong include guard name '
'WrongInBlink_h')
self.assertIn('chrome/renderer/thing/qux.h', msgs[9].message)
self.assertIn(
'Recommended #endif comment: // CHROME_RENDERER_THING_QUX_H_',
msgs[9].message)
class AccessibilityRelnotesFieldTest(unittest.TestCase):
def testRelnotesPresent(self):
mock_input_api = MockInputApi()
mock_output_api = MockOutputApi()
mock_input_api.files = [
MockAffectedFile('ui/accessibility/foo.bar', [''])
]
mock_input_api.change.DescriptionText = lambda: 'Commit description'
mock_input_api.change.footers['AX-Relnotes'] = [
'Important user facing change'
]
msgs = PRESUBMIT.CheckAccessibilityRelnotesField(
mock_input_api, mock_output_api)
self.assertEqual(
0, len(msgs),
'Expected %d messages, found %d: %s' % (0, len(msgs), msgs))
def testRelnotesMissingFromAccessibilityChange(self):
mock_input_api = MockInputApi()
mock_output_api = MockOutputApi()
mock_input_api.files = [
MockAffectedFile('some/file', ['']),
MockAffectedFile('ui/accessibility/foo.bar', ['']),
MockAffectedFile('some/other/file', [''])
]
mock_input_api.change.DescriptionText = lambda: 'Commit description'
msgs = PRESUBMIT.CheckAccessibilityRelnotesField(
mock_input_api, mock_output_api)
self.assertEqual(
1, len(msgs),
'Expected %d messages, found %d: %s' % (1, len(msgs), msgs))
self.assertTrue(
"Missing 'AX-Relnotes:' field" in msgs[0].message,
'Missing AX-Relnotes field message not found in errors')
# The relnotes footer is not required for changes which do not touch any
# accessibility directories.
def testIgnoresNonAccessibilityCode(self):
mock_input_api = MockInputApi()
mock_output_api = MockOutputApi()
mock_input_api.files = [
MockAffectedFile('some/file', ['']),
MockAffectedFile('some/other/file', [''])
]
mock_input_api.change.DescriptionText = lambda: 'Commit description'
msgs = PRESUBMIT.CheckAccessibilityRelnotesField(
mock_input_api, mock_output_api)
self.assertEqual(
0, len(msgs),
'Expected %d messages, found %d: %s' % (0, len(msgs), msgs))
# Test that our presubmit correctly raises an error for a set of known paths.
def testExpectedPaths(self):
filesToTest = [
"chrome/browser/accessibility/foo.py",
"chrome/browser/ash/arc/accessibility/foo.cc",
"chrome/browser/ui/views/accessibility/foo.h",
"chrome/browser/extensions/api/automation/foo.h",
"chrome/browser/extensions/api/automation_internal/foo.cc",
"chrome/renderer/extensions/accessibility_foo.h",
"chrome/tests/data/accessibility/foo.html",
"content/browser/accessibility/foo.cc",
"content/renderer/accessibility/foo.h",
"content/tests/data/accessibility/foo.cc",
"extensions/renderer/api/automation/foo.h",
"ui/accessibility/foo/bar/baz.cc",
"ui/views/accessibility/foo/bar/baz.h",
]
for testFile in filesToTest:
mock_input_api = MockInputApi()
mock_output_api = MockOutputApi()
mock_input_api.files = [MockAffectedFile(testFile, [''])]
mock_input_api.change.DescriptionText = lambda: 'Commit description'
msgs = PRESUBMIT.CheckAccessibilityRelnotesField(
mock_input_api, mock_output_api)
self.assertEqual(
1, len(msgs),
'Expected %d messages, found %d: %s, for file %s' %
(1, len(msgs), msgs, testFile))
self.assertTrue(
"Missing 'AX-Relnotes:' field" in msgs[0].message,
('Missing AX-Relnotes field message not found in errors '
' for file %s' % (testFile)))
# Test that AX-Relnotes field can appear in the commit description (as long
# as it appears at the beginning of a line).
def testRelnotesInCommitDescription(self):
mock_input_api = MockInputApi()
mock_output_api = MockOutputApi()
mock_input_api.files = [
MockAffectedFile('ui/accessibility/foo.bar', ['']),
]
mock_input_api.change.DescriptionText = lambda: (
'Description:\n' +
'AX-Relnotes: solves all accessibility issues forever')
msgs = PRESUBMIT.CheckAccessibilityRelnotesField(
mock_input_api, mock_output_api)
self.assertEqual(
0, len(msgs),
'Expected %d messages, found %d: %s' % (0, len(msgs), msgs))
# Test that we don't match AX-Relnotes if it appears in the middle of a line.
def testRelnotesMustAppearAtBeginningOfLine(self):
mock_input_api = MockInputApi()
mock_output_api = MockOutputApi()
mock_input_api.files = [
MockAffectedFile('ui/accessibility/foo.bar', ['']),
]
mock_input_api.change.DescriptionText = lambda: (
'Description:\n' +
'This change has no AX-Relnotes: we should print a warning')
msgs = PRESUBMIT.CheckAccessibilityRelnotesField(
mock_input_api, mock_output_api)
self.assertTrue(
"Missing 'AX-Relnotes:' field" in msgs[0].message,
'Missing AX-Relnotes field message not found in errors')
# Tests that the AX-Relnotes field can be lowercase and use a '=' in place
# of a ':'.
def testRelnotesLowercaseWithEqualSign(self):
mock_input_api = MockInputApi()
mock_output_api = MockOutputApi()
mock_input_api.files = [
MockAffectedFile('ui/accessibility/foo.bar', ['']),
]
mock_input_api.change.DescriptionText = lambda: (
'Description:\n' +
'ax-relnotes= this is a valid format for accessibility relnotes')
msgs = PRESUBMIT.CheckAccessibilityRelnotesField(
mock_input_api, mock_output_api)
self.assertEqual(
0, len(msgs),
'Expected %d messages, found %d: %s' % (0, len(msgs), msgs))
class AccessibilityEventsTestsAreIncludedForAndroidTest(unittest.TestCase):
# Test that no warning is raised when the Android file is also modified.
def testAndroidChangeIncluded(self):
mock_input_api = MockInputApi()
mock_input_api.files = [
MockAffectedFile(
'content/test/data/accessibility/event/foo-expected-mac.txt',
[''],
action='A'),
MockAffectedFile(
'accessibility/WebContentsAccessibilityEventsTest.java', [''],
action='M')
]
msgs = PRESUBMIT.CheckAccessibilityEventsTestsAreIncludedForAndroid(
mock_input_api, MockOutputApi())
self.assertEqual(
0, len(msgs),
'Expected %d messages, found %d: %s' % (0, len(msgs), msgs))
# Test that Android change is not required when no html file is added/removed.
def testIgnoreNonHtmlFiles(self):
mock_input_api = MockInputApi()
mock_input_api.files = [
MockAffectedFile('content/test/data/accessibility/event/foo.txt',
[''],
action='A'),
MockAffectedFile('content/test/data/accessibility/event/foo.cc',
[''],
action='A'),
MockAffectedFile('content/test/data/accessibility/event/foo.h',
[''],
action='A'),
MockAffectedFile('content/test/data/accessibility/event/foo.py',
[''],
action='A')
]
msgs = PRESUBMIT.CheckAccessibilityEventsTestsAreIncludedForAndroid(
mock_input_api, MockOutputApi())
self.assertEqual(
0, len(msgs),
'Expected %d messages, found %d: %s' % (0, len(msgs), msgs))
# Test that Android change is not required for unrelated html files.
def testIgnoreNonRelatedHtmlFiles(self):
mock_input_api = MockInputApi()
mock_input_api.files = [
MockAffectedFile('content/test/data/accessibility/aria/foo.html',
[''],
action='A'),
MockAffectedFile('content/test/data/accessibility/html/foo.html',
[''],
action='A'),
MockAffectedFile('chrome/tests/data/accessibility/foo.html', [''],
action='A')
]
msgs = PRESUBMIT.CheckAccessibilityEventsTestsAreIncludedForAndroid(
mock_input_api, MockOutputApi())
self.assertEqual(
0, len(msgs),
'Expected %d messages, found %d: %s' % (0, len(msgs), msgs))
# Test that only modifying an html file will not trigger the warning.
def testIgnoreModifiedFiles(self):
mock_input_api = MockInputApi()
mock_input_api.files = [
MockAffectedFile(
'content/test/data/accessibility/event/foo-expected-win.txt',
[''],
action='M')
]
msgs = PRESUBMIT.CheckAccessibilityEventsTestsAreIncludedForAndroid(
mock_input_api, MockOutputApi())
self.assertEqual(
0, len(msgs),
'Expected %d messages, found %d: %s' % (0, len(msgs), msgs))
class AccessibilityTreeTestsAreIncludedForAndroidTest(unittest.TestCase):
# Test that no warning is raised when the Android file is also modified.
def testAndroidChangeIncluded(self):
mock_input_api = MockInputApi()
mock_input_api.files = [
MockAffectedFile('content/test/data/accessibility/aria/foo.html',
[''],
action='A'),
MockAffectedFile(
'accessibility/WebContentsAccessibilityTreeTest.java', [''],
action='M')
]
msgs = PRESUBMIT.CheckAccessibilityTreeTestsAreIncludedForAndroid(
mock_input_api, MockOutputApi())
self.assertEqual(
0, len(msgs),
'Expected %d messages, found %d: %s' % (0, len(msgs), msgs))
# Test that no warning is raised when the Android file is also modified.
def testAndroidChangeIncludedManyFiles(self):
mock_input_api = MockInputApi()
mock_input_api.files = [
MockAffectedFile(
'content/test/data/accessibility/accname/foo.html', [''],
action='A'),
MockAffectedFile('content/test/data/accessibility/aria/foo.html',
[''],
action='A'),
MockAffectedFile('content/test/data/accessibility/css/foo.html',
[''],
action='A'),
MockAffectedFile('content/test/data/accessibility/html/foo.html',
[''],
action='A'),
MockAffectedFile(
'accessibility/WebContentsAccessibilityTreeTest.java', [''],
action='M')
]
msgs = PRESUBMIT.CheckAccessibilityTreeTestsAreIncludedForAndroid(
mock_input_api, MockOutputApi())
self.assertEqual(
0, len(msgs),
'Expected %d messages, found %d: %s' % (0, len(msgs), msgs))
# Test that a warning is raised when the Android file is not modified.
def testAndroidChangeMissing(self):
mock_input_api = MockInputApi()
mock_input_api.files = [
MockAffectedFile(
'content/test/data/accessibility/aria/foo-expected-win.txt',
[''],
action='A'),
]
msgs = PRESUBMIT.CheckAccessibilityTreeTestsAreIncludedForAndroid(
mock_input_api, MockOutputApi())
self.assertEqual(
1, len(msgs),
'Expected %d messages, found %d: %s' % (1, len(msgs), msgs))
# Test that Android change is not required when no platform expectations files are changed.
def testAndroidChangNotMissing(self):
mock_input_api = MockInputApi()
mock_input_api.files = [
MockAffectedFile('content/test/data/accessibility/accname/foo.txt',
[''],
action='A'),
MockAffectedFile(
'content/test/data/accessibility/html/foo-expected-blink.txt',
[''],
action='A'),
MockAffectedFile('content/test/data/accessibility/html/foo.html',
[''],
action='A'),
MockAffectedFile('content/test/data/accessibility/aria/foo.cc',
[''],
action='A'),
MockAffectedFile('content/test/data/accessibility/css/foo.h', [''],
action='A'),
MockAffectedFile('content/test/data/accessibility/tree/foo.py',
[''],
action='A')
]
msgs = PRESUBMIT.CheckAccessibilityTreeTestsAreIncludedForAndroid(
mock_input_api, MockOutputApi())
self.assertEqual(
0, len(msgs),
'Expected %d messages, found %d: %s' % (0, len(msgs), msgs))
# Test that Android change is not required for unrelated html files.
def testIgnoreNonRelatedHtmlFiles(self):
mock_input_api = MockInputApi()
mock_input_api.files = [
MockAffectedFile('content/test/data/accessibility/event/foo.html',
[''],
action='A'),
]
msgs = PRESUBMIT.CheckAccessibilityTreeTestsAreIncludedForAndroid(
mock_input_api, MockOutputApi())
self.assertEqual(
0, len(msgs),
'Expected %d messages, found %d: %s' % (0, len(msgs), msgs))
# Test that only modifying an html file will not trigger the warning.
def testIgnoreModifiedFiles(self):
mock_input_api = MockInputApi()
mock_input_api.files = [
MockAffectedFile('content/test/data/accessibility/aria/foo.html',
[''],
action='M')
]
msgs = PRESUBMIT.CheckAccessibilityTreeTestsAreIncludedForAndroid(
mock_input_api, MockOutputApi())
self.assertEqual(
0, len(msgs),
'Expected %d messages, found %d: %s' % (0, len(msgs), msgs))
class AndroidDeprecatedTestAnnotationTest(unittest.TestCase):
def testCheckAndroidTestAnnotationUsage(self):
mock_input_api = MockInputApi()
mock_output_api = MockOutputApi()
mock_input_api.files = [
MockAffectedFile('LalaLand.java', ['random stuff']),
MockAffectedFile('CorrectUsage.java', [
'import androidx.test.filters.LargeTest;',
'import androidx.test.filters.MediumTest;',
'import androidx.test.filters.SmallTest;',
]),
MockAffectedFile('UsedDeprecatedLargeTestAnnotation.java', [
'import android.test.suitebuilder.annotation.LargeTest;',
]),
MockAffectedFile('UsedDeprecatedMediumTestAnnotation.java', [
'import android.test.suitebuilder.annotation.MediumTest;',
]),
MockAffectedFile('UsedDeprecatedSmallTestAnnotation.java', [
'import android.test.suitebuilder.annotation.SmallTest;',
]),
MockAffectedFile('UsedDeprecatedSmokeAnnotation.java', [
'import android.test.suitebuilder.annotation.Smoke;',
])
]
msgs = PRESUBMIT._CheckAndroidTestAnnotationUsage(
mock_input_api, mock_output_api)
self.assertEqual(
1, len(msgs),
'Expected %d items, found %d: %s' % (1, len(msgs), msgs))
self.assertEqual(
4, len(msgs[0].items), 'Expected %d items, found %d: %s' %
(4, len(msgs[0].items), msgs[0].items))
self.assertTrue(
'UsedDeprecatedLargeTestAnnotation.java:1' in msgs[0].items,
'UsedDeprecatedLargeTestAnnotation not found in errors')
self.assertTrue(
'UsedDeprecatedMediumTestAnnotation.java:1' in msgs[0].items,
'UsedDeprecatedMediumTestAnnotation not found in errors')
self.assertTrue(
'UsedDeprecatedSmallTestAnnotation.java:1' in msgs[0].items,
'UsedDeprecatedSmallTestAnnotation not found in errors')
self.assertTrue(
'UsedDeprecatedSmokeAnnotation.java:1' in msgs[0].items,
'UsedDeprecatedSmokeAnnotation not found in errors')
class AndroidBannedImportTest(unittest.TestCase):
def testCheckAndroidNoBannedImports(self):
mock_input_api = MockInputApi()
mock_output_api = MockOutputApi()
test_files = [
MockAffectedFile('RandomStufff.java', ['random stuff']),
MockAffectedFile('NoBannedImports.java', [
'import androidx.test.filters.LargeTest;',
'import androidx.test.filters.MediumTest;',
'import androidx.test.filters.SmallTest;',
]),
MockAffectedFile('BannedUri.java', [
'import java.net.URI;',
]),
MockAffectedFile('BannedTargetApi.java', [
'import android.annotation.TargetApi;',
]),
MockAffectedFile('BannedUiThreadTestRule.java', [
'import androidx.test.rule.UiThreadTestRule;',
]),
MockAffectedFile('BannedUiThreadTest.java', [
'import androidx.test.annotation.UiThreadTest;',
]),
MockAffectedFile('BannedActivityTestRule.java', [
'import androidx.test.rule.ActivityTestRule;',
]),
MockAffectedFile('BannedVectorDrawableCompat.java', [
'import androidx.vectordrawable.graphics.drawable.VectorDrawableCompat;',
])
]
msgs = []
for file in test_files:
mock_input_api.files = [file]
msgs.append(
PRESUBMIT._CheckAndroidNoBannedImports(mock_input_api,
mock_output_api))
self.assertEqual(0, len(msgs[0]))
self.assertEqual(0, len(msgs[1]))
self.assertTrue(msgs[2][0].message.startswith(
textwrap.dedent("""\
Banned imports were used.
BannedUri.java:1:""")))
self.assertTrue(msgs[3][0].message.startswith(
textwrap.dedent("""\
Banned imports were used.
BannedTargetApi.java:1:""")))
self.assertTrue(msgs[4][0].message.startswith(
textwrap.dedent("""\
Banned imports were used.
BannedUiThreadTestRule.java:1:""")))
self.assertTrue(msgs[5][0].message.startswith(
textwrap.dedent("""\
Banned imports were used.
BannedUiThreadTest.java:1:""")))
self.assertTrue(msgs[6][0].message.startswith(
textwrap.dedent("""\
Banned imports were used.
BannedActivityTestRule.java:1:""")))
self.assertTrue(msgs[7][0].message.startswith(
textwrap.dedent("""\
Banned imports were used.
BannedVectorDrawableCompat.java:1:""")))
class CheckNoDownstreamDepsTest(unittest.TestCase):
def testInvalidDepFromUpstream(self):
mock_input_api = MockInputApi()
mock_output_api = MockOutputApi()
mock_input_api.files = [
MockAffectedFile('BUILD.gn',
['deps = [', ' "//clank/target:test",', ']']),
MockAffectedFile('chrome/android/BUILD.gn',
['deps = [ "//clank/target:test" ]']),
MockAffectedFile(
'chrome/chrome_java_deps.gni',
['java_deps = [', ' "//clank/target:test",', ']']),
]
mock_input_api.change.RepositoryRoot = lambda: 'chromium/src'
msgs = PRESUBMIT.CheckNoUpstreamDepsOnClank(mock_input_api,
mock_output_api)
self.assertEqual(
1, len(msgs),
'Expected %d items, found %d: %s' % (1, len(msgs), msgs))
self.assertEqual(
3, len(msgs[0].items), 'Expected %d items, found %d: %s' %
(3, len(msgs[0].items), msgs[0].items))
self.assertTrue(any('BUILD.gn:2' in item for item in msgs[0].items),
'BUILD.gn not found in errors')
self.assertTrue(
any('chrome/android/BUILD.gn:1' in item for item in msgs[0].items),
'chrome/android/BUILD.gn:1 not found in errors')
self.assertTrue(
any('chrome/chrome_java_deps.gni:2' in item
for item in msgs[0].items),
'chrome/chrome_java_deps.gni:2 not found in errors')
def testAllowsComments(self):
mock_input_api = MockInputApi()
mock_output_api = MockOutputApi()
mock_input_api.files = [
MockAffectedFile('BUILD.gn', [
'# real implementation in //clank/target:test',
]),
]
mock_input_api.change.RepositoryRoot = lambda: 'chromium/src'
msgs = PRESUBMIT.CheckNoUpstreamDepsOnClank(mock_input_api,
mock_output_api)
self.assertEqual(
0, len(msgs),
'Expected %d items, found %d: %s' % (0, len(msgs), msgs))
def testOnlyChecksBuildFiles(self):
mock_input_api = MockInputApi()
mock_output_api = MockOutputApi()
mock_input_api.files = [
MockAffectedFile('README.md',
['DEPS = [ "//clank/target:test" ]']),
MockAffectedFile('chrome/android/java/file.java',
['//clank/ only function']),
]
mock_input_api.change.RepositoryRoot = lambda: 'chromium/src'
msgs = PRESUBMIT.CheckNoUpstreamDepsOnClank(mock_input_api,
mock_output_api)
self.assertEqual(
0, len(msgs),
'Expected %d items, found %d: %s' % (0, len(msgs), msgs))
def testValidDepFromDownstream(self):
mock_input_api = MockInputApi()
mock_output_api = MockOutputApi()
mock_input_api.files = [
MockAffectedFile('BUILD.gn',
['DEPS = [', ' "//clank/target:test",', ']']),
MockAffectedFile('java/BUILD.gn',
['DEPS = [ "//clank/target:test" ]']),
]
mock_input_api.change.RepositoryRoot = lambda: 'chromium/src/clank'
msgs = PRESUBMIT.CheckNoUpstreamDepsOnClank(mock_input_api,
mock_output_api)
self.assertEqual(
0, len(msgs),
'Expected %d items, found %d: %s' % (0, len(msgs), msgs))
class AndroidDebuggableBuildTest(unittest.TestCase):
def testCheckAndroidDebuggableBuild(self):
mock_input_api = MockInputApi()
mock_output_api = MockOutputApi()
mock_input_api.files = [
MockAffectedFile('RandomStuff.java', ['random stuff']),
MockAffectedFile('CorrectUsage.java', [
'import org.chromium.base.BuildInfo;',
'some random stuff',
'boolean isOsDebuggable = BuildInfo.isDebugAndroid();',
]),
MockAffectedFile('JustCheckUserdebugBuild.java', [
'import android.os.Build;',
'some random stuff',
'boolean isOsDebuggable = Build.TYPE.equals("userdebug")',
]),
MockAffectedFile('JustCheckEngineeringBuild.java', [
'import android.os.Build;',
'some random stuff',
'boolean isOsDebuggable = "eng".equals(Build.TYPE)',
]),
MockAffectedFile('UsedBuildType.java', [
'import android.os.Build;',
'some random stuff',
'boolean isOsDebuggable = Build.TYPE.equals("userdebug")'
'|| "eng".equals(Build.TYPE)',
]),
MockAffectedFile('UsedExplicitBuildType.java', [
'some random stuff',
'boolean isOsDebuggable = android.os.Build.TYPE.equals("userdebug")'
'|| "eng".equals(android.os.Build.TYPE)',
]),
]
msgs = PRESUBMIT._CheckAndroidDebuggableBuild(mock_input_api,
mock_output_api)
self.assertEqual(
1, len(msgs),
'Expected %d items, found %d: %s' % (1, len(msgs), msgs))
self.assertEqual(
4, len(msgs[0].items), 'Expected %d items, found %d: %s' %
(4, len(msgs[0].items), msgs[0].items))
self.assertTrue('JustCheckUserdebugBuild.java:3' in msgs[0].items)
self.assertTrue('JustCheckEngineeringBuild.java:3' in msgs[0].items)
self.assertTrue('UsedBuildType.java:3' in msgs[0].items)
self.assertTrue('UsedExplicitBuildType.java:2' in msgs[0].items)
class LogUsageTest(unittest.TestCase):
def testCheckAndroidCrLogUsage(self):
mock_input_api = MockInputApi()
mock_output_api = MockOutputApi()
mock_input_api.files = [
MockAffectedFile('RandomStuff.java', ['random stuff']),
MockAffectedFile('HasAndroidLog.java', [
'import android.util.Log;',
'some random stuff',
'Log.d("TAG", "foo");',
]),
MockAffectedFile('HasExplicitUtilLog.java', [
'some random stuff',
'android.util.Log.d("TAG", "foo");',
]),
MockAffectedFile('IsInBasePackage.java', [
'package org.chromium.base;',
'private static final String TAG = "cr_Foo";',
'Log.d(TAG, "foo");',
]),
MockAffectedFile('IsInBasePackageButImportsLog.java', [
'package org.chromium.base;',
'import android.util.Log;',
'private static final String TAG = "cr_Foo";',
'Log.d(TAG, "foo");',
]),
MockAffectedFile('HasBothLog.java', [
'import org.chromium.base.Log;',
'some random stuff',
'private static final String TAG = "cr_Foo";',
'Log.d(TAG, "foo");',
'android.util.Log.d("TAG", "foo");',
]),
MockAffectedFile('HasCorrectTag.java', [
'import org.chromium.base.Log;',
'some random stuff',
'private static final String TAG = "cr_Foo";',
'Log.d(TAG, "foo");',
]),
MockAffectedFile('HasOldTag.java', [
'import org.chromium.base.Log;',
'some random stuff',
'private static final String TAG = "cr.Foo";',
'Log.d(TAG, "foo");',
]),
MockAffectedFile('HasDottedTag.java', [
'import org.chromium.base.Log;',
'some random stuff',
'private static final String TAG = "cr_foo.bar";',
'Log.d(TAG, "foo");',
]),
MockAffectedFile('HasDottedTagPublic.java', [
'import org.chromium.base.Log;',
'some random stuff',
'public static final String TAG = "cr_foo.bar";',
'Log.d(TAG, "foo");',
]),
MockAffectedFile('HasNoTagDecl.java', [
'import org.chromium.base.Log;',
'some random stuff',
'Log.d(TAG, "foo");',
]),
MockAffectedFile('HasIncorrectTagDecl.java', [
'import org.chromium.base.Log;',
'private static final String TAHG = "cr_Foo";',
'some random stuff',
'Log.d(TAG, "foo");',
]),
MockAffectedFile('HasInlineTag.java', [
'import org.chromium.base.Log;',
'some random stuff',
'private static final String TAG = "cr_Foo";',
'Log.d("TAG", "foo");',
]),
MockAffectedFile('HasInlineTagWithSpace.java', [
'import org.chromium.base.Log;',
'some random stuff',
'private static final String TAG = "cr_Foo";',
'Log.d("log message", "foo");',
]),
MockAffectedFile('HasUnprefixedTag.java', [
'import org.chromium.base.Log;',
'some random stuff',
'private static final String TAG = "rubbish";',
'Log.d(TAG, "foo");',
]),
MockAffectedFile('HasTooLongTag.java', [
'import org.chromium.base.Log;',
'some random stuff',
'private static final String TAG = "21_characters_long___";',
'Log.d(TAG, "foo");',
]),
MockAffectedFile('HasTooLongTagWithNoLogCallsInDiff.java', [
'import org.chromium.base.Log;',
'some random stuff',
'private static final String TAG = "21_characters_long___";',
]),
]
msgs = PRESUBMIT._CheckAndroidCrLogUsage(mock_input_api,
mock_output_api)
self.assertEqual(
5, len(msgs),
'Expected %d items, found %d: %s' % (5, len(msgs), msgs))
# Declaration format
nb = len(msgs[0].items)
self.assertEqual(
2, nb, 'Expected %d items, found %d: %s' % (2, nb, msgs[0].items))
self.assertTrue('HasNoTagDecl.java' in msgs[0].items)
self.assertTrue('HasIncorrectTagDecl.java' in msgs[0].items)
# Tag length
nb = len(msgs[1].items)
self.assertEqual(
2, nb, 'Expected %d items, found %d: %s' % (2, nb, msgs[1].items))
self.assertTrue('HasTooLongTag.java' in msgs[1].items)
self.assertTrue(
'HasTooLongTagWithNoLogCallsInDiff.java' in msgs[1].items)
# Tag must be a variable named TAG
nb = len(msgs[2].items)
self.assertEqual(
3, nb, 'Expected %d items, found %d: %s' % (3, nb, msgs[2].items))
self.assertTrue('HasBothLog.java:5' in msgs[2].items)
self.assertTrue('HasInlineTag.java:4' in msgs[2].items)
self.assertTrue('HasInlineTagWithSpace.java:4' in msgs[2].items)
# Util Log usage
nb = len(msgs[3].items)
self.assertEqual(
3, nb, 'Expected %d items, found %d: %s' % (3, nb, msgs[3].items))
self.assertTrue('HasAndroidLog.java:3' in msgs[3].items)
self.assertTrue('HasExplicitUtilLog.java:2' in msgs[3].items)
self.assertTrue('IsInBasePackageButImportsLog.java:4' in msgs[3].items)
# Tag must not contain
nb = len(msgs[4].items)
self.assertEqual(
3, nb, 'Expected %d items, found %d: %s' % (2, nb, msgs[4].items))
self.assertTrue('HasDottedTag.java' in msgs[4].items)
self.assertTrue('HasDottedTagPublic.java' in msgs[4].items)
self.assertTrue('HasOldTag.java' in msgs[4].items)
class GoogleAnswerUrlFormatTest(unittest.TestCase):
def testCatchAnswerUrlId(self):
input_api = MockInputApi()
input_api.files = [
MockFile('somewhere/file.cc', [
'char* host = '
' "https://support.google.com/chrome/answer/123456";'
]),
MockFile('somewhere_else/file.cc', [
'char* host = '
' "https://support.google.com/chrome/a/answer/123456";'
]),
]
warnings = PRESUBMIT.CheckGoogleSupportAnswerUrlOnUpload(
input_api, MockOutputApi())
self.assertEqual(1, len(warnings))
self.assertEqual(2, len(warnings[0].items))
def testAllowAnswerUrlParam(self):
input_api = MockInputApi()
input_api.files = [
MockFile('somewhere/file.cc', [
'char* host = '
' "https://support.google.com/chrome/?p=cpn_crash_reports";'
]),
]
warnings = PRESUBMIT.CheckGoogleSupportAnswerUrlOnUpload(
input_api, MockOutputApi())
self.assertEqual(0, len(warnings))
class HardcodedGoogleHostsTest(unittest.TestCase):
def testWarnOnAssignedLiterals(self):
input_api = MockInputApi()
input_api.files = [
MockFile('content/file.cc',
['char* host = "https://www.google.com";']),
MockFile('content/file.cc',
['char* host = "https://www.googleapis.com";']),
MockFile('content/file.cc',
['char* host = "https://clients1.google.com";']),
]
warnings = PRESUBMIT.CheckHardcodedGoogleHostsInLowerLayers(
input_api, MockOutputApi())
self.assertEqual(1, len(warnings))
self.assertEqual(3, len(warnings[0].items))
def testAllowInComment(self):
input_api = MockInputApi()
input_api.files = [
MockFile('content/file.cc',
['char* host = "https://www.aol.com"; // google.com'])
]
warnings = PRESUBMIT.CheckHardcodedGoogleHostsInLowerLayers(
input_api, MockOutputApi())
self.assertEqual(0, len(warnings))
class ChromeOsSyncedPrefRegistrationTest(unittest.TestCase):
def testWarnsOnChromeOsDirectories(self):
files = [
MockFile('ash/file.cc', ['PrefRegistrySyncable::SYNCABLE_PREF']),
MockFile('chrome/browser/chromeos/file.cc',
['PrefRegistrySyncable::SYNCABLE_PREF']),
MockFile('chromeos/file.cc',
['PrefRegistrySyncable::SYNCABLE_PREF']),
MockFile('components/arc/file.cc',
['PrefRegistrySyncable::SYNCABLE_PREF']),
MockFile('components/exo/file.cc',
['PrefRegistrySyncable::SYNCABLE_PREF']),
]
input_api = MockInputApi()
for file in files:
input_api.files = [file]
warnings = PRESUBMIT.CheckChromeOsSyncedPrefRegistration(
input_api, MockOutputApi())
self.assertEqual(1, len(warnings))
def testDoesNotWarnOnSyncOsPref(self):
input_api = MockInputApi()
input_api.files = [
MockFile('chromeos/file.cc',
['PrefRegistrySyncable::SYNCABLE_OS_PREF']),
]
warnings = PRESUBMIT.CheckChromeOsSyncedPrefRegistration(
input_api, MockOutputApi())
self.assertEqual(0, len(warnings))
def testDoesNotWarnOnOtherDirectories(self):
input_api = MockInputApi()
input_api.files = [
MockFile('chrome/browser/ui/file.cc',
['PrefRegistrySyncable::SYNCABLE_PREF']),
MockFile('components/sync/file.cc',
['PrefRegistrySyncable::SYNCABLE_PREF']),
MockFile('content/browser/file.cc',
['PrefRegistrySyncable::SYNCABLE_PREF']),
MockFile('a/notchromeos/file.cc',
['PrefRegistrySyncable::SYNCABLE_PREF']),
]
warnings = PRESUBMIT.CheckChromeOsSyncedPrefRegistration(
input_api, MockOutputApi())
self.assertEqual(0, len(warnings))
def testSeparateWarningForPriorityPrefs(self):
input_api = MockInputApi()
input_api.files = [
MockFile('chromeos/file.cc', [
'PrefRegistrySyncable::SYNCABLE_PREF',
'PrefRegistrySyncable::SYNCABLE_PRIORITY_PREF'
]),
]
warnings = PRESUBMIT.CheckChromeOsSyncedPrefRegistration(
input_api, MockOutputApi())
self.assertEqual(2, len(warnings))
class ForwardDeclarationTest(unittest.TestCase):
def testCheckHeadersOnlyOutsideThirdParty(self):
mock_input_api = MockInputApi()
mock_input_api.files = [
MockAffectedFile('somewhere/file.cc', ['class DummyClass;']),
MockAffectedFile('third_party/header.h', ['class DummyClass;'])
]
warnings = PRESUBMIT.CheckUselessForwardDeclarations(
mock_input_api, MockOutputApi())
self.assertEqual(0, len(warnings))
def testNoNestedDeclaration(self):
mock_input_api = MockInputApi()
mock_input_api.files = [
MockAffectedFile('somewhere/header.h', [
'class SomeClass {', ' protected:', ' class NotAMatch;', '};'
])
]
warnings = PRESUBMIT.CheckUselessForwardDeclarations(
mock_input_api, MockOutputApi())
self.assertEqual(0, len(warnings))
def testSubStrings(self):
mock_input_api = MockInputApi()
mock_input_api.files = [
MockAffectedFile('somewhere/header.h', [
'class NotUsefulClass;', 'struct SomeStruct;',
'UsefulClass *p1;', 'SomeStructPtr *p2;'
])
]
warnings = PRESUBMIT.CheckUselessForwardDeclarations(
mock_input_api, MockOutputApi())
self.assertEqual(2, len(warnings))
def testUselessForwardDeclaration(self):
mock_input_api = MockInputApi()
mock_input_api.files = [
MockAffectedFile('somewhere/header.h', [
'class DummyClass;', 'struct DummyStruct;',
'class UsefulClass;', 'std::unique_ptr<UsefulClass> p;'
])
]
warnings = PRESUBMIT.CheckUselessForwardDeclarations(
mock_input_api, MockOutputApi())
self.assertEqual(2, len(warnings))
def testBlinkHeaders(self):
mock_input_api = MockInputApi()
mock_input_api.files = [
MockAffectedFile('third_party/blink/header.h', [
'class DummyClass;',
'struct DummyStruct;',
]),
MockAffectedFile('third_party\\blink\\header.h', [
'class DummyClass;',
'struct DummyStruct;',
])
]
warnings = PRESUBMIT.CheckUselessForwardDeclarations(
mock_input_api, MockOutputApi())
self.assertEqual(4, len(warnings))
class RelativeIncludesTest(unittest.TestCase):
def testThirdPartyNotWebKitIgnored(self):
mock_input_api = MockInputApi()
mock_input_api.files = [
MockAffectedFile('third_party/test.cpp', '#include "../header.h"'),
MockAffectedFile('third_party/test/test.cpp',
'#include "../header.h"'),
]
mock_output_api = MockOutputApi()
errors = PRESUBMIT.CheckForRelativeIncludes(mock_input_api,
mock_output_api)
self.assertEqual(0, len(errors))
def testNonCppFileIgnored(self):
mock_input_api = MockInputApi()
mock_input_api.files = [
MockAffectedFile('test.py', '#include "../header.h"'),
]
mock_output_api = MockOutputApi()
errors = PRESUBMIT.CheckForRelativeIncludes(mock_input_api,
mock_output_api)
self.assertEqual(0, len(errors))
def testInnocuousChangesAllowed(self):
mock_input_api = MockInputApi()
mock_input_api.files = [
MockAffectedFile('test.cpp', '#include "header.h"'),
MockAffectedFile('test2.cpp', '../'),
]
mock_output_api = MockOutputApi()
errors = PRESUBMIT.CheckForRelativeIncludes(mock_input_api,
mock_output_api)
self.assertEqual(0, len(errors))
def testRelativeIncludeNonWebKitProducesError(self):
mock_input_api = MockInputApi()
mock_input_api.files = [
MockAffectedFile('test.cpp', ['#include "../header.h"']),
]
mock_output_api = MockOutputApi()
errors = PRESUBMIT.CheckForRelativeIncludes(mock_input_api,
mock_output_api)
self.assertEqual(1, len(errors))
def testRelativeIncludeWebKitProducesError(self):
mock_input_api = MockInputApi()
mock_input_api.files = [
MockAffectedFile('third_party/blink/test.cpp',
['#include "../header.h']),
]
mock_output_api = MockOutputApi()
errors = PRESUBMIT.CheckForRelativeIncludes(mock_input_api,
mock_output_api)
self.assertEqual(1, len(errors))
class CCIncludeTest(unittest.TestCase):
def testThirdPartyNotBlinkIgnored(self):
mock_input_api = MockInputApi()
mock_input_api.files = [
MockAffectedFile('third_party/test.cpp', '#include "file.cc"'),
]
mock_output_api = MockOutputApi()
errors = PRESUBMIT.CheckForCcIncludes(mock_input_api, mock_output_api)
self.assertEqual(0, len(errors))
def testPythonFileIgnored(self):
mock_input_api = MockInputApi()
mock_input_api.files = [
MockAffectedFile('test.py', '#include "file.cc"'),
]
mock_output_api = MockOutputApi()
errors = PRESUBMIT.CheckForCcIncludes(mock_input_api, mock_output_api)
self.assertEqual(0, len(errors))
def testIncFilesAccepted(self):
mock_input_api = MockInputApi()
mock_input_api.files = [
MockAffectedFile('test.py', '#include "file.inc"'),
]
mock_output_api = MockOutputApi()
errors = PRESUBMIT.CheckForCcIncludes(mock_input_api, mock_output_api)
self.assertEqual(0, len(errors))
def testInnocuousChangesAllowed(self):
mock_input_api = MockInputApi()
mock_input_api.files = [
MockAffectedFile('test.cpp', '#include "header.h"'),
MockAffectedFile('test2.cpp', 'Something "file.cc"'),
]
mock_output_api = MockOutputApi()
errors = PRESUBMIT.CheckForCcIncludes(mock_input_api, mock_output_api)
self.assertEqual(0, len(errors))
def testCcIncludeNonBlinkProducesError(self):
mock_input_api = MockInputApi()
mock_input_api.files = [
MockAffectedFile('test.cpp', ['#include "file.cc"']),
]
mock_output_api = MockOutputApi()
errors = PRESUBMIT.CheckForCcIncludes(mock_input_api, mock_output_api)
self.assertEqual(1, len(errors))
def testCppIncludeBlinkProducesError(self):
mock_input_api = MockInputApi()
mock_input_api.files = [
MockAffectedFile('third_party/blink/test.cpp',
['#include "foo/file.cpp"']),
]
mock_output_api = MockOutputApi()
errors = PRESUBMIT.CheckForCcIncludes(mock_input_api, mock_output_api)
self.assertEqual(1, len(errors))
class GnGlobForwardTest(unittest.TestCase):
def testAddBareGlobs(self):
mock_input_api = MockInputApi()
mock_input_api.files = [
MockAffectedFile('base/stuff.gni',
['forward_variables_from(invoker, "*")']),
MockAffectedFile('base/BUILD.gn',
['forward_variables_from(invoker, "*")']),
]
warnings = PRESUBMIT.CheckGnGlobForward(mock_input_api,
MockOutputApi())
self.assertEqual(1, len(warnings))
msg = '\n'.join(warnings[0].items)
self.assertIn('base/stuff.gni', msg)
# Should not check .gn files. Local templates don't need to care about
# visibility / testonly.
self.assertNotIn('base/BUILD.gn', msg)
def testValidUses(self):
mock_input_api = MockInputApi()
mock_input_api.files = [
MockAffectedFile('base/stuff.gni',
['forward_variables_from(invoker, "*", [])']),
MockAffectedFile('base/stuff2.gni', [
'forward_variables_from(invoker, "*", TESTONLY_AND_VISIBILITY)'
]),
MockAffectedFile(
'base/stuff3.gni',
['forward_variables_from(invoker, [ "testonly" ])']),
]
warnings = PRESUBMIT.CheckGnGlobForward(mock_input_api,
MockOutputApi())
self.assertEqual([], warnings)
class GnRebasePathTest(unittest.TestCase):
def testAddAbsolutePath(self):
mock_input_api = MockInputApi()
mock_input_api.files = [
MockAffectedFile('base/BUILD.gn',
['rebase_path("$target_gen_dir", "//")']),
MockAffectedFile('base/root/BUILD.gn',
['rebase_path("$target_gen_dir", "/")']),
MockAffectedFile('base/variable/BUILD.gn',
['rebase_path(target_gen_dir, "/")']),
]
warnings = PRESUBMIT.CheckGnRebasePath(mock_input_api, MockOutputApi())
self.assertEqual(1, len(warnings))
msg = '\n'.join(warnings[0].items)
self.assertIn('base/BUILD.gn', msg)
self.assertIn('base/root/BUILD.gn', msg)
self.assertIn('base/variable/BUILD.gn', msg)
self.assertEqual(3, len(warnings[0].items))
def testValidUses(self):
mock_input_api = MockInputApi()
mock_input_api.files = [
MockAffectedFile(
'base/foo/BUILD.gn',
['rebase_path("$target_gen_dir", root_build_dir)']),
MockAffectedFile(
'base/bar/BUILD.gn',
['rebase_path("$target_gen_dir", root_build_dir, "/")']),
MockAffectedFile('base/baz/BUILD.gn',
['rebase_path(target_gen_dir, root_build_dir)']),
MockAffectedFile(
'base/baz/BUILD.gn',
['rebase_path(target_gen_dir, "//some/arbitrary/path")']),
MockAffectedFile('base/okay_slash/BUILD.gn',
['rebase_path(".", "//")']),
]
warnings = PRESUBMIT.CheckGnRebasePath(mock_input_api, MockOutputApi())
self.assertEqual([], warnings)
class NewHeaderWithoutGnChangeTest(unittest.TestCase):
def testAddHeaderWithoutGn(self):
mock_input_api = MockInputApi()
mock_input_api.files = [
MockAffectedFile('base/stuff.h', ''),
]
warnings = PRESUBMIT.CheckNewHeaderWithoutGnChangeOnUpload(
mock_input_api, MockOutputApi())
self.assertEqual(1, len(warnings))
self.assertTrue('base/stuff.h' in warnings[0].items)
def testModifyHeader(self):
mock_input_api = MockInputApi()
mock_input_api.files = [
MockAffectedFile('base/stuff.h', '', action='M'),
]
warnings = PRESUBMIT.CheckNewHeaderWithoutGnChangeOnUpload(
mock_input_api, MockOutputApi())
self.assertEqual(0, len(warnings))
def testDeleteHeader(self):
mock_input_api = MockInputApi()
mock_input_api.files = [
MockAffectedFile('base/stuff.h', '', action='D'),
]
warnings = PRESUBMIT.CheckNewHeaderWithoutGnChangeOnUpload(
mock_input_api, MockOutputApi())
self.assertEqual(0, len(warnings))
def testAddHeaderWithGn(self):
mock_input_api = MockInputApi()
mock_input_api.files = [
MockAffectedFile('base/stuff.h', ''),
MockAffectedFile('base/BUILD.gn', 'stuff.h'),
]
warnings = PRESUBMIT.CheckNewHeaderWithoutGnChangeOnUpload(
mock_input_api, MockOutputApi())
self.assertEqual(0, len(warnings))
def testAddHeaderWithGni(self):
mock_input_api = MockInputApi()
mock_input_api.files = [
MockAffectedFile('base/stuff.h', ''),
MockAffectedFile('base/files.gni', 'stuff.h'),
]
warnings = PRESUBMIT.CheckNewHeaderWithoutGnChangeOnUpload(
mock_input_api, MockOutputApi())
self.assertEqual(0, len(warnings))
def testAddHeaderWithOther(self):
mock_input_api = MockInputApi()
mock_input_api.files = [
MockAffectedFile('base/stuff.h', ''),
MockAffectedFile('base/stuff.cc', 'stuff.h'),
]
warnings = PRESUBMIT.CheckNewHeaderWithoutGnChangeOnUpload(
mock_input_api, MockOutputApi())
self.assertEqual(1, len(warnings))
def testAddHeaderWithWrongGn(self):
mock_input_api = MockInputApi()
mock_input_api.files = [
MockAffectedFile('base/stuff.h', ''),
MockAffectedFile('base/BUILD.gn', 'stuff_h'),
]
warnings = PRESUBMIT.CheckNewHeaderWithoutGnChangeOnUpload(
mock_input_api, MockOutputApi())
self.assertEqual(1, len(warnings))
def testAddHeadersWithGn(self):
mock_input_api = MockInputApi()
mock_input_api.files = [
MockAffectedFile('base/stuff.h', ''),
MockAffectedFile('base/another.h', ''),
MockAffectedFile('base/BUILD.gn', 'another.h\nstuff.h'),
]
warnings = PRESUBMIT.CheckNewHeaderWithoutGnChangeOnUpload(
mock_input_api, MockOutputApi())
self.assertEqual(0, len(warnings))
def testAddHeadersWithWrongGn(self):
mock_input_api = MockInputApi()
mock_input_api.files = [
MockAffectedFile('base/stuff.h', ''),
MockAffectedFile('base/another.h', ''),
MockAffectedFile('base/BUILD.gn', 'another_h\nstuff.h'),
]
warnings = PRESUBMIT.CheckNewHeaderWithoutGnChangeOnUpload(
mock_input_api, MockOutputApi())
self.assertEqual(1, len(warnings))
self.assertFalse('base/stuff.h' in warnings[0].items)
self.assertTrue('base/another.h' in warnings[0].items)
def testAddHeadersWithWrongGn2(self):
mock_input_api = MockInputApi()
mock_input_api.files = [
MockAffectedFile('base/stuff.h', ''),
MockAffectedFile('base/another.h', ''),
MockAffectedFile('base/BUILD.gn', 'another_h\nstuff_h'),
]
warnings = PRESUBMIT.CheckNewHeaderWithoutGnChangeOnUpload(
mock_input_api, MockOutputApi())
self.assertEqual(1, len(warnings))
self.assertTrue('base/stuff.h' in warnings[0].items)
self.assertTrue('base/another.h' in warnings[0].items)
class CorrectProductNameInMessagesTest(unittest.TestCase):
def testProductNameInDesc(self):
mock_input_api = MockInputApi()
mock_input_api.files = [
MockAffectedFile('chrome/app/google_chrome_strings.grd', [
'<message name="Foo" desc="Welcome to Chrome">',
' Welcome to Chrome!',
'</message>',
]),
MockAffectedFile('chrome/app/chromium_strings.grd', [
'<message name="Bar" desc="Welcome to Chrome">',
' Welcome to Chromium!',
'</message>',
]),
]
warnings = PRESUBMIT.CheckCorrectProductNameInMessages(
mock_input_api, MockOutputApi())
self.assertEqual(0, len(warnings))
def testChromeInChromium(self):
mock_input_api = MockInputApi()
mock_input_api.files = [
MockAffectedFile('chrome/app/google_chrome_strings.grd', [
'<message name="Foo" desc="Welcome to Chrome">',
' Welcome to Chrome!',
'</message>',
]),
MockAffectedFile('chrome/app/chromium_strings.grd', [
'<message name="Bar" desc="Welcome to Chrome">',
' Welcome to Chrome!',
'</message>',
]),
]
warnings = PRESUBMIT.CheckCorrectProductNameInMessages(
mock_input_api, MockOutputApi())
self.assertEqual(1, len(warnings))
self.assertTrue(
'chrome/app/chromium_strings.grd' in warnings[0].items[0])
def testChromiumInChrome(self):
mock_input_api = MockInputApi()
mock_input_api.files = [
MockAffectedFile('chrome/app/google_chrome_strings.grd', [
'<message name="Foo" desc="Welcome to Chrome">',
' Welcome to Chromium!',
'</message>',
]),
MockAffectedFile('chrome/app/chromium_strings.grd', [
'<message name="Bar" desc="Welcome to Chrome">',
' Welcome to Chromium!',
'</message>',
]),
]
warnings = PRESUBMIT.CheckCorrectProductNameInMessages(
mock_input_api, MockOutputApi())
self.assertEqual(1, len(warnings))
self.assertTrue(
'chrome/app/google_chrome_strings.grd:2' in warnings[0].items[0])
def testChromeForTestingInChromium(self):
mock_input_api = MockInputApi()
mock_input_api.files = [
MockAffectedFile('chrome/app/chromium_strings.grd', [
'<message name="Bar" desc="Welcome to Chrome">',
' Welcome to Chrome for Testing!',
'</message>',
]),
]
warnings = PRESUBMIT.CheckCorrectProductNameInMessages(
mock_input_api, MockOutputApi())
self.assertEqual(0, len(warnings))
def testChromeForTestingInChrome(self):
mock_input_api = MockInputApi()
mock_input_api.files = [
MockAffectedFile('chrome/app/google_chrome_strings.grd', [
'<message name="Bar" desc="Welcome to Chrome">',
' Welcome to Chrome for Testing!',
'</message>',
]),
]
warnings = PRESUBMIT.CheckCorrectProductNameInMessages(
mock_input_api, MockOutputApi())
self.assertEqual(1, len(warnings))
self.assertTrue(
'chrome/app/google_chrome_strings.grd:2' in warnings[0].items[0])
def testMultipleInstances(self):
mock_input_api = MockInputApi()
mock_input_api.files = [
MockAffectedFile('chrome/app/chromium_strings.grd', [
'<message name="Bar" desc="Welcome to Chrome">',
' Welcome to Chrome!',
'</message>',
'<message name="Baz" desc="A correct message">',
' Chromium is the software you are using.',
'</message>',
'<message name="Bat" desc="An incorrect message">',
' Google Chrome is the software you are using.',
'</message>',
]),
]
warnings = PRESUBMIT.CheckCorrectProductNameInMessages(
mock_input_api, MockOutputApi())
self.assertEqual(1, len(warnings))
self.assertTrue(
'chrome/app/chromium_strings.grd:2' in warnings[0].items[0])
self.assertTrue(
'chrome/app/chromium_strings.grd:8' in warnings[0].items[1])
def testMultipleWarnings(self):
mock_input_api = MockInputApi()
mock_input_api.files = [
MockAffectedFile('chrome/app/chromium_strings.grd', [
'<message name="Bar" desc="Welcome to Chrome">',
' Welcome to Chrome!',
'</message>',
'<message name="Baz" desc="A correct message">',
' Chromium is the software you are using.',
'</message>',
'<message name="Bat" desc="An incorrect message">',
' Google Chrome is the software you are using.',
'</message>',
]),
MockAffectedFile(
'components/components_google_chrome_strings.grd', [
'<message name="Bar" desc="Welcome to Chrome">',
' Welcome to Chrome!',
'</message>',
'<message name="Baz" desc="A correct message">',
' Chromium is the software you are using.',
'</message>',
'<message name="Bat" desc="An incorrect message">',
' Google Chrome is the software you are using.',
'</message>',
]),
]
warnings = PRESUBMIT.CheckCorrectProductNameInMessages(
mock_input_api, MockOutputApi())
self.assertEqual(2, len(warnings))
self.assertTrue('components/components_google_chrome_strings.grd:5' in
warnings[0].items[0])
self.assertTrue(
'chrome/app/chromium_strings.grd:2' in warnings[1].items[0])
self.assertTrue(
'chrome/app/chromium_strings.grd:8' in warnings[1].items[1])
class _SecurityOwnersTestCase(unittest.TestCase):
def _createMockInputApi(self):
mock_input_api = MockInputApi()
def FakeRepositoryRoot():
return mock_input_api.os_path.join('chromium', 'src')
mock_input_api.change.RepositoryRoot = FakeRepositoryRoot
self._injectFakeOwnersClient(
mock_input_api, ['apple@chromium.org', 'orange@chromium.org'])
return mock_input_api
def _setupFakeChange(self, input_api):
class FakeGerrit(object):
def IsOwnersOverrideApproved(self, issue):
return False
input_api.change.issue = 123
input_api.gerrit = FakeGerrit()
def _injectFakeOwnersClient(self, input_api, owners):
class FakeOwnersClient(object):
def ListOwners(self, f):
return owners
input_api.owners_client = FakeOwnersClient()
def _injectFakeChangeOwnerAndReviewers(self, input_api, owner, reviewers):
def MockOwnerAndReviewers(input_api,
email_regexp,
approval_needed=False):
return [owner, reviewers]
input_api.canned_checks.GetCodereviewOwnerAndReviewers = \
MockOwnerAndReviewers
class IpcSecurityOwnerTest(_SecurityOwnersTestCase):
_test_cases = [
('*_messages.cc', 'scary_messages.cc'),
('*_messages*.h', 'scary_messages.h'),
('*_messages*.h', 'scary_messages_android.h'),
('*_param_traits*.*', 'scary_param_traits.h'),
('*_param_traits*.*', 'scary_param_traits_win.h'),
('*.mojom', 'scary.mojom'),
('*_mojom_traits*.*', 'scary_mojom_traits.h'),
('*_mojom_traits*.*', 'scary_mojom_traits_mac.h'),
('*_type_converter*.*', 'scary_type_converter.h'),
('*_type_converter*.*', 'scary_type_converter_nacl.h'),
('*.aidl', 'scary.aidl'),
]
def testHasCorrectPerFileRulesAndSecurityReviewer(self):
mock_input_api = self._createMockInputApi()
new_owners_file_path = mock_input_api.os_path.join(
'services', 'goat', 'public', 'OWNERS')
new_owners_file = [
'per-file *.mojom=set noparent',
'per-file *.mojom=file://ipc/SECURITY_OWNERS'
]
def FakeReadFile(filename):
self.assertEqual(
mock_input_api.os_path.join('chromium', 'src',
new_owners_file_path), filename)
return '\n'.join(new_owners_file)
mock_input_api.ReadFile = FakeReadFile
mock_input_api.files = [
MockAffectedFile(new_owners_file_path, new_owners_file),
MockAffectedFile(
mock_input_api.os_path.join('services', 'goat', 'public',
'goat.mojom'),
['// Scary contents.'])
]
self._setupFakeChange(mock_input_api)
self._injectFakeChangeOwnerAndReviewers(mock_input_api,
'owner@chromium.org',
['orange@chromium.org'])
mock_input_api.is_committing = True
mock_input_api.dry_run = False
mock_output_api = MockOutputApi()
results = PRESUBMIT.CheckSecurityOwners(mock_input_api,
mock_output_api)
self.assertEqual(0, len(results))
def testMissingSecurityReviewerAtUpload(self):
mock_input_api = self._createMockInputApi()
new_owners_file_path = mock_input_api.os_path.join(
'services', 'goat', 'public', 'OWNERS')
new_owners_file = [
'per-file *.mojom=set noparent',
'per-file *.mojom=file://ipc/SECURITY_OWNERS'
]
def FakeReadFile(filename):
self.assertEqual(
mock_input_api.os_path.join('chromium', 'src',
new_owners_file_path), filename)
return '\n'.join(new_owners_file)
mock_input_api.ReadFile = FakeReadFile
mock_input_api.files = [
MockAffectedFile(new_owners_file_path, new_owners_file),
MockAffectedFile(
mock_input_api.os_path.join('services', 'goat', 'public',
'goat.mojom'),
['// Scary contents.'])
]
self._setupFakeChange(mock_input_api)
self._injectFakeChangeOwnerAndReviewers(mock_input_api,
'owner@chromium.org',
['banana@chromium.org'])
mock_input_api.is_committing = False
mock_input_api.dry_run = False
mock_output_api = MockOutputApi()
results = PRESUBMIT.CheckSecurityOwners(mock_input_api,
mock_output_api)
self.assertEqual(1, len(results))
self.assertEqual('notify', results[0].type)
self.assertEqual(
'Review from an owner in ipc/SECURITY_OWNERS is required for the '
'following newly-added files:', results[0].message)
def testMissingSecurityReviewerAtDryRunCommit(self):
mock_input_api = self._createMockInputApi()
new_owners_file_path = mock_input_api.os_path.join(
'services', 'goat', 'public', 'OWNERS')
new_owners_file = [
'per-file *.mojom=set noparent',
'per-file *.mojom=file://ipc/SECURITY_OWNERS'
]
def FakeReadFile(filename):
self.assertEqual(
mock_input_api.os_path.join('chromium', 'src',
new_owners_file_path), filename)
return '\n'.join(new_owners_file)
mock_input_api.ReadFile = FakeReadFile
mock_input_api.files = [
MockAffectedFile(new_owners_file_path, new_owners_file),
MockAffectedFile(
mock_input_api.os_path.join('services', 'goat', 'public',
'goat.mojom'),
['// Scary contents.'])
]
self._setupFakeChange(mock_input_api)
self._injectFakeChangeOwnerAndReviewers(mock_input_api,
'owner@chromium.org',
['banana@chromium.org'])
mock_input_api.is_committing = True
mock_input_api.dry_run = True
mock_output_api = MockOutputApi()
results = PRESUBMIT.CheckSecurityOwners(mock_input_api,
mock_output_api)
self.assertEqual(1, len(results))
self.assertEqual('error', results[0].type)
self.assertEqual(
'Review from an owner in ipc/SECURITY_OWNERS is required for the '
'following newly-added files:', results[0].message)
def testMissingSecurityApprovalAtRealCommit(self):
mock_input_api = self._createMockInputApi()
new_owners_file_path = mock_input_api.os_path.join(
'services', 'goat', 'public', 'OWNERS')
new_owners_file = [
'per-file *.mojom=set noparent',
'per-file *.mojom=file://ipc/SECURITY_OWNERS'
]
def FakeReadFile(filename):
self.assertEqual(
mock_input_api.os_path.join('chromium', 'src',
new_owners_file_path), filename)
return '\n'.join(new_owners_file)
mock_input_api.ReadFile = FakeReadFile
mock_input_api.files = [
MockAffectedFile(new_owners_file_path, new_owners_file),
MockAffectedFile(
mock_input_api.os_path.join('services', 'goat', 'public',
'goat.mojom'),
['// Scary contents.'])
]
self._setupFakeChange(mock_input_api)
self._injectFakeChangeOwnerAndReviewers(mock_input_api,
'owner@chromium.org',
['banana@chromium.org'])
mock_input_api.is_committing = True
mock_input_api.dry_run = False
mock_output_api = MockOutputApi()
results = PRESUBMIT.CheckSecurityOwners(mock_input_api,
mock_output_api)
self.assertEqual('error', results[0].type)
self.assertEqual(
'Review from an owner in ipc/SECURITY_OWNERS is required for the '
'following newly-added files:', results[0].message)
def testIpcChangeNeedsSecurityOwner(self):
for is_committing in [True, False]:
for pattern, filename in self._test_cases:
with self.subTest(
line=
f'is_committing={is_committing}, filename={filename}'):
mock_input_api = self._createMockInputApi()
mock_input_api.files = [
MockAffectedFile(
mock_input_api.os_path.join(
'services', 'goat', 'public', filename),
['// Scary contents.'])
]
self._setupFakeChange(mock_input_api)
self._injectFakeChangeOwnerAndReviewers(
mock_input_api, 'owner@chromium.org',
['banana@chromium.org'])
mock_input_api.is_committing = is_committing
mock_input_api.dry_run = False
mock_output_api = MockOutputApi()
results = PRESUBMIT.CheckSecurityOwners(
mock_input_api, mock_output_api)
self.assertEqual(1, len(results))
self.assertEqual('error', results[0].type)
self.assertTrue(results[0].message.replace(
'\\', '/'
).startswith(
'Found missing OWNERS lines for security-sensitive files. '
'Please add the following lines to services/goat/public/OWNERS:'
))
self.assertEqual(['ipc-security-reviews@chromium.org'],
mock_output_api.more_cc)
def testServiceManifestChangeNeedsSecurityOwner(self):
mock_input_api = self._createMockInputApi()
mock_input_api.files = [
MockAffectedFile(
mock_input_api.os_path.join('services', 'goat', 'public',
'cpp', 'manifest.cc'),
[
'#include "services/goat/public/cpp/manifest.h"',
'const service_manager::Manifest& GetManifest() {}',
])
]
self._setupFakeChange(mock_input_api)
self._injectFakeChangeOwnerAndReviewers(mock_input_api,
'owner@chromium.org',
['banana@chromium.org'])
mock_output_api = MockOutputApi()
errors = PRESUBMIT.CheckSecurityOwners(mock_input_api, mock_output_api)
self.assertEqual(1, len(errors))
self.assertTrue(errors[0].message.replace('\\', '/').startswith(
'Found missing OWNERS lines for security-sensitive files. '
'Please add the following lines to services/goat/public/cpp/OWNERS:'
))
self.assertEqual(['ipc-security-reviews@chromium.org'],
mock_output_api.more_cc)
def testNonServiceManifestSourceChangesDoNotRequireSecurityOwner(self):
mock_input_api = self._createMockInputApi()
self._injectFakeChangeOwnerAndReviewers(mock_input_api,
'owner@chromium.org',
['banana@chromium.org'])
mock_input_api.files = [
MockAffectedFile('some/non/service/thing/foo_manifest.cc', [
'const char kNoEnforcement[] = "not a manifest!";',
])
]
mock_output_api = MockOutputApi()
errors = PRESUBMIT.CheckSecurityOwners(mock_input_api, mock_output_api)
self.assertEqual([], errors)
self.assertEqual([], mock_output_api.more_cc)
class FuchsiaSecurityOwnerTest(_SecurityOwnersTestCase):
def testFidlChangeNeedsSecurityOwner(self):
mock_input_api = self._createMockInputApi()
mock_input_api.files = [
MockAffectedFile('potentially/scary/ipc.fidl',
['library test.fidl'])
]
self._setupFakeChange(mock_input_api)
self._injectFakeChangeOwnerAndReviewers(mock_input_api,
'owner@chromium.org',
['banana@chromium.org'])
mock_output_api = MockOutputApi()
errors = PRESUBMIT.CheckSecurityOwners(mock_input_api, mock_output_api)
self.assertEqual(1, len(errors))
self.assertTrue(errors[0].message.replace('\\', '/').startswith(
'Found missing OWNERS lines for security-sensitive files. '
'Please add the following lines to potentially/scary/OWNERS:'))
def testComponentManifestV1ChangeNeedsSecurityOwner(self):
mock_input_api = self._createMockInputApi()
mock_input_api.files = [
MockAffectedFile('potentially/scary/v2_manifest.cmx',
['{ "that is no": "manifest!" }'])
]
self._setupFakeChange(mock_input_api)
self._injectFakeChangeOwnerAndReviewers(mock_input_api,
'owner@chromium.org',
['banana@chromium.org'])
mock_output_api = MockOutputApi()
errors = PRESUBMIT.CheckSecurityOwners(mock_input_api, mock_output_api)
self.assertEqual(1, len(errors))
self.assertTrue(errors[0].message.replace('\\', '/').startswith(
'Found missing OWNERS lines for security-sensitive files. '
'Please add the following lines to potentially/scary/OWNERS:'))
def testComponentManifestV2NeedsSecurityOwner(self):
mock_input_api = self._createMockInputApi()
mock_input_api.files = [
MockAffectedFile('potentially/scary/v2_manifest.cml',
['{ "that is no": "manifest!" }'])
]
self._setupFakeChange(mock_input_api)
self._injectFakeChangeOwnerAndReviewers(mock_input_api,
'owner@chromium.org',
['banana@chromium.org'])
mock_output_api = MockOutputApi()
errors = PRESUBMIT.CheckSecurityOwners(mock_input_api, mock_output_api)
self.assertEqual(1, len(errors))
self.assertTrue(errors[0].message.replace('\\', '/').startswith(
'Found missing OWNERS lines for security-sensitive files. '
'Please add the following lines to potentially/scary/OWNERS:'))
def testThirdPartyTestsDoNotRequireSecurityOwner(self):
mock_input_api = MockInputApi()
self._injectFakeChangeOwnerAndReviewers(mock_input_api,
'owner@chromium.org',
['banana@chromium.org'])
mock_input_api.files = [
MockAffectedFile('third_party/crashpad/test/tests.cmx', [
'const char kNoEnforcement[] = "Security?!? Pah!";',
])
]
mock_output_api = MockOutputApi()
errors = PRESUBMIT.CheckSecurityOwners(mock_input_api, mock_output_api)
self.assertEqual([], errors)
def testOtherFuchsiaChangesDoNotRequireSecurityOwner(self):
mock_input_api = MockInputApi()
self._injectFakeChangeOwnerAndReviewers(mock_input_api,
'owner@chromium.org',
['banana@chromium.org'])
mock_input_api.files = [
MockAffectedFile(
'some/non/service/thing/fuchsia_fidl_cml_cmx_magic.cc', [
'const char kNoEnforcement[] = "Security?!? Pah!";',
])
]
mock_output_api = MockOutputApi()
errors = PRESUBMIT.CheckSecurityOwners(mock_input_api, mock_output_api)
self.assertEqual([], errors)
class SecurityChangeTest(_SecurityOwnersTestCase):
def testDiffGetServiceSandboxType(self):
mock_input_api = MockInputApi()
mock_input_api.files = [
MockAffectedFile('services/goat/teleporter_host.cc', [
'template <>', 'inline content::SandboxType',
'content::GetServiceSandboxType<chrome::mojom::GoatTeleporter>() {',
'#if defined(OS_WIN)', ' return SandboxType::kGoaty;',
'#else', ' return SandboxType::kNoSandbox;',
'#endif // !defined(OS_WIN)', '}'
]),
]
files_to_functions = PRESUBMIT._GetFilesUsingSecurityCriticalFunctions(
mock_input_api)
self.assertEqual(
{
'services/goat/teleporter_host.cc':
set(['content::GetServiceSandboxType<>()'])
}, files_to_functions)
def testDiffRemovingLine(self):
mock_input_api =