File: api_static_checks_unittest.py

package info (click to toggle)
chromium 139.0.7258.138-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 6,120,676 kB
  • sloc: cpp: 35,100,869; ansic: 7,163,530; javascript: 4,103,002; python: 1,436,920; asm: 946,517; xml: 746,709; pascal: 187,653; perl: 88,691; sh: 88,436; objc: 79,953; sql: 51,488; cs: 44,583; fortran: 24,137; makefile: 22,147; tcl: 15,277; php: 13,980; yacc: 8,984; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (286 lines) | stat: -rwxr-xr-x 8,809 bytes parent folder | download | duplicates (5)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
#!/usr/bin/env python3
# Copyright 2016 The Chromium Authors
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""api_static_checks_unittest.py - Unittests for api_static_checks.py"""

import contextlib
import hashlib
import io
import os
import shutil
import sys
import tempfile
import unittest

REPOSITORY_ROOT = os.path.abspath(
    os.path.join(os.path.dirname(__file__), '..', '..', '..'))
sys.path.insert(0, REPOSITORY_ROOT)

from build.android.gyp.util import build_utils  # pylint: disable=wrong-import-position
from components.cronet.tools import api_static_checks  # pylint: disable=wrong-import-position
from components.cronet.tools import update_api  # pylint: disable=wrong-import-position

JAR_PATH = os.path.join(build_utils.JAVA_HOME, 'bin', 'jar')
JAVAC_PATH = os.path.join(build_utils.JAVA_HOME, 'bin', 'javac')

# pylint: disable=useless-object-inheritance

ERROR_PREFIX_CHECK_API_CALLS = (
    """ERROR: Found the following calls from implementation classes through
       API classes.  These could fail if older API is used that
       does not contain newer methods.  Please call through a
       wrapper class from VersionSafeCallbacks.
""")

ERROR_PREFIX_UPDATE_API = ("""ERROR: This API was modified or removed:
             """)

ERROR_SUFFIX_UPDATE_API = ("""

       Cronet API methods and classes cannot be modified.
""")

CHECK_API_VERSION_PREFIX = (
    """DO NOT EDIT THIS FILE, USE update_api.py TO UPDATE IT

""")

API_FILENAME = './android/api.txt'
API_VERSION_FILENAME = './android/api_version.txt'


@contextlib.contextmanager
def capture_output():
  # A contextmanger that collects the stdout and stderr of wrapped code

  oldout, olderr = sys.stdout, sys.stderr
  try:
    out = [io.StringIO(), io.StringIO()]
    sys.stdout, sys.stderr = out
    yield out
  finally:
    sys.stdout, sys.stderr = oldout, olderr
    out[0] = out[0].getvalue()
    out[1] = out[1].getvalue()


class ApiStaticCheckUnitTest(unittest.TestCase):

  def setUp(self):
    self.exe_path = os.path.join(REPOSITORY_ROOT, 'out')
    self.temp_dir = tempfile.mkdtemp(dir=self.exe_path)
    os.chdir(self.temp_dir)
    os.mkdir('android')
    with open(API_VERSION_FILENAME, 'w') as api_version_file:
      api_version_file.write('0')
    with open(API_FILENAME, 'w') as api_file:
      api_file.write('}\nStamp: 7d9d25f71cb8a5aba86202540a20d405\n')
    shutil.copytree(os.path.dirname(__file__), 'tools')

  def tearDown(self):
    shutil.rmtree(self.temp_dir)

  def make_jar(self, java, class_name):
    # Compile |java| wrapped in a class named |class_name| to a jar file and
    # return jar filename.

    java_filename = class_name + '.java'
    class_filenames = class_name + '*.class'
    jar_filename = class_name + '.jar'

    with open(java_filename, 'w') as java_file:
      java_file.write('public class %s {' % class_name)
      java_file.write(java)
      java_file.write('}')
    os.system(f'{os.path.abspath(JAVAC_PATH)} {java_filename}')
    os.system(
        f'{os.path.abspath(JAR_PATH)} cf {jar_filename} {class_filenames}')
    return jar_filename

  def run_check_api_calls(self, api_java, impl_java):
    test = self

    class MockOpts(object):

      def __init__(self):
        self.api_jar = test.make_jar(api_java, 'Api')
        self.impl_jar = [test.make_jar(impl_java, 'Impl')]

    opts = MockOpts()
    with capture_output() as return_output:
      return_code = api_static_checks.check_api_calls(opts)
    return [return_code, return_output[0]]

  def test_check_api_calls_success(self):
    # Test simple classes with functions
    self.assertEqual(self.run_check_api_calls('void a(){}', 'void b(){}'),
                     [True, ''])
    # Test simple classes with functions calling themselves
    self.assertEqual(
        self.run_check_api_calls('void a(){} void b(){a();}',
                                 'void c(){} void d(){c();}'), [True, ''])

  def test_check_api_calls_failure(self):
    # Test static call
    self.assertEqual(
        self.run_check_api_calls('public static void a(){}',
                                 'void b(){Api.a();}'),
        [False, ERROR_PREFIX_CHECK_API_CALLS + 'Impl/b -> Api/a:()V\n'])
    # Test virtual call
    self.assertEqual(
        self.run_check_api_calls('public void a(){}',
                                 'void b(){new Api().a();}'),
        [False, ERROR_PREFIX_CHECK_API_CALLS + 'Impl/b -> Api/a:()V\n'])

  def run_check_api_version(self, java):
    OUT_FILENAME = 'out.txt'
    return_code = os.system('./tools/update_api.py --api_jar %s > %s' %
                            (self.make_jar(java, 'Api'), OUT_FILENAME))
    with open(API_FILENAME, 'r') as api_file:
      api = api_file.read()
    with open(API_VERSION_FILENAME, 'r') as api_version_file:
      api_version = api_version_file.read()
    with open(OUT_FILENAME, 'r') as out_file:
      output = out_file.read()

    # Verify stamp
    api_stamp = api.split('\n')[-2]
    stamp_length = len('Stamp: 78418460c193047980ae9eabb79293f2\n')
    api = api[:-stamp_length]
    api_hash = hashlib.md5()
    api_hash.update(api.encode('utf-8'))
    self.assertEqual(api_stamp, 'Stamp: %s' % api_hash.hexdigest())

    return [return_code == 0, output, api, api_version]

  def test_split_by_class_sort(self):
    expected = [
        [
            'public class Api {',
            'public Api();',
            'public void a();',
            'public void b();',
            '}',
        ],
        [
            'public class zee {',
            'public abstract int z();',
            'public void x();',
            'public void y();',
            'public zee();',
            '}',
        ],
    ]
    input_str = """Compiled from Api.java
public class Api {
public void b();
public Api();
public void a();
}
Compiled from zee.java
public class zee {
public void x();
public zee();
public void y();
public abstract int z();
}
"""
    self.assertEqual(update_api._split_by_class(input_str.splitlines()),
                     expected)

  def test_update_api_success(self):
    # Test simple new API
    self.assertEqual(self.run_check_api_version('public void a(){}'), [
        True, '', CHECK_API_VERSION_PREFIX + """public class Api {
  public Api();
  public void a();
}
""", '1'
    ])
    # Test version number not increased when API not changed
    self.assertEqual(self.run_check_api_version('public void a(){}'), [
        True, '', CHECK_API_VERSION_PREFIX + """public class Api {
  public Api();
  public void a();
}
""", '1'
    ])
    # Test acceptable API method addition
    self.assertEqual(
        self.run_check_api_version('public void a(){} public void b(){}'), [
            True, '', CHECK_API_VERSION_PREFIX + """public class Api {
  public Api();
  public void a();
  public void b();
}
""", '2'
        ])
    # Test version number not increased when API not changed
    self.assertEqual(
        self.run_check_api_version('public void a(){} public void b(){}'), [
            True, '', CHECK_API_VERSION_PREFIX + """public class Api {
  public Api();
  public void a();
  public void b();
}
""", '2'
        ])
    # Test acceptable API class addition
    self.assertEqual(
        self.run_check_api_version(
            'public void a(){} public void b(){} public class C {}'), [
                True, '', CHECK_API_VERSION_PREFIX + """public class Api$C {
  public Api$C(Api);
}
public class Api {
  public Api();
  public void a();
  public void b();
}
""", '3'
            ])
    # Test version number not increased when API not changed
    self.assertEqual(
        self.run_check_api_version(
            'public void a(){} public void b(){} public class C {}'), [
                True, '', CHECK_API_VERSION_PREFIX + """public class Api$C {
  public Api$C(Api);
}
public class Api {
  public Api();
  public void a();
  public void b();
}
""", '3'
            ])

  def test_update_api_failure(self):
    # Create a simple new API
    self.assertEqual(self.run_check_api_version('public void a(){}'), [
        True, '', CHECK_API_VERSION_PREFIX + """public class Api {
  public Api();
  public void a();
}
""", '1'
    ])
    # Test removing API method not allowed
    self.assertEqual(self.run_check_api_version(''), [
        False,
        ERROR_PREFIX_UPDATE_API + 'public void a();' + ERROR_SUFFIX_UPDATE_API,
        CHECK_API_VERSION_PREFIX + """public class Api {
  public Api();
  public void a();
}
""", '1'
    ])
    # Test modifying API method not allowed
    self.assertEqual(self.run_check_api_version('public void a(int x){}'), [
        False,
        ERROR_PREFIX_UPDATE_API + 'public void a();' + ERROR_SUFFIX_UPDATE_API,
        CHECK_API_VERSION_PREFIX + """public class Api {
  public Api();
  public void a();
}
""", '1'
    ])