blob: 5cb43db0b00dca8cf079ffa5f1450ce4d37193a7 [file] [log] [blame]
Adrian Roos5ed42b62018-12-19 17:10:22 +01001#!/usr/bin/env python
2
3# Copyright (C) 2018 The Android Open Source Project
4#
5# Licensed under the Apache License, Version 2.0 (the 'License');
6# you may not use this file except in compliance with the License.
7# You may obtain a copy of the License at
8#
9# http://www.apache.org/licenses/LICENSE-2.0
10#
11# Unless required by applicable law or agreed to in writing, software
12# distributed under the License is distributed on an 'AS IS' BASIS,
13# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14# See the License for the specific language governing permissions and
15# limitations under the License.
16
17import unittest
18
19import apilint
20
21def cls(pkg, name):
22 return apilint.Class(apilint.Package(999, "package %s {" % pkg, None), 999,
23 "public final class %s {" % name, None)
24
25_ri = apilint._retry_iterator
26
27c1 = cls("android.app", "ActivityManager")
28c2 = cls("android.app", "Notification")
29c3 = cls("android.app", "Notification.Action")
30c4 = cls("android.graphics", "Bitmap")
31
32class UtilTests(unittest.TestCase):
33 def test_retry_iterator(self):
34 it = apilint._retry_iterator([1, 2, 3, 4])
35 self.assertEqual(it.next(), 1)
36 self.assertEqual(it.next(), 2)
37 self.assertEqual(it.next(), 3)
38 it.send("retry")
39 self.assertEqual(it.next(), 3)
40 self.assertEqual(it.next(), 4)
41 with self.assertRaises(StopIteration):
42 it.next()
43
44 def test_retry_iterator_one(self):
45 it = apilint._retry_iterator([1])
46 self.assertEqual(it.next(), 1)
47 it.send("retry")
48 self.assertEqual(it.next(), 1)
49 with self.assertRaises(StopIteration):
50 it.next()
51
52 def test_retry_iterator_one(self):
53 it = apilint._retry_iterator([1])
54 self.assertEqual(it.next(), 1)
55 it.send("retry")
56 self.assertEqual(it.next(), 1)
57 with self.assertRaises(StopIteration):
58 it.next()
59
60 def test_skip_to_matching_class_found(self):
61 it = _ri([c1, c2, c3, c4])
Adrian Roos038a0292018-12-19 17:11:21 +010062 self.assertEquals(apilint._skip_to_matching_class(it, c3),
Adrian Roos5ed42b62018-12-19 17:10:22 +010063 c3)
64 self.assertEqual(it.next(), c4)
65
66 def test_skip_to_matching_class_not_found(self):
67 it = _ri([c1, c2, c3, c4])
Adrian Roos038a0292018-12-19 17:11:21 +010068 self.assertEquals(apilint._skip_to_matching_class(it, cls("android.content", "ContentProvider")),
Adrian Roos5ed42b62018-12-19 17:10:22 +010069 None)
70 self.assertEqual(it.next(), c4)
71
Adrian Roos038a0292018-12-19 17:11:21 +010072 def test_yield_until_matching_class_found(self):
73 it = _ri([c1, c2, c3, c4])
74 self.assertEquals(list(apilint._yield_until_matching_class(it, c3)),
75 [c1, c2])
76 self.assertEqual(it.next(), c4)
77
78 def test_yield_until_matching_class_not_found(self):
79 it = _ri([c1, c2, c3, c4])
80 self.assertEquals(list(apilint._yield_until_matching_class(it, cls("android.content", "ContentProvider"))),
81 [c1, c2, c3])
82 self.assertEqual(it.next(), c4)
83
84 def test_yield_until_matching_class_None(self):
85 it = _ri([c1, c2, c3, c4])
86 self.assertEquals(list(apilint._yield_until_matching_class(it, None)),
87 [c1, c2, c3, c4])
88
89
90faulty_current_txt = """
Adrian Roos80545ef2019-02-27 16:45:00 +010091// Signature format: 2.0
Adrian Roos038a0292018-12-19 17:11:21 +010092package android.app {
93 public final class Activity {
94 }
95
96 public final class WallpaperColors implements android.os.Parcelable {
Adrian Roos80545ef2019-02-27 16:45:00 +010097 ctor public WallpaperColors(@NonNull android.os.Parcel);
Adrian Roos038a0292018-12-19 17:11:21 +010098 method public int describeContents();
Adrian Roos80545ef2019-02-27 16:45:00 +010099 method public void writeToParcel(@NonNull android.os.Parcel, int);
100 field @NonNull public static final android.os.Parcelable.Creator<android.app.WallpaperColors> CREATOR;
Adrian Roos038a0292018-12-19 17:11:21 +0100101 }
102}
Adrian Roos80545ef2019-02-27 16:45:00 +0100103""".strip().split('\n')
Adrian Roos038a0292018-12-19 17:11:21 +0100104
105ok_current_txt = """
Adrian Roos80545ef2019-02-27 16:45:00 +0100106// Signature format: 2.0
Adrian Roos038a0292018-12-19 17:11:21 +0100107package android.app {
108 public final class Activity {
109 }
110
111 public final class WallpaperColors implements android.os.Parcelable {
112 ctor public WallpaperColors();
113 method public int describeContents();
Adrian Roos80545ef2019-02-27 16:45:00 +0100114 method public void writeToParcel(@NonNull android.os.Parcel, int);
115 field @NonNull public static final android.os.Parcelable.Creator<android.app.WallpaperColors> CREATOR;
Adrian Roos038a0292018-12-19 17:11:21 +0100116 }
117}
Adrian Roos80545ef2019-02-27 16:45:00 +0100118""".strip().split('\n')
Adrian Roos038a0292018-12-19 17:11:21 +0100119
120system_current_txt = """
Adrian Roos80545ef2019-02-27 16:45:00 +0100121// Signature format: 2.0
Adrian Roos038a0292018-12-19 17:11:21 +0100122package android.app {
123 public final class WallpaperColors implements android.os.Parcelable {
124 method public int getSomething();
125 }
126}
Adrian Roos80545ef2019-02-27 16:45:00 +0100127""".strip().split('\n')
Adrian Roos038a0292018-12-19 17:11:21 +0100128
129
130
131class BaseFileTests(unittest.TestCase):
132 def test_base_file_avoids_errors(self):
133 failures, _ = apilint.examine_stream(system_current_txt, ok_current_txt)
134 self.assertEquals(failures, {})
135
136 def test_class_with_base_finds_same_errors(self):
137 failures_with_classes_with_base, _ = apilint.examine_stream("", faulty_current_txt,
138 in_classes_with_base=[cls("android.app", "WallpaperColors")])
139 failures_with_system_txt, _ = apilint.examine_stream(system_current_txt, faulty_current_txt)
140
141 self.assertEquals(failures_with_classes_with_base.keys(), failures_with_system_txt.keys())
142
143 def test_classes_with_base_is_emited(self):
144 classes_with_base = []
145 _, _ = apilint.examine_stream(system_current_txt, faulty_current_txt,
146 out_classes_with_base=classes_with_base)
147 self.assertEquals(map(lambda x: x.fullname, classes_with_base), ["android.app.WallpaperColors"])
148
Adrian Roos258c5722019-01-21 15:43:15 +0100149class ParseV2Stream(unittest.TestCase):
150 def test_field_kinds(self):
151 api = apilint._parse_stream("""
152// Signature format: 2.0
153package android {
154 public enum SomeEnum {
155 enum_constant public static final android.SomeEnum ENUM_CONST;
156 field public static final int FIELD_CONST;
157 property public final int someProperty;
158 ctor public SomeEnum();
159 method public Object? getObject();
160 }
161}
162 """.strip().split('\n'))
163
164 self.assertEquals(api['android.SomeEnum'].fields[0].split[0], 'enum_constant')
165 self.assertEquals(api['android.SomeEnum'].fields[1].split[0], 'field')
166 self.assertEquals(api['android.SomeEnum'].fields[2].split[0], 'property')
167 self.assertEquals(api['android.SomeEnum'].ctors[0].split[0], 'ctor')
168 self.assertEquals(api['android.SomeEnum'].methods[0].split[0], 'method')
169
Adrian Rooscf82e042019-01-29 15:01:28 +0100170class ParseV3Stream(unittest.TestCase):
171 def test_field_kinds(self):
172 api = apilint._parse_stream("""
173// Signature format: 3.0
174package a {
175
176 public final class ContextKt {
177 method public static inline <reified T> T! getSystemService(android.content.Context);
178 method public static inline void withStyledAttributes(android.content.Context, android.util.AttributeSet? set = null, int[] attrs, @AttrRes int defStyleAttr = 0, @StyleRes int defStyleRes = 0, kotlin.jvm.functions.Function1<? super android.content.res.TypedArray,kotlin.Unit> block);
179 }
180}
181 """.strip().split('\n'))
182 self.assertEquals(api['a.ContextKt'].methods[0].name, 'getSystemService')
183 self.assertEquals(api['a.ContextKt'].methods[0].split[:4], ['method', 'public', 'static', 'inline'])
184 self.assertEquals(api['a.ContextKt'].methods[1].name, 'withStyledAttributes')
185 self.assertEquals(api['a.ContextKt'].methods[1].split[:4], ['method', 'public', 'static', 'inline'])
186
Adrian Roosb787c182019-01-03 18:54:33 +0100187class V2TokenizerTests(unittest.TestCase):
188 def _test(self, raw, expected):
189 self.assertEquals(apilint.V2Tokenizer(raw).tokenize(), expected)
190
191 def test_simple(self):
192 self._test(" method public some.Type someName(some.Argument arg, int arg);",
193 ['method', 'public', 'some.Type', 'someName', '(', 'some.Argument',
194 'arg', ',', 'int', 'arg', ')', ';'])
195 self._test("class Some.Class extends SomeOther {",
196 ['class', 'Some.Class', 'extends', 'SomeOther', '{'])
197
Adrian Roos5cdfb692019-01-05 22:04:55 +0100198 def test_varargs(self):
199 self._test("name(String...)",
200 ['name', '(', 'String', '...', ')'])
201
202 def test_kotlin(self):
203 self._test("String? name(String!...)",
204 ['String', '?', 'name', '(', 'String', '!', '...', ')'])
205
Adrian Roosb787c182019-01-03 18:54:33 +0100206 def test_annotation(self):
207 self._test("method @Nullable public void name();",
208 ['method', '@', 'Nullable', 'public', 'void', 'name', '(', ')', ';'])
209
210 def test_annotation_args(self):
211 self._test("@Some(val=1, other=2) class Class {",
212 ['@', 'Some', '(', 'val', '=', '1', ',', 'other', '=', '2', ')',
213 'class', 'Class', '{'])
214 def test_comment(self):
215 self._test("some //comment", ['some'])
216
217 def test_strings(self):
218 self._test(r'"" "foo" "\"" "\\"', ['""', '"foo"', r'"\""', r'"\\"'])
219
220 def test_at_interface(self):
221 self._test("public @interface Annotation {",
222 ['public', '@interface', 'Annotation', '{'])
223
224 def test_array_type(self):
225 self._test("int[][]", ['int', '[]', '[]'])
226
227 def test_generics(self):
228 self._test("<>foobar<A extends Object>",
229 ['<', '>', 'foobar', '<', 'A', 'extends', 'Object', '>'])
230
231class V2ParserTests(unittest.TestCase):
232 def _cls(self, raw):
233 pkg = apilint.Package(999, "package pkg {", None)
234 return apilint.Class(pkg, 1, raw, '', sig_format=2)
235
236 def _method(self, raw, cls=None):
237 if not cls:
238 cls = self._cls("class Class {")
239 return apilint.Method(cls, 1, raw, '', sig_format=2)
240
241 def _field(self, raw):
242 cls = self._cls("class Class {")
243 return apilint.Field(cls, 1, raw, '', sig_format=2)
244
Adrian Roosd9871b12019-02-28 12:42:22 +0100245 def test_parse_package(self):
246 pkg = apilint.Package(999, "package wifi.p2p {", None)
247 self.assertEquals("wifi.p2p", pkg.name)
248
Adrian Roosb787c182019-01-03 18:54:33 +0100249 def test_class(self):
250 cls = self._cls("@Deprecated @IntRange(from=1, to=2) public static abstract class Some.Name extends Super<Class> implements Interface<Class> {")
251 self.assertTrue('deprecated' in cls.split)
252 self.assertTrue('static' in cls.split)
253 self.assertTrue('abstract' in cls.split)
254 self.assertTrue('class' in cls.split)
255 self.assertEquals('Super', cls.extends)
256 self.assertEquals('Interface', cls.implements)
257 self.assertEquals('pkg.Some.Name', cls.fullname)
258
Adrian Roos258c5722019-01-21 15:43:15 +0100259 def test_enum(self):
260 cls = self._cls("public enum Some.Name {")
261 self._field("enum_constant public static final android.ValueType COLOR;")
262
Adrian Roosb787c182019-01-03 18:54:33 +0100263 def test_interface(self):
264 cls = self._cls("@Deprecated @IntRange(from=1, to=2) public interface Some.Name extends Interface<Class> {")
265 self.assertTrue('deprecated' in cls.split)
266 self.assertTrue('interface' in cls.split)
267 self.assertEquals('Interface', cls.extends)
268 self.assertEquals('Interface', cls.implements)
269 self.assertEquals('pkg.Some.Name', cls.fullname)
270
271 def test_at_interface(self):
272 cls = self._cls("@java.lang.annotation.Target({java.lang.annotation.ElementType.TYPE, java.lang.annotation.ElementType.FIELD, java.lang.annotation.ElementType.METHOD, java.lang.annotation.ElementType.PARAMETER, java.lang.annotation.ElementType.CONSTRUCTOR, java.lang.annotation.ElementType.LOCAL_VARIABLE}) @java.lang.annotation.Retention(java.lang.annotation.RetentionPolicy.CLASS) public @interface SuppressLint {")
273 self.assertTrue('@interface' in cls.split)
274 self.assertEquals('pkg.SuppressLint', cls.fullname)
275
276 def test_parse_method(self):
Adrian Roosd1e38922019-01-14 15:44:15 +0100277 m = self._method("method @Deprecated public static native <T> Class<T>[][] name("
Adrian Roosb787c182019-01-03 18:54:33 +0100278 + "Class<T[]>[][], Class<T[][][]>[][]...) throws Exception, T;")
279 self.assertTrue('static' in m.split)
280 self.assertTrue('public' in m.split)
281 self.assertTrue('method' in m.split)
Adrian Roosd1e38922019-01-14 15:44:15 +0100282 self.assertTrue('native' in m.split)
Adrian Roosb787c182019-01-03 18:54:33 +0100283 self.assertTrue('deprecated' in m.split)
284 self.assertEquals('java.lang.Class[][]', m.typ)
285 self.assertEquals('name', m.name)
286 self.assertEquals(['java.lang.Class[][]', 'java.lang.Class[][]...'], m.args)
287 self.assertEquals(['java.lang.Exception', 'T'], m.throws)
288
289 def test_ctor(self):
290 m = self._method("ctor @Deprecated <T> ClassName();")
291 self.assertTrue('ctor' in m.split)
292 self.assertTrue('deprecated' in m.split)
293 self.assertEquals('ctor', m.typ)
294 self.assertEquals('ClassName', m.name)
295
296 def test_parse_annotation_method(self):
297 cls = self._cls("@interface Annotation {")
298 self._method('method abstract String category() default "";', cls=cls)
299 self._method('method abstract boolean deepExport() default false;', cls=cls)
300 self._method('method abstract ViewDebug.FlagToString[] flagMapping() default {};', cls=cls)
Adrian Roosd1e38922019-01-14 15:44:15 +0100301 self._method('method abstract ViewDebug.FlagToString[] flagMapping() default (double)java.lang.Float.NEGATIVE_INFINITY;', cls=cls)
Adrian Roosb787c182019-01-03 18:54:33 +0100302
303 def test_parse_string_field(self):
304 f = self._field('field @Deprecated public final String SOME_NAME = "value";')
305 self.assertTrue('field' in f.split)
306 self.assertTrue('deprecated' in f.split)
307 self.assertTrue('final' in f.split)
308 self.assertEquals('java.lang.String', f.typ)
309 self.assertEquals('SOME_NAME', f.name)
310 self.assertEquals('value', f.value)
311
312 def test_parse_field(self):
313 f = self._field('field public Object SOME_NAME;')
314 self.assertTrue('field' in f.split)
315 self.assertEquals('java.lang.Object', f.typ)
316 self.assertEquals('SOME_NAME', f.name)
317 self.assertEquals(None, f.value)
318
319 def test_parse_int_field(self):
320 f = self._field('field public int NAME = 123;')
321 self.assertTrue('field' in f.split)
322 self.assertEquals('int', f.typ)
323 self.assertEquals('NAME', f.name)
324 self.assertEquals('123', f.value)
325
326 def test_parse_quotient_field(self):
327 f = self._field('field public int NAME = (0.0/0.0);')
328 self.assertTrue('field' in f.split)
329 self.assertEquals('int', f.typ)
330 self.assertEquals('NAME', f.name)
331 self.assertEquals('( 0.0 / 0.0 )', f.value)
332
Adrian Roos5cdfb692019-01-05 22:04:55 +0100333 def test_kotlin_types(self):
334 self._field('field public List<Integer[]?[]!>?[]![]? NAME;')
335 self._method("method <T?> Class<T!>?[]![][]? name(Type!, Type argname,"
336 + "Class<T?>[][]?[]!...!) throws Exception, T;")
337 self._method("method <T> T name(T a = 1, T b = A(1), Lambda f = { false }, N? n = null, "
338 + """double c = (1/0), float d = 1.0f, String s = "heyo", char c = 'a');""")
339
Adrian Roosd1e38922019-01-14 15:44:15 +0100340 def test_kotlin_operator(self):
341 self._method('method public operator void unaryPlus(androidx.navigation.NavDestination);')
342 self._method('method public static operator androidx.navigation.NavDestination get(androidx.navigation.NavGraph, @IdRes int id);')
343 self._method('method public static operator <T> T get(androidx.navigation.NavigatorProvider, kotlin.reflect.KClass<T> clazz);')
344
345 def test_kotlin_property(self):
346 self._field('property public VM value;')
347 self._field('property public final String? action;')
348
349 def test_kotlin_varargs(self):
350 self._method('method public void error(int p = "42", Integer int2 = "null", int p1 = "42", vararg String args);')
351
352 def test_kotlin_default_values(self):
353 self._method('method public void foo(String! = null, String! = "Hello World", int = 42);')
354 self._method('method void method(String, String firstArg = "hello", int secondArg = "42", String thirdArg = "world");')
355 self._method('method void method(String, String firstArg = "hello", int secondArg = "42");')
356 self._method('method void method(String, String firstArg = "hello");')
357 self._method('method void edit(android.Type, boolean commit = false, Function1<? super Editor,kotlin.Unit> action);')
358 self._method('method <K, V> LruCache<K,V> lruCache(int maxSize, Function2<? super K,? super V,java.lang.Integer> sizeOf = { _, _ -> 1 }, Function1<? extends V> create = { (V)null }, Function4<kotlin.Unit> onEntryRemoved = { _, _, _, _ -> });')
359 self._method('method android.Bitmap? drawToBitmap(android.View, android.Config config = android.graphics.Bitmap.Config.ARGB_8888);')
360 self._method('method void emptyLambda(Function0<kotlin.Unit> sizeOf = {});')
361 self._method('method void method1(int p = 42, Integer? int2 = null, int p1 = 42, String str = "hello world", java.lang.String... args);')
362 self._method('method void method2(int p, int int2 = (2 * int) * some.other.pkg.Constants.Misc.SIZE);')
363 self._method('method void method3(String str, int p, int int2 = double(int) + str.length);')
364 self._method('method void print(test.pkg.Foo foo = test.pkg.Foo());')
365
366 def test_type_use_annotation(self):
367 self._method('method public static int codePointAt(char @NonNull [], int);')
368 self._method('method @NonNull public java.util.Set<java.util.Map.@NonNull Entry<K,V>> entrySet();')
369
370 m = self._method('method @NonNull public java.lang.annotation.@NonNull Annotation @NonNull [] getAnnotations();')
371 self.assertEquals('java.lang.annotation.Annotation[]', m.typ)
372
373 m = self._method('method @NonNull public abstract java.lang.annotation.@NonNull Annotation @NonNull [] @NonNull [] getParameterAnnotations();')
374 self.assertEquals('java.lang.annotation.Annotation[][]', m.typ)
375
376 m = self._method('method @NonNull public @NonNull String @NonNull [] split(@NonNull String, int);')
377 self.assertEquals('java.lang.String[]', m.typ)
378
Adrian Roosb1faa0b2019-02-26 11:54:40 +0100379class PackageTests(unittest.TestCase):
380 def _package(self, raw):
381 return apilint.Package(123, raw, "blame")
382
383 def test_regular_package(self):
384 p = self._package("package an.pref.int {")
385 self.assertEquals('an.pref.int', p.name)
386
387 def test_annotation_package(self):
388 p = self._package("package @RestrictTo(a.b.C) an.pref.int {")
389 self.assertEquals('an.pref.int', p.name)
390
391 def test_multi_annotation_package(self):
392 p = self._package("package @Rt(a.b.L_G_P) @RestrictTo(a.b.C) an.pref.int {")
393 self.assertEquals('an.pref.int', p.name)
394
Adrian Roos5ed42b62018-12-19 17:10:22 +0100395if __name__ == "__main__":
Adrian Roosb787c182019-01-03 18:54:33 +0100396 unittest.main()