gfrast 0.3.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- gfrast-0.3.0/LICENSE +18 -0
- gfrast-0.3.0/PKG-INFO +212 -0
- gfrast-0.3.0/README.md +183 -0
- gfrast-0.3.0/pyproject.toml +78 -0
- gfrast-0.3.0/pyproject.toml.orig +75 -0
- gfrast-0.3.0/src/gfrast/__init__.py +0 -0
- gfrast-0.3.0/src/gfrast/cli.py +173 -0
- gfrast-0.3.0/src/gfrast/common.py +410 -0
gfrast-0.3.0/LICENSE
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
MIT No Attribution
|
|
2
|
+
|
|
3
|
+
Copyright 2026 Vasold Gunter
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so.
|
|
11
|
+
|
|
12
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
13
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
14
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
15
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
16
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
17
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
18
|
+
SOFTWARE.
|
gfrast-0.3.0/PKG-INFO
ADDED
|
@@ -0,0 +1,212 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: gfrast
|
|
3
|
+
Version: 0.3.0
|
|
4
|
+
Summary: GFRAST (GAMS Flexible Repository ASsertion Tool) is a small script to test HTTP server responses.
|
|
5
|
+
Keywords: GAMS,twill,testing
|
|
6
|
+
Author: Gunter Vasold
|
|
7
|
+
Author-email: Gunter Vasold <gunter.vasold@uni-graz.at>
|
|
8
|
+
License-Expression: MIT-0
|
|
9
|
+
License-File: LICENSE
|
|
10
|
+
Classifier: Development Status :: 4 - Beta
|
|
11
|
+
Classifier: Intended Audience :: Developers
|
|
12
|
+
Classifier: Intended Audience :: System Administrators
|
|
13
|
+
Classifier: Topic :: Internet :: WWW/HTTP
|
|
14
|
+
Classifier: Topic :: Software Development :: Testing
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
20
|
+
Classifier: Programming Language :: Python :: 3.15
|
|
21
|
+
Requires-Dist: twill>=3.4.0
|
|
22
|
+
Requires-Python: >=3.10
|
|
23
|
+
Project-URL: Homepage, https://git.uni-graz.at/open/562-dh/gams/tools/gfrast
|
|
24
|
+
Project-URL: Issues, https://git.uni-graz.at/open/562-dh/gams/tools/gfrast/issues
|
|
25
|
+
Project-URL: Documentation, https://git.uni-graz.at/open/562-dh/gams/tools/gfrast
|
|
26
|
+
Project-URL: Source, https://git.uni-graz.at/open/562-dh/gams/tools/gfrast
|
|
27
|
+
Project-URL: Download, https://pypi.org/project/gfrast
|
|
28
|
+
Description-Content-Type: text/markdown
|
|
29
|
+
|
|
30
|
+
# GFRAST
|
|
31
|
+
|
|
32
|
+
GFRAST (**G**AMS **F**lexible **R**epository **As**sertion **T**ool) is a small
|
|
33
|
+
wrapper around the
|
|
34
|
+
[Twill](https://github.com/twill-tools/twill) HTTP testing client. It lets you run
|
|
35
|
+
repeatable, script-driven checks against a web server and summarize the results in
|
|
36
|
+
a machine-friendly way.
|
|
37
|
+
|
|
38
|
+
The main difference from using Twill directly is that GFRAST filters and normalizes
|
|
39
|
+
its output so it can be consumed by other tools or custom clients. The current CLI
|
|
40
|
+
provides a simple, focused interface for running scripts and writing a JSON summary.
|
|
41
|
+
|
|
42
|
+
## Installation
|
|
43
|
+
|
|
44
|
+
GFRAST is available on PyPI and can be installed with common package managers:
|
|
45
|
+
|
|
46
|
+
```bash
|
|
47
|
+
pip install gfrast
|
|
48
|
+
uv add gfrast
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
If you use `uv` and only want to run GFRAST temporarily, you can do so without a
|
|
52
|
+
permanent install:
|
|
53
|
+
|
|
54
|
+
```bash
|
|
55
|
+
uvx gfrast --help
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
## Usage
|
|
59
|
+
|
|
60
|
+
GFRAST executes Twill script files. These are plain text files that describe the
|
|
61
|
+
HTTP checks to run.
|
|
62
|
+
|
|
63
|
+
A minimal example script, `example.twill`, might look like this:
|
|
64
|
+
|
|
65
|
+
```text
|
|
66
|
+
go /foo/bar
|
|
67
|
+
code 200
|
|
68
|
+
find "foobar"
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
This loads `/foo/bar` from the configured base URL and asserts that the response has
|
|
72
|
+
status code `200` and contains the text `foobar`.
|
|
73
|
+
|
|
74
|
+
To run a script:
|
|
75
|
+
|
|
76
|
+
```bash
|
|
77
|
+
gfrast example.twill
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
By default, GFRAST uses `https://gams.uni-graz.at` as the base URL. You can override
|
|
81
|
+
that with `-u` / `--baseurl`:
|
|
82
|
+
|
|
83
|
+
```bash
|
|
84
|
+
gfrast -u https://example.com example.twill
|
|
85
|
+
```
|
|
86
|
+
|
|
87
|
+
You can run multiple scripts by passing several files:
|
|
88
|
+
|
|
89
|
+
```bash
|
|
90
|
+
gfrast -u https://example.com example1.twill example2.twill
|
|
91
|
+
```
|
|
92
|
+
|
|
93
|
+
Or you can point GFRAST to a directory. It will recursively run all `.twill` files
|
|
94
|
+
inside that directory:
|
|
95
|
+
|
|
96
|
+
```bash
|
|
97
|
+
gfrast -u https://example.com my_scripts
|
|
98
|
+
```
|
|
99
|
+
|
|
100
|
+
This is especially useful for organizing tests by project or repository section.
|
|
101
|
+
|
|
102
|
+
### Command-line options
|
|
103
|
+
|
|
104
|
+
The CLI supports the following options:
|
|
105
|
+
|
|
106
|
+
- `-u`, `--baseurl <URL>`: Set the base URL prepended to each `go` command.
|
|
107
|
+
- `-w`, `--workers <INTEGER>`: Number of worker processes to use. Default is `1`.
|
|
108
|
+
- `--log-level <STRING>`: Set the log level (`ERROR`, `WARNING`, `INFO`, `DEBUG`).
|
|
109
|
+
- `--logfile <PATH>`: Path for the JSON summary log file. Default is `gfrast.log.json`.
|
|
110
|
+
- `--no-log`: Disable writing the JSON summary file.
|
|
111
|
+
|
|
112
|
+
## Script files
|
|
113
|
+
|
|
114
|
+
A Twill script is just a plain text file that controls the client.
|
|
115
|
+
|
|
116
|
+
Example:
|
|
117
|
+
|
|
118
|
+
```text
|
|
119
|
+
go /foo/bar
|
|
120
|
+
code 200
|
|
121
|
+
find "foobar"
|
|
122
|
+
```
|
|
123
|
+
|
|
124
|
+
The first line (`go /foo/bar`) issues the request. The base URL is prepended before
|
|
125
|
+
sending the request. For example, with `--baseurl https://example.com`, this becomes:
|
|
126
|
+
|
|
127
|
+
```text
|
|
128
|
+
https://example.com/foo/bar
|
|
129
|
+
```
|
|
130
|
+
|
|
131
|
+
The next line (`code 200`) asserts that the response status is `200`.
|
|
132
|
+
|
|
133
|
+
The third line (`find "foobar"`) asserts that the response body contains the string
|
|
134
|
+
`foobar`.
|
|
135
|
+
|
|
136
|
+
For more advanced behavior, Twill supports a wide range of commands for forms,
|
|
137
|
+
cookies, redirects, and more. See the official Twill docs:
|
|
138
|
+
https://twill.readthedocs.io/en/latest/commands.html
|
|
139
|
+
|
|
140
|
+
## Frequently used script commands
|
|
141
|
+
|
|
142
|
+
### `go <PATH>`
|
|
143
|
+
|
|
144
|
+
This is usually the first command in a script. Most other commands operate on the
|
|
145
|
+
result of the last `go` request.
|
|
146
|
+
|
|
147
|
+
```text
|
|
148
|
+
go /foo/bar
|
|
149
|
+
code 200
|
|
150
|
+
find "foobar"
|
|
151
|
+
```
|
|
152
|
+
|
|
153
|
+
When the base URL is set, `go` values are automatically expanded to full URLs.
|
|
154
|
+
|
|
155
|
+
### `code <INT>`
|
|
156
|
+
|
|
157
|
+
Asserts that the response status matches the given integer.
|
|
158
|
+
|
|
159
|
+
```text
|
|
160
|
+
code 200
|
|
161
|
+
```
|
|
162
|
+
|
|
163
|
+
### `find <PATTERN> [<FLAGS>]`
|
|
164
|
+
|
|
165
|
+
Checks whether the response contains the given pattern.
|
|
166
|
+
|
|
167
|
+
```text
|
|
168
|
+
find "foo"
|
|
169
|
+
```
|
|
170
|
+
|
|
171
|
+
This supports regular expressions and flags such as `i` (ignore case) and `m`
|
|
172
|
+
(multiline). It can also be used with XPath via the `x` flag.
|
|
173
|
+
|
|
174
|
+
Example:
|
|
175
|
+
|
|
176
|
+
```text
|
|
177
|
+
find "//xhtml:input/@id[.='query']" x
|
|
178
|
+
```
|
|
179
|
+
|
|
180
|
+
### `not_find`
|
|
181
|
+
|
|
182
|
+
Asserts that a pattern does not appear in the response.
|
|
183
|
+
|
|
184
|
+
### `url <PATTERN>`
|
|
185
|
+
|
|
186
|
+
Asserts that the current page URL matches a given pattern. This is especially useful
|
|
187
|
+
for redirect tests.
|
|
188
|
+
|
|
189
|
+
### `title <PATTERN>`
|
|
190
|
+
|
|
191
|
+
Asserts that the page title matches the supplied pattern.
|
|
192
|
+
|
|
193
|
+
### `header <NAME>[<PATTERN>]`
|
|
194
|
+
|
|
195
|
+
Checks that an HTTP header has the expected value.
|
|
196
|
+
|
|
197
|
+
### `echo`
|
|
198
|
+
|
|
199
|
+
Prints a string to the output stream.
|
|
200
|
+
|
|
201
|
+
### `info`
|
|
202
|
+
|
|
203
|
+
Displays information about the current page for debugging.
|
|
204
|
+
|
|
205
|
+
### `show`
|
|
206
|
+
|
|
207
|
+
Prints the current page content for debugging.
|
|
208
|
+
|
|
209
|
+
|
|
210
|
+
## Development
|
|
211
|
+
|
|
212
|
+
The git.uni-graz.at server is only a mirror for the private repository, where the development takes place.
|
gfrast-0.3.0/README.md
ADDED
|
@@ -0,0 +1,183 @@
|
|
|
1
|
+
# GFRAST
|
|
2
|
+
|
|
3
|
+
GFRAST (**G**AMS **F**lexible **R**epository **As**sertion **T**ool) is a small
|
|
4
|
+
wrapper around the
|
|
5
|
+
[Twill](https://github.com/twill-tools/twill) HTTP testing client. It lets you run
|
|
6
|
+
repeatable, script-driven checks against a web server and summarize the results in
|
|
7
|
+
a machine-friendly way.
|
|
8
|
+
|
|
9
|
+
The main difference from using Twill directly is that GFRAST filters and normalizes
|
|
10
|
+
its output so it can be consumed by other tools or custom clients. The current CLI
|
|
11
|
+
provides a simple, focused interface for running scripts and writing a JSON summary.
|
|
12
|
+
|
|
13
|
+
## Installation
|
|
14
|
+
|
|
15
|
+
GFRAST is available on PyPI and can be installed with common package managers:
|
|
16
|
+
|
|
17
|
+
```bash
|
|
18
|
+
pip install gfrast
|
|
19
|
+
uv add gfrast
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
If you use `uv` and only want to run GFRAST temporarily, you can do so without a
|
|
23
|
+
permanent install:
|
|
24
|
+
|
|
25
|
+
```bash
|
|
26
|
+
uvx gfrast --help
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
## Usage
|
|
30
|
+
|
|
31
|
+
GFRAST executes Twill script files. These are plain text files that describe the
|
|
32
|
+
HTTP checks to run.
|
|
33
|
+
|
|
34
|
+
A minimal example script, `example.twill`, might look like this:
|
|
35
|
+
|
|
36
|
+
```text
|
|
37
|
+
go /foo/bar
|
|
38
|
+
code 200
|
|
39
|
+
find "foobar"
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
This loads `/foo/bar` from the configured base URL and asserts that the response has
|
|
43
|
+
status code `200` and contains the text `foobar`.
|
|
44
|
+
|
|
45
|
+
To run a script:
|
|
46
|
+
|
|
47
|
+
```bash
|
|
48
|
+
gfrast example.twill
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
By default, GFRAST uses `https://gams.uni-graz.at` as the base URL. You can override
|
|
52
|
+
that with `-u` / `--baseurl`:
|
|
53
|
+
|
|
54
|
+
```bash
|
|
55
|
+
gfrast -u https://example.com example.twill
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
You can run multiple scripts by passing several files:
|
|
59
|
+
|
|
60
|
+
```bash
|
|
61
|
+
gfrast -u https://example.com example1.twill example2.twill
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
Or you can point GFRAST to a directory. It will recursively run all `.twill` files
|
|
65
|
+
inside that directory:
|
|
66
|
+
|
|
67
|
+
```bash
|
|
68
|
+
gfrast -u https://example.com my_scripts
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
This is especially useful for organizing tests by project or repository section.
|
|
72
|
+
|
|
73
|
+
### Command-line options
|
|
74
|
+
|
|
75
|
+
The CLI supports the following options:
|
|
76
|
+
|
|
77
|
+
- `-u`, `--baseurl <URL>`: Set the base URL prepended to each `go` command.
|
|
78
|
+
- `-w`, `--workers <INTEGER>`: Number of worker processes to use. Default is `1`.
|
|
79
|
+
- `--log-level <STRING>`: Set the log level (`ERROR`, `WARNING`, `INFO`, `DEBUG`).
|
|
80
|
+
- `--logfile <PATH>`: Path for the JSON summary log file. Default is `gfrast.log.json`.
|
|
81
|
+
- `--no-log`: Disable writing the JSON summary file.
|
|
82
|
+
|
|
83
|
+
## Script files
|
|
84
|
+
|
|
85
|
+
A Twill script is just a plain text file that controls the client.
|
|
86
|
+
|
|
87
|
+
Example:
|
|
88
|
+
|
|
89
|
+
```text
|
|
90
|
+
go /foo/bar
|
|
91
|
+
code 200
|
|
92
|
+
find "foobar"
|
|
93
|
+
```
|
|
94
|
+
|
|
95
|
+
The first line (`go /foo/bar`) issues the request. The base URL is prepended before
|
|
96
|
+
sending the request. For example, with `--baseurl https://example.com`, this becomes:
|
|
97
|
+
|
|
98
|
+
```text
|
|
99
|
+
https://example.com/foo/bar
|
|
100
|
+
```
|
|
101
|
+
|
|
102
|
+
The next line (`code 200`) asserts that the response status is `200`.
|
|
103
|
+
|
|
104
|
+
The third line (`find "foobar"`) asserts that the response body contains the string
|
|
105
|
+
`foobar`.
|
|
106
|
+
|
|
107
|
+
For more advanced behavior, Twill supports a wide range of commands for forms,
|
|
108
|
+
cookies, redirects, and more. See the official Twill docs:
|
|
109
|
+
https://twill.readthedocs.io/en/latest/commands.html
|
|
110
|
+
|
|
111
|
+
## Frequently used script commands
|
|
112
|
+
|
|
113
|
+
### `go <PATH>`
|
|
114
|
+
|
|
115
|
+
This is usually the first command in a script. Most other commands operate on the
|
|
116
|
+
result of the last `go` request.
|
|
117
|
+
|
|
118
|
+
```text
|
|
119
|
+
go /foo/bar
|
|
120
|
+
code 200
|
|
121
|
+
find "foobar"
|
|
122
|
+
```
|
|
123
|
+
|
|
124
|
+
When the base URL is set, `go` values are automatically expanded to full URLs.
|
|
125
|
+
|
|
126
|
+
### `code <INT>`
|
|
127
|
+
|
|
128
|
+
Asserts that the response status matches the given integer.
|
|
129
|
+
|
|
130
|
+
```text
|
|
131
|
+
code 200
|
|
132
|
+
```
|
|
133
|
+
|
|
134
|
+
### `find <PATTERN> [<FLAGS>]`
|
|
135
|
+
|
|
136
|
+
Checks whether the response contains the given pattern.
|
|
137
|
+
|
|
138
|
+
```text
|
|
139
|
+
find "foo"
|
|
140
|
+
```
|
|
141
|
+
|
|
142
|
+
This supports regular expressions and flags such as `i` (ignore case) and `m`
|
|
143
|
+
(multiline). It can also be used with XPath via the `x` flag.
|
|
144
|
+
|
|
145
|
+
Example:
|
|
146
|
+
|
|
147
|
+
```text
|
|
148
|
+
find "//xhtml:input/@id[.='query']" x
|
|
149
|
+
```
|
|
150
|
+
|
|
151
|
+
### `not_find`
|
|
152
|
+
|
|
153
|
+
Asserts that a pattern does not appear in the response.
|
|
154
|
+
|
|
155
|
+
### `url <PATTERN>`
|
|
156
|
+
|
|
157
|
+
Asserts that the current page URL matches a given pattern. This is especially useful
|
|
158
|
+
for redirect tests.
|
|
159
|
+
|
|
160
|
+
### `title <PATTERN>`
|
|
161
|
+
|
|
162
|
+
Asserts that the page title matches the supplied pattern.
|
|
163
|
+
|
|
164
|
+
### `header <NAME>[<PATTERN>]`
|
|
165
|
+
|
|
166
|
+
Checks that an HTTP header has the expected value.
|
|
167
|
+
|
|
168
|
+
### `echo`
|
|
169
|
+
|
|
170
|
+
Prints a string to the output stream.
|
|
171
|
+
|
|
172
|
+
### `info`
|
|
173
|
+
|
|
174
|
+
Displays information about the current page for debugging.
|
|
175
|
+
|
|
176
|
+
### `show`
|
|
177
|
+
|
|
178
|
+
Prints the current page content for debugging.
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
## Development
|
|
182
|
+
|
|
183
|
+
The git.uni-graz.at server is only a mirror for the private repository, where the development takes place.
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "gfrast"
|
|
3
|
+
version = "0.3.0"
|
|
4
|
+
description = "GFRAST (GAMS Flexible Repository ASsertion Tool) is a small script to test HTTP server responses."
|
|
5
|
+
readme = "README.md"
|
|
6
|
+
license = "MIT-0"
|
|
7
|
+
license-files = ["LICENSE"]
|
|
8
|
+
requires-python = ">=3.10"
|
|
9
|
+
dependencies = ["twill>=3.4.0"]
|
|
10
|
+
keywords = [
|
|
11
|
+
"GAMS",
|
|
12
|
+
"twill",
|
|
13
|
+
"testing",
|
|
14
|
+
]
|
|
15
|
+
classifiers = [
|
|
16
|
+
"Development Status :: 4 - Beta",
|
|
17
|
+
"Intended Audience :: Developers",
|
|
18
|
+
"Intended Audience :: System Administrators",
|
|
19
|
+
"Topic :: Internet :: WWW/HTTP",
|
|
20
|
+
"Topic :: Software Development :: Testing",
|
|
21
|
+
"Programming Language :: Python :: 3.10",
|
|
22
|
+
"Programming Language :: Python :: 3.11",
|
|
23
|
+
"Programming Language :: Python :: 3.12",
|
|
24
|
+
"Programming Language :: Python :: 3.13",
|
|
25
|
+
"Programming Language :: Python :: 3.14",
|
|
26
|
+
"Programming Language :: Python :: 3.15",
|
|
27
|
+
]
|
|
28
|
+
|
|
29
|
+
[[project.authors]]
|
|
30
|
+
name = "Gunter Vasold"
|
|
31
|
+
email = "gunter.vasold@uni-graz.at"
|
|
32
|
+
|
|
33
|
+
[project.urls]
|
|
34
|
+
Homepage = "https://git.uni-graz.at/open/562-dh/gams/tools/gfrast"
|
|
35
|
+
Issues = "https://git.uni-graz.at/open/562-dh/gams/tools/gfrast/issues"
|
|
36
|
+
Documentation = "https://git.uni-graz.at/open/562-dh/gams/tools/gfrast"
|
|
37
|
+
Source = "https://git.uni-graz.at/open/562-dh/gams/tools/gfrast"
|
|
38
|
+
Download = "https://pypi.org/project/gfrast"
|
|
39
|
+
|
|
40
|
+
[project.scripts]
|
|
41
|
+
gfrast = "gfrast.cli:main"
|
|
42
|
+
|
|
43
|
+
[build-system]
|
|
44
|
+
requires = ["uv_build>=0.13,<0.14"]
|
|
45
|
+
build-backend = "uv_build"
|
|
46
|
+
|
|
47
|
+
[dependency-groups]
|
|
48
|
+
dev = [
|
|
49
|
+
"pre-commit>=4.6.2",
|
|
50
|
+
"pytest>=9.1.1",
|
|
51
|
+
"pytest-cov>=7.1.0",
|
|
52
|
+
"ruff>=0.17.4",
|
|
53
|
+
]
|
|
54
|
+
|
|
55
|
+
[tool.pytest.ini_options]
|
|
56
|
+
addopts = [
|
|
57
|
+
"--cov=src",
|
|
58
|
+
"--cov-report=term-missing",
|
|
59
|
+
]
|
|
60
|
+
|
|
61
|
+
[tool.ruff]
|
|
62
|
+
line-length = 119
|
|
63
|
+
target-version = "py310"
|
|
64
|
+
src = [
|
|
65
|
+
"src",
|
|
66
|
+
"scripts",
|
|
67
|
+
]
|
|
68
|
+
|
|
69
|
+
[tool.ruff.lint]
|
|
70
|
+
select = [
|
|
71
|
+
"E",
|
|
72
|
+
"F",
|
|
73
|
+
"I",
|
|
74
|
+
"UP",
|
|
75
|
+
]
|
|
76
|
+
|
|
77
|
+
[tool.ruff.format]
|
|
78
|
+
quote-style = "double"
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "gfrast"
|
|
3
|
+
version = "0.3.0"
|
|
4
|
+
description = "GFRAST (GAMS Flexible Repository ASsertion Tool) is a small script to test HTTP server responses."
|
|
5
|
+
readme = "README.md"
|
|
6
|
+
authors = [
|
|
7
|
+
{ name = "Gunter Vasold", email = "gunter.vasold@uni-graz.at" }
|
|
8
|
+
]
|
|
9
|
+
license = "MIT-0"
|
|
10
|
+
license-files = ["LICENSE"]
|
|
11
|
+
|
|
12
|
+
requires-python = ">=3.10"
|
|
13
|
+
dependencies = [
|
|
14
|
+
"twill>=3.4.0",
|
|
15
|
+
]
|
|
16
|
+
keywords = ["GAMS", "twill", "testing"]
|
|
17
|
+
|
|
18
|
+
classifiers = [
|
|
19
|
+
"Development Status :: 4 - Beta",
|
|
20
|
+
"Intended Audience :: Developers",
|
|
21
|
+
"Intended Audience :: System Administrators",
|
|
22
|
+
"Topic :: Internet :: WWW/HTTP",
|
|
23
|
+
"Topic :: Software Development :: Testing",
|
|
24
|
+
"Programming Language :: Python :: 3.10",
|
|
25
|
+
"Programming Language :: Python :: 3.11",
|
|
26
|
+
"Programming Language :: Python :: 3.12",
|
|
27
|
+
"Programming Language :: Python :: 3.13",
|
|
28
|
+
"Programming Language :: Python :: 3.14",
|
|
29
|
+
"Programming Language :: Python :: 3.15",
|
|
30
|
+
]
|
|
31
|
+
|
|
32
|
+
[project.urls]
|
|
33
|
+
Homepage = "https://git.uni-graz.at/open/562-dh/gams/tools/gfrast"
|
|
34
|
+
Issues = "https://git.uni-graz.at/open/562-dh/gams/tools/gfrast/issues"
|
|
35
|
+
Documentation = "https://git.uni-graz.at/open/562-dh/gams/tools/gfrast"
|
|
36
|
+
Source = "https://git.uni-graz.at/open/562-dh/gams/tools/gfrast"
|
|
37
|
+
Download = "https://pypi.org/project/gfrast"
|
|
38
|
+
|
|
39
|
+
[project.scripts]
|
|
40
|
+
gfrast = "gfrast.cli:main"
|
|
41
|
+
|
|
42
|
+
[build-system]
|
|
43
|
+
requires = ["uv_build>=0.13,<0.14"]
|
|
44
|
+
build-backend = "uv_build"
|
|
45
|
+
|
|
46
|
+
[dependency-groups]
|
|
47
|
+
dev = [
|
|
48
|
+
"pre-commit>=4.6.2",
|
|
49
|
+
"pytest>=9.1.1",
|
|
50
|
+
"pytest-cov>=7.1.0",
|
|
51
|
+
"ruff>=0.17.4",
|
|
52
|
+
]
|
|
53
|
+
|
|
54
|
+
[tool.pytest.ini_options]
|
|
55
|
+
addopts = [
|
|
56
|
+
"--cov=src",
|
|
57
|
+
"--cov-report=term-missing",
|
|
58
|
+
]
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
[tool.ruff]
|
|
62
|
+
line-length = 119
|
|
63
|
+
target-version = "py310"
|
|
64
|
+
src = ["src", "scripts"]
|
|
65
|
+
|
|
66
|
+
[tool.ruff.lint]
|
|
67
|
+
select = [
|
|
68
|
+
"E",
|
|
69
|
+
"F",
|
|
70
|
+
"I",
|
|
71
|
+
"UP"
|
|
72
|
+
]
|
|
73
|
+
|
|
74
|
+
[tool.ruff.format]
|
|
75
|
+
quote-style = "double"
|
|
File without changes
|
|
@@ -0,0 +1,173 @@
|
|
|
1
|
+
"The command line interface for gfrast."
|
|
2
|
+
|
|
3
|
+
import argparse
|
|
4
|
+
import json
|
|
5
|
+
import logging
|
|
6
|
+
from concurrent.futures import ProcessPoolExecutor
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
|
|
9
|
+
from gfrast.common import RunSummary, ScriptResult, TwillRunner, find_scripts
|
|
10
|
+
|
|
11
|
+
log = logging.getLogger()
|
|
12
|
+
|
|
13
|
+
DEFAULT_LOG_FILE = "gfrast.log.json"
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def restricted_range(min_val, max_val):
|
|
17
|
+
"""Factory function to create a validator that restricts an integer to a range."""
|
|
18
|
+
|
|
19
|
+
def validator(arg):
|
|
20
|
+
try:
|
|
21
|
+
value = int(arg)
|
|
22
|
+
except ValueError as e:
|
|
23
|
+
raise argparse.ArgumentTypeError(f"'{arg}' is not a valid integer.") from e
|
|
24
|
+
|
|
25
|
+
if not min_val <= value <= max_val:
|
|
26
|
+
raise argparse.ArgumentTypeError(
|
|
27
|
+
f"Value is out of range. Must be between {min_val} and {max_val} (given: {value})."
|
|
28
|
+
)
|
|
29
|
+
return value
|
|
30
|
+
|
|
31
|
+
return validator
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _make_arg_parser() -> argparse.ArgumentParser:
|
|
35
|
+
"Make an argument parser for the command line interface."
|
|
36
|
+
parser = argparse.ArgumentParser(description="Run a Twill script.")
|
|
37
|
+
parser.add_argument(
|
|
38
|
+
"scripts",
|
|
39
|
+
type=str,
|
|
40
|
+
nargs="+",
|
|
41
|
+
metavar="SCRIPT or DIRECTORY",
|
|
42
|
+
help=(
|
|
43
|
+
"Path to the Twill script or a directory containing twill scripts. "
|
|
44
|
+
"If a directory is provided, all '*.twill' files in that directory "
|
|
45
|
+
"and all sub directories will be run. Can be set multiple times to "
|
|
46
|
+
"run multiple scripts or directories."
|
|
47
|
+
),
|
|
48
|
+
)
|
|
49
|
+
parser.add_argument(
|
|
50
|
+
"-u",
|
|
51
|
+
"--baseurl",
|
|
52
|
+
type=str,
|
|
53
|
+
required=False,
|
|
54
|
+
default="https://gams.uni-graz.at",
|
|
55
|
+
help=(
|
|
56
|
+
"Base URL of the test server. This is what is put in "
|
|
57
|
+
"front of relative URLs in the Twill script. "
|
|
58
|
+
"(e.g. https://gams.uni-graz.at - with is the default base URL). "
|
|
59
|
+
"If not set, make sure the 'baseurl' variable is set in the Twill script."
|
|
60
|
+
),
|
|
61
|
+
)
|
|
62
|
+
parser.add_argument("--log-level", type=str, default="INFO", help="Set the logging level.")
|
|
63
|
+
parser.add_argument(
|
|
64
|
+
"--no-log",
|
|
65
|
+
action="store_true",
|
|
66
|
+
help="Disable logging to a file.",
|
|
67
|
+
)
|
|
68
|
+
parser.add_argument(
|
|
69
|
+
"--logfile",
|
|
70
|
+
type=str,
|
|
71
|
+
default=DEFAULT_LOG_FILE,
|
|
72
|
+
help=f"Path to the log file. Default: {DEFAULT_LOG_FILE}",
|
|
73
|
+
)
|
|
74
|
+
parser.add_argument(
|
|
75
|
+
"--workers",
|
|
76
|
+
"-w",
|
|
77
|
+
type=restricted_range(1, 5),
|
|
78
|
+
default=1,
|
|
79
|
+
help="Number of worker processes to use.",
|
|
80
|
+
)
|
|
81
|
+
return parser
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def set_log_level(level: int | str | None = None) -> int:
|
|
85
|
+
"""Set the logging level.
|
|
86
|
+
|
|
87
|
+
If no level is passed, use INFO as logging level.
|
|
88
|
+
|
|
89
|
+
Returns the resolved logging level as an integer.
|
|
90
|
+
"""
|
|
91
|
+
if level is None:
|
|
92
|
+
resolved_level = logging.INFO
|
|
93
|
+
elif isinstance(level, int):
|
|
94
|
+
resolved_level = level
|
|
95
|
+
else:
|
|
96
|
+
resolved_level = getattr(logging, level.upper(), logging.INFO)
|
|
97
|
+
log.setLevel(resolved_level)
|
|
98
|
+
return resolved_level
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def _print_script_result(result: ScriptResult, verbose: bool) -> None:
|
|
102
|
+
print(
|
|
103
|
+
f"[{result.status}]\n\t"
|
|
104
|
+
f"{result.line_count} lines, "
|
|
105
|
+
f"{result.assertion_failed_count} failed assertions, "
|
|
106
|
+
f"{result.http_error_count} http errors,"
|
|
107
|
+
f"{result.warning_count} warnings "
|
|
108
|
+
)
|
|
109
|
+
|
|
110
|
+
if not verbose and not result.failed:
|
|
111
|
+
return
|
|
112
|
+
|
|
113
|
+
for event in result.events:
|
|
114
|
+
print(f" - {event.name}: {event.line}")
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def _print_final_summary(summary: RunSummary) -> None:
|
|
118
|
+
"Print the final summary of the run."
|
|
119
|
+
print("=" * 40)
|
|
120
|
+
print("Run summary:")
|
|
121
|
+
print(f"duration: {summary.duration:.2f} seconds")
|
|
122
|
+
print(f"\tNumber of scripts processed: {summary.total_scripts}")
|
|
123
|
+
print(f"\tNumber of URLs checked: {summary.total_urls}")
|
|
124
|
+
print(f"\tNumber of assertions: {summary.total_lines}")
|
|
125
|
+
print(f"\tNumber of failed scripts: {summary.failed_scripts}")
|
|
126
|
+
print(f"\tNumber of failed assertions: {summary.total_assertions_failed}")
|
|
127
|
+
print(f"\tNumber of http errors: {summary.total_http_errors}")
|
|
128
|
+
print(f"\tNumber of warnings: {summary.total_warnings}")
|
|
129
|
+
print("=" * 40)
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def _write_json_summary(path: str, summary: RunSummary) -> None:
|
|
133
|
+
output_path = Path(path)
|
|
134
|
+
output_path.parent.mkdir(parents=True, exist_ok=True)
|
|
135
|
+
output_path.write_text(json.dumps(summary.to_dict(), indent=2), encoding="utf-8")
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def _run_one(script: str, baseurl) -> ScriptResult:
|
|
139
|
+
return TwillRunner(baseurl).run_script(script)
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def main() -> None:
|
|
143
|
+
"Run the TwillRunner from the command line."
|
|
144
|
+
parser = _make_arg_parser()
|
|
145
|
+
args = parser.parse_args()
|
|
146
|
+
logging_level = set_log_level(args.log_level)
|
|
147
|
+
verbose = logging_level <= logging.WARNING
|
|
148
|
+
|
|
149
|
+
summary = RunSummary()
|
|
150
|
+
scripts = sorted(find_scripts(args.scripts))
|
|
151
|
+
if not scripts:
|
|
152
|
+
print(f"No .twill scripts found at: {args.scripts}")
|
|
153
|
+
raise SystemExit(1)
|
|
154
|
+
|
|
155
|
+
with ProcessPoolExecutor(max_workers=args.workers) as pool:
|
|
156
|
+
results = pool.map(
|
|
157
|
+
_run_one,
|
|
158
|
+
scripts,
|
|
159
|
+
[args.baseurl] * len(scripts),
|
|
160
|
+
)
|
|
161
|
+
for script, result in zip(scripts, results):
|
|
162
|
+
summary.add(result)
|
|
163
|
+
print(f"{script} ...", end=" ")
|
|
164
|
+
_print_script_result(result, verbose)
|
|
165
|
+
|
|
166
|
+
_print_final_summary(summary)
|
|
167
|
+
|
|
168
|
+
if not args.no_log:
|
|
169
|
+
_write_json_summary(args.logfile, summary)
|
|
170
|
+
print(f"JSON summary written to: {args.logfile}")
|
|
171
|
+
|
|
172
|
+
if summary.has_failures:
|
|
173
|
+
raise SystemExit(1)
|
|
@@ -0,0 +1,410 @@
|
|
|
1
|
+
"""Shared classes and functions for running Twill scripts and parsing their output."""
|
|
2
|
+
|
|
3
|
+
import logging
|
|
4
|
+
import re
|
|
5
|
+
import time
|
|
6
|
+
from collections.abc import Callable, Iterable
|
|
7
|
+
from contextlib import redirect_stderr, redirect_stdout
|
|
8
|
+
from dataclasses import dataclass, field
|
|
9
|
+
from datetime import datetime
|
|
10
|
+
from io import StringIO
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
from typing import TextIO
|
|
13
|
+
|
|
14
|
+
from twill.parse import execute_file
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
@dataclass(frozen=True, slots=True)
|
|
18
|
+
class EventRecord:
|
|
19
|
+
"""Structured event payload produced by the Twill output parser."""
|
|
20
|
+
|
|
21
|
+
name: str
|
|
22
|
+
source: str
|
|
23
|
+
line: str
|
|
24
|
+
metadata: dict[str, str]
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
EventCallback = Callable[[EventRecord], None]
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
@dataclass(slots=True)
|
|
31
|
+
class ScriptResult:
|
|
32
|
+
"""Result data for one executed Twill script."""
|
|
33
|
+
|
|
34
|
+
script: str
|
|
35
|
+
events: list[EventRecord] = field(default_factory=list)
|
|
36
|
+
line_count: int = 0
|
|
37
|
+
url_count: int = 0
|
|
38
|
+
assertion_failed_count: int = 0
|
|
39
|
+
http_error_count: int = 0
|
|
40
|
+
warning_count: int = 0
|
|
41
|
+
duration: float = 0.0 # Duration of the script execution in seconds
|
|
42
|
+
_saw_at_line: bool = field(default=False, init=False, repr=False, compare=False)
|
|
43
|
+
|
|
44
|
+
def add_event(self, event: EventRecord) -> None:
|
|
45
|
+
"Add an event to the result and update counters."
|
|
46
|
+
if event.name == "line":
|
|
47
|
+
# Twill announces the script line being executed as "AT LINE: ...".
|
|
48
|
+
# When that marker is absent (for instance in mocked tests or helper
|
|
49
|
+
# output), fall back to counting ordinary emitted lines until the first
|
|
50
|
+
# "AT LINE" marker is seen.
|
|
51
|
+
if "AT LINE:" in event.line:
|
|
52
|
+
if not self._saw_at_line:
|
|
53
|
+
self._saw_at_line = True
|
|
54
|
+
return
|
|
55
|
+
self.line_count += 1
|
|
56
|
+
return
|
|
57
|
+
|
|
58
|
+
# line: ==> at http://example.com/foo/bar
|
|
59
|
+
# the first one is only the baseurl and should not increase the count
|
|
60
|
+
if "at http" in event.line and self.line_count > 0 and self.url_count == 0:
|
|
61
|
+
self.url_count += 1
|
|
62
|
+
# twill first prints the line and then the url, so we need to
|
|
63
|
+
# decrement the line count for this line
|
|
64
|
+
self.line_count -= 1
|
|
65
|
+
return
|
|
66
|
+
|
|
67
|
+
if not self._saw_at_line:
|
|
68
|
+
self.line_count += 1
|
|
69
|
+
return
|
|
70
|
+
|
|
71
|
+
self.events.append(event)
|
|
72
|
+
if event.name == "assertion_failed":
|
|
73
|
+
self.assertion_failed_count += 1
|
|
74
|
+
elif event.name == "http_error":
|
|
75
|
+
self.http_error_count += 1
|
|
76
|
+
elif event.name == "warning":
|
|
77
|
+
self.warning_count += 1
|
|
78
|
+
|
|
79
|
+
@property
|
|
80
|
+
def failed(self) -> bool:
|
|
81
|
+
"Return True if the script failed (assertion or HTTP error), False otherwise."
|
|
82
|
+
return self.assertion_failed_count > 0 or self.http_error_count > 0
|
|
83
|
+
|
|
84
|
+
@property
|
|
85
|
+
def status(self) -> str:
|
|
86
|
+
"Return 'FAIL' if the script failed, 'PASS' otherwise."
|
|
87
|
+
return "FAIL" if self.failed else "PASS"
|
|
88
|
+
|
|
89
|
+
def to_dict(self) -> dict[str, object]:
|
|
90
|
+
"Return a dictionary representation of the script result."
|
|
91
|
+
return {
|
|
92
|
+
"script": self.script,
|
|
93
|
+
"status": self.status,
|
|
94
|
+
"failed": self.failed,
|
|
95
|
+
"URLs checked": self.url_count,
|
|
96
|
+
"assertions": self.line_count,
|
|
97
|
+
"assertions failed": self.assertion_failed_count,
|
|
98
|
+
"http errors": self.http_error_count,
|
|
99
|
+
"warnings": self.warning_count,
|
|
100
|
+
"duration": self.duration,
|
|
101
|
+
"events": [
|
|
102
|
+
{
|
|
103
|
+
"name": event.name,
|
|
104
|
+
"source": event.source,
|
|
105
|
+
"line": event.line,
|
|
106
|
+
"metadata": event.metadata,
|
|
107
|
+
}
|
|
108
|
+
for event in self.events
|
|
109
|
+
],
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
@dataclass(slots=True)
|
|
114
|
+
class RunSummary:
|
|
115
|
+
"""Aggregate result data for a full run over one or more scripts."""
|
|
116
|
+
|
|
117
|
+
scripts: list[ScriptResult] = field(default_factory=list)
|
|
118
|
+
start_time: float = field(default=0.0, init=False)
|
|
119
|
+
end_time: float | None = field(default=None, init=False)
|
|
120
|
+
|
|
121
|
+
def __post_init__(self) -> None:
|
|
122
|
+
self.start_time: float = time.time()
|
|
123
|
+
|
|
124
|
+
def add(self, result: ScriptResult) -> None:
|
|
125
|
+
"Add a script result to the summary."
|
|
126
|
+
self.scripts.append(result)
|
|
127
|
+
self.end_time = time.time() # Update end time on each addition
|
|
128
|
+
|
|
129
|
+
@property
|
|
130
|
+
def total_scripts(self) -> int:
|
|
131
|
+
"Return the total number of scripts run."
|
|
132
|
+
return len(self.scripts)
|
|
133
|
+
|
|
134
|
+
@property
|
|
135
|
+
def failed_scripts(self) -> int:
|
|
136
|
+
"Return the number of scripts that failed."
|
|
137
|
+
return sum(1 for script in self.scripts if script.failed)
|
|
138
|
+
|
|
139
|
+
@property
|
|
140
|
+
def passed_scripts(self) -> int:
|
|
141
|
+
"Return the number of scripts that passed."
|
|
142
|
+
return self.total_scripts - self.failed_scripts
|
|
143
|
+
|
|
144
|
+
@property
|
|
145
|
+
def total_lines(self) -> int:
|
|
146
|
+
"Return the total number of lines processed across all scripts."
|
|
147
|
+
return sum(script.line_count for script in self.scripts)
|
|
148
|
+
|
|
149
|
+
@property
|
|
150
|
+
def total_urls(self) -> int:
|
|
151
|
+
"Return the total number of URLs checked across all scripts."
|
|
152
|
+
return sum(script.url_count for script in self.scripts)
|
|
153
|
+
|
|
154
|
+
@property
|
|
155
|
+
def total_assertions_failed(self) -> int:
|
|
156
|
+
"Return the total number of assertion failures across all scripts."
|
|
157
|
+
return sum(script.assertion_failed_count for script in self.scripts)
|
|
158
|
+
|
|
159
|
+
@property
|
|
160
|
+
def total_http_errors(self) -> int:
|
|
161
|
+
"Return the total number of HTTP errors across all scripts."
|
|
162
|
+
return sum(script.http_error_count for script in self.scripts)
|
|
163
|
+
|
|
164
|
+
@property
|
|
165
|
+
def total_warnings(self) -> int:
|
|
166
|
+
"Return the total number of warnings across all scripts."
|
|
167
|
+
return sum(script.warning_count for script in self.scripts)
|
|
168
|
+
|
|
169
|
+
@property
|
|
170
|
+
def has_failures(self) -> bool:
|
|
171
|
+
"Return True if any script failed, False otherwise."
|
|
172
|
+
return self.failed_scripts > 0
|
|
173
|
+
|
|
174
|
+
@property
|
|
175
|
+
def duration(self) -> float:
|
|
176
|
+
"Return the total duration of the run in seconds."
|
|
177
|
+
if self.end_time is None:
|
|
178
|
+
return 0.0
|
|
179
|
+
return self.end_time - self.start_time
|
|
180
|
+
|
|
181
|
+
@property
|
|
182
|
+
def finished_at(self) -> float | None:
|
|
183
|
+
"Return the timestamp when the run finished, or None if not finished."
|
|
184
|
+
if self.end_time is not None:
|
|
185
|
+
return datetime.fromtimestamp(self.end_time).isoformat()
|
|
186
|
+
return self.end_time
|
|
187
|
+
|
|
188
|
+
def to_dict(self) -> dict[str, object]:
|
|
189
|
+
"Return a dictionary representation of the summary."
|
|
190
|
+
return {
|
|
191
|
+
"finished_at": self.finished_at,
|
|
192
|
+
"duration": self.duration,
|
|
193
|
+
"total_scripts": self.total_scripts,
|
|
194
|
+
"passed_scripts": self.passed_scripts,
|
|
195
|
+
"failed_scripts": self.failed_scripts,
|
|
196
|
+
"total_lines": self.total_lines,
|
|
197
|
+
"total_assertions_failed": self.total_assertions_failed,
|
|
198
|
+
"total_http_errors": self.total_http_errors,
|
|
199
|
+
"total_warnings": self.total_warnings,
|
|
200
|
+
"scripts": [script.to_dict() for script in self.scripts],
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
class EventParser:
|
|
205
|
+
"""Parse output lines and dispatch named events to callbacks."""
|
|
206
|
+
|
|
207
|
+
def __init__(self) -> None:
|
|
208
|
+
self._rules: list[tuple[str, re.Pattern[str]]] = [
|
|
209
|
+
(
|
|
210
|
+
"assertion_failed",
|
|
211
|
+
re.compile(
|
|
212
|
+
r"(?:twillassertionerror|assertionerror|\bassert(?:ion)?\b|\bfailed\b)",
|
|
213
|
+
re.IGNORECASE,
|
|
214
|
+
),
|
|
215
|
+
),
|
|
216
|
+
(
|
|
217
|
+
"http_error",
|
|
218
|
+
re.compile(
|
|
219
|
+
r"(?:\bHTTP(?:/\d\.\d)?\s+[45]\d\d\b|\bhttp error\b|\bcode is [45]\d\d\b)",
|
|
220
|
+
re.IGNORECASE,
|
|
221
|
+
),
|
|
222
|
+
),
|
|
223
|
+
("warning", re.compile(r"\bwarn(?:ing)?\b", re.IGNORECASE)),
|
|
224
|
+
# ("go", re.compile(r"^==>\s+at\s+.+$", re.IGNORECASE)),
|
|
225
|
+
]
|
|
226
|
+
self._callbacks: dict[str, list[EventCallback]] = {}
|
|
227
|
+
self._callbacks.setdefault("line", [])
|
|
228
|
+
|
|
229
|
+
def on(self, event_name: str, callback: EventCallback) -> None:
|
|
230
|
+
"Register a callback for a specific event."
|
|
231
|
+
self._callbacks.setdefault(event_name, []).append(callback)
|
|
232
|
+
|
|
233
|
+
def off(self, event_name: str, callback: EventCallback) -> None:
|
|
234
|
+
"Remove a previously registered callback for a specific event."
|
|
235
|
+
callbacks = self._callbacks.get(event_name)
|
|
236
|
+
if not callbacks:
|
|
237
|
+
return
|
|
238
|
+
try:
|
|
239
|
+
callbacks.remove(callback)
|
|
240
|
+
except ValueError:
|
|
241
|
+
return
|
|
242
|
+
if not callbacks:
|
|
243
|
+
self._callbacks.pop(event_name, None)
|
|
244
|
+
|
|
245
|
+
def emit(
|
|
246
|
+
self,
|
|
247
|
+
event_name: str,
|
|
248
|
+
source: str,
|
|
249
|
+
line: str,
|
|
250
|
+
metadata: dict[str, str] | None = None,
|
|
251
|
+
) -> None:
|
|
252
|
+
"Emit an event to all registered callbacks."
|
|
253
|
+
event = EventRecord(
|
|
254
|
+
name=event_name,
|
|
255
|
+
source=source,
|
|
256
|
+
line=line,
|
|
257
|
+
metadata=metadata or {},
|
|
258
|
+
)
|
|
259
|
+
for callback in self._callbacks.get(event_name, []):
|
|
260
|
+
callback(event)
|
|
261
|
+
|
|
262
|
+
def feed_line(self, source: str, line: str) -> None:
|
|
263
|
+
"Feed a line of output to the parser."
|
|
264
|
+
self.emit("line", source, line, {})
|
|
265
|
+
for event_name, pattern in self._rules:
|
|
266
|
+
match = pattern.search(line)
|
|
267
|
+
if match:
|
|
268
|
+
metadata: dict[str, str] = {}
|
|
269
|
+
if match.group(0):
|
|
270
|
+
metadata["match"] = match.group(0)
|
|
271
|
+
self.emit(event_name, source, line, metadata)
|
|
272
|
+
|
|
273
|
+
|
|
274
|
+
class EventStream:
|
|
275
|
+
"""Write-through stream that forwards complete lines to an EventParser."""
|
|
276
|
+
|
|
277
|
+
def __init__(self, sink: TextIO, parser: EventParser, source: str) -> None:
|
|
278
|
+
self._sink = sink
|
|
279
|
+
self._parser = parser
|
|
280
|
+
self._source = source
|
|
281
|
+
self._buffer = ""
|
|
282
|
+
|
|
283
|
+
def write(self, text: str) -> int:
|
|
284
|
+
"Write text to the sink and feed complete lines to the parser."
|
|
285
|
+
written = self._sink.write(text)
|
|
286
|
+
self._buffer += text
|
|
287
|
+
|
|
288
|
+
while True:
|
|
289
|
+
newline_index = self._buffer.find("\n")
|
|
290
|
+
if newline_index == -1:
|
|
291
|
+
break
|
|
292
|
+
line = self._buffer[:newline_index]
|
|
293
|
+
self._buffer = self._buffer[newline_index + 1 :]
|
|
294
|
+
self._parser.feed_line(self._source, line)
|
|
295
|
+
|
|
296
|
+
return written
|
|
297
|
+
|
|
298
|
+
def flush(self) -> None:
|
|
299
|
+
"Flush the sink and feed any remaining buffered text to the parser."
|
|
300
|
+
self._sink.flush()
|
|
301
|
+
|
|
302
|
+
def finalize(self) -> None:
|
|
303
|
+
"Feed any remaining buffered text to the parser."
|
|
304
|
+
if self._buffer:
|
|
305
|
+
self._parser.feed_line(self._source, self._buffer)
|
|
306
|
+
self._buffer = ""
|
|
307
|
+
|
|
308
|
+
|
|
309
|
+
class TwillRunner:
|
|
310
|
+
"Represents a single run of Twill."
|
|
311
|
+
|
|
312
|
+
def __init__(self, baseurl=None) -> None:
|
|
313
|
+
"""Initialize the runner."""
|
|
314
|
+
self.baseurl = baseurl
|
|
315
|
+
self.stdout: TextIO | None = None
|
|
316
|
+
self.stderr: TextIO | None = None
|
|
317
|
+
self.event_parser = EventParser()
|
|
318
|
+
self.duration: float = 0.0 # Duration of the script execution in seconds
|
|
319
|
+
|
|
320
|
+
def run_script(self, script: str) -> ScriptResult:
|
|
321
|
+
"""Run the Twill script."""
|
|
322
|
+
start_time = time.time()
|
|
323
|
+
script_result = ScriptResult(script=script)
|
|
324
|
+
event_sink = script_result.add_event
|
|
325
|
+
for event_name in (
|
|
326
|
+
"line",
|
|
327
|
+
"assertion_failed",
|
|
328
|
+
"http_error",
|
|
329
|
+
"warning",
|
|
330
|
+
):
|
|
331
|
+
self.add_event_handler(event_name, event_sink)
|
|
332
|
+
|
|
333
|
+
# create new stdout/stderr
|
|
334
|
+
self.stdout = StringIO()
|
|
335
|
+
self.stderr = StringIO()
|
|
336
|
+
event_stdout = EventStream(self.stdout, self.event_parser, "stdout")
|
|
337
|
+
event_stderr = EventStream(self.stderr, self.event_parser, "stderr")
|
|
338
|
+
|
|
339
|
+
saved_streams = []
|
|
340
|
+
seen_handlers = set()
|
|
341
|
+
|
|
342
|
+
# Twill or libraries may log via dedicated named loggers, not only root.
|
|
343
|
+
all_loggers = [logging.getLogger()]
|
|
344
|
+
manager = logging.getLogger().manager
|
|
345
|
+
all_loggers.extend(logger for logger in manager.loggerDict.values() if isinstance(logger, logging.Logger))
|
|
346
|
+
|
|
347
|
+
for logger in all_loggers:
|
|
348
|
+
for handler in logger.handlers:
|
|
349
|
+
if not isinstance(handler, logging.StreamHandler):
|
|
350
|
+
continue
|
|
351
|
+
if id(handler) in seen_handlers:
|
|
352
|
+
continue
|
|
353
|
+
seen_handlers.add(id(handler))
|
|
354
|
+
saved_streams.append((handler, handler.stream))
|
|
355
|
+
if handler.level >= logging.ERROR:
|
|
356
|
+
handler.setStream(event_stderr)
|
|
357
|
+
else:
|
|
358
|
+
handler.setStream(event_stdout)
|
|
359
|
+
|
|
360
|
+
try:
|
|
361
|
+
with redirect_stdout(event_stdout), redirect_stderr(event_stderr):
|
|
362
|
+
self._run_url(script)
|
|
363
|
+
finally:
|
|
364
|
+
event_stdout.finalize()
|
|
365
|
+
event_stderr.finalize()
|
|
366
|
+
for handler, stream in saved_streams:
|
|
367
|
+
handler.setStream(stream)
|
|
368
|
+
for event_name in (
|
|
369
|
+
"line",
|
|
370
|
+
"assertion_failed",
|
|
371
|
+
"http_error",
|
|
372
|
+
"warning",
|
|
373
|
+
):
|
|
374
|
+
self.remove_event_handler(event_name, event_sink)
|
|
375
|
+
script_result.duration = time.time() - start_time
|
|
376
|
+
return script_result
|
|
377
|
+
|
|
378
|
+
def add_event_handler(self, event_name: str, callback: EventCallback) -> None:
|
|
379
|
+
"Register a callback for a specific event."
|
|
380
|
+
self.event_parser.on(event_name, callback)
|
|
381
|
+
|
|
382
|
+
def remove_event_handler(self, event_name: str, callback: EventCallback) -> None:
|
|
383
|
+
"Remove a previously registered callback for a specific event."
|
|
384
|
+
self.event_parser.off(event_name, callback)
|
|
385
|
+
|
|
386
|
+
def _run_url(self, script: str) -> None:
|
|
387
|
+
"""Really run the twill script.
|
|
388
|
+
|
|
389
|
+
The run_url method, which calls this method only deals with the output
|
|
390
|
+
streams and event handling. This method is responsible for executing
|
|
391
|
+
the Twill script.
|
|
392
|
+
"""
|
|
393
|
+
execute_file(
|
|
394
|
+
script,
|
|
395
|
+
initial_url=self.baseurl,
|
|
396
|
+
never_fail=True,
|
|
397
|
+
)
|
|
398
|
+
|
|
399
|
+
|
|
400
|
+
def find_scripts(paths: list[str] | None) -> Iterable[str]:
|
|
401
|
+
"Find all Twill scripts in the given path(s)."
|
|
402
|
+
if paths is None:
|
|
403
|
+
return
|
|
404
|
+
for path in paths:
|
|
405
|
+
p = Path(path)
|
|
406
|
+
if p.is_file() and p.suffix == ".twill":
|
|
407
|
+
yield str(p)
|
|
408
|
+
elif p.is_dir():
|
|
409
|
+
for twill_file in p.rglob("*.twill"):
|
|
410
|
+
yield str(twill_file)
|