File: testprogramrunner.py

package info (click to toggle)
glib2.0 2.86.3-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 66,456 kB
  • sloc: ansic: 544,658; python: 9,702; sh: 1,612; xml: 1,482; perl: 1,222; cpp: 535; makefile: 321; javascript: 11
file content (162 lines) | stat: -rw-r--r-- 4,650 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
#!/usr/bin/python3
# -*- coding: utf-8 -*-
#
# Copyright © 2018 Endless Mobile, Inc.
# Copyright © 2025 Canonical Ltd.
#
# SPDX-License-Identifier: LGPL-2.1-or-later
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
# MA  02110-1301  USA

"""Integration tests for GLib utilities."""

import os
import shutil
import subprocess
import tempfile
import unittest
import sys

from dataclasses import dataclass
from enum import Enum


class ProgramType(Enum):
    """Enum to define the kind of tool to use"""

    NATIVE = 1
    INTERPRETED = 2


@dataclass
class Result:
    """Class for keeping track of the executable result."""

    info: subprocess.CompletedProcess
    out: str
    err: str
    subs: dict


class TestProgramRunner(unittest.TestCase):
    """Integration test for running glib-based tools.

    This can be run when installed or uninstalled. When uninstalled, it
    requires G_TEST_BUILDDIR or _G_TEST_PROGRAM_RUNNER_PATH to be set.
    """

    PROGRAM_NAME: str = None
    PROGRAM_TYPE: ProgramType = ProgramType.NATIVE
    INTERPRETER: str = None

    @classmethod
    def setUpClass(cls):
        super().setUpClass()
        cls.assertTrue(cls.PROGRAM_NAME, "class PROGRAM_NAME must be set")

        ext = ""
        if cls.PROGRAM_TYPE == ProgramType.NATIVE and os.name == "nt":
            ext = ".exe"

        cls._program_name = f"{cls.PROGRAM_NAME}{ext}"

        if "_G_TEST_PROGRAM_RUNNER_PATH" in os.environ:
            cls.__program = os.path.join(
                os.environ["_G_TEST_PROGRAM_RUNNER_PATH"], cls._program_name
            )
        elif "G_TEST_BUILDDIR" in os.environ:
            cls.__program = os.path.join(
                os.environ["G_TEST_BUILDDIR"], cls._program_name
            )
        else:
            cls.__program = os.path.join(os.path.dirname(__file__), cls._program_name)
            if not os.path.exists(cls.__program):
                cls.__program = shutil.which(cls._program_name)

    def setUp(self):
        print(f"{self.PROGRAM_NAME}: {self.__program}")
        self.assertTrue(os.path.exists(self.__program))

        self.tmpdir = tempfile.TemporaryDirectory()
        self.addCleanup(self.tmpdir.cleanup)
        old_cwd = os.getcwd()
        self.addCleanup(os.chdir, old_cwd)
        os.chdir(self.tmpdir.name)
        print("tmpdir:", self.tmpdir.name)

    def runTestProgram(
        self,
        *args,
        should_fail=False,
        wrapper_args=[],
        environment={},
        cwd=None,
    ) -> Result:
        argv = [self.__program]

        argv.extend(*args)

        # shebang lines are not supported on native
        # Windows consoles
        if self.PROGRAM_TYPE == ProgramType.INTERPRETED and os.name == "nt":
            argv.insert(0, self.INTERPRETER if self.INTERPRETER else sys.executable)

        argv = wrapper_args + argv

        env = os.environ.copy()
        env["LC_ALL"] = "C.UTF-8"
        env["G_DEBUG"] = "fatal-warnings"
        env.update(environment)

        print("Running:", argv)

        if cwd is not None:
            print("Working Directory:", cwd)

        # We want to ensure consistent line endings...
        info = subprocess.run(
            argv,
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
            env=env,
            universal_newlines=True,
            text=True,
            encoding="utf-8",
            check=False,
            cwd=cwd,
        )

        result = Result(
            info=info,
            out=info.stdout.strip(),
            err=info.stderr.strip(),
            subs=self._getSubs(),
        )

        print("Return code:", result.info.returncode)
        print("Output:\n", result.out)
        print("Error:\n", result.err)

        if should_fail:
            with self.assertRaises(subprocess.CalledProcessError):
                info.check_returncode()
        else:
            info.check_returncode()

        return result

    def _getSubs(self) -> dict:
        return {}