Beispiel #1
0
    def test_instructor_can_respond_with_faq(self):

        qkey = self.q00_key

        respond = ResponseHandler()
        session = {
            'account': self.instructor.username,
            'accounttypr': ADMIN,
            'class': self.classy.classname,
            'question_key': qkey.urlsafe(),
        }
        secure_cookie_serializer = SecureCookieSerializer(SECRET_KEY)
        serialized = secure_cookie_serializer.serialize('session', session)
        headers = {'Cookie': 'session=%s' % serialized}
        respond.request = Request.blank('/respond?response=test&infaq=infaq')
        respond.request.method = 'POST'
        respond.request.headers = headers

        self.assertTrue(respond.request.get('response') == 'test')
        self.assertTrue(respond.request.get('infaq') == 'infaq')

        response = respond.request.get_response(main.app)

        time.sleep(2)

        question = qkey.get()
        self.assertTrue(question.response == R_INFAQ)
Beispiel #2
0
    def test_instructor_can_respond(self):

        qkey = self.q00_key
        respond = ResponseHandler()
        session = {
            'account': self.instructor.username,
            'accounttypr': ADMIN,
            'class': self.classy.classname,
            'question_key': qkey.urlsafe(),
        }
        secure_cookie_serializer = SecureCookieSerializer(SECRET_KEY)
        serialized = secure_cookie_serializer.serialize('session', session)
        headers = {'Cookie': 'session=%s' % serialized}

        respond.request = Request.blank('/respond?response=test')
        respond.request.method = 'POST'
        #respond.request.body = 'response=test'
        respond.request.headers = headers
        #print '\n'+respond.request.get('message')+'\n'

        self.assertTrue(respond.request.get('response') == 'test')

        response = respond.request.get_response(main.app)
        #message = response.get('message')
        question = qkey.get()
        self.assertFalse(question == None)
        self.assertFalse(question.respondentUID == None)
        self.assertFalse(question.response == None)
        self.assertFalse(question.response == '')
        self.assertTrue(question.respondentUID == self.instructor.key)
        self.assertTrue(question.response == 'test')
Beispiel #3
0
    def test_instructor_can_set_category_to_answer(self):

        qkey = self.q00_key

        respond = ResponseHandler()
        session = {
            'account': self.instructor.username,
            'accounttypr': ADMIN,
            'class': self.classy.classname,
            'question_key': qkey.urlsafe(),
        }
        secure_cookie_serializer = SecureCookieSerializer(SECRET_KEY)
        serialized = secure_cookie_serializer.serialize('session', session)
        headers = {'Cookie': 'session=%s' % serialized}
        respond.request = Request.blank(
            '/respond?response=test&cname=test_category')
        respond.request.method = 'POST'
        respond.request.headers = headers

        #ensure that the vars were passed to test properly
        self.assertTrue(respond.request.get('response') == 'test')
        self.assertTrue(respond.request.get('cname') == 'test_category')

        response = respond.request.get_response(main.app)

        time.sleep(2)
        question = qkey.get()
        cate = Category.query(Category.name == 'test_category').fetch()
        self.assertTrue(
            len(cate) ==
            1)  #was created/found and is unique, also has the correct name
        cate = cate[0]
        self.assertTrue(question.category == cate.key)
        question.key.delete()
        cate.key.delete()
	def test_instructor_can_create_new_category(self):
		
		qkey = self.q00_key
		respond = ResponseHandler()
		session = {
			'account': self.instructor.username,
			'accounttype': ADMIN,
			'class': self.classy.classname,
			'question_key': qkey.urlsafe(),
		}
		secure_cookie_serializer = SecureCookieSerializer(SECRET_KEY)
		serialized = secure_cookie_serializer.serialize('session', session)
		headers = {'Cookie':'session=%s' % serialized}
		respond.request = Request.blank('/respond?add_to_category=1&response=test&cname=Default&new_cname=test_category')
		respond.request.method='POST'
		respond.request.headers=headers
		
		#ensure that the vars were passed to test properly
		self.assertTrue(respond.request.get('response') == 'test')
		self.assertTrue(respond.request.get('new_cname') == 'test_category')
		
		temp = Category.query(Category.name=='test_category').fetch()
		for c in temp:
			c.key.delete()
		del temp
		
		response = respond.request.get_response(main.app)
		
		time.sleep(2)
		category = Category.query(Category.name == 'test_category').fetch()
		
		self.assertTrue(len(category)==1) #was created and is unique, also has the correct name
		category = category[0]
		self.assertTrue(category.key.parent() == self.classy.key)
		category.key.delete()
Beispiel #5
0
    def setUp(self):
        self.testbed = testbed.Testbed()
        self.testbed.activate()
        self.testbed.init_datastore_v3_stub()
        self.testbed.init_memcache_stub()

        # create a cookie serializer to emulate our sessions
        self.secure_cookie_serializer = SecureCookieSerializer(
            'no-one-will-guess-kwsfs-secret-key')
        sessionConfig = {}
        sessionConfig['webapp2_extras.sessions'] = {
            'secret_key': 'no-one-will-guess-kwsfs-secret-key',
        }
        # redirect Jinja Env to a directory up
        Base.JINJA_ENVIRONMENT = jinja2.Environment(
            loader=jinja2.FileSystemLoader('../html'),
            extensions=['jinja2.ext.autoescape'],
            autoescape=True)

        # prepare env with only needed URLs
        app = webapp2.WSGIApplication(
            [('/', Login.LoginHandler),
             ('/manage.html', Management.ManagementHandler)],
            debug=True,
            config=sessionConfig)

        self.testapp = webtest.TestApp(app)
Beispiel #6
0
def login_headers(user_id):
    """Simulate a logged-in session cookie to be included in requests.

    http://www.recursion.org/2011/10/12/testing-webapp2-sessions-with-webtest
    """
    session = {'user': user_id}
    scs = SecureCookieSerializer(config.default_session_cookie_secret_key)
    cookie_value = scs.serialize(config.session_cookie_name, session)
    headers = {
        'Cookie': '{}={}'.format(config.session_cookie_name, cookie_value)
    }
    return headers
Beispiel #7
0
    def get(self, path, data=None, session={}):

        secure_cookie_serializer = SecureCookieSerializer(SPLUNK_PROJECT_ID)
        serialized_session = secure_cookie_serializer.serialize(
            'session', session)
        headers = {'Cookie': 'session=%s' % serialized_session}
        if data:
            return self.app.post_json(path,
                                      data,
                                      headers=headers,
                                      expect_errors=True)
        return self.app.get(path, headers=headers)
Beispiel #8
0
    def login(self, user=None, app_name="dashboard"):
        """Return a header containing the auth cookie.

        """
        user = user if user else self.new_user()
        session_name = "session_%s" % app_name
        session = {'user_id': user.key.id(), 'user_domain': 'example.com'}
        secure_cookie_serializer = SecureCookieSerializer(self.secret)
        serialized = secure_cookie_serializer.serialize(session_name, session)
        return {
            'X-App-Name': app_name,
            'Cookie': '%s=%s' % (
                session_name,
                serialized,
            )
        }
Beispiel #9
0
    def setUp(self):
        self.testbed = testbed.Testbed()
        self.testbed.activate()
        self.testbed.init_datastore_v3_stub()
        self.testbed.init_memcache_stub()

        # create a cookie serializer to emulate our sessions
        self.secure_cookie_serializer = SecureCookieSerializer('no-one-will-guess-kwsfs-secret-key')
        sessionConfig = {}
        sessionConfig['webapp2_extras.sessions'] = {
            'secret_key': 'no-one-will-guess-kwsfs-secret-key',
        }
        # redirect Jinja Env to a directory up
        Base.JINJA_ENVIRONMENT = jinja2.Environment(
            loader=jinja2.FileSystemLoader('../html'),
            extensions=['jinja2.ext.autoescape'],
            autoescape=True)

        # prepare env with only needed URLs
        app = webapp2.WSGIApplication([
            ('/syllabusStepCalendar.html', Calendar.CalendarHandler),
            ('/deleteCalendarEntry', Calendar.DeleteCalendarEntryHandler),
            ('/updateCalendarEntries', Calendar.UpdateCalendarEntriesHandler)
        ], debug=True, config=sessionConfig)

        self.testapp = webtest.TestApp(app)

        # TODO: replace this with a parser mock once the parser is integrated
        # This is used to verify functionality in tests that are not testing entry's results
        # Entry is tested separately, and these responses allows further test isolation
        self.start_date = date(2015, 8, 1)
        self.end_date = date(2016, 2, 1)
        self.days_of_week = [0, 2, 4]
        self.entry_response = Calendar.generateEntryRange(self.start_date, self.end_date, self.days_of_week)

        # create a test user
        newUser = DBM.User(parent=DBM.UserKey("rock"),
                           username="******", password="******")
        newUser.put()

        # create a test syllabus
        self.syllabusKey = DBM.SyllabusKey("MyTestSyllabus")
        self.syllabusName = "MyTestSyllabus"
        newSyllabus = DBM.Syllabus(parent=self.syllabusKey, name=self.syllabusName,
                                   active=False)
        newSyllabus.put()
Beispiel #10
0
    def setUp(self):
        self.testbed = testbed.Testbed()
        self.testbed.activate()
        self.testbed.init_datastore_v3_stub()
        self.testbed.init_memcache_stub()

        # create a cookie serializer to emulate our sessions
        self.secure_cookie_serializer = SecureCookieSerializer('no-one-will-guess-kwsfs-secret-key')
        sessionConfig = {}
        sessionConfig['webapp2_extras.sessions'] = {
            'secret_key': 'no-one-will-guess-kwsfs-secret-key',
        }
        # redirect Jinja Env to a directory up
        Base.JINJA_ENVIRONMENT = jinja2.Environment(
            loader=jinja2.FileSystemLoader('../html'),
            extensions=['jinja2.ext.autoescape'],
            autoescape=True)

        # prepare env with only needed URLs
        app = webapp2.WSGIApplication([
            ('/delinkPolicy', CoursePolicy.DelinkPolicyHandler),
            ('/deletePolicy', CoursePolicy.DeletePolicyHandler),
            ('/editPolicy', CoursePolicy.EditPolicyHandler),
            ('/linkPolicy', CoursePolicy.LinkPolicyHandler),
            ('/syllabusStepPoliciesEditor.html', CoursePolicy.CoursePolicyEditHandler),
            ('/policyLib.html', CoursePolicy.PolicyLibHandler)
        ], debug=True, config=sessionConfig)

        self.testapp = webtest.TestApp(app)

        # create a test user
        newUser = DBM.User(parent=DBM.UserKey("rock"),
                           username="******", password="******")
        newUser.put()

        # create a test syllabus
        self.syllabusKey = DBM.SyllabusKey("MyTestSyllabus")
        self.syllabusName = "MyTestSyllabus"
        newSyllabus = DBM.Syllabus(parent=self.syllabusKey, name=self.syllabusName,
                                   active=False)
        newSyllabus.put()
Beispiel #11
0
  def post(self, **kwargs):
    self.request.charset = 'utf-8'
    # Todo esto es para recuperar la session en funcion de un parametro del post 
    # que nos manda el flash swfupload
    cookie_name  = self.app.config['webapp2_extras.sessions']['cookie_name']
    secret_key   = self.app.config['webapp2_extras.sessions']['secret_key']
    raw_data     = str(self.request.POST[cookie_name])
    
    if raw_data[0] == "\"" and raw_data[-1] == "\"":
      raw_data = raw_data[1:][:-1]
    
    # ALTO HACK: no se por que carajo no funcion el urllib.unquote
    raw_data     = raw_data.decode('string_escape')
    self.session = SecureCookieSerializer(secret_key).deserialize(cookie_name, raw_data)
    
    # Hacemos lo que hacia el decorator
    if not self.is_logged:
      self.abort(500)
    
    property = self.mine_or_404(kwargs['key'])
  
    fs = self.request.POST['file']
    # Create the file
    file_name = files.blobstore.create(mime_type='image/jpg', _blobinfo_uploaded_filename=fs.filename)

    # Open the file and write to it
    img = images.Image(fs.file.getvalue())
    img.resize(width=800, height=600)

    with files.open(file_name, 'a') as f:
      f.write(img.execute_transforms(output_encoding=images.JPEG, quality=70))

    # Finalize the file. Do this before attempting to read it.
    files.finalize(file_name)

    # Get the file's blob key
    blob_key = files.blobstore.get_blob_key(file_name)

    # ------ BEGIN HACK -------- #
    # GAE BUG => http://code.google.com/p/googleappengine/issues/detail?id=5142
    for i in range(1,10):
      if not blob_key:
        time.sleep(0.05)
        blob_key = files.blobstore.get_blob_key(file_name)
      else:
        break
    
    if not blob_key:
      logging.error("no pude obtener el blob_key, hay un leak en el blobstore!")
      abort(500)
    # ------ END HACK -------- #
      
    imgfile = ImageFile()
    imgfile.title     = get_serving_url(blob_key)
    imgfile.file      = blob_key
    imgfile.filename  = fs.filename
    imgfile.realestate= property.realestate.key()
    imgfile.property  = db.Key(encoded=kwargs['key'])
    imgfile.put()
    
    #Update property
    if property.images_count:
      property.images_count = property.images_count + 1
    else:
      property.images_count = 1
      property.main_image_url   = imgfile.title
    
    result = property.save(build_index=False)
    # HACK: No mandamos a regenerar el PropertyIndex
    #if result != 'nones':
    #  taskqueue.add(url=self.url_for('property/update_index'), params={'key': str(property.key()),'action':result})
    
    return self.render_response('backend/includes/img_box.html', image=imgfile)
Beispiel #12
0
 def __init__(self):
     self.user_cookie = 'uc'
     self.secure_cookie_serializer = SecureCookieSerializer(SECRET_KEY)
Beispiel #13
0
 def __init__(self, secret_key=None):
     if secret_key:
         self.cookie = SecureCookieSerializer(secret_key)
     else:
         self.cookie = SecureCookieSerializer(SECRET_KEY)
Beispiel #14
0
import unittest
import webapp2
from webtest import TestApp
from config import config
from routes import routes
from webapp2_extras.securecookie import SecureCookieSerializer

app = webapp2.WSGIApplication(routes, config=config)
secure_cookie_serializer = SecureCookieSerializer(
    config['webapp2_extras.sessions']['secret_key'])


class Helper():
    """
    A helper to let TestCase make requests with pre-defined headers and csrf
    """
    def get(self, *args, **kwargs):
        if 'headers' not in kwargs:
            kwargs['headers'] = self.headers
        return self.app.get(*args, **kwargs)

    def post(self, url, params, *args, **kwargs):
        if 'headers' not in kwargs:
            kwargs['headers'] = self.headers
        if 'csrf' in kwargs and kwargs['csrf'] == True and self.csrf_data:
            if params and isinstance(
                    params, dict) and self.csrf_token_name not in params:
                params.update(**self.csrf_data)
            elif 'params' in kwargs and self.csrf_token_name not in params[
                    'kwargs']:
                kwargs['params'].update(**self.csrf_data)
Beispiel #15
0
def gen_user_cookie():
    session = {'user': {'id': '123', 'googleId': '1'}}
    secure_cookie_serializer = SecureCookieSerializer('abcdefg')
    serialized = secure_cookie_serializer.serialize('session', session)
    return {'Cookie': 'session=%s' % serialized}