blob: c10ef15d02ad8d1d4e54007b63510d1f9598c80a [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 = """
91package android.app {
92 public final class Activity {
93 }
94
95 public final class WallpaperColors implements android.os.Parcelable {
96 ctor public WallpaperColors(android.os.Parcel);
97 method public int describeContents();
98 method public void writeToParcel(android.os.Parcel, int);
99 field public static final android.os.Parcelable.Creator<android.app.WallpaperColors> CREATOR;
100 }
101}
102""".split('\n')
103
104ok_current_txt = """
105package android.app {
106 public final class Activity {
107 }
108
109 public final class WallpaperColors implements android.os.Parcelable {
110 ctor public WallpaperColors();
111 method public int describeContents();
112 method public void writeToParcel(android.os.Parcel, int);
113 field public static final android.os.Parcelable.Creator<android.app.WallpaperColors> CREATOR;
114 }
115}
116""".split('\n')
117
118system_current_txt = """
119package android.app {
120 public final class WallpaperColors implements android.os.Parcelable {
121 method public int getSomething();
122 }
123}
124""".split('\n')
125
126
127
128class BaseFileTests(unittest.TestCase):
129 def test_base_file_avoids_errors(self):
130 failures, _ = apilint.examine_stream(system_current_txt, ok_current_txt)
131 self.assertEquals(failures, {})
132
133 def test_class_with_base_finds_same_errors(self):
134 failures_with_classes_with_base, _ = apilint.examine_stream("", faulty_current_txt,
135 in_classes_with_base=[cls("android.app", "WallpaperColors")])
136 failures_with_system_txt, _ = apilint.examine_stream(system_current_txt, faulty_current_txt)
137
138 self.assertEquals(failures_with_classes_with_base.keys(), failures_with_system_txt.keys())
139
140 def test_classes_with_base_is_emited(self):
141 classes_with_base = []
142 _, _ = apilint.examine_stream(system_current_txt, faulty_current_txt,
143 out_classes_with_base=classes_with_base)
144 self.assertEquals(map(lambda x: x.fullname, classes_with_base), ["android.app.WallpaperColors"])
145
Adrian Roos258c5722019-01-21 15:43:15 +0100146class ParseV2Stream(unittest.TestCase):
147 def test_field_kinds(self):
148 api = apilint._parse_stream("""
149// Signature format: 2.0
150package android {
151 public enum SomeEnum {
152 enum_constant public static final android.SomeEnum ENUM_CONST;
153 field public static final int FIELD_CONST;
154 property public final int someProperty;
155 ctor public SomeEnum();
156 method public Object? getObject();
157 }
158}
159 """.strip().split('\n'))
160
161 self.assertEquals(api['android.SomeEnum'].fields[0].split[0], 'enum_constant')
162 self.assertEquals(api['android.SomeEnum'].fields[1].split[0], 'field')
163 self.assertEquals(api['android.SomeEnum'].fields[2].split[0], 'property')
164 self.assertEquals(api['android.SomeEnum'].ctors[0].split[0], 'ctor')
165 self.assertEquals(api['android.SomeEnum'].methods[0].split[0], 'method')
166
Adrian Rooscf82e042019-01-29 15:01:28 +0100167class ParseV3Stream(unittest.TestCase):
168 def test_field_kinds(self):
169 api = apilint._parse_stream("""
170// Signature format: 3.0
171package a {
172
173 public final class ContextKt {
174 method public static inline <reified T> T! getSystemService(android.content.Context);
175 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);
176 }
177}
178 """.strip().split('\n'))
179 self.assertEquals(api['a.ContextKt'].methods[0].name, 'getSystemService')
180 self.assertEquals(api['a.ContextKt'].methods[0].split[:4], ['method', 'public', 'static', 'inline'])
181 self.assertEquals(api['a.ContextKt'].methods[1].name, 'withStyledAttributes')
182 self.assertEquals(api['a.ContextKt'].methods[1].split[:4], ['method', 'public', 'static', 'inline'])
183
Adrian Roosb787c182019-01-03 18:54:33 +0100184class V2TokenizerTests(unittest.TestCase):
185 def _test(self, raw, expected):
186 self.assertEquals(apilint.V2Tokenizer(raw).tokenize(), expected)
187
188 def test_simple(self):
189 self._test(" method public some.Type someName(some.Argument arg, int arg);",
190 ['method', 'public', 'some.Type', 'someName', '(', 'some.Argument',
191 'arg', ',', 'int', 'arg', ')', ';'])
192 self._test("class Some.Class extends SomeOther {",
193 ['class', 'Some.Class', 'extends', 'SomeOther', '{'])
194
Adrian Roos5cdfb692019-01-05 22:04:55 +0100195 def test_varargs(self):
196 self._test("name(String...)",
197 ['name', '(', 'String', '...', ')'])
198
199 def test_kotlin(self):
200 self._test("String? name(String!...)",
201 ['String', '?', 'name', '(', 'String', '!', '...', ')'])
202
Adrian Roosb787c182019-01-03 18:54:33 +0100203 def test_annotation(self):
204 self._test("method @Nullable public void name();",
205 ['method', '@', 'Nullable', 'public', 'void', 'name', '(', ')', ';'])
206
207 def test_annotation_args(self):
208 self._test("@Some(val=1, other=2) class Class {",
209 ['@', 'Some', '(', 'val', '=', '1', ',', 'other', '=', '2', ')',
210 'class', 'Class', '{'])
211 def test_comment(self):
212 self._test("some //comment", ['some'])
213
214 def test_strings(self):
215 self._test(r'"" "foo" "\"" "\\"', ['""', '"foo"', r'"\""', r'"\\"'])
216
217 def test_at_interface(self):
218 self._test("public @interface Annotation {",
219 ['public', '@interface', 'Annotation', '{'])
220
221 def test_array_type(self):
222 self._test("int[][]", ['int', '[]', '[]'])
223
224 def test_generics(self):
225 self._test("<>foobar<A extends Object>",
226 ['<', '>', 'foobar', '<', 'A', 'extends', 'Object', '>'])
227
228class V2ParserTests(unittest.TestCase):
229 def _cls(self, raw):
230 pkg = apilint.Package(999, "package pkg {", None)
231 return apilint.Class(pkg, 1, raw, '', sig_format=2)
232
233 def _method(self, raw, cls=None):
234 if not cls:
235 cls = self._cls("class Class {")
236 return apilint.Method(cls, 1, raw, '', sig_format=2)
237
238 def _field(self, raw):
239 cls = self._cls("class Class {")
240 return apilint.Field(cls, 1, raw, '', sig_format=2)
241
242 def test_class(self):
243 cls = self._cls("@Deprecated @IntRange(from=1, to=2) public static abstract class Some.Name extends Super<Class> implements Interface<Class> {")
244 self.assertTrue('deprecated' in cls.split)
245 self.assertTrue('static' in cls.split)
246 self.assertTrue('abstract' in cls.split)
247 self.assertTrue('class' in cls.split)
248 self.assertEquals('Super', cls.extends)
249 self.assertEquals('Interface', cls.implements)
250 self.assertEquals('pkg.Some.Name', cls.fullname)
251
Adrian Roos258c5722019-01-21 15:43:15 +0100252 def test_enum(self):
253 cls = self._cls("public enum Some.Name {")
254 self._field("enum_constant public static final android.ValueType COLOR;")
255
Adrian Roosb787c182019-01-03 18:54:33 +0100256 def test_interface(self):
257 cls = self._cls("@Deprecated @IntRange(from=1, to=2) public interface Some.Name extends Interface<Class> {")
258 self.assertTrue('deprecated' in cls.split)
259 self.assertTrue('interface' in cls.split)
260 self.assertEquals('Interface', cls.extends)
261 self.assertEquals('Interface', cls.implements)
262 self.assertEquals('pkg.Some.Name', cls.fullname)
263
264 def test_at_interface(self):
265 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 {")
266 self.assertTrue('@interface' in cls.split)
267 self.assertEquals('pkg.SuppressLint', cls.fullname)
268
269 def test_parse_method(self):
Adrian Roosd1e38922019-01-14 15:44:15 +0100270 m = self._method("method @Deprecated public static native <T> Class<T>[][] name("
Adrian Roosb787c182019-01-03 18:54:33 +0100271 + "Class<T[]>[][], Class<T[][][]>[][]...) throws Exception, T;")
272 self.assertTrue('static' in m.split)
273 self.assertTrue('public' in m.split)
274 self.assertTrue('method' in m.split)
Adrian Roosd1e38922019-01-14 15:44:15 +0100275 self.assertTrue('native' in m.split)
Adrian Roosb787c182019-01-03 18:54:33 +0100276 self.assertTrue('deprecated' in m.split)
277 self.assertEquals('java.lang.Class[][]', m.typ)
278 self.assertEquals('name', m.name)
279 self.assertEquals(['java.lang.Class[][]', 'java.lang.Class[][]...'], m.args)
280 self.assertEquals(['java.lang.Exception', 'T'], m.throws)
281
282 def test_ctor(self):
283 m = self._method("ctor @Deprecated <T> ClassName();")
284 self.assertTrue('ctor' in m.split)
285 self.assertTrue('deprecated' in m.split)
286 self.assertEquals('ctor', m.typ)
287 self.assertEquals('ClassName', m.name)
288
289 def test_parse_annotation_method(self):
290 cls = self._cls("@interface Annotation {")
291 self._method('method abstract String category() default "";', cls=cls)
292 self._method('method abstract boolean deepExport() default false;', cls=cls)
293 self._method('method abstract ViewDebug.FlagToString[] flagMapping() default {};', cls=cls)
Adrian Roosd1e38922019-01-14 15:44:15 +0100294 self._method('method abstract ViewDebug.FlagToString[] flagMapping() default (double)java.lang.Float.NEGATIVE_INFINITY;', cls=cls)
Adrian Roosb787c182019-01-03 18:54:33 +0100295
296 def test_parse_string_field(self):
297 f = self._field('field @Deprecated public final String SOME_NAME = "value";')
298 self.assertTrue('field' in f.split)
299 self.assertTrue('deprecated' in f.split)
300 self.assertTrue('final' in f.split)
301 self.assertEquals('java.lang.String', f.typ)
302 self.assertEquals('SOME_NAME', f.name)
303 self.assertEquals('value', f.value)
304
305 def test_parse_field(self):
306 f = self._field('field public Object SOME_NAME;')
307 self.assertTrue('field' in f.split)
308 self.assertEquals('java.lang.Object', f.typ)
309 self.assertEquals('SOME_NAME', f.name)
310 self.assertEquals(None, f.value)
311
312 def test_parse_int_field(self):
313 f = self._field('field public int NAME = 123;')
314 self.assertTrue('field' in f.split)
315 self.assertEquals('int', f.typ)
316 self.assertEquals('NAME', f.name)
317 self.assertEquals('123', f.value)
318
319 def test_parse_quotient_field(self):
320 f = self._field('field public int NAME = (0.0/0.0);')
321 self.assertTrue('field' in f.split)
322 self.assertEquals('int', f.typ)
323 self.assertEquals('NAME', f.name)
324 self.assertEquals('( 0.0 / 0.0 )', f.value)
325
Adrian Roos5cdfb692019-01-05 22:04:55 +0100326 def test_kotlin_types(self):
327 self._field('field public List<Integer[]?[]!>?[]![]? NAME;')
328 self._method("method <T?> Class<T!>?[]![][]? name(Type!, Type argname,"
329 + "Class<T?>[][]?[]!...!) throws Exception, T;")
330 self._method("method <T> T name(T a = 1, T b = A(1), Lambda f = { false }, N? n = null, "
331 + """double c = (1/0), float d = 1.0f, String s = "heyo", char c = 'a');""")
332
Adrian Roosd1e38922019-01-14 15:44:15 +0100333 def test_kotlin_operator(self):
334 self._method('method public operator void unaryPlus(androidx.navigation.NavDestination);')
335 self._method('method public static operator androidx.navigation.NavDestination get(androidx.navigation.NavGraph, @IdRes int id);')
336 self._method('method public static operator <T> T get(androidx.navigation.NavigatorProvider, kotlin.reflect.KClass<T> clazz);')
337
338 def test_kotlin_property(self):
339 self._field('property public VM value;')
340 self._field('property public final String? action;')
341
342 def test_kotlin_varargs(self):
343 self._method('method public void error(int p = "42", Integer int2 = "null", int p1 = "42", vararg String args);')
344
345 def test_kotlin_default_values(self):
346 self._method('method public void foo(String! = null, String! = "Hello World", int = 42);')
347 self._method('method void method(String, String firstArg = "hello", int secondArg = "42", String thirdArg = "world");')
348 self._method('method void method(String, String firstArg = "hello", int secondArg = "42");')
349 self._method('method void method(String, String firstArg = "hello");')
350 self._method('method void edit(android.Type, boolean commit = false, Function1<? super Editor,kotlin.Unit> action);')
351 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 = { _, _, _, _ -> });')
352 self._method('method android.Bitmap? drawToBitmap(android.View, android.Config config = android.graphics.Bitmap.Config.ARGB_8888);')
353 self._method('method void emptyLambda(Function0<kotlin.Unit> sizeOf = {});')
354 self._method('method void method1(int p = 42, Integer? int2 = null, int p1 = 42, String str = "hello world", java.lang.String... args);')
355 self._method('method void method2(int p, int int2 = (2 * int) * some.other.pkg.Constants.Misc.SIZE);')
356 self._method('method void method3(String str, int p, int int2 = double(int) + str.length);')
357 self._method('method void print(test.pkg.Foo foo = test.pkg.Foo());')
358
359 def test_type_use_annotation(self):
360 self._method('method public static int codePointAt(char @NonNull [], int);')
361 self._method('method @NonNull public java.util.Set<java.util.Map.@NonNull Entry<K,V>> entrySet();')
362
363 m = self._method('method @NonNull public java.lang.annotation.@NonNull Annotation @NonNull [] getAnnotations();')
364 self.assertEquals('java.lang.annotation.Annotation[]', m.typ)
365
366 m = self._method('method @NonNull public abstract java.lang.annotation.@NonNull Annotation @NonNull [] @NonNull [] getParameterAnnotations();')
367 self.assertEquals('java.lang.annotation.Annotation[][]', m.typ)
368
369 m = self._method('method @NonNull public @NonNull String @NonNull [] split(@NonNull String, int);')
370 self.assertEquals('java.lang.String[]', m.typ)
371
Adrian Roosb1faa0b2019-02-26 11:54:40 +0100372class PackageTests(unittest.TestCase):
373 def _package(self, raw):
374 return apilint.Package(123, raw, "blame")
375
376 def test_regular_package(self):
377 p = self._package("package an.pref.int {")
378 self.assertEquals('an.pref.int', p.name)
379
380 def test_annotation_package(self):
381 p = self._package("package @RestrictTo(a.b.C) an.pref.int {")
382 self.assertEquals('an.pref.int', p.name)
383
384 def test_multi_annotation_package(self):
385 p = self._package("package @Rt(a.b.L_G_P) @RestrictTo(a.b.C) an.pref.int {")
386 self.assertEquals('an.pref.int', p.name)
387
Adrian Roos5ed42b62018-12-19 17:10:22 +0100388if __name__ == "__main__":
Adrian Roosb787c182019-01-03 18:54:33 +0100389 unittest.main()