| 1 | package control |
| 2 | |
| 3 | import ( |
| 4 | "errors" |
| 5 | "math" |
| 6 | "os" |
| 7 | "path/filepath" |
| 8 | "testing" |
| 9 | |
| 10 | "reasonix/internal/config" |
| 11 | ) |
| 12 | |
| 13 | func TestAttachmentStreamLimitCountsActualBytesAndCleansOversize(t *testing.T) { |
| 14 | for _, tc := range []struct { |
| 15 | name string |
| 16 | limit, size int64 |
| 17 | tooLarge bool |
| 18 | }{ |
| 19 | {"below", 4, 3, false}, |
| 20 | {"exact", 4, 4, false}, |
| 21 | {"plus one", 4, 5, true}, |
| 22 | {"long stream", 4, 1 << 20, true}, |
| 23 | {"unlimited", 0, 20, false}, |
| 24 | {"maximum integer", math.MaxInt64, 20, false}, |
| 25 | } { |
| 26 | t.Run(tc.name, func(t *testing.T) { |
| 27 | root := t.TempDir() |
| 28 | reader := &attachmentPatternReader{remaining: tc.size} |
| 29 | path, err := SaveAttachmentStreamInRoot(t.Context(), root, "app.apk", reader, config.AttachmentLimit{Bytes: tc.limit, Source: "user"}) |
| 30 | if tc.tooLarge { |
| 31 | var limitErr *AttachmentStreamLimitError |
| 32 | if !errors.As(err, &limitErr) || limitErr.LimitBytes != tc.limit || limitErr.LimitSource != "user" || path != "" { |
| 33 | t.Fatalf("path=%s err=%v", path, err) |
| 34 | } |
| 35 | if read := tc.size - reader.remaining; read != tc.limit+1 { |
| 36 | t.Fatalf("consumed=%d, want only boundary probe=%d", read, tc.limit+1) |
| 37 | } |
| 38 | entries, readErr := os.ReadDir(filepath.Join(root, ".reasonix", "attachments")) |
| 39 | if readErr != nil || len(entries) != 0 { |
| 40 | t.Fatalf("partial files=%v err=%v", entries, readErr) |
| 41 | } |
| 42 | return |
| 43 | } |
| 44 | if err != nil { |
| 45 | t.Fatal(err) |
| 46 | } |
| 47 | info, err := os.Stat(filepath.Join(root, filepath.FromSlash(path))) |
| 48 | if err != nil || info.Size() != tc.size { |
| 49 | t.Fatalf("file=%v err=%v", info, err) |
| 50 | } |
| 51 | }) |
| 52 | } |
| 53 | } |
| 54 |