File: test_request_log_middleware.py

package info (click to toggle)
ironic-python-agent 11.5.0-1
  • links: PTS, VCS
  • area: main
  • in suites:
  • size: 4,328 kB
  • sloc: python: 38,539; sh: 60; makefile: 29
file content (353 lines) | stat: -rw-r--r-- 10,856 bytes parent folder | download | duplicates (2)
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
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
"""
Tests for the RequestLogMiddleware
"""

from unittest import mock

from ironic_python_agent.api import request_log
from ironic_python_agent.tests.unit import base


class TestRequestLogMiddleware(base.IronicAgentTest):
    """Test cases for RequestLogMiddleware."""

    def setUp(self):
        super(TestRequestLogMiddleware, self).setUp()

        # Create a mock application
        self.mock_app = mock.Mock()
        self.mock_app.return_value = [b'response body']

        # Create the middleware instance
        self.middleware = request_log.RequestLogMiddleware(self.mock_app)

        # Mock the logger
        self.mock_log = mock.patch.object(
            request_log, 'LOG', autospec=True
        ).start()

        self.template = ("%(source_ip)s - %(method)s %(path)s - %(status)s "
                         "(%(duration)sms)")

        # Mock time for consistent timing tests
        self.mock_time = mock.patch.object(
            request_log, 'time', autospec=True
        ).start()
        self.mock_time.time.side_effect = [1000.0, 1000.5]  # 500ms duration

    def test_successful_get_request(self):
        """Test logging of a successful GET request."""
        environ = {
            'REQUEST_METHOD': 'GET',
            'PATH_INFO': '/v1/status',
            'QUERY_STRING': ''
        }

        def start_response(status, headers, exc_info=None):
            return None

        # Configure mock app to call start_response with 200 OK
        def mock_app_call(env, sr):
            sr('200 OK', [('Content-Type', 'application/json')])
            return [b'response']

        self.mock_app.side_effect = mock_app_call

        # Call the middleware
        response = self.middleware(environ, start_response)

        # Verify the response is returned correctly
        self.assertEqual(response, [b'response'])

        # Verify the log was called with correct parameters
        self.mock_log.info.assert_called_once_with(
            self.template,
            {'method': 'GET',
             'path': '/v1/status',
             'status': 200,
             'duration': 500.0,
             'source_ip': 'unknown'}
        )

    def test_post_request_with_query_string(self):
        """Test logging of a POST request with query parameters."""
        environ = {
            'REQUEST_METHOD': 'POST',
            'PATH_INFO': '/v1/commands/',
            'QUERY_STRING': 'wait=true&agent_token=abc'
        }

        def start_response(status, headers, exc_info=None):
            return None

        def mock_app_call(env, sr):
            sr('201 Created', [('Content-Type', 'application/json')])
            return [b'created']

        self.mock_app.side_effect = mock_app_call

        response = self.middleware(environ, start_response)

        self.assertEqual(response, [b'created'])

        self.mock_log.info.assert_called_once_with(
            self.template,
            {'method': 'POST',
             'path': '/v1/commands/?wait=true&agent_token=abc',
             'status': 201,
             'duration': 500.0,
             'source_ip': 'unknown'}
        )

    def test_error_response(self):
        """Test logging of an error response."""
        environ = {
            'REQUEST_METHOD': 'GET',
            'PATH_INFO': '/v1/commands/123',
            'QUERY_STRING': ''
        }

        def start_response(status, headers, exc_info=None):
            return None

        def mock_app_call(env, sr):
            sr('404 Not Found', [('Content-Type', 'application/json')])
            return [b'not found']

        self.mock_app.side_effect = mock_app_call

        response = self.middleware(environ, start_response)

        self.assertEqual(response, [b'not found'])

        self.mock_log.info.assert_called_once_with(
            self.template,
            {'method': 'GET',
             'path': '/v1/commands/123',
             'status': 404,
             'duration': 500.0,
             'source_ip': 'unknown'}
        )

    def test_invalid_status_code(self):
        """Test handling of invalid status code."""
        environ = {
            'REQUEST_METHOD': 'GET',
            'PATH_INFO': '/v1/status',
            'QUERY_STRING': ''
        }

        def start_response(status, headers, exc_info=None):
            return None

        def mock_app_call(env, sr):
            sr('INVALID', [])  # Invalid status format
            return [b'response']

        self.mock_app.side_effect = mock_app_call

        response = self.middleware(environ, start_response)

        self.assertEqual(response, [b'response'])

        # Should log with status 'unknown' for invalid status
        self.mock_log.info.assert_called_once_with(
            self.template,
            {'method': 'GET',
             'path': '/v1/status',
             'status': 'unknown',
             'duration': 500.0,
             'source_ip': 'unknown'}
        )

    def test_generator_response(self):
        """Test handling of generator responses."""
        environ = {
            'REQUEST_METHOD': 'GET',
            'PATH_INFO': '/v1/status',
            'QUERY_STRING': ''
        }

        def start_response(status, headers, exc_info=None):
            return None

        def response_generator():
            yield b'part1'
            yield b'part2'

        def mock_app_call(env, sr):
            sr('200 OK', [])
            return response_generator()

        self.mock_app.side_effect = mock_app_call

        response = self.middleware(environ, start_response)

        # Response should be consumed and converted to list
        self.assertEqual(response, [b'part1', b'part2'])

        self.mock_log.info.assert_called_once()

    def test_missing_environ_values(self):
        """Test handling of missing environ values."""
        environ = {}  # Empty environ

        def start_response(status, headers, exc_info=None):
            return None

        def mock_app_call(env, sr):
            sr('200 OK', [])
            return [b'response']

        self.mock_app.side_effect = mock_app_call

        response = self.middleware(environ, start_response)

        self.assertEqual(response, [b'response'])

        # Should use empty strings for missing values
        self.mock_log.info.assert_called_once_with(
            self.template,
            {'method': '',
             'path': '',
             'status': 200,
             'duration': 500.0,
             'source_ip': 'unknown'}
        )

    def test_request_with_remote_addr(self):
        """Test logging with REMOTE_ADDR present."""
        environ = {
            'REQUEST_METHOD': 'GET',
            'PATH_INFO': '/v1/status',
            'QUERY_STRING': '',
            'REMOTE_ADDR': '192.168.1.100'
        }

        def start_response(status, headers, exc_info=None):
            return None

        def mock_app_call(env, sr):
            sr('200 OK', [])
            return [b'response']

        self.mock_app.side_effect = mock_app_call

        response = self.middleware(environ, start_response)

        self.assertEqual(response, [b'response'])

        # Should log with source IP
        self.mock_log.info.assert_called_once_with(
            self.template,
            {'method': 'GET',
             'path': '/v1/status',
             'status': 200,
             'duration': 500.0,
             'source_ip': '192.168.1.100'}
        )

    def test_request_with_x_forwarded_for(self):
        """Test logging with X-Forwarded-For header."""
        environ = {
            'REQUEST_METHOD': 'GET',
            'PATH_INFO': '/v1/status',
            'QUERY_STRING': '',
            'REMOTE_ADDR': '10.0.0.1',
            'HTTP_X_FORWARDED_FOR': '192.168.1.100, 10.0.0.2'
        }

        def start_response(status, headers, exc_info=None):
            return None

        def mock_app_call(env, sr):
            sr('200 OK', [])
            return [b'response']

        self.mock_app.side_effect = mock_app_call

        response = self.middleware(environ, start_response)

        self.assertEqual(response, [b'response'])

        # Should use first IP from X-Forwarded-For
        self.mock_log.info.assert_called_once_with(
            self.template,
            {'method': 'GET',
             'path': '/v1/status',
             'status': 200,
             'duration': 500.0,
             'source_ip': '192.168.1.100'}
        )

    def test_request_with_x_real_ip(self):
        """Test logging with X-Real-IP header."""
        environ = {
            'REQUEST_METHOD': 'GET',
            'PATH_INFO': '/v1/status',
            'QUERY_STRING': '',
            'REMOTE_ADDR': '10.0.0.1',
            'HTTP_X_REAL_IP': '192.168.1.100'
        }

        def start_response(status, headers, exc_info=None):
            return None

        def mock_app_call(env, sr):
            sr('200 OK', [])
            return [b'response']

        self.mock_app.side_effect = mock_app_call

        response = self.middleware(environ, start_response)

        self.assertEqual(response, [b'response'])

        # Should use X-Real-IP
        self.mock_log.info.assert_called_once_with(
            self.template,
            {'method': 'GET',
             'path': '/v1/status',
             'status': 200,
             'duration': 500.0,
             'source_ip': '192.168.1.100'}
        )

    def test_exception_still_logs(self):
        """Test that logging happens even if app raises exception."""
        environ = {
            'REQUEST_METHOD': 'GET',
            'PATH_INFO': '/v1/status',
            'QUERY_STRING': ''
        }

        def start_response(status, headers, exc_info=None):
            return None

        # Mock app raises an exception
        self.mock_app.side_effect = ValueError("Test error")

        # The middleware should re-raise the exception but still log
        self.assertRaises(ValueError, self.middleware, environ, start_response)

        # Verify the log was still called (with unknown status since
        # start_response was never called)
        self.mock_log.info.assert_called_once_with(
            self.template,
            {'method': 'GET',
             'path': '/v1/status',
             'status': 'unknown',
             'duration': 500.0,
             'source_ip': 'unknown'}
        )