Skip to content

Commit

Permalink
feat(forum_files): manage object throught admin panels only
Browse files Browse the repository at this point in the history
  • Loading branch information
vincentporte committed Sep 5, 2023
1 parent 22cc18b commit 7ef790e
Show file tree
Hide file tree
Showing 2 changed files with 77 additions and 0 deletions.
23 changes: 23 additions & 0 deletions lacommunaute/forum_file/admin.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
from django.contrib import admin
from django.utils.html import format_html

from lacommunaute.forum_file.models import PublicFile


@admin.register(PublicFile)
class PublicFileAdmin(admin.ModelAdmin):
list_display = ("user", "created", "file_url", "keywords")
list_filter = ("created",)
raw_id_fields = ("user",)
search_fields = ("user__email", "keywords", "file__name")
fields = ("file", "keywords")

def save_model(self, request, obj, form, change):
if not obj.user_id:
obj.user = request.user
obj.save()

def file_url(self, obj):
return format_html(f'<a href="{obj.get_file_url()}" target="_blank">{obj.get_file_url()}</a>')

file_url.short_description = "URL du fichier"
54 changes: 54 additions & 0 deletions lacommunaute/forum_file/tests/test_admin.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
import os
from io import BytesIO

import boto3
import faker
import pytest
from django.conf import settings
from django.core.files.uploadedfile import SimpleUploadedFile
from django.urls import reverse
from moto import mock_s3
from PIL import Image

from lacommunaute.forum_file.models import PublicFile
from lacommunaute.users.factories import UserFactory


fake = faker.Faker()

# https://docs.getmoto.org/en/latest/docs/services/s3.html
# Note that this only works if the environment variable is set before the mock is initialized.
os.environ["MOTO_S3_CUSTOM_ENDPOINTS"] = settings.AWS_S3_ENDPOINT_URL


@pytest.fixture(name="superuser")
def superuser_fixture():
return UserFactory(is_superuser=True, is_staff=True)


@pytest.fixture(name="image_content")
def image_content_fixture():
img = Image.new("RGB", (1, 1), color="white")
buffer = BytesIO()
img.save(buffer, format="JPEG")
return buffer.getvalue()


@mock_s3
def test_file_is_saved_with_logged_user(client, db, superuser, image_content):
conn = boto3.client("s3", endpoint_url=settings.AWS_S3_ENDPOINT_URL, region_name="us-east-1")
conn.create_bucket(Bucket=settings.AWS_STORAGE_BUCKET_NAME_PUBLIC)
client.force_login(superuser)
not_the_logged_in_user = UserFactory()

response = client.post(
reverse("admin:forum_file_publicfile_add"),
{
"file": SimpleUploadedFile("test.jpg", image_content, content_type="image/jpeg"),
"user": not_the_logged_in_user.id,
"keywords": fake.words(3),
},
)
assert response.status_code == 302
file = PublicFile.objects.get()
assert file.user == superuser

0 comments on commit 7ef790e

Please sign in to comment.