PageRenderTime 44ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 0ms

/Test/Case.php

https://github.com/codeactual/hashmark
PHP | 354 lines | 169 code | 51 blank | 134 comment | 24 complexity | b1bffcd90ff2a3e8b69cb25d2d059d16 MD5 | raw file
  1. <?php
  2. // vim: fenc=utf-8:ft=php:ai:si:ts=4:sw=4:et:
  3. /**
  4. * Hashmark_TestCase
  5. *
  6. * @filesource
  7. * @copyright Copyright (c) 2008-2011 David Smith
  8. * @license http://www.opensource.org/licenses/mit-license.php MIT License
  9. * @package Hashmark-Test
  10. * @subpackage Base
  11. * @version $Id$
  12. */
  13. /**
  14. * Base class for all module test classes.
  15. *
  16. * @package Hashmark-Test
  17. * @subpackage Base
  18. */
  19. abstract class Hashmark_TestCase extends PHPUnit_Framework_TestCase
  20. {
  21. /**
  22. * @var boolean If true, PHPUnit lets globals persist between tests.
  23. * @link http://sebastian-bergmann.de/archives/797-Global-Variables-and-PHPUnit.html
  24. */
  25. protected $backupGlobals = false;
  26. /**
  27. * @var Zend_Db_Adapter_* Current instance.
  28. * @see setUp()
  29. */
  30. protected $_db;
  31. /**
  32. * @var string Test case type, ex. 'DbDependent' (Hashmark_Module_DbDependent).
  33. * @see setUp()
  34. */
  35. protected $_type;
  36. /**
  37. * Set up the test case fixtures.
  38. *
  39. * @return void
  40. */
  41. protected function setUp()
  42. {
  43. // Extract suffix (ex. 'DbDependent') from class (ex. 'Hashmark_TestCase_Module_DbDependent').
  44. $className = get_class($this);
  45. $this->_type = substr($className, strrpos($className, '_') + 1);
  46. $this->_db = Hashmark::getModule('DbHelper')->openDb('unittest');
  47. }
  48. /**
  49. * @return void
  50. */
  51. protected function tearDown()
  52. {
  53. if ($this->_db) {
  54. $this->_db->closeConnection();
  55. }
  56. }
  57. /**
  58. * Return a @dataProvider-compat argument set without the array()
  59. * wrapping around each value.
  60. *
  61. * @return Array
  62. */
  63. public static function unwrapProviderData($providerData)
  64. {
  65. array_walk($providerData, create_function('&$v,$k', '$v = $v[0];'));
  66. return $providerData;
  67. }
  68. /**
  69. * Provide valid increment values (initial, delta, expected result).
  70. *
  71. * @return Array Test method argument sets.
  72. * @see Loaded data file for return value format.
  73. */
  74. public static function provideIncrementValues()
  75. {
  76. static $data;
  77. require_once HASHMARK_ROOT_DIR . '/Test/Core/Data/' . __FUNCTION__ . '.php';
  78. return $data;
  79. }
  80. /**
  81. * Provide valid decrement values (initial, delta, expected result).
  82. *
  83. * @return Array Test method argument sets.
  84. * @see Loaded data file for return value format.
  85. */
  86. public static function provideDecrementValues()
  87. {
  88. static $data;
  89. require_once HASHMARK_ROOT_DIR . '/Test/Core/Data/' . __FUNCTION__ . '.php';
  90. return $data;
  91. }
  92. /**
  93. * Provide valid string values.
  94. *
  95. * @return Array Test method argument sets.
  96. */
  97. public static function provideStringValues()
  98. {
  99. static $data;
  100. if (!$data) {
  101. $data = array(array(''),
  102. array(' '),
  103. array('87a46c25bc0723ada70db470198e887d'));
  104. }
  105. return $data;
  106. }
  107. /**
  108. * Provide valid decimal values.
  109. *
  110. * @return Array Test method argument sets.
  111. */
  112. public static function provideDecimalValues()
  113. {
  114. static $data;
  115. if (!$data) {
  116. $data = array(array('0'),
  117. array('1'),
  118. array('-1'),
  119. array('1.0001'),
  120. array('-1.0001'),
  121. array('0.0001'),
  122. array('-0.0001'),
  123. array('1000000000000000.0001'),
  124. array('-1000000000000000.0001'));
  125. }
  126. return $data;
  127. }
  128. /**
  129. * Provide names which should never identify a scalar.
  130. *
  131. * @return Array Test method argument sets.
  132. */
  133. public static function provideInvalidScalarNames()
  134. {
  135. static $data;
  136. if (!$data) {
  137. $data = array(array(''),
  138. array(' '),
  139. array(null),
  140. array(true),
  141. array(false),
  142. array(0),
  143. array(1),
  144. array(-1));
  145. }
  146. return $data;
  147. }
  148. /**
  149. * Provide sets of scalar types and values.
  150. *
  151. * @return Array Test method argument sets.
  152. *
  153. * Format:
  154. *
  155. * array(array('decimal', 0),
  156. * ...
  157. * array('string', 'aef448733247db5be49ae8597aa94d59S'));
  158. */
  159. public static function provideScalarTypesAndValues()
  160. {
  161. static $data;
  162. if (!$data) {
  163. $strings = self::provideStringValues();
  164. $numbers = self::provideDecimalValues();
  165. $data = array();
  166. foreach ($strings as $str) {
  167. $data[] = array('string', $str[0]);
  168. }
  169. foreach ($numbers as $num) {
  170. $data[] = array('decimal', $num[0]);
  171. }
  172. }
  173. return $data;
  174. }
  175. /**
  176. * Return a random decimal string. Based on DECIMAL(M,D) configuration.
  177. *
  178. * @see DECIMAL type, http://dev.mysql.com/doc/refman/5.0/en/numeric-type-overview.html#id4944739
  179. * @see Config/Hashmark.php, $config['DbHelper']
  180. * @return string
  181. */
  182. public static function randomDecimal()
  183. {
  184. $decimalTotalWidth = Hashmark::getConfig('DbHelper', '', 'decimal_total_width');
  185. $decimalRightWidth = Hashmark::getConfig('DbHelper', '', 'decimal_right_width');
  186. // Random DECIMAL(M,D) numbers.
  187. // Before decimal point:
  188. $value = '';
  189. $wholeDigits = mt_rand(1, $decimalTotalWidth - $decimalRightWidth);
  190. for ($d = 0; $d < $wholeDigits; $d++) {
  191. $value .= mt_rand(0, 9);
  192. }
  193. // After:
  194. $value = preg_replace('/^0+/', '', $value) . '.';
  195. $pointDigits = mt_rand(1, $decimalRightWidth);
  196. for ($d = 0; $d < $pointDigits; $d++) {
  197. $value .= mt_rand(0, 9);
  198. }
  199. return $value;
  200. }
  201. /**
  202. * Return a random string.
  203. *
  204. * @param int $minLength 1 to 40.
  205. * @param int $maxLength 1 to 40.
  206. * @return string
  207. * @throws Exception If $minLength or $maxLength is greater than 40 or negative.
  208. */
  209. public static function randomString($minLength = 30, $maxLength = 30)
  210. {
  211. $str = Hashmark_Util::randomSha1();
  212. if ($maxLength > 0 && $maxLength < 41 && $minLength > 0 && $minLength <= $maxLength) {
  213. return substr($str, 0, mt_rand($minLength, $maxLength));
  214. }
  215. throw new Exception('Random string limits are invalid.', HASHMARK_EXCEPTION_VALIDATION);
  216. }
  217. /**
  218. * Testable logic for assertArrayContainsOnly().
  219. *
  220. * @param mixed $needle Only expected element of $haystack.
  221. * @param Array $haystack
  222. * @param boolean $strict If true, $a === $b logic is used; othewise in_array().
  223. * @return boolean True if $haystack only contains one $needle.
  224. */
  225. public static function checkArrayContainsOnly($needle, $haystack, $strict = false)
  226. {
  227. if (!is_array($haystack) || count($haystack) != 1) {
  228. return false;
  229. }
  230. if ($strict) {
  231. $values = array_values($haystack);
  232. return $values[0] === $needle;
  233. } else {
  234. return in_array($needle, $haystack);
  235. }
  236. }
  237. /**
  238. * Assert $haystack contains only one element that is equal to $needle.
  239. *
  240. * - Uses assertTrue() internally to increment assertion count.
  241. *
  242. * @param mixed $needle Only expected element of $haystack.
  243. * @param Array $haystack
  244. * @param boolean $strict If true, $a === $b logic is used; othewise in_array().
  245. * @return void
  246. */
  247. public function assertArrayContainsOnly($needle, $haystack, $message = '')
  248. {
  249. if (self::checkArrayContainsOnly($needle, $haystack, $message)) {
  250. $this->assertTrue(true);
  251. } else {
  252. $needleType = gettype($needle);
  253. $needle = str_replace("\n", '', print_r($needle, true));
  254. $haystackType = gettype($haystack);
  255. $haystack = str_replace("\n", '', print_r($haystack, true));
  256. if ($message) {
  257. $message .= "\n";
  258. }
  259. $message .= "Failed asserting that Array <{$haystackType}:{$haystack}> "
  260. . "contains only element <{$needleType}:{$needle}>.";
  261. $this->assertTrue(false, $message);
  262. }
  263. }
  264. /**
  265. * Testable logic for assertDecimalEquals().
  266. *
  267. * @param string $expected
  268. * @param string $actual
  269. * @return boolean True if equal.
  270. */
  271. public static function checkDecimalEquals($expected, $actual)
  272. {
  273. if (!is_string($expected) || !is_string($actual)) {
  274. return false;
  275. }
  276. bcscale(Hashmark::getConfig('DbHelper', '', 'decimal_right_width'));
  277. return 0 === bccomp($expected, $actual);
  278. }
  279. /**
  280. * Uses bccomp() to check equality of two strings representing decimal values.
  281. *
  282. * - Uses assertTrue() internally to increment assertion count.
  283. *
  284. * @param string $expected
  285. * @param string $actual
  286. * @return void
  287. */
  288. public function assertDecimalEquals($expected, $actual, $message = '')
  289. {
  290. if (self::checkDecimalEquals($expected, $actual)) {
  291. $this->assertTrue(true);
  292. } else {
  293. $actualType = gettype($actual);
  294. $expectedType = gettype($expected);
  295. if ($message) {
  296. $message .= "\n";
  297. }
  298. $message .= "Failed asserting that actual decimal string <{$actualType}:"
  299. . "{$actual}> equals expected <{$expectedType}:{$expected}>.";
  300. $this->assertTrue(false, $message);
  301. }
  302. }
  303. }