Example #1
0
    def test_copy_exclude_fields(self):
        """Test the models copy method with excluding fields. When passing an
        excluded fields list, the value will become None or the models default
        for that field.
        """
        test_model = TestModel.objects.create(
            created_user=self.user,
            some_unique_field=random_alphanum(),
            some_unique_field_blank=random_alphanum(),
            some_unique_field_default=random_alphanum())

        exclude_fields = [
            'some_string_w_default', 'some_int', 'some_string_no_default',
            'some_boolean', 'some_unique_field', 'some_unique_field_blank',
            'some_unique_field_default'
        ]

        test_model_copy = test_model.copy(exclude_fields=exclude_fields)

        self.assertEqual(test_model_copy.some_string_w_default, 'hello')
        self.assertEqual(test_model_copy.some_int, 5)
        self.assertIsNone(test_model_copy.some_string_no_default)
        self.assertTrue(test_model_copy.some_boolean)
        self.assertIsNone(test_model_copy.some_unique_field)
        self.assertIsNone(test_model_copy.some_unique_field_blank)
        self.assertEqual(test_model_copy.some_unique_field_default,
                         'Hello world')
Example #2
0
    def test_expire_by_emails(self):
        """Test expiring tokens by an email addresses."""
        email_address_1 = 'testing@example1{0}.com'.format(random_alphanum(5))
        email_address_2 = 'testing@example2{0}.com'.format(random_alphanum(5))
        reason = 'BECAUSE_I_AM_TESTING_{0}'.format(random_alphanum(5))

        # created the token auth for email 1
        TokenAuthorization.objects.create(email_address=email_address_1,
                                          reason=reason,
                                          created_user=self.user)

        # created the token auth for email 2
        TokenAuthorization.objects.create(email_address=email_address_2,
                                          reason=reason,
                                          created_user=self.user)

        TokenAuthorization.objects.expire_by_emails(
            email_addresses=[email_address_1, email_address_2], reason=reason)

        token_auths = TokenAuthorization.objects.filter(
            email_address__in=[email_address_1, email_address_2])

        self.assertEqual(len(token_auths), 2)

        for auth in token_auths:
            self.assertTrue(auth.is_expired())
Example #3
0
 def test_get_by_id(self):
     """Test getting an object by id."""
     test_model = TestModel.objects.create(
         created_user=self.user,
         some_unique_field=random_alphanum(),
         some_unique_field_default=random_alphanum())
     test_model_db = TestModel.objects.get_by_id(id=test_model.id)
     self.assertEqual(test_model, test_model_db)
Example #4
0
    def test_get_or_none(self):
        """Getting an object which returns None if one is not found."""
        test_model = TestModel.objects.create(
            created_user=self.user,
            some_unique_field=random_alphanum(),
            some_unique_field_default=random_alphanum())
        test_model_db = TestModel.objects.get_or_none(id=test_model.id)
        self.assertEqual(test_model, test_model_db)

        self.assertIsNone(TestModel.objects.get_or_none(id=1234567890))
Example #5
0
    def test_forgot_username_form_email_invalid(self):
        """Test the forgot username user's email"""
        random_email = '{0}@{1}.com'.format(random_alphanum(5),
                                            random_alphanum(5))
        form = ForgotUsernameForm(data={'email': random_email})
        self.assertFalse(form.is_valid())

        form.cleaned_data['email'] = random_email

        with self.assertRaises(ValidationError):
            form.clean_email()
Example #6
0
    def test_forgot_username_form_email_invalid(self):
        """Test the forgot username user's email"""
        random_email = '{0}@{1}.com'.format(random_alphanum(5),
                                            random_alphanum(5))
        form = ForgotUsernameForm(data={'email': random_email})
        self.assertFalse(form.is_valid())

        form.cleaned_data['email'] = random_email

        with self.assertRaises(ValidationError):
            form.clean_email()
Example #7
0
    def test_umanage_change_email_activation_view(self):
        """Test the change email activation url to ensure it renders correctly.
        """
        new_email_address = '{0}@{1}.com'.format(random_alphanum(5),
                                                 random_alphanum(5))
        authorization = ChangeEmailAuthorization.objects.create(
            created_user=self.user, email_address=new_email_address)
        self.response_test_get(url=authorization.get_absolute_url(),
                               expected_status_code=302)

        test_user = get_user_model().objects.get(id=self.user.id)
        self.assertEqual(test_user.email, new_email_address)
Example #8
0
    def get_available_tokens(self, count=10, token_length=15, **kwargs):
        """Gets a list of available tokens.

        :param count: the number of tokens to return.
        :param token_length: the length of the tokens.  The higher the number
            the easier it will be to return a list.  If token_length == 1
            there's a strong probability that the enough tokens will exist in
            the db.

        """
        # This is the number of extra tokens to try and retrieve so calls to
        # the db can be limited
        token_buffer = int(math.ceil(count * .05))

        if token_buffer < 5:
            token_buffer = 5

        available = set([])

        while True:
            tokens = [
                random_alphanum(length=token_length)
                for t in range(count + token_buffer)
            ]
            db_tokens = self.filter(token__in=tokens).values_list('token',
                                                                  flat=True)
            available.update(set(tokens).difference(db_tokens))

            if len(available) >= count:
                return list(available)[:count]
Example #9
0
    def test_umanage_change_email_activation_view(self):
        """Test the change email activation url to ensure it renders correctly.
        """
        new_email_address = '{0}@{1}.com'.format(random_alphanum(5),
                                                 random_alphanum(5))
        authorization = ChangeEmailAuthorization.objects.create(
            created_user=self.user,
            email_address=new_email_address
        )
        self.response_test_get(
            url=authorization.get_absolute_url(),
            expected_status_code=302
        )

        test_user = get_user_model().objects.get(id=self.user.id)
        self.assertEqual(test_user.email, new_email_address)
Example #10
0
 def test_get_by_slug(self):
     """Test model manager get by slug."""
     slug = slugify(random_alphanum())
     obj = TestManagerModel.objects.create(created_user=self.user,
                                           slug=slug)
     obj_db = TestManagerModel.objects.get_by_slug(slug=slug)
     self.assertEqual(obj, obj_db)
Example #11
0
    def test_forgot_password_form_user_invalid(self):
        """Test the forgot password user's email"""
        form = ForgotPasswordForm(data={'username_or_email': random_alphanum()})
        self.assertFalse(form.is_valid())

        with self.assertRaises(ValidationError):
            form.clean_username_or_email()
Example #12
0
 def test_get_by_token(self):
     """Test model manager get by token."""
     token = random_alphanum()
     obj = TestManagerModel.objects.create(created_user=self.user,
                                           token=token)
     obj_db = TestManagerModel.objects.get_by_token(token=token)
     self.assertEqual(obj, obj_db)
Example #13
0
    def get_available_tokens(self, count=10, token_length=15, **kwargs):
        """Gets a list of available tokens.

        :param count: the number of tokens to return.
        :param token_length: the length of the tokens.  The higher the number
            the easier it will be to return a list.  If token_length == 1
            there's a strong probability that the enough tokens will exist in
            the db.

        """
        # This is the number of extra tokens to try and retrieve so calls to
        # the db can be limited
        token_buffer = int(math.ceil(count * .05))

        if token_buffer < 5:
            token_buffer = 5

        available = set([])

        while True:
            tokens = [random_alphanum(length=token_length)
                      for t in range(count + token_buffer)]
            db_tokens = self.filter(token__in=tokens).values_list('token',
                                                                  flat=True)
            available.update(set(tokens).difference(db_tokens))

            if len(available) >= count:
                return list(available)[:count]
Example #14
0
    def test_forgot_password_form_user_invalid(self):
        """Test the forgot password user's email"""
        form = ForgotPasswordForm(
            data={'username_or_email': random_alphanum()})
        self.assertFalse(form.is_valid())

        with self.assertRaises(ValidationError):
            form.clean_username_or_email()
    def test_random_utils_lower_only(self):
        """Test len of random utils for lower only characters."""
        random_val = random_alphanum(35, lower_only=True)
        self.assertEqual(len(random_val), 35)

        for c in random_val:
            if not c.isdigit() and not c.islower():
                self.fail('Random value has an upper case character: '
                          '{0}'.format(random_val))
Example #16
0
    def test_copy1(self):
        test_model = TestModel.objects.create(
            created_user=self.user,
            some_unique_field=random_alphanum(),
            some_unique_field_blank=random_alphanum(),
            some_unique_field_default=random_alphanum())

        test_model_copy = test_model.copy()

        utcnow = datetime.utcnow()
        self.assertIsNone(test_model_copy.id)
        self.assertTrue(test_model_copy.created_dttm <= utcnow)
        self.assertTrue(test_model_copy.last_modified_dttm <= utcnow)
        self.assertEqual(test_model_copy.last_modified_user,
                         test_model_copy.created_user)
        self.assertIsNone(test_model_copy.some_unique_field)
        self.assertIsNone(test_model_copy.some_unique_field_blank)
        self.assertEqual(test_model_copy.some_unique_field_default,
                         'Hello world')
 def create_blog_entries(self, user):
     entry1 = Entry.objects.create(
         title='title',
         slug='title-{0}'.format(random_alphanum()),
         body='content',
         created_user=user)
     entry2 = Entry.objects.create(
         title=('title kal jdfalkd klsjdals kfjaklfjaskdljfklfjsj fkajsflk'
                'sjflkdsjf slkdjflkdj lk'),
         slug='title-{0}'.format(random_alphanum()),
         body='content',
         created_user=user
     )
     entry3 = Entry.objects.create(
         title='title-3',
         slug='title-{0}'.format(random_alphanum()),
         body='content',
         created_user=user
     )
     print('added 3 new blog entries for: {0}'.format(user.username))
 def test_create_blog_posts(self):
     # - get the user
     # self.non_superuser()
     user = create_user(username=random_alphanum())
     # - get the number of current blog posts
     count_before = Entry.objects.filter(created_user=user).count()
     # - run the management command
     call_command('datascript', user.username)
     # - assert that after the manamaement command has run that the user now
     #   has 3 more blog entries than they did before running the management
     #   command.
     count_after = Entry.objects.filter(created_user=user).count()
     self.assertEqual(count_after - count_before, 3)
Example #19
0
    def test_expire_by_email_proxy_model(self):
        """Test expiring tokens by an email address."""
        email_address = 'testing@example{0}.com'.format(random_alphanum(5))
        num_tokens = 3
        created_tokens = []

        for num in range(num_tokens):
            created_tokens.append(
                TestTokenAuthorization.objects.create(
                    email_address=email_address, created_user=self.user))

        TestTokenAuthorization.objects.expire_by_email(
            email_address=email_address)

        token_auths = TestTokenAuthorization.objects.filter(
            email_address=email_address)

        self.assertEqual(len(token_auths), num_tokens)

        for auth in token_auths:
            self.assertTrue(auth.is_expired())
Example #20
0
    def test_copy_override_fields(self):
        """Test overriding fields with the model's .copy method."""
        test_model = TestModel.objects.create(
            created_user=self.user,
            some_unique_field=random_alphanum(),
            some_unique_field_blank=random_alphanum(),
            some_unique_field_default=random_alphanum())

        some_string_w_default = random_alphanum()
        some_int = randint(1, 1000)
        some_string_no_default = random_alphanum()
        some_boolean = False
        some_unique_field = random_alphanum()
        some_unique_field_blank = random_alphanum()
        some_unique_field_default = random_alphanum()

        test_model_copy = test_model.copy(
            some_string_w_default=some_string_w_default,
            some_int=some_int,
            some_string_no_default=some_string_no_default,
            some_boolean=some_boolean,
            some_unique_field=some_unique_field,
            some_unique_field_blank=some_unique_field_blank,
            some_unique_field_default=some_unique_field_default)

        self.assertEqual(test_model_copy.some_string_w_default,
                         some_string_w_default)
        self.assertEqual(test_model_copy.some_int, some_int)
        self.assertEqual(test_model_copy.some_string_no_default,
                         some_string_no_default)
        self.assertEqual(test_model_copy.some_boolean, some_boolean)
        self.assertEqual(test_model_copy.some_unique_field, some_unique_field)
        self.assertEqual(test_model_copy.some_unique_field_blank,
                         some_unique_field_blank)
        self.assertEqual(test_model_copy.some_unique_field_default,
                         some_unique_field_default)
Example #21
0
    def test_expire_by_email_all_reasons(self):
        """Test expiring tokens by an email address for all reasons."""
        email_address = 'testing@example{0}.com'.format(random_alphanum(5))
        reason = 'BECAUSE_I_AM_TESTING'
        num_tokens = 3
        created_tokens = []

        for num in range(num_tokens):
            created_tokens.append(
                TokenAuthorization.objects.create(
                    email_address=email_address,
                    reason='TEST_REASON_{0}'.format(num),
                    created_user=self.user))

        TokenAuthorization.objects.expire_by_email(email_address=email_address,
                                                   reason=None)

        token_auths = TokenAuthorization.objects.filter(
            email_address=email_address)

        self.assertEqual(len(token_auths), num_tokens)

        for auth in token_auths:
            self.assertTrue(auth.is_expired())
Example #22
0
 def test_get_next_slug(self):
     """Test getting next available slug."""
     slug = slugify(random_alphanum())
     TestManagerModel.objects.create(created_user=self.user, slug=slug)
     next_slug = TestManagerModel.objects.get_next_slug(slug=slug)
     self.assertEqual(next_slug, '{0}-1'.format(slug))
Example #23
0
 def test_not_is_slug_available(self):
     """Test if a slug is not available."""
     slug = slugify(random_alphanum())
     TestManagerModel.objects.create(created_user=self.user, slug=slug)
     self.assertFalse(TestManagerModel.objects.is_slug_available(slug=slug))
Example #24
0
 def test_is_slug_available(self):
     """Test if a slug is available."""
     self.assertTrue(
         TestManagerModel.objects.is_slug_available(slug=random_alphanum()))
Example #25
0
def create_user(username=None):
    """Create a new test user."""
    return User.objects.create(
        username=username or random_alphanum(),
        email='{0}@blah.com'.format(random_alphanum())
    )
 def test_len_random_utils_high_length(self):
     """Test high random utils length."""
     self.assertEqual(len(random_alphanum(75)), 75)
 def test_len_random_utils(self):
     """Test len of random utils string."""
     self.assertEqual(len(random_alphanum(15)), 15)