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