1# Copyright 2017, The Android Open Source Project
2#
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7# http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14
15
16"""Generates necessary files for unit test versions for testing.
17
18After adding/changing RenderScript unit tests, run `python RSUnitTests.py`
19to ensure that forward/backward compatibility tests run properly.
20
21This file is so when updating/adding unit tests there is one central location
22for managing the list of unit tests and their versions.
23
24This is necessary since forward compatibility unit tests are chosen at compile
25time where backward compatibility tests are chosen at runtime.
26
27Generates a Java file for backward compatibility testing.
28Generates an Android.mk file for forward compatibility testing.
29"""
30
31
32import shutil
33import sys
34import os
35
36
37# List of platform API versions and the tests that pass on that version as
38# well as all newer versions (e.g. tests under 23 also pass on 24, 25, etc.).
39# The Slang version that correctly compiles the test is assumed to be the
40# same build tools version unless otherwise specified in
41# UNIT_TEST_TOOLS_VERSIONS below.
42# The test name must correspond to a UT_{}.java file.
43# e.g. alloc -> UT_alloc.java
44UNIT_TEST_PLATFORM_VERSIONS = {
45    19: [
46        'alloc',
47        'array_alloc',
48        'array_init',
49        'atomic',
50        'bitfield',
51        'bug_char',
52        'check_dims',
53        'clamp_relaxed',
54        'clamp',
55        'constant',
56        'convert_relaxed',
57        'convert',
58        'copy_test',
59        'element',
60        'foreach',
61        'foreach_bounds',
62        'fp_mad',
63        'instance',
64        'int4',
65        'kernel',
66        'kernel_struct',
67        'math',
68        'min',
69        'noroot',
70        'primitives',
71        'refcount',
72        'reflection3264',
73        'rsdebug',
74        'rstime',
75        'rstypes',
76        'sampler',
77        'static_globals',
78        'struct',
79        'unsigned',
80        'vector',
81    ],
82
83    21: [
84        'foreach_multi',
85        'math_agree',
86        'math_conformance',
87    ],
88
89    23: [
90        'alloc_copy',
91        'alloc_copyPadded',
92        'ctxt_default',
93        'kernel2d',
94        'kernel2d_oldstyle',
95        'kernel3d',
96        'rsdebug_23',
97        'script_group2_gatherscatter',
98        'script_group2_nochain',
99        'script_group2_pointwise',
100    ],
101
102    24: [
103        'fp16',
104        'fp16_globals',
105        'math_24',
106        'math_fp16',
107        'reduce_backward',
108        'reduce',
109        'rsdebug_24',
110        'script_group2_float',
111        'single_source_alloc',
112        'single_source_ref_count',
113        'single_source_script',
114        'small_struct',
115        'small_struct_2',
116    ],
117
118    26: [
119        'blur_validation',
120        'struct_field',
121        'struct_field_simple',
122    ],
123}
124
125
126# List of tests and the build tools version they compile correctly on.
127# The build tools version is the earliest build tools version that can
128# compile it correctly, all versions newer than that version are also
129# expected to compile correctly.
130# Only to override the platform version in UNIT_TEST_PLATFORM_VERSIONS.
131# Only affects forward compatibility tests.
132# Useful for Slang regression fixes.
133UNIT_TEST_TOOLS_VERSIONS = {
134    'small_struct': 26,
135    'reflection3264': 26,
136}
137
138
139# Tests that only belong to RSTest_Compat (support lib tests)
140SUPPORT_LIB_ONLY_UNIT_TESTS = {
141    'alloc_supportlib',
142    'apitest',
143}
144
145
146# Tests that are skipped in RSTest_Compat (support lib tests)
147SUPPORT_LIB_IGNORE_TESTS = {
148    'fp16',
149    'fp16_globals',
150    'math_fp16',
151}
152
153
154# Dictionary mapping unit tests to the corresponding needed .rs files
155# Only needed if UT_{}.java does not map to {}.rs
156UNIT_TEST_RS_FILES_OVERRIDE = {
157    'alloc_copy': [],
158    'alloc_copyPadded': [],
159    'blur_validation': [],
160    'script_group2_float': ['float_test.rs'],
161    'script_group2_gatherscatter': ['addup.rs'],
162    'script_group2_nochain': ['increment.rs', 'increment2.rs', 'double.rs'],
163    'script_group2_pointwise': ['increment.rs', 'double.rs'],
164}
165
166
167# List of API versions and the corresponding build tools release version
168# For use with forward compatibility testing
169BUILD_TOOL_VERSIONS = {
170    21: '21.1.2',
171    22: '22.0.1',
172    23: '23.0.3',
173    24: '24.0.3',
174    25: '25.0.2',
175}
176
177
178# ---------- Makefile generation ----------
179
180
181def WriteMakeCopyright(gen_file):
182  """Writes the copyright for a Makefile to a file."""
183  gen_file.write(
184      '#\n'
185      '# Copyright (C) 2017 The Android Open Source Project\n'
186      '#\n'
187      '# Licensed under the Apache License, Version 2.0 (the "License");\n'
188      '# you may not use this file except in compliance with the License.\n'
189      '# You may obtain a copy of the License at\n'
190      '#\n'
191      '#      http://www.apache.org/licenses/LICENSE-2.0\n'
192      '#\n'
193      '# Unless required by applicable law or agreed to in writing, software\n'
194      '# distributed under the License is distributed on an "AS IS" BASIS,\n'
195      '# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n'
196      '# See the License for the specific language governing permissions and\n'
197      '# limitations under the License.\n'
198      '#\n\n'
199  )
200
201
202def WriteMakeSrcFiles(gen_file, api_version, src_dirs=['src'],
203                      use_build_tools_version=False):
204  """Writes applicable LOCAL_SRC_FILES to gen_file.
205
206  Includes everything under ./src, base UnitTest class, and test files.
207
208  api_version: only tests that can run on this version are added."""
209  # Get all tests compatible with the build tool version
210  # Compatible means build tool version >= test version
211  tests = []
212  for test_version, tests_for_version in (
213      UNIT_TEST_PLATFORM_VERSIONS.iteritems()):
214    if api_version >= test_version:
215      tests.extend(tests_for_version)
216  if use_build_tools_version:
217    tests = [x for x in tests if (x not in UNIT_TEST_TOOLS_VERSIONS or
218                                  test_version >= UNIT_TEST_TOOLS_VERSIONS[x])]
219  tests = sorted(tests)
220  gen_file.write(
221      'LOCAL_SRC_FILES :=\\\n'
222  )
223  for src_dir in src_dirs:
224    gen_file.write('    $(call all-java-files-under,{})\\\n'.format(src_dir))
225
226  gen_file.write(
227      '    $(my_rs_unit_tests_path)/UnitTest.java\\\n'.format(src_dir)
228  )
229  for test in tests:
230    # Add the Java and corresponding rs files to LOCAL_SRC_FILES
231    gen_file.write(
232        '    $(my_rs_unit_tests_path)/{}\\\n'.format(JavaFileForUnitTest(test))
233    )
234    for rs_file in RSFilesForUnitTest(test):
235      gen_file.write('    $(my_rs_unit_tests_path)/{}\\\n'.format(rs_file))
236
237
238# ---------- Java file generation ----------
239
240
241def WriteJavaCopyright(gen_file):
242  """Writes the copyright for a Java file to gen_file."""
243  gen_file.write(
244      '/*\n'
245      ' * Copyright (C) 2017 The Android Open Source Project\n'
246      ' *\n'
247      ' * Licensed under the Apache License, Version 2.0 (the "License");\n'
248      ' * you may not use this file except in compliance with the License.\n'
249      ' * You may obtain a copy of the License at\n'
250      ' *\n'
251      ' *      http://www.apache.org/licenses/LICENSE-2.0\n'
252      ' *\n'
253      ' * Unless required by applicable law or agreed to in writing, software\n'
254      ' * distributed under the License is distributed on an "AS IS" BASIS,\n'
255      ' * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n'
256      ' * See the License for the specific language governing permissions and\n'
257      ' * limitations under the License.\n'
258      ' */\n\n'
259  )
260
261
262# ---------- Unit Test file functions ----------
263
264
265def JavaFileForUnitTest(test):
266  """Returns the Java file name for a unit test."""
267  return 'UT_{}.java'.format(test)
268
269
270def RSFilesForUnitTest(test):
271  """Returns a list of .rs files associated with a test."""
272  if test in UNIT_TEST_RS_FILES_OVERRIDE:
273    return UNIT_TEST_RS_FILES_OVERRIDE[test]
274  else:
275    # Default is one .rs file with the same name as the input
276    return ['{}.rs'.format(test)]
277
278
279# ---------- Dirs ----------
280
281
282def ThisScriptDir():
283  """Returns the directory this script is in."""
284  return os.path.dirname(os.path.realpath(__file__))
285
286
287def UnitTestDir():
288  """Returns the path to the directory containing the unit tests."""
289  return os.path.join(ThisScriptDir(), 'src', 'com', 'android', 'rs',
290                      'unittest')
291
292
293def SupportLibOnlyTestDir():
294  """Returns the path to the directory with unit tests for support lib."""
295  return os.path.join(ThisScriptDir(), 'supportlibonlysrc', 'com',
296                      'android', 'rs', 'unittest')
297
298
299def SupportLibGenTestDir():
300  """Returns the path to the directory with unit tests for support lib."""
301  return os.path.join(ThisScriptDir(), 'supportlibsrc_gen', 'com',
302                      'android', 'rs', 'unittest')
303
304
305# ---------- RSTest_Compat/RSTest_Compat19 test generation ----------
306
307
308def AllUnitTestsExceptSupportLibOnly():
309  """Returns a set of all unit tests except SUPPORT_LIB_ONLY_UNIT_TESTS."""
310  ret = set()
311  for _, tests in UNIT_TEST_PLATFORM_VERSIONS.iteritems():
312    ret.update(tests)
313  return ret
314
315
316def CopyUnitTestJavaFileToSupportLibTest(java_file_name, java_file_dir):
317  """Copies the Java file to the support lib dir.
318
319  Replaces RenderScript imports with corresponding support lib imports."""
320  in_path = os.path.join(java_file_dir, java_file_name)
321  out_path = os.path.join(SupportLibGenTestDir(), java_file_name)
322  with open(in_path, 'r') as in_file, open(out_path, 'w') as out_file:
323    out_file.write(
324        '// This file is automatically generated from\n'
325        '// frameworks/rs/tests/java_api/RSUnitTests/RSUnitTests.py\n'
326    )
327    for line in in_file.readlines():
328      if line.startswith('import android.renderscript.'):
329        line = line.replace('android.renderscript.',
330                            'androidx.renderscript.')
331      out_file.write(line)
332
333
334def CopyUnitTestRSToSupportLibTest(rs_file_name, rs_file_dir):
335  """Copies the .rs to the support lib dir."""
336  in_path = os.path.join(rs_file_dir, rs_file_name)
337  out_path = os.path.join(SupportLibGenTestDir(), rs_file_name)
338  with open(out_path, 'w') as out_file:
339    out_file.write(
340        '// This file is automatically generated from\n'
341        '// frameworks/rs/tests/java_api/RSUnitTests/RSUnitTests.py\n'
342    )
343    with open(in_path, 'r') as in_file:
344      out_file.write(in_file.read())
345
346
347def CopySharedRshToSupportLibTest():
348  """Copies shared.rsh to the support lib dir.
349
350  Adds a #define RSTEST_COMPAT at the end."""
351  shared_rsh = 'shared.rsh'
352  CopyUnitTestRSToSupportLibTest(shared_rsh, UnitTestDir())
353  with open(os.path.join(SupportLibGenTestDir(), shared_rsh), 'a') as shared:
354    shared.write('\n#define RSTEST_COMPAT\n')
355
356
357def CopyUnitTestToSupportLibTest(test, test_dir):
358  """Copies all files corresponding to a unit test to support lib dir."""
359  CopyUnitTestJavaFileToSupportLibTest(JavaFileForUnitTest(test), test_dir)
360  for rs in RSFilesForUnitTest(test):
361    CopyUnitTestRSToSupportLibTest(rs, test_dir)
362
363
364def GenerateSupportLibUnitTests():
365  """Generates all support lib unit tests."""
366  if os.path.exists(SupportLibGenTestDir()):
367    shutil.rmtree(SupportLibGenTestDir())
368  os.makedirs(SupportLibGenTestDir())
369
370  CopySharedRshToSupportLibTest()
371  CopyUnitTestJavaFileToSupportLibTest('UnitTest.java', UnitTestDir())
372
373  for test in AllUnitTestsExceptSupportLibOnly() - SUPPORT_LIB_IGNORE_TESTS:
374    CopyUnitTestToSupportLibTest(test, UnitTestDir())
375
376  for test in SUPPORT_LIB_ONLY_UNIT_TESTS:
377    CopyUnitTestToSupportLibTest(test, SupportLibOnlyTestDir())
378
379  print ('Generated support lib tests at {}'
380         .format(SupportLibGenTestDir()))
381
382
383# ---------- RSTest_Compat19 ----------
384
385
386def WriteSupportLib19Makefile(gen_file):
387  """Writes the Makefile for support lib 19 testing."""
388  WriteMakeCopyright(gen_file)
389  gen_file.write(
390      '# This file is auto-generated by frameworks/rs/tests/java_api/RSUnitTests/RSUnitTests.py.\n'
391      '# To change unit tests version, please run the Python script above.\n\n'
392      'LOCAL_PATH := $(call my-dir)\n'
393      'include $(CLEAR_VARS)\n\n'
394      'LOCAL_PACKAGE_NAME := RSTest_Compat19\n'
395      'LOCAL_MODULE_TAGS := tests\n\n'
396      'LOCAL_STATIC_JAVA_LIBRARIES := \\\n'
397      '    android-support-test \\\n'
398      '    android-support-v8-renderscript \\\n\n'
399      'LOCAL_RENDERSCRIPT_TARGET_API := 19\n'
400      'LOCAL_RENDERSCRIPT_COMPATIBILITY := true\n'
401      'LOCAL_RENDERSCRIPT_FLAGS := -rs-package-name=androidx.renderscript\n'
402      'LOCAL_SDK_VERSION := current\n'
403      'LOCAL_MIN_SDK_VERSION := 8\n\n'
404      'my_rs_unit_tests_path := ../RSUnitTests/supportlibsrc_gen/com/android/rs/unittest\n'
405  )
406  WriteMakeSrcFiles(gen_file, 19)
407  gen_file.write(
408      '\n'
409      'include $(BUILD_PACKAGE)\n\n'
410      'my_rs_unit_tests_path :=\n\n'
411  )
412
413
414def SupportLib19MakefileLocation():
415  """Returns the location of Makefile for backward compatibility 19 testing."""
416  return os.path.join(ThisScriptDir(), '..', 'RSTest_CompatLib19', 'Android.mk')
417
418
419def GenerateSupportLib19():
420  """Generates the necessary file for Support Library tests (19)."""
421  with open(SupportLib19MakefileLocation(), 'w') as gen_file:
422    WriteSupportLib19Makefile(gen_file)
423  print ('Generated support lib (19) Makefile at {}'
424         .format(SupportLib19MakefileLocation()))
425
426
427# ---------- RSTestForward ----------
428
429
430def ForwardTargetName(build_tool_version_name):
431  """Returns the target name for a forward compatibility build tool name."""
432  make_target_name = 'RSTestForward_{}'.format(build_tool_version_name)
433  make_target_name = make_target_name.replace('.', '_')
434  return make_target_name
435
436
437def ForwardDirLocation(build_tool_version_name):
438  """Returns location of directory for forward compatibility testing."""
439  return os.path.join(ThisScriptDir(), '..', 'RSTestForward',
440                      build_tool_version_name)
441
442
443def ForwardJavaSrcLocation(build_tool_version_name):
444  """Returns location of src directory for forward compatibility testing."""
445  return os.path.join(ForwardDirLocation(build_tool_version_name), 'src')
446
447
448def ForwardMakefileLocation(build_tool_version_name):
449  """Returns the location of the Makefile for forward compatibility testing."""
450  return os.path.join(ForwardDirLocation(build_tool_version_name),
451                      'Android.mk')
452
453
454def ForwardAndroidManifestLocation(build_tool_version_name):
455  """Returns AndroidManifest.xml location for forward compatibility testing."""
456  return os.path.join(ForwardDirLocation(build_tool_version_name),
457                      'AndroidManifest.xml')
458
459
460def ForwardJavaApiVersionLocation(build_tool_version_name):
461  """Returns Java version file location for forward compatibility testing."""
462  return os.path.join(ForwardJavaSrcLocation(build_tool_version_name),
463                      'RSForwardVersion.java')
464
465
466def WriteForwardAndroidManifest(gen_file, package):
467  """Writes forward compatibility AndroidManifest.xml to gen_file."""
468  gen_file.write(
469      '<?xml version="1.0" encoding="utf-8"?>\n'
470      '<!-- Copyright (C) 2017 The Android Open Source Project\n'
471      '\n'
472      '     Licensed under the Apache License, Version 2.0 (the "License");\n'
473      '     you may not use this file except in compliance with the License.\n'
474      '     You may obtain a copy of the License at\n'
475      '\n'
476      '          http://www.apache.org/licenses/LICENSE-2.0\n'
477      '\n'
478      '     Unless required by applicable law or agreed to in writing, software\n'
479      '     distributed under the License is distributed on an "AS IS" BASIS,\n'
480      '     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n'
481      '     See the License for the specific language governing permissions and\n'
482      '     limitations under the License.\n'
483      '\n'
484      '     This file is automatically generated by\n'
485      '     frameworks/rs/tests/java_api/RSUnitTests/RSUnitTests.py.\n'
486      '-->\n'
487      '<manifest xmlns:android="http://schemas.android.com/apk/res/android"\n'
488      '    package="{}">\n'
489      '    <uses-sdk\n'
490      '        android:minSdkVersion="21"\n'
491      '        android:targetSdkVersion="26" />\n'
492      '\n'
493      '    <application\n'
494      '        android:label="RSTestForward">\n'
495      '        <uses-library android:name="android.test.runner" />\n'
496      '    </application>\n'
497      '\n'
498      '    <instrumentation\n'
499      '        android:name="androidx.test.runner.AndroidJUnitRunner"\n'
500      '        android:targetPackage="{}"\n'
501      '        android:label="RenderScript Forward Compatibility Tests" />\n'
502      '</manifest>\n'.format(package, package)
503  )
504
505
506def WriteForwardToolsVersion(gen_file, version):
507  """Writes forward compatibility Java class with tools version as String."""
508  WriteJavaCopyright(gen_file)
509  gen_file.write(
510      'package com.android.rs.testforward;\n\n'
511      'public class RSForwardVersion {{\n'
512      '    public static final String VERSION = "{}";\n'
513      '}}\n'.format(version)
514  )
515
516
517def WriteForwardMakefile(gen_file, build_tool_version, build_tool_version_name):
518  """Writes the Makefile for forward compatibility testing.
519
520  Makefile contains a build target per build tool version
521  for forward compatibility testing based on the unit test list at the
522  top of this file."""
523  WriteMakeCopyright(gen_file)
524  gen_file.write(
525      '# This file is auto-generated by frameworks/rs/tests/java_api/RSUnitTests/RSUnitTests.py.\n'
526      '# To change unit tests version, please run the Python script above.\n\n'
527      'ifneq ($(ENABLE_RSTESTS),)\n\n'
528      'LOCAL_PATH := $(call my-dir)\n'
529      'my_rs_unit_tests_path := ../../RSUnitTests/src/com/android/rs/unittest\n'
530  )
531  make_target_name = ForwardTargetName(build_tool_version_name)
532  gen_file.write(
533      '\n'
534      '# RSTestForward for build tool version {}\n\n'
535      'include $(CLEAR_VARS)\n\n'
536      'LOCAL_MODULE_TAGS := tests\n'
537      'LOCAL_STATIC_JAVA_LIBRARIES := android-support-test\n'
538      'LOCAL_COMPATIBILITY_SUITE := device-tests\n'
539      'LOCAL_RENDERSCRIPT_TARGET_API := current\n'
540      'LOCAL_PACKAGE_NAME := {}\n'
541      'LOCAL_SDK_VERSION := current\n'
542      'my_rs_path := $(TOP)/prebuilts/renderscript/host/linux-x86/{}\n'
543      'LOCAL_RENDERSCRIPT_CC := $(my_rs_path)/bin/llvm-rs-cc\n'
544      'LOCAL_RENDERSCRIPT_INCLUDES_OVERRIDE := $(my_rs_path)/include $(my_rs_path)/clang-include\n'
545      'my_rs_path :=\n'.format(
546          build_tool_version_name, make_target_name, build_tool_version_name
547      )
548  )
549  WriteMakeSrcFiles(gen_file, build_tool_version, ['../src', 'src'], True)
550  gen_file.write(
551      '\n'
552      'include $(BUILD_PACKAGE)\n\n'
553      'my_rs_unit_tests_path :=\n\n'
554      'endif\n'
555  )
556
557
558def ForwardMakeTargetsLocation():
559  """Returns the location of the file with all forward compatibility targets."""
560  return os.path.join(ThisScriptDir(), '..', 'RSTestForward', 'Targets.mk')
561
562
563def WriteForwardMakeTargets(gen_file):
564  """Writes forward compatibility make target names to gen_file."""
565  gen_file.write('RSTESTFORWARD_TARGETS := \\\n')
566  for build_tool_version_name in sorted(BUILD_TOOL_VERSIONS.values()):
567    make_target_name = ForwardTargetName(build_tool_version_name)
568    gen_file.write('    {} \\\n'.format(make_target_name))
569
570
571def GenerateForward():
572  """Generates the necessary file for forward compatibility testing."""
573  for build_tool_version in sorted(BUILD_TOOL_VERSIONS.keys()):
574    build_tool_version_name = BUILD_TOOL_VERSIONS[build_tool_version]
575    if not os.path.exists(ForwardDirLocation(build_tool_version_name)):
576      os.mkdir(ForwardDirLocation(build_tool_version_name))
577      os.mkdir(ForwardJavaSrcLocation(build_tool_version_name))
578    with open(ForwardMakefileLocation(build_tool_version_name), 'w') as gen_file:
579      WriteForwardMakefile(gen_file, build_tool_version, build_tool_version_name)
580    print ('Generated forward compatibility Makefile at {}'
581           .format(ForwardMakefileLocation(build_tool_version_name)))
582    with open(ForwardAndroidManifestLocation(build_tool_version_name), 'w') as gen_file:
583      package = 'com.android.rs.testforward{}'.format(build_tool_version)
584      WriteForwardAndroidManifest(gen_file, package)
585    print ('Generated forward compatibility AndroidManifest.xml at {}'
586           .format(ForwardAndroidManifestLocation(build_tool_version_name)))
587    with open(ForwardJavaApiVersionLocation(build_tool_version_name), 'w') as gen_file:
588      WriteForwardToolsVersion(gen_file, build_tool_version)
589    print ('Generated forward compatibility RSForwardVersion.java at {}'
590           .format(ForwardJavaApiVersionLocation(build_tool_version_name)))
591  with open(ForwardMakeTargetsLocation(), 'w') as gen_file:
592    WriteForwardMakeTargets(gen_file)
593  print ('Generated forward compatibility targets at {}'
594         .format(ForwardMakeTargetsLocation()))
595
596
597# ---------- RSTestBackward ----------
598
599
600def BackwardJavaFileLocation():
601  """Returns the location of Java file for backward compatibility testing."""
602  return os.path.join(ThisScriptDir(), '..', 'RSTestBackward', 'src', 'com',
603                      'android', 'rs', 'testbackward', 'RSTests.java')
604
605
606def Backward19JavaFileLocation():
607  """Returns the location of Java file for backward compatibility 19 testing."""
608  return os.path.join(ThisScriptDir(), '..', 'RSTestBackward19', 'src', 'com',
609                      'android', 'rs', 'testbackward19', 'RSTests.java')
610
611
612def Backward19MakefileLocation():
613  """Returns the location of Makefile for backward compatibility 19 testing."""
614  return os.path.join(ThisScriptDir(), '..', 'RSTestBackward19', 'Android.mk')
615
616
617def WriteBackwardJavaFile(gen_file, package, max_api_version=None):
618  """Writes the Java file for backward compatibility testing to gen_file.
619
620  Java file determines unit tests for backward compatibility
621  testing based on the unit test list at the top of this file."""
622  WriteJavaCopyright(gen_file)
623  gen_file.write(
624      'package {};\n'
625      '\n'
626      'import com.android.rs.unittest.*;\n'
627      '\n'
628      'import java.util.ArrayList;\n'
629      '\n'
630      '/**\n'
631      ' * This class is auto-generated by frameworks/rs/tests/java_api/RSUnitTests/RSUnitTests.py.\n'
632      ' * To change unit tests version, please run the Python script above.\n'
633      ' */\n'
634      'public class RSTests {{\n'
635      '    public static Iterable<Class<? extends UnitTest>> getTestClassesForCurrentAPIVersion() {{\n'
636      '        int thisApiVersion = android.os.Build.VERSION.SDK_INT;\n'
637      '\n'
638      '        ArrayList<Class<? extends UnitTest>> validClasses = new ArrayList<>();'.format(
639          package
640      )
641  )
642  for version in sorted(UNIT_TEST_PLATFORM_VERSIONS.keys()):
643    if max_api_version is None or version <= max_api_version:
644      tests = sorted(UNIT_TEST_PLATFORM_VERSIONS[version])
645      gen_file.write(
646          '\n\n        if (thisApiVersion >= {}) {{\n'.format(version)
647      )
648      for test in tests:
649        gen_file.write(
650            '            validClasses.add(UT_{}.class);\n'.format(test)
651        )
652      gen_file.write('        }')
653  gen_file.write('\n\n        return validClasses;\n    }\n}\n')
654
655
656def WriteBackward19Makefile(gen_file):
657  """Writes the Makefile for backward compatibility 19 testing."""
658  WriteMakeCopyright(gen_file)
659  gen_file.write(
660      '# This file is auto-generated by frameworks/rs/tests/java_api/RSUnitTests/RSUnitTests.py.\n'
661      '# To change unit tests version, please run the Python script above.\n\n'
662      'LOCAL_PATH := $(call my-dir)\n'
663      'include $(CLEAR_VARS)\n\n'
664      'LOCAL_MODULE_TAGS := tests\n'
665      'LOCAL_STATIC_JAVA_LIBRARIES := android-support-test\n'
666      'LOCAL_COMPATIBILITY_SUITE := device-tests\n'
667      'LOCAL_RENDERSCRIPT_TARGET_API := 19\n'
668      'LOCAL_MIN_SDK_VERSION := 17\n'
669      'LOCAL_SDK_VERSION := current\n'
670      'LOCAL_PACKAGE_NAME := RSTestBackward19\n'
671      'my_rs_unit_tests_path := ../RSUnitTests/src/com/android/rs/unittest\n'
672  )
673  WriteMakeSrcFiles(gen_file, 19)
674  gen_file.write(
675      '\n'
676      'include $(BUILD_PACKAGE)\n\n'
677      'my_rs_unit_tests_path :=\n\n'
678  )
679
680
681def GenerateBackward():
682  """Generates Java file for backward compatibility testing."""
683  with open(BackwardJavaFileLocation(), 'w') as gen_file:
684    WriteBackwardJavaFile(gen_file, 'com.android.rs.testbackward')
685  print ('Generated backward compatibility Java file at {}'
686         .format(BackwardJavaFileLocation()))
687
688
689def GenerateBackward19():
690  """Generates files for backward compatibility testing for API 19."""
691  with open(Backward19JavaFileLocation(), 'w') as gen_file:
692    WriteBackwardJavaFile(gen_file, 'com.android.rs.testbackward19', 19)
693  print ('Generated backward compatibility (19) Java file at {}'
694         .format(Backward19JavaFileLocation()))
695
696  with open(Backward19MakefileLocation(), 'w') as gen_file:
697    WriteBackward19Makefile(gen_file)
698  print ('Generated backward compatibility (19) Makefile at {}'
699         .format(Backward19MakefileLocation()))
700
701
702# ---------- Main ----------
703
704
705def DisplayHelp():
706  """Prints help message."""
707  print >> sys.stderr, ('Usage: {} [forward] [backward] [backward19] [help|-h|--help]\n'
708                        .format(sys.argv[0]))
709  print >> sys.stderr, ('[forward]: write forward compatibility Makefile to\n    {}\n'
710                        .format(ForwardMakefileLocation()))
711  print >> sys.stderr, ('[backward]: write backward compatibility Java file to\n    {}\n'
712                        .format(BackwardJavaFileLocation()))
713  print >> sys.stderr, ('[backward19]: write backward compatibility Java file (19) to\n    {}\n'
714                        .format(Backward19JavaFileLocation()))
715  print >> sys.stderr, ('[backward19]: write backward compatibility Makefile (19) to\n    {}\n'
716                        .format(Backward19MakefileLocation()))
717  print >> sys.stderr, ('[supportlib]: generate support lib unit tests to\n    {}\n'
718                        .format(SupportLibGenTestDir()))
719  print >> sys.stderr, ('[supportlib19]: generate support lib Makefile (19) to\n    {}\n'
720                        .format(SupportLib19MakefileLocation()))
721  print >> sys.stderr, 'if no options are chosen, then all files are generated'
722
723
724def main():
725  """Parses sys.argv and does stuff."""
726  display_help = False
727  error = False
728  actions = []
729
730  for arg in sys.argv[1:]:
731    if arg in ('help', '-h', '--help'):
732      display_help = True
733    elif arg == 'backward':
734      actions.append(GenerateBackward)
735    elif arg == 'backward19':
736      actions.append(GenerateBackward19)
737    elif arg == 'forward':
738      actions.append(GenerateForward)
739    elif arg == 'supportlib':
740      actions.append(GenerateSupportLibUnitTests)
741    elif arg == 'supportlib19':
742      actions.append(GenerateSupportLib19)
743    else:
744      print >> sys.stderr, 'unrecognized arg: {}'.format(arg)
745      error = True
746
747  if display_help or error:
748    DisplayHelp()
749  elif actions:
750    for action in actions:
751      action()
752  else:
753    # No args - do default action.
754    GenerateBackward()
755    GenerateBackward19()
756    GenerateForward()
757    GenerateSupportLibUnitTests()
758    GenerateSupportLib19()
759
760
761if __name__ == '__main__':
762  main()
763