|
| 1 | +<?php |
| 2 | + |
| 3 | +use DirectoryTree\Metrics\Jobs\RecordMetric; |
| 4 | +use DirectoryTree\Metrics\Metric; |
| 5 | +use DirectoryTree\Metrics\MetricData; |
| 6 | +use Illuminate\Database\Schema\Blueprint; |
| 7 | +use Illuminate\Support\Facades\Schema; |
| 8 | + |
| 9 | +beforeEach(function () { |
| 10 | + Metric::query()->delete(); |
| 11 | + |
| 12 | + if (! Schema::hasColumn('metrics', 'payload')) { |
| 13 | + Schema::table('metrics', function (Blueprint $table) { |
| 14 | + $table->json('payload'); |
| 15 | + }); |
| 16 | + } |
| 17 | +}); |
| 18 | + |
| 19 | +afterEach(function () { |
| 20 | + if (Schema::hasColumn('metrics', 'payload')) { |
| 21 | + Schema::table('metrics', function (Blueprint $table) { |
| 22 | + $table->dropColumn('payload'); |
| 23 | + }); |
| 24 | + } |
| 25 | +}); |
| 26 | + |
| 27 | +it('creates metrics with json payload attributes', function () { |
| 28 | + $data = new MetricData('page_views_with_json', additional: [ |
| 29 | + 'payload' => [ |
| 30 | + 'a' => 1, |
| 31 | + 'b' => 'test', |
| 32 | + ], |
| 33 | + ]); |
| 34 | + |
| 35 | + (new RecordMetric($data))->handle(); |
| 36 | + (new RecordMetric($data))->handle(); |
| 37 | + |
| 38 | + // Count may be 1 (SQLite dedupes by JSON string) or 2 (MySQL compares JSON differently). |
| 39 | + expect(Metric::where('name', 'page_views_with_json')->count())->toBeGreaterThanOrEqual(1); |
| 40 | + |
| 41 | + $metric = Metric::where('name', 'page_views_with_json')->first(); |
| 42 | + |
| 43 | + // Cast the payload attribute manually since we added the column dynamically |
| 44 | + $metric->mergeCasts(['payload' => 'array']); |
| 45 | + |
| 46 | + expect($metric->payload)->toBe(['a' => 1, 'b' => 'test']); |
| 47 | + |
| 48 | + // Total value across all matching records should equal 2 regardless of DB. |
| 49 | + expect(Metric::where('name', 'page_views_with_json')->sum('value'))->toEqual(2); |
| 50 | +}); |
| 51 | + |
| 52 | +it('differentiates metrics by json payload content', function () { |
| 53 | + $data1 = new MetricData('page_views_by_source', additional: [ |
| 54 | + 'payload' => ['source' => 'google'], |
| 55 | + ]); |
| 56 | + |
| 57 | + $data2 = new MetricData('page_views_by_source', additional: [ |
| 58 | + 'payload' => ['source' => 'facebook'], |
| 59 | + ]); |
| 60 | + |
| 61 | + (new RecordMetric($data1))->handle(); |
| 62 | + (new RecordMetric($data2))->handle(); |
| 63 | + |
| 64 | + // Count may be 2 (SQLite) or more (MySQL) depending on JSON comparison behavior. |
| 65 | + expect(Metric::where('name', 'page_views_by_source')->count())->toBeGreaterThanOrEqual(2); |
| 66 | +}); |
0 commit comments