def _build_server(tmpdir, host): ca = trustme.CA() ca_cert_path = str(tmpdir / "ca.pem") ca.cert_pem.write_to_path(ca_cert_path) server_cert = ca.issue_cert(host) context = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH) server_crt = server_cert.cert_chain_pems[0] server_key = server_cert.private_key_pem with server_crt.tempfile() as crt_file, server_key.tempfile() as key_file: context.load_cert_chain(crt_file, key_file) server = HTTPServer(ssl_context=context) # Fake what the client expects from Elasticsearch server.expect_request("/").respond_with_json( headers={ "x-elastic-product": "Elasticsearch", }, response_json={"version": { "number": "8.0.0", }}, ) server.start() yield server, ca, ca_cert_path server.clear() if server.is_running(): server.stop()
async def test_do_get_connection_refused( httpserver: pytest_httpserver.HTTPServer): httpserver.expect_request('/index.html').\ respond_with_data('Not Found', content_type='text/html', status=404) # close HTTP server on purpose: make sure the connection will be refused httpserver.stop() try: async with http.new_client() as session: response, error = await http.get(session, httpserver.url_for('/index.html')) finally: # start again to avoid side effect httpserver.start() assert response is None assert error == 'Connection refused'
def _create_http_endpoint( raw_message_delivery: bool = False, ) -> Tuple[str, str, str, HTTPServer]: server = HTTPServer() server.start() http_servers.append(server) server.expect_request("/sns-endpoint").respond_with_data(status=200) endpoint_url = server.url_for("/sns-endpoint") wait_for_port_open(endpoint_url) topic_arn = sns_create_topic()["TopicArn"] subscription = sns_subscription(TopicArn=topic_arn, Protocol="http", Endpoint=endpoint_url) subscription_arn = subscription["SubscriptionArn"] delivery_policy = { "healthyRetryPolicy": { "minDelayTarget": 1, "maxDelayTarget": 1, "numRetries": 0, "numNoDelayRetries": 0, "numMinDelayRetries": 0, "numMaxDelayRetries": 0, "backoffFunction": "linear", }, "sicklyRetryPolicy": None, "throttlePolicy": { "maxReceivesPerSecond": 1000 }, "guaranteed": False, } sns_client.set_subscription_attributes( SubscriptionArn=subscription_arn, AttributeName="DeliveryPolicy", AttributeValue=json.dumps(delivery_policy), ) if raw_message_delivery: sns_client.set_subscription_attributes( SubscriptionArn=subscription_arn, AttributeName="RawMessageDelivery", AttributeValue="true", ) return topic_arn, subscription_arn, endpoint_url, server
def test_unzip(test_folder, tmp_folder, clean_tmp): # GIVEN zip file in test_folder # WHEN downloaded in tmp folder # THEN should be unzipped and zip file removed sample = test_folder / "sample.zip" server = HTTPServer(port=0) s = server.expect_request("/sample.zip", method="GET") s.respond_with_data(sample.read_bytes(), mimetype="application/zip") server.start() core.unzip(url=server.url_for("/sample.zip"), dest=tmp_folder, chunk_size=1, remove_zip=True) server.stop() assert tmp_folder.joinpath("sample.txt").exists() assert not tmp_folder.joinpath("sample.zip").exists() # clean the tmp folder clean_tmp
async def forwarder(client, example_id, example_entry_ids): """A http server forwarding REST requests to `client`, bound to app under test.""" httpserver = HTTPServer() httpserver \ .expect_request(re.compile(r'/about/[0-9a-f]+')) \ .respond_with_json((await client.get(f'/about/{example_id}')).json()) httpserver \ .expect_request(re.compile(r'/list/[0-9a-f]+')) \ .respond_with_json((await client.get(f'/list/{example_id}')).json()) json_responses = [Response((await client.get(f'/json/{example_id}/{id}')).content) for id in example_entry_ids] json_responses_iter = iter(json_responses) httpserver \ .expect_request(re.compile(rf'/json/{example_id}/[0-9a-f]+')) \ .respond_with_handler(lambda _: next(json_responses_iter)) try: httpserver.start() yield httpserver finally: httpserver.stop()
def test_rig(): logging.basicConfig(level=logging.DEBUG) bootstrap = Bootstrap() http_server = HTTPServer() http_server.start() http_server.expect_request("/" + test_id).respond_with_data("OK") http_server.expect_request("/" + test_id + "/fail").respond_with_data("OK") url_for_test = http_server.url_for("/" + test_id) no_char_to_remove = len(test_id) url_for_test = url_for_test[:-no_char_to_remove] rig = {} rig["client"] = testing.TestClient( bootstrap.create(hc_override=url_for_test)) rig["server"] = http_server yield rig http_server.stop()
#!.venv/bin/python3 import urllib.request import urllib.error from pytest_httpserver import HTTPServer server = HTTPServer(port=4000) server.expect_request("/foobar").respond_with_json({"foo": "bar"}) server.start() try: print( urllib.request.urlopen( "http://localhost:4000/foobar?name=John%20Smith&age=123").read()) except urllib.error.HTTPError as err: print(err) server.stop()