aboutsummaryrefslogtreecommitdiff
path: root/tools/python/test_server/server/ResponseProvider.py
blob: a552960c36078ea54fa405d4b76915b99f66af67 (plain) (blame)
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
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
from __future__ import print_function

import jsons
import logging
import os

from urllib.parse import unquote

# Should match size defined in platform/platform_tests/downloader_tests/downloader_test.cpp
BIG_FILE_SIZE = 47684

# Synthetic map files served under /unit_tests/maps/<version>/<name>.mwm, which is the URL
# shape platform::GetFileDownloadUrl() produces. The bytes depend only on the file name, so
# libs/storage/storage_tests/storage_download_tests.cpp reproduces them to fill "s" and "h"
# in its countries JSON. Keep the two generators identical: a mismatch shows up as a map
# integrity failure rather than as a server error.
# Sizes are 2.00-2.25 MB, i.e. 4-5 of the downloader's 512 KB chunks, so an interrupted
# download always leaves a partial file to resume from.
SYNTHETIC_MWM_PREFIX = "/unit_tests/maps/"
SYNTHETIC_MWM_BASE_SIZE = 2 * 1024 * 1024


def synthetic_mwm_seed(file_name):
    return sum(file_name.encode("utf-8")) % 256


def synthetic_mwm_size(file_name):
    return SYNTHETIC_MWM_BASE_SIZE + 1024 * synthetic_mwm_seed(file_name)


def synthetic_mwm_content(file_name):
    seed = synthetic_mwm_seed(file_name)
    size = synthetic_mwm_size(file_name)
    # content[i] == (i + seed) % 256, built by tiling one period instead of per-byte.
    period = bytes((i + seed) % 256 for i in range(256))
    return (period * (size // 256 + 1))[:size]


class Payload:
    def __init__(self, message, response_code=200, headers={}):
        self.__response_code = response_code
        self.__message = message if type(message) is bytes else message.encode('utf8')
        self.__headers = headers


    def response_code(self):
        """
        Response code to send to the client.
        """
        return self.__response_code


    def message(self):
        """
        The message to send to the client.
        """
        return self.__message


    def length(self):
        """
        The length of the response.
        """
        return len(self.message())


    def headers(self):
        """
        The headers to be sent to the client. Please, note, that these do not include
        the Content-Length header, which you need to send separately.
        """
        return self.__headers


    def __repr__(self):
        return "{}: {}: {}".format(self.response_code(), self.length(), self.message())


class ResponseProviderMixin:
    """
A mixin (basically, an interface) that the web-server that we might use relies on.

In this implementation, the job of the web-server is just to get the request
(the url and the headers), and to send the response as it knows how. It isn't
its job to decide how to respond to what request. It is the job of the
ResponseProvider.

In your web-server you should initialize the ResponseProvider, and ask it for

response_for_url_and_headers(url, headers)

Which will return a Payload object that the server must send as response.

The server might be notified when a particular request has been received:

got_pinged(self) - someone sent a ping request. The Response provider will
respond with "pong" and call this method of the server. You might want to
increment the count of active users, for ping is the request that new instances
of servers send to check if other servers are currently serving.

kill(self) - someone sent the kill request, which means that that someone
no longer needs this server to serve. You might want to decrement the count of
active users and/or stop the server.
"""

    def dispatch_response(self, payload):
        """
    Define this mehtod to dispatch the response received from the ResponseProvider
    """
        raise NotImplementedError()


    def got_pinged(self):
        """
    A ping request has been received. In most scenarios it means that the number of
    users of this server has increased by 1.
    """
        raise NotImplementedError()


    def kill(self):
        """
    Someone no longer needs this server. Decrement the number of users and stop
    the server if the number fell to 0.
    """
        raise NotImplementedError()


class ResponseProvider:
    def __init__(self, delegate):
        self.headers = list()
        self.delegate = delegate
        self.byterange = None
        self.is_chunked = False
        self.response_code = 200


    def pong(self):
        self.delegate.got_pinged()
        return Payload("pong")


    def my_id(self):
        return Payload(str(os.getpid()))


    def strip_query(self, url):
        query_start = url.find("?")
        if (query_start > 0):
            return url[:query_start]
        return url


    def response_for_url_and_headers(self, url, headers):
        self.headers = headers
        self.chunk_requested()
        url = self.strip_query(url)
        try:
            handler = {
                "/unit_tests/1.txt": self.test1,
                "/unit_tests/notexisting_unittest": self.test_404,
                "/unit_tests/permanent": self.test_301,
                "/unit_tests/47kb.file": self.test_47_kb,
                # Used to test a failing map download; the rest of /unit_tests/maps/ is served
                # as a synthetic mwm below.
                "/unit_tests/maps/1234/Uruguay.mwm": self.test_404,
                "/ping": self.pong,
                "/kill": self.kill,
                "/id": self.my_id,
                "/partners/time": self.partners_time,
                "/partners/price": self.partners_price,
                "/booking/hotelAvailability": self.partners_hotel_availability,
                "/booking/deals": self.partners_hotels_with_deals,
                "/booking/blockAvailability": self.partners_block_availability,
                "/partners/taxi_info": self.partners_yandex_taxi_info,
                "/partners/get-offers-in-bbox/": self.partners_rent_nearby,
                "/partners/CalculateByCoords": self.partners_calculate_by_coords,
                "/gallery/v2/search/": self.promo_gallery_city,
                "/single/empty/gallery/v2/search/": self.promo_gallery_city_single_empty,
                "/single/gallery/v2/search/": self.promo_gallery_city_single,
                "/partners/oauth/token": self.freenow_auth_token,
                "/partners/service-types": self.freenow_service_types,
                "/gallery/v2/map": self.guides_on_map_gallery,
                "/partners/get_supported_tariffs": self.citymobil_supported_tariffs,
                "/partners/calculate_price": self.citymobil_calculate_price,
                "/unit_tests/echo_headers": self.echo_headers,
                "/unit_tests/echo_cookies": self.echo_cookies,
                "/unit_tests/timeout": self.test_timeout,
                "/unit_tests/500": self.test_500,
                "/unit_tests/403": self.test_403,
                "/unit_tests/redirect_to_1txt": self.test_redirect_to_1txt,
                "/unit_tests/set_cookies": self.test_set_cookies,
                "/unit_tests/multi_set_cookies": self.test_multi_set_cookies,
                "/unit_tests/204": self.test_204,
                "/unit_tests/basic_auth": self.test_basic_auth,
                "/unit_tests/set_cookies_lowercase": self.test_set_cookies_lowercase,
                "/unit_tests/set_cookies_uppercase": self.test_set_cookies_uppercase,
                # Segment-mode (ReceivedFileSegment) failure routes.
                # SEGMENT_TEST_TOTAL_SIZE (1000) is the advertised total file size.
                "/unit_tests/segment/ignore_range": self.test_segment_ignore_range,
                "/unit_tests/segment/missing_content_range": self.test_segment_missing_content_range,
                "/unit_tests/segment/short_body": self.test_segment_short_body,
                "/unit_tests/segment/overflow_body": self.test_segment_overflow_body,
                "/unit_tests/segment/unknown_total": self.test_segment_unknown_total,
                "/unit_tests/segment/ok": self.test_segment_ok,
            }.get(url)
            if handler is None and url.startswith(SYNTHETIC_MWM_PREFIX):
                return self.synthetic_mwm(unquote(url[url.rfind("/") + 1:]))
            return (handler or self.test_404)()
        except Exception as e:
            logging.error("test_server: Can't build server response", exc_info=e)
            return self.test_404()


    def chunk_requested(self):
        if "range" in self.headers:
            self.is_chunked = True
            self.response_code = 206
            meaningful_string = self.headers["range"][6:]
            first, last = meaningful_string.split("-")
            # Open-ended range: "bytes=N-" means from N to the end.
            # last will be set to None; trim_message and check_byterange handle it.
            self.byterange = (int(first), int(last) if last else None)


    def trim_message(self, message):
        if not self.is_chunked:
            return message
        start = self.byterange[0]
        end = self.byterange[1]
        if end is not None:
            return message[start: end + 1]
        return message[start:]


    def test1(self):
        init_message = "Test1"
        message = self.trim_message(init_message)
        size = len(init_message)
        self.check_byterange(size)
        headers = self.chunked_response_header(size)

        return Payload(message, self.response_code, headers)


    def test_404(self):
        return Payload("", response_code=404)


    def test_301(self):
        return Payload("", 301, {"Location" : "google.com"})


    def check_byterange(self, size):
        if self.byterange is None:
            self.byterange = (0, size)
        elif self.byterange[1] is None:
            # Open-ended range: "bytes=N-" means from N to end.
            self.byterange = (self.byterange[0], size - 1)

    def chunked_response_header(self, size):
        return {
            "Content-Range" : "bytes {start}-{end}/{out_of}".format(start=self.byterange[0],
            end=self.byterange[1], out_of=size)
        }


    def synthetic_mwm(self, file_name):
        content = synthetic_mwm_content(file_name)
        self.check_byterange(len(content))
        headers = self.chunked_response_header(len(content))

        return Payload(self.trim_message(content), self.response_code, headers)


    def test_47_kb(self):
        self.check_byterange(BIG_FILE_SIZE)
        headers = self.chunked_response_header(BIG_FILE_SIZE)
        message = self.trim_message(self.message_for_47kb_file())

        return Payload(message, self.response_code, headers)


    def message_for_47kb_file(self):
        message = []
        for i in range(0, BIG_FILE_SIZE + 1):
            message.append(i // 256)
            message.append(i % 256)

        return bytes(message)


    # Partners_api_tests
    def partners_time(self):
        return Payload(jsons.PARTNERS_TIME)


    def partners_price(self):
        return Payload(jsons.PARTNERS_PRICE)

    def partners_hotel_availability(self):
        return Payload(jsons.HOTEL_AVAILABILITY)

    def partners_hotels_with_deals(self):
        return Payload(jsons.HOTELS_WITH_DEALS)

    def partners_block_availability(self):
        return Payload(jsons.BLOCK_AVAILABILITY)

    def partners_yandex_taxi_info(self):
        return Payload(jsons.PARTNERS_TAXI_INFO)

    def partners_rent_nearby(self):
        return Payload(jsons.PARTNERS_RENT_NEARBY)

    def partners_calculate_by_coords(self):
        return Payload(jsons.PARTNERS_CALCULATE_BY_COORDS)

    def promo_gallery_city(self):
        return Payload(jsons.PROMO_GALLERY_CITY)

    def promo_gallery_city_single_empty(self):
        return Payload(jsons.PROMO_GALLERY_CITY_SINGLE_EMPTY)

    def promo_gallery_city_single(self):
        return Payload(jsons.PROMO_GALLERY_CITY_SINGLE)

    def freenow_auth_token(self):
        return Payload(jsons.FREENOW_AUTH_TOKEN)

    def freenow_service_types(self):
        return Payload(jsons.FREENOW_SERVICE_TYPES)

    def guides_on_map_gallery(self):
        return Payload(jsons.GUIDES_ON_MAP_GALLERY)

    def citymobil_supported_tariffs(self):
        return Payload(jsons.CITYMOBIL_SUPPORTED_TARIFFS)

    def citymobil_calculate_price(self):
        return Payload(jsons.CITYMOBIL_CALCULATE_PRICE)

    def echo_headers(self):
        """Return request headers as key:value lines so tests can verify custom headers."""
        import json
        return Payload(json.dumps(self.headers), 200, {"Content-Type": "application/json"})

    def echo_cookies(self):
        """Return the Cookie header value."""
        cookie = self.headers.get("cookie", "")
        return Payload(cookie)

    def test_timeout(self):
        """Sleep longer than the client's 2-second timeout to trigger a timeout error.
        Keep the delay short (5s) because Tornado's single-threaded IO loop is blocked
        during sleep, preventing other requests from being processed."""
        import time
        time.sleep(3)
        return Payload("should not reach")

    def test_500(self):
        return Payload("Internal Server Error", response_code=500)

    def test_403(self):
        return Payload("Forbidden", response_code=403)

    def test_redirect_to_1txt(self):
        return Payload("", 301, {"Location": "http://localhost:24568/unit_tests/1.txt"})

    def test_set_cookies(self):
        return Payload("ok", 200, {"Set-Cookie": "session=abc123; Path=/"})

    def test_multi_set_cookies(self):
        """Return multiple Set-Cookie values via a single comma-joined header.
        HTTP/1.1 servers may fold multiple Set-Cookie headers into one comma-separated value."""
        return Payload("ok", 200, {"Set-Cookie": "a=1; Path=/, b=2; Path=/"})

    def test_204(self):
        return Payload("", response_code=204)

    def test_basic_auth(self):
        """Returns 200 if valid Basic auth header present, 401 otherwise."""
        import base64
        auth = self.headers.get("authorization", "")
        expected = "Basic " + base64.b64encode(b"testuser:testpass").decode()
        if auth == expected:
            return Payload("authorized", 200)
        return Payload("Unauthorized", 401, {"WWW-Authenticate": "Basic realm=\"test\""})

    def test_set_cookies_lowercase(self):
        """Return Set-Cookie with all-lowercase header name."""
        return Payload("ok", 200, {"set-cookie": "lower=yes; Path=/"})

    def test_set_cookies_uppercase(self):
        """Return Set-Cookie with all-uppercase header name."""
        return Payload("ok", 200, {"SET-COOKIE": "upper=yes; Path=/"})

    # --- Segment-mode (ReceivedFileSegment) failure-injection routes. ---
    # These routes exist to test HttpClient::SetReceivedFileSegment error handling.
    # SEGMENT_TEST_TOTAL_SIZE must match the value in http_client_test.cpp.
    SEGMENT_TEST_TOTAL_SIZE = 1000
    SEGMENT_TEST_RANGE_END = 99  # Inclusive end of the test range (100 bytes: 0-99).

    def segment_test_body(self, size):
        """Returns a deterministic byte sequence of the given size (values 0,1,2,...,255,0,...)."""
        return bytes(i % 256 for i in range(size))

    def test_segment_ignore_range(self):
        """Always returns 200 OK with the full file body, ignoring any Range header.
        Simulates a mis-configured mirror that doesn't honor partial requests.
        Segment-mode clients must detect this and fail with kInconsistentFileSize
        before any byte is written to the target file."""
        body = self.segment_test_body(self.SEGMENT_TEST_TOTAL_SIZE)
        return Payload(body, 200, {})

    def test_segment_missing_content_range(self):
        """Returns 206 Partial Content but WITHOUT a Content-Range header.
        Spec violation per RFC 7233 §4.1 - segment-mode clients must reject this."""
        body = self.segment_test_body(self.SEGMENT_TEST_RANGE_END + 1)
        return Payload(body, 206, {})

    def test_segment_short_body(self):
        """Returns 206 with Content-Range advertising 100 bytes (0-99/1000), but the
        body has only 50 bytes. Tests segment-underflow detection at finish."""
        body = self.segment_test_body(50)
        return Payload(body, 206, {"Content-Range": "bytes 0-{end}/{total}".format(
            end=self.SEGMENT_TEST_RANGE_END, total=self.SEGMENT_TEST_TOTAL_SIZE)})

    def test_segment_overflow_body(self):
        """Returns 206 with Content-Range advertising 100 bytes (0-99/1000), but the
        body has 150 bytes. Tests segment-overflow detection (abort mid-stream)."""
        body = self.segment_test_body(150)
        return Payload(body, 206, {"Content-Range": "bytes 0-{end}/{total}".format(
            end=self.SEGMENT_TEST_RANGE_END, total=self.SEGMENT_TEST_TOTAL_SIZE)})

    def test_segment_unknown_total(self):
        """Returns 206 with Content-Range: bytes 0-99/* and a correct 100-byte body.
        RFC 7233 allows "*" for unknown total, but segment-mode clients that supply
        an expected total must reject it (different file version / mirror drift)."""
        body = self.segment_test_body(self.SEGMENT_TEST_RANGE_END + 1)
        return Payload(body, 206, {"Content-Range": "bytes 0-{end}/*".format(end=self.SEGMENT_TEST_RANGE_END)})

    def test_segment_ok(self):
        """Returns 206 with correct Content-Range and exact byte count. Happy-path
        reference. Honors the Range header like test1/test_47_kb via chunk_requested()."""
        body = self.segment_test_body(self.SEGMENT_TEST_TOTAL_SIZE)
        self.check_byterange(self.SEGMENT_TEST_TOTAL_SIZE)
        headers = self.chunked_response_header(self.SEGMENT_TEST_TOTAL_SIZE)
        return Payload(self.trim_message(body), self.response_code, headers)

    def kill(self):
        logging.debug("Kill called in ResponseProvider")
        self.delegate.kill()
        return Payload("Bye...")