1#!/usr/bin/python3
2# Copyright (C) 2023 The Android Open Source Project
3#
4# Licensed under the Apache License, Version 2.0 (the "License");
5# you may not use this file except in compliance with the License.
6# You may obtain a copy of the License at
7#
8#      http://www.apache.org/licenses/LICENSE-2.0
9#
10# Unless required by applicable law or agreed to in writing, software
11# distributed under the License is distributed on an "AS IS" BASIS,
12# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13# See the License for the specific language governing permissions and
14# limitations under the License.
15
16# Compare the tiny-framework JAR dumps to the golden files.
17
18import sys
19import os
20import unittest
21import subprocess
22
23GOLDEN_DIRS = [
24    'golden-output',
25    'golden-output.RELEASE_TARGET_JAVA_21',
26]
27
28
29# Run diff.
30def run_diff(file1, file2):
31    command = ['diff', '-u', '--ignore-blank-lines',
32               '--ignore-space-change', file1, file2]
33    print(' '.join(command))
34    result = subprocess.run(command, stderr=sys.stdout)
35
36    success = result.returncode == 0
37
38    if success:
39        print('No diff found.')
40    else:
41        print(f'Fail: {file1} and {file2} are different.')
42
43    return success
44
45
46# Check one golden file.
47def check_one_file(golden_dir, filename):
48    print(f'= Checking file: {filename}')
49    return run_diff(os.path.join(golden_dir, filename), filename)
50
51
52class TestWithGoldenOutput(unittest.TestCase):
53
54    # Test to check the generated jar files to the golden output.
55    # Depending on build flags, the golden output may differ in expected ways.
56    # So only expect the files to match one of the possible golden outputs.
57    def test_compare_to_golden(self):
58        success = False
59
60        for golden_dir in GOLDEN_DIRS:
61            if self.matches_golden(golden_dir):
62                success = True
63                print(f"Test passes for dir: {golden_dir}")
64                break
65
66        if not success:
67            self.fail('Some files are different. ' +
68                      'See stdout log for more details.')
69
70    def matches_golden(self, golden_dir):
71        files = os.listdir(golden_dir)
72        files.sort()
73
74        print(f"Golden files for {golden_dir}: {files}")
75        match_success = True
76
77        for file in files:
78            if not check_one_file(golden_dir, file):
79                match_success = False
80
81        return match_success
82
83
84if __name__ == "__main__":
85    unittest.main(verbosity=2)
86