def consumer_add_action(self, context): if context.environ['REQUEST_METHOD'].upper() != 'POST': raise wsgi.MethodNotAllowed owner = context.session.get_owner() if owner is None: # we require an owner to be logged in raise wsgi.PageNotAuthorized silo = owner['Silo'].GetEntity() try: handle = context.get_form_string('handle', 80) key = context.get_form_string('key', 80) secret = context.get_form_string('secret', 80) with silo['Consumers'].OpenCollection() as collection: consumer = lti.ToolConsumer.new_from_values( collection.new_entity(), self.app_cipher, handle, key=key, secret=secret) collection.insert_entity(consumer.entity) except edm.ConstraintError: # ID/Key clash most likely, offer a message and a back page link = URI.from_octets( "./?error=duplicate_key").resolve(context.get_url()) return self.redirect_page(context, link, 303) except ValueError: raise wsgi.BadRequest except KeyError: raise wsgi.PageNotAuthorized link = URI.from_octets("./").resolve(context.get_url()) return self.redirect_page(context, link, 303)
def edit_action(self, context): if context.environ['REQUEST_METHOD'].upper() != 'POST': raise wsgi.MethodNotAllowed self.load_visit(context) # we must have both a user and a group if context.group is None: raise wsgi.PageNotAuthorized try: key = odata.uri_literal_from_str( context.get_form_string('id')).value with context.group['Notices'].open() \ as collection: collection.set_expand({'User': None}) entity = collection[key] user = entity['User'].get_entity() if not (context.user and context.user == user): # only the owner can edit their post raise wsgi.PageNotAuthorized now = time.time() entity['Title'].set_from_value( context.get_form_string('title')) entity['Description'].set_from_value( context.get_form_string('description')) entity['Updated'].set_from_value(now) collection.update_entity(entity) except ValueError: raise wsgi.BadRequest except KeyError: raise wsgi.PageNotFound link = URI.from_octets("view").resolve(context.get_url()) return self.redirect_page(context, link, 303)
def delete_action(self, context): if context.environ['REQUEST_METHOD'].upper() != 'POST': raise wsgi.MethodNotAllowed self.load_visit(context) # we must have both a user and a group if context.group is None: raise wsgi.PageNotAuthorized try: key = odata.uri_literal_from_str( context.get_form_string('id')).value with context.group['Notices'].open() \ as collection: collection.set_expand({'User': None}) entity = collection[key] user = entity['User'].get_entity() if (not (context.user and context.user == user) and not (context.permissions & self.WRITE_PERMISSION)): # only the owner or user with write permissions can delete raise wsgi.PageNotAuthorized entity.delete() except ValueError: raise wsgi.BadRequest except KeyError: raise wsgi.PageNotFound link = URI.from_octets("view").resolve(context.get_url()) return self.redirect_page(context, link, 303)
def main(user, password, product_list): metadata = URI.from_path('metadata.xml') service = URI.from_path('scihub.copernicus.eu.xml') credentials = BasicCredentials() credentials.userid = user credentials.password = password credentials.protectionSpace = URI.from_octets(SERVICE).get_canonical_root() # the full link of odata is https://scihub.copernicus.eu/apihub/odata/v1 # this is for the authentication c = Client(ca_certs=CERTIFICATE) c.add_credentials(credentials) c.load_service(service_root=service, metadata=metadata) with c.feeds['Products'].open() as products: for pid in product_list: p = products[pid] name = p['Name'].value size = p['ContentLength'].value output("Product: %s [%i]\n" % (name, size)) with open('%s.zip' % name, 'wb') as f: products.read_stream(p.key(), f) if not product_list: i = 0 for p in products.itervalues(): name = p['Name'].value type = p['ContentType'].value size = p['ContentLength'].value output("%s\n" % str(p.get_location())) output(" %s %s[%i]\n" % (name, type, size)) i += 1 if i > MAX_LIST: break
def add_action(self, context): if context.environ['REQUEST_METHOD'].upper() != 'POST': raise wsgi.MethodNotAllowed self.load_visit(context) # we must have both a user and a group if context.user is None: raise wsgi.PageNotAuthorized if context.group is None: raise wsgi.PageNotAuthorized # create a new Notice entity with self.container['Notices'].open() \ as collection: now = time.time() new_notice = collection.new_entity() new_notice['Title'].set_from_value( context.get_form_string('title')) new_notice['Description'].set_from_value( context.get_form_string('description')) new_notice['Created'].set_from_value(now) new_notice['Updated'].set_from_value(now) new_notice['User'].bind_entity(context.user) new_notice['Context'].bind_entity(context.group) collection.insert_entity(new_notice) link = URI.from_octets("view").resolve(context.get_url()) return self.redirect_page(context, link, 303)
def setup(cls, options=None, args=None, **kwargs): """Adds OData initialisation Loads the :attr:`metadata` document. Creates the :attr:`data_source` according to the configured :attr:`settings` (creating the tables only if requested in the command line options). Finally sets the :attr:`container` to the entity container for the application. If the -s or --sqlout option is given in options then the data source's create table script is output to standard output and sys.exit(0) is used to terminate the process.""" super(DemoApp, cls).setup(options, args, **kwargs) settings = cls.settings.setdefault('DemoApp', {}) customer_id = settings.setdefault('customer_id', None) url = settings.setdefault('deliveryodata', None) if url: # overrides customer_id in settings file customer_id = None if options and options.customer_id: # overrides url in settings file customer_id = options.customer_id url = None if options and options.deliveryodata_url: # overrides everything customer_id = None url = options.deliveryodata_url if customer_id: if customer_id.isdigit(): if int(customer_id) < 600000: url = US_ONDEMAND % customer_id else: url = EU_ONDEMAND % customer_id elif customer_id.isalnum(): url = US_ONDEMAND % customer_id else: sys.exit("Bad customer id: %s" % customer_id) if url: cls.deliveryodata = URI.from_octets(url) if not cls.deliveryodata.is_absolute(): # resolve relative to the current working directory cls.deliveryodata = cls.deliveryodata.resolve( URI.from_path(os.path.join(os.getcwd(), 'index'))) elif not url.endswith('/'): url = url + '/' else: sys.exit("One of customer id or Delivery OData URL is required") if options and options.cert: # grab the certificate from the live server cls.ca_path = options.cert settings.setdefault('user', customer_id) if options and options.user is not None: settings['user'] = options.user settings.setdefault('password', None) if options and options.password is not None: settings['password'] = options.password if not settings['password']: settings['password'] = getpass.getpass()
def test_framed_cookies(self): req = MockRequest() req.call_app(self.app) # we expect a redirect self.assertTrue(req.status.startswith('303 ')) self.assertTrue('location' in req.headers) target = req.headers['location'] self.assertTrue(len(target) == 1) target = URI.from_octets(target[0]) self.assertTrue(target.get_addr() == ('localhost', 80)) self.assertTrue(isinstance(target, params.HTTPURL)) # and we expect a warning cookie self.assertTrue(noticeboard.COOKIE_WARNING in req.cookies) # and we expect a session cookie self.assertTrue(noticeboard.COOKIE_SESSION in req.cookies) cflag = req.cookies[noticeboard.COOKIE_WARNING] sid = req.cookies[noticeboard.COOKIE_SESSION] # follow the redirect, passing the cookies req = MockRequest(path=target.abs_path, query=target.query) req.add_cookies([cflag, sid]) req.call_app(self.app) # we expect a redirect back to our original path self.assertTrue(req.status.startswith('303 '), req.status) self.assertTrue('location' in req.headers) target = req.headers['location'] self.assertTrue(len(target) == 1) target = URI.from_octets(target[0]) self.assertTrue(target.get_addr() == ('localhost', 80)) self.assertTrue(isinstance(target, params.HTTPURL)) self.assertTrue(target.abs_path == '/') # and an updated sid! self.assertTrue(noticeboard.COOKIE_SESSION in req.cookies) new_sid = req.cookies[noticeboard.COOKIE_SESSION] self.assertFalse(sid.value == new_sid.value) sid = new_sid # now we repeat the first request with the cookies, # should not get a redirect anymore req = MockRequest() req.add_cookies([cflag, sid]) req.call_app(self.app) self.assertTrue(req.status.startswith('200 ')) self.assertFalse('location' in req.headers)
def test_split_role(self): learner = lti.ROLE_HANDLES['Learner'] vocab, rtype, subtype = lti.split_role(learner) self.assertTrue(vocab == 'role') self.assertTrue(rtype == 'Learner') self.assertTrue(subtype is None) instructor = lti.ROLE_HANDLES['Instructor/Lecturer'] vocab, rtype, subtype = lti.split_role(instructor) self.assertTrue(vocab == 'role') self.assertTrue(rtype == 'Instructor') self.assertTrue(subtype == 'Lecturer') guest = lti.INSTROLE_HANDLES['Guest'] vocab, rtype, subtype = lti.split_role(guest) self.assertTrue(vocab == 'instrole') self.assertTrue(rtype == 'Guest') self.assertTrue(subtype is None) # now check for badly formed or unknown paths badrole = URI.from_octets('urn:lti:xrole:pyslet/lti/User') try: vocab, rtype, subtype = lti.split_role(badrole) self.fail("bad lis path") except ValueError: pass # and now with something that isn't the right type of URN badrole = URI.from_octets('URN:ISBN:9780099512240') self.assertTrue(isinstance(badrole, URN)) try: vocab, rtype, subtype = lti.split_role(badrole) self.fail("bad URN type") except ValueError: pass # and finally something that isn't even a URN badrole = URI.from_octets( 'http://www.example.com/ims/lis/WebDeveloper') try: vocab, rtype, subtype = lti.split_role(badrole) self.fail("role from http URL") except ValueError: pass
def snapview(self, context): qparams = context.get_query() sid = long(qparams['sid']) with self.container['AssessmentSnapshots'].OpenCollection() as snapshots: snapshot = snapshots[sid] link = snapshot['PrintableDocumentSourceUrl'].value.split() rlink = string.join(link, '%20') if len(link) > 1: logging.error("URL contained unencoded space: %s" % repr(snapshot['PrintableDocumentSourceUrl'].value)) return self.redirect_page( context, URI.from_octets(rlink), 303)
def plaunch(self, context): qparams = context.get_query() aid = long(qparams['aid']) with self.container['Attempts'].OpenCollection() as attempts: attempt = attempts[aid] link = attempt['ProctorFacingQMControlsWidgetUrl'].value.split() rlink = string.join(link, '%20') if len(link) > 1: logging.error( "URL contained unencoded space: %s" % repr(attempt['ProctorFacingQMControlsWidgetUrl'].value)) return self.redirect_page( context, URI.from_octets(rlink), 303)
def test_no_cookies(self): req = MockRequest() req.call_app(self.app) # follow the redirect, tested in the framed test target = URI.from_octets(req.headers['location'][0]) # ...but ignore the cookies req = MockRequest(path=target.abs_path, query=target.query) req.call_app(self.app) # this should display the frame detection page, no cookies self.assertTrue(req.status.startswith('200 ')) self.assertFalse('location' in req.headers) self.assertTrue(len(req.cookies) == 0) # can we check the content? doc = html.XHTMLDocument() req.output.seek(0) doc.Read(req.output) # there should be a form called 'wlaunch' form = doc.GetElementByID('wlaunch') target = form.action # get the input fields query = {} for input in form.FindChildrenDepthFirst(html.Input): if input.name in ("return", "sid", "submit"): query[input.name] = str(input.value) query = urllib.urlencode(query) # autosubmit the form, no cookies to send req = MockRequest(path=target.abs_path, query=query) req.call_app(self.app) # should now get a very similar response to our first ever call, # redirect to the test page with no cookies target = URI.from_octets(req.headers['location'][0]) req = MockRequest(path=target.abs_path, query=target.query) req.call_app(self.app) # we expect content - explaining that we've failed self.assertTrue(req.status.startswith('200 ')) self.assertFalse('location' in req.headers)
def setup(cls, options=None, args=None, **kwargs): """Adds multi-tenant initialisation""" super(MultiTenantTPApp, cls).setup(options, args, **kwargs) mt_settings = cls.settings.setdefault("MultiTenantTPApp", {}) mt_settings.setdefault("google_client_id", "") mt_settings.setdefault("google_client_secret", "") cert_url = mt_settings.setdefault("google_certs", "google_certs.pem") cls.cert_file = cls.resolve_setup_path(cert_url) if options and options.google_certs: # update the certs_file and exit c = http.Client() certs = [] for s in ("https://accounts.google.com", "https://www.googleapis.com"): url = URI.from_octets(s) certs.append(c.get_server_certificate_chain(url)) with open(cls.cert_file, "wb") as f: f.write(string.join(certs, "")) sys.exit(0)
def get_MailBoxUsage(userid,password, begin, end): """ Get Office365 MailBoxUsage """ from pyslet.http.auth import BasicCredentials from pyslet.rfc2396 import URI credentials = BasicCredentials() credentials.userid = userid credentials.password = password if credentials.userid == "": credentials.userid = o365_settings.o365defaultuserid if credentials.password == "": credentials.password = o365_settings.o365defaultpassword credentials.protectionSpace = URI.from_octets("https://reports.office365.com/ecp/reportingwebservice/reporting.svc").get_canonical_root() # DEBUG # str(credentials) import pyslet.http.client as http c = http.Client() c.add_credentials(credentials) r = http.ClientRequest('https://reports.office365.com/ecp/reportingwebservice/reporting.svc/MailboxUsage') c.process_request(r) # DEBUG # r.response.status # print r.response.get_content_type() # #>>> application/atom+xml; charset=utf-8; type=feed # print r.response.entity_body.getvalue() import xml.etree.ElementTree as ET root = ET.fromstring(r.response.entity_body.getvalue()) ns = {'d': 'http://schemas.microsoft.com/ado/2007/08/dataservices' , 'm': 'http://schemas.microsoft.com/ado/2007/08/dataservices/metadata' } ret = [] for entry in root.findall('.//m:properties',ns): date = entry.find('d:Date',ns).text TotalMailboxCount = entry.find('d:TotalMailboxCount',ns).text TotalInactiveMailboxCount = entry.find('d:TotalInactiveMailboxCount',ns).text # DEBUG # print date,TotalMailboxCount,TotalInactiveMailboxCount result = { 'Date': date , 'TotalMailboxCount' : TotalMailboxCount, 'TotalInactiveMailboxCount' : TotalInactiveMailboxCount } ret.append(result) c.close() return ret
def setup(cls, options=None, args=None, **kwargs): """Adds multi-tenant initialisation""" super(MultiTenantTPApp, cls).setup(options, args, **kwargs) mt_settings = cls.settings.setdefault('MultiTenantTPApp', {}) mt_settings.setdefault('google_client_id', '') mt_settings.setdefault('google_client_secret', '') cert_url = mt_settings.setdefault('google_certs', 'google_certs.pem') cls.cert_file = cls.resolve_setup_path(cert_url) if options and options.google_certs: # update the certs_file and exit c = http.Client() certs = [] for s in ('https://accounts.google.com', 'https://www.googleapis.com', ): url = URI.from_octets(s) certs.append(c.get_server_certificate_chain(url)) with open(cls.cert_file, 'wb') as f: f.write(string.join(certs, '')) sys.exit(0)
def new_attempt_action(self, context): if context.environ['REQUEST_METHOD'].upper() != 'POST': raise wsgi.MethodNotAllowed pid = context.get_form_long('pid') aid = context.get_form_long('aid') with self.container['Attempts'].OpenCollection() as attempts: a = attempts.new_entity() a['ID'].set_from_value(0) a['ExternalAttemptID'].set_from_value( "Heathrow/%s" % str(iso.TimePoint.from_now())) a['ParticipantID'].set_from_value(pid) a['AssessmentID'].set_from_value(aid) a['LockRequired'].set_from_value(True) a['LockStatus'].set_from_value(True) a['ParticipantFacingProctorSystemWidgetUrl'].set_from_value("http://labs.adobe.com/technologies/cirrus/samples/") a['LastModifiedDateTime'].set_from_value(iso.TimePoint.from_now()) attempts.insert_entity(a) return self.redirect_page( context, URI.from_octets('ops').resolve( context.get_app_root()), 303)
def main(user, password, product_list): metadata = URI.from_path('metadata.xml') credentials = BasicCredentials() credentials.userid = user credentials.password = password credentials.protectionSpace = URI.from_octets(SERVICE).get_canonical_root() # the full link of odata is https://scihub.esa.int/dhus/odata/v1 # this is for the authentication c = Client(ca_certs=CERTIFICATE) c.add_credentials(credentials) c.LoadService(SERVICE, metadata=metadata) with c.feeds['Products'].OpenCollection() as products: for pid in product_list: p = products[pid] name = p['Name'].value size = p['ContentLength'].value print name, size with open('%s.zip' % name, 'wb') as f: products.read_stream(p.key(), f)
def consumer_del_action(self, context): if context.environ['REQUEST_METHOD'].upper() != 'POST': raise wsgi.MethodNotAllowed owner = context.session.get_owner() if owner is None: # we require an owner to be logged in raise wsgi.PageNotAuthorized silo = owner['Silo'].GetEntity() try: cid = context.get_form_long('cid') with silo['Consumers'].OpenCollection() as collection: consumer = collection[cid] # now to delete we must delete from the parent collection consumer.Delete() except ValueError: raise wsgi.BadRequest except KeyError: raise wsgi.PageNotAuthorized link = URI.from_octets("./").resolve(context.get_url()) return self.redirect_page(context, link, 303)
def consumer_del_action(self, context): if context.environ["REQUEST_METHOD"].upper() != "POST": raise wsgi.MethodNotAllowed owner = self.get_owner(context) if owner is None: # we require an owner to be logged in raise wsgi.PageNotAuthorized silo = owner["Silo"].get_entity() try: cid = context.get_form_long("cid") with silo["Consumers"].open() as collection: consumer = collection[cid] # now to delete we must delete from the parent collection consumer.delete() except ValueError: raise wsgi.BadRequest except KeyError: raise wsgi.PageNotAuthorized link = URI.from_octets("./").resolve(context.get_url()) return self.redirect_page(context, link, 303)
def consumer_edit_action(self, context): if context.environ['REQUEST_METHOD'].upper() != 'POST': raise wsgi.MethodNotAllowed owner = context.session.get_owner() if owner is None: # we require an owner to be logged in raise wsgi.PageNotAuthorized silo = owner['Silo'].GetEntity() try: cid = context.get_form_long('cid') key = context.get_form_string('key', 80) secret = context.get_form_string('secret', 80) with silo['Consumers'].OpenCollection() as collection: consumer = lti.ToolConsumer(collection[cid], self.app_cipher) # we never change the handle consumer.update_from_values(key, secret) except ValueError: raise wsgi.BadRequest except KeyError: raise wsgi.PageNotAuthorized link = URI.from_octets("./").resolve(context.get_url()) return self.redirect_page(context, link, 303)
def snapshot(self, context): qparams = context.get_query() aid = long(qparams['aid']) with self.container['Assessments'].OpenCollection() as assessments: assessment = assessments[aid] with self.container['AssessmentSnapshots'].OpenCollection() as snapshots: s = snapshots.new_entity() s['ID'].set_from_value(0) s['AssessmentID'].set_from_value(aid) s['Name'].set_from_value( "DemoSnap/%s" % str(iso.TimePoint.from_now())) # <Property Name="PrintableDocumentSourceUrl" Type="Edm.String"/> # <Property Name="Language" Type="Edm.String"/> # <Property Name="CreatedDateTime" Type="Edm.DateTime" Nullable="false"/> # <Property Name="ModifiedDateTime" Type="Edm.DateTime" Nullable="false"/> # <Property Name="ExpiresDateTime" Type="Edm.DateTime"/> s['CreatedDateTime'].set_from_value(iso.TimePoint.from_now()) s['ModifiedDateTime'].set_from_value(iso.TimePoint.from_now()) snapshots.insert_entity(s) return self.redirect_page( context, URI.from_octets('pas').resolve( context.get_app_root()), 303)
def consumer_edit_action(self, context): if context.environ["REQUEST_METHOD"].upper() != "POST": raise wsgi.MethodNotAllowed owner = self.get_owner(context) if owner is None: # we require an owner to be logged in raise wsgi.PageNotAuthorized silo = owner["Silo"].get_entity() try: cid = context.get_form_long("cid") key = context.get_form_string("key", 80) secret = context.get_form_string("secret", 80) with silo["Consumers"].open() as collection: consumer = lti.ToolConsumer(collection[cid], self.app_cipher) # we never change the handle consumer.update_from_values(key, secret) except ValueError: raise wsgi.BadRequest except KeyError: raise wsgi.PageNotAuthorized link = URI.from_octets("./").resolve(context.get_url()) return self.redirect_page(context, link, 303)
def launch(self, context): qparams = context.get_query() aid = long(qparams['aid']) with self.container['Attempts'].OpenCollection() as attempts: attempt = attempts[aid] link = attempt['ParticipantFacingQMLobbyUrl'].value.split() rlink = string.join(link, '%20') if len(link) > 1: logging.error("URL contained unencoded space: %s" % repr(attempt['ParticipantFacingQMLobbyUrl'].value)) # if rlink.startswith('qmsb'): # # special handling of this redirect # page_context = self.new_page_context(context) # page_context['link_attr'] = xml.EscapeCharData7(str(rlink), True) # data = self.render_template(context, 'qmsb.html', page_context) # context.set_status(200) # return self.html_response(context, data) # else: return self.redirect_page( context, URI.from_octets(rlink), 303)
def test_unframed_cookies(self): req = MockRequest() req.call_app(self.app) # follow the redirect, tested in the framed test target = URI.from_octets(req.headers['location'][0]) # ...but ignore the cookies req = MockRequest(path=target.abs_path, query=target.query) req.call_app(self.app) # this should display the frame detection page, no cookies self.assertTrue(req.status.startswith('200 ')) self.assertFalse('location' in req.headers) self.assertTrue(len(req.cookies) == 0) # can we check the content? doc = html.XHTMLDocument() req.output.seek(0) doc.Read(req.output) # there should be a form called 'wlaunch' form = doc.GetElementByID('wlaunch') self.assertTrue(isinstance(form, html.Form)) self.assertTrue(form.action is not None) target = form.action self.assertTrue(target.get_addr() == ('localhost', 80)) self.assertTrue(isinstance(target, params.HTTPURL)) # get the input fields query = {} for input in form.FindChildrenDepthFirst(html.Input): if input.name in ("return", "sid", "submit"): query[input.name] = str(input.value) query = urllib.urlencode(query) # autosubmit the form, no cookies to send req = MockRequest(path=target.abs_path, query=query) req.call_app(self.app) # should now get a very similar response to our first ever call, # redirect to the test page with cookies and complete as per the # first scenario self.assertTrue(req.status.startswith('303 ')) self.assertTrue('location' in req.headers) target = req.headers['location'] self.assertTrue(len(target) == 1) target = URI.from_octets(target[0]) self.assertTrue(target.get_addr() == ('localhost', 80)) self.assertTrue(isinstance(target, params.HTTPURL)) # and we expect a warning cookie self.assertTrue(noticeboard.COOKIE_WARNING in req.cookies) # and we expect a session cookie self.assertTrue(noticeboard.COOKIE_SESSION in req.cookies) cflag = req.cookies[noticeboard.COOKIE_WARNING] sid = req.cookies[noticeboard.COOKIE_SESSION] # follow the redirect, passing the cookies req = MockRequest(path=target.abs_path, query=target.query) req.add_cookies([cflag, sid]) req.call_app(self.app) # we expect a redirect back to our original path self.assertTrue(req.status.startswith('303 '), req.status) self.assertTrue('location' in req.headers) target = req.headers['location'] self.assertTrue(len(target) == 1) target = URI.from_octets(target[0]) self.assertTrue(target.get_addr() == ('localhost', 80)) self.assertTrue(isinstance(target, params.HTTPURL)) self.assertTrue(target.abs_path == '/') # and an updated sid! self.assertTrue(noticeboard.COOKIE_SESSION in req.cookies) new_sid = req.cookies[noticeboard.COOKIE_SESSION] self.assertFalse(sid.value == new_sid.value) sid = new_sid # now we repeat the first request with the cookies, # should not get a redirect anymore req = MockRequest() req.add_cookies([cflag, sid]) req.call_app(self.app) self.assertTrue(req.status.startswith('200 ')) self.assertFalse('location' in req.headers) # now we have an established session, what happens if we launch # again in a third-party blocked cookie situation? req = MockRequest() req.call_app(self.app) # follow the redirect, tested in the framed test target = URI.from_octets(req.headers['location'][0]) # ...but ignore the cookies again! req = MockRequest(path=target.abs_path, query=target.query) req.call_app(self.app) # this should display the frame detection page, no cookies self.assertTrue(req.status.startswith('200 ')) doc = html.XHTMLDocument() req.output.seek(0) doc.Read(req.output) form = doc.GetElementByID('wlaunch') target = form.action query = {} for input in form.FindChildrenDepthFirst(html.Input): if input.name in ("return", "sid", "submit"): query[input.name] = str(input.value) query = urllib.urlencode(query) # autosubmit the form, but we're in a new window now so we can # send the cookies from the established session req = MockRequest(path=target.abs_path, query=query) req.add_cookies([cflag, sid]) req.call_app(self.app) # this should redirect straight to the original home self.assertTrue(req.status.startswith('303 '), req.status) self.assertTrue('location' in req.headers) target = req.headers['location'] self.assertTrue(len(target) == 1) target = URI.from_octets(target[0]) self.assertTrue(target.get_addr() == ('localhost', 80)) self.assertTrue(isinstance(target, params.HTTPURL)) self.assertTrue(target.abs_path == '/') # our session should be merged in, so we have the existing sid # and therefore no cookie need be set self.assertFalse(noticeboard.COOKIE_SESSION in req.cookies) # now we repeat the first request with the cookies again, should # not get a redirect anymore req = MockRequest() req.add_cookies([cflag, sid]) req.call_app(self.app) self.assertTrue(req.status.startswith('200 ')) self.assertFalse('location' in req.headers)
def get_cert(): c = Client() url = URI.from_octets(SERVICE) output = c.get_server_certificate_chain(url) with open(CERTIFICATE, 'wb') as f: f.write(output)