Exemplo n.º 1
0
        def test_user1_cant_delete_user2_account(self, api_client):
            new_user = UserFactory()
            new_user2 = UserFactory()
            api_client.force_authenticate(new_user)
            response = api_client.delete(new_user2.get_absolute_url())

            assert response.status_code == 403
Exemplo n.º 2
0
def test_if_comissions_are_being_properly_returned(currencies):
    user = UserFactory()
    promoter = UserFactory()
    referral = ReferralFactory(user=user, promoter=promoter)
    user_investment = InvestmentFactory(account__user=user)
    promoter_investment = InvestmentFactory(account__user=promoter)
    account = promoter.accounts.filter(currency__type='investment').first()

    assert user_investment.amount == Decimal('0.01')
    assert promoter_investment.amount == Decimal('0.01')

    pay_investments_comissions()
    account.refresh_from_db()

    assert Comissions.objects.count() == 1
    comission = Comissions.objects.first()
    assert comission.amount == Decimal('0.0002')
    assert account.deposit == Decimal('0.0002')
    assert comission.referral.pk == referral.pk

    change_referral(user, promoter)
    account.refresh_from_db()

    assert Comissions.objects.count() == 0
    assert account.deposit == Decimal('0')
Exemplo n.º 3
0
 def setUp(self):
     self.user = UserFactory(username='******')
     self.admin = UserFactory(username='******', super_user=True)
     self.norm = UserFactory(username='******')
     self.collab = UserFactory(username='******')
     self.created_queue = self.mock_create_queue(owner=self.user, name='TestUserQueue')
     self.created_queue.organizers.add(self.collab)
Exemplo n.º 4
0
def test_if_course_comission_has_being_properly_returned(currencies):
    user = UserFactory()
    promoter = UserFactory()
    new_promoter = UserFactory()
    referral = ReferralFactory(user=user, promoter=promoter)
    user_investment = InvestmentFactory(account__user=user)
    promoter_investment = InvestmentFactory(account__user=promoter)
    checking_account = user.accounts.filter(currency__type='checking').first()
    promoter_investment_account = promoter.accounts.filter(
        currency__type='investment').first()
    promoter_graduation = GraduationFactory(user=promoter)

    statement = StatementFactory(amount=Decimal('0.03'),
                                 type='course_subscription',
                                 description='Course Subscription',
                                 account=checking_account)
    assert statement.amount == Decimal('0.03')
    assert promoter_graduation.type == 'advisor'

    pay_course_comissions()
    promoter_investment_account.refresh_from_db()

    assert Statement.objects.count() == 1
    assert Comissions.objects.count() == 1
    assert Comissions.objects.first().amount == Decimal('0.003')
    assert promoter_investment_account.deposit == Decimal('0.003')

    change_referral(user, new_promoter)
    promoter_investment_account.refresh_from_db()
    referral.refresh_from_db()

    assert Statement.objects.count() == 0
    assert Comissions.objects.count() == 0
    assert promoter_investment_account.deposit == Decimal('0')
    assert new_promoter.pk == referral.promoter.pk
    def setUp(self):
        self.owner = UserFactory(username='******', super_user=True)
        self.normal_user = UserFactory(username='******')
        self.competition = CompetitionFactory(created_by=self.owner,
                                              title="Competition One")
        self.competition_participant = CompetitionParticipantFactory(
            user=self.normal_user, competition=self.competition)
        self.phase1 = PhaseFactory(competition=self.competition,
                                   auto_migrate_to_this_phase=False,
                                   start=twenty_five_minutes_ago,
                                   end=twenty_minutes_ago,
                                   index=0,
                                   name='Phase1',
                                   status=Phase.CURRENT)

        self.phase2 = PhaseFactory(competition=self.competition,
                                   auto_migrate_to_this_phase=True,
                                   start=five_minutes_ago,
                                   end=twenty_minutes_from_now,
                                   index=1,
                                   name='Phase2',
                                   status=Phase.NEXT)

        self.phase3 = PhaseFactory(competition=self.competition,
                                   auto_migrate_to_this_phase=False,
                                   start=twenty_minutes_from_now,
                                   index=2,
                                   name='Phase3',
                                   status=Phase.FINAL)

        for _ in range(4):
            self.make_submission()
Exemplo n.º 6
0
 def setUp(self):
     self.creator = UserFactory(username='******', password='******')
     self.other_user = UserFactory(username='******', password='******')
     self.comp = CompetitionFactory(created_by=self.creator)
     PhaseFactory(competition=self.comp)
     self.leaderboard = LeaderboardFactory(competition=self.comp)
     ColumnFactory(leaderboard=self.leaderboard)
Exemplo n.º 7
0
    def setUp(self):
        """
        method that prepares tests with required data
        """
        self.fake = Factory.create()
        self.client = APIClient()

        self.test_user3 = {
        'username': self.fake.user_name(),
        'first_name': self.fake.first_name(),
        'last_name': self.fake.last_name(),
        'password': self.fake.password(),
        'email': self.fake.email()
        }
        self.test_user2 = {
        'username': self.fake.user_name(),
        'first_name': self.fake.first_name(),
        'last_name': self.fake.last_name(),
        'password': self.fake.password(),
        'email': self.fake.email()
        }
        self.test_user1 = UserFactory(username='******', password='******')
        self.test_user4 = UserFactory(username='******')


        self.single_bucketlist_url = '/bucketlists/'
        self.all_bucketlists__url = '/bucketlists/'
        self.create_bucketlist_item__url = '/bucketlists/1/items/'
        self.single_bucketlist_item__url = '/bucketlists/1/items/'
Exemplo n.º 8
0
        def test_ratings_from_different_users(self, api_client):
            new_user = UserFactory()
            api_client.force_authenticate(new_user)
            new_recipe = RecipeFactory()

            data = {
                'recipe': new_recipe.id,
                'stars': '5'
            }
            api_client.post(rating_rate_url, data)
            api_client.logout()

            new_user2 = UserFactory()
            api_client.force_authenticate(new_user2)
            data = {
                'recipe': new_recipe.id,
                'stars': '4'
            }
            api_client.post(rating_rate_url, data)

            first_rating = Rating.objects.all().get(author__exact=new_user.id)
            second_rating = Rating.objects.all().get(author__exact=new_user2.id)


            assert Rating.objects.all().count() == 2
            assert first_rating.stars == 5
            assert second_rating.stars== 4
Exemplo n.º 9
0
    def test_parse_post(self):
        response = '''{"comments": {"can_post": 0, "count": 4},
                 "date": 1298365200,
                 "from_id": 55555,
                 "geo": {"coordinates": "55.6745689498 37.8724562529",
                  "place": {"city": "Moskovskaya oblast",
                   "country": "Russian Federation",
                   "title": "Shosseynaya ulitsa, Moskovskaya oblast"},
                  "type": "point"},
                 "id": 465,
                 "likes": {"can_like": 1, "can_publish": 1, "count": 10, "user_likes": 0},
                 "online": 1,
                 "post_source": {"type": "api"},
                 "reply_count": 0,
                 "reposts": {"count": 3, "user_reposted": 0},
                 "text": "qwerty",
                 "to_id": 201164356}
            '''
        instance = Post()
        owner = UserFactory(remote_id=201164356)  # Travis Djangov
        author = UserFactory(remote_id=55555)
        instance.parse(json.loads(response))
        instance.save()

        self.assertTrue(instance.remote_id.startswith('201164356_'))
        self.assertEqual(instance.wall_owner, owner)
        self.assertEqual(instance.author, author)
        self.assertEqual(instance.reply_count, 0)
        self.assertEqual(instance.likes, 10)
        self.assertEqual(instance.reposts, 3)
        self.assertEqual(instance.comments, 4)
        self.assertEqual(instance.text, 'qwerty')
        self.assertTrue(isinstance(instance.date, datetime))
Exemplo n.º 10
0
    def test_parse_comment(self):

        response = '''{"response":[6,
            {"cid":2505,"uid":16271479,"date":1298365200,"text":"Добрый день , кароче такая идея когда опросы создаешь вместо статуса - можно выбрать аудитории опрашиваемых, например только женский или мужской пол могут участвовать (то бишь голосовать в опросе)."},
            {"cid":2507,"uid":16271479,"date":1286105582,"text":"Это уже не практично, имхо.<br>Для этого делайте группу и там опрос, а в группу принимайте тех, кого нужно.","reply_to_uid":16271479,"reply_to_cid":2505},
            {"cid":2547,"uid":2943,"date":1286218080,"text":"Он будет только для групп благотворительных организаций."}]}
            '''
        user = UserFactory(remote_id=USER_ID)
        post = PostFactory(remote_id=POST_ID, wall_owner=user)
        #instance = Comment(post=post)
        instance = CommentFactory(post=post)
        author = UserFactory(remote_id=16271479)
        instance.parse(json.loads(response)['response'][1])
        instance.save()

        self.assertEqual(instance.remote_id, '%s_2505' % USER_ID)
        self.assertEqual(
            instance.text,
            u'Добрый день , кароче такая идея когда опросы создаешь вместо статуса - можно выбрать аудитории опрашиваемых, например только женский или мужской пол могут участвовать (то бишь голосовать в опросе).'
        )
        self.assertEqual(instance.author, author)
        self.assertTrue(isinstance(instance.date, datetime))

        instance = Comment(post=post)
        instance.parse(json.loads(response)['response'][2])
        instance.save()

        self.assertEqual(instance.remote_id, '%s_2507' % USER_ID)
        self.assertEqual(instance.reply_for.remote_id, 16271479)
def test_user_follow():
    user1 = UserFactory()
    user2 = UserFactory()
    user1.follow(user2)

    assert len(user1.following) == 1
    assert user2 in user1.following
def test_user_timeline():
    """Should only return posts from users I'm following"""
    user1 = UserFactory()
    user2 = UserFactory()
    user3 = UserFactory()
    user4 = UserFactory()

    user2_post1 = TextPostFactory()
    user2_post2 = TextPostFactory()
    user3_post1 = PicturePostFactory()
    user4_post1 = TextPostFactory()

    user2.add_post(user2_post1)
    user2.add_post(user2_post2)
    user3.add_post(user3_post1)
    user4.add_post(user4_post1)
    # user1 follows user2 and user3
    user1.follow(user2)
    user1.follow(user3)
    # 2 posts from user2 and 1 from user3
    # post from user4 is excluded
    assert len(user1.get_timeline()) == 3

    assert user4_post1 not in user1.get_timeline()

    # should be sorted by creation timestamp
    assert user1.get_timeline() == [user2_post1, user2_post2, user3_post1]
Exemplo n.º 13
0
def test_create_siteuser():
    count_a = 3
    count_b = 4
    site_a = SiteFactory()
    site_b = SiteFactory()

    assert site_a.domain != site_b.domain

    expected_users_a = [
        SiteUserFactory(site=site_a, user=UserFactory())
        for i in range(count_a)
    ]
    expected_users_b = [
        SiteUserFactory(site=site_b, user=UserFactory())
        for i in range(count_b)
    ]

    found_a = get_users_for_site(site=Site.objects.get(domain=site_a.domain))
    found_b = get_users_for_site(site=Site.objects.get(domain=site_b.domain))

    # May be overkill, but first testing counts, then test ids
    assert found_a.count() == len(expected_users_a)
    assert found_b.count() == len(expected_users_b)

    assert set(found_a.values_list('id', flat=True)) == set(
        [obj.id for obj in expected_users_a])
    assert set(found_b.values_list('id', flat=True)) == set(
        [obj.id for obj in expected_users_b])
Exemplo n.º 14
0
def test_referral_was_found():
    user = UserFactory()
    promoter = UserFactory()
    referral = ReferralFactory(user=user, promoter=promoter)

    assert referral.user.pk == user.pk
    assert referral.user.pk == user.pk
    assert referral.promoter.pk == promoter.pk
 def setUp(self):
     self.admin = UserFactory(username='******', password='******', super_user=True)
     self.user = UserFactory(username='******', password='******')
     self.norm = UserFactory(username='******', password='******')
     self.collab = UserFactory(username='******', password='******')
     self.comp = CompetitionFactory(created_by=self.user, collaborators=[self.collab], published=True)
     for _ in range(5):
         CompetitionParticipantFactory(competition=self.comp)
Exemplo n.º 16
0
        def test_user_cant_update_othes_accounts(self, api_client):
            new_user = UserFactory()
            new_user2 = UserFactory()
            api_client.force_authenticate(new_user2)
            data = {'email': '*****@*****.**', 'name': 'test'}
            response = api_client.patch(new_user.get_absolute_url(), data)

            assert response.status_code == 403
Exemplo n.º 17
0
            def test_follow_post_request(self, api_client):
                author = UserFactory()
                user_followed = UserFactory()
                api_client.force_authenticate(author)

                data = {'user_followed': user_followed.id}
                response = api_client.post(follow_url, data)

                assert response.status_code == 200
Exemplo n.º 18
0
    def test_privacy_mode_user_queries(self):
        """Test API user queries for privacy mode with private fields in query
        """
        admin = UserFactory.create()
        user = UserFactory.create()
        # Add user with fullname 'Public user', privacy mode disabled
        user_with_privacy_disabled = UserFactory(email_addr='*****@*****.**',
                                                 name='publicUser',
                                                 fullname='User',
                                                 privacy_mode=False)
        # Add user with fullname 'Private user', privacy mode enabled
        user_with_privacy_enabled = UserFactory(email_addr='*****@*****.**',
                                                name='privateUser',
                                                fullname='User',
                                                info=dict(container=1,
                                                          avatar='png',
                                                          avatar_url='1png',
                                                          extra='badge1.png'),
                                                privacy_mode=True)

        # When querying with private fields
        query = 'api/user?fullname=User'
        # with no API-KEY, no user with privacy enabled should be returned,
        # even if it matches the query
        # res = self.app.get(query)
        # data = json.loads(res.data)
        # assert len(data) == 1, data
        # public_user = data[0]
        # assert public_user['name'] == 'publicUser', public_user
        # assert 'email_addr' not in public_user.keys(), public_user
        # assert 'id' not in public_user.keys(), public_user
        # assert 'info' not in public_user.keys(), public_user
        #
        # # with a non-admin API-KEY, the result should be the same
        # res = self.app.get(query + '&api_key=' + user.api_key)
        # data = json.loads(res.data)
        # assert len(data) == 1, data
        # public_user = data[0]
        # assert public_user['name'] == 'publicUser', public_user
        # assert 'email_addr' not in public_user.keys(), public_user
        # assert 'id' not in public_user.keys(), public_user
        # assert 'info' not in public_user.keys(), public_user

        # with an admin API-KEY, all the matching results should be returned
        res = self.app.get(query + '&api_key=' + admin.api_key)
        data = json.loads(res.data)
        assert len(data) == 2, data
        public_user = data[0]
        assert public_user['name'] == 'publicUser', public_user
        private_user = data[1]
        assert private_user['name'] == 'privateUser', private_user
        assert private_user[
            'email_addr'] == user_with_privacy_enabled.email_addr, private_user
        assert private_user['id'] == user_with_privacy_enabled.id, private_user
        assert private_user[
            'info'] == user_with_privacy_enabled.info, private_user
Exemplo n.º 19
0
    def setUp(self):

        # Disconnect signals so there's no problem to use UserProfileFactory
        signals.post_save.disconnect(
            dispatch_uid='eff._models.user_profile.create_profile_for_user',
            sender=User)

        # Create a external source
        self.ext_src = ExternalSourceFactory(name='DotprojectMachinalis')

        # Create 2 client user and 2 companies.
        self.company = ClientFactory(name='Fake Client 1',
                                     external_source=self.ext_src)
        user = UserFactory(username='******')
        self.client1 = ClientProfileFactory(user=user, company=self.company)
        user = UserFactory(username='******')
        self.company2 = ClientFactory(name='Fake Client 2',
                                      external_source=self.ext_src)
        self.client2 = ClientProfileFactory(user=user, company=self.company2)

        # Create some commercial documents for company1
        self.billing = BillingFactory(client=self.company,
                                      amount=Decimal('1000'),
                                      date=date(2012, 5, 3),
                                      concept="Billing1 " + self.company.name,
                                      expire_date=date(2012, 5, 30),
                                      payment_date=date(2012, 5, 25))
        self.credit_note = CreditNoteFactory(client=self.company,
                                             amount=Decimal('100'),
                                             date=date(2012, 5, 4),
                                             concept="CreditNote1 " +
                                             self.company.name)
        self.payment = PaymentFactory(client=self.company,
                                      amount=Decimal('1500'),
                                      date=date(2012, 5, 2),
                                      concept="Payment1 " + self.company.name,
                                      status="Notified")

        # Create some commercial documents for company2
        BillingFactory(client=self.company2,
                       amount=Decimal('1200'),
                       date=date(2012, 5, 1),
                       concept="Billing2 " + self.company.name,
                       expire_date=date(2012, 5, 30),
                       payment_date=date(2012, 5, 25))
        CreditNoteFactory(client=self.company2,
                          amount=Decimal('200'),
                          date=date(2012, 5, 2),
                          concept="CreditNote2 " + self.company.name)
        PaymentFactory(client=self.company2,
                       amount=Decimal('1600'),
                       date=date(2012, 5, 7),
                       concept="Payment2 " + self.company.name,
                       status="Tracking")
        self.test_client = TestClient()
Exemplo n.º 20
0
    def setUp(self):
        self.user = UserFactory(username='******')
        self.admin = UserFactory(username='******', super_user=True)
        self.collab = UserFactory(username='******')
        self.normal_user = UserFactory(username='******')
        self.competition = CompetitionFactory(created_by=self.user)
        self.competition.collaborators.add(self.collab)
        self.phase = PhaseFactory(competition=self.competition)

        for _ in range(4):
            self.make_submission()
 def setUp(self):
     self.user = UserFactory(username='******')
     self.admin = UserFactory(username='******', super_user=True)
     self.collab = UserFactory(username='******')
     self.normal_user = UserFactory(username='******')
     self.competition = CompetitionFactory(created_by=self.user)
     self.competition.collaborators.add(self.collab)
     self.phase = PhaseFactory(competition=self.competition)
     self.leaderboard = LeaderboardFactory(competition=self.competition)
     self.column = ColumnFactory(leaderboard=self.leaderboard, key='test')
     self.submission = self.make_submission()
Exemplo n.º 22
0
            def test_author_should_be_added_to_user_followed_followers_list(
                    self, api_client):
                author = UserFactory()
                user_followed = UserFactory()
                api_client.force_authenticate(author)

                data = {'user_followed': user_followed.id}
                api_client.post(follow_url, data)

                assert user_followed.followers.all().get(
                    id__exact=author.id) == author
Exemplo n.º 23
0
        def test_likes_from_different_users(self, api_client):
            new_user = UserFactory()
            api_client.force_authenticate(new_user)
            new_recipe = RecipeFactory()
            data = {'recipe': new_recipe.id}
            api_client.post(like_url, data)
            api_client.logout()

            new_user2 = UserFactory()
            api_client.force_authenticate(new_user2)
            data = {'recipe': new_recipe.id}
            api_client.post(like_url, data)

            assert new_recipe.likes.all().count() == 2
Exemplo n.º 24
0
 def setUp(self):
     self.user = UserFactory()
     self.up = UserProfileFactory(user=self.user)
     self.client = Client()
     self.client.login(username=self.user.username, password="******")
     self.country = CountryFactory()
     self.school = SchoolFactory()
Exemplo n.º 25
0
        def test_rating_page_render(self, api_client):
            new_user = UserFactory()
            api_client.force_authenticate(new_user)

            response = api_client.get(rating_rate_url) 

            assert response.status_code == 405
Exemplo n.º 26
0
        def test_followed_users_recipes_page_should_render(self, api_client):
            new_user = UserFactory()
            api_client.force_authenticate(new_user)

            response = api_client.get(followed_users_recipes_url)

            assert response.status_code == 200
Exemplo n.º 27
0
        def test_not_author_cant_delete_recipe(self, api_client):
            new_recipe = RecipeFactory()
            random_user = UserFactory()
            api_client.force_authenticate(random_user)
            response = api_client.delete(new_recipe.get_absolute_url())

            assert response.status_code == 403
Exemplo n.º 28
0
    def handle(self, *args, **options):
        count = 1
        if options['amount']:
            count = options['amount']

        for i in range(count):
            try:
                # Setup a temp user
                temp_user = UserFactory()

                temp_title = "New Competition_{}".format(str(uuid.uuid4()))
                temp_desc = temp_title + "'s description"
                # Setup a new comp
                new_comp = Competition.objects.create(
                    title=temp_title,
                    description=temp_desc,
                    created_by=temp_user.username,
                    remote_id=999,
                    published=True
                )
                new_comp.created_when = timezone.now() + datetime.timedelta(days=random.randint(-15, 15))
                new_comp.save()
                print(colored('Successfully created new user and competition: {0}, {1}'.format(temp_user, new_comp),
                              'green'))
            except:
                print(colored('Failed to create competition', 'red'))
Exemplo n.º 29
0
 def setUp(self):
     self.program = ProgramFactory(
         reporting_period_start=datetime.date(2018, 1, 1),
         reporting_period_end=datetime.date(2019, 1, 1),
     )
     self.indicator = IndicatorFactory(
         program=self.program,
         target_frequency=Indicator.MID_END,
     )
     PeriodicTargetFactory(
         indicator=self.indicator,
         start_date=datetime.date(2018, 1, 1),
         end_date=datetime.date(2018, 12, 31),
     )
     self.result = ResultFactory(
         indicator=self.indicator,
         date_collected=datetime.date(2017, 1, 1),
         achieved=42,
         record_name='My Test Record',
         evidence_url='http://my_evidence_url',
     )
     self.count = 1
     self.count += str(self.indicator.pk).count('42') * 2
     self.count += str(self.indicator.name).count('42')
     self.count += str(self.result.pk).count('42')
     self.user = UserFactory(first_name="FN", last_name="LN", username="******", is_superuser=True)
     self.user.set_password('password')
     self.user.save()
     self.tola_user = TolaUserFactory(user=self.user)
     self.client.login(username='******', password='******')
Exemplo n.º 30
0
def _create_fake_user():
    try:
        return UserFactory()
    except:
        print(colored("Could not create fake user! Operation failed!", 'red'))
        raise ObjectDoesNotExist(
            "Could not create fake user! Operation failed!")