|
| 1 | +package test |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "testing" |
| 6 | + |
| 7 | + "github.com/stretchr/testify/require" |
| 8 | + v1pb "github.com/usememos/memos/proto/gen/api/v1" |
| 9 | +) |
| 10 | + |
| 11 | +func TestCreateAttachment(t *testing.T) { |
| 12 | + ts := NewTestService(t) |
| 13 | + defer ts.Cleanup() |
| 14 | + ctx := context.Background() |
| 15 | + |
| 16 | + user, err := ts.CreateRegularUser(ctx, "test_user") |
| 17 | + require.NoError(t, err) |
| 18 | + userCtx := ts.CreateUserContext(ctx, user.ID) |
| 19 | + |
| 20 | + // Test case 1: Create attachment with empty type but known extension |
| 21 | + t.Run("EmptyType_KnownExtension", func(t *testing.T) { |
| 22 | + attachment, err := ts.Service.CreateAttachment(userCtx, &v1pb.CreateAttachmentRequest{ |
| 23 | + Attachment: &v1pb.Attachment{ |
| 24 | + Filename: "test.png", |
| 25 | + Content: []byte("fake png content"), |
| 26 | + }, |
| 27 | + }) |
| 28 | + require.NoError(t, err) |
| 29 | + require.Equal(t, "image/png", attachment.Type) |
| 30 | + }) |
| 31 | + |
| 32 | + // Test case 2: Create attachment with empty type and unknown extension, but detectable content |
| 33 | + t.Run("EmptyType_UnknownExtension_ContentSniffing", func(t *testing.T) { |
| 34 | + // PNG magic header: 89 50 4E 47 0D 0A 1A 0A |
| 35 | + pngContent := []byte{0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A} |
| 36 | + attachment, err := ts.Service.CreateAttachment(userCtx, &v1pb.CreateAttachmentRequest{ |
| 37 | + Attachment: &v1pb.Attachment{ |
| 38 | + Filename: "test.unknown", |
| 39 | + Content: pngContent, |
| 40 | + }, |
| 41 | + }) |
| 42 | + require.NoError(t, err) |
| 43 | + require.Equal(t, "image/png", attachment.Type) |
| 44 | + }) |
| 45 | + |
| 46 | + // Test case 3: Empty type, unknown extension, random content -> fallback to application/octet-stream |
| 47 | + t.Run("EmptyType_Fallback", func(t *testing.T) { |
| 48 | + randomContent := []byte{0x00, 0x01, 0x02, 0x03} |
| 49 | + attachment, err := ts.Service.CreateAttachment(userCtx, &v1pb.CreateAttachmentRequest{ |
| 50 | + Attachment: &v1pb.Attachment{ |
| 51 | + Filename: "test.data", |
| 52 | + Content: randomContent, |
| 53 | + }, |
| 54 | + }) |
| 55 | + require.NoError(t, err) |
| 56 | + require.Equal(t, "application/octet-stream", attachment.Type) |
| 57 | + }) |
| 58 | +} |
0 commit comments