source: mod_gnutls/test/https-test-client.py @ 096859f

asyncioproxy-ticket
Last change on this file since 096859f was 096859f, checked in by Fiona Klute <fiona.klute@…>, 23 months ago

https-test-client.py: Check if the HTTP body contains certain strings

There are a few test cases where we currently only check the end of
the returned body. Searching for certain strings within the body
instead of expecting a full match allows them to work with the
Python-based test client.

  • Property mode set to 100755
File size: 8.8 KB
Line 
1#!/usr/bin/python3
2# PYTHON_ARGCOMPLETE_OK
3
4# Copyright 2019 Fiona Klute
5#
6# Licensed under the Apache License, Version 2.0 (the "License");
7# you may not use this file except in compliance with the License.
8# You may obtain a copy of the License at
9#
10#     http://www.apache.org/licenses/LICENSE-2.0
11#
12# Unless required by applicable law or agreed to in writing, software
13# distributed under the License is distributed on an "AS IS" BASIS,
14# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15# See the License for the specific language governing permissions and
16# limitations under the License.
17
18import socket
19import subprocess
20import yaml
21
22from http.client import HTTPConnection
23from time import sleep
24
25class HTTPSubprocessConnection(HTTPConnection):
26    def __init__(self, command, host, port=None,
27                 timeout=socket._GLOBAL_DEFAULT_TIMEOUT,
28                 blocksize=8192):
29        super(HTTPSubprocessConnection, self).__init__(host, port, timeout,
30                                                       source_address=None,
31                                                       blocksize=blocksize)
32        # "command" must be a list containing binary and command line
33        # parameters
34        self.command = command
35        # This will be the subprocess reference when connected
36        self._sproc = None
37        # The subprocess return code is stored here on close()
38        self.returncode = None
39        # The set_tunnel method of the super class is not supported
40        # (see exception doc)
41        self.set_tunnel = None
42
43    def connect(self):
44        s_local, s_remote = socket.socketpair(socket.AF_UNIX,
45                                              socket.SOCK_STREAM)
46        s_local.settimeout(self.timeout)
47
48        # TODO: Maybe capture stderr?
49        self._sproc = subprocess.Popen(self.command, stdout=s_remote,
50                                       stdin=s_remote, close_fds=True)
51        s_remote.close()
52        self.sock = s_local
53
54    def close(self):
55        super().close()
56        # Wait for the process to stop, send SIGTERM/SIGKILL if
57        # necessary
58        self.returncode = self._sproc.wait(self.timeout)
59        if self.returncode == None:
60            self._sproc.terminate()
61            self.returncode = self._sproc.wait(self.timeout)
62            if self.returncode == None:
63                self._sproc.kill()
64                self.returncode = self._sproc.wait(self.timeout)
65
66
67
68class TestRequest(yaml.YAMLObject):
69    yaml_tag = '!request'
70    def __init__(self, path, method='GET', headers=dict(),
71                 expect=dict(status=200)):
72        self.method = method
73        self.path = path
74        self.headers = headers
75        self.expect = expect
76
77    def __repr__(self):
78        return (f'{self.__class__.__name__!s}(path={self.path!r}, '
79                f'method={self.method!r}, headers={self.headers!r}, '
80                f'expect={self.expect!r})')
81
82    def _check_body(self, body):
83        """
84        >>> r1 = TestRequest(path='/test.txt', method='GET', headers={}, expect={'status': 200, 'body': {'exactly': 'test\\n'}})
85        >>> r1._check_body('test\\n')
86        >>> r1._check_body('xyz\\n')
87        Traceback (most recent call last):
88        ...
89        https-test-client.TestExpectationFailed: Unexpected body: 'xyz\\n' != 'test\\n'
90        >>> r2 = TestRequest(path='/test.txt', method='GET', headers={}, expect={'status': 200, 'body': {'contains': ['tes', 'est']}})
91        >>> r2._check_body('test\\n')
92        >>> r2._check_body('est\\n')
93        Traceback (most recent call last):
94        ...
95        https-test-client.TestExpectationFailed: Unexpected body: 'est\\n' does not contain 'tes'
96        >>> r3 = TestRequest(path='/test.txt', method='GET', headers={}, expect={'status': 200, 'body': {'contains': 'test'}})
97        >>> r3._check_body('test\\n')
98        """
99        if 'exactly' in self.expect['body'] \
100           and body != self.expect['body']['exactly']:
101            raise TestExpectationFailed(
102                f'Unexpected body: {body!r} != '
103                f'{self.expect["body"]["exactly"]!r}')
104        if 'contains' in self.expect['body']:
105            if type(self.expect['body']['contains']) is str:
106                self.expect['body']['contains'] = [
107                    self.expect['body']['contains']]
108            for s in self.expect['body']['contains']:
109                if not s in body:
110                    raise TestExpectationFailed(
111                        f'Unexpected body: {body!r} does not contain '
112                        f'{s!r}')
113
114    def check_response(self, response, body):
115        if response.status != self.expect['status']:
116            raise TestExpectationFailed(
117                f'Unexpected status: {response.status} != '
118                f'{self.expect["status"]}')
119        if 'body' in self.expect:
120            self._check_body(body)
121
122    @classmethod
123    def _from_yaml(cls, loader, node):
124        fields = loader.construct_mapping(node)
125        req = TestRequest(**fields)
126        return req
127
128class TestConnection(yaml.YAMLObject):
129    yaml_tag = '!connection'
130
131    def __init__(self, actions, gnutls_params=[], protocol='https'):
132        self.gnutls_params = gnutls_params
133        self.actions = actions
134        self.protocol = protocol
135
136    def __repr__(self):
137        return (f'{self.__class__.__name__!s}'
138                f'(gnutls_params={self.gnutls_params!r}, '
139                f'actions={self.actions!r}, protocol={self.protocol!r})')
140
141    @classmethod
142    def _from_yaml(cls, loader, node):
143        fields = loader.construct_mapping(node)
144        conn = TestConnection(**fields)
145        return conn
146
147# Override the default constructors. Pyyaml ignores default parameters
148# otherwise.
149yaml.add_constructor('!request', TestRequest._from_yaml, yaml.Loader)
150yaml.add_constructor('!connection', TestConnection._from_yaml, yaml.Loader)
151
152
153
154class TestExpectationFailed(Exception):
155    """Raise if a test failed. The constructor should be called with a
156    string describing the problem."""
157    pass
158
159
160
161def format_response(resp, body):
162    s = f'{resp.status} {resp.reason}\n'
163    s = s + '\n'.join(f'{name}: {value}' for name, value in resp.getheaders())
164    s = s + '\n\n' + body
165    return s
166
167
168
169if __name__ == "__main__":
170    import argparse
171    parser = argparse.ArgumentParser(
172        description='Send HTTP requests through gnutls-cli',
173        formatter_class=argparse.ArgumentDefaultsHelpFormatter)
174    parser.add_argument('host', nargs='?', help='Access the specified host',
175                        default='localhost')
176    parser.add_argument('--insecure', action='store_true',
177                        help='do not validate the server certificate')
178    parser.add_argument('-p', '--port', type=int,
179                        help='Access the specified port', default='8000')
180    parser.add_argument('--x509cafile', type=str,
181                        help='Use the specified CA to validate the '
182                        'server certificate')
183    parser.add_argument('--test-config', type=argparse.FileType('r'),
184                        help='load YAML test configuration')
185
186    # enable bash completion if argcomplete is available
187    try:
188        import argcomplete
189        argcomplete.autocomplete(parser)
190    except ImportError:
191        pass
192
193    args = parser.parse_args()
194
195    test_conn = None
196    test_actions = None
197
198    if args.test_config:
199        config = yaml.load(args.test_config, Loader=yaml.Loader)
200        if type(config) is TestConnection:
201            test_conn = config
202            print(test_conn)
203            test_actions = test_conn.actions
204    else:
205        # simple default request
206        test_actions = [TestRequest(path='/test.txt',
207                                    expect={'status': 200, 'body': 'test\n'},
208                                    method='GET')]
209
210
211    # note: "--logfile" option requires GnuTLS version >= 3.6.7
212    command = ['gnutls-cli', '--logfile=/dev/stderr']
213    if args.insecure:
214        command.append('--insecure')
215    if args.x509cafile:
216        command.append('--x509cafile')
217        command.append(args.x509cafile)
218    if test_conn != None:
219        for s in test_conn.gnutls_params:
220            command.append('--' + s)
221    command = command + ['-p', str(args.port), args.host]
222
223    conn = HTTPSubprocessConnection(command, args.host, port=args.port,
224                                    timeout=6.0)
225
226    try:
227        for act in test_actions:
228            if type(act) is TestRequest:
229                # Add headers={'Host': 'test.host'} to provoke "421
230                # Misdirected
231                conn.request(act.method, act.path, headers=act.headers)
232                resp = conn.getresponse()
233                body = resp.read().decode()
234                print(format_response(resp, body))
235                act.check_response(resp, body)
236            else:
237                raise TypeError(f'Unsupported action requested: {act!r}')
238    finally:
239        conn.close()
Note: See TracBrowser for help on using the repository browser.