rules.test 87 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101
  1. <?php
  2. /**
  3. * @file
  4. * Rules tests.
  5. */
  6. class RulesTestCase extends DrupalWebTestCase {
  7. static function getInfo() {
  8. return array(
  9. 'name' => 'Rules Engine tests',
  10. 'description' => 'Test using the rules API to create and evaluate rules.',
  11. 'group' => 'Rules',
  12. );
  13. }
  14. function setUp() {
  15. parent::setUp('rules', 'rules_test');
  16. RulesLog::logger()->clear();
  17. variable_set('rules_debug_log', 1);
  18. }
  19. /**
  20. * Calculates the output of t() given an array of placeholders to replace.
  21. */
  22. static function t($text, $strings) {
  23. $placeholders = array();
  24. foreach ($strings as $key => $string) {
  25. $key = !is_numeric($key) ? $key : $string;
  26. $placeholders['%' . $key] = drupal_placeholder($string);
  27. }
  28. return strtr($text, $placeholders);
  29. }
  30. protected function createTestRule() {
  31. $rule = rule();
  32. $rule->condition('rules_test_condition_true')
  33. ->condition('rules_test_condition_true')
  34. ->condition(rules_or()
  35. ->condition(rules_condition('rules_test_condition_true')->negate())
  36. ->condition('rules_test_condition_false')
  37. ->condition(rules_and()
  38. ->condition('rules_test_condition_false')
  39. ->condition('rules_test_condition_true')
  40. ->negate()
  41. )
  42. );
  43. $rule->action('rules_test_action');
  44. return $rule;
  45. }
  46. /**
  47. * Tests creating a rule and iterating over the rule elements.
  48. */
  49. function testRuleCreation() {
  50. $rule = $this->createTestRule();
  51. $rule->integrityCheck();
  52. $rule->execute();
  53. $log = RulesLog::logger()->get();
  54. $last = array_pop($log);
  55. $last = array_pop($log);
  56. $last = array_pop($log);
  57. $this->assertEqual($last[0], 'action called', 'Action called');
  58. RulesLog::logger()->checkLog();
  59. // Make sure condition and action iterators are working.
  60. $it = new RecursiveIteratorIterator($rule->conditions(), RecursiveIteratorIterator::SELF_FIRST);
  61. $this->assertEqual(iterator_count($it), 8, 'Iterated over all conditions and condition containers');
  62. $it = new RecursiveIteratorIterator($rule->conditions());
  63. $this->assertEqual(iterator_count($it), 6, 'Iterated over all conditions');
  64. $this->assertEqual(iterator_count($rule->actions()), 1, 'Iterated over all actions');
  65. $this->assertEqual(iterator_count($rule->elements()), 10, 'Iterated over all rule elements.');
  66. // Test getting dependencies and the integrity check.
  67. $rule->integrityCheck();
  68. $this->assertTrue($rule->dependencies() === array('rules_test'), 'Dependencies correctly returned.');
  69. }
  70. /**
  71. * Test handling dependencies.
  72. */
  73. function testdependencies() {
  74. $action = rules_action('rules_node_publish_action');
  75. $this->assertEqual($action->dependencies(), array('rules_test'), 'Providing module is returned as dependency.');
  76. $container = new RulesTestContainer();
  77. $this->assertEqual($container->dependencies(), array('rules_test'), 'Providing module for container plugin is returned as dependency.');
  78. // Test handling unmet dependencies.
  79. $rule = rules_config_load('rules_export_test');
  80. $this->assertTrue(in_array('comment', $rule->dependencies) && !$rule->dirty, 'Dependencies have been imported.');
  81. // Remove the required comment module and make sure the rule is dirty then.
  82. module_disable(array('comment'));
  83. rules_clear_cache();
  84. $rule = rules_config_load('rules_export_test');
  85. $this->assertTrue($rule->dirty, 'Rule has been marked as dirty');
  86. // Now try re-enabling.
  87. module_enable(array('comment'));
  88. rules_clear_cache();
  89. $rule = rules_config_load('rules_export_test');
  90. $this->assertTrue(!$rule->dirty, 'Rule has been marked as not dirty again.');
  91. // Test it with components.
  92. module_enable(array('path'));
  93. $action_set = rules_action_set(array('node' => array('type' => 'node')));
  94. $action_set->action('node_path_alias');
  95. $action_set->save('rules_test_alias');
  96. $rule = rule(array('node' => array('type' => 'node')));
  97. $rule->action('component_rules_test_alias');
  98. $rule->integrityCheck();
  99. $rule->save('rules_test_rule');
  100. $rule = rules_config_load('rules_test_rule');
  101. $component = rules_config_load('rules_test_alias');
  102. $this->assertTrue(in_array('path', $component->dependencies) && !$rule->dirty && !$component->dirty, 'Component has path module dependency.');
  103. // Now disable path module and make sure both configs are marked as dirty.
  104. module_disable(array('path'));
  105. rules_clear_cache();
  106. $rule = rules_config_load('rules_test_rule');
  107. $component = rules_config_load('rules_test_alias');
  108. $this->assertTrue($component->dirty, 'Component has been marked as dirty');
  109. $node = $this->drupalCreateNode();
  110. $result = rules_invoke_component('rules_test_alias', $node);
  111. $this->assertTrue($result === FALSE, 'Unable to execute a dirty component.');
  112. // When the rule is evaluated, the broken component is detected and the
  113. // rule should be marked as dirty too.
  114. $rule->execute($node);
  115. $this->assertTrue($rule->dirty, 'Rule has been marked as dirty');
  116. module_enable(array('path'));
  117. rules_clear_cache();
  118. // Trigger rebuilding the cache, so configs are checked again.
  119. rules_get_cache();
  120. $rule = rules_config_load('rules_test_rule');
  121. $component = rules_config_load('rules_test_alias');
  122. $this->assertTrue(!$component->dirty, 'Component has been marked as not dirty again.');
  123. $this->assertTrue(!$rule->dirty, 'Rule has been marked as not dirty again.');
  124. }
  125. /**
  126. * Test setting up an action with some action_info and serializing and
  127. * executing it.
  128. */
  129. function testActionSetup() {
  130. $action = rules_action('rules_node_publish_action');
  131. $s = serialize($action);
  132. $action2 = unserialize($s);
  133. $node = (object) array('status' => 0, 'type' => 'page');
  134. $node->title = 'test';
  135. $action2->execute($node);
  136. $this->assertEqual($node->status, 1, 'Action executed correctly');
  137. $this->assertTrue(in_array('node', array_keys($action2->parameterInfo())), 'Parameter info returned.');
  138. $node->status = 0;
  139. $action2->integrityCheck();
  140. $action2->executeByArgs(array('node' => $node));
  141. $this->assertEqual($node->status, 1, 'Action executed correctly');
  142. // Test calling an extended + overriden method.
  143. $this->assertEqual($action2->help(), 'custom', 'Using custom help callback.');
  144. // Inspect the cache
  145. //$this->pass(serialize(rules_get_cache()));
  146. RulesLog::logger()->checkLog();
  147. }
  148. /**
  149. * Test executing with wrong arguments.
  150. */
  151. function testActionExecutionFails() {
  152. $action = rules_action('rules_node_publish_action');
  153. try {
  154. $action->execute();
  155. $this->fail("Execution hasn't created an exception.");
  156. }
  157. catch (RulesEvaluationException $e) {
  158. $this->pass("RulesEvaluationException was thrown: ". $e);
  159. }
  160. }
  161. /**
  162. * Test setting up a rule and mapping variables.
  163. */
  164. function testVariableMapping() {
  165. $rule = rule(array(
  166. 'node' => array('type' => 'node'),
  167. 'node_unchanged' => array('type' => 'node'),
  168. ));
  169. $rule->condition(rules_condition('rules_condition_content_is_published')->negate())
  170. ->condition('rules_condition_content_is_type', array('type' => array('page', 'story')))
  171. ->action('rules_node_publish_action', array('node:select' => 'node_unchanged'));
  172. $node1 = $this->drupalCreateNode(array('status' => 0, 'type' => 'page'));
  173. $node2 = $this->drupalCreateNode(array('status' => 0, 'type' => 'page'));
  174. $rule->integrityCheck();
  175. $rule->execute($node1, $node2);
  176. $this->assertEqual($node2->status, 1, 'Action executed correctly on node2.');
  177. $this->assertEqual($node1->status, 0, 'Action not executed on node1.');
  178. RulesLog::logger()->checkLog();
  179. }
  180. /**
  181. * Tests making use of class based actions.
  182. */
  183. function testClassBasedActions() {
  184. $cache = rules_get_cache();
  185. $this->assertTrue(!empty($cache['action_info']['rules_test_class_action']), 'Action has been discovered.');
  186. $action = rules_action('rules_test_class_action');
  187. $parameters = $action->parameterInfo();
  188. $this->assertTrue($parameters['node'], 'Action parameter needs a value.');
  189. $node = $this->drupalCreateNode();
  190. $action->execute($node);
  191. $log = RulesLog::logger()->get();
  192. $last = array_pop($log);
  193. $last = array_pop($log);
  194. $this->assertEqual($last[0], 'Action called with node ' . $node->nid, 'Action called');
  195. RulesLog::logger()->checkLog();
  196. }
  197. /**
  198. * Tests CRUD functionality.
  199. */
  200. function testRulesCRUD() {
  201. $rule = $this->createTestRule();
  202. $rule->integrityCheck()->save('test');
  203. $this->assertEqual(TRUE, $rule->active, 'Rule is active.');
  204. $this->assertEqual(0, $rule->weight, 'Rule weight is zero.');
  205. $results = entity_load('rules_config', array('test'));
  206. $rule2 = array_pop($results);
  207. $this->assertEqual($rule->id, $rule2->id, 'Rule created and loaded');
  208. $this->assertEqual(get_class($rule2), get_class($rule), 'Class properly instantiated.');
  209. $rule2->execute();
  210. // Update.
  211. $rule2->save();
  212. // Make sure all rule elements are still here.
  213. $it = new RecursiveIteratorIterator($rule2->conditions(), RecursiveIteratorIterator::SELF_FIRST);
  214. $this->assertEqual(iterator_count($it), 8, 'Iterated over all conditions and condition containers');
  215. $it = new RecursiveIteratorIterator($rule2->conditions());
  216. $this->assertEqual(iterator_count($it), 6, 'Iterated over all conditions');
  217. $this->assertEqual(iterator_count($rule2->actions()), 1, 'Iterated over all actions');
  218. // Delete.
  219. $rule2->delete();
  220. $this->assertEqual(entity_load('rules_config', FALSE, array('id' => $rule->id)), array(), 'Deleted.');
  221. // Tests CRUD for tags - making sure the tags are stored properly..
  222. $rule = $this->createTestRule();
  223. $tag = $this->randomString();
  224. $rule->tags = array($tag);
  225. $rule->save();
  226. $result = db_select('rules_tags')
  227. ->fields('rules_tags', array('tag'))
  228. ->condition('id', $rule->id)
  229. ->execute();
  230. $this->assertEqual($result->fetchField(), $tag, 'Associated tag has been saved.');
  231. // Try updating.
  232. $rule->tags = array($this->randomName(), $this->randomName());
  233. $rule->integrityCheck()->save();
  234. $result = db_select('rules_tags')
  235. ->fields('rules_tags', array('tag'))
  236. ->condition('id', $rule->id)
  237. ->execute()
  238. ->fetchCol();
  239. $this->assertTrue(in_array($rule->tags[0], $result) && in_array($rule->tags[1], $result), 'Updated associated tags.');
  240. // Try loading multiple rules by tags.
  241. $rule2 = $this->createTestRule();
  242. $rule2->tags = array($this->randomName());
  243. $rule2->save();
  244. $loaded = entity_load('rules_config', FALSE, array('tags' => array($rule->tags[0], $rule2->tags[0])));
  245. $this->assertTrue($loaded[$rule->id]->id == $rule->id && $loaded[$rule2->id]->id == $rule2->id, 'Loading configs by tags');
  246. // Try deleting.
  247. $rule->delete();
  248. $result = db_select('rules_tags')
  249. ->fields('rules_tags', array('tag'))
  250. ->condition('id', $rule->id)
  251. ->execute();
  252. $this->assertEqual($result->fetchField(), FALSE, 'Deleted associated tags.');
  253. }
  254. /**
  255. * Test automatic saving of variables.
  256. */
  257. function testActionSaving() {
  258. // Test saving a parameter.
  259. $action = rules_action('rules_node_publish_action_save');
  260. $node = $this->drupalCreateNode(array('status' => 0, 'type' => 'page'));
  261. $action->executeByArgs(array('node' => $node));
  262. $this->assertEqual($node->status, 1, 'Action executed correctly on node.');
  263. // Sync node_load cache with node_save
  264. entity_get_controller('node')->resetCache();
  265. $node = node_load($node->nid);
  266. $this->assertEqual($node->status, 1, 'Node has been saved.');
  267. // Now test saving a provided variable, which is renamed and modified before
  268. // it is saved.
  269. $title = $this->randomName();
  270. $rule = rule();
  271. $rule->action('entity_create', array(
  272. 'type' => 'node',
  273. 'param_type' => 'article',
  274. 'param_author:select' => 'site:current-user',
  275. 'param_title' => $title,
  276. 'entity_created:var' => 'node',
  277. ));
  278. $rule->action('data_set', array(
  279. 'data:select' => 'node:body',
  280. 'value' => array('value' => 'body'),
  281. ));
  282. $rule->integrityCheck();
  283. $rule->execute();
  284. $node = $this->drupalGetNodeByTitle($title);
  285. $this->assertTrue(!empty($node) && $node->body[LANGUAGE_NONE][0]['value'] == 'body', 'Saved a provided variable');
  286. RulesLog::logger()->checkLog();
  287. }
  288. /**
  289. * Test adding a variable and optional parameters.
  290. */
  291. function testVariableAdding() {
  292. $node = $this->drupalCreateNode();
  293. $rule = rule(array('nid' => array('type' => 'integer')));
  294. $rule->condition('rules_test_condition_true')
  295. ->action('rules_action_load_node')
  296. ->action('rules_action_delete_node', array('node:select' => 'node_loaded'))
  297. ->execute($node->nid);
  298. $this->assertEqual(FALSE, node_load($node->nid), 'Variable added and skipped optional parameter.');
  299. RulesLog::logger()->checkLog();
  300. $vars = $rule->conditions()->offsetGet(0)->availableVariables();
  301. $this->assertEqual(!isset($vars['node_loaded']), 'Loaded variable is not available to conditions.');
  302. // Test adding a variable with a custom variable name.
  303. $node = $this->drupalCreateNode();
  304. $rule = rule(array('nid' => array('type' => 'integer')));
  305. $rule->action('rules_action_load_node', array('node_loaded:var' => 'node'))
  306. ->action('rules_action_delete_node')
  307. ->execute($node->nid);
  308. $this->assertEqual(FALSE, node_load($node->nid), 'Variable with custom name added.');
  309. RulesLog::logger()->checkLog();
  310. }
  311. /**
  312. * Test custom access for using component actions/conditions.
  313. */
  314. function testRuleComponentAccess() {
  315. // Create a normal user.
  316. $normal_user = $this->drupalCreateUser();
  317. // Create a role for granting access to the rule component.
  318. $this->normal_role = $this->drupalCreateRole(array(), 'test_role');
  319. $normal_user->roles[$this->normal_role] = 'test_role';
  320. user_save($normal_user, array('roles' => $normal_user->roles));
  321. // Create an 'action set' rule component making use of a permission.
  322. $action_set = rules_action_set(array('node' => array('type' => 'node')));
  323. $action_set->access_exposed = TRUE;
  324. $action_set->save('rules_test_roles');
  325. // Set the global user to be the current one as access is checked for the
  326. // global user.
  327. global $user;
  328. $user = user_load($normal_user->uid);
  329. $this->assertFalse(rules_action('component_rules_test_roles')->access(), 'Authenticated user without the correct role can\'t use the rule component.');
  330. // Assign the role that will have permissions for the rule component.
  331. user_role_change_permissions($this->normal_role, array('use Rules component rules_test_roles' => TRUE));
  332. $this->assertTrue(rules_action('component_rules_test_roles')->access(), 'Authenticated user with the correct role can use the rule component.');
  333. // Reset global user to anonyous.
  334. $user = user_load(0);
  335. $this->assertFalse(rules_action('component_rules_test_roles')->access(), 'Anonymous user can\'t use the rule component.');
  336. }
  337. /**
  338. * Test passing arguments by reference to an action.
  339. */
  340. function testPassingByReference() {
  341. // Keeping references of variables is unsupported, though the
  342. // EntityMetadataArrayObject may be used to achieve that.
  343. $array = array('foo' => 'bar');
  344. $data = new EntityMetadataArrayObject($array);
  345. rules_action('rules_action_test_reference')->execute($data);
  346. $this->assertTrue($data['changed'], 'Parameter has been passed by reference');
  347. }
  348. /**
  349. * Test sorting rule elements.
  350. */
  351. function testSorting() {
  352. $rule = $this->createTestRule();
  353. $conditions = $rule->conditions();
  354. $conditions[0]->weight = 10;
  355. $conditions[2]->weight = 10;
  356. $id[0] = $conditions[0]->elementId();
  357. $id[1] = $conditions[1]->elementId();
  358. $id[2] = $conditions[2]->elementId();
  359. // For testing use a deep sort, even if not necessary here.
  360. $rule->sortChildren(TRUE);
  361. $conditions = $rule->conditions();
  362. $this->assertEqual($conditions[0]->elementId(), $id[1], 'Condition sorted correctly.');
  363. $this->assertEqual($conditions[1]->elementId(), $id[0], 'Condition sorted correctly.');
  364. $this->assertEqual($conditions[2]->elementId(), $id[2], 'Condition sorted correctly.');
  365. }
  366. /**
  367. * Tests using data selectors.
  368. */
  369. function testDataSelectors() {
  370. $body[LANGUAGE_NONE][0] = array('value' => '<b>The body & nothing.</b>');
  371. $node = $this->drupalCreateNode(array('body' => $body, 'type' => 'page', 'summary' => ''));
  372. $rule = rule(array('nid' => array('type' => 'integer')));
  373. $rule->action('rules_action_load_node')
  374. ->action('drupal_message', array('message:select' => 'node_loaded:body:value'))
  375. ->execute($node->nid);
  376. RulesLog::logger()->checkLog();
  377. $msg = drupal_get_messages('status');
  378. $last_msg = array_pop($msg['status']);
  379. $wrapper = entity_metadata_wrapper('node', $node);
  380. $this->assertEqual($last_msg, $wrapper->body->value->value(array('sanitize' => TRUE)), 'Data selector for getting parameter applied.');
  381. // Get a "reference" on the same object as returned by node_load().
  382. $node = node_load($node->nid);
  383. $rule = rule(array('nid' => array('type' => 'integer')));
  384. $rule->action('rules_action_load_node')
  385. ->action('data_set', array('data:select' => 'node_loaded:title', 'value' => 'Test title'))
  386. // Use two actions and make sure the node get saved only once.
  387. ->action('data_set', array('data:select' => 'node_loaded:title', 'value' => 'Test title2'))
  388. ->execute($node->nid);
  389. $wrapper = entity_metadata_wrapper('node', $node);
  390. $this->assertEqual('Test title2', $wrapper->title->value(), 'Data has been modified and saved.');
  391. RulesLog::logger()->checkLog();
  392. $text = RulesLog::logger()->render();
  393. $msg = RulesTestCase::t('Saved %node_loaded of type %node.', array('node_loaded', 'node'));
  394. if ($pos1 = strpos($text, $msg)) {
  395. $pos2 = strpos($text, $msg, $pos1 + 1);
  396. }
  397. $this->assertTrue($pos1 && $pos2 === FALSE, 'Data has been saved only once.');
  398. // Test validation.
  399. try {
  400. rules_action('data_set', array('data' => 'no-selector', 'value' => ''))->integrityCheck();
  401. $this->fail("Validation hasn't created an exception.");
  402. }
  403. catch (RulesIntegrityException $e) {
  404. $this->pass("Validation error correctly detected: ". $e);
  405. }
  406. // Test auto creation of nested data structures, like the node body field.
  407. // I.e. if $node->body is not set, it is automatically initialized to an
  408. // empty array, so that the nested value can be set and the wrappers do not
  409. // complain about missing parent data structures.
  410. $rule = rule();
  411. $rule->action('entity_create', array(
  412. 'type' => 'node',
  413. 'param_type' => 'page',
  414. 'param_title' => 'foo',
  415. 'param_author' => $GLOBALS['user'],
  416. ));
  417. $rule->action('data_set', array('data:select' => 'entity_created:body:value', 'value' => 'test content'))
  418. ->execute();
  419. try {
  420. RulesLog::logger()->checkLog();
  421. $this->pass('Auto creation of nested data structures.');
  422. }
  423. catch (Exception $e) {
  424. $this->fail('Auto creation of nested data structures.');
  425. }
  426. // Make sure variables that are passed wrapped work.
  427. $result = rules_condition('rules_test_condition_node_wrapped')->execute($node->nid);
  428. $this->assertTrue($result, 'Condition receiving wrapped parameter.');
  429. // Make sure wrapped parameters are checked for containing NULL values.
  430. $rule = rule(array('node' => array('type' => 'node', 'optional' => TRUE)));
  431. $rule->condition('rules_test_condition_node_wrapped', array('node:select' => 'node'));
  432. $rule->execute(entity_metadata_wrapper('node'));
  433. $text = RulesLog::logger()->render();
  434. $msg = RulesTestCase::t('The variable or parameter %node is empty.', array('node'));
  435. $this->assertTrue(strpos($text, $msg) !== FALSE, 'Evaluation aborted due to an empty argument value.');
  436. }
  437. /**
  438. * Tests making use of rule sets.
  439. */
  440. function testRuleSets() {
  441. $set = rules_rule_set(array(
  442. 'node' => array('type' => 'node', 'label' => 'node'),
  443. ));
  444. $set->rule(rule()->action('drupal_message', array('message:select' => 'node:title')))
  445. ->rule(rule()->condition('rules_condition_content_is_published')
  446. ->action('drupal_message', array('message' => 'Node is published.'))
  447. );
  448. $set->integrityCheck()->save('rules_test_set_1');
  449. $node = $this->drupalCreateNode(array('title' => 'The title.', 'status' => 1));
  450. // Execute.
  451. rules_invoke_component('rules_test_set_1', $node);
  452. $msg = drupal_get_messages();
  453. $this->assertEqual($msg['status'][0], 'The title.', 'First rule evaluated.');
  454. $this->assertEqual($msg['status'][1], 'Node is published.', 'Second rule evaluated.');
  455. // Test a condition set.
  456. $set = rules_or(array(
  457. 'node' => array('type' => 'node', 'label' => 'node'),
  458. ));
  459. $set->condition('data_is', array('data:select' => 'node:author:name', 'value' => 'notthename'))
  460. ->condition('data_is', array('data:select' => 'node:nid', 'value' => $node->nid))
  461. ->integrityCheck()
  462. ->save('test', 'rules_test');
  463. // Load and execute condition set.
  464. $set = rules_config_load('test');
  465. $this->assertTrue($set->execute($node), 'Set has been correctly evaluated.');
  466. RulesLog::logger()->checkLog();
  467. }
  468. /**
  469. * Tests invoking components from the action.
  470. */
  471. function testComponentInvocations() {
  472. $set = rules_rule_set(array(
  473. 'node1' => array('type' => 'node', 'label' => 'node'),
  474. ));
  475. $set->rule(rule()->condition('node_is_published', array('node:select' => 'node1'))
  476. ->action('node_unpublish', array('node:select' => 'node1'))
  477. );
  478. $set->integrityCheck()->save('rules_test_set_2');
  479. // Use different names for the variables to ensure they are properly mapped
  480. // when taking over the variables to be saved.
  481. $rule = rule(array(
  482. 'node2' => array('type' => 'node', 'label' => 'node'),
  483. ));
  484. $rule->action('component_rules_test_set_2', array('node1:select' => 'node2'));
  485. $rule->action('node_make_sticky', array('node:select' => 'node2'));
  486. $node = $this->drupalCreateNode(array('title' => 'The title.', 'status' => 1, 'sticky' => 0));
  487. $rule->execute($node);
  488. $node = node_load($node->nid, NULL, TRUE);
  489. $this->assertFalse($node->status, 'The component changes have been saved correctly.');
  490. $this->assertTrue($node->sticky, 'The action changes have been saved correctly.');
  491. // Check that we have saved the changes only once.
  492. $text = RulesLog::logger()->render();
  493. // Make sure both saves are handled in one save operation.
  494. $this->assertEqual(substr_count($text, 'Saved'), 1, 'Changes have been saved in one save operation.');
  495. RulesLog::logger()->checkLog();
  496. // Test recursion prevention on components by invoking the component from
  497. // itself, what should be prevented.
  498. $set->action('component_rules_test_set_2', array('node1:select' => 'node1'))
  499. ->save();
  500. $rule->execute($node);
  501. $text1 = RulesLog::logger()->render();
  502. $text2 = RulesTestCase::t('Not evaluating rule set %rules_test_set_2 to prevent recursion.', array('rules_test_set_2'));
  503. $this->assertTrue((strpos($text1, $text2) !== FALSE), "Recursion of component invocation prevented.");
  504. // Test executing the component provided in code via the action. This makes
  505. // sure the component in code has been properly picked up.
  506. $node->status = 0;
  507. node_save($node);
  508. rules_action('component_rules_test_action_set')->execute($node);
  509. $this->assertTrue($node->status == 1, 'Component provided in code has been executed.');
  510. }
  511. /**
  512. * Test asserting metadata, customizing action info and make sure integrity
  513. * is checked.
  514. */
  515. function testMetadataAssertion() {
  516. $action = rules_action('rules_node_make_sticky_action');
  517. // Test failing integrity check.
  518. try {
  519. $rule = rule(array('node' => array('type' => 'entity')));
  520. $rule->action($action);
  521. // Fails due to the 'node' variable not matching the node type.
  522. $rule->integrityCheck();
  523. $this->fail('Integrity check has not thrown an exception.');
  524. }
  525. catch (RulesIntegrityException $e) {
  526. $this->pass('Integrity check has thrown exception: ' . $e->getMessage());
  527. }
  528. // Test asserting additional metadata.
  529. $rule = rule(array('node' => array('type' => 'node')));
  530. // Customize action info using the settings.
  531. $rule->condition('data_is', array('data:select' => 'node:type', 'value' => 'page'))
  532. // Configure an condition using the body. As the body is a field,
  533. // tis requires the bundle to be correctly asserted.
  534. ->condition(rules_condition('data_is', array('data:select' => 'node:body:value', 'value' => 'foo'))->negate())
  535. // The action also requires the page bundle in order to work.
  536. ->action($action);
  537. // Make sure the integrity check doesn't throw an exception.
  538. $rule->integrityCheck();
  539. // Test the rule.
  540. $node = $this->drupalCreateNode(array('type' => 'page', 'sticky' => 0));
  541. $rule->execute($node);
  542. $this->assertTrue($node->sticky, 'Rule with asserted metadata executed.');
  543. // Test asserting metadata on a derived property, i.e. not a variable.
  544. $rule = rule(array('node' => array('type' => 'node')));
  545. $rule->condition('entity_is_of_type', array('entity:select' => 'node:reference', 'type' => 'node'))
  546. ->condition('data_is', array('data:select' => 'node:reference:type', 'value' => 'page'))
  547. ->action('rules_node_page_make_sticky_action', array('node:select' => 'node:reference'));
  548. $rule->integrityCheck();
  549. $rule->execute($node);
  550. // Test asserting an entity field.
  551. $rule = rule(array('node' => array('type' => 'node')));
  552. $rule->condition('entity_has_field', array('entity:select' => 'node:reference', 'field' => 'field_tags'))
  553. ->action('data_set', array('data:select' => 'node:reference:field-tags', 'value' => array()));
  554. $rule->integrityCheck();
  555. $rule->execute($node);
  556. // Make sure an asserted bundle can be used as argument.
  557. $rule = rule(array('node' => array('type' => 'node')));
  558. $rule->condition('entity_is_of_type', array('entity:select' => 'node:reference', 'type' => 'node'))
  559. ->condition('node_is_of_type', array('node:select' => 'node:reference', 'type' => array('page')))
  560. ->action('rules_node_page_make_sticky_action', array('node:select' => 'node:reference'));
  561. $rule->integrityCheck();
  562. $rule->execute($node);
  563. // Test asserting metadata on a derived property being a list item.
  564. $rule = rule(array('node' => array('type' => 'node')));
  565. $rule->condition('node_is_of_type', array('node:select' => 'node:ref-nodes:0', 'type' => array('article')))
  566. ->action('data_set', array('data:select' => 'node:ref-nodes:0:field-tags', 'value' => array()));
  567. $rule->integrityCheck();
  568. $rule->execute($node);
  569. // Give green lights if there were no exceptions and check rules-log errors.
  570. $this->pass('Rules asserting metadata on a derived property pass integrity checks.');
  571. RulesLog::logger()->checkLog();
  572. // Make sure assertions of a one list item are not valid for another item.
  573. $rule = rule(array('node' => array('type' => 'node')));
  574. $rule->condition('node_is_of_type', array('node:select' => 'node:ref-nodes:0', 'type' => array('article')))
  575. ->action('data_set', array('data:select' => 'node:ref-nodes:1:field-tags', 'value' => array()));
  576. try {
  577. $rule->integrityCheck();
  578. $this->fail('Assertion of a list item is not valid for another item.');
  579. }
  580. catch (RulesException $e) {
  581. $this->pass('Assertion of a list item is not valid for another item.');
  582. }
  583. }
  584. /**
  585. * Test using loops.
  586. */
  587. function testLoops() {
  588. // Test passing the list parameter as argument to ensure that is working
  589. // generally for plugin container too.
  590. drupal_get_messages(NULL, TRUE);
  591. $loop = rules_loop();
  592. $loop->action('drupal_message', array('message' => 'test'));
  593. $arg_info = $loop->parameterInfo();
  594. $this->assert($arg_info['list']['type'] == 'list', 'Argument info contains list.');
  595. $loop->execute(array(1, 2));
  596. // Ensure the action has been executed twice, once for each list item.
  597. $msg = drupal_get_messages();
  598. $this->assert($msg['status'][0] == 'test' && $msg['status'][1], 'Loop has been properly executed');
  599. // Now test looping over nodes.
  600. $node1 = $this->drupalCreateNode(array('type' => 'page', 'sticky' => 0));
  601. $node2 = $this->drupalCreateNode(array('type' => 'page', 'sticky' => 0));
  602. $node3 = $this->drupalCreateNode(array('type' => 'page', 'sticky' => 0));
  603. $rule = rule(array(
  604. 'list' => array(
  605. 'type' => 'list<node>',
  606. 'label' => 'A list of nodes',
  607. )
  608. ));
  609. $loop = rules_loop(array('list:select' => 'list', 'item:var' => 'node'));
  610. $loop->action('data_set', array('data:select' => 'node:sticky', 'value' => TRUE));
  611. $rule->action($loop);
  612. // Test using a list with data selectors, just output the last nodes type.
  613. $rule->action('drupal_message', array('message:select' => 'list:2:type'));
  614. $rule->execute(array($node1->nid, $node2->nid, $node3->nid));
  615. $text = RulesLog::logger()->render();
  616. $save_msg = RulesTestCase::t('Saved %node of type %node.', array('node', 'node'));
  617. $this->assertTrue(substr_count($text, $save_msg) == 3, 'List item variables have been saved.');
  618. RulesLog::logger()->checkLog();
  619. }
  620. /**
  621. * Test access checks.
  622. */
  623. function testAccessCheck() {
  624. $rule = rule();
  625. // Try to set a property which is provided by the test module and is not
  626. // accessible, so the access check has to return FALSE.
  627. $rule->action('data_set', array('data:select' => 'site:no-access-user', 'value' => 'foo'));
  628. $this->assertTrue($rule->access() === FALSE, 'Access check is working.');
  629. }
  630. /**
  631. * Test returning provided variables.
  632. */
  633. function testReturningVariables() {
  634. $node = $this->drupalCreateNode();
  635. $action = rules_action('entity_fetch', array('type' => 'node', 'id' => $node->nid));
  636. list($node2) = $action->execute();
  637. $this->assertTrue($node2->nid == $node->nid, 'Action returned a variable.');
  638. // Create a simple set that just passed through the given node.
  639. $set = rules_rule_set(array('node' => array('type' => 'node')), array('node'));
  640. $set->integrityCheck()->save('rules_test_set_1');
  641. $provides = $set->providesVariables();
  642. $this->assertTrue($provides['node']['type'] == 'node', 'Rule set correctly passed through the node.');
  643. list($node2) = $set->execute($node);
  644. $this->assertTrue($node2->nid == $node->nid, 'Rule set returned a variable.');
  645. // Create an action set returning a variable that is no parameter.
  646. $set = rules_action_set(array(
  647. 'node' => array(
  648. 'type' => 'node',
  649. 'parameter' => FALSE,
  650. )), array('node'));
  651. $set->action('entity_fetch', array('type' => 'node', 'id' => $node->nid))
  652. ->action('data_set', array('data:select' => 'node', 'value:select' => 'entity_fetched'));
  653. $set->integrityCheck();
  654. list($node3) = $set->execute();
  655. $this->assertTrue($node3->nid == $node->nid, 'Action set returned a variable that has not been passed as parameter.');
  656. // Test the same again with a variable holding a not wrapped data type.
  657. $set = rules_action_set(array(
  658. 'number' => array(
  659. 'type' => 'integer',
  660. 'parameter' => FALSE,
  661. )), array('number'));
  662. $set->action('data_set', array('data:select' => 'number', 'value' => 3));
  663. $set->integrityCheck();
  664. list($number) = $set->execute();
  665. $this->assertTrue($number == 3, 'Actions set returned a number.');
  666. }
  667. /**
  668. * Tests using input evaluators.
  669. */
  670. function testInputEvaluators() {
  671. $node = $this->drupalCreateNode(array('title' => '<b>The body & nothing.</b>', 'type' => 'page'));
  672. $rule = rule(array('nid' => array('type' => 'integer')));
  673. $rule->action('rules_action_load_node')
  674. ->action('drupal_message', array('message' => 'Title: [node_loaded:title]'))
  675. ->execute($node->nid);
  676. RulesLog::logger()->checkLog();
  677. $msg = drupal_get_messages();
  678. $this->assertEqual(array_pop($msg['status']), 'Title: ' . check_plain('<b>The body & nothing.</b>'), 'Token input evaluator applied.');
  679. // Test token replacements on a list of text values.
  680. $component = rules_action_set(array('var' => array('type' => 'list<text>', 'label' => 'var')), array('var'));
  681. $component->save('rules_test_input');
  682. $action = rules_action('component_rules_test_input', array('var' => array('uid: [site:current-user:uid]')));
  683. list($var) = $action->execute();
  684. $uid = $GLOBALS['user']->uid;
  685. $this->assertEqual(array("uid: $uid"), $var, 'Token replacements on a list of values applied.');
  686. }
  687. /**
  688. * Test importing and exporting a rule.
  689. */
  690. function testRuleImportExport() {
  691. $rule = rule(array('nid' => array('type' => 'integer')));
  692. $rule->name = "rules_export_test";
  693. $rule->action('rules_action_load_node')
  694. ->action('drupal_message', array('message' => 'Title: [node_loaded:title]'));
  695. $export =
  696. '{ "rules_export_test" : {
  697. "PLUGIN" : "rule",
  698. "REQUIRES" : [ "rules_test", "rules" ],
  699. "USES VARIABLES" : { "nid" : { "type" : "integer" } },
  700. "DO" : [
  701. { "rules_action_load_node" : { "PROVIDE" : { "node_loaded" : { "node_loaded" : "Loaded content" } } } },
  702. { "drupal_message" : { "message" : "Title: [node_loaded:title]" } }
  703. ]
  704. }
  705. }';
  706. $this->assertEqual($export, $rule->export(), 'Rule has been exported correctly.');
  707. // Test importing a rule which makes use of almost all features.
  708. $export = _rules_export_get_test_export();
  709. $rule = rules_import($export);
  710. $this->assertTrue(!empty($rule) && $rule->integrityCheck(), 'Rule has been imported.');
  711. // Test loading the same export provided as default rule.
  712. $rule = rules_config_load('rules_export_test');
  713. $this->assertTrue(!empty($rule) && $rule->integrityCheck(), 'Export has been provided in code.');
  714. // Export it and make sure the same export is generated again.
  715. $this->assertEqual($export, $rule->export(), 'Export of imported rule equals original export.');
  716. // Now try importing a rule set.
  717. $export =
  718. '{ "rules_test_set" : {
  719. "LABEL" : "Test set",
  720. "PLUGIN" : "rule set",
  721. "REQUIRES" : [ "rules" ],
  722. "USES VARIABLES" : { "node" : { "label" : "Test node", "type" : "node" } },
  723. "RULES" : [
  724. { "RULE" : {
  725. "IF" : [ { "NOT data_is" : { "data" : [ "node:title" ], "value" : "test" } } ],
  726. "DO" : [ { "data_set" : { "data" : [ "node:title" ], "value" : "test" } } ],
  727. "LABEL" : "Test Rule"
  728. }
  729. },
  730. { "RULE" : {
  731. "DO" : [ { "drupal_message" : { "message" : "hi" } } ],
  732. "LABEL" : "Test Rule 2"
  733. }
  734. }
  735. ]
  736. }
  737. }';
  738. $set = rules_import($export);
  739. $this->assertTrue(!empty($set) && $set->integrityCheck(), 'Rule set has been imported.');
  740. // Export it and make sure the same export is generated again.
  741. $this->assertEqual($export, $set->export(), 'Export of imported rule set equals original export.');
  742. // Try executing the imported rule set.
  743. $node = $this->drupalCreateNode();
  744. $set->execute($node);
  745. $this->assertEqual($node->title, 'test', 'Imported rule set has been executed.');
  746. RulesLog::logger()->checkLog();
  747. // Try import / export for a rule component providing a variable.
  748. $rule = rule(array(
  749. 'number' => array(
  750. 'type' => 'integer',
  751. 'label' => 'Number',
  752. 'parameter' => FALSE,
  753. )), array('number'));
  754. $rule->action('data_set', array('data:select' => 'number', 'value' => 3));
  755. $rule->name = 'rules_test_provides';
  756. $export = '{ "rules_test_provides" : {
  757. "PLUGIN" : "rule",
  758. "REQUIRES" : [ "rules" ],
  759. "USES VARIABLES" : { "number" : { "type" : "integer", "label" : "Number", "parameter" : false } },
  760. "DO" : [ { "data_set" : { "data" : [ "number" ], "value" : 3 } } ],
  761. "PROVIDES VARIABLES" : [ "number" ]
  762. }
  763. }';
  764. $this->assertEqual($export, $rule->export(), 'Rule 2 has been exported correctly.');
  765. $imported_rule = rules_import($rule->export());
  766. $this->assertTrue(!empty($imported_rule) && $imported_rule->integrityCheck(), 'Rule 2 has been imported.');
  767. $this->assertEqual($export, $imported_rule->export(), 'Export of imported rule 2 equals original export.');
  768. // Test importing a negated condition component.
  769. $export = '{ "rules_negated_component" : {
  770. "LABEL" : "negated_component",
  771. "PLUGIN" : "or",
  772. "REQUIRES" : [ "rules" ],
  773. "NOT OR" : [ { "data_is_empty" : { "data" : [ "site:slogan" ] } } ]
  774. }
  775. }';
  776. $or = rules_import($export);
  777. $this->assertTrue($or->integrityCheck() && $or->isNegated(), 'Negated condition component imported.');
  778. }
  779. /**
  780. * Test the named parameter mode.
  781. */
  782. function testNamedParameters() {
  783. $rule = rule(array('node' => array('type' => 'node')));
  784. $rule->action('rules_action_node_set_title', array('title' => 'foo'));
  785. $rule->integrityCheck();
  786. // Test the rule.
  787. $node = $this->drupalCreateNode(array('type' => 'page', 'sticky' => 0));
  788. $rule->execute($node);
  789. $this->assertTrue($node->title == 'foo', 'Action with named parameters has been correctly executed.');
  790. RulesLog::logger()->checkLog();
  791. }
  792. /**
  793. * Make sure Rules aborts when NULL values are used.
  794. */
  795. function testAbortOnNULLValues() {
  796. $rule = rule(array('node' => array('type' => 'node')));
  797. $rule->action('drupal_message', array('message:select' => 'node:log'));
  798. $rule->integrityCheck();
  799. // Test the rule.
  800. $node = $this->drupalCreateNode();
  801. $node->log = NULL;
  802. $rule->execute($node);
  803. $text = RulesLog::logger()->render();
  804. $msg = RulesTestCase::t('The variable or parameter %message is empty.', array('message'));
  805. $this->assertTrue(strpos($text, $msg) !== FALSE, 'Evaluation aborted due to an empty argument value.');
  806. }
  807. }
  808. /**
  809. * Test rules data wrappers.
  810. */
  811. class RulesTestDataCase extends DrupalWebTestCase {
  812. static function getInfo() {
  813. return array(
  814. 'name' => 'Rules Data tests',
  815. 'description' => 'Tests rules data saving and type matching.',
  816. 'group' => 'Rules',
  817. );
  818. }
  819. function setUp() {
  820. parent::setUp('rules', 'rules_test');
  821. variable_set('rules_debug_log', 1);
  822. // Make sure we don't ran over issues with the node_load static cache.
  823. entity_get_controller('node')->resetCache();
  824. }
  825. /**
  826. * Tests intelligently saving data.
  827. */
  828. function testDataSaving() {
  829. $node = $this->drupalCreateNode();
  830. $state = new RulesState(rule());
  831. $state->addVariable('node', $node, array('type' => 'node'));
  832. $wrapper = $state->get('node');
  833. $node->title = 'test';
  834. $wrapper->set($node);
  835. $state->saveChanges('node', $wrapper, FALSE);
  836. $this->assertFalse($this->drupalGetNodeByTitle('test'), 'Changes have not been saved.');
  837. $state->saveChanges('node', $wrapper, TRUE);
  838. $this->assertTrue($this->drupalGetNodeByTitle('test'), 'Changes have been saved.');
  839. // Test skipping saving.
  840. $state->addVariable('node2', $node, array(
  841. 'type' => 'node',
  842. 'skip save' => TRUE,
  843. ));
  844. $wrapper = $state->get('node2');
  845. $node->title = 'test2';
  846. $wrapper->set($node);
  847. $state->saveChanges('node2', $wrapper, TRUE);
  848. $this->assertFalse($this->drupalGetNodeByTitle('test2'), 'Changes have not been saved.');
  849. // Try saving a non-entity wrapper, which should result in saving the
  850. // parent entity containing the property.
  851. $wrapper = $state->get('node');
  852. $wrapper->title->set('test3');
  853. $state->saveChanges('node:title', $wrapper, TRUE);
  854. $this->assertTrue($this->drupalGetNodeByTitle('test3'), 'Parent entity has been saved.');
  855. }
  856. /**
  857. * Test type matching
  858. */
  859. function testTypeMatching() {
  860. $entity = array('type' => 'entity');
  861. $node = array('type' => 'node');
  862. $this->assertTrue(RulesData::typesMatch($node, $entity), 'Types match.');
  863. $this->assertFalse(RulesData::typesMatch($entity, $node), 'Types don\'t match.');
  864. $this->assertTrue(RulesData::typesMatch($node + array('bundle' => 'page'), $node), 'Types match.');
  865. $this->assertTrue(RulesData::typesMatch($node + array('bundle' => 'page'), $entity), 'Types match.');
  866. $this->assertTrue(RulesData::typesMatch(array('type' => 'list<node>'), array('type' => 'list')), 'Types match.');
  867. $this->assertTrue(RulesData::typesMatch($node + array('bundle' => 'page'), $node + array('bundles' => array('page', 'story'))), 'Types match.');
  868. $this->assertFalse(RulesData::typesMatch($node, $node + array('bundles' => array('page', 'story'))), 'Types don\'t match.');
  869. // Test that a type matches its grand-parent type (text > decimal > integer)
  870. $this->assertTrue(RulesData::typesMatch(array('type' => 'integer'), array('type' => 'text')), 'Types match.');
  871. $this->assertFalse(RulesData::typesMatch(array('type' => 'text'), array('type' => 'integer')), 'Types don\'t match.');
  872. }
  873. /**
  874. * Tests making use of custom wrapper classes.
  875. */
  876. function testCustomWrapperClasses() {
  877. // Test loading a vocabulary by name, which is done by a custom wrapper.
  878. $set = rules_action_set(array('vocab' => array('type' => 'taxonomy_vocabulary')), array('vocab'));
  879. $set->action('drupal_message', array('message:select' => 'vocab:name'));
  880. $set->integrityCheck();
  881. list($vocab) = $set->execute('tags');
  882. $this->assertTrue($vocab->machine_name == 'tags', 'Loaded vocabulary by name.');
  883. // Now test wrapper creation for a direct input argument value.
  884. $set = rules_action_set(array('term' => array('type' => 'taxonomy_term')));
  885. $set->action('data_set', array('data:select' => 'term:vocabulary', 'value' => 'tags'));
  886. $set->integrityCheck();
  887. $vocab = entity_create('taxonomy_vocabulary', array(
  888. 'name' => 'foo',
  889. 'machine_name' => 'foo',
  890. ));
  891. entity_save('taxonomy_vocabulary', $vocab);
  892. $term_wrapped = entity_property_values_create_entity('taxonomy_term', array(
  893. 'name' => $this->randomName(),
  894. 'vocabulary' => $vocab,
  895. ))->save();
  896. $set->execute($term_wrapped);
  897. $this->assertEqual($term_wrapped->vocabulary->machine_name->value(), 'tags', 'Vocabulary name used as direct input value.');
  898. RulesLog::logger()->checkLog();
  899. }
  900. /**
  901. * Makes sure the RulesIdentifiableDataWrapper is working correctly.
  902. */
  903. function testRulesIdentifiableDataWrapper() {
  904. $node = $this->drupalCreateNode();
  905. $wrapper = new RulesTestTypeWrapper('rules_test_type', $node);
  906. $this->assertTrue($wrapper->value() == $node, 'Data correctly wrapped.');
  907. // Test serializing and make sure only the id is stored.
  908. $this->assertTrue(strpos(serialize($wrapper), $node->title) === FALSE, 'Data has been correctly serialized.');
  909. $this->assertEqual(unserialize(serialize($wrapper))->value()->title, $node->title, 'Serializing works right.');
  910. $wrapper2 = unserialize(serialize($wrapper));
  911. // Test serializing the unloaded wrapper.
  912. $this->assertEqual(unserialize(serialize($wrapper2))->value()->title, $node->title, 'Serializing works right.');
  913. // Test loading a not more existing node.
  914. $s = serialize($wrapper2);
  915. node_delete($node->nid);
  916. $this->assertFalse(node_load($node->nid), 'Node deleted.');
  917. try {
  918. unserialize($s)->value();
  919. $this->fail("Loading hasn't created an exception.");
  920. }
  921. catch (EntityMetadataWrapperException $e) {
  922. $this->pass("Exception was thrown: ". $e->getMessage());
  923. }
  924. // Test saving a savable custom, identifiable wrapper.
  925. $action = rules_action('test_type_save');
  926. $node = $this->drupalCreateNode(array('status' => 0, 'type' => 'page'));
  927. $node->status = 1;
  928. $action->execute($node);
  929. // Load the node fresh from the db.
  930. $node = node_load($node->nid, NULL, TRUE);
  931. $this->assertEqual($node->status, 1, 'Savable non-entity has been saved.');
  932. }
  933. }
  934. /**
  935. * Test triggering rules.
  936. */
  937. class RulesTriggerTestCase extends DrupalWebTestCase {
  938. static function getInfo() {
  939. return array(
  940. 'name' => 'Reaction Rules',
  941. 'description' => 'Tests triggering reactive rules.',
  942. 'group' => 'Rules',
  943. );
  944. }
  945. function setUp() {
  946. parent::setUp('rules', 'rules_test');
  947. RulesLog::logger()->clear();
  948. variable_set('rules_debug_log', 1);
  949. }
  950. protected function createTestRule($action = TRUE, $event = 'node_presave') {
  951. $rule = rules_reaction_rule();
  952. $rule->event($event)
  953. ->condition(rules_condition('data_is', array('data:select' => 'node:status', 'value' => TRUE))->negate())
  954. ->condition('data_is', array('data:select' => 'node:type', 'value' => 'page'));
  955. if ($action) {
  956. $rule->action('rules_action_delete_node');
  957. }
  958. return $rule;
  959. }
  960. /**
  961. * Tests CRUD for reaction rules - making sure the events are stored properly.
  962. */
  963. function testReactiveRuleCreation() {
  964. $rule = $this->createTestRule();
  965. $rule->save();
  966. $result = db_query("SELECT event FROM {rules_trigger} WHERE id = :id", array(':id' => $rule->id));
  967. $this->assertEqual($result->fetchField(), 'node_presave', 'Associated event has been saved.');
  968. // Try updating.
  969. $rule->removeEvent('node_presave');
  970. $rule->event('node_insert');
  971. $rule->event('node_update');
  972. $rule->active = FALSE;
  973. $rule->integrityCheck()->save();
  974. $result = db_query("SELECT event FROM {rules_trigger} WHERE id = :id", array(':id' => $rule->id));
  975. $this->assertEqual($result->fetchCol(), array_values($rule->events()), 'Updated associated events.');
  976. // Try deleting.
  977. $rule->delete();
  978. $result = db_query("SELECT event FROM {rules_trigger} WHERE id = :id", array(':id' => $rule->id));
  979. $this->assertEqual($result->fetchField(), FALSE, 'Deleted associated events.');
  980. }
  981. /**
  982. * Tests creating and triggering a basic reaction rule.
  983. */
  984. function testBasicReactionRule() {
  985. $node = $this->drupalCreateNode(array('type' => 'page'));
  986. $rule = $this->createTestRule();
  987. $rule->integrityCheck()->save();
  988. // Test the basics of the event set work right.
  989. $event = rules_get_cache('event_node_presave');
  990. $this->assertEqual(array_keys($event->parameterInfo()), array('node'), 'EventSet returns correct argument info.');
  991. // Trigger the rule by updating the node.
  992. $nid = $node->nid;
  993. $node->status = 0;
  994. node_save($node);
  995. RulesLog::logger()->checkLog();
  996. $this->assertFalse(node_load($nid), 'Rule successfully triggered and executed');
  997. //debug(RulesLog::logger()->render());
  998. }
  999. /**
  1000. * Test a rule using a handler to load a variable.
  1001. */
  1002. function testVariableHandler() {
  1003. $node = $this->drupalCreateNode(array('type' => 'page', 'sticky' => 0, 'status' => 0));
  1004. $rule = $this->createTestRule(FALSE, 'node_update');
  1005. $rule->action('rules_node_publish_action_save', array('node:select' => 'node_unchanged'));
  1006. // Test without recursion prevention to make sure recursive invocations
  1007. // work right too. This rule won't ran in an infinite loop anyway.
  1008. $rule->recursion = TRUE;
  1009. $rule->label = 'rule 1';
  1010. $rule->integrityCheck()->save();
  1011. $node->status = 0;
  1012. $node->sticky = 1;
  1013. node_save($node);
  1014. RulesLog::logger()->checkLog();
  1015. entity_get_controller('node')->resetCache();
  1016. $node = node_load($node->nid);
  1017. $this->assertFalse($node->sticky, 'Parameter has been loaded and saved.');
  1018. $this->assertTrue($node->status, 'Action has been executed.');
  1019. // Ensure the rule was evaluated a second time
  1020. $text = RulesLog::logger()->render();
  1021. $msg = RulesTestCase::t('Evaluating conditions of rule %rule 1', array('rule 1'));
  1022. $pos = strpos($text, $msg);
  1023. $pos = ($pos !== FALSE) ? strpos($text, $msg, $pos) : FALSE;
  1024. $this->assertTrue($pos !== FALSE, "Recursion prevented.");
  1025. //debug(RulesLog::logger()->render());
  1026. }
  1027. /**
  1028. * Test aborting silently when handlers are not able to load.
  1029. */
  1030. function testVariableHandlerFailing() {
  1031. $rule = $this->createTestRule(FALSE, 'node_presave');
  1032. $rule->action('rules_node_publish_action_save', array('node:select' => 'node_unchanged'));
  1033. $rule->integrityCheck()->save();
  1034. // On insert it's not possible to get the unchanged node during presave.
  1035. $node = $this->drupalCreateNode(array('type' => 'page', 'sticky' => 0, 'status' => 0));
  1036. //debug(RulesLog::logger()->render());
  1037. $text = RulesTestCase::t('Unable to load variable %node_unchanged, aborting.', array('node_unchanged'));
  1038. $this->assertTrue(strpos(RulesLog::logger()->render(), $text) !== FALSE, "Aborted evaluation.");
  1039. }
  1040. /**
  1041. * Tests preventing recursive rule invocations by creating a rule that reacts
  1042. * on node-update and generates a node update that would trigger it itself.
  1043. */
  1044. function testRecursionPrevention() {
  1045. $rule = $this->createTestRule(FALSE, 'node_update');
  1046. $rule->action('rules_node_make_sticky_action');
  1047. $rule->integrityCheck()->save();
  1048. // Now trigger the rule.
  1049. $node = $this->drupalCreateNode(array('type' => 'page', 'sticky' => 0, 'status' => 0));
  1050. node_save($node);
  1051. $text = RulesTestCase::t('Not evaluating reaction rule %label to prevent recursion.', array('label' => $rule->name));
  1052. //debug(RulesLog::logger()->render());
  1053. $this->assertTrue((strpos(RulesLog::logger()->render(), $text) !== FALSE), "Recursion prevented.");
  1054. //debug(RulesLog::logger()->render());
  1055. }
  1056. /**
  1057. * Ensure the recursion prevention still allows to let the rule trigger again
  1058. * during evaluation of the same event set, if the event isn't caused by the
  1059. * rule itself - thus we won't run in an infinte loop.
  1060. */
  1061. function testRecursionOnDifferentArguments() {
  1062. // Create rule1 - which might recurse.
  1063. $rule = $this->createTestRule(FALSE, 'node_update');
  1064. $rule->action('rules_node_make_sticky_action');
  1065. $rule->label = 'rule 1';
  1066. $rule->integrityCheck()->save();
  1067. // Create rule2 - which triggers rule1 on another node.
  1068. $node2 = $this->drupalCreateNode(array('type' => 'page', 'sticky' => 0, 'status' => 0));
  1069. $rule2 = $this->createTestRule(FALSE, 'node_update');
  1070. $rule2->action('rules_action_load_node', array('nid' => $node2->nid))
  1071. ->action('rules_node_make_sticky_action', array('node:select' => 'node_loaded'));
  1072. $rule2->label = 'rule 2';
  1073. $rule2->save();
  1074. // Now trigger both rules by generating the event.
  1075. $node = $this->drupalCreateNode(array('type' => 'page', 'sticky' => 0, 'status' => 0));
  1076. node_save($node);
  1077. //debug(RulesLog::logger()->render());
  1078. $text = RulesLog::logger()->render();
  1079. $pos = strpos($text, RulesTestCase::t('Evaluating conditions of rule %rule 1', array('rule 1')));
  1080. $pos = ($pos !== FALSE) ? strpos($text, RulesTestCase::t('Evaluating conditions of rule %rule 2', array('rule 2')), $pos) : FALSE;
  1081. $pos = ($pos !== FALSE) ? strpos($text, RulesTestCase::t('Saved %node_loaded of type %node.', array('node_loaded', 'node')), $pos) : FALSE;
  1082. $pos = ($pos !== FALSE) ? strpos($text, RulesTestCase::t('Evaluating conditions of rule %rule 1', array('rule 1')), $pos) : FALSE;
  1083. $pos = ($pos !== FALSE) ? strpos($text, RulesTestCase::t('Not evaluating reaction rule %rule 2 to prevent recursion', array('rule 2')), $pos) : FALSE;
  1084. $this->assertTrue($pos !== FALSE, 'Rule1 was triggered on the event caused by Rule2.');
  1085. }
  1086. /**
  1087. * Tests the provided default rule 'rules_test_default_1'.
  1088. */
  1089. function testDefaultRule() {
  1090. $rule = rules_config_load('rules_test_default_1');
  1091. $this->assertTrue($rule->status & ENTITY_IN_CODE && !($rule->status & ENTITY_IN_DB), 'Default rule can be loaded and has the right status.');
  1092. // Enable.
  1093. $rule->active = TRUE;
  1094. $rule->save();
  1095. // Create a node that triggers the rule.
  1096. $node = $this->drupalCreateNode(array('type' => 'page', 'sticky' => 0, 'status' => 0));
  1097. // Clear messages.
  1098. drupal_get_messages();
  1099. // Let event node_update occur.
  1100. node_save($node);
  1101. $msg = drupal_get_messages();
  1102. $this->assertEqual($msg['status'][0], 'A node has been updated.', 'Default rule has been triggered.');
  1103. }
  1104. /**
  1105. * Tests creating and triggering a reaction rule with event settings.
  1106. */
  1107. function testEventSettings() {
  1108. $rule = rules_reaction_rule();
  1109. $rule->event('node_presave', array('bundle' => 'article'))
  1110. ->condition('data_is_empty', array('data:select' => 'node:field-tags'))
  1111. ->action('node_publish', array('node:select' => 'node'));
  1112. $rule->integrityCheck()->save();
  1113. $node = $this->drupalCreateNode(array('type' => 'page', 'status' => 0));
  1114. $this->assertEqual($node->status, 0, 'Rule has not been triggered.');
  1115. $node = $this->drupalCreateNode(array('type' => 'article', 'status' => 0));
  1116. $this->assertEqual($node->status, 1, 'Rule has been triggered.');
  1117. RulesLog::logger()->checkLog();
  1118. // Make sure an invalid bundle raises integrity problems.
  1119. $rule->event('node_presave', array('bundle' => 'invalid'));
  1120. try {
  1121. $rule->integrityCheck();
  1122. $this->fail('Integrity check failed.');
  1123. }
  1124. catch (RulesIntegrityException $e) {
  1125. $this->pass('Integrity check failed: ' . $e);
  1126. }
  1127. }
  1128. }
  1129. /**
  1130. * Tests provided module integration.
  1131. */
  1132. class RulesIntegrationTestCase extends DrupalWebTestCase {
  1133. static function getInfo() {
  1134. return array(
  1135. 'name' => 'Rules Core Integration',
  1136. 'description' => 'Tests provided integration for drupal core.',
  1137. 'group' => 'Rules',
  1138. );
  1139. }
  1140. function setUp() {
  1141. parent::setUp('rules', 'rules_test', 'php', 'path');
  1142. RulesLog::logger()->clear();
  1143. variable_set('rules_debug_log', 1);
  1144. }
  1145. /**
  1146. * Just make sure the access callback run without errors.
  1147. */
  1148. function testAccessCallbacks() {
  1149. $cache = rules_get_cache();
  1150. foreach (array('action', 'condition', 'event') as $type) {
  1151. foreach (rules_fetch_data($type . '_info') as $name => $info) {
  1152. if (isset($info['access callback'])) {
  1153. $info['access callback']($type, $name);
  1154. }
  1155. }
  1156. }
  1157. }
  1158. /**
  1159. * Test data integration.
  1160. */
  1161. function testDataIntegration() {
  1162. // Test data_create action.
  1163. $action = rules_action('data_create', array(
  1164. 'type' => 'log_entry',
  1165. 'param_type' => 'rules_test',
  1166. 'param_message' => 'Rules test log message',
  1167. 'param_severity' => WATCHDOG_WARNING,
  1168. 'param_request_uri' => 'http://example.com',
  1169. 'param_link' => '',
  1170. ));
  1171. $action->access();
  1172. $action->execute();
  1173. $text = RulesLog::logger()->render();
  1174. $pos = strpos($text, RulesTestCase::t('Added the provided variable %data_created of type %log_entry', array('data_created', 'log_entry')));
  1175. $this->assertTrue($pos !== FALSE, 'Data of type log entry has been created.');
  1176. // Test variable_add action.
  1177. $action = rules_action('variable_add', array(
  1178. 'type' => 'text_formatted',
  1179. 'value' => array(
  1180. 'value' => 'test text',
  1181. 'format' => 1,
  1182. )
  1183. ));
  1184. $action->access();
  1185. $action->execute();
  1186. $text = RulesLog::logger()->render();
  1187. $pos = strpos($text, RulesTestCase::t('Added the provided variable %variable_added of type %text_formatted', array('variable_added', 'text_formatted')));
  1188. $this->assertTrue($pos !== FALSE, 'Data of type text formatted has been created.');
  1189. // Test using the list actions.
  1190. $rule = rule(array(
  1191. 'list' => array(
  1192. 'type' => 'list<text>',
  1193. 'label' => 'A list of text',
  1194. )
  1195. ));
  1196. $rule->action('list_add', array('list:select' => 'list', 'item' => 'bar2'));
  1197. $rule->action('list_add', array('list:select' => 'list', 'item' => 'bar', 'pos' => 'start'));
  1198. $rule->action('list_add', array('list:select' => 'list', 'item' => 'bar', 'unique' => TRUE));
  1199. $rule->action('list_remove', array('list:select' => 'list', 'item' => 'bar2'));
  1200. $list = entity_metadata_wrapper('list', array('foo', 'foo2'));
  1201. $rule->execute($list);
  1202. RulesLog::logger()->checkLog();
  1203. $this->assertEqual($list->value(), array('bar', 'foo', 'foo2'), 'List items removed and added.');
  1204. $this->assertFalse(rules_condition('list_contains')->execute($list, 'foo-bar'), 'Condition "List item contains" evaluates to FALSE');
  1205. $this->assertTrue(rules_condition('list_contains')->execute($list, 'foo'), 'Condition "List item contains" evaluates to TRUE');
  1206. //debug(RulesLog::logger()->render());
  1207. // Test data_is condition with IN operation.
  1208. $rule = rule(array('node' => array('type' => 'node')));
  1209. $rule->condition('data_is', array('data:select' => 'node:title', 'op' => 'IN', 'value' => array('foo', 'bar')));
  1210. $rule->action('data_set', array('data:select' => 'node:title', 'value' => 'bar'));
  1211. $rule->integrityCheck();
  1212. $node = $this->drupalCreateNode(array('title' => 'foo'));
  1213. $rule->execute($node);
  1214. $this->assertEqual($node->title, 'bar', "Data comparision using IN operation evaluates to TRUE.");
  1215. // Test Condition: Data is empty.
  1216. $rule = rule(array('node' => array('type' => 'node')));
  1217. $rule->condition('data_is_empty', array('data:select' => 'node:title'));
  1218. $rule->action('data_set', array('data:select' => 'node:title', 'value' => 'bar'));
  1219. $rule->integrityCheck();
  1220. // Data is empty condition evaluates to TRUE
  1221. // for node with empty title, action sets title to 'bar'.
  1222. $node = $this->drupalCreateNode(array('title' => '', 'type' => 'article'));
  1223. $rule->execute($node);
  1224. $this->assertEqual($node->title, 'bar', "Data is empty condition evaluates to TRUE for node with empty title, action sets title to 'bar'.");
  1225. // Data is empty condition evaluates to FALSE
  1226. // for node with title 'foo', action is not executed.
  1227. $node = $this->drupalCreateNode(array('title' => 'foo', 'type' => 'article'));
  1228. $rule->execute($node);
  1229. $this->assertEqual($node->title, 'foo', "Data is empty condition evaluates to FALSE for node with title 'foo', action is not executed.");
  1230. // Data is empty condition evaluates to TRUE for the parent of a
  1231. // not existing term in the tags field of the node.
  1232. $rule = rule(array('node' => array('type' => 'node')));
  1233. $rule->condition('node_is_of_type', array('type' => array('article')));
  1234. $rule->condition('data_is_empty', array('data:select' => 'node:field-tags:0:parent'));
  1235. $rule->action('data_set', array('data:select' => 'node:title', 'value' => 'bar'));
  1236. $rule->integrityCheck();
  1237. $node = $this->drupalCreateNode(array('title' => 'foo', 'type' => 'article'));
  1238. $rule->execute($node);
  1239. $this->assertEqual($node->title, 'bar', "Data is empty condition evaluates to TRUE for not existing data structures");
  1240. // Test Action: Calculate a value.
  1241. $rule = rule(array('node' => array('type' => 'node')));
  1242. $rule->action('data_calc', array('input_1:select' => 'node:nid', 'op' => '*', 'input_2' => 2));
  1243. $rule->action('data_set', array('data:select' => 'node:title', 'value:select' => 'result'));
  1244. $rule->integrityCheck();
  1245. $rule->execute($node);
  1246. $this->assertEqual($node->title, $node->nid * 2, "Value has been calculated.");
  1247. // Test moving a date.
  1248. $action_set = rules_action_set(array('date' => array('type' => 'date')), array('date'));
  1249. $action_set->action('data_calc', array('input_1:select' => 'date', 'op' => '+', 'input_2' => 3600))
  1250. ->action('data_set', array('data:select' => 'date', 'value:select' => 'result'));
  1251. $action_set->integrityCheck();
  1252. list($result) = $action_set->execute(REQUEST_TIME);
  1253. $this->assertEqual($result, REQUEST_TIME + 3600, 'Used data calculation action to move a date by an hour.');
  1254. // Test data type conversion action.
  1255. $set = rules_action_set(array('result' => array('type' => 'text', 'parameter' => FALSE)), array('result'));
  1256. $set->action('data_convert', array('type' => 'text', 'value:select' => 'site:login-url'));
  1257. $set->action('data_set', array('data:select' => 'result', 'value:select' => 'conversion_result'));
  1258. list($result) = $set->execute();
  1259. $set->integrityCheck();
  1260. $this->assertEqual($result, url('user', array('absolute' => TRUE)), 'Converted URI to text.');
  1261. $set = rules_action_set(array(
  1262. 'result' => array('type' => 'integer', 'parameter' => FALSE),
  1263. 'source' => array('type' => 'text'),
  1264. ), array('result'));
  1265. $set->action('data_convert', array('type' => 'integer', 'value:select' => 'source'));
  1266. $set->action('data_set', array('data:select' => 'result', 'value:select' => 'conversion_result'));
  1267. list($result) = $set->execute('9.4');
  1268. $this->assertEqual($result, 9, 'Converted decimal to integer using rounding.');
  1269. $set = rules_action_set(array(
  1270. 'result' => array('type' => 'integer', 'parameter' => FALSE),
  1271. 'source' => array('type' => 'text'),
  1272. ), array('result'));
  1273. $set->action('data_convert', array('type' => 'integer', 'value:select' => 'source', 'rounding_behavior' => 'down'));
  1274. $set->action('data_set', array('data:select' => 'result', 'value:select' => 'conversion_result'));
  1275. list($result) = $set->execute('9.6');
  1276. $this->assertEqual($result, 9, 'Converted decimal to integer using roundin behavio down.');
  1277. $set = rules_action_set(array(
  1278. 'result' => array('type' => 'integer', 'parameter' => FALSE),
  1279. 'source' => array('type' => 'text'),
  1280. ), array('result'));
  1281. $set->action('data_convert', array('type' => 'integer', 'value:select' => 'source', 'rounding_behavior' => 'up'));
  1282. $set->action('data_set', array('data:select' => 'result', 'value:select' => 'conversion_result'));
  1283. list($result) = $set->execute('9.4');
  1284. $this->assertEqual($result, 10, 'Converted decimal to integer using rounding behavior up.');
  1285. // Test text matching condition.
  1286. $result = rules_condition('text_matches')->execute('my-text', 'text', 'contains');
  1287. $result2 = rules_condition('text_matches')->execute('my-text', 'tex2t', 'contains');
  1288. $this->assertTrue($result && !$result2, 'Text matching condition using operation contain evaluated.');
  1289. $result = rules_condition('text_matches')->execute('my-text', 'my', 'starts');
  1290. $result2 = rules_condition('text_matches')->execute('my-text', 'text', 'starts');
  1291. $this->assertTrue($result && !$result2, 'Text matching condition using operation starts evaluated.');
  1292. $result = rules_condition('text_matches')->execute('my-text', 'text', 'ends');
  1293. $result2 = rules_condition('text_matches')->execute('my-text', 'my', 'ends');
  1294. $this->assertTrue($result && !$result2, 'Text matching condition using operation ends evaluated.');
  1295. $result = rules_condition('text_matches')->execute('my-text', 'me?y-texx?t', 'regex');
  1296. $result2 = rules_condition('text_matches')->execute('my-text', 'me+y-texx?t', 'regex');
  1297. $this->assertTrue($result && !$result2, 'Text matching condition using operation regex evaluated.');
  1298. }
  1299. /**
  1300. * Tests entity related integration.
  1301. */
  1302. function testEntityIntegration() {
  1303. global $user;
  1304. $page = $this->drupalCreateNode(array('type' => 'page'));
  1305. $article = $this->drupalCreateNode(array('type' => 'article'));
  1306. $result = rules_condition('entity_field_access')
  1307. ->execute(entity_metadata_wrapper('node', $article), 'field_tags');
  1308. $this->assertTrue($result);
  1309. // Test entiy_is_of_bundle condition.
  1310. $result = rules_condition('entity_is_of_bundle', array(
  1311. 'type' => 'node',
  1312. 'bundle' => array('article'),
  1313. ))->execute(entity_metadata_wrapper('node', $page));
  1314. $this->assertFalse($result, 'Entity is of bundle condition has not been met.');
  1315. $result = rules_condition('entity_is_of_bundle', array(
  1316. 'type' => 'node',
  1317. 'bundle' => array('article'),
  1318. ))->execute(entity_metadata_wrapper('node', $article));
  1319. $this->assertTrue($result, 'Entity is of bundle condition has been met.');
  1320. // Also test a full rule so the integrity check must work.
  1321. $term_wrapped = entity_property_values_create_entity('taxonomy_term', array(
  1322. 'name' => $this->randomName(),
  1323. 'vocabulary' => 1,
  1324. ))->save();
  1325. $rule = rule(array(
  1326. 'node' => array('type' => 'node'),
  1327. ));
  1328. $rule->condition('entity_is_of_bundle', array(
  1329. 'entity:select' => 'node',
  1330. 'bundle' => array('article'),
  1331. ));
  1332. $rule->action('data_set', array('data:select' => 'node:field_tags', 'value' => array($term_wrapped->getIdentifier())));
  1333. $rule->integrityCheck();
  1334. $rule->execute($article);
  1335. $this->assertEqual($term_wrapped->getIdentifier(), $article->field_tags[LANGUAGE_NONE][0]['tid'], 'Entity is of bundle condition has been met.');
  1336. // Test again using an entity variable.
  1337. $article = $this->drupalCreateNode(array('type' => 'article'));
  1338. $rule = rule(array(
  1339. 'entity' => array('type' => 'entity'),
  1340. ));
  1341. $rule->condition('entity_is_of_bundle', array(
  1342. 'entity:select' => 'entity',
  1343. 'type' => 'node',
  1344. 'bundle' => array('article'),
  1345. ));
  1346. $rule->action('data_set', array('data:select' => 'entity:field_tags', 'value' => array($term_wrapped->getIdentifier())));
  1347. $rule->integrityCheck();
  1348. $rule->execute(entity_metadata_wrapper('node', $article));
  1349. $this->assertEqual($term_wrapped->getIdentifier(), $article->field_tags[LANGUAGE_NONE][0]['tid'], 'Entity is of bundle condition has been met.');
  1350. // Test CRUD actions.
  1351. $action = rules_action('entity_create', array(
  1352. 'type' => 'node',
  1353. 'param_type' => 'page',
  1354. 'param_title' => 'foo',
  1355. 'param_author' => $GLOBALS['user'],
  1356. ));
  1357. $action->access();
  1358. $action->execute();
  1359. $text = RulesLog::logger()->render();
  1360. $pos = strpos($text, RulesTestCase::t('Added the provided variable %entity_created of type %node', array('entity_created', 'node')));
  1361. $pos = ($pos !== FALSE) ? strpos($text, RulesTestCase::t('Saved %entity_created of type %node.', array('entity_created', 'node')), $pos) : FALSE;
  1362. $this->assertTrue($pos !== FALSE, 'Data has been created and saved.');
  1363. $node = $this->drupalCreateNode(array('type' => 'page', 'sticky' => 0, 'status' => 0));
  1364. $rule = rule();
  1365. $rule->action('entity_fetch', array('type' => 'node', 'id' => $node->nid, 'entity_fetched:var' => 'node'));
  1366. $rule->action('entity_save', array('data:select' => 'node', 'immediate' => TRUE));
  1367. $rule->action('entity_delete', array('data:select' => 'node'));
  1368. $rule->access();
  1369. $rule->integrityCheck()->execute();
  1370. $text = RulesLog::logger()->render();
  1371. $pos = strpos($text, RulesTestCase::t('Evaluating the action %entity_fetch.', array('entity_fetch')));
  1372. $pos = ($pos !== FALSE) ? strpos($text, RulesTestCase::t('Added the provided variable %node of type %node', array('node')), $pos) : FALSE;
  1373. $pos = ($pos !== FALSE) ? strpos($text, RulesTestCase::t('Saved %node of type %node.', array('node')), $pos) : FALSE;
  1374. $pos = ($pos !== FALSE) ? strpos($text, RulesTestCase::t('Evaluating the action %entity_delete.', array('entity_delete')), $pos) : FALSE;
  1375. $this->assertTrue($pos !== FALSE, 'Data has been fetched, saved and deleted.');
  1376. //debug(RulesLog::logger()->render());
  1377. $node = entity_property_values_create_entity('node', array(
  1378. 'type' => 'article',
  1379. 'author' => $user,
  1380. 'title' => 'foo',
  1381. ))->value();
  1382. $term_wrapped = entity_property_values_create_entity('taxonomy_term', array(
  1383. 'name' => $this->randomName(),
  1384. 'vocabulary' => 1,
  1385. ))->save();
  1386. // Test asserting the field and using it afterwards.
  1387. $rule = rule(array('node' => array('type' => 'node')));
  1388. $rule->condition('entity_has_field', array('entity:select' => 'node', 'field' => 'field_tags'));
  1389. $rule->condition('entity_is_new', array('entity:select' => 'node'));
  1390. $rule->action('list_add', array('list:select' => 'node:field-tags', 'item' => $term_wrapped));
  1391. $rule->integrityCheck();
  1392. $rule->execute($node);
  1393. $tid = $term_wrapped->getIdentifier();
  1394. $this->assertEqual(array_values($node->field_tags[LANGUAGE_NONE]), array(0 => array('tid' => $tid)), 'Entity has field conditions evaluted.');
  1395. // Test loading a non-node entity.
  1396. $action = rules_action('entity_fetch', array('type' => 'taxonomy_term', 'id' => $tid));
  1397. list($term) = $action->execute();
  1398. $this->assertEqual($term->tid, $tid, 'Fetched a taxonomy term using "entity_fetch".');
  1399. // Test the entity is of type condition.
  1400. $rule = rule(array('entity' => array('type' => 'entity', 'label' => 'entity')));
  1401. $rule->condition('entity_is_of_type', array('type' => 'node'));
  1402. $rule->action('data_set', array('data:select' => 'entity:title', 'value' => 'bar'));
  1403. $rule->integrityCheck();
  1404. $rule->execute(entity_metadata_wrapper('node', $node));
  1405. $this->assertEqual(entity_metadata_wrapper('node', $node->nid)->title->value(), 'bar', 'Entity is of type condition correctly asserts the entity type.');
  1406. // Test the entity_query action.
  1407. $node = $this->drupalCreateNode(array('type' => 'page', 'title' => 'foo2'));
  1408. $rule = rule();
  1409. $rule->action('entity_query', array('type' => 'node', 'property' => 'title', 'value' => 'foo2'))
  1410. ->action('data_set', array('data:select' => 'entity_fetched:0:title', 'value' => 'bar'));
  1411. $rule->access();
  1412. $rule->integrityCheck();
  1413. $rule->execute();
  1414. $node = node_load($node->nid);
  1415. $this->assertEqual('bar', $node->title, 'Fetched a node by title and modified it.');
  1416. RulesLog::logger()->checkLog();
  1417. }
  1418. /**
  1419. * Test integration for the taxonomy module.
  1420. */
  1421. function testTaxonomyIntegration() {
  1422. $term = entity_property_values_create_entity('taxonomy_term', array(
  1423. 'name' => $this->randomName(),
  1424. 'vocabulary' => 1,
  1425. ))->value();
  1426. $term2 = clone $term;
  1427. taxonomy_term_save($term);
  1428. taxonomy_term_save($term2);
  1429. $tags[LANGUAGE_NONE][0]['tid'] = $term->tid;
  1430. $node = $this->drupalCreateNode(array('title' => 'foo', 'type' => 'article', 'field_tags' => $tags));
  1431. // Test assigning and remove a term from an article.
  1432. $rule = rule(array('node' => array('type' => 'node', 'bundle' => 'article')));
  1433. $term_wrapped = rules_wrap_data($term->tid, array('type' => 'taxonomy_term'));
  1434. $term_wrapped2 = rules_wrap_data($term2->tid, array('type' => 'taxonomy_term'));
  1435. $rule->action('list_add', array('list:select' => 'node:field-tags', 'item' => $term_wrapped2));
  1436. $rule->action('list_remove', array('list:select' => 'node:field-tags', 'item' => $term_wrapped));
  1437. $rule->execute($node);
  1438. RulesLog::logger()->checkLog();
  1439. $this->assertEqual(array_values($node->field_tags[LANGUAGE_NONE]), array(0 => array('tid' => $term2->tid)), 'Term removed and added from a node.');
  1440. // Test using the taxonomy term reference field on a term object.
  1441. $field_name = drupal_strtolower($this->randomName() . '_field_name');
  1442. $field = field_create_field(array(
  1443. 'field_name' => $field_name,
  1444. 'type' => 'taxonomy_term_reference',
  1445. // Set cardinality to unlimited for tagging.
  1446. 'cardinality' => FIELD_CARDINALITY_UNLIMITED,
  1447. 'settings' => array(
  1448. 'allowed_values' => array(
  1449. array(
  1450. 'vocabulary' => 'tags',
  1451. 'parent' => 0,
  1452. ),
  1453. ),
  1454. ),
  1455. ));
  1456. $instance = array(
  1457. 'field_name' => $field_name,
  1458. 'entity_type' => 'taxonomy_term',
  1459. 'bundle' => 'tags', // Machine name of vocabulary.
  1460. 'label' => $this->randomName() . '_label',
  1461. 'description' => $this->randomName() . '_description',
  1462. 'weight' => mt_rand(0, 127),
  1463. 'widget' => array(
  1464. 'type' => 'taxonomy_autocomplete',
  1465. 'weight' => -4,
  1466. ),
  1467. 'display' => array(
  1468. 'default' => array(
  1469. 'type' => 'taxonomy_term_reference_link',
  1470. 'weight' => 10,
  1471. ),
  1472. ),
  1473. );
  1474. field_create_instance($instance);
  1475. $term1 = entity_property_values_create_entity('taxonomy_term', array(
  1476. 'name' => $this->randomName(),
  1477. 'vocabulary' => 1,
  1478. ))->save();
  1479. $term2 = entity_property_values_create_entity('taxonomy_term', array(
  1480. 'name' => $this->randomName(),
  1481. 'vocabulary' => 1,
  1482. ))->save();
  1483. // Test asserting the term reference field and using it afterwards.
  1484. $rule = rule(array('taxonomy_term' => array('type' => 'taxonomy_term')));
  1485. $rule->condition('entity_has_field', array('entity:select' => 'taxonomy-term', 'field' => $field_name));
  1486. // Add $term2 to $term1 using the term reference field.
  1487. $selector = str_replace('_', '-', 'taxonomy_term:' . $field_name);
  1488. $rule->action('list_add', array('list:select' => $selector, 'item' => $term2));
  1489. $rule->integrityCheck();
  1490. $rule->execute($term1);
  1491. RulesLog::logger()->checkLog();
  1492. $this->assertEqual($term1->{$field_name}[0]->getIdentifier(), $term2->getIdentifier(), 'Rule appended a term to the term reference field on a term.');
  1493. // Test an action set for merging term parents, which is provided as default
  1494. // config.
  1495. $term = entity_property_values_create_entity('taxonomy_term', array(
  1496. 'name' => $this->randomName(),
  1497. 'vocabulary' => 1,
  1498. 'parent' => array($term1->value()),
  1499. ))->save();
  1500. $action = rules_action('component_rules_retrieve_term_parents');
  1501. list($parents) = $action->execute(array($term->getIdentifier()));
  1502. $this->assertTrue($parents[0]->tid == $term1->getIdentifier(), 'Invoked component to retrieve term parents.');
  1503. RulesLog::logger()->checkLog();
  1504. }
  1505. /**
  1506. * Test integration for the node module.
  1507. */
  1508. function testNodeIntegration() {
  1509. $tests = array(
  1510. array('node_unpublish', 'node_is_published', 'node_publish', 'status'),
  1511. array('node_make_unsticky', 'node_is_sticky', 'node_make_sticky', 'sticky'),
  1512. array('node_unpromote', 'node_is_promoted', 'node_promote', 'promote'),
  1513. );
  1514. $node = $this->drupalCreateNode(array('type' => 'page', 'status' => 1, 'sticky' => 1, 'promote' => 1));
  1515. foreach ($tests as $info) {
  1516. list($action1, $condition, $action2, $property) = $info;
  1517. rules_action($action1)->execute($node);
  1518. $node = node_load($node->nid, NULL, TRUE);
  1519. $this->assertFalse($node->$property, 'Action has permanently disabled node '. $property);
  1520. $return = rules_condition($condition)->execute($node);
  1521. $this->assertFalse($return, 'Condition determines node '. $property . ' is disabled.');
  1522. rules_action($action2)->execute($node);
  1523. $node = node_load($node->nid, NULL, TRUE);
  1524. $this->assertTrue($node->$property, 'Action has permanently enabled node '. $property);
  1525. $return = rules_condition($condition)->execute($node);
  1526. $this->assertTrue($return, 'Condition determines node '. $property . ' is enabled.');
  1527. }
  1528. $return = rules_condition('node_is_of_type', array('type' => array('page', 'article')))->execute($node);
  1529. $this->assertTrue($return, 'Condition determines node is of type page.');
  1530. $return = rules_condition('node_is_of_type', array('type' => array('article')))->execute($node);
  1531. $this->assertFalse($return, 'Condition determines node is not of type article.');
  1532. // Test auto saving of a new node after it has been inserted into the DB.
  1533. $rule = rules_reaction_rule();
  1534. $rand = $this->randomName();
  1535. $rule->event('node_insert')
  1536. ->action('data_set', array('data:select' => 'node:title', 'value' => $rand));
  1537. $rule->save('test');
  1538. $node = $this->drupalCreateNode();
  1539. $node = node_load($node->nid);
  1540. $this->assertEqual($node->title, $rand, 'Node title is correct.');
  1541. RulesLog::logger()->checkLog();
  1542. }
  1543. /**
  1544. * Test integration for the user module.
  1545. */
  1546. function testUserIntegration() {
  1547. $rid = $this->drupalCreateRole(array('administer nodes'), 'foo');
  1548. $user = $this->drupalCreateUser();
  1549. // Test assigning a role with the list_add action.
  1550. $rule = rule(array('user' => array('type' => 'user')));
  1551. $rule->action('list_add', array('list:select' => 'user:roles', 'item' => $rid));
  1552. $rule->execute($user);
  1553. $this->assertTrue(isset($user->roles[$rid]), 'Role assigned to user.');
  1554. // Test removing a role with the list_remove action.
  1555. $rule = rule(array('user' => array('type' => 'user')));
  1556. $rule->action('list_remove', array('list:select' => 'user:roles', 'item' => $rid));
  1557. $rule->execute($user);
  1558. $this->assertTrue(!isset($user->roles[$rid]), 'Role removed from user.');
  1559. // Test assigning a role with user_add_role action.
  1560. $rule = rule(array('user' => array('type' => 'user')));
  1561. $rule->action('user_add_role', array('account:select' => 'user', 'roles' => array($rid)));
  1562. $rule->execute($user);
  1563. $user = user_load($user->uid, TRUE);
  1564. $result = rules_condition('user_has_role', array('roles' => array($rid)))->execute($user);
  1565. $this->assertTrue($result, 'Role assigned to user.');
  1566. // Test removing a role with the user_remove_role action.
  1567. $rule = rule(array('user' => array('type' => 'user')));
  1568. $rule->action('user_remove_role', array('account:select' => 'user', 'roles' => array($rid)));
  1569. $rule->execute($user);
  1570. $user = user_load($user->uid, TRUE);
  1571. $result = rules_condition('user_has_role', array('roles' => array($rid)))->execute($user);
  1572. $this->assertFalse($result, 'Role removed from user.');
  1573. // Test user blocking.
  1574. rules_action('user_block')->execute($user);
  1575. $user = user_load($user->uid, TRUE);
  1576. $this->assertTrue(rules_condition('user_is_blocked')->execute($user), 'User has been blocked.');
  1577. rules_action('user_unblock')->execute($user);
  1578. $user = user_load($user->uid, TRUE);
  1579. $this->assertFalse(rules_condition('user_is_blocked')->execute($user), 'User has been unblocked.');
  1580. RulesLog::logger()->checkLog();
  1581. }
  1582. /**
  1583. * Test integration for the php module.
  1584. */
  1585. function testPHPIntegration() {
  1586. $node = $this->drupalCreateNode(array('title' => 'foo'));
  1587. $rule = rule(array('var_name' => array('type' => 'node')));
  1588. $rule->condition('php_eval', array('code' => 'return TRUE;'))
  1589. ->action('php_eval', array('code' => 'drupal_set_message("Executed-" . $var_name->title);'))
  1590. ->action('drupal_message', array('message' => 'Title: <?php echo $var_name->title; ?> Token: [var_name:title]'));
  1591. $rule->execute($node);
  1592. $rule->access();
  1593. RulesLog::logger()->checkLog();
  1594. $msg = drupal_get_messages();
  1595. $this->assertEqual(array_pop($msg['status']), "Title: foo Token: foo", 'PHP input evaluation has been applied.');
  1596. $this->assertEqual(array_pop($msg['status']), "Executed-foo", 'PHP code condition and action have been evaluated.');
  1597. // Test PHP data processor
  1598. $rule = rule(array('var_name' => array('type' => 'node')));
  1599. $rule->action('drupal_message', array(
  1600. 'message:select' => 'var_name:title',
  1601. 'message:process' => array(
  1602. 'php' => array('code' => 'return "Title: $value";')
  1603. ),
  1604. ));
  1605. $rule->execute($node);
  1606. $rule->access();
  1607. RulesLog::logger()->checkLog();
  1608. $msg = drupal_get_messages();
  1609. $this->assertEqual(array_pop($msg['status']), "Title: foo", 'PHP data processor has been applied.');
  1610. }
  1611. /**
  1612. * Test the "rules_core" integration.
  1613. */
  1614. function testRulesCoreIntegration() {
  1615. // Make sure the date input evaluator evaluates properly using strtotime().
  1616. $node = $this->drupalCreateNode(array('title' => 'foo'));
  1617. $rule = rule(array('node' => array('type' => 'node')));
  1618. $rule->action('data_set', array('data:select' => 'node:created', 'value' => '+1 day'));
  1619. $rule->execute($node);
  1620. RulesLog::logger()->checkLog();
  1621. $node = node_load($node->nid, NULL, TRUE);
  1622. $now = RulesDateInputEvaluator::gmstrtotime('now');
  1623. // Tolerate a difference of a second.
  1624. $this->assertTrue(abs($node->created - $now - 86400) <= 1, 'Date input has been evaluated.');
  1625. // Test using a numeric offset.
  1626. $rule = rule(array('number' => array('type' => 'decimal')), array('number'));
  1627. $rule->action('data_set', array(
  1628. 'data:select' => 'number',
  1629. 'value:select' => 'number',
  1630. 'value:process' => array(
  1631. 'num_offset' => array('value' => 1),
  1632. ),
  1633. ));
  1634. $rule->integrityCheck();
  1635. list($result) = $rule->execute(10);
  1636. $this->assertTrue($result == 11, 'Numeric offset has been applied');
  1637. // Test using a date offset.
  1638. $set = rules_action_set(array('date' => array('type' => 'date')), array('date'));
  1639. $set->action('data_set', array(
  1640. 'data:select' => 'date',
  1641. 'value:select' => 'date',
  1642. 'value:process' => array(
  1643. 'date_offset' => array('value' => 1000),
  1644. ),
  1645. ));
  1646. $date = date_create("14 Mar 1984 10:19:23 +01:00")->format('U');
  1647. list($result) = $set->execute($date);
  1648. $this->assertEqual($result, $date + 1000, 'Date offset in seconds has been added.');
  1649. // Test using a negative offset of 2 months.
  1650. $set = rules_action_set(array('date' => array('type' => 'date')), array('date'));
  1651. $set->action('data_set', array(
  1652. 'data:select' => 'date',
  1653. 'value:select' => 'date',
  1654. 'value:process' => array(
  1655. 'date_offset' => array('value' => - 86400 * 30 * 2),
  1656. ),
  1657. ));
  1658. $date = date_create("14 Mar 1984 10:19:23 +01:00")->format('U');
  1659. list($result) = $set->execute($date);
  1660. $this->assertEqual($result, date_create("14 Jan 1984 10:19:23 +01:00")->format('U'), 'Date offset of -2 months has been added.');
  1661. // Test using a positive offset of 1 year 6 months and 30 minutes.
  1662. $set = rules_action_set(array('date' => array('type' => 'date')), array('date'));
  1663. $set->action('data_set', array(
  1664. 'data:select' => 'date',
  1665. 'value:select' => 'date',
  1666. 'value:process' => array(
  1667. 'date_offset' => array('value' => 86400 * 30 * 18 + 30 * 60),
  1668. ),
  1669. ));
  1670. $date = date_create("14 Mar 1984 10:19:23 +01:00")->format('U');
  1671. list($result) = $set->execute($date);
  1672. $this->assertEqual($result, date_create("14 Sep 1985 10:49:23 +01:00")->format('U'), 'Date offset of 1 year 6 months and 30 minutes has been added.');
  1673. RulesLog::logger()->checkLog();
  1674. }
  1675. /**
  1676. * Test site/system integration.
  1677. */
  1678. function testSystemIntegration() {
  1679. // Test using the 'site' variable.
  1680. $condition = rules_condition('data_is', array('data:select' => 'site:current-user:name', 'value' => $GLOBALS['user']->name));
  1681. $this->assertTrue($condition->execute(), 'Retrieved the current user\'s name.');
  1682. // Another test using a token replacement.
  1683. $condition = rules_condition('data_is', array('data:select' => 'site:current-user:name', 'value' => '[site:current-user:name]'));
  1684. $this->assertTrue($condition->execute(), 'Replaced the token for the current user\'s name.');
  1685. // Test breadcrumbs and drupal set message.
  1686. $rule = rules_reaction_rule();
  1687. $rule->event('init')
  1688. ->action('breadcrumb_set', array('titles' => array('foo'), 'paths' => array('bar')))
  1689. ->action('drupal_message', array('message' => 'A message.'));
  1690. $rule->save('test');
  1691. $this->drupalGet('node');
  1692. $this->assertLink('foo', 0, 'Breadcrumb has been set.');
  1693. $this->assertText('A message.', 'Drupal message has been shown.');
  1694. // Test the page redirect.
  1695. $node = $this->drupalCreateNode();
  1696. $rule = rules_reaction_rule();
  1697. $rule->event('node_view')
  1698. ->action('redirect', array('url' => 'user'));
  1699. $rule->save('test2');
  1700. $this->drupalGet('node/' . $node->nid);
  1701. $this->assertEqual($this->getUrl(), url('user', array('absolute' => TRUE)), 'Redirect has been issued.');
  1702. // Also test using a url including a fragment.
  1703. $actions = $rule->actions();
  1704. $actions[0]->settings['url'] = 'user#fragment';
  1705. $rule->save();
  1706. $this->drupalGet('node/' . $node->nid);
  1707. $this->assertEqual($this->getUrl(), url('user', array('absolute' => TRUE, 'fragment' => 'fragment')), 'Redirect has been issued.');
  1708. // Test sending mail.
  1709. $settings = array('to' => 'mail@example.com', 'subject' => 'subject', 'message' => 'hello.');
  1710. rules_action('mail', $settings)->execute();
  1711. $this->assertMail('to', 'mail@example.com', 'Mail has been sent.');
  1712. $this->assertMail('from', variable_get('site_mail', ini_get('sendmail_from')), 'Default from address has been used');
  1713. rules_action('mail', $settings + array('from' => 'sender@example.com'))->execute();
  1714. $this->assertMail('from', 'sender@example.com', 'Specified from address has been used');
  1715. // Test sending mail to all users of a role. First make sure there is a
  1716. // custom role and a user for it.
  1717. $user = $this->drupalCreateUser(array('administer nodes'));
  1718. $roles = $user->roles;
  1719. // Remove the authenticate role so we only use the new role created by
  1720. // drupalCreateUser().
  1721. unset($roles[DRUPAL_AUTHENTICATED_RID]);
  1722. rules_action('mail_to_users_of_role', $settings + array('roles' => array_keys($roles)))->execute();
  1723. $this->assertMail('to', $user->mail, 'Mail to users of a role has been sent.');
  1724. // Test reacting on new log entries and make sure the log entry is usable.
  1725. $rule = rules_reaction_rule();
  1726. $rule->event('watchdog');
  1727. $rule->action('drupal_message', array('message:select' => 'log_entry:message'));
  1728. $rule->integrityCheck()->save('test_watchdog');
  1729. watchdog('php', 'test %message', array('%message' => 'message'));
  1730. $msg = drupal_get_messages();
  1731. $this->assertEqual(array_pop($msg['status']), t('test %message', array('%message' => 'message')), 'Watchdog event occurred and log entry properties can be used.');
  1732. }
  1733. /**
  1734. * Tests the path module integration.
  1735. */
  1736. function testPathIntegration() {
  1737. rules_action('path_alias')->execute('foo', 'bar');
  1738. $path = path_load('foo');
  1739. $this->assertTrue($path['alias'] == 'bar', 'URL alias has been created.');
  1740. $alias_exists = rules_condition('path_alias_exists', array('alias' => 'bar'))->execute();
  1741. $this->assertTrue($alias_exists, 'Created URL alias exists.');
  1742. $has_alias = rules_condition('path_has_alias', array('source' => 'foo'))->execute();
  1743. $this->assertTrue($has_alias, 'System path has an alias.');
  1744. // Test node alias action.
  1745. $node = $this->drupalCreateNode();
  1746. rules_action('node_path_alias')->execute($node, 'test');
  1747. $path = path_load("node/$node->nid");
  1748. $this->assertTrue($path['alias'] == 'test', 'Node URL alias has been created.');
  1749. // Test term alias action.
  1750. $term = entity_property_values_create_entity('taxonomy_term', array(
  1751. 'name' => $this->randomName(),
  1752. 'vocabulary' => 1,
  1753. ))->value();
  1754. rules_action('taxonomy_term_path_alias')->execute($term, 'term-test');
  1755. $path = path_load("taxonomy/term/$term->tid");
  1756. $this->assertTrue($path['alias'] == 'term-test', 'Term URL alias has been created.');
  1757. RulesLog::logger()->checkLog();
  1758. }
  1759. }
  1760. /**
  1761. * Test event dispatcher functionality.
  1762. */
  1763. class RulesEventDispatcherTestCase extends DrupalWebTestCase {
  1764. static function getInfo() {
  1765. return array(
  1766. 'name' => 'Rules event dispatchers',
  1767. 'description' => 'Tests event dispatcher functionality.',
  1768. 'group' => 'Rules',
  1769. );
  1770. }
  1771. function setUp() {
  1772. parent::setUp('rules', 'rules_test');
  1773. }
  1774. /**
  1775. * Tests start and stop functionality.
  1776. */
  1777. public function testStartAndStop() {
  1778. $handler = rules_get_event_handler('rules_test_event');
  1779. $rule = rules_reaction_rule();
  1780. $rule->event('rules_test_event');
  1781. // The handler should not yet be watching.
  1782. $this->assertFalse($handler->isWatching());
  1783. // Once saved, the event cache rebuild should start the watcher.
  1784. $rule->save();
  1785. RulesEventSet::rebuildEventCache();
  1786. $this->assertTrue($handler->isWatching());
  1787. // Deleting should stop the watcher.
  1788. $rule->delete();
  1789. $this->assertFalse($handler->isWatching());
  1790. }
  1791. /**
  1792. * Tests start and stop functionality when used with multiple events.
  1793. */
  1794. public function testStartAndStopMultiple() {
  1795. $handler = rules_get_event_handler('rules_test_event');
  1796. // Initially, the task handler should not be watching.
  1797. $this->assertFalse($handler->isWatching());
  1798. // Set up five rules that all use the same event.
  1799. $rules = array();
  1800. foreach (array(1, 2, 3, 4, 5) as $key) {
  1801. $rules[$key] = rules_reaction_rule();
  1802. $rules[$key]->event('rules_test_event');
  1803. $rules[$key]->save();
  1804. }
  1805. // Once saved, the event cache rebuild should start the watcher.
  1806. RulesEventSet::rebuildEventCache();
  1807. $this->assertTrue($handler->isWatching());
  1808. // It should continue watching until all events are deleted.
  1809. foreach ($rules as $key => $rule) {
  1810. $rule->delete();
  1811. $this->assertEqual($key !== 5, $handler->isWatching());
  1812. }
  1813. }
  1814. }