xref: /aosp_15_r20/external/autotest/client/common_lib/seven_unittest.py (revision 9c5db1993ded3edbeafc8092d69fe5de2ee02df7)
1#!/usr/bin/python3
2
3# Copyright (c) 2020 The Chromium Authors. All rights reserved.
4# Use of this source code is governed by a BSD-style license that can be
5# found in the LICENSE file.
6
7from __future__ import print_function
8
9import os
10import sys
11import tempfile
12import unittest
13
14from autotest_lib.client.common_lib import seven
15
16
17class TestExecCompileFile(unittest.TestCase):
18    """Unittests for Seven helpers."""
19
20    def _remove_tempfile(self):
21        if hasattr(self, "tempfile"):
22            try:
23                os.remove(self.tempfile)
24            except OSError:
25                pass
26        return None
27
28    def setUp(self):
29        try:
30            with tempfile.NamedTemporaryFile(delete=False) as fh:
31                self.tempfile = fh.name
32        except Exception:  # pylint: disable=broad-except
33            self._remove_tempfile()
34        super(TestExecCompileFile, self).setUp()
35
36    def tearDown(self):
37        super(TestExecCompileFile, self).tearDown()
38        self._remove_tempfile()
39
40    def testExecSyntaxError(self):
41        with open(self.tempfile, "wb") as fh:
42            fh.write(br"(")
43
44        try:
45            seven.exec_file(
46                    filename=self.tempfile,
47                    globals_={},
48                    locals_={},
49            )
50            exn = None
51        except Exception as e:  # pylint: disable=broad-except
52            exn = e
53
54        self.assertIsInstance(exn, SyntaxError)
55
56    def testExecPrint(self):
57        with open(self.tempfile, "wb") as fh:
58            fh.write(br"print 'hi'")
59
60        try:
61            seven.exec_file(
62                    filename=self.tempfile,
63                    globals_={},
64                    locals_={},
65            )
66            exn = None
67        except Exception as e:  # pylint: disable=broad-except
68            exn = e
69
70        if sys.version_info[0] <= 2:
71            self.assertIsNone(exn)
72        else:
73            self.assertIsInstance(exn, SyntaxError)
74
75    def testExecPrintWithFutureImport(self):
76        with open(self.tempfile, "wb") as fh:
77            fh.write(br"from __future__ import print_function; print 'hi'")
78
79        try:
80            seven.exec_file(
81                    filename=self.tempfile,
82                    globals_={},
83                    locals_={},
84            )
85            exn = None
86        except Exception as e:  # pylint: disable=broad-except
87            exn = e
88
89        self.assertIsInstance(exn, SyntaxError)
90
91
92if __name__ == "__main__":
93    unittest.main()
94