xref: /aosp_15_r20/external/cronet/build/action_helpers_unittest.py (revision 6777b5387eb2ff775bb5750e3f5d96f37fb7352b)
1#!/usr/bin/env python3
2# Copyright 2023 The Chromium Authors
3# Use of this source code is governed by a BSD-style license that can be
4# found in the LICENSE file.
5
6import os
7import pathlib
8import shutil
9import sys
10import tempfile
11import time
12import unittest
13
14import action_helpers
15
16
17class ActionHelpersTest(unittest.TestCase):
18  def test_atomic_output(self):
19    tmp_file = pathlib.Path(tempfile.mktemp())
20    tmp_file.write_text('test')
21    try:
22      # Test that same contents does not change mtime.
23      orig_mtime = os.path.getmtime(tmp_file)
24      with action_helpers.atomic_output(str(tmp_file), 'wt') as af:
25        time.sleep(.01)
26        af.write('test')
27
28      self.assertEqual(os.path.getmtime(tmp_file), orig_mtime)
29
30      # Test that contents is written.
31      with action_helpers.atomic_output(str(tmp_file), 'wt') as af:
32        af.write('test2')
33      self.assertEqual(tmp_file.read_text(), 'test2')
34      self.assertNotEqual(os.path.getmtime(tmp_file), orig_mtime)
35    finally:
36      tmp_file.unlink()
37
38  def test_parse_gn_list(self):
39    def test(value, expected):
40      self.assertEqual(action_helpers.parse_gn_list(value), expected)
41
42    test(None, [])
43    test('', [])
44    test('asdf', ['asdf'])
45    test('["one"]', ['one'])
46    test(['["one"]', '["two"]'], ['one', 'two'])
47    test(['["one", "two"]', '["three"]'], ['one', 'two', 'three'])
48
49  def test_write_depfile(self):
50    tmp_file = pathlib.Path(tempfile.mktemp())
51    try:
52
53      def capture_output(inputs):
54        action_helpers.write_depfile(str(tmp_file), 'output', inputs)
55        return tmp_file.read_text()
56
57      self.assertEqual(capture_output(None), 'output: \n')
58      self.assertEqual(capture_output([]), 'output: \n')
59      self.assertEqual(capture_output(['a']), 'output: \\\n a\n')
60      # Check sorted.
61      self.assertEqual(capture_output(['b', 'a']), 'output: \\\n a \\\n b\n')
62      # Check converts to forward slashes.
63      self.assertEqual(capture_output(['a', os.path.join('b', 'c')]),
64                       'output: \\\n a \\\n b/c\n')
65
66      # Arg should be a list.
67      with self.assertRaises(AssertionError):
68        capture_output('a')
69
70      # Do not use depfile itself as an output.
71      with self.assertRaises(AssertionError):
72        capture_output([str(tmp_file)])
73
74      # Do not use absolute paths.
75      with self.assertRaises(AssertionError):
76        capture_output([os.path.sep + 'foo'])
77
78      # Do not use absolute paths (output path).
79      with self.assertRaises(AssertionError):
80        action_helpers.write_depfile(str(tmp_file), '/output', [])
81
82    finally:
83      tmp_file.unlink()
84
85
86if __name__ == '__main__':
87  unittest.main()
88