예제 #1
0
def test_apiview_get_multiple(rf, no_extra_users):
    """Tests retrieving multiple objects using the API."""
    view = UserAPIView.as_view()
    UserFactory.create(username='******')

    request = create_api_request(rf)

    response = view(request)
    response_data = json.loads(response.content)

    # Response should contain a 1-item list
    assert response.status_code == 200
    assert isinstance(response_data, dict)
    assert 'count' in response_data
    assert 'models' in response_data
    assert len(response_data['models']) == User.objects.count()

    # Let's add more users
    UserFactory.create_batch(5)

    response = view(request)
    response_data = json.loads(response.content)

    assert response.status_code == 200
    assert isinstance(response_data, dict)
    assert 'count' in response_data
    assert 'models' in response_data
    assert len(response_data['models']) == User.objects.count()

    # Let's add even more users to test pagination
    UserFactory.create_batch(5)

    response = view(request)
    response_data = json.loads(response.content)

    # First page is full
    assert response.status_code == 200
    assert isinstance(response_data, dict)
    assert 'count' in response_data
    assert 'models' in response_data
    assert len(response_data['models']) == 10

    request = create_api_request(rf, url='/?p=2')
    response = view(request)
    response_data = json.loads(response.content)

    # Second page constains a single user
    assert response.status_code == 200
    assert isinstance(response_data, dict)
    assert 'count' in response_data
    assert 'models' in response_data
    assert len(response_data['models']) == User.objects.count() - 10
예제 #2
0
def generate() -> None:
    """
    Generates some initial records in database
    """
    from tests.factories import UserFactory, ActionFactory, MessageFactory, CostFactory
    db.connect()
    db.create_tables([db_models.User, db_models.Cost, db_models.Action, db_models.Photo, db_models.Message])

    # will generate the whole database by chain of subfactories
    UserFactory.create_batch(size=5)
    ActionFactory.create_batch(size=5)
    MessageFactory.create_batch(size=5)
    CostFactory.create_batch(size=5)
    click.secho("\nGeneration done!", fg='green')
    db.close()
예제 #3
0
def test_update_editor_follows_signal(client, factory, reverse):
    m1, m2 = factory.create_batch(2)
    u1, u2, u3, u4 = UserFactory.create_batch(4)

    if not reverse:
        for user in [u1, u2, u3, u4]:
            user.groups.add(m1.editors_group, m2.editors_group)
        for user in [u3, u4]:
            user.groups.remove(m1.editors_group)
        for user in [u1, u2, u3, u4]:
            user.groups.remove(m2.editors_group)

    else:
        g = Group.objects.filter(name=m1.editors_group).get()
        g.user_set.add(u1, u2, u3, u4)
        g.user_set.remove(u3, u4)

    assert is_following(u1, m1)
    assert is_following(u2, m1)
    assert not is_following(u3, m1)
    assert not is_following(u4, m1)
    assert not is_following(u1, m2)
    assert not is_following(u2, m2)
    assert not is_following(u3, m2)
    assert not is_following(u4, m2)

    # Test clearing
    if reverse:
        u1.groups.clear()
    else:
        g = Group.objects.filter(name=m1.editors_group).get()
        g.user_set.clear()

    assert not is_following(u1, m1)
예제 #4
0
def test_get_receivers(factory, action):
    u1, u2, u3, u4 = UserFactory.create_batch(4)
    for user in [u1, u2]:
        user.user_profile.receive_newsletter = True
        user.user_profile.save()
        if action == SendActionChoices.STAFF:
            user.is_staff = True
            user.save()

    if factory == ChallengeFactory:
        obj = factory(creator=u1)
        obj2 = factory(creator=u2)
    elif factory in [AlgorithmFactory, ReaderStudyFactory]:
        obj = factory()
        obj2 = factory()
        obj.add_editor(u1)
        obj2.add_editor(u2)

    receivers = get_receivers(action)

    assert len(receivers) == 2
    for user in [u1, u2]:
        assert user in receivers
    for user in [u3, u4]:
        assert user not in receivers
예제 #5
0
def test_get_users(db: Session, client: TestClient, http_basic_auth: HTTPBasicAuth):
    existing_users = user_crud.get_multi(db)
    users = UserFactory.create_batch(3)
    response = client.get('/users', auth=http_basic_auth)
    assert response.status_code == status.HTTP_200_OK

    actual_users = UserListSchema(__root__=existing_users + users)
    retrieved_users = UserListSchema.parse_raw(response.text)
    assert actual_users == retrieved_users
예제 #6
0
 def test_dispatch_event_with_backends(self):
     users = UserFactory.create_batch(size=5)
     self.assertEqual(0, Event.objects.filter(verb=CONFIRMED_EVENT).count())
     stuff = StuffFactory()
     stuff.confirm()
     self.assertEqual(1, Event.objects.filter(verb=CONFIRMED_EVENT).count())
     event = Event.objects.filter(verb=CONFIRMED_EVENT).first()
     self.assertTrue(isinstance(event.handler(), ConfirmedHandler))
     self.assertEqual(ConfirmedHandler.title, event.title())
     self.assertTrue(event.notified)
     self.assertEqual(len(users), Notification.objects.all().count())
def main(num_manufacturers, num_items_per_man, num_orders):
    mans = ManufacturerFactory.create_batch(num_manufacturers)
    print(f"Created {num_manufacturers} Manufacturers")

    items = list(
        chain.from_iterable([
            ItemFactory.create_batch(num_items_per_man, manufacturer=man)
            for man in mans
        ]))
    print(f"Created {len(items)} Items")

    users = UserFactory.create_batch(50)
    for _ in range(0, num_orders):
        num_items = random.randint(5, 20)
        user = random.choice(users)
        OrderFactory.create(user=user, items=random.sample(items, num_items))
    print(f"Created {num_orders} Orders")
예제 #8
0
    def handle(self, *args, **options):
        call_command("reset_db", "--noinput")
        call_command("migrate")

        library = LibraryFactory()
        UserFactory(username="******",
                    email="*****@*****.**",
                    password="******",
                    is_superuser=True)

        users = UserFactory.create_batch(2, is_staff=False)

        GroupFactory.create_batch(5)

        for author in AuthorFactory.create_batch(10):
            for book in BookFactory.create_batch(5,
                                                 author=author,
                                                 library=library):
                BookLoanFactory(book=book, borrower=choice(users))

        self.stdout.write("All Data reset")
예제 #9
0
def test_email_content(settings):
    # Override the celery settings
    settings.task_eager_propagates = (True,)
    settings.task_always_eager = (True,)

    email = EmailFactory(subject="Test email", body="Test content")
    u1, u2 = UserFactory.create_batch(2)
    for user in [u1, u2]:
        user.user_profile.receive_newsletter = True
        user.user_profile.save()

    assert len(mail.outbox) == 0

    send_bulk_email(action=SendActionChoices.MAILING_LIST, email_pk=email.pk)

    assert len(mail.outbox) == 2
    email.refresh_from_db()
    assert email.sent

    for m in mail.outbox:
        assert (
            m.subject
            == f"[{Site.objects.get_current().domain.lower()}] Test email"
        )
        assert "Test content" in m.body
        if m.to == [u1.email]:
            assert reverse(
                "profile-update", kwargs={"username": u1.username}
            ) in str(m.alternatives)
        else:
            assert reverse(
                "profile-update", kwargs={"username": u2.username}
            ) in str(m.alternatives)

    # check that email sending task is idempotent
    mail.outbox.clear()
    send_bulk_email(action=SendActionChoices.MAILING_LIST, email_pk=email.pk)
    assert len(mail.outbox) == 0
예제 #10
0
    def create_factories(self):
        super().create_factories()
        u1, u2 = UserFactory.create_batch(2, with_unix_account=True)
        inconsistent = UserFactory.create(with_unix_account=True, email=None)

        p_dummy = PropertyGroupFactory.create(name='group_without_grants')
        pg_member = PropertyGroupFactory.create(
            name='member', granted={'mail', 'ldap_login_enabled'})

        UserWithMembershipFactory.create(membership__group=p_dummy,
                                         with_unix_account=True)
        for user in [u1, u2, inconsistent]:
            MembershipFactory.create(group=pg_member, user=user)

        MembershipFactory.create(
            user=inconsistent,
            group=PropertyGroupFactory.create(
                name='some_weird_group',
                granted={
                    'mail'
                },  # weird, because grants mail, but not ldap_login_enabled
            ),
        )
예제 #11
0
def test_post_authors_permissions_signal(client, reverse):
    p1, p2 = PostFactory.create_batch(2)
    u1, u2, u3, u4 = UserFactory.create_batch(4)

    # Remove permissions from the default created user
    p1.authors.clear()
    p2.authors.clear()

    if reverse:
        for user in [u1, u2, u3, u4]:
            user.blog_authors.add(p1, p2)
        for user in [u3, u4]:
            user.blog_authors.remove(p1, p2)
        for user in [u1, u2]:
            user.blog_authors.remove(p2)
    else:
        # Test that adding authors works
        p1.authors.add(u1, u2, u3, u4)
        # Test that removing authors works
        p1.authors.remove(u3, u4)

    assert get_users_with_set_perms(p1) == {
        u1: {"change_post"},
        u2: {"change_post"},
    }
    assert get_users_with_set_perms(p2) == {}

    # Test clearing
    if reverse:
        u1.blog_authors.clear()
        u2.blog_authors.clear()
    else:
        p1.authors.clear()

    assert get_users_with_set_perms(p1) == {}
    assert get_users_with_set_perms(p2) == {}
예제 #12
0
def test_get_users(db: Session):
    actual_users = UserFactory.create_batch(3)
    retrieved_users = user_crud.get_multi(db)
    assert actual_users == retrieved_users
예제 #13
0
 def create_factories(self):
     super().create_factories()
     self.group = PropertyGroupFactory.create()
     self.user, self.processor = UserFactory.create_batch(2)
예제 #14
0
 def make_fake_users(count=1, is_staff=False):
     if count == 1:
         return UserFactory(is_staff=is_staff)
     else:
         return UserFactory.create_batch(count, is_staff=is_staff)
예제 #15
0
 def create_factories(self):
     super().create_factories()
     UserFactory.create_batch(5)
예제 #16
0
 def test_get_export_users(self):
     UserFactory.create_batch(size=20)
     with self.login(self.user):
         self.get("backoffice:user-export")
     self.response_200()
예제 #17
0
def user_data(session):
    return UserFactory.create_batch(5)