def test_header_appears_in_subsequent_request(self): key = "x-spam" value = "eggs" sut = HttpClient() sut.set_persistent_headers(**{key: value}) sut.get("http://spam") sut.get("http://eggs") expect(self.extract_request_headers()).to(contain_key_with_value(key, value))
def check_request(self, method): url = "http://nothing" kwargs = {"spam": 42, "eggs": 0} getattr(HttpClient(), method)(url, **kwargs) req_args, req_kwargs = self.requests_spy.last_call_to(method) expect(req_args).to(equal((url, ))) for k, v in kwargs.items(): expect(req_kwargs).to(contain_key_with_value(k, v))
def test_first_header_persists_after_adding_second(self): key = "x-spam" value = "eggs" sut = HttpClient() sut.set_persistent_headers(**{key: value}) sut.set_persistent_headers(something="13") sut.get("http://spam") expect(self.extract_request_headers()).to(contain_key_with_value(key, value))
def test_rejects_child_class_of_existing_key(self): client = HttpClient() client.set_exceptional_response_callback(exception_class=Spam, callback=EndlessFake()) expect( partial(client.set_exceptional_response_callback, exception_class=SonOfSpam, callback=EndlessFake())).to(raise_ex(TypeError))
def test_can_change_a_persistent_header(self): key = "thing" value = "new-value" sut = HttpClient() sut.set_persistent_headers(**{key: "old-value"}) sut.set_persistent_headers(**{key: value}) sut.get("http://things") expect(self.extract_request_headers()).to(contain_key_with_value(key, value))
def update_user(self, usr_body_dic, usr_id): uri = '{}{}'.format(self.url, EP.USER_BY_ID.params(usr_id)) headrs = { 'authorization': 'Bearer {}'.format(self.token), "Content-Type": "application/json" } return HttpClient().put(uri, data=json.dumps(usr_body_dic), headers=headrs)
def test_publish_with_test_name_on_test_failed(self): sut = HttpClient() sut.get("http://spamoni.io") name = "nombre" EventBroker.publish(event=TestEvent.test_failed, test_name=name, exception=RuntimeError()) assert self.published, "Nothing was published" expect(self.published).to(contain_key_with_value("test_name", name))
def test_publish_with_suite_name_on_suite_erred(self): sut = HttpClient() sut.get("http://spamoni.io") name = "bubba" EventBroker.publish(event=TestEvent.suite_erred, suite_name=name, exception=RuntimeError()) assert self.published, "Nothing was published" expect(self.published).to(contain_key_with_value("suite_name", name))
def test_lets_exception_raised_by_callback_pass_through(self): exception_class = Spam raised = exception_class() callback = func_that_raises(raised) client = HttpClient() client.set_exceptional_response_callback(exception_class=HttpNotFound, callback=callback) self.context.inject(inspect_response, func_that_raises(HttpNotFound)) expect(partial(client.put, "https://up.with.it")).to(raise_ex(raised))
def test_request_method_and_url(self): method = "HEAD" sut = HttpClient() url = "http://i.love2spam.net/spam" getattr(sut, method.lower())(url) EventBroker.publish(event=TestEvent.test_failed, exception=RuntimeError()) expect(self.published["artifact"]).to( contain("\n%s %s" % (method, url)))
def test_request_headers(self): headers = {"X-yz": "yogurt humphrey", "Content-length": "infinite"} sut = HttpClient() sut.get("http://something", headers=headers) EventBroker.publish(event=TestEvent.test_failed, exception=RuntimeError()) expect(self.published["artifact"]).to( contain("\n".join(["%s: %s" % (k, v) for k, v in headers.items()])))
def test_repeats_arbitrary_keyword_arguments(self): planted = { "slogan": "Nobody rejects the Spinach Imposition!", "weapons": ["surprise", "fear", "ruthless efficiency"], } self.queue_response(status_code=301, location="http://ratses") self.queue_response(status_code=200) HttpClient().get("something", **planted) expect(self.spies.get.kwargs_from_last_call()).to(have_keys(**planted))
def test_sends_prepared_request(self): client = HttpClient() client.enable_cookies() client.post("http://pewpewpew") prep_spy = self.extract_prep_spy() prepped = prep_spy.return_value_spies[-1] send_spy = self.extract_send_spy() args, kwargs = send_spy.call_history[-1] expect(args[0]).to(be(prepped))
def test_enabled_in_session_by_default(self): requests_stub = EndlessFake() self.context.inject(requests, requests_stub) spy = MasterSpy(EndlessFake()) requests_stub.Session = lambda *a, **k: spy client = HttpClient() client.enable_cookies() client.get("http://spam") args, kwargs = spy.last_call_to("send") expect(kwargs).to(have_keys(verify=True))
def test_response_headers(self): headers = {"X-yz": "Sam the spammer", "Content-length": "2"} self.fake_requests.response.headers = headers sut = HttpClient() sut.get("http://something") EventBroker.publish(event=TestEvent.test_failed, exception=RuntimeError()) expect(self.published["artifact"]).to( contain("\n".join(["%s: %s" % (k, v) for k, v in headers.items()])))
def test_passes_exception_as_kwarg(self): exception_class = HttpImATeapot spy = FunctionSpy(return_value=EndlessFake()) client = HttpClient() client.set_exceptional_response_callback( exception_class=exception_class, callback=spy) self.context.inject(inspect_response, func_that_raises(exception_class())) client.get("http://foo.bar") expect(spy["exception"]).to(be_a(exception_class))
def test_enabling_cookies_does_not_break_this_feature(self): key = "spam" value = "eggs" sut = HttpClient() sut.enable_cookies() sut.set_persistent_headers(**{key: value}) sut.get("http://something") spy = self.spy.session_spy.attribute_spies["prepare_request"] args, kwargs = spy.call_history[-1] request = args[0] expect(request.headers).to(contain_key_with_value(key, value))
def test_request_uuid_is_a_uuid(self): published_uuid = None def subscriber(request_uuid, **kwargs): nonlocal published_uuid published_uuid = request_uuid EventBroker.subscribe(event=TestEvent.http_request_sent, func=subscriber) HttpClient().get("http://spam.spam") expect(published_uuid).to(be_a(uuid.UUID))
def test_sends_configured_timeout_for_session_request(self): planted = 37 self.context.set_env(HTTP_CLIENT_SOCKET_TIMEOUT=planted) session_stub = EndlessFake() self.requests_stub.Session = lambda: session_stub send_spy = FunctionSpy(return_value=EndlessFake()) session_stub.send = send_spy client = HttpClient() client.enable_cookies() client.get("http://truffles") expect(send_spy["timeout"]).to(equal(planted))
def test_disabled_in_session_when_configured(self): self.context.set_env(HTTPS_VERIFY_CERTS="FAlSe") requests_stub = EndlessFake() self.context.inject(requests, requests_stub) spy = MasterSpy(EndlessFake()) requests_stub.Session = lambda *a, **k: spy client = HttpClient() client.enable_cookies() client.get("http://spam") args, kwargs = spy.last_call_to("send") expect(kwargs).to(have_keys(verify=False))
def test_publishes_request_headers(self): request_headers = {"spam": "surprise", "eggs": "fear", "beans": 0} published_headers = None def subscriber(request_headers, **kwargs): nonlocal published_headers published_headers = request_headers EventBroker.subscribe(event=TestEvent.http_request_sent, func=subscriber) HttpClient().post("https://blah.blah", headers=request_headers) expect(published_headers).to(equal(request_headers))
def test_publishes_request_url(self): called_url = "https://art-mart.net" published_url = None def subscriber(request_url, **kwargs): nonlocal published_url published_url = request_url EventBroker.subscribe(event=TestEvent.http_request_sent, func=subscriber) HttpClient().get(called_url) expect(published_url).to(equal(called_url))
def test_publishes_request_data(self): planted_data = "blah blah blah blah blah" published_data = None def subscriber(request_data, **kwargs): nonlocal published_data published_data = request_data EventBroker.subscribe(event=TestEvent.http_request_sent, func=subscriber) HttpClient().post("https://blah.blah", data=planted_data) expect(published_data).to(equal(planted_data))
def test_follows_relative_location_url(self): original = "https://some-host:42/some/resource?key=val#some-fragment" original_parsed = urlparse(original) redirect = "/yadda?something=12#another-fragment" self.queue_response(status_code=301, location=redirect) self.queue_response(status_code=200) HttpClient().get(original) expect(self.spies.get.args_from_last_call()[0]).to( equal( url_append( f"{original_parsed.scheme}://{original_parsed.netloc}", redirect)))
def test_publishes_http_method(self): called_method = "put" published_method = None def subscriber(http_method, **kwargs): nonlocal published_method published_method = http_method EventBroker.subscribe(event=TestEvent.http_request_sent, func=subscriber) client = HttpClient() getattr(client, called_method)("https://upwith.it") expect(published_method).to(equal(called_method.upper()))
def test_calls_callback_for_exception(self): exception_class = HttpUnauthorized spy = FunctionSpy() client = HttpClient() client.set_exceptional_response_callback( exception_class=HttpUnauthorized, callback=spy) self.context.inject(inspect_response, func_that_raises(exception_class())) try: client.get("http://spam") except exception_class: # This shouldn't be raised but this test doesn't care pass spy.assert_was_called()
def test_calls_callback_for_child_class(self): specified_class = Spam raised_class = SonOfSpam spy = FunctionSpy() client = HttpClient() client.set_exceptional_response_callback( exception_class=specified_class, callback=spy) self.context.inject(inspect_response, func_that_raises(raised_class())) try: client.get("http://stuffed.com.au") except raised_class: # Exception should not be raised, but this test does not care pass spy.assert_was_called()
def test_publishes_response_object(self): planted_response = EndlessFake() published_response = None def subscriber(response, **kwargs): nonlocal published_response published_response = response requests_stub = EndlessFake() requests_stub.post = lambda *a, **k: planted_response self.context.inject(requests, requests_stub) EventBroker.subscribe(event=TestEvent.http_response_received, func=subscriber) HttpClient().post("http://something") expect(published_response).to(be(planted_response))
def test_preserves_fragment_if_none_specified_in_location_header(self): # As required by RFC 7231 section 7.1.2 original = "https://some-host:42/some/resource?key=val#some-fragment" original_parsed = urlparse(original) redirect = "/yadda?something=12" self.queue_response(status_code=301, location=redirect) self.queue_response(status_code=200) HttpClient().get(original) expect(self.spies.get.args_from_last_call()[0]).to( equal( url_append( f"{original_parsed.scheme}://{original_parsed.netloc}", redirect) + f"#{original_parsed.fragment}"))
def test_request_uuid_is_same_in_request_event_and_response_event(self): class UuidCatcher: def __init__(self): self.uuid = None def __call__(self, request_uuid, **kwargs): self.uuid = request_uuid request_event_catcher = UuidCatcher() response_event_catcher = UuidCatcher() EventBroker.subscribe(event=TestEvent.http_request_sent, func=request_event_catcher) EventBroker.subscribe(event=TestEvent.http_response_received, func=response_event_catcher) HttpClient().get("http://stuff") expect(request_event_catcher.uuid).to( equal(response_event_catcher.uuid))