source: calamares/trunk/fuentes/src/modules/testmodule.py @ 7538

Last change on this file since 7538 was 7538, checked in by kbut, 17 months ago

sync with github

  • Property svn:executable set to *
File size: 6.1 KB
Line 
1#!/usr/bin/env python3
2# -*- coding: utf-8 -*-
3#
4# === This file is part of Calamares - <https://github.com/calamares> ===
5#
6#   Copyright 2014, Teo Mrnjavac <teo@kde.org>
7#   Copyright 2017, Adriaan de Groot <groot@kde.org>
8#
9#   Calamares is free software: you can redistribute it and/or modify
10#   it under the terms of the GNU General Public License as published by
11#   the Free Software Foundation, either version 3 of the License, or
12#   (at your option) any later version.
13#
14#   Calamares is distributed in the hope that it will be useful,
15#   but WITHOUT ANY WARRANTY; without even the implied warranty of
16#   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17#   GNU General Public License for more details.
18#
19#   You should have received a copy of the GNU General Public License
20#   along with Calamares. If not, see <http://www.gnu.org/licenses/>.
21"""
22Testing tool to run a single Python module; optionally a global configuration
23and module configuration can be read from YAML files.
24"""
25argumentepilog = """
26moduledir may be a module name (e.g. "welcome") or a full path to the
27    module (e.g. "src/modules/welcome"). In the former case, an attempt
28    is made to find the module in several sensible places.
29globalstorage_yaml may be given as a full path to a YAML file containing
30    the global configuration, or as "" or "-" which will leave the
31    global storage empty.
32configuration_yaml may be given as a full path to a YAML file with the
33    module configuration, as "" or "-" to leave the configuration
34    empty, or as "+" to load the standard configuration from the
35    module-directory (e.g. welcome.conf if the welcome module is given).
36
37The simplest invocation to test a module, with its default configuration, is
38to call this program as follows (for, e.g., the welcome module):
39
40    testmodule.py welcome - +"""
41
42import argparse
43import os
44import sys
45
46import yaml
47
48calamaresimporterror = ("Can not import libcalamares. Ensure the PYTHONPATH "
49    "environment variable includes the dir where libcalamares.so is "
50    "installed.")
51try:
52    import libcalamares
53except ImportError:
54    print(calamaresimporterror)
55    print()
56    libcalamares = None
57
58
59class Job:
60    """
61
62    :param working_path:
63    :param doc:
64    :param cfg_doc:
65    """
66
67    def __init__(self, working_path, doc, cfg_doc):
68        self.module_name = doc["name"]
69        self.pretty_name = "Testing job " + doc["name"]
70        self.working_path = working_path
71        self.configuration = cfg_doc
72
73    def setprogress(self, progress):
74        """
75
76        :param progress:
77        """
78        print("Job set progress to {}%.".format(progress * 100))
79
80
81def test_module(moduledir, globalconfigfilename, moduleconfigfilename, lang):
82    print("Testing module in: " + moduledir)
83
84    confpath = os.path.join(moduledir, "module.desc")
85    with open(confpath) as f:
86        doc = yaml.load(f)
87
88    if doc["type"] != "job" or doc["interface"] != "python":
89        print("Only Python jobs can be tested.")
90        return 1
91
92    # Parameter None creates a new, empty GlobalStorage
93    libcalamares.globalstorage = libcalamares.GlobalStorage(None)
94    libcalamares.globalstorage.insert("testing", True)
95    if lang:
96        libcalamares.globalstorage.insert("locale", lang)
97        libcalamares.globalstorage.insert("localeConf", {"LANG": lang})
98
99    # if a file for simulating globalStorage contents is provided, load it
100    if globalconfigfilename:
101        with open(globalconfigfilename) as f:
102            gs_doc = yaml.load(f)
103        for key, value in gs_doc.items():
104            libcalamares.globalstorage.insert(key, value)
105        print("Global configuration '" + globalconfigfilename + "' loaded.")
106    else:
107        print("No global configuration loaded.")
108
109    cfg_doc = dict()
110    if moduleconfigfilename:
111        with open(moduleconfigfilename) as f:
112            cfg_doc = yaml.load(f)
113            print("Local configuration '" + moduleconfigfilename + "' loaded.")
114    else:
115        print("No module configuration loaded.")
116
117    libcalamares.job = Job(moduledir, doc, cfg_doc)
118
119    scriptpath = os.path.abspath(moduledir)
120    sys.path.append(scriptpath)
121    import main  # Assumed to import main from module itself
122
123    print("Output from module:")
124    print(main.run())
125
126    return 0
127
128
129def munge_filename(filename, module=None):
130    """
131    Maps files "" (empty) and "-" (just a dash) to None,
132    to simplify processing elsewhere.
133    """
134    if not filename or filename == "-":
135        return None
136    if filename == "+" and module is not None:
137        d, name = os.path.split(module)
138        if d and not name:
139            # Ended in a /
140            d, name = os.path.split(module)
141        if name:
142            return os.path.join(module, name + ".conf")
143
144    return filename
145
146
147def find_module(modulename):
148    if "/" in modulename:
149        return modulename
150    else:
151        for prefix in ("src/modules", "build/src/modules", "../src/modules"):
152            mp = os.path.join( prefix, modulename )
153            if os.path.exists( mp ):
154                return mp
155    # Not found? Bail out elsewhere
156    return modulename
157
158def main():
159    parser = argparse.ArgumentParser(description=globals()["__doc__"], epilog=argumentepilog, formatter_class=argparse.RawDescriptionHelpFormatter)
160    parser.add_argument("moduledir",
161                        help="Dir containing the Python module.")
162    parser.add_argument("globalstorage_yaml", nargs="?",
163                        help="A yaml file to initialize GlobalStorage.")
164    parser.add_argument("configuration_yaml", nargs="?",
165                        help="A yaml file to initialize the Job.")
166    parser.add_argument("--lang", "-l", nargs="?", default=None,
167                        help="Set translation language.")
168    args = parser.parse_args()
169
170    # If we get here, it wasn't a --help invocation, so complain
171    # if libcalamares wasn't found.
172    if not libcalamares:
173        parser.error(calamaresimporterror)
174
175    moduledir = find_module(args.moduledir)
176    return test_module(moduledir,
177                       munge_filename(args.globalstorage_yaml),
178                       munge_filename(args.configuration_yaml, moduledir),
179                       args.lang)
180
181
182if __name__ == "__main__":
183    sys.exit(main())
Note: See TracBrowser for help on using the repository browser.