-
Notifications
You must be signed in to change notification settings - Fork 27
Expand file tree
/
Copy pathExportActionPerformanceTest.php
More file actions
596 lines (491 loc) · 21 KB
/
Copy pathExportActionPerformanceTest.php
File metadata and controls
596 lines (491 loc) · 21 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
<?php
/*
* Copyright (c) 2025-2026 Netresearch DTT GmbH
* SPDX-License-Identifier: AGPL-3.0-only
*/
declare(strict_types=1);
namespace Tests\Performance;
use App\Controller\Controlling\ExportAction;
use App\Entity\Activity;
use App\Entity\Customer;
use App\Entity\Entry;
use App\Entity\Project;
use App\Entity\User;
use App\Service\ExportService;
use DateTime;
use PHPUnit\Framework\Attributes\AllowMockObjectsWithoutExpectations;
use PHPUnit\Framework\TestCase;
use ReflectionClass;
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBag;
use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\KernelInterface;
use Symfony\Component\Stopwatch\Stopwatch;
use function in_array;
use function is_array;
use function sprintf;
use function strlen;
use const STDERR;
/**
* Performance benchmarks for ExportAction (PhpSpreadsheet processing).
*
* Tests the complete export pipeline including Excel generation,
* focusing on memory usage and processing time for different data volumes.
*
* @group performance
*
* @internal
*
* @coversNothing
*/
#[AllowMockObjectsWithoutExpectations]
final class ExportActionPerformanceTest extends TestCase
{
private Stopwatch $stopwatch;
/**
* @var array<string, int>
*/
private array $performanceBaselines;
private string $tempDir;
protected function setUp(): void
{
$this->stopwatch = new Stopwatch();
$this->setupPerformanceBaselines();
$this->tempDir = sys_get_temp_dir() . '/export_performance_test_' . uniqid();
if (!is_dir($this->tempDir)) {
mkdir($this->tempDir, 0o777, true);
}
}
protected function tearDown(): void
{
// Clean up temporary files recursively (the dir contains a `public/` subdir).
if (is_dir($this->tempDir)) {
new Filesystem()->remove($this->tempDir);
}
}
/**
* Performance baseline thresholds for ExportAction.
*/
private function setupPerformanceBaselines(): void
{
$this->performanceBaselines = [
'small_excel_export' => 1000, // 1000ms for 50 entries with Excel generation (Docker environment)
'medium_excel_export' => 4500, // 4.5s for 500 entries with Excel generation (Docker environment)
'large_excel_export' => 11000, // 11s for 5000 entries with Excel generation (Docker environment)
'excel_memory_threshold' => 100 * 1024 * 1024, // 100MB for Excel processing
'template_loading' => 100, // 100ms for template loading
'statistics_calculation' => 200, // 200ms for statistics calculation
];
}
/**
* Test small dataset Excel export (baseline scenario).
*
* @covers \App\Controller\Controlling\ExportAction::__invoke
*/
public function testSmallDatasetExcelExportPerformance(): void
{
$exportAction = $this->createExportActionWithMocks(50, false);
$request = $this->createExportRequest(1, 2025, 8);
$this->stopwatch->start('small_excel_export');
$memoryBefore = memory_get_usage(true);
$response = $exportAction($request);
$memoryAfter = memory_get_usage(true);
$event = $this->stopwatch->stop('small_excel_export');
// Performance assertions
$duration = $event->getDuration();
$memoryUsage = $memoryAfter - $memoryBefore;
self::assertLessThanOrEqual(
$this->performanceBaselines['small_excel_export'],
$duration,
"Small Excel export took {$duration}ms, expected <= {$this->performanceBaselines['small_excel_export']}ms",
);
self::assertLessThan(
$this->performanceBaselines['excel_memory_threshold'] / 4, // 25MB for small dataset
$memoryUsage,
'Small Excel export used ' . number_format($memoryUsage / 1024 / 1024, 2) . 'MB memory',
);
// Response type is guaranteed by method return type
self::assertSame(200, $response->getStatusCode());
$contentType = $response->headers->get('Content-Type');
self::assertNotNull($contentType, 'Content-Type header should not be null');
self::assertStringContainsString(
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
$contentType,
);
$this->logPerformanceMetric('Small Excel Export', $duration, $memoryUsage, 50);
}
/**
* Test medium dataset Excel export.
*
* @covers \App\Controller\Controlling\ExportAction::__invoke
*/
public function testMediumDatasetExcelExportPerformance(): void
{
$exportAction = $this->createExportActionWithMocks(500, false);
$request = $this->createExportRequest(1, 2025, 8);
$this->stopwatch->start('medium_excel_export');
$memoryBefore = memory_get_usage(true);
$exportAction($request);
$memoryAfter = memory_get_usage(true);
$event = $this->stopwatch->stop('medium_excel_export');
// Performance assertions
$duration = $event->getDuration();
$memoryUsage = $memoryAfter - $memoryBefore;
self::assertLessThan(
$this->performanceBaselines['medium_excel_export'],
$duration,
"Medium Excel export took {$duration}ms, expected < {$this->performanceBaselines['medium_excel_export']}ms",
);
self::assertLessThan(
$this->performanceBaselines['excel_memory_threshold'] / 2, // 50MB for medium dataset
$memoryUsage,
'Medium Excel export used ' . number_format($memoryUsage / 1024 / 1024, 2) . 'MB memory',
);
// Response type is guaranteed by method return type
$this->logPerformanceMetric('Medium Excel Export', $duration, $memoryUsage, 500);
}
/**
* Test large dataset Excel export (stress test).
*
* @covers \App\Controller\Controlling\ExportAction::__invoke
*/
public function testLargeDatasetExcelExportPerformance(): void
{
$exportAction = $this->createExportActionWithMocks(5000, false);
$request = $this->createExportRequest(1, 2025, 8);
$this->stopwatch->start('large_excel_export');
$memoryBefore = memory_get_usage(true);
$exportAction($request);
$memoryAfter = memory_get_usage(true);
$event = $this->stopwatch->stop('large_excel_export');
// Performance assertions
$duration = $event->getDuration();
$memoryUsage = $memoryAfter - $memoryBefore;
self::assertLessThan(
$this->performanceBaselines['large_excel_export'],
$duration,
"Large Excel export took {$duration}ms, expected < {$this->performanceBaselines['large_excel_export']}ms",
);
self::assertLessThan(
$this->performanceBaselines['excel_memory_threshold'],
$memoryUsage,
'Large Excel export used ' . number_format($memoryUsage / 1024 / 1024, 2) . 'MB memory',
);
// Response type is guaranteed by method return type
$this->logPerformanceMetric('Large Excel Export', $duration, $memoryUsage, 5000);
}
/**
* Test Excel export with ticket enrichment performance.
*
* @covers \App\Controller\Controlling\ExportAction::__invoke
*/
public function testExcelExportWithTicketEnrichmentPerformance(): void
{
$exportAction = $this->createExportActionWithMocks(200, true);
$request = $this->createExportRequest(1, 2025, 8, true, true);
$this->stopwatch->start('excel_export_enriched');
$memoryBefore = memory_get_usage(true);
$exportAction($request);
$memoryAfter = memory_get_usage(true);
$event = $this->stopwatch->stop('excel_export_enriched');
// Performance assertions - enrichment should add some overhead
$duration = $event->getDuration();
$memoryUsage = $memoryAfter - $memoryBefore;
self::assertLessThan(
$this->performanceBaselines['medium_excel_export'], // Should still be within medium baseline
$duration,
"Excel export with enrichment took {$duration}ms",
);
// Response type is guaranteed by method return type
$this->logPerformanceMetric('Excel Export with Ticket Enrichment', $duration, $memoryUsage, 200);
}
/**
* Test statistics calculation performance (holidays/sick days).
*
* @covers \App\Controller\Controlling\ExportAction::__invoke
*/
public function testStatisticsCalculationPerformance(): void
{
$exportAction = $this->createExportActionWithMocks(1000, false, true);
$request = $this->createExportRequest(1, 2025, 8);
$this->stopwatch->start('statistics_calculation');
$memoryBefore = memory_get_usage(true);
$exportAction($request);
$memoryAfter = memory_get_usage(true);
$event = $this->stopwatch->stop('statistics_calculation');
// Statistics processing should be efficient
$duration = $event->getDuration();
$memoryUsage = $memoryAfter - $memoryBefore;
// Should handle statistics without significant performance impact
self::assertLessThan(
$this->performanceBaselines['large_excel_export'],
$duration,
"Export with statistics took {$duration}ms",
);
// Response type is guaranteed by method return type
$this->logPerformanceMetric('Export with Statistics Calculation', $duration, $memoryUsage, 1000);
}
/**
* Test Excel file size scaling with dataset size.
*/
public function testExcelFileSizeScaling(): void
{
$sizes = [50, 200, 1000];
$fileSizes = [];
foreach ($sizes as $size) {
$exportAction = $this->createExportActionWithMocks($size, false);
$request = $this->createExportRequest(1, 2025, 8);
$response = $exportAction($request);
$content = $response->getContent();
$fileSize = false !== $content ? strlen($content) : 0;
$fileSizes[$size] = $fileSize;
}
// File size should scale reasonably (not exponentially)
self::assertLessThan(
$fileSizes[200] * 10, // Allow reasonable overhead but not exponential growth
$fileSizes[1000],
'Excel file size scaling appears excessive: 200 entries = ' .
number_format($fileSizes[200] / 1024, 2) . 'KB, 1000 entries = ' .
number_format($fileSizes[1000] / 1024, 2) . 'KB',
);
// Log file size scaling
foreach ($fileSizes as $size => $fileSize) {
$this->logPerformanceMetric('File Size Scaling', 0, $fileSize, $size);
}
}
/**
* Test memory cleanup after Excel generation.
*/
public function testMemoryCleanupAfterExcelGeneration(): void
{
$exportAction = $this->createExportActionWithMocks(500, false);
$request = $this->createExportRequest(1, 2025, 8);
$memoryBefore = memory_get_usage(true);
// Generate Excel file
$response = $exportAction($request);
$memoryPeak = memory_get_peak_usage(true);
// Force garbage collection
unset($response);
gc_collect_cycles();
$memoryAfter = memory_get_usage(true);
$memoryDifference = $memoryAfter - $memoryBefore;
$peakUsage = $memoryPeak - $memoryBefore;
// Memory should be mostly cleaned up
self::assertLessThan(
$peakUsage / 2, // Should retain less than 50% of peak memory usage
$memoryDifference,
'Memory not properly cleaned up. Peak usage: ' .
number_format($peakUsage / 1024 / 1024, 2) .
'MB, Remaining: ' .
number_format($memoryDifference / 1024 / 1024, 2) . 'MB',
);
$this->logPerformanceMetric('Memory Cleanup Test', 0, $memoryDifference, 500);
}
/**
* Create ExportAction with mocked dependencies.
*/
private function createExportActionWithMocks(int $entryCount, bool $withTickets = false, bool $withStats = false): ExportAction
{
$exportAction = new ExportAction();
// Mock export service
$exportService = $this->createMock(ExportService::class);
$exportService->method('exportEntries')
->willReturn($this->generateTestEntries($entryCount, $withTickets, $withStats));
$exportService->method('enrichEntriesWithTicketInformation')
->willReturnCallback(static function ($userId, $entries) {
return $entries; // Return entries as-is for performance testing
});
$exportService->method('getUsername')
->willReturn('perftest');
$exportAction->setExportService($exportService);
// Mock kernel for template file path
$kernel = $this->createMock(KernelInterface::class);
$kernel->method('getProjectDir')
->willReturn($this->createMockTemplateFile());
// Use reflection to set private properties
$reflection = new ReflectionClass($exportAction);
$kernelProperty = $reflection->getProperty('kernel');
$kernelProperty->setValue($exportAction, $kernel);
// Mock parameters
$params = new ParameterBag([
'app_show_billable_field_in_export' => false,
]);
$paramsProperty = $reflection->getProperty('params');
$paramsProperty->setValue($exportAction, $params);
// Mock container to prevent initialization errors
$container = $this->createMock(\Symfony\Component\DependencyInjection\ContainerInterface::class);
// Mock session service
$session = $this->createMock(\Symfony\Component\HttpFoundation\Session\SessionInterface::class);
$session->method('has')->willReturn(true);
// Mock security authorization checker
$authChecker = $this->createMock(\Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface::class);
$authChecker->method('isGranted')->willReturn(true);
// Mock security token storage with user
$user = $this->createMock(User::class);
$user->method('getId')->willReturn(1);
$token = $this->createMock(\Symfony\Component\Security\Core\Authentication\Token\TokenInterface::class);
$token->method('getUser')->willReturn($user);
$tokenStorage = $this->createMock(\Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface::class);
$tokenStorage->method('getToken')->willReturn($token);
$container->method('has')->willReturn(true);
$container->method('get')->willReturnMap([
['session', \Symfony\Component\DependencyInjection\ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE, $session],
['security.authorization_checker', \Symfony\Component\DependencyInjection\ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE, $authChecker],
['security.token_storage', \Symfony\Component\DependencyInjection\ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE, $tokenStorage],
]);
$exportAction->setContainer($container);
return $exportAction;
}
/**
* Create a mock Excel template file for testing.
*/
private function createMockTemplateFile(): string
{
// Create public directory structure to match real application
$publicDir = $this->tempDir . '/public';
if (!is_dir($publicDir)) {
mkdir($publicDir, 0o777, true);
}
$templatePath = $publicDir . '/template.xlsx';
// Create a minimal Excel template
$spreadsheet = new \PhpOffice\PhpSpreadsheet\Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
// Set up headers similar to the real template
$sheet->setCellValue('A2', 'Date');
$sheet->setCellValue('B2', 'Start');
$sheet->setCellValue('C2', 'End');
$sheet->setCellValue('D2', 'Customer');
$sheet->setCellValue('E2', 'Project');
$sheet->setCellValue('F2', 'Activity');
$sheet->setCellValue('G2', 'Description');
$sheet->setCellValue('H2', 'Ticket');
$sheet->setCellValue('I2', 'Duration');
$sheet->setCellValue('J2', 'User');
$sheet->setCellValue('K2', 'External Reporter');
$sheet->setCellValue('L2', 'External Summary');
$sheet->setCellValue('M2', 'External Labels');
// Create additional sheets for statistics
$spreadsheet->createSheet();
$spreadsheet->createSheet();
$writer = new \PhpOffice\PhpSpreadsheet\Writer\Xlsx($spreadsheet);
$writer->save($templatePath);
return $this->tempDir;
}
/**
* Create test request for export.
*/
private function createExportRequest(int $userId, int $year, int $month, bool $billable = false, bool $ticketTitles = false): Request
{
$request = new Request();
$request->query->set('userid', (string) $userId);
$request->query->set('year', (string) $year);
$request->query->set('month', (string) $month);
$request->query->set('billable', $billable ? '1' : '0');
$request->query->set('tickettitles', $ticketTitles ? '1' : '0');
// Mock session for authentication check
$session = $this->createMock(\Symfony\Component\HttpFoundation\Session\SessionInterface::class);
$session->method('get')->willReturn($userId);
$request->setSession($session);
return $request;
}
/**
* Generate test entries for performance testing.
*/
/**
* @return array<int, Entry>
*/
private function generateTestEntries(int $count, bool $withTickets = false, bool $withStats = false): array
{
$entries = [];
$user = $this->createTestUser();
$customer = $this->createTestCustomer();
$project = $this->createTestProject($customer);
$activity = $this->createTestActivity($withStats);
for ($i = 0; $i < $count; ++$i) {
$entry = new Entry();
$entry->setUser($user);
$entry->setCustomer($customer);
$entry->setProject($project);
$entry->setActivity($activity);
$entry->setDay(new DateTime(sprintf('2025-08-%02d', ($i % 28) + 1)));
$entry->setStart(new DateTime(sprintf('2025-08-%02d 09:%02d:00', ($i % 28) + 1, $i % 60)));
$entry->setEnd(new DateTime(sprintf('2025-08-%02d 17:%02d:00', ($i % 28) + 1, $i % 60)));
$entry->setDescription("Performance test entry {$i} with longer description for realistic Excel cell content");
$entry->setExternalReporter('external.reporter@example.com');
$entry->setExternalSummary('External summary for performance testing with longer text content');
$entry->setExternalLabels(['performance', 'test', 'benchmark']);
if ($withTickets) {
$entry->setTicket('PERF-' . (1000 + $i));
}
$entries[] = $entry;
}
return $entries;
}
/**
* Create a test user.
*/
private function createTestUser(): User
{
$user = new User();
$user->setUsername('perftest');
$user->setAbbr('PT');
return $user;
}
/**
* Create a test customer.
*/
private function createTestCustomer(): Customer
{
$customer = new Customer();
$customer->setName('Performance Test Customer');
return $customer;
}
/**
* Create a test project.
*/
private function createTestProject(Customer $customer): Project
{
$project = new Project();
$project->setName('Performance Test Project');
$project->setCustomer($customer);
return $project;
}
/**
* Create a test activity with optional statistics flags.
*/
private function createTestActivity(bool $withStats = false): Activity
{
$activity = new Activity();
$activity->setName('Performance Testing Activity');
// Some entries (~20%) become holidays/sick days for statistics testing.
if ($withStats && random_int(1, 10) <= 2) {
$activity->setName($activity->getName() . ' (Holiday)');
}
return $activity;
}
/**
* Log performance metrics for analysis (only in verbose mode).
*/
private function logPerformanceMetric(string $testName, float|int $durationMs, int $memoryBytes, int $recordCount): void
{
// Only output metrics in verbose mode to reduce PHPUnit noise
$args = $_SERVER['argv'] ?? [];
if (!is_array($args)) {
return;
}
$isVerbose = in_array('--verbose', $args, true) || in_array('-v', $args, true);
if (!$isVerbose) {
return;
}
$memoryMB = number_format($memoryBytes / 1024 / 1024, 2);
$throughput = $recordCount > 0 ? round($recordCount / max((float) $durationMs / 1000, 0.001), 2) : 0;
fwrite(STDERR, sprintf(
"\n[EXCEL PERFORMANCE] %s: %dms, %sMB memory, %d records, %s records/sec\n",
$testName,
(int) $durationMs,
$memoryMB,
$recordCount,
$throughput,
));
}
}