avocado-run-testplan 5.5 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
#!/usr/bin/env python

# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; specifically version 2 of the License.
#
# This program 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 LICENSE for more details.
#
# Copyright: RedHat 2015
# Author: Cleber Rosa <cleber@redhat.com>


17
import datetime
18
import getpass
19 20 21 22 23
import json
import os
import subprocess
import sys

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
import argparse


class Parser(argparse.ArgumentParser):

    def __init__(self):
        super(Parser, self).__init__(
            prog='avocado-run-testplan',
            description='Tracks manual test plans progress and results')

        self.add_argument('-t', '--template', type=file,
                          help='Template file with the predefined test plan')

        self.add_argument('-o', '--output',
                          help='Output (test plan results) file location')

        self.add_argument('-i', '--input', type=file,
                          help=('A previously saved result file to use. This '
                                'will show a human readable report for the '
                                'given result file'))

RESULT_MAP = {"P": "PASS",
              "p": "PASS",
              "F": "FAIL",
              "f": "FAIL",
              "S": "SKIP",
              "s": "SKIP"}


class App(object):

    def __init__(self):
        self.parser = Parser()

    def run(self):
        self.args, _ = self.parser.parse_known_args()
        if not (self.args.template or self.args.input):
            self.parser.print_usage()
62
            return 0
63 64 65 66

        if self.args.input:
            self.report()
        else:
67 68 69 70 71
            try:
                self.run_test_plan()
            except KeyboardInterrupt:
                print("\nTest Plan interrupted by the user")
                return 1
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

    def run_test_plan(self):
        self.json = json.load(self.args.template)
        self.user_identification = None
        self.datetime = datetime.datetime.now()
        self.results = []

        print("Name: %s" % self.json.get("name"))
        print("Description: %s\n" % self.json.get("description"))

        test_count = len(self.json.get("tests"))
        current = 1
        for test in self.json.get("tests"):
            print("Test %d/%d: %s" % (current, test_count, test.get("name")))
            print("Description: %s\n" % test.get("description"))
            current += 1

            result = None
            while True:
                result = raw_input("Result ([P]ass, [F]ail, [S]kip): ")
                if result in RESULT_MAP.keys():
                    notes = raw_input("Additional Notes: ")
                    break
            print("")

            self.results.append({"name": test.get("name"),
                                 "result": RESULT_MAP.get(result),
                                 "notes": notes.strip()})

        user = raw_input("Your identification [%s]: " % getpass.getuser())
        if not user:
            user = getpass.getuser()
        self.user_identification = user

        self.save()
107
        return 0
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

    def get_output_file_name(self, suffix='json'):
        """
        Return the user given or default output file name
        """
        if self.args.output:
            return self.args.output

        name = self.json.get("name")
        name = name.strip()
        name = name.replace(" ", "_")
        return "%s_%s_%s.%s" % (name,
                                self.user_identification,
                                self.datetime.isoformat(),
                                suffix)

    def result_to_output_format(self):
        return {"name": self.json.get("name"),
                "user_identification": self.user_identification,
                "datetime": self.datetime.isoformat(),
                "results": self.results}

    def save(self):
        """
        Save the test plan execution result to a file
        """
        filename = self.get_output_file_name()
        with open(filename, 'w') as output:
            json.dump(self.result_to_output_format(), output)
        print("Wrote results to: %s" % filename)

    def report(self):
        """
        Write the test plan execution result to a human readable report
        """
        if self.args.input:
            data = json.load(self.args.input)
        else:
            data = self.result_to_output_format()

        print("Test Plan: %s" % data.get("name"))
        print("Run by '%s' at %s" % (data.get("user_identification"),
                                     data.get("datetime")))
151
        print("")
152
        for result in data.get("results"):
153 154 155
            print("%s: '%s': %s" % (result.get("result"),
                                    result.get("name"),
                                    result.get("notes")))
156 157 158 159 160 161 162 163 164 165 166 167
        print("")
        for name in sorted(os.listdir(os.path.pardir)):
            path = os.path.join(os.path.pardir, name)
            if not os.path.isdir(path):
                continue
            proc = subprocess.Popen("cd '%s' && git rev-parse HEAD" % path,
                                    stdout=subprocess.PIPE,
                                    stderr=subprocess.STDOUT,
                                    shell=True)
            out = proc.communicate()[0].strip()
            if not proc.poll():
                print("%s: %s" % (name, out))
168
        return 0
169 170 171 172

if __name__ == '__main__':
    app = App()
    sys.exit(app.run())