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//.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...")