CRM-12193 - Add pick() function randomly choose among options (provided that permissi...
[civicrm-core.git] / tests / phpunit / CRM / Core / CommunityMessagesTest.php
CommitLineData
ecbe1139
TO
1<?php
2
3/*
4 +--------------------------------------------------------------------+
5 | CiviCRM version 4.3 |
6 +--------------------------------------------------------------------+
7 | Copyright CiviCRM LLC (c) 2004-2013 |
8 +--------------------------------------------------------------------+
9 | This file is a part of CiviCRM. |
10 | |
11 | CiviCRM is free software; you can copy, modify, and distribute it |
12 | under the terms of the GNU Affero General Public License |
13 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
14 | |
15 | CiviCRM is distributed in the hope that it will be useful, but |
16 | WITHOUT ANY WARRANTY; without even the implied warranty of |
17 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
18 | See the GNU Affero General Public License for more details. |
19 | |
20 | You should have received a copy of the GNU Affero General Public |
21 | License and the CiviCRM Licensing Exception along |
22 | with this program; if not, contact CiviCRM LLC |
23 | at info[AT]civicrm[DOT]org. If you have questions about the |
24 | GNU Affero General Public License or the licensing of CiviCRM, |
25 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
26 +--------------------------------------------------------------------+
27*/
28
29
30require_once 'CiviTest/CiviUnitTestCase.php';
31class CRM_Core_CommunityMessagesTest extends CiviUnitTestCase {
32
33 /**
34 * @var CRM_Utils_Cache_Interface
35 */
36 protected $cache;
37
38 /**
39 * @var array list of possible web responses
40 */
376d8353 41 protected static $webResponses = NULL;
ecbe1139 42
376d8353
TO
43 public static function initWebResponses() {
44 if (self::$webResponses === NULL) {
45 self::$webResponses = array(
46 'http-error' => array(
47 CRM_Utils_HttpClient::STATUS_DL_ERROR,
48 NULL
49 ),
50 'bad-json' => array(
51 CRM_Utils_HttpClient::STATUS_OK,
52 '<html>this is not json!</html>'
53 ),
54 'invalid-ttl-document' => array(
55 CRM_Utils_HttpClient::STATUS_OK,
56 json_encode(array(
57 'ttl' => 'z', // not an integer!
58 'retry' => 'z', // not an integer!
59 'messages' => array(
60 array(
61 'markup' => '<h1>Invalid document</h1>',
62 ),
8bfc3cb1 63 ),
376d8353
TO
64 ))
65 ),
3dcd50d8 66 'first-valid-response' => array(
376d8353
TO
67 CRM_Utils_HttpClient::STATUS_OK,
68 json_encode(array(
69 'ttl' => 600,
70 'retry' => 600,
71 'messages' => array(
72 array(
3dcd50d8 73 'markup' => '<h1>First valid response</h1>',
376d8353 74 ),
ecbe1139 75 ),
376d8353
TO
76 ))
77 ),
3dcd50d8 78 'second-valid-response' => array(
376d8353
TO
79 CRM_Utils_HttpClient::STATUS_OK,
80 json_encode(array(
81 'ttl' => 600,
82 'retry' => 600,
83 'messages' => array(
84 array(
3dcd50d8 85 'markup' => '<h1>Second valid response</h1>',
376d8353 86 ),
ecbe1139 87 ),
376d8353
TO
88 ))
89 ),
dc92f2f8
TO
90 'two-messages' => array(
91 CRM_Utils_HttpClient::STATUS_OK,
92 json_encode(array(
93 'ttl' => 600,
94 'retry' => 600,
95 'messages' => array(
96 array(
97 'markup' => '<h1>One</h1>',
98 'components' => array('CiviMail'),
99 ),
100 array(
101 'markup' => '<h1>Two</h1>',
102 'components' => array('CiviMail'),
103 ),
104 ),
105 ))
106 ),
107 'two-messages-halfbadcomp' => array(
108 CRM_Utils_HttpClient::STATUS_OK,
109 json_encode(array(
110 'ttl' => 600,
111 'retry' => 600,
112 'messages' => array(
113 array(
114 'markup' => '<h1>One</h1>',
115 'components' => array('NotARealComponent'),
116 ),
117 array(
118 'markup' => '<h1>Two</h1>',
119 'components' => array('CiviMail'),
120 ),
121 ),
122 ))
123 ),
376d8353
TO
124 );
125 }
126 return self::$webResponses;
127 }
128
129 public function setUp() {
130 parent::setUp();
131 $this->cache = new CRM_Utils_Cache_Arraycache(array());
132 self::initWebResponses();
ecbe1139
TO
133 }
134
135 public function tearDown() {
136 parent::tearDown();
137 CRM_Utils_Time::resetTime();
138 }
139
376d8353
TO
140 public function badWebRequests() {
141 self::initWebResponses();
142 $result = array(
143 array(self::$webResponses['http-error']),
144 array(self::$webResponses['bad-json']),
145 array(self::$webResponses['invalid-ttl-document']),
146 );
147 return $result;
148 }
149
e8977170
TO
150 public function testGetDocument_disabled() {
151 $communityMessages = new CRM_Core_CommunityMessages(
152 $this->cache,
153 $this->expectNoHttpRequest(),
154 FALSE
155 );
156 $doc = $communityMessages->getDocument();
157 $this->assertTrue(NULL === $doc);
158 }
159
ecbe1139
TO
160 /**
161 * Download a document; after the set expiration period, download again.
162 */
e8977170 163 public function testGetDocument_NewOK_CacheOK_UpdateOK() {
ecbe1139
TO
164 // first try, good response
165 CRM_Utils_Time::setTime('2013-03-01 10:00:00');
166 $communityMessages = new CRM_Core_CommunityMessages(
167 $this->cache,
3dcd50d8 168 $this->expectOneHttpRequest(self::$webResponses['first-valid-response'])
ecbe1139
TO
169 );
170 $doc1 = $communityMessages->getDocument();
3dcd50d8 171 $this->assertEquals('<h1>First valid response</h1>', $doc1['messages'][0]['markup']);
ecbe1139
TO
172 $this->assertEquals(strtotime('2013-03-01 10:10:00'), $doc1['expires']);
173
174 // second try, $doc1 hasn't expired yet, so still use it
175 CRM_Utils_Time::setTime('2013-03-01 10:09:00');
176 $communityMessages = new CRM_Core_CommunityMessages(
177 $this->cache,
178 $this->expectNoHttpRequest()
179 );
180 $doc2 = $communityMessages->getDocument();
3dcd50d8 181 $this->assertEquals('<h1>First valid response</h1>', $doc2['messages'][0]['markup']);
ecbe1139
TO
182 $this->assertEquals(strtotime('2013-03-01 10:10:00'), $doc2['expires']);
183
184 // third try, $doc1 expired, update it
185 CRM_Utils_Time::setTime('2013-03-01 12:00:02'); // more than 2 hours later (DEFAULT_RETRY)
186 $communityMessages = new CRM_Core_CommunityMessages(
187 $this->cache,
3dcd50d8 188 $this->expectOneHttpRequest(self::$webResponses['second-valid-response'])
ecbe1139
TO
189 );
190 $doc3 = $communityMessages->getDocument();
3dcd50d8 191 $this->assertEquals('<h1>Second valid response</h1>', $doc3['messages'][0]['markup']);
ecbe1139
TO
192 $this->assertEquals(strtotime('2013-03-01 12:10:02'), $doc3['expires']);
193 }
194
195 /**
376d8353
TO
196 * First download attempt fails (due to some bad web request).
197 * Store the NACK and retry after the default time period (DEFAULT_RETRY).
198 *
199 * @dataProvider badWebRequests
3dcd50d8 200 * @param array $$badWebRequest Description of a web request that returns some kind of failure
ecbe1139 201 */
376d8353
TO
202 public function testGetDocument_NewFailure_CacheOK_UpdateOK($badWebRequest) {
203 $this->assertNotEmpty($badWebRequest);
204
ecbe1139
TO
205 // first try, bad response
206 CRM_Utils_Time::setTime('2013-03-01 10:00:00');
207 $communityMessages = new CRM_Core_CommunityMessages(
208 $this->cache,
376d8353 209 $this->expectOneHttpRequest($badWebRequest)
ecbe1139
TO
210 );
211 $doc1 = $communityMessages->getDocument();
212 $this->assertEquals(array(), $doc1['messages']);
213 $this->assertTrue($doc1['expires'] > CRM_Utils_Time::getTimeRaw());
214
215 // second try, $doc1 hasn't expired yet, so still use it
216 CRM_Utils_Time::setTime('2013-03-01 10:09:00');
217 $communityMessages = new CRM_Core_CommunityMessages(
218 $this->cache,
219 $this->expectNoHttpRequest()
220 );
221 $doc2 = $communityMessages->getDocument();
222 $this->assertEquals(array(), $doc2['messages']);
223 $this->assertEquals($doc1['expires'], $doc2['expires']);
224
225 // third try, $doc1 expired, try again, get a good response
226 CRM_Utils_Time::setTime('2013-03-01 12:00:02'); // more than 2 hours later (DEFAULT_RETRY)
227 $communityMessages = new CRM_Core_CommunityMessages(
228 $this->cache,
3dcd50d8 229 $this->expectOneHttpRequest(self::$webResponses['first-valid-response'])
ecbe1139
TO
230 );
231 $doc3 = $communityMessages->getDocument();
3dcd50d8 232 $this->assertEquals('<h1>First valid response</h1>', $doc3['messages'][0]['markup']);
ecbe1139
TO
233 $this->assertTrue($doc3['expires'] > CRM_Utils_Time::getTimeRaw());
234 }
235
236 /**
237 * First download of new doc is OK.
376d8353 238 * The update fails (due to some bad web request)
ecbe1139
TO
239 * The failure cached.
240 * The failure eventually expires and new update succeeds.
376d8353
TO
241 *
242 * @dataProvider badWebRequests
3dcd50d8 243 * @param array $$badWebRequest Description of a web request that returns some kind of failure
ecbe1139 244 */
376d8353
TO
245 public function testGetDocument_NewOK_UpdateFailure_CacheOK_UpdateOK($badWebRequest) {
246 $this->assertNotEmpty($badWebRequest);
247
ecbe1139
TO
248 // first try, good response
249 CRM_Utils_Time::setTime('2013-03-01 10:00:00');
250 $communityMessages = new CRM_Core_CommunityMessages(
251 $this->cache,
3dcd50d8 252 $this->expectOneHttpRequest(self::$webResponses['first-valid-response'])
ecbe1139
TO
253 );
254 $doc1 = $communityMessages->getDocument();
3dcd50d8 255 $this->assertEquals('<h1>First valid response</h1>', $doc1['messages'][0]['markup']);
ecbe1139
TO
256 $this->assertEquals(strtotime('2013-03-01 10:10:00'), $doc1['expires']);
257
258 // second try, $doc1 has expired; bad response; keep old data
259 CRM_Utils_Time::setTime('2013-03-01 12:00:02'); // more than 2 hours later (DEFAULT_RETRY)
260 $communityMessages = new CRM_Core_CommunityMessages(
261 $this->cache,
376d8353 262 $this->expectOneHttpRequest($badWebRequest)
ecbe1139
TO
263 );
264 $doc2 = $communityMessages->getDocument();
3dcd50d8 265 $this->assertEquals('<h1>First valid response</h1>', $doc2['messages'][0]['markup']);
ecbe1139
TO
266 $this->assertTrue($doc2['expires'] > CRM_Utils_Time::getTimeRaw());
267
268 // third try, $doc2 hasn't expired yet; no request; keep old data
269 CRM_Utils_Time::setTime('2013-03-01 12:09:00');
270 $communityMessages = new CRM_Core_CommunityMessages(
271 $this->cache,
272 $this->expectNoHttpRequest()
273 );
274 $doc3 = $communityMessages->getDocument();
3dcd50d8 275 $this->assertEquals('<h1>First valid response</h1>', $doc3['messages'][0]['markup']);
ecbe1139
TO
276 $this->assertEquals($doc2['expires'], $doc3['expires']);
277
278 // fourth try, $doc2 has expired yet; new request; replace data
279 CRM_Utils_Time::setTime('2013-03-01 12:10:02');
280 $communityMessages = new CRM_Core_CommunityMessages(
281 $this->cache,
3dcd50d8 282 $this->expectOneHttpRequest(self::$webResponses['second-valid-response'])
ecbe1139
TO
283 );
284 $doc4 = $communityMessages->getDocument();
3dcd50d8 285 $this->assertEquals('<h1>Second valid response</h1>', $doc4['messages'][0]['markup']);
ecbe1139
TO
286 $this->assertEquals(strtotime('2013-03-01 12:20:02'), $doc4['expires']);
287 }
288
dc92f2f8
TO
289 /**
290 * Randomly pick among two options
291 */
292 public function testPick_rand() {
293 $communityMessages = new CRM_Core_CommunityMessages(
294 $this->cache,
295 $this->expectOneHttpRequest(self::$webResponses['two-messages'])
296 );
297 $doc1 = $communityMessages->getDocument();
298 $this->assertEquals('<h1>One</h1>', $doc1['messages'][0]['markup']);
299 $this->assertEquals('<h1>Two</h1>', $doc1['messages'][1]['markup']);
300
301 // randomly pick many times
302 $trials = 40;
303 $freq = array(); // array($message => $count)
304 for ($i = 0; $i < $trials; $i++) {
305 $message = $communityMessages->pick();
306 $freq[$message['markup']]++;
307 }
308
309 // assert the probabilities
310 $this->assertApproxEquals(0.5, $freq['<h1>One</h1>'] / $trials, 0.2);
311 $this->assertApproxEquals(0.5, $freq['<h1>Two</h1>'] / $trials, 0.2);
312 $this->assertEquals($trials, $freq['<h1>One</h1>'] + $freq['<h1>Two</h1>']);
313 }
314
315 /**
316 * When presented with two options using component filters, always
317 * choose the one which references an active component.
318 */
319 public function testPick_componentFilter() {
320 $communityMessages = new CRM_Core_CommunityMessages(
321 $this->cache,
322 $this->expectOneHttpRequest(self::$webResponses['two-messages-halfbadcomp'])
323 );
324 $doc1 = $communityMessages->getDocument();
325 $this->assertEquals('<h1>One</h1>', $doc1['messages'][0]['markup']);
326 $this->assertEquals('<h1>Two</h1>', $doc1['messages'][1]['markup']);
327
328 // randomly pick many times
329 $trials = 10;
330 $freq = array(); // array($message => $count)
331 for ($i = 0; $i < $trials; $i++) {
332 $message = $communityMessages->pick();
333 $freq[$message['markup']]++;
334 }
335
336 $this->assertEquals($trials, $freq['<h1>Two</h1>']);
337 }
338
ecbe1139
TO
339 /**
340 * Generate a mock HTTP client with the expectation that it is never called.
341 *
342 * @return CRM_Utils_HttpClient|PHPUnit_Framework_MockObject_MockObject
343 */
344 protected function expectNoHttpRequest() {
345 $client = $this->getMock('CRM_Utils_HttpClient');
346 $client->expects($this->never())
347 ->method('get');
348 return $client;
349 }
350
351 /**
352 * Generate a mock HTTP client with the expectation that it is called once.
353 *
354 * @return CRM_Utils_HttpClient|PHPUnit_Framework_MockObject_MockObject
355 */
356 protected function expectOneHttpRequest($response) {
357 $client = $this->getMock('CRM_Utils_HttpClient');
358 $client->expects($this->once())
359 ->method('get')
360 ->will($this->returnValue($response));
361 return $client;
362 }
363}