示例#1
0
文件: seed_db.py 项目: ajaksu/Melange
 def seed(self, i, entities=None):
   user_properties = {
       'key_name': 'user_%04d' % i,
       'link_id': 'user_%04d' % i,
       'account': users.User(email='*****@*****.**' % i),
       'name': 'User %04d' % i,
       }
   entity = User(**user_properties)
   if entities is None:
     entity.put()
   else:
     entities.append(entity)
示例#2
0
 def seed(self, i, entities=None):
     user_properties = {
         'key_name': 'user_%04d' % i,
         'link_id': 'user_%04d' % i,
         'account': users.User(email='*****@*****.**' % i),
         'name': 'User %04d' % i,
     }
     entity = User(**user_properties)
     if entities is None:
         entity.put()
         user_logic._onCreate(entity)
     else:
         entities.append(entity)
示例#3
0
    def clean_email(self):
        email_cleaner = cleaning.clean_email('email')

        try:
            email_address = email_cleaner(self)
        except djangoforms.ValidationError as e:
            if e.code != 'invalid':
                raise
            msg = ugettext(u'Enter a valid email address.')
            raise djangoforms.ValidationError(msg, code='invalid')

        account = users.User(email_address)
        user_account = accounts.normalizeAccount(account)
        user = User.all().filter('account', user_account).get()

        if not user:
            raise djangoforms.ValidationError(
                "There is no user with that email address")

        self.cleaned_data['user'] = user

        q = GCIProfile.all()
        q.filter('program', self.request_data.program)
        q.ancestor(user)
        self.cleaned_data['profile'] = q.get()
示例#4
0
def _getAllUsers():
    """Returns a list of all valid users.
  """

    from soc.models.user import User

    gen = lambda: User.all().filter('status =', 'valid')
    return interactive.deepFetch(gen)
示例#5
0
def _getAllUsers():
  """Returns a list of all valid users.
  """

  from soc.models.user import User

  gen = lambda: User.all().filter('status =', 'valid')
  return interactive.deepFetch(gen)
示例#6
0
class InviteForm(forms.ModelForm):
  """Django form for the invite page.
  """

  link_id = djangoforms.CharField(label='Link ID/Email')

  class Meta:
    model = Request
    css_prefix = 'gsoc_intivation'
    fields = ['message']

  def __init__(self, request_data, *args, **kwargs):
    super(InviteForm, self).__init__(*args, **kwargs)

    # store request object to cache results of queries
    self.request_data = request_data

    # reorder the fields so that link_id is the first one
    field = self.fields.pop('link_id')
    self.fields.insert(0, 'link_id', field)
    field.help_text = "The link_id or email address of the invitee"
    
  def clean_link_id(self):
    """Accepts link_id of users which may be invited.
    """

    assert isSet(self.request_data.organization)

    invited_user = None

    link_id_cleaner = cleaning.clean_link_id('link_id')

    try:
      link_id = link_id_cleaner(self)
    except djangoforms.ValidationError, e:
      if e.code != 'invalid':
        raise

      email_cleaner = cleaning.clean_email('link_id')

      try:
        email_address = email_cleaner(self)
      except djangoforms.ValidationError, e:
        if e.code != 'invalid':
          raise
        msg = ugettext(u'Enter a valid link_id or email address.')
        raise djangoforms.ValidationError(msg, code='invalid')

      account = users.User(email_address)
      user_account = accounts.normalizeAccount(account)
      invited_user = User.all().filter('account', user_account).get()

      if not invited_user:
        raise djangoforms.ValidationError(
            "There is no user with that email address")
示例#7
0
def ensureUser():
  """Returns the current user account and associated user object.
  """

  account = accounts.getCurrentAccount()

  if not account:
    account = users.User(email='*****@*****.**')

  user_properties = {
      'key_name': 'test',
      'link_id': 'test',
      'account': account,
      'name': 'Test',
      }

  current_user = User(**user_properties)
  current_user.put()

  return account, current_user
示例#8
0
def ensureUser():
    """Returns the current user account and associated user object.
  """

    account = accounts.getCurrentAccount()

    if not account:
        account = users.User(email='*****@*****.**')

    user_properties = {
        'key_name': 'test',
        'link_id': 'test',
        'account': account,
        'name': 'Test',
    }

    current_user = User(**user_properties)
    current_user.put()

    return account, current_user
示例#9
0
  def wrapped(self):
    """Decorator wrapper method.
    """
    link_id = clean_link_id(field_name)(self)

    user_entity = User.get_by_key_name(link_id)

    if not user_entity:
      # user does not exist
      raise forms.ValidationError("This user does not exist.")

    return user_entity
示例#10
0
  def wrapped(self):
    """Decorator wrapper method.
    """
    link_id = clean_link_id(field_name)(self)

    user_entity = User.get_by_key_name(link_id)

    if user_entity:
      # user exists already
      raise forms.ValidationError("There is already a user with this link id.")

    return link_id
示例#11
0
def seed_survey_answer(request, i):
    """Returns the properties of a student's survey answers.
  """

    ensureUser()
    survey = Survey.get_by_key_name('program/google/gsoc2009/survey_%d' % i)
    user = User.get_by_key_name('user_%d' % i)
    #student = GSoCStudent.get_by_key_name('google/gsoc2009/student_%d' % i)

    if not user:
        raise Error('Run seed_many for at least %d users first.' % i)

    if not survey:
        raise Error('Run seed_many for at least %d surveys first.' % i)

    all_properties = []
    scope_path = 'google/gsoc2009/'
    checkbox = 'PickMultipleQ Checkbox 2 for survey_%d' % i
    # pylint: disable=E1103
    for i in range(5):
        #student = GSoCStudent.get_by_key_name('google/gsoc2009/student_%d' % i)
        user = User.get_by_key_name('user_%d' % i)

        properties = {
            'scope_path': scope_path,
            'user': user,
            'project': None,
            '_survey': survey,
            '_fields': {
                'ShortQ': 'Test',
                'SelectionQ': u'SelectionQ Option 2',
                'LongQ': 'Long answer... \n' * 10,
                'PickMultipleQ': checkbox,
            }
        }

        all_properties.append(properties)

    return all_properties
示例#12
0
def clear(*args, **kwargs):
    """Removes all entities from the datastore.
  """

    # there no explicit ranker model anywhere, so make one for
    # our own convenience to delete all rankers
    class ranker(db.Model):
        """ranker model used with ranklist module.
    """
        pass

    # TODO(dbentley): If there are more than 1000 instances of any model,
    # this method will not clear all instances.  Instead, it should continually
    # call .all(), delete all those, and loop until .all() is empty.
    entities = itertools.chain(*[
        Notification.all(),
        GSoCMentor.all(),
        GHOPMentor.all(),
        GSoCStudent.all(),
        GHOPStudent.all(),
        Survey.all(),
        SurveyContent.all(),
        SurveyRecord.all(),
        GSoCOrgAdmin.all(),
        GHOPOrgAdmin.all(),
        ranker.all(),
        RankerRoot.all(),
        StudentProposal.all(),
        GSoCOrganization.all(),
        GHOPOrganization.all(),
        OrgApplication.all(),
        GSoCTimeline.all(),
        GHOPTimeline.all(),
        GSoCProgram.all(),
        GHOPProgram.all(),
        Host.all(),
        Sponsor.all(),
        User.all(),
        Site.all(),
        Document.all(),
    ])

    try:
        for entity in entities:
            entity.delete()
    except db.Timeout:
        return http.HttpResponseRedirect('#')
    # pylint: disable-msg=E1101
    memcache.flush_all()

    return http.HttpResponse('Done')
示例#13
0
文件: user.py 项目: adviti/melange
def forUserId(user_id):
  """Retrieves the user entity for the specified user id.

  If there is no user logged in, or they have no valid associated User
  entity, None is returned.
  """

  if not user_id:
    raise base.InvalidArgumentError("Missing argument 'user_id'")

  q = User.all()
  q.filter('user_id', user_id)
  q.filter('status', 'valid')
  return q.get()
示例#14
0
def clear(*args, **kwargs):
  """Removes all entities from the datastore.
  """

  # there no explicit ranker model anywhere, so make one for
  # our own convenience to delete all rankers
  class ranker(db.Model):
    """ranker model used with ranklist module.
    """
    pass

  # TODO(dbentley): If there are more than 1000 instances of any model,
  # this method will not clear all instances.  Instead, it should continually
  # call .all(), delete all those, and loop until .all() is empty.
  entities = itertools.chain(*[
      Notification.all(),
      GSoCMentor.all(),
      GCIMentor.all(),
      GSoCStudent.all(),
      GCIStudent.all(),
      Survey.all(),
      SurveyContent.all(),
      SurveyRecord.all(),
      GSoCOrgAdmin.all(),
      GCIOrgAdmin.all(),
      ranker.all(),
      RankerRoot.all(),
      StudentProposal.all(),
      GSoCOrganization.all(),
      GCIOrganization.all(),
      GSoCTimeline.all(),
      GCITimeline.all(),
      GSoCProgram.all(),
      GCIProgram.all(),
      Host.all(),
      Sponsor.all(),
      User.all(),
      Site.all(),
      Document.all(),
      ])

  try:
    for entity in entities:
      entity.delete()
  except db.Timeout:
    return http.HttpResponseRedirect('#')
  # pylint: disable=E1101
  memcache.flush_all()

  return http.HttpResponse('Done')
示例#15
0
def seed_survey_answer(request, i):
  """Returns the properties of a student's survey answers.
  """

  ensureUser()
  survey = Survey.get_by_key_name('program/google/gsoc2009/survey_%d' % i)
  user = User.get_by_key_name('user_%d' % i)
  #student = GSoCStudent.get_by_key_name('google/gsoc2009/student_%d' % i)

  if not user:
    raise Error('Run seed_many for at least %d users first.' % i)

  if not survey:
    raise Error('Run seed_many for at least %d surveys first.' % i)

  all_properties = []
  scope_path = 'google/gsoc2009/'
  checkbox = 'PickMultipleQ Checkbox 2 for survey_%d' % i
  # pylint: disable=E1103
  for i in range(5):
    #student = GSoCStudent.get_by_key_name('google/gsoc2009/student_%d' % i)
    user = User.get_by_key_name('user_%d' % i)

    properties = {
        'scope_path': scope_path,
        'user': user,
        'project': None,
        '_survey': survey,
        '_fields': {'ShortQ':'Test', 'SelectionQ': u'SelectionQ Option 2',
                   'LongQ': 'Long answer... \n' * 10,
                   'PickMultipleQ': checkbox,
                   }
        }

    all_properties.append(properties)

  return all_properties
示例#16
0
  def wrapped(self):
    """Decorator wrapper method.
    """
    email_adress = self.cleaned_data.get(field_name).lower()

    # get the user account for this email and check if it's in use
    user_account = users.User(email_adress)

    user_entity = User.all().filter('account', user_account).get()

    if user_entity or user.isFormerAccount(user_account):
      raise forms.ValidationError("There is already a user "
          "with this email address.")

    return user_account
示例#17
0
 def convert(self, email, same_user_id=False):
   account = users.User(email=email)
   properties = {
       'account': account,
       'key_name': self.link_id,
       'link_id': self.link_id,
       'name': 'Test user',
       'status': 'valid',
   }
   user = seeder_logic.seed(User, properties)
   if same_user_id:
     user = User.get_by_key_name(self.link_id)
     user.user_id = user.account.user_id()
     user.put()
   return convert_user.convert_user_txn(user.key())
示例#18
0
 def setUp(self):
     """Set up required for the cleaning logic tests.
 """
     self.init()
     # Ensure that current user is created
     user_properties = {
         'account': users.get_current_user(),
         'link_id': 'current_user',
         'key_name': 'current_user',
         'name': 'Current User',
     }
     self.user = User(**user_properties)
     self.user.put()
     # Create another user
     another_user_properties = {
         'account': users.User(email="*****@*****.**"),
         'link_id': 'another_user',
         'key_name': 'another_user',
         'name': 'Another User',
     }
     self.another_user = User(**another_user_properties)
     self.another_user.put()
     # Create a dummy form object
     self.form = Form()
示例#19
0
 def setUp(self):
   """Set up required for the cleaning logic tests.
   """
   self.init()
   # Ensure that current user is created
   user_properties = {
       'account': users.get_current_user(),
       'link_id': 'current_user',
       'key_name': 'current_user',
       'name': 'Current User',
       }
   self.user = User(**user_properties)
   self.user.put()
   # Create another user
   another_user_properties = {
       'account': users.User(email="*****@*****.**"),
       'link_id': 'another_user',
       'key_name': 'another_user',
       'name': 'Another User',
       }
   self.another_user = User(**another_user_properties)
   self.another_user.put()
   # Create a dummy form object
   self.form = Form()
示例#20
0
def seed_student_proposal(request, i):
    """Returns the properties of a new student proposal.
  """

    ensureUser()
    org = GSoCOrganization.get_by_key_name('google/gsoc2009/org_%d' % i)
    mentor = GSoCMentor.get_by_key_name('google/gsoc2009/org_%d/mentor' % i)
    user = User.get_by_key_name('user_%d' % i)
    student = GSoCStudent.get_by_key_name('google/gsoc2009/student_%d' % i)

    if not user:
        raise Error('Run seed_many for at least %d users first.' % i)

    if not student:
        raise Error('Run seed_many for at least %d students first.' % i)

    if not org:
        raise Error('Run seed_many for at least %d orgs first.' % i)

    if not mentor:
        raise Error('Run seed_many for at least %d mentors first.' % i)

    all_properties = []

    # pylint: disable=E1103
    for i in range(random.randint(5, 20)):
        link_id = 'proposal_%s_%d' % (org.link_id, i)
        scope_path = 'google/gsoc2009/' + user.link_id

        properties = {
            'link_id': link_id,
            'scope_path': scope_path,
            'scope': student,
            'key_name': '%s/%s' % (scope_path, link_id),
            'title': 'The Awesome Proposal %s %d' % (user.link_id, i),
            'abstract':
            'This is an Awesome Proposal, look at its awesomeness!',
            'content': 'Sorry, too Awesome for you to read!',
            'additional_info': 'http://www.zipit.com',
            'mentor': mentor,
            'status': 'pending',
            'org': org,
            'program': org.scope,
        }

        all_properties.append(properties)

    return all_properties
示例#21
0
文件: user.py 项目: adviti/melange
def forAccount(account):
  """Retrieves the user entity for the specified account.

  If there is no user logged in, or they have no valid associated User
  entity, None is returned.
  """

  if not account:
    raise base.InvalidArgumentError("Missing argument 'account'")

  account = accounts.normalizeAccount(account)

  q = User.all()
  q.filter('account', account)
  q.filter('status', 'valid')
  return q.get()
示例#22
0
def seed_student_proposal(request, i):
  """Returns the properties of a new student proposal.
  """

  ensureUser()
  org = GSoCOrganization.get_by_key_name('google/gsoc2009/org_%d' % i)
  mentor = GSoCMentor.get_by_key_name('google/gsoc2009/org_%d/mentor' % i)
  user = User.get_by_key_name('user_%d' % i)
  student = GSoCStudent.get_by_key_name('google/gsoc2009/student_%d' % i)

  if not user:
    raise Error('Run seed_many for at least %d users first.' % i)

  if not student:
    raise Error('Run seed_many for at least %d students first.' % i)

  if not org:
    raise Error('Run seed_many for at least %d orgs first.' % i)

  if not mentor:
    raise Error('Run seed_many for at least %d mentors first.' % i)

  all_properties = []
  
  # pylint: disable=E1103
  for i in range(random.randint(5, 20)):
    link_id = 'proposal_%s_%d' % (org.link_id, i)
    scope_path = 'google/gsoc2009/' + user.link_id

    properties = {
        'link_id': link_id,
        'scope_path': scope_path,
        'scope': student,
        'key_name': '%s/%s' % (scope_path, link_id),
        'title': 'The Awesome Proposal %s %d' % (user.link_id, i),
        'abstract': 'This is an Awesome Proposal, look at its awesomeness!',
        'content': 'Sorry, too Awesome for you to read!',
        'additional_info': 'http://www.zipit.com',
        'mentor': mentor,
        'status': 'pending',
        'org': org,
        'program': org.scope,
        }

    all_properties.append(properties)

  return all_properties
示例#23
0
def convertUser(user_key):
    """Converts the specified user by creating a new user entity that inherits
  from the newly added NewUser model.

  Args:
    user_key: User key.
  """
    user = User.get(user_key)

    entity_id = user.key().name()
    account_id = user.user_id or 'unset'

    if user.status == 'valid':
        status = user_model.Status.ACTIVE
    elif user.status == 'invalid':
        status = user_model.Status.BANNED
    else:
        operation.counters.Increment('Bad status')
        logging.warning('Invalid status %s for user %s', user.status,
                        user.key().name())
        return

    host_for = []
    for sponsor_key in user.host_for:
        host_for.extend(
            map(
                ndb.Key.from_old_key,
                GSoCProgram.all(keys_only=True).filter(
                    'sponsor', sponsor_key).fetch(1000)))
        host_for.extend(
            map(
                ndb.Key.from_old_key,
                GCIProgram.all(keys_only=True).filter(
                    'sponsor', sponsor_key).fetch(1000)))

    account = user.account

    new_user = NewUser(id=entity_id,
                       account_id=account_id,
                       status=status,
                       host_for=host_for,
                       account=account)
    _createUserTxn(new_user)
示例#24
0
文件: seed_db.py 项目: adviti/melange
def clear(*args, **kwargs):
  """Removes all entities from the datastore.
  """

  # TODO(dbentley): If there are more than 1000 instances of any model,
  # this method will not clear all instances.  Instead, it should continually
  # call .all(), delete all those, and loop until .all() is empty.
  entities = itertools.chain(*[
      Notification.all(),
      GCIStudent.all(),
      Survey.all(),
      SurveyRecord.all(),
      StudentProposal.all(),
      GSoCOrganization.all(),
      GCIOrganization.all(),
      GSoCTimeline.all(),
      GCITimeline.all(),
      GSoCProgram.all(),
      GSoCProfile.all(),
      GCIProfile.all(),
      GSoCProposal.all(),
      GCIProgram.all(),
      GCIScore.all(),
      GSoCStudentInfo.all(),
      GCIStudentInfo.all(),
      GCITask.all(),
      Host.all(),
      Sponsor.all(),
      User.all(),
      Site.all(),
      Document.all(),
      ])

  try:
    for entity in entities:
      entity.delete()
  except db.Timeout:
    return http.HttpResponseRedirect('#')
  # pylint: disable=E1101
  memcache.flush_all()

  return http.HttpResponse('Done')
示例#25
0
def seed_student(request, i):
  """Returns the properties for a new student entity.
  """

  gsoc2009 = GSoCProgram.get_by_key_name('google/gsoc2009')
  user = User.get_by_key_name('user_%d' % i)

  if not gsoc2009:
    raise Error('Run seed_db first')

  if not user:
    raise Error('Run seed_many for at least %d users first.' % i)

  properties = {
      'key_name':'google/gsoc2009/student_%d' % i,
      'link_id': 'student_%d' % i,
      'scope_path': 'google/gsoc2009',
      'scope': gsoc2009,
      'user' : user,
      'given_name': 'Student %d' % i,
      'surname': 'Last Name',
      'name_on_documents': 'Test Example',
      'email': '*****@*****.**',
      'res_street': 'Some Street',
      'res_city': 'Some City',
      'res_state': 'Some State',
      'res_country': 'United States',
      'res_postalcode': '12345',
      'phone': '1-555-BANANA',
      'birth_date': db.DateProperty.now(),
      'agreed_to_tos': True,
      'school_name': 'School %d' % i,
      'school_country': 'United States',
      'major': 'Computer Science',
      'degree': 'Undergraduate',
      'expected_graduation': 2012,
      'program_knowledge': 'Knowledge %d' % i,
      'school': None,
      'can_we_contact_you': True,
  }

  return properties
示例#26
0
def seed_student(request, i):
    """Returns the properties for a new student entity.
  """

    gsoc2009 = GSoCProgram.get_by_key_name('google/gsoc2009')
    user = User.get_by_key_name('user_%d' % i)

    if not gsoc2009:
        raise Error('Run seed_db first')

    if not user:
        raise Error('Run seed_many for at least %d users first.' % i)

    properties = {
        'key_name': 'google/gsoc2009/student_%d' % i,
        'link_id': 'student_%d' % i,
        'scope_path': 'google/gsoc2009',
        'scope': gsoc2009,
        'user': user,
        'given_name': 'Student %d' % i,
        'surname': 'Last Name',
        'name_on_documents': 'Test Example',
        'email': '*****@*****.**',
        'res_street': 'Some Street',
        'res_city': 'Some City',
        'res_state': 'Some State',
        'res_country': 'United States',
        'res_postalcode': '12345',
        'phone': '1-555-BANANA',
        'birth_date': db.DateProperty.now(),
        'agreed_to_tos': True,
        'school_name': 'School %d' % i,
        'school_country': 'United States',
        'major': 'Computer Science',
        'degree': 'Undergraduate',
        'expected_graduation': 2012,
        'program_knowledge': 'Knowledge %d' % i,
        'school': None,
        'can_we_contact_you': True,
    }

    return properties
示例#27
0
  def profileFromKwargs(self, profile_model):
    """Retrieves a profile from kwargs.

    Args:
      profile_model: The datastore model class
    """
    key_name = self.data.kwargs['user']
    self.data.url_user = User.get_by_key_name(key_name)

    if not self.data.url_user:
      raise NotFound('Requested user does not exist')

    fields = ['sponsor', 'program', 'user']
    key_name = '/'.join(self.data.kwargs[i] for i in fields)

    self.data.url_profile = profile_model.get_by_key_name(
        key_name, parent=self.data.url_user)

    if not self.data.url_profile:
      raise NotFound('Requested user does not have a profile')
示例#28
0
def convertUser(user_key):
  """Converts the specified user by creating a new user entity that inherits
  from the newly added NewUser model.

  Args:
    user_key: User key.
  """
  user = User.get(user_key)

  entity_id = user.key().name()
  account_id = user.user_id or 'unset'

  if user.status == 'valid':
    status = user_model.Status.ACTIVE
  elif user.status == 'invalid':
    status = user_model.Status.BANNED
  else:
    operation.counters.Increment('Bad status')
    logging.warning(
        'Invalid status %s for user %s', user.status, user.key().name())
    return

  host_for = []
  for sponsor_key in user.host_for:
    host_for.extend(map(
        ndb.Key.from_old_key,
        GSoCProgram.all(keys_only=True)
            .filter('sponsor', sponsor_key).fetch(1000)))
    host_for.extend(map(
        ndb.Key.from_old_key,
        GCIProgram.all(keys_only=True)
            .filter('sponsor', sponsor_key).fetch(1000)))

  account = user.account

  new_user = NewUser(
      id=entity_id, account_id=account_id, status=status, host_for=host_for,
      account=account)
  _createUserTxn(new_user)
示例#29
0
    def checkAccess(self):
        self.data.proposer_user = User.get_by_key_name(
            self.data.kwargs['student'])

        fields = ['sponsor', 'program', 'student']
        key_name = '/'.join(self.data.kwargs[i] for i in fields)

        self.data.proposer_profile = GSoCProfile.get_by_key_name(
            key_name, parent=self.data.proposer_user)

        if not self.data.proposer_profile:
            raise NotFound('Requested user does not exist')

        self.data.proposal = GSoCProposal.get_by_id(
            int(self.data.kwargs['id']), parent=self.data.proposer_profile)

        if not self.data.proposal:
            raise NotFound('Requested proposal does not exist')

        self.data.proposal_org = self.data.proposal.org

        self.check.canAccessProposalEntity()
        self.mutator.commentVisible()
示例#30
0
  def checkAccess(self):
    self.data.proposer_user = User.get_by_key_name(self.data.kwargs['student'])

    fields = ['sponsor', 'program', 'student']
    key_name = '/'.join(self.data.kwargs[i] for i in fields)

    self.data.proposer_profile = GSoCProfile.get_by_key_name(
        key_name, parent=self.data.proposer_user)

    if not self.data.proposer_profile:
      raise NotFound('Requested user does not exist')

    self.data.proposal = GSoCProposal.get_by_id(
        int(self.data.kwargs['id']),
        parent=self.data.proposer_profile)

    if not self.data.proposal:
      raise NotFound('Requested proposal does not exist')

    self.data.proposal_org = self.data.proposal.org

    self.check.canAccessProposalEntity()
    self.mutator.commentVisible()
示例#31
0
    def clean_email(self):
        email_cleaner = cleaning.clean_email("email")

        try:
            email_address = email_cleaner(self)
        except djangoforms.ValidationError as e:
            if e.code != "invalid":
                raise
            msg = ugettext(u"Enter a valid email address.")
            raise djangoforms.ValidationError(msg, code="invalid")

        account = users.User(email_address)
        user_account = accounts.normalizeAccount(account)
        user = User.all().filter("account", user_account).get()

        if not user:
            raise djangoforms.ValidationError("There is no user with that email address")

        self.cleaned_data["user"] = user

        q = GCIProfile.all()
        q.filter("program", self.request_data.program)
        q.ancestor(user)
        self.cleaned_data["profile"] = q.get()
示例#32
0
文件: host.py 项目: adviti/melange
def getHostsForProgram(program_entity, limit=1000):
  """Returns all the host entities for the given program.

  Args:
    program_entity: The Program entity for which the hosts must be determined

  Returns:
    The list of host entities for the specified program entity
  """
  sponsor_key = Program.scope.get_value_for_datastore(
      program_entity)
  q = User.all()
  q.filter('host_for', sponsor_key)
  host_users = q.fetch(1000)

  # TODO(Madhu): to be simplified after host_for is moved from user entity
  # to host entity
  hosts = []
  for user in host_users:
    q = Host.all()
    q.ancestor(user)
    hosts.append(q.get())

  return hosts
示例#33
0
 def assertUserEqual(self, email):
   user = User.get_by_key_name(self.link_id)
   self.assertEqual(email, user.account.email())
   self.assertTrue(user.account.user_id())
   self.assertEqual(user.account.user_id(), user.user_id)
示例#34
0
文件: user.py 项目: adviti/melange
def isFormerAccount(account):
  """Returns true if account is a former account of some User.
  """
  return User.all().filter('former_accounts', account).count() > 0
示例#35
0
文件: seed_db.py 项目: adviti/melange
def seed(request, *args, **kwargs):
  """Seeds the datastore with some default values.
  """

  site_properties = {
      'key_name': 'site',
      'link_id': 'site',
      }

  site = Site(**site_properties)
  site.put()

  account = accounts.getCurrentAccount()

  if not account:
    account = users.User(email='*****@*****.**')

  user_properties = {
      'key_name': 'test',
      'link_id': 'test',
      'account': account,
      'name': 'Test',
      }

  current_user = User(**user_properties)
  current_user.put()

  group_properties = {
       'key_name': 'google',
       'link_id': 'google',
       'name': 'Google Inc.',
       'short_name': 'Google',
       'founder': current_user,
       'home_page': 'http://www.google.com',
       'email': '*****@*****.**',
       'description': 'This is the profile for Google.',
       'contact_street': 'Some Street',
       'contact_city': 'Some City',
       'contact_country': 'United States',
       'contact_postalcode': '12345',
       'phone': '1-555-BANANA',
       'status': 'active',
       }

  google = Sponsor(**group_properties)
  google.put()


  role_properties = {
      'key_name': 'google/test',
      'link_id': 'test',
      'public_name': 'test',
      'scope': google,
      'scope_path': 'google',
      'user': current_user,
      'given_name': 'Test',
      'surname': 'Example',
      'name_on_documents': 'Test Example',
      'email': '*****@*****.**',
      'res_street': 'Some Street',
      'res_city': 'Some City',
      'res_state': 'Some State',
      'res_country': 'United States',
      'res_postalcode': '12345',
      'phone': '1-555-BANANA',
      'birth_date': db.DateProperty.now(),
      'agreed_to_tos': True,
      'is_org_admin': True,
      'is_mentor': True,
      }


  current_user.host_for = [google.key()]
  current_user.put()

  google_host = Host(**role_properties)
  google_host.put()

  from datetime import datetime
  from datetime import timedelta

  now = datetime.now()
  before = now - timedelta(365)
  after = now + timedelta(365)

  timeline_properties = {
      'key_name': 'google/gsoc2009',
      'link_id': 'gsoc2009',
      'scope_path': 'google',
      'scope': google,
      'program_start': before,
      'program_end': after,
      'accepted_organization_announced_deadline': before,
      'student_signup_start': before,
      'student_signup_end': after,
  }

  gsoc2009_timeline = GSoCTimeline(**timeline_properties)
  gsoc2009_timeline.put()


  program_properties = {
      'key_name': 'google/gsoc2009',
      'link_id': 'gsoc2009',
      'scope_path': 'google',
      'scope': google,
      'name': 'Google Summer of Code 2009',
      'short_name': 'GSoC 2009',
      'group_label': 'GSOC',
      'description': 'This is the program for GSoC 2009.',
      'apps_tasks_limit': 42,
      'slots': 42,
      'timeline': gsoc2009_timeline,
      'status': 'visible',
      }

  gsoc2009 = GSoCProgram(**program_properties)
  gsoc2009.put()


  timeline_properties.update({
      'key_name': 'google/gsoc2010',
      'link_id': 'gsoc2010',
  })

  gsoc2010_timeline = GSoCTimeline(**timeline_properties)
  gsoc2010_timeline.put()

  program_properties.update({
      'key_name': 'google/gsoc2010',
      'link_id': 'gsoc2010',
      'name': 'Google Summer of Code 2010',
      'description': 'This is the program for GSoC 2010.',
      'short_name': 'GSoC 2010',
      'timeline': gsoc2010_timeline,
  })

  gsoc2010 = GSoCProgram(**program_properties)
  gsoc2010.put()

  timeline_properties = {
        'key_name': 'google/gci2009',
        'link_id': 'gci2009',
        'scope_path': 'google',
        'scope': google,
        'program_start': before,
        'program_end': after,
        'accepted_organization_announced_deadline': before,
        'student_signup_start': before,
        'student_signup_end': after,
        'tasks_publicly_visible': before,
        'task_claim_deadline': after,
        'stop_all_work_deadline': after,
  }

  gci2009_timeline = GCITimeline(**timeline_properties)
  gci2009_timeline.put()


  program_properties.update({
      'key_name': 'google/gci2009',
      'link_id': 'gci2009',
      'name': 'Google Code In Contest 2009',
      'short_name': 'GCI 2009',
      'group_label': 'GCI',
      'description': 'This is the program for GCI 2009.',
      'timeline': gci2009_timeline,
      })

  gci2009 = GCIProgram(**program_properties)
  gci2009.put()

  site.active_program = gci2009
  site.put()


  group_properties.update({
    'key_name': 'google/gci2009/melange',
    'link_id': 'melange',
    'name': 'Melange Development Team',
    'short_name': 'Melange',
    'scope_path': 'google/gci2009',
    'scope': gci2009,
    'home_page': 'http://code.google.com/p/soc',
    'description': 'Melange, share the love!',
    'license_name': 'Apache License',
    'ideas': 'http://code.google.com/p/soc/issues',
    })

  melange = GCIOrganization(**group_properties)
  melange.put()

  group_properties.update({
    'scope_path': 'google/gsoc2009',
    'scope': gsoc2009,
    })

  role_properties.update({
      'key_name': 'google/gsoc2009/test',
      'link_id': 'test',
      'scope_path': 'google/gsoc2009',
      'scope': gsoc2009,
      'program': gsoc2009,
      'parent': current_user,
      })

  profile = GSoCProfile(**role_properties)
  role_properties.pop('parent')

  orgs = []
  for i in range(15):
    group_properties.update({
        'key_name': 'google/gsoc2009/org_%d' % i,
        'link_id': 'org_%d' % i,
        'name': 'Organization %d' % i,
        'short_name': 'Org %d' % i,
        'description': 'Organization %d!' % i,
        })

    entity = GSoCOrganization(**group_properties)
    orgs.append(entity)
    entity.put()

    # Admin (and thus mentor) for the first org
    if i == 0:
      profile.org_admin_for.append(entity.key())
      profile.mentor_for.append(entity.key())
      profile.is_mentor = True
      profile.is_org_admin = True
      profile.put()

    # Mentor for the second org
    if i == 1:
      profile.mentor_for.append(entity.key())
      profile.is_mentor = True
      profile.put()

  role_properties.update({
      'key_name': 'google/gci2009/test',
      'link_id': 'test',
      'scope_path': 'google/gci2009',
      'scope': gci2009,
      'program': gci2009,
      'org_admin_for': [melange.key()],
      'mentor_for': [melange.key()],
      'parent': current_user,
      })

  melange_admin = GCIProfile(**role_properties)
  # TODO: add GCI orgs
  melange_admin.put()

  task_properties = {
      'status': 'Open',
      'modified_by': melange_admin.key(),
      'subscribers': [melange_admin.key()],
      'title': 'Awesomeness',
      'created_by': melange_admin.key(),
      'created_on': now,
      'program': gci2009,
      'time_to_complete': 1337,
      'modified_on': now,
      'org': melange.key(),
      'description': '<p>AWESOME</p>',
      'difficulty_level': DifficultyLevel.MEDIUM,
      'types': ['Code']
  }

  gci_task = GCITask(**task_properties)
  gci_task.put()

  user_properties = {
      'key_name': 'student',
      'link_id': 'student',
      'account': users.User(email='*****@*****.**'),
      'name': 'Student',
      }

  student_user = User(**user_properties)
  student_user.put()

  student_id = 'student'
  student_properties = {
      'key_name': gsoc2009.key().name() + "/" + student_id,
      'link_id': student_id, 
      'scope_path': gsoc2009.key().name(),
      'parent': student_user,
      'scope': gsoc2009,
      'program': gsoc2009,
      'user': student_user,
      'is_student': True,
      'public_name': 'Student',
      'given_name': 'Student',
      'surname': 'Student',
      'birth_date': db.DateProperty.now(),
      'email': '*****@*****.**',
      'im_handle': 'student_im_handle',
      'major': 'test major',
      'name_on_documents': 'Student',
      'res_country': 'United States',
      'res_city': 'city',
      'res_street': 'test street',
      'res_postalcode': '12345',
      'publish_location': True,
      'blog': 'http://www.blog.com/',
      'home_page': 'http://www.homepage.com/',
      'photo_url': 'http://www.photosite.com/thumbnail.png',
      'ship_state': None,
      'tshirt_size': 'XS',
      'tshirt_style': 'male',
      'degree': 'Undergraduate',
      'phone': '1650253000',
      'can_we_contact_you': True, 
      'program_knowledge': 'I heard about this program through a friend.'
      }

  melange_student = GSoCProfile(**student_properties)

  student_info_properties = {
      'key_name': melange_student.key().name(),
      'parent': melange_student,
      'expected_graduation': 2009,
      'program': gsoc2009,
      'school_country': 'United States',
      'school_name': 'Test School',
      'school_home_page': 'http://www.example.com',
      'program': gsoc2009,
  }
  student_info = GSoCStudentInfo(**student_info_properties)
  student_info.put()

  melange_student.student_info = student_info
  melange_student.put()

  user_properties = {
      'key_name': 'student2',
      'link_id': 'student2',
      'account': users.User(email='*****@*****.**'),
      'name': 'Student 2',
      }

  student_user2 = User(**user_properties)
  student_user2.put()
  student_id = 'student2'
  student_properties.update({
      'key_name': gsoc2009.key().name() + "/" + student_id,
      'link_id': student_id,
      'user': student_user2,
      'parent': student_user2,
  })

  melange_student2 = GSoCProfile(**student_properties)
  melange_student2.put()

  project_id = 'test_project'
  project_properties = {
      'key_name':  gsoc2009.key().name() + "/org_1/" + project_id,
      'link_id': project_id, 
      'scope_path': gsoc2009.key().name() + "/org_1",
      'scope': orgs[1].key(),

      'title': 'test project',
      'abstract': 'test abstract',
      'status': 'accepted',
      'student': melange_student,
      'mentor': profile,
      'program':  gsoc2009
       }

  melange_project = StudentProject(**project_properties)
  melange_project.put()
  student_info_properties.update({'number_of_projects': 1,
                                  'project_for_orgs': [orgs[1].key()]})
  student_info = GSoCStudentInfo(**student_info_properties)
  student_info.put()

  melange_student.student_info = student_info
  melange_student.put()

  project_id = 'test_project2'
  project_properties.update({
      'key_name':  gsoc2009.key().name() + "/org_1/" + project_id,
      'link_id': project_id,
      'student': melange_student2,
      'title': 'test project2'
      })
      
  student_info_properties.update({
      'key_name': gsoc2009.key().name() + "/" + student_id,
      'link_id': student_id,
      'parent': melange_student2,
  })
  student_info2 = GSoCStudentInfo(**student_info_properties)
  student_info2.put()

  melange_student2.student_info = student_info2
  melange_student2.put()

  melange_project2 = StudentProject(**project_properties)
  melange_project2.put()

  student_id = 'student'
  student_properties.update({
      'key_name': gci2009.key().name() + '/' + student_id,
      'parent': student_user,
      'scope': gci2009,
      'scope_path': gci2009.key().name(),
  })
  gci_student = GCIProfile(**student_properties)
  gci_student.put()

  student_info_properties.update({
      'key_name': gci_student.key().name(),
      'parent': gci_student,
      'program': gci2009,
  })
  student_info = GCIStudentInfo(**student_info_properties)
  student_info.put()
  gci_student.student_info = student_info
  gci_student.put()

  score_properties = {
      'parent': gci_student,
      'program': gci2009,
      'points': 5,
      'tasks': [gci_task.key()]
      }
  score = GCIScore(**score_properties)
  score.put()

  document_properties = {
      'key_name': 'site/site/home',
      'link_id': 'home',
      'scope_path': 'site',
      'scope': site,
      'prefix': 'site',
      'author': current_user,
      'title': 'Home Page',
      'short_name': 'Home',
      'content': 'This is the Home Page',
      'modified_by': current_user,
      }

  home_document = Document(**document_properties)
  home_document.put()


  document_properties = {
      'key_name': 'user/test/notes',
      'link_id': 'notes',
      'scope_path': 'test',
      'scope': current_user,
      'prefix': 'user',
      'author': current_user,
      'title': 'My Notes',
      'short_name': 'Notes',
      'content': 'These are my notes',
      'modified_by': current_user,
      }

  notes_document = Document(**document_properties)
  notes_document.put()

  site.home = home_document
  site.put()
  # pylint: disable=E1101
  memcache.flush_all()

  return http.HttpResponse('Done')
示例#36
0
class CleaningTest(GSoCDjangoTestCase):
    """Tests related to cleaning logic.
  """
    def setUp(self):
        """Set up required for the cleaning logic tests.
    """
        self.init()
        # Ensure that current user is created
        user_properties = {
            'account': users.get_current_user(),
            'link_id': 'current_user',
            'key_name': 'current_user',
            'name': 'Current User',
        }
        self.user = User(**user_properties)
        self.user.put()
        # Create another user
        another_user_properties = {
            'account': users.User(email="*****@*****.**"),
            'link_id': 'another_user',
            'key_name': 'another_user',
            'name': 'Another User',
        }
        self.another_user = User(**another_user_properties)
        self.another_user.put()
        # Create a dummy form object
        self.form = Form()

    def testCleanEmptyField(self):
        """Tests that empty field can be cleaned.
    """
        field_name = 'field'
        clean_field = cleaning.clean_empty_field(field_name)
        # Test that the same value will be returned, the cleaned_data of form
        # does not change and there is no error message if the value of field
        # is not empty
        field_value = 'v1_@?'
        cleaned_data_before = {field_name: field_value}
        self.form.cleaned_data = cleaned_data_before.copy()
        self.assertEqual(clean_field(self.form), field_value)
        self.assertEqual(self.form.cleaned_data, cleaned_data_before)
        self.assertEqual(self.form._errors, {})
        # Test that None will be returned, the cleaned_data of form does not change
        # and there is no error message if the value of field is empty
        field_value = ''
        cleaned_data_before = {field_name: field_value}
        self.form.cleaned_data = cleaned_data_before.copy()
        self.assertEqual(clean_field(self.form), None)
        self.assertEqual(self.form.cleaned_data, cleaned_data_before)
        self.assertEqual(self.form._errors, {})

    def testCleanEmail(self):
        """Tests that an email is cleaned.
    """
        field_name = 'email'
        clean_field = cleaning.clean_email(field_name)
        #Test that the same value is returned, the cleaned_data of the from does
        #not change and there is no error message if the value of the field has a
        #valid email
        field_value = '*****@*****.**'
        cleaned_data_before = {field_name: field_value}
        self.form.cleaned_data = cleaned_data_before.copy()
        self.assertEqual(clean_field(self.form), field_value)
        self.assertEqual(self.form.cleaned_data, cleaned_data_before)
        self.assertEqual(self.form._errors, {})
        #Test that forms.ValidationError is raised if email is not valid.
        field_value = '#$test&*('
        cleaned_data_before = {field_name: field_value}
        self.form.cleaned_data = cleaned_data_before.copy()
        self.assertRaises(forms.ValidationError, clean_field, self.form)
        self.assertEqual(self.form.cleaned_data, cleaned_data_before)
        self.assertEqual(self.form._errors, {})

    def testCleanLinkId(self):
        """Tests that link_id field can be cleaned.
    """
        field_name = 'link_id'
        clean_field = cleaning.clean_link_id(field_name)
        # Test that the value will be returned, the cleaned_data of form does not
        # change and there is no error message if the value of field has a valid
        # link_id format
        field_value = 'valid_link_id'
        cleaned_data_before = {field_name: field_value}
        self.form.cleaned_data = cleaned_data_before.copy()
        self.assertEqual(clean_field(self.form), field_value)
        self.assertEqual(self.form.cleaned_data, cleaned_data_before)
        self.assertEqual(self.form._errors, {})
        # Test that forms.ValidationError will be raised, the cleaned_data of form
        # does not change and there is no error message if the value of field has
        # not a valid link_id format
        field_value = 'v1_@?'
        cleaned_data_before = {field_name: field_value}
        self.form.cleaned_data = cleaned_data_before.copy()
        self.assertRaises(forms.ValidationError, clean_field, self.form)
        self.assertEqual(self.form.cleaned_data, cleaned_data_before)
        self.assertEqual(self.form._errors, {})

    def testCleanScopePath(self):
        """Tests that scope_path field can be cleaned.
    """
        field_name = 'scope_path'
        clean_field = cleaning.clean_scope_path(field_name)
        # Test that the value will be returned if the value of field
        # has a valid scope_path format
        field_value = 'valid_scope_path'
        cleaned_data_before = {field_name: field_value}
        self.form.cleaned_data = cleaned_data_before.copy()
        self.assertEqual(clean_field(self.form), field_value)
        self.assertEqual(self.form.cleaned_data, cleaned_data_before)
        self.assertEqual(self.form._errors, {})
        # Test that forms.ValidationError will be raised if the value of field
        # has not a valid scope_path format
        field_value = 'v1_@?'
        cleaned_data_before = {field_name: field_value}
        self.form.cleaned_data = cleaned_data_before.copy()
        self.assertRaises(forms.ValidationError, clean_field, self.form)
        self.assertEqual(self.form.cleaned_data, cleaned_data_before)
        self.assertEqual(self.form._errors, {})

    def testCleanExistingUser(self):
        """Tests that the user field can be cleaned for existing users.
    """
        field_name = 'user'
        clean_field = cleaning.clean_existing_user(field_name)
        # Test that the user will be returned if the value of field
        # is an existent user's link_id
        field_value = self.user.link_id
        self.form.cleaned_data = {field_name: field_value}
        cleaned_data_after = clean_field(self.form)
        self.assertEqual(cleaned_data_after.link_id, self.user.link_id)
        # Test that forms.ValidationError will be raised if the value of field
        # is not an existent user's link_id
        field_value = 'non_existent_user'
        self.form.cleaned_data = {field_name: field_value}
        self.assertRaises(forms.ValidationError, clean_field, self.form)

    def testCleanUserIsCurrent(self):
        """Tests that the user field can be cleaned for current users.
    """
        field_name = 'user'
        clean_field = cleaning.clean_user_is_current(field_name)
        # Test that the user will be returned if the value of field is
        # an existent user's link_id
        field_value = self.user.link_id
        self.form.cleaned_data = {field_name: field_value}
        cleaned_data_after = clean_field(self.form)
        self.assertEqual(cleaned_data_after.link_id, self.user.link_id)
        # Test that forms.ValidationError will be raised if the value of field
        # is a user's link_id other than the current user's
        field_value = self.another_user.link_id
        self.form.cleaned_data = {field_name: field_value}
        self.assertRaises(forms.ValidationError, clean_field, self.form)
        # Test that forms.ValidationError will be raised if the value of field
        # is not an existent user's link_id
        field_value = 'non_existent_user'
        self.form.cleaned_data = {field_name: field_value}
        self.assertRaises(forms.ValidationError, clean_field, self.form)

    def testCleanUserNotExist(self):
        """Tests that the user field can be cleaned for non-existent users.
    """
        field_name = 'user'
        clean_field = cleaning.clean_user_not_exist(field_name)
        # Test that the value will be returned if the value of field
        # is not an existent user's link_id
        field_value = 'non_existent_user'
        self.form.cleaned_data = {field_name: field_value}
        self.assertEqual(clean_field(self.form), field_value)
        # Test that forms.ValidationError will be raised if the value of field
        # is an existent user's link_id
        field_value = self.user.link_id
        self.form.cleaned_data = {field_name: field_value}
        self.assertRaises(forms.ValidationError, clean_field, self.form)

    def testCleanUsersNotSame(self):
        """Tests that the user field can be cleaned for non current users.
    """
        field_name = 'not_current_user'
        clean_field = cleaning.clean_users_not_same(field_name)
        # Test that forms.ValidationError will be raised if the value of field
        # is the current user's link_id
        field_value = self.user.link_id
        self.form.cleaned_data = {field_name: field_value}
        self.assertRaises(forms.ValidationError, clean_field, self.form)
        # Test that the user will be returned if the value of field is
        # a user's link_id other than the current user
        field_value = self.another_user.link_id
        self.form.cleaned_data = {field_name: field_value}
        self.assertEqual(
            clean_field(self.form).link_id, self.another_user.link_id)
        # Test that forms.ValidationError will be raised if the value of field
        # is not an existent user's link_id
        field_value = 'non_existent_user'
        self.form.cleaned_data = {field_name: field_value}
        self.assertRaises(forms.ValidationError, clean_field, self.form)

    def testCleanUserAccount(self):
        """Test that user account can be cleaned.
    """
        field_name = 'user_account'
        clean_field = cleaning.clean_user_account(field_name)
        # Test that a new account will be returned if the value of field is
        # a valid new email address
        field_value = '*****@*****.**'
        self.form.cleaned_data = {field_name: field_value}
        cleaned_data_after = clean_field(self.form)
        self.assertEqual(cleaned_data_after.email(), field_value)
        # Test that the existing account will be returned if the value of field is
        # an existent user's email address
        field_value = self.user.account.email()
        self.form.cleaned_data = {field_name: field_value}
        cleaned_data_after = clean_field(self.form)
        self.assertEqual(cleaned_data_after.email(), field_value)
        self.assertEqual(cleaned_data_after, self.user.account)
        # Test that a new account will be returned even if the value of field is
        # an invalid email address
        field_value = 'invalid_*mail'
        self.form.cleaned_data = {field_name: field_value}
        self.assertEqual(clean_field(self.form).email(), field_value)

    def testCleanUserAccountNotInUse(self):
        """Tests that user account can be cleaned for non-existent user accounts.
    """
        field_name = 'user_account_not_in_use'
        clean_field = cleaning.clean_user_account_not_in_use(field_name)
        # Test that a new account will be created and returned
        # if the value of field is a valid new email address
        field_value = '*****@*****.**'
        self.form.cleaned_data = {field_name: field_value}
        cleaned_data_after = clean_field(self.form)
        self.assertEqual(cleaned_data_after.email(), field_value)
        # Test that forms.ValidationError will be raised if the value of field is
        # an existent user's email address
        field_value = self.user.account.email()
        self.form.cleaned_data = {field_name: field_value}
        self.assertRaises(forms.ValidationError, clean_field, self.form)
        # Test that a new account will be created and returned
        # even if the value of field is an invalid email address
        field_value = 'invalid_*mail'
        self.form.cleaned_data = {field_name: field_value}
        cleaned_data_after = clean_field(self.form)
        self.assertEqual(cleaned_data_after.email(), field_value)

    def testCleanValidShippingChars(self):
        """Tests that the shipping fields can be cleaned.
    """
        field_name = 'ascii'
        clean_field = cleaning.clean_valid_shipping_chars(field_name)
        # Test that the value will be returned if the value of field is valid
        field_value = 'ab12'
        self.form.cleaned_data = {field_name: field_value}
        self.assertEqual(clean_field(self.form), field_value)
        # Test that forms.ValidationError will be raised if the value of field
        # is not valid ascii
        field_value = u'\ua000'
        self.form.cleaned_data = {field_name: field_value}
        self.assertRaises(forms.ValidationError, clean_field, self.form)

    def testCleanContentLength(self):
        """Tests that content length can be cleaned.
    """
        field_name = 'content_length'
        clean_field = cleaning.clean_content_length(field_name, 3, 5)
        # Test that the value will be returned if the length of the value of field
        # is within min_length and max_length
        field_value = 'a1&'
        self.form.cleaned_data = {field_name: field_value}
        self.assertEqual(clean_field(self.form), field_value)
        # Test that forms.ValidationError will be raised if the length of the value
        # of field is less than min_length
        field_value = 'ab'
        self.form.cleaned_data = {field_name: field_value}
        self.assertRaises(forms.ValidationError, clean_field, self.form)
        # Test that forms.ValidationError will be raised if the length of the value
        # of field is more than max_length
        field_value = 'ab12&*'
        self.form.cleaned_data = {field_name: field_value}
        self.assertRaises(forms.ValidationError, clean_field, self.form)

    def testCleanPhoneNumber(self):
        """Tests that phone number can be cleaned.
    """
        field_name = 'phone'
        clean_field = cleaning.clean_phone_number(field_name)
        # Test that the phone number will be returned if it contains digits only
        field_value = '0010208636479'
        self.form.cleaned_data = {field_name: field_value}
        self.assertEqual(clean_field(self.form), field_value)
        # Test that forms.ValidationError will be raised if
        # the phone number contains non digits (except '+')
        field_value = '001-020-8636479'
        self.form.cleaned_data[field_name] = field_value
        self.assertRaises(forms.ValidationError, clean_field, self.form)
        # Test that the '+' will be replaced with 00 and then the modified number
        # will be returned if the phone number starts with a '+'
        field_value = '+10208636479'
        self.form.cleaned_data[field_name] = field_value
        expected = '00' + field_value[1:]
        self.assertEqual(clean_field(self.form), expected)
        # Test that forms.ValidationError will be raised if
        # a '+' is in the middle of the phone number
        field_value = '1+0208636479'
        self.form.cleaned_data[field_name] = field_value
        self.assertRaises(forms.ValidationError, clean_field, self.form)
        # Test that forms.ValidationError will be raised if
        # a '+' is at the end of the phone number
        field_value = '10208636479+'
        self.form.cleaned_data[field_name] = field_value
        self.assertRaises(forms.ValidationError, clean_field, self.form)

    def testCleanFeedUrl(self):
        """Tests that feed url can be cleaned.

    Note: unlike other cleaning functions, it has not used a decorator.
    So, the field name 'feed_url' is hardwired in the code.
    """
        field_name = 'feed_url'
        clean_field = cleaning.clean_feed_url(field_name)
        # Test that the value of the feed url field will be returned if
        # the value of the feed url field is an existent feed url
        field_value = 'http://rss.cnn.com/rss/edition.rss'
        self.form.cleaned_data = {field_name: field_value}
        self.assertEqual(clean_field(self.form), field_value)
        # Test that None will be returned if the value of the feed url field is
        # an empty string
        field_value = ''
        self.form.cleaned_data = {field_name: field_value}
        self.assertEqual(clean_field(self.form), None)
        # Test that forms.ValidationError error will be raised if the value of
        # the feed url field is not an existent feed url
        field_value = 'http://example.com/invalidfeed/'
        self.form.cleaned_data = {field_name: field_value}
        self.assertRaises(forms.ValidationError, clean_field, self.form)

    def testCleanHtmlContent(self):
        """Tests that html content can be cleaned.
    """
        field_name = 'html'
        clean_field = cleaning.clean_html_content(field_name)
        # Test that normal html can be cleaned
        expected = html = '<div>f9-+@4</div>'
        self.form.cleaned_data = {field_name: html}
        self.assertEqual(clean_field(self.form), expected)
        # Test that normal html can be cleaned
        html = '<html>f9-+@4</html>'
        self.form.cleaned_data = {field_name: html}
        expected = html[6:-7]
        self.assertEqual(clean_field(self.form), expected)
        # Test that unicode is also supported
        expected = html = u'\ua000'
        self.form.cleaned_data = {field_name: html}
        self.assertEqual(clean_field(self.form), expected)
        # Test that input with scripts will raise forms.ValidationError
        html = '<script></script>'
        self.form.cleaned_data = {field_name: html}
        self.assertRaises(forms.ValidationError, clean_field, self.form)
        # Test that input can contain scripts when the current user is a developer
        self.user.is_developer = True
        self.user.put()
        expected = html = '<script></script>'
        self.form.cleaned_data = {field_name: html}
        self.assertEqual(clean_field(self.form), expected)

    def testCleanUrl(self):
        """Tests that url can be cleaned.
    """
        field_name = 'url'
        clean_field = cleaning.clean_url(field_name)
        # Test that the value of the url field will be returned
        # if it is a valid url
        field_value = 'http://exampleabc.com/'
        self.form.cleaned_data = {field_name: field_value}
        self.form.fields = {field_name: forms.URLField()}
        self.assertEqual(clean_field(self.form), field_value)
        # Test that None will be returned if the value of the url field
        # is an empty string
        field_value = ''
        self.form.cleaned_data = {field_name: field_value}
        self.assertEqual(clean_field(self.form), None)
        # Test that forms.ValidationError error will be raised
        # if the value of the url field is not a valid url
        field_value = 'exampleabc'
        self.form.cleaned_data = {field_name: field_value}
        self.assertRaises(forms.ValidationError, clean_field, self.form)

    def testStr2Set(self):
        """Tests if symbol separated strings are cleaned.
    """
        string_field = 'string_field'
        clean_field = cleaning.str2set(string_field, separator=',')

        string_field_value = "a,b,c"
        cleaned_data_before = {string_field: string_field_value}
        self.form.cleaned_data = cleaned_data_before
        expected = string_field_value.split(',')
        self.assertEqual(clean_field(self.form), expected)

        string_field_value = "a"
        cleaned_data_before = {string_field: string_field_value}
        self.form.cleaned_data = cleaned_data_before
        expected = string_field_value.split()
        self.assertEqual(clean_field(self.form), expected)

        string_field_value = "a b c"
        clean_field = cleaning.str2set(string_field, separator=' ')
        cleaned_data_before = {string_field: string_field_value}
        self.form.cleaned_data = cleaned_data_before
        expected = string_field_value.split()
        self.assertEqual(clean_field(self.form), expected)

        string_field_value = "a, b, c, a"
        clean_field = cleaning.str2set(string_field, separator=',')
        cleaned_data_before = {string_field: string_field_value}
        self.form.cleaned_data = cleaned_data_before
        temp = string_field_value.split(',')
        expected = set([char.strip() for char in temp])
        actual = set(clean_field(self.form))
        self.assertEqual(expected, actual)
示例#37
0
class CleaningTest(GSoCDjangoTestCase):
  """Tests related to cleaning logic.
  """
  def setUp(self):
    """Set up required for the cleaning logic tests.
    """
    self.init()
    # Ensure that current user is created
    user_properties = {
        'account': users.get_current_user(),
        'link_id': 'current_user',
        'key_name': 'current_user',
        'name': 'Current User',
        }
    self.user = User(**user_properties)
    self.user.put()
    # Create another user
    another_user_properties = {
        'account': users.User(email="*****@*****.**"),
        'link_id': 'another_user',
        'key_name': 'another_user',
        'name': 'Another User',
        }
    self.another_user = User(**another_user_properties)
    self.another_user.put()
    # Create a dummy form object
    self.form = Form()

  def testCleanEmptyField(self):
    """Tests that empty field can be cleaned.
    """
    field_name = 'field'
    clean_field = cleaning.clean_empty_field(field_name)
    # Test that the same value will be returned, the cleaned_data of form
    # does not change and there is no error message if the value of field
    # is not empty
    field_value = 'v1_@?'
    cleaned_data_before = {field_name: field_value}
    self.form.cleaned_data = cleaned_data_before.copy()
    self.assertEqual(clean_field(self.form), field_value)
    self.assertEqual(self.form.cleaned_data, cleaned_data_before)
    self.assertEqual(self.form._errors, {})
    # Test that None will be returned, the cleaned_data of form does not change
    # and there is no error message if the value of field is empty
    field_value = ''
    cleaned_data_before = {field_name: field_value}
    self.form.cleaned_data = cleaned_data_before.copy()
    self.assertEqual(clean_field(self.form), None)
    self.assertEqual(self.form.cleaned_data, cleaned_data_before)
    self.assertEqual(self.form._errors, {})

  def testCleanEmail(self):
    """Tests that an email is cleaned.
    """
    field_name = 'email'
    clean_field = cleaning.clean_email(field_name)
    #Test that the same value is returned, the cleaned_data of the from does
    #not change and there is no error message if the value of the field has a
    #valid email
    field_value = '*****@*****.**'
    cleaned_data_before = {field_name: field_value}
    self.form.cleaned_data = cleaned_data_before.copy()
    self.assertEqual(clean_field(self.form), field_value)
    self.assertEqual(self.form.cleaned_data, cleaned_data_before)
    self.assertEqual(self.form._errors, {})
    #Test that forms.ValidationError is raised if email is not valid.
    field_value = '#$test&*('
    cleaned_data_before = {field_name: field_value}
    self.form.cleaned_data = cleaned_data_before.copy()
    self.assertRaises(forms.ValidationError, clean_field, self.form)
    self.assertEqual(self.form.cleaned_data, cleaned_data_before)
    self.assertEqual(self.form._errors, {})

  def testCleanLinkId(self):
    """Tests that link_id field can be cleaned.
    """
    field_name = 'link_id'
    clean_field = cleaning.clean_link_id(field_name)
    # Test that the value will be returned, the cleaned_data of form does not
    # change and there is no error message if the value of field has a valid
    # link_id format
    field_value = 'valid_link_id'
    cleaned_data_before = {field_name: field_value}
    self.form.cleaned_data = cleaned_data_before.copy()
    self.assertEqual(clean_field(self.form), field_value)
    self.assertEqual(self.form.cleaned_data, cleaned_data_before)
    self.assertEqual(self.form._errors, {})
    # Test that forms.ValidationError will be raised, the cleaned_data of form
    # does not change and there is no error message if the value of field has
    # not a valid link_id format
    field_value = 'v1_@?'
    cleaned_data_before = {field_name: field_value}
    self.form.cleaned_data = cleaned_data_before.copy()
    self.assertRaises(forms.ValidationError, clean_field, self.form)
    self.assertEqual(self.form.cleaned_data, cleaned_data_before)
    self.assertEqual(self.form._errors, {})

  def testCleanScopePath(self):
    """Tests that scope_path field can be cleaned.
    """
    field_name = 'scope_path'
    clean_field = cleaning.clean_scope_path(field_name)
    # Test that the value will be returned if the value of field
    # has a valid scope_path format
    field_value = 'valid_scope_path'
    cleaned_data_before = {field_name: field_value}
    self.form.cleaned_data = cleaned_data_before.copy()
    self.assertEqual(clean_field(self.form), field_value)
    self.assertEqual(self.form.cleaned_data, cleaned_data_before)
    self.assertEqual(self.form._errors, {})
    # Test that forms.ValidationError will be raised if the value of field
    # has not a valid scope_path format
    field_value = 'v1_@?'
    cleaned_data_before = {field_name: field_value}
    self.form.cleaned_data = cleaned_data_before.copy()
    self.assertRaises(forms.ValidationError, clean_field, self.form)
    self.assertEqual(self.form.cleaned_data, cleaned_data_before)
    self.assertEqual(self.form._errors, {})

  def testCleanExistingUser(self):
    """Tests that the user field can be cleaned for existing users.
    """
    field_name = 'user'
    clean_field = cleaning.clean_existing_user(field_name)
    # Test that the user will be returned if the value of field
    # is an existent user's link_id
    field_value = self.user.link_id
    self.form.cleaned_data = {field_name: field_value}
    cleaned_data_after = clean_field(self.form)
    self.assertEqual(cleaned_data_after.link_id, self.user.link_id)
    # Test that forms.ValidationError will be raised if the value of field
    # is not an existent user's link_id
    field_value = 'non_existent_user'
    self.form.cleaned_data = {field_name: field_value}
    self.assertRaises(forms.ValidationError, clean_field, self.form)

  def testCleanUserIsCurrent(self):
    """Tests that the user field can be cleaned for current users.
    """
    field_name = 'user'
    clean_field = cleaning.clean_user_is_current(field_name)
    # Test that the user will be returned if the value of field is
    # an existent user's link_id
    field_value = self.user.link_id
    self.form.cleaned_data = {field_name: field_value}
    cleaned_data_after = clean_field(self.form)
    self.assertEqual(cleaned_data_after.link_id, self.user.link_id)
    # Test that forms.ValidationError will be raised if the value of field
    # is a user's link_id other than the current user's
    field_value = self.another_user.link_id
    self.form.cleaned_data = {field_name: field_value}
    self.assertRaises(forms.ValidationError, clean_field, self.form)
    # Test that forms.ValidationError will be raised if the value of field
    # is not an existent user's link_id
    field_value = 'non_existent_user'
    self.form.cleaned_data = {field_name: field_value}
    self.assertRaises(forms.ValidationError, clean_field, self.form)

  def testCleanUserNotExist(self):
    """Tests that the user field can be cleaned for non-existent users.
    """
    field_name = 'user'
    clean_field = cleaning.clean_user_not_exist(field_name)
    # Test that the value will be returned if the value of field
    # is not an existent user's link_id
    field_value = 'non_existent_user'
    self.form.cleaned_data = {field_name: field_value}
    self.assertEqual(clean_field(self.form), field_value)
    # Test that forms.ValidationError will be raised if the value of field
    # is an existent user's link_id
    field_value = self.user.link_id
    self.form.cleaned_data = {field_name: field_value}
    self.assertRaises(forms.ValidationError, clean_field, self.form)

  def testCleanUsersNotSame(self):
    """Tests that the user field can be cleaned for non current users.
    """
    field_name = 'not_current_user'
    clean_field = cleaning.clean_users_not_same(field_name)
    # Test that forms.ValidationError will be raised if the value of field
    # is the current user's link_id
    field_value = self.user.link_id
    self.form.cleaned_data = {field_name: field_value}
    self.assertRaises(forms.ValidationError, clean_field, self.form)
    # Test that the user will be returned if the value of field is
    # a user's link_id other than the current user
    field_value = self.another_user.link_id
    self.form.cleaned_data = {field_name: field_value}
    self.assertEqual(clean_field(self.form).link_id, self.another_user.link_id)
    # Test that forms.ValidationError will be raised if the value of field
    # is not an existent user's link_id
    field_value = 'non_existent_user'
    self.form.cleaned_data = {field_name: field_value}
    self.assertRaises(forms.ValidationError, clean_field, self.form)

  def testCleanUserAccount(self):
    """Test that user account can be cleaned.
    """
    field_name = 'user_account'
    clean_field = cleaning.clean_user_account(field_name)
    # Test that a new account will be returned if the value of field is
    # a valid new email address
    field_value = '*****@*****.**'
    self.form.cleaned_data = {field_name: field_value}
    cleaned_data_after = clean_field(self.form)
    self.assertEqual(cleaned_data_after.email(), field_value)
    # Test that the existing account will be returned if the value of field is
    # an existent user's email address
    field_value = self.user.account.email()
    self.form.cleaned_data = {field_name: field_value}
    cleaned_data_after = clean_field(self.form)
    self.assertEqual(cleaned_data_after.email(), field_value)
    self.assertEqual(cleaned_data_after, self.user.account)
    # Test that a new account will be returned even if the value of field is
    # an invalid email address
    field_value = 'invalid_*mail'
    self.form.cleaned_data = {field_name: field_value}
    self.assertEqual(clean_field(self.form).email(), field_value)

  def testCleanUserAccountNotInUse(self):
    """Tests that user account can be cleaned for non-existent user accounts.
    """
    field_name = 'user_account_not_in_use'
    clean_field = cleaning.clean_user_account_not_in_use(field_name)
    # Test that a new account will be created and returned
    # if the value of field is a valid new email address
    field_value = '*****@*****.**'
    self.form.cleaned_data = {field_name: field_value}
    cleaned_data_after = clean_field(self.form)
    self.assertEqual(cleaned_data_after.email(), field_value)
    # Test that forms.ValidationError will be raised if the value of field is
    # an existent user's email address
    field_value = self.user.account.email()
    self.form.cleaned_data = {field_name: field_value}
    self.assertRaises(forms.ValidationError, clean_field, self.form)
    # Test that a new account will be created and returned
    # even if the value of field is an invalid email address
    field_value = 'invalid_*mail'
    self.form.cleaned_data = {field_name: field_value}
    cleaned_data_after = clean_field(self.form)
    self.assertEqual(cleaned_data_after.email(), field_value)

  def testCleanValidShippingChars(self):
    """Tests that the shipping fields can be cleaned.
    """
    field_name = 'ascii'
    clean_field = cleaning.clean_valid_shipping_chars(field_name)
    # Test that the value will be returned if the value of field is valid
    field_value = 'ab12'
    self.form.cleaned_data = {field_name: field_value}
    self.assertEqual(clean_field(self.form), field_value)
    # Test that forms.ValidationError will be raised if the value of field
    # is not valid ascii
    field_value = u'\ua000'
    self.form.cleaned_data = {field_name: field_value}
    self.assertRaises(forms.ValidationError, clean_field, self.form)

  def testCleanContentLength(self):
    """Tests that content length can be cleaned.
    """
    field_name = 'content_length'
    clean_field = cleaning.clean_content_length(field_name, 3, 5)
    # Test that the value will be returned if the length of the value of field
    # is within min_length and max_length
    field_value = 'a1&'
    self.form.cleaned_data = {field_name: field_value}
    self.assertEqual(clean_field(self.form), field_value)
    # Test that forms.ValidationError will be raised if the length of the value
    # of field is less than min_length
    field_value = 'ab'
    self.form.cleaned_data = {field_name: field_value}
    self.assertRaises(forms.ValidationError, clean_field, self.form)
    # Test that forms.ValidationError will be raised if the length of the value
    # of field is more than max_length
    field_value = 'ab12&*'
    self.form.cleaned_data = {field_name: field_value}
    self.assertRaises(forms.ValidationError, clean_field, self.form)

  def testCleanPhoneNumber(self):
    """Tests that phone number can be cleaned.
    """
    field_name = 'phone'
    clean_field = cleaning.clean_phone_number(field_name)
    # Test that the phone number will be returned if it contains digits only
    field_value = '0010208636479'
    self.form.cleaned_data = {field_name: field_value}
    self.assertEqual(clean_field(self.form), field_value)
    # Test that forms.ValidationError will be raised if
    # the phone number contains non digits (except '+')
    field_value = '001-020-8636479'
    self.form.cleaned_data[field_name] = field_value
    self.assertRaises(forms.ValidationError, clean_field, self.form)
    # Test that the '+' will be replaced with 00 and then the modified number
    # will be returned if the phone number starts with a '+'
    field_value = '+10208636479'
    self.form.cleaned_data[field_name] = field_value
    expected = '00' + field_value[1:]
    self.assertEqual(clean_field(self.form), expected)
    # Test that forms.ValidationError will be raised if
    # a '+' is in the middle of the phone number
    field_value = '1+0208636479'
    self.form.cleaned_data[field_name] = field_value
    self.assertRaises(forms.ValidationError, clean_field, self.form)
    # Test that forms.ValidationError will be raised if
    # a '+' is at the end of the phone number
    field_value = '10208636479+'
    self.form.cleaned_data[field_name] = field_value
    self.assertRaises(forms.ValidationError, clean_field, self.form)

  def testCleanFeedUrl(self):
    """Tests that feed url can be cleaned.

    Note: unlike other cleaning functions, it has not used a decorator.
    So, the field name 'feed_url' is hardwired in the code.
    """
    field_name = 'feed_url'
    clean_field = cleaning.clean_feed_url(field_name)
    # Test that the value of the feed url field will be returned if
    # the value of the feed url field is an existent feed url
    field_value = 'http://rss.cnn.com/rss/edition.rss'
    self.form.cleaned_data = {field_name: field_value}
    self.assertEqual(clean_field(self.form), field_value)
    # Test that None will be returned if the value of the feed url field is
    # an empty string
    field_value = ''
    self.form.cleaned_data = {field_name: field_value}
    self.assertEqual(clean_field(self.form), None)
    # Test that forms.ValidationError error will be raised if the value of
    # the feed url field is not an existent feed url
    field_value = 'http://example.com/invalidfeed/'
    self.form.cleaned_data = {field_name: field_value}
    self.assertRaises(forms.ValidationError, clean_field, self.form)

  def testCleanHtmlContent(self):
    """Tests that html content can be cleaned.
    """
    field_name = 'html'
    clean_field = cleaning.clean_html_content(field_name)
    # Test that normal html can be cleaned
    expected = html = '<div>f9-+@4</div>'
    self.form.cleaned_data = {field_name: html}
    self.assertEqual(clean_field(self.form), expected)
    # Test that normal html can be cleaned
    html = '<html>f9-+@4</html>'
    self.form.cleaned_data = {field_name: html}
    expected = html[6:-7]
    self.assertEqual(clean_field(self.form), expected)
    # Test that unicode is also supported
    expected = html = u'\ua000'
    self.form.cleaned_data = {field_name: html}
    self.assertEqual(clean_field(self.form), expected)
    # Test that input with scripts will raise forms.ValidationError
    html = '<script></script>'
    self.form.cleaned_data = {field_name: html}
    self.assertRaises(forms.ValidationError, clean_field, self.form)
    # Test that input can contain scripts when the current user is a developer
    self.user.is_developer = True
    self.user.put()
    expected = html = '<script></script>'
    self.form.cleaned_data = {field_name: html}
    self.assertEqual(clean_field(self.form), expected)

  def testCleanUrl(self):
    """Tests that url can be cleaned.
    """
    field_name = 'url'
    clean_field = cleaning.clean_url(field_name)
    # Test that the value of the url field will be returned 
    # if it is a valid url
    field_value = 'http://exampleabc.com/'
    self.form.cleaned_data = {field_name: field_value}
    self.form.fields = {field_name: forms.URLField()}
    self.assertEqual(clean_field(self.form), field_value)
    # Test that None will be returned if the value of the url field 
    # is an empty string
    field_value = ''
    self.form.cleaned_data = {field_name: field_value}
    self.assertEqual(clean_field(self.form), None)
    # Test that forms.ValidationError error will be raised 
    # if the value of the url field is not a valid url
    field_value = 'exampleabc'
    self.form.cleaned_data = {field_name: field_value}
    self.assertRaises(forms.ValidationError, clean_field, self.form)

  def testStr2Set(self):
    """Tests if symbol separated strings are cleaned.
    """
    string_field = 'string_field'
    clean_field = cleaning.str2set(string_field, separator=',')

    string_field_value = "a,b,c"
    cleaned_data_before = {string_field: string_field_value}
    self.form.cleaned_data = cleaned_data_before
    expected = string_field_value.split(',')
    self.assertEqual(clean_field(self.form), expected)

    string_field_value = "a"
    cleaned_data_before = {string_field: string_field_value}
    self.form.cleaned_data = cleaned_data_before
    expected = string_field_value.split()
    self.assertEqual(clean_field(self.form), expected)

    string_field_value = "a b c"
    clean_field = cleaning.str2set(string_field, separator=' ')
    cleaned_data_before = {string_field: string_field_value}
    self.form.cleaned_data = cleaned_data_before
    expected = string_field_value.split()
    self.assertEqual(clean_field(self.form), expected)
    
    string_field_value = "a, b, c, a"
    clean_field = cleaning.str2set(string_field, separator=',')
    cleaned_data_before = {string_field: string_field_value}
    self.form.cleaned_data = cleaned_data_before
    temp = string_field_value.split(',')
    expected = set([char.strip() for char in temp])
    actual = set(clean_field(self.form))
    self.assertEqual(expected, actual)