def test_returns_the_key_as_json_if_found(self): request = DummyRequest(['/keys']) request.addArg('search', 'some@key') when(self.keymanager).fetch_key('some@key').thenReturn(defer.succeed(OpenPGPKey('some@key'))) d = self.web.get(request) expected = { "tags": ["keymanager-key"], "fingerprint": '', "private": False, 'sign_used': False, 'refreshed_at': 0, "expiry_date": 0, "address": 'some@key', 'encr_used': False, 'last_audited_at': 0, 'key_data': '', 'length': 0, 'key_id': '', 'validation': 'Weak_Chain', 'type': 'OpenPGPKey', } def assert_response(_): actual = json.loads(ast.literal_eval(request.written[0])) self.assertEquals(expected, actual) d.addCallback(assert_response) return d
def test_returns_the_key_as_json_if_found(self): request = DummyRequest(['/keys']) request.addArg('search', 'some@key') when(self.keymanager).fetch_key('some@key').thenReturn(defer.succeed(OpenPGPKey('some@key'))) d = self.web.get(request) expected = { u'address': u'some@key', u'encr_used': False, u'fingerprint': u'', u'last_audited_at': 0, u'private': False, u'sign_used': False, u'tags': [u'keymanager-active'], u'type': u'OpenPGPKey-active', u'validation': u'Weak_Chain', u'version': 1, } def assert_response(_): actual = json.loads(ast.literal_eval(request.written[0])) self.assertEquals(expected, actual) d.addCallback(assert_response) return d
def test_render_soap_fault(self): """ `SmsNotificationService.render_POST` logs any exceptions that occur during processing and writes a SOAP fault back to the request. If the logged exception is a `SoapFault` its ``to_element`` method is invoked to serialize the fault. """ service = SmsNotificationService(None, None) service.process = lambda *a, **kw: L.done() request = DummyRequest([]) request.content = StringIO(tostring(L.hello())) d = request.notifyFinish() service.render_POST(request) self.successResultOf(d) self.assertEqual(http.INTERNAL_SERVER_ERROR, request.responseCode) failures = self.flushLoggedErrors(SoapFault) self.assertEqual(1, len(failures)) self.assertEqual( {str(SOAP_ENV.Envelope): { str(SOAP_ENV.Body): { str(SOAP_ENV.Fault): { 'faultcode': 'soapenv:Client', 'faultstring': 'Malformed SOAP request'}}}}, element_to_dict(fromstring(''.join(request.written))))
def test_render_exceptions(self): """ `SmsNotificationService.render_POST` logs any exceptions that occur during processing and writes a SOAP fault back to the request. """ def process(*a, **kw): raise ValueError('What is this') service = SmsNotificationService(None, None) service.process = process request = DummyRequest([]) request.content = StringIO(tostring(soap_envelope('hello'))) d = request.notifyFinish() service.render_POST(request) self.successResultOf(d) self.assertEqual(http.INTERNAL_SERVER_ERROR, request.responseCode) failures = self.flushLoggedErrors(ValueError) self.assertEqual(1, len(failures)) self.assertEqual( {str(SOAP_ENV.Envelope): { str(SOAP_ENV.Body): { str(SOAP_ENV.Fault): { 'faultcode': 'soapenv:Server', 'faultstring': 'What is this'}}}}, element_to_dict(fromstring(''.join(request.written))))
def test_returns_the_key_as_json_if_found(self): request = DummyRequest(["/keys"]) request.addArg("search", "some@key") when(self.keymanager).fetch_key("some@key").thenReturn(defer.succeed(OpenPGPKey("some@key"))) d = self.web.get(request) expected = { u"address": u"some@key", u"encr_used": False, u"fingerprint": u"", u"last_audited_at": 0, u"private": False, u"sign_used": False, u"tags": [u"keymanager-active"], u"type": u"OpenPGPKey-active", u"validation": u"Weak_Chain", u"version": 1, } def assert_response(_): actual = json.loads(ast.literal_eval(request.written[0])) self.assertEquals(expected, actual) d.addCallback(assert_response) return d
class CallbackResourceTest(TestCase): def setUp(self): self.resource = CallbackResource() self.resource.factory = DecoupledRequestFactory() self.request = DummyRequest(['']) self.request.method = 'POST' self.request.content = StringIO() def test_no_request_id(self): def on_rendered(_): self.assertEqual(self.request.responseCode, 503) self.assertEqual(['No request_id given'], self.request.written) return _render(self.resource, self.request).addCallback(on_rendered) def test_unknown_request_id(self): self.request.addArg('request_id', 'xxx') def on_rendered(_): self.assertEqual(self.request.responseCode, 503) self.assertEqual(['Request not found'], self.request.written) return _render(self.resource, self.request).addCallback(on_rendered) def test_success(self): self.request.addArg('request_id', 'xxx') self.resource.factory.requests['xxx'] = DecoupledRequest( self.resource.factory, 'xxx', DummyRequest([''])) def on_rendered(_): self.assertEqual(['ok'], self.request.written) return _render(self.resource, self.request).addCallback(on_rendered)
def request_same_or_different_thread_thread(self): hr = HendrixWSGIResource(reactor, self.tp, self.wsgi_thing) request1 = DummyRequest('r1') request1.isSecure = lambda: False request1.content = "llamas" d = deferToThreadPool(reactor, self.tp, hr.render, request1) return d
def _create_request(self, number_of_commits): body = { "commits": [{"rev": i} for i in range(number_of_commits)] } request = DummyRequest([b"/"]) request.method = "POST" request.args["payload"] = [json.dumps(body)] return request
def request_same_or_different_thread_thread(self): hr = HendrixWSGIResource(reactor, self.tp, self.wsgi_thing) request1 = DummyRequest([b'r1']) request1.isSecure = lambda: False request1.content = b"llamas" request1.client = IPv4Address("TCP", b"50.0.50.0", 5000) d = deferToThreadPool(reactor, self.tp, hr.render, request1) d.addCallback(lambda _: request1.notifyFinish()) return d
def test_defaultHEAD(self): """ When not otherwise overridden, L{Resource.render} treats a I{HEAD} request as if it were a I{GET} request. """ expected = b"insert response here" request = DummyRequest([]) request.method = b'HEAD' resource = BytesReturnedRenderable(expected) self.assertEqual(expected, resource.render(request))
def test_success(self): def on_rendered(_): self.assertEqual(['backend reply'], self.request.written) d = _render(self.resource, self.request).addCallback(on_rendered) callback_request = DummyRequest(['']) callback_request.content = StringIO('backend reply') self.resource.factory.requests.values()[0].notify(callback_request) return d
def test_get(self): request = DummyRequest(['/account-recovery']) request.method = 'GET' d = self.web.get(request) def assert_200_when_user_logged_in(_): self.assertEqual(200, request.responseCode) self.assertIn("DOCTYPE html", request.written[0]) d.addCallback(assert_200_when_user_logged_in) return d
def test_returns_404_if_key_not_found(self): request = DummyRequest(['/keys']) request.addArg('search', '*****@*****.**') when(self.keymanager).get_key_from_cache('*****@*****.**', OpenPGPKey).thenRaise(KeyNotFound()) d = self.web.get(request) def assert_404(_): self.assertEquals(404, request.code) d.addCallback(assert_404) return d
def test_returns_404_if_key_not_found(self): request = DummyRequest(['/keys']) request.addArg('search', '*****@*****.**') when(self.keymanager).fetch_key('*****@*****.**').thenReturn(defer.fail(KeyNotFound())) d = self.web.get(request) def assert_404(_): self.assertEquals(404, request.code) d.addCallback(assert_404) return d
def test_post_returns_successfully(self): request = DummyRequest(['/account-recovery']) request.method = 'POST' self.resource._handle_post = MagicMock(return_value=defer.succeed(None)) d = self.web.get(request) def assert_successful_response(_): self.assertEqual(200, request.responseCode) d.addCallback(assert_successful_response) return d
def test_post_returns_failure(self): request = DummyRequest(['/account-recovery']) request.method = 'POST' self.resource._handle_post = MagicMock(return_value=defer.fail(InvalidPasswordError)) d = self.web.get(request) def assert_error_response(_): self.assertEqual(500, request.responseCode) d.addCallback(assert_error_response) return d
def test_returns_unauthorized_if_key_is_private(self): request = DummyRequest(['/keys']) request.addArg('search', 'some@key') when(self.keymanager).fetch_key('some@key').thenReturn(defer.succeed(OpenPGPKey('some@key', private=True))) d = self.web.get(request) def assert_response(_): self.assertEquals(401, request.code) d.addCallback(assert_response) return d
def test_post_returns_successfully(self, mock_update_recovery_code): mock_update_recovery_code.return_value = defer.succeed("Success") request = DummyRequest(['/backup-account']) request.method = 'POST' request.content = MagicMock() request.content.getvalue.return_value = '{"email": "*****@*****.**"}' d = self.web.get(request) def assert_successful_response(_): self.assertEqual(204, request.responseCode) d.addCallback(assert_successful_response) return d
def test_render_GET_should_template_account_email(self): request = DummyRequest(['']) request.addCookie = lambda key, value: 'stubbed' d = self.web.get(request) def assert_response(_): expected = "<title>{0}</title>".format(self.MAIL_ADDRESS) matches = re.findall(expected, request.written[0]) self.assertEquals(len(matches), 1) d.addCallback(assert_response) return d
def test_post_returns_internal_server_error(self, mock_update_recovery_code): mock_update_recovery_code.return_value = defer.fail(Exception) request = DummyRequest(['/backup-account']) request.method = 'POST' request.content = MagicMock() request.content.getvalue.return_value = '{"email": "*****@*****.**"}' d = self.web.get(request) def assert_successful_response(_): self.assertEqual(500, request.responseCode) d.addCallback(assert_successful_response) return d
def test_explicitAllowedMethods(self): """ The L{UnsupportedMethod} raised by L{Resource.render} for an unsupported request method has a C{allowedMethods} attribute set to the value of the C{allowedMethods} attribute of the L{Resource}, if it has one. """ expected = [b'GET', b'HEAD', b'PUT'] resource = Resource() resource.allowedMethods = expected request = DummyRequest([]) request.method = b'FICTIONAL' exc = self.assertRaises(UnsupportedMethod, resource.render, request) self.assertEqual(set(expected), set(exc.allowedMethods))
def test_should_authorize_child_resource_non_ajax_GET_requests(self): request = DummyRequest(['features']) request.getCookie = MagicMock(return_value='irrelevant -- stubbed') self.root_resource._child_resources.add('features', FeaturesResource()) d = self.web.get(request) def assert_unauthorized(_): self.assertEqual(200, request.code) d.addCallback(assert_unauthorized) return d
def test_should_unauthorize_child_resource_ajax_requests_when_csrf_mismatch(self): request = DummyRequest(['/child']) self._mock_ajax_csrf(request, 'stubbed csrf token') request.getCookie = MagicMock(return_value='mismatched csrf token') d = self.web.get(request) def assert_unauthorized(_): self.assertEqual(401, request.responseCode) self.assertEqual("Unauthorized!", request.written[0]) d.addCallback(assert_unauthorized) return d
def test_should_unavailable_child_resource_during_startup(self): self.root_resource._mode = MODE_STARTUP request = DummyRequest(['/child']) request.getCookie = MagicMock(return_value='irrelevant -- stubbed') d = self.web.get(request) def assert_unavailable(_): self.assertEqual(503, request.responseCode) self.assertEqual("Service Unavailable", request.written[0]) d.addCallback(assert_unavailable) return d
def test_sends_feedback_to_leap_web(self): request = DummyRequest(['/feedback']) request.method = 'POST' content = mock() when(content).read().thenReturn(json.dumps({'feedback': 'Pixelated is awesome!'})) request.content = content d = self.web.get(request) def assert_posted_feedback_to_leap_web(_): verify(self.feedback_service).open_ticket('Pixelated is awesome!') d.addCallback(assert_posted_feedback_to_leap_web) return d
def test_implicitAllowedMethods(self): """ The L{UnsupportedMethod} raised by L{Resource.render} for an unsupported request method has a C{allowedMethods} attribute set to a list of the methods supported by the L{Resource}, as determined by the I{render_}-prefixed methods which it defines, if C{allowedMethods} is not explicitly defined by the L{Resource}. """ expected = set([b'GET', b'HEAD', b'PUT']) resource = ImplicitAllowedMethods() request = DummyRequest([]) request.method = b'FICTIONAL' exc = self.assertRaises(UnsupportedMethod, resource.render, request) self.assertEqual(expected, set(exc.allowedMethods))
def test_render(self): """ L{DeferredResource} uses the request object's C{render} method to render the resource which is the result of the L{Deferred} being handled. """ rendered = [] request = DummyRequest([]) request.render = rendered.append result = resource.Resource() deferredResource = DeferredResource(defer.succeed(result)) deferredResource.render(request) self.assertEqual(rendered, [result])
def test_contemporaneous_requests(self): ''' We're going to create two request-response cycles here: Cycle 1 will begin. Cycle 2 will begin. Cycle 2 will return. Cycle 1 will return. This way, we can prove that the crosstown_traffic created by cycle 1 is not resolved by the return of cycle 2. ''' tp = ThreadPool(maxthreads=20) tp.start() self.addCleanup(tp.stop) log.debug("\n\nStarting the two stream stuff.") request1 = DummyRequest('r1') request1.isSecure = lambda: False request1.content = "Nothing really here." request1.headers['llamas'] = 'dingo' nameSpace.test_case = self hr = HendrixWSGIResource(reactor, tp, wsgi_application) d1 = deferToThreadPool(reactor, tp, hr.render, request1) request2 = DummyRequest('r2') request2.isSecure = lambda: False request2.content = "Nothing really here." request2.headers['llamas'] = 'dingo' d2 = deferToThreadPool(reactor, tp, hr.render, request2) def woah_stop(failure): nameSpace.async_task_was_done.put_nowait(False) nameSpace.second_cycle_complete.put_nowait(False) nameSpace.ready_to_proceed_with_second_cycle.put_nowait(False) d1.addErrback(woah_stop) d2.addErrback(woah_stop) combo_deferred = gatherResults([d1, d2]) def wait_for_queue_resolution(): nameSpace.async_task_was_done.get(True, 3) combo_deferred.addCallback( lambda _: deferToThreadPool(reactor, tp, wait_for_queue_resolution) ) combo_deferred.addCallback( lambda _: self.assertTrue(nameSpace.async_task_was_run) ) return combo_deferred
def _test_should_renew_xsrf_cookie(self): request = DummyRequest(['']) request.addCookie = MagicMock() generated_csrf_token = 'csrf_token' mock_sha = MagicMock() mock_sha.hexdigest = MagicMock(return_value=generated_csrf_token) with patch('hashlib.sha256', return_value=mock_sha): d = self.web.get(request) def assert_csrf_cookie(_): request.addCookie.assert_called_once_with('XSRF-TOKEN', generated_csrf_token) d.addCallback(assert_csrf_cookie) return d
def test_should_404_non_existing_resource_with_valid_csrf(self): request = DummyRequest(['/non-existing-child']) request.method = 'POST' self._mock_ajax_csrf(request, 'stubbed csrf token') request.getCookie = MagicMock(return_value='stubbed csrf token') d = self.web.get(request) def assert_not_found(_): self.assertEqual(404, request.responseCode) self.assertIn("No Such Resource", request.written[0]) d.addCallback(assert_not_found) return d
def test_contemporaneous_requests(): ''' We're going to create two request-response cycles here: Cycle 1 will begin. Cycle 2 will begin. Cycle 2 will return. Cycle 1 will return. This way, we can prove that the crosstown_traffic created by cycle 1 is not resolved by the return of cycle 2. ''' tp = ThreadPool(maxthreads=20) tp.start() log.debug("\n\nStarting the two stream stuff.") request1 = DummyRequest([b'r1']) request1.isSecure = lambda: False request1.content = "Nothing really here." request1.requestHeaders.addRawHeader('llamas', 'dingo') request1.client = IPv4Address("TCP", b"50.0.50.0", 5000) hr = HendrixWSGIResource(reactor, tp, wsgi_application) yield deferToThreadPool(reactor, tp, hr.render, request1) request2 = DummyRequest([b'r2']) request2.isSecure = lambda: False request2.content = b"Nothing really here." request2.requestHeaders.addRawHeader('llamas', 'dingo') request2.client = IPv4Address("TCP", b"100.0.50.0", 5000) yield deferToThreadPool(reactor, tp, hr.render, request2) # def woah_stop(failure): # nameSpace.async_task_was_done.put_nowait(False) # nameSpace.second_cycle_complete.put_nowait(False) # nameSpace.ready_to_proceed_with_second_cycle.put_nowait(False) # # d1.addErrback(woah_stop) # d2.addErrback(woah_stop) # combo_deferred = gatherResults([d1, d2]) # yield d1 # yield d2 # combo_deferred = DeferredList([d1, d2]) def wait_for_queue_resolution(): nameSpace.async_task_was_done.get(True, 3) # combo_deferred.addCallback( # lambda _: # ) # yield deferToThreadPool(reactor, tp, wait_for_queue_resolution) # combo_deferred.addCallback( # lambda _: # ) assert nameSpace.async_task_was_run tp.stop()
def forge_request(uri='https://www.globaleaks.org/', headers=None, body='', client_addr=None, method='GET', handler_cls=None, attached_file={}): """ Creates a twisted.web.Request compliant request that is from an external IP address. """ if headers is None: headers = {} _, host, path, query, frag = urlparse.urlsplit(uri) x = host.split(':') if len(x) > 1: port = int(x[1]) else: port = 80 request = DummyRequest(['']) request.tid = 1 request.method = method request.uri = uri request.path = path request._serverName = bytes(host) request.code = 200 request.client_ip = '127.0.0.1' request.client_proto = 'https' request.client_using_tor = False def getResponseBody(): return ''.join(request.written) request.getResponseBody = getResponseBody if client_addr is None: request.client = IPv4Address('TCP', '1.2.3.4', 12345) else: request.client = client_addr def getHost(): return IPv4Address('TCP', '127.0.0.1', port) request.getHost = getHost def notifyFinish(): return Deferred() request.notifyFinish = notifyFinish request.requestHeaders.setRawHeaders('host', ['127.0.0.1']) for k, v in headers.items(): request.requestHeaders.setRawHeaders(bytes(k), [bytes(v)]) request.headers = request.getAllHeaders() request.args = {} if attached_file is not None: request.args = {'file': [attached_file]} class fakeBody(object): def read(self): if isinstance(body, dict): return json.dumps(body) else: return body def close(self): pass request.content = fakeBody() return request
def __init__(self, *args, **kw): # Twisted 13.2.0 doesn't have .requestHeaders on DummyRequest TwistedDummyRequest.__init__(self, *args, **kw) if not hasattr(self, 'requestHeaders'): self.requestHeaders = Headers()
def test_getResourceFor_returns_no_resource_wo_underlay(self): root = Resource() site = OverlaySite(root) request = DummyRequest([b"MAAS"]) resource = site.getResourceFor(request) self.assertThat(resource, IsInstance(NoResource))
def setUp(self): super(EventSourceProducerTest, self).setUp() self.request = DummyRequest([]) self.producer = EventSourceProducer(self.request)
def test__render_POST_missing_authorization(self): resource = StatusHandlerResource(sentinel.status_worker) request = DummyRequest([]) output = resource.render_POST(request) self.assertEquals(b'', output) self.assertEquals(401, request.responseCode)
def test_putNamedChild_sort_of_wrong_request(self): "requests to incorrect subpaths go to NoResource" with mock.patch('hendrix.facilities.resources.WSGIResource') as wsgi: request = DummyRequest(['path', 'to', 'wrong']) actual_res = getChildForRequest(self.hr, request) self.assertIsInstance(actual_res, NoResource)
def test_putNamedChild_very_wrong_request(self): "check that requests outside of the children go to the WSGIResoure" with mock.patch('hendrix.facilities.resources.WSGIResource') as wsgi: request = DummyRequest(['very', 'wrong', 'uri']) actual_res = getChildForRequest(self.hr, request) self.assertIsInstance(actual_res, WSGIResource)
def test_putNamedChild_success(self): with mock.patch('hendrix.facilities.resources.WSGIResource') as wsgi: request = DummyRequest(['path', 'to', 'child']) actual_res = getChildForRequest(self.hr, request) self.assertEqual(self.res, actual_res)
class TestLoginPOST(unittest.TestCase): def setUp(self): self.services_factory = mock() self.portal = mock() self.provider = mock() self.resource = LoginResource(self.services_factory, self.portal) self.web = DummySite(self.resource) self.request = DummyRequest(['']) username = '******' self.request.addArg('username', username) password = '******' self.username = username self.password = password self.request.addArg('password', password) self.request.method = 'POST' leap_session = mock(LeapSession) user_auth = mock() user_auth.uuid = 'some_user_uuid' leap_session.user_auth = user_auth config = mock() config.leap_home = 'some_folder' leap_session.config = config leap_session.fresh_account = False self.leap_session = leap_session self.user_auth = user_auth def mock_user_has_services_setup(self): when(self.services_factory).is_logged_in('some_user_uuid').thenReturn( True) def test_login_responds_interstitial_and_add_corresponding_session_to_services_factory( self): irrelevant = None when(self.portal).login(ANY(), None, IResource).thenReturn( (irrelevant, self.leap_session, irrelevant)) when(self.services_factory).create_services_from( self.leap_session).thenAnswer(self.mock_user_has_services_setup) d = self.web.get(self.request) def assert_login_setup_service_for_user(_): verify(self.portal).login(ANY(), None, IResource) verify(self.services_factory).create_services_from( self.leap_session) interstitial_js_in_template = '<script src="startup-assets/Interstitial.js"></script>' self.assertIn(interstitial_js_in_template, self.request.written[0]) self.assertTrue(self.resource.is_logged_in(self.request)) d.addCallback(assert_login_setup_service_for_user) return d def test_login_does_not_reload_services_if_already_loaded(self): irrelevant = None when(self.portal).login(ANY(), None, IResource).thenReturn( (irrelevant, self.leap_session, irrelevant)) when(self.services_factory).is_logged_in('some_user_uuid').thenReturn( True) d = self.web.get(self.request) def assert_login_setup_service_for_user(_): verify(self.portal).login(ANY(), None, IResource) verify(self.services_factory).is_logged_in('some_user_uuid') verifyNoMoreInteractions(self.services_factory) interstitial_js_in_template = '<script src="startup-assets/Interstitial.js"></script>' self.assertIn(interstitial_js_in_template, self.request.written[0]) self.assertTrue(self.resource.is_logged_in(self.request)) d.addCallback(assert_login_setup_service_for_user) return d def test_should_return_form_back_with_error_message_when_login_fails(self): when(self.portal).login(ANY(), None, IResource).thenRaise(Exception()) d = self.web.get(self.request) def assert_login_setup_service_for_user(_): verify(self.portal).login(ANY(), None, IResource) self.assertEqual(401, self.request.responseCode) written_response = ''.join(self.request.written) self.assertIn('Invalid credentials', written_response) self.assertFalse(self.resource.is_logged_in(self.request)) d.addCallback(assert_login_setup_service_for_user) return d @patch('pixelated.bitmask_libraries.session.LeapSessionFactory.create') @patch('leap.auth.SRPAuth.authenticate') @patch('pixelated.config.services.Services.setup') def test_leap_session_is_not_created_when_leap_auth_fails( self, mock_service_setup, mock_leap_srp_auth, mock_leap_session_create): mock_leap_srp_auth.side_effect = SRPAuthenticationError() d = self.web.get(self.request) def assert_login_setup_service_for_user(_): verify(self.portal).login(ANY(), None, IResource) self.assertFalse(mock_leap_session_create.called) self.assertFalse(mock_service_setup.called) self.assertEqual(401, self.request.responseCode) self.assertFalse(self.resource.is_logged_in(self.request)) d.addCallback(assert_login_setup_service_for_user) return d @patch('twisted.web.util.redirectTo') @patch('pixelated.resources.session.PixelatedSession.is_logged_in') def test_should_not_process_login_if_already_logged_in( self, mock_logged_in, mock_redirect): mock_logged_in.return_value = True when(self.services_factory).is_logged_in(ANY()).thenReturn(True) mock_redirect.return_value = "mocked redirection" when(self.portal).login(ANY(), None, IResource).thenRaise(Exception()) d = self.web.get(self.request) def assert_login_setup_service_for_user(_): verifyZeroInteractions(self.portal) mock_redirect.assert_called_once_with('/', self.request) d.addCallback(assert_login_setup_service_for_user) return d
def test_get_is_not_supported_for_logout(self): request = DummyRequest(['/logout']) request.method = 'GET' self.assertRaises(UnsupportedMethod, self.web.get, request)
def test_other_404(self): request = DummyRequest([b"foo.jpg"]) resource = self.docs.getChild(b"foo.jpg", request) self.assertTrue(resource.path.endswith("404.html"), resource.path)
def write(self, method, data): DummyRequest.write(self, data) self.startedWriting = True
def test_other_resource(self): self.touch_file("foo.jpg") request = DummyRequest([b"foo.jpg"]) resource = self.docs.getChild(b"foo.jpg", request) self.assertTrue(resource.path.endswith("foo.jpg"), resource.path)
def notifyFinish(self): # Working around a possible bug in DummyRequest, where self._finishedDeferreds somehow gets set to None if self._finishedDeferreds is None: self._finishedDeferreds = [] return DummyRequest.notifyFinish(self)
def test_append_html(self): self.touch_file("foo.html") request = DummyRequest([b"foo"]) resource = self.docs.getChild(b"foo", request) self.assertTrue(resource.path.endswith("foo.html"), resource.path)
def test_index(self): self.touch_file("maas-documentation-25.html") request = DummyRequest([b""]) resource = self.docs.getChild(b"", request) self.assertTrue(resource.path.endswith("maas-documentation-25.html"), resource.path)
def request(self, jbody=None, user_id=None, role=None, headers=None, body='', path=None, remote_ip='0.0.0.0', method='MOCK', handler_cls=None, attached_file={}, kwargs={}): """ Constructs a handler for preforming mock requests using the bag of params described below. Args: jbody: The body of the request as a dict (it will be automatically converted to string) body: The body of the request as a string user_id: when simulating authentication the session should be bound to a certain user_id. role: when simulating authentication the session should be bound to a certain role. method: HTTP method, e.g. "GET" or "POST" headers: Dict of headers to pass on the request remote_ip: If a particular remote_ip should be set. handler_cls: The type of handler that will respond to the request. If this is not set self._handler is used. attached_file: A dict to place in the request.args.files obj """ if jbody and not body: body = json.dumps(jbody) elif body and jbody: raise ValueError('jbody and body in conflict') if handler_cls is None: handler_cls = self._handler request = DummyRequest(['']) def getResponseBody(): return ''.join(request.written) request.path = '' request.code = 200 request.language = 'en' request.client_ip = '127.0.0.1' request.client_proto = 'https' request.client_using_tor = False request.getResponseBody = getResponseBody request.client = IPv4Address('TCP', '1.2.3.4', 12345) request.args = {} if attached_file is not None: request.args = {'file': [attached_file]} if headers is not None: for k, v in headers.iteritems(): request.requestHeaders.setRawHeaders(bytes(k), [bytes(v)]) request.headers = request.getAllHeaders() from globaleaks.rest import api x = api.APIResourceWrapper() x.preprocess(request) if path is not None: if not path.startswith('/'): raise ValueError('Must pass a valid url path') request.path = path class fakeBody(object): def read(self): return body def close(self): pass request.content = fakeBody() from globaleaks.rest.api import decorate_method if not getattr(handler_cls, 'decorated', False): for method in ['get', 'post', 'put', 'delete']: if getattr(handler_cls, method, None) is not None: decorate_method(handler_cls, method) handler_cls.decorated = True handler = handler_cls(request, **kwargs) if user_id is None and role is not None: if role == 'admin': user_id = self.dummyAdminUser['id'] elif role == 'receiver': user_id = self.dummyReceiverUser_1['id'] elif role == 'custodian': user_id = self.dummyCustodianUser['id'] if role is not None: session = new_session(user_id, role, 'enabled') handler.request.headers['x-session'] = session.id return handler
def test_root_json(self): """ The 'welcome' / root page renders properly with ?t=json when some servers show None for available_space while others show a valid int See also https://tahoe-lafs.org/trac/tahoe-lafs/ticket/3852 """ ann = { "anonymous-storage-FURL": "pb://w2hqnbaa25yw4qgcvghl5psa3srpfgw3@tcp:127.0.0.1:51309/vucto2z4fxment3vfxbqecblbf6zyp6x", "permutation-seed-base32": "w2hqnbaa25yw4qgcvghl5psa3srpfgw3", } srv0 = NativeStorageServer(b"server_id0", ann, None, {}, EMPTY_CLIENT_CONFIG) srv0.get_connection_status = lambda: ConnectionStatus( False, "summary0", {}, 0, 0) srv1 = NativeStorageServer(b"server_id1", ann, None, {}, EMPTY_CLIENT_CONFIG) srv1.get_connection_status = lambda: ConnectionStatus( False, "summary1", {}, 0, 0) # arrange for this server to have some valid available space srv1.get_available_space = lambda: 12345 class FakeClient(_Client): history = [] stats_provider = object() nickname = "" nodeid = b"asdf" _node_public_key = create_signing_keypair()[1] introducer_clients = [] helper = None def __init__(self): service.MultiService.__init__(self) self.storage_broker = StorageFarmBroker( permute_peers=True, tub_maker=None, node_config=EMPTY_CLIENT_CONFIG, ) self.storage_broker.test_add_server(b"test-srv0", srv0) self.storage_broker.test_add_server(b"test-srv1", srv1) root = Root(FakeClient(), now_fn=time.time) lines = [] req = DummyRequest(b"") req.fields = {} req.args = { b"t": [b"json"], } # for some reason, DummyRequest is already finished when we # try to add a notifyFinish handler, so override that # behavior. def nop(): return succeed(None) req.notifyFinish = nop req.write = lines.append yield root.render(req) raw_js = b"".join(lines).decode("utf8") js = json.loads(raw_js) servers = js["servers"] self.assertEquals(len(servers), 2) self.assertIn( { "connection_status": "summary0", "nodeid": "server_id0", "last_received_data": 0, "version": None, "available_space": None, "nickname": "" }, servers) self.assertIn( { "connection_status": "summary1", "nodeid": "server_id1", "last_received_data": 0, "version": None, "available_space": 12345, "nickname": "" }, servers)
def forge_request(uri=b'https://www.globaleaks.org/', headers=None, body='', client_addr=None, method=b'GET', handler_cls=None, attached_file={}): """ Creates a twisted.web.Request compliant request that is from an external IP address. """ if headers is None: headers = {} _, host, path, query, frag = urlsplit(uri) x = host.split (b':') if len(x) > 1: port = int(x[1]) else: port = 80 request = DummyRequest([b'']) request.tid = 1 request.method = method request.uri = uri request.path = path request._serverName = host request.code = 200 request.client_ip = b'127.0.0.1' request.client_proto = b'https' request.client_using_tor = False def getResponseBody(): # Ugh, hack. Twisted returns this all as bytes, and we want it as str if isinstance(request.written[0], binary_type): return b''.join(request.written) else: return ''.join(request.written) request.getResponseBody = getResponseBody if client_addr is None: request.client = IPv4Address('TCP', b'1.2.3.4', 12345) else: request.client = client_addr def getHost(): return IPv4Address('TCP', b'127.0.0.1', port) request.getHost = getHost def notifyFinish(): return Deferred() request.notifyFinish = notifyFinish request.requestHeaders.setRawHeaders('host', [b'127.0.0.1']) request.requestHeaders.setRawHeaders('user-agent', [b'NSA Agent']) for k, v in headers.items(): request.requestHeaders.setRawHeaders(k, [v]) request.headers = request.getAllHeaders() request.args = {} if attached_file is not None: request.args = {'file': [attached_file]} class fakeBody(object): def read(self): if isinstance(body, dict): ret = json.dumps(body) else: ret = body if isinstance(ret, text_type): ret = ret.encode('utf-8') return ret def close(self): pass request.content = fakeBody() return request
def makeRequest(self, *args, **kwargs): request = DummyRequest(*args, **kwargs) request.path = '/' return request
def forge_request(uri='https://www.globaleaks.org/', headers={}, method=b'GET', client_addr=None): """ Creates a twisted.web.Request compliant request that is from an external IP address. """ _, host, path, query, frag = urlparse.urlsplit(uri) x = host.split(':') if len(x) > 1: port = int(x[1]) else: port = 80 ret = DummyRequest(['']) ret.method = method ret.uri = uri ret.path = path ret._serverName = bytes(host) if client_addr is None: ret.client = IPv4Address('TCP', '1.2.3.4', 12345) else: ret.client = client_addr def getHost(): return IPv4Address('TCP', '127.0.0.1', port) ret.getHost = getHost def notifyFinish(): return Deferred() ret.notifyFinish = notifyFinish for k, v in headers.iteritems(): ret.requestHeaders.setRawHeaders(bytes(k), [bytes(v)]) ret.headers = ret.getAllHeaders() return ret