def test_re_raises_unspecified_response_exception(self): client = HttpClient() client.set_exceptional_response_callback(exception_class=HttpNotFound, callback=lambda *a, **k: None) raised = HttpUnauthorized() self.context.inject(inspect_response, func_that_raises(raised)) expect(partial(client.post, "http://mail.net")).to(raise_ex(raised))
def test_re_raises_exception_if_callback_returns_none(self): original = HttpImATeapot() self.context.inject(inspect_response, func_that_raises(original)) client = HttpClient() client.set_exceptional_response_callback(exception_class=HttpImATeapot, callback=lambda *a, **k: None) expect(partial(client.delete, "http://nothing.new")).to(raise_ex(original))
def test_returns_response_returned_by_callback(self): callback_response = EndlessFake() self.context.inject(inspect_response, func_that_raises(HttpNotFound())) client = HttpClient() client.set_exceptional_response_callback( exception_class=HttpNotFound, callback=lambda *a, **k: callback_response) expect(client.get("http://stuffed")).to(be(callback_response))
def test_rejects_parent_class_of_existing_key(self): client = HttpClient() client.set_exceptional_response_callback(exception_class=SonOfSpam, callback=EndlessFake()) expect( partial(client.set_exceptional_response_callback, exception_class=Spam, callback=EndlessFake())).to(raise_ex(TypeError))
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_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_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_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_setting_header_to_none_removes_it(self): key = "something" sut = HttpClient() sut.set_persistent_headers(**{key: "spam"}) sut.set_persistent_headers(**{key: None}) sut.get("http://albatross") expect(self.extract_request_headers().keys()).not_to(contain(key))
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 test_repeats_initial_request_headers(self): headers = {"spams": 22, "eggs": 7, "the-spanish-inquisition": "fang"} self.queue_response(status_code=301, location="http://ratses") self.queue_response(status_code=200) HttpClient().get("something", headers=headers) expect(self.spies.get.kwargs_from_last_call()).to( have_keys(headers=headers))
def test_disabled_when_configured(self): spy = MasterSpy(EndlessFake()) self.context.inject(requests, spy) self.context.set_env(HTTPS_VERIFY_CERTS="FAlSe") HttpClient().get("http://spam") args, kwargs = spy.last_call_to("get") expect(kwargs).to(have_keys(verify=False))
def test_publishes_event_before_sending_the_request(self): event_published = False request_sent = False request_sent_before_event_published = False def stub_post(*args, **kwargs): nonlocal request_sent request_sent = True return EndlessFake() def mock_subscriber(**kwargs): nonlocal event_published nonlocal request_sent_before_event_published event_published = True request_sent_before_event_published = request_sent self.requests_stub.post = stub_post EventBroker.subscribe(event=TestEvent.http_request_sent, func=mock_subscriber) HttpClient().post("http://something") assert event_published, "The event was not published" assert not request_sent_before_event_published, "Thre request was sent before the event was published" assert request_sent, "Request was not sent after the event was published"
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 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_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_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_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_payload(self): payload = """ Immanuel Kant was a real pissant Who was very rarely stable. Heidigger Heidigger was a boozy beggar Who could think you under the table. David Hume could outconsume Schopenhauer and Hegel And Wittgenstein was a beery swine Who was just as sloshed as Schlegel. There's nothing Neitche couldn't teach about the raising of the wrist. Socrates himself was permanently pissed.""" sut = HttpClient() sut.put("http://python.net/philosophers.txt", data=payload) EventBroker.publish(event=TestEvent.test_failed, exception=RuntimeError()) expect(self.published["artifact"]).to(contain(payload))
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_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_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_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_session_from_environment(self): client = HttpClient() client.enable_cookies() client.post("http://something") spy = self.session_spy.attribute_spies["send"] args, kwargs = spy.call_history[-1] expect(kwargs).to(contain_key_with_value("proxies", {"http": self.http_proxy, "https": self.https_proxy}))
def test_header_appears_in_next_request(self): key = "x-spam" value = "eggs" sut = HttpClient() sut.set_persistent_headers(**{key: value}) sut.get("http://spam") expect(self.extract_request_headers()).to(contain_key_with_value(key, value))
def test_specified_header_overrides_persistent(self): key = "page" value = "LIX" sut = HttpClient() sut.set_persistent_headers(**{key: "something-else"}) sut.get("http://yadda", headers={key: value}) expect(self.extract_request_headers()).to(contain_key_with_value(key, value))
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_session_from_call(self): expected = "an halibut" client = HttpClient() client.enable_cookies() client.delete("http://nothing-to.see/here", proxies=expected) spy = self.session_spy.attribute_spies["send"] args, kwargs = spy.call_history[-1] expect(kwargs).to(contain_key_with_value("proxies", expected))