using System.Data; using Microsoft.Data.Sqlite; namespace ZKTecoSyncService.Tests; /// /// Database safety tests that verify schema invariants. /// These should be run as part of any migration/deploy process. /// public class DatabaseSafetyTests { [Fact] public void BufferedPunches_ShouldDeduplicateSamePunchType() { var dbPath = Path.Combine(Path.GetTempPath(), $"test_safety_{Guid.NewGuid():N}.db"); try { using var connection = new SqliteConnection($"Data Source={dbPath}"); connection.Open(); using var cmd = connection.CreateCommand(); cmd.CommandText = @" CREATE TABLE IF NOT EXISTS buffered_punches ( id INTEGER PRIMARY KEY AUTOINCREMENT, device_ip TEXT NOT NULL, device_port INTEGER NOT NULL, personnel_code TEXT NOT NULL, punch_time TEXT NOT NULL, punch_type TEXT NOT NULL, verify_mode TEXT DEFAULT '', work_code INTEGER DEFAULT 0, status TEXT NOT NULL DEFAULT 'PENDING', attempt_count INTEGER DEFAULT 0, first_seen_at TEXT NOT NULL DEFAULT (datetime('now')), created_at TEXT NOT NULL DEFAULT (datetime('now')), updated_at TEXT NOT NULL DEFAULT (datetime('now')) )"; cmd.ExecuteNonQuery(); cmd.CommandText = @" CREATE UNIQUE INDEX IF NOT EXISTS uq_buffer_dedup ON buffered_punches (device_ip, device_port, personnel_code, punch_time, punch_type, verify_mode, work_code)"; cmd.ExecuteNonQuery(); // Insert same punch_time + same punch_type — second should be ignored cmd.CommandText = "INSERT OR IGNORE INTO buffered_punches (device_ip, device_port, personnel_code, punch_time, punch_type, verify_mode, work_code, status, first_seen_at, created_at, updated_at) VALUES ('192.168.1.1', 4370, '1001', '2026-09-14 10:00:00', 'in', 'fingerprint', 0, 'PENDING', datetime('now'), datetime('now'), datetime('now'))"; Assert.Equal(1, cmd.ExecuteNonQuery()); cmd.CommandText = "INSERT OR IGNORE INTO buffered_punches (device_ip, device_port, personnel_code, punch_time, punch_type, verify_mode, work_code, status, first_seen_at, created_at, updated_at) VALUES ('192.168.1.1', 4370, '1001', '2026-09-14 10:00:00', 'in', 'fingerprint', 0, 'PENDING', datetime('now'), datetime('now'), datetime('now'))"; Assert.Equal(0, cmd.ExecuteNonQuery()); // Ignored // Insert same punch_time but different punch_type — should succeed cmd.CommandText = "INSERT OR IGNORE INTO buffered_punches (device_ip, device_port, personnel_code, punch_time, punch_type, verify_mode, work_code, status, first_seen_at, created_at, updated_at) VALUES ('192.168.1.1', 4370, '1001', '2026-09-14 10:00:00', 'out', 'fingerprint', 0, 'PENDING', datetime('now'), datetime('now'), datetime('now'))"; Assert.Equal(1, cmd.ExecuteNonQuery()); cmd.CommandText = "SELECT COUNT(*) FROM buffered_punches"; Assert.Equal(2, Convert.ToInt32(cmd.ExecuteScalar())); } finally { try { if (File.Exists(dbPath)) File.Delete(dbPath); } catch { } } } [Fact] public void MigrationGuard_OnUpdateRemoved() { // NOTE: This is a SURROGATE / SANITY CHECK only. // It reads migration FILE contents on disk — it does NOT check the // actual MySQL schema. The authoritative guard is the PHP test // tests/Feature/MigrationSafetyTest.php which connects to MySQL // and runs SHOW CREATE TABLE raw_attendance_logs. // // This C# test catches the most obvious case: a new migration file // that explicitly contains "ON UPDATE current_timestamp()". // Read the latest migration file for raw_attendance_logs var migrationsDir = Path.Combine(FindProjectRoot(), "database", "migrations"); if (!Directory.Exists(migrationsDir)) { Assert.Fail("Migrations directory not found"); return; } // Check that no migration after the fix re-introduces ON UPDATE var migrationFiles = Directory.GetFiles(migrationsDir, "*raw_attendance*") .Concat(Directory.GetFiles(migrationsDir, "*punch_time*")) .OrderBy(f => f) .ToList(); foreach (var file in migrationFiles) { var content = File.ReadAllText(file); if (content.Contains("ON UPDATE current_timestamp()") && !content.Contains("MODIFY")) { // Only fail if the migration ADDS ON UPDATE without MODIFY (which removes it) Assert.Fail($"Migration {Path.GetFileName(file)} may re-introduce ON UPDATE current_timestamp()"); } } // Also check the SQL definition directly var latestMigration = Directory.GetFiles(migrationsDir, "*remove_on_update*") .Concat(Directory.GetFiles(migrationsDir, "*punch_time*")) .OrderByDescending(f => f) .FirstOrDefault(); if (latestMigration != null) { var content = File.ReadAllText(latestMigration); // The fix migration should contain "MODIFY" and NOT contain "ON UPDATE" in the up() method Assert.Contains("MODIFY", content); } } private static string FindProjectRoot() { // Walk up from test output dir to find the Laravel project root var dir = AppContext.BaseDirectory; while (dir != null) { if (Directory.Exists(Path.Combine(dir, "database")) && Directory.Exists(Path.Combine(dir, "app"))) return dir; dir = Directory.GetParent(dir)?.FullName; } // Fallback: check common paths var candidates = new[] { @"G:\WEB-SERVER\htdocs\AttendanceHub", Directory.GetCurrentDirectory() }; foreach (var c in candidates) { if (Directory.Exists(Path.Combine(c, "database", "migrations"))) return c; } return Directory.GetCurrentDirectory(); } }