SapphireTest.php 27.6 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 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887
<?php
require_once 'TestRunner.php';

/**
 * Test case class for the Sapphire framework.
 * Sapphire unit testing is based on PHPUnit, but provides a number of hooks into our data model that make it easier
 * to work with.
 * 
 * @package framework
 * @subpackage testing
 */
class SapphireTest extends PHPUnit_Framework_TestCase {
	
	/** @config */
	private static $dependencies = array(
		'fixtureFactory' => '%$FixtureFactory',
	);

	/**
	 * Path to fixture data for this test run.
	 * If passed as an array, multiple fixture files will be loaded.
	 * Please note that you won't be able to refer with "=>" notation
	 * between the fixtures, they act independent of each other.
	 * 
	 * @var string|array
	 */
	protected static $fixture_file = null;

	/**
	 * @var FixtureFactory
	 */
	protected $fixtureFactory;
	
	/**
	 * @var bool Set whether to include this test in the TestRunner or to skip this.
	 */
	protected $skipTest = false;
	
	/**
	 * @var Boolean If set to TRUE, this will force a test database to be generated
	 * in {@link setUp()}. Note that this flag is overruled by the presence of a 
	 * {@link $fixture_file}, which always forces a database build.
	 */
	protected $usesDatabase = null;
	
	protected $originalMailer;
	protected $originalMemberPasswordValidator;
	protected $originalRequirements;
	protected $originalIsRunningTest;
	protected $originalTheme;
	protected $originalNestedURLsState;
	protected $originalMemoryLimit;
	
	protected $mailer;
	
	/**
	 * Pointer to the manifest that isn't a test manifest
	 */
	protected static $regular_manifest;
	
	/**
	 * @var boolean
	 */
	protected static $is_running_test = false;
	
	protected static $test_class_manifest;
	
	/**
	 * By default, setUp() does not require default records. Pass
	 * class names in here, and the require/augment default records
	 * function will be called on them.
	 */
	protected $requireDefaultRecordsFrom = array();
	
	
	/**
	 * A list of extensions that can't be applied during the execution of this run.  If they are
	 * applied, they will be temporarily removed and a database migration called.
	 * 
	 * The keys of the are the classes that the extensions can't be applied the extensions to, and
	 * the values are an array of illegal extensions on that class.
	 */
	protected $illegalExtensions = array(
	);

	/**
	 * A list of extensions that must be applied during the execution of this run.  If they are
	 * not applied, they will be temporarily added and a database migration called.
	 * 
	 * The keys of the are the classes to apply the extensions to, and the values are an array
	 * of required extensions on that class.
	 * 
	 * Example:
	 * <code>
	 * array("MyTreeDataObject" => array("Versioned", "Hierarchy"))
	 * </code>
	 */
	protected $requiredExtensions = array(
	);
	
	/**
	 * By default, the test database won't contain any DataObjects that have the interface TestOnly.
	 * This variable lets you define additional TestOnly DataObjects to set up for this test.
	 * Set it to an array of DataObject subclass names.
	 */
	protected $extraDataObjects = array();
	
	/**
	 * We need to disabling backing up of globals to avoid overriding
	 * the few globals SilverStripe relies on, like $lang for the i18n subsystem.
	 * 
	 * @see http://sebastian-bergmann.de/archives/797-Global-Variables-and-PHPUnit.html
	 */
	protected $backupGlobals = FALSE;

	/** 
	 * Helper arrays for illegalExtensions/requiredExtensions code
	 */
	private $extensionsToReapply = array(), $extensionsToRemove = array();

	
	/**
	 * Determines if unit tests are currently run (via {@link TestRunner}).
	 * This is used as a cheap replacement for fully mockable state
	 * in certain contiditions (e.g. access checks).
	 * Caution: When set to FALSE, certain controllers might bypass
	 * access checks, so this is a very security sensitive setting.
	 * 
	 * @return boolean
	 */
	public static function is_running_test() {
		return self::$is_running_test;
	}

	public static function set_is_running_test($bool) {
		self::$is_running_test = $bool;	
	}

	/**
	 * Set the manifest to be used to look up test classes by helper functions
	 */
	public static function set_test_class_manifest($manifest) {
		self::$test_class_manifest = $manifest;
	}

	/**
	 * Return the manifest being used to look up test classes by helper functions
	 */
	public static function get_test_class_manifest() {
		return self::$test_class_manifest;
	}

	/**
	 * @return String
	 */
	public static function get_fixture_file() {
		return static::$fixture_file;
	}

	/**
	 * @var array $fixtures Array of {@link YamlFixture} instances
	 * @deprecated 3.1 Use $fixtureFactory instad
	 */
	protected $fixtures = array(); 
	
	protected $model;
	
	public function setUp() {
		// We cannot run the tests on this abstract class.
		if(get_class($this) == "SapphireTest") $this->skipTest = true;
		
		if($this->skipTest) {
			$this->markTestSkipped(sprintf(
				'Skipping %s ', get_class($this)
			));
			
			return;
		}
		
		// Mark test as being run
		$this->originalIsRunningTest = self::$is_running_test;
		self::$is_running_test = true;

		// i18n needs to be set to the defaults or tests fail
		i18n::set_locale(i18n::default_locale());
		i18n::config()->date_format = null;
		i18n::config()->time_format = null;
		
		// Set default timezone consistently to avoid NZ-specific dependencies
		date_default_timezone_set('UTC');
		
		// Remove password validation
		$this->originalMemberPasswordValidator = Member::password_validator();
		$this->originalRequirements = Requirements::backend();
		Member::set_password_validator(null);
		Config::inst()->update('Cookie', 'report_errors', false);
		
		if(class_exists('RootURLController')) RootURLController::reset();
		if(class_exists('Translatable')) Translatable::reset();
		Versioned::reset();
		DataObject::reset();
		if(class_exists('SiteTree')) SiteTree::reset();
		Hierarchy::reset();
		if(Controller::has_curr()) Controller::curr()->setSession(Injector::inst()->create('Session', array()));
		Security::$database_is_ready = null;
		
		$fixtureFile = static::get_fixture_file();

		$prefix = defined('SS_DATABASE_PREFIX') ? SS_DATABASE_PREFIX : 'ss_';

		// Set up email
		$this->originalMailer = Email::mailer();
		$this->mailer = new TestMailer();
		Email::set_mailer($this->mailer);
		Config::inst()->remove('Email', 'send_all_emails_to');
		
		// Todo: this could be a special test model
		$this->model = DataModel::inst();

		// Set up fixture
		if($fixtureFile || $this->usesDatabase || !self::using_temp_db()) {
			if(substr(DB::getConn()->currentDatabase(), 0, strlen($prefix) + 5) 
					!= strtolower(sprintf('%stmpdb', $prefix))) {

				//echo "Re-creating temp database... ";
				self::create_temp_db();
				//echo "done.\n";
			}

			singleton('DataObject')->flushCache();
			
			self::empty_temp_db();
			
			foreach($this->requireDefaultRecordsFrom as $className) {
				$instance = singleton($className);
				if (method_exists($instance, 'requireDefaultRecords')) $instance->requireDefaultRecords();
				if (method_exists($instance, 'augmentDefaultRecords')) $instance->augmentDefaultRecords();
			}

			if($fixtureFile) {
				$pathForClass = $this->getCurrentAbsolutePath();
				$fixtureFiles = (is_array($fixtureFile)) ? $fixtureFile : array($fixtureFile);

				$i = 0;
				foreach($fixtureFiles as $fixtureFilePath) {
					// Support fixture paths relative to the test class, rather than relative to webroot
					// String checking is faster than file_exists() calls.
					$isRelativeToFile = (strpos('/', $fixtureFilePath) === false 
						|| preg_match('/^\.\./', $fixtureFilePath));

					if($isRelativeToFile) {
						$resolvedPath = realpath($pathForClass . '/' . $fixtureFilePath);
						if($resolvedPath) $fixtureFilePath = $resolvedPath;
					}
					
					$fixture = Injector::inst()->create('YamlFixture', $fixtureFilePath);
					$fixture->writeInto($this->getFixtureFactory());
					$this->fixtures[] = $fixture;

					// backwards compatibility: Load first fixture into $this->fixture
					if($i == 0) $this->fixture = $fixture;
					$i++;
				}
			}
			
			$this->logInWithPermission("ADMIN");
		}
		
		// Preserve memory settings
		$this->originalMemoryLimit = ini_get('memory_limit');
		
		// turn off template debugging
		Config::inst()->update('SSViewer', 'source_file_comments', false);
		
		// Clear requirements
		Requirements::clear();
	}
	
	/**
	 * Called once per test case ({@link SapphireTest} subclass).
	 * This is different to {@link setUp()}, which gets called once
	 * per method. Useful to initialize expensive operations which
	 * don't change state for any called method inside the test,
	 * e.g. dynamically adding an extension. See {@link tearDownOnce()}
	 * for tearing down the state again.
	 */
	public function setUpOnce() {
		$isAltered = false;

		if(!Director::isDev()) {
			user_error('Tests can only run in "dev" mode', E_USER_ERROR);
		}

		// Remove any illegal extensions that are present
		foreach($this->illegalExtensions as $class => $extensions) {
			foreach($extensions as $extension) {
				if ($class::has_extension($extension)) {
					if(!isset($this->extensionsToReapply[$class])) $this->extensionsToReapply[$class] = array();
					$this->extensionsToReapply[$class][] = $extension;
					$class::remove_extension($extension);
					$isAltered = true;
				}
			}
		}

		// Add any required extensions that aren't present
		foreach($this->requiredExtensions as $class => $extensions) {
			$this->extensionsToRemove[$class] = array();
			foreach($extensions as $extension) {
				if(!$class::has_extension($extension)) {
					if(!isset($this->extensionsToRemove[$class])) $this->extensionsToReapply[$class] = array();
					$this->extensionsToRemove[$class][] = $extension;
					$class::add_extension($extension);
					$isAltered = true;
				}
			}
		}
		
		// If we have made changes to the extensions present, then migrate the database schema.
		if($isAltered || $this->extensionsToReapply || $this->extensionsToRemove || $this->extraDataObjects) {
			if(!self::using_temp_db()) self::create_temp_db();
			$this->resetDBSchema(true);
		}
		// clear singletons, they're caching old extension info 
		// which is used in DatabaseAdmin->doBuild()
		Injector::inst()->unregisterAllObjects();

		// Set default timezone consistently to avoid NZ-specific dependencies
		date_default_timezone_set('UTC');
	}
	
	/**
	 * tearDown method that's called once per test class rather once per test method.
	 */
	public function tearDownOnce() {
		// If we have made changes to the extensions present, then migrate the database schema.
		if($this->extensionsToReapply || $this->extensionsToRemove) {
			// Remove extensions added for testing
			foreach($this->extensionsToRemove as $class => $extensions) {
				foreach($extensions as $extension) {
					$class::remove_extension($extension);
				}
			}

			// Reapply ones removed
			foreach($this->extensionsToReapply as $class => $extensions) {
				foreach($extensions as $extension) {
					$class::add_extension($extension);
				}
			}
		}

		if($this->extensionsToReapply || $this->extensionsToRemove || $this->extraDataObjects) {
			$this->resetDBSchema();
		}
	}
	
	/**
	 * @return FixtureFactory
	 */
	public function getFixtureFactory() {
		if(!$this->fixtureFactory) $this->fixtureFactory = Injector::inst()->create('FixtureFactory');
		return $this->fixtureFactory;
	}

	public function setFixtureFactory(FixtureFactory $factory) {
		$this->fixtureFactory = $factory;
		return $this;
	}
	
	/**
	 * Get the ID of an object from the fixture.
	 * 
	 * @param $className The data class, as specified in your fixture file.  Parent classes won't work
	 * @param $identifier The identifier string, as provided in your fixture file
	 * @return int
	 */
	protected function idFromFixture($className, $identifier) {
		$id = $this->getFixtureFactory()->getId($className, $identifier);

		if(!$id) {
			user_error(sprintf(
				"Couldn't find object '%s' (class: %s)",
				$identifier,
				$className
			), E_USER_ERROR);
		}

		return $id;
	}

	/**
	 * Return all of the IDs in the fixture of a particular class name.
	 * Will collate all IDs form all fixtures if multiple fixtures are provided.
	 *
	 * @param string $className
	 * @return A map of fixture-identifier => object-id
	 */
	protected function allFixtureIDs($className) {
		return $this->getFixtureFactory()->getIds($className);
	}

	/**
	 * Get an object from the fixture.
	 *
	 * @param string $className The data class, as specified in your fixture file. Parent classes won't work
	 * @param string $identifier The identifier string, as provided in your fixture file
	 *
	 * @return DataObject
	 */
	protected function objFromFixture($className, $identifier) {
		$obj = $this->getFixtureFactory()->get($className, $identifier);

		if(!$obj) {
			user_error(sprintf(
				"Couldn't find object '%s' (class: %s)",
				$identifier,
				$className
			), E_USER_ERROR);	
		}
		
		return $obj;
	}
	
	/**
	 * Load a YAML fixture file into the database.
	 * Once loaded, you can use idFromFixture() and objFromFixture() to get items from the fixture.
	 * Doesn't clear existing fixtures.
	 *
	 * @param $fixtureFile The location of the .yml fixture file, relative to the site base dir
	 */
	public function loadFixture($fixtureFile) {
		$fixture = Injector::inst()->create('YamlFixture', $fixtureFile);
		$fixture->writeInto($this->getFixtureFactory());
		$this->fixtures[] = $fixture;
	}
	
	/**
	 * Clear all fixtures which were previously loaded through
	 * {@link loadFixture()} 
	 */
	public function clearFixtures() {
		$this->fixtures = array();
		$this->getFixtureFactory()->clear();
	}
	
	/**
	 * Useful for writing unit tests without hardcoding folder structures.
	 * 
	 * @return String Absolute path to current class.
	 */
	protected function getCurrentAbsolutePath() {
		$filename = self::$test_class_manifest->getItemPath(get_class($this));
		if(!$filename) throw new LogicException("getItemPath returned null for " . get_class($this));
		return dirname($filename);
	}
	
	/**
	 * @return String File path relative to webroot
	 */
	protected function getCurrentRelativePath() {
		$base = Director::baseFolder();
		$path = $this->getCurrentAbsolutePath();
		if(substr($path,0,strlen($base)) == $base) $path = preg_replace('/^\/*/', '', substr($path,strlen($base)));
		return $path;
	}
	
	public function tearDown() {
		// Preserve memory settings
		ini_set('memory_limit', ($this->originalMemoryLimit) ? $this->originalMemoryLimit : -1);

		// Restore email configuration
		if($this->originalMailer) {
			Email::set_mailer($this->originalMailer);
			$this->originalMailer = null;
		}
		$this->mailer = null;	

		// Restore password validation
		if($this->originalMemberPasswordValidator) {
			Member::set_password_validator($this->originalMemberPasswordValidator);	
		}
		
		// Restore requirements
		if($this->originalRequirements) {
			Requirements::set_backend($this->originalRequirements);	
		}

		// Mark test as no longer being run - we use originalIsRunningTest to allow for nested SapphireTest calls
		self::$is_running_test = $this->originalIsRunningTest;
		$this->originalIsRunningTest = null;

		// Reset mocked datetime
		SS_Datetime::clear_mock_now();
		
		// Stop the redirection that might have been requested in the test.
		// Note: Ideally a clean Controller should be created for each test. 
		// Now all tests executed in a batch share the same controller.
		$controller = Controller::has_curr() ? Controller::curr() : null;
		if ( $controller && $controller->response && $controller->response->getHeader('Location') ) {
			$controller->response->setStatusCode(200);
			$controller->response->removeHeader('Location');
		}
	}

	public static function assertContains(
		$needle,
		$haystack,
		$message = '',
		$ignoreCase = FALSE,
		$checkForObjectIdentity = TRUE,
		$checkForNonObjectIdentity = false
	) {
		if ($haystack instanceof DBField) $haystack = (string)$haystack;
		parent::assertContains($needle, $haystack, $message, $ignoreCase, $checkForObjectIdentity, $checkForNonObjectIdentity);
	}

	public static function assertNotContains(
		$needle,
		$haystack,
		$message = '',
		$ignoreCase = FALSE,
		$checkForObjectIdentity = TRUE,
		$checkForNonObjectIdentity = false
	) {
		if ($haystack instanceof DBField) $haystack = (string)$haystack;
		parent::assertNotContains($needle, $haystack, $message, $ignoreCase, $checkForObjectIdentity, $checkForNonObjectIdentity);
	}

	/**
	 * Clear the log of emails sent
	 */
	public function clearEmails() {
		return $this->mailer->clearEmails();
	}

	/**
	 * Search for an email that was sent.
	 * All of the parameters can either be a string, or, if they start with "/", a PREG-compatible regular expression.
	 * @param $to
	 * @param $from
	 * @param $subject
	 * @param $content
	 * @return array Contains keys: 'type', 'to', 'from', 'subject','content', 'plainContent', 'attachedFiles',
	 *               'customHeaders', 'htmlContent', 'inlineImages'
	 */
	public function findEmail($to, $from = null, $subject = null, $content = null) {
		return $this->mailer->findEmail($to, $from, $subject, $content);
	}
	
	/**
	 * Assert that the matching email was sent since the last call to clearEmails()
	 * All of the parameters can either be a string, or, if they start with "/", a PREG-compatible regular expression.
	 * @param $to
	 * @param $from
	 * @param $subject
	 * @param $content
	 * @return array Contains the keys: 'type', 'to', 'from', 'subject', 'content', 'plainContent', 'attachedFiles',
	 *               'customHeaders', 'htmlContent', inlineImages'
	 */
	public function assertEmailSent($to, $from = null, $subject = null, $content = null) {
		$found = (bool)$this->findEmail($to, $from, $subject, $content);

		$infoParts = "";
		$withParts = array();
		if($to) $infoParts .= " to '$to'";
		if($from) $infoParts .= " from '$from'";
		if($subject) $withParts[] = "subject '$subject'";
		if($content) $withParts[] = "content '$content'";
		if($withParts) $infoParts .= " with " . implode(" and ", $withParts);

		$this->assertTrue(
			$found,
			"Failed asserting that an email was sent$infoParts."
		);
	}


	/**
	 * Assert that the given {@link SS_List} includes DataObjects matching the given key-value
	 * pairs.  Each match must correspond to 1 distinct record.
	 * 
	 * @param $matches The patterns to match.  Each pattern is a map of key-value pairs.  You can
	 * either pass a single pattern or an array of patterns.
	 * @param $dataObjectSet The {@link SS_List} to test.
	 *
	 * Examples
	 * --------
	 * Check that $members includes an entry with Email = sam@example.com:
	 *      $this->assertDOSContains(array('Email' => '...@example.com'), $members); 
	 * 
	 * Check that $members includes entries with Email = sam@example.com and with 
	 * Email = ingo@example.com:
	 *      $this->assertDOSContains(array( 
	 *         array('Email' => '...@example.com'), 
	 *         array('Email' => 'i...@example.com'), 
	 *      ), $members); 
	 */
	public function assertDOSContains($matches, $dataObjectSet) {
		$extracted = array();
		foreach($dataObjectSet as $item) $extracted[] = $item->toMap();
		
		foreach($matches as $match) {
			$matched = false;
			foreach($extracted as $i => $item) {
				if($this->dataObjectArrayMatch($item, $match)) {
					// Remove it from $extracted so that we don't get duplicate mapping.
					unset($extracted[$i]);
					$matched = true;
					break;
				}
			}

			// We couldn't find a match - assertion failed
			$this->assertTrue(
				$matched,
				"Failed asserting that the SS_List contains an item matching "
				. var_export($match, true) . "\n\nIn the following SS_List:\n" 
				. $this->DOSSummaryForMatch($dataObjectSet, $match)
			);
		}
	} 
	
	/**
	 * Assert that the given {@link SS_List} includes only DataObjects matching the given 
	 * key-value pairs.  Each match must correspond to 1 distinct record.
	 * 
	 * @param $matches The patterns to match.  Each pattern is a map of key-value pairs.  You can
	 * either pass a single pattern or an array of patterns.
	 * @param $dataObjectSet The {@link SS_List} to test.
	 *
	 * Example
	 * --------
	 * Check that *only* the entries Sam Minnee and Ingo Schommer exist in $members.  Order doesn't 
	 * matter:
	 *     $this->assertDOSEquals(array( 
	 *        array('FirstName' =>'Sam', 'Surname' => 'Minnee'), 
	 *        array('FirstName' => 'Ingo', 'Surname' => 'Schommer'), 
	 *      ), $members); 
	 */
	public function assertDOSEquals($matches, $dataObjectSet) {
		if(!$dataObjectSet) return false;
		
		$extracted = array();
		foreach($dataObjectSet as $item) $extracted[] = $item->toMap();
		
		foreach($matches as $match) {
			$matched = false;
			foreach($extracted as $i => $item) {
				if($this->dataObjectArrayMatch($item, $match)) {
					// Remove it from $extracted so that we don't get duplicate mapping.
					unset($extracted[$i]);
					$matched = true;
					break;
				}
			}

			// We couldn't find a match - assertion failed
			$this->assertTrue(
				$matched,
				"Failed asserting that the SS_List contains an item matching "
				. var_export($match, true) . "\n\nIn the following SS_List:\n" 
				. $this->DOSSummaryForMatch($dataObjectSet, $match)
			);
		}
		
		// If we have leftovers than the DOS has extra data that shouldn't be there
		$this->assertTrue(
			(count($extracted) == 0),
			// If we didn't break by this point then we couldn't find a match
			"Failed asserting that the SS_List contained only the given items, the "
			. "following items were left over:\n" . var_export($extracted, true)
		);
	} 

	/**
	 * Assert that the every record in the given {@link SS_List} matches the given key-value
	 * pairs.
	 * 
	 * @param $match The pattern to match.  The pattern is a map of key-value pairs.
	 * @param $dataObjectSet The {@link SS_List} to test.
	 *
	 * Example
	 * --------
	 * Check that every entry in $members has a Status of 'Active':
	 *     $this->assertDOSAllMatch(array('Status' => 'Active'), $members); 
	 */
	public function assertDOSAllMatch($match, $dataObjectSet) {
		$extracted = array();
		foreach($dataObjectSet as $item) $extracted[] = $item->toMap();

		foreach($extracted as $i => $item) {
			$this->assertTrue(
				$this->dataObjectArrayMatch($item, $match),
				"Failed asserting that the the following item matched " 
				. var_export($match, true) . ": " . var_export($item, true)
			);
		}
	} 
	
	/**
	 * Helper function for the DOS matchers
	 */
	private function dataObjectArrayMatch($item, $match) {
		foreach($match as $k => $v) {
			if(!array_key_exists($k, $item) || $item[$k] != $v) return false;
		}
		return true;
	}

	/**
	 * Helper function for the DOS matchers
	 */
	private function DOSSummaryForMatch($dataObjectSet, $match) {
		$extracted = array();
		foreach($dataObjectSet as $item) $extracted[] = array_intersect_key($item->toMap(), $match);
		return var_export($extracted, true);
	}

	/**
	 * Returns true if we are currently using a temporary database
	 */
	public static function using_temp_db() {
		$dbConn = DB::getConn();
		$prefix = defined('SS_DATABASE_PREFIX') ? SS_DATABASE_PREFIX : 'ss_';
		return $dbConn && (substr($dbConn->currentDatabase(), 0, strlen($prefix) + 5) 
			== strtolower(sprintf('%stmpdb', $prefix)));
	}
	
	public static function kill_temp_db() {
		// Delete our temporary database
		if(self::using_temp_db()) {
			$dbConn = DB::getConn();
			$dbName = $dbConn->currentDatabase();
			if($dbName && DB::getConn()->databaseExists($dbName)) {
				// Some DataExtensions keep a static cache of information that needs to 
				// be reset whenever the database is killed
				foreach(ClassInfo::subclassesFor('DataExtension') as $class) {
					$toCall = array($class, 'on_db_reset');
					if(is_callable($toCall)) call_user_func($toCall);
				}

				// echo "Deleted temp database " . $dbConn->currentDatabase() . "\n";
				$dbConn->dropDatabase();
			}
		}
	}
	
	/**
	 * Remove all content from the temporary database.
	 */
	public static function empty_temp_db() {
		if(self::using_temp_db()) {
			$dbadmin = new DatabaseAdmin();
			$dbadmin->clearAllData();
			
			// Some DataExtensions keep a static cache of information that needs to 
			// be reset whenever the database is cleaned out
			$classes = array_merge(ClassInfo::subclassesFor('DataExtension'), ClassInfo::subclassesFor('DataObject'));
			foreach($classes as $class) {
				$toCall = array($class, 'on_db_reset');
				if(is_callable($toCall)) call_user_func($toCall);
			}
		}
	}
	
	public static function create_temp_db() {
		// Disable PHPUnit error handling
		restore_error_handler();

		// Create a temporary database, and force the connection to use UTC for time
		global $databaseConfig;
		$databaseConfig['timezone'] = '+0:00';
		DB::connect($databaseConfig);
		$dbConn = DB::getConn();
		$prefix = defined('SS_DATABASE_PREFIX') ? SS_DATABASE_PREFIX : 'ss_';
		$dbname = strtolower(sprintf('%stmpdb', $prefix)) . rand(1000000,9999999);
		while(!$dbname || $dbConn->databaseExists($dbname)) {
			$dbname = strtolower(sprintf('%stmpdb', $prefix)) . rand(1000000,9999999);
		}

		$dbConn->selectDatabase($dbname);
		$dbConn->createDatabase();

		$st = Injector::inst()->create('SapphireTest');
		$st->resetDBSchema();
		
		// Reinstate PHPUnit error handling
		set_error_handler(array('PHPUnit_Util_ErrorHandler', 'handleError'));
		
		return $dbname;
	}
	
	public static function delete_all_temp_dbs() {
		$prefix = defined('SS_DATABASE_PREFIX') ? SS_DATABASE_PREFIX : 'ss_';
		foreach(DB::getConn()->allDatabaseNames() as $dbName) {
			if(preg_match(sprintf('/^%stmpdb[0-9]+$/', $prefix), $dbName)) {
				DB::getConn()->dropDatabaseByName($dbName);
				if(Director::is_cli()) {
					echo "Dropped database \"$dbName\"" . PHP_EOL;
				} else {
					echo "<li>Dropped database \"$dbName\"</li>" . PHP_EOL;
				}
				flush();
			}
		}
	}
	
	/**
	 * Reset the testing database's schema.
	 * @param $includeExtraDataObjects If true, the extraDataObjects tables will also be included
	 */
	public function resetDBSchema($includeExtraDataObjects = false) {
		if(self::using_temp_db()) {
			DataObject::reset();

			// clear singletons, they're caching old extension info which is used in DatabaseAdmin->doBuild()
			Injector::inst()->unregisterAllObjects();

			$dataClasses = ClassInfo::subclassesFor('DataObject');
			array_shift($dataClasses);

			$conn = DB::getConn();
			$conn->beginSchemaUpdate();
			DB::quiet();

			foreach($dataClasses as $dataClass) {
				// Check if class exists before trying to instantiate - this sidesteps any manifest weirdness
				if(class_exists($dataClass)) {
					$SNG = singleton($dataClass);
					if(!($SNG instanceof TestOnly)) $SNG->requireTable();
				}
			}

			// If we have additional dataobjects which need schema, do so here:
			if($includeExtraDataObjects && $this->extraDataObjects) {
				foreach($this->extraDataObjects as $dataClass) {
					$SNG = singleton($dataClass);
					if(singleton($dataClass) instanceof DataObject) $SNG->requireTable();
				}
			}

			$conn->endSchemaUpdate();

			ClassInfo::reset_db_cache();
			singleton('DataObject')->flushCache();
		}
	}
	
	/**
	 * Create a member and group with the given permission code, and log in with it.
	 * Returns the member ID.
	 */
	public function logInWithPermission($permCode = "ADMIN") {
		if(!isset($this->cache_generatedMembers[$permCode])) {
			$group = Injector::inst()->create('Group');
			$group->Title = "$permCode group";
			$group->write();

			$permission = Injector::inst()->create('Permission');
			$permission->Code = $permCode;
			$permission->write();
			$group->Permissions()->add($permission);
			
			$member = DataObject::get_one('Member', sprintf('"Email" = \'%s\'', "$permCode@example.org"));
			if(!$member) $member = Injector::inst()->create('Member');
			
			$member->FirstName = $permCode;
			$member->Surname = "User";
			$member->Email = "$permCode@example.org";
			$member->write();
			$group->Members()->add($member);
			
			$this->cache_generatedMembers[$permCode] = $member;
		}
		
		$this->cache_generatedMembers[$permCode]->logIn();
		return $this->cache_generatedMembers[$permCode]->ID;
	}
	
	/**
	 * Cache for logInWithPermission()
	 */
	protected $cache_generatedMembers = array();
}