testcase.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318
  1. <?php
  2. require_once dirname( __FILE__ ) . '/factory.php';
  3. require_once dirname( __FILE__ ) . '/trac.php';
  4. class WP_UnitTestCase extends PHPUnit_Framework_TestCase {
  5. protected static $forced_tickets = array();
  6. protected $expected_deprecated = array();
  7. protected $caught_deprecated = array();
  8. protected $expected_doing_it_wrong = array();
  9. protected $caught_doing_it_wrong = array();
  10. /**
  11. * @var WP_UnitTest_Factory
  12. */
  13. protected $factory;
  14. function setUp() {
  15. set_time_limit(0);
  16. global $wpdb;
  17. $wpdb->suppress_errors = false;
  18. $wpdb->show_errors = true;
  19. $wpdb->db_connect();
  20. ini_set('display_errors', 1 );
  21. $this->factory = new WP_UnitTest_Factory;
  22. $this->clean_up_global_scope();
  23. $this->start_transaction();
  24. $this->expectDeprecated();
  25. add_filter( 'wp_die_handler', array( $this, 'get_wp_die_handler' ) );
  26. }
  27. function tearDown() {
  28. global $wpdb;
  29. $this->expectedDeprecated();
  30. $wpdb->query( 'ROLLBACK' );
  31. remove_filter( 'dbdelta_create_queries', array( $this, '_create_temporary_tables' ) );
  32. remove_filter( 'query', array( $this, '_drop_temporary_tables' ) );
  33. remove_filter( 'wp_die_handler', array( $this, 'get_wp_die_handler' ) );
  34. }
  35. function clean_up_global_scope() {
  36. $_GET = array();
  37. $_POST = array();
  38. $this->flush_cache();
  39. }
  40. function flush_cache() {
  41. global $wp_object_cache;
  42. $wp_object_cache->group_ops = array();
  43. $wp_object_cache->stats = array();
  44. $wp_object_cache->memcache_debug = array();
  45. $wp_object_cache->cache = array();
  46. if ( method_exists( $wp_object_cache, '__remoteset' ) ) {
  47. $wp_object_cache->__remoteset();
  48. }
  49. wp_cache_flush();
  50. wp_cache_add_global_groups( array( 'users', 'userlogins', 'usermeta', 'user_meta', 'site-transient', 'site-options', 'site-lookup', 'blog-lookup', 'blog-details', 'rss', 'global-posts', 'blog-id-cache' ) );
  51. wp_cache_add_non_persistent_groups( array( 'comment', 'counts', 'plugins' ) );
  52. }
  53. function start_transaction() {
  54. global $wpdb;
  55. $wpdb->query( 'SET autocommit = 0;' );
  56. $wpdb->query( 'START TRANSACTION;' );
  57. add_filter( 'dbdelta_create_queries', array( $this, '_create_temporary_tables' ) );
  58. add_filter( 'query', array( $this, '_drop_temporary_tables' ) );
  59. }
  60. function _create_temporary_tables( $queries ) {
  61. return str_replace( 'CREATE TABLE', 'CREATE TEMPORARY TABLE', $queries );
  62. }
  63. function _drop_temporary_tables( $query ) {
  64. if ( 'DROP TABLE' === substr( $query, 0, 10 ) )
  65. return 'DROP TEMPORARY TABLE ' . substr( $query, 10 );
  66. return $query;
  67. }
  68. function get_wp_die_handler( $handler ) {
  69. return array( $this, 'wp_die_handler' );
  70. }
  71. function wp_die_handler( $message ) {
  72. throw new WPDieException( $message );
  73. }
  74. function expectDeprecated() {
  75. $annotations = $this->getAnnotations();
  76. foreach ( array( 'class', 'method' ) as $depth ) {
  77. if ( ! empty( $annotations[ $depth ]['expectedDeprecated'] ) )
  78. $this->expected_deprecated = array_merge( $this->expected_deprecated, $annotations[ $depth ]['expectedDeprecated'] );
  79. if ( ! empty( $annotations[ $depth ]['expectedIncorrectUsage'] ) )
  80. $this->expected_doing_it_wrong = array_merge( $this->expected_doing_it_wrong, $annotations[ $depth ]['expectedIncorrectUsage'] );
  81. }
  82. add_action( 'deprecated_function_run', array( $this, 'deprecated_function_run' ) );
  83. add_action( 'deprecated_argument_run', array( $this, 'deprecated_function_run' ) );
  84. add_action( 'doing_it_wrong_run', array( $this, 'doing_it_wrong_run' ) );
  85. add_action( 'deprecated_function_trigger_error', '__return_false' );
  86. add_action( 'deprecated_argument_trigger_error', '__return_false' );
  87. add_action( 'doing_it_wrong_trigger_error', '__return_false' );
  88. }
  89. function expectedDeprecated() {
  90. $not_caught_deprecated = array_diff( $this->expected_deprecated, $this->caught_deprecated );
  91. foreach ( $not_caught_deprecated as $not_caught ) {
  92. $this->fail( "Failed to assert that $not_caught triggered a deprecated notice" );
  93. }
  94. $unexpected_deprecated = array_diff( $this->caught_deprecated, $this->expected_deprecated );
  95. foreach ( $unexpected_deprecated as $unexpected ) {
  96. $this->fail( "Unexpected deprecated notice for $unexpected" );
  97. }
  98. $not_caught_doing_it_wrong = array_diff( $this->expected_doing_it_wrong, $this->caught_doing_it_wrong );
  99. foreach ( $not_caught_doing_it_wrong as $not_caught ) {
  100. $this->fail( "Failed to assert that $not_caught triggered an incorrect usage notice" );
  101. }
  102. $unexpected_doing_it_wrong = array_diff( $this->caught_doing_it_wrong, $this->expected_doing_it_wrong );
  103. foreach ( $unexpected_doing_it_wrong as $unexpected ) {
  104. $this->fail( "Unexpected incorrect usage notice for $unexpected" );
  105. }
  106. }
  107. function deprecated_function_run( $function ) {
  108. if ( ! in_array( $function, $this->caught_deprecated ) )
  109. $this->caught_deprecated[] = $function;
  110. }
  111. function doing_it_wrong_run( $function ) {
  112. if ( ! in_array( $function, $this->caught_doing_it_wrong ) )
  113. $this->caught_doing_it_wrong[] = $function;
  114. }
  115. function assertWPError( $actual, $message = '' ) {
  116. $this->assertInstanceOf( 'WP_Error', $actual, $message );
  117. }
  118. function assertEqualFields( $object, $fields ) {
  119. foreach( $fields as $field_name => $field_value ) {
  120. if ( $object->$field_name != $field_value ) {
  121. $this->fail();
  122. }
  123. }
  124. }
  125. function assertDiscardWhitespace( $expected, $actual ) {
  126. $this->assertEquals( preg_replace( '/\s*/', '', $expected ), preg_replace( '/\s*/', '', $actual ) );
  127. }
  128. function assertEqualSets( $expected, $actual ) {
  129. $this->assertEquals( array(), array_diff( $expected, $actual ) );
  130. $this->assertEquals( array(), array_diff( $actual, $expected ) );
  131. }
  132. function go_to( $url ) {
  133. // note: the WP and WP_Query classes like to silently fetch parameters
  134. // from all over the place (globals, GET, etc), which makes it tricky
  135. // to run them more than once without very carefully clearing everything
  136. $_GET = $_POST = array();
  137. foreach (array('query_string', 'id', 'postdata', 'authordata', 'day', 'currentmonth', 'page', 'pages', 'multipage', 'more', 'numpages', 'pagenow') as $v) {
  138. if ( isset( $GLOBALS[$v] ) ) unset( $GLOBALS[$v] );
  139. }
  140. $parts = parse_url($url);
  141. if (isset($parts['scheme'])) {
  142. $req = $parts['path'];
  143. if (isset($parts['query'])) {
  144. $req .= '?' . $parts['query'];
  145. // parse the url query vars into $_GET
  146. parse_str($parts['query'], $_GET);
  147. }
  148. } else {
  149. $req = $url;
  150. }
  151. if ( ! isset( $parts['query'] ) ) {
  152. $parts['query'] = '';
  153. }
  154. $_SERVER['REQUEST_URI'] = $req;
  155. unset($_SERVER['PATH_INFO']);
  156. $this->flush_cache();
  157. unset($GLOBALS['wp_query'], $GLOBALS['wp_the_query']);
  158. $GLOBALS['wp_the_query'] = new WP_Query();
  159. $GLOBALS['wp_query'] = $GLOBALS['wp_the_query'];
  160. $GLOBALS['wp'] = new WP();
  161. _cleanup_query_vars();
  162. $GLOBALS['wp']->main($parts['query']);
  163. }
  164. protected function checkRequirements() {
  165. parent::checkRequirements();
  166. if ( WP_TESTS_FORCE_KNOWN_BUGS )
  167. return;
  168. $tickets = PHPUnit_Util_Test::getTickets( get_class( $this ), $this->getName( false ) );
  169. foreach ( $tickets as $ticket ) {
  170. if ( is_numeric( $ticket ) ) {
  171. $this->knownWPBug( $ticket );
  172. } elseif ( 'UT' == substr( $ticket, 0, 2 ) ) {
  173. $ticket = substr( $ticket, 2 );
  174. if ( $ticket && is_numeric( $ticket ) )
  175. $this->knownUTBug( $ticket );
  176. } elseif ( 'Plugin' == substr( $ticket, 0, 6 ) ) {
  177. $ticket = substr( $ticket, 6 );
  178. if ( $ticket && is_numeric( $ticket ) )
  179. $this->knownPluginBug( $ticket );
  180. }
  181. }
  182. }
  183. /**
  184. * Skips the current test if there is an open WordPress ticket with id $ticket_id
  185. */
  186. function knownWPBug( $ticket_id ) {
  187. if ( WP_TESTS_FORCE_KNOWN_BUGS || in_array( $ticket_id, self::$forced_tickets ) )
  188. return;
  189. if ( ! TracTickets::isTracTicketClosed( 'https://core.trac.wordpress.org', $ticket_id ) )
  190. $this->markTestSkipped( sprintf( 'WordPress Ticket #%d is not fixed', $ticket_id ) );
  191. }
  192. /**
  193. * Skips the current test if there is an open unit tests ticket with id $ticket_id
  194. */
  195. function knownUTBug( $ticket_id ) {
  196. if ( WP_TESTS_FORCE_KNOWN_BUGS || in_array( 'UT' . $ticket_id, self::$forced_tickets ) )
  197. return;
  198. if ( ! TracTickets::isTracTicketClosed( 'https://unit-tests.trac.wordpress.org', $ticket_id ) )
  199. $this->markTestSkipped( sprintf( 'Unit Tests Ticket #%d is not fixed', $ticket_id ) );
  200. }
  201. /**
  202. * Skips the current test if there is an open plugin ticket with id $ticket_id
  203. */
  204. function knownPluginBug( $ticket_id ) {
  205. if ( WP_TESTS_FORCE_KNOWN_BUGS || in_array( 'Plugin' . $ticket_id, self::$forced_tickets ) )
  206. return;
  207. if ( ! TracTickets::isTracTicketClosed( 'https://plugins.trac.wordpress.org', $ticket_id ) )
  208. $this->markTestSkipped( sprintf( 'WordPress Plugin Ticket #%d is not fixed', $ticket_id ) );
  209. }
  210. public static function forceTicket( $ticket ) {
  211. self::$forced_tickets[] = $ticket;
  212. }
  213. /**
  214. * Define constants after including files.
  215. */
  216. function prepareTemplate( Text_Template $template ) {
  217. $template->setVar( array( 'constants' => '' ) );
  218. $template->setVar( array( 'wp_constants' => PHPUnit_Util_GlobalState::getConstantsAsString() ) );
  219. parent::prepareTemplate( $template );
  220. }
  221. /**
  222. * Returns the name of a temporary file
  223. */
  224. function temp_filename() {
  225. $tmp_dir = '';
  226. $dirs = array( 'TMP', 'TMPDIR', 'TEMP' );
  227. foreach( $dirs as $dir )
  228. if ( isset( $_ENV[$dir] ) && !empty( $_ENV[$dir] ) ) {
  229. $tmp_dir = $dir;
  230. break;
  231. }
  232. if ( empty( $tmp_dir ) ) {
  233. $tmp_dir = '/tmp';
  234. }
  235. $tmp_dir = realpath( $dir );
  236. return tempnam( $tmp_dir, 'wpunit' );
  237. }
  238. /**
  239. * Check each of the WP_Query is_* functions/properties against expected boolean value.
  240. *
  241. * Any properties that are listed by name as parameters will be expected to be true; any others are
  242. * expected to be false. For example, assertQueryTrue('is_single', 'is_feed') means is_single()
  243. * and is_feed() must be true and everything else must be false to pass.
  244. *
  245. * @param string $prop,... Any number of WP_Query properties that are expected to be true for the current request.
  246. */
  247. function assertQueryTrue(/* ... */) {
  248. global $wp_query;
  249. $all = array(
  250. 'is_single', 'is_preview', 'is_page', 'is_archive', 'is_date', 'is_year', 'is_month', 'is_day', 'is_time',
  251. 'is_author', 'is_category', 'is_tag', 'is_tax', 'is_search', 'is_feed', 'is_comment_feed', 'is_trackback',
  252. 'is_home', 'is_404', 'is_comments_popup', 'is_paged', 'is_admin', 'is_attachment', 'is_singular', 'is_robots',
  253. 'is_posts_page', 'is_post_type_archive',
  254. );
  255. $true = func_get_args();
  256. $passed = true;
  257. $not_false = $not_true = array(); // properties that were not set to expected values
  258. foreach ( $all as $query_thing ) {
  259. $result = is_callable( $query_thing ) ? call_user_func( $query_thing ) : $wp_query->$query_thing;
  260. if ( in_array( $query_thing, $true ) ) {
  261. if ( ! $result ) {
  262. array_push( $not_true, $query_thing );
  263. $passed = false;
  264. }
  265. } else if ( $result ) {
  266. array_push( $not_false, $query_thing );
  267. $passed = false;
  268. }
  269. }
  270. $message = '';
  271. if ( count($not_true) )
  272. $message .= implode( $not_true, ', ' ) . ' should be true. ';
  273. if ( count($not_false) )
  274. $message .= implode( $not_false, ', ' ) . ' should be false.';
  275. $this->assertTrue( $passed, $message );
  276. }
  277. }