setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $pdo->exec('PRAGMA foreign_keys = ON'); $pdo->exec('CREATE TABLE Users (Id INTEGER PRIMARY KEY, Username TEXT)'); $pdo->exec('CREATE TABLE User_Preferences (Id INTEGER PRIMARY KEY, UserId INTEGER NOT NULL, Name TEXT NOT NULL, Value TEXT, FOREIGN KEY (UserId) REFERENCES Users(Id))'); class FakeUser { public $id; function exists() { global $pdo; $q = $pdo->prepare('SELECT COUNT(*) FROM Users WHERE Id=?'); $q->execute(array($this->id)); return $q->fetchColumn() > 0; } function delete() { global $pdo; return $pdo->prepare('DELETE FROM Users WHERE Id=?')->execute(array($this->id)); } } class FakeUserPreference { function deleteAll($conditions, $cascade = true) { global $pdo; $where = array(); foreach ($conditions as $field => $value) { $where[] = preg_replace('/^UserPreference\./', '', $field).'='.$pdo->quote($value); } return $pdo->exec('DELETE FROM User_Preferences WHERE '.implode(' AND ', $where)) !== false; } } class FakeRequest { function allowMethod() { return true; } } eval('class UsersHarness { public $request, $User, $UserPreference, $vars; function set($v) { $this->vars = $v; } function loadModel($name) { if ($name == "UserPreference") $this->UserPreference = new FakeUserPreference(); } '.$method.' }'); function count_rows($sql) { global $pdo; return intval($pdo->query($sql)->fetchColumn()); } $pdo->exec("INSERT INTO Users (Id, Username) VALUES (1, 'admin'), (5, 'viewer'), (6, 'other')"); $pdo->exec("INSERT INTO User_Preferences (UserId, Name, Value) VALUES (5, 'TagRecent', '[3,1]'), (6, 'TagRecent', '[2]')"); $user = null; // authentication off $h = new UsersHarness(); $h->request = new FakeRequest(); $h->User = new FakeUser(); try { $h->delete(5); $result = $h->vars['message']; } catch (Exception $e) { $result = get_class($e).': '.$e->getMessage(); } check('a user with preferences is deleted', $result, 'The user has been deleted.'); check('the user row is gone', count_rows('SELECT COUNT(*) FROM Users WHERE Id=5'), 0); check('their preferences are gone', count_rows('SELECT COUNT(*) FROM User_Preferences WHERE UserId=5'), 0); check('other users keep their preferences', count_rows('SELECT COUNT(*) FROM User_Preferences WHERE UserId=6'), 1); $h = new UsersHarness(); $h->request = new FakeRequest(); $h->User = new FakeUser(); $h->delete(1); check('a user without preferences is still deleted', $h->vars['message'], 'The user has been deleted.'); echo $failures ? "\n$failures failed\n" : "\nall passed\n"; exit($failures ? 1 : 0); ?>