summaryrefslogtreecommitdiff
path: root/templates/python/template.py
blob: 62b1fc9c6c424cbacc6cefc662d61766a8562176 (plain)
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
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
#############################################################################
# Functions that implement steps. From {{ functions_filename }}.

{{ functions }}


#############################################################################
# Helper code generated by Subplot.

import argparse
import base64
import logging
import os
import random
import shutil
import sys
import tarfile
import tempfile

# Store context between steps.
class Context:

    def __init__(self):
        self._vars = {}

    def as_dict(self):
        return dict(self._vars)

    def get(self, key, default=None):
        return self._vars.get(key, default)

    def __getitem__(self, key):
        return self._vars[key]

    def __setitem__(self, key, value):
        logging.info('Context: {}={!r}'.format(key, value))
        self._vars[key] = value

# Decode a base64 encoded string. Result is binary or unicode string.

def decode_bytes(s):
    return base64.b64decode(s)

def decode_str(s):
    return base64.b64decode(s).decode()

# Test data files that were embedded in the source document. Base64
# encoding is used to allow arbitrary data.
_files = {}
{% for file in files %}
# {{ file.filename }}
filename = decode_str('{{ file.filename | base64 }}')
contents = decode_bytes('{{ file.contents | base64 }}')
_files[filename] = contents
{% endfor %}


# Retrieve an embedded test data file using filename.
def get_file(filename):
    return _files[filename]

# Check two values for equality and give error if they are not equal
def assert_eq(a, b):
    assert a == b, 'expected %r == %r' % (a, b)

# Check two values for inequality and give error if they are equal
def assert_ne(a, b):
    assert a != b, 'expected %r != %r' % (a, b)

# Remember where we started from. The step functions may need to refer
# to files there.
srcdir = os.getcwd()
print('srcdir', srcdir)

# Create a new temporary directory and chdir there. This allows step
# functions to create new files in the current working directory
# without having to be so careful.
_datadir = tempfile.mkdtemp()
print('datadir', _datadir)
os.chdir(_datadir)

#############################################################################
# Code to implement the scenarios.

{% for scenario in scenarios %}
######################################
# Scenario: {{ scenario.title }}
def scenario_{{ loop.index }}():
    title = decode_str('{{ scenario.title | base64 }}')
    print('scenario: {}'.format(title))
    logging.info("Scenario: {}".format(title))
    _scendir = tempfile.mkdtemp(dir=_datadir)
    os.chdir(_scendir)
    ctx = Context()
    {% for step in scenario.steps %}
    # Step: {{ step.text }}
    step = decode_str('{{ step.text | base64 }}')
    print('  step: {{ step.kind | lower }} {}'.format(step))
    logging.info('  step: {{ step.kind | lower }} {}'.format(step))
    args = {}
    {% for part in step.parts %}{% if part.CapturedText is defined -%}
    name = decode_str('{{ part.CapturedText.name | base64 }}')
    text = decode_str('{{ part.CapturedText.text | base64 }}')
    args[name] = text
    {% endif -%}
    {% endfor -%}
    {{ step.function }}(ctx, **args)
    {% endfor %}
{% endfor %}

_scenarios = {
{% for scenario in scenarios %}
    '{{ scenario.title }}': scenario_{{ loop.index }},
{% endfor %}
}


def parse_command_line():
    p = argparse.ArgumentParser()
    p.add_argument("--log")
    p.add_argument("--save-on-failure")
    p.add_argument("patterns", nargs="*")
    return p.parse_args()


def setup_logging(args):
    if args.log:
        fmt = "%(asctime)s %(levelname)s %(message)s"
        datefmt = "%Y-%m-%d %H:%M:%S"
        formatter = logging.Formatter(fmt, datefmt)

        filename = os.path.abspath(os.path.join(srcdir, args.log))
        handler = logging.FileHandler(filename)
        handler.setFormatter(formatter)
    else:
        handler = logging.NullHandler()

    logger = logging.getLogger()
    logger.addHandler(handler)
    logger.setLevel(logging.DEBUG)


def save_directory(dirname, tarname):
    print('tarname', tarname)
    logging.info("Saving {} to {}".format(dirname, tarname))
    tar = tarfile.open(tarname, "w")
    tar.add(dirname, arcname="datadir")
    tar.close()


def main():
    args = parse_command_line()
    setup_logging(args)
    logging.info("Test program starts")

    logging.info("patterns: {}".format(args.patterns))
    if len(args.patterns) == 0:
        logging.info("Executing all scenarios")
        funcs = list(_scenarios.values())
        random.shuffle(funcs)
    else:
        logging.info("Executing requested scenarios only: {}".format(args.patterns))
        patterns = [arg.lower() for arg in args.patterns]
        funcs = [
            func
            for title, func in _scenarios.items()
            if any(pattern in title.lower() for pattern in patterns)
        ]

    try:
        for func in funcs:
            func()
    except Exception as e:
        logging.error(str(e), exc_info=True)
        if args.save_on_failure:
            print(args.save_on_failure)
            filename = os.path.abspath(os.path.join(srcdir, args.save_on_failure))
            print(filename)
            save_directory(_datadir, filename)
        raise


main()

#############################################################################
# Clean up temporary directory and report success.

shutil.rmtree(_datadir)
print('OK, all scenarios finished successfully')
logging.info("OK, all scenarios finished successfully")